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

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