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

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