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 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Copyright (c) 2006-2013 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.Server;
  24. import com.dmdirc.ServerManager;
  25. import com.dmdirc.config.ConfigManager;
  26. import com.dmdirc.logger.ErrorLevel;
  27. import com.dmdirc.logger.Logger;
  28. import com.dmdirc.util.io.StreamUtils;
  29. import java.io.BufferedReader;
  30. import java.io.IOException;
  31. import java.io.InputStreamReader;
  32. import java.io.PrintWriter;
  33. import java.net.Socket;
  34. /**
  35. * The IdentClient responds to an ident request.
  36. */
  37. public final class IdentClient implements Runnable {
  38. /** The IdentdServer that owns this Client. */
  39. private final IdentdServer myServer;
  40. /** The Socket that we are in charge of. */
  41. private final Socket mySocket;
  42. /** The Thread in use for this client. */
  43. private volatile Thread myThread;
  44. /** The plugin that owns us. */
  45. private final IdentdPlugin myPlugin;
  46. /** Server manager. */
  47. private final ServerManager serverManager;
  48. /**
  49. * Create the IdentClient.
  50. *
  51. * @param server The server that owns this
  52. * @param socket The socket we are handing
  53. * @param plugin Parent plugin
  54. * @param serverManager Server manager to retrieve servers from
  55. */
  56. public IdentClient(final IdentdServer server, final Socket socket,
  57. final IdentdPlugin plugin, final ServerManager serverManager) {
  58. myServer = server;
  59. mySocket = socket;
  60. myPlugin = plugin;
  61. this.serverManager = serverManager;
  62. }
  63. /**
  64. * Starts this ident client in a new thread.
  65. */
  66. public void start() {
  67. myThread = new Thread(this);
  68. myThread.start();
  69. }
  70. /**
  71. * Process this connection.
  72. */
  73. @Override
  74. public void run() {
  75. final Thread thisThread = Thread.currentThread();
  76. PrintWriter out = null;
  77. BufferedReader in = null;
  78. try {
  79. out = new PrintWriter(mySocket.getOutputStream(), true);
  80. in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
  81. final String inputLine;
  82. if ((inputLine = in.readLine()) != null) {
  83. out.println(getIdentResponse(inputLine, myPlugin.getConfig()));
  84. }
  85. } catch (IOException e) {
  86. if (thisThread == myThread) {
  87. Logger.userError(ErrorLevel.HIGH, "ClientSocket Error: " + e.getMessage());
  88. }
  89. } finally {
  90. StreamUtils.close(in);
  91. StreamUtils.close(out);
  92. StreamUtils.close(mySocket);
  93. myServer.delClient(this);
  94. }
  95. }
  96. /**
  97. * Get the ident response for a given line.
  98. * Complies with rfc1413 (http://www.faqs.org/rfcs/rfc1413.html)
  99. *
  100. * @param input Line to generate response for
  101. * @param config The config manager to use for settings
  102. * @return the ident response for the given line
  103. */
  104. protected String getIdentResponse(final String input, final ConfigManager config) {
  105. final String unescapedInput = unescapeString(input);
  106. final String[] bits = unescapedInput.replaceAll("\\s+", "").split(",", 2);
  107. if (bits.length < 2) {
  108. return String.format("%s : ERROR : X-INVALID-INPUT", escapeString(unescapedInput));
  109. }
  110. final int myPort;
  111. final int theirPort;
  112. try {
  113. myPort = Integer.parseInt(bits[0].trim());
  114. theirPort = Integer.parseInt(bits[1].trim());
  115. } catch (NumberFormatException e) {
  116. return String.format("%s , %s : ERROR : X-INVALID-INPUT", escapeString(bits[0]), escapeString(bits[1]));
  117. }
  118. if (myPort > 65535 || myPort < 1 || theirPort > 65535 || theirPort < 1) {
  119. return String.format("%d , %d : ERROR : INVALID-PORT", myPort, theirPort);
  120. }
  121. final Server server = getServerByPort(myPort);
  122. if (!config.getOptionBool(myPlugin.getDomain(), "advanced.alwaysOn") && (server == null || config.getOptionBool(myPlugin.getDomain(), "advanced.isNoUser"))) {
  123. return String.format("%d , %d : ERROR : NO-USER", myPort, theirPort);
  124. }
  125. if (config.getOptionBool(myPlugin.getDomain(), "advanced.isHiddenUser")) {
  126. return String.format("%d , %d : ERROR : HIDDEN-USER", myPort, theirPort);
  127. }
  128. final String osName = System.getProperty("os.name").toLowerCase();
  129. final String os;
  130. final String username;
  131. final String customSystem = config.getOption(myPlugin.getDomain(), "advanced.customSystem");
  132. if (config.getOptionBool(myPlugin.getDomain(), "advanced.useCustomSystem") && customSystem != null && customSystem.length() > 0 && 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.indexOf("bsd") > -1) {
  145. os = "UNIX-BSD";
  146. } else if ("os/2".equals(osName)) {
  147. os = "OS/2";
  148. } else if (osName.indexOf("unix") > -1) {
  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(myPlugin.getDomain(), "general.customName");
  157. if (config.getOptionBool(myPlugin.getDomain(), "general.useCustomName") && customName != null && customName.length() > 0 && customName.length() < 513) {
  158. username = customName;
  159. } else if (server != null && config.getOptionBool(myPlugin.getDomain(), "general.useNickname")) {
  160. username = server.getParser().getLocalClient().getNickname();
  161. } else if (server != null && config.getOptionBool(myPlugin.getDomain(), "general.useUsername")) {
  162. username = server.getParser().getLocalClient().getUsername();
  163. } else {
  164. username = System.getProperty("user.name");
  165. }
  166. return String.format("%d , %d : USERID : %s : %s", myPort, theirPort, escapeString(os), escapeString(username));
  167. }
  168. /**
  169. * Escape special chars.
  170. *
  171. * @param str String to escape
  172. * @return Escaped string.
  173. */
  174. public static String escapeString(final String str) {
  175. return str.replace("\\", "\\\\").replace(":", "\\:").replace(",", "\\,").replace(" ", "\\ ");
  176. }
  177. /**
  178. * Unescape special chars.
  179. *
  180. * @param str String to escape
  181. * @return Escaped string.
  182. */
  183. public static String unescapeString(final String str) {
  184. return str.replace("\\:", ":").replace("\\ ", " ").replace("\\,", ",").replace("\\\\", "\\");
  185. }
  186. /**
  187. * Close this IdentClient.
  188. */
  189. public void close() {
  190. if (myThread != null) {
  191. final Thread tmpThread = myThread;
  192. myThread = null;
  193. if (tmpThread != null) {
  194. tmpThread.interrupt();
  195. }
  196. StreamUtils.close(mySocket);
  197. }
  198. }
  199. /**
  200. * Retrieves the server that is bound to the specified local port.
  201. *
  202. * @param port Port to check for
  203. * @return The server instance listening on the given port
  204. */
  205. protected Server getServerByPort(final int port) {
  206. for (Server server : serverManager.getServers()) {
  207. if (server.getParser().getLocalPort() == port) {
  208. return server;
  209. }
  210. }
  211. return null;
  212. }
  213. }