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

IRCParser.java 75KB

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