Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

IRCParser.java 73KB

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