1 /*****************************************************************************
2 * strings.c: String related functions
3 *****************************************************************************
4 * Copyright (C) 2006 the VideoLAN team
5 * Copyright (C) 2008-2009 Rémi Denis-Courmont
8 * Authors: Antoine Cellerier <dionoea at videolan dot org>
9 * Daniel Stranger <vlc at schmaller dot de>
10 * Rémi Denis-Courmont <rem # videolan org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
34 #include <vlc_common.h>
37 /* Needed by str_format_time */
41 /* Needed by str_format_meta */
42 #include <vlc_input.h>
44 #include <vlc_playlist.h>
47 #include <vlc_strings.h>
49 #include <vlc_charset.h>
52 * Decode encoded URI component. See also decode_URI().
53 * \return decoded duplicated string
55 char *decode_URI_duplicate( const char *psz )
57 char *psz_dup = strdup( psz );
58 decode_URI( psz_dup );
63 * Decode an encoded URI component in place.
64 * <b>This function does NOT decode entire URIs.</b>
65 * It decodes components (e.g. host name, directory, file name).
66 * Decoded URIs do not exist in the real world (see RFC3986 §2.4).
67 * Complete URIs are always "encoded" (or they are syntaxically invalid).
69 * Note that URI encoding is different from Javascript escaping. Especially,
70 * white spaces and Unicode non-ASCII code points are encoded differently.
72 * \return psz on success, NULL if it was not properly encoded
74 char *decode_URI( char *psz )
76 unsigned char *in = (unsigned char *)psz, *out = in, c;
81 while( ( c = *in++ ) != '\0' )
89 if( ( ( hex[0] = *in++ ) == 0 )
90 || ( ( hex[1] = *in++ ) == 0 ) )
94 *out++ = (unsigned char)strtoul( hex, NULL, 0x10 );
98 case '+': /* This is HTTP forms, not URI decoding... */
103 /* Inserting non-ASCII or non-printable characters is unsafe,
104 * and no sane browser will send these unencoded */
105 if( ( c < 32 ) || ( c > 127 ) )
116 static inline bool isurisafe( int c )
118 /* These are the _unreserved_ URI characters (RFC3986 §2.3) */
119 return ( (unsigned char)( c - 'a' ) < 26 )
120 || ( (unsigned char)( c - 'A' ) < 26 )
121 || ( (unsigned char)( c - '0' ) < 10 )
122 || ( strchr( "-._~", c ) != NULL );
125 static char *encode_URI_bytes (const char *psz_uri, size_t len)
127 char *psz_enc = malloc (3 * len + 1), *out = psz_enc;
131 for (size_t i = 0; i < len; i++)
133 static const char hex[16] = "0123456789ABCDEF";
134 uint8_t c = *psz_uri;
138 /* This is URI encoding, not HTTP forms:
139 * Space is encoded as '%20', not '+'. */
143 *out++ = hex[c >> 4];
144 *out++ = hex[c & 0xf];
150 out = realloc (psz_enc, out - psz_enc);
151 return out ? out : psz_enc; /* realloc() can fail (safe) */
155 * Encodes an URI component (RFC3986 §2).
157 * @param psz_uri nul-terminated UTF-8 representation of the component.
158 * Obviously, you can't pass an URI containing a nul character, but you don't
159 * want to do that, do you?
161 * @return encoded string (must be free()'d), or NULL for ENOMEM.
163 char *encode_URI_component( const char *psz_uri )
165 return encode_URI_bytes (psz_uri, strlen (psz_uri));
169 static const struct xml_entity_s
174 /* Important: this list has to be in alphabetical order (psz_entity-wise) */
256 { "nbsp;", "\xc2\xa0" },
301 static int cmp_entity (const void *key, const void *elem)
303 const struct xml_entity_s *ent = elem;
304 const char *name = key;
306 return strncmp (name, ent->psz_entity, strlen (ent->psz_entity));
310 * Converts "<", ">" and "&" to "<", ">" and "&"
311 * \param string to convert
313 void resolve_xml_special_chars( char *psz_value )
315 char *p_pos = psz_value;
319 if( *psz_value == '&' )
321 if( psz_value[1] == '#' )
322 { /* &#xxx; Unicode code point */
324 unsigned long cp = strtoul( psz_value+2, &psz_end, 10 );
325 if( *psz_end == ';' )
327 psz_value = psz_end + 1;
329 (void)0; /* skip nuls */
336 /* Unicode code point outside ASCII.
337 * &#xxx; representation is longer than UTF-8 :) */
340 *p_pos++ = 0xC0 | (cp >> 6);
341 *p_pos = 0x80 | (cp & 0x3F);
346 *p_pos++ = 0xE0 | (cp >> 12);
347 *p_pos++ = 0x80 | ((cp >> 6) & 0x3F);
348 *p_pos = 0x80 | (cp & 0x3F);
351 if( cp <= 0x1FFFFF ) /* Outside the BMP */
352 { /* Unicode stops at 10FFFF, but who cares? */
353 *p_pos++ = 0xF0 | (cp >> 18);
354 *p_pos++ = 0x80 | ((cp >> 12) & 0x3F);
355 *p_pos++ = 0x80 | ((cp >> 6) & 0x3F);
356 *p_pos = 0x80 | (cp & 0x3F);
361 /* Invalid entity number */
367 { /* Well-known XML entity */
368 const struct xml_entity_s *ent;
370 ent = bsearch (psz_value + 1, xml_entities,
371 sizeof (xml_entities) / sizeof (*ent),
372 sizeof (*ent), cmp_entity);
375 size_t olen = strlen (ent->psz_char);
376 memcpy (p_pos, ent->psz_char, olen);
378 psz_value += strlen (ent->psz_entity) + 1;
400 * Converts '<', '>', '\"', '\'' and '&' to their html entities
401 * \param psz_content simple element content that is to be converted
403 char *convert_xml_special_chars( const char *psz_content )
405 assert( psz_content );
407 const size_t len = strlen( psz_content );
408 char *const psz_temp = malloc( 6 * len + 1 );
409 char *p_to = psz_temp;
411 if( psz_temp == NULL )
413 for( size_t i = 0; i < len; i++ )
416 char c = psz_content[i];
420 case '\"': str = "quot"; break;
421 case '&': str = "amp"; break;
422 case '\'': str = "#39"; break;
423 case '<': str = "lt"; break;
424 case '>': str = "gt"; break;
429 p_to += sprintf( p_to, "&%s;", str );
433 p_to = realloc( psz_temp, p_to - psz_temp );
434 return p_to ? p_to : psz_temp; /* cannot fail */
437 /* Base64 encoding */
438 char *vlc_b64_encode_binary( const uint8_t *src, size_t i_src )
440 static const char b64[] =
441 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
443 char *ret = malloc( ( i_src + 4 ) * 4 / 3 );
451 /* pops (up to) 3 bytes of input, push 4 bytes */
456 *dst++ = b64[v >> 26];
462 *dst++ = b64[v >> 26];
467 v |= *src++ << 20; // 3/3
468 *dst++ = ( i_src >= 2 ) ? b64[v >> 26] : '='; // 3/4
472 *dst++ = ( i_src >= 3 ) ? b64[v >> 26] : '='; // 4/4
484 char *vlc_b64_encode( const char *src )
487 return vlc_b64_encode_binary( (const uint8_t*)src, strlen(src) );
489 return vlc_b64_encode_binary( (const uint8_t*)"", 0 );
492 /* Base64 decoding */
493 size_t vlc_b64_decode_binary_to_buffer( uint8_t *p_dst, size_t i_dst, const char *p_src )
495 static const int b64[256] = {
496 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
497 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
498 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
499 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
500 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
501 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
502 -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
503 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
504 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
505 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
506 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
507 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
508 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
509 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
510 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
511 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
513 uint8_t *p_start = p_dst;
514 uint8_t *p = (uint8_t *)p_src;
519 for( i_level = 0, i_last = 0; (size_t)( p_dst - p_start ) < i_dst && *p != '\0'; p++ )
521 const int c = b64[(unsigned int)*p];
531 *p_dst++ = ( i_last << 2 ) | ( ( c >> 4)&0x03 );
535 *p_dst++ = ( ( i_last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
539 *p_dst++ = ( ( i_last &0x03 ) << 6 ) | c;
545 return p_dst - p_start;
547 size_t vlc_b64_decode_binary( uint8_t **pp_dst, const char *psz_src )
549 const int i_src = strlen( psz_src );
552 *pp_dst = p_dst = malloc( i_src );
555 return vlc_b64_decode_binary_to_buffer( p_dst, i_src, psz_src );
557 char *vlc_b64_decode( const char *psz_src )
559 const int i_src = strlen( psz_src );
560 char *p_dst = malloc( i_src + 1 );
565 i_dst = vlc_b64_decode_binary_to_buffer( (uint8_t*)p_dst, i_src, psz_src );
572 * Formats current time into a heap-allocated string.
573 * @param tformat time format (as with C strftime())
574 * @return an allocated string (must be free()'d), or NULL on memory error.
576 char *str_format_time( const char *tformat )
581 if (strcmp (tformat, "") == 0)
582 return strdup (""); /* corner case w.r.t. strftime() return value */
584 /* Get the current time. */
587 /* Convert it to local time representation. */
588 localtime_r( &curtime, &loctime );
589 for (size_t buflen = strlen (tformat) + 32;; buflen += 32)
591 char *str = malloc (buflen);
595 size_t len = strftime (str, buflen, tformat, &loctime);
598 char *ret = realloc (str, len + 1);
599 return ret ? ret : str; /* <- this cannot fail */
605 #define INSERT_STRING( string ) \
606 if( string != NULL ) \
608 int len = strlen( string ); \
609 dst = xrealloc( dst, i_size = i_size + len );\
610 memcpy( (dst+d), string, len ); \
614 else if( !b_empty_if_na ) \
620 /* same than INSERT_STRING, except that string won't be freed */
621 #define INSERT_STRING_NO_FREE( string ) \
623 int len = strlen( string ); \
624 dst = xrealloc( dst, i_size = i_size + len );\
625 memcpy( dst+d, string, len ); \
628 char *__str_format_meta( vlc_object_t *p_object, const char *string )
630 const char *s = string;
631 bool b_is_format = false;
632 bool b_empty_if_na = false;
634 int i_size = strlen( string ) + 1; /* +1 to store '\0' */
635 char *dst = strdup( string );
636 if( !dst ) return NULL;
639 playlist_t *p_playlist = pl_Hold( p_object );
640 input_thread_t *p_input = playlist_CurrentInput( p_playlist );
641 input_item_t *p_item = NULL;
642 pl_Release( p_object );
645 p_item = input_GetItem(p_input);
657 INSERT_STRING( input_item_GetArtist( p_item ) );
663 INSERT_STRING( input_item_GetAlbum( p_item ) );
669 INSERT_STRING( input_item_GetCopyright( p_item ) );
675 INSERT_STRING( input_item_GetDescription( p_item ) );
681 INSERT_STRING( input_item_GetEncodedBy( p_item ) );
685 if( p_item && p_item->p_stats )
687 vlc_mutex_lock( &p_item->p_stats->lock );
688 snprintf( buf, 10, "%d",
689 p_item->p_stats->i_displayed_pictures );
690 vlc_mutex_unlock( &p_item->p_stats->lock );
694 sprintf( buf, b_empty_if_na ? "" : "-" );
696 INSERT_STRING_NO_FREE( buf );
701 INSERT_STRING( input_item_GetGenre( p_item ) );
707 INSERT_STRING( input_item_GetLanguage( p_item ) );
713 INSERT_STRING( input_item_GetTrackNum( p_item ) );
719 INSERT_STRING( input_item_GetNowPlaying( p_item ) );
725 INSERT_STRING( input_item_GetRating( p_item ) );
732 lang = var_GetNonEmptyString( p_input, "sub-language" );
734 lang = strdup( b_empty_if_na ? "" : "-" );
735 INSERT_STRING( lang );
741 INSERT_STRING( input_item_GetTitle( p_item ) );
747 INSERT_STRING( input_item_GetURL( p_item ) );
753 INSERT_STRING( input_item_GetDate( p_item ) );
759 snprintf( buf, 10, "%d",
760 var_GetInteger( p_input, "bit-rate" )/1000 );
764 sprintf( buf, b_empty_if_na ? "" : "-" );
766 INSERT_STRING_NO_FREE( buf );
771 snprintf( buf, 10, "%d",
772 var_GetInteger( p_input, "chapter" ) );
776 sprintf( buf, b_empty_if_na ? "" : "-" );
778 INSERT_STRING_NO_FREE( buf );
783 mtime_t i_duration = input_item_GetDuration( p_item );
784 snprintf( buf, 10, "%02d:%02d:%02d",
785 (int)(i_duration/(3600000000)),
786 (int)((i_duration/(60000000))%60),
787 (int)((i_duration/1000000)%60) );
791 snprintf( buf, 10, b_empty_if_na ? "" : "--:--:--" );
793 INSERT_STRING_NO_FREE( buf );
798 INSERT_STRING( input_item_GetURI( p_item ) );
804 snprintf( buf, 10, "%d",
805 var_GetInteger( p_input, "title" ) );
809 sprintf( buf, b_empty_if_na ? "" : "-" );
811 INSERT_STRING_NO_FREE( buf );
814 if( p_item && p_input )
816 mtime_t i_duration = input_item_GetDuration( p_item );
817 int64_t i_time = var_GetTime( p_input, "time" );
818 snprintf( buf, 10, "%02d:%02d:%02d",
819 (int)( ( i_duration - i_time ) / 3600000000 ),
820 (int)( ( ( i_duration - i_time ) / 60000000 ) % 60 ),
821 (int)( ( ( i_duration - i_time ) / 1000000 ) % 60 ) );
825 snprintf( buf, 10, b_empty_if_na ? "" : "--:--:--" );
827 INSERT_STRING_NO_FREE( buf );
832 INSERT_STRING( input_item_GetName( p_item ) );
839 lang = var_GetNonEmptyString( p_input,
842 lang = strdup( b_empty_if_na ? "" : "-" );
843 INSERT_STRING( lang );
849 snprintf( buf, 10, "%2.1lf",
850 var_GetFloat( p_input, "position" ) * 100. );
854 snprintf( buf, 10, b_empty_if_na ? "" : "--.-%%" );
856 INSERT_STRING_NO_FREE( buf );
861 float f = var_GetFloat( p_input, "rate" );
862 snprintf( buf, 10, "%.3f", f );
866 sprintf( buf, b_empty_if_na ? "" : "-" );
868 INSERT_STRING_NO_FREE( buf );
873 int r = var_GetInteger( p_input, "sample-rate" );
874 snprintf( buf, 10, "%d.%d", r/1000, (r/100)%10 );
878 sprintf( buf, b_empty_if_na ? "" : "-" );
880 INSERT_STRING_NO_FREE( buf );
885 int64_t i_time = var_GetTime( p_input, "time" );
886 snprintf( buf, 10, "%02d:%02d:%02d",
887 (int)( i_time / ( 3600000000 ) ),
888 (int)( ( i_time / ( 60000000 ) ) % 60 ),
889 (int)( ( i_time / 1000000 ) % 60 ) );
893 snprintf( buf, 10, b_empty_if_na ? "" : "--:--:--" );
895 INSERT_STRING_NO_FREE( buf );
900 INSERT_STRING( input_item_GetPublisher( p_item ) );
905 audio_volume_t volume;
906 aout_VolumeGet( p_object, &volume );
907 snprintf( buf, 10, "%d", volume );
908 INSERT_STRING_NO_FREE( buf );
917 b_empty_if_na = true;
931 b_empty_if_na = false;
943 vlc_object_release( p_input );
948 #undef INSERT_STRING_NO_FREE
951 * Apply str format time and str format meta
953 char *__str_format( vlc_object_t *p_this, const char *psz_src )
955 char *psz_buf1, *psz_buf2;
956 psz_buf1 = str_format_time( psz_src );
957 psz_buf2 = str_format_meta( p_this, psz_buf1 );
963 * Remove forbidden characters from filenames (including slashes)
965 char* filename_sanitize( const char *str_origin )
967 char *str = strdup( str_origin );
968 char *str_base = str;
969 if( *str == '.' && (str[1] == '\0' || (str[1] == '.' && str[2] == '\0' ) ) )
980 // Change leading spaces into underscores
981 while( *str && *str == ' ' )
990 #if defined( __APPLE__ )
992 #elif defined( WIN32 )
1007 #if defined( WIN32 )
1008 // Change trailing spaces into underscores
1010 while( str != str_base )
1022 * Remove forbidden characters from full paths (leaves slashes)
1024 void path_sanitize( char *str )
1027 /* check drive prefix if path is absolute */
1028 if( (((unsigned char)(str[0] - 'A') < 26)
1029 || ((unsigned char)(str[0] - 'a') < 26)) && (':' == str[1]) )
1034 #if defined( __APPLE__ )
1037 #elif defined( WIN32 )
1038 if( strchr( "*\"?:|<>", *str ) )
1041 *str = DIR_SEP_CHAR;
1047 #include <vlc_url.h>
1050 * Convert a file path to an URI. If already an URI, do nothing.
1052 char *make_URI (const char *path)
1056 if (strstr (path, "://") != NULL)
1057 return strdup (path); /* Already an URI */
1058 /* Note: VLC cannot handle URI schemes without double slash after the
1059 * scheme name (such as mailto: or news:). */
1063 if (isalpha (path[0]) && (path[1] == ':'))
1065 if (asprintf (&buf, "file:///%c:", path[0]) == -1)
1071 if (!strncmp (path, "\\\\", 2))
1072 { /* Windows UNC paths */
1074 /* \\host\share\path -> smb://host/share/path */
1075 if (strchr (path + 2, '\\') != NULL)
1076 { /* Convert antislashes to slashes */
1077 char *dup = strdup (path);
1080 for (size_t i = 2; dup[i]; i++)
1082 dup[i] = DIR_SEP_CHAR;
1084 char *ret = make_URI (dup);
1088 # define SMB_SCHEME "smb"
1090 /* \\host\share\path -> file://host/share/path */
1091 # define SMB_SCHEME "file"
1093 size_t hostlen = strcspn (path + 2, DIR_SEP);
1095 buf = malloc (sizeof (SMB_SCHEME) + 3 + hostlen);
1097 snprintf (buf, sizeof (SMB_SCHEME) + 3 + hostlen,
1098 SMB_SCHEME"://%s", path + 2);
1099 path += 2 + hostlen;
1102 if (path[0] != DIR_SEP_CHAR)
1103 { /* Relative path: prepend the current working directory */
1106 if (getcwd (cwd, sizeof (cwd)) == NULL) /* FIXME: UTF8? */
1108 if (asprintf (&buf, "%s/%s", cwd, path) == -1)
1110 char *ret = make_URI (buf);
1115 buf = strdup ("file://");
1119 assert (path[0] == DIR_SEP_CHAR);
1121 /* Absolute file path */
1122 for (const char *ptr = path + 1;; ptr++)
1124 size_t len = strcspn (ptr, DIR_SEP);
1125 char *component = encode_URI_bytes (ptr, len);
1126 if (component == NULL)
1132 int val = asprintf (&uri, "%s/%s", buf, component);