source: trunk/libtransmission/fastresume.h @ 1060

Last change on this file since 1060 was 1060, checked in by titer, 15 years ago

Saves a list of peers when you pause a torrent, and tries to reconnect to them next time you resume it

  • Property svn:keywords set to Date Rev Author Id
File size: 11.3 KB
Line 
1/******************************************************************************
2 * $Id: fastresume.h 1060 2006-11-09 04:45:14Z titer $
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/***********************************************************************
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            tr_err( "Could not stat '%s'", path );
91            free( path );
92            return 1;
93        }
94        if( ( sb.st_mode & S_IFMT ) != S_IFREG )
95        {
96            tr_err( "Wrong st_mode for '%s'", path );
97            free( path );
98            return 1;
99        }
100        free( path );
101
102#ifdef SYS_DARWIN
103        tab[i] = ( sb.st_mtimespec.tv_sec & 0x7FFFFFFF );
104#else
105        tab[i] = ( sb.st_mtime & 0x7FFFFFFF );
106#endif
107    }
108
109    return 0;
110}
111
112static inline void fastResumeWriteData( uint8_t id, void * data, uint32_t size,
113                                        uint32_t count, FILE * file )
114{
115    uint32_t  datalen = size * count;
116
117    fwrite( &id, 1, 1, file );
118    fwrite( &datalen, 4, 1, file );
119    fwrite( data, size, count, file );
120}
121
122static void fastResumeSave( tr_io_t * io )
123{
124    tr_torrent_t * tor = io->tor;
125   
126    FILE    * file;
127    int       version = 1;
128    char    * path;
129    uint8_t * buf;
130    uint64_t  total;
131    int       size;
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    memcpy(buf + FR_MTIME_LEN( tor ), tr_cpBlockBitfield( tor->completion ),
157           FR_BLOCK_BITFIELD_LEN( tor ) );
158
159    /* Copy the 'slotPiece' table */
160    memcpy(buf + FR_MTIME_LEN( tor ) + FR_BLOCK_BITFIELD_LEN( tor ),
161           io->slotPiece, FR_SLOTPIECE_LEN( tor ) );
162
163    /* Write progress data */
164    fastResumeWriteData( FR_ID_PROGRESS, buf, 1, FR_PROGRESS_LEN( tor ), file );
165    free( buf );
166
167    /* Write download and upload totals */
168    total = tor->downloadedCur + tor->downloadedPrev;
169    fastResumeWriteData( FR_ID_DOWNLOADED, &total, 8, 1, file );
170    total = tor->uploadedCur + tor->uploadedPrev;
171    fastResumeWriteData( FR_ID_UPLOADED, &total, 8, 1, file );
172
173    /* Write IPs and ports of connectable peers, if any */
174    if( ( size = tr_peerGetConnectable( tor, &buf ) ) > 0 )
175    {
176        fastResumeWriteData( FR_ID_PEERS, buf, size, 1, file );
177        free( buf );
178    }
179
180    fclose( file );
181
182    tr_dbg( "Resume file '%s' written", path );
183    free( path );
184}
185
186static int fastResumeLoadProgress( tr_io_t * io, FILE * file )
187{
188    tr_torrent_t * tor = io->tor;
189    tr_info_t    * inf = &tor->info;
190
191    int     * fileMTimes;
192    int       i, j;
193    uint8_t * buf;
194    size_t    len;
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    tr_cpBlockBitfieldSet( tor->completion, buf + FR_MTIME_LEN( tor ) );
224
225    /* Copy the 'slotPiece' table */
226    memcpy( io->slotPiece, buf + FR_MTIME_LEN( tor ) +
227            FR_BLOCK_BITFIELD_LEN( tor ), FR_SLOTPIECE_LEN( tor ) );
228
229    free( buf );
230
231    /* Update io->pieceSlot, io->slotsUsed, and tor->bitfield */
232    io->slotsUsed = 0;
233    for( i = 0; i < inf->pieceCount; i++ )
234    {
235        io->pieceSlot[i] = -1;
236        for( j = 0; j < inf->pieceCount; j++ )
237        {
238            if( io->slotPiece[j] == i )
239            {
240                // tr_dbg( "Has piece %d in slot %d", i, j );
241                io->pieceSlot[i] = j;
242                io->slotsUsed = MAX( io->slotsUsed, j + 1 );
243                break;
244            }
245        }
246    }
247    // tr_dbg( "Slot used: %d", io->slotsUsed );
248
249    return 0;
250}
251
252static int fastResumeLoadOld( tr_io_t * io, FILE * file )
253{
254    tr_torrent_t * tor = io->tor;
255   
256    int size;
257
258    /* Check the size */
259    size = 4 + FR_PROGRESS_LEN( tor );
260    fseek( file, 0, SEEK_END );
261    if( ftell( file ) != size )
262    {
263        tr_inf( "Wrong size for resume file (%d bytes, %d expected)",
264                (int)ftell( file ), size );
265        fclose( file );
266        return 1;
267    }
268
269    /* load progress information */
270    fseek( file, 4, SEEK_SET );
271    if( fastResumeLoadProgress( io, file ) )
272    {
273        fclose( file );
274        return 1;
275    }
276
277    fclose( file );
278
279    tr_inf( "Fast resuming successful (version 0)" );
280   
281    return 0;
282}
283
284static int fastResumeLoad( tr_io_t * io )
285{
286    tr_torrent_t * tor = io->tor;
287   
288    FILE    * file;
289    int       version = 0;
290    char    * path;
291    uint8_t   id;
292    uint32_t  len;
293    int       ret;
294
295    /* Open resume file */
296    path = fastResumeFileName( io );
297    if( !( file = fopen( path, "r" ) ) )
298    {
299        tr_inf( "Could not open '%s' for reading", path );
300        free( path );
301        return 1;
302    }
303    tr_dbg( "Resume file '%s' loaded", path );
304    free( path );
305
306    /* Check format version */
307    fread( &version, 4, 1, file );
308    if( 0 == version )
309    {
310        return fastResumeLoadOld( io, file );
311    }
312    if( 1 != version )
313    {
314        tr_inf( "Resume file has version %d, not supported", version );
315        fclose( file );
316        return 1;
317    }
318
319    ret = 1;
320    /* read each block of data */
321    while( 1 == fread( &id, 1, 1, file ) && 1 == fread( &len, 4, 1, file ) )
322    {
323        switch( id )
324        {
325            case FR_ID_PROGRESS:
326                /* read progress data */
327                if( (uint32_t)FR_PROGRESS_LEN( tor ) == len )
328                {
329                    if( fastResumeLoadProgress( io, file ) )
330                    {
331                        if( feof( file ) || ferror( file ) )
332                        {
333                            fclose( file );
334                            return 1;
335                        }
336                    }
337                    else
338                    {
339                        ret = 0;
340                    }
341                    continue;
342                }
343                break;
344
345            case FR_ID_DOWNLOADED:
346                /* read download total */
347                if( 8 == len)
348                {
349                    if( 1 != fread( &tor->downloadedPrev, 8, 1, file ) )
350                    {
351                        fclose( file );
352                        return 1;
353                    }
354                    continue;
355                }
356                break;
357
358            case FR_ID_UPLOADED:
359                /* read upload total */
360                if( 8 == len)
361                {
362                    if( 1 != fread( &tor->uploadedPrev, 8, 1, file ) )
363                    {
364                        fclose( file );
365                        return 1;
366                    }
367                    continue;
368                }
369                break;
370
371            case FR_ID_PEERS:
372            {
373                uint8_t * buf = malloc( len );
374                if( 1 != fread( buf, len, 1, file ) )
375                {
376                    free( buf );
377                    fclose( file );
378                    return 1;
379                }
380                tr_peerAddCompactMany( tor, buf, len );
381                free( buf );
382                continue;
383            }
384
385            default:
386                break;
387        }
388
389        /* if we didn't read the data, seek past it */
390        tr_inf( "Skipping resume data type %02x, %u bytes", id, len );
391        fseek( file, len, SEEK_CUR );
392    }
393
394    fclose( file );
395
396    if( !ret )
397    {
398        tr_inf( "Fast resuming successful" );
399    }
400   
401    return ret;
402}
Note: See TracBrowser for help on using the repository browser.