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

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