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

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