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.

Server.java 59KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  1. /*
  2. * Copyright (c) 2006-2011 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;
  23. import com.dmdirc.actions.ActionManager;
  24. import com.dmdirc.actions.CoreActionType;
  25. import com.dmdirc.actions.wrappers.AliasWrapper;
  26. import com.dmdirc.commandparser.CommandManager;
  27. import com.dmdirc.commandparser.CommandType;
  28. import com.dmdirc.commandparser.parsers.ServerCommandParser;
  29. import com.dmdirc.config.ConfigManager;
  30. import com.dmdirc.config.Identity;
  31. import com.dmdirc.config.IdentityManager;
  32. import com.dmdirc.interfaces.AwayStateListener;
  33. import com.dmdirc.interfaces.ConfigChangeListener;
  34. import com.dmdirc.interfaces.InviteListener;
  35. import com.dmdirc.logger.ErrorLevel;
  36. import com.dmdirc.logger.Logger;
  37. import com.dmdirc.parser.common.ChannelJoinRequest;
  38. import com.dmdirc.parser.common.DefaultStringConverter;
  39. import com.dmdirc.parser.common.IgnoreList;
  40. import com.dmdirc.parser.common.MyInfo;
  41. import com.dmdirc.parser.common.ParserError;
  42. import com.dmdirc.parser.interfaces.ChannelInfo;
  43. import com.dmdirc.parser.interfaces.ClientInfo;
  44. import com.dmdirc.parser.interfaces.EncodingParser;
  45. import com.dmdirc.parser.interfaces.Parser;
  46. import com.dmdirc.parser.interfaces.ProtocolDescription;
  47. import com.dmdirc.parser.interfaces.SecureParser;
  48. import com.dmdirc.parser.interfaces.StringConverter;
  49. import com.dmdirc.ui.WindowManager;
  50. import com.dmdirc.ui.core.components.StatusBarManager;
  51. import com.dmdirc.ui.input.TabCompleter;
  52. import com.dmdirc.ui.input.TabCompletionType;
  53. import com.dmdirc.ui.interfaces.ServerWindow;
  54. import com.dmdirc.ui.interfaces.Window;
  55. import com.dmdirc.ui.messages.Formatter;
  56. import java.net.URI;
  57. import java.util.ArrayList;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.HashMap;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.Random;
  65. import java.util.Set;
  66. import java.util.Timer;
  67. import java.util.TimerTask;
  68. import java.util.concurrent.locks.ReadWriteLock;
  69. import java.util.concurrent.locks.ReentrantReadWriteLock;
  70. import javax.net.ssl.TrustManager;
  71. /**
  72. * The Server class represents the client's view of a server. It maintains
  73. * a list of all channels, queries, etc, and handles parser callbacks pertaining
  74. * to the server.
  75. *
  76. * @author chris
  77. */
  78. public class Server extends WritableFrameContainer<ServerWindow> implements ConfigChangeListener {
  79. // <editor-fold defaultstate="collapsed" desc="Properties">
  80. // <editor-fold defaultstate="collapsed" desc="Static">
  81. /** The name of the general domain. */
  82. private static final String DOMAIN_GENERAL = "general".intern();
  83. /** The name of the profile domain. */
  84. private static final String DOMAIN_PROFILE = "profile".intern();
  85. /** The name of the server domain. */
  86. private static final String DOMAIN_SERVER = "server".intern();
  87. // </editor-fold>
  88. // <editor-fold defaultstate="collapsed" desc="Instance">
  89. /** Open channels that currently exist on the server. */
  90. private final Map<String, Channel> channels = new HashMap<String, Channel>();
  91. /** Open query windows on the server. */
  92. private final Map<String, Query> queries = new HashMap<String, Query>();
  93. /** The Parser instance handling this server. */
  94. private Parser parser;
  95. /** The Parser instance that used to be handling this server. */
  96. private Parser oldParser;
  97. /** The parser-supplied protocol description object. */
  98. private ProtocolDescription protocolDescription;
  99. /**
  100. * Object used to synchronoise access to parser. This object should be
  101. * locked by anything requiring that the parser reference remains the same
  102. * for a duration of time, or by anything which is updating the parser
  103. * reference.
  104. *
  105. * If used in conjunction with myStateLock, the parserLock must always be
  106. * locked INSIDE the myStateLock to prevent deadlocks.
  107. */
  108. private final ReadWriteLock parserLock = new ReentrantReadWriteLock();
  109. /** The Parser Thread. */
  110. private Thread parserThread;
  111. /** The raw frame used for this server instance. */
  112. private Raw raw;
  113. /** The address of the server we're connecting to. */
  114. private URI address;
  115. /** The profile we're using. */
  116. private Identity profile;
  117. /** Object used to synchronise access to myState. */
  118. private final Object myStateLock = new Object();
  119. /** The current state of this server. */
  120. private final ServerStatus myState = new ServerStatus(this, myStateLock);
  121. /** The timer we're using to delay reconnects. */
  122. private Timer reconnectTimer;
  123. /** The tabcompleter used for this server. */
  124. private final TabCompleter tabCompleter = new TabCompleter();
  125. /** The last activated internal frame for this server. */
  126. private FrameContainer<?> activeFrame = this;
  127. /** Our reason for being away, if any. */
  128. private String awayMessage;
  129. /** Our event handler. */
  130. private final ServerEventHandler eventHandler = new ServerEventHandler(this);
  131. /** A list of outstanding invites. */
  132. private final List<Invite> invites = new ArrayList<Invite>();
  133. /** A set of channels we want to join without focusing. */
  134. private final Set<String> backgroundChannels = new HashSet<String>();
  135. /** Our ignore list. */
  136. private final IgnoreList ignoreList = new IgnoreList();
  137. /** Our string convertor. */
  138. private StringConverter converter = new DefaultStringConverter();
  139. // </editor-fold>
  140. // </editor-fold>
  141. // <editor-fold defaultstate="collapsed" desc="Constructors">
  142. /**
  143. * Creates a new server which will connect to the specified URL with
  144. * the specified profile.
  145. *
  146. * @since 0.6.3
  147. * @param uri The address of the server to connect to
  148. * @param profile The profile to use
  149. */
  150. public Server(final URI uri, final Identity profile) {
  151. super("server-disconnected", getHost(uri), getHost(uri),
  152. ServerWindow.class,
  153. new ConfigManager(uri.getScheme(), "", "", uri.getHost()),
  154. new ServerCommandParser());
  155. this.address = uri;
  156. this.protocolDescription = new ParserFactory().getDescription(address);
  157. this.profile = profile;
  158. ServerManager.getServerManager().registerServer(this);
  159. WindowManager.addWindow(this);
  160. tabCompleter.addEntries(TabCompletionType.COMMAND,
  161. AliasWrapper.getAliasWrapper().getAliases());
  162. tabCompleter.addEntries(TabCompletionType.COMMAND,
  163. CommandManager.getCommandNames(CommandType.TYPE_SERVER));
  164. tabCompleter.addEntries(TabCompletionType.COMMAND,
  165. CommandManager.getCommandNames(CommandType.TYPE_GLOBAL));
  166. updateIcon();
  167. new Timer("Server Who Timer").schedule(new TimerTask() {
  168. @Override
  169. public void run() {
  170. for (Channel channel : channels.values()) {
  171. channel.checkWho();
  172. }
  173. }
  174. }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime"));
  175. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) {
  176. addRaw();
  177. }
  178. getConfigManager().addChangeListener("formatter", "serverName", this);
  179. getConfigManager().addChangeListener("formatter", "serverTitle", this);
  180. }
  181. // </editor-fold>
  182. // <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection">
  183. /**
  184. * Connects to a new server with the previously supplied address and profile.
  185. *
  186. * @since 0.6.3m2
  187. */
  188. public void connect() {
  189. connect(address, profile);
  190. }
  191. /**
  192. * Connects to a new server with the specified details.
  193. *
  194. * @param address The address of the server to connect to
  195. * @param profile The profile to use
  196. * @since 0.6.3
  197. */
  198. @Precondition({
  199. "The current parser is null or not connected",
  200. "The specified profile is not null"
  201. })
  202. @SuppressWarnings("fallthrough")
  203. public void connect(final URI address, final Identity profile) {
  204. assert profile != null;
  205. synchronized (myStateLock) {
  206. switch (myState.getState()) {
  207. case RECONNECT_WAIT:
  208. reconnectTimer.cancel();
  209. break;
  210. case CLOSING:
  211. // Ignore the connection attempt
  212. return;
  213. case CONNECTED:
  214. case CONNECTING:
  215. disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
  216. case DISCONNECTING:
  217. while (!myState.getState().isDisconnected()) {
  218. try {
  219. myStateLock.wait();
  220. } catch (InterruptedException ex) {
  221. return;
  222. }
  223. }
  224. break;
  225. default:
  226. // Do nothing
  227. break;
  228. }
  229. final URI connectAddress;
  230. try {
  231. parserLock.writeLock().lock();
  232. if (parser != null) {
  233. throw new IllegalArgumentException("Connection attempt while parser "
  234. + "is still connected.\n\nMy state:" + getState());
  235. }
  236. getConfigManager().migrate(address.getScheme(), "", "", address.getHost());
  237. this.address = address;
  238. this.protocolDescription = new ParserFactory().getDescription(address);
  239. this.profile = profile;
  240. updateTitle();
  241. updateIcon();
  242. parser = buildParser();
  243. if (parser == null) {
  244. addLine("serverUnknownProtocol", address.getScheme());
  245. return;
  246. }
  247. connectAddress = parser.getURI();
  248. } finally {
  249. parserLock.writeLock().unlock();
  250. }
  251. addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
  252. myState.transition(ServerState.CONNECTING);
  253. doCallbacks();
  254. updateAwayState(null);
  255. removeInvites();
  256. try {
  257. parserThread = new Thread(parser, "Parser thread");
  258. parserThread.start();
  259. } catch (IllegalThreadStateException ex) {
  260. // This won't happen. Ever. But it's a checked exception. Yay.
  261. Logger.appError(ErrorLevel.HIGH, "Unable to start parser", ex);
  262. return;
  263. }
  264. }
  265. ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
  266. }
  267. /**
  268. * Reconnects to the server with a specified reason.
  269. *
  270. * @param reason The quit reason to send
  271. */
  272. public void reconnect(final String reason) {
  273. synchronized (myStateLock) {
  274. if (myState.getState() == ServerState.CLOSING) {
  275. return;
  276. }
  277. disconnect(reason);
  278. connect(address, profile);
  279. }
  280. }
  281. /**
  282. * Reconnects to the server.
  283. */
  284. public void reconnect() {
  285. reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage"));
  286. }
  287. /**
  288. * Disconnects from the server with the default quit message.
  289. */
  290. public void disconnect() {
  291. disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
  292. }
  293. /**
  294. * Disconnects from the server.
  295. *
  296. * @param reason disconnect reason
  297. */
  298. public void disconnect(final String reason) {
  299. synchronized (myStateLock) {
  300. switch (myState.getState()) {
  301. case CLOSING:
  302. case DISCONNECTING:
  303. case DISCONNECTED:
  304. case TRANSIENTLY_DISCONNECTED:
  305. return;
  306. case RECONNECT_WAIT:
  307. reconnectTimer.cancel();
  308. break;
  309. default:
  310. break;
  311. }
  312. clearChannels();
  313. backgroundChannels.clear();
  314. try {
  315. parserLock.readLock().lock();
  316. if (parser == null) {
  317. myState.transition(ServerState.DISCONNECTED);
  318. } else {
  319. myState.transition(ServerState.DISCONNECTING);
  320. removeInvites();
  321. updateIcon();
  322. parserThread.interrupt();
  323. parser.disconnect(reason);
  324. }
  325. } finally {
  326. parserLock.readLock().unlock();
  327. }
  328. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  329. "closechannelsonquit")) {
  330. closeChannels();
  331. }
  332. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  333. "closequeriesonquit")) {
  334. closeQueries();
  335. }
  336. }
  337. }
  338. /**
  339. * Schedules a reconnect attempt to be performed after a user-defiend delay.
  340. */
  341. @Precondition("The server state is transiently disconnected")
  342. private void doDelayedReconnect() {
  343. synchronized (myStateLock) {
  344. if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) {
  345. throw new IllegalStateException("doDelayedReconnect when not "
  346. + "transiently disconnected\n\nState: " + myState);
  347. }
  348. final int delay = Math.max(1000,
  349. getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay"));
  350. handleNotification("connectRetry", getAddress(), delay / 1000);
  351. reconnectTimer = new Timer("Server Reconnect Timer");
  352. reconnectTimer.schedule(new TimerTask() {
  353. @Override
  354. public void run() {
  355. synchronized (myStateLock) {
  356. if (myState.getState() == ServerState.RECONNECT_WAIT) {
  357. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  358. reconnect();
  359. }
  360. }
  361. }
  362. }, delay);
  363. myState.transition(ServerState.RECONNECT_WAIT);
  364. updateIcon();
  365. }
  366. }
  367. // </editor-fold>
  368. // <editor-fold defaultstate="collapsed" desc="Child windows">
  369. /**
  370. * Determines whether the server knows of the specified channel.
  371. *
  372. * @param channel The channel to be checked
  373. * @return True iff the channel is known, false otherwise
  374. */
  375. public boolean hasChannel(final String channel) {
  376. return channels.containsKey(converter.toLowerCase(channel));
  377. }
  378. /**
  379. * Retrieves the specified channel belonging to this server.
  380. *
  381. * @param channel The channel to be retrieved
  382. * @return The appropriate channel object
  383. */
  384. public Channel getChannel(final String channel) {
  385. return channels.get(converter.toLowerCase(channel));
  386. }
  387. /**
  388. * Retrieves a list of channel names belonging to this server.
  389. *
  390. * @return list of channel names belonging to this server
  391. */
  392. public List<String> getChannels() {
  393. final ArrayList<String> res = new ArrayList<String>();
  394. for (String channel : channels.keySet()) {
  395. res.add(channel);
  396. }
  397. return res;
  398. }
  399. /**
  400. * Determines whether the server knows of the specified query.
  401. *
  402. * @param host The host of the query to look for
  403. * @return True iff the query is known, false otherwise
  404. */
  405. public boolean hasQuery(final String host) {
  406. return queries.containsKey(converter.toLowerCase(parseHostmask(host)[0]));
  407. }
  408. /**
  409. * Retrieves the specified query belonging to this server. If the query
  410. * does not yet exist, it is created automatically.
  411. *
  412. * @param host The host of the query to look for
  413. * @return The appropriate query object
  414. */
  415. public Query getQuery(final String host) {
  416. synchronized (myStateLock) {
  417. if (myState.getState() == ServerState.CLOSING) {
  418. // Can't open queries while the server is closing
  419. return null;
  420. }
  421. }
  422. final String nick = parseHostmask(host)[0];
  423. final String lnick = converter.toLowerCase(nick);
  424. if (!queries.containsKey(lnick)) {
  425. final Query newQuery = new Query(this, host);
  426. tabCompleter.addEntry(TabCompletionType.QUERY_NICK, nick);
  427. queries.put(lnick, newQuery);
  428. }
  429. return queries.get(lnick);
  430. }
  431. /**
  432. * Updates the state of this server following a nick change of someone
  433. * that the user has a query open with. Namely, this updates the
  434. * tabcompleter with the new name, and ensures that the <code>queries</code>
  435. * map uses the correct nickname.
  436. *
  437. * @param query The query object being updated
  438. * @param oldNick The old nickname of the user
  439. * @param newNick The new nickname of the user
  440. * @since 0.6.4
  441. */
  442. public void updateQuery(final Query query, final String oldNick, final String newNick) {
  443. tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, oldNick);
  444. tabCompleter.addEntry(TabCompletionType.QUERY_NICK, newNick);
  445. queries.put(converter.toLowerCase(newNick), query);
  446. queries.remove(converter.toLowerCase(oldNick));
  447. }
  448. /**
  449. * Retrieves a list of queries belonging to this server.
  450. *
  451. * @return list of queries belonging to this server
  452. */
  453. public Collection<Query> getQueries() {
  454. return Collections.unmodifiableCollection(queries.values());
  455. }
  456. /**
  457. * Adds a query to this server.
  458. *
  459. * @param host host of the remote client being queried
  460. * @return The query that was added (may be null if closing)
  461. * @deprecated Use {@link #getQuery(java.lang.String)} instead
  462. */
  463. @Deprecated
  464. public Query addQuery(final String host) {
  465. return getQuery(host);
  466. }
  467. /**
  468. * Deletes a query from this server.
  469. *
  470. * @param query The query that should be removed.
  471. */
  472. public void delQuery(final Query query) {
  473. tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname());
  474. queries.remove(converter.toLowerCase(query.getNickname()));
  475. }
  476. /**
  477. * Adds a raw window to this server.
  478. */
  479. public void addRaw() {
  480. if (raw == null) {
  481. raw = new Raw(this);
  482. try {
  483. parserLock.readLock().lock();
  484. if (parser != null) {
  485. raw.registerCallbacks();
  486. }
  487. } finally {
  488. parserLock.readLock().unlock();
  489. }
  490. } else {
  491. raw.activateFrame();
  492. }
  493. }
  494. /**
  495. * Retrieves the raw window associated with this server.
  496. *
  497. * @return The raw window associated with this server.
  498. */
  499. public Raw getRaw() {
  500. return raw;
  501. }
  502. /**
  503. * Removes our reference to the raw object (presumably after it has been
  504. * closed).
  505. */
  506. public void delRaw() {
  507. raw = null; //NOPMD
  508. }
  509. /**
  510. * Removes a specific channel and window from this server.
  511. *
  512. * @param chan channel to remove
  513. */
  514. public void delChannel(final String chan) {
  515. tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan);
  516. channels.remove(converter.toLowerCase(chan));
  517. }
  518. /**
  519. * Adds a specific channel and window to this server.
  520. *
  521. * @param chan channel to add
  522. * @return The channel that was added (may be null if closing)
  523. */
  524. public Channel addChannel(final ChannelInfo chan) {
  525. return addChannel(chan, !backgroundChannels.contains(chan.getName())
  526. || getConfigManager().getOptionBool(DOMAIN_GENERAL,
  527. "hidechannels"));
  528. }
  529. /**
  530. * Adds a specific channel and window to this server.
  531. *
  532. * @param chan channel to add
  533. * @param focus Whether or not to focus the channel
  534. * @return The channel that was added (may be null if closing)
  535. */
  536. public Channel addChannel(final ChannelInfo chan, final boolean focus) {
  537. synchronized (myStateLock) {
  538. if (myState.getState() == ServerState.CLOSING) {
  539. // Can't join channels while the server is closing
  540. return null;
  541. }
  542. }
  543. backgroundChannels.remove(chan.getName());
  544. if (hasChannel(chan.getName())) {
  545. getChannel(chan.getName()).setChannelInfo(chan);
  546. getChannel(chan.getName()).selfJoin();
  547. } else {
  548. final Channel newChan = new Channel(this, chan, focus);
  549. tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName());
  550. channels.put(converter.toLowerCase(chan.getName()), newChan);
  551. }
  552. return getChannel(chan.getName());
  553. }
  554. /** {@inheritDoc} */
  555. @Override
  556. @SuppressWarnings("element-type-mismatch")
  557. public boolean ownsFrame(final Window target) {
  558. // Check if it's our server frame
  559. if (windows.contains(target)) { return true; }
  560. // Check if it's the raw frame
  561. if (raw != null && raw.ownsFrame(target)) { return true; }
  562. // Check if it's a channel frame
  563. for (Channel channel : channels.values()) {
  564. if (channel.ownsFrame(target)) { return true; }
  565. }
  566. // Check if it's a query frame
  567. for (Query query : queries.values()) {
  568. if (query.ownsFrame(target)) { return true; }
  569. }
  570. return false;
  571. }
  572. /**
  573. * Sets the specified frame as the most-recently activated.
  574. *
  575. * @param source The frame that was activated
  576. */
  577. public void setActiveFrame(final FrameContainer<?> source) {
  578. activeFrame = source;
  579. }
  580. /**
  581. * Closes all open channel windows associated with this server.
  582. */
  583. private void closeChannels() {
  584. for (Channel channel : new ArrayList<Channel>(channels.values())) {
  585. channel.close();
  586. }
  587. }
  588. /**
  589. * Clears the nicklist of all open channels.
  590. */
  591. private void clearChannels() {
  592. for (Channel channel : channels.values()) {
  593. channel.resetWindow();
  594. }
  595. }
  596. /**
  597. * Closes all open query windows associated with this server.
  598. */
  599. private void closeQueries() {
  600. for (Query query : new ArrayList<Query>(queries.values())) {
  601. query.close();
  602. }
  603. }
  604. // </editor-fold>
  605. // <editor-fold defaultstate="collapsed" desc="Miscellaneous methods">
  606. /**
  607. * Retrieves the host component of the specified URI, or throws a relevant
  608. * exception if this is not possible.
  609. *
  610. * @param uri The URI to be processed
  611. * @return The URI's host component, as returned by {@link URI#getHost()}.
  612. * @throws NullPointerException If <code>uri</code> is null
  613. * @throws IllegalArgumentException If the specified URI has no host
  614. * @since 0.6.4
  615. */
  616. private static String getHost(final URI uri) {
  617. if (uri.getHost() == null) {
  618. throw new IllegalArgumentException("URIs must have hosts");
  619. }
  620. return uri.getHost();
  621. }
  622. /**
  623. * Builds an appropriately configured {@link Parser} for this server.
  624. *
  625. * @return A configured parser.
  626. */
  627. private Parser buildParser() {
  628. final MyInfo myInfo = buildMyInfo();
  629. final Parser myParser = new ParserFactory().getParser(myInfo, address);
  630. if (myParser instanceof SecureParser) {
  631. final CertificateManager certManager
  632. = new CertificateManager(address.getHost(), getConfigManager());
  633. final SecureParser secureParser = (SecureParser) myParser;
  634. secureParser.setTrustManagers(new TrustManager[]{certManager});
  635. secureParser.setKeyManagers(certManager.getKeyManager());
  636. }
  637. if (myParser instanceof EncodingParser) {
  638. final EncodingParser encodingParser = (EncodingParser) myParser;
  639. encodingParser.setEncoder(new MessageEncoder(this, myParser));
  640. }
  641. if (myParser != null) {
  642. myParser.setIgnoreList(ignoreList);
  643. myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER,
  644. "pingtimer"));
  645. myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER,
  646. "pingfrequency") / myParser.getPingTimerInterval()));
  647. if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) {
  648. myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip"));
  649. }
  650. }
  651. return myParser;
  652. }
  653. /**
  654. * Compare the given URI to the URI we are currently using to see if they
  655. * would both result in the server connecting to the same place, even if the
  656. * URIs do not match exactly.
  657. *
  658. * @param uri URI to compare with the Servers own URI.
  659. * @return True if the Given URI is the "same" as the one we are using.
  660. * @since 0.6.3
  661. */
  662. public boolean compareURI(final URI uri) {
  663. if (parser != null) {
  664. return parser.compareURI(uri);
  665. }
  666. if (oldParser != null) {
  667. return oldParser.compareURI(uri);
  668. }
  669. return false;
  670. }
  671. /**
  672. * Parses the specified hostmask in a manner prescribed by the protocol
  673. * currently used by this server.
  674. *
  675. * @see ProtocolDescription#parseHostmask(java.lang.String)
  676. * @param hostmask The hostmask to be parsed
  677. * @return An array containing the nickname, username and hostname
  678. * @since 0.6.4
  679. */
  680. public String[] parseHostmask(final String hostmask) {
  681. return protocolDescription.parseHostmask(hostmask);
  682. }
  683. /**
  684. * Retrieves the MyInfo object used for the Parser.
  685. *
  686. * @return The MyInfo object for our profile
  687. */
  688. @Precondition({
  689. "The current profile is not null",
  690. "The current profile specifies at least one nickname"
  691. })
  692. private MyInfo buildMyInfo() {
  693. Logger.assertTrue(profile != null);
  694. Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty());
  695. final MyInfo myInfo = new MyInfo();
  696. myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0));
  697. myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname"));
  698. if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) {
  699. myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident"));
  700. }
  701. return myInfo;
  702. }
  703. /**
  704. * Updates this server's icon.
  705. */
  706. private void updateIcon() {
  707. final String icon = myState.getState() == ServerState.CONNECTED
  708. ? address.getScheme().endsWith("s") ? "secure-server" : "server"
  709. : "server-disconnected";
  710. setIcon(icon);
  711. }
  712. /**
  713. * Registers callbacks.
  714. */
  715. private void doCallbacks() {
  716. if (raw != null) {
  717. raw.registerCallbacks();
  718. }
  719. eventHandler.registerCallbacks();
  720. for (Query query : queries.values()) {
  721. query.reregister();
  722. }
  723. }
  724. /**
  725. * Joins the specified channel with the specified key.
  726. *
  727. * @since 0.6.3m1
  728. * @param channel The channel to be joined
  729. * @param key The key for the channel
  730. * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])}
  731. */
  732. @Deprecated
  733. public void join(final String channel, final String key) {
  734. join(new ChannelJoinRequest(channel, key));
  735. }
  736. /**
  737. * Attempts to join the specified channels. If channels with the same name
  738. * already exist, they are (re)joined and their windows activated.
  739. *
  740. * @param requests The channel join requests to process
  741. * @since 0.6.4
  742. */
  743. public void join(final ChannelJoinRequest ... requests) {
  744. join(true, requests);
  745. }
  746. /**
  747. * Attempts to join the specified channels. If channels with the same name
  748. * already exist, they are (re)joined and their windows activated.
  749. *
  750. * @param focus Whether or not to focus any new channels
  751. * @param requests The channel join requests to process
  752. * @since 0.6.4
  753. */
  754. public void join(final boolean focus, final ChannelJoinRequest ... requests) {
  755. synchronized (myStateLock) {
  756. if (myState.getState() == ServerState.CONNECTED) {
  757. final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>();
  758. for (ChannelJoinRequest request : requests) {
  759. removeInvites(request.getName());
  760. final String name;
  761. if (parser.isValidChannelName(request.getName())) {
  762. name = request.getName();
  763. } else {
  764. name = parser.getChannelPrefixes().substring(0, 1)
  765. + request.getName();
  766. }
  767. if (hasChannel(name) && focus) {
  768. getChannel(name).activateFrame();
  769. }
  770. if (!hasChannel(name) || !getChannel(name).isOnChannel()) {
  771. if (!focus) {
  772. backgroundChannels.add(name);
  773. }
  774. pending.add(request);
  775. }
  776. }
  777. parser.joinChannels(pending.toArray(new ChannelJoinRequest[pending.size()]));
  778. } else {
  779. // TODO: Need to pass key
  780. // TODO (uris): address.getChannels().add(channel);
  781. }
  782. }
  783. }
  784. /**
  785. * Joins the specified channel, or adds it to the auto-join list if the
  786. * server is not connected.
  787. *
  788. * @param channel The channel to be joined
  789. * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])}
  790. */
  791. @Deprecated
  792. public void join(final String channel) {
  793. join(new ChannelJoinRequest(channel));
  794. }
  795. /** {@inheritDoc} */
  796. @Override
  797. public void sendLine(final String line) {
  798. synchronized (myStateLock) {
  799. try {
  800. parserLock.readLock().lock();
  801. if (parser != null && !line.isEmpty()
  802. && myState.getState() == ServerState.CONNECTED) {
  803. parser.sendRawMessage(getTranscoder().encode(line));
  804. }
  805. } finally {
  806. parserLock.readLock().unlock();
  807. }
  808. }
  809. }
  810. /** {@inheritDoc} */
  811. @Override
  812. public int getMaxLineLength() {
  813. try {
  814. parserLock.readLock().lock();
  815. return parser == null ? -1 : parser.getMaxLength();
  816. } finally {
  817. parserLock.readLock().unlock();
  818. }
  819. }
  820. /**
  821. * Retrieves the parser used for this connection.
  822. *
  823. * @return this connection's parser
  824. */
  825. public Parser getParser() {
  826. return parser;
  827. }
  828. /**
  829. * Retrieves the profile that's in use for this server.
  830. *
  831. * @return The profile in use by this server
  832. */
  833. public Identity getProfile() {
  834. return profile;
  835. }
  836. /**
  837. * Retrieves the possible channel prefixes in use on this server.
  838. *
  839. * @return This server's possible channel prefixes
  840. */
  841. public String getChannelPrefixes() {
  842. try {
  843. parserLock.readLock().lock();
  844. return parser == null ? "#&" : parser.getChannelPrefixes();
  845. } finally {
  846. parserLock.readLock().unlock();
  847. }
  848. }
  849. /**
  850. * Retrieves the address of this server.
  851. *
  852. * @return This sever's address
  853. */
  854. public String getAddress() {
  855. try {
  856. parserLock.readLock().lock();
  857. return parser == null ? address.getHost() : parser.getServerName();
  858. } finally {
  859. parserLock.readLock().unlock();
  860. }
  861. }
  862. /**
  863. * Retrieves the name of this server's network. The network name is
  864. * determined using the following rules:
  865. *
  866. * 1. If the server includes its network name in the 005 information, we
  867. * use that
  868. * 2. If the server's name ends in biz, com, info, net or org, we use the
  869. * second level domain (e.g., foo.com)
  870. * 3. If the server's name contains more than two dots, we drop everything
  871. * up to and including the first part, and use the remainder
  872. * 4. In all other cases, we use the full server name
  873. *
  874. * @return The name of this server's network
  875. */
  876. public String getNetwork() {
  877. try {
  878. parserLock.readLock().lock();
  879. if (parser == null) {
  880. throw new IllegalStateException("getNetwork called when "
  881. + "parser is null (state: " + getState() + ")");
  882. } else if (parser.getNetworkName().isEmpty()) {
  883. return getNetworkFromServerName(parser.getServerName());
  884. } else {
  885. return parser.getNetworkName();
  886. }
  887. } finally {
  888. parserLock.readLock().unlock();
  889. }
  890. }
  891. /**
  892. * Determines whether this server is currently connected to the specified
  893. * network.
  894. *
  895. * @param target The network to check for
  896. * @return True if this server is connected to the network, false otherwise
  897. * @since 0.6.3m1rc3
  898. */
  899. public boolean isNetwork(final String target) {
  900. synchronized (myStateLock) {
  901. try {
  902. parserLock.readLock().lock();
  903. if (parser == null) {
  904. return false;
  905. } else {
  906. return getNetwork().equalsIgnoreCase(target);
  907. }
  908. } finally {
  909. parserLock.readLock().unlock();
  910. }
  911. }
  912. }
  913. /**
  914. * Calculates a network name from the specified server name. This method
  915. * implements parts 2-4 of the procedure documented at getNetwork().
  916. *
  917. * @param serverName The server name to parse
  918. * @return A network name for the specified server
  919. */
  920. protected static String getNetworkFromServerName(final String serverName) {
  921. final String[] parts = serverName.split("\\.");
  922. final String[] tlds = {"biz", "com", "info", "net", "org"};
  923. boolean isTLD = false;
  924. for (String tld : tlds) {
  925. if (serverName.endsWith("." + tld)) {
  926. isTLD = true;
  927. break;
  928. }
  929. }
  930. if (isTLD && parts.length > 2) {
  931. return parts[parts.length - 2] + "." + parts[parts.length - 1];
  932. } else if (parts.length > 2) {
  933. final StringBuilder network = new StringBuilder();
  934. for (int i = 1; i < parts.length; i++) {
  935. if (network.length() > 0) {
  936. network.append('.');
  937. }
  938. network.append(parts[i]);
  939. }
  940. return network.toString();
  941. } else {
  942. return serverName;
  943. }
  944. }
  945. /**
  946. * Retrieves the name of this server's IRCd.
  947. *
  948. * @return The name of this server's IRCd
  949. */
  950. public String getIrcd() {
  951. return parser.getServerSoftwareType();
  952. }
  953. /**
  954. * Retrieves the protocol used by this server.
  955. *
  956. * @return This server's protocol
  957. * @since 0.6.3
  958. */
  959. public String getProtocol() {
  960. return address.getScheme();
  961. }
  962. /**
  963. * Returns the current away status.
  964. *
  965. * @return True if the client is marked as away, false otherwise
  966. */
  967. public boolean isAway() {
  968. return awayMessage != null;
  969. }
  970. /**
  971. * Gets the current away message.
  972. *
  973. * @return Null if the client isn't away, or a textual away message if it is
  974. */
  975. public String getAwayMessage() {
  976. return awayMessage;
  977. }
  978. /** {@inheritDoc} */
  979. @Override
  980. public TabCompleter getTabCompleter() {
  981. return tabCompleter;
  982. }
  983. /**
  984. * Retrieves the current state for this server.
  985. *
  986. * @return This server's state
  987. */
  988. public ServerState getState() {
  989. return myState.getState();
  990. }
  991. /**
  992. * Retrieves the status object for this server. Effecting state transitions
  993. * on the object returned by this method will almost certainly cause
  994. * problems.
  995. *
  996. * @since 0.6.3m1
  997. * @return This server's status object.
  998. */
  999. public ServerStatus getStatus() {
  1000. return myState;
  1001. }
  1002. /** {@inheritDoc} */
  1003. @Override
  1004. public void windowClosing() {
  1005. synchronized (myStateLock) {
  1006. // 2: Remove any callbacks or listeners
  1007. eventHandler.unregisterCallbacks();
  1008. // 3: Trigger any actions neccessary
  1009. disconnect();
  1010. myState.transition(ServerState.CLOSING);
  1011. }
  1012. closeChannels();
  1013. closeQueries();
  1014. removeInvites();
  1015. if (raw != null) {
  1016. raw.close();
  1017. }
  1018. // 4: Trigger action for the window closing
  1019. // 5: Inform any parents that the window is closing
  1020. ServerManager.getServerManager().unregisterServer(this);
  1021. }
  1022. /** {@inheritDoc} */
  1023. @Override
  1024. public void windowClosed() {
  1025. // 7: Remove any references to the window and parents
  1026. oldParser = null; //NOPMD
  1027. parser = null; //NOPMD
  1028. }
  1029. /**
  1030. * Passes the arguments to the most recently activated frame for this
  1031. * server. If the frame isn't know, or isn't visible, use this frame
  1032. * instead.
  1033. *
  1034. * @param messageType The type of message to send
  1035. * @param args The arguments for the message
  1036. */
  1037. public void addLineToActive(final String messageType, final Object... args) {
  1038. if (activeFrame == null || !activeFrame.getFrame().isVisible()) {
  1039. activeFrame = this;
  1040. }
  1041. activeFrame.addLine(messageType, args);
  1042. }
  1043. /**
  1044. * Passes the arguments to all frames for this server.
  1045. *
  1046. * @param messageType The type of message to send
  1047. * @param args The arguments of the message
  1048. */
  1049. public void addLineToAll(final String messageType, final Object... args) {
  1050. for (Channel channel : channels.values()) {
  1051. channel.addLine(messageType, args);
  1052. }
  1053. for (Query query : queries.values()) {
  1054. query.addLine(messageType, args);
  1055. }
  1056. addLine(messageType, args);
  1057. }
  1058. /**
  1059. * Replies to an incoming CTCP message.
  1060. *
  1061. * @param source The source of the message
  1062. * @param type The CTCP type
  1063. * @param args The CTCP arguments
  1064. */
  1065. public void sendCTCPReply(final String source, final String type, final String args) {
  1066. if (type.equalsIgnoreCase("VERSION")) {
  1067. parser.sendCTCPReply(source, "VERSION", "DMDirc "
  1068. + getConfigManager().getOption("version", "version")
  1069. + " - http://www.dmdirc.com/");
  1070. } else if (type.equalsIgnoreCase("PING")) {
  1071. parser.sendCTCPReply(source, "PING", args);
  1072. } else if (type.equalsIgnoreCase("CLIENTINFO")) {
  1073. parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
  1074. }
  1075. }
  1076. /**
  1077. * Determines if the specified channel name is valid. A channel name is
  1078. * valid if we already have an existing Channel with the same name, or
  1079. * we have a valid parser instance and the parser says it's valid.
  1080. *
  1081. * @param channelName The name of the channel to test
  1082. * @return True if the channel name is valid, false otherwise
  1083. */
  1084. public boolean isValidChannelName(final String channelName) {
  1085. try {
  1086. parserLock.readLock().lock();
  1087. return hasChannel(channelName)
  1088. || (parser != null && parser.isValidChannelName(channelName));
  1089. } finally {
  1090. parserLock.readLock().unlock();
  1091. }
  1092. }
  1093. /**
  1094. * Returns the server instance associated with this frame.
  1095. *
  1096. * @return the associated server connection
  1097. */
  1098. @Override
  1099. public Server getServer() {
  1100. return this;
  1101. }
  1102. /** {@inheritDoc} */
  1103. @Override
  1104. protected boolean processNotificationArg(final Object arg, final List<Object> args) {
  1105. if (arg instanceof ClientInfo) {
  1106. final ClientInfo clientInfo = (ClientInfo) arg;
  1107. args.add(clientInfo.getNickname());
  1108. args.add(clientInfo.getUsername());
  1109. args.add(clientInfo.getHostname());
  1110. return true;
  1111. } else {
  1112. return super.processNotificationArg(arg, args);
  1113. }
  1114. }
  1115. /**
  1116. * Updates the name and title of this window.
  1117. */
  1118. public void updateTitle() {
  1119. synchronized (myStateLock) {
  1120. if (myState.getState() == ServerState.CLOSING) {
  1121. return;
  1122. }
  1123. try {
  1124. parserLock.readLock().lock();
  1125. final Object[] arguments = new Object[]{
  1126. address.getHost(), parser == null ? "Unknown" : parser.getServerName(),
  1127. address.getPort(), parser == null ? "Unknown" : getNetwork(),
  1128. parser == null ? "Unknown" : parser.getLocalClient().getNickname()
  1129. };
  1130. setName(Formatter.formatMessage(getConfigManager(),
  1131. "serverName", arguments));
  1132. setTitle(Formatter.formatMessage(getConfigManager(),
  1133. "serverTitle", arguments));
  1134. } finally {
  1135. parserLock.readLock().unlock();
  1136. }
  1137. }
  1138. }
  1139. /** {@inheritDoc} */
  1140. @Override
  1141. public void configChanged(final String domain, final String key) {
  1142. if ("formatter".equals(domain)) {
  1143. updateTitle();
  1144. }
  1145. }
  1146. // </editor-fold>
  1147. // <editor-fold defaultstate="collapsed" desc="Parser callbacks">
  1148. /**
  1149. * Called when the server says that the nickname we're trying to use is
  1150. * already in use.
  1151. *
  1152. * @param nickname The nickname that we were trying to use
  1153. */
  1154. public void onNickInUse(final String nickname) {
  1155. final String lastNick = parser.getLocalClient().getNickname();
  1156. // If our last nick is still valid, ignore the in use message
  1157. if (!converter.equalsIgnoreCase(lastNick, nickname)) {
  1158. return;
  1159. }
  1160. String newNick = lastNick + new Random().nextInt(10);
  1161. final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames");
  1162. int offset = 0;
  1163. // Loop so we can check case sensitivity
  1164. for (String alt : alts) {
  1165. offset++;
  1166. if (converter.equalsIgnoreCase(alt, lastNick)) {
  1167. break;
  1168. }
  1169. }
  1170. if (offset < alts.size() && !alts.get(offset).isEmpty()) {
  1171. newNick = alts.get(offset);
  1172. }
  1173. parser.getLocalClient().setNickname(newNick);
  1174. }
  1175. /**
  1176. * Called when the server sends a numeric event.
  1177. *
  1178. * @param numeric The numeric code for the event
  1179. * @param tokens The (tokenised) arguments of the event
  1180. */
  1181. public void onNumeric(final int numeric, final String[] tokens) {
  1182. String snumeric = String.valueOf(numeric);
  1183. if (numeric < 10) {
  1184. snumeric = "00" + snumeric;
  1185. } else if (numeric < 100) {
  1186. snumeric = "0" + snumeric;
  1187. }
  1188. final String sansIrcd = "numeric_" + snumeric;
  1189. StringBuffer target = new StringBuffer("");
  1190. if (getConfigManager().hasOptionString("formatter", sansIrcd)) {
  1191. target = new StringBuffer(sansIrcd);
  1192. } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) {
  1193. target = new StringBuffer("numeric_unknown");
  1194. }
  1195. ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this,
  1196. Integer.valueOf(numeric), tokens);
  1197. handleNotification(target.toString(), (Object[]) tokens);
  1198. }
  1199. /**
  1200. * Called when the socket has been closed.
  1201. */
  1202. public void onSocketClosed() {
  1203. if (Thread.holdsLock(myStateLock)) {
  1204. new Thread(new Runnable() {
  1205. /** {@inheritDoc} */
  1206. @Override
  1207. public void run() {
  1208. onSocketClosed();
  1209. }
  1210. }, "Socket closed deferred thread").start();
  1211. return;
  1212. }
  1213. handleNotification("socketClosed", getAddress());
  1214. ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this);
  1215. eventHandler.unregisterCallbacks();
  1216. synchronized (myStateLock) {
  1217. if (myState.getState() == ServerState.CLOSING
  1218. || myState.getState() == ServerState.DISCONNECTED) {
  1219. // This has been triggered via .disconnect()
  1220. return;
  1221. }
  1222. if (myState.getState() == ServerState.DISCONNECTING) {
  1223. myState.transition(ServerState.DISCONNECTED);
  1224. } else {
  1225. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  1226. }
  1227. clearChannels();
  1228. try {
  1229. parserLock.writeLock().lock();
  1230. oldParser = parser;
  1231. parser = null;
  1232. } finally {
  1233. parserLock.writeLock().unlock();
  1234. }
  1235. updateIcon();
  1236. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1237. "closechannelsondisconnect")) {
  1238. closeChannels();
  1239. }
  1240. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1241. "closequeriesondisconnect")) {
  1242. closeQueries();
  1243. }
  1244. removeInvites();
  1245. updateAwayState(null);
  1246. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1247. "reconnectondisconnect")
  1248. && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) {
  1249. doDelayedReconnect();
  1250. }
  1251. }
  1252. }
  1253. /**
  1254. * Called when an error was encountered while connecting.
  1255. *
  1256. * @param errorInfo The parser's error information
  1257. */
  1258. @Precondition("The current server state is CONNECTING")
  1259. public void onConnectError(final ParserError errorInfo) {
  1260. synchronized (myStateLock) {
  1261. if (myState.getState() == ServerState.CLOSING
  1262. || myState.getState() == ServerState.DISCONNECTING) {
  1263. // Do nothing
  1264. return;
  1265. } else if (myState.getState() != ServerState.CONNECTING) {
  1266. // Shouldn't happen
  1267. throw new IllegalStateException("Connect error when not "
  1268. + "connecting\n\n" + getStatus().getTransitionHistory());
  1269. }
  1270. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  1271. try {
  1272. parserLock.writeLock().lock();
  1273. oldParser = parser;
  1274. parser = null;
  1275. } finally {
  1276. parserLock.writeLock().unlock();
  1277. }
  1278. updateIcon();
  1279. String description;
  1280. if (errorInfo.getException() == null) {
  1281. description = errorInfo.getData();
  1282. } else {
  1283. final Exception exception = errorInfo.getException();
  1284. if (exception instanceof java.net.UnknownHostException) {
  1285. description = "Unknown host (unable to resolve)";
  1286. } else if (exception instanceof java.net.NoRouteToHostException) {
  1287. description = "No route to host";
  1288. } else if (exception instanceof java.net.SocketTimeoutException) {
  1289. description = "Connection attempt timed out";
  1290. } else if (exception instanceof java.net.SocketException
  1291. || exception instanceof javax.net.ssl.SSLException) {
  1292. description = exception.getMessage();
  1293. } else {
  1294. Logger.appError(ErrorLevel.LOW, "Unknown socket error",
  1295. new IllegalArgumentException(exception));
  1296. description = "Unknown error: " + exception.getMessage();
  1297. }
  1298. }
  1299. ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null,
  1300. this, description);
  1301. handleNotification("connectError", getAddress(), description);
  1302. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1303. "reconnectonconnectfailure")) {
  1304. doDelayedReconnect();
  1305. }
  1306. }
  1307. }
  1308. /**
  1309. * Called when we fail to receive a ping reply within a set period of time.
  1310. */
  1311. public void onPingFailed() {
  1312. StatusBarManager.getStatusBarManager().setMessage("No ping reply from "
  1313. + getName() + " for over "
  1314. + ((int) (Math.floor(parser.getPingTime() / 1000.0)))
  1315. + " seconds.", null, 10);
  1316. ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this,
  1317. Long.valueOf(parser.getPingTime()));
  1318. if (parser.getPingTime()
  1319. >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) {
  1320. handleNotification("stonedServer", getAddress());
  1321. reconnect();
  1322. }
  1323. }
  1324. /**
  1325. * Called after the parser receives the 005 headers from the server.
  1326. */
  1327. @Precondition("State is CONNECTING")
  1328. public void onPost005() {
  1329. synchronized (myStateLock) {
  1330. if (myState.getState() != ServerState.CONNECTING) {
  1331. // Shouldn't happen
  1332. throw new IllegalStateException("Received onPost005 while not "
  1333. + "connecting\n\n" + myState.getTransitionHistory());
  1334. }
  1335. if (myState.getState() != ServerState.CONNECTING) {
  1336. // We've transitioned while waiting for the lock. Just abort.
  1337. return;
  1338. }
  1339. myState.transition(ServerState.CONNECTED);
  1340. getConfigManager().migrate(address.getScheme(),
  1341. parser.getServerSoftwareType(), getNetwork(), parser.getServerName());
  1342. updateIcon();
  1343. updateTitle();
  1344. updateIgnoreList();
  1345. converter = parser.getStringConverter();
  1346. final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>();
  1347. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) {
  1348. for (Channel chan : channels.values()) {
  1349. requests.add(new ChannelJoinRequest(chan.getName()));
  1350. }
  1351. }
  1352. join(requests.toArray(new ChannelJoinRequest[0]));
  1353. checkModeAliases();
  1354. }
  1355. ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this);
  1356. }
  1357. /**
  1358. * Checks that we have the necessary mode aliases for this server.
  1359. */
  1360. private void checkModeAliases() {
  1361. // Check we have mode aliases
  1362. final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes()
  1363. + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes();
  1364. final String umodes = parser.getUserModes();
  1365. final StringBuffer missingModes = new StringBuffer();
  1366. final StringBuffer missingUmodes = new StringBuffer();
  1367. for (char mode : modes.toCharArray()) {
  1368. if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) {
  1369. missingModes.append(mode);
  1370. }
  1371. }
  1372. for (char mode : umodes.toCharArray()) {
  1373. if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) {
  1374. missingUmodes.append(mode);
  1375. }
  1376. }
  1377. if (missingModes.length() + missingUmodes.length() > 0) {
  1378. final StringBuffer missing = new StringBuffer("Missing mode aliases: ");
  1379. if (missingModes.length() > 0) {
  1380. missing.append("channel: +");
  1381. missing.append(missingModes);
  1382. }
  1383. if (missingUmodes.length() > 0) {
  1384. if (missingModes.length() > 0) {
  1385. missing.append(' ');
  1386. }
  1387. missing.append("user: +");
  1388. missing.append(missingUmodes);
  1389. }
  1390. Logger.appError(ErrorLevel.LOW, missing.toString() + " ["
  1391. + parser.getServerSoftwareType() + "]",
  1392. new MissingModeAliasException(getNetwork(), parser,
  1393. getConfigManager().getOption("identity",
  1394. "modealiasversion"), missing.toString()));
  1395. }
  1396. }
  1397. // </editor-fold>
  1398. // <editor-fold defaultstate="collapsed" desc="Ignore lists">
  1399. /**
  1400. * Retrieves this server's ignore list.
  1401. *
  1402. * @return This server's ignore list
  1403. */
  1404. public IgnoreList getIgnoreList() {
  1405. return ignoreList;
  1406. }
  1407. /**
  1408. * Updates this server's ignore list to use the entries stored in the
  1409. * config manager.
  1410. */
  1411. public void updateIgnoreList() {
  1412. ignoreList.clear();
  1413. ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist"));
  1414. }
  1415. /**
  1416. * Saves the contents of our ignore list to the network identity.
  1417. */
  1418. public void saveIgnoreList() {
  1419. getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList());
  1420. }
  1421. // </editor-fold>
  1422. // <editor-fold defaultstate="collapsed" desc="Identity handling">
  1423. /**
  1424. * Retrieves the identity for this server.
  1425. *
  1426. * @return This server's identity
  1427. */
  1428. public Identity getServerIdentity() {
  1429. return IdentityManager.getServerConfig(parser.getServerName());
  1430. }
  1431. /**
  1432. * Retrieves the identity for this server's network.
  1433. *
  1434. * @return This server's network identity
  1435. */
  1436. public Identity getNetworkIdentity() {
  1437. return IdentityManager.getNetworkConfig(getNetwork());
  1438. }
  1439. // </editor-fold>
  1440. // <editor-fold defaultstate="collapsed" desc="Invite handling">
  1441. /**
  1442. * Adds an invite listener to this server.
  1443. *
  1444. * @param listener The listener to be added
  1445. */
  1446. public void addInviteListener(final InviteListener listener) {
  1447. synchronized (listeners) {
  1448. listeners.add(InviteListener.class, listener);
  1449. }
  1450. }
  1451. /**
  1452. * Removes an invite listener from this server.
  1453. *
  1454. * @param listener The listener to be removed
  1455. */
  1456. public void removeInviteListener(final InviteListener listener) {
  1457. synchronized (listeners) {
  1458. listeners.remove(InviteListener.class, listener);
  1459. }
  1460. }
  1461. /**
  1462. * Adds an invite to this server, and fires the appropriate listeners.
  1463. *
  1464. * @param invite The invite to be added
  1465. */
  1466. public void addInvite(final Invite invite) {
  1467. synchronized (invites) {
  1468. for (Invite oldInvite : new ArrayList<Invite>(invites)) {
  1469. if (oldInvite.getChannel().equals(invite.getChannel())) {
  1470. removeInvite(oldInvite);
  1471. }
  1472. }
  1473. invites.add(invite);
  1474. synchronized (listeners) {
  1475. for (InviteListener listener : listeners.get(InviteListener.class)) {
  1476. listener.inviteReceived(this, invite);
  1477. }
  1478. }
  1479. }
  1480. }
  1481. /**
  1482. * Attempts to accept the specified invites, and join the corresponding
  1483. * channels.
  1484. *
  1485. * @param invites The invites to process
  1486. * @since 0.6.4
  1487. */
  1488. public void acceptInvites(final Invite ... invites) {
  1489. final ChannelJoinRequest[] requests = new ChannelJoinRequest[invites.length];
  1490. for (int i = 0; i < invites.length; i++) {
  1491. requests[i] = new ChannelJoinRequest(invites[i].getChannel());
  1492. }
  1493. join(requests);
  1494. }
  1495. /**
  1496. * Attempts to accept all active invites for this server, and join the
  1497. * corresponding channels.
  1498. *
  1499. * @since 0.6.4
  1500. */
  1501. public void acceptInvites() {
  1502. synchronized (invites) {
  1503. acceptInvites(invites.toArray(new Invite[invites.size()]));
  1504. }
  1505. }
  1506. /**
  1507. * Removes all invites for the specified channel.
  1508. *
  1509. * @param channel The channel to remove invites for
  1510. */
  1511. public void removeInvites(final String channel) {
  1512. for (Invite invite : new ArrayList<Invite>(invites)) {
  1513. if (invite.getChannel().equals(channel)) {
  1514. removeInvite(invite);
  1515. }
  1516. }
  1517. }
  1518. /**
  1519. * Removes all invites for all channels.
  1520. */
  1521. public void removeInvites() {
  1522. for (Invite invite : new ArrayList<Invite>(invites)) {
  1523. removeInvite(invite);
  1524. }
  1525. }
  1526. /**
  1527. * Removes an invite from this server, and fires the appropriate listeners.
  1528. *
  1529. * @param invite The invite to be removed
  1530. */
  1531. public void removeInvite(final Invite invite) {
  1532. synchronized (invites) {
  1533. invites.remove(invite);
  1534. synchronized (listeners) {
  1535. for (InviteListener listener : listeners.get(InviteListener.class)) {
  1536. listener.inviteExpired(this, invite);
  1537. }
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Retusnt the list of invites for this server.
  1543. *
  1544. * @return Invite list
  1545. */
  1546. public List<Invite> getInvites() {
  1547. return invites;
  1548. }
  1549. // </editor-fold>
  1550. // <editor-fold defaultstate="collapsed" desc="Away state handling">
  1551. /**
  1552. * Adds an away state lisener to this server.
  1553. *
  1554. * @param listener The listener to be added
  1555. */
  1556. public void addAwayStateListener(final AwayStateListener listener) {
  1557. synchronized (listeners) {
  1558. listeners.add(AwayStateListener.class, listener);
  1559. }
  1560. }
  1561. /**
  1562. * Removes an away state lisener from this server.
  1563. *
  1564. * @param listener The listener to be removed
  1565. */
  1566. public void removeAwayStateListener(final AwayStateListener listener) {
  1567. synchronized (listeners) {
  1568. listeners.remove(AwayStateListener.class, listener);
  1569. }
  1570. }
  1571. /**
  1572. * Updates our away state and fires the relevant listeners.
  1573. *
  1574. * @param message The away message to use, or null if we're not away.
  1575. */
  1576. public void updateAwayState(final String message) {
  1577. if ((awayMessage != null && awayMessage.equals(message))
  1578. || (awayMessage == null && message == null)) {
  1579. return;
  1580. }
  1581. awayMessage = message;
  1582. new Thread(new Runnable() {
  1583. /** {@inheritDoc} */
  1584. @Override
  1585. public void run() {
  1586. synchronized (listeners) {
  1587. if (message == null) {
  1588. for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
  1589. listener.onBack();
  1590. }
  1591. } else {
  1592. for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
  1593. listener.onAway(message);
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }, "Away state listener runner").start();
  1599. }
  1600. // </editor-fold>
  1601. }