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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  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.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.ParserError;
  41. import com.dmdirc.parser.interfaces.ChannelInfo;
  42. import com.dmdirc.parser.interfaces.ClientInfo;
  43. import com.dmdirc.parser.interfaces.Parser;
  44. import com.dmdirc.parser.interfaces.SecureParser;
  45. import com.dmdirc.parser.interfaces.StringConverter;
  46. import com.dmdirc.parser.common.MyInfo;
  47. import com.dmdirc.parser.interfaces.ProtocolDescription;
  48. import com.dmdirc.ui.WindowManager;
  49. import com.dmdirc.ui.input.TabCompleter;
  50. import com.dmdirc.ui.input.TabCompletionType;
  51. import com.dmdirc.ui.interfaces.ServerWindow;
  52. import com.dmdirc.ui.interfaces.Window;
  53. import com.dmdirc.ui.messages.Formatter;
  54. import java.net.URI;
  55. import java.util.ArrayList;
  56. import java.util.Collection;
  57. import java.util.Collections;
  58. import java.util.HashMap;
  59. import java.util.HashSet;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Random;
  63. import java.util.Set;
  64. import java.util.Timer;
  65. import java.util.TimerTask;
  66. import java.util.concurrent.locks.ReadWriteLock;
  67. import java.util.concurrent.locks.ReentrantReadWriteLock;
  68. import javax.net.ssl.TrustManager;
  69. /**
  70. * The Server class represents the client's view of a server. It maintains
  71. * a list of all channels, queries, etc, and handles parser callbacks pertaining
  72. * to the server.
  73. *
  74. * @author chris
  75. */
  76. public class Server extends WritableFrameContainer<ServerWindow> implements ConfigChangeListener {
  77. // <editor-fold defaultstate="collapsed" desc="Properties">
  78. // <editor-fold defaultstate="collapsed" desc="Static">
  79. /** The name of the general domain. */
  80. private static final String DOMAIN_GENERAL = "general".intern();
  81. /** The name of the profile domain. */
  82. private static final String DOMAIN_PROFILE = "profile".intern();
  83. /** The name of the server domain. */
  84. private static final String DOMAIN_SERVER = "server".intern();
  85. // </editor-fold>
  86. // <editor-fold defaultstate="collapsed" desc="Instance">
  87. /** Open channels that currently exist on the server. */
  88. private final Map<String, Channel> channels = new HashMap<String, Channel>();
  89. /** Open query windows on the server. */
  90. private final Map<String, Query> queries = new HashMap<String, Query>();
  91. /** The Parser instance handling this server. */
  92. private transient Parser parser;
  93. /** The Parser instance that used to be handling this server. */
  94. private transient Parser oldParser;
  95. /** The parser-supplied protocol description object. */
  96. private ProtocolDescription protocolDescription;
  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 ReadWriteLock parserLock = new ReentrantReadWriteLock();
  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 address of the server we're connecting to. */
  112. private URI address;
  113. /** The profile we're using. */
  114. private transient Identity profile;
  115. /** Object used to synchronise access to myState. */
  116. private final Object myStateLock = new Object();
  117. /** The current state of this server. */
  118. private final ServerStatus myState = new ServerStatus(this, myStateLock);
  119. /** The timer we're using to delay reconnects. */
  120. private Timer reconnectTimer;
  121. /** The tabcompleter used for this server. */
  122. private final TabCompleter tabCompleter = new TabCompleter();
  123. /** The last activated internal frame for this server. */
  124. private FrameContainer<?> activeFrame = this;
  125. /** Our reason for being away, if any. */
  126. private String awayMessage;
  127. /** Our event handler. */
  128. private final ServerEventHandler eventHandler = new ServerEventHandler(this);
  129. /** A list of outstanding invites. */
  130. private final List<Invite> invites = new ArrayList<Invite>();
  131. /** A set of channels we want to join without focusing. */
  132. private final Set<String> backgroundChannels = new HashSet<String>();
  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.3
  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(), uri.getHost(),
  150. ServerWindow.class,
  151. new ConfigManager(uri.getScheme(), "", "", uri.getHost()),
  152. new ServerCommandParser());
  153. this.address = uri;
  154. this.protocolDescription = new ParserFactory().getDescription(address);
  155. this.profile = profile;
  156. ServerManager.getServerManager().registerServer(this);
  157. WindowManager.addWindow(this);
  158. tabCompleter.addEntries(TabCompletionType.COMMAND,
  159. AliasWrapper.getAliasWrapper().getAliases());
  160. tabCompleter.addEntries(TabCompletionType.COMMAND,
  161. CommandManager.getCommandNames(CommandType.TYPE_SERVER));
  162. tabCompleter.addEntries(TabCompletionType.COMMAND,
  163. CommandManager.getCommandNames(CommandType.TYPE_GLOBAL));
  164. updateIcon();
  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.3
  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. myStateLock.wait();
  218. } catch (InterruptedException ex) {
  219. return;
  220. }
  221. }
  222. break;
  223. default:
  224. // Do nothing
  225. break;
  226. }
  227. final URI connectAddress;
  228. try {
  229. parserLock.writeLock().lock();
  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.getScheme(), "", "", address.getHost());
  235. this.address = address;
  236. this.protocolDescription = new ParserFactory().getDescription(address);
  237. this.profile = profile;
  238. updateTitle();
  239. updateIcon();
  240. parser = buildParser();
  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. } finally {
  251. parserLock.writeLock().unlock();
  252. }
  253. addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
  254. myState.transition(ServerState.CONNECTING);
  255. doCallbacks();
  256. updateAwayState(null);
  257. removeInvites();
  258. try {
  259. parserThread = new Thread(parser, "IRC Parser thread");
  260. parserThread.start();
  261. } catch (IllegalThreadStateException ex) {
  262. Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
  263. }
  264. }
  265. ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
  266. }
  267. /**
  268. * Reconnects to the IRC 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 IRC 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. * Builds an appropriately configured {@link Parser} for this server.
  608. *
  609. * @return A configured IRC parser.
  610. */
  611. private Parser buildParser() {
  612. final CertificateManager certManager = new CertificateManager(address.getHost(),
  613. getConfigManager());
  614. final MyInfo myInfo = buildMyInfo();
  615. final Parser myParser = new ParserFactory().getParser(myInfo, address);
  616. if (myParser instanceof SecureParser) {
  617. final SecureParser secureParser = (SecureParser) myParser;
  618. secureParser.setTrustManagers(new TrustManager[]{certManager});
  619. secureParser.setKeyManagers(certManager.getKeyManager());
  620. }
  621. if (myParser != null) {
  622. myParser.setIgnoreList(ignoreList);
  623. myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER,
  624. "pingtimer"));
  625. myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER,
  626. "pingfrequency") / myParser.getPingTimerInterval()));
  627. if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) {
  628. myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip"));
  629. }
  630. }
  631. return myParser;
  632. }
  633. /**
  634. * Compare the given URI to the URI we are currently using to see if they
  635. * would both result in the server connecting to the same place, even if the
  636. * URIs do not match exactly.
  637. *
  638. * @param uri URI to compare with the Servers own URI.
  639. * @return True if the Given URI is the "same" as the one we are using.
  640. * @since 0.6.3
  641. */
  642. public boolean compareURI(final URI uri) {
  643. if (parser != null) {
  644. return parser.compareURI(uri);
  645. }
  646. if (oldParser != null) {
  647. return oldParser.compareURI(uri);
  648. }
  649. return false;
  650. }
  651. /**
  652. * Parses the specified hostmask in a manner prescribed by the protocol
  653. * currently used by this server.
  654. *
  655. * @see ProtocolDescription#parseHostmask(java.lang.String)
  656. * @param hostmask The hostmask to be parsed
  657. * @return An array containing the nickname, username and hostname
  658. * @since 0.6.4
  659. */
  660. public String[] parseHostmask(final String hostmask) {
  661. return protocolDescription.parseHostmask(hostmask);
  662. }
  663. /**
  664. * Retrieves the MyInfo object used for the IRC Parser.
  665. *
  666. * @return The MyInfo object for our profile
  667. */
  668. @Precondition({
  669. "The current profile is not null",
  670. "The current profile specifies at least one nickname"
  671. })
  672. private MyInfo buildMyInfo() {
  673. Logger.assertTrue(profile != null);
  674. Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty());
  675. final MyInfo myInfo = new MyInfo();
  676. myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0));
  677. myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname"));
  678. if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) {
  679. myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident"));
  680. }
  681. return myInfo;
  682. }
  683. /**
  684. * Updates this server's icon.
  685. */
  686. private void updateIcon() {
  687. final String icon = myState.getState() == ServerState.CONNECTED
  688. ? address.getScheme().endsWith("s") ? "secure-server" : "server"
  689. : "server-disconnected";
  690. setIcon(icon);
  691. }
  692. /**
  693. * Registers callbacks.
  694. */
  695. private void doCallbacks() {
  696. if (raw != null) {
  697. raw.registerCallbacks();
  698. }
  699. eventHandler.registerCallbacks();
  700. for (Query query : queries.values()) {
  701. query.reregister();
  702. }
  703. }
  704. /**
  705. * Joins the specified channel with the specified key.
  706. *
  707. * @since 0.6.3m1
  708. * @param channel The channel to be joined
  709. * @param key The key for the channel
  710. * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])}
  711. */
  712. @Deprecated
  713. public void join(final String channel, final String key) {
  714. join(new ChannelJoinRequest(channel, key));
  715. }
  716. /**
  717. * Attempts to join the specified channels. If channels with the same name
  718. * already exist, they are (re)joined and their windows activated.
  719. *
  720. * @param requests The channel join requests to process
  721. * @since 0.6.4
  722. */
  723. public void join(final ChannelJoinRequest ... requests) {
  724. join(true, requests);
  725. }
  726. /**
  727. * Attempts to join the specified channels. If channels with the same name
  728. * already exist, they are (re)joined and their windows activated.
  729. *
  730. * @param focus Whether or not to focus any new channels
  731. * @param requests The channel join requests to process
  732. * @since 0.6.4
  733. */
  734. public void join(final boolean focus, final ChannelJoinRequest ... requests) {
  735. synchronized (myStateLock) {
  736. if (myState.getState() == ServerState.CONNECTED) {
  737. final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>();
  738. for (ChannelJoinRequest request : requests) {
  739. removeInvites(request.getName());
  740. final String name;
  741. if (parser.isValidChannelName(request.getName())) {
  742. name = request.getName();
  743. } else {
  744. name = parser.getChannelPrefixes().substring(0, 1)
  745. + request.getName();
  746. }
  747. if (hasChannel(name) && focus) {
  748. getChannel(name).activateFrame();
  749. }
  750. if (!hasChannel(name) || !getChannel(name).isOnChannel()) {
  751. if (!focus) {
  752. backgroundChannels.add(name);
  753. }
  754. pending.add(request);
  755. }
  756. }
  757. parser.joinChannels(pending.toArray(new ChannelJoinRequest[0]));
  758. } else {
  759. // TODO: Need to pass key
  760. // TODO (uris): address.getChannels().add(channel);
  761. }
  762. }
  763. }
  764. /**
  765. * Joins the specified channel, or adds it to the auto-join list if the
  766. * server is not connected.
  767. *
  768. * @param channel The channel to be joined
  769. * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])}
  770. */
  771. @Deprecated
  772. public void join(final String channel) {
  773. join(new ChannelJoinRequest(channel));
  774. }
  775. /** {@inheritDoc} */
  776. @Override
  777. public void sendLine(final String line) {
  778. synchronized (myStateLock) {
  779. try {
  780. parserLock.readLock().lock();
  781. if (parser != null && !line.isEmpty()
  782. && myState.getState() == ServerState.CONNECTED) {
  783. parser.sendRawMessage(getTranscoder().encode(line));
  784. }
  785. } finally {
  786. parserLock.readLock().unlock();
  787. }
  788. }
  789. }
  790. /** {@inheritDoc} */
  791. @Override
  792. public int getMaxLineLength() {
  793. try {
  794. parserLock.readLock().lock();
  795. return parser == null ? -1 : parser.getMaxLength();
  796. } finally {
  797. parserLock.readLock().unlock();
  798. }
  799. }
  800. /**
  801. * Retrieves the parser used for this connection.
  802. *
  803. * @return IRCParser this connection's parser
  804. */
  805. public Parser getParser() {
  806. return parser;
  807. }
  808. /**
  809. * Retrieves the profile that's in use for this server.
  810. *
  811. * @return The profile in use by this server
  812. */
  813. public Identity getProfile() {
  814. return profile;
  815. }
  816. /**
  817. * Retrieves the possible channel prefixes in use on this server.
  818. *
  819. * @return This server's possible channel prefixes
  820. */
  821. public String getChannelPrefixes() {
  822. try {
  823. parserLock.readLock().lock();
  824. return parser == null ? "#&" : parser.getChannelPrefixes();
  825. } finally {
  826. parserLock.readLock().unlock();
  827. }
  828. }
  829. /**
  830. * Retrieves the address of this server.
  831. *
  832. * @return This sever's address
  833. */
  834. public String getAddress() {
  835. try {
  836. parserLock.readLock().lock();
  837. return parser == null ? address.getHost() : parser.getServerName();
  838. } finally {
  839. parserLock.readLock().unlock();
  840. }
  841. }
  842. /**
  843. * Retrieves the name of this server's network. The network name is
  844. * determined using the following rules:
  845. *
  846. * 1. If the server includes its network name in the 005 information, we
  847. * use that
  848. * 2. If the server's name ends in biz, com, info, net or org, we use the
  849. * second level domain (e.g., foo.com)
  850. * 3. If the server's name contains more than two dots, we drop everything
  851. * up to and including the first part, and use the remainder
  852. * 4. In all other cases, we use the full server name
  853. *
  854. * @return The name of this server's network
  855. */
  856. public String getNetwork() {
  857. try {
  858. parserLock.readLock().lock();
  859. if (parser == null) {
  860. throw new IllegalStateException("getNetwork called when "
  861. + "parser is null (state: " + getState() + ")");
  862. } else if (parser.getNetworkName().isEmpty()) {
  863. return getNetworkFromServerName(parser.getServerName());
  864. } else {
  865. return parser.getNetworkName();
  866. }
  867. } finally {
  868. parserLock.readLock().unlock();
  869. }
  870. }
  871. /**
  872. * Determines whether this server is currently connected to the specified
  873. * network.
  874. *
  875. * @param target The network to check for
  876. * @return True if this server is connected to the network, false otherwise
  877. * @since 0.6.3m1rc3
  878. */
  879. public boolean isNetwork(String target) {
  880. synchronized (myStateLock) {
  881. try {
  882. parserLock.readLock().lock();
  883. if (parser == null) {
  884. return false;
  885. } else {
  886. return getNetwork().equalsIgnoreCase(target);
  887. }
  888. } finally {
  889. parserLock.readLock().unlock();
  890. }
  891. }
  892. }
  893. /**
  894. * Calculates a network name from the specified server name. This method
  895. * implements parts 2-4 of the procedure documented at getNetwork().
  896. *
  897. * @param serverName The server name to parse
  898. * @return A network name for the specified server
  899. */
  900. protected static String getNetworkFromServerName(final String serverName) {
  901. final String[] parts = serverName.split("\\.");
  902. final String[] tlds = {"biz", "com", "info", "net", "org"};
  903. boolean isTLD = false;
  904. for (String tld : tlds) {
  905. if (serverName.endsWith("." + tld)) {
  906. isTLD = true;
  907. }
  908. }
  909. if (isTLD && parts.length > 2) {
  910. return parts[parts.length - 2] + "." + parts[parts.length - 1];
  911. } else if (parts.length > 2) {
  912. final StringBuilder network = new StringBuilder();
  913. for (int i = 1; i < parts.length; i++) {
  914. if (network.length() > 0) {
  915. network.append('.');
  916. }
  917. network.append(parts[i]);
  918. }
  919. return network.toString();
  920. } else {
  921. return serverName;
  922. }
  923. }
  924. /**
  925. * Retrieves the name of this server's IRCd.
  926. *
  927. * @return The name of this server's IRCd
  928. */
  929. public String getIrcd() {
  930. return parser.getServerSoftwareType();
  931. }
  932. /**
  933. * Retrieves the protocol used by this server.
  934. *
  935. * @return This server's protocol
  936. * @since 0.6.3
  937. */
  938. public String getProtocol() {
  939. return address.getScheme();
  940. }
  941. /**
  942. * Returns the current away status.
  943. *
  944. * @return True if the client is marked as away, false otherwise
  945. */
  946. public boolean isAway() {
  947. return awayMessage != null;
  948. }
  949. /**
  950. * Gets the current away message.
  951. *
  952. * @return Null if the client isn't away, or a textual away message if it is
  953. */
  954. public String getAwayMessage() {
  955. return awayMessage;
  956. }
  957. /** {@inheritDoc} */
  958. @Override
  959. public TabCompleter getTabCompleter() {
  960. return tabCompleter;
  961. }
  962. /**
  963. * Retrieves the current state for this server.
  964. *
  965. * @return This server's state
  966. */
  967. public ServerState getState() {
  968. return myState.getState();
  969. }
  970. /**
  971. * Retrieves the status object for this server. Effecting state transitions
  972. * on the object returned by this method will almost certainly cause
  973. * problems.
  974. *
  975. * @since 0.6.3m1
  976. * @return This server's status object.
  977. */
  978. public ServerStatus getStatus() {
  979. return myState;
  980. }
  981. /** {@inheritDoc} */
  982. @Override
  983. public void windowClosing() {
  984. synchronized (myStateLock) {
  985. // 1: Make the window non-visible
  986. for (Window window : getWindows()) {
  987. window.setVisible(false);
  988. }
  989. // 2: Remove any callbacks or listeners
  990. eventHandler.unregisterCallbacks();
  991. // 3: Trigger any actions neccessary
  992. disconnect();
  993. myState.transition(ServerState.CLOSING);
  994. }
  995. closeChannels();
  996. closeQueries();
  997. removeInvites();
  998. if (raw != null) {
  999. raw.close();
  1000. }
  1001. // 4: Trigger action for the window closing
  1002. // 5: Inform any parents that the window is closing
  1003. ServerManager.getServerManager().unregisterServer(this);
  1004. // 6: Remove the window from the window manager
  1005. WindowManager.removeWindow(this);
  1006. }
  1007. /** {@inheritDoc} */
  1008. @Override
  1009. public void windowClosed() {
  1010. // 7: Remove any references to the window and parents
  1011. oldParser = null; //NOPMD
  1012. parser = null; //NOPMD
  1013. }
  1014. /**
  1015. * Passes the arguments to the most recently activated frame for this
  1016. * server. If the frame isn't know, or isn't visible, use this frame
  1017. * instead.
  1018. *
  1019. * @param messageType The type of message to send
  1020. * @param args The arguments for the message
  1021. */
  1022. public void addLineToActive(final String messageType, final Object... args) {
  1023. if (activeFrame == null || !activeFrame.getFrame().isVisible()) {
  1024. activeFrame = this;
  1025. }
  1026. activeFrame.addLine(messageType, args);
  1027. }
  1028. /**
  1029. * Passes the arguments to all frames for this server.
  1030. *
  1031. * @param messageType The type of message to send
  1032. * @param args The arguments of the message
  1033. */
  1034. public void addLineToAll(final String messageType, final Object... args) {
  1035. for (Channel channel : channels.values()) {
  1036. channel.addLine(messageType, args);
  1037. }
  1038. for (Query query : queries.values()) {
  1039. query.addLine(messageType, args);
  1040. }
  1041. addLine(messageType, args);
  1042. }
  1043. /**
  1044. * Replies to an incoming CTCP message.
  1045. *
  1046. * @param source The source of the message
  1047. * @param type The CTCP type
  1048. * @param args The CTCP arguments
  1049. */
  1050. public void sendCTCPReply(final String source, final String type, final String args) {
  1051. if (type.equalsIgnoreCase("VERSION")) {
  1052. parser.sendCTCPReply(source, "VERSION", "DMDirc " +
  1053. getConfigManager().getOption("version", "version")
  1054. + " - http://www.dmdirc.com/");
  1055. } else if (type.equalsIgnoreCase("PING")) {
  1056. parser.sendCTCPReply(source, "PING", args);
  1057. } else if (type.equalsIgnoreCase("CLIENTINFO")) {
  1058. parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
  1059. }
  1060. }
  1061. /**
  1062. * Determines if the specified channel name is valid. A channel name is
  1063. * valid if we already have an existing Channel with the same name, or
  1064. * we have a valid parser instance and the parser says it's valid.
  1065. *
  1066. * @param channelName The name of the channel to test
  1067. * @return True if the channel name is valid, false otherwise
  1068. */
  1069. public boolean isValidChannelName(final String channelName) {
  1070. try {
  1071. parserLock.readLock().lock();
  1072. return hasChannel(channelName)
  1073. || (parser != null && parser.isValidChannelName(channelName));
  1074. } finally {
  1075. parserLock.readLock().unlock();
  1076. }
  1077. }
  1078. /**
  1079. * Returns the server instance associated with this frame.
  1080. *
  1081. * @return the associated server connection
  1082. */
  1083. @Override
  1084. public Server getServer() {
  1085. return this;
  1086. }
  1087. /** {@inheritDoc} */
  1088. @Override
  1089. protected boolean processNotificationArg(final Object arg, final List<Object> args) {
  1090. if (arg instanceof ClientInfo) {
  1091. final ClientInfo clientInfo = (ClientInfo) arg;
  1092. args.add(clientInfo.getNickname());
  1093. args.add(clientInfo.getUsername());
  1094. args.add(clientInfo.getHostname());
  1095. return true;
  1096. } else {
  1097. return super.processNotificationArg(arg, args);
  1098. }
  1099. }
  1100. /**
  1101. * Updates the name and title of this window.
  1102. */
  1103. public void updateTitle() {
  1104. synchronized (myStateLock) {
  1105. if (myState.getState() == ServerState.CLOSING) {
  1106. return;
  1107. }
  1108. try {
  1109. parserLock.readLock().lock();
  1110. final Object[] arguments = new Object[]{
  1111. address.getHost(), parser == null ? "Unknown" : parser.getServerName(),
  1112. address.getPort(), parser == null ? "Unknown" : getNetwork(),
  1113. parser == null ? "Unknown" : parser.getLocalClient().getNickname()
  1114. };
  1115. setName(Formatter.formatMessage(getConfigManager(),
  1116. "serverName", arguments));
  1117. setTitle(Formatter.formatMessage(getConfigManager(),
  1118. "serverTitle", arguments));
  1119. } finally {
  1120. parserLock.readLock().unlock();
  1121. }
  1122. }
  1123. }
  1124. /** {@inheritDoc} */
  1125. @Override
  1126. public void configChanged(final String domain, final String key) {
  1127. if ("formatter".equals(domain)) {
  1128. updateTitle();
  1129. }
  1130. }
  1131. // </editor-fold>
  1132. // <editor-fold defaultstate="collapsed" desc="Parser callbacks">
  1133. /**
  1134. * Called when the server says that the nickname we're trying to use is
  1135. * already in use.
  1136. *
  1137. * @param nickname The nickname that we were trying to use
  1138. */
  1139. public void onNickInUse(final String nickname) {
  1140. final String lastNick = parser.getLocalClient().getNickname();
  1141. // If our last nick is still valid, ignore the in use message
  1142. if (!converter.equalsIgnoreCase(lastNick, nickname)) {
  1143. return;
  1144. }
  1145. String newNick = lastNick + new Random().nextInt(10);
  1146. final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames");
  1147. int offset = 0;
  1148. // Loop so we can check case sensitivity
  1149. for (String alt : alts) {
  1150. offset++;
  1151. if (converter.equalsIgnoreCase(alt, lastNick)) {
  1152. break;
  1153. }
  1154. }
  1155. if (offset < alts.size() && !alts.get(offset).isEmpty()) {
  1156. newNick = alts.get(offset);
  1157. }
  1158. parser.getLocalClient().setNickname(newNick);
  1159. }
  1160. /**
  1161. * Called when the server sends a numeric event.
  1162. *
  1163. * @param numeric The numeric code for the event
  1164. * @param tokens The (tokenised) arguments of the event
  1165. */
  1166. public void onNumeric(final int numeric, final String[] tokens) {
  1167. String snumeric = String.valueOf(numeric);
  1168. if (numeric < 10) {
  1169. snumeric = "00" + snumeric;
  1170. } else if (numeric < 100) {
  1171. snumeric = "0" + snumeric;
  1172. }
  1173. final String sansIrcd = "numeric_" + snumeric;
  1174. StringBuffer target = new StringBuffer("");
  1175. if (getConfigManager().hasOptionString("formatter", sansIrcd)) {
  1176. target = new StringBuffer(sansIrcd);
  1177. } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) {
  1178. target = new StringBuffer("numeric_unknown");
  1179. }
  1180. ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this,
  1181. Integer.valueOf(numeric), tokens);
  1182. handleNotification(target.toString(), (Object[]) tokens);
  1183. }
  1184. /**
  1185. * Called when the socket has been closed.
  1186. */
  1187. public void onSocketClosed() {
  1188. if (Thread.holdsLock(myStateLock)) {
  1189. new Thread(new Runnable() {
  1190. /** {@inheritDoc} */
  1191. @Override
  1192. public void run() {
  1193. onSocketClosed();
  1194. }
  1195. }, "Socket closed deferred thread").start();
  1196. return;
  1197. }
  1198. handleNotification("socketClosed", getAddress());
  1199. ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this);
  1200. eventHandler.unregisterCallbacks();
  1201. synchronized (myStateLock) {
  1202. if (myState.getState() == ServerState.CLOSING
  1203. || myState.getState() == ServerState.DISCONNECTED) {
  1204. // This has been triggered via .disconect()
  1205. return;
  1206. }
  1207. if (myState.getState() == ServerState.DISCONNECTING) {
  1208. myState.transition(ServerState.DISCONNECTED);
  1209. } else {
  1210. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  1211. }
  1212. clearChannels();
  1213. try {
  1214. parserLock.writeLock().lock();
  1215. oldParser = parser;
  1216. parser = null;
  1217. } finally {
  1218. parserLock.writeLock().unlock();
  1219. }
  1220. updateIcon();
  1221. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1222. "closechannelsondisconnect")) {
  1223. closeChannels();
  1224. }
  1225. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1226. "closequeriesondisconnect")) {
  1227. closeQueries();
  1228. }
  1229. removeInvites();
  1230. updateAwayState(null);
  1231. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1232. "reconnectondisconnect")
  1233. && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) {
  1234. doDelayedReconnect();
  1235. }
  1236. }
  1237. }
  1238. /**
  1239. * Called when an error was encountered while connecting.
  1240. *
  1241. * @param errorInfo The parser's error information
  1242. */
  1243. @Precondition("The current server state is CONNECTING")
  1244. public void onConnectError(final ParserError errorInfo) {
  1245. synchronized (myStateLock) {
  1246. if (myState.getState() == ServerState.CLOSING
  1247. || myState.getState() == ServerState.DISCONNECTING) {
  1248. // Do nothing
  1249. return;
  1250. } else if (myState.getState() != ServerState.CONNECTING) {
  1251. // Shouldn't happen
  1252. throw new IllegalStateException("Connect error when not "
  1253. + "connecting\n\n" + getStatus().getTransitionHistory());
  1254. }
  1255. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  1256. try {
  1257. parserLock.writeLock().lock();
  1258. oldParser = parser;
  1259. parser = null;
  1260. } finally {
  1261. parserLock.writeLock().unlock();
  1262. }
  1263. updateIcon();
  1264. String description;
  1265. if (errorInfo.getException() == null) {
  1266. description = errorInfo.getData();
  1267. } else {
  1268. final Exception exception = errorInfo.getException();
  1269. if (exception instanceof java.net.UnknownHostException) {
  1270. description = "Unknown host (unable to resolve)";
  1271. } else if (exception instanceof java.net.NoRouteToHostException) {
  1272. description = "No route to host";
  1273. } else if (exception instanceof java.net.SocketTimeoutException) {
  1274. description = "Connection attempt timed out";
  1275. } else if (exception instanceof java.net.SocketException
  1276. || exception instanceof javax.net.ssl.SSLException) {
  1277. description = exception.getMessage();
  1278. } else {
  1279. Logger.appError(ErrorLevel.LOW, "Unknown socket error",
  1280. new IllegalArgumentException(exception));
  1281. description = "Unknown error: " + exception.getMessage();
  1282. }
  1283. }
  1284. ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null,
  1285. this, description);
  1286. handleNotification("connectError", getAddress(), description);
  1287. if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
  1288. "reconnectonconnectfailure")) {
  1289. doDelayedReconnect();
  1290. }
  1291. }
  1292. }
  1293. /**
  1294. * Called when we fail to receive a ping reply within a set period of time.
  1295. */
  1296. public void onPingFailed() {
  1297. Main.getUI().getStatusBar().setMessage("No ping reply from "
  1298. + getName() + " for over "
  1299. + ((int) (Math.floor(parser.getPingTime() / 1000.0)))
  1300. + " seconds.", null, 10);
  1301. ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this,
  1302. Long.valueOf(parser.getPingTime()));
  1303. if (parser.getPingTime()
  1304. >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) {
  1305. handleNotification("stonedServer", getAddress());
  1306. reconnect();
  1307. }
  1308. }
  1309. /**
  1310. * Called after the parser receives the 005 headers from the server.
  1311. */
  1312. @Precondition("State is CONNECTING")
  1313. public void onPost005() {
  1314. synchronized (myStateLock) {
  1315. if (myState.getState() != ServerState.CONNECTING) {
  1316. // Shouldn't happen
  1317. throw new IllegalStateException("Received onPost005 while not "
  1318. + "connecting\n\n" + myState.getTransitionHistory());
  1319. }
  1320. if (myState.getState() != ServerState.CONNECTING) {
  1321. // We've transitioned while waiting for the lock. Just abort.
  1322. return;
  1323. }
  1324. myState.transition(ServerState.CONNECTED);
  1325. getConfigManager().migrate(address.getScheme(),
  1326. parser.getServerSoftwareType(), getNetwork(), parser.getServerName());
  1327. updateIcon();
  1328. updateTitle();
  1329. updateIgnoreList();
  1330. converter = parser.getStringConverter();
  1331. final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>();
  1332. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) {
  1333. for (Channel chan : channels.values()) {
  1334. requests.add(new ChannelJoinRequest(chan.getName()));
  1335. }
  1336. }
  1337. join(requests.toArray(new ChannelJoinRequest[0]));
  1338. checkModeAliases();
  1339. }
  1340. ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this);
  1341. }
  1342. /**
  1343. * Checks that we have the neccessary mode aliases for this server.
  1344. */
  1345. private void checkModeAliases() {
  1346. // Check we have mode aliases
  1347. final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes()
  1348. + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes();
  1349. final String umodes = parser.getUserModes();
  1350. final StringBuffer missingModes = new StringBuffer();
  1351. final StringBuffer missingUmodes = new StringBuffer();
  1352. for (char mode : modes.toCharArray()) {
  1353. if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) {
  1354. missingModes.append(mode);
  1355. }
  1356. }
  1357. for (char mode : umodes.toCharArray()) {
  1358. if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) {
  1359. missingUmodes.append(mode);
  1360. }
  1361. }
  1362. if (missingModes.length() + missingUmodes.length() > 0) {
  1363. final StringBuffer missing = new StringBuffer("Missing mode aliases: ");
  1364. if (missingModes.length() > 0) {
  1365. missing.append("channel: +");
  1366. missing.append(missingModes);
  1367. }
  1368. if (missingUmodes.length() > 0) {
  1369. if (missingModes.length() > 0) {
  1370. missing.append(' ');
  1371. }
  1372. missing.append("user: +");
  1373. missing.append(missingUmodes);
  1374. }
  1375. Logger.appError(ErrorLevel.LOW, missing.toString() + " ["
  1376. + parser.getServerSoftwareType() + "]",
  1377. new Exception(missing.toString() + "\n" // NOPMD
  1378. + "Network: " + getNetwork() + "\n"
  1379. + "IRCd: " + parser.getServerSoftware()
  1380. + " (" + parser.getServerSoftwareType() + ")\n"
  1381. + "Mode alias version: "
  1382. + getConfigManager().getOption("identity", "modealiasversion")
  1383. + "\n\n"));
  1384. }
  1385. }
  1386. // </editor-fold>
  1387. // <editor-fold defaultstate="collapsed" desc="Ignore lists">
  1388. /**
  1389. * Retrieves this server's ignore list.
  1390. *
  1391. * @return This server's ignore list
  1392. */
  1393. public IgnoreList getIgnoreList() {
  1394. return ignoreList;
  1395. }
  1396. /**
  1397. * Updates this server's ignore list to use the entries stored in the
  1398. * config manager.
  1399. */
  1400. public void updateIgnoreList() {
  1401. ignoreList.clear();
  1402. ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist"));
  1403. }
  1404. /**
  1405. * Saves the contents of our ignore list to the network identity.
  1406. */
  1407. public void saveIgnoreList() {
  1408. getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList());
  1409. }
  1410. // </editor-fold>
  1411. // <editor-fold defaultstate="collapsed" desc="Identity handling">
  1412. /**
  1413. * Retrieves the identity for this server.
  1414. *
  1415. * @return This server's identity
  1416. */
  1417. public Identity getServerIdentity() {
  1418. return IdentityManager.getServerConfig(parser.getServerName());
  1419. }
  1420. /**
  1421. * Retrieves the identity for this server's network.
  1422. *
  1423. * @return This server's network identity
  1424. */
  1425. public Identity getNetworkIdentity() {
  1426. return IdentityManager.getNetworkConfig(getNetwork());
  1427. }
  1428. // </editor-fold>
  1429. // <editor-fold defaultstate="collapsed" desc="Invite handling">
  1430. /**
  1431. * Adds an invite listener to this server.
  1432. *
  1433. * @param listener The listener to be added
  1434. */
  1435. public void addInviteListener(final InviteListener listener) {
  1436. synchronized (listeners) {
  1437. listeners.add(InviteListener.class, listener);
  1438. }
  1439. }
  1440. /**
  1441. * Removes an invite listener from this server.
  1442. *
  1443. * @param listener The listener to be removed
  1444. */
  1445. public void removeInviteListener(final InviteListener listener) {
  1446. synchronized (listeners) {
  1447. listeners.remove(InviteListener.class, listener);
  1448. }
  1449. }
  1450. /**
  1451. * Adds an invite to this server, and fires the appropriate listeners.
  1452. *
  1453. * @param invite The invite to be added
  1454. */
  1455. public void addInvite(final Invite invite) {
  1456. synchronized (invites) {
  1457. for (Invite oldInvite : new ArrayList<Invite>(invites)) {
  1458. if (oldInvite.getChannel().equals(invite.getChannel())) {
  1459. removeInvite(oldInvite);
  1460. }
  1461. }
  1462. invites.add(invite);
  1463. synchronized (listeners) {
  1464. for (InviteListener listener : listeners.get(InviteListener.class)) {
  1465. listener.inviteReceived(this, invite);
  1466. }
  1467. }
  1468. }
  1469. }
  1470. /**
  1471. * Removes all invites for the specified channel.
  1472. *
  1473. * @param channel The channel to remove invites for
  1474. */
  1475. public void removeInvites(final String channel) {
  1476. for (Invite invite : new ArrayList<Invite>(invites)) {
  1477. if (invite.getChannel().equals(channel)) {
  1478. removeInvite(invite);
  1479. }
  1480. }
  1481. }
  1482. /**
  1483. * Removes all invites for all channels.
  1484. */
  1485. private void removeInvites() {
  1486. for (Invite invite : new ArrayList<Invite>(invites)) {
  1487. removeInvite(invite);
  1488. }
  1489. }
  1490. /**
  1491. * Removes an invite from this server, and fires the appropriate listeners.
  1492. *
  1493. * @param invite The invite to be removed
  1494. */
  1495. public void removeInvite(final Invite invite) {
  1496. synchronized (invites) {
  1497. invites.remove(invite);
  1498. synchronized (listeners) {
  1499. for (InviteListener listener : listeners.get(InviteListener.class)) {
  1500. listener.inviteExpired(this, invite);
  1501. }
  1502. }
  1503. }
  1504. }
  1505. /**
  1506. * Retusnt the list of invites for this server.
  1507. *
  1508. * @return Invite list
  1509. */
  1510. public List<Invite> getInvites() {
  1511. return invites;
  1512. }
  1513. // </editor-fold>
  1514. // <editor-fold defaultstate="collapsed" desc="Away state handling">
  1515. /**
  1516. * Adds an away state lisener to this server.
  1517. *
  1518. * @param listener The listener to be added
  1519. */
  1520. public void addAwayStateListener(final AwayStateListener listener) {
  1521. synchronized (listeners) {
  1522. listeners.add(AwayStateListener.class, listener);
  1523. }
  1524. }
  1525. /**
  1526. * Removes an away state lisener from this server.
  1527. *
  1528. * @param listener The listener to be removed
  1529. */
  1530. public void removeAwayStateListener(final AwayStateListener listener) {
  1531. synchronized (listeners) {
  1532. listeners.remove(AwayStateListener.class, listener);
  1533. }
  1534. }
  1535. /**
  1536. * Updates our away state and fires the relevant listeners.
  1537. *
  1538. * @param message The away message to use, or null if we're not away.
  1539. */
  1540. public void updateAwayState(final String message) {
  1541. if ((awayMessage != null && awayMessage.equals(message))
  1542. || (awayMessage == null && message == null)) {
  1543. return;
  1544. }
  1545. awayMessage = message;
  1546. new Thread(new Runnable() {
  1547. /** {@inheritDoc} */
  1548. @Override
  1549. public void run() {
  1550. synchronized (listeners) {
  1551. if (message == null) {
  1552. for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
  1553. listener.onBack();
  1554. }
  1555. } else {
  1556. for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
  1557. listener.onAway(message);
  1558. }
  1559. }
  1560. }
  1561. }
  1562. }, "Away state listener runner").start();
  1563. }
  1564. // </editor-fold>
  1565. }