選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

IRCParser.java 74KB

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