source: branches/pex/libtransmission/fastresume.h @ 1540

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

Implement Azureus peer protocol, including PEX message.
Implement extended messages, including uTorrent PEX.

  • Property svn:keywords set to Date Rev Author Id
File size: 11.4 KB
Line 
1/******************************************************************************
2 * $Id: fastresume.h 1540 2007-03-08 04:06:58Z 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
132    buf = malloc( FR_PROGRESS_LEN( tor ) );
133
134    /* Get file sizes */
135    if( fastResumeMTimes( io, (int*)buf ) )
136    {
137        free( buf );
138        return;
139    }
140
141    /* Create/overwrite the resume file */
142    path = fastResumeFileName( io );
143    if( !( file = fopen( path, "w" ) ) )
144    {
145        tr_err( "Could not open '%s' for writing", path );
146        free( buf );
147        free( path );
148        return;
149    }
150   
151    /* Write format version */
152    fwrite( &version, 4, 1, file );
153
154    /* Build and copy the bitfield for blocks */
155    memcpy(buf + FR_MTIME_LEN( tor ), tr_cpBlockBitfield( tor->completion ),
156           FR_BLOCK_BITFIELD_LEN( tor ) );
157
158    /* Copy the 'slotPiece' table */
159    memcpy(buf + FR_MTIME_LEN( tor ) + FR_BLOCK_BITFIELD_LEN( tor ),
160           io->slotPiece, FR_SLOTPIECE_LEN( tor ) );
161
162    /* Write progress data */
163    fastResumeWriteData( FR_ID_PROGRESS, buf, 1, FR_PROGRESS_LEN( tor ), file );
164    free( buf );
165
166    /* Write download and upload totals */
167    total = tor->downloadedCur + tor->downloadedPrev;
168    fastResumeWriteData( FR_ID_DOWNLOADED, &total, 8, 1, file );
169    total = tor->uploadedCur + tor->uploadedPrev;
170    fastResumeWriteData( FR_ID_UPLOADED, &total, 8, 1, file );
171
172    /* Write IPs and ports of connectable peers, if any */
173    if( ( size = tr_peerGetConnectable( tor, &buf ) ) > 0 )
174    {
175        fastResumeWriteData( FR_ID_PEERS, buf, size, 1, file );
176        free( buf );
177    }
178
179    fclose( file );
180
181    tr_dbg( "Resume file '%s' written", path );
182    free( path );
183}
184
185static int fastResumeLoadProgress( tr_io_t * io, FILE * file )
186{
187    tr_torrent_t * tor = io->tor;
188    tr_info_t    * inf = &tor->info;
189
190    int     * fileMTimes;
191    int       i, j;
192    uint8_t * buf;
193    size_t    len;
194    tr_bitfield_t bitfield;
195
196    len = FR_PROGRESS_LEN( tor );
197    buf = calloc( len, 1 );
198    if( len != fread( buf, 1, len, file ) )
199    {
200        tr_inf( "Could not read from resume file" );
201        free( buf );
202        return 1;
203    }
204
205    /* Compare file mtimes */
206    fileMTimes = malloc( FR_MTIME_LEN( tor ) );
207    if( fastResumeMTimes( io, fileMTimes ) )
208    {
209        free( buf );
210        free( fileMTimes );
211        return 1;
212    }
213    if( memcmp( fileMTimes, buf, FR_MTIME_LEN( tor ) ) )
214    {
215        tr_inf( "File mtimes don't match" );
216        free( buf );
217        free( fileMTimes );
218        return 1;
219    }
220    free( fileMTimes );
221
222    /* Copy the bitfield for blocks and fill blockHave */
223    memset( &bitfield, 0, sizeof bitfield );
224    bitfield.len = FR_BLOCK_BITFIELD_LEN( tor );
225    bitfield.bits = buf + FR_MTIME_LEN( tor );
226    tr_cpBlockBitfieldSet( tor->completion, &bitfield );
227
228    /* Copy the 'slotPiece' table */
229    memcpy( io->slotPiece, buf + FR_MTIME_LEN( tor ) +
230            FR_BLOCK_BITFIELD_LEN( tor ), FR_SLOTPIECE_LEN( tor ) );
231
232    free( buf );
233
234    /* Update io->pieceSlot, io->slotsUsed, and tor->bitfield */
235    io->slotsUsed = 0;
236    for( i = 0; i < inf->pieceCount; i++ )
237    {
238        io->pieceSlot[i] = -1;
239        for( j = 0; j < inf->pieceCount; j++ )
240        {
241            if( io->slotPiece[j] == i )
242            {
243                // tr_dbg( "Has piece %d in slot %d", i, j );
244                io->pieceSlot[i] = j;
245                io->slotsUsed = MAX( io->slotsUsed, j + 1 );
246                break;
247            }
248        }
249    }
250    // tr_dbg( "Slot used: %d", io->slotsUsed );
251
252    return 0;
253}
254
255static int fastResumeLoadOld( tr_io_t * io, FILE * file )
256{
257    tr_torrent_t * tor = io->tor;
258   
259    int size;
260
261    /* Check the size */
262    size = 4 + FR_PROGRESS_LEN( tor );
263    fseek( file, 0, SEEK_END );
264    if( ftell( file ) != size )
265    {
266        tr_inf( "Wrong size for resume file (%d bytes, %d expected)",
267                (int)ftell( file ), size );
268        fclose( file );
269        return 1;
270    }
271
272    /* load progress information */
273    fseek( file, 4, SEEK_SET );
274    if( fastResumeLoadProgress( io, file ) )
275    {
276        fclose( file );
277        return 1;
278    }
279
280    fclose( file );
281
282    tr_inf( "Fast resuming successful (version 0)" );
283   
284    return 0;
285}
286
287static int fastResumeLoad( tr_io_t * io )
288{
289    tr_torrent_t * tor = io->tor;
290   
291    FILE    * file;
292    int       version = 0;
293    char    * path;
294    uint8_t   id;
295    uint32_t  len;
296    int       ret;
297
298    /* Open resume file */
299    path = fastResumeFileName( io );
300    if( !( file = fopen( path, "r" ) ) )
301    {
302        tr_inf( "Could not open '%s' for reading", path );
303        free( path );
304        return 1;
305    }
306    tr_dbg( "Resume file '%s' loaded", path );
307    free( path );
308
309    /* Check format version */
310    fread( &version, 4, 1, file );
311    if( 0 == version )
312    {
313        return fastResumeLoadOld( io, file );
314    }
315    if( 1 != version )
316    {
317        tr_inf( "Resume file has version %d, not supported", version );
318        fclose( file );
319        return 1;
320    }
321
322    ret = 1;
323    /* read each block of data */
324    while( 1 == fread( &id, 1, 1, file ) && 1 == fread( &len, 4, 1, file ) )
325    {
326        switch( id )
327        {
328            case FR_ID_PROGRESS:
329                /* read progress data */
330                if( (uint32_t)FR_PROGRESS_LEN( tor ) == len )
331                {
332                    if( fastResumeLoadProgress( io, file ) )
333                    {
334                        if( feof( file ) || ferror( file ) )
335                        {
336                            fclose( file );
337                            return 1;
338                        }
339                    }
340                    else
341                    {
342                        ret = 0;
343                    }
344                    continue;
345                }
346                break;
347
348            case FR_ID_DOWNLOADED:
349                /* read download total */
350                if( 8 == len)
351                {
352                    if( 1 != fread( &tor->downloadedPrev, 8, 1, file ) )
353                    {
354                        fclose( file );
355                        return 1;
356                    }
357                    continue;
358                }
359                break;
360
361            case FR_ID_UPLOADED:
362                /* read upload total */
363                if( 8 == len)
364                {
365                    if( 1 != fread( &tor->uploadedPrev, 8, 1, file ) )
366                    {
367                        fclose( file );
368                        return 1;
369                    }
370                    continue;
371                }
372                break;
373
374            case FR_ID_PEERS:
375            {
376                uint8_t * buf = malloc( len );
377                if( 1 != fread( buf, len, 1, file ) )
378                {
379                    free( buf );
380                    fclose( file );
381                    return 1;
382                }
383                tr_torrentAddCompact( tor, TR_PEER_FROM_CACHE, buf, len / 6 );
384                free( buf );
385                continue;
386            }
387
388            default:
389                break;
390        }
391
392        /* if we didn't read the data, seek past it */
393        tr_inf( "Skipping resume data type %02x, %u bytes", id, len );
394        fseek( file, len, SEEK_CUR );
395    }
396
397    fclose( file );
398
399    if( !ret )
400    {
401        tr_inf( "Fast resuming successful" );
402    }
403   
404    return ret;
405}
Note: See TracBrowser for help on using the repository browser.