source: trunk/libtransmission/makemeta.c @ 6451

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

#1155: when creating new torrents > 2 GiB, piece size should be 2 MiB

  • Property svn:keywords set to Date Rev Author Id
File size: 13.9 KB
Line 
1/*
2 * This file Copyright (C) 2007-2008 Charles Kerr <charles@rebelbase.com>
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: makemeta.c 6451 2008-08-07 19:25:19Z charles $
11 */
12
13#include <assert.h>
14#include <errno.h>
15#include <stdio.h> /* FILE, stderr */
16#include <stdlib.h> /* qsort */
17
18#include <sys/types.h>
19#include <sys/stat.h>
20#include <unistd.h>
21#include <libgen.h> /* dirname, basename */
22#include <dirent.h>
23
24#include "crypto.h" /* tr_sha1 */
25#include "transmission.h"
26#include "bencode.h"
27#include "makemeta.h"
28#include "platform.h" /* threads, locks */
29#include "utils.h" /* buildpath */
30#include "version.h"
31
32/****
33*****
34****/
35
36struct FileList
37{
38    struct FileList * next;
39    uint64_t size;
40    char * filename;
41};
42
43static struct FileList*
44getFiles( const char        * dir,
45          const char        * base,
46          struct FileList   * list )
47{
48    int i;
49    char buf[MAX_PATH_LENGTH];
50    struct stat sb;
51    DIR * odir = NULL;
52    sb.st_size = 0;
53
54    tr_buildPath( buf, sizeof(buf), dir, base, NULL );
55    i = stat( buf, &sb );
56    if( i ) {
57        tr_err( _( "Torrent Creator is skipping file \"%s\": %s" ), buf, tr_strerror(errno));
58        return list;
59    }
60
61    if ( S_ISDIR( sb.st_mode ) && (( odir = opendir ( buf ) )) )
62    {
63        struct dirent *d;
64        for (d = readdir( odir ); d!=NULL; d=readdir( odir ) )
65            if( d->d_name && d->d_name[0]!='.' ) /* skip dotfiles, ., and .. */
66                list = getFiles( buf, d->d_name, list );
67        closedir( odir );
68    }
69    else if( S_ISREG( sb.st_mode ) )
70    {
71        struct FileList * node = tr_new( struct FileList, 1 );
72        node->size = sb.st_size;
73        if( ( buf[0]=='.' ) && ( buf[1]=='/' ) )
74            node->filename = tr_strdup( buf + 2 );
75        else
76            node->filename = tr_strdup( buf );
77        node->next = list;
78        list = node;
79    }
80
81    return list;
82}
83
84static int
85bestPieceSize( uint64_t totalSize )
86{
87    static const uint64_t GiB = 1073741824;
88    static const uint64_t MiB = 1048576;
89    static const uint64_t KiB = 1024;
90
91    if( totalSize >=   (2*GiB) ) return (2*MiB);
92    if( totalSize >=   (1*GiB) ) return (1*MiB);
93    if( totalSize >= (512*MiB) ) return (512*KiB);
94    if( totalSize >= (350*MiB) ) return (256*KiB);
95    if( totalSize >= (150*MiB) ) return (128*KiB);
96    if( totalSize >=  (50*MiB) ) return (64*KiB);
97    return (32*KiB); /* less than 50 meg */
98}
99
100static int
101builderFileCompare ( const void * va, const void * vb)
102{
103    const tr_metainfo_builder_file * a = va;
104    const tr_metainfo_builder_file * b = vb;
105    return strcmp( a->filename, b->filename );
106}
107
108tr_metainfo_builder*
109tr_metaInfoBuilderCreate( tr_handle * handle, const char * topFile )
110{
111    int i;
112    struct FileList * files;
113    struct FileList * walk;
114    tr_metainfo_builder * ret = tr_new0( tr_metainfo_builder, 1 );
115    ret->top = tr_strdup( topFile );
116    ret->handle = handle; 
117    {
118        struct stat sb;
119        stat( topFile, &sb );
120        ret->isSingleFile = !S_ISDIR( sb.st_mode );
121    }
122
123    /* build a list of files containing topFile and,
124       if it's a directory, all of its children */
125    {
126        char *dir, *base;
127        char dirbuf[MAX_PATH_LENGTH];
128        char basebuf[MAX_PATH_LENGTH];
129        tr_strlcpy( dirbuf, topFile, sizeof( dirbuf ) );
130        tr_strlcpy( basebuf, topFile, sizeof( basebuf ) );
131        dir = dirname( dirbuf );
132        base = basename( basebuf );
133        files = getFiles( dir, base, NULL );
134    }
135
136    for( walk=files; walk!=NULL; walk=walk->next )
137        ++ret->fileCount;
138
139    ret->files = tr_new0( tr_metainfo_builder_file, ret->fileCount );
140
141    for( i=0, walk=files; walk!=NULL; ++i )
142    {
143        struct FileList * tmp = walk;
144        tr_metainfo_builder_file * file = &ret->files[i];
145        walk = walk->next;
146        file->filename = tmp->filename;
147        file->size = tmp->size;
148        ret->totalSize += tmp->size;
149        tr_free( tmp );
150    }
151
152    qsort( ret->files,
153           ret->fileCount,
154           sizeof(tr_metainfo_builder_file),
155           builderFileCompare );
156
157    ret->pieceSize = bestPieceSize( ret->totalSize );
158    ret->pieceCount = ret->pieceSize
159        ? (int)( ret->totalSize / ret->pieceSize)
160        : 0;
161    if( ret->totalSize % ret->pieceSize )
162        ++ret->pieceCount;
163
164    return ret;
165}
166
167void
168tr_metaInfoBuilderFree( tr_metainfo_builder * builder )
169{
170    if( builder )
171    {
172        tr_file_index_t t;
173        int i;
174        for( t=0; t<builder->fileCount; ++t )
175            tr_free( builder->files[t].filename );
176        tr_free( builder->files );
177        tr_free( builder->top );
178        tr_free( builder->comment );
179        for( i=0; i<builder->trackerCount; ++i )
180            tr_free( builder->trackers[i].announce );
181        tr_free( builder->trackers );
182        tr_free( builder->outputFile );
183        tr_free( builder );
184    }
185}
186
187/****
188*****
189****/
190
191static uint8_t*
192getHashInfo ( tr_metainfo_builder * b )
193{
194    uint32_t fileIndex = 0;
195    uint8_t *ret = tr_new0( uint8_t, SHA_DIGEST_LENGTH * b->pieceCount );
196    uint8_t *walk = ret;
197    uint8_t *buf;
198    uint64_t totalRemain;
199    uint64_t off = 0;
200    FILE * fp;
201
202    if( !b->totalSize )
203        return ret;
204
205    buf = tr_new( uint8_t, b->pieceSize );
206    b->pieceIndex = 0;
207    totalRemain = b->totalSize;
208    fp = fopen( b->files[fileIndex].filename, "rb" );
209    if( !fp ) {
210        b->my_errno = errno;
211        tr_snprintf( b->errfile, sizeof( b->errfile ), b->files[fileIndex].filename );
212        b->result = TR_MAKEMETA_IO_READ;
213        tr_free( ret );
214        return NULL;
215    }
216    while ( totalRemain )
217    {
218        uint8_t *bufptr = buf;
219        const uint64_t thisPieceSize =
220            MIN( (uint32_t)b->pieceSize, totalRemain );
221        uint64_t pieceRemain = thisPieceSize;
222
223        assert( b->pieceIndex < b->pieceCount );
224
225        while( pieceRemain )
226        {
227            const uint64_t n_this_pass =
228                MIN( (b->files[fileIndex].size - off), pieceRemain );
229            fread( bufptr, 1, n_this_pass, fp );
230            bufptr += n_this_pass;
231            off += n_this_pass;
232            pieceRemain -= n_this_pass;
233            if( off == b->files[fileIndex].size ) {
234                off = 0;
235                fclose( fp );
236                fp = NULL;
237                if( ++fileIndex < b->fileCount ) {
238                    fp = fopen( b->files[fileIndex].filename, "rb" );
239                    if( !fp ) {
240                        b->my_errno = errno;
241                        tr_snprintf( b->errfile, sizeof( b->errfile ), b->files[fileIndex].filename );
242                        b->result = TR_MAKEMETA_IO_READ;
243                        tr_free( ret );
244                        return NULL;
245                    }
246                }
247            }
248        }
249
250        assert( bufptr-buf == (int)thisPieceSize );
251        assert( pieceRemain == 0 );
252        tr_sha1( walk, buf, thisPieceSize, NULL );
253        walk += SHA_DIGEST_LENGTH;
254
255        if( b->abortFlag ) {
256            b->result = TR_MAKEMETA_CANCELLED;
257            break;
258        }
259
260        totalRemain -= thisPieceSize;
261        ++b->pieceIndex;
262    }
263    assert( b->abortFlag || (walk-ret == (int)(SHA_DIGEST_LENGTH*b->pieceCount)) );
264    assert( b->abortFlag || !totalRemain );
265
266    if( fp )
267        fclose( fp );
268
269    tr_free( buf );
270    return ret;
271}
272
273static void
274getFileInfo( const char                      * topFile,
275             const tr_metainfo_builder_file  * file,
276             tr_benc                         * uninitialized_length,
277             tr_benc                         * uninitialized_path )
278{
279    const char *pch, *prev;
280    const size_t topLen = strlen(topFile) + 1; /* +1 for '/' */
281    int n;
282
283    /* get the file size */
284    tr_bencInitInt( uninitialized_length, file->size );
285
286    /* the path list */
287    n = 1;
288    for( pch=file->filename+topLen; *pch; ++pch )
289        if (*pch == TR_PATH_DELIMITER)
290            ++n;
291    tr_bencInitList( uninitialized_path, n );
292    for( prev=pch=file->filename+topLen; ; ++pch )
293    {
294        char buf[MAX_PATH_LENGTH];
295
296        if (*pch && *pch!=TR_PATH_DELIMITER )
297            continue;
298
299        memcpy( buf, prev, pch-prev );
300        buf[pch-prev] = '\0';
301
302        tr_bencListAddStr( uninitialized_path, buf );
303
304        prev = pch + 1;
305        if (!*pch)
306           break;
307    }
308}
309
310static void
311makeInfoDict ( tr_benc              * dict,
312               tr_metainfo_builder  * builder )
313{
314    uint8_t * pch;
315    char base[MAX_PATH_LENGTH];
316
317    tr_bencDictReserve( dict, 5 );
318   
319    if ( builder->isSingleFile )
320        tr_bencDictAddInt( dict, "length", builder->files[0].size );
321    else {
322        uint32_t i;
323        tr_benc * list = tr_bencDictAddList( dict, "files", builder->fileCount );
324        for( i=0; i<builder->fileCount; ++i ) {
325            tr_benc * dict = tr_bencListAddDict( list, 2 );
326            tr_benc * length = tr_bencDictAdd( dict, "length" );
327            tr_benc * pathVal = tr_bencDictAdd( dict, "path" );
328            getFileInfo( builder->top, &builder->files[i], length, pathVal );
329        }
330    }
331
332    tr_strlcpy( base, builder->top, sizeof( base ) );
333    tr_bencDictAddStr( dict, "name", basename( base ) );
334
335    tr_bencDictAddInt( dict, "piece length", builder->pieceSize );
336
337    if(( pch = getHashInfo( builder ))) {
338        tr_bencDictAddRaw( dict, "pieces", pch, SHA_DIGEST_LENGTH * builder->pieceCount );
339        tr_free( pch );
340    }
341
342    tr_bencDictAddInt( dict, "private", builder->isPrivate ? 1 : 0 );
343}
344
345static void
346tr_realMakeMetaInfo ( tr_metainfo_builder * builder )
347{
348    int i;
349    tr_benc top;
350
351    /* allow an empty set, but if URLs *are* listed, verify them. #814, #971 */
352    for( i=0; i<builder->trackerCount && !builder->result; ++i )
353        if( !tr_httpIsValidURL( builder->trackers[i].announce ) )
354            builder->result = TR_MAKEMETA_URL;
355
356    tr_bencInitDict( &top, 6 );
357
358    if( !builder->result && builder->trackerCount )
359    {
360        int prevTier = -1;
361        tr_benc * tier = NULL;
362        tr_benc * announceList;
363
364        announceList = tr_bencDictAddList( &top, "announce-list", 0 );
365        for( i=0; i<builder->trackerCount; ++i ) {
366            if( prevTier != builder->trackers[i].tier ) {
367                prevTier = builder->trackers[i].tier;
368                tier = tr_bencListAddList( announceList, 0 );
369            }
370            tr_bencListAddStr( tier, builder->trackers[i].announce );
371        }
372
373        tr_bencDictAddStr( &top, "announce", builder->trackers[0].announce );
374    }
375   
376    if( !builder->result && !builder->abortFlag )
377    {
378        if( builder->comment && *builder->comment )
379            tr_bencDictAddStr( &top, "comment", builder->comment );
380        tr_bencDictAddStr( &top, "created by", TR_NAME "/" LONG_VERSION_STRING );
381        tr_bencDictAddInt( &top, "creation date", time(0) );
382        tr_bencDictAddStr( &top, "encoding", "UTF-8" );
383        makeInfoDict( tr_bencDictAddDict( &top, "info", 666 ), builder );
384    }
385
386    /* save the file */
387    if ( !builder->result && !builder->abortFlag ) {
388        if( tr_bencSaveFile( builder->outputFile, &top ) ) {
389            builder->my_errno = errno;
390            tr_strlcpy( builder->errfile, builder->outputFile, sizeof( builder->errfile ) );
391            builder->result = TR_MAKEMETA_IO_WRITE;
392        }
393    }
394
395    /* cleanup */
396    tr_bencFree( &top );
397    if( builder->abortFlag )
398        builder->result = TR_MAKEMETA_CANCELLED;
399    builder->isDone = 1;
400}
401
402/***
403****
404****  A threaded builder queue
405****
406***/
407
408static tr_metainfo_builder * queue = NULL;
409
410static tr_thread * workerThread = NULL;
411
412static tr_lock* getQueueLock( tr_handle * h )
413{
414    static tr_lock * lock = NULL;
415
416    tr_globalLock( h );
417    if( !lock )
418         lock = tr_lockNew( );
419    tr_globalUnlock( h );
420
421    return lock;
422}
423
424static void workerFunc( void * user_data )
425{
426    tr_handle * handle = (tr_handle *) user_data;
427
428    for (;;)
429    {
430        tr_metainfo_builder * builder = NULL;
431
432        /* find the next builder to process */
433        tr_lock * lock = getQueueLock ( handle );
434        tr_lockLock( lock );
435        if( queue ) {
436            builder = queue;
437            queue = queue->nextBuilder;
438        }
439        tr_lockUnlock( lock );
440
441        /* if no builders, this worker thread is done */
442        if( builder == NULL )
443          break;
444
445        tr_realMakeMetaInfo ( builder );
446    }
447
448    workerThread = NULL;
449}
450
451void
452tr_makeMetaInfo( tr_metainfo_builder    * builder,
453                 const char             * outputFile,
454                 const tr_tracker_info  * trackers,
455                 int                      trackerCount,
456                 const char             * comment,
457                 int                      isPrivate )
458{
459    int i;
460    tr_lock * lock;
461
462    /* free any variables from a previous run */
463    for( i=0; i<builder->trackerCount; ++i )
464        tr_free( builder->trackers[i].announce );
465    tr_free( builder->trackers );
466    tr_free( builder->comment );
467    tr_free( builder->outputFile );
468
469    /* initialize the builder variables */
470    builder->abortFlag = 0;
471    builder->isDone = 0;
472    builder->trackerCount = trackerCount;
473    builder->trackers = tr_new0( tr_tracker_info, builder->trackerCount );
474    for( i=0; i<builder->trackerCount; ++i ) {
475        builder->trackers[i].tier = trackers[i].tier;
476        builder->trackers[i].announce = tr_strdup( trackers[i].announce );
477    }
478    builder->comment = tr_strdup( comment );
479    builder->isPrivate = isPrivate;
480    if( outputFile && *outputFile )
481        builder->outputFile = tr_strdup( outputFile );
482    else {
483        char out[MAX_PATH_LENGTH];
484        tr_snprintf( out, sizeof(out), "%s.torrent", builder->top);
485        builder->outputFile = tr_strdup( out );
486    }
487
488    /* enqueue the builder */
489    lock = getQueueLock ( builder->handle );
490    tr_lockLock( lock );
491    builder->nextBuilder = queue;
492    queue = builder;
493    if( !workerThread )
494         workerThread = tr_threadNew( workerFunc, builder->handle, "makeMeta" );
495    tr_lockUnlock( lock );
496}
497
Note: See TracBrowser for help on using the repository browser.