Java IRC bot
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 66KB

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