Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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