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 */
40 /* Needed by str_format_meta */
41 #include <vlc_input.h>
43 #include <vlc_playlist.h>
46 #include <vlc_strings.h>
48 #include <vlc_charset.h>
51 * Unescape URI encoded string
52 * \return decoded duplicated string
54 char *unescape_URI_duplicate( const char *psz )
56 char *psz_dup = strdup( psz );
57 unescape_URI( psz_dup );
62 * Unescape URI encoded string in place
65 void unescape_URI( char *psz )
67 unsigned char *in = (unsigned char *)psz, *out = in, c;
71 while( ( c = *in++ ) != '\0' )
77 char val[5], *pval = val;
87 if( ( *pval++ = *in++ ) == '\0' )
89 if( ( *pval++ = *in++ ) == '\0' )
95 if( ( *pval++ = *in++ ) == '\0' )
100 cp = strtoul( val, NULL, 0x10 );
106 *out++ = (( cp >> 6) | 0xc0);
107 *out++ = (( cp & 0x3f) | 0x80);
111 assert( cp < 0x10000 );
112 *out++ = (( cp >> 12) | 0xe0);
113 *out++ = (((cp >> 6) & 0x3f) | 0x80);
114 *out++ = (( cp & 0x3f) | 0x80);
119 /* + is not a special case - it means plus, not space. */
122 /* Inserting non-ASCII or non-printable characters is unsafe,
123 * and no sane browser will send these unencoded */
124 if( ( c < 32 ) || ( c > 127 ) )
134 * Decode encoded URI component. See also decode_URI().
135 * \return decoded duplicated string
137 char *decode_URI_duplicate( const char *psz )
139 char *psz_dup = strdup( psz );
140 decode_URI( psz_dup );
145 * Decode an encoded URI component in place.
146 * <b>This function does NOT decode entire URIs.</b>
147 * It decodes components (e.g. host name, directory, file name).
148 * Decoded URIs do not exist in the real world (see RFC3986 §2.4).
149 * Complete URIs are always "encoded" (or they are syntaxically invalid).
151 * Note that URI encoding is different from Javascript escaping. Especially,
152 * white spaces and Unicode non-ASCII code points are encoded differently.
154 * \return psz on success, NULL if it was not properly encoded
156 char *decode_URI( char *psz )
158 unsigned char *in = (unsigned char *)psz, *out = in, c;
163 while( ( c = *in++ ) != '\0' )
171 if( ( ( hex[0] = *in++ ) == 0 )
172 || ( ( hex[1] = *in++ ) == 0 ) )
176 *out++ = (unsigned char)strtoul( hex, NULL, 0x10 );
180 case '+': /* This is HTTP forms, not URI decoding... */
185 /* Inserting non-ASCII or non-printable characters is unsafe,
186 * and no sane browser will send these unencoded */
187 if( ( c < 32 ) || ( c > 127 ) )
198 static inline bool isurisafe( int c )
200 /* These are the _unreserved_ URI characters (RFC3986 §2.3) */
201 return ( (unsigned char)( c - 'a' ) < 26 )
202 || ( (unsigned char)( c - 'A' ) < 26 )
203 || ( (unsigned char)( c - '0' ) < 10 )
204 || ( strchr( "-._~", c ) != NULL );
207 static char *encode_URI_bytes (const char *psz_uri, size_t len)
209 char *psz_enc = malloc (3 * len + 1), *out = psz_enc;
213 for (size_t i = 0; i < len; i++)
215 static const char hex[16] = "0123456789ABCDEF";
216 uint8_t c = *psz_uri;
220 /* This is URI encoding, not HTTP forms:
221 * Space is encoded as '%20', not '+'. */
225 *out++ = hex[c >> 4];
226 *out++ = hex[c & 0xf];
232 out = realloc (psz_enc, out - psz_enc);
233 return out ? out : psz_enc; /* realloc() can fail (safe) */
237 * Encodes an URI component (RFC3986 §2).
239 * @param psz_uri nul-terminated UTF-8 representation of the component.
240 * Obviously, you can't pass an URI containing a nul character, but you don't
241 * want to do that, do you?
243 * @return encoded string (must be free()'d), or NULL for ENOMEM.
245 char *encode_URI_component( const char *psz_uri )
247 return encode_URI_bytes (psz_uri, strlen (psz_uri));
251 static const struct xml_entity_s
256 /* Important: this list has to be in alphabetical order (psz_entity-wise) */
338 { "nbsp;", "\xc2\xa0" },
383 static int cmp_entity (const void *key, const void *elem)
385 const struct xml_entity_s *ent = elem;
386 const char *name = key;
388 return strncmp (name, ent->psz_entity, strlen (ent->psz_entity));
392 * Converts "<", ">" and "&" to "<", ">" and "&"
393 * \param string to convert
395 void resolve_xml_special_chars( char *psz_value )
397 char *p_pos = psz_value;
401 if( *psz_value == '&' )
403 if( psz_value[1] == '#' )
404 { /* &#xxx; Unicode code point */
406 unsigned long cp = strtoul( psz_value+2, &psz_end, 10 );
407 if( *psz_end == ';' )
409 psz_value = psz_end + 1;
411 (void)0; /* skip nuls */
418 /* Unicode code point outside ASCII.
419 * &#xxx; representation is longer than UTF-8 :) */
422 *p_pos++ = 0xC0 | (cp >> 6);
423 *p_pos = 0x80 | (cp & 0x3F);
428 *p_pos++ = 0xE0 | (cp >> 12);
429 *p_pos++ = 0x80 | ((cp >> 6) & 0x3F);
430 *p_pos = 0x80 | (cp & 0x3F);
433 if( cp <= 0x1FFFFF ) /* Outside the BMP */
434 { /* Unicode stops at 10FFFF, but who cares? */
435 *p_pos++ = 0xF0 | (cp >> 18);
436 *p_pos++ = 0x80 | ((cp >> 12) & 0x3F);
437 *p_pos++ = 0x80 | ((cp >> 6) & 0x3F);
438 *p_pos = 0x80 | (cp & 0x3F);
443 /* Invalid entity number */
449 { /* Well-known XML entity */
450 const struct xml_entity_s *ent;
452 ent = bsearch (psz_value + 1, xml_entities,
453 sizeof (xml_entities) / sizeof (*ent),
454 sizeof (*ent), cmp_entity);
457 size_t olen = strlen (ent->psz_char);
458 memcpy (p_pos, ent->psz_char, olen);
460 psz_value += strlen (ent->psz_entity) + 1;
482 * Converts '<', '>', '\"', '\'' and '&' to their html entities
483 * \param psz_content simple element content that is to be converted
485 char *convert_xml_special_chars( const char *psz_content )
487 char *psz_temp = malloc( 6 * strlen( psz_content ) + 1 );
488 const char *p_from = psz_content;
489 char *p_to = psz_temp;
493 if ( *p_from == '<' )
495 strcpy( p_to, "<" );
498 else if ( *p_from == '>' )
500 strcpy( p_to, ">" );
503 else if ( *p_from == '&' )
505 strcpy( p_to, "&" );
508 else if( *p_from == '\"' )
510 strcpy( p_to, """ );
513 else if( *p_from == '\'' )
515 strcpy( p_to, "'" );
530 /* Base64 encoding */
531 char *vlc_b64_encode_binary( const uint8_t *src, size_t i_src )
533 static const char b64[] =
534 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
536 char *ret = malloc( ( i_src + 4 ) * 4 / 3 );
544 /* pops (up to) 3 bytes of input, push 4 bytes */
549 *dst++ = b64[v >> 26];
555 *dst++ = b64[v >> 26];
560 v |= *src++ << 20; // 3/3
561 *dst++ = ( i_src >= 2 ) ? b64[v >> 26] : '='; // 3/4
565 *dst++ = ( i_src >= 3 ) ? b64[v >> 26] : '='; // 4/4
577 char *vlc_b64_encode( const char *src )
580 return vlc_b64_encode_binary( (const uint8_t*)src, strlen(src) );
582 return vlc_b64_encode_binary( (const uint8_t*)"", 0 );
585 /* Base64 decoding */
586 size_t vlc_b64_decode_binary_to_buffer( uint8_t *p_dst, size_t i_dst, const char *p_src )
588 static const int b64[256] = {
589 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
590 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
591 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
592 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
593 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
594 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
595 -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
596 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
597 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
598 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
599 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
600 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
601 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
602 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
603 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
604 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
606 uint8_t *p_start = p_dst;
607 uint8_t *p = (uint8_t *)p_src;
612 for( i_level = 0, i_last = 0; (size_t)( p_dst - p_start ) < i_dst && *p != '\0'; p++ )
614 const int c = b64[(unsigned int)*p];
624 *p_dst++ = ( i_last << 2 ) | ( ( c >> 4)&0x03 );
628 *p_dst++ = ( ( i_last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
632 *p_dst++ = ( ( i_last &0x03 ) << 6 ) | c;
638 return p_dst - p_start;
640 size_t vlc_b64_decode_binary( uint8_t **pp_dst, const char *psz_src )
642 const int i_src = strlen( psz_src );
645 *pp_dst = p_dst = malloc( i_src );
648 return vlc_b64_decode_binary_to_buffer( p_dst, i_src, psz_src );
650 char *vlc_b64_decode( const char *psz_src )
652 const int i_src = strlen( psz_src );
653 char *p_dst = malloc( i_src + 1 );
658 i_dst = vlc_b64_decode_binary_to_buffer( (uint8_t*)p_dst, i_src, psz_src );
665 * Formats current time into a heap-allocated string.
666 * @param tformat time format (as with C strftime())
667 * @return an allocated string (must be free()'d), or NULL on memory error.
669 char *str_format_time( const char *tformat )
674 if (strcmp (tformat, "") == 0)
675 return strdup (""); /* corner case w.r.t. strftime() return value */
677 /* Get the current time. */
680 /* Convert it to local time representation. */
681 localtime_r( &curtime, &loctime );
682 for (size_t buflen = strlen (tformat) + 32;; buflen += 32)
684 char *str = malloc (buflen);
688 size_t len = strftime (str, buflen, tformat, &loctime);
691 char *ret = realloc (str, len + 1);
692 return ret ? ret : str; /* <- this cannot fail */
698 #define INSERT_STRING( string ) \
699 if( string != NULL ) \
701 int len = strlen( string ); \
702 dst = realloc( dst, i_size = i_size + len );\
703 memcpy( (dst+d), string, len ); \
707 else if( !b_empty_if_na ) \
713 /* same than INSERT_STRING, except that string won't be freed */
714 #define INSERT_STRING_NO_FREE( string ) \
716 int len = strlen( string ); \
717 dst = realloc( dst, i_size = i_size + len );\
718 memcpy( dst+d, string, len ); \
721 char *__str_format_meta( vlc_object_t *p_object, const char *string )
723 const char *s = string;
724 bool b_is_format = false;
725 bool b_empty_if_na = false;
727 int i_size = strlen( string ) + 1; /* +1 to store '\0' */
728 char *dst = strdup( string );
729 if( !dst ) return NULL;
732 playlist_t *p_playlist = pl_Hold( p_object );
733 input_thread_t *p_input = playlist_CurrentInput( p_playlist );
734 input_item_t *p_item = NULL;
735 pl_Release( p_object );
738 p_item = input_GetItem(p_input);
750 INSERT_STRING( input_item_GetArtist( p_item ) );
756 INSERT_STRING( input_item_GetAlbum( p_item ) );
762 INSERT_STRING( input_item_GetCopyright( p_item ) );
768 INSERT_STRING( input_item_GetDescription( p_item ) );
774 INSERT_STRING( input_item_GetEncodedBy( p_item ) );
778 if( p_item && p_item->p_stats )
780 vlc_mutex_lock( &p_item->p_stats->lock );
781 snprintf( buf, 10, "%d",
782 p_item->p_stats->i_displayed_pictures );
783 vlc_mutex_unlock( &p_item->p_stats->lock );
787 sprintf( buf, b_empty_if_na ? "" : "-" );
789 INSERT_STRING_NO_FREE( buf );
794 INSERT_STRING( input_item_GetGenre( p_item ) );
800 INSERT_STRING( input_item_GetLanguage( p_item ) );
806 INSERT_STRING( input_item_GetTrackNum( p_item ) );
812 INSERT_STRING( input_item_GetNowPlaying( p_item ) );
818 INSERT_STRING( input_item_GetRating( p_item ) );
825 lang = var_GetNonEmptyString( p_input, "sub-language" );
827 lang = strdup( b_empty_if_na ? "" : "-" );
828 INSERT_STRING( lang );
834 INSERT_STRING( input_item_GetTitle( p_item ) );
840 INSERT_STRING( input_item_GetURL( p_item ) );
846 INSERT_STRING( input_item_GetDate( p_item ) );
852 snprintf( buf, 10, "%d",
853 var_GetInteger( p_input, "bit-rate" )/1000 );
857 sprintf( buf, b_empty_if_na ? "" : "-" );
859 INSERT_STRING_NO_FREE( buf );
864 snprintf( buf, 10, "%d",
865 var_GetInteger( p_input, "chapter" ) );
869 sprintf( buf, b_empty_if_na ? "" : "-" );
871 INSERT_STRING_NO_FREE( buf );
876 mtime_t i_duration = input_item_GetDuration( p_item );
877 sprintf( buf, "%02d:%02d:%02d",
878 (int)(i_duration/(3600000000)),
879 (int)((i_duration/(60000000))%60),
880 (int)((i_duration/1000000)%60) );
884 sprintf( buf, b_empty_if_na ? "" : "--:--:--" );
886 INSERT_STRING_NO_FREE( buf );
891 INSERT_STRING( input_item_GetURI( p_item ) );
897 snprintf( buf, 10, "%d",
898 var_GetInteger( p_input, "title" ) );
902 sprintf( buf, b_empty_if_na ? "" : "-" );
904 INSERT_STRING_NO_FREE( buf );
907 if( p_item && p_input )
909 mtime_t i_duration = input_item_GetDuration( p_item );
910 int64_t i_time = var_GetInteger( p_input, "time" );
911 sprintf( buf, "%02d:%02d:%02d",
912 (int)( ( i_duration - i_time ) / 3600000000 ),
913 (int)( ( ( i_duration - i_time ) / 60000000 ) % 60 ),
914 (int)( ( ( i_duration - i_time ) / 1000000 ) % 60 ) );
918 sprintf( buf, b_empty_if_na ? "" : "--:--:--" );
920 INSERT_STRING_NO_FREE( buf );
925 INSERT_STRING( input_item_GetName( p_item ) );
932 lang = var_GetNonEmptyString( p_input,
935 lang = strdup( b_empty_if_na ? "" : "-" );
936 INSERT_STRING( lang );
942 snprintf( buf, 10, "%2.1lf",
943 var_GetFloat( p_input, "position" ) * 100. );
947 sprintf( buf, b_empty_if_na ? "" : "--.-%%" );
949 INSERT_STRING_NO_FREE( buf );
954 int r = var_GetInteger( p_input, "rate" );
955 snprintf( buf, 10, "%d.%d", r/1000, r%1000 );
959 sprintf( buf, b_empty_if_na ? "" : "-" );
961 INSERT_STRING_NO_FREE( buf );
966 int r = var_GetInteger( p_input, "sample-rate" );
967 snprintf( buf, 10, "%d.%d", r/1000, (r/100)%10 );
971 sprintf( buf, b_empty_if_na ? "" : "-" );
973 INSERT_STRING_NO_FREE( buf );
978 int64_t i_time = var_GetInteger( p_input, "time" );
979 sprintf( buf, "%02d:%02d:%02d",
980 (int)( i_time / ( 3600000000 ) ),
981 (int)( ( i_time / ( 60000000 ) ) % 60 ),
982 (int)( ( i_time / 1000000 ) % 60 ) );
986 sprintf( buf, b_empty_if_na ? "" : "--:--:--" );
988 INSERT_STRING_NO_FREE( buf );
993 INSERT_STRING( input_item_GetPublisher( p_item ) );
998 audio_volume_t volume;
999 aout_VolumeGet( p_object, &volume );
1000 snprintf( buf, 10, "%d", volume );
1001 INSERT_STRING_NO_FREE( buf );
1010 b_empty_if_na = true;
1019 b_is_format = false;
1021 else if( *s == '$' )
1024 b_empty_if_na = false;
1036 vlc_object_release( p_input );
1040 #undef INSERT_STRING
1041 #undef INSERT_STRING_NO_FREE
1044 * Apply str format time and str format meta
1046 char *__str_format( vlc_object_t *p_this, const char *psz_src )
1048 char *psz_buf1, *psz_buf2;
1049 psz_buf1 = str_format_time( psz_src );
1050 psz_buf2 = str_format_meta( p_this, psz_buf1 );
1056 * Remove forbidden characters from filenames (including slashes)
1058 char* filename_sanitize( const char *str_origin )
1060 char *str = strdup( str_origin );
1061 char *str_base = str;
1062 if( *str == '.' && (str[1] == '\0' || (str[1] == '.' && str[2] == '\0' ) ) )
1072 #if defined( WIN32 )
1073 // Change leading spaces into underscores
1074 while( *str && *str == ' ' )
1083 #if defined( __APPLE__ )
1085 #elif defined( WIN32 )
1100 #if defined( WIN32 )
1101 // Change trailing spaces into underscores
1103 while( str != str_base )
1115 * Remove forbidden characters from full paths (leaves slashes)
1117 void path_sanitize( char *str )
1120 /* check drive prefix if path is absolute */
1121 if( (((unsigned char)(str[0] - 'A') < 26)
1122 || ((unsigned char)(str[0] - 'a') < 26)) && (':' == str[1]) )
1127 #if defined( __APPLE__ )
1130 #elif defined( WIN32 )
1131 if( strchr( "*\"?:|<>", *str ) )
1134 *str = DIR_SEP_CHAR;
1140 #include <vlc_url.h>
1143 * Convert a file path to an URI. If already an URI, do nothing.
1145 char *make_URI (const char *path)
1149 if (strstr (path, "://") != NULL)
1150 return strdup (path); /* Already an URI */
1151 /* Note: VLC cannot handle URI schemes without double slash after the
1152 * scheme name (such as mailto: or news:). */
1156 if (isalpha (path[0]) && (path[1] == ':'))
1158 if (asprintf (&buf, "file:///%c:", path[0]) == -1)
1165 /* Windows UNC paths (file://host/share/path instead of file:///path) */
1166 if (!strncmp (path, "\\\\", 2))
1169 buf = strdup ("file://");
1173 if (path[0] != DIR_SEP_CHAR)
1174 { /* Relative path: prepend the current working directory */
1177 if (getcwd (cwd, sizeof (cwd)) == NULL) /* FIXME: UTF8? */
1179 if (asprintf (&buf, "%s/%s", cwd, path) == -1)
1181 char *ret = make_URI (buf);
1186 buf = strdup ("file://");
1190 assert (path[0] == DIR_SEP_CHAR);
1192 /* Absolute file path */
1193 for (const char *ptr = path + 1;; ptr++)
1195 size_t len = strcspn (ptr, DIR_SEP);
1196 char *component = encode_URI_bytes (ptr, len);
1197 if (component == NULL)
1203 int val = asprintf (&uri, "%s/%s", buf, component);