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

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