replace-object.h: move read_replace_refs declaration from cache.h to here
[git.git] / urlmatch.c
blob2965cbe774ff12a67dd19e93b4f4d0467975a854
1 #include "cache.h"
2 #include "hex.h"
3 #include "urlmatch.h"
5 #define URL_ALPHA "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
6 #define URL_DIGIT "0123456789"
7 #define URL_ALPHADIGIT URL_ALPHA URL_DIGIT
8 #define URL_SCHEME_CHARS URL_ALPHADIGIT "+.-"
9 #define URL_HOST_CHARS URL_ALPHADIGIT ".-_[:]" /* IPv6 literals need [:] */
10 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`" /* plus 0x00-0x1F,0x7F-0xFF */
11 #define URL_GEN_RESERVED ":/?#[]@"
12 #define URL_SUB_RESERVED "!$&'()*+,;="
13 #define URL_RESERVED URL_GEN_RESERVED URL_SUB_RESERVED /* only allowed delims */
15 static int append_normalized_escapes(struct strbuf *buf,
16 const char *from,
17 size_t from_len,
18 const char *esc_extra,
19 const char *esc_ok)
22 * Append to strbuf 'buf' characters from string 'from' with length
23 * 'from_len' while unescaping characters that do not need to be escaped
24 * and escaping characters that do. The set of characters to escape
25 * (the complement of which is unescaped) starts out as the RFC 3986
26 * unsafe characters (0x00-0x1F,0x7F-0xFF," <>\"#%{}|\\^`"). If
27 * 'esc_extra' is not NULL, those additional characters will also always
28 * be escaped. If 'esc_ok' is not NULL, those characters will be left
29 * escaped if found that way, but will not be unescaped otherwise (used
30 * for delimiters). If a %-escape sequence is encountered that is not
31 * followed by 2 hexadecimal digits, the sequence is invalid and
32 * false (0) will be returned. Otherwise true (1) will be returned for
33 * success.
35 * Note that all %-escape sequences will be normalized to UPPERCASE
36 * as indicated in RFC 3986. Unless included in esc_extra or esc_ok
37 * alphanumerics and "-._~" will always be unescaped as per RFC 3986.
40 while (from_len) {
41 int ch = *from++;
42 int was_esc = 0;
44 from_len--;
45 if (ch == '%') {
46 if (from_len < 2)
47 return 0;
48 ch = hex2chr(from);
49 if (ch < 0)
50 return 0;
51 from += 2;
52 from_len -= 2;
53 was_esc = 1;
55 if ((unsigned char)ch <= 0x1F || (unsigned char)ch >= 0x7F ||
56 strchr(URL_UNSAFE_CHARS, ch) ||
57 (esc_extra && strchr(esc_extra, ch)) ||
58 (was_esc && strchr(esc_ok, ch)))
59 strbuf_addf(buf, "%%%02X", (unsigned char)ch);
60 else
61 strbuf_addch(buf, ch);
64 return 1;
67 static const char *end_of_token(const char *s, int c, size_t n)
69 const char *next = memchr(s, c, n);
70 if (!next)
71 next = s + n;
72 return next;
75 static int match_host(const struct url_info *url_info,
76 const struct url_info *pattern_info)
78 const char *url = url_info->url + url_info->host_off;
79 const char *pat = pattern_info->url + pattern_info->host_off;
80 int url_len = url_info->host_len;
81 int pat_len = pattern_info->host_len;
83 while (url_len && pat_len) {
84 const char *url_next = end_of_token(url, '.', url_len);
85 const char *pat_next = end_of_token(pat, '.', pat_len);
87 if (pat_next == pat + 1 && pat[0] == '*')
88 /* wildcard matches anything */
90 else if ((pat_next - pat) == (url_next - url) &&
91 !memcmp(url, pat, url_next - url))
92 /* the components are the same */
94 else
95 return 0; /* found an unmatch */
97 if (url_next < url + url_len)
98 url_next++;
99 url_len -= url_next - url;
100 url = url_next;
101 if (pat_next < pat + pat_len)
102 pat_next++;
103 pat_len -= pat_next - pat;
104 pat = pat_next;
107 return (!url_len && !pat_len);
110 static char *url_normalize_1(const char *url, struct url_info *out_info, char allow_globs)
113 * Normalize NUL-terminated url using the following rules:
115 * 1. Case-insensitive parts of url will be converted to lower case
116 * 2. %-encoded characters that do not need to be will be unencoded
117 * 3. Characters that are not %-encoded and must be will be encoded
118 * 4. All %-encodings will be converted to upper case hexadecimal
119 * 5. Leading 0s are removed from port numbers
120 * 6. If the default port for the scheme is given it will be removed
121 * 7. A path part (including empty) not starting with '/' has one added
122 * 8. Any dot segments (. or ..) in the path are resolved and removed
123 * 9. IPv6 host literals are allowed (but not normalized or validated)
125 * The rules are based on information in RFC 3986.
127 * Please note this function requires a full URL including a scheme
128 * and host part (except for file: URLs which may have an empty host).
130 * The return value is a newly allocated string that must be freed
131 * or NULL if the url is not valid.
133 * If out_info is non-NULL, the url and err fields therein will always
134 * be set. If a non-NULL value is returned, it will be stored in
135 * out_info->url as well, out_info->err will be set to NULL and the
136 * other fields of *out_info will also be filled in. If a NULL value
137 * is returned, NULL will be stored in out_info->url and out_info->err
138 * will be set to a brief, translated, error message, but no other
139 * fields will be filled in.
141 * This is NOT a URL validation function. Full URL validation is NOT
142 * performed. Some invalid host names are passed through this function
143 * undetected. However, most all other problems that make a URL invalid
144 * will be detected (including a missing host for non file: URLs).
147 size_t url_len = strlen(url);
148 struct strbuf norm;
149 size_t spanned;
150 size_t scheme_len, user_off=0, user_len=0, passwd_off=0, passwd_len=0;
151 size_t host_off=0, host_len=0, port_off=0, port_len=0, path_off, path_len, result_len;
152 const char *slash_ptr, *at_ptr, *colon_ptr, *path_start;
153 char *result;
156 * Copy lowercased scheme and :// suffix, %-escapes are not allowed
157 * First character of scheme must be URL_ALPHA
159 spanned = strspn(url, URL_SCHEME_CHARS);
160 if (!spanned || !isalpha(url[0]) || spanned + 3 > url_len ||
161 url[spanned] != ':' || url[spanned+1] != '/' || url[spanned+2] != '/') {
162 if (out_info) {
163 out_info->url = NULL;
164 out_info->err = _("invalid URL scheme name or missing '://' suffix");
166 return NULL; /* Bad scheme and/or missing "://" part */
168 strbuf_init(&norm, url_len);
169 scheme_len = spanned;
170 spanned += 3;
171 url_len -= spanned;
172 while (spanned--)
173 strbuf_addch(&norm, tolower(*url++));
177 * Copy any username:password if present normalizing %-escapes
179 at_ptr = strchr(url, '@');
180 slash_ptr = url + strcspn(url, "/?#");
181 if (at_ptr && at_ptr < slash_ptr) {
182 user_off = norm.len;
183 if (at_ptr > url) {
184 if (!append_normalized_escapes(&norm, url, at_ptr - url,
185 "", URL_RESERVED)) {
186 if (out_info) {
187 out_info->url = NULL;
188 out_info->err = _("invalid %XX escape sequence");
190 strbuf_release(&norm);
191 return NULL;
193 colon_ptr = strchr(norm.buf + scheme_len + 3, ':');
194 if (colon_ptr) {
195 passwd_off = (colon_ptr + 1) - norm.buf;
196 passwd_len = norm.len - passwd_off;
197 user_len = (passwd_off - 1) - (scheme_len + 3);
198 } else {
199 user_len = norm.len - (scheme_len + 3);
202 strbuf_addch(&norm, '@');
203 url_len -= (++at_ptr - url);
204 url = at_ptr;
209 * Copy the host part excluding any port part, no %-escapes allowed
211 if (!url_len || strchr(":/?#", *url)) {
212 /* Missing host invalid for all URL schemes except file */
213 if (!starts_with(norm.buf, "file:")) {
214 if (out_info) {
215 out_info->url = NULL;
216 out_info->err = _("missing host and scheme is not 'file:'");
218 strbuf_release(&norm);
219 return NULL;
221 } else {
222 host_off = norm.len;
224 colon_ptr = slash_ptr - 1;
225 while (colon_ptr > url && *colon_ptr != ':' && *colon_ptr != ']')
226 colon_ptr--;
227 if (*colon_ptr != ':') {
228 colon_ptr = slash_ptr;
229 } else if (!host_off && colon_ptr < slash_ptr && colon_ptr + 1 != slash_ptr) {
230 /* file: URLs may not have a port number */
231 if (out_info) {
232 out_info->url = NULL;
233 out_info->err = _("a 'file:' URL may not have a port number");
235 strbuf_release(&norm);
236 return NULL;
239 if (allow_globs)
240 spanned = strspn(url, URL_HOST_CHARS "*");
241 else
242 spanned = strspn(url, URL_HOST_CHARS);
244 if (spanned < colon_ptr - url) {
245 /* Host name has invalid characters */
246 if (out_info) {
247 out_info->url = NULL;
248 out_info->err = _("invalid characters in host name");
250 strbuf_release(&norm);
251 return NULL;
253 while (url < colon_ptr) {
254 strbuf_addch(&norm, tolower(*url++));
255 url_len--;
260 * Check the port part and copy if not the default (after removing any
261 * leading 0s); no %-escapes allowed
263 if (colon_ptr < slash_ptr) {
264 /* skip the ':' and leading 0s but not the last one if all 0s */
265 url++;
266 url += strspn(url, "0");
267 if (url == slash_ptr && url[-1] == '0')
268 url--;
269 if (url == slash_ptr) {
270 /* Skip ":" port with no number, it's same as default */
271 } else if (slash_ptr - url == 2 &&
272 starts_with(norm.buf, "http:") &&
273 !strncmp(url, "80", 2)) {
274 /* Skip http :80 as it's the default */
275 } else if (slash_ptr - url == 3 &&
276 starts_with(norm.buf, "https:") &&
277 !strncmp(url, "443", 3)) {
278 /* Skip https :443 as it's the default */
279 } else {
281 * Port number must be all digits with leading 0s removed
282 * and since all the protocols we deal with have a 16-bit
283 * port number it must also be in the range 1..65535
284 * 0 is not allowed because that means "next available"
285 * on just about every system and therefore cannot be used
287 unsigned long pnum = 0;
288 spanned = strspn(url, URL_DIGIT);
289 if (spanned < slash_ptr - url) {
290 /* port number has invalid characters */
291 if (out_info) {
292 out_info->url = NULL;
293 out_info->err = _("invalid port number");
295 strbuf_release(&norm);
296 return NULL;
298 if (slash_ptr - url <= 5)
299 pnum = strtoul(url, NULL, 10);
300 if (pnum == 0 || pnum > 65535) {
301 /* port number not in range 1..65535 */
302 if (out_info) {
303 out_info->url = NULL;
304 out_info->err = _("invalid port number");
306 strbuf_release(&norm);
307 return NULL;
309 strbuf_addch(&norm, ':');
310 port_off = norm.len;
311 strbuf_add(&norm, url, slash_ptr - url);
312 port_len = slash_ptr - url;
314 url_len -= slash_ptr - colon_ptr;
315 url = slash_ptr;
317 if (host_off)
318 host_len = norm.len - host_off - (port_len ? port_len + 1 : 0);
322 * Now copy the path resolving any . and .. segments being careful not
323 * to corrupt the URL by unescaping any delimiters, but do add an
324 * initial '/' if it's missing and do normalize any %-escape sequences.
326 path_off = norm.len;
327 path_start = norm.buf + path_off;
328 strbuf_addch(&norm, '/');
329 if (*url == '/') {
330 url++;
331 url_len--;
333 for (;;) {
334 const char *seg_start;
335 size_t seg_start_off = norm.len;
336 const char *next_slash = url + strcspn(url, "/?#");
337 int skip_add_slash = 0;
340 * RFC 3689 indicates that any . or .. segments should be
341 * unescaped before being checked for.
343 if (!append_normalized_escapes(&norm, url, next_slash - url, "",
344 URL_RESERVED)) {
345 if (out_info) {
346 out_info->url = NULL;
347 out_info->err = _("invalid %XX escape sequence");
349 strbuf_release(&norm);
350 return NULL;
353 seg_start = norm.buf + seg_start_off;
354 if (!strcmp(seg_start, ".")) {
355 /* ignore a . segment; be careful not to remove initial '/' */
356 if (seg_start == path_start + 1) {
357 strbuf_setlen(&norm, norm.len - 1);
358 skip_add_slash = 1;
359 } else {
360 strbuf_setlen(&norm, norm.len - 2);
362 } else if (!strcmp(seg_start, "..")) {
364 * ignore a .. segment and remove the previous segment;
365 * be careful not to remove initial '/' from path
367 const char *prev_slash = norm.buf + norm.len - 3;
368 if (prev_slash == path_start) {
369 /* invalid .. because no previous segment to remove */
370 if (out_info) {
371 out_info->url = NULL;
372 out_info->err = _("invalid '..' path segment");
374 strbuf_release(&norm);
375 return NULL;
377 while (*--prev_slash != '/') {}
378 if (prev_slash == path_start) {
379 strbuf_setlen(&norm, prev_slash - norm.buf + 1);
380 skip_add_slash = 1;
381 } else {
382 strbuf_setlen(&norm, prev_slash - norm.buf);
385 url_len -= next_slash - url;
386 url = next_slash;
387 /* if the next char is not '/' done with the path */
388 if (*url != '/')
389 break;
390 url++;
391 url_len--;
392 if (!skip_add_slash)
393 strbuf_addch(&norm, '/');
395 path_len = norm.len - path_off;
399 * Now simply copy the rest, if any, only normalizing %-escapes and
400 * being careful not to corrupt the URL by unescaping any delimiters.
402 if (*url) {
403 if (!append_normalized_escapes(&norm, url, url_len, "", URL_RESERVED)) {
404 if (out_info) {
405 out_info->url = NULL;
406 out_info->err = _("invalid %XX escape sequence");
408 strbuf_release(&norm);
409 return NULL;
414 result = strbuf_detach(&norm, &result_len);
415 if (out_info) {
416 out_info->url = result;
417 out_info->err = NULL;
418 out_info->url_len = result_len;
419 out_info->scheme_len = scheme_len;
420 out_info->user_off = user_off;
421 out_info->user_len = user_len;
422 out_info->passwd_off = passwd_off;
423 out_info->passwd_len = passwd_len;
424 out_info->host_off = host_off;
425 out_info->host_len = host_len;
426 out_info->port_off = port_off;
427 out_info->port_len = port_len;
428 out_info->path_off = path_off;
429 out_info->path_len = path_len;
431 return result;
434 char *url_normalize(const char *url, struct url_info *out_info)
436 return url_normalize_1(url, out_info, 0);
439 static size_t url_match_prefix(const char *url,
440 const char *url_prefix,
441 size_t url_prefix_len)
444 * url_prefix matches url if url_prefix is an exact match for url or it
445 * is a prefix of url and the match ends on a path component boundary.
446 * Both url and url_prefix are considered to have an implicit '/' on the
447 * end for matching purposes if they do not already.
449 * url must be NUL terminated. url_prefix_len is the length of
450 * url_prefix which need not be NUL terminated.
452 * The return value is the length of the match in characters (including
453 * the final '/' even if it's implicit) or 0 for no match.
455 * Passing NULL as url and/or url_prefix will always cause 0 to be
456 * returned without causing any faults.
458 if (!url || !url_prefix)
459 return 0;
460 if (!url_prefix_len || (url_prefix_len == 1 && *url_prefix == '/'))
461 return (!*url || *url == '/') ? 1 : 0;
462 if (url_prefix[url_prefix_len - 1] == '/')
463 url_prefix_len--;
464 if (strncmp(url, url_prefix, url_prefix_len))
465 return 0;
466 if ((strlen(url) == url_prefix_len) || (url[url_prefix_len] == '/'))
467 return url_prefix_len + 1;
468 return 0;
471 static int match_urls(const struct url_info *url,
472 const struct url_info *url_prefix,
473 struct urlmatch_item *match)
476 * url_prefix matches url if the scheme, host and port of url_prefix
477 * are the same as those of url and the path portion of url_prefix
478 * is the same as the path portion of url or it is a prefix that
479 * matches at a '/' boundary. If url_prefix contains a user name,
480 * that must also exactly match the user name in url.
482 * If the user, host, port and path match in this fashion, the returned
483 * value is the length of the path match including any implicit
484 * final '/'. For example, "http://me@example.com/path" is matched by
485 * "http://example.com" with a path length of 1.
487 * If there is a match and exactusermatch is not NULL, then
488 * *exactusermatch will be set to true if both url and url_prefix
489 * contained a user name or false if url_prefix did not have a
490 * user name. If there is no match *exactusermatch is left untouched.
492 char usermatched = 0;
493 size_t pathmatchlen;
495 if (!url || !url_prefix || !url->url || !url_prefix->url)
496 return 0;
498 /* check the scheme */
499 if (url_prefix->scheme_len != url->scheme_len ||
500 strncmp(url->url, url_prefix->url, url->scheme_len))
501 return 0; /* schemes do not match */
503 /* check the user name if url_prefix has one */
504 if (url_prefix->user_off) {
505 if (!url->user_off || url->user_len != url_prefix->user_len ||
506 strncmp(url->url + url->user_off,
507 url_prefix->url + url_prefix->user_off,
508 url->user_len))
509 return 0; /* url_prefix has a user but it's not a match */
510 usermatched = 1;
513 /* check the host */
514 if (!match_host(url, url_prefix))
515 return 0; /* host names do not match */
517 /* check the port */
518 if (url_prefix->port_len != url->port_len ||
519 strncmp(url->url + url->port_off,
520 url_prefix->url + url_prefix->port_off, url->port_len))
521 return 0; /* ports do not match */
523 /* check the path */
524 pathmatchlen = url_match_prefix(
525 url->url + url->path_off,
526 url_prefix->url + url_prefix->path_off,
527 url_prefix->url_len - url_prefix->path_off);
528 if (!pathmatchlen)
529 return 0; /* paths do not match */
531 if (match) {
532 match->hostmatch_len = url_prefix->host_len;
533 match->pathmatch_len = pathmatchlen;
534 match->user_matched = usermatched;
537 return 1;
540 static int cmp_matches(const struct urlmatch_item *a,
541 const struct urlmatch_item *b)
543 if (a->hostmatch_len != b->hostmatch_len)
544 return a->hostmatch_len < b->hostmatch_len ? -1 : 1;
545 if (a->pathmatch_len != b->pathmatch_len)
546 return a->pathmatch_len < b->pathmatch_len ? -1 : 1;
547 if (a->user_matched != b->user_matched)
548 return b->user_matched ? -1 : 1;
549 return 0;
552 int urlmatch_config_entry(const char *var, const char *value, void *cb)
554 struct string_list_item *item;
555 struct urlmatch_config *collect = cb;
556 struct urlmatch_item matched = {0};
557 struct url_info *url = &collect->url;
558 const char *key, *dot;
559 struct strbuf synthkey = STRBUF_INIT;
560 int retval;
561 int (*select_fn)(const struct urlmatch_item *a, const struct urlmatch_item *b) =
562 collect->select_fn ? collect->select_fn : cmp_matches;
564 if (!skip_prefix(var, collect->section, &key) || *(key++) != '.') {
565 if (collect->cascade_fn)
566 return collect->cascade_fn(var, value, cb);
567 return 0; /* not interested */
569 dot = strrchr(key, '.');
570 if (dot) {
571 char *config_url, *norm_url;
572 struct url_info norm_info;
574 config_url = xmemdupz(key, dot - key);
575 norm_url = url_normalize_1(config_url, &norm_info, 1);
576 if (norm_url)
577 retval = match_urls(url, &norm_info, &matched);
578 else if (collect->fallback_match_fn)
579 retval = collect->fallback_match_fn(config_url,
580 collect->cb);
581 else
582 retval = 0;
583 free(config_url);
584 free(norm_url);
585 if (!retval)
586 return 0;
587 key = dot + 1;
590 if (collect->key && strcmp(key, collect->key))
591 return 0;
593 item = string_list_insert(&collect->vars, key);
594 if (!item->util) {
595 item->util = xcalloc(1, sizeof(matched));
596 } else {
597 if (select_fn(&matched, item->util) < 0)
599 * Our match is worse than the old one,
600 * we cannot use it.
602 return 0;
603 /* Otherwise, replace it with this one. */
606 memcpy(item->util, &matched, sizeof(matched));
607 strbuf_addstr(&synthkey, collect->section);
608 strbuf_addch(&synthkey, '.');
609 strbuf_addstr(&synthkey, key);
610 retval = collect->collect_fn(synthkey.buf, value, collect->cb);
612 strbuf_release(&synthkey);
613 return retval;
616 void urlmatch_config_release(struct urlmatch_config *config)
618 string_list_clear(&config->vars, 1);