strings.c 32.9 KB
Newer Older
1 2 3 4 5 6 7 8
/*****************************************************************************
 * strings.c: String related functions
 *****************************************************************************
 * Copyright (C) 2006 the VideoLAN team
 * $Id$
 *
 * Authors: Antoine Cellerier <dionoea at videolan dot org>
 *          Daniel Stranger <vlc at schmaller dot de>
9
 *          Rémi Denis-Courmont <rem # videolan org>
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
29 30 31 32
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

33
#include <vlc_common.h>
34
#include <assert.h>
35

36 37 38 39
/* Needed by str_format_time */
#include <time.h>

/* Needed by str_format_meta */
Clément Stenac's avatar
Clément Stenac committed
40 41 42 43
#include <vlc_input.h>
#include <vlc_meta.h>
#include <vlc_playlist.h>
#include <vlc_aout.h>
44

Clément Stenac's avatar
Clément Stenac committed
45 46 47
#include <vlc_strings.h>
#include <vlc_url.h>
#include <vlc_charset.h>
48 49

/**
50
 * Unescape URI encoded string
51 52
 * \return decoded duplicated string
 */
53
char *unescape_URI_duplicate( const char *psz )
54 55
{
    char *psz_dup = strdup( psz );
56
    unescape_URI( psz_dup );
57 58 59 60
    return psz_dup;
}

/**
61
 * Unescape URI encoded string in place
62 63
 * \return nothing
 */
64
void unescape_URI( char *psz )
65
{
66
    unsigned char *in = (unsigned char *)psz, *out = in, c;
67 68
    if( psz == NULL )
        return;
69

70
    while( ( c = *in++ ) != '\0' )
71
    {
72
        switch( c )
73
        {
74
            case '%':
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
                char val[5], *pval = val;
                unsigned long cp;

                switch( c = *in++ )
                {
                    case '\0':
                        return;

                    case 'u':
                    case 'U':
                        if( ( *pval++ = *in++ ) == '\0' )
                            return;
                        if( ( *pval++ = *in++ ) == '\0' )
                            return;
                        c = *in++;

                    default:
                        *pval++ = c;
                        if( ( *pval++ = *in++ ) == '\0' )
                            return;
                        *pval = '\0';
                }

                cp = strtoul( val, NULL, 0x10 );
                if( cp < 0x80 )
                    *out++ = cp;
                else
                if( cp < 0x800 )
                {
                    *out++ = (( cp >>  6)         | 0xc0);
                    *out++ = (( cp        & 0x3f) | 0x80);
                }
                else
                {
                    assert( cp < 0x10000 );
                    *out++ = (( cp >> 12)         | 0xe0);
                    *out++ = (((cp >>  6) & 0x3f) | 0x80);
                    *out++ = (( cp        & 0x3f) | 0x80);
                }
115 116 117
                break;
            }

118
            /* + is not a special case - it means plus, not space. */
119

120 121 122 123 124 125 126
            default:
                /* Inserting non-ASCII or non-printable characters is unsafe,
                 * and no sane browser will send these unencoded */
                if( ( c < 32 ) || ( c > 127 ) )
                    *out++ = '?';
                else
                    *out++ = c;
127 128
        }
    }
129
    *out = '\0';
130 131
}

132 133 134 135 136 137 138
/**
 * Decode encoded URI string
 * \return decoded duplicated string
 */
char *decode_URI_duplicate( const char *psz )
{
    char *psz_dup = strdup( psz );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
139
    decode_URI( psz_dup );
140 141 142 143 144 145 146 147 148 149
    return psz_dup;
}

/**
 * Decode encoded URI string in place
 * \return nothing
 */
void decode_URI( char *psz )
{
    unsigned char *in = (unsigned char *)psz, *out = in, c;
150 151
    if( psz == NULL )
        return;
152 153 154 155 156 157 158

    while( ( c = *in++ ) != '\0' )
    {
        switch( c )
        {
            case '%':
            {
Rémi Denis-Courmont's avatar
Lalala  
Rémi Denis-Courmont committed
159
                char hex[3];
160 161 162 163 164 165 166 167 168 169 170 171

                if( ( ( hex[0] = *in++ ) == 0 )
                 || ( ( hex[1] = *in++ ) == 0 ) )
                    return;

                hex[2] = '\0';
                *out++ = (unsigned char)strtoul( hex, NULL, 0x10 );
                break;
            }

            case '+':
                *out++ = ' ';
172
                break;
173 174 175 176 177 178 179 180 181 182 183 184 185 186

            default:
                /* Inserting non-ASCII or non-printable characters is unsafe,
                 * and no sane browser will send these unencoded */
                if( ( c < 32 ) || ( c > 127 ) )
                    *out++ = '?';
                else
                    *out++ = c;
        }
    }
    *out = '\0';
    EnsureUTF8( psz );
}

187
static inline bool isurisafe( int c )
188
{
189
    /* These are the _unreserved_ URI characters (RFC3986 §2.3) */
190 191 192
    return ( (unsigned char)( c - 'a' ) < 26 )
            || ( (unsigned char)( c - 'A' ) < 26 )
            || ( (unsigned char)( c - '0' ) < 10 )
193
            || ( strchr( "-._~", c ) != NULL );
194 195 196
}

/**
197
 * Encodes an URI component (RFC3986 §2).
198
 *
199
 * @param psz_uri nul-terminated UTF-8 representation of the component.
200 201 202
 * Obviously, you can't pass an URI containing a nul character, but you don't
 * want to do that, do you?
 *
203
 * @return encoded string (must be free()'d), or NULL for ENOMEM.
204
 */
205
char *encode_URI_component( const char *psz_uri )
206
{
207
    char *psz_enc = malloc ((3 * strlen (psz_uri)) + 1), *out = psz_enc;
208

209 210 211 212
    if (psz_enc == NULL)
        return NULL;

    while (*psz_uri)
213
    {
214 215
        static const char hex[16] = "0123456789ABCDEF";
        uint8_t c = *psz_uri;
216

217 218 219 220
        if( isurisafe( c ) )
            *out++ = c;
        /* This is URI encoding, not HTTP forms:
         * Space is encoded as '%20', not '+'. */
221 222 223
        else
        {
            *out++ = '%';
224 225
            *out++ = hex[c >> 4];
            *out++ = hex[c & 0xf];
226
        }
227
        psz_uri++;
228 229 230
    }
    *out++ = '\0';

231 232
    out = realloc (psz_enc, out - psz_enc);
    return out ? out : psz_enc; /* realloc() can fail (safe) */
233 234
}

235
static const struct xml_entity_s
236
{
Antoine Cellerier's avatar
Antoine Cellerier committed
237
    char    psz_entity[8];
238
    char    psz_char[4];
239
} xml_entities[] = {
240
    /* Important: this list has to be in alphabetical order (psz_entity-wise) */
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    { "AElig;",  "Æ" },
    { "Aacute;", "Á" },
    { "Acirc;",  "Â" },
    { "Agrave;", "À" },
    { "Aring;",  "Å" },
    { "Atilde;", "Ã" },
    { "Auml;",   "Ä" },
    { "Ccedil;", "Ç" },
    { "Dagger;", "‡" },
    { "ETH;",    "Ð" },
    { "Eacute;", "É" },
    { "Ecirc;",  "Ê" },
    { "Egrave;", "È" },
    { "Euml;",   "Ë" },
    { "Iacute;", "Í" },
    { "Icirc;",  "Î" },
    { "Igrave;", "Ì" },
    { "Iuml;",   "Ï" },
    { "Ntilde;", "Ñ" },
    { "OElig;",  "Œ" },
    { "Oacute;", "Ó" },
    { "Ocirc;",  "Ô" },
    { "Ograve;", "Ò" },
    { "Oslash;", "Ø" },
    { "Otilde;", "Õ" },
    { "Ouml;",   "Ö" },
    { "Scaron;", "Š" },
    { "THORN;",  "Þ" },
    { "Uacute;", "Ú" },
    { "Ucirc;",  "Û" },
    { "Ugrave;", "Ù" },
    { "Uuml;",   "Ü" },
    { "Yacute;", "Ý" },
    { "Yuml;",   "Ÿ" },
    { "aacute;", "á" },
    { "acirc;",  "â" },
    { "acute;",  "´" },
    { "aelig;",  "æ" },
    { "agrave;", "à" },
280
    { "amp;",    "&" },
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
281
    { "apos;",   "'" },
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    { "aring;",  "å" },
    { "atilde;", "ã" },
    { "auml;",   "ä" },
    { "bdquo;",  "„" },
    { "brvbar;", "¦" },
    { "ccedil;", "ç" },
    { "cedil;",  "¸" },
    { "cent;",   "¢" },
    { "circ;",   "ˆ" },
    { "copy;",   "©" },
    { "curren;", "¤" },
    { "dagger;", "†" },
    { "deg;",    "°" },
    { "divide;", "÷" },
    { "eacute;", "é" },
    { "ecirc;",  "ê" },
    { "egrave;", "è" },
    { "eth;",    "ð" },
    { "euml;",   "ë" },
    { "euro;",   "€" },
    { "frac12;", "½" },
    { "frac14;", "¼" },
    { "frac34;", "¾" },
305
    { "gt;",     ">" },
306 307 308 309 310 311 312 313 314 315 316
    { "hellip;", "…" },
    { "iacute;", "í" },
    { "icirc;",  "î" },
    { "iexcl;",  "¡" },
    { "igrave;", "ì" },
    { "iquest;", "¿" },
    { "iuml;",   "ï" },
    { "laquo;",  "«" },
    { "ldquo;",  "“" },
    { "lsaquo;", "‹" },
    { "lsquo;",  "‘" },
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
317
    { "lt;",     "<" },
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    { "macr;",   "¯" },
    { "mdash;",  "—" },
    { "micro;",  "µ" },
    { "middot;", "·" },
    { "nbsp;",   "\xc2\xa0" },
    { "ndash;",  "–" },
    { "not;",    "¬" },
    { "ntilde;", "ñ" },
    { "oacute;", "ó" },
    { "ocirc;",  "ô" },
    { "oelig;",  "œ" },
    { "ograve;", "ò" },
    { "ordf;",   "ª" },
    { "ordm;",   "º" },
    { "oslash;", "ø" },
    { "otilde;", "õ" },
    { "ouml;",   "ö" },
    { "para;",   "¶" },
    { "permil;", "‰" },
    { "plusmn;", "±" },
    { "pound;",  "£" },
339
    { "quot;",   "\"" },
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    { "raquo;",  "»" },
    { "rdquo;",  "”" },
    { "reg;",    "®" },
    { "rsaquo;", "›" },
    { "rsquo;",  "’" },
    { "sbquo;",  "‚" },
    { "scaron;", "š" },
    { "sect;",   "§" },
    { "shy;",    "­" },
    { "sup1;",   "¹" },
    { "sup2;",   "²" },
    { "sup3;",   "³" },
    { "szlig;",  "ß" },
    { "thorn;",  "þ" },
    { "tilde;",  "˜" },
    { "times;",  "×" },
    { "trade;",  "™" },
    { "uacute;", "ú" },
    { "ucirc;",  "û" },
    { "ugrave;", "ù" },
    { "uml;",    "¨" },
    { "uuml;",   "ü" },
    { "yacute;", "ý" },
    { "yen;",    "¥" },
    { "yuml;",   "ÿ" },
365 366
};

367 368 369 370 371 372 373 374
static int cmp_entity (const void *key, const void *elem)
{
    const struct xml_entity_s *ent = elem;
    const char *name = key;

    return strncmp (name, ent->psz_entity, strlen (ent->psz_entity));
}

375 376 377 378 379 380 381 382 383 384
/**
 * Converts "&lt;", "&gt;" and "&amp;" to "<", ">" and "&"
 * \param string to convert
 */
void resolve_xml_special_chars( char *psz_value )
{
    char *p_pos = psz_value;

    while ( *psz_value )
    {
385
        if( *psz_value == '&' )
386
        {
387 388
            if( psz_value[1] == '#' )
            {   /* &#xxx; Unicode code point */
389
                char *psz_end;
390
                unsigned long cp = strtoul( psz_value+2, &psz_end, 10 );
391 392
                if( *psz_end == ';' )
                {
393 394 395 396 397 398 399 400 401 402 403 404
                    psz_value = psz_end + 1;
                    if( cp == 0 )
                        (void)0; /* skip nuls */
                    else
                    if( cp <= 0x7F )
                    {
                        *p_pos =            cp;
                    }
                    else
                    /* Unicode code point outside ASCII.
                     * &#xxx; representation is longer than UTF-8 :) */
                    if( cp <= 0x7FF )
405
                    {
406 407
                        *p_pos++ = 0xC0 |  (cp >>  6);
                        *p_pos   = 0x80 |  (cp        & 0x3F);
408 409
                    }
                    else
410
                    if( cp <= 0xFFFF )
411
                    {
412 413 414 415 416 417 418 419 420 421 422
                        *p_pos++ = 0xE0 |  (cp >> 12);
                        *p_pos++ = 0x80 | ((cp >>  6) & 0x3F);
                        *p_pos   = 0x80 |  (cp        & 0x3F);
                    }
                    else
                    if( cp <= 0x1FFFFF ) /* Outside the BMP */
                    {   /* Unicode stops at 10FFFF, but who cares? */
                        *p_pos++ = 0xF0 |  (cp >> 18);
                        *p_pos++ = 0x80 | ((cp >> 12) & 0x3F);
                        *p_pos++ = 0x80 | ((cp >>  6) & 0x3F);
                        *p_pos   = 0x80 |  (cp        & 0x3F);
423 424 425 426 427 428 429 430 431 432
                    }
                }
                else
                {
                    /* Invalid entity number */
                    *p_pos = *psz_value;
                    psz_value++;
                }
            }
            else
433
            {   /* Well-known XML entity */
434 435
                const struct xml_entity_s *ent;

436
                ent = bsearch (psz_value + 1, xml_entities,
437 438 439
                               sizeof (xml_entities) / sizeof (*ent),
                               sizeof (*ent), cmp_entity);
                if (ent != NULL)
440
                {
441 442 443 444
                    size_t olen = strlen (ent->psz_char);
                    memcpy (p_pos, ent->psz_char, olen);
                    p_pos += olen - 1;
                    psz_value += strlen (ent->psz_entity) + 1;
445
                }
446 447
                else
                {   /* No match */
448 449 450
                    *p_pos = *psz_value;
                    psz_value++;
                }
451
            }
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        }
        else
        {
            *p_pos = *psz_value;
            psz_value++;
        }

        p_pos++;
    }

    *p_pos = '\0';
}

/**
 * Converts '<', '>', '\"', '\'' and '&' to their html entities
 * \param psz_content simple element content that is to be converted
 */
char *convert_xml_special_chars( const char *psz_content )
{
    char *psz_temp = malloc( 6 * strlen( psz_content ) + 1 );
    const char *p_from = psz_content;
    char *p_to   = psz_temp;

    while ( *p_from )
    {
        if ( *p_from == '<' )
        {
            strcpy( p_to, "&lt;" );
            p_to += 4;
        }
        else if ( *p_from == '>' )
        {
            strcpy( p_to, "&gt;" );
            p_to += 4;
        }
        else if ( *p_from == '&' )
        {
            strcpy( p_to, "&amp;" );
            p_to += 5;
        }
        else if( *p_from == '\"' )
        {
            strcpy( p_to, "&quot;" );
            p_to += 6;
        }
        else if( *p_from == '\'' )
        {
            strcpy( p_to, "&#039;" );
            p_to += 6;
        }
        else
        {
            *p_to = *p_from;
            p_to++;
        }
        p_from++;
    }
    *p_to = '\0';

    return psz_temp;
}
513

514
/* Base64 encoding */
515
char *vlc_b64_encode_binary( const uint8_t *src, size_t i_src )
516 517 518 519
{
    static const char b64[] =
           "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

520 521 522
    char *ret = malloc( ( i_src + 4 ) * 4 / 3 );
    char *dst = ret;

523 524 525
    if( dst == NULL )
        return NULL;

526
    while( i_src > 0 )
527 528
    {
        /* pops (up to) 3 bytes of input, push 4 bytes */
529 530 531 532 533
        uint32_t v;

        /* 1/3 -> 1/4 */
        v = *src++ << 24;
        *dst++ = b64[v >> 26];
534 535
        v = v << 6;

536 537 538 539
        /* 2/3 -> 2/4 */
        if( i_src >= 2 )
            v |= *src++ << 22;
        *dst++ = b64[v >> 26];
540 541
        v = v << 6;

542 543 544 545
        /* 3/3 -> 3/4 */
        if( i_src >= 3 )
            v |= *src++ << 20; // 3/3
        *dst++ = ( i_src >= 2 ) ? b64[v >> 26] : '='; // 3/4
546 547
        v = v << 6;

548 549
        /* -> 4/4 */
        *dst++ = ( i_src >= 3 ) ? b64[v >> 26] : '='; // 4/4
550

551 552 553
        if( i_src <= 3 )
            break;
        i_src -= 3;
554 555 556 557 558 559 560
    }

    *dst = '\0';

    return ret;
}

561 562 563 564 565 566 567 568
char *vlc_b64_encode( const char *src )
{
    if( src )
        return vlc_b64_encode_binary( (const uint8_t*)src, strlen(src) );
    else
        return vlc_b64_encode_binary( (const uint8_t*)"", 0 );
}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
/* Base64 decoding */
size_t vlc_b64_decode_binary_to_buffer( uint8_t *p_dst, size_t i_dst, const char *p_src )
{
    static const int b64[256] = {
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
        52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
        -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
        15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
        -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
        41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
    };
    uint8_t *p_start = p_dst;
    uint8_t *p = (uint8_t *)p_src;

    int i_level;
    int i_last;

596
    for( i_level = 0, i_last = 0; (size_t)( p_dst - p_start ) < i_dst && *p != '\0'; p++ )
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    {
        const int c = b64[(unsigned int)*p];
        if( c == -1 )
            continue;

        switch( i_level )
        {
            case 0:
                i_level++;
                break;
            case 1:
                *p_dst++ = ( i_last << 2 ) | ( ( c >> 4)&0x03 );
                i_level++;
                break;
            case 2:
                *p_dst++ = ( ( i_last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
                i_level++;
                break;
            case 3:
                *p_dst++ = ( ( i_last &0x03 ) << 6 ) | c;
                i_level = 0;
        }
        i_last = c;
    }

    return p_dst - p_start;
}
size_t vlc_b64_decode_binary( uint8_t **pp_dst, const char *psz_src )
{
    const int i_src = strlen( psz_src );
    uint8_t   *p_dst;

    *pp_dst = p_dst = malloc( i_src );
    if( !p_dst )
        return 0;
    return  vlc_b64_decode_binary_to_buffer( p_dst, i_src, psz_src );
}
char *vlc_b64_decode( const char *psz_src )
{
    const int i_src = strlen( psz_src );
    char *p_dst = malloc( i_src + 1 );
    size_t i_dst;
    if( !p_dst )
        return NULL;

    i_dst = vlc_b64_decode_binary_to_buffer( (uint8_t*)p_dst, i_src, psz_src );
    p_dst[i_dst] = '\0';

    return p_dst;
}

648 649 650 651 652
/**
 * Formats current time into a heap-allocated string.
 * @param tformat time format (as with C strftime())
 * @return an allocated string (must be free()'d), or NULL on memory error.
 */
653
char *str_format_time( const char *tformat )
654 655 656 657
{
    time_t curtime;
    struct tm loctime;

658 659 660
    if (strcmp (tformat, "") == 0)
        return strdup (""); /* corner case w.r.t. strftime() return value */

661
    /* Get the current time.  */
662
    time( &curtime );
663 664 665

    /* Convert it to local time representation.  */
    localtime_r( &curtime, &loctime );
666 667 668 669 670 671 672 673 674 675 676 677 678 679
    for (size_t buflen = strlen (tformat) + 32;; buflen += 32)
    {
        char *str = malloc (buflen);
        if (str == NULL)
            return NULL;

        size_t len = strftime (str, buflen, tformat, &loctime);
        if (len > 0)
        {
            char *ret = realloc (str, len + 1);
            return ret ? ret : str; /* <- this cannot fail */
        }
    }
    assert (0);
680 681
}

682 683
#define INSERT_STRING( string )                                     \
                    if( string != NULL )                            \
684
                    {                                               \
685 686 687 688 689 690
                        int len = strlen( string );                 \
                        dst = realloc( dst, i_size = i_size + len );\
                        memcpy( (dst+d), string, len );             \
                        d += len;                                   \
                        free( string );                             \
                    }                                               \
691
                    else if( !b_empty_if_na )                       \
692 693 694 695
                    {                                               \
                        *(dst+d) = '-';                             \
                        d++;                                        \
                    }                                               \
696 697

/* same than INSERT_STRING, except that string won't be freed */
Christophe Mutricy's avatar
Christophe Mutricy committed
698
#define INSERT_STRING_NO_FREE( string )                             \
699
                    {                                               \
700 701 702 703 704
                        int len = strlen( string );                 \
                        dst = realloc( dst, i_size = i_size + len );\
                        memcpy( dst+d, string, len );               \
                        d += len;                                   \
                    }
705
char *__str_format_meta( vlc_object_t *p_object, const char *string )
706
{
707
    const char *s = string;
708 709
    bool b_is_format = false;
    bool b_empty_if_na = false;
710
    char buf[10];
711
    int i_size = strlen( string ) + 1; /* +1 to store '\0' */
712 713
    char *dst = strdup( string );
    if( !dst ) return NULL;
714
    int d = 0;
715

Antoine Cellerier's avatar
Antoine Cellerier committed
716
    playlist_t *p_playlist = pl_Hold( p_object );
717
    input_thread_t *p_input = playlist_CurrentInput( p_playlist );
718 719 720 721
    input_item_t *p_item = NULL;
    pl_Release( p_object );
    if( p_input )
    {
Clément Stenac's avatar
Clément Stenac committed
722
        p_item = input_GetItem(p_input);
723 724 725 726 727 728 729 730 731
    }

    while( *s )
    {
        if( b_is_format )
        {
            switch( *s )
            {
                case 'a':
732 733 734 735
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetArtist( p_item ) );
                    }
736 737
                    break;
                case 'b':
738 739 740 741
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetAlbum( p_item ) );
                    }
742 743
                    break;
                case 'c':
744 745 746 747
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetCopyright( p_item ) );
                    }
748 749
                    break;
                case 'd':
750 751 752 753
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetDescription( p_item ) );
                    }
754 755
                    break;
                case 'e':
756 757 758 759
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetEncodedBy( p_item ) );
                    }
760
                    break;
761 762 763
                case 'f':
                    if( p_item && p_item->p_stats )
                    {
764
                        vlc_mutex_lock( &p_item->p_stats->lock );
765 766
                        snprintf( buf, 10, "%d",
                                  p_item->p_stats->i_displayed_pictures );
767
                        vlc_mutex_unlock( &p_item->p_stats->lock );
768 769 770 771 772 773 774
                    }
                    else
                    {
                        sprintf( buf, b_empty_if_na ? "" : "-" );
                    }
                    INSERT_STRING_NO_FREE( buf );
                    break;
775
                case 'g':
776 777 778 779
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetGenre( p_item ) );
                    }
780 781
                    break;
                case 'l':
782 783 784 785
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetLanguage( p_item ) );
                    }
786 787
                    break;
                case 'n':
788 789 790 791
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetTrackNum( p_item ) );
                    }
792 793
                    break;
                case 'p':
794 795 796 797
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetNowPlaying( p_item ) );
                    }
798 799
                    break;
                case 'r':
800 801 802 803
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetRating( p_item ) );
                    }
804 805 806
                    break;
                case 's':
                {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
807
                    char *lang = NULL;
808
                    if( p_input )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
809 810
                        lang = var_GetNonEmptyString( p_input, "sub-language" );
                    if( lang == NULL )
811
                        lang = strdup( b_empty_if_na ? "" : "-" );
812
                    INSERT_STRING( lang );
813 814 815
                    break;
                }
                case 't':
816 817 818 819
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetTitle( p_item ) );
                    }
820 821
                    break;
                case 'u':
822 823 824 825
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetURL( p_item ) );
                    }
826 827
                    break;
                case 'A':
828 829 830 831
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetDate( p_item ) );
                    }
832 833 834 835 836 837 838 839 840
                    break;
                case 'B':
                    if( p_input )
                    {
                        snprintf( buf, 10, "%d",
                                  var_GetInteger( p_input, "bit-rate" )/1000 );
                    }
                    else
                    {
841
                        sprintf( buf, b_empty_if_na ? "" : "-" );
842
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
843
                    INSERT_STRING_NO_FREE( buf );
844 845 846 847 848 849 850 851 852
                    break;
                case 'C':
                    if( p_input )
                    {
                        snprintf( buf, 10, "%d",
                                  var_GetInteger( p_input, "chapter" ) );
                    }
                    else
                    {
853
                        sprintf( buf, b_empty_if_na ? "" : "-" );
854
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
855
                    INSERT_STRING_NO_FREE( buf );
856 857 858 859
                    break;
                case 'D':
                    if( p_item )
                    {
860
                        mtime_t i_duration = input_item_GetDuration( p_item );
861
                        sprintf( buf, "%02d:%02d:%02d",
862 863 864
                                 (int)(i_duration/(3600000000)),
                                 (int)((i_duration/(60000000))%60),
                                 (int)((i_duration/1000000)%60) );
865 866 867
                    }
                    else
                    {
868
                        sprintf( buf, b_empty_if_na ? "" : "--:--:--" );
869
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
870
                    INSERT_STRING_NO_FREE( buf );
871 872
                    break;
                case 'F':
873 874 875 876
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetURI( p_item ) );
                    }
877 878 879 880 881 882 883 884 885
                    break;
                case 'I':
                    if( p_input )
                    {
                        snprintf( buf, 10, "%d",
                                  var_GetInteger( p_input, "title" ) );
                    }
                    else
                    {
886
                        sprintf( buf, b_empty_if_na ? "" : "-" );
887
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
888
                    INSERT_STRING_NO_FREE( buf );
889 890 891 892
                    break;
                case 'L':
                    if( p_item && p_input )
                    {
893
                        mtime_t i_duration = input_item_GetDuration( p_item );
Laurent Aimar's avatar
Laurent Aimar committed
894
                        int64_t i_time = var_GetInteger( p_input, "time" );
895
                        sprintf( buf, "%02d:%02d:%02d",
896 897 898
                     (int)( ( i_duration - i_time ) / 3600000000 ),
                     (int)( ( ( i_duration - i_time ) / 60000000 ) % 60 ),
                     (int)( ( ( i_duration - i_time ) / 1000000 ) % 60 ) );
899 900 901
                    }
                    else
                    {
902
                        sprintf( buf, b_empty_if_na ? "" : "--:--:--" );
903
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
904
                    INSERT_STRING_NO_FREE( buf );
905 906
                    break;
                case 'N':
907 908 909 910
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetName( p_item ) );
                    }
911 912 913
                    break;
                case 'O':
                {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
914
                    char *lang = NULL;
915
                    if( p_input )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
916 917 918
                        lang = var_GetNonEmptyString( p_input,
                                                      "audio-language" );
                    if( lang == NULL )
919
                        lang = strdup( b_empty_if_na ? "" : "-" );
920
                    INSERT_STRING( lang );
921 922 923 924 925 926 927 928 929 930
                    break;
                }
                case 'P':
                    if( p_input )
                    {
                        snprintf( buf, 10, "%2.1lf",
                                  var_GetFloat( p_input, "position" ) * 100. );
                    }
                    else
                    {
931
                        sprintf( buf, b_empty_if_na ? "" : "--.-%%" );
932
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
933
                    INSERT_STRING_NO_FREE( buf );
934 935 936 937 938 939 940 941 942
                    break;
                case 'R':
                    if( p_input )
                    {
                        int r = var_GetInteger( p_input, "rate" );
                        snprintf( buf, 10, "%d.%d", r/1000, r%1000 );
                    }
                    else
                    {
943
                        sprintf( buf, b_empty_if_na ? "" : "-" );
944
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
945
                    INSERT_STRING_NO_FREE( buf );
946 947 948 949 950 951 952 953 954
                    break;
                case 'S':
                    if( p_input )
                    {
                        int r = var_GetInteger( p_input, "sample-rate" );
                        snprintf( buf, 10, "%d.%d", r/1000, (r/100)%10 );
                    }
                    else
                    {
955
                        sprintf( buf, b_empty_if_na ? "" : "-" );
956
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
957
                    INSERT_STRING_NO_FREE( buf );
958 959 960 961
                    break;
                case 'T':
                    if( p_input )
                    {
Laurent Aimar's avatar
Laurent Aimar committed
962
                        int64_t i_time = var_GetInteger( p_input, "time" );
963
                        sprintf( buf, "%02d:%02d:%02d",
Laurent Aimar's avatar
Laurent Aimar committed
964 965 966
                            (int)( i_time / ( 3600000000 ) ),
                            (int)( ( i_time / ( 60000000 ) ) % 60 ),
                            (int)( ( i_time / 1000000 ) % 60 ) );
967 968 969
                    }
                    else
                    {
970
                        sprintf( buf, b_empty_if_na ? "" :  "--:--:--" );
971
                    }
Christophe Mutricy's avatar
Christophe Mutricy committed
972
                    INSERT_STRING_NO_FREE( buf );
973 974
                    break;
                case 'U':
975 976 977 978
                    if( p_item )
                    {
                        INSERT_STRING( input_item_GetPublisher( p_item ) );
                    }
979 980 981 982 983 984
                    break;
                case 'V':
                {
                    audio_volume_t volume;
                    aout_VolumeGet( p_object, &volume );
                    snprintf( buf, 10, "%d", volume );
Christophe Mutricy's avatar
Christophe Mutricy committed
985
                    INSERT_STRING_NO_FREE( buf );
986 987 988
                    break;
                }
                case '_':
989
                    *(dst+d) = '\n';
990 991 992
                    d++;
                    break;

993
                case ' ':
994
                    b_empty_if_na = true;
995 996
                    break;

997
                default:
998
                    *(dst+d) = *s;
999 1000 1001
                    d++;
                    break;
            }
1002
            if( *s != ' ' )
1003
                b_is_format = false;
1004 1005 1006
        }
        else if( *s == '$' )
        {
1007 1008
            b_is_format = true;
            b_empty_if_na = false;
1009 1010 1011
        }
        else
        {
1012
            *(dst+d) = *s;
1013 1014 1015 1016
            d++;
        }
        s++;
    }
1017
    *(dst+d) = '\0';
1018 1019 1020 1021 1022 1023

    if( p_input )
        vlc_object_release( p_input );

    return dst;
}
Antoine Cellerier's avatar
Antoine Cellerier committed
1024 1025
#undef INSERT_STRING
#undef INSERT_STRING_NO_FREE
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

/**
 * Apply str format time and str format meta
 */
char *__str_format( vlc_object_t *p_this, const char *psz_src )
{
    char *psz_buf1, *psz_buf2;
    psz_buf1 = str_format_time( psz_src );
    psz_buf2 = str_format_meta( p_this, psz_buf1 );
    free( psz_buf1 );
    return psz_buf2;
}

/**
 * Remove forbidden characters from filenames (including slashes)
 */
1042
char* filename_sanitize( const char *str_origin )
1043
{
1044 1045
    char *str = strdup( str_origin );
    char *str_base = str;
1046 1047 1048 1049 1050 1051 1052
    if( *str == '.' && (str[1] == '\0' || (str[1] == '.' && str[2] == '\0' ) ) )
    {
        while( *str )
        {
            *str = '_';
            str++;
        }
1053
        return str_base;
1054 1055
    }

1056 1057 1058 1059 1060 1061
#if defined( WIN32 )
    // Change leading spaces into underscores
    while( *str && *str == ' ' )
        *str++ = '_';
#endif

1062 1063 1064 1065 1066
    while( *str )
    {
        switch( *str )
        {
            case '/':
1067 1068 1069
#if defined( __APPLE__ )
            case ':':
#elif defined( WIN32 )
1070
            case '\\':
1071 1072
            case '*':
            case '"':
Antoine Cellerier's avatar
Oops.  
Antoine Cellerier committed
1073
            case '?':
1074 1075
            case ':':
            case '|':
1076
            case '<':
Antoine Cellerier's avatar
Oops.  
Antoine Cellerier committed
1077
            case '>':
1078 1079 1080
#endif
                *str = '_';
        }
Antoine Cellerier's avatar
Oops.  
Antoine Cellerier committed
1081
        str++;
1082
    }
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

#if defined( WIN32 )
    // Change trailing spaces into underscores
    str--;
    while( str != str_base )
    {
        if( *str != ' ' )
            break;
        *str-- = '_';
    }
#endif

1095
    return str_base;
1096 1097 1098 1099 1100 1101 1102
}

/**
 * Remove forbidden characters from full paths (leaves slashes)
 */
void path_sanitize( char *str )
{
1103 1104
#ifdef WIN32
    /* check drive prefix if path is absolute */
1105 1106
    if( (((unsigned char)(str[0] - 'A') < 26)
      || ((unsigned char)(str[0] - 'a') < 26)) && (':' == str[1]) )
1107
        str += 2;
1108
#endif
1109 1110
    while( *str )
    {
1111 1112 1113 1114
#if defined( __APPLE__ )
        if( *str == ':' )
            *str = '_';
#elif defined( WIN32 )
1115 1116 1117 1118
        if( strchr( "*\"?:|<>", *str ) )
            *str = '_';
        if( *str == '/' )
            *str = DIR_SEP_CHAR;
1119
#endif
Antoine Cellerier's avatar
Oops.  
Antoine Cellerier committed
1120
        str++;
1121 1122
    }
}