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.

url.c 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. #include <sys/types.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <syslog.h>
  6. #include <sys/socket.h>
  7. #include <arpa/inet.h>
  8. #include <netinet/in.h>
  9. #include <netdb.h>
  10. #include "url.h"
  11. #include "fstring.h"
  12. #include "main.h"
  13. #define POST_CHAR 1
  14. #define POST_CHAR_S "\001"
  15. /* Tcp port range */
  16. #define LOWEST_PORT 0
  17. #define HIGHEST_PORT 65535
  18. #define uri_port_is_valid(port) \
  19. (LOWEST_PORT <= (port) && (port) <= HIGHEST_PORT)
  20. struct _proto {
  21. unsigned char *name;
  22. int port;
  23. uintptr_t *unused;
  24. unsigned int need_slashes:1;
  25. unsigned int need_slash_after_host:1;
  26. unsigned int free_syntax:1;
  27. unsigned int need_ssl:1;
  28. };
  29. static const char *text_url = "((https?|ftp)://)?"
  30. "(\\b(?<![.\\@A-Za-z0-9-])"
  31. "(?: [A-Za-z0-9][A-Za-z0-9-]*(?:\\.[A-Za-z0-9-]+)*\\."
  32. "(?i:com|net|org|biz|edu|gov|info|name|int|mil|aero|coop|jobs|mobi|museum|pro|travel"
  33. "|[rs]u|uk|ua|by|de|jp|fr|fi|no|no|ca|it|ro|cn|nl|at|nu|se"
  34. "|[a-z]{2}"
  35. "(?(1)|(?=/)))"
  36. "(?!\\w)"
  37. "|(?:\\d{1,3}\\.){3}\\d{1,3}(?(1)|(?=[/:]))"
  38. ")"
  39. "(?::\\d{1,5})?" /* port */
  40. "(?!\\.\\w)" /* host part ended, no more of this further on */
  41. "(?:[/?][;/?:@&=+\\$,[\\]\\-_.!~*'()A-Za-z0-9#%]*)?" /* path (&query) */
  42. "(?<![\\s>?!),.'\"\\]:])"
  43. "(?!@)"
  44. ")";
  45. static const char *html_url = "(?: src|href)=\"("
  46. "((https?|ftp)://)?"
  47. "(\\b(?<![.\\@A-Za-z0-9-])"
  48. "(?: [A-Za-z0-9][A-Za-z0-9-]*(?:\\.[A-Za-z0-9-]+)*\\."
  49. "(?i:com|net|org|biz|edu|gov|info|name|int|mil|aero|coop|jobs|mobi|museum|pro|travel"
  50. "|[rs]u|uk|ua|by|de|jp|fr|fi|no|no|ca|it|ro|cn|nl|at|nu|se"
  51. "|[a-z]{2}"
  52. "(?(1)|(?=/)))"
  53. "(?!\\w)"
  54. "|(?:\\d{1,3}\\.){3}\\d{1,3}(?(1)|(?=[/:]))"
  55. ")"
  56. "(?::\\d{1,5})?" /* port */
  57. "(?!\\.\\w)" /* host part ended, no more of this further on */
  58. "(?:[/?][;/?:@&=+\\$,[\\]\\-_.!~*'()A-Za-z0-9#%]*)?" /* path (&query) */
  59. "(?<![\\s>?!),.'\"\\]:])"
  60. "(?!@)"
  61. "))\"";
  62. static short url_initialized = 0;
  63. GRegex *text_re, *html_re;
  64. static const struct _proto protocol_backends[] = {
  65. { "file", 0, NULL, 1, 0, 0, 0 },
  66. { "ftp", 21, NULL, 1, 1, 0, 0 },
  67. { "http", 80, NULL, 1, 1, 0, 0 },
  68. { "https", 443, NULL, 1, 1, 0, 1 },
  69. /* Keep these last! */
  70. { NULL, 0, NULL, 0, 0, 1, 0 },
  71. };
  72. /*
  73. Table of "reserved" and "unsafe" characters. Those terms are
  74. rfc1738-speak, as such largely obsoleted by rfc2396 and later
  75. specs, but the general idea remains.
  76. A reserved character is the one that you can't decode without
  77. changing the meaning of the URL. For example, you can't decode
  78. "/foo/%2f/bar" into "/foo///bar" because the number and contents of
  79. path components is different. Non-reserved characters can be
  80. changed, so "/foo/%78/bar" is safe to change to "/foo/x/bar". The
  81. unsafe characters are loosely based on rfc1738, plus "$" and ",",
  82. as recommended by rfc2396, and minus "~", which is very frequently
  83. used (and sometimes unrecognized as %7E by broken servers).
  84. An unsafe character is the one that should be encoded when URLs are
  85. placed in foreign environments. E.g. space and newline are unsafe
  86. in HTTP contexts because HTTP uses them as separator and line
  87. terminator, so they must be encoded to %20 and %0A respectively.
  88. "*" is unsafe in shell context, etc.
  89. We determine whether a character is unsafe through static table
  90. lookup. This code assumes ASCII character set and 8-bit chars. */
  91. enum {
  92. /* rfc1738 reserved chars + "$" and ",". */
  93. urlchr_reserved = 1,
  94. /* rfc1738 unsafe chars, plus non-printables. */
  95. urlchr_unsafe = 2
  96. };
  97. #define urlchr_test(c, mask) (urlchr_table[(unsigned char)(c)] & (mask))
  98. #define URL_RESERVED_CHAR(c) urlchr_test(c, urlchr_reserved)
  99. #define URL_UNSAFE_CHAR(c) urlchr_test(c, urlchr_unsafe)
  100. /* Convert an ASCII hex digit to the corresponding number between 0
  101. and 15. H should be a hexadecimal digit that satisfies isxdigit;
  102. otherwise, the result is undefined. */
  103. #define XDIGIT_TO_NUM(h) ((h) < 'A' ? (h) - '0' : toupper (h) - 'A' + 10)
  104. #define X2DIGITS_TO_NUM(h1, h2) ((XDIGIT_TO_NUM (h1) << 4) + XDIGIT_TO_NUM (h2))
  105. /* The reverse of the above: convert a number in the [0, 16) range to
  106. the ASCII representation of the corresponding hexadecimal digit.
  107. `+ 0' is there so you can't accidentally use it as an lvalue. */
  108. #define XNUM_TO_DIGIT(x) ("0123456789ABCDEF"[x] + 0)
  109. #define XNUM_TO_digit(x) ("0123456789abcdef"[x] + 0)
  110. /* Shorthands for the table: */
  111. #define R urlchr_reserved
  112. #define U urlchr_unsafe
  113. #define RU R|U
  114. static const unsigned char urlchr_table[256] =
  115. {
  116. U, U, U, U, U, U, U, U, /* NUL SOH STX ETX EOT ENQ ACK BEL */
  117. U, U, U, U, U, U, U, U, /* BS HT LF VT FF CR SO SI */
  118. U, U, U, U, U, U, U, U, /* DLE DC1 DC2 DC3 DC4 NAK SYN ETB */
  119. U, U, U, U, U, U, U, U, /* CAN EM SUB ESC FS GS RS US */
  120. U, 0, U, RU, R, U, R, 0, /* SP ! " # $ % & ' */
  121. 0, 0, 0, R, R, 0, 0, R, /* ( ) * + , - . / */
  122. 0, 0, 0, 0, 0, 0, 0, 0, /* 0 1 2 3 4 5 6 7 */
  123. 0, 0, RU, R, U, R, U, R, /* 8 9 : ; < = > ? */
  124. RU, 0, 0, 0, 0, 0, 0, 0, /* @ A B C D E F G */
  125. 0, 0, 0, 0, 0, 0, 0, 0, /* H I J K L M N O */
  126. 0, 0, 0, 0, 0, 0, 0, 0, /* P Q R S T U V W */
  127. 0, 0, 0, RU, U, RU, U, 0, /* X Y Z [ \ ] ^ _ */
  128. U, 0, 0, 0, 0, 0, 0, 0, /* ` a b c d e f g */
  129. 0, 0, 0, 0, 0, 0, 0, 0, /* h i j k l m n o */
  130. 0, 0, 0, 0, 0, 0, 0, 0, /* p q r s t u v w */
  131. 0, 0, 0, U, U, U, 0, U, /* x y z { | } ~ DEL */
  132. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  133. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  134. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  135. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  136. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  137. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  138. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  139. U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U,
  140. };
  141. #undef R
  142. #undef U
  143. #undef RU
  144. static inline int
  145. end_of_dir(unsigned char c)
  146. {
  147. return c == POST_CHAR || c == '#' || c == ';' || c == '?';
  148. }
  149. static inline int
  150. is_uri_dir_sep(struct uri *uri, unsigned char pos)
  151. {
  152. return (pos == '/');
  153. }
  154. static int
  155. check_uri_file(unsigned char *name)
  156. {
  157. static const unsigned char chars[] = POST_CHAR_S "#?";
  158. return strcspn(name, chars);
  159. }
  160. static int
  161. url_init (void)
  162. {
  163. GError *err = NULL;
  164. if (url_initialized == 0) {
  165. text_re = g_regex_new (text_url, G_REGEX_CASELESS | G_REGEX_MULTILINE | G_REGEX_OPTIMIZE | G_REGEX_EXTENDED, 0, &err);
  166. if (err != NULL) {
  167. msg_info ("url_init: cannot init text url parsing regexp: %s", err->message);
  168. g_error_free (err);
  169. return -1;
  170. }
  171. html_re = g_regex_new (html_url, G_REGEX_CASELESS | G_REGEX_MULTILINE | G_REGEX_OPTIMIZE | G_REGEX_EXTENDED, 0, &err);
  172. if (err != NULL) {
  173. msg_info ("url_init: cannot init html url parsing regexp: %s", err->message);
  174. g_error_free (err);
  175. return -1;
  176. }
  177. url_initialized = 1;
  178. msg_debug ("url_init: url regexps initialized successfully, text regexp: /%s/, html_regexp: /%s/", text_url, html_url);
  179. }
  180. return 0;
  181. }
  182. enum protocol
  183. get_protocol(unsigned char *name, int namelen)
  184. {
  185. /* These are really enum protocol values but can take on negative
  186. * values and since 0 <= -1 for enum values it's better to use clean
  187. * integer type. */
  188. int start, end;
  189. enum protocol protocol;
  190. unsigned char *pname;
  191. int pnamelen, minlen, compare;
  192. /* Almost dichotomic search is used here */
  193. /* Starting at the HTTP entry which is the most common that will make
  194. * file and NNTP the next entries checked and amongst the third checks
  195. * are proxy and FTP. */
  196. start = 0;
  197. end = PROTOCOL_UNKNOWN - 1;
  198. protocol = PROTOCOL_HTTP;
  199. while (start <= end) {
  200. pname = protocol_backends[protocol].name;
  201. pnamelen = strlen (pname);
  202. minlen = MIN (pnamelen, namelen);
  203. compare = strncasecmp (pname, name, minlen);
  204. if (compare == 0) {
  205. if (pnamelen == namelen)
  206. return protocol;
  207. /* If the current protocol name is longer than the
  208. * protocol name being searched for move @end else move
  209. * @start. */
  210. compare = pnamelen > namelen ? 1 : -1;
  211. }
  212. if (compare > 0)
  213. end = protocol - 1;
  214. else
  215. start = protocol + 1;
  216. protocol = (start + end) / 2;
  217. }
  218. return PROTOCOL_UNKNOWN;
  219. }
  220. int
  221. get_protocol_port(enum protocol protocol)
  222. {
  223. return protocol_backends[protocol].port;
  224. }
  225. int
  226. get_protocol_need_slashes(enum protocol protocol)
  227. {
  228. return protocol_backends[protocol].need_slashes;
  229. }
  230. int
  231. get_protocol_need_slash_after_host(enum protocol protocol)
  232. {
  233. return protocol_backends[protocol].need_slash_after_host;
  234. }
  235. int
  236. get_protocol_free_syntax(enum protocol protocol)
  237. {
  238. return protocol_backends[protocol].free_syntax;
  239. }
  240. static int
  241. get_protocol_length(const unsigned char *url)
  242. {
  243. unsigned char *end = (unsigned char *) url;
  244. /* Seek the end of the protocol name if any. */
  245. /* RFC1738:
  246. * scheme = 1*[ lowalpha | digit | "+" | "-" | "." ]
  247. * (but per its recommendations we accept "upalpha" too) */
  248. while (isalnum(*end) || *end == '+' || *end == '-' || *end == '.')
  249. end++;
  250. /* Also return 0 if there's no protocol name (@end == @url). */
  251. return (*end == ':') ? end - url : 0;
  252. }
  253. /* URL-unescape the string S.
  254. This is done by transforming the sequences "%HH" to the character
  255. represented by the hexadecimal digits HH. If % is not followed by
  256. two hexadecimal digits, it is inserted literally.
  257. The transformation is done in place. If you need the original
  258. string intact, make a copy before calling this function. */
  259. static void
  260. url_unescape (char *s)
  261. {
  262. char *t = s; /* t - tortoise */
  263. char *h = s; /* h - hare */
  264. for (; *h; h++, t++) {
  265. if (*h != '%') {
  266. copychar:
  267. *t = *h;
  268. }
  269. else {
  270. char c;
  271. /* Do nothing if '%' is not followed by two hex digits. */
  272. if (!h[1] || !h[2] || !(isxdigit (h[1]) && isxdigit (h[2])))
  273. goto copychar;
  274. c = X2DIGITS_TO_NUM (h[1], h[2]);
  275. /* Don't unescape %00 because there is no way to insert it
  276. * into a C string without effectively truncating it. */
  277. if (c == '\0')
  278. goto copychar;
  279. *t = c;
  280. h += 2;
  281. }
  282. }
  283. *t = '\0';
  284. }
  285. /* The core of url_escape_* functions. Escapes the characters that
  286. match the provided mask in urlchr_table.
  287. If ALLOW_PASSTHROUGH is non-zero, a string with no unsafe chars
  288. will be returned unchanged. If ALLOW_PASSTHROUGH is zero, a
  289. freshly allocated string will be returned in all cases. */
  290. static char *
  291. url_escape_1 (const char *s, unsigned char mask, int allow_passthrough)
  292. {
  293. const char *p1;
  294. char *p2, *newstr;
  295. int newlen;
  296. int addition = 0;
  297. for (p1 = s; *p1; p1++)
  298. if (urlchr_test (*p1, mask))
  299. addition += 2; /* Two more characters (hex digits) */
  300. if (!addition)
  301. return allow_passthrough ? (char *)s : strdup (s);
  302. newlen = (p1 - s) + addition;
  303. newstr = (char *) g_malloc (newlen + 1);
  304. p1 = s;
  305. p2 = newstr;
  306. while (*p1) {
  307. /* Quote the characters that match the test mask. */
  308. if (urlchr_test (*p1, mask)) {
  309. unsigned char c = *p1++;
  310. *p2++ = '%';
  311. *p2++ = XNUM_TO_DIGIT (c >> 4);
  312. *p2++ = XNUM_TO_DIGIT (c & 0xf);
  313. }
  314. else
  315. *p2++ = *p1++;
  316. }
  317. *p2 = '\0';
  318. return newstr;
  319. }
  320. /* URL-escape the unsafe characters (see urlchr_table) in a given
  321. string, returning a freshly allocated string. */
  322. char *
  323. url_escape (const char *s)
  324. {
  325. return url_escape_1 (s, urlchr_unsafe, 0);
  326. }
  327. /* URL-escape the unsafe characters (see urlchr_table) in a given
  328. string. If no characters are unsafe, S is returned. */
  329. static char *
  330. url_escape_allow_passthrough (const char *s)
  331. {
  332. return url_escape_1 (s, urlchr_unsafe, 1);
  333. }
  334. /* Decide whether the char at position P needs to be encoded. (It is
  335. not enough to pass a single char *P because the function may need
  336. to inspect the surrounding context.)
  337. Return 1 if the char should be escaped as %XX, 0 otherwise. */
  338. static inline int
  339. char_needs_escaping (const char *p)
  340. {
  341. if (*p == '%') {
  342. if (isxdigit (*(p + 1)) && isxdigit (*(p + 2)))
  343. return 0;
  344. else
  345. /* Garbled %.. sequence: encode `%'. */
  346. return 1;
  347. }
  348. else if (URL_UNSAFE_CHAR (*p) && !URL_RESERVED_CHAR (*p))
  349. return 1;
  350. else
  351. return 0;
  352. }
  353. /* Translate a %-escaped (but possibly non-conformant) input string S
  354. into a %-escaped (and conformant) output string. If no characters
  355. are encoded or decoded, return the same string S; otherwise, return
  356. a freshly allocated string with the new contents.
  357. After a URL has been run through this function, the protocols that
  358. use `%' as the quote character can use the resulting string as-is,
  359. while those that don't can use url_unescape to get to the intended
  360. data. This function is stable: once the input is transformed,
  361. further transformations of the result yield the same output.
  362. */
  363. static char *
  364. reencode_escapes (const char *s)
  365. {
  366. const char *p1;
  367. char *newstr, *p2;
  368. int oldlen, newlen;
  369. int encode_count = 0;
  370. /* First pass: inspect the string to see if there's anything to do,
  371. and to calculate the new length. */
  372. for (p1 = s; *p1; p1++)
  373. if (char_needs_escaping (p1))
  374. ++encode_count;
  375. if (!encode_count)
  376. /* The string is good as it is. */
  377. return g_strdup (s); /* C const model sucks. */
  378. oldlen = p1 - s;
  379. /* Each encoding adds two characters (hex digits). */
  380. newlen = oldlen + 2 * encode_count;
  381. newstr = g_malloc (newlen + 1);
  382. /* Second pass: copy the string to the destination address, encoding
  383. chars when needed. */
  384. p1 = s;
  385. p2 = newstr;
  386. while (*p1)
  387. if (char_needs_escaping (p1)) {
  388. unsigned char c = *p1++;
  389. *p2++ = '%';
  390. *p2++ = XNUM_TO_DIGIT (c >> 4);
  391. *p2++ = XNUM_TO_DIGIT (c & 0xf);
  392. }
  393. else {
  394. *p2++ = *p1++;
  395. }
  396. *p2 = '\0';
  397. return newstr;
  398. }
  399. /* Unescape CHR in an otherwise escaped STR. Used to selectively
  400. escaping of certain characters, such as "/" and ":". Returns a
  401. count of unescaped chars. */
  402. static void
  403. unescape_single_char (char *str, char chr)
  404. {
  405. const char c1 = XNUM_TO_DIGIT (chr >> 4);
  406. const char c2 = XNUM_TO_DIGIT (chr & 0xf);
  407. char *h = str; /* hare */
  408. char *t = str; /* tortoise */
  409. for (; *h; h++, t++) {
  410. if (h[0] == '%' && h[1] == c1 && h[2] == c2) {
  411. *t = chr;
  412. h += 2;
  413. }
  414. else {
  415. *t = *h;
  416. }
  417. }
  418. *t = '\0';
  419. }
  420. /* Escape unsafe and reserved characters, except for the slash
  421. characters. */
  422. static char *
  423. url_escape_dir (const char *dir)
  424. {
  425. char *newdir = url_escape_1 (dir, urlchr_unsafe | urlchr_reserved, 1);
  426. if (newdir == dir)
  427. return (char *)dir;
  428. unescape_single_char (newdir, '/');
  429. return newdir;
  430. }
  431. /* Resolve "." and ".." elements of PATH by destructively modifying
  432. PATH and return non-zero if PATH has been modified, zero otherwise.
  433. The algorithm is in spirit similar to the one described in rfc1808,
  434. although implemented differently, in one pass. To recap, path
  435. elements containing only "." are removed, and ".." is taken to mean
  436. "back up one element". Single leading and trailing slashes are
  437. preserved.
  438. For example, "a/b/c/./../d/.." will yield "a/b/". More exhaustive
  439. test examples are provided below. If you change anything in this
  440. function, run test_path_simplify to make sure you haven't broken a
  441. test case. */
  442. static int
  443. path_simplify (char *path)
  444. {
  445. char *h = path; /* hare */
  446. char *t = path; /* tortoise */
  447. char *beg = path; /* boundary for backing the tortoise */
  448. char *end = path + strlen (path);
  449. while (h < end) {
  450. /* Hare should be at the beginning of a path element. */
  451. if (h[0] == '.' && (h[1] == '/' || h[1] == '\0')) {
  452. /* Ignore "./". */
  453. h += 2;
  454. }
  455. else if (h[0] == '.' && h[1] == '.' && (h[2] == '/' || h[2] == '\0')) {
  456. /* Handle "../" by retreating the tortoise by one path
  457. element -- but not past beggining. */
  458. if (t > beg) {
  459. /* Move backwards until T hits the beginning of the
  460. previous path element or the beginning of path. */
  461. for (--t; t > beg && t[-1] != '/'; t--);
  462. }
  463. else {
  464. /* If we're at the beginning, copy the "../" literally
  465. move the beginning so a later ".." doesn't remove
  466. it. */
  467. beg = t + 3;
  468. goto regular;
  469. }
  470. h += 3;
  471. }
  472. else {
  473. regular:
  474. /* A regular path element. If H hasn't advanced past T,
  475. simply skip to the next path element. Otherwise, copy
  476. the path element until the next slash. */
  477. if (t == h) {
  478. /* Skip the path element, including the slash. */
  479. while (h < end && *h != '/')
  480. t++, h++;
  481. if (h < end)
  482. t++, h++;
  483. }
  484. else {
  485. /* Copy the path element, including the final slash. */
  486. while (h < end && *h != '/')
  487. *t++ = *h++;
  488. if (h < end)
  489. *t++ = *h++;
  490. }
  491. }
  492. }
  493. if (t != h)
  494. *t = '\0';
  495. return t != h;
  496. }
  497. enum uri_errno
  498. parse_uri(struct uri *uri, unsigned char *uristring)
  499. {
  500. unsigned char *prefix_end, *host_end, *p;
  501. unsigned char *lbracket, *rbracket;
  502. int datalen, n, addrlen;
  503. unsigned char *frag_or_post, *user_end, *port_end;
  504. memset (uri, 0, sizeof (*uri));
  505. /* Nothing to do for an empty url. */
  506. if (!*uristring) return URI_ERRNO_EMPTY;
  507. uri->string = reencode_escapes (uristring);
  508. msg_debug ("parse_uri: reencoding escapes in original url: '%s'", struri (uri));
  509. uri->protocollen = get_protocol_length (struri (uri));
  510. /* Assume http as default protocol */
  511. if (!uri->protocollen || (uri->protocol = get_protocol (struri(uri), uri->protocollen)) == PROTOCOL_UNKNOWN) {
  512. p = g_strconcat ("http://", uri->string, NULL);
  513. g_free (uri->string);
  514. uri->string = p;
  515. uri->protocol = PROTOCOL_HTTP;
  516. prefix_end = struri (uri) + 7;
  517. }
  518. else {
  519. /* Figure out whether the protocol is known */
  520. msg_debug ("parse_uri: getting protocol from url: %d", uri->protocol);
  521. prefix_end = struri (uri) + uri->protocollen; /* ':' */
  522. /* Check if there's a digit after the protocol name. */
  523. if (isdigit (*prefix_end)) {
  524. p = struri (uri);
  525. uri->ip_family = p[uri->protocollen] - '0';
  526. prefix_end++;
  527. }
  528. if (*prefix_end != ':') {
  529. msg_debug ("parse_uri: invalid protocol in uri");
  530. return URI_ERRNO_INVALID_PROTOCOL;
  531. }
  532. prefix_end++;
  533. /* Skip slashes */
  534. if (prefix_end[0] == '/' && prefix_end[1] == '/') {
  535. if (prefix_end[2] == '/') {
  536. msg_debug ("parse_uri: too many '/' in uri");
  537. return URI_ERRNO_TOO_MANY_SLASHES;
  538. }
  539. prefix_end += 2;
  540. } else {
  541. msg_debug ("parse_uri: no '/' in uri");
  542. return URI_ERRNO_NO_SLASHES;
  543. }
  544. }
  545. if (get_protocol_free_syntax (uri->protocol)) {
  546. uri->data = prefix_end;
  547. uri->datalen = strlen (prefix_end);
  548. return URI_ERRNO_OK;
  549. } else if (uri->protocol == PROTOCOL_FILE) {
  550. datalen = check_uri_file (prefix_end);
  551. frag_or_post = prefix_end + datalen;
  552. /* Extract the fragment part. */
  553. if (datalen >= 0) {
  554. if (*frag_or_post == '#') {
  555. uri->fragment = frag_or_post + 1;
  556. uri->fragmentlen = strcspn(uri->fragment, POST_CHAR_S);
  557. frag_or_post = uri->fragment + uri->fragmentlen;
  558. }
  559. if (*frag_or_post == POST_CHAR) {
  560. uri->post = frag_or_post + 1;
  561. }
  562. } else {
  563. datalen = strlen(prefix_end);
  564. }
  565. uri->data = prefix_end;
  566. uri->datalen = datalen;
  567. return URI_ERRNO_OK;
  568. }
  569. /* Isolate host */
  570. /* Get brackets enclosing IPv6 address */
  571. lbracket = strchr (prefix_end, '[');
  572. if (lbracket) {
  573. rbracket = strchr (lbracket, ']');
  574. /* [address] is handled only inside of hostname part (surprisingly). */
  575. if (rbracket && rbracket < prefix_end + strcspn (prefix_end, "/"))
  576. uri->ipv6 = 1;
  577. else
  578. lbracket = rbracket = NULL;
  579. } else {
  580. rbracket = NULL;
  581. }
  582. /* Possibly skip auth part */
  583. host_end = prefix_end + strcspn (prefix_end, "@");
  584. if (prefix_end + strcspn (prefix_end, "/") > host_end
  585. && *host_end) { /* we have auth info here */
  586. /* Allow '@' in the password component */
  587. while (strcspn (host_end + 1, "@") < strcspn (host_end + 1, "/?"))
  588. host_end = host_end + 1 + strcspn (host_end + 1, "@");
  589. user_end = strchr (prefix_end, ':');
  590. if (!user_end || user_end > host_end) {
  591. uri->user = prefix_end;
  592. uri->userlen = host_end - prefix_end;
  593. } else {
  594. uri->user = prefix_end;
  595. uri->userlen = user_end - prefix_end;
  596. uri->password = user_end + 1;
  597. uri->passwordlen = host_end - user_end - 1;
  598. }
  599. prefix_end = host_end + 1;
  600. }
  601. if (uri->ipv6)
  602. host_end = rbracket + strcspn (rbracket, ":/?");
  603. else
  604. host_end = prefix_end + strcspn (prefix_end, ":/?");
  605. if (uri->ipv6) {
  606. addrlen = rbracket - lbracket - 1;
  607. uri->host = lbracket + 1;
  608. uri->hostlen = addrlen;
  609. } else {
  610. uri->host = prefix_end;
  611. uri->hostlen = host_end - prefix_end;
  612. /* Trim trailing '.'s */
  613. if (uri->hostlen && uri->host[uri->hostlen - 1] == '.')
  614. return URI_ERRNO_TRAILING_DOTS;
  615. }
  616. if (*host_end == ':') { /* we have port here */
  617. port_end = host_end + 1 + strcspn (host_end + 1, "/");
  618. host_end++;
  619. uri->port = host_end;
  620. uri->portlen = port_end - host_end;
  621. if (uri->portlen == 0)
  622. return URI_ERRNO_NO_PORT_COLON;
  623. /* We only use 8 bits for portlen so better check */
  624. if (uri->portlen != port_end - host_end)
  625. return URI_ERRNO_INVALID_PORT;
  626. /* test if port is number */
  627. for (; host_end < port_end; host_end++)
  628. if (!isdigit (*host_end))
  629. return URI_ERRNO_INVALID_PORT;
  630. /* Check valid port value, and let show an error message
  631. * about invalid url syntax. */
  632. if (uri->port && uri->portlen) {
  633. errno = 0;
  634. n = strtol (uri->port, NULL, 10);
  635. if (errno || !uri_port_is_valid (n))
  636. return URI_ERRNO_INVALID_PORT;
  637. }
  638. }
  639. if (*host_end == '/') {
  640. host_end++;
  641. } else if (get_protocol_need_slash_after_host (uri->protocol) && *host_end != '?') {
  642. /* The need for slash after the host component depends on the
  643. * need for a host component. -- The dangerous mind of Jonah */
  644. if (!uri->hostlen)
  645. return URI_ERRNO_NO_HOST;
  646. return URI_ERRNO_NO_HOST_SLASH;
  647. }
  648. /* Look for #fragment or POST_CHAR */
  649. prefix_end = host_end + strcspn (host_end, "#" POST_CHAR_S);
  650. uri->data = host_end;
  651. uri->datalen = prefix_end - host_end;
  652. if (*prefix_end == '#') {
  653. uri->fragment = prefix_end + 1;
  654. uri->fragmentlen = strcspn (uri->fragment, POST_CHAR_S);
  655. prefix_end = uri->fragment + uri->fragmentlen;
  656. }
  657. if (*prefix_end == POST_CHAR) {
  658. uri->post = prefix_end + 1;
  659. }
  660. convert_to_lowercase (uri->string, uri->protocollen);
  661. convert_to_lowercase (uri->host, uri->hostlen);
  662. /* Decode %HH sequences in host name. This is important not so much
  663. to support %HH sequences in host names (which other browser
  664. don't), but to support binary characters (which will have been
  665. converted to %HH by reencode_escapes). */
  666. if (strchr (uri->host, '%')) {
  667. url_unescape (uri->host);
  668. }
  669. path_simplify (uri->data);
  670. return URI_ERRNO_OK;
  671. }
  672. void
  673. url_parse_text (struct worker_task *task, GByteArray *content)
  674. {
  675. GMatchInfo *info;
  676. GError *err = NULL;
  677. int pos = 0, start;
  678. gboolean rc;
  679. char *url_str = NULL;
  680. struct uri *new;
  681. if (url_init () == 0) {
  682. do {
  683. rc = g_regex_match_full (text_re, (const char *)content->data, content->len, pos, 0, &info, &err);
  684. if (rc) {
  685. if (g_match_info_matches (info)) {
  686. g_match_info_fetch_pos (info, 0, &start, &pos);
  687. url_str = g_match_info_fetch (info, 0);
  688. msg_debug ("url_parse_text: extracted string with regexp: '%s'", url_str);
  689. if (url_str != NULL) {
  690. new = g_malloc (sizeof (struct uri));
  691. if (new != NULL) {
  692. parse_uri (new, url_str);
  693. TAILQ_INSERT_TAIL (&task->urls, new, next);
  694. }
  695. }
  696. g_free (url_str);
  697. }
  698. g_match_info_free (info);
  699. }
  700. else if (err != NULL) {
  701. msg_debug ("url_parse_text: error matching regexp: %s", err->message);
  702. g_free (err);
  703. }
  704. else {
  705. msg_debug ("url_parse_text: cannot find url pattern in given string");
  706. }
  707. } while (rc);
  708. }
  709. }
  710. void
  711. url_parse_html (struct worker_task *task, GByteArray *content)
  712. {
  713. GMatchInfo *info;
  714. GError *err = NULL;
  715. int pos = 0, start;
  716. gboolean rc;
  717. char *url_str = NULL;
  718. struct uri *new;
  719. if (url_init () == 0) {
  720. do {
  721. rc = g_regex_match_full (html_re, (const char *)content->data, content->len, pos, 0, &info, &err);
  722. if (rc) {
  723. if (g_match_info_matches (info)) {
  724. g_match_info_fetch_pos (info, 0, &start, &pos);
  725. url_str = g_match_info_fetch (info, 1);
  726. msg_debug ("url_parse_html: extracted string with regexp: '%s'", url_str);
  727. if (url_str != NULL) {
  728. new = g_malloc (sizeof (struct uri));
  729. if (new != NULL) {
  730. parse_uri (new, url_str);
  731. TAILQ_INSERT_TAIL (&task->urls, new, next);
  732. }
  733. }
  734. g_free (url_str);
  735. }
  736. g_match_info_free (info);
  737. }
  738. else if (err) {
  739. msg_debug ("url_parse_html: error matching regexp: %s", err->message);
  740. g_free (err);
  741. }
  742. else {
  743. msg_debug ("url_parse_html: cannot find url pattern in given string");
  744. }
  745. } while (rc);
  746. }
  747. }