Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

URIParser.java 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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.util;
  18. import java.io.UnsupportedEncodingException;
  19. import java.net.URI;
  20. import java.net.URISyntaxException;
  21. import java.net.URLDecoder;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import javax.inject.Inject;
  25. import javax.inject.Singleton;
  26. /**
  27. * Utility class for parsing IRC URIs from user input.
  28. */
  29. @Singleton
  30. public class URIParser {
  31. /**
  32. * Pattern used to breakdown a URI authority.
  33. */
  34. private final Pattern authorityBreakdown = Pattern.compile(
  35. "(?:(?<auth>[^@]*)@)?(?<host>[^:]+)(?::(?<secure>\\+)?(?<port>[0-9]*))?");
  36. /**
  37. * Pattern used to breakdown a URI. From RFC3986 appendix-B.
  38. */
  39. private final Pattern uriBreakdown = Pattern.compile(
  40. "((?<scheme>[^:/?#]+):)?(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?");
  41. /**
  42. * Creates a new instance of {@link URIParser}.
  43. */
  44. @Inject
  45. public URIParser() {
  46. }
  47. /**
  48. * Parses the given string as a URI, allowing for a '+' symbol at the start of the port to
  49. * indicate a secure connection.
  50. *
  51. * @param input The string to be parsed.
  52. *
  53. * @return An equivalent URI, if one can be parsed.
  54. *
  55. * @throws InvalidURIException If the string cannot be parsed as a URI.
  56. */
  57. public URI parseFromURI(final String input) throws InvalidURIException {
  58. String scheme;
  59. final String userInfo;
  60. final String authority;
  61. final String host;
  62. final String portString;
  63. final int port;
  64. final String path;
  65. final String query;
  66. final String fragment;
  67. final Matcher uriMatcher = uriBreakdown.matcher(input);
  68. if (!uriMatcher.matches() || uriMatcher.group("scheme") == null || uriMatcher.group(
  69. "authority") == null) {
  70. throw new InvalidURIException("Invalid address specified");
  71. }
  72. scheme = uriMatcher.group("scheme");
  73. authority = uriMatcher.group("authority");
  74. path = uriMatcher.group("path");
  75. query = uriMatcher.group("query");
  76. fragment = uriMatcher.group("fragment");
  77. final Matcher authorityMatcher = authorityBreakdown.matcher(authority);
  78. if (!authorityMatcher.matches()) {
  79. throw new InvalidURIException("Invalid address specified");
  80. }
  81. try {
  82. // User info may contain special characters. When we pass individual parts to
  83. // the URI constructor below, it encodes any characters not allowed in the user
  84. // info. To avoid doubly-encoding them we need to decode here...
  85. String auth = authorityMatcher.group("auth");
  86. userInfo = auth == null ? null : URLDecoder.decode(auth, "UTF-8");
  87. } catch (UnsupportedEncodingException ex) {
  88. throw new InvalidURIException("Unable to create user info", ex);
  89. }
  90. host = authorityMatcher.group("host");
  91. if (authorityMatcher.group("secure") != null && scheme.charAt(scheme.length() - 1) != 's') {
  92. scheme += "s";
  93. }
  94. portString = authorityMatcher.group("port");
  95. if (portString != null) {
  96. try {
  97. port = Integer.parseInt(authorityMatcher.group(4));
  98. } catch (NumberFormatException ex) {
  99. throw new InvalidURIException("Invalid port specified", ex);
  100. }
  101. if (port <= 0 || port > 65535) {
  102. throw new InvalidURIException("Invalid port specified",
  103. new IllegalArgumentException("Port must be between 1 and 65535"));
  104. }
  105. } else {
  106. port = -1;
  107. }
  108. try {
  109. return new URI(scheme, userInfo, host, port, path, query, fragment);
  110. } catch (URISyntaxException ex) {
  111. throw new InvalidURIException("Invalid address specified", ex);
  112. }
  113. }
  114. /**
  115. * Parses the given string as a free-form address. This takes the form of a hostname and
  116. * optional port, followed by an optional password. If the input appears to contain a full URI
  117. * already, it is parsed by {@link #parseFromURI(java.lang.String)}.
  118. *
  119. * @param input The string to be parsed.
  120. *
  121. * @return An equivalent URI, if one can be parsed.
  122. *
  123. * @throws InvalidURIException If the string cannot be parsed as a URI, or an invalid component
  124. * is specified.
  125. */
  126. public URI parseFromText(final String input) throws InvalidURIException {
  127. if (input.indexOf(' ') == -1 && input.contains("://")) {
  128. // Looks like a full URI, parse it as such.
  129. return parseFromURI(input);
  130. }
  131. boolean ssl = false;
  132. final String host;
  133. String pass = null;
  134. int port = -1;
  135. final String[] parts = input.split(" ", 2);
  136. // Check for port
  137. if (parts[0].indexOf(':') > -1) {
  138. final String[] portParts = parts[0].split(":");
  139. if (portParts.length < 2) {
  140. throw new InvalidURIException("Invalid port specified");
  141. }
  142. host = portParts[0];
  143. if (!portParts[1].isEmpty() && portParts[1].charAt(0) == '+') {
  144. ssl = true;
  145. portParts[1] = portParts[1].substring(1);
  146. }
  147. try {
  148. port = Integer.parseInt(portParts[1]);
  149. } catch (NumberFormatException ex) {
  150. throw new InvalidURIException("Invalid port specified", ex);
  151. }
  152. if (port <= 0 || port > 65535) {
  153. throw new InvalidURIException("Invalid port specified",
  154. new IllegalArgumentException("Port must be between 1 and 65535"));
  155. }
  156. } else {
  157. host = parts[0];
  158. }
  159. // Check for password
  160. if (parts.length > 1) {
  161. pass = parts[1];
  162. }
  163. try {
  164. return new URI("irc" + (ssl ? "s" : ""), pass, host, port, null, null, null);
  165. } catch (URISyntaxException ex) {
  166. throw new InvalidURIException("Invalid address specified", ex);
  167. }
  168. }
  169. }