]> git.sesse.net Git - vlc/blob - src/misc/update.c
macosx: Ask to send a mail to our bugreport ML if a crash log is detected.
[vlc] / src / misc / update.c
1 /*****************************************************************************
2  * update.c: VLC update checking and downloading
3  *****************************************************************************
4  * Copyright © 2005-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Antoine Cellerier <dionoea -at- videolan -dot- org>
8  *          Rémi Duraffort <ivoire at via.ecp.fr>
9             Rafaël Carré <funman@videolanorg>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either release 2 of the License, or
14  * (at your option) any later release.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /**
27  *   \file
28  *   This file contains functions related to VLC update management
29  */
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38
39 #include <vlc_common.h>
40 #include <vlc_update.h>
41
42 #ifdef UPDATE_CHECK
43
44 #include <assert.h>
45
46 #include <vlc_pgpkey.h>
47 #include <vlc_stream.h>
48 #include <vlc_strings.h>
49 #include <vlc_charset.h>
50 #include <vlc_interface.h>
51
52 #include <gcrypt.h>
53 #include <vlc_gcrypt.h>
54
55 #include "update.h"
56 #include "../libvlc.h"
57
58 /*****************************************************************************
59  * Misc defines
60  *****************************************************************************/
61
62 /*
63  * Here is the format of these "status files" :
64  * First line is the last version: "X.Y.Ze" where:
65  *      * X is the major number
66  *      * Y is the minor number
67  *      * Z is the revision number
68  *      * e is an OPTIONAL extra letter
69  *      * AKA "0.8.6d" or "0.9.0"
70  * Second line is an url of the binary for this last version
71  * Remaining text is a required description of the update
72  */
73
74 #if defined( UNDER_CE )
75 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-ce"
76 #elif defined( WIN32 )
77 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-win-x86"
78 #elif defined( __APPLE__ )
79 #   if defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc64__ )
80 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-mac-ppc"
81 #   else
82 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-mac-x86"
83 #   endif
84 #elif defined( SYS_BEOS )
85 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-beos-x86"
86 #else
87 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status"
88 #endif
89
90
91 /*****************************************************************************
92  * Local Prototypes
93  *****************************************************************************/
94 static void EmptyRelease( update_t *p_update );
95 static bool GetUpdateFile( update_t *p_update );
96 static char * size_str( long int l_size );
97
98
99 /*****************************************************************************
100  * OpenPGP functions
101  *****************************************************************************/
102
103 #define packet_type( c ) ( ( c & 0x3c ) >> 2 )      /* 0x3C = 00111100 */
104 #define packet_header_len( c ) ( ( c & 0x03 ) + 1 ) /* number of bytes in a packet header */
105
106 static inline int scalar_number( uint8_t *p, int header_len )
107 {
108     assert( header_len == 1 || header_len == 2 || header_len == 4 );
109
110     if( header_len == 1 )
111         return( p[0] );
112     else if( header_len == 2 )
113         return( (p[0] << 8) + p[1] );
114     else if( header_len == 4 )
115         return( (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3] );
116
117     abort(); /* to shut up GCC warning */
118 }
119
120 /* number of data bytes in a MPI */
121 #define mpi_len( mpi ) ( ( scalar_number( mpi, 2 ) + 7 ) / 8 )
122
123 /*
124  * fill a public_key_packet_t structure from public key packet data
125  * verify that it is a version 4 public key packet, using DSA
126  */
127 static int parse_public_key_packet( public_key_packet_t *p_key, uint8_t *p_buf,
128                                     size_t i_packet_len )
129 {
130
131     if( i_packet_len > 418 || i_packet_len < 6 )
132         return VLC_EGENERIC;
133
134     size_t i_read = 0;
135
136     p_key->version   = *p_buf++; i_read++;
137     if( p_key->version != 4 )
138         return VLC_EGENERIC;
139
140     /* XXX: warn when timestamp is > date ? */
141     memcpy( p_key->timestamp, p_buf, 4 ); p_buf += 4; i_read += 4;
142
143     p_key->algo      = *p_buf++; i_read++;
144     if( p_key->algo != PUBLIC_KEY_ALGO_DSA )
145         return VLC_EGENERIC;
146
147     /* read p */
148     if( i_read + 2 > i_packet_len )
149         return VLC_EGENERIC;
150
151     int i_p_len = mpi_len( p_buf );
152
153     if( i_p_len > 128 || i_read + 2 + i_p_len > i_packet_len )
154         return VLC_EGENERIC;
155
156     memcpy( p_key->p, p_buf, 2+i_p_len );
157     p_buf += 2+i_p_len; i_read += 2+i_p_len;
158
159     /* read q */
160     if( i_read + 2 > i_packet_len )
161         return VLC_EGENERIC;
162
163     int i_q_len = mpi_len( p_buf );
164
165     if( i_q_len > 20 || i_read+2+i_q_len > i_packet_len )
166         return VLC_EGENERIC;
167
168     memcpy( p_key->q, p_buf, 2+i_q_len );
169     p_buf += 2+i_q_len; i_read += 2+i_q_len;
170
171     /* read g */
172     if( i_read + 2 > i_packet_len )
173         return VLC_EGENERIC;
174
175     int i_g_len = mpi_len( p_buf );
176
177     if( i_g_len > 128 || i_read+2+i_g_len > i_packet_len )
178         return VLC_EGENERIC;
179
180     memcpy( p_key->g, p_buf, 2+i_g_len );
181     p_buf += 2+i_g_len; i_read += 2+i_g_len;
182
183     /* read y */
184     if( i_read + 2 > i_packet_len )
185         return VLC_EGENERIC;
186
187     int i_y_len = mpi_len( p_buf );
188
189
190     if( i_y_len > 128 || i_read+2+i_y_len > i_packet_len )
191         return VLC_EGENERIC;
192
193     memcpy( p_key->y, p_buf, 2+i_y_len );
194     i_read += 2+i_y_len;
195
196     if( i_read != i_packet_len ) /* some extra data eh ? */
197         return VLC_EGENERIC;
198
199     return VLC_SUCCESS;
200 }
201
202 static size_t parse_signature_v3_packet( signature_packet_t *p_sig,
203                                       uint8_t *p_buf, size_t i_sig_len )
204 {
205     size_t i_read = 1; /* we already read the version byte */
206
207     if( i_sig_len < 19 ) /* signature is at least 19 bytes + the 2 MPIs */
208         return 0;
209
210     p_sig->specific.v3.hashed_data_len = *p_buf++; i_read++;
211     if( p_sig->specific.v3.hashed_data_len != 5 )
212         return 0;
213
214     p_sig->type = *p_buf++; i_read++;
215
216     memcpy( p_sig->specific.v3.timestamp, p_buf, 4 );
217     p_buf += 4; i_read += 4;
218
219     memcpy( p_sig->issuer_longid, p_buf, 8 );
220     p_buf += 8; i_read += 8;
221
222     p_sig->public_key_algo = *p_buf++; i_read++;
223
224     p_sig->digest_algo = *p_buf++; i_read++;
225
226     p_sig->hash_verification[0] = *p_buf++; i_read++;
227     p_sig->hash_verification[1] = *p_buf++; i_read++;
228
229     assert( i_read == 19 );
230
231     return i_read;
232 }
233
234 /*
235  * fill a signature_packet_v4_t from signature packet data
236  * verify that it was used with a DSA public key, using SHA-1 digest
237  */
238 static size_t parse_signature_v4_packet( signature_packet_t *p_sig,
239                                       uint8_t *p_buf, size_t i_sig_len )
240 {
241     size_t i_read = 1; /* we already read the version byte */
242
243     if( i_sig_len < 10 ) /* signature is at least 10 bytes + the 2 MPIs */
244         return 0;
245
246     p_sig->type = *p_buf++; i_read++;
247
248     p_sig->public_key_algo = *p_buf++; i_read++;
249
250     p_sig->digest_algo = *p_buf++; i_read++;
251
252     memcpy( p_sig->specific.v4.hashed_data_len, p_buf, 2 );
253     p_buf += 2; i_read += 2;
254
255     size_t i_hashed_data_len =
256         scalar_number( p_sig->specific.v4.hashed_data_len, 2 );
257     i_read += i_hashed_data_len;
258     if( i_read + 4 > i_sig_len )
259         return 0;
260
261     p_sig->specific.v4.hashed_data = (uint8_t*) malloc( i_hashed_data_len );
262     if( !p_sig->specific.v4.hashed_data )
263         return 0;
264     memcpy( p_sig->specific.v4.hashed_data, p_buf, i_hashed_data_len );
265     p_buf += i_hashed_data_len;
266
267     memcpy( p_sig->specific.v4.unhashed_data_len, p_buf, 2 );
268     p_buf += 2; i_read += 2;
269
270     size_t i_unhashed_data_len =
271         scalar_number( p_sig->specific.v4.unhashed_data_len, 2 );
272     i_read += i_unhashed_data_len;
273     if( i_read + 2 > i_sig_len )
274         return 0;
275
276     p_sig->specific.v4.unhashed_data = (uint8_t*) malloc( i_unhashed_data_len );
277     if( !p_sig->specific.v4.unhashed_data )
278         return 0;
279
280     memcpy( p_sig->specific.v4.unhashed_data, p_buf, i_unhashed_data_len );
281     p_buf += i_unhashed_data_len;
282
283     memcpy( p_sig->hash_verification, p_buf, 2 );
284     p_buf += 2; i_read += 2;
285
286     uint8_t *p, *max_pos;
287     p = p_sig->specific.v4.unhashed_data;
288     max_pos = p + scalar_number( p_sig->specific.v4.unhashed_data_len, 2 );
289
290     for( ;; )
291     {
292         if( p > max_pos )
293             return 0;
294
295         size_t i_subpacket_len;
296         if( *p < 192 )
297         {
298             if( p + 1 > max_pos )
299                 return 0;
300             i_subpacket_len = *p++;
301         }
302         else if( *p < 255 )
303         {
304             if( p + 2 > max_pos )
305                 return 0;
306             i_subpacket_len = (*p++ - 192) << 8;
307             i_subpacket_len += *p++ + 192;
308         }
309         else
310         {
311             if( p + 4 > max_pos )
312                 return 0;
313             i_subpacket_len = *++p << 24;
314             i_subpacket_len += *++p << 16;
315             i_subpacket_len += *++p << 8;
316             i_subpacket_len += *++p;
317         }
318
319         if( *p == ISSUER_SUBPACKET )
320         {
321             if( p + 9 > max_pos )
322                 return 0;
323
324             memcpy( &p_sig->issuer_longid, p+1, 8 );
325
326             return i_read;
327         }
328
329         p += i_subpacket_len;
330     }
331 }
332
333 static int parse_signature_packet( signature_packet_t *p_sig,
334                                    uint8_t *p_buf, size_t i_sig_len )
335 {
336     if( !i_sig_len ) /* 1st sanity check, we need at least the version */
337         return VLC_EGENERIC;
338
339     p_sig->version = *p_buf++;
340
341     size_t i_read;
342     switch( p_sig->version )
343     {
344         case 3:
345             i_read = parse_signature_v3_packet( p_sig, p_buf, i_sig_len );
346             break;
347         case 4:
348             p_sig->specific.v4.hashed_data = NULL;
349             p_sig->specific.v4.unhashed_data = NULL;
350             i_read = parse_signature_v4_packet( p_sig, p_buf, i_sig_len );
351             break;
352         default:
353             return VLC_EGENERIC;
354     }
355
356     if( i_read == 0 ) /* signature packet parsing has failed */
357         goto error;
358
359     if( p_sig->public_key_algo != PUBLIC_KEY_ALGO_DSA )
360         goto error;
361
362     if( p_sig->digest_algo != DIGEST_ALGO_SHA1 )
363         goto error;
364
365     switch( p_sig->type )
366     {
367         case BINARY_SIGNATURE:
368         case TEXT_SIGNATURE:
369         case GENERIC_KEY_SIGNATURE:
370         case PERSONA_KEY_SIGNATURE:
371         case CASUAL_KEY_SIGNATURE:
372         case POSITIVE_KEY_SIGNATURE:
373             break;
374         default:
375             goto error;
376     }
377
378     p_buf--; /* rewind to the version byte */
379     p_buf += i_read;
380
381     if( i_read + 2 > i_sig_len )
382         goto error;
383
384     size_t i_r_len = mpi_len( p_buf ); i_read += 2;
385     if( i_read + i_r_len > i_sig_len || i_r_len > 20 )
386         goto error;
387
388     memcpy( p_sig->r, p_buf, 2 + i_r_len );
389     p_buf += 2 + i_r_len;
390     i_read += i_r_len;
391
392     if( i_read + 2 > i_sig_len )
393         goto error;
394
395     size_t i_s_len = mpi_len( p_buf ); i_read += 2;
396     if( i_read + i_s_len > i_sig_len || i_s_len > 20 )
397         goto error;
398
399     memcpy( p_sig->s, p_buf, 2 + i_s_len );
400     p_buf += 2 + i_s_len;
401     i_read += i_s_len;
402
403     assert( i_read == i_sig_len );
404     if( i_read < i_sig_len ) /* some extra data, hm ? */
405         goto error;
406
407     return VLC_SUCCESS;
408
409 error:
410
411     if( p_sig->version == 4 )
412     {
413         free( p_sig->specific.v4.hashed_data );
414         free( p_sig->specific.v4.unhashed_data );
415     }
416
417     return VLC_EGENERIC;
418 }
419
420 /*
421  * crc_octets() was lamely copied from rfc 2440
422  * Copyright (C) The Internet Society (1998).  All Rights Reserved.
423  */
424 #define CRC24_INIT 0xB704CEL
425 #define CRC24_POLY 0x1864CFBL
426
427 static long crc_octets( uint8_t *octets, size_t len )
428 {
429     long crc = CRC24_INIT;
430     int i;
431     while (len--)
432     {
433         crc ^= (*octets++) << 16;
434         for (i = 0; i < 8; i++)
435         {
436             crc <<= 1;
437             if (crc & 0x1000000)
438                 crc ^= CRC24_POLY;
439         }
440     }
441     return crc & 0xFFFFFFL;
442 }
443
444 /*
445  * Transform an armored document in binary format
446  * Used on public keys and signatures
447  */
448 static int pgp_unarmor( char *p_ibuf, size_t i_ibuf_len,
449                         uint8_t *p_obuf, size_t i_obuf_len )
450 {
451     char *p_ipos = p_ibuf;
452     uint8_t *p_opos = p_obuf;
453     int i_end = 0;
454     int i_header_skipped = 0;
455
456     while( !i_end && p_ipos < p_ibuf + i_ibuf_len && *p_ipos != '=' )
457     {
458         if( *p_ipos == '\r' || *p_ipos == '\n' )
459         {
460             p_ipos++;
461             continue;
462         }
463
464         size_t i_line_len = strcspn( p_ipos, "\r\n" );
465         if( i_line_len == 0 )
466             continue;
467
468         if( !i_header_skipped )
469         {
470             if( !strncmp( p_ipos, "-----BEGIN PGP", 14 ) )
471                 i_header_skipped = 1;
472
473             p_ipos += i_line_len + 1;
474             continue;
475         }
476
477         if( !strncmp( p_ipos, "Version:", 8 ) )
478         {
479             p_ipos += i_line_len + 1;
480             continue;
481         }
482
483         if( p_ipos[i_line_len - 1] == '=' )
484         {
485             i_end = 1;
486             p_ipos[i_line_len - 1] = '\0';
487         }
488         else
489             p_ipos[i_line_len] = '\0';
490
491         p_opos += vlc_b64_decode_binary_to_buffer(  p_opos,
492                         p_obuf - p_opos + i_obuf_len, p_ipos );
493         p_ipos += i_line_len + 1;
494     }
495
496     /* XXX: the CRC is OPTIONAL, really require it ? */
497     if( p_ipos + 5 > p_ibuf + i_ibuf_len || *p_ipos++ != '=' )
498         return 0;
499
500     uint8_t p_crc[3];
501     if( vlc_b64_decode_binary_to_buffer( p_crc, 3, p_ipos ) != 3 )
502         return 0;
503
504     long l_crc = crc_octets( p_obuf, p_opos - p_obuf );
505     long l_crc2 = ( 0 << 24 ) + ( p_crc[0] << 16 ) + ( p_crc[1] << 8 ) + p_crc[2];
506
507     return l_crc2 == l_crc ? p_opos - p_obuf : 0;
508 }
509
510 /*
511  * Download the signature associated to a document or a binary file.
512  * We're given the file's url, we just append ".asc" to it and download
513  */
514 static int download_signature(  vlc_object_t *p_this,
515                                 signature_packet_t *p_sig,
516                                 const char *psz_url )
517 {
518     char *psz_sig = (char*) malloc( strlen( psz_url ) + 4 + 1 ); /* ".asc" + \0 */
519     if( !psz_sig )
520         return VLC_ENOMEM;
521
522     strcpy( psz_sig, psz_url );
523     strcat( psz_sig, ".asc" );
524
525     stream_t *p_stream = stream_UrlNew( p_this, psz_sig );
526     free( psz_sig );
527
528     if( !p_stream )
529         return VLC_ENOMEM;
530
531     int64_t i_size = stream_Size( p_stream );
532
533     msg_Dbg( p_this, "Downloading signature (%"PRId64" bytes)", i_size );
534     uint8_t *p_buf = (uint8_t*)malloc( i_size );
535     if( !p_buf )
536     {
537         stream_Delete( p_stream );
538         return VLC_ENOMEM;
539     }
540
541     int i_read = stream_Read( p_stream, p_buf, (int)i_size );
542
543     stream_Delete( p_stream );
544
545     if( i_read != (int)i_size )
546     {
547         msg_Dbg( p_this,
548             "Couldn't download full signature (only %d bytes)", i_read );
549         free( p_buf );
550         return VLC_EGENERIC;
551     }
552
553     if( (uint8_t)*p_buf < 0x80 ) /* ASCII */
554     {
555         msg_Dbg( p_this, "Unarmoring signature" );
556
557         uint8_t* p_unarmored = (uint8_t*) malloc( ( i_size * 3 ) / 4 + 1 );
558         if( !p_unarmored )
559         {
560             free( p_buf );
561             return VLC_EGENERIC;
562         }
563
564         int i_bytes = pgp_unarmor( (char*)p_buf, i_size, p_unarmored, i_size );
565         free( p_buf );
566
567         p_buf = p_unarmored;
568         i_size = i_bytes;
569
570         if( i_bytes < 2 )
571         {
572             free( p_buf );
573             msg_Dbg( p_this, "Unarmoring failed : corrupted signature ?" );
574             return VLC_EGENERIC;
575         }
576     }
577
578     if( packet_type( *p_buf ) != SIGNATURE_PACKET )
579     {
580         free( p_buf );
581         msg_Dbg( p_this, "Not a signature: %d", *p_buf );
582         return VLC_EGENERIC;
583     }
584
585     size_t i_header_len = packet_header_len( *p_buf );
586     if( ( i_header_len != 1 && i_header_len != 2 && i_header_len != 4 ) ||
587         i_header_len + 1 > (size_t)i_size )
588     {
589         free( p_buf );
590         msg_Dbg( p_this, "Invalid signature packet header" );
591         return VLC_EGENERIC;
592     }
593
594     size_t i_len = scalar_number( p_buf+1, i_header_len );
595     if( i_len + i_header_len + 1 != (size_t)i_size )
596     {
597         free( p_buf );
598         msg_Dbg( p_this, "Invalid signature packet" );
599         return VLC_EGENERIC;
600     }
601
602     int i_ret = parse_signature_packet( p_sig, p_buf+1+i_header_len, i_len );
603     free( p_buf );
604     if( i_ret != VLC_SUCCESS )
605     {
606         msg_Dbg( p_this, "Couldn't parse signature" );
607         return i_ret;
608     }
609
610     if( p_sig->type != BINARY_SIGNATURE && p_sig->type != TEXT_SIGNATURE )
611     {
612         msg_Dbg( p_this, "Invalid signature type: %d", p_sig->type );
613         if( p_sig->version == 4 )
614         {
615             free( p_sig->specific.v4.hashed_data );
616             free( p_sig->specific.v4.unhashed_data );
617         }
618         return VLC_EGENERIC;
619     }
620
621     return VLC_SUCCESS;
622 }
623
624 /*
625  * Verify an OpenPGP signature made on some SHA-1 hash, with some DSA public key
626  */
627 static int verify_signature( uint8_t *p_r, uint8_t *p_s,
628         public_key_packet_t *p_key, uint8_t *p_hash )
629 {
630     /* the data to be verified (a SHA-1 hash) */
631     const char *hash_sexp_s = "(data(flags raw)(value %m))";
632     /* the public key */
633     const char *key_sexp_s = "(public-key(dsa(p %m)(q %m)(g %m)(y %m)))";
634     /* the signature */
635     const char *sig_sexp_s = "(sig-val(dsa(r %m )(s %m )))";
636
637     size_t erroff;
638     gcry_mpi_t p, q, g, y, r, s, hash;
639     p = q = g = y = r = s = hash = NULL;
640     gcry_sexp_t key_sexp, hash_sexp, sig_sexp;
641     key_sexp = hash_sexp = sig_sexp = NULL;
642
643     int i_p_len = mpi_len( p_key->p );
644     int i_q_len = mpi_len( p_key->q );
645     int i_g_len = mpi_len( p_key->g );
646     int i_y_len = mpi_len( p_key->y );
647     if( gcry_mpi_scan( &p, GCRYMPI_FMT_USG, p_key->p + 2, i_p_len, NULL ) ||
648         gcry_mpi_scan( &q, GCRYMPI_FMT_USG, p_key->q + 2, i_q_len, NULL ) ||
649         gcry_mpi_scan( &g, GCRYMPI_FMT_USG, p_key->g + 2, i_g_len, NULL ) ||
650         gcry_mpi_scan( &y, GCRYMPI_FMT_USG, p_key->y + 2, i_y_len, NULL ) ||
651         gcry_sexp_build( &key_sexp, &erroff, key_sexp_s, p, q, g, y ) )
652         goto problem;
653
654     int i_r_len = mpi_len( p_r );
655     int i_s_len = mpi_len( p_s );
656     if( gcry_mpi_scan( &r, GCRYMPI_FMT_USG, p_r + 2, i_r_len, NULL ) ||
657         gcry_mpi_scan( &s, GCRYMPI_FMT_USG, p_s + 2, i_s_len, NULL ) ||
658         gcry_sexp_build( &sig_sexp, &erroff, sig_sexp_s, r, s ) )
659         goto problem;
660
661     int i_hash_len = 20;
662     if( gcry_mpi_scan( &hash, GCRYMPI_FMT_USG, p_hash, i_hash_len, NULL ) ||
663         gcry_sexp_build( &hash_sexp, &erroff, hash_sexp_s, hash ) )
664         goto problem;
665
666     if( gcry_pk_verify( sig_sexp, hash_sexp, key_sexp ) )
667         goto problem;
668
669     return VLC_SUCCESS;
670
671 problem:
672     if( p ) gcry_mpi_release( p );
673     if( q ) gcry_mpi_release( q );
674     if( g ) gcry_mpi_release( g );
675     if( y ) gcry_mpi_release( y );
676     if( r ) gcry_mpi_release( r );
677     if( s ) gcry_mpi_release( s );
678     if( hash ) gcry_mpi_release( hash );
679     if( key_sexp ) gcry_sexp_release( key_sexp );
680     if( sig_sexp ) gcry_sexp_release( sig_sexp );
681     if( hash_sexp ) gcry_sexp_release( hash_sexp );
682     return VLC_EGENERIC;
683 }
684
685 /*
686  * fill a public_key_t with public key data, including:
687  *   * public key packet
688  *   * signature packet issued by key which long id is p_sig_issuer
689  *   * user id packet
690  */
691 static int parse_public_key( const uint8_t *p_key_data, size_t i_key_len,
692                              public_key_t *p_key, const uint8_t *p_sig_issuer )
693 {
694     uint8_t *pos = (uint8_t*) p_key_data;
695     uint8_t *max_pos = pos + i_key_len;
696
697     int i_status = 0;
698 #define PUBLIC_KEY_FOUND    0x01
699 #define USER_ID_FOUND       0x02
700 #define SIGNATURE_FOUND     0X04
701
702     uint8_t *p_key_unarmored = NULL;
703
704     p_key->psz_username = NULL;
705     p_key->sig.specific.v4.hashed_data = NULL;
706     p_key->sig.specific.v4.unhashed_data = NULL;
707
708     if( !( *pos & 0x80 ) )
709     {   /* first byte is ASCII, unarmoring */
710         p_key_unarmored = (uint8_t*)malloc( i_key_len );
711         if( !p_key_unarmored )
712             return VLC_ENOMEM;
713         int i_len = pgp_unarmor( (char*)p_key_data, i_key_len,
714                                  p_key_unarmored, i_key_len );
715
716         if( i_len == 0 )
717             goto error;
718
719         pos = p_key_unarmored;
720         max_pos = pos + i_len;
721     }
722
723     while( pos < max_pos )
724     {
725         if( !(*pos & 0x80) || *pos & 0x40 )
726             goto error;
727
728         int i_type = packet_type( *pos );
729
730         int i_header_len = packet_header_len( *pos++ );
731         if( pos + i_header_len > max_pos ||
732             ( i_header_len != 1 && i_header_len != 2 && i_header_len != 4 ) )
733             goto error;
734
735         int i_packet_len = scalar_number( pos, i_header_len );
736         pos += i_header_len;
737
738         if( pos + i_packet_len > max_pos )
739             goto error;
740
741         switch( i_type )
742         {
743             case PUBLIC_KEY_PACKET:
744                 i_status |= PUBLIC_KEY_FOUND;
745                 if( parse_public_key_packet( &p_key->key, pos, i_packet_len ) != VLC_SUCCESS )
746                     goto error;
747                 break;
748
749             case SIGNATURE_PACKET: /* we accept only v4 signatures here */
750                 if( i_status & SIGNATURE_FOUND || !p_sig_issuer )
751                     break;
752                 int i_ret = parse_signature_packet( &p_key->sig, pos,
753                                                     i_packet_len );
754                 if( i_ret == VLC_SUCCESS )
755                 {
756                     if( p_key->sig.version != 4 )
757                         break;
758                     if( memcmp( p_key->sig.issuer_longid, p_sig_issuer, 8 ) )
759                     {
760                         free( p_key->sig.specific.v4.hashed_data );
761                         free( p_key->sig.specific.v4.unhashed_data );
762                         p_key->sig.specific.v4.hashed_data = NULL;
763                         p_key->sig.specific.v4.unhashed_data = NULL;
764                         break;
765                     }
766                     i_status |= SIGNATURE_FOUND;
767                 }
768                 break;
769
770             case USER_ID_PACKET:
771                 if( p_key->psz_username ) /* save only the first User ID */
772                     break;
773                 i_status |= USER_ID_FOUND;
774                 p_key->psz_username = (uint8_t*)malloc( i_packet_len + 1);
775                 if( !p_key->psz_username )
776                     goto error;
777
778                 memcpy( p_key->psz_username, pos, i_packet_len );
779                 p_key->psz_username[i_packet_len] = '\0';
780                 break;
781
782             default:
783                 break;
784         }
785         pos += i_packet_len;
786     }
787     free( p_key_unarmored );
788
789     if( !( i_status & ( PUBLIC_KEY_FOUND | USER_ID_FOUND ) ) )
790         return VLC_EGENERIC;
791
792     if( p_sig_issuer && !( i_status & SIGNATURE_FOUND ) )
793         return VLC_EGENERIC;
794
795     return VLC_SUCCESS;
796
797 error:
798     if( p_key->sig.version == 4 )
799     {
800         free( p_key->sig.specific.v4.hashed_data );
801         free( p_key->sig.specific.v4.unhashed_data );
802     }
803     free( p_key->psz_username );
804     free( p_key_unarmored );
805     return VLC_EGENERIC;
806 }
807
808 /*
809  * return a sha1 hash of a file
810  */
811 static uint8_t *hash_sha1_from_file( const char *psz_file,
812                             signature_packet_t *p_sig )
813 {
814     if( p_sig->type != BINARY_SIGNATURE && p_sig->type != TEXT_SIGNATURE )
815         return NULL;
816
817     FILE *f = utf8_fopen( psz_file, "r" );
818     if( !f )
819         return NULL;
820
821     uint8_t buffer[4096];
822
823     gcry_md_hd_t hd;
824     if( gcry_md_open( &hd, GCRY_MD_SHA1, 0 ) )
825     {
826         fclose( f );
827         return NULL;
828     }
829
830     size_t i_read;
831     while( ( i_read = fread( buffer, 1, sizeof(buffer), f ) ) > 0 )
832         gcry_md_write( hd, buffer, i_read );
833
834     if( p_sig->version == 3 )
835     {
836         gcry_md_putc( hd, p_sig->type );
837         gcry_md_write( hd, &p_sig->specific.v3.timestamp, 4 );
838     }
839     else if( p_sig->version == 4 )
840     {
841         gcry_md_putc( hd, p_sig->version );
842         gcry_md_putc( hd, p_sig->type );
843         gcry_md_putc( hd, p_sig->public_key_algo );
844         gcry_md_putc( hd, p_sig->digest_algo );
845         gcry_md_write( hd, p_sig->specific.v4.hashed_data_len, 2 );
846         size_t i_len = scalar_number( p_sig->specific.v4.hashed_data_len, 2 );
847         gcry_md_write( hd, p_sig->specific.v4.hashed_data, i_len );
848     }
849     else
850     {   /* RFC 4880 only tells about versions 3 and 4 */
851         gcry_md_close( hd );
852         return NULL;
853     }
854
855     fclose( f );
856     gcry_md_final( hd );
857
858     uint8_t *p_tmp = (uint8_t*) gcry_md_read( hd, GCRY_MD_SHA1);
859     uint8_t *p_hash = malloc( 20 );
860     if( p_hash )
861         memcpy( p_hash, p_tmp, 20 );
862     gcry_md_close( hd );
863     return p_hash;
864 }
865
866 /*
867  * download a public key (the last one) from videolan server, and parse it
868  */
869 static public_key_t *download_key( vlc_object_t *p_this,
870                     const uint8_t *p_longid, const uint8_t *p_signature_issuer )
871 {
872     char *psz_url;
873     if( asprintf( &psz_url, "http://download.videolan.org/pub/keys/%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X.asc",
874                     p_longid[0], p_longid[1], p_longid[2], p_longid[3],
875                     p_longid[4], p_longid[5], p_longid[6], p_longid[7] ) == -1 )
876         return NULL;
877
878     stream_t *p_stream = stream_UrlNew( p_this, psz_url );
879     free( psz_url );
880     if( !p_stream )
881         return NULL;
882
883     int64_t i_size = stream_Size( p_stream );
884     if( i_size < 0 )
885     {
886         stream_Delete( p_stream );
887         return NULL;
888     }
889
890     uint8_t *p_buf = (uint8_t*)malloc( i_size );
891     if( !p_buf )
892     {
893         stream_Delete( p_stream );
894         return NULL;
895     }
896
897     int i_read = stream_Read( p_stream, p_buf, (int)i_size );
898     stream_Delete( p_stream );
899
900     if( i_read != (int)i_size )
901     {
902         msg_Dbg( p_this, "Couldn't read full GPG key" );
903         free( p_buf );
904         return NULL;
905     }
906
907     public_key_t *p_pkey = (public_key_t*) malloc( sizeof( public_key_t ) );
908     if( !p_pkey )
909     {
910         free( p_buf );
911         return NULL;
912     }
913
914     memcpy( p_pkey->longid, p_longid, 8 );
915
916     int i_error = parse_public_key( p_buf, i_read, p_pkey, p_signature_issuer );
917     free( p_buf );
918
919     if( i_error != VLC_SUCCESS )
920     {
921         msg_Dbg( p_this, "Couldn't parse GPG key" );
922         free( p_pkey );
923         return NULL;
924     }
925
926     return p_pkey;
927 }
928
929 /*
930  * Generate a SHA1 hash on a public key, to verify a signature made on that hash
931  * Note that we need the signature (v4) to compute the hash
932  */
933 static uint8_t *key_sign_hash( public_key_t *p_pkey )
934 {
935     if( p_pkey->sig.version != 4 )
936         return NULL;
937
938     if( p_pkey->sig.type < GENERIC_KEY_SIGNATURE ||
939         p_pkey->sig.type > POSITIVE_KEY_SIGNATURE )
940         return NULL;
941
942     gcry_error_t error = 0;
943     gcry_md_hd_t hd;
944
945     error = gcry_md_open( &hd, GCRY_MD_SHA1, 0 );
946     if( error )
947         return NULL;
948
949     gcry_md_putc( hd, 0x99 );
950
951     size_t i_p_len = mpi_len( p_pkey->key.p );
952     size_t i_g_len = mpi_len( p_pkey->key.g );
953     size_t i_q_len = mpi_len( p_pkey->key.q );
954     size_t i_y_len = mpi_len( p_pkey->key.y );
955
956     size_t i_size = 6 + 2*4 + i_p_len + i_g_len + i_q_len + i_y_len;
957
958     gcry_md_putc( hd, (i_size >> 8) & 0xff );
959     gcry_md_putc( hd, i_size & 0xff );
960
961     gcry_md_putc( hd, p_pkey->key.version );
962     gcry_md_write( hd, p_pkey->key.timestamp, 4 );
963     gcry_md_putc( hd, p_pkey->key.algo );
964
965     gcry_md_write( hd, (uint8_t*)&p_pkey->key.p, 2 );
966     gcry_md_write( hd, (uint8_t*)&p_pkey->key.p + 2, i_p_len );
967
968     gcry_md_write( hd, (uint8_t*)&p_pkey->key.q, 2 );
969     gcry_md_write( hd, (uint8_t*)&p_pkey->key.q + 2, i_q_len );
970
971     gcry_md_write( hd, (uint8_t*)&p_pkey->key.g, 2 );
972     gcry_md_write( hd, (uint8_t*)&p_pkey->key.g + 2, i_g_len );
973
974     gcry_md_write( hd, (uint8_t*)&p_pkey->key.y, 2 );
975     gcry_md_write( hd, (uint8_t*)&p_pkey->key.y + 2, i_y_len );
976
977     gcry_md_putc( hd, 0xb4 );
978
979     size_t i_len = strlen((char*)p_pkey->psz_username);
980
981     gcry_md_putc( hd, (i_len << 24) & 0xff );
982     gcry_md_putc( hd, (i_len << 16) & 0xff );
983     gcry_md_putc( hd, (i_len << 8) & 0xff );
984     gcry_md_putc( hd, (i_len) & 0xff );
985
986     gcry_md_write( hd, p_pkey->psz_username, i_len );
987
988     size_t i_hashed_data_len =
989         scalar_number( p_pkey->sig.specific.v4.hashed_data_len, 2 );
990
991     gcry_md_putc( hd, p_pkey->sig.version );
992     gcry_md_putc( hd, p_pkey->sig.type );
993     gcry_md_putc( hd, p_pkey->sig.public_key_algo );
994     gcry_md_putc( hd, p_pkey->sig.digest_algo );
995     gcry_md_write( hd, p_pkey->sig.specific.v4.hashed_data_len, 2 );
996     gcry_md_write( hd, p_pkey->sig.specific.v4.hashed_data, i_hashed_data_len );
997
998     gcry_md_putc( hd, 0x04 );
999     gcry_md_putc( hd, 0xff );
1000
1001     i_hashed_data_len += 6; /* hashed data + 6 bytes header */
1002
1003     gcry_md_putc( hd, (i_hashed_data_len << 24) & 0xff);
1004     gcry_md_putc( hd, (i_hashed_data_len << 16) &0xff );
1005     gcry_md_putc( hd, (i_hashed_data_len << 8) & 0xff );
1006     gcry_md_putc( hd, (i_hashed_data_len) & 0xff );
1007
1008     gcry_md_final( hd );
1009
1010     uint8_t *p_tmp = gcry_md_read( hd, GCRY_MD_SHA1);
1011
1012     if( !p_tmp ||
1013         p_tmp[0] != p_pkey->sig.hash_verification[0] ||
1014         p_tmp[1] != p_pkey->sig.hash_verification[1] )
1015     {
1016         gcry_md_close( hd );
1017         return NULL;
1018     }
1019
1020     uint8_t *p_hash = malloc( 20 );
1021     if( p_hash )
1022         memcpy( p_hash, p_tmp, 20 );
1023     gcry_md_close( hd );
1024     return p_hash;
1025 }
1026
1027
1028 /*****************************************************************************
1029  * Update_t functions
1030  *****************************************************************************/
1031
1032 /**
1033  * Create a new update VLC struct
1034  *
1035  * \param p_this the calling vlc_object
1036  * \return pointer to new update_t or NULL
1037  */
1038 update_t *__update_New( vlc_object_t *p_this )
1039 {
1040     update_t *p_update;
1041     assert( p_this );
1042
1043     p_update = (update_t *)malloc( sizeof( update_t ) );
1044     if( !p_update ) return NULL;
1045
1046     vlc_mutex_init( &p_update->lock );
1047
1048     p_update->p_libvlc = p_this->p_libvlc;
1049
1050     p_update->release.psz_url = NULL;
1051     p_update->release.psz_desc = NULL;
1052
1053     p_update->p_download = NULL;
1054     p_update->p_check = NULL;
1055
1056     p_update->p_pkey = NULL;
1057     vlc_gcrypt_init();
1058
1059     return p_update;
1060 }
1061
1062 /**
1063  * Delete an update_t struct
1064  *
1065  * \param p_update update_t* pointer
1066  * \return nothing
1067  */
1068 void update_Delete( update_t *p_update )
1069 {
1070     assert( p_update );
1071
1072     if( p_update->p_check )
1073     {
1074         assert( !p_update->p_download );
1075         vlc_object_kill( p_update->p_check );
1076         vlc_thread_join( p_update->p_check );
1077     }
1078     else if( p_update->p_download )
1079     {
1080         vlc_object_kill( p_update->p_download );
1081         vlc_thread_join( p_update->p_download );
1082     }
1083
1084     vlc_mutex_destroy( &p_update->lock );
1085
1086     free( p_update->release.psz_url );
1087     free( p_update->release.psz_desc );
1088     free( p_update->p_pkey );
1089
1090     free( p_update );
1091 }
1092
1093 /**
1094  * Empty the release struct
1095  *
1096  * \param p_update update_t* pointer
1097  * \return nothing
1098  */
1099 static void EmptyRelease( update_t *p_update )
1100 {
1101     p_update->release.i_major = 0;
1102     p_update->release.i_minor = 0;
1103     p_update->release.i_revision = 0;
1104
1105     FREENULL( p_update->release.psz_url );
1106     FREENULL( p_update->release.psz_desc );
1107 }
1108
1109 /**
1110  * Get the update file and parse it
1111  * p_update has to be locked when calling this function
1112  *
1113  * \param p_update pointer to update struct
1114  * \return true if the update is valid and authenticated
1115  */
1116 static bool GetUpdateFile( update_t *p_update )
1117 {
1118     stream_t *p_stream = NULL;
1119     int i_major = 0;
1120     int i_minor = 0;
1121     int i_revision = 0;
1122     unsigned char extra;
1123     char *psz_version_line = NULL;
1124
1125     p_stream = stream_UrlNew( p_update->p_libvlc, UPDATE_VLC_STATUS_URL );
1126     if( !p_stream )
1127     {
1128         msg_Err( p_update->p_libvlc, "Failed to open %s for reading",
1129                  UPDATE_VLC_STATUS_URL );
1130         goto error;
1131     }
1132
1133     /* Start reading the status file */
1134     if( !( psz_version_line = stream_ReadLine( p_stream ) ) )
1135     {
1136         msg_Err( p_update->p_libvlc, "Update file %s is corrupted : missing version",
1137                  UPDATE_VLC_STATUS_URL );
1138         goto error;
1139     }
1140
1141     /* first line : version number */
1142     p_update->release.extra = 0;
1143     switch( sscanf( psz_version_line, "%i.%i.%i%c",
1144                     &i_major, &i_minor, &i_revision, &extra ) )
1145     {
1146         case 4:
1147             p_update->release.extra = extra;
1148         case 3:
1149             p_update->release.i_major = i_major;
1150             p_update->release.i_minor = i_minor;
1151             p_update->release.i_revision = i_revision;
1152             break;
1153         default:
1154             msg_Err( p_update->p_libvlc, "Update version false formated" );
1155             goto error;
1156     }
1157
1158     /* second line : URL */
1159     if( !( p_update->release.psz_url = stream_ReadLine( p_stream ) ) )
1160     {
1161         msg_Err( p_update->p_libvlc, "Update file %s is corrupted : URL missing",
1162                  UPDATE_VLC_STATUS_URL );
1163         goto error;
1164     }
1165
1166     /* Remaining data : description */
1167     int i_read = stream_Size( p_stream ) - stream_Tell( p_stream );
1168     if( i_read <= 0 )
1169     {
1170         msg_Err( p_update->p_libvlc,
1171                 "Update file %s is corrupted: description missing",
1172                 UPDATE_VLC_STATUS_URL );
1173         goto error;
1174     }
1175
1176     p_update->release.psz_desc = (char*) malloc( i_read + 1 );
1177     if( !p_update->release.psz_desc )
1178         goto error;
1179
1180     if( stream_Read( p_stream, p_update->release.psz_desc, i_read ) != i_read )
1181     {
1182         msg_Err( p_update->p_libvlc, "Couldn't download update file %s",
1183                 UPDATE_VLC_STATUS_URL );
1184         goto error;
1185     }
1186     p_update->release.psz_desc[i_read] = '\0';
1187
1188     stream_Delete( p_stream );
1189     p_stream = NULL;
1190
1191     /* Now that we know the status is valid, we must download its signature
1192      * to authenticate it */
1193     signature_packet_t sign;
1194     if( download_signature( VLC_OBJECT( p_update->p_libvlc ), &sign,
1195             UPDATE_VLC_STATUS_URL ) != VLC_SUCCESS )
1196     {
1197         msg_Err( p_update->p_libvlc, "Couldn't download signature of status file" );
1198         goto error;
1199     }
1200
1201     if( sign.type != BINARY_SIGNATURE && sign.type != TEXT_SIGNATURE )
1202     {
1203         msg_Err( p_update->p_libvlc, "Invalid signature type" );
1204         goto error;
1205     }
1206
1207     p_update->p_pkey = (public_key_t*)malloc( sizeof( public_key_t ) );
1208     if( !p_update->p_pkey )
1209         goto error;
1210
1211     if( parse_public_key( videolan_public_key, sizeof( videolan_public_key ),
1212                         p_update->p_pkey, NULL ) != VLC_SUCCESS )
1213     {
1214         msg_Err( p_update->p_libvlc, "Couldn't parse embedded public key, something went really wrong..." );
1215         FREENULL( p_update->p_pkey );
1216         goto error;
1217     }
1218
1219     memcpy( p_update->p_pkey->longid, videolan_public_key_longid, 8 );
1220
1221     if( memcmp( sign.issuer_longid, p_update->p_pkey->longid , 8 ) != 0 )
1222     {
1223         msg_Dbg( p_update->p_libvlc, "Need to download the GPG key" );
1224         public_key_t *p_new_pkey = download_key(
1225                 VLC_OBJECT(p_update->p_libvlc),
1226                 sign.issuer_longid, videolan_public_key_longid );
1227         if( !p_new_pkey )
1228         {
1229             msg_Err( p_update->p_libvlc, "Couldn't download GPG key" );
1230             FREENULL( p_update->p_pkey );
1231             goto error;
1232         }
1233
1234         uint8_t *p_hash = key_sign_hash( p_new_pkey );
1235         if( !p_hash )
1236         {
1237             msg_Err( p_update->p_libvlc, "Failed to hash signature" );
1238             free( p_new_pkey );
1239             FREENULL( p_update->p_pkey );
1240             goto error;
1241         }
1242
1243         if( verify_signature( p_new_pkey->sig.r, p_new_pkey->sig.s,
1244                     &p_update->p_pkey->key, p_hash ) == VLC_SUCCESS )
1245         {
1246             free( p_hash );
1247             msg_Info( p_update->p_libvlc, "Key authenticated" );
1248             free( p_update->p_pkey );
1249             p_update->p_pkey = p_new_pkey;
1250         }
1251         else
1252         {
1253             free( p_hash );
1254             msg_Err( p_update->p_libvlc, "Key signature invalid !\n" );
1255             goto error;
1256         }
1257     }
1258
1259     gcry_md_hd_t hd;
1260     if( gcry_md_open( &hd, GCRY_MD_SHA1, 0 ) )
1261         goto error_hd;
1262
1263     gcry_md_write( hd, psz_version_line, strlen( psz_version_line ) );
1264     FREENULL( psz_version_line );
1265     if( sign.type == TEXT_SIGNATURE )
1266         gcry_md_putc( hd, '\r' );
1267     gcry_md_putc( hd, '\n' );
1268     gcry_md_write( hd, p_update->release.psz_url,
1269                         strlen( p_update->release.psz_url ) );
1270     if( sign.type == TEXT_SIGNATURE )
1271         gcry_md_putc( hd, '\r' );
1272     gcry_md_putc( hd, '\n' );
1273
1274     char *psz_desc = p_update->release.psz_desc;
1275     while( *psz_desc )
1276     {
1277         size_t i_len = strcspn( psz_desc, "\r\n" );
1278         if( !i_len )
1279             break;
1280
1281         gcry_md_write( hd, psz_desc, i_len );
1282         if( sign.type == TEXT_SIGNATURE )
1283             gcry_md_putc( hd, '\r' );
1284         gcry_md_putc( hd, '\n' );
1285
1286         psz_desc += i_len;
1287         while( *psz_desc == '\r' || *psz_desc == '\n' )
1288             psz_desc++;
1289     }
1290
1291     if( sign.version == 3 )
1292     {
1293         gcry_md_putc( hd, sign.type );
1294         gcry_md_write( hd, &sign.specific.v3.timestamp, 4 );
1295     }
1296     else if( sign.version == 4 )
1297     {
1298         gcry_md_putc( hd, sign.version );
1299         gcry_md_putc( hd, sign.type );
1300         gcry_md_putc( hd, sign.public_key_algo );
1301         gcry_md_putc( hd, sign.digest_algo );
1302         gcry_md_write( hd, sign.specific.v4.hashed_data_len, 2 );
1303         size_t i_len = scalar_number( sign.specific.v4.hashed_data_len, 2 );
1304         gcry_md_write( hd, sign.specific.v4.hashed_data, i_len );
1305         gcry_md_putc( hd, 0x04 );
1306         gcry_md_putc( hd, 0xFF );
1307
1308         i_len += 6; /* hashed data + 6 bytes header */
1309
1310         gcry_md_putc( hd, (i_len << 24) & 0xff);
1311         gcry_md_putc( hd, (i_len << 16) &0xff );
1312         gcry_md_putc( hd, (i_len << 8) & 0xff );
1313         gcry_md_putc( hd, (i_len) & 0xff );
1314     }
1315     else
1316     {   /* RFC 4880 only tells about versions 3 and 4 */
1317         msg_Warn( p_update->p_libvlc, "Invalid signature version %d",
1318                 sign.version);
1319         goto error_hd;
1320     }
1321
1322     gcry_md_final( hd );
1323
1324     uint8_t *p_hash = gcry_md_read( hd, GCRY_MD_SHA1 );
1325
1326     if( p_hash[0] != sign.hash_verification[0] ||
1327         p_hash[1] != sign.hash_verification[1] )
1328     {
1329         msg_Warn( p_update->p_libvlc, "Bad SHA1 hash for status file" );
1330         goto error_hd;
1331     }
1332
1333     if( verify_signature( sign.r, sign.s, &p_update->p_pkey->key, p_hash )
1334             != VLC_SUCCESS )
1335     {
1336         msg_Err( p_update->p_libvlc, "BAD SIGNATURE for status file" );
1337         goto error_hd;
1338     }
1339     else
1340     {
1341         msg_Info( p_update->p_libvlc, "Status file authenticated" );
1342         gcry_md_close( hd );
1343         return true;
1344     }
1345
1346 error_hd:
1347     gcry_md_close( hd );
1348 error:
1349     if( p_stream )
1350         stream_Delete( p_stream );
1351     free( psz_version_line );
1352     return false;
1353 }
1354
1355 static void update_CheckReal( update_check_thread_t *p_uct );
1356
1357 /**
1358  * Check for updates
1359  *
1360  * \param p_update pointer to update struct
1361  * \param pf_callback pointer to a function to call when the update_check is finished
1362  * \param p_data pointer to some datas to give to the callback
1363  * \returns nothing
1364  */
1365 void update_Check( update_t *p_update, void (*pf_callback)( void*, bool ), void *p_data )
1366 {
1367     assert( p_update );
1368
1369     update_check_thread_t *p_uct =
1370         vlc_custom_create( p_update->p_libvlc, sizeof( *p_uct ),
1371                            VLC_OBJECT_GENERIC, "update check" );
1372     if( !p_uct ) return;
1373
1374     p_uct->p_update = p_update;
1375     p_update->p_check = p_uct;
1376     p_uct->pf_callback = pf_callback;
1377     p_uct->p_data = p_data;
1378
1379     vlc_thread_create( p_uct, "check for update", update_CheckReal,
1380                        VLC_THREAD_PRIORITY_LOW, false );
1381 }
1382
1383 void update_CheckReal( update_check_thread_t *p_uct )
1384 {
1385     bool b_ret;
1386     vlc_mutex_lock( &p_uct->p_update->lock );
1387
1388     EmptyRelease( p_uct->p_update );
1389     b_ret = GetUpdateFile( p_uct->p_update );
1390     vlc_mutex_unlock( &p_uct->p_update->lock );
1391
1392     if( p_uct->pf_callback )
1393         (p_uct->pf_callback)( p_uct->p_data, b_ret );
1394
1395     p_uct->p_update->p_check = NULL;
1396
1397     vlc_object_release( p_uct );
1398 }
1399
1400 /**
1401  * Compare a given release's version number to the current VLC's one
1402  *
1403  * \param p_update structure
1404  * \return true if we have to upgrade to the given version to be up to date
1405  */
1406 bool update_NeedUpgrade( update_t *p_update )
1407 {
1408     assert( p_update );
1409
1410     return  p_update->release.i_major    < *PACKAGE_VERSION_MAJOR    - '0'  ||
1411             p_update->release.i_minor    < *PACKAGE_VERSION_MINOR    - '0'  ||
1412             p_update->release.i_revision < *PACKAGE_VERSION_REVISION - '0'  ||
1413             p_update->release.extra      < *PACKAGE_VERSION_EXTRA;
1414 }
1415
1416 /**
1417  * Convert a long int size in bytes to a string
1418  *
1419  * \param l_size the size in bytes
1420  * \return the size as a string
1421  */
1422 static char *size_str( long int l_size )
1423 {
1424     char *psz_tmp = NULL;
1425     int i_retval = 0;
1426     if( l_size >> 30 )
1427         i_retval = asprintf( &psz_tmp, "%.1f GB", (float)l_size/(1<<30) );
1428     else if( l_size >> 20 )
1429         i_retval = asprintf( &psz_tmp, "%.1f MB", (float)l_size/(1<<20) );
1430     else if( l_size >> 10 )
1431         i_retval = asprintf( &psz_tmp, "%.1f kB", (float)l_size/(1<<10) );
1432     else
1433         i_retval = asprintf( &psz_tmp, "%ld B", l_size );
1434
1435     return i_retval == -1 ? NULL : psz_tmp;
1436 }
1437
1438 static void update_DownloadReal( update_download_thread_t *p_udt );
1439
1440 /**
1441  * Download the file given in the update_t
1442  *
1443  * \param p_update structure
1444  * \param dir to store the download file
1445  * \return nothing
1446  */
1447 void update_Download( update_t *p_update, const char *psz_destdir )
1448 {
1449     assert( p_update );
1450
1451     update_download_thread_t *p_udt =
1452         vlc_custom_create( p_update->p_libvlc, sizeof( *p_udt ),
1453                            VLC_OBJECT_GENERIC, "update download" );
1454     if( !p_udt )
1455         return;
1456
1457     p_udt->p_update = p_update;
1458     p_update->p_download = p_udt;
1459     p_udt->psz_destdir = psz_destdir ? strdup( psz_destdir ) : NULL;
1460
1461     vlc_thread_create( p_udt, "download update", update_DownloadReal,
1462                        VLC_THREAD_PRIORITY_LOW, false );
1463 }
1464
1465 static void update_DownloadReal( update_download_thread_t *p_udt )
1466 {
1467     int i_progress = 0;
1468     long int l_size;
1469     long int l_downloaded = 0;
1470     float f_progress;
1471     char *psz_status = NULL;
1472     char *psz_downloaded = NULL;
1473     char *psz_size = NULL;
1474     char *psz_destfile = NULL;
1475     char *psz_tmpdestfile = NULL;
1476
1477     FILE *p_file = NULL;
1478     stream_t *p_stream = NULL;
1479     void* p_buffer = NULL;
1480     int i_read;
1481
1482     update_t *p_update = p_udt->p_update;
1483     char *psz_destdir = p_udt->psz_destdir;
1484
1485     /* Open the stream */
1486     p_stream = stream_UrlNew( p_udt, p_update->release.psz_url );
1487     if( !p_stream )
1488     {
1489         msg_Err( p_udt, "Failed to open %s for reading", p_update->release.psz_url );
1490         goto end;
1491     }
1492
1493     /* Get the stream size */
1494     l_size = stream_Size( p_stream );
1495
1496     /* Get the file name and open it*/
1497     psz_tmpdestfile = strrchr( p_update->release.psz_url, '/' );
1498     if( !psz_tmpdestfile )
1499     {
1500         msg_Err( p_udt, "The URL %s is false formated", p_update->release.psz_url );
1501         goto end;
1502     }
1503     psz_tmpdestfile++;
1504     if( asprintf( &psz_destfile, "%s%s", psz_destdir, psz_tmpdestfile ) == -1 )
1505         goto end;
1506
1507     p_file = utf8_fopen( psz_destfile, "w" );
1508     if( !p_file )
1509     {
1510         msg_Err( p_udt, "Failed to open %s for writing", psz_destfile );
1511         goto end;
1512     }
1513
1514     /* Create a buffer and fill it with the downloaded file */
1515     p_buffer = (void *)malloc( 1 << 10 );
1516     if( !p_buffer )
1517         goto end;
1518
1519     psz_size = size_str( l_size );
1520     if( asprintf( &psz_status, "%s\nDownloading... O.O/%s %.1f%% done",
1521         p_update->release.psz_url, psz_size, 0.0 ) != -1 )
1522     {
1523         i_progress = intf_UserProgress( p_udt, "Downloading ...", psz_status, 0.0, 0 );
1524         free( psz_status );
1525     }
1526
1527     vlc_object_lock( p_udt );
1528     while( vlc_object_alive( p_udt ) &&
1529            ( i_read = stream_Read( p_stream, p_buffer, 1 << 10 ) ) &&
1530            !intf_ProgressIsCancelled( p_udt, i_progress ) )
1531     {
1532         vlc_object_unlock( p_udt );
1533         if( fwrite( p_buffer, i_read, 1, p_file ) < 1 )
1534         {
1535             msg_Err( p_udt, "Failed to write into %s", psz_destfile );
1536             break;
1537         }
1538
1539         l_downloaded += i_read;
1540         psz_downloaded = size_str( l_downloaded );
1541         f_progress = 100.0*(float)l_downloaded/(float)l_size;
1542
1543         if( asprintf( &psz_status, "%s\nDonwloading... %s/%s %.1f%% done",
1544                       p_update->release.psz_url, psz_downloaded, psz_size,
1545                       f_progress ) != -1 )
1546         {
1547             intf_ProgressUpdate( p_udt, i_progress, psz_status, f_progress, 0 );
1548             free( psz_status );
1549         }
1550         free( psz_downloaded );
1551         vlc_object_lock( p_udt );
1552     }
1553
1554     /* Finish the progress bar or delete the file if the user had canceled */
1555     fclose( p_file );
1556     p_file = NULL;
1557
1558     if( vlc_object_alive( p_udt ) &&
1559         !intf_ProgressIsCancelled( p_udt, i_progress ) )
1560     {
1561         vlc_object_unlock( p_udt );
1562         if( asprintf( &psz_status, "%s\nDone %s (100.0%%)",
1563             p_update->release.psz_url, psz_size ) != -1 )
1564         {
1565             intf_ProgressUpdate( p_udt, i_progress, psz_status, 100.0, 0 );
1566             free( psz_status );
1567         }
1568     }
1569     else
1570     {
1571         vlc_object_unlock( p_udt );
1572         utf8_unlink( psz_destfile );
1573         goto end;
1574     }
1575
1576     signature_packet_t sign;
1577     if( download_signature( VLC_OBJECT( p_udt ), &sign,
1578             p_update->release.psz_url ) != VLC_SUCCESS )
1579     {
1580         utf8_unlink( psz_destfile );
1581
1582         intf_UserFatal( p_udt, true, _("File could not be verified"),
1583             _("It was not possible to download a cryptographic signature for "
1584               "the downloaded file \"%s\". Thus, it was deleted."),
1585             psz_destfile );
1586         msg_Err( p_udt, "Couldn't download signature of downloaded file" );
1587         goto end;
1588     }
1589
1590     if( memcmp( sign.issuer_longid, p_update->p_pkey->longid, 8 ) )
1591     {
1592         utf8_unlink( psz_destfile );
1593         msg_Err( p_udt, "Invalid signature issuer" );
1594         intf_UserFatal( p_udt, true, _("Invalid signature"),
1595             _("The cryptographic signature for the downloaded file \"%s\" was "
1596               "invalid and could not be used to securely verify it. Thus, the "
1597               "file was deleted."),
1598             psz_destfile );
1599         goto end;
1600     }
1601
1602     if( sign.type != BINARY_SIGNATURE )
1603     {
1604         utf8_unlink( psz_destfile );
1605         msg_Err( p_udt, "Invalid signature type" );
1606         intf_UserFatal( p_udt, true, _("Invalid signature"),
1607             _("The cryptographic signature for the downloaded file \"%s\" was "
1608               "invalid and could not be used to securely verify it. Thus, the "
1609               "file was deleted."),
1610             psz_destfile );
1611         goto end;
1612     }
1613
1614     uint8_t *p_hash = hash_sha1_from_file( psz_destfile, &sign );
1615     if( !p_hash )
1616     {
1617         msg_Err( p_udt, "Unable to hash %s", psz_destfile );
1618         utf8_unlink( psz_destfile );
1619         intf_UserFatal( p_udt, true, _("File not verifiable"),
1620             _("It was not possible to securely verify the downloaded file"
1621               " \"%s\". Thus, it was VLC deleted."),
1622             psz_destfile );
1623
1624         goto end;
1625     }
1626
1627     if( p_hash[0] != sign.hash_verification[0] ||
1628         p_hash[1] != sign.hash_verification[1] )
1629     {
1630         utf8_unlink( psz_destfile );
1631         intf_UserFatal( p_udt, true, _("File corrupted"),
1632             _("Downloaded file \"%s\" was corrupted. Thus, it was deleted."),
1633              psz_destfile );
1634         msg_Err( p_udt, "Bad SHA1 hash for %s", psz_destfile );
1635         free( p_hash );
1636         goto end;
1637     }
1638
1639     if( verify_signature( sign.r, sign.s, &p_update->p_pkey->key, p_hash )
1640             != VLC_SUCCESS )
1641     {
1642         utf8_unlink( psz_destfile );
1643         intf_UserFatal( p_udt, true, _("File corrupted"),
1644             _("Downloaded file \"%s\" was corrupted. Thus, it was deleted."),
1645              psz_destfile );
1646         msg_Err( p_udt, "BAD SIGNATURE for %s", psz_destfile );
1647         free( p_hash );
1648         goto end;
1649     }
1650
1651     msg_Info( p_udt, "%s authenticated", psz_destfile );
1652     free( p_hash );
1653
1654 end:
1655     if( p_stream )
1656         stream_Delete( p_stream );
1657     if( p_file )
1658         fclose( p_file );
1659     free( psz_destdir );
1660     free( psz_destfile );
1661     free( p_buffer );
1662     free( psz_size );
1663
1664     p_udt->p_update->p_download = NULL;
1665
1666     vlc_object_release( p_udt );
1667 }
1668
1669 update_release_t *update_GetRelease( update_t *p_update )
1670 {
1671     return &p_update->release;
1672 }
1673
1674 #else
1675 update_t *__update_New( vlc_object_t *p_this )
1676 {
1677     (void)p_this;
1678     return NULL;
1679 }
1680
1681 void update_Delete( update_t *p_update )
1682 {
1683     (void)p_update;
1684 }
1685
1686 void update_Check( update_t *p_update, void (*pf_callback)( void*, bool ),
1687                    void *p_data )
1688 {
1689     (void)p_update; (void)pf_callback; (void)p_data;
1690 }
1691
1692 bool update_NeedUpgrade( update_t *p_update )
1693 {
1694     (void)p_update;
1695     return false;
1696 }
1697
1698 void update_Download( update_t *p_update, const char *psz_destdir )
1699 {
1700     (void)p_update; (void)psz_destdir;
1701 }
1702
1703 update_release_t *update_GetRelease( update_t *p_update )
1704 {
1705     (void)p_update;
1706     return NULL;
1707 }
1708 #endif