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

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