Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

IRCParser.java 75KB

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