]> git.sesse.net Git - vlc/blob - src/misc/update.c
update: put pgp key in its own header (and update the key to 2008), put a FIXME for...
[vlc] / src / misc / update.c
1 /*****************************************************************************
2  * update.c: VLC update checking and downloading
3  *****************************************************************************
4  * Copyright © 2005-2007 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 and plugins update management
29  */
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #include <vlc/vlc.h>
36
37 #ifdef UPDATE_CHECK
38
39 #include <assert.h>
40
41 #include <vlc_update.h>
42 #include <vlc_pgpkey.h>
43 #include <vlc_stream.h>
44 #include <vlc_interface.h>
45
46
47 /*****************************************************************************
48  * Misc defines
49  *****************************************************************************/
50
51 /*
52  * Here is the format of these "status files" :
53  * First line is the last version: "X.Y.Ze" where:
54  *      * X is the major number
55  *      * Y is the minor number
56  *      * Z is the revision number
57  *      * e is an OPTIONAL extra letter
58  *      * AKA "0.8.6d" or "0.9.0"
59  * Second line is an url to the last binary
60  * Third line is a description of the update (it MAY be extended to several lines, but for now it is only one line)
61  */
62
63 #if defined( UNDER_CE )
64 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-ce"
65 #elif defined( WIN32 )
66 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-win-x86"
67 #elif defined( __APPLE__ )
68 #   if defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc64__ )
69 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-mac-ppc"
70 #   else
71 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-mac-x86"
72 #   endif
73 #elif defined( SYS_BEOS )
74 #       define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status-beos-x86"
75 #else
76 #   define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status"
77 #endif
78
79
80 /*****************************************************************************
81  * Local Prototypes
82  *****************************************************************************/
83 static void EmptyRelease( update_t *p_update );
84 static vlc_bool_t GetUpdateFile( update_t *p_update );
85 static int CompareReleases( const struct update_release_t *p1,
86                             const struct update_release_t *p2 );
87 static char * size_str( long int l_size );
88
89
90 /*****************************************************************************
91  * OpenPGP functions
92  *****************************************************************************/
93
94 #define packet_type( c ) ( ( c & 0x3c ) >> 2 )      /* 0x3C = 00111100 */
95 #define packet_header_len( c ) ( ( c & 0x03 ) + 1 ) /* number of bytes in a packet header */
96
97 static inline int scalar_number( uint8_t *p, int header_len )
98 {
99     if( header_len == 1 )
100         return( p[0] );
101     else if( header_len == 2 )
102         return( (p[0] << 8) + p[1] );
103     else if( header_len == 4 )
104         return( (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3] );
105     else
106         abort();
107 }
108
109 /* number of data bytes in a MPI */
110 #define mpi_len( mpi ) ( ( scalar_number( mpi, 2 ) + 7 ) / 8 )
111
112 /* 
113  * fill a public_key_packet_t structure from public key packet data
114  * verify that it is a version 4 public key packet, using DSA
115  */
116 static int parse_public_key_packet( public_key_packet_t *p_key, uint8_t *p_buf,
117                                     size_t i_packet_len )
118 {
119     if( i_packet_len != 418 )
120         return VLC_EGENERIC;
121
122     p_key->version   = *p_buf++;
123     if( p_key->version != 4 )
124         return VLC_EGENERIC;
125
126     /* warn when timestamp is > date ? */
127     memcpy( p_key->timestamp, p_buf, 4 ); p_buf += 4;
128
129     p_key->algo      = *p_buf++;
130     if( p_key->algo != PUBLIC_KEY_ALGO_DSA )
131         return VLC_EGENERIC;
132
133     memcpy( p_key->p, p_buf, 2+128 ); p_buf += 2+128;
134     if( mpi_len( p_key->p ) != 128 )
135         return VLC_EGENERIC;
136
137     memcpy( p_key->q, p_buf, 2+20 );  p_buf += 2+20;
138     if( mpi_len( p_key->q ) != 20 )
139         return VLC_EGENERIC;
140
141     memcpy( p_key->g, p_buf, 2+128 ); p_buf += 2+128;
142     if( mpi_len( p_key->g ) != 128 )
143         return VLC_EGENERIC;
144
145     memcpy( p_key->y, p_buf, 2+128 ); p_buf += 2+128;
146     if( mpi_len( p_key->y ) != 128 )
147         return VLC_EGENERIC;
148
149     return VLC_SUCCESS;
150 }
151
152 /*
153  * fill a signature_packet_v4_t from signature packet data
154  * verify that it was used with a DSA public key, using SHA-1 digest
155  */
156 static int parse_signature_v4_packet( signature_packet_v4_t *p_sig,
157                                       uint8_t *p_buf, size_t i_sig_len )
158 {
159     if( i_sig_len < 54 )
160         return VLC_EGENERIC;
161
162     p_sig->version = *p_buf++;
163     if( p_sig->version != 4 )
164         return VLC_EGENERIC;
165
166     p_sig->type = *p_buf++;
167     if( p_sig->type < GENERIC_KEY_SIGNATURE ||
168         p_sig->type > POSITIVE_KEY_SIGNATURE )
169         return VLC_EGENERIC;
170
171     p_sig->public_key_algo = *p_buf++;
172     if( p_sig->public_key_algo != PUBLIC_KEY_ALGO_DSA )
173         return VLC_EGENERIC;
174
175     p_sig->digest_algo = *p_buf++;
176     if( p_sig->digest_algo != DIGEST_ALGO_SHA1 )
177         return VLC_EGENERIC;
178
179     memcpy( p_sig->hashed_data_len, p_buf, 2 ); p_buf += 2;
180
181     size_t i_pos = 6;
182     size_t i_hashed_data_len = scalar_number( p_sig->hashed_data_len, 2 );
183     i_pos += i_hashed_data_len;
184     if( i_pos > i_sig_len - 48 ) /* r & s are 44 bytes in total, 
185                               * + the unhashed data length (2 bytes)
186                               * + the hash verification (2 bytes) */
187         return VLC_EGENERIC;
188
189     p_sig->hashed_data = (uint8_t*) malloc( i_hashed_data_len );
190     if( !p_sig->hashed_data )
191         return VLC_ENOMEM;
192     memcpy( p_sig->hashed_data, p_buf, i_hashed_data_len );
193     p_buf += i_hashed_data_len;
194
195     memcpy( p_sig->unhashed_data_len, p_buf, 2 ); p_buf += 2;
196
197     size_t i_unhashed_data_len = scalar_number( p_sig->unhashed_data_len, 2 );
198     i_pos += 2 + i_unhashed_data_len;
199     if( i_pos != i_sig_len - 46 )
200     {
201         free( p_sig->hashed_data );
202         return VLC_EGENERIC;
203     }
204
205     p_sig->unhashed_data = (uint8_t*) malloc( i_unhashed_data_len );
206     if( !p_sig->unhashed_data )
207     {
208         free( p_sig->hashed_data );
209         return VLC_ENOMEM;
210     }
211     memcpy( p_sig->unhashed_data, p_buf, i_unhashed_data_len );
212     p_buf += i_unhashed_data_len;
213
214     memcpy( p_sig->hash_verification, p_buf, 2 ); p_buf += 2;
215
216     memcpy( p_sig->r, p_buf, 22 ); p_buf += 22;
217     if( mpi_len( p_sig->r ) != 20 )
218     {
219         free( p_sig->hashed_data );
220         free( p_sig->unhashed_data );
221         return VLC_EGENERIC;
222     }
223
224     memcpy( p_sig->s, p_buf, 22 );
225     if( mpi_len( p_sig->s ) != 20 )
226     {
227         free( p_sig->hashed_data );
228         free( p_sig->unhashed_data );
229         return VLC_EGENERIC;
230     }
231
232     return VLC_SUCCESS;
233 }
234
235 /*
236  * crc_octets() was lamely copied from rfc 2440
237  * Copyright (C) The Internet Society (1998).  All Rights Reserved.
238  */
239 #define CRC24_INIT 0xB704CEL
240 #define CRC24_POLY 0x1864CFBL
241
242 static long crc_octets( uint8_t *octets, size_t len )
243 {
244     long crc = CRC24_INIT;
245     int i;
246     while (len--)
247     {
248         crc ^= (*octets++) << 16;
249         for (i = 0; i < 8; i++)
250         {
251             crc <<= 1;
252             if (crc & 0x1000000)
253                 crc ^= CRC24_POLY;
254         }
255     }
256     return crc & 0xFFFFFFL;
257 }
258
259 /*
260  * Transform an armored document in binary format
261  * Used on public keys and signatures
262  */
263 static int pgp_unarmor( char *p_ibuf, size_t i_ibuf_len,
264                         uint8_t *p_obuf, size_t i_obuf_len )
265 {
266     char *p_ipos = p_ibuf;
267     uint8_t *p_opos = p_obuf;
268     int i_end = 0;
269     int i_header_skipped = 0;
270
271     while( !i_end && p_ipos < p_ibuf + i_ibuf_len && *p_ipos != '=' )
272     {
273         if( *p_ipos == '\r' || *p_ipos == '\n' )
274         {
275             p_ipos++;
276             continue;
277         }
278
279         size_t i_line_len = strcspn( p_ipos, "\r\n" );
280         if( i_line_len == 0 )
281             continue;
282
283         if( !i_header_skipped )
284         {
285             if( !strncmp( p_ipos, "-----BEGIN PGP", 14 ) )
286                 i_header_skipped = 1;
287
288             p_ipos += i_line_len + 1;
289             continue;
290         }
291         
292         if( !strncmp( p_ipos, "Version:", 8 ) )
293         {
294             p_ipos += i_line_len + 1;
295             continue;
296         }
297
298         if( p_ipos[i_line_len - 1] == '=' )
299         {
300             i_end = 1;
301             p_ipos[i_line_len - 1] = '\0';
302         }
303         else
304             p_ipos[i_line_len] = '\0';
305
306         p_opos += vlc_b64_decode_binary_to_buffer(  p_opos,
307                         p_obuf - p_opos + i_obuf_len, p_ipos );
308         p_ipos += i_line_len + 1;
309     }
310
311     /* XXX: the CRC is OPTIONAL, really require it ? */
312     if( p_ipos + 5 > p_ibuf + i_ibuf_len || *p_ipos++ != '=' )
313         return 0;
314
315     uint8_t p_crc[3];
316     if( vlc_b64_decode_binary_to_buffer( p_crc, 3, p_ipos ) != 3 )
317         return 0;
318
319     long l_crc = crc_octets( p_obuf, p_opos - p_obuf );
320     long l_crc2 = ( 0 << 24 ) + ( p_crc[0] << 16 ) + ( p_crc[1] << 8 ) + p_crc[2];
321
322     return l_crc2 == l_crc ? p_opos - p_obuf : 0;
323 }
324
325 /*
326  * Download the signature associated to a document or a binary file.
327  * We're given the file's url, we just append ".asc" to it and download 
328  */
329 static int download_signature(  vlc_object_t *p_this,
330                                 signature_packet_v3_t *p_sig,
331                                 const char *psz_url )
332 {
333     char *psz_sig = (char*) malloc( strlen( psz_url ) + 4 + 1 ); /* ".asc" + \0 */
334     if( !psz_sig )
335         return VLC_ENOMEM;
336
337     strcpy( psz_sig, psz_url );
338     strcat( psz_sig, ".asc" );
339
340     stream_t *p_stream = stream_UrlNew( p_this, psz_sig );
341     free( psz_sig );
342
343     if( !p_stream )
344         return VLC_ENOMEM;
345
346     int64_t i_size = stream_Size( p_stream );
347     /* FIXME: a signature can be less than 65 bytes, if r & s numbers
348      * do not have 160 significant bits.
349      */
350     if( i_size < 65 )
351     {
352         stream_Delete( p_stream );
353         msg_Dbg( p_this, "Signature too small" );
354         return VLC_EGENERIC;
355     }
356     else if( i_size == 65 ) /* binary format signature */
357     {
358         msg_Dbg( p_this, "Downloading unarmored signature" );
359         int i_read = stream_Read( p_stream, p_sig, (int)i_size );
360         stream_Delete( p_stream );
361         if( i_read != i_size )
362         {
363             msg_Dbg( p_this, "Couldn't read full signature" );
364             return VLC_EGENERIC;
365         }
366         else
367             return VLC_SUCCESS;
368     }
369
370     msg_Dbg( p_this, "Downloading armored signature" );
371     char *p_buf = (char*)malloc( i_size );
372     if( !p_buf )
373     {
374         stream_Delete( p_stream );
375         return VLC_ENOMEM;
376     }
377     
378     int i_read = stream_Read( p_stream, p_buf, (int)i_size );
379
380     stream_Delete( p_stream );
381
382     if( i_read != i_size )
383     {
384         msg_Dbg( p_this, "Couldn't read full signature" );
385         free( p_buf );
386         return VLC_EGENERIC;
387     }
388     
389     int i_bytes = pgp_unarmor( p_buf, i_size, (uint8_t*)p_sig, 65 );
390     free( p_buf );
391
392     if( i_bytes != 65 )
393     {
394         msg_Dbg( p_this, "Unarmoring failed: signature is %d bytes", i_bytes );
395         return VLC_EGENERIC;
396     }
397     else
398         return VLC_SUCCESS;
399 }
400
401 /*
402  * Verify an OpenPGP signature made on some SHA-1 hash, with some DSA public key
403  */
404 static int verify_signature( vlc_object_t *p_this, uint8_t *p_r, uint8_t *p_s,
405         public_key_packet_t *p_key, uint8_t *p_hash )
406 {
407     /* the data to be verified (a SHA-1 hash) */
408     const char *hash_sexp_s = "(data(flags raw)(value %m))";
409     /* the public key */
410     const char *key_sexp_s = "(public-key(dsa(p %m)(q %m)(g %m)(y %m)))";
411     /* the signature */
412     const char *sig_sexp_s = "(sig-val(dsa(r %m )(s %m )))";
413
414     size_t erroff;
415     gcry_mpi_t p, q, g, y, r, s, hash;
416     p = q = g = y = r = s = hash = NULL;
417     gcry_sexp_t key_sexp, hash_sexp, sig_sexp;
418     key_sexp = hash_sexp = sig_sexp = NULL;
419
420     if( gcry_mpi_scan( &p, GCRYMPI_FMT_USG, p_key->p + 2, 128, NULL ) ||
421         gcry_mpi_scan( &q, GCRYMPI_FMT_USG, p_key->q + 2, 20, NULL ) ||
422         gcry_mpi_scan( &g, GCRYMPI_FMT_USG, p_key->g + 2, 128, NULL ) ||
423         gcry_mpi_scan( &y, GCRYMPI_FMT_USG, p_key->y + 2, 128, NULL ) ||
424         gcry_sexp_build( &key_sexp, &erroff, key_sexp_s, p, q, g, y ) )
425         goto problem;
426
427     if( gcry_mpi_scan( &r, GCRYMPI_FMT_USG, p_r + 2, 20, NULL ) ||
428         gcry_mpi_scan( &s, GCRYMPI_FMT_USG, p_s + 2, 20, NULL ) ||
429         gcry_sexp_build( &sig_sexp, &erroff, sig_sexp_s, r, s ) )
430         goto problem;
431
432     if( gcry_mpi_scan( &hash, GCRYMPI_FMT_USG, p_hash, 20, NULL ) ||
433         gcry_sexp_build( &hash_sexp, &erroff, hash_sexp_s, hash ) )
434         goto problem;
435
436     if( gcry_pk_verify( sig_sexp, hash_sexp, key_sexp ) )
437         goto problem;
438
439     return VLC_SUCCESS;
440
441 problem:
442     if( p ) gcry_mpi_release( p );
443     if( q ) gcry_mpi_release( q );
444     if( g ) gcry_mpi_release( g );
445     if( y ) gcry_mpi_release( y );
446     if( r ) gcry_mpi_release( r );
447     if( s ) gcry_mpi_release( s );
448     if( hash ) gcry_mpi_release( hash );
449     if( key_sexp ) gcry_sexp_release( key_sexp );
450     if( sig_sexp ) gcry_sexp_release( sig_sexp );
451     if( hash_sexp ) gcry_sexp_release( hash_sexp );
452     return VLC_EGENERIC;
453 }
454
455 /*
456  * Return the long id (8 bytes) of the public key used to generate a signature
457  */
458 static uint8_t *get_issuer_from_signature_v4( signature_packet_v4_t *p_sig )
459 {
460     uint8_t *p = p_sig->unhashed_data;
461     uint8_t *max_pos = p + scalar_number( p_sig->unhashed_data_len, 2 );
462
463     while( p < max_pos )
464     {
465         int i_subpacket_len = *p < 192 ? *p++ :
466                 *p < 255 ? ((*p++ - 192) << 8) + *p++ + 192 :
467                 ((*++p) << 24) + (*++p << 16) + (*++p << 8) + *++p;
468
469         if( p >= max_pos - 1 )
470             return NULL;
471
472         if( *p == ISSUER_SUBPACKET )
473             return p+1;
474         else
475             p += i_subpacket_len;
476     }
477     return NULL;
478 }
479
480 /*
481  * fill a public_key_t with public key data, including:
482  *   * public key packet
483  *   * signature packet issued by key which long id is p_sig_issuer
484  *   * user id packet
485  */
486 static int parse_public_key( const uint8_t *p_key_data, size_t i_key_len, public_key_t *p_key, const uint8_t *p_sig_issuer )
487 {
488     uint8_t *pos = (uint8_t*) p_key_data;
489     uint8_t *max_pos = pos + i_key_len;
490
491     int i_status = 0;
492 #define PUBLIC_KEY_FOUND    0x01
493 #define USER_ID_FOUND       0x02
494 #define SIGNATURE_FOUND     0X04
495
496     uint8_t *p_key_unarmored = NULL;
497
498     signature_packet_v4_t sig;
499
500     p_key->psz_username = NULL;
501     p_key->sig.hashed_data = p_key->sig.unhashed_data = NULL;
502
503     if( !( *pos & 0x80 ) )
504     {   /* first byte is ASCII, unarmoring */
505         p_key_unarmored = (uint8_t*)malloc( i_key_len );
506         if( !p_key_unarmored )
507             return VLC_ENOMEM;
508         int i_len = pgp_unarmor( (char*)p_key_data, i_key_len,
509                                  p_key_unarmored, i_key_len );
510
511         if( i_len == 0 )
512             goto error;
513
514         pos = p_key_unarmored;
515         max_pos = pos + i_len;
516     }
517
518     while( pos < max_pos )
519     {
520         if( !(*pos & 0x80) || *pos & 0x40 )
521             goto error;
522
523         int i_type = packet_type( *pos );
524
525         int i_header_len = packet_header_len( *pos++ );
526         if( pos + i_header_len > max_pos )
527             goto error;
528
529         int i_packet_len = scalar_number( pos, i_header_len );
530         pos += i_header_len;
531
532         if( pos + i_packet_len > max_pos )
533             goto error;
534
535         switch( i_type )
536         {
537             uint8_t *p_issuer;
538
539             case PUBLIC_KEY_PACKET:
540                 i_status |= PUBLIC_KEY_FOUND;
541                 if( parse_public_key_packet( &p_key->key, pos, i_packet_len ) != VLC_SUCCESS )
542                     goto error;
543                 break;
544
545             case SIGNATURE_PACKET:
546                 if( !p_sig_issuer || i_status & SIGNATURE_FOUND ||
547                     parse_signature_v4_packet( &sig, pos, i_packet_len ) != VLC_SUCCESS )
548                     break;
549                 p_issuer = get_issuer_from_signature_v4( &sig );
550                 if( memcmp( p_issuer, p_sig_issuer, 8 ) == 0 )
551                 {
552                     memcpy( &p_key->sig, &sig, sizeof( signature_packet_v4_t ) );
553                     i_status |= SIGNATURE_FOUND;
554                 }
555                 else
556                 {
557                     free( sig.hashed_data );
558                     free( sig.unhashed_data );
559                 }
560                 break;
561
562             case USER_ID_PACKET:
563                 if( p_key->psz_username ) /* save only the first User ID */
564                     break;
565                 i_status |= USER_ID_FOUND;
566                 p_key->psz_username = (uint8_t*)malloc( i_packet_len + 1);
567                 if( !p_key->psz_username )
568                     goto error;
569
570                 memcpy( p_key->psz_username, pos, i_packet_len );
571                 p_key->psz_username[i_packet_len] = '\0';
572                 break;
573             
574             default:
575                 break;
576         }
577         pos += i_packet_len;
578     }
579     free( p_key_unarmored );
580
581     if( !( i_status & ( PUBLIC_KEY_FOUND + USER_ID_FOUND ) ) )
582         return VLC_EGENERIC;
583
584     if( p_sig_issuer && !( i_status & SIGNATURE_FOUND ) )
585         return VLC_EGENERIC;
586
587     return VLC_SUCCESS;
588
589 error:
590     free( p_key->sig.hashed_data );
591     free( p_key->sig.unhashed_data );
592     free( p_key->psz_username );
593     free( p_key_unarmored );
594     return VLC_EGENERIC;
595 }
596
597 /*
598  * return a sha1 hash of a file
599  */
600 static uint8_t *hash_sha1_from_file( const char *psz_file,
601                             signature_packet_v3_t *p_sig )
602 {
603     FILE *f = utf8_fopen( psz_file, "r" );
604     if( !f )
605         return NULL;
606
607     uint8_t buffer[4096];
608
609     gcry_md_hd_t hd;
610     if( gcry_md_open( &hd, GCRY_MD_SHA1, 0 ) )
611     {
612         fclose( f );
613         return NULL;
614     } 
615
616     size_t i_read;
617     while( ( i_read = fread( buffer, 1, sizeof(buffer), f ) ) > 0 )
618         gcry_md_write( hd, buffer, i_read );
619
620     gcry_md_putc( hd, p_sig->type );
621     gcry_md_write( hd, &p_sig->timestamp, 4 );
622
623     fclose( f );
624     gcry_md_final( hd );
625
626     return( (uint8_t*) gcry_md_read( hd, GCRY_MD_SHA1) );
627 }
628
629 /*
630  * download a public key (the last one) from videolan server, and parse it
631  */
632 static public_key_t *download_key( vlc_object_t *p_this, const uint8_t *p_longid, const uint8_t *p_signature_issuer )
633 {
634     char *psz_url;
635     if( asprintf( &psz_url, "http://download.videolan.org/pub/keys/%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X.asc",
636                     p_longid[0], p_longid[1], p_longid[2], p_longid[3],
637                     p_longid[4], p_longid[5], p_longid[6], p_longid[7] ) == -1 )
638         return NULL;
639
640     stream_t *p_stream = stream_UrlNew( p_this, psz_url );
641     free( psz_url );
642     if( !p_stream )
643         return NULL;
644
645     int64_t i_size = stream_Size( p_stream );
646     if( i_size < 0 )
647     {
648         stream_Delete( p_stream );
649         return NULL;
650     }
651
652     uint8_t *p_buf = (uint8_t*)malloc( i_size );
653     if( !p_buf )
654     {
655         stream_Delete( p_stream );
656         return NULL;
657     }
658
659     int i_read = stream_Read( p_stream, p_buf, (int)i_size );
660     stream_Delete( p_stream );
661
662     if( i_read != (int)i_size )
663     {
664         msg_Dbg( p_this, "Couldn't read full GPG key" );
665         free( p_buf );
666         return NULL;
667     }
668
669     public_key_t *p_pkey = (public_key_t*) malloc( sizeof( public_key_t ) );
670     if( !p_pkey )
671     {
672         free( p_buf );
673         return NULL;
674     }
675
676     int i_error = parse_public_key( p_buf, i_read, p_pkey, p_signature_issuer );
677     free( p_buf );
678
679     if( i_error != VLC_SUCCESS )
680     {
681         msg_Dbg( p_this, "Couldn't parse GPG key" );
682         free( p_pkey );
683         return NULL;
684     }
685
686     return p_pkey;
687 }
688
689 /*
690  * Generate a SHA-1 hash on a public key, to verify a signature made on that hash
691  * Note that we need the signature to compute the hash
692  */
693 static uint8_t *key_sign_hash( public_key_t *p_pkey )
694 {
695     gcry_error_t error = 0;
696     gcry_md_hd_t hd;
697
698     error = gcry_md_open( &hd, GCRY_MD_SHA1, 0 );
699     if( error )
700         return NULL;
701
702     gcry_md_putc( hd, 0x99 );
703
704     gcry_md_putc( hd, (418 >> 8) & 0xff );
705     gcry_md_putc( hd, 418 & 0xff );
706
707     gcry_md_write( hd, (uint8_t*)&p_pkey->key, 418 );
708
709     gcry_md_putc( hd, 0xb4 );
710
711     int i_len = strlen((char*)p_pkey->psz_username);
712
713     gcry_md_putc( hd, (i_len << 24) & 0xff );
714     gcry_md_putc( hd, (i_len << 16) & 0xff );
715     gcry_md_putc( hd, (i_len << 8) & 0xff );
716     gcry_md_putc( hd, (i_len) & 0xff );
717
718     gcry_md_write( hd, p_pkey->psz_username, i_len );
719
720     size_t i_hashed_data_len = scalar_number( p_pkey->sig.hashed_data_len, 2 );
721
722     gcry_md_putc( hd, p_pkey->sig.version );
723     gcry_md_putc( hd, p_pkey->sig.type );
724     gcry_md_putc( hd, p_pkey->sig.public_key_algo );
725     gcry_md_putc( hd, p_pkey->sig.digest_algo );
726     gcry_md_write( hd, p_pkey->sig.hashed_data_len, 2 );
727     gcry_md_write( hd, p_pkey->sig.hashed_data, i_hashed_data_len );
728
729     gcry_md_putc( hd, 0x04 );
730     gcry_md_putc( hd, 0xff );
731
732     i_hashed_data_len += 6; /* hashed data + 6 bytes header */
733
734     gcry_md_putc( hd, (i_hashed_data_len << 24) & 0xff);
735     gcry_md_putc( hd, (i_hashed_data_len << 16) &0xff );
736     gcry_md_putc( hd, (i_hashed_data_len << 8) & 0xff );
737     gcry_md_putc( hd, (i_hashed_data_len) & 0xff );
738
739     gcry_md_final( hd );
740
741     uint8_t *p_hash = gcry_md_read( hd, GCRY_MD_SHA1);
742
743     if( p_hash[0] != p_pkey->sig.hash_verification[0] ||
744         p_hash[1] != p_pkey->sig.hash_verification[1] )
745     {
746         free( p_hash );
747         return NULL;
748     }
749
750     return p_hash;
751 }
752
753
754 /*****************************************************************************
755  * Update_t functions
756  *****************************************************************************/
757
758 /**
759  * Create a new update VLC struct
760  *
761  * \param p_this the calling vlc_object
762  * \return pointer to new update_t or NULL
763  */
764 update_t *__update_New( vlc_object_t *p_this )
765 {
766     update_t *p_update;
767     assert( p_this );
768
769     p_update = (update_t *)malloc( sizeof( update_t ) );
770     if( !p_update ) return NULL;
771
772     vlc_mutex_init( p_this, &p_update->lock );
773
774     p_update->p_libvlc = p_this->p_libvlc;
775
776     p_update->release.psz_url = NULL;
777     p_update->release.psz_desc = NULL;
778     
779     p_update->p_pkey = NULL;
780
781     return p_update;
782 }
783
784 /**
785  * Delete an update_t struct
786  *
787  * \param p_update update_t* pointer
788  * \return nothing
789  */
790 void update_Delete( update_t *p_update )
791 {
792     assert( p_update );
793
794     vlc_mutex_destroy( &p_update->lock );
795
796     free( p_update->release.psz_url );
797     free( p_update->release.psz_desc );
798     free( p_update->p_pkey );
799
800     free( p_update );
801 }
802
803 /**
804  * Empty the release struct
805  *
806  * \param p_update update_t* pointer
807  * \return nothing
808  */
809 static void EmptyRelease( update_t *p_update )
810 {
811     p_update->release.i_major = 0;
812     p_update->release.i_minor = 0;
813     p_update->release.i_revision = 0;
814
815     FREENULL( p_update->release.psz_url );
816     FREENULL( p_update->release.psz_desc );
817 }
818
819 /**
820  * Get the update file and parse it
821  * *p_update has to be locked when calling this function
822  *
823  * \param p_update pointer to update struct
824  * \return VLC_TRUE if the update is valid and authenticated
825  */
826 static vlc_bool_t GetUpdateFile( update_t *p_update )
827 {
828     stream_t *p_stream = NULL;
829     int i_major = 0;
830     int i_minor = 0;
831     int i_revision = 0;
832     unsigned char extra;
833     char *psz_line = NULL;
834     char *psz_version_line = NULL;
835
836     p_stream = stream_UrlNew( p_update->p_libvlc, UPDATE_VLC_STATUS_URL );
837     if( !p_stream )
838     {
839         msg_Err( p_update->p_libvlc, "Failed to open %s for reading",
840                  UPDATE_VLC_STATUS_URL );
841         goto error;
842     }
843
844     /* Try to read three lines */
845     if( !( psz_line = stream_ReadLine( p_stream ) ) )
846     {
847         msg_Err( p_update->p_libvlc, "Update file %s is corrupted : missing version",
848                  UPDATE_VLC_STATUS_URL );
849         goto error;
850     }
851
852     psz_version_line = psz_line;
853     /* first line : version number */
854     p_update->release.extra = 0;
855     switch( sscanf( psz_line, "%i.%i.%i%c", &i_major, &i_minor, &i_revision, &extra ) )
856     {
857         case 4:
858             p_update->release.extra = extra;
859         case 3:
860             p_update->release.i_major = i_major;
861             p_update->release.i_minor = i_minor;
862             p_update->release.i_revision = i_revision;
863             break;
864         default:
865             msg_Err( p_update->p_libvlc, "Update version false formated" );
866             goto error;
867     }
868
869     /* Second line : URL */
870     if( !( psz_line = stream_ReadLine( p_stream ) ) )
871     {
872         msg_Err( p_update->p_libvlc, "Update file %s is corrupted : URL missing",
873                  UPDATE_VLC_STATUS_URL );
874         goto error;
875     }
876     p_update->release.psz_url = psz_line;
877
878
879     /* Third line : description */
880     if( !( psz_line = stream_ReadLine( p_stream ) ) )
881     {
882         msg_Err( p_update->p_libvlc, "Update file %s is corrupted : description missing",
883                  UPDATE_VLC_STATUS_URL );
884         goto error;
885     }
886     p_update->release.psz_desc = psz_line;
887
888     stream_Delete( p_stream );
889     p_stream = NULL;
890
891     /* Now that we know the status is valid, we must download its signature 
892      * to authenticate it */
893     signature_packet_v3_t sign;
894     if( download_signature( VLC_OBJECT( p_update->p_libvlc ), &sign, 
895             UPDATE_VLC_STATUS_URL ) != VLC_SUCCESS )
896     {
897         msg_Err( p_update->p_libvlc, "Couldn't download signature of status file" );
898         goto error;
899     }
900
901     if( sign.type != BINARY_SIGNATURE && sign.type != TEXT_SIGNATURE )
902     {
903         msg_Err( p_update->p_libvlc, "Invalid signature type" );
904         goto error;
905     }
906
907     p_update->p_pkey = (public_key_t*)malloc( sizeof( public_key_t ) );
908     if( !p_update->p_pkey )
909         goto error;
910
911     if( parse_public_key( videolan_public_key, sizeof( videolan_public_key ),
912                         p_update->p_pkey, NULL ) != VLC_SUCCESS )
913     {
914         msg_Err( p_update->p_libvlc, "Couldn't parse embedded public key, something went really wrong..." );
915         FREENULL( p_update->p_pkey );
916         goto error;
917     }
918
919     if( memcmp( sign.issuer_longid, videolan_public_key_longid , 8 ) != 0 )
920     {
921         msg_Dbg( p_update->p_libvlc, "Need to download the GPG key" );
922         public_key_t *p_new_pkey = download_key(
923                 VLC_OBJECT(p_update->p_libvlc),
924                 sign.issuer_longid, videolan_public_key_longid );
925         if( !p_new_pkey )
926         {
927             msg_Err( p_update->p_libvlc, "Couldn't download GPG key" );
928             FREENULL( p_update->p_pkey );
929             goto error;
930         }
931
932         uint8_t *p_hash = key_sign_hash( p_new_pkey );
933         if( !p_hash )
934         {
935             msg_Err( p_update->p_libvlc, "Failed to hash signature" );
936             free( p_new_pkey );
937             FREENULL( p_update->p_pkey );
938             goto error;
939         }
940
941         if( verify_signature( VLC_OBJECT(p_update->p_libvlc),
942                     p_new_pkey->sig.r, p_new_pkey->sig.s,
943                     &p_update->p_pkey->key, p_hash ) == VLC_SUCCESS )
944         {
945             free( p_hash );
946             msg_Info( p_update->p_libvlc, "Key authenticated" );
947             free( p_update->p_pkey );
948             p_update->p_pkey = p_new_pkey;
949         }
950         else
951         {
952             free( p_hash );
953             msg_Err( p_update->p_libvlc, "Key signature invalid !\n" );
954             goto error;
955         }
956     }
957
958     gcry_md_hd_t hd;
959     if( gcry_md_open( &hd, GCRY_MD_SHA1, 0 ) )
960         goto error;
961
962     gcry_md_write( hd, psz_version_line, strlen( psz_version_line ) );
963     FREENULL( psz_version_line );
964     if( sign.type == TEXT_SIGNATURE )
965         gcry_md_putc( hd, '\r' );
966     gcry_md_putc( hd, '\n' );
967     gcry_md_write( hd, p_update->release.psz_url,
968                         strlen( p_update->release.psz_url ) );
969     if( sign.type == TEXT_SIGNATURE )
970         gcry_md_putc( hd, '\r' );
971     gcry_md_putc( hd, '\n' );
972     gcry_md_write( hd, p_update->release.psz_desc,
973                         strlen( p_update->release.psz_desc ) );
974     if( sign.type == TEXT_SIGNATURE )
975         gcry_md_putc( hd, '\r' );
976     gcry_md_putc( hd, '\n' );
977
978     gcry_md_putc( hd, sign.type );
979     gcry_md_write( hd, &sign.timestamp, 4 );
980
981     gcry_md_final( hd );
982
983     uint8_t *p_hash = gcry_md_read( hd, GCRY_MD_SHA1 );
984
985     if( p_hash[0] != sign.hash_verification[0] ||
986         p_hash[1] != sign.hash_verification[1] )
987     {
988         msg_Warn( p_update->p_libvlc, "Bad SHA1 hash for status file" );
989         free( p_hash );
990         goto error;
991     }
992
993     if( verify_signature( VLC_OBJECT(p_update->p_libvlc),
994             sign.r, sign.s, &p_update->p_pkey->key, p_hash ) != VLC_SUCCESS )
995     {
996         msg_Err( p_update->p_libvlc, "BAD SIGNATURE for status file" );
997         free( p_hash );
998         goto error;
999     }
1000     else
1001     {
1002         msg_Info( p_update->p_libvlc, "Status file authenticated" );
1003         free( p_hash );
1004         return VLC_TRUE;
1005     }
1006
1007 error:
1008     if( p_stream )
1009         stream_Delete( p_stream );
1010     free( psz_version_line );
1011     return VLC_FALSE;
1012 }
1013
1014
1015 /**
1016  * Struct to launch the check in an other thread
1017  */
1018 typedef struct
1019 {
1020     VLC_COMMON_MEMBERS
1021     update_t *p_update;
1022     void (*pf_callback)( void *, vlc_bool_t );
1023     void *p_data;
1024 } update_check_thread_t;
1025
1026 void update_CheckReal( update_check_thread_t *p_uct );
1027
1028 /**
1029  * Check for updates
1030  *
1031  * \param p_update pointer to update struct
1032  * \param pf_callback pointer to a function to call when the update_check is finished
1033  * \param p_data pointer to some datas to give to the callback
1034  * \returns nothing
1035  */
1036 void update_Check( update_t *p_update, void (*pf_callback)( void*, vlc_bool_t ), void *p_data )
1037 {
1038     assert( p_update );
1039
1040     update_check_thread_t *p_uct = vlc_object_create( p_update->p_libvlc,
1041                                             sizeof( update_check_thread_t ) );
1042     p_uct->p_update = p_update;
1043     p_uct->pf_callback = pf_callback;
1044     p_uct->p_data = p_data;
1045
1046     vlc_thread_create( p_uct, "check for update", update_CheckReal,
1047                        VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
1048 }
1049
1050 void update_CheckReal( update_check_thread_t *p_uct )
1051 {
1052     vlc_bool_t b_ret;
1053     vlc_mutex_lock( &p_uct->p_update->lock );
1054
1055     EmptyRelease( p_uct->p_update );
1056     b_ret = GetUpdateFile( p_uct->p_update );
1057     vlc_mutex_unlock( &p_uct->p_update->lock );
1058
1059     if( p_uct->pf_callback )
1060         (p_uct->pf_callback)( p_uct->p_data, b_ret );
1061
1062     vlc_object_destroy( p_uct );
1063 }
1064
1065 /**
1066  * Compare two release numbers
1067  *
1068  * \param p1 first release
1069  * \param p2 second release
1070  * \return UpdateReleaseStatus(Older|Equal|Newer)
1071  */
1072 static int CompareReleases( const struct update_release_t *p1,
1073                             const struct update_release_t *p2 )
1074 {
1075     int32_t d;
1076     d = ( p1->i_major << 24 ) + ( p1->i_minor << 16 ) + ( p1->i_revision << 8 )
1077       - ( p2->i_major << 24 ) - ( p2->i_minor << 16 ) - ( p2->i_revision << 8 )
1078       + ( p1->extra ) - ( p2->extra );
1079
1080     if( d < 0 )
1081         return UpdateReleaseStatusOlder;
1082     else if( d == 0 )
1083         return UpdateReleaseStatusEqual;
1084     else
1085         return UpdateReleaseStatusNewer;
1086 }
1087
1088 /**
1089  * Compare a given release's version number to the current VLC's one
1090  *
1091  * \param p_update structure
1092  * \return UpdateReleaseStatus(Older|Equal|Newer)
1093  */
1094 int update_CompareReleaseToCurrent( update_t *p_update )
1095 {
1096     assert( p_update );
1097
1098     struct update_release_t c;
1099
1100     /* get the current version number */
1101     c.i_major = *PACKAGE_VERSION_MAJOR - '0';
1102     c.i_minor = *PACKAGE_VERSION_MINOR - '0';
1103     c.i_revision = *PACKAGE_VERSION_REVISION - '0';
1104     c.extra = *PACKAGE_VERSION_EXTRA;
1105
1106     return CompareReleases( &p_update->release, &c );
1107 }
1108
1109 /**
1110  * Convert a long int size in bytes to a string
1111  *
1112  * \param l_size the size in bytes
1113  * \return the size as a string
1114  */
1115 static char *size_str( long int l_size )
1116 {
1117     char *psz_tmp = NULL;
1118     if( l_size >> 30 )
1119         asprintf( &psz_tmp, "%.1f GB", (float)l_size/(1<<30) );
1120     else if( l_size >> 20 )
1121         asprintf( &psz_tmp, "%.1f MB", (float)l_size/(1<<20) );
1122     else if( l_size >> 10 )
1123         asprintf( &psz_tmp, "%.1f kB", (float)l_size/(1<<10) );
1124     else
1125         asprintf( &psz_tmp, "%ld B", l_size );
1126     return psz_tmp;
1127 }
1128
1129
1130 /*
1131  * Struct to launch the download in a thread
1132  */
1133 typedef struct
1134 {
1135     VLC_COMMON_MEMBERS
1136     update_t *p_update;
1137     char *psz_destdir;
1138 } update_download_thread_t;
1139
1140 void update_DownloadReal( update_download_thread_t *p_udt );
1141
1142 /**
1143  * Download the file given in the update_t
1144  *
1145  * \param p_update structure
1146  * \param dir to store the download file
1147  * \return nothing
1148  */
1149 void update_Download( update_t *p_update, char *psz_destdir )
1150 {
1151     assert( p_update );
1152
1153     update_download_thread_t *p_udt = vlc_object_create( p_update->p_libvlc,
1154                                                       sizeof( update_download_thread_t ) );
1155
1156     p_udt->p_update = p_update;
1157     p_udt->psz_destdir = psz_destdir ? strdup( psz_destdir ) : NULL;
1158
1159     vlc_thread_create( p_udt, "download update", update_DownloadReal,
1160                        VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
1161 }
1162
1163 void update_DownloadReal( update_download_thread_t *p_udt )
1164 {
1165     int i_progress = 0;
1166     long int l_size;
1167     long int l_downloaded = 0;
1168     float f_progress;
1169     char *psz_status = NULL;
1170     char *psz_downloaded = NULL;
1171     char *psz_size = NULL;
1172     char *psz_destfile = NULL;
1173     char *psz_tmpdestfile = NULL;
1174
1175     FILE *p_file = NULL;
1176     stream_t *p_stream = NULL;
1177     void* p_buffer = NULL;
1178     int i_read;
1179
1180     update_t *p_update = p_udt->p_update;
1181     char *psz_destdir = p_udt->psz_destdir;
1182
1183     /* Open the stream */
1184     p_stream = stream_UrlNew( p_udt, p_update->release.psz_url );
1185     if( !p_stream )
1186     {
1187         msg_Err( p_udt, "Failed to open %s for reading", p_update->release.psz_url );
1188         goto end;
1189     }
1190
1191     /* Get the stream size */
1192     l_size = stream_Size( p_stream );
1193
1194     /* Get the file name and open it*/
1195     psz_tmpdestfile = strrchr( p_update->release.psz_url, '/' );
1196     if( !psz_tmpdestfile )
1197     {
1198         msg_Err( p_udt, "The URL %s is false formated", p_update->release.psz_url );
1199         goto end;
1200     }
1201     psz_tmpdestfile++;
1202     if( asprintf( &psz_destfile, "%s%s", psz_destdir, psz_tmpdestfile ) == -1 )
1203         goto end;
1204
1205     p_file = utf8_fopen( psz_destfile, "w" );
1206     if( !p_file )
1207     {
1208         msg_Err( p_udt, "Failed to open %s for writing", psz_destfile );
1209         goto end;
1210     }
1211
1212     /* Create a buffer and fill it with the downloaded file */
1213     p_buffer = (void *)malloc( 1 << 10 );
1214     if( !p_buffer )
1215         goto end;
1216
1217     psz_size = size_str( l_size );
1218     if( asprintf( &psz_status, "%s\nDownloading... O.O/%s %.1f%% done",  p_update->release.psz_url, psz_size, 0.0 ) != -1 )
1219     {
1220         i_progress = intf_UserProgress( p_udt, "Downloading ...", psz_status, 0.0, 0 );
1221         free( psz_status );
1222     }
1223
1224     while( ( i_read = stream_Read( p_stream, p_buffer, 1 << 10 ) ) &&
1225                                    !intf_ProgressIsCancelled( p_udt, i_progress ) )
1226     {
1227         fwrite( p_buffer, i_read, 1, p_file );
1228
1229         l_downloaded += i_read;
1230         psz_downloaded = size_str( l_downloaded );
1231         f_progress = 100.0*(float)l_downloaded/(float)l_size;
1232
1233         if( asprintf( &psz_status, "%s\nDonwloading... %s/%s %.1f%% done", p_update->release.psz_url,
1234                       psz_downloaded, psz_size, f_progress ) != -1 )
1235         {
1236             intf_ProgressUpdate( p_udt, i_progress, psz_status, f_progress, 0 );
1237             free( psz_status );
1238         }
1239         free( psz_downloaded );
1240     }
1241
1242     /* Finish the progress bar or delete the file if the user had canceled */
1243     fclose( p_file );
1244     p_file = NULL;
1245
1246     if( !intf_ProgressIsCancelled( p_udt, i_progress ) )
1247     {
1248         if( asprintf( &psz_status, "%s\nDone %s (100.0%%)", p_update->release.psz_url, psz_size ) != -1 )
1249         {
1250             intf_ProgressUpdate( p_udt, i_progress, psz_status, 100.0, 0 );
1251             free( psz_status );
1252         }
1253     }
1254     else
1255     {
1256         utf8_unlink( psz_destfile );
1257         goto end;
1258     }
1259
1260     signature_packet_v3_t sign;
1261     if( download_signature( VLC_OBJECT( p_udt ), &sign,
1262             p_update->release.psz_url ) != VLC_SUCCESS )
1263     {
1264         msg_Err( p_udt, "Couldn't download signature of downloaded file" );
1265         goto end;
1266     }
1267
1268     if( sign.type != BINARY_SIGNATURE )
1269     {
1270         msg_Err( p_udt, "Invalid signature type" );
1271         goto end;
1272     }
1273
1274     uint8_t *p_hash = hash_sha1_from_file( psz_destfile, &sign );
1275     if( !p_hash )
1276     {
1277         msg_Err( p_udt, "Unable to hash %s", psz_destfile );
1278         utf8_unlink( psz_destfile );
1279         goto end;
1280     }
1281
1282     if( p_hash[0] != sign.hash_verification[0] ||
1283         p_hash[1] != sign.hash_verification[1] )
1284     {
1285         msg_Err( p_udt, "Bad SHA1 hash for %s", psz_destfile );
1286         utf8_unlink( psz_destfile );
1287         goto end;
1288     }
1289
1290     if( verify_signature( VLC_OBJECT(p_udt), sign.r, sign.s,
1291                 &p_update->p_pkey->key, p_hash ) != VLC_SUCCESS )
1292     {
1293         msg_Err( p_udt, "BAD SIGNATURE for %s", psz_destfile );
1294         free( p_hash );
1295         utf8_unlink( psz_destfile );
1296         goto end;
1297     }
1298
1299     msg_Info( p_udt, "%s authenticated", psz_destfile );
1300     free( p_hash );
1301
1302 end:
1303     if( p_stream )
1304         stream_Delete( p_stream );
1305     if( p_file )
1306         fclose( p_file );
1307     free( psz_destdir );
1308     free( psz_destfile );
1309     free( p_buffer );
1310     free( psz_size );
1311
1312     vlc_object_destroy( p_udt );
1313 }
1314
1315 #endif