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

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