gsturi.c 76.1 KB
Newer Older
1 2 3
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2000 Wim Taymans <wtay@chello.be>
4
 * Copyright (C) 2011 Tim-Philipp Müller <tim centricular net>
5 6
 * Copyright (C) 2014 David Waring, British Broadcasting Corporation
 *                        <david.waring@rd.bbc.co.uk>
7
 *
8
 * gsturi.c: register URI handlers and IETF RFC 3986 URI manipulations.
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
22 23
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
24
 */
25

26 27
/**
 * SECTION:gsturihandler
Edward Hervey's avatar
Edward Hervey committed
28
 * @short_description: Interface to ease URI handling in plugins.
29
 *
30 31
 * The #GstURIHandler is an interface that is implemented by Source and Sink
 * #GstElement to unify handling of URI.
Edward Hervey's avatar
Edward Hervey committed
32 33
 *
 * An application can use the following functions to quickly get an element
34 35
 * that handles the given URI for reading or writing
 * (gst_element_make_from_uri()).
Edward Hervey's avatar
Edward Hervey committed
36
 *
37
 * Source and Sink plugins should implement this interface when possible.
38
 */
39

Benjamin Otte's avatar
Benjamin Otte committed
40 41 42
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
43

44
#include "gst_private.h"
45
#include "gst.h"
46
#include "gsturi.h"
47
#include "gstinfo.h"
David Schleef's avatar
David Schleef committed
48
#include "gstregistry.h"
Benjamin Otte's avatar
Benjamin Otte committed
49

50 51
#include "gst-i18n-lib.h"

Benjamin Otte's avatar
Benjamin Otte committed
52
#include <string.h>
53 54
#include <glib.h>
#include <glib/gprintf.h>
55

Benjamin Otte's avatar
Benjamin Otte committed
56 57
GST_DEBUG_CATEGORY_STATIC (gst_uri_handler_debug);
#define GST_CAT_DEFAULT gst_uri_handler_debug
58

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
#ifndef HAVE_STRCASESTR
#define strcasestr _gst_ascii_strcasestr

/* From https://github.com/freebsd/freebsd/blob/master/contrib/file/src/strcasestr.c
 * Updated to use GLib types and GLib string functions
 *
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Find the first occurrence of find in s, ignore case.
 */

static gchar *
_gst_ascii_strcasestr (const gchar * s, const gchar * find)
{
  gchar c, sc;
  gsize len;

  if ((c = *find++) != 0) {
    c = g_ascii_tolower (c);
    len = strlen (find);
    do {
      do {
        if ((sc = *s++) == 0)
          return (NULL);
      } while (g_ascii_tolower (sc) != c);
    } while (g_ascii_strncasecmp (s, find, len) != 0);
    s--;
  }
  return (gchar *) (gintptr) (s);
}
#endif

121 122 123
GType
gst_uri_handler_get_type (void)
{
124
  static volatile gsize urihandler_type = 0;
125

126 127
  if (g_once_init_enter (&urihandler_type)) {
    GType _type;
128
    static const GTypeInfo urihandler_info = {
Benjamin Otte's avatar
Benjamin Otte committed
129
      sizeof (GstURIHandlerInterface),
130
      NULL,
131 132 133 134 135
      NULL,
      NULL,
      NULL,
      NULL,
      0,
Benjamin Otte's avatar
Benjamin Otte committed
136 137
      0,
      NULL,
138 139
      NULL
    };
140

141
    _type = g_type_register_static (G_TYPE_INTERFACE,
142
        "GstURIHandler", &urihandler_info, 0);
Benjamin Otte's avatar
Benjamin Otte committed
143

144
    GST_DEBUG_CATEGORY_INIT (gst_uri_handler_debug, "GST_URI", GST_DEBUG_BOLD,
145
        "handling of URIs");
146
    g_once_init_leave (&urihandler_type, _type);
147
  }
148
  return urihandler_type;
149
}
150

151 152 153 154 155 156
GQuark
gst_uri_error_quark (void)
{
  return g_quark_from_static_string ("gst-uri-error-quark");
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
static const guchar acceptable[96] = {  /* X0   X1   X2   X3   X4   X5   X6   X7   X8   X9   XA   XB   XC   XD   XE   XF */
  0x00, 0x3F, 0x20, 0x20, 0x20, 0x00, 0x2C, 0x3F, 0x3F, 0x3F, 0x3F, 0x22, 0x20, 0x3F, 0x3F, 0x1C,       /* 2X  !"#$%&'()*+,-./   */
  0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x38, 0x20, 0x20, 0x2C, 0x20, 0x2C,       /* 3X 0123456789:;<=>?   */
  0x30, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       /* 4X @ABCDEFGHIJKLMNO   */
  0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x20, 0x20, 0x20, 0x20, 0x3F,       /* 5X PQRSTUVWXYZ[\]^_   */
  0x20, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,       /* 6X `abcdefghijklmno   */
  0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x20, 0x20, 0x20, 0x3F, 0x20        /* 7X pqrstuvwxyz{|}~DEL */
};

typedef enum
{
  UNSAFE_ALL = 0x1,             /* Escape all unsafe characters   */
  UNSAFE_ALLOW_PLUS = 0x2,      /* Allows '+'  */
  UNSAFE_PATH = 0x4,            /* Allows '/' and '?' and '&' and '='  */
  UNSAFE_DOS_PATH = 0x8,        /* Allows '/' and '?' and '&' and '=' and ':' */
  UNSAFE_HOST = 0x10,           /* Allows '/' and ':' and '@' */
  UNSAFE_SLASHES = 0x20         /* Allows all characters except for '/' and '%' */
} UnsafeCharacterSet;

#define HEX_ESCAPE '%'

/*  Escape undesirable characters using %
 *  -------------------------------------
 *
 * This function takes a pointer to a string in which
 * some characters may be unacceptable unescaped.
 * It returns a string which has these characters
 * represented by a '%' character followed by two hex digits.
 *
 * This routine returns a g_malloced string.
 */

static const gchar hex[16] = "0123456789ABCDEF";

static gchar *
escape_string_internal (const gchar * string, UnsafeCharacterSet mask)
{
#define ACCEPTABLE_CHAR(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))

  const gchar *p;
  gchar *q;
  gchar *result;
  guchar c;
  gint unacceptable;
  UnsafeCharacterSet use_mask;

  g_return_val_if_fail (mask == UNSAFE_ALL
      || mask == UNSAFE_ALLOW_PLUS
      || mask == UNSAFE_PATH
      || mask == UNSAFE_DOS_PATH
      || mask == UNSAFE_HOST || mask == UNSAFE_SLASHES, NULL);

  if (string == NULL) {
    return NULL;
  }

  unacceptable = 0;
  use_mask = mask;
  for (p = string; *p != '\0'; p++) {
    c = *p;
    if (!ACCEPTABLE_CHAR (c)) {
      unacceptable++;
    }
    if ((use_mask == UNSAFE_HOST) && (unacceptable || (c == '/'))) {
      /* when escaping a host, if we hit something that needs to be escaped, or we finally
       * hit a path separator, revert to path mode (the host segment of the url is over).
       */
      use_mask = UNSAFE_PATH;
    }
  }

  result = g_malloc (p - string + unacceptable * 2 + 1);

  use_mask = mask;
  for (q = result, p = string; *p != '\0'; p++) {
    c = *p;

    if (!ACCEPTABLE_CHAR (c)) {
      *q++ = HEX_ESCAPE;        /* means hex coming */
      *q++ = hex[c >> 4];
      *q++ = hex[c & 15];
    } else {
      *q++ = c;
    }
    if ((use_mask == UNSAFE_HOST) && (!ACCEPTABLE_CHAR (c) || (c == '/'))) {
      use_mask = UNSAFE_PATH;
    }
  }

  *q = '\0';

  return result;
}

251
/* escape_string:
252 253
 * @string: string to be escaped
 *
254
 * Escapes @string, replacing any and all special characters
255 256 257 258 259
 * with equivalent escape sequences.
 *
 * Return value: a newly allocated string equivalent to @string
 * but with all special characters escaped
 **/
Edward Hervey's avatar
Edward Hervey committed
260
static gchar *
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
escape_string (const gchar * string)
{
  return escape_string_internal (string, UNSAFE_ALL);
}

static int
hex_to_int (gchar c)
{
  return c >= '0' && c <= '9' ? c - '0'
      : c >= 'A' && c <= 'F' ? c - 'A' + 10
      : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1;
}

static int
unescape_character (const char *scanner)
{
  int first_digit;
  int second_digit;

  first_digit = hex_to_int (*scanner++);
  if (first_digit < 0) {
    return -1;
  }

285
  second_digit = hex_to_int (*scanner);
286 287 288 289 290 291 292
  if (second_digit < 0) {
    return -1;
  }

  return (first_digit << 4) | second_digit;
}

293
/* unescape_string:
294 295 296 297 298
 * @escaped_string: an escaped URI, path, or other string
 * @illegal_characters: a string containing a sequence of characters
 * considered "illegal", '\0' is automatically in this list.
 *
 * Decodes escaped characters (i.e. PERCENTxx sequences) in @escaped_string.
299
 * Characters are encoded in PERCENTxy form, where xy is the ASCII hex code
300
 * for character 16x+y.
301
 *
302 303 304
 * Return value: (nullable): a newly allocated string with the
 * unescaped equivalents, or %NULL if @escaped_string contained one of
 * the characters in @illegal_characters.
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
 **/
static char *
unescape_string (const gchar * escaped_string, const gchar * illegal_characters)
{
  const gchar *in;
  gchar *out, *result;
  gint character;

  if (escaped_string == NULL) {
    return NULL;
  }

  result = g_malloc (strlen (escaped_string) + 1);

  out = result;
  for (in = escaped_string; *in != '\0'; in++) {
    character = *in;
    if (*in == HEX_ESCAPE) {
      character = unescape_character (in + 1);

      /* Check for an illegal character. We consider '\0' illegal here. */
      if (character <= 0
          || (illegal_characters != NULL
              && strchr (illegal_characters, (char) character) != NULL)) {
        g_free (result);
        return NULL;
      }
      in += 2;
    }
    *out++ = (char) character;
  }

  *out = '\0';
338
  g_assert ((gsize) (out - result) <= strlen (escaped_string));
339 340 341 342 343
  return result;

}


344
static void
345
gst_uri_protocol_check_internal (const gchar * uri, gchar ** endptr)
346
{
Benjamin Otte's avatar
Benjamin Otte committed
347
  gchar *check = (gchar *) uri;
348

Benjamin Otte's avatar
Benjamin Otte committed
349 350 351
  g_assert (uri != NULL);
  g_assert (endptr != NULL);

352
  if (g_ascii_isalpha (*check)) {
Benjamin Otte's avatar
Benjamin Otte committed
353
    check++;
354 355
    while (g_ascii_isalnum (*check) || *check == '+'
        || *check == '-' || *check == '.')
356
      check++;
Benjamin Otte's avatar
Benjamin Otte committed
357 358 359
  }

  *endptr = check;
360
}
361

Benjamin Otte's avatar
Benjamin Otte committed
362 363
/**
 * gst_uri_protocol_is_valid:
Edward Hervey's avatar
Edward Hervey committed
364
 * @protocol: A string
Benjamin Otte's avatar
Benjamin Otte committed
365 366
 *
 * Tests if the given string is a valid protocol identifier. Protocols
367 368
 * must consist of alphanumeric characters, '+', '-' and '.' and must
 * start with a alphabetic character. See RFC 3986 Section 3.1.
Benjamin Otte's avatar
Benjamin Otte committed
369
 *
370
 * Returns: %TRUE if the string is a valid protocol identifier, %FALSE otherwise.
Benjamin Otte's avatar
Benjamin Otte committed
371 372
 */
gboolean
373
gst_uri_protocol_is_valid (const gchar * protocol)
Benjamin Otte's avatar
Benjamin Otte committed
374 375
{
  gchar *endptr;
376

Benjamin Otte's avatar
Benjamin Otte committed
377
  g_return_val_if_fail (protocol != NULL, FALSE);
378

Benjamin Otte's avatar
Benjamin Otte committed
379
  gst_uri_protocol_check_internal (protocol, &endptr);
380

381
  return *endptr == '\0' && ((gsize) (endptr - protocol)) >= 2;
Benjamin Otte's avatar
Benjamin Otte committed
382
}
383

384
/**
Benjamin Otte's avatar
Benjamin Otte committed
385
 * gst_uri_is_valid:
Edward Hervey's avatar
Edward Hervey committed
386
 * @uri: A URI string
387
 *
Benjamin Otte's avatar
Benjamin Otte committed
388
 * Tests if the given string is a valid URI identifier. URIs start with a valid
389
 * scheme followed by ":" and maybe a string identifying the location.
390
 *
391
 * Returns: %TRUE if the string is a valid URI
392
 */
Benjamin Otte's avatar
Benjamin Otte committed
393
gboolean
394
gst_uri_is_valid (const gchar * uri)
395
{
Benjamin Otte's avatar
Benjamin Otte committed
396
  gchar *endptr;
397

Benjamin Otte's avatar
Benjamin Otte committed
398
  g_return_val_if_fail (uri != NULL, FALSE);
399

Benjamin Otte's avatar
Benjamin Otte committed
400
  gst_uri_protocol_check_internal (uri, &endptr);
401

402
  return *endptr == ':' && ((gsize) (endptr - uri)) >= 2;
Benjamin Otte's avatar
Benjamin Otte committed
403
}
404

Benjamin Otte's avatar
Benjamin Otte committed
405 406
/**
 * gst_uri_get_protocol:
Edward Hervey's avatar
Edward Hervey committed
407
 * @uri: A URI string
Benjamin Otte's avatar
Benjamin Otte committed
408 409 410 411 412 413 414
 *
 * Extracts the protocol out of a given valid URI. The returned string must be
 * freed using g_free().
 *
 * Returns: The protocol for this URI.
 */
gchar *
415
gst_uri_get_protocol (const gchar * uri)
Benjamin Otte's avatar
Benjamin Otte committed
416 417
{
  gchar *colon;
418

419
  g_return_val_if_fail (uri != NULL, NULL);
Benjamin Otte's avatar
Benjamin Otte committed
420
  g_return_val_if_fail (gst_uri_is_valid (uri), NULL);
421

422
  colon = strstr (uri, ":");
423

424
  return g_ascii_strdown (uri, colon - uri);
425
}
426

427 428
/**
 * gst_uri_has_protocol:
429
 * @uri: a URI string
430 431
 * @protocol: a protocol string (e.g. "http")
 *
432 433 434
 * Checks if the protocol of a given valid URI matches @protocol.
 *
 * Returns: %TRUE if the protocol matches.
435 436 437 438 439 440 441 442 443 444
 */
gboolean
gst_uri_has_protocol (const gchar * uri, const gchar * protocol)
{
  gchar *colon;

  g_return_val_if_fail (uri != NULL, FALSE);
  g_return_val_if_fail (protocol != NULL, FALSE);
  g_return_val_if_fail (gst_uri_is_valid (uri), FALSE);

445
  colon = strstr (uri, ":");
446 447 448 449

  if (colon == NULL)
    return FALSE;

450
  return (g_ascii_strncasecmp (uri, protocol, (gsize) (colon - uri)) == 0);
451 452
}

453
/**
Benjamin Otte's avatar
Benjamin Otte committed
454
 * gst_uri_get_location:
Edward Hervey's avatar
Edward Hervey committed
455
 * @uri: A URI string
456
 *
457 458 459
 * Extracts the location out of a given valid URI, ie. the protocol and "://"
 * are stripped from the URI, which means that the location returned includes
 * the hostname if one is specified. The returned string must be freed using
Benjamin Otte's avatar
Benjamin Otte committed
460
 * g_free().
461
 *
462 463
 * Free-function: g_free
 *
464
 * Returns: (transfer full): the location for this URI. Returns %NULL if the
465 466
 *     URI isn't valid. If the URI does not contain a location, an empty
 *     string is returned.
467
 */
Benjamin Otte's avatar
Benjamin Otte committed
468
gchar *
469
gst_uri_get_location (const gchar * uri)
470
{
471 472
  const gchar *colon;
  gchar *unescaped = NULL;
473

Benjamin Otte's avatar
Benjamin Otte committed
474 475
  g_return_val_if_fail (uri != NULL, NULL);
  g_return_val_if_fail (gst_uri_is_valid (uri), NULL);
476

Benjamin Otte's avatar
Benjamin Otte committed
477
  colon = strstr (uri, "://");
478 479
  if (!colon)
    return NULL;
480

481 482 483 484 485 486 487 488 489 490 491 492
  unescaped = unescape_string (colon + 3, "/");

  /* On Windows an URI might look like file:///c:/foo/bar.txt or
   * file:///c|/foo/bar.txt (some Netscape versions) and we want to
   * return c:/foo/bar.txt as location rather than /c:/foo/bar.txt.
   * Can't use g_filename_from_uri() here because it will only handle the
   * file:// protocol */
#ifdef G_OS_WIN32
  if (unescaped != NULL && unescaped[0] == '/' &&
      g_ascii_isalpha (unescaped[1]) &&
      (unescaped[2] == ':' || unescaped[2] == '|')) {
    unescaped[2] = ':';
493
    memmove (unescaped, unescaped + 1, strlen (unescaped + 1) + 1);
494 495
  }
#endif
496

497
  GST_LOG ("extracted location '%s' from URI '%s'", GST_STR_NULL (unescaped),
498
      uri);
499
  return unescaped;
500
}
501

Benjamin Otte's avatar
Benjamin Otte committed
502 503
/**
 * gst_uri_construct:
Edward Hervey's avatar
Edward Hervey committed
504
 * @protocol: Protocol for URI
505
 * @location: (transfer none): Location for URI
Benjamin Otte's avatar
Benjamin Otte committed
506 507 508
 *
 * Constructs a URI for a given valid protocol and location.
 *
509 510
 * Free-function: g_free
 *
511 512
 * Returns: (transfer full): a new string for this URI. Returns %NULL if the
 *     given URI protocol is not valid, or the given location is %NULL.
513
 */
Benjamin Otte's avatar
Benjamin Otte committed
514
gchar *
515
gst_uri_construct (const gchar * protocol, const gchar * location)
Benjamin Otte's avatar
Benjamin Otte committed
516
{
517
  char *escaped, *proto_lowercase;
518 519
  char *retval;

Benjamin Otte's avatar
Benjamin Otte committed
520 521 522
  g_return_val_if_fail (gst_uri_protocol_is_valid (protocol), NULL);
  g_return_val_if_fail (location != NULL, NULL);

523
  proto_lowercase = g_ascii_strdown (protocol, -1);
524
  escaped = escape_string (location);
525
  retval = g_strdup_printf ("%s://%s", proto_lowercase, escaped);
526
  g_free (escaped);
527
  g_free (proto_lowercase);
528 529

  return retval;
Benjamin Otte's avatar
Benjamin Otte committed
530
}
531

532 533 534
typedef struct
{
  GstURIType type;
535
  const gchar *protocol;
536 537
}
SearchEntry;
538

539
static gboolean
540
search_by_entry (GstPluginFeature * feature, gpointer search_entry)
541
{
542
  const gchar *const *protocols;
Benjamin Otte's avatar
Benjamin Otte committed
543 544 545 546
  GstElementFactory *factory;
  SearchEntry *entry = (SearchEntry *) search_entry;

  if (!GST_IS_ELEMENT_FACTORY (feature))
547
    return FALSE;
548
  factory = GST_ELEMENT_FACTORY_CAST (feature);
Benjamin Otte's avatar
Benjamin Otte committed
549

550
  if (factory->uri_type != entry->type)
Benjamin Otte's avatar
Benjamin Otte committed
551
    return FALSE;
552

Benjamin Otte's avatar
Benjamin Otte committed
553
  protocols = gst_element_factory_get_uri_protocols (factory);
554 555 556 557 558 559 560

  if (protocols == NULL) {
    g_warning ("Factory '%s' implements GstUriHandler interface but returned "
        "no supported protocols!", gst_plugin_feature_get_name (feature));
    return FALSE;
  }

Benjamin Otte's avatar
Benjamin Otte committed
561
  while (*protocols != NULL) {
562
    if (g_ascii_strcasecmp (*protocols, entry->protocol) == 0)
Benjamin Otte's avatar
Benjamin Otte committed
563 564
      return TRUE;
    protocols++;
565 566 567
  }
  return FALSE;
}
568

Benjamin Otte's avatar
Benjamin Otte committed
569
static gint
570
sort_by_rank (GstPluginFeature * first, GstPluginFeature * second)
Benjamin Otte's avatar
Benjamin Otte committed
571
{
572 573
  return gst_plugin_feature_get_rank (second) -
      gst_plugin_feature_get_rank (first);
Benjamin Otte's avatar
Benjamin Otte committed
574
}
575

576 577 578 579 580 581 582 583 584 585 586
static GList *
get_element_factories_from_uri_protocol (const GstURIType type,
    const gchar * protocol)
{
  GList *possibilities;
  SearchEntry entry;

  g_return_val_if_fail (protocol, NULL);

  entry.type = type;
  entry.protocol = protocol;
587
  possibilities = gst_registry_feature_filter (gst_registry_get (),
588 589 590 591 592 593 594
      search_by_entry, FALSE, &entry);

  return possibilities;
}

/**
 * gst_uri_protocol_is_supported:
595 596
 * @type: Whether to check for a source or a sink
 * @protocol: Protocol that should be checked for (e.g. "http" or "smb")
597
 *
598 599 600
 * Checks if an element exists that supports the given URI protocol. Note
 * that a positive return value does not imply that a subsequent call to
 * gst_element_make_from_uri() is guaranteed to work.
601
 *
602
 * Returns: %TRUE
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
*/
gboolean
gst_uri_protocol_is_supported (const GstURIType type, const gchar * protocol)
{
  GList *possibilities;

  g_return_val_if_fail (protocol, FALSE);

  possibilities = get_element_factories_from_uri_protocol (type, protocol);

  if (possibilities) {
    g_list_free (possibilities);
    return TRUE;
  } else
    return FALSE;
}

Wim Taymans's avatar
Wim Taymans committed
620
/**
Benjamin Otte's avatar
Benjamin Otte committed
621
 * gst_element_make_from_uri:
622
 * @type: Whether to create a source or a sink
Edward Hervey's avatar
Edward Hervey committed
623
 * @uri: URI to create an element for
624 625
 * @elementname: (allow-none): Name of created element, can be %NULL.
 * @error: (allow-none): address where to store error information, or %NULL.
Wim Taymans's avatar
Wim Taymans committed
626
 *
627 628
 * Creates an element for handling the given URI.
 *
629
 * Returns: (transfer floating): a new element or %NULL if none could be created
Wim Taymans's avatar
Wim Taymans committed
630
 */
Benjamin Otte's avatar
Benjamin Otte committed
631
GstElement *
632
gst_element_make_from_uri (const GstURIType type, const gchar * uri,
633
    const gchar * elementname, GError ** error)
634
{
Benjamin Otte's avatar
Benjamin Otte committed
635
  GList *possibilities, *walk;
636
  gchar *protocol;
Benjamin Otte's avatar
Benjamin Otte committed
637 638
  GstElement *ret = NULL;

639
  g_return_val_if_fail (gst_is_initialized (), NULL);
Benjamin Otte's avatar
Benjamin Otte committed
640 641
  g_return_val_if_fail (GST_URI_TYPE_IS_VALID (type), NULL);
  g_return_val_if_fail (gst_uri_is_valid (uri), NULL);
642
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Benjamin Otte's avatar
Benjamin Otte committed
643

644 645
  GST_DEBUG ("type:%d, uri:%s, elementname:%s", type, uri, elementname);

646 647
  protocol = gst_uri_get_protocol (uri);
  possibilities = get_element_factories_from_uri_protocol (type, protocol);
Benjamin Otte's avatar
Benjamin Otte committed
648 649

  if (!possibilities) {
650
    GST_DEBUG ("No %s for URI '%s'", type == GST_URI_SINK ? "sink" : "source",
651
        uri);
652 653 654 655 656
    /* The error message isn't great, but we don't expect applications to
     * show that error to users, but call the missing plugins functions */
    g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_UNSUPPORTED_PROTOCOL,
        _("No URI handler for the %s protocol found"), protocol);
    g_free (protocol);
Benjamin Otte's avatar
Benjamin Otte committed
657 658
    return NULL;
  }
659
  g_free (protocol);
660

661
  possibilities = g_list_sort (possibilities, (GCompareFunc) sort_by_rank);
Benjamin Otte's avatar
Benjamin Otte committed
662 663
  walk = possibilities;
  while (walk) {
664 665 666 667 668
    GstElementFactory *factory = walk->data;
    GError *uri_err = NULL;

    ret = gst_element_factory_create (factory, elementname);
    if (ret != NULL) {
Benjamin Otte's avatar
Benjamin Otte committed
669
      GstURIHandler *handler = GST_URI_HANDLER (ret);
670

671
      if (gst_uri_handler_set_uri (handler, uri, &uri_err))
672
        break;
673 674 675 676 677 678 679 680 681

      GST_WARNING ("%s didn't accept URI '%s': %s", GST_OBJECT_NAME (ret), uri,
          uri_err->message);

      if (error != NULL && *error == NULL)
        g_propagate_error (error, uri_err);
      else
        g_error_free (uri_err);

682
      gst_object_unref (ret);
Benjamin Otte's avatar
Benjamin Otte committed
683
      ret = NULL;
684
    }
685
    walk = walk->next;
686
  }
687
  gst_plugin_feature_list_free (possibilities);
Wim Taymans's avatar
Wim Taymans committed
688

689 690
  GST_LOG_OBJECT (ret, "created %s for URL '%s'",
      type == GST_URI_SINK ? "sink" : "source", uri);
691 692 693 694 695

  /* if the first handler didn't work, but we found another one that works */
  if (ret != NULL)
    g_clear_error (error);

Benjamin Otte's avatar
Benjamin Otte committed
696 697
  return ret;
}
698

699
/**
Benjamin Otte's avatar
Benjamin Otte committed
700
 * gst_uri_handler_get_uri_type:
Edward Hervey's avatar
Edward Hervey committed
701
 * @handler: A #GstURIHandler.
702
 *
Edward Hervey's avatar
Edward Hervey committed
703
 * Gets the type of the given URI handler
704
 *
Edward Hervey's avatar
Edward Hervey committed
705 706
 * Returns: the #GstURIType of the URI handler.
 * Returns #GST_URI_UNKNOWN if the @handler isn't implemented correctly.
707
 */
708
GstURIType
709
gst_uri_handler_get_uri_type (GstURIHandler * handler)
710
{
Benjamin Otte's avatar
Benjamin Otte committed
711
  GstURIHandlerInterface *iface;
712
  GstURIType ret;
713

Benjamin Otte's avatar
Benjamin Otte committed
714
  g_return_val_if_fail (GST_IS_URI_HANDLER (handler), GST_URI_UNKNOWN);
715

Benjamin Otte's avatar
Benjamin Otte committed
716 717
  iface = GST_URI_HANDLER_GET_INTERFACE (handler);
  g_return_val_if_fail (iface != NULL, GST_URI_UNKNOWN);
718
  g_return_val_if_fail (iface->get_type != NULL, GST_URI_UNKNOWN);
719

720
  ret = iface->get_type (G_OBJECT_TYPE (handler));
Benjamin Otte's avatar
Benjamin Otte committed
721
  g_return_val_if_fail (GST_URI_TYPE_IS_VALID (ret), GST_URI_UNKNOWN);
722

Benjamin Otte's avatar
Benjamin Otte committed
723
  return ret;
724
}
725

726
/**
Benjamin Otte's avatar
Benjamin Otte committed
727
 * gst_uri_handler_get_protocols:
Edward Hervey's avatar
Edward Hervey committed
728
 * @handler: A #GstURIHandler.
729
 *
Edward Hervey's avatar
Edward Hervey committed
730
 * Gets the list of protocols supported by @handler. This list may not be
Benjamin Otte's avatar
Benjamin Otte committed
731
 * modified.
732
 *
733 734 735 736
 * Returns: (transfer none) (element-type utf8) (nullable): the
 *     supported protocols.  Returns %NULL if the @handler isn't
 *     implemented properly, or the @handler doesn't support any
 *     protocols.
737
 */
738
const gchar *const *
739
gst_uri_handler_get_protocols (GstURIHandler * handler)
740
{
Benjamin Otte's avatar
Benjamin Otte committed
741
  GstURIHandlerInterface *iface;
742
  const gchar *const *ret;
743

Benjamin Otte's avatar
Benjamin Otte committed
744
  g_return_val_if_fail (GST_IS_URI_HANDLER (handler), NULL);
745

Benjamin Otte's avatar
Benjamin Otte committed
746 747
  iface = GST_URI_HANDLER_GET_INTERFACE (handler);
  g_return_val_if_fail (iface != NULL, NULL);
748
  g_return_val_if_fail (iface->get_protocols != NULL, NULL);
749

750
  ret = iface->get_protocols (G_OBJECT_TYPE (handler));
Benjamin Otte's avatar
Benjamin Otte committed
751
  g_return_val_if_fail (ret != NULL, NULL);
752

Benjamin Otte's avatar
Benjamin Otte committed
753
  return ret;
754
}
755

756
/**
Benjamin Otte's avatar
Benjamin Otte committed
757
 * gst_uri_handler_get_uri:
Edward Hervey's avatar
Edward Hervey committed
758
 * @handler: A #GstURIHandler
759
 *
Edward Hervey's avatar
Edward Hervey committed
760
 * Gets the currently handled URI.
761
 *
762 763 764 765
 * Returns: (transfer full) (nullable): the URI currently handled by
 *   the @handler.  Returns %NULL if there are no URI currently
 *   handled. The returned string must be freed with g_free() when no
 *   longer needed.
766
 */
767
gchar *
768
gst_uri_handler_get_uri (GstURIHandler * handler)
769
{
Benjamin Otte's avatar
Benjamin Otte committed
770
  GstURIHandlerInterface *iface;
771
  gchar *ret;
772

Benjamin Otte's avatar
Benjamin Otte committed
773 774 775 776 777 778 779 780
  g_return_val_if_fail (GST_IS_URI_HANDLER (handler), NULL);

  iface = GST_URI_HANDLER_GET_INTERFACE (handler);
  g_return_val_if_fail (iface != NULL, NULL);
  g_return_val_if_fail (iface->get_uri != NULL, NULL);
  ret = iface->get_uri (handler);
  if (ret != NULL)
    g_return_val_if_fail (gst_uri_is_valid (ret), NULL);
781

Benjamin Otte's avatar
Benjamin Otte committed
782
  return ret;
783
}
784

Benjamin Otte's avatar
Benjamin Otte committed
785 786
/**
 * gst_uri_handler_set_uri:
Edward Hervey's avatar
Edward Hervey committed
787
 * @handler: A #GstURIHandler
Benjamin Otte's avatar
Benjamin Otte committed
788
 * @uri: URI to set
789
 * @error: (allow-none): address where to store a #GError in case of
790
 *    an error, or %NULL
Benjamin Otte's avatar
Benjamin Otte committed
791
 *
Edward Hervey's avatar
Edward Hervey committed
792
 * Tries to set the URI of the given handler.
Benjamin Otte's avatar
Benjamin Otte committed
793
 *
794
 * Returns: %TRUE if the URI was set successfully, else %FALSE.
Benjamin Otte's avatar
Benjamin Otte committed
795 796
 */
gboolean
797 798
gst_uri_handler_set_uri (GstURIHandler * handler, const gchar * uri,
    GError ** error)
Benjamin Otte's avatar
Benjamin Otte committed
799 800
{
  GstURIHandlerInterface *iface;
801
  gboolean ret;
802
  gchar *protocol;
803

Benjamin Otte's avatar
Benjamin Otte committed
804 805
  g_return_val_if_fail (GST_IS_URI_HANDLER (handler), FALSE);
  g_return_val_if_fail (gst_uri_is_valid (uri), FALSE);
806
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
807

Benjamin Otte's avatar
Benjamin Otte committed
808 809 810
  iface = GST_URI_HANDLER_GET_INTERFACE (handler);
  g_return_val_if_fail (iface != NULL, FALSE);
  g_return_val_if_fail (iface->set_uri != NULL, FALSE);
811 812

  protocol = gst_uri_get_protocol (uri);
813

814
  if (iface->get_protocols) {
815 816
    const gchar *const *protocols;
    const gchar *const *p;
817 818 819 820 821 822 823 824 825 826 827 828
    gboolean found_protocol = FALSE;

    protocols = iface->get_protocols (G_OBJECT_TYPE (handler));
    if (protocols != NULL) {
      for (p = protocols; *p != NULL; ++p) {
        if (g_ascii_strcasecmp (protocol, *p) == 0) {
          found_protocol = TRUE;
          break;
        }
      }

      if (!found_protocol) {
829
        g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_UNSUPPORTED_PROTOCOL,
830 831 832 833 834 835 836 837
            _("URI scheme '%s' not supported"), protocol);
        g_free (protocol);
        return FALSE;
      }
    }
  }

  ret = iface->set_uri (handler, uri, error);
838 839 840 841

  g_free (protocol);

  return ret;
Benjamin Otte's avatar
Benjamin Otte committed
842
}
843

844 845 846 847 848
static gchar *
gst_file_utils_canonicalise_path (const gchar * path)
{
  gchar **parts, **p, *clean_path;

849 850 851 852 853 854 855
#ifdef G_OS_WIN32
  {
    GST_WARNING ("FIXME: canonicalise win32 path");
    return g_strdup (path);
  }
#endif

856 857 858 859 860 861 862
  parts = g_strsplit (path, "/", -1);

  p = parts;
  while (*p != NULL) {
    if (strcmp (*p, ".") == 0) {
      /* just move all following parts on top of this, incl. NUL terminator */
      g_free (*p);
863
      memmove (p, p + 1, (g_strv_length (p + 1) + 1) * sizeof (gchar *));
864 865 866 867 868 869 870
      /* re-check the new current part again in the next iteration */
      continue;
    } else if (strcmp (*p, "..") == 0 && p > parts) {
      /* just move all following parts on top of the previous part, incl.
       * NUL terminator */
      g_free (*(p - 1));
      g_free (*p);
871
      memmove (p - 1, p + 1, (g_strv_length (p + 1) + 1) * sizeof (gchar *));
872 873 874 875 876 877 878 879 880 881 882
      /* re-check the new current part again in the next iteration */
      --p;
      continue;
    }
    ++p;
  }
  if (*path == '/') {
    guint num_parts;

    num_parts = g_strv_length (parts) + 1;      /* incl. terminator */
    parts = g_renew (gchar *, parts, num_parts + 1);
883
    memmove (parts + 1, parts, num_parts * sizeof (gchar *));
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    parts[0] = g_strdup ("/");
  }

  clean_path = g_build_filenamev (parts);
  g_strfreev (parts);
  return clean_path;
}

static gboolean
file_path_contains_relatives (const gchar * path)
{
  return (strstr (path, "/./") != NULL || strstr (path, "/../") != NULL ||
      strstr (path, G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S) != NULL ||
      strstr (path, G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S) != NULL);
}

/**
 * gst_filename_to_uri:
 * @filename: absolute or relative file name path
903
 * @error: pointer to error, or %NULL
904 905 906 907 908 909 910
 *
 * Similar to g_filename_to_uri(), but attempts to handle relative file paths
 * as well. Before converting @filename into an URI, it will be prefixed by
 * the current working directory if it is a relative path, and then the path
 * will be canonicalised so that it doesn't contain any './' or '../' segments.
 *
 * On Windows #filename should be in UTF-8 encoding.
911 912 913
 *
 * Returns: newly-allocated URI string, or NULL on error. The caller must
 *   free the URI string with g_free() when no longer needed.
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
 */
gchar *
gst_filename_to_uri (const gchar * filename, GError ** error)
{
  gchar *abs_location = NULL;
  gchar *uri, *abs_clean;

  g_return_val_if_fail (filename != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  if (g_path_is_absolute (filename)) {
    if (!file_path_contains_relatives (filename)) {
      uri = g_filename_to_uri (filename, NULL, error);
      goto beach;
    }

    abs_location = g_strdup (filename);
  } else {
    gchar *cwd;

    cwd = g_get_current_dir ();
    abs_location = g_build_filename (cwd, filename, NULL);
    g_free (cwd);

    if (!file_path_contains_relatives (abs_location)) {
      uri = g_filename_to_uri (abs_location, NULL, error);
      goto beach;
    }
  }

  /* path is now absolute, but contains '.' or '..' */
  abs_clean = gst_file_utils_canonicalise_path (abs_location);
  GST_LOG ("'%s' -> '%s' -> '%s'", filename, abs_location, abs_clean);
  uri = g_filename_to_uri (abs_clean, NULL, error);
  g_free (abs_clean);

beach:

  g_free (abs_location);
  GST_DEBUG ("'%s' -> '%s'", filename, uri);
  return uri;
}
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

/****************************************************************************
 * GstUri - GstMiniObject to parse and merge URIs according to IETF RFC 3986
 ****************************************************************************/

/**
 * SECTION:gsturi
 * @short_description: URI parsing and manipulation.
 *
 * A #GstUri object can be used to parse and split a URI string into its
 * constituant parts. Two #GstUri objects can be joined to make a new #GstUri
 * using the algorithm described in RFC3986.
 */

/* Definition for GstUri object */
struct _GstUri
{
  /*< private > */
  GstMiniObject mini_object;
  gchar *scheme;
  gchar *userinfo;
  gchar *host;
  guint port;
  GList *path;
  GHashTable *query;
  gchar *fragment;
};

GST_DEFINE_MINI_OBJECT_TYPE (GstUri, gst_uri);

static GstUri *_gst_uri_copy (const GstUri * uri);
static void _gst_uri_free (GstUri * uri);
static GstUri *_gst_uri_new (void);
static GList *_remove_dot_segments (GList * path);

991
/* private GstUri functions */
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

static GstUri *
_gst_uri_new (void)
{
  GstUri *uri;
  uri = GST_URI_CAST (g_slice_new0 (GstUri));

  if (uri)
    gst_mini_object_init (GST_MINI_OBJECT_CAST (uri), 0, gst_uri_get_type (),
        (GstMiniObjectCopyFunction) _gst_uri_copy, NULL,
        (GstMiniObjectFreeFunction) _gst_uri_free);

  return uri;
}

static void
_gst_uri_free (GstUri * uri)
{
  g_return_if_fail (GST_IS_URI (uri));

  g_free (uri->scheme);
  g_free (uri->userinfo);
  g_free (uri->host);
  g_list_free_full (uri->path, g_free);
  if (uri->query)
    g_hash_table_unref (uri->query);
  g_free (uri->fragment);

  g_slice_free1 (sizeof (*uri), uri);
}

static GHashTable *
_gst_uri_copy_query_table (GHashTable * orig)
{
  GHashTable *new = NULL;

  if (orig != NULL) {
    GHashTableIter iter;
    gpointer key, value;
    new = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
    g_hash_table_iter_init (&iter, orig);
    while (g_hash_table_iter_next (&iter, &key, &value)) {
      g_hash_table_insert (new, g_strdup (key), g_strdup (value));
    }
  }

  return new;
}

static GstUri *
_gst_uri_copy (const GstUri * orig_uri)
{
  GstUri *new_uri;

  g_return_val_if_fail (GST_IS_URI (orig_uri), NULL);

  new_uri = _gst_uri_new ();

  if (new_uri) {
    new_uri->scheme = g_strdup (orig_uri->scheme);
    new_uri->userinfo = g_strdup (orig_uri->userinfo);
    new_uri->host = g_strdup (orig_uri->host);
    new_uri->port = orig_uri->port;
    new_uri->path = g_list_copy_deep (orig_uri->path, (GCopyFunc) g_strdup,
        NULL);
    new_uri->query = _gst_uri_copy_query_table (orig_uri->query);
    new_uri->fragment = g_strdup (orig_uri->fragment);
  }

  return new_uri;
}

/*
 * _gst_uri_compare_lists:
 *
 * Compare two lists for equality. This compares the two lists, item for item,
 * comparing items in the same position in the two lists. If @first is
 * considered less than @second the result will be negative. If @first is
 * considered to be more than @second then the result will be positive. If the
 * lists are considered to be equal then the result will be 0. If two lists
 * have the same items, but one list is shorter than the other, then the
 * shorter list is considered to be less than the longer list.
 */
static gint
_gst_uri_compare_lists (GList * first, GList * second, GCompareFunc cmp_fn)
{
  GList *itr1, *itr2;
  gint result;

  for (itr1 = first, itr2 = second;
      itr1 != NULL || itr2 != NULL; itr1 = itr1->next, itr2 = itr2->next) {
    if (itr1 == NULL)
      return -1;
    if (itr2 == NULL)
      return 1;
    result = cmp_fn (itr1->data, itr2->data);
    if (result != 0)
      return result;
  }
  return 0;
}

typedef enum
{
  _GST_URI_NORMALIZE_LOWERCASE = 1,
  _GST_URI_NORMALIZE_UPPERCASE = 2
} _GstUriNormalizations;

/*
 * Find the first character that hasn't been normalized according to the @flags.
 */
static gchar *
_gst_uri_first_non_normalized_char (gchar * str, guint flags)
{
  gchar *pos;

  if (str == NULL)
    return NULL;

  for (pos = str; *pos; pos++) {
    if ((flags & _GST_URI_NORMALIZE_UPPERCASE) && g_ascii_islower (*pos))
      return pos;
    if ((flags & _GST_URI_NORMALIZE_LOWERCASE) && g_ascii_isupper (*pos))
      return pos;
  }
  return NULL;
}

static gboolean
_gst_uri_normalize_lowercase (gchar * str)
{
  gchar *pos;
  gboolean ret = FALSE;

  for (pos = _gst_uri_first_non_normalized_char (str,
          _GST_URI_NORMALIZE_LOWERCASE);
      pos != NULL;
      pos = _gst_uri_first_non_normalized_char (pos + 1,
          _GST_URI_NORMALIZE_LOWERCASE)) {
    *pos = g_ascii_tolower (*pos);
    ret = TRUE;
  }

  return ret;
}

#define _gst_uri_normalize_scheme _gst_uri_normalize_lowercase
#define _gst_uri_normalize_hostname _gst_uri_normalize_lowercase

static gboolean
_gst_uri_normalize_path (GList ** path)
{
  GList *new_path;

  new_path = _remove_dot_segments (*path);
  if (_gst_uri_compare_lists (new_path, *path, (GCompareFunc) g_strcmp0) != 0) {
    g_list_free_full (*path, g_free);
    *path = new_path;
    return TRUE;
  }
  g_list_free_full (new_path, g_free);

  return FALSE;
}

static gboolean
_gst_uri_normalize_str_noop (gchar * str)
{
  return FALSE;
}

static gboolean
_gst_uri_normalize_table_noop (GHashTable * table)
{
  return FALSE;
}

#define _gst_uri_normalize_userinfo _gst_uri_normalize_str_noop
#define _gst_uri_normalize_query _gst_uri_normalize_table_noop
#define _gst_uri_normalize_fragment _gst_uri_normalize_str_noop

1173
/* RFC 3986 functions */
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

static GList *
_merge (GList * base, GList * path)
{
  GList *ret, *path_copy, *last;

  path_copy = g_list_copy_deep (path, (GCopyFunc) g_strdup, NULL);
  /* if base is NULL make path absolute */
  if (base == NULL) {
    if (path_copy != NULL && path_copy->data != NULL) {
      path_copy = g_list_prepend (path_copy, NULL);
    }
    return path_copy;
  }

  ret = g_list_copy_deep (base, (GCopyFunc) g_strdup, NULL);
  last = g_list_last (ret);
  ret = g_list_remove_link (ret, last);
  g_list_free_full (last, g_free);
  ret = g_list_concat (ret, path_copy);

  return ret;
}

static GList *
_remove_dot_segments (GList * path)
{
  GList *out, *elem, *next;

  if (path == NULL)
    return NULL;

  out = g_list_copy_deep (path, (GCopyFunc) g_strdup, NULL);

  for (elem = out; elem; elem = next) {
    next = elem->next;
    if (elem->data == NULL && elem != out && next != NULL) {
      out = g_list_delete_link (out, elem);
    } else if (g_strcmp0 (elem->data, ".") == 0) {
      g_free (elem->data);
      out = g_list_delete_link (out, elem);
    } else if (g_strcmp0 (elem->data, "..") == 0) {
      GList *prev = g_list_previous (elem);
      if (prev && (prev != out || prev->data != NULL)) {
        g_free (prev->data);
        out = g_list_delete_link (out, prev);
      }
      g_free (elem->data);
      out = g_list_delete_link (out, elem);
    }
  }

  return out;
}

static gchar *
_gst_uri_escape_userinfo (const gchar * userinfo)
{
  return g_uri_escape_string (userinfo,
      G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
}

static gchar *
_gst_uri_escape_host (const gchar * host)
{
  return g_uri_escape_string (host,
      G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, FALSE);
}

David Waring's avatar
David Waring committed
1243 1244 1245 1246 1247 1248 1249
static gchar *
_gst_uri_escape_host_colon (const gchar * host)
{
  return g_uri_escape_string (host,
      G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS ":", FALSE);
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
static gchar *
_gst_uri_escape_path_segment (const gchar * segment)
{
  return g_uri_escape_string (segment,
      G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT, FALSE);
}

static gchar *
_gst_uri_escape_http_query_element (const gchar * element)
{
  gchar *ret, *c;

  ret = g_uri_escape_string (element, "!$'()*,;:@/? ", FALSE);
  for (c = ret; *c; c++)
    if (*c == ' ')
      *c = '+';
  return ret;
}

static gchar *
_gst_uri_escape_fragment (const gchar * fragment)
{
  return g_uri_escape_string (fragment,
      G_URI_RESERVED_CHARS_ALLOWED_IN_PATH "?", FALSE);
}

static GList *
_gst_uri_string_to_list (const gchar * str, const gchar * sep, gboolean convert,
    gboolean unescape)
{
  GList *new_list = NULL;

  if (str) {
    guint pct_sep_len = 0;
1284
    gchar *pct_sep = NULL;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    gchar **split_str;

    if (convert && !unescape) {
      pct_sep = g_strdup_printf ("%%%2.2X", (guint) (*sep));
      pct_sep_len = 3;
    }

    split_str = g_strsplit (str, sep, -1);
    if (split_str) {
      gchar **next_elem;
      for (next_elem = split_str; *next_elem; next_elem += 1) {
        gchar *elem = *next_elem;
        if (*elem == '\0') {
          new_list = g_list_append (new_list, NULL);
        } else {
          if (convert && !unescape) {
            gchar *next_sep;
            for (next_sep = strcasestr (elem, pct_sep); next_sep;
                next_sep = strcasestr (next_sep + 1, pct_sep)) {
              *next_sep = *sep;
              memmove (next_sep + 1, next_sep + pct_sep_len,
                  strlen (next_sep + pct_sep_len) + 1);
            }
          }
          if (unescape) {
            *next_elem = g_uri_unescape_string (elem, NULL);
            g_free (elem);
            elem = *next_elem;
          }
          new_list = g_list_append (new_list, g_strdup (elem));
        }
      }
    }
    g_strfreev (split_str);
    if (convert && !unescape)
      g_free (pct_sep);
  }

  return new_list;
}

static GHashTable *
_gst_uri_string_to_table (const gchar * str, const gchar * part_sep,
    const gchar * kv_sep, gboolean convert, gboolean unescape)
{
  GHashTable *new_table = NULL;

  if (str) {
1333
    gchar *pct_part_sep = NULL, *pct_kv_sep = NULL;
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
    gchar **split_parts;

    new_table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

    if (convert && !unescape) {
      pct_part_sep = g_strdup_printf ("%%%2.2X", (guint) (*part_sep));
      pct_kv_sep = g_strdup_printf ("%%%2.2X", (guint) (*kv_sep));
    }

    split_parts = g_strsplit (str, part_sep, -1);
    if (split_parts) {
      gchar **next_part;
      for (next_part = split_parts; *next_part; next_part += 1) {
        gchar *part = *next_part;
        gchar *kv_sep_pos;
        gchar *key, *value;
        /* if we are converting percent encoded versions of separators then
         *  substitute the part separator now. */
        if (convert && !unescape) {
          gchar *next_sep;
          for (next_sep = strcasestr (part, pct_part_sep); next_sep;
              next_sep = strcasestr (next_sep + 1, pct_part_sep)) {
            *next_sep = *part_sep;
            memmove (next_sep + 1, next_sep + 3, strlen (next_sep + 3) + 1);
          }
        }
        /* find the key/value separator within the part */
        kv_sep_pos = g_strstr_len (part, -1, kv_sep);
        if (kv_sep_pos == NULL) {
          if (unescape) {
            key = g_uri_unescape_string (part, NULL);
          } else {
            key = g_strdup (part);
          }
          value = NULL;
        } else {
          if (unescape) {
            key = g_uri_unescape_segment (part, kv_sep_pos, NULL);
            value = g_uri_unescape_string (kv_sep_pos + 1, NULL);
          } else {
            key = g_strndup (part, kv_sep_pos - part);
            value = g_strdup (kv_sep_pos + 1);
          }
        }
        /* if we are converting percent encoded versions of separators then
         *  substitute the key/value separator in both key and value now. */
        if (convert && !unescape) {
          gchar *next_sep;
          for (next_sep = strcasestr (key, pct_kv_sep); next_sep;
              next_sep = strcasestr (next_sep + 1, pct_kv_sep)) {
            *next_sep = *kv_sep;
            memmove (next_sep + 1, next_sep + 3, strlen (next_sep + 3) + 1);
          }
          if (value) {
            for (next_sep = strcasestr (value, pct_kv_sep); next_sep;
                next_sep = strcasestr (next_sep + 1, pct_kv_sep)) {
              *next_sep = *kv_sep;
              memmove (next_sep + 1, next_sep + 3, strlen (next_sep + 3) + 1);
            }
          }
        }
        /* add value to the table */
        g_hash_table_insert (new_table, key, value);
      }
    }
    /* tidy up */
    g_strfreev (split_parts);
    if (convert && !unescape) {
      g_free (pct_part_sep);
      g_free (pct_kv_sep);
    }
  }

  return new_table;
}


/*
 * Method definitions.
 */

/**
 * gst_uri_new:
 * @scheme: (nullable): The scheme for the new URI.
 * @userinfo: (nullable): The user-info for the new URI.
 * @host: (nullable): The host name for the new URI.
 * @port: The port number for the new URI or %GST_URI_NO_PORT.
 * @path: (nullable): The path for the new URI with '/' separating path
 *                      elements.
 * @query: (nullable): The query string for the new URI with '&' separating
 *                       query elements. Elements containing '&' characters
1425
 *                       should encode them as "&percnt;26".
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
 * @fragment: (nullable): The fragment name for the new URI.
 *
 * Creates a new #GstUri object with the given URI parts. The path and query
 * strings will be broken down into their elements. All strings should not be
 * escaped except where indicated.
 *
 * Returns: (transfer full): A new #GstUri object.
 *
 * Since: 1.6
 */
GstUri *
gst_uri_new (const gchar * scheme, const gchar * userinfo, const gchar * host,
    guint port, const gchar * path, const gchar * query, const gchar * fragment)
{
  GstUri *new_uri;

  new_uri = _gst_uri_new ();
  if (new_uri) {
    new_uri->scheme = g_strdup (scheme);
    new_uri->userinfo = g_strdup (userinfo);
    new_uri->host = g_strdup (host);
    new_uri->port = port;
    new_uri->path = _gst_uri_string_to_list (path, "/", FALSE, FALSE);
    new_uri->query = _gst_uri_string_to_table (query, "&", "=", TRUE, FALSE);
    new_uri->fragment = g_strdup (fragment);
  }

  return new_uri;
}

/**
 * gst_uri_new_with_base:
 * @base: (transfer none)(nullable): The base URI to join the new URI to.
 * @scheme: (nullable): The scheme for the new URI.
 * @userinfo: (nullable): The user-info for the new URI.
 * @host: (nullable): The host name for the new URI.
 * @port: The port number for the new URI or %GST_URI_NO_PORT.
 * @path: (nullable): The path for the new URI with '/' separating path
 *                      elements.
 * @query: (nullable): The query string for the new URI with '&' separating
 *                       query elements. Elements containing '&' characters
1467
 *                       should encode them as "&percnt;26".
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
 * @fragment: (nullable): The fragment name for the new URI.
 *
 * Like gst_uri_new(), but joins the new URI onto a base URI.
 *
 * Returns: (transfer full): The new URI joined onto @base.
 *
 * Since: 1.6
 */
GstUri *
gst_uri_new_with_base (GstUri * base, const gchar * scheme,
    const gchar * userinfo, const gchar * host, guint port, const gchar * path,
    const gchar * query, const gchar * fragment)
{
  GstUri *new_rel_uri;
  GstUri *new_uri;

  g_return_val_if_fail (base == NULL || GST_IS_URI (base), NULL);

  new_rel_uri = gst_uri_new (scheme, userinfo, host, port, path, query,
      fragment);
  new_uri = gst_uri_join (base, new_rel_uri);
  gst_uri_unref (new_rel_uri);

  return new_uri;
}

/**
 * gst_uri_from_string:
 * @uri: The URI string to parse.
 *
David Waring's avatar
David Waring committed
1498 1499
 * Parses a URI string into a new #GstUri object. Will return NULL if the URI
 * cannot be parsed.
1500
 *
David Waring's avatar
David Waring committed
1501
 * Returns: (transfer full)(nullable): A new #GstUri object, or NULL.
1502 1503 1504 1505 1506 1507
 *
 * Since: 1.6
 */
GstUri *
gst_uri_from_string (const gchar * uri)
{
David Waring's avatar
David Waring committed
1508
  const gchar *orig_uri = uri;
1509 1510 1511 1512 1513 1514
  GstUri *uri_obj;

  uri_obj = _gst_uri_new ();

  if (uri_obj && uri != NULL) {
    int i = 0;
David Waring's avatar
David Waring committed
1515 1516

    /* be helpful and skip initial white space */
Sebastian Dröge's avatar
Sebastian Dröge committed
1517 1518
    while (*uri == '\v' || g_ascii_isspace (*uri))
      uri++;
David Waring's avatar
David Waring committed
1519

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    if (g_ascii_isalpha (uri[i])) {
      /* find end of scheme name */
      i++;
      while (g_ascii_isalnum (uri[i]) || uri[i] == '+' || uri[i] == '-' ||
          uri[i] == '.')
        i++;
    }
    if (i > 0 && uri[i] == ':') {
      /* get scheme */
      uri_obj->scheme = g_strndup (uri, i);
      uri += i + 1;
    }
    if (uri[0] == '/' && uri[1] == '/') {
David Waring's avatar
David Waring committed
1533
      const gchar *eoa, *eoui, *eoh, *reoh;
1534 1535 1536
      /* get authority [userinfo@]host[:port] */
      uri += 2;
      /* find end of authority */
David Waring's avatar
David Waring committed
1537 1538
      eoa = uri + strcspn (uri, "/?#");

1539 1540 1541 1542 1543 1544 1545 1546 1547
      /* find end of userinfo */
      eoui = strchr (uri, '@');
      if (eoui != NULL && eoui < eoa) {
        uri_obj->userinfo = g_uri_unescape_segment (uri, eoui, NULL);
        uri = eoui + 1;
      }
      /* find end of host */
      if (uri[0] == '[') {
        eoh = strchr (uri, ']');
David Waring's avatar
David Waring committed
1548 1549
        if (eoh == NULL || eoh > eoa) {
          GST_DEBUG ("Unable to parse the host part of the URI '%s'.",
Sebastian Dröge's avatar
Sebastian Dröge committed
1550 1551
              orig_uri);
          _gst_uri_free (uri_obj);
David Waring's avatar
David Waring committed
1552 1553 1554 1555
          return NULL;
        }
        reoh = eoh + 1;
        uri++;
1556
      } else {
David Waring's avatar
David Waring committed
1557 1558 1559
        reoh = eoh = strchr (uri, ':');
        if (eoh == NULL || eoh > eoa)
          reoh = eoh = eoa;
1560
      }
David Waring's avatar
David Waring committed
1561 1562 1563 1564 1565
      /* don't capture empty host strings */
      if (eoh != uri)
        uri_obj->host = g_uri_unescape_segment (uri, eoh, NULL);

      uri = reoh;
1566
      if (uri < eoa) {
David Waring's avatar
David Waring committed
1567
        /* if port number is malformed then we can't parse this */
1568
        if (uri[0] != ':' || strspn (uri + 1, "0123456789") != eoa - uri - 1) {
David Waring's avatar
David Waring committed
1569
          GST_DEBUG ("Unable to parse host/port part of the URI '%s'.",
Sebastian Dröge's avatar
Sebastian Dröge committed
1570
              orig_uri);
David Waring's avatar
David Waring committed
1571 1572 1573 1574 1575 1576 1577
          _gst_uri_free (uri_obj);
          return NULL;
        }
        /* otherwise treat port as unsigned decimal number */
        uri++;
        while (uri < eoa) {
          uri_obj->port = uri_obj->port * 10 + g_ascii_digit_value (*uri);
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690