Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

IRCParser.java 75KB

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