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.

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