source: trunk/libtransmission/metainfo.c @ 920

Last change on this file since 920 was 920, checked in by joshe, 16 years ago

Merge nat-traversal branch to trunk.

  • Property svn:keywords set to Date Rev Author Id
File size: 10.4 KB
Line 
1/******************************************************************************
2 * $Id: metainfo.c 920 2006-09-25 18:37:45Z joshe $
3 *
4 * Copyright (c) 2005-2006 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 "transmission.h"
26
27#define TORRENT_MAX_SIZE (5*1024*1024)
28
29/***********************************************************************
30 * Local prototypes
31 **********************************************************************/
32static void strcatUTF8( char *, char * );
33
34/***********************************************************************
35 * tr_metainfoParse
36 ***********************************************************************
37 *
38 **********************************************************************/
39int tr_metainfoParse( tr_info_t * inf, const char * path,
40                      const char * savedHash, int saveCopy )
41{
42    FILE       * file;
43    char       * buf;
44    benc_val_t   meta, * beInfo, * list, * val;
45    char * s, * s2, * s3;
46    int          i;
47    struct stat sb;
48
49    assert( NULL == path || NULL == savedHash );
50    /* if savedHash isn't null, saveCopy should be false */
51    assert( NULL == savedHash || !saveCopy );
52
53    if ( NULL != savedHash )
54    {
55        snprintf( inf->torrent, MAX_PATH_LENGTH, "%s/%s",
56                  tr_getTorrentsDirectory(), savedHash );
57        path = inf->torrent;
58    }
59
60    if( stat( path, &sb ) )
61    {
62        tr_err( "Could not stat file (%s)", path );
63        return 1;
64    }
65    if( ( sb.st_mode & S_IFMT ) != S_IFREG )
66    {
67        tr_err( "Not a regular file (%s)", path );
68        return 1;
69    }
70    if( sb.st_size > TORRENT_MAX_SIZE )
71    {
72        tr_err( "Torrent file is too big (%d bytes)", (int)sb.st_size );
73        return 1;
74    }
75
76    /* Load the torrent file into our buffer */
77    file = fopen( path, "rb" );
78    if( !file )
79    {
80        tr_err( "Could not open file (%s)", path );
81        return 1;
82    }
83    buf = malloc( sb.st_size );
84    fseek( file, 0, SEEK_SET );
85    if( fread( buf, sb.st_size, 1, file ) != 1 )
86    {
87        tr_err( "Read error (%s)", path );
88        free( buf );
89        fclose( file );
90        return 1;
91    }
92    fclose( file );
93
94    /* Parse bencoded infos */
95    if( tr_bencLoad( buf, sb.st_size, &meta, NULL ) )
96    {
97        tr_err( "Error while parsing bencoded data" );
98        free( buf );
99        return 1;
100    }
101
102    /* Get info hash */
103    if( !( beInfo = tr_bencDictFind( &meta, "info" ) ) )
104    {
105        tr_err( "Could not find \"info\" dictionary" );
106        tr_bencFree( &meta );
107        free( buf );
108        return 1;
109    }
110    SHA1( (uint8_t *) beInfo->begin,
111          (long) beInfo->end - (long) beInfo->begin, inf->hash );
112    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
113    {
114        sprintf( inf->hashString + i * 2, "%02x", inf->hash[i] );
115    }
116
117    if( saveCopy )
118    {
119        /* Save a copy of the torrent file in the private torrent directory */
120        snprintf( inf->torrent, MAX_PATH_LENGTH, "%s/%s",
121                  tr_getTorrentsDirectory(), inf->hashString );
122        file = fopen( inf->torrent, "wb" );
123        if( !file )
124        {
125            tr_err( "Could not open file (%s) (%s)",
126                    inf->torrent, strerror(errno) );
127            tr_bencFree( &meta );
128            free( buf );
129            return 1;
130        }
131        fseek( file, 0, SEEK_SET );
132        if( fwrite( buf, sb.st_size, 1, file ) != 1 )
133        {
134            tr_err( "Write error (%s)", inf->torrent );
135            tr_bencFree( &meta );
136            free( buf );
137            fclose( file );
138            return 1;
139        }
140        fclose( file );
141    }
142    else
143    {
144        snprintf( inf->torrent, MAX_PATH_LENGTH, "%s", path );
145    }
146
147    /* We won't need this anymore */
148    free( buf );
149
150    if( !( val = tr_bencDictFind( &meta, "announce" ) ) )
151    {
152        tr_err( "No \"announce\" entry" );
153        tr_bencFree( &meta );
154        return 1;
155    }
156   
157    /* Skip spaces */
158    s3 = val->val.s.s;
159    while( *s3 && *s3 == ' ' )
160    {
161        s3++;
162    }
163
164    /* Parse announce URL */
165    if( strncmp( s3, "http://", 7 ) )
166    {
167        tr_err( "Invalid announce URL (%s)", inf->trackerAddress );
168        tr_bencFree( &meta );
169        return 1;
170    }
171    s  = strchr( s3 + 7, ':' );
172    s2 = strchr( s3 + 7, '/' );
173    if( s && s < s2 )
174    {
175        memcpy( inf->trackerAddress, s3 + 7,
176                (long) s - (long) s3 - 7 );
177        inf->trackerPort = atoi( s + 1 );
178    }
179    else if( s2 )
180    {
181        memcpy( inf->trackerAddress, s3 + 7,
182                (long) s2 - (long) s3 - 7 );
183        inf->trackerPort = 80;
184    }
185    else
186    {
187        tr_err( "Invalid announce URL (%s)", inf->trackerAddress );
188        tr_bencFree( &meta );
189        return 1;
190    }
191    snprintf( inf->trackerAnnounce, MAX_PATH_LENGTH, "%s", s2 );
192
193    /* Piece length */
194    if( !( val = tr_bencDictFind( beInfo, "piece length" ) ) )
195    {
196        tr_err( "No \"piece length\" entry" );
197        tr_bencFree( &meta );
198        return 1;
199    }
200    inf->pieceSize = val->val.i;
201
202    /* Hashes */
203    val = tr_bencDictFind( beInfo, "pieces" );
204    if( val->val.s.i % SHA_DIGEST_LENGTH )
205    {
206        tr_err( "Invalid \"piece\" string (size is %d)", val->val.s.i );
207        tr_bencFree( &meta );
208        return 1;
209    }
210    inf->pieceCount = val->val.s.i / SHA_DIGEST_LENGTH;
211    inf->pieces = (uint8_t *) val->val.s.s; /* Ugly, but avoids a memcpy */
212    val->val.s.s = NULL;
213
214    /* TODO add more tests so we don't crash on weird files */
215
216    inf->totalSize = 0;
217    if( ( list = tr_bencDictFind( beInfo, "files" ) ) )
218    {
219        /* Multi-file mode */
220        int j;
221
222        val = tr_bencDictFind( beInfo, "name.utf-8" );
223        if( NULL == val )
224        {
225            val = tr_bencDictFind( beInfo, "name" );
226        }
227        strcatUTF8( inf->name, val->val.s.s );
228
229        inf->multifile = 1;
230        inf->fileCount = list->val.l.count;
231        inf->files     = calloc( inf->fileCount * sizeof( tr_file_t ), 1 );
232
233        for( i = 0; i < list->val.l.count; i++ )
234        {
235            val = tr_bencDictFind( &list->val.l.vals[i], "path.utf-8" );
236            if( NULL == val )
237            {
238                val = tr_bencDictFind( &list->val.l.vals[i], "path" );
239            }
240            strcatUTF8( inf->files[i].name, inf->name );
241            for( j = 0; j < val->val.l.count; j++ )
242            {
243                strcatUTF8( inf->files[i].name, "/" );
244                strcatUTF8( inf->files[i].name,
245                            val->val.l.vals[j].val.s.s );
246            }
247            val = tr_bencDictFind( &list->val.l.vals[i], "length" );
248            inf->files[i].length  = val->val.i;
249            inf->totalSize       += val->val.i;
250        }
251
252    }
253    else
254    {
255        /* Single-file mode */
256        inf->multifile = 0;
257        inf->fileCount = 1;
258        inf->files     = calloc( sizeof( tr_file_t ), 1 );
259
260        val = tr_bencDictFind( beInfo, "name.utf-8" );
261        if( NULL == val )
262        {
263            val = tr_bencDictFind( beInfo, "name" );
264        }
265        strcatUTF8( inf->files[0].name, val->val.s.s );
266        strcatUTF8( inf->name, val->val.s.s );
267       
268        val = tr_bencDictFind( beInfo, "length" );
269        inf->files[0].length  = val->val.i;
270        inf->totalSize       += val->val.i;
271    }
272
273    if( (uint64_t) inf->pieceCount !=
274        ( inf->totalSize + inf->pieceSize - 1 ) / inf->pieceSize )
275    {
276        tr_err( "Size of hashes and files don't match" );
277        free( inf->pieces );
278        tr_bencFree( &meta );
279        return 1;
280    }
281
282    tr_bencFree( &meta );
283    return 0;
284}
285
286void tr_metainfoRemoveSaved( const char * hashString )
287{
288    char file[MAX_PATH_LENGTH];
289
290    snprintf( file, MAX_PATH_LENGTH, "%s/%s",
291              tr_getTorrentsDirectory(), hashString );
292    unlink(file);
293}
294
295/***********************************************************************
296 * strcatUTF8
297 ***********************************************************************
298 * According to the official specification, all strings in the torrent
299 * file are supposed to be UTF-8 encoded. However, there are
300 * non-compliant torrents around... If we encounter an invalid UTF-8
301 * character, we assume it is ISO 8859-1 and convert it to UTF-8.
302 **********************************************************************/
303static void strcatUTF8( char * s, char * append )
304{
305    char * p;
306
307    /* Go to the end of the destination string */
308    while( s[0] )
309    {
310        s++;
311    }
312
313    /* Now start appending, converting on the fly if necessary */
314    for( p = append; p[0]; )
315    {
316        if( !( p[0] & 0x80 ) )
317        {
318            /* ASCII character */
319            *(s++) = *(p++);
320            continue;
321        }
322
323        if( ( p[0] & 0xE0 ) == 0xC0 && ( p[1] & 0xC0 ) == 0x80 )
324        {
325            /* 2-bytes UTF-8 character */
326            *(s++) = *(p++); *(s++) = *(p++);
327            continue;
328        }
329
330        if( ( p[0] & 0xF0 ) == 0xE0 && ( p[1] & 0xC0 ) == 0x80 &&
331            ( p[2] & 0xC0 ) == 0x80 )
332        {
333            /* 3-bytes UTF-8 character */
334            *(s++) = *(p++); *(s++) = *(p++);
335            *(s++) = *(p++);
336            continue;
337        }
338
339        if( ( p[0] & 0xF8 ) == 0xF0 && ( p[1] & 0xC0 ) == 0x80 &&
340            ( p[2] & 0xC0 ) == 0x80 && ( p[3] & 0xC0 ) == 0x80 )
341        {
342            /* 4-bytes UTF-8 character */
343            *(s++) = *(p++); *(s++) = *(p++);
344            *(s++) = *(p++); *(s++) = *(p++);
345            continue;
346        }
347
348        /* ISO 8859-1 -> UTF-8 conversion */
349        *(s++) = 0xC0 | ( ( *p & 0xFF ) >> 6 );
350        *(s++) = 0x80 | ( *(p++) & 0x3F );
351    }
352}
Note: See TracBrowser for help on using the repository browser.