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

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