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

IRCParser.java 74KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  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. tokens = line.split(" ", 2);
  832. final int tsEnd = tokens[0].indexOf('@', 1);
  833. boolean hasTSIRCDate = false;
  834. if (tsEnd > -1) {
  835. try {
  836. final long ts = Long.parseLong(tokens[0].substring(1, tsEnd));
  837. hasTSIRCDate = true;
  838. } catch (final NumberFormatException nfe) { /* Not a timestamp. */ }
  839. }
  840. if (!hasTSIRCDate) {
  841. // IRCv3 Tags, last arg is actually the second " :"
  842. lastarg = line.indexOf(" :", lastarg+1);
  843. }
  844. }
  845. if (lastarg > -1) {
  846. final String[] temp = line.substring(0, lastarg).split(" ");
  847. tokens = new String[temp.length + 1];
  848. System.arraycopy(temp, 0, tokens, 0, temp.length);
  849. tokens[temp.length] = line.substring(lastarg + 2);
  850. } else {
  851. tokens = line.split(" ");
  852. }
  853. if (tokens.length < 1) {
  854. tokens = new String[]{""};
  855. }
  856. return tokens;
  857. }
  858. @Override
  859. public IRCClientInfo getClient(final String details) {
  860. final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(details));
  861. if (clientList.containsKey(sWho)) {
  862. return clientList.get(sWho);
  863. } else {
  864. return new IRCClientInfo(this, userModes, details).setFake(true);
  865. }
  866. }
  867. public boolean isKnownClient(final String host) {
  868. final String sWho = getStringConverter().toLowerCase(IRCClientInfo.parseHost(host));
  869. return clientList.containsKey(sWho);
  870. }
  871. @Override
  872. public IRCChannelInfo getChannel(final String channel) {
  873. synchronized (channelList) {
  874. return channelList.get(getStringConverter().toLowerCase(channel));
  875. }
  876. }
  877. @Override
  878. public void sendInvite(final String channel, final String user) {
  879. sendRawMessage("INVITE " + user + ' ' + channel);
  880. }
  881. @Override
  882. public void sendWhois(final String nickname) {
  883. sendRawMessage("WHOIS " + nickname);
  884. }
  885. @Override
  886. public void sendRawMessage(final String message) {
  887. sendString(message, QueuePriority.NORMAL, false);
  888. }
  889. @Override
  890. public void sendRawMessage(final String message, final QueuePriority priority) {
  891. sendString(message, priority, false);
  892. }
  893. /**
  894. * Send a line to the server and add proper line ending.
  895. *
  896. * @param line Line to send (\r\n termination is added automatically)
  897. * @return True if line was sent, else false.
  898. */
  899. public boolean sendString(final String line) {
  900. return sendString(line, QueuePriority.NORMAL, true);
  901. }
  902. /**
  903. * Send a line to the server and add proper line ending.
  904. * If a non-empty argument is given, it is appended as a trailing argument
  905. * (i.e., separated by " :"); otherwise, the line is sent as-is.
  906. *
  907. * @param line Line to send
  908. * @param argument Trailing argument for the command, if any
  909. * @return True if line was sent, else false.
  910. */
  911. protected boolean sendString(final String line, final String argument) {
  912. return sendString(argument.isEmpty() ? line : line + " :" + argument);
  913. }
  914. /**
  915. * Send a line to the server and add proper line ending.
  916. *
  917. * @param line Line to send (\r\n termination is added automatically)
  918. * @param priority Priority of this line.
  919. * @return True if line was sent, else false.
  920. */
  921. public boolean sendString(final String line, final QueuePriority priority) {
  922. return sendString(line, priority, true);
  923. }
  924. /**
  925. * Send a line to the server and add proper line ending.
  926. *
  927. * @param line Line to send (\r\n termination is added automatically)
  928. * @param priority Priority of this line.
  929. * @param fromParser is this line from the parser? (used for callDataOut)
  930. * @return True if line was sent, else false.
  931. */
  932. protected boolean sendString(final String line, final QueuePriority priority, final boolean fromParser) {
  933. if (getSocketState() != SocketState.OPEN) {
  934. return false;
  935. }
  936. callDataOut(line, fromParser);
  937. out.sendLine(line, priority);
  938. parseOutgoingLine(line);
  939. return true;
  940. }
  941. /**
  942. * Parses a line that has been sent to the server in order to track state.
  943. *
  944. * @param line The line to be parsed.
  945. */
  946. private void parseOutgoingLine(final String line) {
  947. final String[] newLine = tokeniseLine(line);
  948. if ("away".equalsIgnoreCase(newLine[0]) && newLine.length > 1) {
  949. myself.setAwayReason(newLine[newLine.length - 1]);
  950. } else if ("mode".equalsIgnoreCase(newLine[0]) && newLine.length == 3) {
  951. final IRCChannelInfo channel = getChannel(newLine[1]);
  952. if (channel != null) {
  953. // This makes sure we don't add the same item to the LMQ twice,
  954. // even if its requested twice, as the ircd will only reply once
  955. final Queue<Character> foundModes = new LinkedList<>();
  956. final Queue<Character> listModeQueue = channel.getListModeQueue();
  957. for (int i = 0; i < newLine[2].length(); ++i) {
  958. final Character mode = newLine[2].charAt(i);
  959. callDebugInfo(DEBUG_LMQ, "Intercepted mode request for " + channel + " for mode " + mode);
  960. if (chanModesOther.containsKey(mode) && chanModesOther.get(mode) == MODE_LIST) {
  961. if (foundModes.contains(mode)) {
  962. callDebugInfo(DEBUG_LMQ, "Already added to LMQ");
  963. } else {
  964. listModeQueue.offer(mode);
  965. foundModes.offer(mode);
  966. callDebugInfo(DEBUG_LMQ, "Added to LMQ");
  967. }
  968. }
  969. }
  970. }
  971. }
  972. }
  973. @Override
  974. public String getNetworkName() {
  975. return networkName;
  976. }
  977. @Override
  978. public String getLastLine() {
  979. return lastLine == null ? "" : lastLine.getLine();
  980. }
  981. @Override
  982. public List<String> getServerInformationLines() {
  983. synchronized (serverInformationLines) {
  984. return new LinkedList<>(serverInformationLines);
  985. }
  986. }
  987. /**
  988. * Process a line and call relevant methods for handling.
  989. *
  990. * @param line Line read from the IRC server
  991. */
  992. @SuppressWarnings("fallthrough")
  993. protected void processLine(final ReadLine line) {
  994. callDataIn(line);
  995. final String[] token = line.getTokens();
  996. LocalDateTime lineTS = LocalDateTime.now();
  997. if (line.getTags().containsKey("tsirc date")) {
  998. try {
  999. final long ts = Long.parseLong(line.getTags().get("tsirc date")) - tsdiff;
  1000. lineTS = LocalDateTime.ofInstant(Instant.ofEpochSecond(ts / 1000L, (int) (ts % 1000L)),
  1001. ZoneId.systemDefault());
  1002. } catch (final NumberFormatException nfe) { /* Do nothing. */ }
  1003. } else if (line.getTags().containsKey("time")) {
  1004. try {
  1005. lineTS = LocalDateTime.parse(line.getTags().get("time"),
  1006. DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
  1007. } catch (final DateTimeParseException pe) { /* Do nothing. */ }
  1008. }
  1009. setPingNeeded(false);
  1010. if (token.length < 2) {
  1011. return;
  1012. }
  1013. try {
  1014. final String sParam = token[1];
  1015. if ("PING".equalsIgnoreCase(token[0]) || "PING".equalsIgnoreCase(token[1])) {
  1016. sendString("PONG :" + sParam, QueuePriority.HIGH);
  1017. } else if ("PONG".equalsIgnoreCase(token[0]) || "PONG".equalsIgnoreCase(token[1])) {
  1018. if (!lastPingValue.isEmpty() && lastPingValue.equals(token[token.length - 1])) {
  1019. lastPingValue = "";
  1020. serverLag = System.currentTimeMillis() - pingTime;
  1021. callPingSuccess();
  1022. }
  1023. } else if ("ERROR".equalsIgnoreCase(token[0])) {
  1024. final StringBuilder errorMessage = new StringBuilder();
  1025. for (int i = 1; i < token.length; ++i) {
  1026. errorMessage.append(token[i]);
  1027. }
  1028. callServerError(errorMessage.toString());
  1029. } else if ("TSIRC".equalsIgnoreCase(token[1]) && token.length > 3) {
  1030. if ("1".equals(token[2])) {
  1031. try {
  1032. final long ts = Long.parseLong(token[3]);
  1033. tsdiff = ts - System.currentTimeMillis();
  1034. } catch (final NumberFormatException nfe) { /* Do nothing. */ }
  1035. }
  1036. } else {
  1037. int nParam;
  1038. if (got001) {
  1039. // Freenode sends a random notice in a stupid place, others might do aswell
  1040. // These shouldn't cause post005 to be fired, so handle them here.
  1041. if ("NOTICE".equalsIgnoreCase(token[0]) ||
  1042. token.length > 2 && "NOTICE".equalsIgnoreCase(token[2])) {
  1043. try {
  1044. myProcessingManager.process(lineTS, "Notice Auth", token);
  1045. } catch (ProcessorNotFoundException e) {
  1046. // ???
  1047. }
  1048. return;
  1049. }
  1050. if (!post005) {
  1051. try {
  1052. nParam = Integer.parseInt(token[1]);
  1053. } catch (NumberFormatException e) {
  1054. nParam = -1;
  1055. }
  1056. if (nParam < 0 || nParam > 5) {
  1057. callPost005();
  1058. } else {
  1059. // Store 001 - 005 for informational purposes.
  1060. synchronized (serverInformationLines) {
  1061. serverInformationLines.add(line.getLine());
  1062. }
  1063. }
  1064. }
  1065. // After 001 we potentially care about everything!
  1066. try {
  1067. myProcessingManager.process(lineTS, sParam, token);
  1068. } catch (ProcessorNotFoundException e) {
  1069. // ???
  1070. }
  1071. } else {
  1072. // Before 001 we don't care about much.
  1073. try {
  1074. nParam = Integer.parseInt(token[1]);
  1075. } catch (NumberFormatException e) {
  1076. nParam = -1;
  1077. }
  1078. switch (nParam) {
  1079. case 1: // 001 - Welcome to IRC
  1080. synchronized (serverInformationLines) {
  1081. serverInformationLines.add(line.getLine());
  1082. }
  1083. // Fallthrough
  1084. case IrcConstants.NUMERIC_ERROR_PASSWORD_MISMATCH:
  1085. case IrcConstants.NUMERIC_ERROR_NICKNAME_IN_USE:
  1086. try {
  1087. myProcessingManager.process(lineTS, sParam, token);
  1088. } catch (ProcessorNotFoundException e) {
  1089. }
  1090. break;
  1091. default: // Unknown - Send to Notice Auth
  1092. // Some networks send a CTCP during the auth process, handle it
  1093. if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char) 1 && token[3].charAt(token[3].length() - 1) == (char) 1) {
  1094. try {
  1095. myProcessingManager.process(lineTS, sParam, token);
  1096. } catch (ProcessorNotFoundException e) {
  1097. }
  1098. break;
  1099. }
  1100. // Some networks may send a NICK message if you nick change before 001
  1101. // Eat it up so that it isn't treated as a notice auth.
  1102. if ("NICK".equalsIgnoreCase(token[1])) {
  1103. break;
  1104. }
  1105. // CAP also happens here, so try that.
  1106. if ("CAP".equalsIgnoreCase(token[1])) {
  1107. myProcessingManager.process(lineTS, sParam, token);
  1108. break;
  1109. }
  1110. // Otherwise, send to Notice Auth
  1111. try {
  1112. myProcessingManager.process(lineTS, "Notice Auth", token);
  1113. } catch (ProcessorNotFoundException e) {
  1114. }
  1115. break;
  1116. }
  1117. }
  1118. }
  1119. } catch (Exception e) {
  1120. final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Fatal Exception in Parser.", getLastLine());
  1121. ei.setException(e);
  1122. callErrorInfo(ei);
  1123. }
  1124. }
  1125. /** The IRCStringConverter for this parser */
  1126. private IRCStringConverter stringConverter;
  1127. @Override
  1128. public IRCStringConverter getStringConverter() {
  1129. if (stringConverter == null) {
  1130. stringConverter = new IRCStringConverter(IRCEncoding.RFC1459);
  1131. }
  1132. return stringConverter;
  1133. }
  1134. /**
  1135. * Sets the encoding that this parser's string converter should use.
  1136. *
  1137. * @param encoding The encoding to use
  1138. */
  1139. public void setEncoding(final IRCEncoding encoding) {
  1140. stringConverter = new IRCStringConverter(encoding);
  1141. }
  1142. /**
  1143. * Check the state of the requested capability.
  1144. *
  1145. * @param capability The capability to check the state of.
  1146. * @return State of the requested capability.
  1147. */
  1148. public CapabilityState getCapabilityState(final String capability) {
  1149. synchronized (capabilities) {
  1150. if (capabilities.containsKey(capability.toLowerCase())) {
  1151. return capabilities.get(capability.toLowerCase());
  1152. } else {
  1153. return CapabilityState.INVALID;
  1154. }
  1155. }
  1156. }
  1157. /**
  1158. * Set the state of the requested capability.
  1159. *
  1160. * @param capability Requested capability
  1161. * @param state State to set for capability
  1162. */
  1163. public void setCapabilityState(final String capability, final CapabilityState state) {
  1164. synchronized (capabilities) {
  1165. if (capabilities.containsKey(capability.toLowerCase())) {
  1166. capabilities.put(capability.toLowerCase(), state);
  1167. }
  1168. }
  1169. }
  1170. /**
  1171. * Add the given capability as a supported capability by the server.
  1172. *
  1173. * @param capability Requested capability
  1174. */
  1175. public void addCapability(final String capability) {
  1176. synchronized (capabilities) {
  1177. capabilities.put(capability.toLowerCase(), CapabilityState.DISABLED);
  1178. }
  1179. }
  1180. /**
  1181. * Get the server capabilities and their current state.
  1182. *
  1183. * @return Server capabilities and their current state.
  1184. */
  1185. public Map<String, CapabilityState> getCapabilities() {
  1186. synchronized (capabilities) {
  1187. return new HashMap<>(capabilities);
  1188. }
  1189. }
  1190. /**
  1191. * Process CHANMODES from 005.
  1192. */
  1193. public void parseChanModes() {
  1194. final StringBuilder sDefaultModes = new StringBuilder("b,k,l,");
  1195. String modeStr;
  1196. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)) {
  1197. if (getServerType() == ServerType.DANCER) {
  1198. sDefaultModes.insert(0, "dqeI");
  1199. } else if (getServerType() == ServerType.AUSTIRC) {
  1200. sDefaultModes.insert(0, 'e');
  1201. }
  1202. modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES);
  1203. for (int i = 0; i < modeStr.length(); ++i) {
  1204. final char mode = modeStr.charAt(i);
  1205. if (!prefixModes.isPrefixMode(mode)
  1206. && sDefaultModes.indexOf(Character.toString(mode)) < 0) {
  1207. sDefaultModes.append(mode);
  1208. }
  1209. }
  1210. } else {
  1211. sDefaultModes.append("imnpstrc");
  1212. }
  1213. if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_MODES)) {
  1214. modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_MODES);
  1215. } else {
  1216. modeStr = sDefaultModes.toString();
  1217. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
  1218. }
  1219. String[] bits = modeStr.split(",", 5);
  1220. if (bits.length < 4) {
  1221. modeStr = sDefaultModes.toString();
  1222. callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. " +
  1223. "Using default string of \"" + modeStr + '"', getLastLine()));
  1224. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_MODES, modeStr);
  1225. bits = modeStr.split(",", 5);
  1226. }
  1227. // resetState
  1228. chanModesOther.clear();
  1229. // List modes.
  1230. for (int i = 0; i < bits[0].length(); ++i) {
  1231. final Character cMode = bits[0].charAt(i);
  1232. callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode);
  1233. if (!chanModesOther.containsKey(cMode)) {
  1234. chanModesOther.put(cMode, MODE_LIST);
  1235. }
  1236. }
  1237. // Param for Set and Unset.
  1238. final Byte nBoth = MODE_SET + MODE_UNSET;
  1239. for (int i = 0; i < bits[1].length(); ++i) {
  1240. final Character cMode = bits[1].charAt(i);
  1241. callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode);
  1242. if (!chanModesOther.containsKey(cMode)) {
  1243. chanModesOther.put(cMode, nBoth);
  1244. }
  1245. }
  1246. // Param just for Set
  1247. for (int i = 0; i < bits[2].length(); ++i) {
  1248. final Character cMode = bits[2].charAt(i);
  1249. callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode);
  1250. if (!chanModesOther.containsKey(cMode)) {
  1251. chanModesOther.put(cMode, MODE_SET);
  1252. }
  1253. }
  1254. // Boolean Mode
  1255. chanModesBool.set(bits[3]);
  1256. callDebugInfo(DEBUG_INFO, "Found boolean modes: %s", bits[3]);
  1257. }
  1258. @Override
  1259. public String getChannelUserModes() {
  1260. return prefixModes.getPrefixes();
  1261. }
  1262. @Override
  1263. public String getBooleanChannelModes() {
  1264. return chanModesBool.getModes();
  1265. }
  1266. @Override
  1267. public String getListChannelModes() {
  1268. return getOtherModeString(MODE_LIST);
  1269. }
  1270. @Override
  1271. public String getParameterChannelModes() {
  1272. return getOtherModeString(MODE_SET);
  1273. }
  1274. @Override
  1275. public String getDoubleParameterChannelModes() {
  1276. return getOtherModeString((byte) (MODE_SET + MODE_UNSET));
  1277. }
  1278. @Override
  1279. public String getChannelPrefixes() {
  1280. return chanPrefix;
  1281. }
  1282. /**
  1283. * Get modes from hChanModesOther that have a specific value.
  1284. * Modes are returned in alphabetical order
  1285. *
  1286. * @param value Value mode must have to be included
  1287. * @return All the currently known Set-Unset modes
  1288. */
  1289. protected String getOtherModeString(final byte value) {
  1290. final char[] modes = new char[chanModesOther.size()];
  1291. int i = 0;
  1292. for (char cTemp : chanModesOther.keySet()) {
  1293. final Byte nTemp = chanModesOther.get(cTemp);
  1294. if (nTemp == value) {
  1295. modes[i] = cTemp;
  1296. i++;
  1297. }
  1298. }
  1299. // Alphabetically sort the array
  1300. Arrays.sort(modes);
  1301. return new String(modes).trim();
  1302. }
  1303. @Override
  1304. public String getUserModes() {
  1305. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
  1306. return h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
  1307. } else {
  1308. return "";
  1309. }
  1310. }
  1311. /**
  1312. * Process USERMODES from 004.
  1313. */
  1314. public void parseUserModes() {
  1315. final String modeStr;
  1316. if (h005Info.containsKey(IrcConstants.ISUPPORT_USER_MODES)) {
  1317. modeStr = h005Info.get(IrcConstants.ISUPPORT_USER_MODES);
  1318. } else {
  1319. final String sDefaultModes = "nwdoi";
  1320. modeStr = sDefaultModes;
  1321. h005Info.put(IrcConstants.ISUPPORT_USER_MODES, sDefaultModes);
  1322. }
  1323. userModes.set(modeStr);
  1324. }
  1325. /**
  1326. * Resets the channel prefix property to the default, RFC specified value.
  1327. */
  1328. public void resetChanPrefix() {
  1329. chanPrefix = DEFAULT_CHAN_PREFIX;
  1330. }
  1331. /**
  1332. * Sets the set of possible channel prefixes to those in the given value.
  1333. *
  1334. * @param value The new set of channel prefixes.
  1335. */
  1336. public void setChanPrefix(final String value) {
  1337. chanPrefix = value;
  1338. }
  1339. /**
  1340. * Process PREFIX from 005.
  1341. */
  1342. public void parsePrefixModes() {
  1343. final String sDefaultModes = "(ohv)@%+";
  1344. String modeStr;
  1345. if (h005Info.containsKey(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES)) {
  1346. modeStr = h005Info.get(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES);
  1347. } else {
  1348. modeStr = sDefaultModes;
  1349. }
  1350. if ("(".equals(modeStr.substring(0, 1))) {
  1351. modeStr = modeStr.substring(1);
  1352. } else {
  1353. modeStr = sDefaultModes.substring(1);
  1354. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
  1355. }
  1356. int closingIndex = modeStr.indexOf(')');
  1357. if (closingIndex * 2 + 1 != modeStr.length()) {
  1358. callErrorInfo(new ParserError(ParserError.ERROR_ERROR,
  1359. "PREFIX String not valid. Using default string of \"" + modeStr +
  1360. '"', getLastLine()));
  1361. h005Info.put(IrcConstants.ISUPPORT_CHANNEL_USER_PREFIXES, sDefaultModes);
  1362. modeStr = sDefaultModes.substring(1);
  1363. closingIndex = modeStr.indexOf(')');
  1364. }
  1365. // The modes passed from the server are in descending order of importance, we want to
  1366. // store them in ascending, so reverse them:
  1367. final String reversedModes = new StringBuilder(modeStr).reverse().toString();
  1368. prefixModes.setModes(reversedModes.substring(closingIndex + 1),
  1369. reversedModes.substring(0, closingIndex));
  1370. }
  1371. @Override
  1372. public void joinChannels(final ChannelJoinRequest... channels) {
  1373. // We store a map from key->channels to allow intelligent joining of
  1374. // channels using as few JOIN commands as needed.
  1375. final Map<String, StringBuffer> joinMap = new HashMap<>();
  1376. for (ChannelJoinRequest channel : channels) {
  1377. // Make sure we have a list to put stuff in.
  1378. StringBuffer list = joinMap.computeIfAbsent(channel.getPassword(), k -> new StringBuffer());
  1379. // Add the channel to the list. If the name is invalid and
  1380. // autoprefix is off we will just skip this channel.
  1381. if (!channel.getName().isEmpty()) {
  1382. if (list.length() > 0) {
  1383. list.append(',');
  1384. }
  1385. if (!isValidChannelName(channel.getName())) {
  1386. if (chanPrefix.isEmpty()) {
  1387. // TODO: This is wrong - empty chan prefix means the
  1388. // IRCd supports no channels.
  1389. list.append('#');
  1390. } else {
  1391. list.append(chanPrefix.charAt(0));
  1392. }
  1393. }
  1394. list.append(channel.getName());
  1395. }
  1396. }
  1397. for (Map.Entry<String, StringBuffer> entrySet : joinMap.entrySet()) {
  1398. final String thisKey = entrySet.getKey();
  1399. final String channelString = entrySet.getValue().toString();
  1400. if (!channelString.isEmpty()) {
  1401. if (thisKey == null || thisKey.isEmpty()) {
  1402. sendString("JOIN " + channelString);
  1403. } else {
  1404. sendString("JOIN " + channelString + ' ' + thisKey);
  1405. }
  1406. }
  1407. }
  1408. }
  1409. /**
  1410. * Leave a Channel.
  1411. *
  1412. * @param channel Name of channel to part
  1413. * @param reason Reason for leaving (Nothing sent if sReason is "")
  1414. */
  1415. public void partChannel(final String channel, final String reason) {
  1416. if (getChannel(channel) == null) {
  1417. return;
  1418. }
  1419. sendString("PART " + channel, reason);
  1420. }
  1421. /**
  1422. * Set Nickname.
  1423. *
  1424. * @param nickname New nickname wanted.
  1425. */
  1426. public void setNickname(final String nickname) {
  1427. if (getSocketState() == SocketState.OPEN) {
  1428. if (!myself.isFake() && myself.getRealNickname().equals(nickname)) {
  1429. return;
  1430. }
  1431. sendString("NICK " + nickname);
  1432. } else {
  1433. me.setNickname(nickname);
  1434. }
  1435. thinkNickname = nickname;
  1436. }
  1437. @Override
  1438. public int getMaxLength(final String type, final String target) {
  1439. // If my host is "nick!user@host" and we are sending "#Channel"
  1440. // a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :"
  1441. // and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases.
  1442. // Lint = the 2 ":" at the start and end and the 3 separating " "s
  1443. int length = 0;
  1444. if (type != null) {
  1445. length += type.length();
  1446. }
  1447. if (target != null) {
  1448. length += target.length();
  1449. }
  1450. return getMaxLength(length);
  1451. }
  1452. /**
  1453. * Get the max length a message can be.
  1454. *
  1455. * @param length Length of stuff. (Ie "PRIVMSG"+"#Channel")
  1456. * @return Max Length message should be.
  1457. */
  1458. public int getMaxLength(final int length) {
  1459. final int lineLint = 5;
  1460. if (myself.isFake()) {
  1461. callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "getMaxLength() called, but I don't know who I am?", getLastLine()));
  1462. return MAX_LINELENGTH - length - lineLint;
  1463. } else {
  1464. return MAX_LINELENGTH - myself.toString().length() - length - lineLint;
  1465. }
  1466. }
  1467. @Override
  1468. public int getMaxListModes(final char mode) {
  1469. // MAXLIST=bdeI:50
  1470. // MAXLIST=b:60,e:60,I:60
  1471. // MAXBANS=30
  1472. callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: " + mode);
  1473. // Try in MAXLIST
  1474. int result = -2;
  1475. if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES) != null) {
  1476. if (h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) == null) {
  1477. result = 0;
  1478. }
  1479. final String maxlist = h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_LIST_MODES);
  1480. callDebugInfo(DEBUG_INFO, "Found maxlist (" + maxlist + ')');
  1481. final String[] bits = maxlist.split(",");
  1482. for (String bit : bits) {
  1483. final String[] parts = bit.split(":", 2);
  1484. callDebugInfo(DEBUG_INFO, "Bit: " + bit + " | parts.length = " + parts.length + " ("
  1485. + parts[0] + " -> " + parts[0].indexOf(mode) + ')');
  1486. if (parts.length == 2 && parts[0].indexOf(mode) > -1) {
  1487. callDebugInfo(DEBUG_INFO, "parts[0] = '" + parts[0] + "' | parts[1] = '"
  1488. + parts[1] + '\'');
  1489. try {
  1490. result = Integer.parseInt(parts[1]);
  1491. break;
  1492. } catch (NumberFormatException nfe) {
  1493. result = -1;
  1494. }
  1495. }
  1496. }
  1497. }
  1498. // If not in max list, try MAXBANS
  1499. if (result == -2 && h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS) != null) {
  1500. callDebugInfo(DEBUG_INFO, "Trying max bans");
  1501. try {
  1502. result = Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_MAXIMUM_BANS));
  1503. } catch (NumberFormatException nfe) {
  1504. result = -1;
  1505. }
  1506. } else if (result == -2 && getServerType() == ServerType.WEIRCD) {
  1507. result = 50;
  1508. } else if (result == -2 && getServerType() == ServerType.OTHERNET) {
  1509. result = 30;
  1510. } else if (result == -2) {
  1511. result = -1;
  1512. callDebugInfo(DEBUG_INFO, "Failed");
  1513. callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "Unable to discover max list modes.", getLastLine()));
  1514. }
  1515. callDebugInfo(DEBUG_INFO, "Result: " + result);
  1516. return result;
  1517. }
  1518. @Override
  1519. public void sendMessage(final String target, final String message) {
  1520. if (target == null || message == null) {
  1521. return;
  1522. }
  1523. if (target.isEmpty()) {
  1524. return;
  1525. }
  1526. sendString("PRIVMSG " + target, message);
  1527. }
  1528. @Override
  1529. public void sendNotice(final String target, final String message) {
  1530. if (target == null || message == null) {
  1531. return;
  1532. }
  1533. if (target.isEmpty()) {
  1534. return;
  1535. }
  1536. sendString("NOTICE " + target, message);
  1537. }
  1538. @Override
  1539. public void sendAction(final String target, final String message) {
  1540. sendCTCP(target, "ACTION", message);
  1541. }
  1542. @Override
  1543. public void sendCTCP(final String target, final String type, final String message) {
  1544. if (target == null || message == null) {
  1545. return;
  1546. }
  1547. if (target.isEmpty() || type.isEmpty()) {
  1548. return;
  1549. }
  1550. final char char1 = (char) 1;
  1551. sendString("PRIVMSG " + target, char1 + type.toUpperCase() + ' ' + message + char1);
  1552. }
  1553. @Override
  1554. public void sendCTCPReply(final String target, final String type, final String message) {
  1555. if (target == null || message == null) {
  1556. return;
  1557. }
  1558. if (target.isEmpty() || type.isEmpty()) {
  1559. return;
  1560. }
  1561. final char char1 = (char) 1;
  1562. sendString("NOTICE " + target, char1 + type.toUpperCase() + ' ' + message + char1);
  1563. }
  1564. @Override
  1565. public void requestGroupList(final String searchTerms) {
  1566. sendString("LIST", searchTerms);
  1567. }
  1568. @Override
  1569. public void quit(final String reason) {
  1570. // Don't attempt to send anything further.
  1571. getOutputQueue().clearQueue();
  1572. final String output = (reason == null || reason.isEmpty()) ? "QUIT" : "QUIT :" + reason;
  1573. sendString(output, QueuePriority.IMMEDIATE, true);
  1574. // Don't bother queueing anything else.
  1575. getOutputQueue().setDiscarding(true);
  1576. }
  1577. @Override
  1578. public void disconnect(final String message) {
  1579. super.disconnect(message);
  1580. if (currentSocketState == SocketState.OPENING || currentSocketState == SocketState.OPEN) {
  1581. if (got001) {
  1582. quit(message);
  1583. }
  1584. currentSocketState = SocketState.CLOSING;
  1585. }
  1586. try {
  1587. // SSLSockets try to close nicely and read data from the socket,
  1588. // which seems to hang indefinitely in some circumstances. We don't
  1589. // like indefinite hangs, so just close the underlying socket
  1590. // direct.
  1591. if (rawSocket != null) {
  1592. rawSocket.close();
  1593. }
  1594. } catch (IOException e) {
  1595. /* Do Nothing */
  1596. } finally {
  1597. if (currentSocketState != SocketState.CLOSED) {
  1598. currentSocketState = SocketState.CLOSED;
  1599. callSocketClosed();
  1600. }
  1601. resetState();
  1602. }
  1603. }
  1604. /** {@inheritDoc}
  1605. *
  1606. * - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks
  1607. * that the first character is either #, &amp;, ! or +
  1608. * - Assumes that any channel that is already known is valid, even if
  1609. * 005 disagrees.
  1610. */
  1611. @Override
  1612. public boolean isValidChannelName(final String name) {
  1613. // Check sChannelName is not empty or null
  1614. if (name == null || name.isEmpty()) {
  1615. return false;
  1616. }
  1617. // Check its not ourself (PM recieved before 005)
  1618. if (getStringConverter().equalsIgnoreCase(getMyNickname(), name)) {
  1619. return false;
  1620. }
  1621. // Check if we are already on this channel
  1622. if (getChannel(name) != null) {
  1623. return true;
  1624. }
  1625. // Otherwise return true if:
  1626. // Channel equals "0"
  1627. // first character of the channel name is a valid channel prefix.
  1628. return chanPrefix.indexOf(name.charAt(0)) >= 0 || "0".equals(name);
  1629. }
  1630. @Override
  1631. public boolean isUserSettable(final char mode) {
  1632. final String validmodes =
  1633. h005Info.containsKey(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)
  1634. ? h005Info.get(IrcConstants.ISUPPORT_USER_CHANNEL_MODES)
  1635. : "bklimnpstrc";
  1636. return validmodes.indexOf(mode) > -1;
  1637. }
  1638. /**
  1639. * Get the 005 info.
  1640. *
  1641. * @return 005Info hashtable.
  1642. */
  1643. public Map<String, String> get005() {
  1644. return Collections.unmodifiableMap(h005Info);
  1645. }
  1646. /**
  1647. * Get the ServerType for this IRCD.
  1648. *
  1649. * @return The ServerType for this IRCD.
  1650. */
  1651. public ServerType getServerType() {
  1652. return ServerType.findServerType(h005Info.get("004IRCD"), networkName, h005Info.get("003IRCD"), h005Info.get("002IRCD"));
  1653. }
  1654. @Override
  1655. public String getServerSoftware() {
  1656. final String version = h005Info.get("004IRCD");
  1657. return version == null ? "" : version;
  1658. }
  1659. @Override
  1660. public String getServerSoftwareType() {
  1661. return getServerType().getType();
  1662. }
  1663. /**
  1664. * Get the value of checkServerPing.
  1665. *
  1666. * @return value of checkServerPing.
  1667. * @see #setCheckServerPing
  1668. */
  1669. public boolean getCheckServerPing() {
  1670. return checkServerPing;
  1671. }
  1672. /**
  1673. * Set the value of checkServerPing.
  1674. *
  1675. * @param newValue New value to use.
  1676. */
  1677. public void setCheckServerPing(final boolean newValue) {
  1678. checkServerPing = newValue;
  1679. if (checkServerPing) {
  1680. startPingTimer();
  1681. } else {
  1682. stopPingTimer();
  1683. }
  1684. }
  1685. @Override
  1686. public void setEncoder(final Encoder encoder) {
  1687. this.encoder = encoder;
  1688. }
  1689. @Override
  1690. public void setPingTimerInterval(final long newValue) {
  1691. super.setPingTimerInterval(newValue);
  1692. startPingTimer();
  1693. }
  1694. /**
  1695. * Start the pingTimer.
  1696. */
  1697. public void startPingTimer() {
  1698. pingTimerSem.acquireUninterruptibly();
  1699. try {
  1700. setPingNeeded(false);
  1701. if (pingTimer != null) {
  1702. pingTimer.cancel();
  1703. }
  1704. pingTimer = new Timer("IRCParser pingTimer");
  1705. pingTimer.schedule(new PingTimer(this, pingTimer), 0, getPingTimerInterval());
  1706. pingCountDown = 1;
  1707. } finally {
  1708. pingTimerSem.release();
  1709. }
  1710. }
  1711. /**
  1712. * Stop the pingTimer.
  1713. */
  1714. protected void stopPingTimer() {
  1715. pingTimerSem.acquireUninterruptibly();
  1716. if (pingTimer != null) {
  1717. pingTimer.cancel();
  1718. pingTimer = null;
  1719. }
  1720. pingTimerSem.release();
  1721. }
  1722. /**
  1723. * This is called when the ping Timer has been executed.
  1724. * As the timer is restarted on every incomming message, this will only be
  1725. * called when there has been no incomming line for 10 seconds.
  1726. *
  1727. * @param timer The timer that called this.
  1728. */
  1729. protected void pingTimerTask(final Timer timer) {
  1730. // If user no longer wants server ping to be checked, or the socket is
  1731. // closed then cancel the time and do nothing else.
  1732. if (!getCheckServerPing() || getSocketState() != SocketState.OPEN) {
  1733. pingTimerSem.acquireUninterruptibly();
  1734. if (pingTimer != null && pingTimer.equals(timer)) {
  1735. pingTimer.cancel();
  1736. }
  1737. pingTimerSem.release();
  1738. return;
  1739. }
  1740. if (getPingNeeded()) {
  1741. callPingFailed();
  1742. } else {
  1743. --pingCountDown;
  1744. if (pingCountDown < 1) {
  1745. pingTime = System.currentTimeMillis();
  1746. setPingNeeded(true);
  1747. pingCountDown = getPingTimerFraction();
  1748. lastPingValue = String.valueOf(System.currentTimeMillis());
  1749. if (sendString("PING " + lastPingValue, QueuePriority.HIGH)) {
  1750. callPingSent();
  1751. }
  1752. }
  1753. }
  1754. }
  1755. @Override
  1756. public long getServerLatency() {
  1757. return serverLag;
  1758. }
  1759. /**
  1760. * Updates the name of the server that this parser is connected to.
  1761. *
  1762. * @param serverName The discovered server name
  1763. */
  1764. public void updateServerName(final String serverName) {
  1765. setServerName(serverName);
  1766. }
  1767. /**
  1768. * Get the current server lag.
  1769. *
  1770. * @param actualTime if True the value returned will be the actual time the ping was sent
  1771. * else it will be the amount of time sinse the last ping was sent.
  1772. * @return Time last ping was sent
  1773. */
  1774. public long getPingTime(final boolean actualTime) {
  1775. if (actualTime) {
  1776. return pingTime;
  1777. } else {
  1778. return System.currentTimeMillis() - pingTime;
  1779. }
  1780. }
  1781. @Override
  1782. public long getPingTime() {
  1783. return getPingTime(false);
  1784. }
  1785. /**
  1786. * Set if a ping is needed or not.
  1787. *
  1788. * @param newStatus new value to set pingNeeded to.
  1789. */
  1790. private void setPingNeeded(final boolean newStatus) {
  1791. pingNeeded.set(newStatus);
  1792. }
  1793. /**
  1794. * Get if a ping is needed or not.
  1795. *
  1796. * @return value of pingNeeded.
  1797. */
  1798. boolean getPingNeeded() {
  1799. return pingNeeded.get();
  1800. }
  1801. @Override
  1802. public IRCClientInfo getLocalClient() {
  1803. return myself;
  1804. }
  1805. /**
  1806. * Get the current nickname.
  1807. * After 001 this returns the exact same as getLocalClient().getRealNickname();
  1808. * Before 001 it returns the nickname that the parser Thinks it has.
  1809. *
  1810. * @return Current nickname.
  1811. */
  1812. public String getMyNickname() {
  1813. if (myself.isFake()) {
  1814. return thinkNickname;
  1815. } else {
  1816. return myself.getRealNickname();
  1817. }
  1818. }
  1819. /**
  1820. * Retrieves the local user information that this parser was configured
  1821. * with.
  1822. *
  1823. * @return This parser's local user configuration
  1824. */
  1825. public MyInfo getMyInfo() {
  1826. return me;
  1827. }
  1828. /**
  1829. * Get the current username (Specified in MyInfo on construction).
  1830. * Get the username given in MyInfo
  1831. *
  1832. * @return My username.
  1833. */
  1834. public String getMyUsername() {
  1835. return me.getUsername();
  1836. }
  1837. /**
  1838. * Add a client to the ClientList.
  1839. *
  1840. * @param client Client to add
  1841. */
  1842. public void addClient(final IRCClientInfo client) {
  1843. clientList.put(getStringConverter().toLowerCase(client.getRealNickname()), client);
  1844. }
  1845. /**
  1846. * Remove a client from the ClientList.
  1847. * This WILL NOT allow cMyself to be removed from the list.
  1848. *
  1849. * @param client Client to remove
  1850. */
  1851. public void removeClient(final IRCClientInfo client) {
  1852. if (client != myself) {
  1853. forceRemoveClient(client);
  1854. }
  1855. }
  1856. /**
  1857. * Remove a client from the ClientList.
  1858. * This WILL allow cMyself to be removed from the list
  1859. *
  1860. * @param client Client to remove
  1861. */
  1862. public void forceRemoveClient(final IRCClientInfo client) {
  1863. clientList.remove(getStringConverter().toLowerCase(client.getRealNickname()));
  1864. }
  1865. /**
  1866. * Get the number of known clients.
  1867. *
  1868. * @return Count of known clients
  1869. */
  1870. public int knownClients() {
  1871. return clientList.size();
  1872. }
  1873. /**
  1874. * Get the known clients as a collection.
  1875. *
  1876. * @return Known clients as a collection
  1877. */
  1878. public Collection<IRCClientInfo> getClients() {
  1879. return clientList.values();
  1880. }
  1881. /**
  1882. * Clear the client list.
  1883. */
  1884. public void clearClients() {
  1885. clientList.clear();
  1886. addClient(getLocalClient());
  1887. }
  1888. /**
  1889. * Add a channel to the ChannelList.
  1890. *
  1891. * @param channel Channel to add
  1892. */
  1893. public void addChannel(final IRCChannelInfo channel) {
  1894. synchronized (channelList) {
  1895. channelList.put(getStringConverter().toLowerCase(channel.getName()), channel);
  1896. }
  1897. }
  1898. /**
  1899. * Remove a channel from the ChannelList.
  1900. *
  1901. * @param channel Channel to remove
  1902. */
  1903. public void removeChannel(final ChannelInfo channel) {
  1904. synchronized (channelList) {
  1905. channelList.remove(getStringConverter().toLowerCase(channel.getName()));
  1906. }
  1907. }
  1908. /**
  1909. * Get the number of known channel.
  1910. *
  1911. * @return Count of known channel
  1912. */
  1913. public int knownChannels() {
  1914. synchronized (channelList) {
  1915. return channelList.size();
  1916. }
  1917. }
  1918. @Override
  1919. public Collection<IRCChannelInfo> getChannels() {
  1920. synchronized (channelList) {
  1921. return channelList.values();
  1922. }
  1923. }
  1924. /**
  1925. * Clear the channel list.
  1926. */
  1927. public void clearChannels() {
  1928. synchronized (channelList) {
  1929. channelList.clear();
  1930. }
  1931. }
  1932. @Override
  1933. public String[] parseHostmask(final String hostmask) {
  1934. return IRCClientInfo.parseHostFull(hostmask);
  1935. }
  1936. @Override
  1937. public int getMaxTopicLength() {
  1938. if (h005Info.containsKey(IrcConstants.ISUPPORT_TOPIC_LENGTH)) {
  1939. try {
  1940. return Integer.parseInt(h005Info.get(IrcConstants.ISUPPORT_TOPIC_LENGTH));
  1941. } catch (NumberFormatException ex) {
  1942. // Do nothing
  1943. }
  1944. }
  1945. return 0;
  1946. }
  1947. @Override
  1948. public int getMaxLength() {
  1949. return MAX_LINELENGTH;
  1950. }
  1951. @Override
  1952. public void setCompositionState(final String host, final CompositionState state) {
  1953. // Do nothing
  1954. }
  1955. @Override
  1956. protected void handleSocketDebug(final String message) {
  1957. super.handleSocketDebug(message);
  1958. callDebugInfo(DEBUG_SOCKET, message);
  1959. }
  1960. }