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.0KB

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