]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
livehttp: don't sanitize segment URI
[vlc] / modules / access_output / livehttp.c
1 /*****************************************************************************
2  * livehttp.c: Live HTTP Streaming
3  *****************************************************************************
4  * Copyright © 2001, 2002, 2013 VLC authors and VideoLAN
5  * Copyright © 2009-2010 by Keary Griffin
6  *
7  * Authors: Keary Griffin <kearygriffin at gmail.com>
8  *          Ilkka Ollakka <ileoo at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <sys/types.h>
34 #include <time.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_sout.h>
44 #include <vlc_block.h>
45 #include <vlc_fs.h>
46 #include <vlc_strings.h>
47 #include <vlc_charset.h>
48
49 #include <gcrypt.h>
50 #include <vlc_gcrypt.h>
51
52 #include <vlc_rand.h>
53
54 #ifndef O_LARGEFILE
55 #   define O_LARGEFILE 0
56 #endif
57
58 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
59
60 #define MAX_RENAME_RETRIES        10
61
62 /*****************************************************************************
63  * Module descriptor
64  *****************************************************************************/
65 static int  Open ( vlc_object_t * );
66 static void Close( vlc_object_t * );
67
68 #define SOUT_CFG_PREFIX "sout-livehttp-"
69 #define SEGLEN_TEXT N_("Segment length")
70 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
71
72 #define SPLITANYWHERE_TEXT N_("Split segments anywhere")
73 #define SPLITANYWHERE_LONGTEXT N_("Don't require a keyframe before splitting "\
74                                 "a segment. Needed for audio only.")
75
76 #define NUMSEGS_TEXT N_("Number of segments")
77 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
78
79 #define NOCACHE_TEXT N_("Allow cache")
80 #define NOCACHE_LONGTEXT N_("Add EXT-X-ALLOW-CACHE:NO directive in playlist-file if this is disabled")
81
82 #define INDEX_TEXT N_("Index file")
83 #define INDEX_LONGTEXT N_("Path to the index file to create")
84
85 #define INDEXURL_TEXT N_("Full URL to put in index file")
86 #define INDEXURL_LONGTEXT N_("Full URL to put in index file. "\
87                           "Use #'s to represent segment number")
88
89 #define DELSEGS_TEXT N_("Delete segments")
90 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
91
92 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
93
94 #define KEYURI_TEXT N_("AES key URI to place in playlist")
95 #define KEYURI_LONGTEXT N_("Location from where client will retrieve the stream decryption key")
96
97 #define KEYFILE_TEXT N_("AES key file")
98 #define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
99
100 #define KEYLOADFILE_TEXT N_("File where vlc reads key-uri and keyfile-location")
101 #define KEYLOADFILE_LONGTEXT N_("File is read when segment starts and is assumet to be in format: "\
102                                 "key-uri\\nkey-file. File is read on the segment opening and "\
103                                 "values are used on that segment.")
104
105 #define RANDOMIV_TEXT N_("Use randomized IV for encryption")
106 #define RANDOMIV_LONGTEXT N_("Generate IV instead using segment-number as IV")
107
108 vlc_module_begin ()
109     set_description( N_("HTTP Live streaming output") )
110     set_shortname( N_("LiveHTTP" ))
111     add_shortcut( "livehttp" )
112     set_capability( "sout access", 0 )
113     set_category( CAT_SOUT )
114     set_subcategory( SUBCAT_SOUT_ACO )
115     add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
116     add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
117     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
118               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
119     add_bool( SOUT_CFG_PREFIX "delsegs", true,
120               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
121     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
122               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
123     add_bool( SOUT_CFG_PREFIX "caching", false,
124               NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
125     add_bool( SOUT_CFG_PREFIX "generate-iv", false,
126               RANDOMIV_TEXT, RANDOMIV_LONGTEXT, true )
127     add_string( SOUT_CFG_PREFIX "index", NULL,
128                 INDEX_TEXT, INDEX_LONGTEXT, false )
129     add_string( SOUT_CFG_PREFIX "index-url", NULL,
130                 INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
131     add_string( SOUT_CFG_PREFIX "key-uri", NULL,
132                 KEYURI_TEXT, KEYURI_TEXT, true )
133     add_loadfile( SOUT_CFG_PREFIX "key-file", NULL,
134                 KEYFILE_TEXT, KEYFILE_LONGTEXT, true )
135     add_loadfile( SOUT_CFG_PREFIX "key-loadfile", NULL,
136                 KEYLOADFILE_TEXT, KEYLOADFILE_LONGTEXT, true )
137     set_callbacks( Open, Close )
138 vlc_module_end ()
139
140
141 /*****************************************************************************
142  * Exported prototypes
143  *****************************************************************************/
144 static const char *const ppsz_sout_options[] = {
145     "seglen",
146     "splitanywhere",
147     "numsegs",
148     "delsegs",
149     "index",
150     "index-url",
151     "ratecontrol",
152     "caching",
153     "key-uri",
154     "key-file",
155     "key-loadfile",
156     "generate-iv",
157     NULL
158 };
159
160 static ssize_t Write( sout_access_out_t *, block_t * );
161 static int Seek ( sout_access_out_t *, off_t  );
162 static int Control( sout_access_out_t *, int, va_list );
163
164 typedef struct output_segment
165 {
166     char *psz_filename;
167     char *psz_uri;
168     char *psz_key_uri;
169     char *psz_duration;
170     uint32_t i_segment_number;
171     uint8_t aes_ivs[16];
172 } output_segment_t;
173
174 struct sout_access_out_sys_t
175 {
176     char *psz_cursegPath;
177     char *psz_indexPath;
178     char *psz_indexUrl;
179     char *psz_keyfile;
180     mtime_t i_keyfile_modification;
181     mtime_t i_opendts;
182     mtime_t  i_seglenm;
183     uint32_t i_segment;
184     size_t  i_seglen;
185     float   f_seglen;
186     block_t *block_buffer;
187     int i_handle;
188     unsigned i_numsegs;
189     bool b_delsegs;
190     bool b_ratecontrol;
191     bool b_splitanywhere;
192     bool b_caching;
193     bool b_generate_iv;
194     uint8_t aes_ivs[16];
195     gcry_cipher_hd_t aes_ctx;
196     char *key_uri;
197     uint8_t stuffing_bytes[16];
198     ssize_t stuffing_size;
199     vlc_array_t *segments_t;
200 };
201
202 static int LoadCryptFile( sout_access_out_t *p_access);
203 static int CryptSetup( sout_access_out_t *p_access, char *keyfile );
204 /*****************************************************************************
205  * Open: open the file
206  *****************************************************************************/
207 static int Open( vlc_object_t *p_this )
208 {
209     sout_access_out_t   *p_access = (sout_access_out_t*)p_this;
210     sout_access_out_sys_t *p_sys;
211     char *psz_idx;
212
213     config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
214
215     if( !p_access->psz_path )
216     {
217         msg_Err( p_access, "no file name specified" );
218         return VLC_EGENERIC;
219     }
220
221     if( unlikely( !( p_sys = malloc ( sizeof( *p_sys ) ) ) ) )
222         return VLC_ENOMEM;
223
224     p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
225     /* Try to get within asked segment length */
226     p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
227     p_sys->block_buffer = NULL;
228
229     p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
230     p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
231     p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
232     p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
233     p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
234     p_sys->b_generate_iv = var_GetBool( p_access, SOUT_CFG_PREFIX "generate-iv") ;
235
236     p_sys->segments_t = vlc_array_new();
237
238     p_sys->stuffing_size = 0;
239
240     p_sys->psz_indexPath = NULL;
241     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
242     if ( psz_idx )
243     {
244         char *psz_tmp;
245         psz_tmp = str_format_time( psz_idx );
246         free( psz_idx );
247         if ( !psz_tmp )
248         {
249             free( p_sys );
250             return VLC_ENOMEM;
251         }
252         path_sanitize( psz_tmp );
253         p_sys->psz_indexPath = psz_tmp;
254         vlc_unlink( p_sys->psz_indexPath );
255     }
256
257     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
258     p_sys->psz_keyfile  = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-loadfile" );
259     p_sys->key_uri      = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
260
261     p_access->p_sys = p_sys;
262
263     if( p_sys->psz_keyfile && ( LoadCryptFile( p_access ) < 0 ) )
264     {
265         free( p_sys->psz_indexUrl );
266         free( p_sys->psz_indexPath );
267         free( p_sys );
268         msg_Err( p_access, "Encryption init failed" );
269         return VLC_EGENERIC;
270     }
271     else if( !p_sys->psz_keyfile && ( CryptSetup( p_access, NULL ) < 0 ) )
272     {
273         free( p_sys->psz_indexUrl );
274         free( p_sys->psz_indexPath );
275         free( p_sys );
276         msg_Err( p_access, "Encryption init failed" );
277         return VLC_EGENERIC;
278     }
279
280     p_sys->i_handle = -1;
281     p_sys->i_segment = 0;
282     p_sys->psz_cursegPath = NULL;
283
284     p_access->pf_write = Write;
285     p_access->pf_seek  = Seek;
286     p_access->pf_control = Control;
287
288     return VLC_SUCCESS;
289 }
290
291 /************************************************************************
292  * CryptSetup: Initialize encryption
293  ************************************************************************/
294 static int CryptSetup( sout_access_out_t *p_access, char *key_file )
295 {
296     sout_access_out_sys_t *p_sys = p_access->p_sys;
297     uint8_t key[16];
298     char *keyfile = NULL;
299
300     if( key_file )
301         keyfile = strdup( key_file );
302     else
303         keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
304
305     if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
306     {
307         msg_Dbg( p_access, "No key uri, no encryption");
308         return VLC_SUCCESS;
309     }
310     vlc_gcrypt_init();
311
312     /*Setup encryption cipher*/
313     gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
314                                          GCRY_CIPHER_MODE_CBC, 0 );
315     if( err )
316     {
317         msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
318         return VLC_EGENERIC;
319     }
320
321     if( unlikely(keyfile == NULL) )
322     {
323         msg_Err( p_access, "No key-file, no encryption" );
324         return VLC_EGENERIC;
325     }
326
327     int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
328     if( unlikely( keyfd == -1 ) )
329     {
330         msg_Err( p_access, "Unable to open keyfile %s: %m", keyfile );
331         free( keyfile );
332         return VLC_EGENERIC;
333     }
334     free( keyfile );
335
336     ssize_t keylen = read( keyfd, key, 16 );
337
338     close( keyfd );
339     if( keylen < 16 )
340     {
341         msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
342         return VLC_EGENERIC;
343     }
344
345     err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
346     if(err)
347     {
348         msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
349         gcry_cipher_close( p_sys->aes_ctx);
350         return VLC_EGENERIC;
351     }
352
353     if( p_sys->b_generate_iv )
354         vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
355
356     return VLC_SUCCESS;
357 }
358
359
360 /************************************************************************
361  * LoadCryptFile: Try to parse key_uri and keyfile-location from file
362  ************************************************************************/
363 static int LoadCryptFile( sout_access_out_t *p_access )
364 {
365     sout_access_out_sys_t *p_sys = p_access->p_sys;
366
367     FILE *stream = vlc_fopen( p_sys->psz_keyfile, "rt" );
368     char *key_file=NULL,*key_uri=NULL;
369
370     if( unlikely( stream == NULL ) )
371     {
372         msg_Err( p_access, "Unable to open keyloadfile %s: %m", p_sys->psz_keyfile );
373         return VLC_EGENERIC;
374     }
375
376
377     //First read key_uri
378     ssize_t len = getline( &key_uri, &(size_t){0}, stream );
379     if( unlikely( len == -1 ) )
380     {
381         msg_Err( p_access, "Cannot read %s: %m", p_sys->psz_keyfile );
382         clearerr( stream );
383         fclose( stream );
384         free( key_uri );
385         return VLC_EGENERIC;
386     }
387     //Strip the newline from uri, maybe scanf would be better?
388     key_uri[len-1]='\0';
389
390     len = getline( &key_file, &(size_t){0}, stream );
391     if( unlikely( len == -1 ) )
392     {
393         msg_Err( p_access, "Cannot read %s: %m", p_sys->psz_keyfile );
394         clearerr( stream );
395         fclose( stream );
396
397         free( key_uri );
398         free( key_file );
399         return VLC_EGENERIC;
400     }
401     // Strip the last newline from filename
402     key_file[len-1]='\0';
403     fclose( stream );
404
405     int returncode = VLC_SUCCESS;
406     if( !p_sys->key_uri || strcmp( p_sys->key_uri, key_uri ) )
407     {
408         if( p_sys->key_uri )
409         {
410             free( p_sys->key_uri );
411             p_sys->key_uri = NULL;
412         }
413         p_sys->key_uri = strdup( key_uri );
414         returncode = CryptSetup( p_access, key_file );
415     }
416     free( key_file );
417     free( key_uri );
418     return returncode;
419 }
420
421 /************************************************************************
422  * CryptKey: Set encryption IV to current segment number
423  ************************************************************************/
424 static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
425 {
426     sout_access_out_sys_t *p_sys = p_access->p_sys;
427
428     if( !p_sys->b_generate_iv )
429     {
430         /* Use segment number as IV if randomIV isn't selected*/
431         memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
432         p_sys->aes_ivs[15] = i_segment & 0xff;
433         p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
434         p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
435         p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
436     }
437
438     gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
439                                           p_sys->aes_ivs, 16);
440     if( err )
441     {
442         msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
443         gcry_cipher_close( p_sys->aes_ctx);
444         return VLC_EGENERIC;
445     }
446     return VLC_SUCCESS;
447 }
448
449
450 #define SEG_NUMBER_PLACEHOLDER "#"
451 /*****************************************************************************
452  * formatSegmentPath: create segment path name based on seg #
453  *****************************************************************************/
454 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
455 {
456     char *psz_result;
457     char *psz_firstNumSign;
458
459     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
460         return NULL;
461
462     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
463     if ( *psz_firstNumSign )
464     {
465         char *psz_newResult;
466         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
467         int ret;
468
469         *psz_firstNumSign = '\0';
470         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
471         free ( psz_result );
472         if ( ret < 0 )
473             return NULL;
474         psz_result = psz_newResult;
475     }
476
477     if ( b_sanitize )
478         path_sanitize( psz_result );
479
480     return psz_result;
481 }
482
483 static void destroySegment( output_segment_t *segment )
484 {
485     free( segment->psz_filename );
486     free( segment->psz_duration );
487     free( segment->psz_uri );
488     free( segment->psz_key_uri );
489     free( segment );
490 }
491
492 /************************************************************************
493  * updateIndexAndDel: If necessary, update index file & delete old segments
494  ************************************************************************/
495 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
496 {
497
498     uint32_t i_firstseg;
499
500     if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
501         i_firstseg = 1;
502     else
503         i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
504
505     // First update index
506     if ( p_sys->psz_indexPath )
507     {
508         int val;
509         FILE *fp;
510         char *psz_idxTmp;
511         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
512             return -1;
513
514         fp = vlc_fopen( psz_idxTmp, "wt");
515         if ( !fp )
516         {
517             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
518             free( psz_idxTmp );
519             return -1;
520         }
521
522         if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s"
523                           "%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen,
524                           p_sys->b_caching ? "YES" : "NO",
525                           p_sys->i_numsegs > 0 ? "" : b_isend ? "\n#EXT-X-PLAYLIST-TYPE:VOD" : "\n#EXT-X-PLAYLIST-TYPE:EVENT",
526                           i_firstseg ) < 0 )
527         {
528             free( psz_idxTmp );
529             fclose( fp );
530             return -1;
531         }
532         char *psz_current_uri=NULL;
533
534
535         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
536         {
537             //scale to 0..numsegs-1
538             uint32_t index = i-i_firstseg;
539
540             output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, index );
541             if( p_sys->key_uri &&
542                 ( !psz_current_uri ||  strcmp( psz_current_uri, segment->psz_key_uri ) )
543               )
544             {
545                 int ret = 0;
546                 free( psz_current_uri );
547                 psz_current_uri = strdup( segment->psz_key_uri );
548                 if( p_sys->b_generate_iv )
549                 {
550                     unsigned long long iv_hi = 0, iv_lo = 0;
551                     for( unsigned short i = 0; i < 8; i++ )
552                     {
553                         iv_hi |= segment->aes_ivs[i] & 0xff;
554                         iv_hi <<= 8;
555                         iv_lo |= segment->aes_ivs[8+i] & 0xff;
556                         iv_lo <<= 8;
557                     }
558                     ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
559                                    segment->psz_key_uri, iv_hi, iv_lo );
560
561                 } else {
562                     ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", segment->psz_key_uri );
563                 }
564                 if( ret < 0 )
565                 {
566                     free( psz_idxTmp );
567                     fclose( fp );
568                     return -1;
569                 }
570             }
571
572             val = fprintf( fp, "#EXTINF:%s,\n%s\n", segment->psz_duration, segment->psz_uri);
573             if ( val < 0 )
574             {
575                 fclose( fp );
576                 return -1;
577             }
578         }
579         free( psz_current_uri );
580
581         if ( b_isend )
582         {
583             if ( fputs ( STR_ENDLIST, fp ) < 0)
584             {
585                 free( psz_idxTmp );
586                 fclose( fp ) ;
587                 return -1;
588             }
589
590         }
591         fclose( fp );
592
593         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
594
595         if ( val < 0 )
596         {
597             vlc_unlink( psz_idxTmp );
598             msg_Err( p_access, "Error moving LiveHttp index file" );
599         }
600         else
601             msg_Dbg( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
602
603         free( psz_idxTmp );
604     }
605
606     // Then take care of deletion
607     while( p_sys->b_delsegs && p_sys->i_numsegs && ( (vlc_array_count( p_sys->segments_t ) ) >= p_sys->i_numsegs ) )
608     {
609          output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
610          vlc_array_remove( p_sys->segments_t, 0 );
611          if ( segment->psz_filename )
612          {
613              vlc_unlink( segment->psz_filename );
614          }
615          destroySegment( segment );
616     }
617
618
619     return 0;
620 }
621
622 /*****************************************************************************
623  * closeCurrentSegment: Close the segment file
624  *****************************************************************************/
625 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
626 {
627     if ( p_sys->i_handle >= 0 )
628     {
629         output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - 1 );
630
631         if( p_sys->key_uri )
632         {
633             size_t pad = 16 - p_sys->stuffing_size;
634             memset(&p_sys->stuffing_bytes[p_sys->stuffing_size], pad, pad);
635             gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx, p_sys->stuffing_bytes, 16, NULL, 0 );
636
637             if( err ) {
638                msg_Err( p_access, "Couldn't encrypt 16 bytes: %s", gpg_strerror(err) );
639             } else {
640             int ret = write( p_sys->i_handle, p_sys->stuffing_bytes, 16 );
641             if( ret != 16 )
642                 msg_Err( p_access, "Couldn't write 16 bytes" );
643             }
644             p_sys->stuffing_size = 0;
645         }
646
647
648         close( p_sys->i_handle );
649         p_sys->i_handle = -1;
650
651         if( ! ( us_asprintf( &segment->psz_duration, "%.2f", p_sys->f_seglen ) ) )
652         {
653             msg_Err( p_access, "Couldn't set duration on closed segment");
654             return;
655         }
656
657         segment->i_segment_number = p_sys->i_segment;
658
659         if ( p_sys->psz_cursegPath )
660         {
661             msg_Dbg( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
662             free( p_sys->psz_cursegPath );
663             p_sys->psz_cursegPath = 0;
664             updateIndexAndDel( p_access, p_sys, b_isend );
665         }
666     }
667 }
668
669 /*****************************************************************************
670  * Close: close the target
671  *****************************************************************************/
672 static void Close( vlc_object_t * p_this )
673 {
674     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
675     sout_access_out_sys_t *p_sys = p_access->p_sys;
676
677     msg_Dbg( p_access, "Flushing buffer to last file");
678     bool crypted = false;
679     while( p_sys->block_buffer )
680     {
681         if( p_sys->key_uri && !crypted)
682         {
683             if( p_sys->stuffing_size )
684             {
685                 p_sys->block_buffer = block_Realloc( p_sys->block_buffer, p_sys->stuffing_size, p_sys->block_buffer->i_buffer );
686                 if( unlikely(!p_sys->block_buffer) )
687                     return;
688                 memcpy( p_sys->block_buffer->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
689                 p_sys->stuffing_size = 0;
690             }
691             size_t original = p_sys->block_buffer->i_buffer;
692             size_t padded = (original + 15 ) & ~15;
693             size_t pad = padded - original;
694             if( pad )
695             {
696                 p_sys->stuffing_size = 16 - pad;
697                 p_sys->block_buffer->i_buffer -= p_sys->stuffing_size;
698                 memcpy( p_sys->stuffing_bytes, &p_sys->block_buffer->p_buffer[p_sys->block_buffer->i_buffer], p_sys->stuffing_size );
699             }
700
701             gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
702                                 p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer, NULL, 0 );
703             if( err )
704             {
705                 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
706                 break;
707             }
708             crypted = true;
709         }
710         ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
711         if ( val == -1 )
712         {
713            if ( errno == EINTR )
714               continue;
715            block_ChainRelease ( p_sys->block_buffer);
716            break;
717         }
718         if( !p_sys->block_buffer->p_next )
719         {
720             p_sys->f_seglen = (float)( p_sys->block_buffer->i_length / (1000000)) +
721                                (float)(p_sys->block_buffer->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
722         }
723
724         if ( likely( (size_t)val >= p_sys->block_buffer->i_buffer ) )
725         {
726            block_t *p_next = p_sys->block_buffer->p_next;
727            block_Release (p_sys->block_buffer);
728            p_sys->block_buffer = p_next;
729            crypted=false;
730         }
731         else
732         {
733            p_sys->block_buffer->p_buffer += val;
734            p_sys->block_buffer->i_buffer -= val;
735         }
736     }
737
738     closeCurrentSegment( p_access, p_sys, true );
739
740     if( p_sys->key_uri )
741     {
742         gcry_cipher_close( p_sys->aes_ctx );
743         free( p_sys->key_uri );
744     }
745
746     while( vlc_array_count( p_sys->segments_t ) > 0 )
747     {
748         output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
749         vlc_array_remove( p_sys->segments_t, 0 );
750         destroySegment( segment );
751     }
752     vlc_array_destroy( p_sys->segments_t );
753
754     free( p_sys->psz_indexUrl );
755     free( p_sys->psz_indexPath );
756     free( p_sys );
757
758     msg_Dbg( p_access, "livehttp access output closed" );
759 }
760
761 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
762 {
763     sout_access_out_sys_t *p_sys = p_access->p_sys;
764
765     switch( i_query )
766     {
767         case ACCESS_OUT_CONTROLS_PACE:
768         {
769             bool *pb = va_arg( args, bool * );
770             *pb = !p_sys->b_ratecontrol;
771             //*pb = true;
772             break;
773         }
774
775         default:
776             return VLC_EGENERIC;
777     }
778     return VLC_SUCCESS;
779 }
780
781 /*****************************************************************************
782  * openNextFile: Open the segment file
783  *****************************************************************************/
784 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
785 {
786     int fd;
787
788     uint32_t i_newseg = p_sys->i_segment + 1;
789
790     /* Create segment and fill it info that we can (everything excluding duration */
791     output_segment_t *segment = (output_segment_t*)malloc(sizeof(output_segment_t));
792     if( unlikely( !segment ) )
793         return -1;
794
795     memset( segment, 0 , sizeof( output_segment_t ) );
796
797     segment->i_segment_number = i_newseg;
798     segment->psz_filename = formatSegmentPath( p_access->psz_path, i_newseg, true );
799     char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
800     segment->psz_uri = formatSegmentPath( psz_idxFormat , i_newseg, false );
801
802     if ( unlikely( !segment->psz_filename ) )
803     {
804         msg_Err( p_access, "Format segmentpath failed");
805         return -1;
806     }
807
808     fd = vlc_open( segment->psz_filename, O_WRONLY | O_CREAT | O_LARGEFILE |
809                      O_TRUNC, 0666 );
810     if ( fd == -1 )
811     {
812         msg_Err( p_access, "cannot open `%s' (%m)", segment->psz_filename );
813         destroySegment( segment );
814         return -1;
815     }
816
817     vlc_array_append( p_sys->segments_t, segment);
818
819     if( p_sys->psz_keyfile )
820     {
821         LoadCryptFile( p_access );
822     }
823
824     if( p_sys->key_uri )
825     {
826         segment->psz_key_uri = strdup( p_sys->key_uri );
827         CryptKey( p_access, i_newseg );
828         if( p_sys->b_generate_iv )
829             memcpy( segment->aes_ivs, p_sys->aes_ivs, sizeof(uint8_t)*16 );
830     }
831     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , segment->psz_filename, i_newseg );
832
833     p_sys->psz_cursegPath = strdup(segment->psz_filename);
834     p_sys->i_handle = fd;
835     p_sys->i_segment = i_newseg;
836     return fd;
837 }
838
839 /*****************************************************************************
840  * Write: standard write on a file descriptor.
841  *****************************************************************************/
842 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
843 {
844     size_t i_write = 0;
845     sout_access_out_sys_t *p_sys = p_access->p_sys;
846     block_t *p_temp;
847
848     while( p_buffer )
849     {
850         if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
851         {
852             bool crypted = false;
853             block_t *output = p_sys->block_buffer;
854             p_sys->block_buffer = NULL;
855
856
857             if( p_sys->i_handle > 0 &&
858                 ( p_buffer->i_dts - p_sys->i_opendts +
859                   p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
860                 ) >= p_sys->i_seglenm )
861                 closeCurrentSegment( p_access, p_sys, false );
862
863             if ( p_sys->i_handle < 0 )
864             {
865                 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
866                 if ( openNextFile( p_access, p_sys ) < 0 )
867                    return -1;
868             }
869
870             while( output )
871             {
872                 if( p_sys->key_uri && !crypted )
873                 {
874                     if( p_sys->stuffing_size )
875                     {
876                         output = block_Realloc( output, p_sys->stuffing_size, output->i_buffer );
877                         if( unlikely(!output ) )
878                             return VLC_ENOMEM;
879                         memcpy( output->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
880                         p_sys->stuffing_size = 0;
881                     }
882                     size_t original = output->i_buffer;
883                     size_t padded = (output->i_buffer + 15 ) & ~15;
884                     size_t pad = padded - original;
885                     if( pad )
886                     {
887                         p_sys->stuffing_size = 16-pad;
888                         output->i_buffer -= p_sys->stuffing_size;
889                         memcpy(p_sys->stuffing_bytes, &output->p_buffer[output->i_buffer], p_sys->stuffing_size);
890                     }
891
892                     gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
893                                         output->p_buffer, output->i_buffer, NULL, 0 );
894                     if( err )
895                     {
896                         msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
897                         return -1;
898                     }
899                     crypted=true;
900
901                 }
902                 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
903                 if ( val == -1 )
904                 {
905                    if ( errno == EINTR )
906                       continue;
907                    block_ChainRelease ( p_buffer );
908                    return -1;
909                 }
910                 p_sys->f_seglen =
911                     (float)output->i_length / INT64_C(1000000) +
912                     (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
913
914                 if ( (size_t)val >= output->i_buffer )
915                 {
916                    block_t *p_next = output->p_next;
917                    block_Release (output);
918                    output = p_next;
919                    crypted=false;
920                 }
921                 else
922                 {
923                    output->p_buffer += val;
924                    output->i_buffer -= val;
925                 }
926                 i_write += val;
927             }
928         }
929
930         p_temp = p_buffer->p_next;
931         p_buffer->p_next = NULL;
932         block_ChainAppend( &p_sys->block_buffer, p_buffer );
933         p_buffer = p_temp;
934     }
935
936     return i_write;
937 }
938
939 /*****************************************************************************
940  * Seek: seek to a specific location in a file
941  *****************************************************************************/
942 static int Seek( sout_access_out_t *p_access, off_t i_pos )
943 {
944     (void) i_pos;
945     msg_Err( p_access, "livehttp sout access cannot seek" );
946     return -1;
947 }