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

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