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