source: trunk/libtransmission/fastresume.h @ 1579

Last change on this file since 1579 was 1579, checked in by joshe, 15 years ago

Merge PEX branch, I hope this works.

  • Property svn:keywords set to Date Rev Author Id
File size: 11.5 KB
Line 
1/******************************************************************************
2 * $Id: fastresume.h 1579 2007-03-23 08:28:01Z joshe $
3 *
4 * Copyright (c) 2005-2007 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/***********************************************************************
26 * Fast resume
27 ***********************************************************************
28 * The format of the resume file is a 4 byte format version (currently 1),
29 * followed by several variable-sized blocks of data.  Each block is
30 * preceded by a 1 byte ID and a 4 byte length.  The currently recognized
31 * IDs are defined below by the FR_ID_* macros.  The length does not include
32 * the 5 bytes for the ID and length.
33 *
34 * The name of the resume file is "resume.<hash>".
35 *
36 * All values are stored in the native endianness. Moving a
37 * libtransmission resume file from an architecture to another will not
38 * work, although it will not hurt either (the version will be wrong,
39 * so the resume file will not be read).
40 **********************************************************************/
41
42/* progress data:
43 *  - 4 bytes * number of files: mtimes of files
44 *  - 1 bit * number of blocks: whether we have the block or not
45 *  - 4 bytes * number of pieces (byte aligned): the pieces that have
46 *    been completed or started in each slot
47 */
48#define FR_ID_PROGRESS          0x01
49/* number of bytes downloaded */
50#define FR_ID_DOWNLOADED        0x02
51/* number of bytes uploaded */
52#define FR_ID_UPLOADED          0x03
53/* IPs and ports of connectable peers */
54#define FR_ID_PEERS             0x04
55
56/* macros for the length of various pieces of the progress data */
57#define FR_MTIME_LEN( t ) \
58  ( 4 * (t)->info.fileCount )
59#define FR_BLOCK_BITFIELD_LEN( t ) \
60  ( ( (t)->blockCount + 7 ) / 8 )
61#define FR_SLOTPIECE_LEN( t ) \
62  ( 4 * (t)->info.pieceCount )
63#define FR_PROGRESS_LEN( t ) \
64  ( FR_MTIME_LEN( t ) + FR_BLOCK_BITFIELD_LEN( t ) + FR_SLOTPIECE_LEN( t ) )
65
66static char * fastResumeFileName( tr_io_t * io )
67{
68    char * ret;
69
70    asprintf( &ret, "%s/resume.%s", tr_getCacheDirectory(),
71              io->tor->info.hashString );
72
73    return ret;
74}
75
76static int fastResumeMTimes( tr_io_t * io, int * tab )
77{
78    tr_torrent_t * tor = io->tor;
79    tr_info_t    * inf = &tor->info;
80
81    int           i;
82    char        * path;
83    struct stat   sb;
84
85    for( i = 0; i < inf->fileCount; i++ )
86    {
87        asprintf( &path, "%s/%s", tor->destination, inf->files[i].name );
88        if( stat( path, &sb ) )
89        {
90            tab[i] = 0xFFFFFFFF;
91        }
92        else if( S_ISREG( sb.st_mode ) )
93        {
94#ifdef SYS_DARWIN
95            tab[i] = ( sb.st_mtimespec.tv_sec & 0x7FFFFFFF );
96#else
97            tab[i] = ( sb.st_mtime & 0x7FFFFFFF );
98#endif
99        }
100        else
101        {
102            /* Empty folder */
103            tab[i] = 0;
104        }
105        free( path );
106    }
107
108    return 0;
109}
110
111static inline void fastResumeWriteData( uint8_t id, void * data, uint32_t size,
112                                        uint32_t count, FILE * file )
113{
114    uint32_t  datalen = size * count;
115
116    fwrite( &id, 1, 1, file );
117    fwrite( &datalen, 4, 1, file );
118    fwrite( data, size, count, file );
119}
120
121static void fastResumeSave( tr_io_t * io )
122{
123    tr_torrent_t * tor = io->tor;
124   
125    FILE    * file;
126    int       version = 1;
127    char    * path;
128    uint8_t * buf;
129    uint64_t  total;
130    int       size;
131    tr_bitfield_t * bitfield;
132
133    buf = malloc( FR_PROGRESS_LEN( tor ) );
134
135    /* Get file sizes */
136    if( fastResumeMTimes( io, (int*)buf ) )
137    {
138        free( buf );
139        return;
140    }
141
142    /* Create/overwrite the resume file */
143    path = fastResumeFileName( io );
144    if( !( file = fopen( path, "w" ) ) )
145    {
146        tr_err( "Could not open '%s' for writing", path );
147        free( buf );
148        free( path );
149        return;
150    }
151   
152    /* Write format version */
153    fwrite( &version, 4, 1, file );
154
155    /* Build and copy the bitfield for blocks */
156    bitfield = tr_cpBlockBitfield( tor->completion );
157    assert( FR_BLOCK_BITFIELD_LEN( tor ) == bitfield->len );
158    memcpy(buf + FR_MTIME_LEN( tor ), bitfield->bits, bitfield->len );
159
160    /* Copy the 'slotPiece' table */
161    memcpy(buf + FR_MTIME_LEN( tor ) + FR_BLOCK_BITFIELD_LEN( tor ),
162           io->slotPiece, FR_SLOTPIECE_LEN( tor ) );
163
164    /* Write progress data */
165    fastResumeWriteData( FR_ID_PROGRESS, buf, 1, FR_PROGRESS_LEN( tor ), file );
166    free( buf );
167
168    /* Write download and upload totals */
169    total = tor->downloadedCur + tor->downloadedPrev;
170    fastResumeWriteData( FR_ID_DOWNLOADED, &total, 8, 1, file );
171    total = tor->uploadedCur + tor->uploadedPrev;
172    fastResumeWriteData( FR_ID_UPLOADED, &total, 8, 1, file );
173
174    /* Write IPs and ports of connectable peers, if any */
175    if( ( size = tr_peerGetConnectable( tor, &buf ) ) > 0 )
176    {
177        fastResumeWriteData( FR_ID_PEERS, buf, size, 1, file );
178        free( buf );
179    }
180
181    fclose( file );
182
183    tr_dbg( "Resume file '%s' written", path );
184    free( path );
185}
186
187static int fastResumeLoadProgress( tr_io_t * io, FILE * file )
188{
189    tr_torrent_t * tor = io->tor;
190    tr_info_t    * inf = &tor->info;
191
192    int     * fileMTimes;
193    int       i, j;
194    uint8_t * buf;
195    size_t    len;
196    tr_bitfield_t bitfield;
197
198    len = FR_PROGRESS_LEN( tor );
199    buf = calloc( len, 1 );
200    if( len != fread( buf, 1, len, file ) )
201    {
202        tr_inf( "Could not read from resume file" );
203        free( buf );
204        return 1;
205    }
206
207    /* Compare file mtimes */
208    fileMTimes = malloc( FR_MTIME_LEN( tor ) );
209    if( fastResumeMTimes( io, fileMTimes ) )
210    {
211        free( buf );
212        free( fileMTimes );
213        return 1;
214    }
215    if( memcmp( fileMTimes, buf, FR_MTIME_LEN( tor ) ) )
216    {
217        tr_inf( "File mtimes don't match" );
218        free( buf );
219        free( fileMTimes );
220        return 1;
221    }
222    free( fileMTimes );
223
224    /* Copy the bitfield for blocks and fill blockHave */
225    memset( &bitfield, 0, sizeof bitfield );
226    bitfield.len = FR_BLOCK_BITFIELD_LEN( tor );
227    bitfield.bits = buf + FR_MTIME_LEN( tor );
228    tr_cpBlockBitfieldSet( tor->completion, &bitfield );
229
230    /* Copy the 'slotPiece' table */
231    memcpy( io->slotPiece, buf + FR_MTIME_LEN( tor ) +
232            FR_BLOCK_BITFIELD_LEN( tor ), FR_SLOTPIECE_LEN( tor ) );
233
234    free( buf );
235
236    /* Update io->pieceSlot, io->slotsUsed, and tor->bitfield */
237    io->slotsUsed = 0;
238    for( i = 0; i < inf->pieceCount; i++ )
239    {
240        io->pieceSlot[i] = -1;
241        for( j = 0; j < inf->pieceCount; j++ )
242        {
243            if( io->slotPiece[j] == i )
244            {
245                // tr_dbg( "Has piece %d in slot %d", i, j );
246                io->pieceSlot[i] = j;
247                io->slotsUsed = MAX( io->slotsUsed, j + 1 );
248                break;
249            }
250        }
251    }
252    // tr_dbg( "Slot used: %d", io->slotsUsed );
253
254    return 0;
255}
256
257static int fastResumeLoadOld( tr_io_t * io, FILE * file )
258{
259    tr_torrent_t * tor = io->tor;
260   
261    int size;
262
263    /* Check the size */
264    size = 4 + FR_PROGRESS_LEN( tor );
265    fseek( file, 0, SEEK_END );
266    if( ftell( file ) != size )
267    {
268        tr_inf( "Wrong size for resume file (%d bytes, %d expected)",
269                (int)ftell( file ), size );
270        fclose( file );
271        return 1;
272    }
273
274    /* load progress information */
275    fseek( file, 4, SEEK_SET );
276    if( fastResumeLoadProgress( io, file ) )
277    {
278        fclose( file );
279        return 1;
280    }
281
282    fclose( file );
283
284    tr_inf( "Fast resuming successful (version 0)" );
285   
286    return 0;
287}
288
289static int fastResumeLoad( tr_io_t * io )
290{
291    tr_torrent_t * tor = io->tor;
292   
293    FILE    * file;
294    int       version = 0;
295    char    * path;
296    uint8_t   id;
297    uint32_t  len;
298    int       ret;
299
300    /* Open resume file */
301    path = fastResumeFileName( io );
302    if( !( file = fopen( path, "r" ) ) )
303    {
304        tr_inf( "Could not open '%s' for reading", path );
305        free( path );
306        return 1;
307    }
308    tr_dbg( "Resume file '%s' loaded", path );
309    free( path );
310
311    /* Check format version */
312    fread( &version, 4, 1, file );
313    if( 0 == version )
314    {
315        return fastResumeLoadOld( io, file );
316    }
317    if( 1 != version )
318    {
319        tr_inf( "Resume file has version %d, not supported", version );
320        fclose( file );
321        return 1;
322    }
323
324    ret = 1;
325    /* read each block of data */
326    while( 1 == fread( &id, 1, 1, file ) && 1 == fread( &len, 4, 1, file ) )
327    {
328        switch( id )
329        {
330            case FR_ID_PROGRESS:
331                /* read progress data */
332                if( (uint32_t)FR_PROGRESS_LEN( tor ) == len )
333                {
334                    if( fastResumeLoadProgress( io, file ) )
335                    {
336                        if( feof( file ) || ferror( file ) )
337                        {
338                            fclose( file );
339                            return 1;
340                        }
341                    }
342                    else
343                    {
344                        ret = 0;
345                    }
346                    continue;
347                }
348                break;
349
350            case FR_ID_DOWNLOADED:
351                /* read download total */
352                if( 8 == len)
353                {
354                    if( 1 != fread( &tor->downloadedPrev, 8, 1, file ) )
355                    {
356                        fclose( file );
357                        return 1;
358                    }
359                    continue;
360                }
361                break;
362
363            case FR_ID_UPLOADED:
364                /* read upload total */
365                if( 8 == len)
366                {
367                    if( 1 != fread( &tor->uploadedPrev, 8, 1, file ) )
368                    {
369                        fclose( file );
370                        return 1;
371                    }
372                    continue;
373                }
374                break;
375
376            case FR_ID_PEERS:
377            {
378                uint8_t * buf = malloc( len );
379                if( 1 != fread( buf, len, 1, file ) )
380                {
381                    free( buf );
382                    fclose( file );
383                    return 1;
384                }
385                tr_torrentAddCompact( tor, TR_PEER_FROM_CACHE, buf, len / 6 );
386                free( buf );
387                continue;
388            }
389
390            default:
391                break;
392        }
393
394        /* if we didn't read the data, seek past it */
395        tr_inf( "Skipping resume data type %02x, %u bytes", id, len );
396        fseek( file, len, SEEK_CUR );
397    }
398
399    fclose( file );
400
401    if( !ret )
402    {
403        tr_inf( "Fast resuming successful" );
404    }
405   
406    return ret;
407}
Note: See TracBrowser for help on using the repository browser.