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.

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