Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

IRCParser.java 75KB

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