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

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