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

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