Coverage Report

Created: 2026-10-17 07:15

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