Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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