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

IRCParser.java 73KB

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