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

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