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

IRCParser.java 74KB

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