You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IRCParser.java 74KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.parser.irc;
  23. import com.dmdirc.parser.common.BaseSocketAwareParser;
  24. import com.dmdirc.parser.common.ChannelJoinRequest;
  25. import com.dmdirc.parser.common.ChildImplementations;
  26. import com.dmdirc.parser.common.CompositionState;
  27. import com.dmdirc.parser.common.IgnoreList;
  28. import com.dmdirc.parser.common.MyInfo;
  29. import com.dmdirc.parser.common.ParserError;
  30. import com.dmdirc.parser.common.QueuePriority;
  31. import com.dmdirc.parser.common.SRVRecord;
  32. import com.dmdirc.parser.common.SystemEncoder;
  33. import com.dmdirc.parser.events.ConnectErrorEvent;
  34. import com.dmdirc.parser.events.DataInEvent;
  35. import com.dmdirc.parser.events.DataOutEvent;
  36. import com.dmdirc.parser.events.DebugInfoEvent;
  37. import com.dmdirc.parser.events.ErrorInfoEvent;
  38. import com.dmdirc.parser.events.PingFailureEvent;
  39. import com.dmdirc.parser.events.PingSentEvent;
  40. import com.dmdirc.parser.events.PingSuccessEvent;
  41. import com.dmdirc.parser.events.ServerErrorEvent;
  42. import com.dmdirc.parser.events.ServerReadyEvent;
  43. import com.dmdirc.parser.events.SocketCloseEvent;
  44. import com.dmdirc.parser.interfaces.ChannelInfo;
  45. import com.dmdirc.parser.interfaces.Encoder;
  46. import com.dmdirc.parser.interfaces.EncodingParser;
  47. import com.dmdirc.parser.interfaces.SecureParser;
  48. import com.dmdirc.parser.irc.IRCReader.ReadLine;
  49. import com.dmdirc.parser.irc.events.IRCDataInEvent;
  50. import com.dmdirc.parser.irc.events.IRCDataOutEvent;
  51. import com.dmdirc.parser.irc.outputqueue.OutputQueue;
  52. import java.io.IOException;
  53. import java.net.InetAddress;
  54. import java.net.Socket;
  55. import java.net.URI;
  56. import java.net.URISyntaxException;
  57. import java.net.UnknownHostException;
  58. import java.security.KeyManagementException;
  59. import java.security.NoSuchAlgorithmException;
  60. import java.security.SecureRandom;
  61. import java.time.LocalDateTime;
  62. import java.time.ZoneOffset;
  63. import java.time.format.DateTimeFormatter;
  64. import java.time.format.DateTimeParseException;
  65. import java.util.ArrayList;
  66. import java.util.Arrays;
  67. import java.util.Collection;
  68. import java.util.Collections;
  69. import java.util.HashMap;
  70. import java.util.LinkedList;
  71. import java.util.List;
  72. import java.util.Map;
  73. import java.util.Queue;
  74. import java.util.Timer;
  75. import java.util.concurrent.Semaphore;
  76. import java.util.concurrent.atomic.AtomicBoolean;
  77. import javax.net.ssl.KeyManager;
  78. import javax.net.ssl.SSLContext;
  79. import javax.net.ssl.SSLSocket;
  80. import javax.net.ssl.SSLSocketFactory;
  81. import javax.net.ssl.TrustManager;
  82. import dagger.ObjectGraph;
  83. /**
  84. * IRC Parser.
  85. */
  86. @ChildImplementations({
  87. IRCChannelClientInfo.class,
  88. IRCChannelInfo.class,
  89. IRCClientInfo.class
  90. })
  91. public class IRCParser extends BaseSocketAwareParser implements SecureParser, EncodingParser {
  92. /** Max length an outgoing line should be (NOT including \r\n). */
  93. public static final int MAX_LINELENGTH = 510;
  94. /** General Debug Information. */
  95. public static final int DEBUG_INFO = 1;
  96. /** Socket Debug Information. */
  97. public static final int DEBUG_SOCKET = 2;
  98. /** Processing Manager Debug Information. */
  99. public static final int DEBUG_PROCESSOR = 4;
  100. /** List Mode Queue Debug Information. */
  101. public static final int DEBUG_LMQ = 8;
  102. /** Attempt to update user host all the time, not just on Who/Add/NickChange. */
  103. public static final boolean ALWAYS_UPDATECLIENT = true;
  104. /** Byte used to show that a non-boolean mode is a list (b). */
  105. public static final byte MODE_LIST = 1;
  106. /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */
  107. static final byte MODE_SET = 2;
  108. /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */
  109. public static final byte MODE_UNSET = 4;
  110. /**
  111. * Default channel prefixes if none are specified by the IRCd.
  112. *
  113. * <p>These are the RFC 2811 specified prefixes: '#', '&amp;', '!' and '+'.
  114. */
  115. private static final String DEFAULT_CHAN_PREFIX = "#&!+";
  116. /**
  117. * This is what the user wants settings to be.
  118. * Nickname here is *not* always accurate.<br><br>
  119. * ClientInfo variable tParser.getMyself() should be used for accurate info.
  120. */
  121. private MyInfo me = new MyInfo();
  122. /** Should PINGs be sent to the server to check if its alive? */
  123. private boolean checkServerPing = true;
  124. /** Timer for server ping. */
  125. private Timer pingTimer;
  126. /** Semaphore for access to pingTimer. */
  127. private final Semaphore pingTimerSem = new Semaphore(1);
  128. /** Is a ping needed? */
  129. private final AtomicBoolean pingNeeded = new AtomicBoolean(false);
  130. /** Time last ping was sent at. */
  131. private long pingTime;
  132. /** Current Server Lag. */
  133. private long serverLag;
  134. /** Last value sent as a ping argument. */
  135. private String lastPingValue = "";
  136. /**
  137. * Count down to next ping.
  138. * The timer fires every 10 seconds, this value is decreased every time the
  139. * timer fires.<br>
  140. * Once it reaches 0, we send a ping, and reset it to 6, this means we ping
  141. * the server every minute.
  142. *
  143. * @see #setPingTimerInterval
  144. */
  145. private int pingCountDown;
  146. /** Network name. This is "" if no network name is provided */
  147. public String networkName;
  148. /** This is what we think the nickname should be. */
  149. public String thinkNickname;
  150. /** Have we received the 001. */
  151. public boolean got001;
  152. /** Have we fired post005? */
  153. boolean post005;
  154. /** Has the thread started execution yet, (Prevents run() being called multiple times). */
  155. boolean hasBegan;
  156. /** Manager used to handle prefix modes. */
  157. private final PrefixModeManager prefixModes = new PrefixModeManager();
  158. /** Manager used to handle user modes (owxis etc). */
  159. private final ModeManager userModes = new ModeManager();
  160. /**
  161. * Manager used to handle channel boolean modes.
  162. * <p>
  163. * Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a ERROR_WARNING Error is called)
  164. */
  165. private final ModeManager chanModesBool = new ModeManager();
  166. /**
  167. * Hashtable storing known non-boolean chan modes (klbeI etc).
  168. * Non Boolean Modes (for Channels) are stored together in this hashtable, the value param
  169. * is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6))<br><br>
  170. * <br>
  171. * see MODE_LIST<br>
  172. * see MODE_SET<br>
  173. * see MODE_UNSET<br>
  174. */
  175. public final Map<Character, Byte> chanModesOther = new HashMap<>();
  176. /** The last line of input received from the server */
  177. private ReadLine lastLine;
  178. /** Should the lastline (where given) be appended to the "data" part of any onErrorInfo call? */
  179. private boolean addLastLine;
  180. /** Channel Prefixes (ie # + etc). */
  181. private String chanPrefix = DEFAULT_CHAN_PREFIX;
  182. /** Hashtable storing all known clients based on nickname (in lowercase). */
  183. private final Map<String, IRCClientInfo> clientList = new HashMap<>();
  184. /** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */
  185. private final Map<String, IRCChannelInfo> channelList = new HashMap<>();
  186. /** Reference to the ClientInfo object that references ourself. */
  187. private IRCClientInfo myself;
  188. /** Hashtable storing all information gathered from 005. */
  189. public final Map<String, String> h005Info = new HashMap<>();
  190. /** difference in ms between our time and the servers time (used for timestampedIRC). */
  191. private long tsdiff;
  192. /** Reference to the Processing Manager. */
  193. private final ProcessingManager myProcessingManager;
  194. /** Should we automatically disconnect on fatal errors?. */
  195. private boolean disconnectOnFatal = true;
  196. /** Current Socket State. */
  197. protected SocketState currentSocketState = SocketState.NULL;
  198. /**
  199. * The underlying socket used for reading/writing to the IRC server.
  200. * For normal sockets this will be the same as {@link #socket} but for SSL
  201. * connections this will be the underlying {@link Socket} while
  202. * {@link #socket} will be an {@link SSLSocket}.
  203. */
  204. private Socket rawSocket;
  205. /** Used for writing to the server. */
  206. private final OutputQueue out;
  207. /** The encoder to use to encode incoming lines. */
  208. private Encoder encoder = new SystemEncoder();
  209. /** Used for reading from the server. */
  210. private IRCReader in;
  211. /** This is the default TrustManager for SSL Sockets, it trusts all ssl certs. */
  212. private final TrustManager[] trustAllCerts = {new TrustingTrustManager()};
  213. /** Should channels automatically request list modes? */
  214. private boolean autoListMode = true;
  215. /** Should part/quit/kick callbacks be fired before removing the user internally? */
  216. private boolean removeAfterCallback = true;
  217. /** This is the TrustManager used for SSL Sockets. */
  218. private TrustManager[] myTrustManager = trustAllCerts;
  219. /** The KeyManagers used for client certificates for SSL sockets. */
  220. private KeyManager[] myKeyManagers;
  221. /** This is list containing 001 - 005 inclusive. */
  222. private final List<String> serverInformationLines = new LinkedList<>();
  223. /** Map of capabilities and their state. */
  224. private final Map<String, CapabilityState> capabilities = new HashMap<>();
  225. /** Handler for whois responses. */
  226. private final WhoisResponseHandler whoisHandler;
  227. /** Used to synchronize calls to resetState. */
  228. private final Object resetStateSync = new Object();
  229. /**
  230. * Default constructor, ServerInfo and MyInfo need to be added separately (using IRC.me and IRC.server).
  231. */
  232. public IRCParser() {
  233. this((MyInfo) null);
  234. }
  235. /**
  236. * Constructor with ServerInfo, MyInfo needs to be added separately (using IRC.me).
  237. *
  238. * @param uri The URI to connect to
  239. */
  240. public IRCParser(final URI uri) {
  241. this(null, uri);
  242. }
  243. /**
  244. * Constructor with MyInfo, ServerInfo needs to be added separately (using IRC.server).
  245. *
  246. * @param myDetails Client information.
  247. */
  248. public IRCParser(final MyInfo myDetails) {
  249. this(myDetails, null);
  250. }
  251. /**
  252. * Creates a new IRCParser with the specified client details which will
  253. * connect to the specified URI.
  254. *
  255. * @since 0.6.3
  256. * @param myDetails The client details to use
  257. * @param uri The URI to connect to
  258. */
  259. public IRCParser(final MyInfo myDetails, final URI uri) {
  260. super(uri);
  261. // TODO: There should be a factory or builder for parsers that can construct the graph
  262. final ObjectGraph graph = ObjectGraph.create(new IRCParserModule(this, prefixModes,
  263. userModes, chanModesBool));
  264. myProcessingManager = graph.get(ProcessingManager.class);
  265. myself = new IRCClientInfo(this, userModes, "myself").setFake(true);
  266. out = new OutputQueue();
  267. if (myDetails != null) {
  268. this.me = myDetails;
  269. }
  270. this.whoisHandler = new WhoisResponseHandler(this, getCallbackManager());
  271. setIgnoreList(new IgnoreList());
  272. setPingTimerInterval(10000);
  273. setPingTimerFraction(6);
  274. resetState();
  275. }
  276. /**
  277. * Get the current OutputQueue
  278. *
  279. * @return the current OutputQueue
  280. */
  281. public OutputQueue getOutputQueue() {
  282. return out;
  283. }
  284. @Override
  285. public boolean compareURI(final URI uri) {
  286. // Get the old URI.
  287. final URI oldURI = getURI();
  288. // Check that protocol, host and port are the same.
  289. // Anything else won't change the server we connect to just what we
  290. // would do after connecting, so is not relevent.
  291. return uri.getScheme().equalsIgnoreCase(oldURI.getScheme())
  292. && uri.getHost().equalsIgnoreCase(oldURI.getHost())
  293. && (uri.getUserInfo() == null || uri.getUserInfo().isEmpty()
  294. || uri.getUserInfo().equalsIgnoreCase(oldURI.getUserInfo() == null ? "" : oldURI.getUserInfo()))
  295. && uri.getPort() == oldURI.getPort();
  296. }
  297. /**
  298. * From the given URI, get a URI to actually connect to.
  299. * This function will check for DNS SRV records for the given URI and use
  300. * those if found.
  301. * If no SRV records exist, then fallback to using the URI as-is but with
  302. * a default port specified if none is given.
  303. *
  304. * @param uri Requested URI.
  305. * @return A connectable version of the given URI.
  306. */
  307. private URI getConnectURI(final URI uri) {
  308. if (uri == null) { return null; }
  309. final boolean isSSL = uri.getScheme().endsWith("s");
  310. final int defaultPort = isSSL ? IrcConstants.DEFAULT_SSL_PORT : IrcConstants.DEFAULT_PORT;
  311. // Default to what the URI has already..
  312. int port = uri.getPort();
  313. String host = uri.getHost();
  314. // Look for SRV records if no port is specified.
  315. if (port == -1) {
  316. List<SRVRecord> recordList = new ArrayList<>();
  317. if (isSSL) {
  318. // There are a few possibilities for ssl...
  319. final String[] protocols = {"_ircs._tcp.", "_irc._tls."};
  320. for (final String protocol : protocols) {
  321. recordList = SRVRecord.getRecords(protocol + host);
  322. if (!recordList.isEmpty()) {
  323. break;
  324. }
  325. }
  326. } else {
  327. recordList = SRVRecord.getRecords("_irc._tcp." + host);
  328. }
  329. if (!recordList.isEmpty()) {
  330. host = recordList.get(0).getHost();
  331. port = recordList.get(0).getPort();
  332. }
  333. }
  334. // Fix the port if required.
  335. if (port == -1) { port = defaultPort; }
  336. // Return the URI to connect to based on the above.
  337. try {
  338. return new URI(uri.getScheme(), uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment());
  339. } catch (URISyntaxException ex) {
  340. // Shouldn't happen - but return the URI as-is if it does.
  341. return uri;
  342. }
  343. }
  344. @Override
  345. public Collection<? extends ChannelJoinRequest> extractChannels(final URI uri) {
  346. if (uri == null) {
  347. return Collections.<ChannelJoinRequest>emptyList();
  348. }
  349. String channelString = uri.getPath();
  350. if (uri.getRawQuery() != null && !uri.getRawQuery().isEmpty()) {
  351. channelString += '?' + uri.getRawQuery();
  352. }
  353. if (uri.getRawFragment() != null && !uri.getRawFragment().isEmpty()) {
  354. channelString += '#' + uri.getRawFragment();
  355. }
  356. if (!channelString.isEmpty() && channelString.charAt(0) == '/') {
  357. channelString = channelString.substring(1);
  358. }
  359. return extractChannels(channelString);
  360. }
  361. /**
  362. * Extracts a set of channels and optional keys from the specified String.
  363. * Channels are separated by commas, and keys are separated from their
  364. * channels by a space.
  365. *
  366. * @since 0.6.4
  367. * @param channels The string of channels to parse
  368. * @return A corresponding collection of join request objects
  369. */
  370. protected Collection<? extends ChannelJoinRequest> extractChannels(final String channels) {
  371. final Collection<ChannelJoinRequest> res = new ArrayList<>();
  372. for (String channel : channels.split(",")) {
  373. final String[] parts = channel.split(" ", 2);
  374. if (parts.length == 2) {
  375. res.add(new ChannelJoinRequest(parts[0], parts[1]));
  376. } else {
  377. res.add(new ChannelJoinRequest(parts[0]));
  378. }
  379. }
  380. return res;
  381. }
  382. /**
  383. * Get the current Value of autoListMode.
  384. *
  385. * @return Value of autoListMode (true if channels automatically ask for list modes on join, else false)
  386. */
  387. public boolean getAutoListMode() {
  388. return autoListMode;
  389. }
  390. /**
  391. * Set the current Value of autoListMode.
  392. *
  393. * @param newValue New value to set autoListMode
  394. */
  395. public void setAutoListMode(final boolean newValue) {
  396. autoListMode = newValue;
  397. }
  398. /**
  399. * Get the current Value of removeAfterCallback.
  400. *
  401. * @return Value of removeAfterCallback (true if kick/part/quit callbacks are fired before internal removal)
  402. */
  403. public boolean getRemoveAfterCallback() {
  404. return removeAfterCallback;
  405. }
  406. /**
  407. * Get the current Value of removeAfterCallback.
  408. *
  409. * @param newValue New value to set removeAfterCallback
  410. */
  411. public void setRemoveAfterCallback(final boolean newValue) {
  412. removeAfterCallback = newValue;
  413. }
  414. /**
  415. * Get the current Value of addLastLine.
  416. *
  417. * @return Value of addLastLine (true if lastLine info will be automatically
  418. * added to the errorInfo data line). This should be true if lastLine
  419. * isn't handled any other way.
  420. */
  421. public boolean getAddLastLine() {
  422. return addLastLine;
  423. }
  424. /**
  425. * Get the current Value of addLastLine.
  426. *
  427. * @param newValue New value to set addLastLine
  428. */
  429. public void setAddLastLine(final boolean newValue) {
  430. addLastLine = newValue;
  431. }
  432. /**
  433. * Get the current socket State.
  434. *
  435. * @since 0.6.3m1
  436. * @return Current {@link SocketState}
  437. */
  438. public SocketState getSocketState() {
  439. return currentSocketState;
  440. }
  441. /**
  442. * Get a reference to the Processing Manager.
  443. *
  444. * @return Reference to the CallbackManager
  445. */
  446. public ProcessingManager getProcessingManager() {
  447. return myProcessingManager;
  448. }
  449. /**
  450. * Get a reference to the default TrustManager for SSL Sockets.
  451. *
  452. * @return a reference to trustAllCerts
  453. */
  454. public TrustManager[] getDefaultTrustManager() {
  455. return Arrays.copyOf(trustAllCerts, trustAllCerts.length);
  456. }
  457. /**
  458. * Get a reference to the current TrustManager for SSL Sockets.
  459. *
  460. * @return a reference to myTrustManager;
  461. */
  462. public TrustManager[] getTrustManager() {
  463. return Arrays.copyOf(myTrustManager, myTrustManager.length);
  464. }
  465. @Override
  466. public void setTrustManagers(final TrustManager... managers) {
  467. myTrustManager = managers == null ? null : Arrays.copyOf(managers, managers.length);
  468. }
  469. @Override
  470. public void setKeyManagers(final KeyManager... managers) {
  471. myKeyManagers = managers == null ? null : Arrays.copyOf(managers, managers.length);
  472. }
  473. //---------------------------------------------------------------------------
  474. // Start Callbacks
  475. //---------------------------------------------------------------------------
  476. /**
  477. * Callback to all objects implementing the ServerError Callback.
  478. *
  479. * @param message The error message
  480. */
  481. protected void callServerError(final String message) {
  482. getCallbackManager().publish(new ServerErrorEvent(this, LocalDateTime.now(), message));
  483. }
  484. /**
  485. * Callback to all objects implementing the DataIn Callback.
  486. *
  487. * @param line Incoming Line.
  488. */
  489. protected void callDataIn(final ReadLine line) {
  490. getCallbackManager().publish(new IRCDataInEvent(this, LocalDateTime.now(), line));
  491. }
  492. /**
  493. * Callback to all objects implementing the DataOut Callback.
  494. *
  495. * @param data Outgoing Data
  496. * @param fromParser True if parser sent the data, false if sent using .sendLine
  497. */
  498. protected void callDataOut(final String data, final boolean fromParser) {
  499. getCallbackManager().publish(new IRCDataOutEvent(this, LocalDateTime.now(), data));
  500. }
  501. /**
  502. * Callback to all objects implementing the DebugInfo Callback.
  503. *
  504. * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
  505. * @param data Debugging Information as a format string
  506. * @param args Formatting String Options
  507. */
  508. public void callDebugInfo(final int level, final String data, final Object... args) {
  509. callDebugInfo(level, String.format(data, args));
  510. }
  511. /**
  512. * Callback to all objects implementing the DebugInfo Callback.
  513. *
  514. * @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
  515. * @param data Debugging Information
  516. */
  517. protected void callDebugInfo(final int level, final String data) {
  518. getCallbackManager().publish(new DebugInfoEvent(this, LocalDateTime.now(), level, data));
  519. }
  520. /**
  521. * Callback to all objects implementing the IErrorInfo Interface.
  522. *
  523. * @param errorInfo ParserError object representing the error.
  524. */
  525. public void callErrorInfo(final ParserError errorInfo) {
  526. getCallbackManager().publish(new ErrorInfoEvent(this, LocalDateTime.now(), errorInfo));
  527. }
  528. /**
  529. * Callback to all objects implementing the IConnectError Interface.
  530. *
  531. * @param errorInfo ParserError object representing the error.
  532. */
  533. protected void callConnectError(final ParserError errorInfo) {
  534. getCallbackManager().publish(new ConnectErrorEvent(this, LocalDateTime.now(), errorInfo));
  535. }
  536. /**
  537. * Callback to all objects implementing the SocketClosed Callback.
  538. */
  539. protected void callSocketClosed() {
  540. // Don't allow state resetting whilst there may be handlers requiring
  541. // state.
  542. synchronized (resetStateSync) {
  543. getCallbackManager().publish(new SocketCloseEvent(this, LocalDateTime.now()));
  544. }
  545. }
  546. /**
  547. * Callback to all objects implementing the PingFailed Callback.
  548. */
  549. protected void callPingFailed() {
  550. getCallbackManager().publish(new PingFailureEvent(this, LocalDateTime.now()));
  551. }
  552. /**
  553. * Callback to all objects implementing the PingSent Callback.
  554. */
  555. protected void callPingSent() {
  556. getCallbackManager().publish(new PingSentEvent(this, LocalDateTime.now()));
  557. }
  558. /**
  559. * Callback to all objects implementing the PingSuccess Callback.
  560. */
  561. protected void callPingSuccess() {
  562. getCallbackManager().publish(new PingSuccessEvent(this, LocalDateTime.now()));
  563. }
  564. /**
  565. * Callback to all objects implementing the Post005 Callback.
  566. */
  567. protected synchronized void callPost005() {
  568. if (post005) {
  569. return;
  570. }
  571. post005 = true;
  572. if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) {
  573. parsePrefixModes();
  574. }
  575. if (!h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
  576. parseUserModes();
  577. }
  578. if (!h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) {
  579. parseChanModes();
  580. }
  581. whoisHandler.start();
  582. getCallbackManager().publish(new ServerReadyEvent(this, LocalDateTime.now()));
  583. }
  584. //---------------------------------------------------------------------------
  585. // End Callbacks
  586. //---------------------------------------------------------------------------
  587. /** Reset internal state (use before doConnect). */
  588. private void resetState() {
  589. synchronized (resetStateSync) {
  590. // Reset General State info
  591. got001 = false;
  592. post005 = false;
  593. // Clear the hash tables
  594. channelList.clear();
  595. clientList.clear();
  596. h005Info.clear();
  597. prefixModes.clear();
  598. chanModesOther.clear();
  599. chanModesBool.clear();
  600. userModes.clear();
  601. chanPrefix = DEFAULT_CHAN_PREFIX;
  602. // Clear output queue.
  603. if (out != null) {
  604. out.clearQueue();
  605. }
  606. setServerName("");
  607. networkName = "";
  608. lastLine = null;
  609. myself = new IRCClientInfo(this, userModes, "myself").setFake(true);
  610. synchronized (serverInformationLines) {
  611. serverInformationLines.clear();
  612. }
  613. stopPingTimer();
  614. currentSocketState = SocketState.CLOSED;
  615. setEncoding(IRCEncoding.RFC1459);
  616. whoisHandler.stop();
  617. }
  618. }
  619. /**
  620. * Called after other error callbacks.
  621. * CallbackOnErrorInfo automatically calls this *AFTER* any registered callbacks
  622. * for it are called.
  623. *
  624. * @param errorInfo ParserError object representing the error.
  625. * @param called True/False depending on the the success of other callbacks.
  626. */
  627. public void onPostErrorInfo(final ParserError errorInfo, final boolean called) {
  628. if (errorInfo.isFatal() && disconnectOnFatal) {
  629. disconnect("Fatal Parser Error");
  630. }
  631. }
  632. /**
  633. * Get the current Value of disconnectOnFatal.
  634. *
  635. * @return Value of disconnectOnFatal (true if the parser automatically disconnects on fatal errors, else false)
  636. */
  637. public boolean getDisconnectOnFatal() {
  638. return disconnectOnFatal;
  639. }
  640. /**
  641. * Set the current Value of disconnectOnFatal.
  642. *
  643. * @param newValue New value to set disconnectOnFatal
  644. */
  645. public void setDisconnectOnFatal(final boolean newValue) {
  646. disconnectOnFatal = newValue;
  647. }
  648. /**
  649. * Connect to IRC.
  650. *
  651. * @throws IOException if the socket can not be connected
  652. * @throws NoSuchAlgorithmException if SSL is not available
  653. * @throws KeyManagementException if the trustManager is invalid
  654. */
  655. private void doConnect() throws IOException, NoSuchAlgorithmException, KeyManagementException {
  656. if (getURI() == null || getURI().getHost() == null) {
  657. throw new UnknownHostException("Unspecified host.");
  658. }
  659. resetState();
  660. callDebugInfo(DEBUG_SOCKET, "Connecting to " + getURI().getHost() + ':' + getURI().getPort());
  661. currentSocketState = SocketState.OPENING;
  662. final URI connectUri = getConnectURI(getURI());
  663. rawSocket = getSocketFactory().createSocket(connectUri.getHost(), connectUri.getPort());
  664. final Socket socket;
  665. if (getURI().getScheme().endsWith("s")) {
  666. callDebugInfo(DEBUG_SOCKET, "Server is SSL.");
  667. if (myTrustManager == null) {
  668. myTrustManager = trustAllCerts;
  669. }
  670. final SSLContext sc = SSLContext.getInstance("SSL");
  671. sc.init(myKeyManagers, myTrustManager, new SecureRandom());
  672. final SSLSocketFactory socketFactory = sc.getSocketFactory();
  673. socket = socketFactory.createSocket(rawSocket, getURI().getHost(), getURI()
  674. .getPort(), false);
  675. // Manually start a handshake so we get proper SSL errors here,
  676. // and so that we can control the connection timeout
  677. final int timeout = socket.getSoTimeout();
  678. socket.setSoTimeout(10000);
  679. ((SSLSocket) socket).startHandshake();
  680. socket.setSoTimeout(timeout);
  681. currentSocketState = SocketState.OPENING;
  682. } else {
  683. socket = rawSocket;
  684. }
  685. callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter");
  686. out.setOutputStream(socket.getOutputStream());
  687. out.setQueueEnabled(true);
  688. currentSocketState = SocketState.OPEN;
  689. callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader");
  690. in = new IRCReader(socket.getInputStream(), encoder);
  691. callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened");
  692. }
  693. /**
  694. * Send server connection strings (NICK/USER/PASS).
  695. */
  696. protected void sendConnectionStrings() {
  697. sendString("CAP LS");
  698. if (getURI().getUserInfo() != null && !getURI().getUserInfo().isEmpty()) {
  699. sendString("PASS " + getURI().getUserInfo());
  700. }
  701. sendString("NICK " + me.getNickname());
  702. thinkNickname = me.getNickname();
  703. String localhost;
  704. try {
  705. localhost = InetAddress.getLocalHost().getHostAddress();
  706. } catch (UnknownHostException uhe) {
  707. localhost = "*";
  708. }
  709. sendString("USER " + me.getUsername() + ' ' + localhost + ' ' + getURI().getHost() + " :" + me.getRealname());
  710. }
  711. /**
  712. * Handle an onConnect error.
  713. *
  714. * @param e Exception to handle
  715. * @param isUserError Is this a user error?
  716. */
  717. private void handleConnectException(final Exception e, final boolean isUserError) {
  718. callDebugInfo(DEBUG_SOCKET, "Error Connecting (" + e.getMessage() + "), Aborted");
  719. final ParserError ei = new ParserError(ParserError.ERROR_ERROR + (isUserError ? ParserError.ERROR_USER : 0), "Exception with server socket", getLastLine());
  720. ei.setException(e);
  721. callConnectError(ei);
  722. if (currentSocketState != SocketState.CLOSED) {
  723. currentSocketState = SocketState.CLOSED;
  724. callSocketClosed();
  725. }
  726. resetState();
  727. }
  728. /**
  729. * Begin execution.
  730. * Connect to server, and start parsing incoming lines
  731. */
  732. @Override
  733. public void run() {
  734. callDebugInfo(DEBUG_INFO, "Begin Thread Execution");
  735. if (hasBegan) {
  736. return;
  737. } else {
  738. hasBegan = true;
  739. }
  740. try {
  741. doConnect();
  742. } catch (IOException e) {
  743. handleConnectException(e, true);
  744. return;
  745. } catch (NoSuchAlgorithmException | KeyManagementException e) {
  746. handleConnectException(e, false);
  747. return;
  748. }
  749. callDebugInfo(DEBUG_SOCKET, "Socket Connected");
  750. sendConnectionStrings();
  751. while (true) {
  752. try {
  753. lastLine = in.readLine(); // Blocking :/
  754. if (lastLine == null) {
  755. if (currentSocketState != SocketState.CLOSED) {
  756. currentSocketState = SocketState.CLOSED;
  757. callSocketClosed();
  758. }
  759. resetState();
  760. break;
  761. } else if (currentSocketState != SocketState.CLOSING) {
  762. processLine(lastLine);
  763. }
  764. } catch (IOException e) {
  765. callDebugInfo(DEBUG_SOCKET, "Exception in main loop (" + e.getMessage() + "), Aborted");
  766. if (currentSocketState != SocketState.CLOSED) {
  767. currentSocketState = SocketState.CLOSED;
  768. callSocketClosed();
  769. }
  770. resetState();
  771. break;
  772. }
  773. }
  774. callDebugInfo(DEBUG_INFO, "End Thread Execution");
  775. }
  776. /** Close socket on destroy. */
  777. @Override
  778. protected void finalize() throws Throwable {
  779. try {
  780. // See note at disconnect() method for why we close rawSocket.
  781. if (rawSocket != null) {
  782. rawSocket.close();
  783. }
  784. } catch (IOException e) {
  785. callDebugInfo(DEBUG_SOCKET, "Could not close socket");
  786. }
  787. super.finalize();
  788. }
  789. /**
  790. * Get the trailing parameter for a line.
  791. * The parameter is everything after the first occurrence of " :" to the last token in the line after a space.
  792. *
  793. * @param line Line to get parameter for
  794. * @return Parameter of the line
  795. */
  796. public static String getParam(final String line) {
  797. final String[] params = line.split(" :", 2);
  798. return params[params.length - 1];
  799. }
  800. /**
  801. * Tokenise a line.
  802. * splits by " " up to the first " :" everything after this is a single token
  803. *
  804. * @param line Line to tokenise
  805. * @return Array of tokens
  806. */
  807. public static String[] tokeniseLine(final String line) {
  808. if (line == null || line.isEmpty()) {
  809. return new String[]{""};
  810. }
  811. int lastarg = line.indexOf(" :");
  812. String[] tokens;
  813. // Check for IRC Tags.
  814. if (line.charAt(0) == '@') {
  815. // We have tags.
  816. tokens = line.split(" ", 2);
  817. final int tsEnd = tokens[0].indexOf('@', 1);
  818. boolean hasTSIRCDate = false;
  819. if (tsEnd > -1) {
  820. try {
  821. final long ts = Long.parseLong(tokens[0].substring(1, tsEnd));
  822. hasTSIRCDate = true;
  823. } catch (final NumberFormatException nfe) { /* Not a timestamp. */ }
  824. }
  825. if (!hasTSIRCDate) {
  826. // IRCv3 Tags, last arg is actually the second " :"
  827. lastarg = line.indexOf(" :", lastarg+1);
  828. }
  829. }
  830. if (lastarg > -1) {
  831. final String[] temp = line.substring(0, lastarg).split(" ");
  832. tokens = new String[temp.length + 1];
  833. System.arraycopy(temp, 0, tokens, 0, temp.length);
  834. tokens[temp.length] = line.substring(lastarg + 2);
  835. } else {
  836. tokens = line.split(" ");
  837. }
  838. if (tokens.length < 1) {
  839. tokens = new String[]{""};
  840. }
  841. return tokens;
  842. }
  843. @Override
  844. public IRCClientInfo getClient(final String details) {
  845. final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(details));
  846. if (clientList.containsKey(sWho)) {
  847. return clientList.get(sWho);
  848. } else {
  849. return new IRCClientInfo(this, userModes, details).setFake(true);
  850. }
  851. }
  852. public boolean isKnownClient(final String host) {
  853. final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(host));
  854. return clientList.containsKey(sWho);
  855. }
  856. @Override
  857. public IRCChannelInfo getChannel(final String channel) {
  858. synchronized (channelList) {
  859. return channelList.get(getStringConverter().toLowerCase(channel));
  860. }
  861. }
  862. @Override
  863. public void sendInvite(final String channel, final String user) {
  864. sendRawMessage("INVITE " + user + ' ' + channel);
  865. }
  866. @Override
  867. public void sendWhois(final String nickname) {
  868. sendRawMessage("WHOIS " + nickname);
  869. }
  870. @Override
  871. public void sendRawMessage(final String message) {
  872. doSendString(message, QueuePriority.NORMAL, false);
  873. }
  874. @Override
  875. public void sendRawMessage(final String message, final QueuePriority priority) {
  876. doSendString(message, priority, false);
  877. }
  878. /**
  879. * Send a line to the server and add proper line ending.
  880. *
  881. * @param line Line to send (\r\n termination is added automatically)
  882. * @return True if line was sent, else false.
  883. */
  884. public boolean sendString(final String line) {
  885. return doSendString(line, QueuePriority.NORMAL, true);
  886. }
  887. /**
  888. * Send a line to the server and add proper line ending.
  889. * If a non-empty argument is given, it is appended as a trailing argument
  890. * (i.e., separated by " :"); otherwise, the line is sent as-is.
  891. *
  892. * @param line Line to send
  893. * @param argument Trailing argument for the command, if any
  894. * @return True if line was sent, else false.
  895. */
  896. protected boolean sendString(final String line, final String argument) {
  897. return sendString(argument.isEmpty() ? line : line + " :" + argument);
  898. }
  899. /**
  900. * Send a line to the server and add proper line ending.
  901. *
  902. * @param line Line to send (\r\n termination is added automatically)
  903. * @param priority Priority of this line.
  904. * @return True if line was sent, else false.
  905. */
  906. public boolean sendString(final String line, final QueuePriority priority) {
  907. return doSendString(line, priority, true);
  908. }
  909. /**
  910. * Send a line to the server and add proper line ending.
  911. *
  912. * @param line Line to send (\r\n termination is added automatically)
  913. * @param priority Priority of this line.
  914. * @param fromParser is this line from the parser? (used for callDataOut)
  915. * @return True if line was sent, else false.
  916. */
  917. protected boolean doSendString(final String line, final QueuePriority priority, final boolean fromParser) {
  918. if (out == null || getSocketState() != SocketState.OPEN) {
  919. return false;
  920. }
  921. callDataOut(line, fromParser);
  922. out.sendLine(line, priority);
  923. final String[] newLine = tokeniseLine(line);
  924. if ("away".equalsIgnoreCase(newLine[0]) && newLine.length > 1) {
  925. myself.setAwayReason(newLine[newLine.length - 1]);
  926. } else if ("mode".equalsIgnoreCase(newLine[0]) && newLine.length == 3) {
  927. final IRCChannelInfo channel = getChannel(newLine[1]);
  928. if (channel != null) {
  929. // This makes sure we don't add the same item to the LMQ twice,
  930. // even if its requested twice, as the ircd will only reply once
  931. final Queue<Character> foundModes = new LinkedList<>();
  932. final Queue<Character> listModeQueue = channel.getListModeQueue();
  933. for (int i = 0; i < newLine[2].length(); ++i) {
  934. final Character mode = newLine[2].charAt(i);
  935. callDebugInfo(DEBUG_LMQ, "Intercepted mode request for " + channel + " for mode " + mode);
  936. if (chanModesOther.containsKey(mode) && chanModesOther.get(mode) == MODE_LIST) {
  937. if (foundModes.contains(mode)) {
  938. callDebugInfo(DEBUG_LMQ, "Already added to LMQ");
  939. } else {
  940. listModeQueue.offer(mode);
  941. foundModes.offer(mode);
  942. callDebugInfo(DEBUG_LMQ, "Added to LMQ");
  943. }
  944. }
  945. }
  946. }
  947. }
  948. return true;
  949. }
  950. @Override
  951. public String getNetworkName() {
  952. return networkName;
  953. }
  954. @Override
  955. public String getLastLine() {
  956. return lastLine == null ? "" : lastLine.getLine();
  957. }
  958. @Override
  959. public List<String> getServerInformationLines() {
  960. synchronized (serverInformationLines) {
  961. return new LinkedList<>(serverInformationLines);
  962. }
  963. }
  964. /**
  965. * Process a line and call relevant methods for handling.
  966. *
  967. * @param line Line read from the IRC server
  968. */
  969. @SuppressWarnings("fallthrough")
  970. protected void processLine(final ReadLine line) {
  971. callDataIn(line);
  972. final String[] token = line.getTokens();
  973. LocalDateTime lineTS = LocalDateTime.now();
  974. if (line.getTags().containsKey("tsirc date")) {
  975. try {
  976. final long ts = Long.parseLong(line.getTags().get("tsirc date")) - tsdiff;
  977. lineTS = LocalDateTime.ofEpochSecond(ts / 1000L, (int) (ts % 1000L), ZoneOffset.UTC);
  978. } catch (final NumberFormatException nfe) { /* Do nothing. */ }
  979. } else if (line.getTags().containsKey("time")) {
  980. try {
  981. lineTS = LocalDateTime.parse(line.getTags().get("time"),
  982. DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
  983. } catch (final DateTimeParseException pe) { /* Do nothing. */ }
  984. }
  985. setPingNeeded(false);
  986. if (token.length < 2) {
  987. return;
  988. }
  989. try {
  990. final String sParam = token[1];
  991. if ("PING".equalsIgnoreCase(token[0]) || "PING".equalsIgnoreCase(token[1])) {
  992. sendString("PONG :" + sParam, QueuePriority.HIGH);
  993. } else if ("PONG".equalsIgnoreCase(token[0]) || "PONG".equalsIgnoreCase(token[1])) {
  994. if (!lastPingValue.isEmpty() && lastPingValue.equals(token[token.length - 1])) {
  995. lastPingValue = "";
  996. serverLag = System.currentTimeMillis() - pingTime;
  997. callPingSuccess();
  998. }
  999. } else if ("ERROR".equalsIgnoreCase(token[0])) {
  1000. final StringBuilder errorMessage = new StringBuilder();
  1001. for (int i = 1; i < token.length; ++i) {
  1002. errorMessage.append(token[i]);
  1003. }
  1004. callServerError(errorMessage.toString());
  1005. } else if ("TSIRC".equalsIgnoreCase(token[1]) && token.length > 3) {
  1006. if ("1".equals(token[2])) {
  1007. try {
  1008. final long ts = Long.parseLong(token[3]);
  1009. tsdiff = ts - System.currentTimeMillis();
  1010. } catch (final NumberFormatException nfe) { /* Do nothing. */ }
  1011. }
  1012. } else {
  1013. int nParam;
  1014. if (got001) {
  1015. // Freenode sends a random notice in a stupid place, others might do aswell
  1016. // These shouldn't cause post005 to be fired, so handle them here.
  1017. if ("NOTICE".equalsIgnoreCase(token[0]) ||
  1018. token.length > 2 && "NOTICE".equalsIgnoreCase(token[2])) {
  1019. try {
  1020. myProcessingManager.process(lineTS, "Notice Auth", token);
  1021. } catch (ProcessorNotFoundException e) {
  1022. // ???
  1023. }
  1024. return;
  1025. }
  1026. if (!post005) {
  1027. try {
  1028. nParam = Integer.parseInt(token[1]);
  1029. } catch (NumberFormatException e) {
  1030. nParam = -1;
  1031. }
  1032. if (nParam < 0 || nParam > 5) {
  1033. callPost005();
  1034. } else {
  1035. // Store 001 - 005 for informational purposes.
  1036. synchronized (serverInformationLines) {
  1037. serverInformationLines.add(line.getLine());
  1038. }
  1039. }
  1040. }
  1041. // After 001 we potentially care about everything!
  1042. try {
  1043. myProcessingManager.process(lineTS, sParam, token);
  1044. } catch (ProcessorNotFoundException e) {
  1045. // ???
  1046. }
  1047. } else {
  1048. // Before 001 we don't care about much.
  1049. try {
  1050. nParam = Integer.parseInt(token[1]);
  1051. } catch (NumberFormatException e) {
  1052. nParam = -1;
  1053. }
  1054. switch (nParam) {
  1055. case 1: // 001 - Welcome to IRC
  1056. synchronized (serverInformationLines) {
  1057. serverInformationLines.add(line.getLine());
  1058. }
  1059. // Fallthrough
  1060. case IrcConstants.NUMERIC_ERROR_PASSWORD_MISMATCH:
  1061. case IrcConstants.NUMERIC_ERROR_NICKNAME_IN_USE:
  1062. try {
  1063. myProcessingManager.process(sParam, token);
  1064. } catch (ProcessorNotFoundException e) {
  1065. }
  1066. break;
  1067. default: // Unknown - Send to Notice Auth
  1068. // Some networks send a CTCP during the auth process, handle it
  1069. if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char) 1 && token[3].charAt(token[3].length() - 1) == (char) 1) {
  1070. try {
  1071. myProcessingManager.process(lineTS, sParam, token);
  1072. } catch (ProcessorNotFoundException e) {
  1073. }
  1074. break;
  1075. }
  1076. // Some networks may send a NICK message if you nick change before 001
  1077. // Eat it up so that it isn't treated as a notice auth.
  1078. if ("NICK".equalsIgnoreCase(token[1])) {
  1079. break;
  1080. }
  1081. // CAP also happens here, so try that.
  1082. if ("CAP".equalsIgnoreCase(token[1])) {
  1083. myProcessingManager.process(lineTS, sParam, token);
  1084. break;
  1085. }
  1086. // Otherwise, send to Notice Auth
  1087. try {
  1088. myProcessingManager.process(lineTS, "Notice Auth", token);
  1089. } catch (ProcessorNotFoundException e) {
  1090. }
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. } catch (Exception e) {
  1096. final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Fatal Exception in Parser.", getLastLine());
  1097. ei.setException(e);
  1098. callErrorInfo(ei);
  1099. }
  1100. }
  1101. /** The IRCStringConverter for this parser */
  1102. private IRCStringConverter stringConverter;
  1103. @Override
  1104. public IRCStringConverter getStringConverter() {
  1105. if (stringConverter == null) {
  1106. stringConverter = new IRCStringConverter(IRCEncoding.RFC1459);
  1107. }
  1108. return stringConverter;
  1109. }
  1110. /**
  1111. * Sets the encoding that this parser's string converter should use.
  1112. *
  1113. * @param encoding The encoding to use
  1114. */
  1115. public void setEncoding(final IRCEncoding encoding) {
  1116. stringConverter = new IRCStringConverter(encoding);
  1117. }
  1118. /**
  1119. * Check the state of the requested capability.
  1120. *
  1121. * @param capability The capability to check the state of.
  1122. * @return State of the requested capability.
  1123. */
  1124. public CapabilityState getCapabilityState(final String capability) {
  1125. synchronized (capabilities) {
  1126. if (capabilities.containsKey(capability.toLowerCase())) {
  1127. return capabilities.get(capability.toLowerCase());
  1128. } else {
  1129. return CapabilityState.INVALID;
  1130. }
  1131. }
  1132. }
  1133. /**
  1134. * Set the state of the requested capability.
  1135. *
  1136. * @param capability Requested capability
  1137. * @param state State to set for capability
  1138. */
  1139. public void setCapabilityState(final String capability, final CapabilityState state) {
  1140. synchronized (capabilities) {
  1141. if (capabilities.containsKey(capability.toLowerCase())) {
  1142. capabilities.put(capability.toLowerCase(), state);
  1143. }
  1144. }
  1145. }
  1146. /**
  1147. * Add the given capability as a supported capability by the server.
  1148. *
  1149. * @param capability Requested capability
  1150. */
  1151. public void addCapability(final String capability) {
  1152. synchronized (capabilities) {
  1153. capabilities.put(capability.toLowerCase(), CapabilityState.DISABLED);
  1154. }
  1155. }
  1156. /**
  1157. * Get the server capabilities and their current state.
  1158. *
  1159. * @return Server capabilities and their current state.
  1160. */
  1161. public Map<String, CapabilityState> getCapabilities() {
  1162. synchronized (capabilities) {
  1163. return new HashMap<>(capabilities);
  1164. }
  1165. }
  1166. /**
  1167. * Process CHANMODES from 005.
  1168. */
  1169. public void parseChanModes() {
  1170. final StringBuilder sDefaultModes = new StringBuilder("b,k,l,");
  1171. String modeStr;
  1172. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) {
  1173. if (getServerType() == ServerType.DANCER) {
  1174. sDefaultModes.insert(0, "dqeI");
  1175. } else if (getServerType() == ServerType.AUSTIRC) {
  1176. sDefaultModes.insert(0, 'e');
  1177. }
  1178. modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES);
  1179. for (int i = 0; i < modeStr.length(); ++i) {
  1180. final char mode = modeStr.charAt(i);
  1181. if (!prefixModes.isPrefixMode(mode)
  1182. && sDefaultModes.indexOf(Character.toString(mode)) < 0) {
  1183. sDefaultModes.append(mode);
  1184. }
  1185. }
  1186. } else {
  1187. sDefaultModes.append("imnpstrc");
  1188. }
  1189. if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) {
  1190. modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_MODES);
  1191. } else {
  1192. modeStr = sDefaultModes.toString();
  1193. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
  1194. }
  1195. String[] bits = modeStr.split(",", 5);
  1196. if (bits.length < 4) {
  1197. modeStr = sDefaultModes.toString();
  1198. callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. " +
  1199. "Using default string of \"" + modeStr + '"', getLastLine()));
  1200. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
  1201. bits = modeStr.split(",", 5);
  1202. }
  1203. // resetState
  1204. chanModesOther.clear();
  1205. // List modes.
  1206. for (int i = 0; i < bits[0].length(); ++i) {
  1207. final Character cMode = bits[0].charAt(i);
  1208. callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode);
  1209. if (!chanModesOther.containsKey(cMode)) {
  1210. chanModesOther.put(cMode, MODE_LIST);
  1211. }
  1212. }
  1213. // Param for Set and Unset.
  1214. final Byte nBoth = MODE_SET + MODE_UNSET;
  1215. for (int i = 0; i < bits[1].length(); ++i) {
  1216. final Character cMode = bits[1].charAt(i);
  1217. callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode);
  1218. if (!chanModesOther.containsKey(cMode)) {
  1219. chanModesOther.put(cMode, nBoth);
  1220. }
  1221. }
  1222. // Param just for Set
  1223. for (int i = 0; i < bits[2].length(); ++i) {
  1224. final Character cMode = bits[2].charAt(i);
  1225. callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode);
  1226. if (!chanModesOther.containsKey(cMode)) {
  1227. chanModesOther.put(cMode, MODE_SET);
  1228. }
  1229. }
  1230. // Boolean Mode
  1231. chanModesBool.set(bits[3]);
  1232. callDebugInfo(DEBUG_INFO, "Found boolean modes: %s", bits[3]);
  1233. }
  1234. @Override
  1235. public String getChannelUserModes() {
  1236. return prefixModes.getPrefixes();
  1237. }
  1238. @Override
  1239. public String getBooleanChannelModes() {
  1240. return chanModesBool.getModes();
  1241. }
  1242. @Override
  1243. public String getListChannelModes() {
  1244. return getOtherModeString(MODE_LIST);
  1245. }
  1246. @Override
  1247. public String getParameterChannelModes() {
  1248. return getOtherModeString(MODE_SET);
  1249. }
  1250. @Override
  1251. public String getDoubleParameterChannelModes() {
  1252. return getOtherModeString((byte) (MODE_SET + MODE_UNSET));
  1253. }
  1254. @Override
  1255. public String getChannelPrefixes() {
  1256. return chanPrefix;
  1257. }
  1258. /**
  1259. * Get modes from hChanModesOther that have a specific value.
  1260. * Modes are returned in alphabetical order
  1261. *
  1262. * @param value Value mode must have to be included
  1263. * @return All the currently known Set-Unset modes
  1264. */
  1265. protected String getOtherModeString(final byte value) {
  1266. final char[] modes = new char[chanModesOther.size()];
  1267. int i = 0;
  1268. for (char cTemp : chanModesOther.keySet()) {
  1269. final Byte nTemp = chanModesOther.get(cTemp);
  1270. if (nTemp == value) {
  1271. modes[i] = cTemp;
  1272. i++;
  1273. }
  1274. }
  1275. // Alphabetically sort the array
  1276. Arrays.sort(modes);
  1277. return new String(modes).trim();
  1278. }
  1279. @Override
  1280. public String getUserModes() {
  1281. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
  1282. return h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
  1283. } else {
  1284. return "";
  1285. }
  1286. }
  1287. /**
  1288. * Process USERMODES from 004.
  1289. */
  1290. public void parseUserModes() {
  1291. final String modeStr;
  1292. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
  1293. modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
  1294. } else {
  1295. final String sDefaultModes = "nwdoi";
  1296. modeStr = sDefaultModes;
  1297. h005Info.put(IrcConstants.ISUPPORT_USER_MODES, sDefaultModes);
  1298. }
  1299. userModes.set(modeStr);
  1300. }
  1301. /**
  1302. * Resets the channel prefix property to the default, RFC specified value.
  1303. */
  1304. public void resetChanPrefix() {
  1305. chanPrefix = DEFAULT_CHAN_PREFIX;
  1306. }
  1307. /**
  1308. * Sets the set of possible channel prefixes to those in the given value.
  1309. *
  1310. * @param value The new set of channel prefixes.
  1311. */
  1312. public void setChanPrefix(final String value) {
  1313. chanPrefix = value;
  1314. }
  1315. /**
  1316. * Process PREFIX from 005.
  1317. */
  1318. public void parsePrefixModes() {
  1319. final String sDefaultModes = "(ohv)@%+";
  1320. String modeStr;
  1321. if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) {
  1322. modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES);
  1323. } else {
  1324. modeStr = sDefaultModes;
  1325. }
  1326. if ("(".equals(modeStr.substring(0, 1))) {
  1327. modeStr = modeStr.substring(1);
  1328. } else {
  1329. modeStr = sDefaultModes.substring(1);
  1330. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
  1331. }
  1332. int closingIndex = modeStr.indexOf(')');
  1333. if (closingIndex * 2 + 1 != modeStr.length()) {
  1334. callErrorInfo(new ParserError(ParserError.ERROR_ERROR,
  1335. "PREFIX String not valid. Using default string of \"" + modeStr +
  1336. '"', getLastLine()));
  1337. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
  1338. modeStr = sDefaultModes.substring(1);
  1339. closingIndex = modeStr.indexOf(')');
  1340. }
  1341. // The modes passed from the server are in descending order of importance, we want to
  1342. // store them in ascending, so reverse them:
  1343. final String reversedModes = new StringBuilder(modeStr).reverse().toString();
  1344. prefixModes.setModes(reversedModes.substring(closingIndex + 1),
  1345. reversedModes.substring(0, closingIndex));
  1346. }
  1347. @Override
  1348. public void joinChannels(final ChannelJoinRequest... channels) {
  1349. // We store a map from key->channels to allow intelligent joining of
  1350. // channels using as few JOIN commands as needed.
  1351. final Map<String, StringBuffer> joinMap = new HashMap<>();
  1352. for (ChannelJoinRequest channel : channels) {
  1353. // Make sure we have a list to put stuff in.
  1354. StringBuffer list = joinMap.get(channel.getPassword());
  1355. if (list == null) {
  1356. list = new StringBuffer();
  1357. joinMap.put(channel.getPassword(), list);
  1358. }
  1359. // Add the channel to the list. If the name is invalid and
  1360. // autoprefix is off we will just skip this channel.
  1361. if (!channel.getName().isEmpty()) {
  1362. if (list.length() > 0) {
  1363. list.append(',');
  1364. }
  1365. if (!isValidChannelName(channel.getName())) {
  1366. if (chanPrefix.isEmpty()) {
  1367. // TODO: This is wrong - empty chan prefix means the
  1368. // IRCd supports no channels.
  1369. list.append('#');
  1370. } else {
  1371. list.append(chanPrefix.charAt(0));
  1372. }
  1373. }
  1374. list.append(channel.getName());
  1375. }
  1376. }
  1377. for (Map.Entry<String, StringBuffer> entrySet : joinMap.entrySet()) {
  1378. final String thisKey = entrySet.getKey();
  1379. final String channelString = entrySet.getValue().toString();
  1380. if (!channelString.isEmpty()) {
  1381. if (thisKey == null || thisKey.isEmpty()) {
  1382. sendString("JOIN " + channelString);
  1383. } else {
  1384. sendString("JOIN " + channelString + ' ' + thisKey);
  1385. }
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Leave a Channel.
  1391. *
  1392. * @param channel Name of channel to part
  1393. * @param reason Reason for leaving (Nothing sent if sReason is "")
  1394. */
  1395. public void partChannel(final String channel, final String reason) {
  1396. if (getChannel(channel) == null) {
  1397. return;
  1398. }
  1399. sendString("PART " + channel, reason);
  1400. }
  1401. /**
  1402. * Set Nickname.
  1403. *
  1404. * @param nickname New nickname wanted.
  1405. */
  1406. public void setNickname(final String nickname) {
  1407. if (getSocketState() == SocketState.OPEN) {
  1408. if (!myself.isFake() && myself.getRealNickname().equals(nickname)) {
  1409. return;
  1410. }
  1411. sendString("NICK " + nickname);
  1412. } else {
  1413. me.setNickname(nickname);
  1414. }
  1415. thinkNickname = nickname;
  1416. }
  1417. @Override
  1418. public int getMaxLength(final String type, final String target) {
  1419. // If my host is "nick!user@host" and we are sending "#Channel"
  1420. // a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :"
  1421. // and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases.
  1422. // Lint = the 2 ":" at the start and end and the 3 separating " "s
  1423. int length = 0;
  1424. if (type != null) {
  1425. length += type.length();
  1426. }
  1427. if (target != null) {
  1428. length += target.length();
  1429. }
  1430. return getMaxLength(length);
  1431. }
  1432. /**
  1433. * Get the max length a message can be.
  1434. *
  1435. * @param length Length of stuff. (Ie "PRIVMSG"+"#Channel")
  1436. * @return Max Length message should be.
  1437. */
  1438. public int getMaxLength(final int length) {
  1439. final int lineLint = 5;
  1440. if (myself.isFake()) {
  1441. callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "getMaxLength() called, but I don't know who I am?", getLastLine()));
  1442. return MAX_LINELENGTH - length - lineLint;
  1443. } else {
  1444. return MAX_LINELENGTH - myself.toString().length() - length - lineLint;
  1445. }
  1446. }
  1447. @Override
  1448. public int getMaxListModes(final char mode) {
  1449. // MAXLIST=bdeI:50
  1450. // MAXLIST=b:60,e:60,I:60
  1451. // MAXBANS=30
  1452. callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: " + mode);
  1453. // Try in MAXLIST
  1454. int result = -2;
  1455. if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES) != null) {
  1456. if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) == null) {
  1457. result = 0;
  1458. }
  1459. final String maxlist = h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES);
  1460. callDebugInfo(DEBUG_INFO, "Found maxlist (" + maxlist + ')');
  1461. final String[] bits = maxlist.split(",");
  1462. for (String bit : bits) {
  1463. final String[] parts = bit.split(":", 2);
  1464. callDebugInfo(DEBUG_INFO, "Bit: " + bit + " | parts.length = " + parts.length + " ("
  1465. + parts[0] + " -> " + parts[0].indexOf(mode) + ')');
  1466. if (parts.length == 2 && parts[0].indexOf(mode) > -1) {
  1467. callDebugInfo(DEBUG_INFO, "parts[0] = '" + parts[0] + "' | parts[1] = '"
  1468. + parts[1] + '\'');
  1469. try {
  1470. result = Integer.parseInt(parts[1]);
  1471. break;
  1472. } catch (NumberFormatException nfe) {
  1473. result = -1;
  1474. }
  1475. }
  1476. }
  1477. }
  1478. // If not in max list, try MAXBANS
  1479. if (result == -2 && h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) != null) {
  1480. callDebugInfo(DEBUG_INFO, "Trying max bans");
  1481. try {
  1482. result = Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS));
  1483. } catch (NumberFormatException nfe) {
  1484. result = -1;
  1485. }
  1486. } else if (result == -2 && getServerType() == ServerType.WEIRCD) {
  1487. result = 50;
  1488. } else if (result == -2 && getServerType() == ServerType.OTHERNET) {
  1489. result = 30;
  1490. } else if (result == -2) {
  1491. result = -1;
  1492. callDebugInfo(DEBUG_INFO, "Failed");
  1493. callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "Unable to discover max list modes.", getLastLine()));
  1494. }
  1495. callDebugInfo(DEBUG_INFO, "Result: " + result);
  1496. return result;
  1497. }
  1498. @Override
  1499. public void sendMessage(final String target, final String message) {
  1500. if (target == null || message == null) {
  1501. return;
  1502. }
  1503. if (target.isEmpty()) {
  1504. return;
  1505. }
  1506. sendString("PRIVMSG " + target, message);
  1507. }
  1508. @Override
  1509. public void sendNotice(final String target, final String message) {
  1510. if (target == null || message == null) {
  1511. return;
  1512. }
  1513. if (target.isEmpty()) {
  1514. return;
  1515. }
  1516. sendString("NOTICE " + target, message);
  1517. }
  1518. @Override
  1519. public void sendAction(final String target, final String message) {
  1520. sendCTCP(target, "ACTION", message);
  1521. }
  1522. @Override
  1523. public void sendCTCP(final String target, final String type, final String message) {
  1524. if (target == null || message == null) {
  1525. return;
  1526. }
  1527. if (target.isEmpty() || type.isEmpty()) {
  1528. return;
  1529. }
  1530. final char char1 = (char) 1;
  1531. sendString("PRIVMSG " + target, char1 + type.toUpperCase() + ' ' + message + char1);
  1532. }
  1533. @Override
  1534. public void sendCTCPReply(final String target, final String type, final String message) {
  1535. if (target == null || message == null) {
  1536. return;
  1537. }
  1538. if (target.isEmpty() || type.isEmpty()) {
  1539. return;
  1540. }
  1541. final char char1 = (char) 1;
  1542. sendString("NOTICE " + target, char1 + type.toUpperCase() + ' ' + message + char1);
  1543. }
  1544. @Override
  1545. public void requestGroupList(final String searchTerms) {
  1546. sendString("LIST", searchTerms);
  1547. }
  1548. @Override
  1549. public void quit(final String reason) {
  1550. sendString("QUIT", reason);
  1551. }
  1552. @Override
  1553. public void disconnect(final String message) {
  1554. super.disconnect(message);
  1555. if (currentSocketState == SocketState.OPENING || currentSocketState == SocketState.OPEN) {
  1556. currentSocketState = SocketState.CLOSING;
  1557. if (got001) {
  1558. quit(message);
  1559. }
  1560. }
  1561. try {
  1562. // SSLSockets try to close nicely and read data from the socket,
  1563. // which seems to hang indefinitely in some circumstances. We don't
  1564. // like indefinite hangs, so just close the underlying socket
  1565. // direct.
  1566. if (rawSocket != null) {
  1567. rawSocket.close();
  1568. }
  1569. } catch (IOException e) {
  1570. /* Do Nothing */
  1571. } finally {
  1572. if (currentSocketState != SocketState.CLOSED) {
  1573. currentSocketState = SocketState.CLOSED;
  1574. callSocketClosed();
  1575. }
  1576. resetState();
  1577. }
  1578. }
  1579. /** {@inheritDoc}
  1580. *
  1581. * - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks
  1582. * that the first character is either #, &amp;, ! or +
  1583. * - Assumes that any channel that is already known is valid, even if
  1584. * 005 disagrees.
  1585. */
  1586. @Override
  1587. public boolean isValidChannelName(final String name) {
  1588. // Check sChannelName is not empty or null
  1589. if (name == null || name.isEmpty()) {
  1590. return false;
  1591. }
  1592. // Check its not ourself (PM recieved before 005)
  1593. if (getStringConverter().equalsIgnoreCase(getMyNickname(), name)) {
  1594. return false;
  1595. }
  1596. // Check if we are already on this channel
  1597. if (getChannel(name) != null) {
  1598. return true;
  1599. }
  1600. // Otherwise return true if:
  1601. // Channel equals "0"
  1602. // first character of the channel name is a valid channel prefix.
  1603. return chanPrefix.indexOf(name.charAt(0)) >= 0 || "0".equals(name);
  1604. }
  1605. @Override
  1606. public boolean isUserSettable(final char mode) {
  1607. final String validmodes;
  1608. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) {
  1609. validmodes = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES);
  1610. } else {
  1611. validmodes = "bklimnpstrc";
  1612. }
  1613. return validmodes.matches(".*" + mode + ".*");
  1614. }
  1615. /**
  1616. * Get the 005 info.
  1617. *
  1618. * @return 005Info hashtable.
  1619. */
  1620. public Map<String, String> get005() {
  1621. return Collections.unmodifiableMap(h005Info);
  1622. }
  1623. /**
  1624. * Get the ServerType for this IRCD.
  1625. *
  1626. * @return The ServerType for this IRCD.
  1627. */
  1628. public ServerType getServerType() {
  1629. return ServerType.findServerType(h005Info.get("004IRCD"), networkName, h005Info.get("003IRCD"), h005Info.get("002IRCD"));
  1630. }
  1631. @Override
  1632. public String getServerSoftware() {
  1633. final String version = h005Info.get("004IRCD");
  1634. return version == null ? "" : version;
  1635. }
  1636. @Override
  1637. public String getServerSoftwareType() {
  1638. return getServerType().getType();
  1639. }
  1640. /**
  1641. * Get the value of checkServerPing.
  1642. *
  1643. * @return value of checkServerPing.
  1644. * @see #setCheckServerPing
  1645. */
  1646. public boolean getCheckServerPing() {
  1647. return checkServerPing;
  1648. }
  1649. /**
  1650. * Set the value of checkServerPing.
  1651. *
  1652. * @param newValue New value to use.
  1653. * @see #setCheckServerPing
  1654. */
  1655. public void setCheckServerPing(final boolean newValue) {
  1656. checkServerPing = newValue;
  1657. if (checkServerPing) {
  1658. startPingTimer();
  1659. } else {
  1660. stopPingTimer();
  1661. }
  1662. }
  1663. @Override
  1664. public void setEncoder(final Encoder encoder) {
  1665. this.encoder = encoder;
  1666. }
  1667. @Override
  1668. public void setPingTimerInterval(final long newValue) {
  1669. super.setPingTimerInterval(newValue);
  1670. startPingTimer();
  1671. }
  1672. /**
  1673. * Start the pingTimer.
  1674. */
  1675. public void startPingTimer() {
  1676. pingTimerSem.acquireUninterruptibly();
  1677. try {
  1678. setPingNeeded(false);
  1679. if (pingTimer != null) {
  1680. pingTimer.cancel();
  1681. }
  1682. pingTimer = new Timer("IRCParser pingTimer");
  1683. pingTimer.schedule(new PingTimer(this, pingTimer), 0, getPingTimerInterval());
  1684. pingCountDown = 1;
  1685. } finally {
  1686. pingTimerSem.release();
  1687. }
  1688. }
  1689. /**
  1690. * Stop the pingTimer.
  1691. */
  1692. protected void stopPingTimer() {
  1693. pingTimerSem.acquireUninterruptibly();
  1694. if (pingTimer != null) {
  1695. pingTimer.cancel();
  1696. pingTimer = null;
  1697. }
  1698. pingTimerSem.release();
  1699. }
  1700. /**
  1701. * This is called when the ping Timer has been executed.
  1702. * As the timer is restarted on every incomming message, this will only be
  1703. * called when there has been no incomming line for 10 seconds.
  1704. *
  1705. * @param timer The timer that called this.
  1706. */
  1707. protected void pingTimerTask(final Timer timer) {
  1708. // If user no longer wants server ping to be checked, or the socket is
  1709. // closed then cancel the time and do nothing else.
  1710. if (!getCheckServerPing() || getSocketState() != SocketState.OPEN) {
  1711. pingTimerSem.acquireUninterruptibly();
  1712. if (pingTimer != null && pingTimer.equals(timer)) {
  1713. pingTimer.cancel();
  1714. }
  1715. pingTimerSem.release();
  1716. return;
  1717. }
  1718. if (getPingNeeded()) {
  1719. callPingFailed();
  1720. } else {
  1721. --pingCountDown;
  1722. if (pingCountDown < 1) {
  1723. pingTime = System.currentTimeMillis();
  1724. setPingNeeded(true);
  1725. pingCountDown = getPingTimerFraction();
  1726. lastPingValue = String.valueOf(System.currentTimeMillis());
  1727. if (sendString("PING " + lastPingValue, QueuePriority.HIGH)) {
  1728. callPingSent();
  1729. }
  1730. }
  1731. }
  1732. }
  1733. @Override
  1734. public long getServerLatency() {
  1735. return serverLag;
  1736. }
  1737. /**
  1738. * Updates the name of the server that this parser is connected to.
  1739. *
  1740. * @param serverName The discovered server name
  1741. */
  1742. public void updateServerName(final String serverName) {
  1743. setServerName(serverName);
  1744. }
  1745. /**
  1746. * Get the current server lag.
  1747. *
  1748. * @param actualTime if True the value returned will be the actual time the ping was sent
  1749. * else it will be the amount of time sinse the last ping was sent.
  1750. * @return Time last ping was sent
  1751. */
  1752. public long getPingTime(final boolean actualTime) {
  1753. if (actualTime) {
  1754. return pingTime;
  1755. } else {
  1756. return System.currentTimeMillis() - pingTime;
  1757. }
  1758. }
  1759. @Override
  1760. public long getPingTime() {
  1761. return getPingTime(false);
  1762. }
  1763. /**
  1764. * Set if a ping is needed or not.
  1765. *
  1766. * @param newStatus new value to set pingNeeded to.
  1767. */
  1768. private void setPingNeeded(final boolean newStatus) {
  1769. pingNeeded.set(newStatus);
  1770. }
  1771. /**
  1772. * Get if a ping is needed or not.
  1773. *
  1774. * @return value of pingNeeded.
  1775. */
  1776. boolean getPingNeeded() {
  1777. return pingNeeded.get();
  1778. }
  1779. @Override
  1780. public IRCClientInfo getLocalClient() {
  1781. return myself;
  1782. }
  1783. /**
  1784. * Get the current nickname.
  1785. * After 001 this returns the exact same as getLocalClient().getRealNickname();
  1786. * Before 001 it returns the nickname that the parser Thinks it has.
  1787. *
  1788. * @return Current nickname.
  1789. */
  1790. public String getMyNickname() {
  1791. if (myself.isFake()) {
  1792. return thinkNickname;
  1793. } else {
  1794. return myself.getRealNickname();
  1795. }
  1796. }
  1797. /**
  1798. * Retrieves the local user information that this parser was configured
  1799. * with.
  1800. *
  1801. * @return This parser's local user configuration
  1802. */
  1803. public MyInfo getMyInfo() {
  1804. return me;
  1805. }
  1806. /**
  1807. * Get the current username (Specified in MyInfo on construction).
  1808. * Get the username given in MyInfo
  1809. *
  1810. * @return My username.
  1811. */
  1812. public String getMyUsername() {
  1813. return me.getUsername();
  1814. }
  1815. /**
  1816. * Add a client to the ClientList.
  1817. *
  1818. * @param client Client to add
  1819. */
  1820. public void addClient(final IRCClientInfo client) {
  1821. clientList.put(getStringConverter().toLowerCase(client.getRealNickname()), client);
  1822. }
  1823. /**
  1824. * Remove a client from the ClientList.
  1825. * This WILL NOT allow cMyself to be removed from the list.
  1826. *
  1827. * @param client Client to remove
  1828. */
  1829. public void removeClient(final IRCClientInfo client) {
  1830. if (client != myself) {
  1831. forceRemoveClient(client);
  1832. }
  1833. }
  1834. /**
  1835. * Remove a client from the ClientList.
  1836. * This WILL allow cMyself to be removed from the list
  1837. *
  1838. * @param client Client to remove
  1839. */
  1840. public void forceRemoveClient(final IRCClientInfo client) {
  1841. clientList.remove(getStringConverter().toLowerCase(client.getRealNickname()));
  1842. }
  1843. /**
  1844. * Get the number of known clients.
  1845. *
  1846. * @return Count of known clients
  1847. */
  1848. public int knownClients() {
  1849. return clientList.size();
  1850. }
  1851. /**
  1852. * Get the known clients as a collection.
  1853. *
  1854. * @return Known clients as a collection
  1855. */
  1856. public Collection<IRCClientInfo> getClients() {
  1857. return clientList.values();
  1858. }
  1859. /**
  1860. * Clear the client list.
  1861. */
  1862. public void clearClients() {
  1863. clientList.clear();
  1864. addClient(getLocalClient());
  1865. }
  1866. /**
  1867. * Add a channel to the ChannelList.
  1868. *
  1869. * @param channel Channel to add
  1870. */
  1871. public void addChannel(final IRCChannelInfo channel) {
  1872. synchronized (channelList) {
  1873. channelList.put(getStringConverter().toLowerCase(channel.getName()), channel);
  1874. }
  1875. }
  1876. /**
  1877. * Remove a channel from the ChannelList.
  1878. *
  1879. * @param channel Channel to remove
  1880. */
  1881. public void removeChannel(final ChannelInfo channel) {
  1882. synchronized (channelList) {
  1883. channelList.remove(getStringConverter().toLowerCase(channel.getName()));
  1884. }
  1885. }
  1886. /**
  1887. * Get the number of known channel.
  1888. *
  1889. * @return Count of known channel
  1890. */
  1891. public int knownChannels() {
  1892. synchronized (channelList) {
  1893. return channelList.size();
  1894. }
  1895. }
  1896. @Override
  1897. public Collection<IRCChannelInfo> getChannels() {
  1898. synchronized (channelList) {
  1899. return channelList.values();
  1900. }
  1901. }
  1902. /**
  1903. * Clear the channel list.
  1904. */
  1905. public void clearChannels() {
  1906. synchronized (channelList) {
  1907. channelList.clear();
  1908. }
  1909. }
  1910. @Override
  1911. public String[] parseHostmask(final String hostmask) {
  1912. return IRCClientInfo.parseHostFull(hostmask);
  1913. }
  1914. @Override
  1915. public int getMaxTopicLength() {
  1916. if (h005Info.containsKey(IrcConstants.ISUPPORT_TOPIC_LENGTH)) {
  1917. try {
  1918. return Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_TOPIC_LENGTH));
  1919. } catch (NumberFormatException ex) {
  1920. // Do nothing
  1921. }
  1922. }
  1923. return 0;
  1924. }
  1925. @Override
  1926. public int getMaxLength() {
  1927. return MAX_LINELENGTH;
  1928. }
  1929. @Override
  1930. public void setCompositionState(final String host, final CompositionState state) {
  1931. // Do nothing
  1932. }
  1933. @Override
  1934. protected void handleSocketDebug(final String message) {
  1935. super.handleSocketDebug(message);
  1936. callDebugInfo(DEBUG_SOCKET, message);
  1937. }
  1938. }