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