You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IRCParser.java 74KB

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