source: trunk/libtransmission/makemeta.c @ 6425

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

minor text cleanup

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