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

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