Coverage Report

Created: 2025-08-28 06:48

/src/tinysparql/subprojects/glib-2.80.3/glib/guri.c
Line
Count
Source (jump to first uncovered line)
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright © 2020 Red Hat, Inc.
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General
17
 * Public License along with this library; if not, see
18
 * <http://www.gnu.org/licenses/>.
19
 */
20
21
#include "config.h"
22
23
#include <stdlib.h>
24
#include <string.h>
25
26
#include "glib.h"
27
#include "glibintl.h"
28
#include "glib-private.h"
29
#include "guriprivate.h"
30
31
/**
32
 * GUri:
33
 *
34
 * The `GUri` type and related functions can be used to parse URIs into
35
 * their components, and build valid URIs from individual components.
36
 *
37
 * Since `GUri` only represents absolute URIs, all `GUri`s will have a
38
 * URI scheme, so [method@GLib.Uri.get_scheme] will always return a non-`NULL`
39
 * answer. Likewise, by definition, all URIs have a path component, so
40
 * [method@GLib.Uri.get_path] will always return a non-`NULL` string (which may
41
 * be empty).
42
 *
43
 * If the URI string has an
44
 * [‘authority’ component](https://tools.ietf.org/html/rfc3986#section-3) (that
45
 * is, if the scheme is followed by `://` rather than just `:`), then the
46
 * `GUri` will contain a hostname, and possibly a port and ‘userinfo’.
47
 * Additionally, depending on how the `GUri` was constructed/parsed (for example,
48
 * using the `G_URI_FLAGS_HAS_PASSWORD` and `G_URI_FLAGS_HAS_AUTH_PARAMS` flags),
49
 * the userinfo may be split out into a username, password, and
50
 * additional authorization-related parameters.
51
 *
52
 * Normally, the components of a `GUri` will have all `%`-encoded
53
 * characters decoded. However, if you construct/parse a `GUri` with
54
 * `G_URI_FLAGS_ENCODED`, then the `%`-encoding will be preserved instead in
55
 * the userinfo, path, and query fields (and in the host field if also
56
 * created with `G_URI_FLAGS_NON_DNS`). In particular, this is necessary if
57
 * the URI may contain binary data or non-UTF-8 text, or if decoding
58
 * the components might change the interpretation of the URI.
59
 *
60
 * For example, with the encoded flag:
61
 *
62
 * ```c
63
 * g_autoptr(GUri) uri = g_uri_parse ("http://host/path?query=http%3A%2F%2Fhost%2Fpath%3Fparam%3Dvalue", G_URI_FLAGS_ENCODED, &err);
64
 * g_assert_cmpstr (g_uri_get_query (uri), ==, "query=http%3A%2F%2Fhost%2Fpath%3Fparam%3Dvalue");
65
 * ```
66
 *
67
 * While the default `%`-decoding behaviour would give:
68
 *
69
 * ```c
70
 * g_autoptr(GUri) uri = g_uri_parse ("http://host/path?query=http%3A%2F%2Fhost%2Fpath%3Fparam%3Dvalue", G_URI_FLAGS_NONE, &err);
71
 * g_assert_cmpstr (g_uri_get_query (uri), ==, "query=http://host/path?param=value");
72
 * ```
73
 *
74
 * During decoding, if an invalid UTF-8 string is encountered, parsing will fail
75
 * with an error indicating the bad string location:
76
 *
77
 * ```c
78
 * g_autoptr(GUri) uri = g_uri_parse ("http://host/path?query=http%3A%2F%2Fhost%2Fpath%3Fbad%3D%00alue", G_URI_FLAGS_NONE, &err);
79
 * g_assert_error (err, G_URI_ERROR, G_URI_ERROR_BAD_QUERY);
80
 * ```
81
 *
82
 * You should pass `G_URI_FLAGS_ENCODED` or `G_URI_FLAGS_ENCODED_QUERY` if you
83
 * need to handle that case manually. In particular, if the query string
84
 * contains `=` characters that are `%`-encoded, you should let
85
 * [func@GLib.Uri.parse_params] do the decoding once of the query.
86
 *
87
 * `GUri` is immutable once constructed, and can safely be accessed from
88
 * multiple threads. Its reference counting is atomic.
89
 *
90
 * Note that the scope of `GUri` is to help manipulate URIs in various applications,
91
 * following [RFC 3986](https://tools.ietf.org/html/rfc3986). In particular,
92
 * it doesn't intend to cover web browser needs, and doesn’t implement the
93
 * [WHATWG URL](https://url.spec.whatwg.org/) standard. No APIs are provided to
94
 * help prevent
95
 * [homograph attacks](https://en.wikipedia.org/wiki/IDN_homograph_attack), so
96
 * `GUri` is not suitable for formatting URIs for display to the user for making
97
 * security-sensitive decisions.
98
 *
99
 * ## Relative and absolute URIs
100
 *
101
 * As defined in [RFC 3986](https://tools.ietf.org/html/rfc3986#section-4), the
102
 * hierarchical nature of URIs means that they can either be ‘relative
103
 * references’ (sometimes referred to as ‘relative URIs’) or ‘URIs’ (for
104
 * clarity, ‘URIs’ are referred to in this documentation as
105
 * ‘absolute URIs’ — although
106
 * [in constrast to RFC 3986](https://tools.ietf.org/html/rfc3986#section-4.3),
107
 * fragment identifiers are always allowed).
108
 *
109
 * Relative references have one or more components of the URI missing. In
110
 * particular, they have no scheme. Any other component, such as hostname,
111
 * query, etc. may be missing, apart from a path, which has to be specified (but
112
 * may be empty). The path may be relative, starting with `./` rather than `/`.
113
 *
114
 * For example, a valid relative reference is `./path?query`,
115
 * `/?query#fragment` or `//example.com`.
116
 *
117
 * Absolute URIs have a scheme specified. Any other components of the URI which
118
 * are missing are specified as explicitly unset in the URI, rather than being
119
 * resolved relative to a base URI using [method@GLib.Uri.parse_relative].
120
 *
121
 * For example, a valid absolute URI is `file:///home/bob` or
122
 * `https://search.com?query=string`.
123
 *
124
 * A `GUri` instance is always an absolute URI. A string may be an absolute URI
125
 * or a relative reference; see the documentation for individual functions as to
126
 * what forms they accept.
127
 *
128
 * ## Parsing URIs
129
 *
130
 * The most minimalist APIs for parsing URIs are [func@GLib.Uri.split] and
131
 * [func@GLib.Uri.split_with_user]. These split a URI into its component
132
 * parts, and return the parts; the difference between the two is that
133
 * [func@GLib.Uri.split] treats the ‘userinfo’ component of the URI as a
134
 * single element, while [func@GLib.Uri.split_with_user] can (depending on the
135
 * [flags@GLib.UriFlags] you pass) treat it as containing a username, password,
136
 * and authentication parameters. Alternatively, [func@GLib.Uri.split_network]
137
 * can be used when you are only interested in the components that are
138
 * needed to initiate a network connection to the service (scheme,
139
 * host, and port).
140
 *
141
 * [func@GLib.Uri.parse] is similar to [func@GLib.Uri.split], but instead of
142
 * returning individual strings, it returns a `GUri` structure (and it requires
143
 * that the URI be an absolute URI).
144
 *
145
 * [func@GLib.Uri.resolve_relative] and [method@GLib.Uri.parse_relative] allow
146
 * you to resolve a relative URI relative to a base URI.
147
 * [func@GLib.Uri.resolve_relative] takes two strings and returns a string,
148
 * and [method@GLib.Uri.parse_relative] takes a `GUri` and a string and returns a
149
 * `GUri`.
150
 *
151
 * All of the parsing functions take a [flags@GLib.UriFlags] argument describing
152
 * exactly how to parse the URI; see the documentation for that type
153
 * for more details on the specific flags that you can pass. If you
154
 * need to choose different flags based on the type of URI, you can
155
 * use [func@GLib.Uri.peek_scheme] on the URI string to check the scheme
156
 * first, and use that to decide what flags to parse it with.
157
 *
158
 * For example, you might want to use `G_URI_PARAMS_WWW_FORM` when parsing the
159
 * params for a web URI, so compare the result of [func@GLib.Uri.peek_scheme]
160
 * against `http` and `https`.
161
 *
162
 * ## Building URIs
163
 *
164
 * [func@GLib.Uri.join] and [func@GLib.Uri.join_with_user] can be used to construct
165
 * valid URI strings from a set of component strings. They are the
166
 * inverse of [func@GLib.Uri.split] and [func@GLib.Uri.split_with_user].
167
 *
168
 * Similarly, [func@GLib.Uri.build] and [func@GLib.Uri.build_with_user] can be
169
 * used to construct a `GUri` from a set of component strings.
170
 *
171
 * As with the parsing functions, the building functions take a
172
 * [flags@GLib.UriFlags] argument. In particular, it is important to keep in mind
173
 * whether the URI components you are using are already `%`-encoded. If so,
174
 * you must pass the `G_URI_FLAGS_ENCODED` flag.
175
 *
176
 * ## `file://` URIs
177
 *
178
 * Note that Windows and Unix both define special rules for parsing
179
 * `file://` URIs (involving non-UTF-8 character sets on Unix, and the
180
 * interpretation of path separators on Windows). `GUri` does not
181
 * implement these rules. Use [func@GLib.filename_from_uri] and
182
 * [func@GLib.filename_to_uri] if you want to properly convert between
183
 * `file://` URIs and local filenames.
184
 *
185
 * ## URI Equality
186
 *
187
 * Note that there is no `g_uri_equal ()` function, because comparing
188
 * URIs usefully requires scheme-specific knowledge that `GUri` does
189
 * not have. `GUri` can help with normalization if you use the various
190
 * encoded [flags@GLib.UriFlags] as well as `G_URI_FLAGS_SCHEME_NORMALIZE`
191
 * however it is not comprehensive.
192
 * For example, `data:,foo` and `data:;base64,Zm9v` resolve to the same
193
 * thing according to the `data:` URI specification which GLib does not
194
 * handle.
195
 *
196
 * Since: 2.66
197
 */
198
struct _GUri {
199
  gchar     *scheme;
200
  gchar     *userinfo;
201
  gchar     *host;
202
  gint       port;
203
  gchar     *path;
204
  gchar     *query;
205
  gchar     *fragment;
206
207
  gchar     *user;
208
  gchar     *password;
209
  gchar     *auth_params;
210
211
  GUriFlags  flags;
212
};
213
214
/**
215
 * g_uri_ref: (skip)
216
 * @uri: a #GUri
217
 *
218
 * Increments the reference count of @uri by one.
219
 *
220
 * Returns: @uri
221
 *
222
 * Since: 2.66
223
 */
224
GUri *
225
g_uri_ref (GUri *uri)
226
0
{
227
0
  g_return_val_if_fail (uri != NULL, NULL);
228
229
0
  return g_atomic_rc_box_acquire (uri);
230
0
}
231
232
static void
233
g_uri_clear (GUri *uri)
234
0
{
235
0
  g_free (uri->scheme);
236
0
  g_free (uri->userinfo);
237
0
  g_free (uri->host);
238
0
  g_free (uri->path);
239
0
  g_free (uri->query);
240
0
  g_free (uri->fragment);
241
0
  g_free (uri->user);
242
0
  g_free (uri->password);
243
0
  g_free (uri->auth_params);
244
0
}
245
246
/**
247
 * g_uri_unref: (skip)
248
 * @uri: a #GUri
249
 *
250
 * Atomically decrements the reference count of @uri by one.
251
 *
252
 * When the reference count reaches zero, the resources allocated by
253
 * @uri are freed
254
 *
255
 * Since: 2.66
256
 */
257
void
258
g_uri_unref (GUri *uri)
259
0
{
260
0
  g_return_if_fail (uri != NULL);
261
262
0
  g_atomic_rc_box_release_full (uri, (GDestroyNotify)g_uri_clear);
263
0
}
264
265
static gboolean
266
g_uri_char_is_unreserved (gchar ch)
267
25.0M
{
268
25.0M
  if (g_ascii_isalnum (ch))
269
21.4M
    return TRUE;
270
3.59M
  return ch == '-' || ch == '.' || ch == '_' || ch == '~';
271
25.0M
}
272
273
9.26k
#define XDIGIT(c) ((c) <= '9' ? (c) - '0' : ((c) & 0x4F) - 'A' + 10)
274
4.63k
#define HEXCHAR(s) ((XDIGIT (s[1]) << 4) + XDIGIT (s[2]))
275
276
static gssize
277
uri_decoder (gchar       **out,
278
             const gchar  *illegal_chars,
279
             const gchar  *start,
280
             gsize         length,
281
             gboolean      just_normalize,
282
             gboolean      www_form,
283
             GUriFlags     flags,
284
             GUriError     parse_error,
285
             GError      **error)
286
93.1k
{
287
93.1k
  gchar c;
288
93.1k
  GString *decoded;
289
93.1k
  const gchar *invalid, *s, *end;
290
93.1k
  gssize len;
291
292
93.1k
  if (!(flags & G_URI_FLAGS_ENCODED))
293
68.3k
    just_normalize = FALSE;
294
295
93.1k
  decoded = g_string_sized_new (length + 1);
296
20.4M
  for (s = start, end = s + length; s < end; s++)
297
20.3M
    {
298
20.3M
      if (*s == '%')
299
4.66k
        {
300
4.66k
          if (s + 2 >= end ||
301
4.66k
              !g_ascii_isxdigit (s[1]) ||
302
4.66k
              !g_ascii_isxdigit (s[2]))
303
35
            {
304
              /* % followed by non-hex or the end of the string; this is an error */
305
35
              if (!(flags & G_URI_FLAGS_PARSE_RELAXED))
306
35
                {
307
35
                  g_set_error_literal (error, G_URI_ERROR, parse_error,
308
                                       /* xgettext: no-c-format */
309
35
                                       _("Invalid %-encoding in URI"));
310
35
                  g_string_free (decoded, TRUE);
311
35
                  return -1;
312
35
                }
313
314
              /* In non-strict mode, just let it through; we *don't*
315
               * fix it to "%25", since that might change the way that
316
               * the URI's owner would interpret it.
317
               */
318
0
              g_string_append_c (decoded, *s);
319
0
              continue;
320
35
            }
321
322
4.63k
          c = HEXCHAR (s);
323
4.63k
          if (illegal_chars && strchr (illegal_chars, c))
324
0
            {
325
0
              g_set_error_literal (error, G_URI_ERROR, parse_error,
326
0
                                   _("Illegal character in URI"));
327
0
              g_string_free (decoded, TRUE);
328
0
              return -1;
329
0
            }
330
4.63k
          if (just_normalize && !g_uri_char_is_unreserved (c))
331
0
            {
332
              /* Leave the % sequence there but normalize it. */
333
0
              g_string_append_c (decoded, *s);
334
0
              g_string_append_c (decoded, g_ascii_toupper (s[1]));
335
0
              g_string_append_c (decoded, g_ascii_toupper (s[2]));
336
0
              s += 2;
337
0
            }
338
4.63k
          else
339
4.63k
            {
340
4.63k
              g_string_append_c (decoded, c);
341
4.63k
              s += 2;
342
4.63k
            }
343
4.63k
        }
344
20.3M
      else if (www_form && *s == '+')
345
0
        g_string_append_c (decoded, ' ');
346
      /* Normalize any illegal characters. */
347
20.3M
      else if (just_normalize && (!g_ascii_isgraph (*s)))
348
0
        g_string_append_printf (decoded, "%%%02X", (guchar)*s);
349
20.3M
      else
350
20.3M
        g_string_append_c (decoded, *s);
351
20.3M
    }
352
353
93.1k
  len = decoded->len;
354
93.1k
  g_assert (len >= 0);
355
356
93.1k
  if (!(flags & G_URI_FLAGS_ENCODED) &&
357
93.1k
      !g_utf8_validate (decoded->str, len, &invalid))
358
220
    {
359
220
      g_set_error_literal (error, G_URI_ERROR, parse_error,
360
220
                           _("Non-UTF-8 characters in URI"));
361
220
      g_string_free (decoded, TRUE);
362
220
      return -1;
363
220
    }
364
365
92.8k
  if (out)
366
32.8k
    *out = g_string_free (decoded, FALSE);
367
60.0k
  else
368
60.0k
    g_string_free (decoded, TRUE);
369
370
92.8k
  return len;
371
93.1k
}
372
373
static gboolean
374
uri_decode (gchar       **out,
375
            const gchar  *illegal_chars,
376
            const gchar  *start,
377
            gsize         length,
378
            gboolean      www_form,
379
            GUriFlags     flags,
380
            GUriError     parse_error,
381
            GError      **error)
382
0
{
383
0
  return uri_decoder (out, illegal_chars, start, length, FALSE, www_form, flags,
384
0
                      parse_error, error) != -1;
385
0
}
386
387
static gboolean
388
uri_normalize (gchar       **out,
389
               const gchar  *start,
390
               gsize         length,
391
               GUriFlags     flags,
392
               GUriError     parse_error,
393
               GError      **error)
394
68.3k
{
395
68.3k
  return uri_decoder (out, NULL, start, length, TRUE, FALSE, flags,
396
68.3k
                      parse_error, error) != -1;
397
68.3k
}
398
399
static gboolean
400
is_valid (guchar       c,
401
          const gchar *reserved_chars_allowed)
402
25.0M
{
403
25.0M
  if (g_uri_char_is_unreserved (c))
404
22.4M
    return TRUE;
405
406
2.57M
  if (reserved_chars_allowed && strchr (reserved_chars_allowed, c))
407
2.57M
    return TRUE;
408
409
0
  return FALSE;
410
2.57M
}
411
412
void
413
_uri_encoder (GString      *out,
414
              const guchar *start,
415
              gsize         length,
416
              const gchar  *reserved_chars_allowed,
417
              gboolean      allow_utf8)
418
528k
{
419
528k
  static const gchar hex[] = "0123456789ABCDEF";
420
528k
  const guchar *p = start;
421
528k
  const guchar *end = p + length;
422
423
25.5M
  while (p < end)
424
25.0M
    {
425
25.0M
      gunichar multibyte_utf8_char = 0;
426
427
25.0M
      if (allow_utf8 && *p >= 0x80)
428
0
        multibyte_utf8_char = g_utf8_get_char_validated ((gchar *)p, end - p);
429
430
25.0M
      if (multibyte_utf8_char > 0 &&
431
25.0M
          multibyte_utf8_char != (gunichar) -1 && multibyte_utf8_char != (gunichar) -2)
432
0
        {
433
0
          gint len = g_utf8_skip [*p];
434
0
          g_string_append_len (out, (gchar *)p, len);
435
0
          p += len;
436
0
        }
437
25.0M
      else if (is_valid (*p, reserved_chars_allowed))
438
25.0M
        {
439
25.0M
          g_string_append_c (out, *p);
440
25.0M
          p++;
441
25.0M
        }
442
0
      else
443
0
        {
444
0
          g_string_append_c (out, '%');
445
0
          g_string_append_c (out, hex[*p >> 4]);
446
0
          g_string_append_c (out, hex[*p & 0xf]);
447
0
          p++;
448
0
        }
449
25.0M
    }
450
528k
}
451
452
/* Parse the IP-literal construction from RFC 6874 (which extends RFC 3986 to
453
 * support IPv6 zone identifiers.
454
 *
455
 * Currently, IP versions beyond 6 (i.e. the IPvFuture rule) are unsupported.
456
 * There’s no point supporting them until (a) they exist and (b) the rest of the
457
 * stack (notably, sockets) supports them.
458
 *
459
 * Rules:
460
 *
461
 * IP-literal = "[" ( IPv6address / IPv6addrz / IPvFuture  ) "]"
462
 *
463
 * ZoneID = 1*( unreserved / pct-encoded )
464
 *
465
 * IPv6addrz = IPv6address "%25" ZoneID
466
 *
467
 * If %G_URI_FLAGS_PARSE_RELAXED is specified, this function also accepts:
468
 *
469
 * IPv6addrz = IPv6address "%" ZoneID
470
 */
471
static gboolean
472
parse_ip_literal (const gchar  *start,
473
                  gsize         length,
474
                  GUriFlags     flags,
475
                  gchar       **out,
476
                  GError      **error)
477
49
{
478
49
  gchar *pct, *zone_id = NULL;
479
49
  gchar *addr = NULL;
480
49
  gsize addr_length = 0;
481
49
  gsize zone_id_length = 0;
482
49
  gchar *decoded_zone_id = NULL;
483
484
49
  if (start[length - 1] != ']')
485
9
    goto bad_ipv6_literal;
486
487
  /* Drop the square brackets */
488
40
  addr = g_strndup (start + 1, length - 2);
489
40
  addr_length = length - 2;
490
491
  /* If there's an IPv6 scope ID, split out the zone. */
492
40
  pct = strchr (addr, '%');
493
40
  if (pct != NULL)
494
9
    {
495
9
      *pct = '\0';
496
497
9
      if (addr_length - (pct - addr) >= 4 &&
498
9
          *(pct + 1) == '2' && *(pct + 2) == '5')
499
1
        {
500
1
          zone_id = pct + 3;
501
1
          zone_id_length = addr_length - (zone_id - addr);
502
1
        }
503
8
      else if (flags & G_URI_FLAGS_PARSE_RELAXED &&
504
8
               addr_length - (pct - addr) >= 2)
505
0
        {
506
0
          zone_id = pct + 1;
507
0
          zone_id_length = addr_length - (zone_id - addr);
508
0
        }
509
8
      else
510
8
        goto bad_ipv6_literal;
511
512
9
      g_assert (zone_id_length >= 1);
513
1
    }
514
515
  /* addr must be an IPv6 address */
516
32
  if (!g_hostname_is_ip_address (addr) || !strchr (addr, ':'))
517
31
    goto bad_ipv6_literal;
518
519
  /* Zone ID must be valid. It can contain %-encoded characters. */
520
1
  if (zone_id != NULL &&
521
1
      !uri_decode (&decoded_zone_id, NULL, zone_id, zone_id_length, FALSE,
522
0
                   flags, G_URI_ERROR_BAD_HOST, NULL))
523
0
    goto bad_ipv6_literal;
524
525
  /* Success */
526
1
  if (out != NULL && decoded_zone_id != NULL)
527
0
    *out = g_strconcat (addr, "%", decoded_zone_id, NULL);
528
1
  else if (out != NULL)
529
1
    *out = g_steal_pointer (&addr);
530
531
1
  g_free (addr);
532
1
  g_free (decoded_zone_id);
533
534
1
  return TRUE;
535
536
48
bad_ipv6_literal:
537
48
  g_free (addr);
538
48
  g_free (decoded_zone_id);
539
48
  g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_HOST,
540
48
               _("Invalid IPv6 address ‘%.*s’ in URI"),
541
48
               (gint)length, start);
542
543
48
  return FALSE;
544
1
}
545
546
static gboolean
547
parse_host (const gchar  *start,
548
            gsize         length,
549
            GUriFlags     flags,
550
            gchar       **out,
551
            GError      **error)
552
8.16k
{
553
8.16k
  gchar *decoded = NULL, *host;
554
8.16k
  gchar *addr = NULL;
555
556
8.16k
  if (*start == '[')
557
49
    {
558
49
      if (!parse_ip_literal (start, length, flags, &host, error))
559
48
        return FALSE;
560
1
      goto ok;
561
49
    }
562
563
8.11k
  if (g_ascii_isdigit (*start))
564
974
    {
565
974
      addr = g_strndup (start, length);
566
974
      if (g_hostname_is_ip_address (addr))
567
4
        {
568
4
          host = addr;
569
4
          goto ok;
570
4
        }
571
970
      g_free (addr);
572
970
    }
573
574
8.10k
  if (flags & G_URI_FLAGS_NON_DNS)
575
8.10k
    {
576
8.10k
      if (!uri_normalize (&decoded, start, length, flags,
577
8.10k
                          G_URI_ERROR_BAD_HOST, error))
578
22
        return FALSE;
579
8.08k
      host = g_steal_pointer (&decoded);
580
8.08k
      goto ok;
581
8.10k
    }
582
583
0
  flags &= ~G_URI_FLAGS_ENCODED;
584
0
  if (!uri_decode (&decoded, NULL, start, length, FALSE, flags,
585
0
                   G_URI_ERROR_BAD_HOST, error))
586
0
    return FALSE;
587
588
  /* You're not allowed to %-encode an IP address, so if it wasn't
589
   * one before, it better not be one now.
590
   */
591
0
  if (g_hostname_is_ip_address (decoded))
592
0
    {
593
0
      g_free (decoded);
594
0
      g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_HOST,
595
0
                   _("Illegal encoded IP address ‘%.*s’ in URI"),
596
0
                   (gint)length, start);
597
0
      return FALSE;
598
0
    }
599
600
0
  if (g_hostname_is_non_ascii (decoded))
601
0
    {
602
0
      host = g_hostname_to_ascii (decoded);
603
0
      if (host == NULL)
604
0
        {
605
0
          g_free (decoded);
606
0
          g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_HOST,
607
0
                       _("Illegal internationalized hostname ‘%.*s’ in URI"),
608
0
                       (gint) length, start);
609
0
          return FALSE;
610
0
        }
611
0
    }
612
0
  else
613
0
    {
614
0
      host = g_steal_pointer (&decoded);
615
0
    }
616
617
8.09k
 ok:
618
8.09k
  if (out)
619
0
    *out = g_steal_pointer (&host);
620
8.09k
  g_free (host);
621
8.09k
  g_free (decoded);
622
623
8.09k
  return TRUE;
624
0
}
625
626
static gboolean
627
parse_port (const gchar  *start,
628
            gsize         length,
629
            gint         *out,
630
            GError      **error)
631
226
{
632
226
  gchar *end;
633
226
  gulong parsed_port;
634
635
  /* strtoul() allows leading + or -, so we have to check this first. */
636
226
  if (!g_ascii_isdigit (*start))
637
22
    {
638
22
      g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_PORT,
639
22
                   _("Could not parse port ‘%.*s’ in URI"),
640
22
                   (gint)length, start);
641
22
      return FALSE;
642
22
    }
643
644
  /* We know that *(start + length) is either '\0' or a non-numeric
645
   * character, so strtoul() won't scan beyond it.
646
   */
647
204
  parsed_port = strtoul (start, &end, 10);
648
204
  if (end != start + length)
649
5
    {
650
5
      g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_PORT,
651
5
                   _("Could not parse port ‘%.*s’ in URI"),
652
5
                   (gint)length, start);
653
5
      return FALSE;
654
5
    }
655
199
  else if (parsed_port > 65535)
656
55
    {
657
55
      g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_PORT,
658
55
                   _("Port ‘%.*s’ in URI is out of range"),
659
55
                   (gint)length, start);
660
55
      return FALSE;
661
55
    }
662
663
144
  if (out)
664
0
    *out = parsed_port;
665
144
  return TRUE;
666
204
}
667
668
static gboolean
669
parse_userinfo (const gchar  *start,
670
                gsize         length,
671
                GUriFlags     flags,
672
                gchar       **user,
673
                gchar       **password,
674
                gchar       **auth_params,
675
                GError      **error)
676
1.30k
{
677
1.30k
  const gchar *user_end = NULL, *password_end = NULL, *auth_params_end;
678
679
1.30k
  auth_params_end = start + length;
680
1.30k
  if (flags & G_URI_FLAGS_HAS_AUTH_PARAMS)
681
1.30k
    password_end = memchr (start, ';', auth_params_end - start);
682
1.30k
  if (!password_end)
683
1.12k
    password_end = auth_params_end;
684
1.30k
  if (flags & G_URI_FLAGS_HAS_PASSWORD)
685
1.30k
    user_end = memchr (start, ':', password_end - start);
686
1.30k
  if (!user_end)
687
1.10k
    user_end = password_end;
688
689
1.30k
  if (!uri_normalize (user, start, user_end - start, flags,
690
1.30k
                      G_URI_ERROR_BAD_USER, error))
691
2
    return FALSE;
692
693
1.30k
  if (*user_end == ':')
694
207
    {
695
207
      start = user_end + 1;
696
207
      if (!uri_normalize (password, start, password_end - start, flags,
697
207
                          G_URI_ERROR_BAD_PASSWORD, error))
698
2
        {
699
2
          if (user)
700
2
            g_clear_pointer (user, g_free);
701
2
          return FALSE;
702
2
        }
703
207
    }
704
1.10k
  else if (password)
705
0
    *password = NULL;
706
707
1.30k
  if (*password_end == ';')
708
186
    {
709
186
      start = password_end + 1;
710
186
      if (!uri_normalize (auth_params, start, auth_params_end - start, flags,
711
186
                          G_URI_ERROR_BAD_AUTH_PARAMS, error))
712
2
        {
713
2
          if (user)
714
2
            g_clear_pointer (user, g_free);
715
2
          if (password)
716
2
            g_clear_pointer (password, g_free);
717
2
          return FALSE;
718
2
        }
719
186
    }
720
1.11k
  else if (auth_params)
721
0
    *auth_params = NULL;
722
723
1.30k
  return TRUE;
724
1.30k
}
725
726
static gchar *
727
uri_cleanup (const gchar *uri_string)
728
0
{
729
0
  GString *copy;
730
0
  const gchar *end;
731
732
  /* Skip leading whitespace */
733
0
  while (g_ascii_isspace (*uri_string))
734
0
    uri_string++;
735
736
  /* Ignore trailing whitespace */
737
0
  end = uri_string + strlen (uri_string);
738
0
  while (end > uri_string && g_ascii_isspace (*(end - 1)))
739
0
    end--;
740
741
  /* Copy the rest, encoding unencoded spaces and stripping other whitespace */
742
0
  copy = g_string_sized_new (end - uri_string);
743
0
  while (uri_string < end)
744
0
    {
745
0
      if (*uri_string == ' ')
746
0
        g_string_append (copy, "%20");
747
0
      else if (g_ascii_isspace (*uri_string))
748
0
        ;
749
0
      else
750
0
        g_string_append_c (copy, *uri_string);
751
0
      uri_string++;
752
0
    }
753
754
0
  return g_string_free (copy, FALSE);
755
0
}
756
757
static gboolean
758
should_normalize_empty_path (const char *scheme)
759
0
{
760
0
  const char * const schemes[] = { "https", "http", "wss", "ws" };
761
0
  gsize i;
762
0
  for (i = 0; i < G_N_ELEMENTS (schemes); ++i)
763
0
    {
764
0
      if (!strcmp (schemes[i], scheme))
765
0
        return TRUE;
766
0
    }
767
0
  return FALSE;
768
0
}
769
770
static int
771
normalize_port (const char *scheme,
772
                int         port)
773
0
{
774
0
  const char *default_schemes[3] = { NULL };
775
0
  int i;
776
777
0
  switch (port)
778
0
    {
779
0
    case 21:
780
0
      default_schemes[0] = "ftp";
781
0
      break;
782
0
    case 80:
783
0
      default_schemes[0] = "http";
784
0
      default_schemes[1] = "ws";
785
0
      break;
786
0
    case 443:
787
0
      default_schemes[0] = "https";
788
0
      default_schemes[1] = "wss";
789
0
      break;
790
0
    default:
791
0
      break;
792
0
    }
793
794
0
  for (i = 0; default_schemes[i]; ++i)
795
0
    {
796
0
      if (!strcmp (scheme, default_schemes[i]))
797
0
        return -1;
798
0
    }
799
800
0
  return port;
801
0
}
802
803
int
804
g_uri_get_default_scheme_port (const char *scheme)
805
0
{
806
0
  if (strcmp (scheme, "http") == 0 || strcmp (scheme, "ws") == 0)
807
0
    return 80;
808
809
0
  if (strcmp (scheme, "https") == 0 || strcmp (scheme, "wss") == 0)
810
0
    return 443;
811
812
0
  if (strcmp (scheme, "ftp") == 0)
813
0
    return 21;
814
815
0
  if (strstr (scheme, "socks") == scheme)
816
0
    return 1080;
817
818
0
  return -1;
819
0
}
820
821
static gboolean
822
g_uri_split_internal (const gchar  *uri_string,
823
                      GUriFlags     flags,
824
                      gchar       **scheme,
825
                      gchar       **userinfo,
826
                      gchar       **user,
827
                      gchar       **password,
828
                      gchar       **auth_params,
829
                      gchar       **host,
830
                      gint         *port,
831
                      gchar       **path,
832
                      gchar       **query,
833
                      gchar       **fragment,
834
                      GError      **error)
835
44.9k
{
836
44.9k
  const gchar *end, *colon, *at, *path_start, *semi, *question;
837
44.9k
  const gchar *p, *bracket, *hostend;
838
44.9k
  gchar *cleaned_uri_string = NULL;
839
44.9k
  gchar *normalized_scheme = NULL;
840
841
44.9k
  if (scheme)
842
44.9k
    *scheme = NULL;
843
44.9k
  if (userinfo)
844
0
    *userinfo = NULL;
845
44.9k
  if (user)
846
0
    *user = NULL;
847
44.9k
  if (password)
848
0
    *password = NULL;
849
44.9k
  if (auth_params)
850
0
    *auth_params = NULL;
851
44.9k
  if (host)
852
0
    *host = NULL;
853
44.9k
  if (port)
854
0
    *port = -1;
855
44.9k
  if (path)
856
0
    *path = NULL;
857
44.9k
  if (query)
858
0
    *query = NULL;
859
44.9k
  if (fragment)
860
0
    *fragment = NULL;
861
862
44.9k
  if ((flags & G_URI_FLAGS_PARSE_RELAXED) && strpbrk (uri_string, " \t\n\r"))
863
0
    {
864
0
      cleaned_uri_string = uri_cleanup (uri_string);
865
0
      uri_string = cleaned_uri_string;
866
0
    }
867
868
  /* Find scheme */
869
44.9k
  p = uri_string;
870
211k
  while (*p && (g_ascii_isalpha (*p) ||
871
211k
               (p > uri_string && (g_ascii_isdigit (*p) ||
872
52.2k
                                   *p == '.' || *p == '+' || *p == '-'))))
873
166k
    p++;
874
875
44.9k
  if (p > uri_string && *p == ':')
876
44.5k
    {
877
44.5k
      normalized_scheme = g_ascii_strdown (uri_string, p - uri_string);
878
44.5k
      if (scheme)
879
44.5k
        *scheme = g_steal_pointer (&normalized_scheme);
880
44.5k
      p++;
881
44.5k
    }
882
402
  else
883
402
    {
884
402
      if (scheme)
885
402
        *scheme = NULL;
886
402
      p = uri_string;
887
402
    }
888
889
  /* Check for authority */
890
44.9k
  if (strncmp (p, "//", 2) == 0)
891
8.16k
    {
892
8.16k
      p += 2;
893
894
8.16k
      path_start = p + strcspn (p, "/?#");
895
8.16k
      at = memchr (p, '@', path_start - p);
896
8.16k
      if (at)
897
1.30k
        {
898
1.30k
          if (flags & G_URI_FLAGS_PARSE_RELAXED)
899
0
            {
900
0
              gchar *next_at;
901
902
              /* Any "@"s in the userinfo must be %-encoded, but
903
               * people get this wrong sometimes. Since "@"s in the
904
               * hostname are unlikely (and also wrong anyway), assume
905
               * that if there are extra "@"s, they belong in the
906
               * userinfo.
907
               */
908
0
              do
909
0
                {
910
0
                  next_at = memchr (at + 1, '@', path_start - (at + 1));
911
0
                  if (next_at)
912
0
                    at = next_at;
913
0
                }
914
0
              while (next_at);
915
0
            }
916
917
1.30k
          if (user || password || auth_params ||
918
1.30k
              (flags & (G_URI_FLAGS_HAS_PASSWORD|G_URI_FLAGS_HAS_AUTH_PARAMS)))
919
1.30k
            {
920
1.30k
              if (!parse_userinfo (p, at - p, flags,
921
1.30k
                                   user, password, auth_params,
922
1.30k
                                   error))
923
6
                goto fail;
924
1.30k
            }
925
926
1.30k
          if (!uri_normalize (userinfo, p, at - p, flags,
927
1.30k
                              G_URI_ERROR_BAD_USER, error))
928
0
            goto fail;
929
930
1.30k
          p = at + 1;
931
1.30k
        }
932
933
8.16k
      if (flags & G_URI_FLAGS_PARSE_RELAXED)
934
0
        {
935
0
          semi = strchr (p, ';');
936
0
          if (semi && semi < path_start)
937
0
            {
938
              /* Technically, semicolons are allowed in the "host"
939
               * production, but no one ever does this, and some
940
               * schemes mistakenly use semicolon as a delimiter
941
               * marking the start of the path. We have to check this
942
               * after checking for userinfo though, because a
943
               * semicolon before the "@" must be part of the
944
               * userinfo.
945
               */
946
0
              path_start = semi;
947
0
            }
948
0
        }
949
950
      /* Find host and port. The host may be a bracket-delimited IPv6
951
       * address, in which case the colon delimiting the port must come
952
       * (immediately) after the close bracket.
953
       */
954
8.16k
      if (*p == '[')
955
49
        {
956
49
          bracket = memchr (p, ']', path_start - p);
957
49
          if (bracket && *(bracket + 1) == ':')
958
3
            colon = bracket + 1;
959
46
          else
960
46
            colon = NULL;
961
49
        }
962
8.11k
      else
963
8.11k
        colon = memchr (p, ':', path_start - p);
964
965
8.16k
      hostend = colon ? colon : path_start;
966
8.16k
      if (!parse_host (p, hostend - p, flags, host, error))
967
70
        goto fail;
968
969
8.09k
      if (colon && colon != path_start - 1)
970
226
        {
971
226
          p = colon + 1;
972
226
          if (!parse_port (p, path_start - p, port, error))
973
82
            goto fail;
974
226
        }
975
976
8.01k
      p = path_start;
977
8.01k
    }
978
979
  /* Find fragment. */
980
44.8k
  end = p + strcspn (p, "#");
981
44.8k
  if (*end == '#')
982
6.06k
    {
983
6.06k
      if (!uri_normalize (fragment, end + 1, strlen (end + 1),
984
6.06k
                          flags | (flags & G_URI_FLAGS_ENCODED_FRAGMENT ? G_URI_FLAGS_ENCODED : 0),
985
6.06k
                          G_URI_ERROR_BAD_FRAGMENT, error))
986
30
        goto fail;
987
6.06k
    }
988
989
  /* Find query */
990
44.7k
  question = memchr (p, '?', end - p);
991
44.7k
  if (question)
992
6.44k
    {
993
6.44k
      if (!uri_normalize (query, question + 1, end - (question + 1),
994
6.44k
                          flags | (flags & G_URI_FLAGS_ENCODED_QUERY ? G_URI_FLAGS_ENCODED : 0),
995
6.44k
                          G_URI_ERROR_BAD_QUERY, error))
996
11
        goto fail;
997
6.43k
      end = question;
998
6.43k
    }
999
1000
44.7k
  if (!uri_normalize (path, p, end - p,
1001
44.7k
                      flags | (flags & G_URI_FLAGS_ENCODED_PATH ? G_URI_FLAGS_ENCODED : 0),
1002
44.7k
                      G_URI_ERROR_BAD_PATH, error))
1003
186
    goto fail;
1004
1005
  /* Scheme-based normalization */
1006
44.5k
  if (flags & G_URI_FLAGS_SCHEME_NORMALIZE && ((scheme && *scheme) || normalized_scheme))
1007
0
    {
1008
0
      const char *scheme_str = scheme && *scheme ? *scheme : normalized_scheme;
1009
1010
0
      if (should_normalize_empty_path (scheme_str) && path && !**path)
1011
0
        {
1012
0
          g_free (*path);
1013
0
          *path = g_strdup ("/");
1014
0
        }
1015
1016
0
      if (port && *port == -1)
1017
0
        *port = g_uri_get_default_scheme_port (scheme_str);
1018
0
    }
1019
1020
44.5k
  g_free (normalized_scheme);
1021
44.5k
  g_free (cleaned_uri_string);
1022
44.5k
  return TRUE;
1023
1024
385
 fail:
1025
385
  if (scheme)
1026
385
    g_clear_pointer (scheme, g_free);
1027
385
  if (userinfo)
1028
385
    g_clear_pointer (userinfo, g_free);
1029
385
  if (host)
1030
385
    g_clear_pointer (host, g_free);
1031
385
  if (port)
1032
0
    *port = -1;
1033
385
  if (path)
1034
385
    g_clear_pointer (path, g_free);
1035
385
  if (query)
1036
385
    g_clear_pointer (query, g_free);
1037
385
  if (fragment)
1038
385
    g_clear_pointer (fragment, g_free);
1039
1040
385
  g_free (normalized_scheme);
1041
385
  g_free (cleaned_uri_string);
1042
385
  return FALSE;
1043
44.7k
}
1044
1045
/**
1046
 * g_uri_split:
1047
 * @uri_ref: a string containing a relative or absolute URI
1048
 * @flags: flags for parsing @uri_ref
1049
 * @scheme: (out) (nullable) (optional) (transfer full): on return, contains
1050
 *    the scheme (converted to lowercase), or %NULL
1051
 * @userinfo: (out) (nullable) (optional) (transfer full): on return, contains
1052
 *    the userinfo, or %NULL
1053
 * @host: (out) (nullable) (optional) (transfer full): on return, contains the
1054
 *    host, or %NULL
1055
 * @port: (out) (optional) (transfer full): on return, contains the
1056
 *    port, or `-1`
1057
 * @path: (out) (not nullable) (optional) (transfer full): on return, contains the
1058
 *    path
1059
 * @query: (out) (nullable) (optional) (transfer full): on return, contains the
1060
 *    query, or %NULL
1061
 * @fragment: (out) (nullable) (optional) (transfer full): on return, contains
1062
 *    the fragment, or %NULL
1063
 * @error: #GError for error reporting, or %NULL to ignore.
1064
 *
1065
 * Parses @uri_ref (which can be an
1066
 * [absolute or relative URI](#relative-and-absolute-uris)) according to @flags, and
1067
 * returns the pieces. Any component that doesn't appear in @uri_ref will be
1068
 * returned as %NULL (but note that all URIs always have a path component,
1069
 * though it may be the empty string).
1070
 *
1071
 * If @flags contains %G_URI_FLAGS_ENCODED, then `%`-encoded characters in
1072
 * @uri_ref will remain encoded in the output strings. (If not,
1073
 * then all such characters will be decoded.) Note that decoding will
1074
 * only work if the URI components are ASCII or UTF-8, so you will
1075
 * need to use %G_URI_FLAGS_ENCODED if they are not.
1076
 *
1077
 * Note that the %G_URI_FLAGS_HAS_PASSWORD and
1078
 * %G_URI_FLAGS_HAS_AUTH_PARAMS @flags are ignored by g_uri_split(),
1079
 * since it always returns only the full userinfo; use
1080
 * g_uri_split_with_user() if you want it split up.
1081
 *
1082
 * Returns: (skip): %TRUE if @uri_ref parsed successfully, %FALSE
1083
 *   on error.
1084
 *
1085
 * Since: 2.66
1086
 */
1087
gboolean
1088
g_uri_split (const gchar  *uri_ref,
1089
             GUriFlags     flags,
1090
             gchar       **scheme,
1091
             gchar       **userinfo,
1092
             gchar       **host,
1093
             gint         *port,
1094
             gchar       **path,
1095
             gchar       **query,
1096
             gchar       **fragment,
1097
             GError      **error)
1098
0
{
1099
0
  g_return_val_if_fail (uri_ref != NULL, FALSE);
1100
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1101
1102
0
  return g_uri_split_internal (uri_ref, flags,
1103
0
                               scheme, userinfo, NULL, NULL, NULL,
1104
0
                               host, port, path, query, fragment,
1105
0
                               error);
1106
0
}
1107
1108
/**
1109
 * g_uri_split_with_user:
1110
 * @uri_ref: a string containing a relative or absolute URI
1111
 * @flags: flags for parsing @uri_ref
1112
 * @scheme: (out) (nullable) (optional) (transfer full): on return, contains
1113
 *    the scheme (converted to lowercase), or %NULL
1114
 * @user: (out) (nullable) (optional) (transfer full): on return, contains
1115
 *    the user, or %NULL
1116
 * @password: (out) (nullable) (optional) (transfer full): on return, contains
1117
 *    the password, or %NULL
1118
 * @auth_params: (out) (nullable) (optional) (transfer full): on return, contains
1119
 *    the auth_params, or %NULL
1120
 * @host: (out) (nullable) (optional) (transfer full): on return, contains the
1121
 *    host, or %NULL
1122
 * @port: (out) (optional) (transfer full): on return, contains the
1123
 *    port, or `-1`
1124
 * @path: (out) (not nullable) (optional) (transfer full): on return, contains the
1125
 *    path
1126
 * @query: (out) (nullable) (optional) (transfer full): on return, contains the
1127
 *    query, or %NULL
1128
 * @fragment: (out) (nullable) (optional) (transfer full): on return, contains
1129
 *    the fragment, or %NULL
1130
 * @error: #GError for error reporting, or %NULL to ignore.
1131
 *
1132
 * Parses @uri_ref (which can be an
1133
 * [absolute or relative URI](#relative-and-absolute-uris)) according to @flags, and
1134
 * returns the pieces. Any component that doesn't appear in @uri_ref will be
1135
 * returned as %NULL (but note that all URIs always have a path component,
1136
 * though it may be the empty string).
1137
 *
1138
 * See g_uri_split(), and the definition of #GUriFlags, for more
1139
 * information on the effect of @flags. Note that @password will only
1140
 * be parsed out if @flags contains %G_URI_FLAGS_HAS_PASSWORD, and
1141
 * @auth_params will only be parsed out if @flags contains
1142
 * %G_URI_FLAGS_HAS_AUTH_PARAMS.
1143
 *
1144
 * Returns: (skip): %TRUE if @uri_ref parsed successfully, %FALSE
1145
 *   on error.
1146
 *
1147
 * Since: 2.66
1148
 */
1149
gboolean
1150
g_uri_split_with_user (const gchar  *uri_ref,
1151
                       GUriFlags     flags,
1152
                       gchar       **scheme,
1153
                       gchar       **user,
1154
                       gchar       **password,
1155
                       gchar       **auth_params,
1156
                       gchar       **host,
1157
                       gint         *port,
1158
                       gchar       **path,
1159
                       gchar       **query,
1160
                       gchar       **fragment,
1161
                       GError      **error)
1162
0
{
1163
0
  g_return_val_if_fail (uri_ref != NULL, FALSE);
1164
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1165
1166
0
  return g_uri_split_internal (uri_ref, flags,
1167
0
                               scheme, NULL, user, password, auth_params,
1168
0
                               host, port, path, query, fragment,
1169
0
                               error);
1170
0
}
1171
1172
1173
/**
1174
 * g_uri_split_network:
1175
 * @uri_string: a string containing an absolute URI
1176
 * @flags: flags for parsing @uri_string
1177
 * @scheme: (out) (nullable) (optional) (transfer full): on return, contains
1178
 *    the scheme (converted to lowercase), or %NULL
1179
 * @host: (out) (nullable) (optional) (transfer full): on return, contains the
1180
 *    host, or %NULL
1181
 * @port: (out) (optional) (transfer full): on return, contains the
1182
 *    port, or `-1`
1183
 * @error: #GError for error reporting, or %NULL to ignore.
1184
 *
1185
 * Parses @uri_string (which must be an [absolute URI](#relative-and-absolute-uris))
1186
 * according to @flags, and returns the pieces relevant to connecting to a host.
1187
 * See the documentation for g_uri_split() for more details; this is
1188
 * mostly a wrapper around that function with simpler arguments.
1189
 * However, it will return an error if @uri_string is a relative URI,
1190
 * or does not contain a hostname component.
1191
 *
1192
 * Returns: (skip): %TRUE if @uri_string parsed successfully,
1193
 *   %FALSE on error.
1194
 *
1195
 * Since: 2.66
1196
 */
1197
gboolean
1198
g_uri_split_network (const gchar  *uri_string,
1199
                     GUriFlags     flags,
1200
                     gchar       **scheme,
1201
                     gchar       **host,
1202
                     gint         *port,
1203
                     GError      **error)
1204
0
{
1205
0
  gchar *my_scheme = NULL, *my_host = NULL;
1206
1207
0
  g_return_val_if_fail (uri_string != NULL, FALSE);
1208
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1209
1210
0
  if (!g_uri_split_internal (uri_string, flags,
1211
0
                             &my_scheme, NULL, NULL, NULL, NULL,
1212
0
                             &my_host, port, NULL, NULL, NULL,
1213
0
                             error))
1214
0
    return FALSE;
1215
1216
0
  if (!my_scheme || !my_host)
1217
0
    {
1218
0
      if (!my_scheme)
1219
0
        {
1220
0
          g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_SCHEME,
1221
0
                       _("URI ‘%s’ is not an absolute URI"),
1222
0
                       uri_string);
1223
0
        }
1224
0
      else
1225
0
        {
1226
0
          g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_HOST,
1227
0
                       _("URI ‘%s’ has no host component"),
1228
0
                       uri_string);
1229
0
        }
1230
0
      g_free (my_scheme);
1231
0
      g_free (my_host);
1232
1233
0
      return FALSE;
1234
0
    }
1235
1236
0
  if (scheme)
1237
0
    *scheme = g_steal_pointer (&my_scheme);
1238
0
  if (host)
1239
0
    *host = g_steal_pointer (&my_host);
1240
1241
0
  g_free (my_scheme);
1242
0
  g_free (my_host);
1243
1244
0
  return TRUE;
1245
0
}
1246
1247
/**
1248
 * g_uri_is_valid:
1249
 * @uri_string: a string containing an absolute URI
1250
 * @flags: flags for parsing @uri_string
1251
 * @error: #GError for error reporting, or %NULL to ignore.
1252
 *
1253
 * Parses @uri_string according to @flags, to determine whether it is a valid
1254
 * [absolute URI](#relative-and-absolute-uris), i.e. it does not need to be resolved
1255
 * relative to another URI using g_uri_parse_relative().
1256
 *
1257
 * If it’s not a valid URI, an error is returned explaining how it’s invalid.
1258
 *
1259
 * See g_uri_split(), and the definition of #GUriFlags, for more
1260
 * information on the effect of @flags.
1261
 *
1262
 * Returns: %TRUE if @uri_string is a valid absolute URI, %FALSE on error.
1263
 *
1264
 * Since: 2.66
1265
 */
1266
gboolean
1267
g_uri_is_valid (const gchar  *uri_string,
1268
                GUriFlags     flags,
1269
                GError      **error)
1270
44.9k
{
1271
44.9k
  gchar *my_scheme = NULL;
1272
1273
44.9k
  g_return_val_if_fail (uri_string != NULL, FALSE);
1274
44.9k
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1275
1276
44.9k
  if (!g_uri_split_internal (uri_string, flags,
1277
44.9k
                             &my_scheme, NULL, NULL, NULL, NULL,
1278
44.9k
                             NULL, NULL, NULL, NULL, NULL,
1279
44.9k
                             error))
1280
385
    return FALSE;
1281
1282
44.5k
  if (!my_scheme)
1283
247
    {
1284
247
      g_set_error (error, G_URI_ERROR, G_URI_ERROR_BAD_SCHEME,
1285
247
                   _("URI ‘%s’ is not an absolute URI"),
1286
247
                   uri_string);
1287
247
      return FALSE;
1288
247
    }
1289
1290
44.3k
  g_free (my_scheme);
1291
1292
44.3k
  return TRUE;
1293
44.5k
}
1294
1295
1296
/* Implements the "Remove Dot Segments" algorithm from section 5.2.4 of
1297
 * RFC 3986.
1298
 *
1299
 * See https://tools.ietf.org/html/rfc3986#section-5.2.4
1300
 */
1301
static void
1302
remove_dot_segments (gchar *path)
1303
0
{
1304
  /* The output can be written to the same buffer that the input
1305
   * is read from, as the output pointer is only ever increased
1306
   * when the input pointer is increased as well, and the input
1307
   * pointer is never decreased. */
1308
0
  gchar *input = path;
1309
0
  gchar *output = path;
1310
1311
0
  if (!*path)
1312
0
    return;
1313
1314
0
  while (*input)
1315
0
    {
1316
      /*  A.  If the input buffer begins with a prefix of "../" or "./",
1317
       *      then remove that prefix from the input buffer; otherwise,
1318
       */
1319
0
      if (strncmp (input, "../", 3) == 0)
1320
0
        input += 3;
1321
0
      else if (strncmp (input, "./", 2) == 0)
1322
0
        input += 2;
1323
1324
      /*  B.  if the input buffer begins with a prefix of "/./" or "/.",
1325
       *      where "." is a complete path segment, then replace that
1326
       *      prefix with "/" in the input buffer; otherwise,
1327
       */
1328
0
      else if (strncmp (input, "/./", 3) == 0)
1329
0
        input += 2;
1330
0
      else if (strcmp (input, "/.") == 0)
1331
0
        input[1] = '\0';
1332
1333
      /*  C.  if the input buffer begins with a prefix of "/../" or "/..",
1334
       *      where ".." is a complete path segment, then replace that
1335
       *      prefix with "/" in the input buffer and remove the last
1336
       *      segment and its preceding "/" (if any) from the output
1337
       *      buffer; otherwise,
1338
       */
1339
0
      else if (strncmp (input, "/../", 4) == 0)
1340
0
        {
1341
0
          input += 3;
1342
0
          if (output > path)
1343
0
            {
1344
0
              do
1345
0
                {
1346
0
                  output--;
1347
0
                }
1348
0
              while (*output != '/' && output > path);
1349
0
            }
1350
0
        }
1351
0
      else if (strcmp (input, "/..") == 0)
1352
0
        {
1353
0
          input[1] = '\0';
1354
0
          if (output > path)
1355
0
            {
1356
0
              do
1357
0
                 {
1358
0
                   output--;
1359
0
                 }
1360
0
              while (*output != '/' && output > path);
1361
0
            }
1362
0
        }
1363
1364
      /*  D.  if the input buffer consists only of "." or "..", then remove
1365
       *      that from the input buffer; otherwise,
1366
       */
1367
0
      else if (strcmp (input, "..") == 0 || strcmp (input, ".") == 0)
1368
0
        input[0] = '\0';
1369
1370
      /*  E.  move the first path segment in the input buffer to the end of
1371
       *      the output buffer, including the initial "/" character (if
1372
       *      any) and any subsequent characters up to, but not including,
1373
       *      the next "/" character or the end of the input buffer.
1374
       */
1375
0
      else
1376
0
        {
1377
0
          *output++ = *input++;
1378
0
          while (*input && *input != '/')
1379
0
            *output++ = *input++;
1380
0
        }
1381
0
    }
1382
0
  *output = '\0';
1383
0
}
1384
1385
/**
1386
 * g_uri_parse:
1387
 * @uri_string: a string representing an absolute URI
1388
 * @flags: flags describing how to parse @uri_string
1389
 * @error: #GError for error reporting, or %NULL to ignore.
1390
 *
1391
 * Parses @uri_string according to @flags. If the result is not a
1392
 * valid [absolute URI](#relative-and-absolute-uris), it will be discarded, and an
1393
 * error returned.
1394
 *
1395
 * Return value: (transfer full): a new #GUri, or NULL on error.
1396
 *
1397
 * Since: 2.66
1398
 */
1399
GUri *
1400
g_uri_parse (const gchar  *uri_string,
1401
             GUriFlags     flags,
1402
             GError      **error)
1403
0
{
1404
0
  g_return_val_if_fail (uri_string != NULL, NULL);
1405
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1406
1407
0
  return g_uri_parse_relative (NULL, uri_string, flags, error);
1408
0
}
1409
1410
/**
1411
 * g_uri_parse_relative:
1412
 * @base_uri: (nullable) (transfer none): a base absolute URI
1413
 * @uri_ref: a string representing a relative or absolute URI
1414
 * @flags: flags describing how to parse @uri_ref
1415
 * @error: #GError for error reporting, or %NULL to ignore.
1416
 *
1417
 * Parses @uri_ref according to @flags and, if it is a
1418
 * [relative URI](#relative-and-absolute-uris), resolves it relative to @base_uri.
1419
 * If the result is not a valid absolute URI, it will be discarded, and an error
1420
 * returned.
1421
 *
1422
 * Return value: (transfer full): a new #GUri, or NULL on error.
1423
 *
1424
 * Since: 2.66
1425
 */
1426
GUri *
1427
g_uri_parse_relative (GUri         *base_uri,
1428
                      const gchar  *uri_ref,
1429
                      GUriFlags     flags,
1430
                      GError      **error)
1431
0
{
1432
0
  GUri *uri = NULL;
1433
1434
0
  g_return_val_if_fail (uri_ref != NULL, NULL);
1435
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1436
0
  g_return_val_if_fail (base_uri == NULL || base_uri->scheme != NULL, NULL);
1437
1438
  /* Use GUri struct to construct the return value: there is no guarantee it is
1439
   * actually correct within the function body. */
1440
0
  uri = g_atomic_rc_box_new0 (GUri);
1441
0
  uri->flags = flags;
1442
1443
0
  if (!g_uri_split_internal (uri_ref, flags,
1444
0
                             &uri->scheme, &uri->userinfo,
1445
0
                             &uri->user, &uri->password, &uri->auth_params,
1446
0
                             &uri->host, &uri->port,
1447
0
                             &uri->path, &uri->query, &uri->fragment,
1448
0
                             error))
1449
0
    {
1450
0
      g_uri_unref (uri);
1451
0
      return NULL;
1452
0
    }
1453
1454
0
  if (!uri->scheme && !base_uri)
1455
0
    {
1456
0
      g_set_error_literal (error, G_URI_ERROR, G_URI_ERROR_FAILED,
1457
0
                           _("URI is not absolute, and no base URI was provided"));
1458
0
      g_uri_unref (uri);
1459
0
      return NULL;
1460
0
    }
1461
1462
0
  if (base_uri)
1463
0
    {
1464
      /* This is section 5.2.2 of RFC 3986, except that we're doing
1465
       * it in place in @uri rather than copying from R to T.
1466
       *
1467
       * See https://tools.ietf.org/html/rfc3986#section-5.2.2
1468
       */
1469
0
      if (uri->scheme)
1470
0
        remove_dot_segments (uri->path);
1471
0
      else
1472
0
        {
1473
0
          uri->scheme = g_strdup (base_uri->scheme);
1474
0
          if (uri->host)
1475
0
            remove_dot_segments (uri->path);
1476
0
          else
1477
0
            {
1478
0
              if (!*uri->path)
1479
0
                {
1480
0
                  g_free (uri->path);
1481
0
                  uri->path = g_strdup (base_uri->path);
1482
0
                  if (!uri->query)
1483
0
                    uri->query = g_strdup (base_uri->query);
1484
0
                }
1485
0
              else
1486
0
                {
1487
0
                  if (*uri->path == '/')
1488
0
                    remove_dot_segments (uri->path);
1489
0
                  else
1490
0
                    {
1491
0
                      gchar *newpath, *last;
1492
1493
0
                      last = strrchr (base_uri->path, '/');
1494
0
                      if (last)
1495
0
                        {
1496
0
                          newpath = g_strdup_printf ("%.*s/%s",
1497
0
                                                     (gint)(last - base_uri->path),
1498
0
                                                     base_uri->path,
1499
0
                                                     uri->path);
1500
0
                        }
1501
0
                      else
1502
0
                        newpath = g_strdup_printf ("/%s", uri->path);
1503
1504
0
                      g_free (uri->path);
1505
0
                      uri->path = g_steal_pointer (&newpath);
1506
1507
0
                      remove_dot_segments (uri->path);
1508
0
                    }
1509
0
                }
1510
1511
0
              uri->userinfo = g_strdup (base_uri->userinfo);
1512
0
              uri->user = g_strdup (base_uri->user);
1513
0
              uri->password = g_strdup (base_uri->password);
1514
0
              uri->auth_params = g_strdup (base_uri->auth_params);
1515
0
              uri->host = g_strdup (base_uri->host);
1516
0
              uri->port = base_uri->port;
1517
0
            }
1518
0
        }
1519
1520
      /* Scheme normalization couldn't have been done earlier
1521
       * as the relative URI may not have had a scheme */
1522
0
      if (flags & G_URI_FLAGS_SCHEME_NORMALIZE)
1523
0
        {
1524
0
          if (should_normalize_empty_path (uri->scheme) && !*uri->path)
1525
0
            {
1526
0
              g_free (uri->path);
1527
0
              uri->path = g_strdup ("/");
1528
0
            }
1529
1530
0
          uri->port = normalize_port (uri->scheme, uri->port);
1531
0
        }
1532
0
    }
1533
0
  else
1534
0
    {
1535
0
      remove_dot_segments (uri->path);
1536
0
    }
1537
1538
0
  return g_steal_pointer (&uri);
1539
0
}
1540
1541
/**
1542
 * g_uri_resolve_relative:
1543
 * @base_uri_string: (nullable): a string representing a base URI
1544
 * @uri_ref: a string representing a relative or absolute URI
1545
 * @flags: flags describing how to parse @uri_ref
1546
 * @error: #GError for error reporting, or %NULL to ignore.
1547
 *
1548
 * Parses @uri_ref according to @flags and, if it is a
1549
 * [relative URI](#relative-and-absolute-uris), resolves it relative to
1550
 * @base_uri_string. If the result is not a valid absolute URI, it will be
1551
 * discarded, and an error returned.
1552
 *
1553
 * (If @base_uri_string is %NULL, this just returns @uri_ref, or
1554
 * %NULL if @uri_ref is invalid or not absolute.)
1555
 *
1556
 * Return value: (transfer full): the resolved URI string,
1557
 * or NULL on error.
1558
 *
1559
 * Since: 2.66
1560
 */
1561
gchar *
1562
g_uri_resolve_relative (const gchar  *base_uri_string,
1563
                        const gchar  *uri_ref,
1564
                        GUriFlags     flags,
1565
                        GError      **error)
1566
0
{
1567
0
  GUri *base_uri, *resolved_uri;
1568
0
  gchar *resolved_uri_string;
1569
1570
0
  g_return_val_if_fail (uri_ref != NULL, NULL);
1571
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1572
1573
0
  flags |= G_URI_FLAGS_ENCODED;
1574
1575
0
  if (base_uri_string)
1576
0
    {
1577
0
      base_uri = g_uri_parse (base_uri_string, flags, error);
1578
0
      if (!base_uri)
1579
0
        return NULL;
1580
0
    }
1581
0
  else
1582
0
    base_uri = NULL;
1583
1584
0
  resolved_uri = g_uri_parse_relative (base_uri, uri_ref, flags, error);
1585
0
  if (base_uri)
1586
0
    g_uri_unref (base_uri);
1587
0
  if (!resolved_uri)
1588
0
    return NULL;
1589
1590
0
  resolved_uri_string = g_uri_to_string (resolved_uri);
1591
0
  g_uri_unref (resolved_uri);
1592
0
  return g_steal_pointer (&resolved_uri_string);
1593
0
}
1594
1595
/* userinfo as a whole can contain sub-delims + ":", but split-out
1596
 * user can't contain ":" or ";", and split-out password can't contain
1597
 * ";".
1598
 */
1599
0
#define USERINFO_ALLOWED_CHARS G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO
1600
0
#define USER_ALLOWED_CHARS "!$&'()*+,="
1601
0
#define PASSWORD_ALLOWED_CHARS "!$&'()*+,=:"
1602
0
#define AUTH_PARAMS_ALLOWED_CHARS USERINFO_ALLOWED_CHARS
1603
0
#define IP_ADDR_ALLOWED_CHARS ":"
1604
0
#define HOST_ALLOWED_CHARS G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS
1605
0
#define PATH_ALLOWED_CHARS G_URI_RESERVED_CHARS_ALLOWED_IN_PATH
1606
0
#define QUERY_ALLOWED_CHARS G_URI_RESERVED_CHARS_ALLOWED_IN_PATH "?"
1607
0
#define FRAGMENT_ALLOWED_CHARS G_URI_RESERVED_CHARS_ALLOWED_IN_PATH "?"
1608
1609
static gchar *
1610
g_uri_join_internal (GUriFlags    flags,
1611
                     const gchar *scheme,
1612
                     gboolean     userinfo,
1613
                     const gchar *user,
1614
                     const gchar *password,
1615
                     const gchar *auth_params,
1616
                     const gchar *host,
1617
                     gint         port,
1618
                     const gchar *path,
1619
                     const gchar *query,
1620
                     const gchar *fragment)
1621
0
{
1622
0
  gboolean encoded = (flags & G_URI_FLAGS_ENCODED);
1623
0
  GString *str;
1624
0
  char *normalized_scheme = NULL;
1625
1626
  /* Restrictions on path prefixes. See:
1627
   * https://tools.ietf.org/html/rfc3986#section-3
1628
   */
1629
0
  g_return_val_if_fail (path != NULL, NULL);
1630
0
  g_return_val_if_fail (host == NULL || (path[0] == '\0' || path[0] == '/'), NULL);
1631
0
  g_return_val_if_fail (host != NULL || (path[0] != '/' || path[1] != '/'), NULL);
1632
1633
  /* Arbitrarily chosen default size which should handle most average length
1634
   * URIs. This should avoid a few reallocations of the buffer in most cases.
1635
   * It’s 1B shorter than a power of two, since GString will add a
1636
   * nul-terminator byte. */
1637
0
  str = g_string_sized_new (127);
1638
1639
0
  if (scheme)
1640
0
    {
1641
0
      g_string_append (str, scheme);
1642
0
      g_string_append_c (str, ':');
1643
0
    }
1644
1645
0
  if (flags & G_URI_FLAGS_SCHEME_NORMALIZE && scheme && ((host && port != -1) || path[0] == '\0'))
1646
0
    normalized_scheme = g_ascii_strdown (scheme, -1);
1647
1648
0
  if (host)
1649
0
    {
1650
0
      g_string_append (str, "//");
1651
1652
0
      if (user)
1653
0
        {
1654
0
          if (encoded)
1655
0
            g_string_append (str, user);
1656
0
          else
1657
0
            {
1658
0
              if (userinfo)
1659
0
                g_string_append_uri_escaped (str, user, USERINFO_ALLOWED_CHARS, TRUE);
1660
0
              else
1661
                /* Encode ':' and ';' regardless of whether we have a
1662
                 * password or auth params, since it may be parsed later
1663
                 * under the assumption that it does.
1664
                 */
1665
0
                g_string_append_uri_escaped (str, user, USER_ALLOWED_CHARS, TRUE);
1666
0
            }
1667
1668
0
          if (password)
1669
0
            {
1670
0
              g_string_append_c (str, ':');
1671
0
              if (encoded)
1672
0
                g_string_append (str, password);
1673
0
              else
1674
0
                g_string_append_uri_escaped (str, password,
1675
0
                                             PASSWORD_ALLOWED_CHARS, TRUE);
1676
0
            }
1677
1678
0
          if (auth_params)
1679
0
            {
1680
0
              g_string_append_c (str, ';');
1681
0
              if (encoded)
1682
0
                g_string_append (str, auth_params);
1683
0
              else
1684
0
                g_string_append_uri_escaped (str, auth_params,
1685
0
                                             AUTH_PARAMS_ALLOWED_CHARS, TRUE);
1686
0
            }
1687
1688
0
          g_string_append_c (str, '@');
1689
0
        }
1690
1691
0
      if (strchr (host, ':') && g_hostname_is_ip_address (host))
1692
0
        {
1693
0
          g_string_append_c (str, '[');
1694
0
          if (encoded)
1695
0
            g_string_append (str, host);
1696
0
          else
1697
0
            g_string_append_uri_escaped (str, host, IP_ADDR_ALLOWED_CHARS, TRUE);
1698
0
          g_string_append_c (str, ']');
1699
0
        }
1700
0
      else
1701
0
        {
1702
0
          if (encoded)
1703
0
            g_string_append (str, host);
1704
0
          else
1705
0
            g_string_append_uri_escaped (str, host, HOST_ALLOWED_CHARS, TRUE);
1706
0
        }
1707
1708
0
      if (port != -1 && (!normalized_scheme || normalize_port (normalized_scheme, port) != -1))
1709
0
        g_string_append_printf (str, ":%d", port);
1710
0
    }
1711
1712
0
  if (path[0] == '\0' && normalized_scheme && should_normalize_empty_path (normalized_scheme))
1713
0
    g_string_append (str, "/");
1714
0
  else if (encoded || flags & G_URI_FLAGS_ENCODED_PATH)
1715
0
    g_string_append (str, path);
1716
0
  else
1717
0
    g_string_append_uri_escaped (str, path, PATH_ALLOWED_CHARS, TRUE);
1718
1719
0
  g_free (normalized_scheme);
1720
1721
0
  if (query)
1722
0
    {
1723
0
      g_string_append_c (str, '?');
1724
0
      if (encoded || flags & G_URI_FLAGS_ENCODED_QUERY)
1725
0
        g_string_append (str, query);
1726
0
      else
1727
0
        g_string_append_uri_escaped (str, query, QUERY_ALLOWED_CHARS, TRUE);
1728
0
    }
1729
0
  if (fragment)
1730
0
    {
1731
0
      g_string_append_c (str, '#');
1732
0
      if (encoded || flags & G_URI_FLAGS_ENCODED_FRAGMENT)
1733
0
        g_string_append (str, fragment);
1734
0
      else
1735
0
        g_string_append_uri_escaped (str, fragment, FRAGMENT_ALLOWED_CHARS, TRUE);
1736
0
    }
1737
1738
0
  return g_string_free (str, FALSE);
1739
0
}
1740
1741
/**
1742
 * g_uri_join:
1743
 * @flags: flags describing how to build the URI string
1744
 * @scheme: (nullable): the URI scheme, or %NULL
1745
 * @userinfo: (nullable): the userinfo component, or %NULL
1746
 * @host: (nullable): the host component, or %NULL
1747
 * @port: the port, or `-1`
1748
 * @path: (not nullable): the path component
1749
 * @query: (nullable): the query component, or %NULL
1750
 * @fragment: (nullable): the fragment, or %NULL
1751
 *
1752
 * Joins the given components together according to @flags to create
1753
 * an absolute URI string. @path may not be %NULL (though it may be the empty
1754
 * string).
1755
 *
1756
 * When @host is present, @path must either be empty or begin with a slash (`/`)
1757
 * character. When @host is not present, @path cannot begin with two slash
1758
 * characters (`//`). See
1759
 * [RFC 3986, section 3](https://tools.ietf.org/html/rfc3986#section-3).
1760
 *
1761
 * See also g_uri_join_with_user(), which allows specifying the
1762
 * components of the ‘userinfo’ separately.
1763
 *
1764
 * %G_URI_FLAGS_HAS_PASSWORD and %G_URI_FLAGS_HAS_AUTH_PARAMS are ignored if set
1765
 * in @flags.
1766
 *
1767
 * Return value: (not nullable) (transfer full): an absolute URI string
1768
 *
1769
 * Since: 2.66
1770
 */
1771
gchar *
1772
g_uri_join (GUriFlags    flags,
1773
            const gchar *scheme,
1774
            const gchar *userinfo,
1775
            const gchar *host,
1776
            gint         port,
1777
            const gchar *path,
1778
            const gchar *query,
1779
            const gchar *fragment)
1780
0
{
1781
0
  g_return_val_if_fail (port >= -1 && port <= 65535, NULL);
1782
0
  g_return_val_if_fail (path != NULL, NULL);
1783
1784
0
  return g_uri_join_internal (flags,
1785
0
                              scheme,
1786
0
                              TRUE, userinfo, NULL, NULL,
1787
0
                              host,
1788
0
                              port,
1789
0
                              path,
1790
0
                              query,
1791
0
                              fragment);
1792
0
}
1793
1794
/**
1795
 * g_uri_join_with_user:
1796
 * @flags: flags describing how to build the URI string
1797
 * @scheme: (nullable): the URI scheme, or %NULL
1798
 * @user: (nullable): the user component of the userinfo, or %NULL
1799
 * @password: (nullable): the password component of the userinfo, or
1800
 *   %NULL
1801
 * @auth_params: (nullable): the auth params of the userinfo, or
1802
 *   %NULL
1803
 * @host: (nullable): the host component, or %NULL
1804
 * @port: the port, or `-1`
1805
 * @path: (not nullable): the path component
1806
 * @query: (nullable): the query component, or %NULL
1807
 * @fragment: (nullable): the fragment, or %NULL
1808
 *
1809
 * Joins the given components together according to @flags to create
1810
 * an absolute URI string. @path may not be %NULL (though it may be the empty
1811
 * string).
1812
 *
1813
 * In contrast to g_uri_join(), this allows specifying the components
1814
 * of the ‘userinfo’ separately. It otherwise behaves the same.
1815
 *
1816
 * %G_URI_FLAGS_HAS_PASSWORD and %G_URI_FLAGS_HAS_AUTH_PARAMS are ignored if set
1817
 * in @flags.
1818
 *
1819
 * Return value: (not nullable) (transfer full): an absolute URI string
1820
 *
1821
 * Since: 2.66
1822
 */
1823
gchar *
1824
g_uri_join_with_user (GUriFlags    flags,
1825
                      const gchar *scheme,
1826
                      const gchar *user,
1827
                      const gchar *password,
1828
                      const gchar *auth_params,
1829
                      const gchar *host,
1830
                      gint         port,
1831
                      const gchar *path,
1832
                      const gchar *query,
1833
                      const gchar *fragment)
1834
0
{
1835
0
  g_return_val_if_fail (port >= -1 && port <= 65535, NULL);
1836
0
  g_return_val_if_fail (path != NULL, NULL);
1837
1838
0
  return g_uri_join_internal (flags,
1839
0
                              scheme,
1840
0
                              FALSE, user, password, auth_params,
1841
0
                              host,
1842
0
                              port,
1843
0
                              path,
1844
0
                              query,
1845
0
                              fragment);
1846
0
}
1847
1848
/**
1849
 * g_uri_build:
1850
 * @flags: flags describing how to build the #GUri
1851
 * @scheme: (not nullable): the URI scheme
1852
 * @userinfo: (nullable): the userinfo component, or %NULL
1853
 * @host: (nullable): the host component, or %NULL
1854
 * @port: the port, or `-1`
1855
 * @path: (not nullable): the path component
1856
 * @query: (nullable): the query component, or %NULL
1857
 * @fragment: (nullable): the fragment, or %NULL
1858
 *
1859
 * Creates a new #GUri from the given components according to @flags.
1860
 *
1861
 * See also g_uri_build_with_user(), which allows specifying the
1862
 * components of the "userinfo" separately.
1863
 *
1864
 * Return value: (not nullable) (transfer full): a new #GUri
1865
 *
1866
 * Since: 2.66
1867
 */
1868
GUri *
1869
g_uri_build (GUriFlags    flags,
1870
             const gchar *scheme,
1871
             const gchar *userinfo,
1872
             const gchar *host,
1873
             gint         port,
1874
             const gchar *path,
1875
             const gchar *query,
1876
             const gchar *fragment)
1877
0
{
1878
0
  GUri *uri;
1879
1880
0
  g_return_val_if_fail (scheme != NULL, NULL);
1881
0
  g_return_val_if_fail (port >= -1 && port <= 65535, NULL);
1882
0
  g_return_val_if_fail (path != NULL, NULL);
1883
1884
0
  uri = g_atomic_rc_box_new0 (GUri);
1885
0
  uri->flags = flags;
1886
0
  uri->scheme = g_ascii_strdown (scheme, -1);
1887
0
  uri->userinfo = g_strdup (userinfo);
1888
0
  uri->host = g_strdup (host);
1889
0
  uri->port = port;
1890
0
  uri->path = g_strdup (path);
1891
0
  uri->query = g_strdup (query);
1892
0
  uri->fragment = g_strdup (fragment);
1893
1894
0
  return g_steal_pointer (&uri);
1895
0
}
1896
1897
/**
1898
 * g_uri_build_with_user:
1899
 * @flags: flags describing how to build the #GUri
1900
 * @scheme: (not nullable): the URI scheme
1901
 * @user: (nullable): the user component of the userinfo, or %NULL
1902
 * @password: (nullable): the password component of the userinfo, or %NULL
1903
 * @auth_params: (nullable): the auth params of the userinfo, or %NULL
1904
 * @host: (nullable): the host component, or %NULL
1905
 * @port: the port, or `-1`
1906
 * @path: (not nullable): the path component
1907
 * @query: (nullable): the query component, or %NULL
1908
 * @fragment: (nullable): the fragment, or %NULL
1909
 *
1910
 * Creates a new #GUri from the given components according to @flags
1911
 * (%G_URI_FLAGS_HAS_PASSWORD is added unconditionally). The @flags must be
1912
 * coherent with the passed values, in particular use `%`-encoded values with
1913
 * %G_URI_FLAGS_ENCODED.
1914
 *
1915
 * In contrast to g_uri_build(), this allows specifying the components
1916
 * of the ‘userinfo’ field separately. Note that @user must be non-%NULL
1917
 * if either @password or @auth_params is non-%NULL.
1918
 *
1919
 * Return value: (not nullable) (transfer full): a new #GUri
1920
 *
1921
 * Since: 2.66
1922
 */
1923
GUri *
1924
g_uri_build_with_user (GUriFlags    flags,
1925
                       const gchar *scheme,
1926
                       const gchar *user,
1927
                       const gchar *password,
1928
                       const gchar *auth_params,
1929
                       const gchar *host,
1930
                       gint         port,
1931
                       const gchar *path,
1932
                       const gchar *query,
1933
                       const gchar *fragment)
1934
0
{
1935
0
  GUri *uri;
1936
0
  GString *userinfo;
1937
1938
0
  g_return_val_if_fail (scheme != NULL, NULL);
1939
0
  g_return_val_if_fail (password == NULL || user != NULL, NULL);
1940
0
  g_return_val_if_fail (auth_params == NULL || user != NULL, NULL);
1941
0
  g_return_val_if_fail (port >= -1 && port <= 65535, NULL);
1942
0
  g_return_val_if_fail (path != NULL, NULL);
1943
1944
0
  uri = g_atomic_rc_box_new0 (GUri);
1945
0
  uri->flags = flags | G_URI_FLAGS_HAS_PASSWORD;
1946
0
  uri->scheme = g_ascii_strdown (scheme, -1);
1947
0
  uri->user = g_strdup (user);
1948
0
  uri->password = g_strdup (password);
1949
0
  uri->auth_params = g_strdup (auth_params);
1950
0
  uri->host = g_strdup (host);
1951
0
  uri->port = port;
1952
0
  uri->path = g_strdup (path);
1953
0
  uri->query = g_strdup (query);
1954
0
  uri->fragment = g_strdup (fragment);
1955
1956
0
  if (user)
1957
0
    {
1958
0
      userinfo = g_string_new (user);
1959
0
      if (password)
1960
0
        {
1961
0
          g_string_append_c (userinfo, ':');
1962
0
          g_string_append (userinfo, uri->password);
1963
0
        }
1964
0
      if (auth_params)
1965
0
        {
1966
0
          g_string_append_c (userinfo, ';');
1967
0
          g_string_append (userinfo, uri->auth_params);
1968
0
        }
1969
0
      uri->userinfo = g_string_free (userinfo, FALSE);
1970
0
    }
1971
1972
0
  return g_steal_pointer (&uri);
1973
0
}
1974
1975
/**
1976
 * g_uri_to_string:
1977
 * @uri: a #GUri
1978
 *
1979
 * Returns a string representing @uri.
1980
 *
1981
 * This is not guaranteed to return a string which is identical to the
1982
 * string that @uri was parsed from. However, if the source URI was
1983
 * syntactically correct (according to RFC 3986), and it was parsed
1984
 * with %G_URI_FLAGS_ENCODED, then g_uri_to_string() is guaranteed to return
1985
 * a string which is at least semantically equivalent to the source
1986
 * URI (according to RFC 3986).
1987
 *
1988
 * If @uri might contain sensitive details, such as authentication parameters,
1989
 * or private data in its query string, and the returned string is going to be
1990
 * logged, then consider using g_uri_to_string_partial() to redact parts.
1991
 *
1992
 * Return value: (not nullable) (transfer full): a string representing @uri,
1993
 *     which the caller must free.
1994
 *
1995
 * Since: 2.66
1996
 */
1997
gchar *
1998
g_uri_to_string (GUri *uri)
1999
0
{
2000
0
  g_return_val_if_fail (uri != NULL, NULL);
2001
2002
0
  return g_uri_to_string_partial (uri, G_URI_HIDE_NONE);
2003
0
}
2004
2005
/**
2006
 * g_uri_to_string_partial:
2007
 * @uri: a #GUri
2008
 * @flags: flags describing what parts of @uri to hide
2009
 *
2010
 * Returns a string representing @uri, subject to the options in
2011
 * @flags. See g_uri_to_string() and #GUriHideFlags for more details.
2012
 *
2013
 * Return value: (not nullable) (transfer full): a string representing
2014
 *     @uri, which the caller must free.
2015
 *
2016
 * Since: 2.66
2017
 */
2018
gchar *
2019
g_uri_to_string_partial (GUri          *uri,
2020
                         GUriHideFlags  flags)
2021
0
{
2022
0
  gboolean hide_user = (flags & G_URI_HIDE_USERINFO);
2023
0
  gboolean hide_password = (flags & (G_URI_HIDE_USERINFO | G_URI_HIDE_PASSWORD));
2024
0
  gboolean hide_auth_params = (flags & (G_URI_HIDE_USERINFO | G_URI_HIDE_AUTH_PARAMS));
2025
0
  gboolean hide_query = (flags & G_URI_HIDE_QUERY);
2026
0
  gboolean hide_fragment = (flags & G_URI_HIDE_FRAGMENT);
2027
2028
0
  g_return_val_if_fail (uri != NULL, NULL);
2029
2030
0
  if (uri->flags & (G_URI_FLAGS_HAS_PASSWORD | G_URI_FLAGS_HAS_AUTH_PARAMS))
2031
0
    {
2032
0
      return g_uri_join_with_user (uri->flags,
2033
0
                                   uri->scheme,
2034
0
                                   hide_user ? NULL : uri->user,
2035
0
                                   hide_password ? NULL : uri->password,
2036
0
                                   hide_auth_params ? NULL : uri->auth_params,
2037
0
                                   uri->host,
2038
0
                                   uri->port,
2039
0
                                   uri->path,
2040
0
                                   hide_query ? NULL : uri->query,
2041
0
                                   hide_fragment ? NULL : uri->fragment);
2042
0
    }
2043
2044
0
  return g_uri_join (uri->flags,
2045
0
                     uri->scheme,
2046
0
                     hide_user ? NULL : uri->userinfo,
2047
0
                     uri->host,
2048
0
                     uri->port,
2049
0
                     uri->path,
2050
0
                     hide_query ? NULL : uri->query,
2051
0
                     hide_fragment ? NULL : uri->fragment);
2052
0
}
2053
2054
/* This is just a copy of g_str_hash() with g_ascii_toupper() added */
2055
static guint
2056
str_ascii_case_hash (gconstpointer v)
2057
0
{
2058
0
  const signed char *p;
2059
0
  guint32 h = 5381;
2060
2061
0
  for (p = v; *p != '\0'; p++)
2062
0
    h = (h << 5) + h + g_ascii_toupper (*p);
2063
2064
0
  return h;
2065
0
}
2066
2067
static gboolean
2068
str_ascii_case_equal (gconstpointer v1,
2069
                      gconstpointer v2)
2070
0
{
2071
0
  const gchar *string1 = v1;
2072
0
  const gchar *string2 = v2;
2073
2074
0
  return g_ascii_strcasecmp (string1, string2) == 0;
2075
0
}
2076
2077
/**
2078
 * GUriParamsIter:
2079
 *
2080
 * Many URI schemes include one or more attribute/value pairs as part of the URI
2081
 * value. For example `scheme://server/path?query=string&is=there` has two
2082
 * attributes – `query=string` and `is=there` – in its query part.
2083
 *
2084
 * A #GUriParamsIter structure represents an iterator that can be used to
2085
 * iterate over the attribute/value pairs of a URI query string. #GUriParamsIter
2086
 * structures are typically allocated on the stack and then initialized with
2087
 * g_uri_params_iter_init(). See the documentation for g_uri_params_iter_init()
2088
 * for a usage example.
2089
 *
2090
 * Since: 2.66
2091
 */
2092
typedef struct
2093
{
2094
  GUriParamsFlags flags;
2095
  const gchar    *attr;
2096
  const gchar    *end;
2097
  guint8          sep_table[256]; /* 1 = index is a separator; 0 otherwise */
2098
} RealIter;
2099
2100
G_STATIC_ASSERT (sizeof (GUriParamsIter) == sizeof (RealIter));
2101
G_STATIC_ASSERT (G_ALIGNOF (GUriParamsIter) >= G_ALIGNOF (RealIter));
2102
2103
/**
2104
 * g_uri_params_iter_init:
2105
 * @iter: an uninitialized #GUriParamsIter
2106
 * @params: a `%`-encoded string containing `attribute=value`
2107
 *   parameters
2108
 * @length: the length of @params, or `-1` if it is nul-terminated
2109
 * @separators: the separator byte character set between parameters. (usually
2110
 *   `&`, but sometimes `;` or both `&;`). Note that this function works on
2111
 *   bytes not characters, so it can't be used to delimit UTF-8 strings for
2112
 *   anything but ASCII characters. You may pass an empty set, in which case
2113
 *   no splitting will occur.
2114
 * @flags: flags to modify the way the parameters are handled.
2115
 *
2116
 * Initializes an attribute/value pair iterator.
2117
 *
2118
 * The iterator keeps pointers to the @params and @separators arguments, those
2119
 * variables must thus outlive the iterator and not be modified during the
2120
 * iteration.
2121
 *
2122
 * If %G_URI_PARAMS_WWW_FORM is passed in @flags, `+` characters in the param
2123
 * string will be replaced with spaces in the output. For example, `foo=bar+baz`
2124
 * will give attribute `foo` with value `bar baz`. This is commonly used on the
2125
 * web (the `https` and `http` schemes only), but is deprecated in favour of
2126
 * the equivalent of encoding spaces as `%20`.
2127
 *
2128
 * Unlike with g_uri_parse_params(), %G_URI_PARAMS_CASE_INSENSITIVE has no
2129
 * effect if passed to @flags for g_uri_params_iter_init(). The caller is
2130
 * responsible for doing their own case-insensitive comparisons.
2131
 *
2132
 * |[<!-- language="C" -->
2133
 * GUriParamsIter iter;
2134
 * GError *error = NULL;
2135
 * gchar *unowned_attr, *unowned_value;
2136
 *
2137
 * g_uri_params_iter_init (&iter, "foo=bar&baz=bar&Foo=frob&baz=bar2", -1, "&", G_URI_PARAMS_NONE);
2138
 * while (g_uri_params_iter_next (&iter, &unowned_attr, &unowned_value, &error))
2139
 *   {
2140
 *     g_autofree gchar *attr = g_steal_pointer (&unowned_attr);
2141
 *     g_autofree gchar *value = g_steal_pointer (&unowned_value);
2142
 *     // do something with attr and value; this code will be called 4 times
2143
 *     // for the params string in this example: once with attr=foo and value=bar,
2144
 *     // then with baz/bar, then Foo/frob, then baz/bar2.
2145
 *   }
2146
 * if (error)
2147
 *   // handle parsing error
2148
 * ]|
2149
 *
2150
 * Since: 2.66
2151
 */
2152
void
2153
g_uri_params_iter_init (GUriParamsIter *iter,
2154
                        const gchar    *params,
2155
                        gssize          length,
2156
                        const gchar    *separators,
2157
                        GUriParamsFlags flags)
2158
0
{
2159
0
  RealIter *ri = (RealIter *)iter;
2160
0
  const gchar *s;
2161
2162
0
  g_return_if_fail (iter != NULL);
2163
0
  g_return_if_fail (length == 0 || params != NULL);
2164
0
  g_return_if_fail (length >= -1);
2165
0
  g_return_if_fail (separators != NULL);
2166
2167
0
  ri->flags = flags;
2168
2169
0
  if (length == -1)
2170
0
    ri->end = params + strlen (params);
2171
0
  else
2172
0
    ri->end = params + length;
2173
2174
0
  memset (ri->sep_table, FALSE, sizeof (ri->sep_table));
2175
0
  for (s = separators; *s != '\0'; ++s)
2176
0
    ri->sep_table[*(guchar *)s] = TRUE;
2177
2178
0
  ri->attr = params;
2179
0
}
2180
2181
/**
2182
 * g_uri_params_iter_next:
2183
 * @iter: an initialized #GUriParamsIter
2184
 * @attribute: (out) (nullable) (optional) (transfer full): on return, contains
2185
 *     the attribute, or %NULL.
2186
 * @value: (out) (nullable) (optional) (transfer full): on return, contains
2187
 *     the value, or %NULL.
2188
 * @error: #GError for error reporting, or %NULL to ignore.
2189
 *
2190
 * Advances @iter and retrieves the next attribute/value. %FALSE is returned if
2191
 * an error has occurred (in which case @error is set), or if the end of the
2192
 * iteration is reached (in which case @attribute and @value are set to %NULL
2193
 * and the iterator becomes invalid). If %TRUE is returned,
2194
 * g_uri_params_iter_next() may be called again to receive another
2195
 * attribute/value pair.
2196
 *
2197
 * Note that the same @attribute may be returned multiple times, since URIs
2198
 * allow repeated attributes.
2199
 *
2200
 * Returns: %FALSE if the end of the parameters has been reached or an error was
2201
 *     encountered. %TRUE otherwise.
2202
 *
2203
 * Since: 2.66
2204
 */
2205
gboolean
2206
g_uri_params_iter_next (GUriParamsIter *iter,
2207
                        gchar         **attribute,
2208
                        gchar         **value,
2209
                        GError        **error)
2210
0
{
2211
0
  RealIter *ri = (RealIter *)iter;
2212
0
  const gchar *attr_end, *val, *val_end;
2213
0
  gchar *decoded_attr, *decoded_value;
2214
0
  gboolean www_form = ri->flags & G_URI_PARAMS_WWW_FORM;
2215
0
  GUriFlags decode_flags = G_URI_FLAGS_NONE;
2216
2217
0
  g_return_val_if_fail (iter != NULL, FALSE);
2218
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2219
2220
  /* Pre-clear these in case of failure or finishing. */
2221
0
  if (attribute)
2222
0
    *attribute = NULL;
2223
0
  if (value)
2224
0
    *value = NULL;
2225
2226
0
  if (ri->attr >= ri->end)
2227
0
    return FALSE;
2228
2229
0
  if (ri->flags & G_URI_PARAMS_PARSE_RELAXED)
2230
0
    decode_flags |= G_URI_FLAGS_PARSE_RELAXED;
2231
2232
  /* Check if each character in @attr is a separator, by indexing by the
2233
   * character value into the @sep_table, which has value 1 stored at an
2234
   * index if that index is a separator. */
2235
0
  for (val_end = ri->attr; val_end < ri->end; val_end++)
2236
0
    if (ri->sep_table[*(guchar *)val_end])
2237
0
      break;
2238
2239
0
  attr_end = memchr (ri->attr, '=', val_end - ri->attr);
2240
0
  if (!attr_end)
2241
0
    {
2242
0
      g_set_error_literal (error, G_URI_ERROR, G_URI_ERROR_FAILED,
2243
0
                           _("Missing ‘=’ and parameter value"));
2244
0
      return FALSE;
2245
0
    }
2246
0
  if (!uri_decode (&decoded_attr, NULL, ri->attr, attr_end - ri->attr,
2247
0
                   www_form, decode_flags, G_URI_ERROR_FAILED, error))
2248
0
    {
2249
0
      return FALSE;
2250
0
    }
2251
2252
0
  val = attr_end + 1;
2253
0
  if (!uri_decode (&decoded_value, NULL, val, val_end - val,
2254
0
                   www_form, decode_flags, G_URI_ERROR_FAILED, error))
2255
0
    {
2256
0
      g_free (decoded_attr);
2257
0
      return FALSE;
2258
0
    }
2259
2260
0
  if (attribute)
2261
0
    *attribute = g_steal_pointer (&decoded_attr);
2262
0
  if (value)
2263
0
    *value = g_steal_pointer (&decoded_value);
2264
2265
0
  g_free (decoded_attr);
2266
0
  g_free (decoded_value);
2267
2268
0
  ri->attr = val_end + 1;
2269
0
  return TRUE;
2270
0
}
2271
2272
/**
2273
 * g_uri_parse_params:
2274
 * @params: a `%`-encoded string containing `attribute=value`
2275
 *   parameters
2276
 * @length: the length of @params, or `-1` if it is nul-terminated
2277
 * @separators: the separator byte character set between parameters. (usually
2278
 *   `&`, but sometimes `;` or both `&;`). Note that this function works on
2279
 *   bytes not characters, so it can't be used to delimit UTF-8 strings for
2280
 *   anything but ASCII characters. You may pass an empty set, in which case
2281
 *   no splitting will occur.
2282
 * @flags: flags to modify the way the parameters are handled.
2283
 * @error: #GError for error reporting, or %NULL to ignore.
2284
 *
2285
 * Many URI schemes include one or more attribute/value pairs as part of the URI
2286
 * value. This method can be used to parse them into a hash table. When an
2287
 * attribute has multiple occurrences, the last value is the final returned
2288
 * value. If you need to handle repeated attributes differently, use
2289
 * #GUriParamsIter.
2290
 *
2291
 * The @params string is assumed to still be `%`-encoded, but the returned
2292
 * values will be fully decoded. (Thus it is possible that the returned values
2293
 * may contain `=` or @separators, if the value was encoded in the input.)
2294
 * Invalid `%`-encoding is treated as with the %G_URI_FLAGS_PARSE_RELAXED
2295
 * rules for g_uri_parse(). (However, if @params is the path or query string
2296
 * from a #GUri that was parsed without %G_URI_FLAGS_PARSE_RELAXED and
2297
 * %G_URI_FLAGS_ENCODED, then you already know that it does not contain any
2298
 * invalid encoding.)
2299
 *
2300
 * %G_URI_PARAMS_WWW_FORM is handled as documented for g_uri_params_iter_init().
2301
 *
2302
 * If %G_URI_PARAMS_CASE_INSENSITIVE is passed to @flags, attributes will be
2303
 * compared case-insensitively, so a params string `attr=123&Attr=456` will only
2304
 * return a single attribute–value pair, `Attr=456`. Case will be preserved in
2305
 * the returned attributes.
2306
 *
2307
 * If @params cannot be parsed (for example, it contains two @separators
2308
 * characters in a row), then @error is set and %NULL is returned.
2309
 *
2310
 * Return value: (transfer full) (element-type utf8 utf8):
2311
 *     A hash table of attribute/value pairs, with both names and values
2312
 *     fully-decoded; or %NULL on error.
2313
 *
2314
 * Since: 2.66
2315
 */
2316
GHashTable *
2317
g_uri_parse_params (const gchar     *params,
2318
                    gssize           length,
2319
                    const gchar     *separators,
2320
                    GUriParamsFlags  flags,
2321
                    GError         **error)
2322
0
{
2323
0
  GHashTable *hash;
2324
0
  GUriParamsIter iter;
2325
0
  gchar *attribute, *value;
2326
0
  GError *err = NULL;
2327
2328
0
  g_return_val_if_fail (length == 0 || params != NULL, NULL);
2329
0
  g_return_val_if_fail (length >= -1, NULL);
2330
0
  g_return_val_if_fail (separators != NULL, NULL);
2331
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2332
2333
0
  if (flags & G_URI_PARAMS_CASE_INSENSITIVE)
2334
0
    {
2335
0
      hash = g_hash_table_new_full (str_ascii_case_hash,
2336
0
                                    str_ascii_case_equal,
2337
0
                                    g_free, g_free);
2338
0
    }
2339
0
  else
2340
0
    {
2341
0
      hash = g_hash_table_new_full (g_str_hash, g_str_equal,
2342
0
                                    g_free, g_free);
2343
0
    }
2344
2345
0
  g_uri_params_iter_init (&iter, params, length, separators, flags);
2346
2347
0
  while (g_uri_params_iter_next (&iter, &attribute, &value, &err))
2348
0
    g_hash_table_insert (hash, attribute, value);
2349
2350
0
  if (err)
2351
0
    {
2352
0
      g_propagate_error (error, g_steal_pointer (&err));
2353
0
      g_hash_table_destroy (hash);
2354
0
      return NULL;
2355
0
    }
2356
2357
0
  return g_steal_pointer (&hash);
2358
0
}
2359
2360
/**
2361
 * g_uri_get_scheme:
2362
 * @uri: a #GUri
2363
 *
2364
 * Gets @uri's scheme. Note that this will always be all-lowercase,
2365
 * regardless of the string or strings that @uri was created from.
2366
 *
2367
 * Return value: (not nullable): @uri's scheme.
2368
 *
2369
 * Since: 2.66
2370
 */
2371
const gchar *
2372
g_uri_get_scheme (GUri *uri)
2373
0
{
2374
0
  g_return_val_if_fail (uri != NULL, NULL);
2375
2376
0
  return uri->scheme;
2377
0
}
2378
2379
/**
2380
 * g_uri_get_userinfo:
2381
 * @uri: a #GUri
2382
 *
2383
 * Gets @uri's userinfo, which may contain `%`-encoding, depending on
2384
 * the flags with which @uri was created.
2385
 *
2386
 * Return value: (nullable): @uri's userinfo.
2387
 *
2388
 * Since: 2.66
2389
 */
2390
const gchar *
2391
g_uri_get_userinfo (GUri *uri)
2392
0
{
2393
0
  g_return_val_if_fail (uri != NULL, NULL);
2394
2395
0
  return uri->userinfo;
2396
0
}
2397
2398
/**
2399
 * g_uri_get_user:
2400
 * @uri: a #GUri
2401
 *
2402
 * Gets the ‘username’ component of @uri's userinfo, which may contain
2403
 * `%`-encoding, depending on the flags with which @uri was created.
2404
 * If @uri was not created with %G_URI_FLAGS_HAS_PASSWORD or
2405
 * %G_URI_FLAGS_HAS_AUTH_PARAMS, this is the same as g_uri_get_userinfo().
2406
 *
2407
 * Return value: (nullable): @uri's user.
2408
 *
2409
 * Since: 2.66
2410
 */
2411
const gchar *
2412
g_uri_get_user (GUri *uri)
2413
0
{
2414
0
  g_return_val_if_fail (uri != NULL, NULL);
2415
2416
0
  return uri->user;
2417
0
}
2418
2419
/**
2420
 * g_uri_get_password:
2421
 * @uri: a #GUri
2422
 *
2423
 * Gets @uri's password, which may contain `%`-encoding, depending on
2424
 * the flags with which @uri was created. (If @uri was not created
2425
 * with %G_URI_FLAGS_HAS_PASSWORD then this will be %NULL.)
2426
 *
2427
 * Return value: (nullable): @uri's password.
2428
 *
2429
 * Since: 2.66
2430
 */
2431
const gchar *
2432
g_uri_get_password (GUri *uri)
2433
0
{
2434
0
  g_return_val_if_fail (uri != NULL, NULL);
2435
2436
0
  return uri->password;
2437
0
}
2438
2439
/**
2440
 * g_uri_get_auth_params:
2441
 * @uri: a #GUri
2442
 *
2443
 * Gets @uri's authentication parameters, which may contain
2444
 * `%`-encoding, depending on the flags with which @uri was created.
2445
 * (If @uri was not created with %G_URI_FLAGS_HAS_AUTH_PARAMS then this will
2446
 * be %NULL.)
2447
 *
2448
 * Depending on the URI scheme, g_uri_parse_params() may be useful for
2449
 * further parsing this information.
2450
 *
2451
 * Return value: (nullable): @uri's authentication parameters.
2452
 *
2453
 * Since: 2.66
2454
 */
2455
const gchar *
2456
g_uri_get_auth_params (GUri *uri)
2457
0
{
2458
0
  g_return_val_if_fail (uri != NULL, NULL);
2459
2460
0
  return uri->auth_params;
2461
0
}
2462
2463
/**
2464
 * g_uri_get_host:
2465
 * @uri: a #GUri
2466
 *
2467
 * Gets @uri's host. This will never have `%`-encoded characters,
2468
 * unless it is non-UTF-8 (which can only be the case if @uri was
2469
 * created with %G_URI_FLAGS_NON_DNS).
2470
 *
2471
 * If @uri contained an IPv6 address literal, this value will be just
2472
 * that address, without the brackets around it that are necessary in
2473
 * the string form of the URI. Note that in this case there may also
2474
 * be a scope ID attached to the address. Eg, `fe80::1234%``em1` (or
2475
 * `fe80::1234%``25em1` if the string is still encoded).
2476
 *
2477
 * Return value: (nullable): @uri's host.
2478
 *
2479
 * Since: 2.66
2480
 */
2481
const gchar *
2482
g_uri_get_host (GUri *uri)
2483
0
{
2484
0
  g_return_val_if_fail (uri != NULL, NULL);
2485
2486
0
  return uri->host;
2487
0
}
2488
2489
/**
2490
 * g_uri_get_port:
2491
 * @uri: a #GUri
2492
 *
2493
 * Gets @uri's port.
2494
 *
2495
 * Return value: @uri's port, or `-1` if no port was specified.
2496
 *
2497
 * Since: 2.66
2498
 */
2499
gint
2500
g_uri_get_port (GUri *uri)
2501
0
{
2502
0
  g_return_val_if_fail (uri != NULL, -1);
2503
2504
0
  if (uri->port == -1 && uri->flags & G_URI_FLAGS_SCHEME_NORMALIZE)
2505
0
    return g_uri_get_default_scheme_port (uri->scheme);
2506
2507
0
  return uri->port;
2508
0
}
2509
2510
/**
2511
 * g_uri_get_path:
2512
 * @uri: a #GUri
2513
 *
2514
 * Gets @uri's path, which may contain `%`-encoding, depending on the
2515
 * flags with which @uri was created.
2516
 *
2517
 * Return value: (not nullable): @uri's path.
2518
 *
2519
 * Since: 2.66
2520
 */
2521
const gchar *
2522
g_uri_get_path (GUri *uri)
2523
0
{
2524
0
  g_return_val_if_fail (uri != NULL, NULL);
2525
2526
0
  return uri->path;
2527
0
}
2528
2529
/**
2530
 * g_uri_get_query:
2531
 * @uri: a #GUri
2532
 *
2533
 * Gets @uri's query, which may contain `%`-encoding, depending on the
2534
 * flags with which @uri was created.
2535
 *
2536
 * For queries consisting of a series of `name=value` parameters,
2537
 * #GUriParamsIter or g_uri_parse_params() may be useful.
2538
 *
2539
 * Return value: (nullable): @uri's query.
2540
 *
2541
 * Since: 2.66
2542
 */
2543
const gchar *
2544
g_uri_get_query (GUri *uri)
2545
0
{
2546
0
  g_return_val_if_fail (uri != NULL, NULL);
2547
2548
0
  return uri->query;
2549
0
}
2550
2551
/**
2552
 * g_uri_get_fragment:
2553
 * @uri: a #GUri
2554
 *
2555
 * Gets @uri's fragment, which may contain `%`-encoding, depending on
2556
 * the flags with which @uri was created.
2557
 *
2558
 * Return value: (nullable): @uri's fragment.
2559
 *
2560
 * Since: 2.66
2561
 */
2562
const gchar *
2563
g_uri_get_fragment (GUri *uri)
2564
0
{
2565
0
  g_return_val_if_fail (uri != NULL, NULL);
2566
2567
0
  return uri->fragment;
2568
0
}
2569
2570
2571
/**
2572
 * g_uri_get_flags:
2573
 * @uri: a #GUri
2574
 *
2575
 * Gets @uri's flags set upon construction.
2576
 *
2577
 * Return value: @uri's flags.
2578
 *
2579
 * Since: 2.66
2580
 **/
2581
GUriFlags
2582
g_uri_get_flags (GUri *uri)
2583
0
{
2584
0
  g_return_val_if_fail (uri != NULL, G_URI_FLAGS_NONE);
2585
2586
0
  return uri->flags;
2587
0
}
2588
2589
/**
2590
 * g_uri_unescape_segment:
2591
 * @escaped_string: (nullable): A string, may be %NULL
2592
 * @escaped_string_end: (nullable): Pointer to end of @escaped_string,
2593
 *   may be %NULL
2594
 * @illegal_characters: (nullable): An optional string of illegal
2595
 *   characters not to be allowed, may be %NULL
2596
 *
2597
 * Unescapes a segment of an escaped string.
2598
 *
2599
 * If any of the characters in @illegal_characters or the NUL
2600
 * character appears as an escaped character in @escaped_string, then
2601
 * that is an error and %NULL will be returned. This is useful if you
2602
 * want to avoid for instance having a slash being expanded in an
2603
 * escaped path element, which might confuse pathname handling.
2604
 *
2605
 * Note: `NUL` byte is not accepted in the output, in contrast to
2606
 * g_uri_unescape_bytes().
2607
 *
2608
 * Returns: (nullable): an unescaped version of @escaped_string,
2609
 * or %NULL on error. The returned string should be freed when no longer
2610
 * needed.  As a special case if %NULL is given for @escaped_string, this
2611
 * function will return %NULL.
2612
 *
2613
 * Since: 2.16
2614
 **/
2615
gchar *
2616
g_uri_unescape_segment (const gchar *escaped_string,
2617
                        const gchar *escaped_string_end,
2618
                        const gchar *illegal_characters)
2619
24.7k
{
2620
24.7k
  gchar *unescaped;
2621
24.7k
  gsize length;
2622
24.7k
  gssize decoded_len;
2623
2624
24.7k
  if (!escaped_string)
2625
0
    return NULL;
2626
2627
24.7k
  if (escaped_string_end)
2628
0
    length = escaped_string_end - escaped_string;
2629
24.7k
  else
2630
24.7k
    length = strlen (escaped_string);
2631
2632
24.7k
  decoded_len = uri_decoder (&unescaped,
2633
24.7k
                             illegal_characters,
2634
24.7k
                             escaped_string, length,
2635
24.7k
                             FALSE, FALSE,
2636
24.7k
                             G_URI_FLAGS_ENCODED,
2637
24.7k
                             0, NULL);
2638
24.7k
  if (decoded_len < 0)
2639
0
    return NULL;
2640
2641
24.7k
  if (memchr (unescaped, '\0', decoded_len))
2642
0
    {
2643
0
      g_free (unescaped);
2644
0
      return NULL;
2645
0
    }
2646
2647
24.7k
  return unescaped;
2648
24.7k
}
2649
2650
/**
2651
 * g_uri_unescape_string:
2652
 * @escaped_string: an escaped string to be unescaped.
2653
 * @illegal_characters: (nullable): a string of illegal characters
2654
 *   not to be allowed, or %NULL.
2655
 *
2656
 * Unescapes a whole escaped string.
2657
 *
2658
 * If any of the characters in @illegal_characters or the NUL
2659
 * character appears as an escaped character in @escaped_string, then
2660
 * that is an error and %NULL will be returned. This is useful if you
2661
 * want to avoid for instance having a slash being expanded in an
2662
 * escaped path element, which might confuse pathname handling.
2663
 *
2664
 * Returns: (nullable): an unescaped version of @escaped_string.
2665
 * The returned string should be freed when no longer needed.
2666
 *
2667
 * Since: 2.16
2668
 **/
2669
gchar *
2670
g_uri_unescape_string (const gchar *escaped_string,
2671
                       const gchar *illegal_characters)
2672
24.7k
{
2673
24.7k
  return g_uri_unescape_segment (escaped_string, NULL, illegal_characters);
2674
24.7k
}
2675
2676
/**
2677
 * g_uri_escape_string:
2678
 * @unescaped: the unescaped input string.
2679
 * @reserved_chars_allowed: (nullable): a string of reserved
2680
 *   characters that are allowed to be used, or %NULL.
2681
 * @allow_utf8: %TRUE if the result can include UTF-8 characters.
2682
 *
2683
 * Escapes a string for use in a URI.
2684
 *
2685
 * Normally all characters that are not "unreserved" (i.e. ASCII
2686
 * alphanumerical characters plus dash, dot, underscore and tilde) are
2687
 * escaped. But if you specify characters in @reserved_chars_allowed
2688
 * they are not escaped. This is useful for the "reserved" characters
2689
 * in the URI specification, since those are allowed unescaped in some
2690
 * portions of a URI.
2691
 *
2692
 * Returns: (not nullable): an escaped version of @unescaped. The
2693
 * returned string should be freed when no longer needed.
2694
 *
2695
 * Since: 2.16
2696
 **/
2697
gchar *
2698
g_uri_escape_string (const gchar *unescaped,
2699
                     const gchar *reserved_chars_allowed,
2700
                     gboolean     allow_utf8)
2701
528k
{
2702
528k
  GString *s;
2703
2704
528k
  g_return_val_if_fail (unescaped != NULL, NULL);
2705
2706
528k
  s = g_string_sized_new (strlen (unescaped) * 1.25);
2707
2708
528k
  g_string_append_uri_escaped (s, unescaped, reserved_chars_allowed, allow_utf8);
2709
2710
528k
  return g_string_free (s, FALSE);
2711
528k
}
2712
2713
/**
2714
 * g_uri_unescape_bytes:
2715
 * @escaped_string: A URI-escaped string
2716
 * @length: the length (in bytes) of @escaped_string to escape, or `-1` if it
2717
 *   is nul-terminated.
2718
 * @illegal_characters: (nullable): a string of illegal characters
2719
 *   not to be allowed, or %NULL.
2720
 * @error: #GError for error reporting, or %NULL to ignore.
2721
 *
2722
 * Unescapes a segment of an escaped string as binary data.
2723
 *
2724
 * Note that in contrast to g_uri_unescape_string(), this does allow
2725
 * nul bytes to appear in the output.
2726
 *
2727
 * If any of the characters in @illegal_characters appears as an escaped
2728
 * character in @escaped_string, then that is an error and %NULL will be
2729
 * returned. This is useful if you want to avoid for instance having a slash
2730
 * being expanded in an escaped path element, which might confuse pathname
2731
 * handling.
2732
 *
2733
 * Returns: (transfer full): an unescaped version of @escaped_string
2734
 *     or %NULL on error (if decoding failed, using %G_URI_ERROR_FAILED error
2735
 *     code). The returned #GBytes should be unreffed when no longer needed.
2736
 *
2737
 * Since: 2.66
2738
 **/
2739
GBytes *
2740
g_uri_unescape_bytes (const gchar *escaped_string,
2741
                      gssize       length,
2742
                      const char *illegal_characters,
2743
                      GError     **error)
2744
0
{
2745
0
  gchar *buf;
2746
0
  gssize unescaped_length;
2747
2748
0
  g_return_val_if_fail (escaped_string != NULL, NULL);
2749
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2750
2751
0
  if (length == -1)
2752
0
    length = strlen (escaped_string);
2753
2754
0
  unescaped_length = uri_decoder (&buf,
2755
0
                                  illegal_characters,
2756
0
                                  escaped_string, length,
2757
0
                                  FALSE,
2758
0
                                  FALSE,
2759
0
                                  G_URI_FLAGS_ENCODED,
2760
0
                                  G_URI_ERROR_FAILED, error);
2761
0
  if (unescaped_length == -1)
2762
0
    return NULL;
2763
2764
0
  return g_bytes_new_take (buf, unescaped_length);
2765
0
}
2766
2767
/**
2768
 * g_uri_escape_bytes:
2769
 * @unescaped: (array length=length): the unescaped input data.
2770
 * @length: the length of @unescaped
2771
 * @reserved_chars_allowed: (nullable): a string of reserved
2772
 *   characters that are allowed to be used, or %NULL.
2773
 *
2774
 * Escapes arbitrary data for use in a URI.
2775
 *
2776
 * Normally all characters that are not ‘unreserved’ (i.e. ASCII
2777
 * alphanumerical characters plus dash, dot, underscore and tilde) are
2778
 * escaped. But if you specify characters in @reserved_chars_allowed
2779
 * they are not escaped. This is useful for the ‘reserved’ characters
2780
 * in the URI specification, since those are allowed unescaped in some
2781
 * portions of a URI.
2782
 *
2783
 * Though technically incorrect, this will also allow escaping nul
2784
 * bytes as `%``00`.
2785
 *
2786
 * Returns: (not nullable) (transfer full): an escaped version of @unescaped.
2787
 *     The returned string should be freed when no longer needed.
2788
 *
2789
 * Since: 2.66
2790
 */
2791
gchar *
2792
g_uri_escape_bytes (const guint8 *unescaped,
2793
                    gsize         length,
2794
                    const gchar  *reserved_chars_allowed)
2795
0
{
2796
0
  GString *string;
2797
2798
0
  g_return_val_if_fail (unescaped != NULL, NULL);
2799
2800
0
  string = g_string_sized_new (length * 1.25);
2801
2802
0
  _uri_encoder (string, unescaped, length,
2803
0
               reserved_chars_allowed, FALSE);
2804
2805
0
  return g_string_free (string, FALSE);
2806
0
}
2807
2808
static gssize
2809
g_uri_scheme_length (const gchar *uri)
2810
24.7k
{
2811
24.7k
  const gchar *p;
2812
2813
24.7k
  p = uri;
2814
24.7k
  if (!g_ascii_isalpha (*p))
2815
0
    return -1;
2816
24.7k
  p++;
2817
198k
  while (g_ascii_isalnum (*p) || *p == '.' || *p == '+' || *p == '-')
2818
173k
    p++;
2819
2820
24.7k
  if (p > uri && *p == ':')
2821
24.7k
    return p - uri;
2822
2823
0
  return -1;
2824
24.7k
}
2825
2826
/**
2827
 * g_uri_parse_scheme:
2828
 * @uri: a valid URI.
2829
 *
2830
 * Gets the scheme portion of a URI string.
2831
 * [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3) decodes the scheme
2832
 * as:
2833
 * |[
2834
 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
2835
 * ]|
2836
 * Common schemes include `file`, `https`, `svn+ssh`, etc.
2837
 *
2838
 * Returns: (transfer full) (nullable): The ‘scheme’ component of the URI, or
2839
 *     %NULL on error. The returned string should be freed when no longer needed.
2840
 *
2841
 * Since: 2.16
2842
 **/
2843
gchar *
2844
g_uri_parse_scheme (const gchar *uri)
2845
24.7k
{
2846
24.7k
  gssize len;
2847
2848
24.7k
  g_return_val_if_fail (uri != NULL, NULL);
2849
2850
24.7k
  len = g_uri_scheme_length (uri);
2851
24.7k
  return len == -1 ? NULL : g_strndup (uri, len);
2852
24.7k
}
2853
2854
/**
2855
 * g_uri_peek_scheme:
2856
 * @uri: a valid URI.
2857
 *
2858
 * Gets the scheme portion of a URI string.
2859
 * [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3) decodes the scheme
2860
 * as:
2861
 * |[
2862
 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
2863
 * ]|
2864
 * Common schemes include `file`, `https`, `svn+ssh`, etc.
2865
 *
2866
 * Unlike g_uri_parse_scheme(), the returned scheme is normalized to
2867
 * all-lowercase and does not need to be freed.
2868
 *
2869
 * Returns: (transfer none) (nullable): The ‘scheme’ component of the URI, or
2870
 *     %NULL on error. The returned string is normalized to all-lowercase, and
2871
 *     interned via g_intern_string(), so it does not need to be freed.
2872
 *
2873
 * Since: 2.66
2874
 **/
2875
const gchar *
2876
g_uri_peek_scheme (const gchar *uri)
2877
0
{
2878
0
  gssize len;
2879
0
  gchar *lower_scheme;
2880
0
  const gchar *scheme;
2881
2882
0
  g_return_val_if_fail (uri != NULL, NULL);
2883
2884
0
  len = g_uri_scheme_length (uri);
2885
0
  if (len == -1)
2886
0
    return NULL;
2887
2888
0
  lower_scheme = g_ascii_strdown (uri, len);
2889
0
  scheme = g_intern_string (lower_scheme);
2890
0
  g_free (lower_scheme);
2891
2892
0
  return scheme;
2893
0
}
2894
2895
G_DEFINE_QUARK (g-uri-quark, g_uri_error)