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 75KB

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