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

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