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

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