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.

IdentClient.java 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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.addons.identd;
  23. import com.dmdirc.DMDircMBassador;
  24. import com.dmdirc.events.UserErrorEvent;
  25. import com.dmdirc.interfaces.Connection;
  26. import com.dmdirc.interfaces.ConnectionManager;
  27. import com.dmdirc.interfaces.User;
  28. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  29. import com.dmdirc.interfaces.config.ReadOnlyConfigProvider;
  30. import com.dmdirc.logger.ErrorLevel;
  31. import com.dmdirc.util.io.StreamUtils;
  32. import java.io.BufferedReader;
  33. import java.io.IOException;
  34. import java.io.InputStreamReader;
  35. import java.io.PrintWriter;
  36. import java.net.Socket;
  37. /**
  38. * The IdentClient responds to an ident request.
  39. */
  40. public class IdentClient implements Runnable {
  41. /** The event bus to post errors on. */
  42. private final DMDircMBassador eventBus;
  43. /** The IdentdServer that owns this Client. */
  44. private final IdentdServer server;
  45. /** The Socket that we are in charge of. */
  46. private final Socket socket;
  47. /** The Thread in use for this client. */
  48. private volatile Thread thread;
  49. /** Server manager. */
  50. private final ConnectionManager connectionManager;
  51. /** Global configuration to read settings from. */
  52. private final AggregateConfigProvider config;
  53. /** This plugin's settings domain. */
  54. private final String domain;
  55. /**
  56. * Create the IdentClient.
  57. *
  58. * @param eventBus The event bus to post errors on
  59. * @param server The server that owns this
  60. * @param socket The socket we are handing
  61. * @param connectionManager Server manager to retrieve servers from
  62. * @param config Global config to read settings from
  63. * @param domain This plugin's settings domain
  64. */
  65. public IdentClient(final DMDircMBassador eventBus, final IdentdServer server, final Socket socket,
  66. final ConnectionManager connectionManager, final AggregateConfigProvider config,
  67. final String domain) {
  68. this.eventBus = eventBus;
  69. this.server = server;
  70. this.socket = socket;
  71. this.connectionManager = connectionManager;
  72. this.config = config;
  73. this.domain = domain;
  74. }
  75. /**
  76. * Starts this ident client in a new thread.
  77. */
  78. public void start() {
  79. thread = new Thread(this);
  80. thread.start();
  81. }
  82. /**
  83. * Process this connection.
  84. */
  85. @Override
  86. public void run() {
  87. final Thread thisThread = Thread.currentThread();
  88. try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
  89. BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
  90. final String inputLine;
  91. if ((inputLine = in.readLine()) != null) {
  92. out.println(getIdentResponse(inputLine, config));
  93. }
  94. } catch (IOException e) {
  95. if (thisThread == thread) {
  96. eventBus.publishAsync(new UserErrorEvent(ErrorLevel.HIGH, e,
  97. "ClientSocket Error: " + e.getMessage(), ""));
  98. }
  99. } finally {
  100. StreamUtils.close(socket);
  101. server.delClient(this);
  102. }
  103. }
  104. /**
  105. * Get the ident response for a given line. Complies with rfc1413
  106. * (http://www.faqs.org/rfcs/rfc1413.html)
  107. *
  108. * @param input Line to generate response for
  109. * @param config The config manager to use for settings
  110. *
  111. * @return the ident response for the given line
  112. */
  113. protected String getIdentResponse(final String input, final ReadOnlyConfigProvider config) {
  114. final String unescapedInput = unescapeString(input);
  115. final String[] bits = unescapedInput.replaceAll("\\s+", "").split(",", 2);
  116. if (bits.length < 2) {
  117. return String.format("%s : ERROR : X-INVALID-INPUT", escapeString(unescapedInput));
  118. }
  119. final int myPort;
  120. final int theirPort;
  121. try {
  122. myPort = Integer.parseInt(bits[0].trim());
  123. theirPort = Integer.parseInt(bits[1].trim());
  124. } catch (NumberFormatException e) {
  125. return String.format("%s , %s : ERROR : X-INVALID-INPUT", escapeString(bits[0]),
  126. escapeString(bits[1]));
  127. }
  128. if (myPort > 65535 || myPort < 1 || theirPort > 65535 || theirPort < 1) {
  129. return String.format("%d , %d : ERROR : INVALID-PORT", myPort, theirPort);
  130. }
  131. final Connection connection = getConnectionByPort(myPort);
  132. if (!config.getOptionBool(domain, "advanced.alwaysOn") && (connection == null
  133. || config.getOptionBool(domain, "advanced.isNoUser"))) {
  134. return String.format("%d , %d : ERROR : NO-USER", myPort, theirPort);
  135. }
  136. if (config.getOptionBool(domain, "advanced.isHiddenUser")) {
  137. return String.format("%d , %d : ERROR : HIDDEN-USER", myPort, theirPort);
  138. }
  139. final String osName = System.getProperty("os.name").toLowerCase();
  140. final String os;
  141. final String customSystem = config.getOption(domain, "advanced.customSystem");
  142. if (config.getOptionBool(domain, "advanced.useCustomSystem") && customSystem
  143. != null && !customSystem.isEmpty() && customSystem.length() < 513) {
  144. os = customSystem;
  145. } else {
  146. // Tad excessive maybe, but complete!
  147. // Based on: http://mindprod.com/jgloss/properties.html
  148. // and the SYSTEM NAMES section of rfc1340 (http://www.faqs.org/rfcs/rfc1340.html)
  149. if (osName.startsWith("windows")) {
  150. os = "WIN32";
  151. } else if (osName.startsWith("mac")) {
  152. os = "MACOS";
  153. } else if (osName.startsWith("linux")) {
  154. os = "UNIX";
  155. } else if (osName.contains("bsd")) {
  156. os = "UNIX-BSD";
  157. } else if ("os/2".equals(osName)) {
  158. os = "OS/2";
  159. } else if (osName.contains("unix")) {
  160. os = "UNIX";
  161. } else if ("irix".equals(osName)) {
  162. os = "IRIX";
  163. } else {
  164. os = "UNKNOWN";
  165. }
  166. }
  167. final String customName = config.getOption(domain, "general.customName");
  168. final String username;
  169. if (config.getOptionBool(domain, "general.useCustomName") && customName
  170. != null && !customName.isEmpty() && customName.length() < 513) {
  171. username = customName;
  172. } else if (connection != null && config.getOptionBool(domain, "general.useNickname")) {
  173. username = connection.getLocalUser().map(User::getNickname).orElse("Unknown");
  174. } else if (connection != null && config.getOptionBool(domain, "general.useUsername")) {
  175. username = connection.getLocalUser().flatMap(User::getUsername).orElse("Unknown");
  176. } else {
  177. username = System.getProperty("user.name");
  178. }
  179. return String.format("%d , %d : USERID : %s : %s", myPort, theirPort, escapeString(os),
  180. escapeString(username));
  181. }
  182. /**
  183. * Escape special chars.
  184. *
  185. * @param str String to escape
  186. *
  187. * @return Escaped string.
  188. */
  189. public static String escapeString(final String str) {
  190. return str.replace("\\", "\\\\").replace(":", "\\:").replace(",", "\\,").replace(" ", "\\ ");
  191. }
  192. /**
  193. * Unescape special chars.
  194. *
  195. * @param str String to escape
  196. *
  197. * @return Escaped string.
  198. */
  199. public static String unescapeString(final String str) {
  200. return str.replace("\\:", ":").replace("\\ ", " ").replace("\\,", ",").replace("\\\\", "\\");
  201. }
  202. /**
  203. * Close this IdentClient.
  204. */
  205. public void close() {
  206. if (thread != null) {
  207. final Thread tmpThread = thread;
  208. thread = null;
  209. if (tmpThread != null) {
  210. tmpThread.interrupt();
  211. }
  212. StreamUtils.close(socket);
  213. }
  214. }
  215. /**
  216. * Retrieves the server that is bound to the specified local port.
  217. *
  218. * @param port Port to check for
  219. *
  220. * @return The server instance listening on the given port
  221. */
  222. protected Connection getConnectionByPort(final int port) {
  223. for (Connection connection : connectionManager.getConnections()) {
  224. if (connection.getParser().get().getLocalPort() == port) {
  225. return connection;
  226. }
  227. }
  228. return null;
  229. }
  230. }