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

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