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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. /*
  2. * Copyright (c) 2006-2015 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.config.profiles.Profile;
  25. import com.dmdirc.events.ServerConnectErrorEvent;
  26. import com.dmdirc.events.ServerConnectedEvent;
  27. import com.dmdirc.events.ServerConnectingEvent;
  28. import com.dmdirc.events.ServerDisconnectedEvent;
  29. import com.dmdirc.events.ServerReconnectScheduledEvent;
  30. import com.dmdirc.interfaces.Connection;
  31. import com.dmdirc.interfaces.GroupChatManager;
  32. import com.dmdirc.interfaces.InviteManager;
  33. import com.dmdirc.interfaces.User;
  34. import com.dmdirc.interfaces.WindowModel;
  35. import com.dmdirc.interfaces.config.ConfigChangeListener;
  36. import com.dmdirc.interfaces.config.ConfigProvider;
  37. import com.dmdirc.interfaces.config.ConfigProviderMigrator;
  38. import com.dmdirc.interfaces.config.IdentityFactory;
  39. import com.dmdirc.parser.common.DefaultStringConverter;
  40. import com.dmdirc.parser.common.IgnoreList;
  41. import com.dmdirc.parser.common.ParserError;
  42. import com.dmdirc.parser.common.ThreadedParser;
  43. import com.dmdirc.parser.interfaces.ClientInfo;
  44. import com.dmdirc.parser.interfaces.EncodingParser;
  45. import com.dmdirc.parser.interfaces.Parser;
  46. import com.dmdirc.parser.interfaces.ProtocolDescription;
  47. import com.dmdirc.parser.interfaces.SecureParser;
  48. import com.dmdirc.parser.interfaces.StringConverter;
  49. import com.dmdirc.tls.CertificateManager;
  50. import com.dmdirc.ui.core.components.WindowComponent;
  51. import com.dmdirc.ui.input.TabCompleterFactory;
  52. import com.dmdirc.ui.input.TabCompletionType;
  53. import com.dmdirc.ui.messages.BackBufferFactory;
  54. import com.dmdirc.ui.messages.ColourManager;
  55. import com.dmdirc.ui.messages.Formatter;
  56. import com.dmdirc.ui.messages.HighlightManager;
  57. import com.dmdirc.ui.messages.sink.MessageSinkManager;
  58. import java.net.NoRouteToHostException;
  59. import java.net.SocketException;
  60. import java.net.SocketTimeoutException;
  61. import java.net.URI;
  62. import java.net.URISyntaxException;
  63. import java.net.UnknownHostException;
  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.List;
  70. import java.util.Map;
  71. import java.util.Optional;
  72. import java.util.concurrent.ConcurrentSkipListMap;
  73. import java.util.concurrent.ScheduledExecutorService;
  74. import java.util.concurrent.ScheduledFuture;
  75. import java.util.concurrent.TimeUnit;
  76. import java.util.concurrent.locks.ReadWriteLock;
  77. import java.util.concurrent.locks.ReentrantReadWriteLock;
  78. import java.util.function.Function;
  79. import javax.annotation.Nonnull;
  80. import javax.annotation.Nullable;
  81. import javax.net.ssl.SSLException;
  82. import org.slf4j.Logger;
  83. import org.slf4j.LoggerFactory;
  84. import static com.dmdirc.util.LogUtils.APP_ERROR;
  85. import static com.google.common.base.Preconditions.checkNotNull;
  86. /**
  87. * The Server class represents the client's view of a server. It maintains a list of all channels,
  88. * queries, etc, and handles parser callbacks pertaining to the server.
  89. */
  90. public class Server extends FrameContainer implements Connection {
  91. private static final Logger LOG = LoggerFactory.getLogger(Server.class);
  92. /** The name of the general domain. */
  93. private static final String DOMAIN_GENERAL = "general";
  94. /** Manager of group chats. */
  95. private final GroupChatManagerImpl groupChatManager;
  96. /** Manager of invites. */
  97. private final InviteManager inviteManager;
  98. /** Open query windows on the server. */
  99. private final Map<String, Query> queries = new ConcurrentSkipListMap<>();
  100. /** The user manager to retrieve users from. */
  101. private final UserManager userManager;
  102. /** The Parser instance handling this server. */
  103. @Nonnull
  104. private Optional<Parser> parser = Optional.empty();
  105. /** The Parser instance that used to be handling this server. */
  106. @Nonnull
  107. private Optional<Parser> oldParser = Optional.empty();
  108. /** The parser-supplied protocol description object. */
  109. @Nonnull
  110. private Optional<ProtocolDescription> protocolDescription = Optional.empty();
  111. /**
  112. * Object used to synchronise access to parser. This object should be locked by anything
  113. * requiring that the parser reference remains the same for a duration of time, or by anything
  114. * which is updating the parser reference.
  115. *
  116. * If used in conjunction with myStateLock, the parserLock must always be locked INSIDE the
  117. * myStateLock to prevent deadlocks.
  118. */
  119. private final ReadWriteLock parserLock = new ReentrantReadWriteLock();
  120. /** Object used to synchronise access to myState. */
  121. private final Object myStateLock = new Object();
  122. /** The current state of this server. */
  123. private final ServerStatus myState = new ServerStatus(this, myStateLock);
  124. /** The address of the server we're connecting to. */
  125. @Nonnull
  126. private URI address;
  127. /** The profile we're using. */
  128. @Nonnull
  129. private Profile profile;
  130. /** Our reason for being away, if any. */
  131. private Optional<String> awayMessage;
  132. /** Our event handler. */
  133. private final ServerEventHandler eventHandler;
  134. /** Our ignore list. */
  135. private final IgnoreList ignoreList = new IgnoreList();
  136. /** Our string convertor. */
  137. private StringConverter converter = new DefaultStringConverter();
  138. /** ParserFactory we use for creating parsers. */
  139. private final ParserFactory parserFactory;
  140. /** Factory to use to create new identities. */
  141. private final IdentityFactory identityFactory;
  142. /** The migrator to use to change our config provider. */
  143. private final ConfigProviderMigrator configMigrator;
  144. /** Factory to use for creating queries. */
  145. private final QueryFactory queryFactory;
  146. /** The config provider to write user settings to. */
  147. private final ConfigProvider userSettings;
  148. /** Executor service to use to schedule repeated events. */
  149. private final ScheduledExecutorService executorService;
  150. /** The message encoder factory to create a message encoder with. */
  151. private final MessageEncoderFactory messageEncoderFactory;
  152. /** The manager to use for highlighting. */
  153. private final HighlightManager highlightManager;
  154. /** Listener to use for config changes. */
  155. private final ConfigChangeListener configListener = (domain, key) -> updateTitle();
  156. /** The future used when a reconnect timer is scheduled. */
  157. private ScheduledFuture<?> reconnectTimerFuture;
  158. /**
  159. * Creates a new server which will connect to the specified URL with the specified profile.
  160. */
  161. public Server(
  162. final ConfigProviderMigrator configMigrator,
  163. final ParserFactory parserFactory,
  164. final TabCompleterFactory tabCompleterFactory,
  165. final IdentityFactory identityFactory,
  166. final MessageSinkManager messageSinkManager,
  167. final QueryFactory queryFactory,
  168. final DMDircMBassador eventBus,
  169. final MessageEncoderFactory messageEncoderFactory,
  170. final ConfigProvider userSettings,
  171. final GroupChatManagerImplFactory groupChatManagerFactory,
  172. final ScheduledExecutorService executorService,
  173. @Nonnull final URI uri,
  174. @Nonnull final Profile profile,
  175. final BackBufferFactory backBufferFactory,
  176. final UserManager userManager) {
  177. super(null, "server-disconnected",
  178. getHost(uri),
  179. getHost(uri),
  180. configMigrator.getConfigProvider(),
  181. backBufferFactory,
  182. tabCompleterFactory.getTabCompleter(configMigrator.getConfigProvider(),
  183. CommandType.TYPE_SERVER, CommandType.TYPE_GLOBAL),
  184. messageSinkManager,
  185. eventBus,
  186. Arrays.asList(
  187. WindowComponent.TEXTAREA.getIdentifier(),
  188. WindowComponent.INPUTFIELD.getIdentifier(),
  189. WindowComponent.CERTIFICATE_VIEWER.getIdentifier()));
  190. this.parserFactory = parserFactory;
  191. this.identityFactory = identityFactory;
  192. this.configMigrator = configMigrator;
  193. this.queryFactory = queryFactory;
  194. this.executorService = executorService;
  195. this.userSettings = userSettings;
  196. this.messageEncoderFactory = messageEncoderFactory;
  197. this.userManager = userManager;
  198. this.groupChatManager = groupChatManagerFactory.create(this);
  199. this.inviteManager = new InviteManagerImpl(this);
  200. awayMessage = Optional.empty();
  201. eventHandler = new ServerEventHandler(this, groupChatManager, getEventBus());
  202. this.address = uri;
  203. this.profile = profile;
  204. setConnectionDetails(uri, profile);
  205. updateIcon();
  206. getConfigManager().addChangeListener("formatter", "serverName", configListener);
  207. getConfigManager().addChangeListener("formatter", "serverTitle", configListener);
  208. initBackBuffer();
  209. this.highlightManager = new HighlightManager(getConfigManager(),
  210. new ColourManager(getConfigManager()));
  211. highlightManager.init();
  212. getEventBus().subscribe(highlightManager);
  213. }
  214. /**
  215. * Updates the connection details for this server. If the specified URI does not define a port,
  216. * the default port from the protocol description will be used.
  217. *
  218. * @param uri The new URI that this server should connect to
  219. * @param profile The profile that this server should use
  220. */
  221. private void setConnectionDetails(final URI uri, final Profile profile) {
  222. this.address = checkNotNull(uri);
  223. this.protocolDescription = Optional.ofNullable(parserFactory.getDescription(uri));
  224. this.profile = profile;
  225. if (uri.getPort() == -1) {
  226. protocolDescription.ifPresent(pd -> {
  227. try {
  228. this.address = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(),
  229. pd.getDefaultPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
  230. } catch (URISyntaxException ex) {
  231. LOG.warn(APP_ERROR, "Unable to construct URI", ex);
  232. }
  233. });
  234. }
  235. }
  236. @Override
  237. public void connect() {
  238. connect(address, profile);
  239. }
  240. @Override
  241. @Precondition({
  242. "The current parser is null or not connected",
  243. "The specified profile is not null"
  244. })
  245. @SuppressWarnings("fallthrough")
  246. public void connect(final URI address, final Profile profile) {
  247. checkNotNull(address);
  248. checkNotNull(profile);
  249. synchronized (myStateLock) {
  250. LOG.info("Connecting to {}, current state is {}", address, myState.getState());
  251. switch (myState.getState()) {
  252. case RECONNECT_WAIT:
  253. LOG.debug("Cancelling reconnection timer");
  254. if (reconnectTimerFuture != null) {
  255. reconnectTimerFuture.cancel(false);
  256. }
  257. break;
  258. case CLOSING:
  259. // Ignore the connection attempt
  260. return;
  261. case CONNECTED:
  262. case CONNECTING:
  263. disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
  264. case DISCONNECTING:
  265. while (!myState.getState().isDisconnected()) {
  266. try {
  267. myStateLock.wait();
  268. } catch (InterruptedException ex) {
  269. return;
  270. }
  271. }
  272. break;
  273. default:
  274. // Do nothing
  275. break;
  276. }
  277. final URI connectAddress;
  278. final Parser newParser;
  279. try {
  280. parserLock.writeLock().lock();
  281. if (parser.isPresent()) {
  282. throw new IllegalArgumentException("Connection attempt while parser "
  283. + "is still connected.\n\nMy state:" + getState());
  284. }
  285. configMigrator.migrate(address.getScheme(), "", "", address.getHost());
  286. setConnectionDetails(address, profile);
  287. updateTitle();
  288. updateIcon();
  289. parser = Optional.ofNullable(buildParser());
  290. if (!parser.isPresent()) {
  291. addLine("serverUnknownProtocol", address.getScheme());
  292. return;
  293. }
  294. newParser = parser.get();
  295. connectAddress = newParser.getURI();
  296. } finally {
  297. parserLock.writeLock().unlock();
  298. }
  299. addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
  300. myState.transition(ServerState.CONNECTING);
  301. doCallbacks();
  302. updateAwayState(Optional.empty());
  303. inviteManager.removeInvites();
  304. newParser.connect();
  305. if (newParser instanceof ThreadedParser) {
  306. ((ThreadedParser) newParser).getControlThread()
  307. .setName("Parser - " + connectAddress.getHost());
  308. }
  309. }
  310. getEventBus().publish(new ServerConnectingEvent(this));
  311. }
  312. @Override
  313. public void reconnect(final String reason) {
  314. synchronized (myStateLock) {
  315. if (myState.getState() == ServerState.CLOSING) {
  316. return;
  317. }
  318. disconnect(reason);
  319. connect(address, profile);
  320. }
  321. }
  322. @Override
  323. public void reconnect() {
  324. reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage"));
  325. }
  326. @Override
  327. public void disconnect() {
  328. disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
  329. }
  330. @Override
  331. public void disconnect(final String reason) {
  332. synchronized (myStateLock) {
  333. LOG.info("Disconnecting. Current state: {}", myState.getState());
  334. switch (myState.getState()) {
  335. case CLOSING:
  336. case DISCONNECTING:
  337. case DISCONNECTED:
  338. case TRANSIENTLY_DISCONNECTED:
  339. return;
  340. case RECONNECT_WAIT:
  341. LOG.debug("Cancelling reconnection timer");
  342. if (reconnectTimerFuture != null) {
  343. reconnectTimerFuture.cancel(false);
  344. }
  345. break;
  346. default:
  347. break;
  348. }
  349. groupChatManager.handleDisconnect();
  350. try {
  351. parserLock.readLock().lock();
  352. if (parser.isPresent()) {
  353. myState.transition(ServerState.DISCONNECTING);
  354. inviteManager.removeInvites();
  355. updateIcon();
  356. parser.get().disconnect(reason);
  357. } else {
  358. myState.transition(ServerState.DISCONNECTED);
  359. }
  360. } finally {
  361. parserLock.readLock().unlock();
  362. }
  363. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit")) {
  364. closeQueries();
  365. }
  366. }
  367. }
  368. /**
  369. * Schedules a reconnect attempt to be performed after a user-defined delay.
  370. */
  371. @Precondition("The server state is transiently disconnected")
  372. private void doDelayedReconnect() {
  373. synchronized (myStateLock) {
  374. LOG.info("Performing delayed reconnect. State: {}", myState.getState());
  375. if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) {
  376. throw new IllegalStateException("doDelayedReconnect when not "
  377. + "transiently disconnected\n\nState: " + myState);
  378. }
  379. final int delay = Math.max(1000,
  380. getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay"));
  381. getEventBus().publishAsync(new ServerReconnectScheduledEvent(this, delay / 1000));
  382. reconnectTimerFuture = executorService.schedule(() -> {
  383. synchronized (myStateLock) {
  384. LOG.debug("Reconnect task executing, state: {}", myState.getState());
  385. if (myState.getState() == ServerState.RECONNECT_WAIT) {
  386. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  387. reconnect();
  388. }
  389. }
  390. }, delay, TimeUnit.MILLISECONDS);
  391. LOG.info("Scheduling reconnect task for delay of {}", delay);
  392. myState.transition(ServerState.RECONNECT_WAIT);
  393. updateIcon();
  394. }
  395. }
  396. @Override
  397. public boolean hasQuery(final String host) {
  398. return queries.containsKey(converter.toLowerCase(getUser(host).getNickname()));
  399. }
  400. @Override
  401. public Optional<User> getLocalUser() {
  402. return parser.map(Parser::getLocalClient)
  403. .map(client -> userManager.getUserFromClientInfo(client, this));
  404. }
  405. @Override
  406. public User getUser(final String details) {
  407. return parser.map(p -> p.getClient(details))
  408. .map(client -> userManager.getUserFromClientInfo(client, this)).get();
  409. }
  410. @Override
  411. public Query getQuery(final String host) {
  412. return getQuery(host, false);
  413. }
  414. @Override
  415. public Query getQuery(final String host, final boolean focus) {
  416. synchronized (myStateLock) {
  417. if (myState.getState() == ServerState.CLOSING) {
  418. // Can't open queries while the server is closing
  419. return null;
  420. }
  421. }
  422. final String nick = getUser(host).getNickname();
  423. final String lnick = converter.toLowerCase(nick);
  424. if (!queries.containsKey(lnick)) {
  425. final Query newQuery = queryFactory.getQuery(this, getUser(host));
  426. if (!getState().isDisconnected()) {
  427. newQuery.reregister();
  428. }
  429. getTabCompleter().addEntry(TabCompletionType.QUERY_NICK, nick);
  430. queries.put(lnick, newQuery);
  431. }
  432. return queries.get(lnick);
  433. }
  434. @Override
  435. public void updateQuery(final Query query, final String oldNick, final String newNick) {
  436. getTabCompleter().removeEntry(TabCompletionType.QUERY_NICK, oldNick);
  437. getTabCompleter().addEntry(TabCompletionType.QUERY_NICK, newNick);
  438. queries.put(converter.toLowerCase(newNick), query);
  439. queries.remove(converter.toLowerCase(oldNick));
  440. }
  441. @Override
  442. public Collection<Query> getQueries() {
  443. return Collections.unmodifiableCollection(queries.values());
  444. }
  445. @Override
  446. public void delQuery(final Query query) {
  447. getTabCompleter().removeEntry(TabCompletionType.QUERY_NICK, query.getNickname());
  448. queries.remove(converter.toLowerCase(query.getNickname()));
  449. }
  450. /**
  451. * Closes all open query windows associated with this server.
  452. */
  453. private void closeQueries() {
  454. new ArrayList<>(queries.values()).forEach(Query::close);
  455. }
  456. /**
  457. * Retrieves the host component of the specified URI, or throws a relevant exception if this is
  458. * not possible.
  459. *
  460. * @param uri The URI to be processed
  461. *
  462. * @return The URI's host component, as returned by {@link URI#getHost()}.
  463. *
  464. * @throws NullPointerException If <code>uri</code> is null
  465. * @throws IllegalArgumentException If the specified URI has no host
  466. * @since 0.6.4
  467. */
  468. private static String getHost(final URI uri) {
  469. if (uri.getHost() == null) {
  470. throw new IllegalArgumentException("URIs must have hosts");
  471. }
  472. return uri.getHost();
  473. }
  474. /**
  475. * Builds an appropriately configured {@link Parser} for this server.
  476. *
  477. * @return A configured parser.
  478. */
  479. @Nullable
  480. private Parser buildParser() {
  481. final Parser myParser = parserFactory.getParser(profile, address, getConfigManager())
  482. .orElse(null);
  483. if (myParser != null) {
  484. myParser.setIgnoreList(ignoreList);
  485. }
  486. if (myParser instanceof SecureParser) {
  487. final CertificateManager certificateManager =
  488. new CertificateManager(this, address.getHost(), getConfigManager(),
  489. userSettings, getEventBus());
  490. final SecureParser secureParser = (SecureParser) myParser;
  491. secureParser.setTrustManagers(certificateManager);
  492. secureParser.setKeyManagers(certificateManager.getKeyManager());
  493. }
  494. if (myParser instanceof EncodingParser) {
  495. final EncodingParser encodingParser = (EncodingParser) myParser;
  496. encodingParser.setEncoder(messageEncoderFactory.getMessageEncoder(this, myParser));
  497. }
  498. return myParser;
  499. }
  500. @Override
  501. public boolean compareURI(final URI uri) {
  502. return parser.map(p -> p.compareURI(uri)).orElse(
  503. oldParser.map(op -> op.compareURI(uri)).orElse(false));
  504. }
  505. /**
  506. * Updates this server's icon.
  507. */
  508. private void updateIcon() {
  509. final String icon = myState.getState() == ServerState.CONNECTED
  510. ? protocolDescription.get().isSecure(address)
  511. ? "secure-server" : "server" : "server-disconnected";
  512. setIcon(icon);
  513. }
  514. /**
  515. * Registers callbacks.
  516. */
  517. private void doCallbacks() {
  518. eventHandler.registerCallbacks();
  519. queries.values().forEach(Query::reregister);
  520. }
  521. @Override
  522. public void sendLine(final String line) {
  523. synchronized (myStateLock) {
  524. try {
  525. parserLock.readLock().lock();
  526. parser.ifPresent(p -> {
  527. if (!line.isEmpty() && myState.getState() == ServerState.CONNECTED) {
  528. p.sendRawMessage(line);
  529. }
  530. });
  531. } finally {
  532. parserLock.readLock().unlock();
  533. }
  534. }
  535. }
  536. @Override
  537. public void sendMessage(final String target, final String message) {
  538. if (!message.isEmpty()) {
  539. parser.ifPresent(p -> p.sendMessage(target, message));
  540. }
  541. }
  542. @Override
  543. public int getMaxLineLength() {
  544. return withParserReadLock(Parser::getMaxLength, -1);
  545. }
  546. @Override
  547. @Nonnull
  548. public Optional<Parser> getParser() {
  549. return parser;
  550. }
  551. @Nonnull
  552. @Override
  553. public Profile getProfile() {
  554. return profile;
  555. }
  556. @Override
  557. public String getAddress() {
  558. return withParserReadLock(Parser::getServerName, address.getHost());
  559. }
  560. @Override
  561. public String getNetwork() {
  562. try {
  563. parserLock.readLock().lock();
  564. return parser.map(p -> p.getNetworkName().isEmpty()
  565. ? getNetworkFromServerName(p.getServerName()) : p.getNetworkName())
  566. .orElseThrow(() -> new IllegalStateException(
  567. "getNetwork called when parser is null (state: " + getState() + ')'));
  568. } finally {
  569. parserLock.readLock().unlock();
  570. }
  571. }
  572. @Override
  573. public boolean isNetwork(final String target) {
  574. synchronized (myStateLock) {
  575. return withParserReadLock(p -> getNetwork().equalsIgnoreCase(target), false);
  576. }
  577. }
  578. /**
  579. * Calculates a network name from the specified server name. This method implements parts 2-4 of
  580. * the procedure documented at getNetwork().
  581. *
  582. * @param serverName The server name to parse
  583. *
  584. * @return A network name for the specified server
  585. */
  586. protected static String getNetworkFromServerName(final String serverName) {
  587. final String[] parts = serverName.split("\\.");
  588. final String[] tlds = {"biz", "com", "info", "net", "org"};
  589. boolean isTLD = false;
  590. for (String tld : tlds) {
  591. if (serverName.endsWith('.' + tld)) {
  592. isTLD = true;
  593. break;
  594. }
  595. }
  596. if (isTLD && parts.length > 2) {
  597. return parts[parts.length - 2] + '.' + parts[parts.length - 1];
  598. } else if (parts.length > 2) {
  599. final StringBuilder network = new StringBuilder();
  600. for (int i = 1; i < parts.length; i++) {
  601. if (network.length() > 0) {
  602. network.append('.');
  603. }
  604. network.append(parts[i]);
  605. }
  606. return network.toString();
  607. } else {
  608. return serverName;
  609. }
  610. }
  611. @Override
  612. public String getIrcd() {
  613. return parser.get().getServerSoftwareType();
  614. }
  615. @Override
  616. public String getProtocol() {
  617. return address.getScheme();
  618. }
  619. @Override
  620. public boolean isAway() {
  621. return awayMessage.isPresent();
  622. }
  623. @Override
  624. public String getAwayMessage() {
  625. return awayMessage.orElse(null);
  626. }
  627. @Override
  628. public ServerState getState() {
  629. return myState.getState();
  630. }
  631. @Override
  632. public ServerStatus getStatus() {
  633. return myState;
  634. }
  635. @Override
  636. public void close() {
  637. synchronized (myStateLock) {
  638. eventHandler.unregisterCallbacks();
  639. getConfigManager().removeListener(configListener);
  640. highlightManager.stop();
  641. getEventBus().unsubscribe(highlightManager);
  642. executorService.shutdown();
  643. disconnect();
  644. myState.transition(ServerState.CLOSING);
  645. }
  646. groupChatManager.closeAll();
  647. closeQueries();
  648. inviteManager.removeInvites();
  649. super.close();
  650. }
  651. @Override
  652. public WindowModel getWindowModel() {
  653. return this;
  654. }
  655. @Override
  656. public void addLineToAll(final String messageType, final Date date,
  657. final Object... args) {
  658. groupChatManager.addLineToAll(messageType, date, args);
  659. for (Query query : queries.values()) {
  660. query.addLine(messageType, date, args);
  661. }
  662. addLine(messageType, date, args);
  663. }
  664. @Override
  665. public void sendCTCPReply(final String source, final String type, final String args) {
  666. if ("VERSION".equalsIgnoreCase(type)) {
  667. parser.get().sendCTCPReply(source, "VERSION",
  668. "DMDirc " + getConfigManager().getOption("version", "version") +
  669. " - https://www.dmdirc.com/");
  670. } else if ("PING".equalsIgnoreCase(type)) {
  671. parser.get().sendCTCPReply(source, "PING", args);
  672. } else if ("CLIENTINFO".equalsIgnoreCase(type)) {
  673. parser.get().sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
  674. }
  675. }
  676. @Override
  677. public Optional<Connection> getConnection() {
  678. return Optional.of(this);
  679. }
  680. @Override
  681. protected boolean processNotificationArg(final Object arg, final List<Object> args) {
  682. if (arg instanceof User) {
  683. final User clientInfo = (User) arg;
  684. args.add(clientInfo.getNickname());
  685. args.add(clientInfo.getUsername());
  686. args.add(clientInfo.getHostname());
  687. return true;
  688. } else {
  689. return super.processNotificationArg(arg, args);
  690. }
  691. }
  692. @Override
  693. public void updateTitle() {
  694. synchronized (myStateLock) {
  695. if (myState.getState() == ServerState.CLOSING) {
  696. return;
  697. }
  698. try {
  699. parserLock.readLock().lock();
  700. final Object[] arguments = {
  701. address.getHost(), parser.map(Parser::getServerName).orElse("Unknown"),
  702. address.getPort(), parser.map(p -> getNetwork()).orElse("Unknown"),
  703. getLocalUser().map(User::getNickname).orElse("Unknown")
  704. };
  705. setName(Formatter.formatMessage(getConfigManager(),
  706. "serverName", arguments));
  707. setTitle(Formatter.formatMessage(getConfigManager(),
  708. "serverTitle", arguments));
  709. } finally {
  710. parserLock.readLock().unlock();
  711. }
  712. }
  713. }
  714. /**
  715. * Called when the socket has been closed.
  716. */
  717. public void onSocketClosed() {
  718. LOG.info("Received socket closed event, state: {}", myState.getState());
  719. if (Thread.holdsLock(myStateLock)) {
  720. LOG.info("State lock contended: rerunning on a new thread");
  721. executorService.schedule(this::onSocketClosed, 0, TimeUnit.SECONDS);
  722. return;
  723. }
  724. getEventBus().publish(new ServerDisconnectedEvent(this));
  725. eventHandler.unregisterCallbacks();
  726. synchronized (myStateLock) {
  727. if (myState.getState() == ServerState.CLOSING
  728. || myState.getState() == ServerState.DISCONNECTED) {
  729. // This has been triggered via .disconnect()
  730. return;
  731. }
  732. if (myState.getState() == ServerState.DISCONNECTING) {
  733. myState.transition(ServerState.DISCONNECTED);
  734. } else {
  735. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  736. }
  737. groupChatManager.handleSocketClosed();
  738. try {
  739. parserLock.writeLock().lock();
  740. oldParser = parser;
  741. parser = Optional.empty();
  742. } finally {
  743. parserLock.writeLock().unlock();
  744. }
  745. updateIcon();
  746. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect")) {
  747. closeQueries();
  748. }
  749. inviteManager.removeInvites();
  750. updateAwayState(Optional.empty());
  751. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect")
  752. && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) {
  753. doDelayedReconnect();
  754. }
  755. }
  756. }
  757. /**
  758. * Called when an error was encountered while connecting.
  759. *
  760. * @param errorInfo The parser's error information
  761. */
  762. @Precondition("The current server state is CONNECTING")
  763. public void onConnectError(final ParserError errorInfo) {
  764. synchronized (myStateLock) {
  765. LOG.info("Received connect error event, state: {}; error: {}", myState.getState(),
  766. errorInfo);
  767. if (myState.getState() == ServerState.CLOSING
  768. || myState.getState() == ServerState.DISCONNECTING) {
  769. // Do nothing
  770. return;
  771. } else if (myState.getState() != ServerState.CONNECTING) {
  772. // Shouldn't happen
  773. throw new IllegalStateException("Connect error when not "
  774. + "connecting\n\n" + getStatus().getTransitionHistory());
  775. }
  776. myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
  777. try {
  778. parserLock.writeLock().lock();
  779. oldParser = parser;
  780. parser = Optional.empty();
  781. } finally {
  782. parserLock.writeLock().unlock();
  783. }
  784. updateIcon();
  785. getEventBus().publish(new ServerConnectErrorEvent(this, getErrorDescription
  786. (errorInfo)));
  787. if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure")) {
  788. doDelayedReconnect();
  789. }
  790. }
  791. }
  792. /**
  793. * Gets a user-readable description of the specified error.
  794. *
  795. * @param errorInfo The parser error to get a description for.
  796. * @return A user-readable error description.
  797. */
  798. private static String getErrorDescription(final ParserError errorInfo) {
  799. final String description;
  800. if (errorInfo.getException() == null) {
  801. description = errorInfo.getData();
  802. } else {
  803. final Exception exception = errorInfo.getException();
  804. if (exception instanceof UnknownHostException) {
  805. description = "Unknown host (unable to resolve)";
  806. } else if (exception instanceof NoRouteToHostException) {
  807. description = "No route to host";
  808. } else if (exception instanceof SocketTimeoutException) {
  809. description = "Connection attempt timed out";
  810. } else if (exception instanceof SocketException
  811. || exception instanceof SSLException) {
  812. description = exception.getMessage();
  813. } else {
  814. LOG.info(APP_ERROR, "Unknown socket error: {}",
  815. exception.getClass().getCanonicalName(), exception);
  816. description = "Unknown error: " + exception.getMessage();
  817. }
  818. }
  819. return description;
  820. }
  821. /**
  822. * Called after the parser receives the 005 headers from the server.
  823. */
  824. @Precondition("State is CONNECTING")
  825. public void onPost005() {
  826. synchronized (myStateLock) {
  827. if (myState.getState() != ServerState.CONNECTING) {
  828. // Shouldn't happen
  829. throw new IllegalStateException("Received onPost005 while not "
  830. + "connecting\n\n" + myState.getTransitionHistory());
  831. }
  832. myState.transition(ServerState.CONNECTED);
  833. configMigrator.migrate(address.getScheme(),
  834. parser.get().getServerSoftwareType(), getNetwork(), parser.get().getServerName());
  835. updateIcon();
  836. updateTitle();
  837. updateIgnoreList();
  838. converter = parser.get().getStringConverter();
  839. groupChatManager.handleConnected();
  840. }
  841. getEventBus().publish(new ServerConnectedEvent(this));
  842. }
  843. @Override
  844. public IgnoreList getIgnoreList() {
  845. return ignoreList;
  846. }
  847. @Override
  848. public void updateIgnoreList() {
  849. ignoreList.clear();
  850. ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist"));
  851. }
  852. @Override
  853. public void saveIgnoreList() {
  854. getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList());
  855. }
  856. @Override
  857. public ConfigProvider getServerIdentity() {
  858. return identityFactory.createServerConfig(parser.get().getServerName());
  859. }
  860. @Override
  861. public ConfigProvider getNetworkIdentity() {
  862. return identityFactory.createNetworkConfig(getNetwork());
  863. }
  864. @Override
  865. public void updateAwayState(final Optional<String> message) {
  866. checkNotNull(message);
  867. if (awayMessage.equals(message)) {
  868. return;
  869. }
  870. awayMessage = message;
  871. }
  872. @Override
  873. public String getUserModes() {
  874. return getParser().map(Parser::getChannelUserModes).orElse("");
  875. }
  876. @Override
  877. public String getBooleanModes() {
  878. return getParser().map(Parser::getBooleanChannelModes).orElse("");
  879. }
  880. @Override
  881. public String getListModes() {
  882. return getParser().map(Parser::getListChannelModes).orElse("");
  883. }
  884. @Override
  885. public String getParameterModes() {
  886. return getParser().map(Parser::getParameterChannelModes).orElse("");
  887. }
  888. @Override
  889. public String getDoubleParameterModes() {
  890. return getParser().map(Parser::getDoubleParameterChannelModes).orElse("");
  891. }
  892. @Override
  893. public int getMaxListModes(final char mode) {
  894. return getParser().map(p -> p.getMaxListModes(mode)).orElse(-1);
  895. }
  896. @Override
  897. public GroupChatManager getGroupChatManager() {
  898. return groupChatManager;
  899. }
  900. @Override
  901. public InviteManager getInviteManager() {
  902. return inviteManager;
  903. }
  904. @Override
  905. public void setNickname(final String nickname) {
  906. parser.map(Parser::getLocalClient).ifPresent(c -> c.setNickname(nickname));
  907. }
  908. @Override
  909. public Optional<String> getNickname() {
  910. return parser.map(Parser::getLocalClient).map(ClientInfo::getNickname);
  911. }
  912. @Override
  913. public void requestUserInfo(final User user) {
  914. parser.ifPresent(p -> p.sendWhois(user.getNickname()));
  915. }
  916. /**
  917. * Utility method to get a result from the parser while holding the {@link #parserLock}
  918. * read lock.
  919. *
  920. * @param func The function to use to retrieve information from the parser.
  921. * @param orElse The value to return if the parser is otherwise not present.
  922. * @param <T> The type of result returned.
  923. * @return The value returned by {@code func}, if the parser is present, otherwise the
  924. * {@code orElse} value.
  925. */
  926. private <T> T withParserReadLock(
  927. final Function<? super Parser, ? extends T> func,
  928. final T orElse) {
  929. try {
  930. parserLock.readLock().lock();
  931. return parser.map(func).orElse(orElse);
  932. } finally {
  933. parserLock.readLock().unlock();
  934. }
  935. }
  936. }