source: trunk/libtransmission/metainfo.c @ 6602

Last change on this file since 6602 was 6602, checked in by charles, 13 years ago

get rid of strlcat_utf8()

  • Property svn:keywords set to Date Rev Author Id
File size: 14.8 KB
Line 
1/******************************************************************************
2 * $Id: metainfo.c 6602 2008-08-20 19:21:57Z charles $
3 *
4 * Copyright (c) 2005-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <assert.h>
26#include <ctype.h> /* isspace */
27#include <errno.h>
28#include <stdio.h>
29#include <stdlib.h>
30
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <unistd.h> /* unlink, stat */
34
35#include <event.h> /* struct evbuffer */
36
37#include "transmission.h"
38#include "bencode.h"
39#include "crypto.h" /* tr_sha1 */
40#include "metainfo.h"
41#include "platform.h"
42#include "utils.h"
43
44/***********************************************************************
45 * Local prototypes
46 **********************************************************************/
47static int parseFiles( tr_info * inf, tr_benc * files, tr_benc * length );
48
49/***
50****
51***/
52
53static char*
54getTorrentFilename( const tr_handle  * handle,
55                    const tr_info    * inf )
56{
57    return tr_strdup_printf( "%s%c%s.%16.16s.torrent",
58                             tr_getTorrentDir( handle ),
59                             TR_PATH_DELIMITER,
60                             inf->name,
61                             inf->hashString );
62}
63
64static char*
65getTorrentOldFilename( const tr_handle * handle,
66                       const tr_info   * inf )
67{
68    char * ret;
69    struct evbuffer * buf = evbuffer_new( );
70    evbuffer_add_printf( buf, "%s%c%s", 
71                         tr_getTorrentDir( handle ),
72                         TR_PATH_DELIMITER,
73                         inf->hashString );
74    if( handle->tag )
75        evbuffer_add_printf( buf, "-%s", handle->tag );
76    ret = tr_strndup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
77    evbuffer_free( buf );
78    return ret;
79}
80
81void
82tr_metainfoMigrate( tr_handle * handle,
83                    tr_info   * inf )
84{
85    struct stat new_sb;
86    char * new_name = getTorrentFilename( handle, inf );
87
88    if( stat( new_name, &new_sb ) || ( ( new_sb.st_mode & S_IFMT ) != S_IFREG ) )
89    {
90        char * old_name = getTorrentOldFilename( handle, inf );
91        size_t contentLen;
92        uint8_t * content;
93
94        tr_mkdirp( tr_getTorrentDir( handle ), 0777 );
95        if(( content = tr_loadFile( old_name, &contentLen )))
96        {
97            FILE * out;
98            errno = 0;
99            out = fopen( new_name, "wb+" );
100            if( !out )
101            {
102                tr_nerr( inf->name, _( "Couldn't create \"%1$s\": %2$s" ), new_name, tr_strerror( errno ) );
103            }
104            else
105            {
106                if( fwrite( content, sizeof( uint8_t ), contentLen, out ) == contentLen )
107                {
108                    tr_free( inf->torrent );
109                    inf->torrent = tr_strdup( new_name );
110                    tr_sessionSetTorrentFile( handle, inf->hashString, new_name );
111                    unlink( old_name );
112                }
113                fclose( out );
114            }
115        }
116
117        tr_free( content );
118        tr_free( old_name );
119    }
120
121    tr_free( new_name );
122}
123
124static char *
125announceToScrape( const char * announce )
126{
127    char * scrape = NULL;
128    const char * s;
129
130    /* To derive the scrape URL use the following steps:
131     * Begin with the announce URL. Find the last '/' in it.
132     * If the text immediately following that '/' isn't 'announce'
133     * it will be taken as a sign that that tracker doesn't support
134     * the scrape convention. If it does, substitute 'scrape' for
135     * 'announce' to find the scrape page.  */
136    if((( s = strrchr( announce, '/' ))) && !strncmp( ++s, "announce", 8 ))
137    {
138        struct evbuffer * buf = evbuffer_new( );
139        evbuffer_add( buf, announce, s-announce );
140        evbuffer_add( buf, "scrape", 6 );
141        evbuffer_add_printf( buf, "%s", s+8 );
142        scrape = tr_strdup( ( char * ) EVBUFFER_DATA( buf ) );
143        evbuffer_free( buf );
144    }
145
146    return scrape;
147}
148
149static void
150geturllist( tr_info * inf, tr_benc * meta )
151{
152    benc_val_t * urls;
153
154    if( tr_bencDictFindList( meta, "url-list", &urls ) )
155    {
156        int i;
157        const char * url;
158        const int n = tr_bencListSize( urls );
159
160        inf->webseedCount = 0;
161        inf->webseeds = tr_new0( char*, n );
162
163        for( i=0; i<n; ++i )
164            if( tr_bencGetStr( tr_bencListChild( urls, i ), &url ) )
165                inf->webseeds[inf->webseedCount++] = tr_strdup( url );
166    }
167}
168
169static int
170getannounce( tr_info * inf, tr_benc * meta )
171{
172    const char * str;
173    tr_tracker_info * trackers = NULL;
174    int trackerCount = 0;
175    tr_benc * tiers;
176
177    /* Announce-list */
178    if( tr_bencDictFindList( meta, "announce-list", &tiers ) )
179    {
180        int n;
181        int i, j;
182
183        n = 0;
184        for( i=0; i<tiers->val.l.count; ++i )
185            n += tiers->val.l.vals[i].val.l.count;
186
187        trackers = tr_new0( tr_tracker_info, n );
188        trackerCount = 0;
189
190        for( i=0; i<tiers->val.l.count; ++i ) {
191            const tr_benc * tier = &tiers->val.l.vals[i];
192            for( j=0; tr_bencIsList(tier) && j<tier->val.l.count; ++j ) {
193                const tr_benc * a = &tier->val.l.vals[j];
194                if( tr_bencIsString( a ) && tr_httpIsValidURL( a->val.s.s ) ) {
195                    tr_tracker_info * t = trackers + trackerCount++;
196                    t->tier = i;
197                    t->announce = tr_strndup( a->val.s.s, a->val.s.i );
198                    t->scrape = announceToScrape( a->val.s.s );
199                    /*fprintf( stderr, "tier %d: %s\n", i, a->val.s.s );*/
200                }
201            }
202        }
203
204        /* did we use any of the tiers? */
205        if( !trackerCount ) {
206            tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "announce-list" );
207            tr_free( trackers );
208            trackers = NULL;
209        }
210    }
211
212    /* Regular announce value */
213    if( !trackerCount
214        && tr_bencDictFindStr( meta, "announce", &str )
215        && tr_httpIsValidURL( str ) )
216    {
217        trackers = tr_new0( tr_tracker_info, 1 );
218        trackers[trackerCount].tier = 0;
219        trackers[trackerCount].announce = tr_strdup( str );
220        trackers[trackerCount++].scrape = announceToScrape( str );
221        /*fprintf( stderr, "single announce: [%s]\n", str );*/
222    }
223
224    inf->trackers = trackers;
225    inf->trackerCount = trackerCount;
226
227    if( !inf->trackerCount )
228        tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "announce" );
229
230    return inf->trackerCount ? TR_OK : TR_ERROR;
231}
232
233int
234tr_metainfoParse( const tr_handle  * handle,
235                  tr_info          * inf,
236                  const tr_benc    * meta_in )
237{
238    int64_t i;
239    const char * str;
240    const uint8_t * raw;
241    size_t rawlen;
242    tr_piece_index_t pi;
243    tr_benc * beInfo;
244    tr_benc * meta = (tr_benc *) meta_in;
245
246    /* info_hash: urlencoded 20-byte SHA1 hash of the value of the info key
247     * from the Metainfo file. Note that the value will be a bencoded
248     * dictionary, given the definition of the info key above. */
249    if( tr_bencDictFindDict( meta, "info", &beInfo ) )
250    {
251        int len;
252        char * str = tr_bencSave( beInfo, &len );
253        tr_sha1( inf->hash, str, len, NULL );
254        tr_sha1_to_hex( inf->hashString, inf->hash );
255        tr_free( str );
256    }
257    else
258    {
259        tr_err( _( "Missing metadata entry \"%s\"" ), "info" );
260        return TR_EINVALID;
261    }
262
263    /* name */
264    if( !tr_bencDictFindStr( beInfo, "name.utf-8", &str ) )
265        if( !tr_bencDictFindStr( beInfo, "name", &str ) )
266            str = NULL;
267    tr_free( inf->name );
268    inf->name = tr_strdup( str );
269    if( !str || !*str ) {
270        tr_err( _( "Invalid metadata entry \"%s\"" ), "name" );
271        return TR_EINVALID;
272    }
273
274    /* comment */
275    if( !tr_bencDictFindStr( meta, "comment.utf-8", &str ) )
276        if( !tr_bencDictFindStr( meta, "comment", &str ) )
277            str = "";
278    tr_free( inf->comment );
279    inf->comment = tr_strdup( str );
280   
281    /* creator */
282    if( !tr_bencDictFindStr( meta, "created by.utf-8", &str ) )
283        if( !tr_bencDictFindStr( meta, "created by", &str ) )
284            str = "";
285    tr_free( inf->creator );
286    inf->creator = tr_strdup( str );
287   
288    /* Date created */
289    if( !tr_bencDictFindInt( meta, "creation date", &i ) )
290        i = 0;
291    inf->dateCreated = i;
292   
293    /* Private torrent */
294    if( !tr_bencDictFindInt( beInfo, "private", &i ) )
295        if( !tr_bencDictFindInt( meta, "private", &i ) )
296            i = 0;
297    inf->isPrivate = i != 0;
298   
299    /* Piece length */
300    if( tr_bencDictFindInt( beInfo, "piece length", &i ) && ( i > 0 ) )
301        inf->pieceSize = i;
302    else {
303        tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "piece length" );
304        goto fail;
305    }
306
307    /* Hashes */
308    if( !tr_bencDictFindRaw( beInfo, "pieces", &raw, &rawlen ) || ( rawlen % SHA_DIGEST_LENGTH ) ) {
309        tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "pieces" );
310        goto fail;
311    }
312    inf->pieceCount = rawlen / SHA_DIGEST_LENGTH;
313    inf->pieces = tr_new0( tr_piece, inf->pieceCount );
314    for ( pi=0; pi<inf->pieceCount; ++pi )
315        memcpy( inf->pieces[pi].hash, &raw[pi*SHA_DIGEST_LENGTH], SHA_DIGEST_LENGTH );
316
317    /* files */
318    if( parseFiles( inf, tr_bencDictFind( beInfo, "files" ),
319                         tr_bencDictFind( beInfo, "length" ) ) )
320    {
321        goto fail;
322    }
323
324    if( !inf->fileCount || !inf->totalSize )
325    {
326        tr_nerr( inf->name, _( "Torrent is corrupt" ) ); /* the content is missing! */
327        goto fail;
328    }
329
330    /* TODO add more tests so we don't crash on weird files */
331
332    if( (uint64_t) inf->pieceCount !=
333        ( inf->totalSize + inf->pieceSize - 1 ) / inf->pieceSize )
334    {
335        tr_nerr( inf->name, _( "Torrent is corrupt" ) ); /* size of hashes and files don't match */
336        goto fail;
337    }
338
339    /* get announce or announce-list */
340    if( getannounce( inf, meta ) )
341        goto fail;
342
343    /* get the url-list */
344    geturllist( inf, meta );
345
346    /* filename of Transmission's copy */
347    tr_free( inf->torrent );
348    inf->torrent = getTorrentFilename( handle, inf );
349
350    return TR_OK;
351
352  fail:
353    tr_metainfoFree( inf );
354    return TR_EINVALID;
355}
356
357void tr_metainfoFree( tr_info * inf )
358{
359    tr_file_index_t ff;
360    int i;
361
362    for( i=0; i<inf->webseedCount; ++i )
363        tr_free( inf->webseeds[i] );
364
365    for( ff=0; ff<inf->fileCount; ++ff )
366        tr_free( inf->files[ff].name );
367
368    tr_free( inf->webseeds );
369    tr_free( inf->pieces );
370    tr_free( inf->files );
371    tr_free( inf->comment );
372    tr_free( inf->creator );
373    tr_free( inf->torrent );
374    tr_free( inf->name );
375   
376    for( i=0; i<inf->trackerCount; ++i ) {
377        tr_free( inf->trackers[i].announce );
378        tr_free( inf->trackers[i].scrape );
379    }
380    tr_free( inf->trackers );
381
382    memset( inf, '\0', sizeof(tr_info) );
383}
384
385static int
386getfile( char ** setme, const char * root, tr_benc * path )
387{
388    int err;
389
390    if( !tr_bencIsList( path ) )
391    {
392        err = TR_EINVALID;
393    }
394    else
395    {
396        struct evbuffer * buf = evbuffer_new( );
397        int n = tr_bencListSize( path );
398        int i;
399
400        evbuffer_add( buf, root, strlen( root ) );
401        for( i=0; i<n; ++i ) {
402            const char * str;
403            if( tr_bencGetStr( tr_bencListChild( path, i ), &str ) && strcmp( str, ".." ) ) {
404                evbuffer_add( buf, TR_PATH_DELIMITER_STR, 1 );
405                evbuffer_add( buf, str, strlen( str ) );
406            }
407        }
408
409        *setme = tr_strndup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
410        /* fprintf( stderr, "[%s]\n", *setme ); */
411        evbuffer_free( buf );
412        err = TR_OK;
413    }
414
415    return err;
416}
417
418void
419tr_metainfoRemoveSaved( const tr_handle * handle,
420                        const tr_info   * inf )
421{
422    char * filename;
423
424    filename = getTorrentFilename( handle, inf );
425    unlink( filename );
426    tr_free( filename );
427
428    filename = getTorrentOldFilename( handle, inf );
429    unlink( filename );
430    tr_free( filename );
431}
432
433static int
434parseFiles( tr_info * inf, tr_benc * files, tr_benc * length )
435{
436    tr_benc * item, * path;
437    int ii;
438    inf->totalSize = 0;
439
440    if( tr_bencIsList( files ) )
441    {
442        /* Multi-file mode */
443        inf->isMultifile = 1;
444        inf->fileCount   = files->val.l.count;
445        inf->files       = tr_new0( tr_file, inf->fileCount );
446
447        if( !inf->files )
448            return TR_EINVALID;
449
450        for( ii = 0; files->val.l.count > ii; ii++ )
451        {
452            item = &files->val.l.vals[ii];
453            path = tr_bencDictFindFirst( item, "path.utf-8", "path", NULL );
454            if( getfile( &inf->files[ii].name, inf->name, path ) )
455            {
456                if( path )
457                    tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "path" );
458                else
459                    tr_nerr( inf->name, _( "Missing metadata entry \"%s\"" ), "path" );
460                return TR_EINVALID;
461            }
462            length = tr_bencDictFind( item, "length" );
463            if( !tr_bencIsInt( length ) )
464            {
465                if( length )
466                    tr_nerr( inf->name, _( "Invalid metadata entry \"%s\"" ), "length" );
467                else
468                    tr_nerr( inf->name, _( "Missing metadata entry \"%s\"" ), "length" );
469                return TR_EINVALID;
470            }
471            inf->files[ii].length = length->val.i;
472            inf->totalSize         += length->val.i;
473        }
474    }
475    else if( tr_bencIsInt( length ) )
476    {
477        /* Single-file mode */
478        inf->isMultifile = 0;
479        inf->fileCount = 1;
480        inf->files = tr_new0( tr_file, 1 );
481
482        if( !inf->files )
483            return TR_EINVALID;
484
485        tr_free( inf->files[0].name );
486        inf->files[0].name   = tr_strdup( inf->name );
487        inf->files[0].length = length->val.i;
488        inf->totalSize      += length->val.i;
489    }
490    else
491    {
492        tr_nerr( inf->name, _( "Invalid or missing metadata entries \"length\" and \"files\"" ) );
493    }
494
495    return TR_OK;
496}
Note: See TracBrowser for help on using the repository browser.