Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

IRCParser.java 73KB

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