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

IRCParser.java 73KB

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