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