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 73KB

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