source: trunk/libtransmission/verify.c @ 9593

Last change on this file since 9593 was 9593, checked in by charles, 12 years ago

(trunk libT) #2610 "avoid unnecessary calls to time(NULL)"

  • Property svn:keywords set to Date Rev Author Id
File size: 9.9 KB
Line 
1/*
2 * This file Copyright (C) 2007-2009 Charles Kerr <charles@transmissionbt.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: verify.c 9593 2009-11-26 18:47:08Z charles $
11 */
12
13#include <unistd.h> /* S_ISREG */
14#include <sys/stat.h>
15
16#ifdef HAVE_POSIX_FADVISE
17 #define _XOPEN_SOURCE 600
18 #include <fcntl.h> /* posix_fadvise() */
19#endif
20
21#include <openssl/sha.h>
22
23#include "transmission.h"
24#include "completion.h"
25#include "fdlimit.h"
26#include "inout.h"
27#include "list.h"
28#include "platform.h"
29#include "torrent.h"
30#include "utils.h" /* tr_buildPath */
31#include "verify.h"
32
33
34/***
35****
36***/
37
38enum
39{
40    MSEC_TO_SLEEP_PER_SECOND_DURING_VERIFY = 200
41};
42
43/* #define STOPWATCH */
44
45static tr_bool
46verifyTorrent( tr_torrent * tor, tr_bool * stopFlag )
47{
48    SHA_CTX sha;
49    int fd = -1;
50    int64_t filePos = 0;
51    tr_bool changed = 0;
52    tr_bool hadPiece = 0;
53    time_t lastSleptAt = 0;
54    uint32_t piecePos = 0;
55    uint32_t pieceBytesRead = 0;
56    tr_file_index_t fileIndex = 0;
57    tr_piece_index_t pieceIndex = 0;
58    const int64_t buflen = tor->info.pieceSize;
59    uint8_t * buffer = tr_new( uint8_t, buflen );
60    const time_t begin = tr_time( );
61    time_t end;
62
63    SHA1_Init( &sha );
64
65    while( !*stopFlag && ( pieceIndex < tor->info.pieceCount ) )
66    {
67        int64_t leftInPiece;
68        int64_t leftInFile;
69        int64_t bytesThisPass;
70        const tr_file * file = &tor->info.files[fileIndex];
71
72        /* if we're starting a new piece... */
73        if( piecePos == 0 )
74        {
75            hadPiece = tr_cpPieceIsComplete( &tor->completion, pieceIndex );
76            /* fprintf( stderr, "starting piece %d of %d\n", (int)pieceIndex, (int)tor->info.pieceCount ); */
77        }
78
79        /* if we're starting a new file... */
80        if( !filePos && (fd<0) )
81        {
82            char * filename = tr_torrentFindFile( tor, fileIndex );
83            fd = filename == NULL ? -1 : tr_open_file_for_scanning( filename );
84            /* fprintf( stderr, "opening file #%d (%s) -- %d\n", fileIndex, filename, fd ); */
85            tr_free( filename );
86        }
87
88        /* figure out how much we can read this pass */
89        leftInPiece = tr_torPieceCountBytes( tor, pieceIndex ) - piecePos;
90        leftInFile = file->length - filePos;
91        bytesThisPass = MIN( leftInFile, leftInPiece );
92        bytesThisPass = MIN( bytesThisPass, buflen );
93        /* fprintf( stderr, "reading this pass: %d\n", (int)bytesThisPass ); */
94
95        /* read a bit */
96        if( (fd>=0) && tr_lseek( fd, filePos, SEEK_SET ) != -1 ) {
97            const int64_t numRead = read( fd, buffer, bytesThisPass );
98            if( numRead > 0 )
99                pieceBytesRead += numRead;
100            if( numRead == bytesThisPass )
101                SHA1_Update( &sha, buffer, numRead );
102        }
103
104        /* move our offsets */
105        leftInPiece -= bytesThisPass;
106        leftInFile -= bytesThisPass;
107        piecePos += bytesThisPass;
108        filePos += bytesThisPass;
109
110        /* if we're finishing a piece... */
111        if( leftInPiece == 0 )
112        {
113            time_t now;
114            tr_bool hasPiece;
115            uint8_t hash[SHA_DIGEST_LENGTH];
116
117            SHA1_Final( hash, &sha );
118            hasPiece = !memcmp( hash, tor->info.pieces[pieceIndex].hash, SHA_DIGEST_LENGTH );
119            /* fprintf( stderr, "do the hashes match? %s\n", (hasPiece?"yes":"no") ); */
120
121            if( hasPiece ) {
122                tr_torrentSetHasPiece( tor, pieceIndex, TRUE );
123                if( !hadPiece )
124                    changed = TRUE;
125            } else if( hadPiece ) {
126                tr_torrentSetHasPiece( tor, pieceIndex, FALSE );
127                changed = TRUE;
128            }
129            tr_torrentSetPieceChecked( tor, pieceIndex, TRUE );
130            now = tr_time( );
131            tor->anyDate = now;
132
133            /* sleeping even just a few msec per second goes a long
134             * way towards reducing IO load... */
135            if( lastSleptAt != now ) {
136                lastSleptAt = now;
137                tr_wait( MSEC_TO_SLEEP_PER_SECOND_DURING_VERIFY );
138            }
139
140            SHA1_Init( &sha );
141            ++pieceIndex;
142            piecePos = 0;
143            pieceBytesRead = 0;
144        }
145
146        /* if we're finishing a file... */
147        if( leftInFile == 0 )
148        {
149            /* fprintf( stderr, "closing file\n" ); */
150            if( fd >= 0 ) { tr_close_file( fd ); fd = -1; }
151            ++fileIndex;
152            filePos = 0;
153        }
154    }
155
156    /* cleanup */
157    if( fd >= 0 )
158        tr_close_file( fd );
159    tr_free( buffer );
160
161    /* stopwatch */
162    end = tr_time( );
163    tr_tordbg( tor, "it took %d seconds to verify %"PRIu64" bytes (%"PRIu64" bytes per second)",
164               (int)(end-begin), tor->info.totalSize, (uint64_t)(tor->info.totalSize/(1+(end-begin))) );
165
166    return changed;
167}
168
169/***
170****
171***/
172
173struct verify_node
174{
175    tr_torrent *         torrent;
176    tr_verify_done_cb    verify_done_cb;
177};
178
179static void
180fireCheckDone( tr_torrent * tor, tr_verify_done_cb verify_done_cb )
181{
182    assert( tr_isTorrent( tor ) );
183
184    if( verify_done_cb )
185        verify_done_cb( tor );
186}
187
188static struct verify_node currentNode;
189static tr_list * verifyList = NULL;
190static tr_thread * verifyThread = NULL;
191static tr_bool stopCurrent = FALSE;
192
193static tr_lock*
194getVerifyLock( void )
195{
196    static tr_lock * lock = NULL;
197
198    if( lock == NULL )
199        lock = tr_lockNew( );
200    return lock;
201}
202
203static void
204verifyThreadFunc( void * unused UNUSED )
205{
206    for( ;; )
207    {
208        int                  changed = 0;
209        tr_torrent         * tor;
210        struct verify_node * node;
211
212        tr_lockLock( getVerifyLock( ) );
213        stopCurrent = FALSE;
214        node = (struct verify_node*) verifyList ? verifyList->data : NULL;
215        if( node == NULL )
216        {
217            currentNode.torrent = NULL;
218            break;
219        }
220
221        currentNode = *node;
222        tor = currentNode.torrent;
223        tr_list_remove_data( &verifyList, node );
224        tr_free( node );
225        tr_lockUnlock( getVerifyLock( ) );
226
227        tr_torinf( tor, "%s", _( "Verifying torrent" ) );
228        tr_torrentSetVerifyState( tor, TR_VERIFY_NOW );
229        changed = verifyTorrent( tor, &stopCurrent );
230        tr_torrentSetVerifyState( tor, TR_VERIFY_NONE );
231        assert( tr_isTorrent( tor ) );
232
233        if( !stopCurrent )
234        {
235            if( changed )
236                tr_torrentSetDirty( tor );
237            fireCheckDone( tor, currentNode.verify_done_cb );
238        }
239    }
240
241    verifyThread = NULL;
242    tr_lockUnlock( getVerifyLock( ) );
243}
244
245static tr_bool
246torrentHasAnyLocalData( const tr_torrent * tor )
247{
248    tr_file_index_t i;
249    tr_bool hasAny = FALSE;
250    const tr_file_index_t n = tor->info.fileCount;
251
252    assert( tr_isTorrent( tor ) );
253
254    for( i=0; i<n && !hasAny; ++i )
255    {
256        struct stat sb;
257        char * path = tr_torrentFindFile( tor, i );
258        if( ( path != NULL ) && !stat( path, &sb ) && ( sb.st_size > 0 ) )
259            hasAny = TRUE;
260        tr_free( path );
261    }
262
263    return hasAny;
264}
265
266void
267tr_verifyAdd( tr_torrent *      tor,
268              tr_verify_done_cb verify_done_cb )
269{
270    assert( tr_isTorrent( tor ) );
271
272    if( tr_torrentCountUncheckedPieces( tor ) == 0 )
273    {
274        /* doesn't need to be checked... */
275        fireCheckDone( tor, verify_done_cb );
276    }
277    else if( !torrentHasAnyLocalData( tor ) )
278    {
279        /* we haven't downloaded anything for this torrent yet...
280         * no need to leave it waiting in the back of the queue.
281         * we can mark it as all-missing from here and fire
282         * the "done" callback */
283        const tr_bool hadAny = tr_cpHaveTotal( &tor->completion ) != 0;
284        tr_piece_index_t i;
285        for( i=0; i<tor->info.pieceCount; ++i ) {
286            tr_torrentSetHasPiece( tor, i, FALSE );
287            tr_torrentSetPieceChecked( tor, i, TRUE );
288        }
289        if( hadAny ) /* if we thought we had some, flag as dirty */
290            tr_torrentSetDirty( tor );
291        fireCheckDone( tor, verify_done_cb );
292    }
293    else
294    {
295        struct verify_node * node;
296
297        tr_torinf( tor, "%s", _( "Queued for verification" ) );
298
299        node = tr_new( struct verify_node, 1 );
300        node->torrent = tor;
301        node->verify_done_cb = verify_done_cb;
302
303        tr_lockLock( getVerifyLock( ) );
304        tr_torrentSetVerifyState( tor, TR_VERIFY_WAIT );
305        tr_list_append( &verifyList, node );
306        if( verifyThread == NULL )
307            verifyThread = tr_threadNew( verifyThreadFunc, NULL );
308        tr_lockUnlock( getVerifyLock( ) );
309    }
310}
311
312static int
313compareVerifyByTorrent( const void * va,
314                        const void * vb )
315{
316    const struct verify_node * a = va;
317    const tr_torrent *         b = vb;
318
319    return a->torrent - b;
320}
321
322tr_bool
323tr_verifyInProgress( const tr_torrent * tor )
324{
325    tr_bool found = FALSE;
326    tr_lock * lock = getVerifyLock( );
327    tr_lockLock( lock );
328
329    assert( tr_isTorrent( tor ) );
330
331    found = ( tor == currentNode.torrent )
332         || ( tr_list_find( verifyList, tor, compareVerifyByTorrent ) != NULL );
333
334    tr_lockUnlock( lock );
335    return found;
336}
337
338void
339tr_verifyRemove( tr_torrent * tor )
340{
341    tr_lock * lock = getVerifyLock( );
342    tr_lockLock( lock );
343
344    assert( tr_isTorrent( tor ) );
345
346    if( tor == currentNode.torrent )
347    {
348        stopCurrent = TRUE;
349        while( stopCurrent )
350        {
351            tr_lockUnlock( lock );
352            tr_wait( 100 );
353            tr_lockLock( lock );
354        }
355    }
356    else
357    {
358        tr_free( tr_list_remove( &verifyList, tor, compareVerifyByTorrent ) );
359        tr_torrentSetVerifyState( tor, TR_VERIFY_NONE );
360    }
361
362    tr_lockUnlock( lock );
363}
364
365void
366tr_verifyClose( tr_session * session UNUSED )
367{
368    tr_lockLock( getVerifyLock( ) );
369
370    stopCurrent = TRUE;
371    tr_list_free( &verifyList, tr_free );
372
373    tr_lockUnlock( getVerifyLock( ) );
374}
Note: See TracBrowser for help on using the repository browser.