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