Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

IRCParser.java 75KB

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