source: trunk/libtransmission/torrent.c @ 13762

Last change on this file since 13762 was 13762, checked in by jordan, 8 years ago

(libT) #4633 fix win32 regression introduced in r13752.

  • Property svn:keywords set to Date Rev Author Id
File size: 84.6 KB
Line 
1/*
2 * This file Copyright (C) Mnemosyne LLC
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: torrent.c 13762 2013-01-04 19:47:01Z jordan $
11 */
12
13#include <signal.h> /* signal () */
14#include <sys/types.h> /* stat */
15#include <sys/stat.h> /* stat */
16#ifndef WIN32
17 #include <sys/wait.h> /* wait () */
18#else
19 #include <process.h>
20 #define waitpid(pid, status, options)  _cwait (status, pid, WAIT_CHILD)
21#endif
22#include <unistd.h> /* stat */
23#include <dirent.h>
24
25#include <assert.h>
26#include <math.h>
27#include <stdarg.h>
28#include <string.h> /* memcmp */
29#include <stdlib.h> /* qsort */
30#include <stdio.h> /* remove () */
31
32#include <event2/util.h> /* evutil_vsnprintf () */
33
34#include "transmission.h"
35#include "announcer.h"
36#include "bandwidth.h"
37#include "cache.h"
38#include "completion.h"
39#include "crypto.h" /* for tr_sha1 */
40#include "resume.h"
41#include "fdlimit.h" /* tr_fdTorrentClose */
42#include "inout.h" /* tr_ioTestPiece () */
43#include "magnet.h"
44#include "metainfo.h"
45#include "peer-common.h" /* MAX_BLOCK_SIZE */
46#include "peer-mgr.h"
47#include "platform.h" /* TR_PATH_DELIMITER_STR */
48#include "ptrarray.h"
49#include "session.h"
50#include "torrent.h"
51#include "torrent-magnet.h"
52#include "trevent.h" /* tr_runInEventThread () */
53#include "utils.h"
54#include "variant.h"
55#include "verify.h"
56#include "version.h"
57
58/***
59****
60***/
61
62#define tr_deeplog_tor(tor, ...) \
63  do \
64    { \
65      if (tr_deepLoggingIsActive ()) \
66        tr_deepLog (__FILE__, __LINE__, tr_torrentName (tor), __VA_ARGS__); \
67    } \
68  while (0)
69
70/***
71****
72***/
73
74const char *
75tr_torrentName (const tr_torrent * tor)
76{
77    assert (tr_isTorrent (tor));
78
79    return tor->info.name;
80}
81
82int
83tr_torrentId (const tr_torrent * tor)
84{
85    return tor->uniqueId;
86}
87
88tr_torrent*
89tr_torrentFindFromId (tr_session * session, int id)
90{
91    tr_torrent * tor = NULL;
92
93    while ((tor = tr_torrentNext (session, tor)))
94        if (tor->uniqueId == id)
95            return tor;
96
97    return NULL;
98}
99
100tr_torrent*
101tr_torrentFindFromHashString (tr_session *  session, const char * str)
102{
103    tr_torrent * tor = NULL;
104
105    while ((tor = tr_torrentNext (session, tor)))
106        if (!evutil_ascii_strcasecmp (str, tor->info.hashString))
107            return tor;
108
109    return NULL;
110}
111
112tr_torrent*
113tr_torrentFindFromHash (tr_session * session, const uint8_t * torrentHash)
114{
115    tr_torrent * tor = NULL;
116
117    while ((tor = tr_torrentNext (session, tor)))
118        if (*tor->info.hash == *torrentHash)
119            if (!memcmp (tor->info.hash, torrentHash, SHA_DIGEST_LENGTH))
120                return tor;
121
122    return NULL;
123}
124
125tr_torrent*
126tr_torrentFindFromMagnetLink (tr_session * session, const char * magnet)
127{
128    tr_magnet_info * info;
129    tr_torrent * tor = NULL;
130
131    if ((info = tr_magnetParse (magnet)))
132    {
133        tor = tr_torrentFindFromHash (session, info->hash);
134        tr_magnetFree (info);
135    }
136
137    return tor;
138}
139
140tr_torrent*
141tr_torrentFindFromObfuscatedHash (tr_session * session,
142                                  const uint8_t * obfuscatedTorrentHash)
143{
144    tr_torrent * tor = NULL;
145
146    while ((tor = tr_torrentNext (session, tor)))
147        if (!memcmp (tor->obfuscatedHash, obfuscatedTorrentHash,
148                     SHA_DIGEST_LENGTH))
149            return tor;
150
151    return NULL;
152}
153
154bool
155tr_torrentIsPieceTransferAllowed (const tr_torrent  * tor,
156                                  tr_direction        direction)
157{
158  bool allowed = true;
159  unsigned int limit;
160
161  assert (tr_isTorrent (tor));
162  assert (tr_isDirection (direction));
163
164  if (tr_torrentUsesSpeedLimit (tor, direction))
165    if (tr_torrentGetSpeedLimit_Bps (tor, direction) <= 0)
166      allowed = false;
167
168  if (tr_torrentUsesSessionLimits (tor))
169    if (tr_sessionGetActiveSpeedLimit_Bps (tor->session, direction, &limit))
170      if (limit <= 0)
171        allowed = false;
172
173  return allowed;
174}
175
176/***
177****  PER-TORRENT UL / DL SPEEDS
178***/
179
180void
181tr_torrentSetSpeedLimit_Bps (tr_torrent * tor, tr_direction dir, unsigned int Bps)
182{
183    assert (tr_isTorrent (tor));
184    assert (tr_isDirection (dir));
185
186    if (tr_bandwidthSetDesiredSpeed_Bps (&tor->bandwidth, dir, Bps))
187        tr_torrentSetDirty (tor);
188}
189void
190tr_torrentSetSpeedLimit_KBps (tr_torrent * tor, tr_direction dir, unsigned int KBps)
191{
192    tr_torrentSetSpeedLimit_Bps (tor, dir, toSpeedBytes (KBps));
193}
194
195unsigned int
196tr_torrentGetSpeedLimit_Bps (const tr_torrent * tor, tr_direction dir)
197{
198    assert (tr_isTorrent (tor));
199    assert (tr_isDirection (dir));
200
201    return tr_bandwidthGetDesiredSpeed_Bps (&tor->bandwidth, dir);
202}
203unsigned int
204tr_torrentGetSpeedLimit_KBps (const tr_torrent * tor, tr_direction dir)
205{
206  assert (tr_isTorrent (tor));
207  assert (tr_isDirection (dir));
208
209  return toSpeedKBps (tr_torrentGetSpeedLimit_Bps (tor, dir));
210}
211
212void
213tr_torrentUseSpeedLimit (tr_torrent * tor, tr_direction dir, bool do_use)
214{
215  assert (tr_isTorrent (tor));
216  assert (tr_isDirection (dir));
217
218  if (tr_bandwidthSetLimited (&tor->bandwidth, dir, do_use))
219    tr_torrentSetDirty (tor);
220}
221
222bool
223tr_torrentUsesSpeedLimit (const tr_torrent * tor, tr_direction dir)
224{
225  assert (tr_isTorrent (tor));
226
227  return tr_bandwidthIsLimited (&tor->bandwidth, dir);
228}
229
230void
231tr_torrentUseSessionLimits (tr_torrent * tor, bool doUse)
232{
233  bool changed;
234
235  assert (tr_isTorrent (tor));
236
237  changed = tr_bandwidthHonorParentLimits (&tor->bandwidth, TR_UP, doUse);
238  changed |= tr_bandwidthHonorParentLimits (&tor->bandwidth, TR_DOWN, doUse);
239
240  if (changed)
241    tr_torrentSetDirty (tor);
242}
243
244bool
245tr_torrentUsesSessionLimits (const tr_torrent * tor)
246{
247  assert (tr_isTorrent (tor));
248
249  return tr_bandwidthAreParentLimitsHonored (&tor->bandwidth, TR_UP);
250}
251
252/***
253****
254***/
255
256void
257tr_torrentSetRatioMode (tr_torrent *  tor, tr_ratiolimit mode)
258{
259  assert (tr_isTorrent (tor));
260  assert (mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED);
261
262  if (mode != tor->ratioLimitMode)
263    {
264      tor->ratioLimitMode = mode;
265
266      tr_torrentSetDirty (tor);
267    }
268}
269
270tr_ratiolimit
271tr_torrentGetRatioMode (const tr_torrent * tor)
272{
273  assert (tr_isTorrent (tor));
274
275  return tor->ratioLimitMode;
276}
277
278void
279tr_torrentSetRatioLimit (tr_torrent * tor, double desiredRatio)
280{
281  assert (tr_isTorrent (tor));
282
283  if ((int)(desiredRatio*100.0) != (int)(tor->desiredRatio*100.0))
284    {
285      tor->desiredRatio = desiredRatio;
286
287      tr_torrentSetDirty (tor);
288    }
289}
290
291double
292tr_torrentGetRatioLimit (const tr_torrent * tor)
293{
294  assert (tr_isTorrent (tor));
295
296  return tor->desiredRatio;
297}
298
299bool
300tr_torrentGetSeedRatio (const tr_torrent * tor, double * ratio)
301{
302  bool isLimited;
303
304  assert (tr_isTorrent (tor));
305
306  switch (tr_torrentGetRatioMode (tor))
307    {
308      case TR_RATIOLIMIT_SINGLE:
309        isLimited = true;
310        if (ratio)
311          *ratio = tr_torrentGetRatioLimit (tor);
312        break;
313
314      case TR_RATIOLIMIT_GLOBAL:
315        isLimited = tr_sessionIsRatioLimited (tor->session);
316        if (isLimited && ratio)
317          *ratio = tr_sessionGetRatioLimit (tor->session);
318        break;
319
320      default: /* TR_RATIOLIMIT_UNLIMITED */
321        isLimited = false;
322        break;
323    }
324
325  return isLimited;
326}
327
328/* returns true if the seed ratio applies --
329 * it applies if the torrent's a seed AND it has a seed ratio set */
330static bool
331tr_torrentGetSeedRatioBytes (const tr_torrent  * tor,
332                             uint64_t          * setmeLeft,
333                             uint64_t          * setmeGoal)
334{
335  double seedRatio;
336  bool seedRatioApplies = false;
337
338  assert (tr_isTorrent (tor));
339
340  if (tr_torrentGetSeedRatio (tor, &seedRatio))
341    {
342      const uint64_t u = tor->uploadedCur + tor->uploadedPrev;
343      const uint64_t d = tor->downloadedCur + tor->downloadedPrev;
344      const uint64_t baseline = d ? d : tr_cpSizeWhenDone (&tor->completion);
345      const uint64_t goal = baseline * seedRatio;
346      if (setmeLeft) *setmeLeft = goal > u ? goal - u : 0;
347      if (setmeGoal) *setmeGoal = goal;
348      seedRatioApplies = tr_torrentIsSeed (tor);
349    }
350
351  return seedRatioApplies;
352}
353
354static bool
355tr_torrentIsSeedRatioDone (const tr_torrent * tor)
356{
357    uint64_t bytesLeft;
358    return tr_torrentGetSeedRatioBytes (tor, &bytesLeft, NULL) && !bytesLeft;
359}
360
361/***
362****
363***/
364
365void
366tr_torrentSetIdleMode (tr_torrent *  tor, tr_idlelimit mode)
367{
368    assert (tr_isTorrent (tor));
369    assert (mode==TR_IDLELIMIT_GLOBAL || mode==TR_IDLELIMIT_SINGLE || mode==TR_IDLELIMIT_UNLIMITED);
370
371    if (mode != tor->idleLimitMode)
372    {
373        tor->idleLimitMode = mode;
374
375        tr_torrentSetDirty (tor);
376    }
377}
378
379tr_idlelimit
380tr_torrentGetIdleMode (const tr_torrent * tor)
381{
382    assert (tr_isTorrent (tor));
383
384    return tor->idleLimitMode;
385}
386
387void
388tr_torrentSetIdleLimit (tr_torrent * tor, uint16_t idleMinutes)
389{
390    assert (tr_isTorrent (tor));
391
392    if (idleMinutes > 0)
393    {
394        tor->idleLimitMinutes = idleMinutes;
395
396        tr_torrentSetDirty (tor);
397    }
398}
399
400uint16_t
401tr_torrentGetIdleLimit (const tr_torrent * tor)
402{
403    assert (tr_isTorrent (tor));
404
405    return tor->idleLimitMinutes;
406}
407
408bool
409tr_torrentGetSeedIdle (const tr_torrent * tor, uint16_t * idleMinutes)
410{
411    bool isLimited;
412
413    switch (tr_torrentGetIdleMode (tor))
414    {
415        case TR_IDLELIMIT_SINGLE:
416            isLimited = true;
417            if (idleMinutes)
418                *idleMinutes = tr_torrentGetIdleLimit (tor);
419            break;
420
421        case TR_IDLELIMIT_GLOBAL:
422            isLimited = tr_sessionIsIdleLimited (tor->session);
423            if (isLimited && idleMinutes)
424                *idleMinutes = tr_sessionGetIdleLimit (tor->session);
425            break;
426
427        default: /* TR_IDLELIMIT_UNLIMITED */
428            isLimited = false;
429            break;
430    }
431
432    return isLimited;
433}
434
435static bool
436tr_torrentIsSeedIdleLimitDone (tr_torrent * tor)
437{
438    uint16_t idleMinutes;
439    return tr_torrentGetSeedIdle (tor, &idleMinutes)
440        && difftime (tr_time (), MAX (tor->startDate, tor->activityDate)) >= idleMinutes * 60u;
441}
442
443/***
444****
445***/
446
447void
448tr_torrentCheckSeedLimit (tr_torrent * tor)
449{
450    assert (tr_isTorrent (tor));
451
452    if (!tor->isRunning || tor->isStopping || !tr_torrentIsSeed (tor))
453        return;
454
455    /* if we're seeding and reach our seed ratio limit, stop the torrent */
456    if (tr_torrentIsSeedRatioDone (tor))
457    {
458        tr_torinf (tor, "%s", "Seed ratio reached; pausing torrent");
459
460        tor->isStopping = true;
461
462        /* maybe notify the client */
463        if (tor->ratio_limit_hit_func != NULL)
464            tor->ratio_limit_hit_func (tor, tor->ratio_limit_hit_func_user_data);
465    }
466    /* if we're seeding and reach our inactiviy limit, stop the torrent */
467    else if (tr_torrentIsSeedIdleLimitDone (tor))
468    {
469        tr_torinf (tor, "%s", "Seeding idle limit reached; pausing torrent");
470
471        tor->isStopping = true;
472        tor->finishedSeedingByIdle = true;
473
474        /* maybe notify the client */
475        if (tor->idle_limit_hit_func != NULL)
476            tor->idle_limit_hit_func (tor, tor->idle_limit_hit_func_user_data);
477    }
478}
479
480/***
481****
482***/
483
484void
485tr_torrentSetLocalError (tr_torrent * tor, const char * fmt, ...)
486{
487    va_list ap;
488
489    assert (tr_isTorrent (tor));
490
491    va_start (ap, fmt);
492    tor->error = TR_STAT_LOCAL_ERROR;
493    tor->errorTracker[0] = '\0';
494    evutil_vsnprintf (tor->errorString, sizeof (tor->errorString), fmt, ap);
495    va_end (ap);
496
497    tr_torerr (tor, "%s", tor->errorString);
498
499    if (tor->isRunning)
500        tor->isStopping = true;
501}
502
503static void
504tr_torrentClearError (tr_torrent * tor)
505{
506    tor->error = TR_STAT_OK;
507    tor->errorString[0] = '\0';
508    tor->errorTracker[0] = '\0';
509}
510
511static void
512onTrackerResponse (tr_torrent * tor, const tr_tracker_event * event, void * unused UNUSED)
513{
514    switch (event->messageType)
515    {
516        case TR_TRACKER_PEERS:
517        {
518            size_t i;
519            const int8_t seedProbability = event->seedProbability;
520            const bool allAreSeeds = seedProbability == 100;
521
522             if (allAreSeeds)
523                tr_tordbg (tor, "Got %zu seeds from tracker", event->pexCount);
524            else
525                tr_tordbg (tor, "Got %zu peers from tracker", event->pexCount);
526
527            for (i = 0; i < event->pexCount; ++i)
528                tr_peerMgrAddPex (tor, TR_PEER_FROM_TRACKER, &event->pex[i], seedProbability);
529
530            break;
531        }
532
533        case TR_TRACKER_WARNING:
534            tr_torerr (tor, _("Tracker warning: \"%s\""), event->text);
535            tor->error = TR_STAT_TRACKER_WARNING;
536            tr_strlcpy (tor->errorTracker, event->tracker, sizeof (tor->errorTracker));
537            tr_strlcpy (tor->errorString, event->text, sizeof (tor->errorString));
538            break;
539
540        case TR_TRACKER_ERROR:
541            tr_torerr (tor, _("Tracker error: \"%s\""), event->text);
542            tor->error = TR_STAT_TRACKER_ERROR;
543            tr_strlcpy (tor->errorTracker, event->tracker, sizeof (tor->errorTracker));
544            tr_strlcpy (tor->errorString, event->text, sizeof (tor->errorString));
545            break;
546
547        case TR_TRACKER_ERROR_CLEAR:
548            if (tor->error != TR_STAT_LOCAL_ERROR)
549                tr_torrentClearError (tor);
550            break;
551    }
552}
553
554/***
555****
556****  TORRENT INSTANTIATION
557****
558***/
559
560static tr_piece_index_t
561getBytePiece (const tr_info * info, uint64_t byteOffset)
562{
563    tr_piece_index_t piece;
564
565    assert (info);
566    assert (info->pieceSize != 0);
567
568    piece = byteOffset / info->pieceSize;
569
570    /* handle 0-byte files at the end of a torrent */
571    if (byteOffset == info->totalSize)
572      piece = info->pieceCount - 1;
573
574    return piece;
575}
576
577static void
578initFilePieces (tr_info *       info,
579                tr_file_index_t fileIndex)
580{
581    tr_file * file;
582    uint64_t  firstByte, lastByte;
583
584    assert (info);
585    assert (fileIndex < info->fileCount);
586
587    file = &info->files[fileIndex];
588    firstByte = file->offset;
589    lastByte = firstByte + (file->length ? file->length - 1 : 0);
590    file->firstPiece = getBytePiece (info, firstByte);
591    file->lastPiece = getBytePiece (info, lastByte);
592}
593
594static int
595pieceHasFile (tr_piece_index_t piece,
596              const tr_file *  file)
597{
598    return (file->firstPiece <= piece) && (piece <= file->lastPiece);
599}
600
601static tr_priority_t
602calculatePiecePriority (const tr_torrent * tor,
603                        tr_piece_index_t   piece,
604                        int                fileHint)
605{
606    tr_file_index_t i;
607    tr_priority_t priority = TR_PRI_LOW;
608
609    /* find the first file that has data in this piece */
610    if (fileHint >= 0) {
611        i = fileHint;
612        while (i > 0 && pieceHasFile (piece, &tor->info.files[i - 1]))
613            --i;
614    } else {
615        for (i = 0; i < tor->info.fileCount; ++i)
616            if (pieceHasFile (piece, &tor->info.files[i]))
617                break;
618    }
619
620    /* the piece's priority is the max of the priorities
621     * of all the files in that piece */
622    for (; i < tor->info.fileCount; ++i)
623    {
624        const tr_file * file = &tor->info.files[i];
625
626        if (!pieceHasFile (piece, file))
627            break;
628
629        priority = MAX (priority, file->priority);
630
631        /* when dealing with multimedia files, getting the first and
632           last pieces can sometimes allow you to preview it a bit
633           before it's fully downloaded... */
634        if (file->priority >= TR_PRI_NORMAL)
635            if (file->firstPiece == piece || file->lastPiece == piece)
636                priority = TR_PRI_HIGH;
637    }
638
639    return priority;
640}
641
642static void
643tr_torrentInitFilePieces (tr_torrent * tor)
644{
645    int * firstFiles;
646    tr_file_index_t f;
647    tr_piece_index_t p;
648    uint64_t offset = 0;
649    tr_info * inf = &tor->info;
650
651    /* assign the file offsets */
652    for (f=0; f<inf->fileCount; ++f) {
653        inf->files[f].offset = offset;
654        offset += inf->files[f].length;
655        initFilePieces (inf, f);
656    }
657
658    /* build the array of first-file hints to give calculatePiecePriority */
659    firstFiles = tr_new (int, inf->pieceCount);
660    for (p=f=0; p<inf->pieceCount; ++p) {
661        while (inf->files[f].lastPiece < p)
662            ++f;
663        firstFiles[p] = f;
664    }
665
666#if 0
667    /* test to confirm the first-file hints are correct */
668    for (p=0; p<inf->pieceCount; ++p) {
669        f = firstFiles[p];
670        assert (inf->files[f].firstPiece <= p);
671        assert (inf->files[f].lastPiece >= p);
672        if (f > 0)
673            assert (inf->files[f-1].lastPiece < p);
674        for (f=0; f<inf->fileCount; ++f)
675            if (pieceHasFile (p, &inf->files[f]))
676                break;
677        assert ((int)f == firstFiles[p]);
678    }
679#endif
680
681    for (p=0; p<inf->pieceCount; ++p)
682        inf->pieces[p].priority = calculatePiecePriority (tor, p, firstFiles[p]);
683
684    tr_free (firstFiles);
685}
686
687static void torrentStart (tr_torrent * tor, bool bypass_queue);
688
689/**
690 * Decide on a block size. Constraints:
691 * (1) most clients decline requests over 16 KiB
692 * (2) pieceSize must be a multiple of block size
693 */
694uint32_t
695tr_getBlockSize (uint32_t pieceSize)
696{
697    uint32_t b = pieceSize;
698
699    while (b > MAX_BLOCK_SIZE)
700        b /= 2u;
701
702    if (!b || (pieceSize % b)) /* not cleanly divisible */
703        return 0;
704    return b;
705}
706
707static void refreshCurrentDir (tr_torrent * tor);
708
709static void
710torrentInitFromInfo (tr_torrent * tor)
711{
712    uint64_t t;
713    tr_info * info = &tor->info;
714
715    tor->blockSize = tr_getBlockSize (info->pieceSize);
716
717    if (info->pieceSize)
718        tor->lastPieceSize = (uint32_t)(info->totalSize % info->pieceSize);
719
720    if (!tor->lastPieceSize)
721        tor->lastPieceSize = info->pieceSize;
722
723    if (tor->blockSize)
724        tor->lastBlockSize = info->totalSize % tor->blockSize;
725
726    if (!tor->lastBlockSize)
727        tor->lastBlockSize = tor->blockSize;
728
729    tor->blockCount = tor->blockSize
730        ? (info->totalSize + tor->blockSize - 1) / tor->blockSize
731        : 0;
732
733    tor->blockCountInPiece = tor->blockSize
734        ? info->pieceSize / tor->blockSize
735        : 0;
736
737    tor->blockCountInLastPiece = tor->blockSize
738        ? (tor->lastPieceSize + tor->blockSize - 1) / tor->blockSize
739        : 0;
740
741    /* check our work */
742    if (tor->blockSize != 0)
743        assert ((info->pieceSize % tor->blockSize) == 0);
744    t = info->pieceCount - 1;
745    t *= info->pieceSize;
746    t += tor->lastPieceSize;
747    assert (t == info->totalSize);
748    t = tor->blockCount - 1;
749    t *= tor->blockSize;
750    t += tor->lastBlockSize;
751    assert (t == info->totalSize);
752    t = info->pieceCount - 1;
753    t *= tor->blockCountInPiece;
754    t += tor->blockCountInLastPiece;
755    assert (t == (uint64_t)tor->blockCount);
756
757    tr_cpConstruct (&tor->completion, tor);
758
759    tr_torrentInitFilePieces (tor);
760
761    tor->completeness = tr_cpGetStatus (&tor->completion);
762}
763
764static void tr_torrentFireMetadataCompleted (tr_torrent * tor);
765
766void
767tr_torrentGotNewInfoDict (tr_torrent * tor)
768{
769    torrentInitFromInfo (tor);
770
771    tr_peerMgrOnTorrentGotMetainfo (tor);
772
773    tr_torrentFireMetadataCompleted (tor);
774}
775
776static bool
777hasAnyLocalData (const tr_torrent * tor)
778{
779    tr_file_index_t i;
780
781    for (i=0; i<tor->info.fileCount; ++i)
782        if (tr_torrentFindFile2 (tor, i, NULL, NULL, NULL))
783            return true;
784
785    return false;
786}
787
788static bool
789setLocalErrorIfFilesDisappeared (tr_torrent * tor)
790{
791    const bool disappeared = (tr_cpHaveTotal (&tor->completion) > 0) && !hasAnyLocalData (tor);
792
793    if (disappeared)
794    {
795        tr_deeplog_tor (tor, "%s", "[LAZY] uh oh, the files disappeared");
796        tr_torrentSetLocalError (tor, "%s", _("No data found! Ensure your drives are connected or use \"Set Location\". To re-download, remove the torrent and re-add it."));
797    }
798
799    return disappeared;
800}
801
802static void
803torrentInit (tr_torrent * tor, const tr_ctor * ctor)
804{
805    int doStart;
806    uint64_t loaded;
807    const char * dir;
808    bool isNewTorrent;
809    struct stat st;
810    static int nextUniqueId = 1;
811    tr_session * session = tr_ctorGetSession (ctor);
812
813    assert (session != NULL);
814
815    tr_sessionLock (session);
816
817    tor->session   = session;
818    tor->uniqueId = nextUniqueId++;
819    tor->magicNumber = TORRENT_MAGIC_NUMBER;
820    tor->queuePosition = session->torrentCount;
821
822    tr_peerIdInit (tor->peer_id);
823
824    tr_sha1 (tor->obfuscatedHash, "req2", 4,
825             tor->info.hash, SHA_DIGEST_LENGTH,
826             NULL);
827
828    if (!tr_ctorGetDownloadDir (ctor, TR_FORCE, &dir) ||
829        !tr_ctorGetDownloadDir (ctor, TR_FALLBACK, &dir))
830            tor->downloadDir = tr_strdup (dir);
831
832    if (tr_ctorGetIncompleteDir (ctor, &dir))
833        dir = tr_sessionGetIncompleteDir (session);
834    if (tr_sessionIsIncompleteDirEnabled (session))
835        tor->incompleteDir = tr_strdup (dir);
836
837    tr_bandwidthConstruct (&tor->bandwidth, session, &session->bandwidth);
838
839    tor->bandwidth.priority = tr_ctorGetBandwidthPriority (ctor);
840
841    tor->error = TR_STAT_OK;
842
843    tor->finishedSeedingByIdle = false;
844
845    tr_peerMgrAddTorrent (session->peerMgr, tor);
846
847    assert (!tor->downloadedCur);
848    assert (!tor->uploadedCur);
849
850    tr_torrentSetAddedDate (tor, tr_time ()); /* this is a default value to be
851                                                  overwritten by the resume file */
852
853    torrentInitFromInfo (tor);
854    loaded = tr_torrentLoadResume (tor, ~0, ctor);
855    tor->completeness = tr_cpGetStatus (&tor->completion);
856    setLocalErrorIfFilesDisappeared (tor);
857
858    tr_ctorInitTorrentPriorities (ctor, tor);
859    tr_ctorInitTorrentWanted (ctor, tor);
860
861    refreshCurrentDir (tor);
862
863    doStart = tor->isRunning;
864    tor->isRunning = 0;
865
866    if (! (loaded & TR_FR_SPEEDLIMIT))
867    {
868        tr_torrentUseSpeedLimit (tor, TR_UP, false);
869        tr_torrentSetSpeedLimit_Bps (tor, TR_UP, tr_sessionGetSpeedLimit_Bps (tor->session, TR_UP));
870        tr_torrentUseSpeedLimit (tor, TR_DOWN, false);
871        tr_torrentSetSpeedLimit_Bps (tor, TR_DOWN, tr_sessionGetSpeedLimit_Bps (tor->session, TR_DOWN));
872        tr_torrentUseSessionLimits (tor, true);
873    }
874
875    if (! (loaded & TR_FR_RATIOLIMIT))
876    {
877        tr_torrentSetRatioMode (tor, TR_RATIOLIMIT_GLOBAL);
878        tr_torrentSetRatioLimit (tor, tr_sessionGetRatioLimit (tor->session));
879    }
880
881    if (! (loaded & TR_FR_IDLELIMIT))
882    {
883        tr_torrentSetIdleMode (tor, TR_IDLELIMIT_GLOBAL);
884        tr_torrentSetIdleLimit (tor, tr_sessionGetIdleLimit (tor->session));
885    }
886
887    /* add the torrent to tr_session.torrentList */
888    session->torrentCount++;
889    if (session->torrentList == NULL)
890        session->torrentList = tor;
891    else {
892        tr_torrent * it = session->torrentList;
893        while (it->next != NULL)
894            it = it->next;
895        it->next = tor;
896    }
897
898    /* if we don't have a local .torrent file already, assume the torrent is new */
899    isNewTorrent = stat (tor->info.torrent, &st);
900
901    /* maybe save our own copy of the metainfo */
902    if (tr_ctorGetSave (ctor))
903    {
904        const tr_variant * val;
905        if (!tr_ctorGetMetainfo (ctor, &val))
906        {
907            const char * path = tor->info.torrent;
908            const int err = tr_variantToFile (val, TR_VARIANT_FMT_BENC, path);
909            if (err)
910                tr_torrentSetLocalError (tor, "Unable to save torrent file: %s", tr_strerror (err));
911            tr_sessionSetTorrentFile (tor->session, tor->info.hashString, path);
912        }
913    }
914
915    tor->tiers = tr_announcerAddTorrent (tor, onTrackerResponse, NULL);
916
917    if (isNewTorrent)
918    {
919        tor->startAfterVerify = doStart;
920        tr_torrentVerify (tor);
921    }
922    else if (doStart)
923    {
924        tr_torrentStart (tor);
925    }
926
927    tr_sessionUnlock (session);
928}
929
930static tr_parse_result
931torrentParseImpl (const tr_ctor * ctor, tr_info * setmeInfo,
932                  bool * setmeHasInfo, int * dictLength)
933{
934    int             doFree;
935    bool            didParse;
936    bool            hasInfo = false;
937    tr_info         tmp;
938    const tr_variant * metainfo;
939    tr_session    * session = tr_ctorGetSession (ctor);
940    tr_parse_result result = TR_PARSE_OK;
941
942    if (setmeInfo == NULL)
943        setmeInfo = &tmp;
944    memset (setmeInfo, 0, sizeof (tr_info));
945
946    if (tr_ctorGetMetainfo (ctor, &metainfo))
947        return TR_PARSE_ERR;
948
949    didParse = tr_metainfoParse (session, metainfo, setmeInfo,
950                                 &hasInfo, dictLength);
951    doFree = didParse && (setmeInfo == &tmp);
952
953    if (!didParse)
954        result = TR_PARSE_ERR;
955
956    if (didParse && hasInfo && !tr_getBlockSize (setmeInfo->pieceSize))
957        result = TR_PARSE_ERR;
958
959    if (didParse && session && tr_torrentExists (session, setmeInfo->hash))
960        result = TR_PARSE_DUPLICATE;
961
962    if (doFree)
963        tr_metainfoFree (setmeInfo);
964
965    if (setmeHasInfo != NULL)
966        *setmeHasInfo = hasInfo;
967
968    return result;
969}
970
971tr_parse_result
972tr_torrentParse (const tr_ctor * ctor, tr_info * setmeInfo)
973{
974    return torrentParseImpl (ctor, setmeInfo, NULL, NULL);
975}
976
977tr_torrent *
978tr_torrentNew (const tr_ctor * ctor, int * setmeError)
979{
980    int len;
981    bool hasInfo;
982    tr_info tmpInfo;
983    tr_parse_result r;
984    tr_torrent * tor = NULL;
985
986    assert (ctor != NULL);
987    assert (tr_isSession (tr_ctorGetSession (ctor)));
988
989    r = torrentParseImpl (ctor, &tmpInfo, &hasInfo, &len);
990    if (r == TR_PARSE_OK)
991    {
992        tor = tr_new0 (tr_torrent, 1);
993        tor->info = tmpInfo;
994        if (hasInfo)
995            tor->infoDictLength = len;
996        torrentInit (tor, ctor);
997    }
998    else
999    {
1000        if (r == TR_PARSE_DUPLICATE)
1001            tr_metainfoFree (&tmpInfo);
1002
1003        if (setmeError)
1004            *setmeError = r;
1005    }
1006
1007    return tor;
1008}
1009
1010/**
1011***
1012**/
1013
1014void
1015tr_torrentSetDownloadDir (tr_torrent * tor, const char * path)
1016{
1017    assert (tr_isTorrent (tor));
1018
1019    if (!path || !tor->downloadDir || strcmp (path, tor->downloadDir))
1020    {
1021        tr_free (tor->downloadDir);
1022        tor->downloadDir = tr_strdup (path);
1023        tr_torrentSetDirty (tor);
1024    }
1025
1026    refreshCurrentDir (tor);
1027}
1028
1029const char*
1030tr_torrentGetDownloadDir (const tr_torrent * tor)
1031{
1032    assert (tr_isTorrent (tor));
1033
1034    return tor->downloadDir;
1035}
1036
1037const char *
1038tr_torrentGetCurrentDir (const tr_torrent * tor)
1039{
1040    assert (tr_isTorrent (tor));
1041
1042    return tor->currentDir;
1043}
1044
1045
1046void
1047tr_torrentChangeMyPort (tr_torrent * tor)
1048{
1049    assert (tr_isTorrent (tor));
1050
1051    if (tor->isRunning)
1052        tr_announcerChangeMyPort (tor);
1053}
1054
1055static inline void
1056tr_torrentManualUpdateImpl (void * vtor)
1057{
1058    tr_torrent * tor = vtor;
1059
1060    assert (tr_isTorrent (tor));
1061
1062    if (tor->isRunning)
1063        tr_announcerManualAnnounce (tor);
1064}
1065
1066void
1067tr_torrentManualUpdate (tr_torrent * tor)
1068{
1069    assert (tr_isTorrent (tor));
1070
1071    tr_runInEventThread (tor->session, tr_torrentManualUpdateImpl, tor);
1072}
1073
1074bool
1075tr_torrentCanManualUpdate (const tr_torrent * tor)
1076{
1077    return (tr_isTorrent (tor))
1078        && (tor->isRunning)
1079        && (tr_announcerCanManualAnnounce (tor));
1080}
1081
1082const tr_info *
1083tr_torrentInfo (const tr_torrent * tor)
1084{
1085    return tr_isTorrent (tor) ? &tor->info : NULL;
1086}
1087
1088const tr_stat *
1089tr_torrentStatCached (tr_torrent * tor)
1090{
1091    const time_t now = tr_time ();
1092
1093    return tr_isTorrent (tor) && (now == tor->lastStatTime)
1094         ? &tor->stats
1095         : tr_torrentStat (tor);
1096}
1097
1098void
1099tr_torrentSetVerifyState (tr_torrent * tor, tr_verify_state state)
1100{
1101    assert (tr_isTorrent (tor));
1102    assert (state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW);
1103
1104    tor->verifyState = state;
1105    tor->anyDate = tr_time ();
1106}
1107
1108tr_torrent_activity
1109tr_torrentGetActivity (const tr_torrent * tor)
1110{
1111  tr_torrent_activity ret = TR_STATUS_STOPPED;
1112
1113  const bool is_seed = tr_torrentIsSeed (tor);
1114
1115  if (tor->verifyState == TR_VERIFY_NOW)
1116    {
1117      ret = TR_STATUS_CHECK;
1118    }
1119  else if (tor->verifyState == TR_VERIFY_WAIT)
1120    {
1121      ret = TR_STATUS_CHECK_WAIT;
1122    }
1123  else if (tor->isRunning)
1124    {
1125      ret = is_seed ? TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
1126    }
1127  else if (tr_torrentIsQueued (tor))
1128    {
1129      if (is_seed && tr_sessionGetQueueEnabled (tor->session, TR_UP))
1130        ret = TR_STATUS_SEED_WAIT;
1131      else if (!is_seed && tr_sessionGetQueueEnabled (tor->session, TR_DOWN))
1132        ret = TR_STATUS_DOWNLOAD_WAIT;
1133    }
1134
1135  return ret;
1136}
1137
1138static time_t
1139torrentGetIdleSecs (const tr_torrent * tor)
1140{
1141    int idle_secs;
1142    const tr_torrent_activity activity = tr_torrentGetActivity (tor);
1143
1144    if ((activity == TR_STATUS_DOWNLOAD || activity == TR_STATUS_SEED) && tor->startDate != 0)
1145        idle_secs = difftime (tr_time (), MAX (tor->startDate, tor->activityDate));
1146    else
1147        idle_secs = -1;
1148
1149    return idle_secs;
1150}
1151
1152bool
1153tr_torrentIsStalled (const tr_torrent * tor)
1154{
1155    return tr_sessionGetQueueStalledEnabled (tor->session)
1156        && (torrentGetIdleSecs (tor) > (tr_sessionGetQueueStalledMinutes (tor->session) * 60));
1157}
1158
1159
1160static double
1161getVerifyProgress (const tr_torrent * tor)
1162{
1163  double d = 0;
1164
1165  if (tr_torrentHasMetadata (tor))
1166    {
1167      tr_piece_index_t i, n;
1168      tr_piece_index_t checked = 0;
1169
1170      for (i=0, n=tor->info.pieceCount; i!=n; ++i)
1171        if (tor->info.pieces[i].timeChecked)
1172          ++checked;
1173
1174      d = checked / (double)tor->info.pieceCount;
1175    }
1176
1177  return d;
1178}
1179
1180const tr_stat *
1181tr_torrentStat (tr_torrent * tor)
1182{
1183  tr_stat * s;
1184  uint64_t seedRatioBytesLeft;
1185  uint64_t seedRatioBytesGoal;
1186  bool seedRatioApplies;
1187  uint16_t seedIdleMinutes;
1188  const uint64_t now = tr_time_msec ();
1189
1190  assert (tr_isTorrent (tor));
1191
1192  tor->lastStatTime = tr_time ();
1193
1194  s = &tor->stats;
1195  s->id = tor->uniqueId;
1196  s->activity = tr_torrentGetActivity (tor);
1197  s->error = tor->error;
1198  s->queuePosition = tor->queuePosition;
1199  s->isStalled = tr_torrentIsStalled (tor);
1200  tr_strlcpy (s->errorString, tor->errorString, sizeof (s->errorString));
1201
1202  s->manualAnnounceTime = tr_announcerNextManualAnnounce (tor);
1203
1204  tr_peerMgrTorrentStats (tor,
1205                          &s->peersConnected,
1206                          &s->webseedsSendingToUs,
1207                          &s->peersSendingToUs,
1208                          &s->peersGettingFromUs,
1209                          s->peersFrom);
1210
1211  s->rawUploadSpeed_KBps     = toSpeedKBps (tr_bandwidthGetRawSpeed_Bps (&tor->bandwidth, now, TR_UP));
1212  s->pieceUploadSpeed_KBps   = toSpeedKBps (tr_bandwidthGetPieceSpeed_Bps (&tor->bandwidth, now, TR_UP));
1213  s->rawDownloadSpeed_KBps   = toSpeedKBps (tr_bandwidthGetRawSpeed_Bps (&tor->bandwidth, now, TR_DOWN));
1214  s->pieceDownloadSpeed_KBps = toSpeedKBps (tr_bandwidthGetPieceSpeed_Bps (&tor->bandwidth, now, TR_DOWN));
1215
1216  s->percentComplete = tr_cpPercentComplete (&tor->completion);
1217  s->metadataPercentComplete = tr_torrentGetMetadataPercent (tor);
1218
1219  s->percentDone         = tr_cpPercentDone (&tor->completion);
1220  s->leftUntilDone       = tr_cpLeftUntilDone (&tor->completion);
1221  s->sizeWhenDone        = tr_cpSizeWhenDone (&tor->completion);
1222  s->recheckProgress     = s->activity == TR_STATUS_CHECK ? getVerifyProgress (tor) : 0;
1223  s->activityDate        = tor->activityDate;
1224  s->addedDate           = tor->addedDate;
1225  s->doneDate            = tor->doneDate;
1226  s->startDate           = tor->startDate;
1227  s->secondsSeeding      = tor->secondsSeeding;
1228  s->secondsDownloading  = tor->secondsDownloading;
1229  s->idleSecs            = torrentGetIdleSecs (tor);
1230
1231  s->corruptEver      = tor->corruptCur    + tor->corruptPrev;
1232  s->downloadedEver   = tor->downloadedCur + tor->downloadedPrev;
1233  s->uploadedEver     = tor->uploadedCur   + tor->uploadedPrev;
1234  s->haveValid        = tr_cpHaveValid (&tor->completion);
1235  s->haveUnchecked    = tr_cpHaveTotal (&tor->completion) - s->haveValid;
1236  s->desiredAvailable = tr_peerMgrGetDesiredAvailable (tor);
1237
1238  s->ratio = tr_getRatio (s->uploadedEver,
1239                          s->downloadedEver ? s->downloadedEver : s->haveValid);
1240
1241  seedRatioApplies = tr_torrentGetSeedRatioBytes (tor, &seedRatioBytesLeft,
1242                                                       &seedRatioBytesGoal);
1243
1244  switch (s->activity)
1245    {
1246      /* etaXLSpeed exists because if we use the piece speed directly,
1247       * brief fluctuations cause the ETA to jump all over the place.
1248       * so, etaXLSpeed is a smoothed-out version of the piece speed
1249       * to dampen the effect of fluctuations */
1250      case TR_STATUS_DOWNLOAD:
1251        if ((tor->etaDLSpeedCalculatedAt + 800) < now)
1252          {
1253            tor->etaDLSpeed_KBps = ((tor->etaDLSpeedCalculatedAt + 4000) < now)
1254              ? s->pieceDownloadSpeed_KBps /* if no recent previous speed, no need to smooth */
1255              : ((tor->etaDLSpeed_KBps*4.0) + s->pieceDownloadSpeed_KBps)/5.0; /* smooth across 5 readings */
1256            tor->etaDLSpeedCalculatedAt = now;
1257          }
1258
1259        if ((s->leftUntilDone > s->desiredAvailable) && (tor->info.webseedCount < 1))
1260          s->eta = TR_ETA_NOT_AVAIL;
1261        else if (tor->etaDLSpeed_KBps < 1)
1262          s->eta = TR_ETA_UNKNOWN;
1263        else
1264          s->eta = s->leftUntilDone / toSpeedBytes (tor->etaDLSpeed_KBps);
1265
1266        s->etaIdle = TR_ETA_NOT_AVAIL;
1267        break;
1268
1269      case TR_STATUS_SEED:
1270        if (!seedRatioApplies)
1271          {
1272            s->eta = TR_ETA_NOT_AVAIL;
1273          }
1274        else
1275          {
1276            if ((tor->etaULSpeedCalculatedAt + 800) < now)
1277              {
1278                tor->etaULSpeed_KBps = ((tor->etaULSpeedCalculatedAt + 4000) < now)
1279                  ? s->pieceUploadSpeed_KBps /* if no recent previous speed, no need to smooth */
1280                  : ((tor->etaULSpeed_KBps*4.0) + s->pieceUploadSpeed_KBps)/5.0; /* smooth across 5 readings */
1281                tor->etaULSpeedCalculatedAt = now;
1282              }
1283
1284            if (tor->etaULSpeed_KBps < 1)
1285              s->eta = TR_ETA_UNKNOWN;
1286            else
1287              s->eta = seedRatioBytesLeft / toSpeedBytes (tor->etaULSpeed_KBps);
1288          }
1289
1290        if (tor->etaULSpeed_KBps < 1 && tr_torrentGetSeedIdle (tor, &seedIdleMinutes))
1291          s->etaIdle = seedIdleMinutes * 60 - s->idleSecs;
1292        else
1293          s->etaIdle = TR_ETA_NOT_AVAIL;
1294        break;
1295
1296      default:
1297        s->eta = TR_ETA_NOT_AVAIL;
1298        s->etaIdle = TR_ETA_NOT_AVAIL;
1299        break;
1300    }
1301
1302  /* s->haveValid is here to make sure a torrent isn't marked 'finished'
1303   * when the user hits "uncheck all" prior to starting the torrent... */
1304  s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && !seedRatioBytesLeft && s->haveValid);
1305
1306  if (!seedRatioApplies || s->finished)
1307    s->seedRatioPercentDone = 1;
1308  else if (!seedRatioBytesGoal) /* impossible? safeguard for div by zero */
1309    s->seedRatioPercentDone = 0;
1310  else
1311    s->seedRatioPercentDone = (double)(seedRatioBytesGoal - seedRatioBytesLeft) / seedRatioBytesGoal;
1312
1313  /* test some of the constraints */
1314  assert (s->sizeWhenDone <= tor->info.totalSize);
1315  assert (s->leftUntilDone <= s->sizeWhenDone);
1316  assert (s->desiredAvailable <= s->leftUntilDone);
1317
1318  return s;
1319}
1320
1321/***
1322****
1323***/
1324
1325static uint64_t
1326fileBytesCompleted (const tr_torrent * tor, tr_file_index_t index)
1327{
1328    uint64_t total = 0;
1329    const tr_file * f = &tor->info.files[index];
1330
1331    if (f->length)
1332    {
1333        tr_block_index_t first;
1334        tr_block_index_t last;
1335        tr_torGetFileBlockRange (tor, index, &first, &last);
1336
1337        if (first == last)
1338        {
1339            if (tr_cpBlockIsComplete (&tor->completion, first))
1340                total = f->length;
1341        }
1342        else
1343        {
1344            /* the first block */
1345            if (tr_cpBlockIsComplete (&tor->completion, first))
1346                total += tor->blockSize - (f->offset % tor->blockSize);
1347
1348            /* the middle blocks */
1349            if (first + 1 < last) {
1350                uint64_t u = tr_bitfieldCountRange (&tor->completion.blockBitfield, first+1, last);
1351                u *= tor->blockSize;
1352                total += u;
1353            }
1354
1355            /* the last block */
1356            if (tr_cpBlockIsComplete (&tor->completion, last))
1357                total += (f->offset + f->length) - ((uint64_t)tor->blockSize * last);
1358        }
1359    }
1360
1361    return total;
1362}
1363
1364tr_file_stat *
1365tr_torrentFiles (const tr_torrent * tor,
1366                 tr_file_index_t *  fileCount)
1367{
1368    tr_file_index_t       i;
1369    const tr_file_index_t n = tor->info.fileCount;
1370    tr_file_stat *        files = tr_new0 (tr_file_stat, n);
1371    tr_file_stat *        walk = files;
1372    const bool            isSeed = tor->completeness == TR_SEED;
1373
1374    assert (tr_isTorrent (tor));
1375
1376    for (i=0; i<n; ++i, ++walk) {
1377        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted (tor, i);
1378        walk->bytesCompleted = b;
1379        walk->progress = tor->info.files[i].length > 0 ? ((float)b / tor->info.files[i].length) : 1.0f;
1380    }
1381
1382    if (fileCount)
1383        *fileCount = n;
1384
1385    return files;
1386}
1387
1388void
1389tr_torrentFilesFree (tr_file_stat *            files,
1390                     tr_file_index_t fileCount UNUSED)
1391{
1392    tr_free (files);
1393}
1394
1395/***
1396****
1397***/
1398
1399double*
1400tr_torrentWebSpeeds_KBps (const tr_torrent * tor)
1401{
1402  assert (tr_isTorrent (tor));
1403
1404  return tr_peerMgrWebSpeeds_KBps (tor);
1405}
1406
1407tr_peer_stat *
1408tr_torrentPeers (const tr_torrent * tor, int * peerCount)
1409{
1410  assert (tr_isTorrent (tor));
1411
1412  return tr_peerMgrPeerStats (tor, peerCount);
1413}
1414
1415void
1416tr_torrentPeersFree (tr_peer_stat * peers, int peerCount UNUSED)
1417{
1418  tr_free (peers);
1419}
1420
1421tr_tracker_stat *
1422tr_torrentTrackers (const tr_torrent * tor, int * setmeTrackerCount)
1423{
1424  assert (tr_isTorrent (tor));
1425
1426  return tr_announcerStats (tor, setmeTrackerCount);
1427}
1428
1429void
1430tr_torrentTrackersFree (tr_tracker_stat * trackers, int trackerCount)
1431{
1432  tr_announcerStatsFree (trackers, trackerCount);
1433}
1434
1435void
1436tr_torrentAvailability (const tr_torrent * tor, int8_t * tab, int size)
1437{
1438  assert (tr_isTorrent (tor));
1439
1440  if ((tab != NULL) && (size > 0))
1441    tr_peerMgrTorrentAvailability (tor, tab, size);
1442}
1443
1444void
1445tr_torrentAmountFinished (const tr_torrent * tor, float * tab, int size)
1446{
1447  tr_cpGetAmountDone (&tor->completion, tab, size);
1448}
1449
1450static void
1451tr_torrentResetTransferStats (tr_torrent * tor)
1452{
1453    tr_torrentLock (tor);
1454
1455    tor->downloadedPrev += tor->downloadedCur;
1456    tor->downloadedCur   = 0;
1457    tor->uploadedPrev   += tor->uploadedCur;
1458    tor->uploadedCur     = 0;
1459    tor->corruptPrev    += tor->corruptCur;
1460    tor->corruptCur      = 0;
1461
1462    tr_torrentSetDirty (tor);
1463
1464    tr_torrentUnlock (tor);
1465}
1466
1467void
1468tr_torrentSetHasPiece (tr_torrent *     tor,
1469                       tr_piece_index_t pieceIndex,
1470                       bool             has)
1471{
1472    assert (tr_isTorrent (tor));
1473    assert (pieceIndex < tor->info.pieceCount);
1474
1475    if (has)
1476        tr_cpPieceAdd (&tor->completion, pieceIndex);
1477    else
1478        tr_cpPieceRem (&tor->completion, pieceIndex);
1479}
1480
1481/***
1482****
1483***/
1484
1485#ifndef NDEBUG
1486static bool queueIsSequenced (tr_session *);
1487#endif
1488
1489static void
1490freeTorrent (tr_torrent * tor)
1491{
1492    tr_torrent * t;
1493    tr_session *  session = tor->session;
1494    tr_info *    inf = &tor->info;
1495    const time_t now = tr_time ();
1496
1497    assert (!tor->isRunning);
1498
1499    tr_sessionLock (session);
1500
1501    tr_peerMgrRemoveTorrent (tor);
1502
1503    tr_announcerRemoveTorrent (session->announcer, tor);
1504
1505    tr_cpDestruct (&tor->completion);
1506
1507    tr_free (tor->downloadDir);
1508    tr_free (tor->incompleteDir);
1509
1510    if (tor == session->torrentList)
1511        session->torrentList = tor->next;
1512    else for (t = session->torrentList; t != NULL; t = t->next) {
1513        if (t->next == tor) {
1514            t->next = tor->next;
1515            break;
1516        }
1517    }
1518
1519    /* decrement the torrent count */
1520    assert (session->torrentCount >= 1);
1521    session->torrentCount--;
1522
1523    /* resequence the queue positions */
1524    t = NULL;
1525    while ((t = tr_torrentNext (session, t))) {
1526        if (t->queuePosition > tor->queuePosition) {
1527            t->queuePosition--;
1528            t->anyDate = now;
1529        }
1530    }
1531    assert (queueIsSequenced (session));
1532
1533    tr_bandwidthDestruct (&tor->bandwidth);
1534
1535    tr_metainfoFree (inf);
1536    memset (tor, ~0, sizeof (tr_torrent));
1537    tr_free (tor);
1538
1539    tr_sessionUnlock (session);
1540}
1541
1542/**
1543***  Start/Stop Callback
1544**/
1545
1546static void torrentSetQueued (tr_torrent * tor, bool queued);
1547
1548static void
1549torrentStartImpl (void * vtor)
1550{
1551    time_t now;
1552    tr_torrent * tor = vtor;
1553
1554    assert (tr_isTorrent (tor));
1555
1556    tr_sessionLock (tor->session);
1557
1558    tr_torrentRecheckCompleteness (tor);
1559    torrentSetQueued (tor, false);
1560
1561    now = tr_time ();
1562    tor->isRunning = true;
1563    tor->completeness = tr_cpGetStatus (&tor->completion);
1564    tor->startDate = tor->anyDate = now;
1565    tr_torrentClearError (tor);
1566    tor->finishedSeedingByIdle = false;
1567
1568    tr_torrentResetTransferStats (tor);
1569    tr_announcerTorrentStarted (tor);
1570    tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt (20);
1571    tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt (20);
1572    tor->lpdAnnounceAt = now;
1573    tr_peerMgrStartTorrent (tor);
1574
1575    tr_sessionUnlock (tor->session);
1576}
1577
1578uint64_t
1579tr_torrentGetCurrentSizeOnDisk (const tr_torrent * tor)
1580{
1581    tr_file_index_t i;
1582    uint64_t byte_count = 0;
1583    const tr_file_index_t n = tor->info.fileCount;
1584
1585    for (i=0; i<n; ++i)
1586    {
1587        struct stat sb;
1588        char * filename = tr_torrentFindFile (tor, i);
1589
1590        sb.st_size = 0;
1591        if (filename && !stat (filename, &sb))
1592            byte_count += sb.st_size;
1593
1594        tr_free (filename);
1595    }
1596
1597    return byte_count;
1598}
1599
1600static bool
1601torrentShouldQueue (const tr_torrent * tor)
1602{
1603    const tr_direction dir = tr_torrentGetQueueDirection (tor);
1604
1605    return tr_sessionCountQueueFreeSlots (tor->session, dir) == 0;
1606}
1607
1608static void
1609torrentStart (tr_torrent * tor, bool bypass_queue)
1610{
1611    switch (tr_torrentGetActivity (tor))
1612    {
1613        case TR_STATUS_SEED:
1614        case TR_STATUS_DOWNLOAD:
1615            return; /* already started */
1616            break;
1617
1618        case TR_STATUS_SEED_WAIT:
1619        case TR_STATUS_DOWNLOAD_WAIT:
1620            if (!bypass_queue)
1621                return; /* already queued */
1622            break;
1623
1624        case TR_STATUS_CHECK:
1625        case TR_STATUS_CHECK_WAIT:
1626            /* verifying right now... wait until that's done so
1627             * we'll know what completeness to use/announce */
1628            tor->startAfterVerify = true;
1629            return;
1630            break;
1631
1632        case TR_STATUS_STOPPED:
1633            if (!bypass_queue && torrentShouldQueue (tor)) {
1634                torrentSetQueued (tor, true);
1635                return;
1636            }
1637            break;
1638    }
1639
1640    /* don't allow the torrent to be started if the files disappeared */
1641    if (setLocalErrorIfFilesDisappeared (tor))
1642        return;
1643
1644    /* otherwise, start it now... */
1645    tr_sessionLock (tor->session);
1646
1647    /* allow finished torrents to be resumed */
1648    if (tr_torrentIsSeedRatioDone (tor)) {
1649        tr_torinf (tor, "%s", _("Restarted manually -- disabling its seed ratio"));
1650        tr_torrentSetRatioMode (tor, TR_RATIOLIMIT_UNLIMITED);
1651    }
1652
1653    /* corresponds to the peer_id sent as a tracker request parameter.
1654     * one tracker admin says: "When the same torrent is opened and
1655     * closed and opened again without quitting Transmission ...
1656     * change the peerid. It would help sometimes if a stopped event
1657     * was missed to ensure that we didn't think someone was cheating. */
1658    tr_peerIdInit (tor->peer_id);
1659    tor->isRunning = 1;
1660    tr_torrentSetDirty (tor);
1661    tr_runInEventThread (tor->session, torrentStartImpl, tor);
1662
1663    tr_sessionUnlock (tor->session);
1664}
1665
1666void
1667tr_torrentStart (tr_torrent * tor)
1668{
1669    if (tr_isTorrent (tor))
1670        torrentStart (tor, false);
1671}
1672
1673void
1674tr_torrentStartNow (tr_torrent * tor)
1675{
1676    if (tr_isTorrent (tor))
1677        torrentStart (tor, true);
1678}
1679
1680static void
1681torrentRecheckDoneImpl (void * vtor)
1682{
1683    tr_torrent * tor = vtor;
1684    assert (tr_isTorrent (tor));
1685
1686    tr_torrentRecheckCompleteness (tor);
1687
1688    if (tor->startAfterVerify) {
1689        tor->startAfterVerify = false;
1690        torrentStart (tor, false);
1691    }
1692}
1693
1694static void
1695torrentRecheckDoneCB (tr_torrent * tor)
1696{
1697    assert (tr_isTorrent (tor));
1698
1699    tr_runInEventThread (tor->session, torrentRecheckDoneImpl, tor);
1700}
1701
1702static void
1703verifyTorrent (void * vtor)
1704{
1705    bool startAfter;
1706    tr_torrent * tor = vtor;
1707
1708    tr_sessionLock (tor->session);
1709
1710    /* if the torrent's already being verified, stop it */
1711    tr_verifyRemove (tor);
1712
1713    startAfter = (tor->isRunning || tor->startAfterVerify) && !tor->isStopping;
1714
1715    if (tor->isRunning)
1716        tr_torrentStop (tor);
1717
1718    tor->startAfterVerify = startAfter;
1719
1720    if (setLocalErrorIfFilesDisappeared (tor))
1721        tor->startAfterVerify = false;
1722    else
1723        tr_verifyAdd (tor, torrentRecheckDoneCB);
1724
1725    tr_sessionUnlock (tor->session);
1726}
1727
1728void
1729tr_torrentVerify (tr_torrent * tor)
1730{
1731    if (tr_isTorrent (tor))
1732        tr_runInEventThread (tor->session, verifyTorrent, tor);
1733}
1734
1735void
1736tr_torrentSave (tr_torrent * tor)
1737{
1738    assert (tr_isTorrent (tor));
1739
1740    if (tor->isDirty)
1741    {
1742        tor->isDirty = false;
1743        tr_torrentSaveResume (tor);
1744    }
1745}
1746
1747static void
1748stopTorrent (void * vtor)
1749{
1750  tr_torrent * tor = vtor;
1751  tr_torinf (tor, "%s", "Pausing");
1752
1753  assert (tr_isTorrent (tor));
1754
1755  tr_torrentLock (tor);
1756
1757  tr_verifyRemove (tor);
1758  torrentSetQueued (tor, false);
1759  tr_peerMgrStopTorrent (tor);
1760  tr_announcerTorrentStopped (tor);
1761  tr_cacheFlushTorrent (tor->session->cache, tor);
1762
1763  tr_fdTorrentClose (tor->session, tor->uniqueId);
1764
1765  if (!tor->isDeleting)
1766    tr_torrentSave (tor);
1767
1768  tr_torrentUnlock (tor);
1769}
1770
1771void
1772tr_torrentStop (tr_torrent * tor)
1773{
1774    assert (tr_isTorrent (tor));
1775
1776    if (tr_isTorrent (tor))
1777    {
1778        tr_sessionLock (tor->session);
1779
1780        tor->isRunning = 0;
1781        tor->isStopping = 0;
1782        tr_torrentSetDirty (tor);
1783        tr_runInEventThread (tor->session, stopTorrent, tor);
1784
1785        tr_sessionUnlock (tor->session);
1786    }
1787}
1788
1789static void
1790closeTorrent (void * vtor)
1791{
1792    tr_variant * d;
1793    tr_torrent * tor = vtor;
1794
1795    assert (tr_isTorrent (tor));
1796
1797    d = tr_variantListAddDict (&tor->session->removedTorrents, 2);
1798    tr_variantDictAddInt (d, TR_KEY_id, tor->uniqueId);
1799    tr_variantDictAddInt (d, TR_KEY_date, tr_time ());
1800
1801    tr_torinf (tor, "%s", _("Removing torrent"));
1802
1803    stopTorrent (tor);
1804
1805    if (tor->isDeleting)
1806    {
1807        tr_metainfoRemoveSaved (tor->session, &tor->info);
1808        tr_torrentRemoveResume (tor);
1809    }
1810
1811    tor->isRunning = 0;
1812    freeTorrent (tor);
1813}
1814
1815void
1816tr_torrentFree (tr_torrent * tor) 
1817{
1818  if (tr_isTorrent (tor)) 
1819    { 
1820      tr_session * session = tor->session; 
1821      assert (tr_isSession (session)); 
1822      tr_sessionLock (session); 
1823
1824      tr_torrentClearCompletenessCallback (tor); 
1825      tr_runInEventThread (session, closeTorrent, tor); 
1826
1827      tr_sessionUnlock (session); 
1828    } 
1829}
1830
1831struct remove_data
1832{
1833    tr_torrent   * tor;
1834    bool           deleteFlag;
1835    tr_fileFunc  * deleteFunc;
1836};
1837
1838static void tr_torrentDeleteLocalData (tr_torrent *, tr_fileFunc);
1839
1840static void
1841removeTorrent (void * vdata)
1842{
1843    struct remove_data * data = vdata;
1844
1845    if (data->deleteFlag)
1846        tr_torrentDeleteLocalData (data->tor, data->deleteFunc);
1847
1848    tr_torrentClearCompletenessCallback (data->tor);
1849    closeTorrent (data->tor);
1850    tr_free (data);
1851}
1852
1853void
1854tr_torrentRemove (tr_torrent   * tor,
1855                  bool           deleteFlag,
1856                  tr_fileFunc    deleteFunc)
1857{
1858    struct remove_data * data;
1859
1860    assert (tr_isTorrent (tor));
1861    tor->isDeleting = 1;
1862
1863    data = tr_new0 (struct remove_data, 1);
1864    data->tor = tor;
1865    data->deleteFlag = deleteFlag;
1866    data->deleteFunc = deleteFunc;
1867    tr_runInEventThread (tor->session, removeTorrent, data);
1868}
1869
1870/**
1871***  Completeness
1872**/
1873
1874static const char *
1875getCompletionString (int type)
1876{
1877    switch (type)
1878    {
1879        /* Translators: this is a minor point that's safe to skip over, but FYI:
1880           "Complete" and "Done" are specific, different terms in Transmission:
1881           "Complete" means we've downloaded every file in the torrent.
1882           "Done" means we're done downloading the files we wanted, but NOT all
1883           that exist */
1884        case TR_PARTIAL_SEED:
1885            return _("Done");
1886
1887        case TR_SEED:
1888            return _("Complete");
1889
1890        default:
1891            return _("Incomplete");
1892    }
1893}
1894
1895static void
1896fireCompletenessChange (tr_torrent       * tor,
1897                        tr_completeness    status,
1898                        bool               wasRunning)
1899{
1900    assert ((status == TR_LEECH)
1901         || (status == TR_SEED)
1902         || (status == TR_PARTIAL_SEED));
1903
1904    if (tor->completeness_func)
1905        tor->completeness_func (tor, status, wasRunning,
1906                                tor->completeness_func_user_data);
1907}
1908
1909void
1910tr_torrentSetCompletenessCallback (tr_torrent                    * tor,
1911                                   tr_torrent_completeness_func    func,
1912                                   void                          * user_data)
1913{
1914    assert (tr_isTorrent (tor));
1915
1916    tor->completeness_func = func;
1917    tor->completeness_func_user_data = user_data;
1918}
1919
1920void
1921tr_torrentClearCompletenessCallback (tr_torrent * torrent)
1922{
1923    tr_torrentSetCompletenessCallback (torrent, NULL, NULL);
1924}
1925
1926void
1927tr_torrentSetRatioLimitHitCallback (tr_torrent                     * tor,
1928                                    tr_torrent_ratio_limit_hit_func  func,
1929                                    void                           * user_data)
1930{
1931    assert (tr_isTorrent (tor));
1932
1933    tor->ratio_limit_hit_func = func;
1934    tor->ratio_limit_hit_func_user_data = user_data;
1935}
1936
1937void
1938tr_torrentClearRatioLimitHitCallback (tr_torrent * torrent)
1939{
1940    tr_torrentSetRatioLimitHitCallback (torrent, NULL, NULL);
1941}
1942
1943void
1944tr_torrentSetIdleLimitHitCallback (tr_torrent                    * tor,
1945                                   tr_torrent_idle_limit_hit_func  func,
1946                                   void                          * user_data)
1947{
1948    assert (tr_isTorrent (tor));
1949
1950    tor->idle_limit_hit_func = func;
1951    tor->idle_limit_hit_func_user_data = user_data;
1952}
1953
1954void
1955tr_torrentClearIdleLimitHitCallback (tr_torrent * torrent)
1956{
1957    tr_torrentSetIdleLimitHitCallback (torrent, NULL, NULL);
1958}
1959
1960static void
1961onSigCHLD (int i UNUSED)
1962{
1963    waitpid (-1, NULL, WNOHANG);
1964}
1965
1966static void
1967torrentCallScript (const tr_torrent * tor, const char * script)
1968{
1969    char timeStr[128];
1970    const time_t now = tr_time ();
1971
1972    tr_strlcpy (timeStr, ctime (&now), sizeof (timeStr));
1973    *strchr (timeStr,'\n') = '\0';
1974
1975    if (script && *script)
1976    {
1977        int i;
1978        char * cmd[] = { tr_strdup (script), NULL };
1979        char * env[] = {
1980            tr_strdup_printf ("TR_APP_VERSION=%s", SHORT_VERSION_STRING),
1981            tr_strdup_printf ("TR_TIME_LOCALTIME=%s", timeStr),
1982            tr_strdup_printf ("TR_TORRENT_DIR=%s", tor->currentDir),
1983            tr_strdup_printf ("TR_TORRENT_ID=%d", tr_torrentId (tor)),
1984            tr_strdup_printf ("TR_TORRENT_HASH=%s", tor->info.hashString),
1985            tr_strdup_printf ("TR_TORRENT_NAME=%s", tr_torrentName (tor)),
1986            NULL };
1987
1988        tr_torinf (tor, "Calling script \"%s\"", script);
1989
1990#ifdef WIN32
1991        if (_spawnvpe (_P_NOWAIT, script, (const char*)cmd, env) == -1)
1992          tr_torerr (tor, "error executing script \"%s\": %s", cmd[0], tr_strerror (errno));
1993#else
1994        signal (SIGCHLD, onSigCHLD);
1995
1996        if (!fork ())
1997        {
1998            for (i=0; env[i]; ++i)
1999                putenv (env[i]);
2000
2001            if (execvp (script, cmd) == -1)
2002              tr_torerr (tor, "error executing script \"%s\": %s", cmd[0], tr_strerror (errno));
2003
2004            _exit (0);
2005        }
2006#endif
2007
2008        for (i=0; cmd[i]; ++i) tr_free (cmd[i]);
2009        for (i=0; env[i]; ++i) tr_free (env[i]);
2010    }
2011}
2012
2013void
2014tr_torrentRecheckCompleteness (tr_torrent * tor)
2015{
2016  tr_completeness completeness;
2017
2018  tr_torrentLock (tor);
2019
2020  completeness = tr_cpGetStatus (&tor->completion);
2021  if (completeness != tor->completeness)
2022    {
2023      const int recentChange = tor->downloadedCur != 0;
2024      const bool wasLeeching = !tr_torrentIsSeed (tor);
2025      const bool wasRunning = tor->isRunning;
2026
2027      if (recentChange)
2028        tr_torinf (tor, _("State changed from \"%1$s\" to \"%2$s\""),
2029                   getCompletionString (tor->completeness),
2030                   getCompletionString (completeness));
2031
2032      tor->completeness = completeness;
2033      tr_fdTorrentClose (tor->session, tor->uniqueId);
2034
2035      fireCompletenessChange (tor, completeness, wasRunning);
2036
2037      if (tr_torrentIsSeed (tor))
2038        {
2039          if (recentChange)
2040            {
2041              tr_announcerTorrentCompleted (tor);
2042              tor->doneDate = tor->anyDate = tr_time ();
2043            }
2044
2045          if (wasLeeching && wasRunning)
2046            {
2047              /* clear interested flag on all peers */
2048              tr_peerMgrClearInterest (tor);
2049
2050              /* if completeness was TR_LEECH then the seed limit check will have been skipped in bandwidthPulse */
2051              tr_torrentCheckSeedLimit (tor);
2052            }
2053
2054          if (tor->currentDir == tor->incompleteDir)
2055            tr_torrentSetLocation (tor, tor->downloadDir, true, NULL, NULL);
2056
2057          if (tr_sessionIsTorrentDoneScriptEnabled (tor->session))
2058            torrentCallScript (tor, tr_sessionGetTorrentDoneScript (tor->session));
2059        }
2060
2061      tr_torrentSetDirty (tor);
2062    }
2063
2064  tr_torrentUnlock (tor);
2065}
2066
2067/***
2068****
2069***/
2070
2071static void
2072tr_torrentFireMetadataCompleted (tr_torrent * tor)
2073{
2074    assert (tr_isTorrent (tor));
2075
2076    if (tor->metadata_func)
2077        tor->metadata_func (tor, tor->metadata_func_user_data);
2078}
2079
2080void
2081tr_torrentSetMetadataCallback (tr_torrent                * tor,
2082                               tr_torrent_metadata_func    func,
2083                               void                      * user_data)
2084{
2085    assert (tr_isTorrent (tor));
2086
2087    tor->metadata_func = func;
2088    tor->metadata_func_user_data = user_data;
2089}
2090
2091
2092/**
2093***  File priorities
2094**/
2095
2096void
2097tr_torrentInitFilePriority (tr_torrent *    tor,
2098                            tr_file_index_t fileIndex,
2099                            tr_priority_t   priority)
2100{
2101    tr_piece_index_t i;
2102    tr_file *        file;
2103
2104    assert (tr_isTorrent (tor));
2105    assert (fileIndex < tor->info.fileCount);
2106    assert (tr_isPriority (priority));
2107
2108    file = &tor->info.files[fileIndex];
2109    file->priority = priority;
2110    for (i = file->firstPiece; i <= file->lastPiece; ++i)
2111        tor->info.pieces[i].priority = calculatePiecePriority (tor, i, fileIndex);
2112}
2113
2114void
2115tr_torrentSetFilePriorities (tr_torrent             * tor,
2116                             const tr_file_index_t  * files,
2117                             tr_file_index_t          fileCount,
2118                             tr_priority_t            priority)
2119{
2120    tr_file_index_t i;
2121    assert (tr_isTorrent (tor));
2122    tr_torrentLock (tor);
2123
2124    for (i = 0; i < fileCount; ++i)
2125        if (files[i] < tor->info.fileCount)
2126            tr_torrentInitFilePriority (tor, files[i], priority);
2127    tr_torrentSetDirty (tor);
2128    tr_peerMgrRebuildRequests (tor);
2129
2130    tr_torrentUnlock (tor);
2131}
2132
2133tr_priority_t*
2134tr_torrentGetFilePriorities (const tr_torrent * tor)
2135{
2136  tr_file_index_t i;
2137  tr_priority_t * p;
2138
2139  assert (tr_isTorrent (tor));
2140
2141  p = tr_new0 (tr_priority_t, tor->info.fileCount);
2142
2143  for (i=0; i<tor->info.fileCount; ++i)
2144    p[i] = tor->info.files[i].priority;
2145
2146  return p;
2147}
2148
2149/**
2150***  File DND
2151**/
2152
2153static void
2154setFileDND (tr_torrent * tor, tr_file_index_t fileIndex, int doDownload)
2155{
2156    const int8_t     dnd = !doDownload;
2157    tr_piece_index_t firstPiece;
2158    int8_t           firstPieceDND;
2159    tr_piece_index_t lastPiece;
2160    int8_t           lastPieceDND;
2161    tr_file_index_t  i;
2162    tr_file *        file = &tor->info.files[fileIndex];
2163
2164    file->dnd = dnd;
2165    firstPiece = file->firstPiece;
2166    lastPiece = file->lastPiece;
2167
2168    /* can't set the first piece to DND unless
2169       every file using that piece is DND */
2170    firstPieceDND = dnd;
2171    if (fileIndex > 0)
2172    {
2173        for (i = fileIndex - 1; firstPieceDND; --i)
2174        {
2175            if (tor->info.files[i].lastPiece != firstPiece)
2176                break;
2177            firstPieceDND = tor->info.files[i].dnd;
2178            if (!i)
2179                break;
2180        }
2181    }
2182
2183    /* can't set the last piece to DND unless
2184       every file using that piece is DND */
2185    lastPieceDND = dnd;
2186    for (i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i)
2187    {
2188        if (tor->info.files[i].firstPiece != lastPiece)
2189            break;
2190        lastPieceDND = tor->info.files[i].dnd;
2191    }
2192
2193    if (firstPiece == lastPiece)
2194    {
2195        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
2196    }
2197    else
2198    {
2199        tr_piece_index_t pp;
2200        tor->info.pieces[firstPiece].dnd = firstPieceDND;
2201        tor->info.pieces[lastPiece].dnd = lastPieceDND;
2202        for (pp = firstPiece + 1; pp < lastPiece; ++pp)
2203            tor->info.pieces[pp].dnd = dnd;
2204    }
2205}
2206
2207void
2208tr_torrentInitFileDLs (tr_torrent             * tor,
2209                       const tr_file_index_t  * files,
2210                       tr_file_index_t          fileCount,
2211                       bool                     doDownload)
2212{
2213    tr_file_index_t i;
2214
2215    assert (tr_isTorrent (tor));
2216
2217    tr_torrentLock (tor);
2218
2219    for (i=0; i<fileCount; ++i)
2220        if (files[i] < tor->info.fileCount)
2221            setFileDND (tor, files[i], doDownload);
2222
2223    tr_cpInvalidateDND (&tor->completion);
2224
2225    tr_torrentUnlock (tor);
2226}
2227
2228void
2229tr_torrentSetFileDLs (tr_torrent             * tor,
2230                      const tr_file_index_t  * files,
2231                      tr_file_index_t          fileCount,
2232                      bool                     doDownload)
2233{
2234    assert (tr_isTorrent (tor));
2235    tr_torrentLock (tor);
2236
2237    tr_torrentInitFileDLs (tor, files, fileCount, doDownload);
2238    tr_torrentSetDirty (tor);
2239    tr_torrentRecheckCompleteness (tor);
2240    tr_peerMgrRebuildRequests (tor);
2241
2242    tr_torrentUnlock (tor);
2243}
2244
2245/***
2246****
2247***/
2248
2249tr_priority_t
2250tr_torrentGetPriority (const tr_torrent * tor)
2251{
2252    assert (tr_isTorrent (tor));
2253
2254    return tor->bandwidth.priority;
2255}
2256
2257void
2258tr_torrentSetPriority (tr_torrent * tor, tr_priority_t priority)
2259{
2260    assert (tr_isTorrent (tor));
2261    assert (tr_isPriority (priority));
2262
2263    if (tor->bandwidth.priority != priority)
2264    {
2265        tor->bandwidth.priority = priority;
2266
2267        tr_torrentSetDirty (tor);
2268    }
2269}
2270
2271/***
2272****
2273***/
2274
2275void
2276tr_torrentSetPeerLimit (tr_torrent * tor,
2277                        uint16_t     maxConnectedPeers)
2278{
2279    assert (tr_isTorrent (tor));
2280
2281    if (tor->maxConnectedPeers != maxConnectedPeers)
2282    {
2283        tor->maxConnectedPeers = maxConnectedPeers;
2284
2285        tr_torrentSetDirty (tor);
2286    }
2287}
2288
2289uint16_t
2290tr_torrentGetPeerLimit (const tr_torrent * tor)
2291{
2292    assert (tr_isTorrent (tor));
2293
2294    return tor->maxConnectedPeers;
2295}
2296
2297/***
2298****
2299***/
2300
2301void
2302tr_torrentGetBlockLocation (const tr_torrent * tor,
2303                            tr_block_index_t   block,
2304                            tr_piece_index_t * piece,
2305                            uint32_t         * offset,
2306                            uint32_t         * length)
2307{
2308    uint64_t pos = block;
2309    pos *= tor->blockSize;
2310    *piece = pos / tor->info.pieceSize;
2311    *offset = pos - (*piece * tor->info.pieceSize);
2312    *length = tr_torBlockCountBytes (tor, block);
2313}
2314
2315
2316tr_block_index_t
2317_tr_block (const tr_torrent * tor,
2318           tr_piece_index_t   index,
2319           uint32_t           offset)
2320{
2321    tr_block_index_t ret;
2322
2323    assert (tr_isTorrent (tor));
2324
2325    ret = index;
2326    ret *= (tor->info.pieceSize / tor->blockSize);
2327    ret += offset / tor->blockSize;
2328    return ret;
2329}
2330
2331bool
2332tr_torrentReqIsValid (const tr_torrent * tor,
2333                      tr_piece_index_t   index,
2334                      uint32_t           offset,
2335                      uint32_t           length)
2336{
2337    int err = 0;
2338
2339    assert (tr_isTorrent (tor));
2340
2341    if (index >= tor->info.pieceCount)
2342        err = 1;
2343    else if (length < 1)
2344        err = 2;
2345    else if ((offset + length) > tr_torPieceCountBytes (tor, index))
2346        err = 3;
2347    else if (length > MAX_BLOCK_SIZE)
2348        err = 4;
2349    else if (tr_pieceOffset (tor, index, offset, length) > tor->info.totalSize)
2350        err = 5;
2351
2352    if (err) tr_tordbg (tor, "index %lu offset %lu length %lu err %d\n",
2353                            (unsigned long)index,
2354                            (unsigned long)offset,
2355                            (unsigned long)length,
2356                              err);
2357
2358    return !err;
2359}
2360
2361uint64_t
2362tr_pieceOffset (const tr_torrent * tor,
2363                tr_piece_index_t   index,
2364                uint32_t           offset,
2365                uint32_t           length)
2366{
2367    uint64_t ret;
2368
2369    assert (tr_isTorrent (tor));
2370
2371    ret = tor->info.pieceSize;
2372    ret *= index;
2373    ret += offset;
2374    ret += length;
2375    return ret;
2376}
2377
2378void
2379tr_torGetFileBlockRange (const tr_torrent        * tor,
2380                         const tr_file_index_t     file,
2381                         tr_block_index_t        * first,
2382                         tr_block_index_t        * last)
2383{
2384    const tr_file * f = &tor->info.files[file];
2385    uint64_t offset = f->offset;
2386    *first = offset / tor->blockSize;
2387    if (!f->length)
2388        *last = *first;
2389    else {
2390        offset += f->length - 1;
2391        *last = offset / tor->blockSize;
2392    }
2393}
2394
2395void
2396tr_torGetPieceBlockRange (const tr_torrent        * tor,
2397                          const tr_piece_index_t    piece,
2398                          tr_block_index_t        * first,
2399                          tr_block_index_t        * last)
2400{
2401    uint64_t offset = tor->info.pieceSize;
2402    offset *= piece;
2403    *first = offset / tor->blockSize;
2404    offset += (tr_torPieceCountBytes (tor, piece) - 1);
2405    *last = offset / tor->blockSize;
2406}
2407
2408
2409/***
2410****
2411***/
2412
2413void
2414tr_torrentSetPieceChecked (tr_torrent * tor, tr_piece_index_t pieceIndex)
2415{
2416    assert (tr_isTorrent (tor));
2417    assert (pieceIndex < tor->info.pieceCount);
2418
2419    tor->info.pieces[pieceIndex].timeChecked = tr_time ();
2420}
2421
2422void
2423tr_torrentSetChecked (tr_torrent * tor, time_t when)
2424{
2425    tr_piece_index_t i, n;
2426
2427    assert (tr_isTorrent (tor));
2428
2429    for (i=0, n=tor->info.pieceCount; i!=n; ++i)
2430        tor->info.pieces[i].timeChecked = when;
2431}
2432
2433bool
2434tr_torrentCheckPiece (tr_torrent * tor, tr_piece_index_t pieceIndex)
2435{
2436    const bool pass = tr_ioTestPiece (tor, pieceIndex);
2437
2438    tr_deeplog_tor (tor, "[LAZY] tr_torrentCheckPiece tested piece %zu, pass==%d", (size_t)pieceIndex, (int)pass);
2439    tr_torrentSetHasPiece (tor, pieceIndex, pass);
2440    tr_torrentSetPieceChecked (tor, pieceIndex);
2441    tor->anyDate = tr_time ();
2442    tr_torrentSetDirty (tor);
2443
2444    return pass;
2445}
2446
2447time_t
2448tr_torrentGetFileMTime (const tr_torrent * tor, tr_file_index_t i)
2449{
2450    time_t mtime = 0;
2451    if (!tr_fdFileGetCachedMTime (tor->session, tor->uniqueId, i, &mtime))
2452        tr_torrentFindFile2 (tor, i, NULL, NULL, &mtime);
2453    return mtime;
2454}
2455
2456bool
2457tr_torrentPieceNeedsCheck (const tr_torrent * tor, tr_piece_index_t p)
2458{
2459    uint64_t unused;
2460    tr_file_index_t f;
2461    const tr_info * inf = tr_torrentInfo (tor);
2462
2463    /* if we've never checked this piece, then it needs to be checked */
2464    if (!inf->pieces[p].timeChecked)
2465        return true;
2466
2467    /* If we think we've completed one of the files in this piece,
2468     * but it's been modified since we last checked it,
2469     * then it needs to be rechecked */
2470    tr_ioFindFileLocation (tor, p, 0, &f, &unused);
2471    for (; f < inf->fileCount && pieceHasFile (p, &inf->files[f]); ++f)
2472        if (tr_cpFileIsComplete (&tor->completion, f))
2473            if (tr_torrentGetFileMTime (tor, f) > inf->pieces[p].timeChecked)
2474                return true;
2475
2476    return false;
2477}
2478
2479/***
2480****
2481***/
2482
2483static int
2484compareTrackerByTier (const void * va, const void * vb)
2485{
2486    const tr_tracker_info * a = va;
2487    const tr_tracker_info * b = vb;
2488
2489    /* sort by tier */
2490    if (a->tier != b->tier)
2491        return a->tier - b->tier;
2492
2493    /* get the effects of a stable sort by comparing the two elements' addresses */
2494    return a - b;
2495}
2496
2497bool
2498tr_torrentSetAnnounceList (tr_torrent             * tor,
2499                           const tr_tracker_info  * trackers_in,
2500                           int                      trackerCount)
2501{
2502    int i;
2503    tr_variant metainfo;
2504    bool ok = true;
2505    tr_tracker_info * trackers;
2506
2507    tr_torrentLock (tor);
2508
2509    assert (tr_isTorrent (tor));
2510
2511    /* ensure the trackers' tiers are in ascending order */
2512    trackers = tr_memdup (trackers_in, sizeof (tr_tracker_info) * trackerCount);
2513    qsort (trackers, trackerCount, sizeof (tr_tracker_info), compareTrackerByTier);
2514
2515    /* look for bad URLs */
2516    for (i=0; ok && i<trackerCount; ++i)
2517        if (!tr_urlIsValidTracker (trackers[i].announce))
2518            ok = false;
2519
2520    /* save to the .torrent file */
2521    if (ok && !tr_variantFromFile (&metainfo, TR_VARIANT_FMT_BENC, tor->info.torrent))
2522    {
2523        bool hasInfo;
2524        tr_info tmpInfo;
2525
2526        /* remove the old fields */
2527        tr_variantDictRemove (&metainfo, TR_KEY_announce);
2528        tr_variantDictRemove (&metainfo, TR_KEY_announce_list);
2529
2530        /* add the new fields */
2531        if (trackerCount > 0)
2532        {
2533            tr_variantDictAddStr (&metainfo, TR_KEY_announce, trackers[0].announce);
2534        }
2535        if (trackerCount > 1)
2536        {
2537            int i;
2538            int prevTier = -1;
2539            tr_variant * tier = NULL;
2540            tr_variant * announceList = tr_variantDictAddList (&metainfo, TR_KEY_announce_list, 0);
2541
2542            for (i=0; i<trackerCount; ++i) {
2543                if (prevTier != trackers[i].tier) {
2544                    prevTier = trackers[i].tier;
2545                    tier = tr_variantListAddList (announceList, 0);
2546                }
2547                tr_variantListAddStr (tier, trackers[i].announce);
2548            }
2549        }
2550
2551        /* try to parse it back again, to make sure it's good */
2552        memset (&tmpInfo, 0, sizeof (tr_info));
2553        if (tr_metainfoParse (tor->session, &metainfo, &tmpInfo,
2554                              &hasInfo, &tor->infoDictLength))
2555        {
2556            /* it's good, so keep these new trackers and free the old ones */
2557
2558            tr_info swap;
2559            swap.trackers = tor->info.trackers;
2560            swap.trackerCount = tor->info.trackerCount;
2561            tor->info.trackers = tmpInfo.trackers;
2562            tor->info.trackerCount = tmpInfo.trackerCount;
2563            tmpInfo.trackers = swap.trackers;
2564            tmpInfo.trackerCount = swap.trackerCount;
2565
2566            tr_metainfoFree (&tmpInfo);
2567            tr_variantToFile (&metainfo, TR_VARIANT_FMT_BENC, tor->info.torrent);
2568        }
2569
2570        /* cleanup */
2571        tr_variantFree (&metainfo);
2572
2573        /* if we had a tracker-related error on this torrent,
2574         * and that tracker's been removed,
2575         * then clear the error */
2576        if ((tor->error == TR_STAT_TRACKER_WARNING)
2577            || (tor->error == TR_STAT_TRACKER_ERROR))
2578        {
2579            bool clear = true;
2580
2581            for (i=0; clear && i<trackerCount; ++i)
2582                if (!strcmp (trackers[i].announce, tor->errorTracker))
2583                    clear = false;
2584
2585            if (clear)
2586                tr_torrentClearError (tor);
2587        }
2588
2589        /* tell the announcer to reload this torrent's tracker list */
2590        tr_announcerResetTorrent (tor->session->announcer, tor);
2591    }
2592
2593    tr_torrentUnlock (tor);
2594
2595    tr_free (trackers);
2596    return ok;
2597}
2598
2599/**
2600***
2601**/
2602
2603void
2604tr_torrentSetAddedDate (tr_torrent * tor,
2605                        time_t       t)
2606{
2607    assert (tr_isTorrent (tor));
2608
2609    tor->addedDate = t;
2610    tor->anyDate = MAX (tor->anyDate, tor->addedDate);
2611}
2612
2613void
2614tr_torrentSetActivityDate (tr_torrent * tor, time_t t)
2615{
2616    assert (tr_isTorrent (tor));
2617
2618    tor->activityDate = t;
2619    tor->anyDate = MAX (tor->anyDate, tor->activityDate);
2620}
2621
2622void
2623tr_torrentSetDoneDate (tr_torrent * tor,
2624                       time_t       t)
2625{
2626    assert (tr_isTorrent (tor));
2627
2628    tor->doneDate = t;
2629    tor->anyDate = MAX (tor->anyDate, tor->doneDate);
2630}
2631
2632/**
2633***
2634**/
2635
2636uint64_t
2637tr_torrentGetBytesLeftToAllocate (const tr_torrent * tor)
2638{
2639    tr_file_index_t i;
2640    uint64_t bytesLeft = 0;
2641
2642    assert (tr_isTorrent (tor));
2643
2644    for (i=0; i<tor->info.fileCount; ++i)
2645    {
2646        if (!tor->info.files[i].dnd)
2647        {
2648            struct stat sb;
2649            const uint64_t length = tor->info.files[i].length;
2650            char * path = tr_torrentFindFile (tor, i);
2651
2652            bytesLeft += length;
2653
2654            if ((path != NULL) && !stat (path, &sb)
2655                                 && S_ISREG (sb.st_mode)
2656                                 && ((uint64_t)sb.st_size <= length))
2657                bytesLeft -= sb.st_size;
2658
2659            tr_free (path);
2660        }
2661    }
2662
2663    return bytesLeft;
2664}
2665
2666/****
2667*****  Removing the torrent's local data
2668****/
2669
2670static bool
2671isJunkFile (const char * base)
2672{
2673    int i;
2674    static const char * files[] = { ".DS_Store", "desktop.ini", "Thumbs.db" };
2675    static const int file_count = sizeof (files) / sizeof (files[0]);
2676
2677    for (i=0; i<file_count; ++i)
2678        if (!strcmp (base, files[i]))
2679            return true;
2680
2681#ifdef SYS_DARWIN
2682    /* check for resource forks. <http://support.apple.com/kb/TA20578> */
2683    if (!memcmp (base, "._", 2))
2684        return true;
2685#endif
2686
2687    return false;
2688}
2689
2690static void
2691removeEmptyFoldersAndJunkFiles (const char * folder)
2692{
2693    DIR * odir;
2694    if ((odir = opendir (folder))) {
2695        struct dirent * d;
2696        while ((d = readdir (odir))) {
2697            if (strcmp (d->d_name, ".") && strcmp (d->d_name, "..")) {
2698                struct stat sb;
2699                char * filename = tr_buildPath (folder, d->d_name, NULL);
2700                if (!stat (filename, &sb) && S_ISDIR (sb.st_mode))
2701                    removeEmptyFoldersAndJunkFiles (filename);
2702                else if (isJunkFile (d->d_name))
2703                    remove (filename);
2704                tr_free (filename);
2705            }
2706        }
2707        remove (folder);
2708        closedir (odir);
2709    }
2710}
2711
2712/**
2713 * This convoluted code does something (seemingly) simple:
2714 * remove the torrent's local files.
2715 *
2716 * Fun complications:
2717 * 1. Try to preserve the directory hierarchy in the recycle bin.
2718 * 2. If there are nontorrent files, don't delete them...
2719 * 3. ...unless the other files are "junk", such as .DS_Store
2720 */
2721static void
2722deleteLocalData (tr_torrent * tor, tr_fileFunc func)
2723{
2724    int i, n;
2725    tr_file_index_t f;
2726    char * base;
2727    DIR * odir;
2728    char * tmpdir = NULL;
2729    tr_ptrArray files = TR_PTR_ARRAY_INIT;
2730    tr_ptrArray folders = TR_PTR_ARRAY_INIT;
2731    const void * const vstrcmp = strcmp;
2732    const char * const top = tor->currentDir;
2733
2734    /* if it's a magnet link, there's nothing to move... */
2735    if (!tr_torrentHasMetadata (tor))
2736        return;
2737
2738    /***
2739    ****  Move the local data to a new tmpdir
2740    ***/
2741
2742    base = tr_strdup_printf ("%s__XXXXXX", tr_torrentName (tor));
2743    tmpdir = tr_buildPath (top, base, NULL);
2744    tr_mkdtemp (tmpdir);
2745    tr_free (base);
2746
2747    for (f=0; f<tor->info.fileCount; ++f)
2748    {
2749        char * filename = tr_buildPath (top, tor->info.files[f].name, NULL);
2750        if (!tr_fileExists (filename, NULL)) {
2751                char * partial = tr_torrentBuildPartial (tor, f);
2752                tr_free (filename);
2753                filename = tr_buildPath (top, partial, NULL);
2754                tr_free (partial);
2755                if (!tr_fileExists (filename, NULL)) {
2756                        tr_free (filename);
2757                        filename = NULL;
2758                }
2759        }
2760
2761        if (filename != NULL)
2762        {
2763            char * target = tr_buildPath (tmpdir, tor->info.files[f].name, NULL);
2764            char * target_dir = tr_dirname (target);
2765            tr_mkdirp (target_dir, 0777);
2766            rename (filename, target);
2767            tr_ptrArrayAppend (&files, target);
2768            tr_free (target_dir);
2769            tr_free (filename);
2770        }
2771    }
2772
2773    /***
2774    ****  Remove tmpdir.
2775    ****
2776    ****  Try deleting the top-level files & folders to preserve
2777    ****  the directory hierarchy in the recycle bin.
2778    ****  If case that fails -- for example, rmdir () doesn't
2779    ****  delete nonempty folders -- go from the bottom up too.
2780    ***/
2781
2782    /* try deleting the local data's top-level files & folders */
2783    if ((odir = opendir (tmpdir)))
2784    {
2785        struct dirent * d;
2786        while ((d = readdir (odir)))
2787        {
2788            if (strcmp (d->d_name, ".") && strcmp (d->d_name, ".."))
2789            {
2790                char * file = tr_buildPath (tmpdir, d->d_name, NULL);
2791                func (file);
2792                tr_free (file);
2793            }
2794        }
2795        closedir (odir);
2796    }
2797
2798    /* go from the bottom up */
2799    for (i=0, n=tr_ptrArraySize (&files); i<n; ++i)
2800    {
2801        char * walk = tr_strdup (tr_ptrArrayNth (&files, i));
2802        while (tr_fileExists (walk, NULL) && !tr_is_same_file (tmpdir, walk))
2803        {
2804            char * tmp = tr_dirname (walk);
2805            func (walk);
2806            tr_free (walk);
2807            walk = tmp;
2808        }
2809        tr_free (walk);
2810    }
2811
2812    /***
2813    ****  The local data has been removed.
2814    ****  What's left in top are empty folders, junk, and user-generated files.
2815    ****  Remove the first two categories and leave the third.
2816    ***/
2817
2818    /* build a list of 'top's child directories that belong to this torrent */
2819    for (f=0; f<tor->info.fileCount; ++f)
2820    {
2821        /* get the directory that this file goes in... */
2822        char * filename = tr_buildPath (top, tor->info.files[f].name, NULL);
2823        char * dir = tr_dirname (filename);
2824        if (!tr_is_same_file (top, dir) && strcmp (top, dir)) {
2825            for (;;) {
2826                char * parent = tr_dirname (dir);
2827                if (tr_is_same_file (top, parent) || !strcmp (top, parent)) {
2828                    if (tr_ptrArrayFindSorted (&folders, dir, vstrcmp) == NULL) {
2829                        tr_ptrArrayInsertSorted (&folders, tr_strdup (dir), vstrcmp);
2830                    }
2831                    break;
2832                }
2833                tr_free (dir);
2834                dir = parent;
2835            }
2836        }
2837        tr_free (dir);
2838        tr_free (filename);
2839    }
2840    for (i=0, n=tr_ptrArraySize (&folders); i<n; ++i)
2841        removeEmptyFoldersAndJunkFiles (tr_ptrArrayNth (&folders, i));
2842
2843    /* cleanup */
2844    rmdir (tmpdir);
2845    tr_free (tmpdir);
2846    tr_ptrArrayDestruct (&folders, tr_free);
2847    tr_ptrArrayDestruct (&files, tr_free);
2848}
2849
2850static void
2851tr_torrentDeleteLocalData (tr_torrent * tor, tr_fileFunc func)
2852{
2853    assert (tr_isTorrent (tor));
2854
2855    if (func == NULL)
2856        func = remove;
2857
2858    /* close all the files because we're about to delete them */
2859    tr_cacheFlushTorrent (tor->session->cache, tor);
2860    tr_fdTorrentClose (tor->session, tor->uniqueId);
2861
2862    deleteLocalData (tor, func);
2863}
2864
2865/***
2866****
2867***/
2868
2869struct LocationData
2870{
2871    bool move_from_old_location;
2872    volatile int * setme_state;
2873    volatile double * setme_progress;
2874    char * location;
2875    tr_torrent * tor;
2876};
2877
2878static void
2879setLocation (void * vdata)
2880{
2881    bool err = false;
2882    struct LocationData * data = vdata;
2883    tr_torrent * tor = data->tor;
2884    const bool do_move = data->move_from_old_location;
2885    const char * location = data->location;
2886    double bytesHandled = 0;
2887
2888    assert (tr_isTorrent (tor));
2889
2890    tr_dbg ("Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2891            tr_torrentName (tor), tor->currentDir, location);
2892
2893    tr_mkdirp (location, 0777);
2894
2895    if (!tr_is_same_file (location, tor->currentDir))
2896    {
2897        tr_file_index_t i;
2898
2899        /* bad idea to move files while they're being verified... */
2900        tr_verifyRemove (tor);
2901
2902        /* try to move the files.
2903         * FIXME: there are still all kinds of nasty cases, like what
2904         * if the target directory runs out of space halfway through... */
2905        for (i=0; !err && i<tor->info.fileCount; ++i)
2906        {
2907            const tr_file * f = &tor->info.files[i];
2908            const char * oldbase;
2909            char * sub;
2910            if (tr_torrentFindFile2 (tor, i, &oldbase, &sub, NULL))
2911            {
2912                char * oldpath = tr_buildPath (oldbase, sub, NULL);
2913                char * newpath = tr_buildPath (location, sub, NULL);
2914
2915                tr_dbg ("Found file #%d: %s", (int)i, oldpath);
2916
2917                if (do_move && !tr_is_same_file (oldpath, newpath))
2918                {
2919                    bool renamed = false;
2920                    errno = 0;
2921                    tr_torinf (tor, "moving \"%s\" to \"%s\"", oldpath, newpath);
2922                    if (tr_moveFile (oldpath, newpath, &renamed))
2923                    {
2924                        err = true;
2925                        tr_torerr (tor, "error moving \"%s\" to \"%s\": %s",
2926                                        oldpath, newpath, tr_strerror (errno));
2927                    }
2928                }
2929
2930                tr_free (newpath);
2931                tr_free (oldpath);
2932                tr_free (sub);
2933            }
2934
2935            if (data->setme_progress)
2936            {
2937                bytesHandled += f->length;
2938                *data->setme_progress = bytesHandled / tor->info.totalSize;
2939            }
2940        }
2941
2942        if (!err)
2943        {
2944            /* blow away the leftover subdirectories in the old location */
2945            if (do_move)
2946                tr_torrentDeleteLocalData (tor, remove);
2947
2948            /* set the new location and reverify */
2949            tr_torrentSetDownloadDir (tor, location);
2950        }
2951    }
2952
2953    if (!err && do_move)
2954    {
2955        tr_free (tor->incompleteDir);
2956        tor->incompleteDir = NULL;
2957        tor->currentDir = tor->downloadDir;
2958    }
2959
2960    if (data->setme_state)
2961        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2962
2963    /* cleanup */
2964    tr_free (data->location);
2965    tr_free (data);
2966}
2967
2968void
2969tr_torrentSetLocation (tr_torrent       * tor,
2970                       const char       * location,
2971                       bool               move_from_old_location,
2972                       volatile double  * setme_progress,
2973                       volatile int     * setme_state)
2974{
2975    struct LocationData * data;
2976
2977    assert (tr_isTorrent (tor));
2978
2979    if (setme_state)
2980        *setme_state = TR_LOC_MOVING;
2981    if (setme_progress)
2982        *setme_progress = 0;
2983
2984    /* run this in the libtransmission thread */
2985    data = tr_new (struct LocationData, 1);
2986    data->tor = tor;
2987    data->location = tr_strdup (location);
2988    data->move_from_old_location = move_from_old_location;
2989    data->setme_state = setme_state;
2990    data->setme_progress = setme_progress;
2991    tr_runInEventThread (tor->session, setLocation, data);
2992}
2993
2994/***
2995****
2996***/
2997
2998void
2999tr_torrentFileCompleted (tr_torrent * tor, tr_file_index_t fileNum)
3000{
3001    char * sub;
3002    const char * base;
3003    const tr_info * inf = &tor->info;
3004    const tr_file * f = &inf->files[fileNum];
3005    tr_piece * p;
3006    const tr_piece * pend;
3007    const time_t now = tr_time ();
3008
3009    /* close the file so that we can reopen in read-only mode as needed */
3010    tr_fdFileClose (tor->session, tor, fileNum);
3011
3012    /* now that the file is complete and closed, we can start watching its
3013     * mtime timestamp for changes to know if we need to reverify pieces */
3014    for (p=&inf->pieces[f->firstPiece], pend=&inf->pieces[f->lastPiece]; p!=pend; ++p)
3015        p->timeChecked = now;
3016
3017    /* if the torrent's current filename isn't the same as the one in the
3018     * metadata -- for example, if it had the ".part" suffix appended to
3019     * it until now -- then rename it to match the one in the metadata */
3020    if (tr_torrentFindFile2 (tor, fileNum, &base, &sub, NULL))
3021    {
3022        if (strcmp (sub, f->name))
3023        {
3024            char * oldpath = tr_buildPath (base, sub, NULL);
3025            char * newpath = tr_buildPath (base, f->name, NULL);
3026
3027            if (rename (oldpath, newpath))
3028                tr_torerr (tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror (errno));
3029
3030            tr_free (newpath);
3031            tr_free (oldpath);
3032        }
3033
3034        tr_free (sub);
3035    }
3036}
3037
3038/***
3039****
3040***/
3041
3042bool
3043tr_torrentFindFile2 (const tr_torrent * tor, tr_file_index_t fileNum,
3044                     const char ** base, char ** subpath, time_t * mtime)
3045{
3046    char * part = NULL;
3047    const tr_file * file;
3048    const char * b = NULL;
3049    const char * s = NULL;
3050
3051    assert (tr_isTorrent (tor));
3052    assert (fileNum < tor->info.fileCount);
3053
3054    file = &tor->info.files[fileNum];
3055
3056    if (b == NULL) {
3057        char * filename = tr_buildPath (tor->downloadDir, file->name, NULL);
3058        if (tr_fileExists (filename, mtime)) {
3059            b = tor->downloadDir;
3060            s = file->name;
3061        }
3062        tr_free (filename);
3063    }
3064
3065    if ((b == NULL) && (tor->incompleteDir != NULL)) {
3066        char * filename = tr_buildPath (tor->incompleteDir, file->name, NULL);
3067        if (tr_fileExists (filename, mtime)) {
3068            b = tor->incompleteDir;
3069            s = file->name;
3070        }
3071        tr_free (filename);
3072    }
3073
3074    if (b == NULL)
3075        part = tr_torrentBuildPartial (tor, fileNum);
3076
3077    if ((b == NULL) && (tor->incompleteDir != NULL)) {
3078        char * filename = tr_buildPath (tor->incompleteDir, part, NULL);
3079        if (tr_fileExists (filename, mtime)) {
3080            b = tor->incompleteDir;
3081            s = part;
3082        }
3083        tr_free (filename);
3084    }
3085
3086    if (b == NULL) {
3087        char * filename = tr_buildPath (tor->downloadDir, part, NULL);
3088        if (tr_fileExists (filename, mtime)) {
3089            b = tor->downloadDir;
3090            s = part;
3091        }
3092        tr_free (filename);
3093    }
3094
3095    if (base != NULL)
3096        *base = b;
3097    if (subpath != NULL)
3098        *subpath = tr_strdup (s);
3099
3100    tr_free (part);
3101    return b != NULL;
3102}
3103
3104char*
3105tr_torrentFindFile (const tr_torrent * tor, tr_file_index_t fileNum)
3106{
3107    char * subpath;
3108    char * ret = NULL;
3109    const char * base;
3110
3111    if (tr_torrentFindFile2 (tor, fileNum, &base, &subpath, NULL))
3112    {
3113        ret = tr_buildPath (base, subpath, NULL);
3114        tr_free (subpath);
3115    }
3116
3117    return ret;
3118}
3119
3120/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
3121static void
3122refreshCurrentDir (tr_torrent * tor)
3123{
3124    const char * dir = NULL;
3125
3126    if (tor->incompleteDir == NULL)
3127        dir = tor->downloadDir;
3128    else if (!tr_torrentHasMetadata (tor)) /* no files to find */
3129        dir = tor->incompleteDir;
3130    else if (!tr_torrentFindFile2 (tor, 0, &dir, NULL, NULL))
3131        dir = tor->incompleteDir;
3132
3133    assert (dir != NULL);
3134    assert ((dir == tor->downloadDir) || (dir == tor->incompleteDir));
3135    tor->currentDir = dir;
3136}
3137
3138char*
3139tr_torrentBuildPartial (const tr_torrent * tor, tr_file_index_t fileNum)
3140{
3141    return tr_strdup_printf ("%s.part", tor->info.files[fileNum].name);
3142}
3143
3144/***
3145****
3146***/
3147
3148static int
3149compareTorrentByQueuePosition (const void * va, const void * vb)
3150{
3151    const tr_torrent * a = * (const tr_torrent **) va;
3152    const tr_torrent * b = * (const tr_torrent **) vb;
3153
3154    return a->queuePosition - b->queuePosition;
3155}
3156
3157#ifndef NDEBUG
3158static bool
3159queueIsSequenced (tr_session * session)
3160{
3161    int i ;
3162    int n ;
3163    bool is_sequenced = true;
3164    tr_torrent * tor;
3165    tr_torrent ** tmp = tr_new (tr_torrent *, session->torrentCount);
3166
3167    /* get all the torrents */
3168    n = 0;
3169    tor = NULL;
3170    while ((tor = tr_torrentNext (session, tor)))
3171        tmp[n++] = tor;
3172
3173    /* sort them by position */
3174    qsort (tmp, n, sizeof (tr_torrent *), compareTorrentByQueuePosition);
3175
3176#if 0
3177    fprintf (stderr, "%s", "queue: ");
3178    for (i=0; i<n; ++i)
3179        fprintf (stderr, "%d ", tmp[i]->queuePosition);
3180    fputc ('\n', stderr);
3181#endif
3182
3183    /* test them */
3184    for (i=0; is_sequenced && i<n; ++i)
3185        if (tmp[i]->queuePosition != i)
3186            is_sequenced = false;
3187
3188    tr_free (tmp);
3189    return is_sequenced;
3190}
3191#endif
3192
3193int
3194tr_torrentGetQueuePosition (const tr_torrent * tor)
3195{
3196    return tor->queuePosition;
3197}
3198
3199void
3200tr_torrentSetQueuePosition (tr_torrent * tor, int pos)
3201{
3202    int back = -1;
3203    tr_torrent * walk;
3204    const int old_pos = tor->queuePosition;
3205    const time_t now = tr_time ();
3206
3207    if (pos < 0)
3208        pos = 0;
3209
3210    tor->queuePosition = -1;
3211
3212    walk = NULL;
3213    while ((walk = tr_torrentNext (tor->session, walk)))
3214    {
3215        if (old_pos < pos) {
3216            if ((old_pos <= walk->queuePosition) && (walk->queuePosition <= pos)) {
3217                walk->queuePosition--;
3218                walk->anyDate = now;
3219            }
3220        }
3221
3222        if (old_pos > pos) {
3223            if ((pos <= walk->queuePosition) && (walk->queuePosition < old_pos)) {
3224                walk->queuePosition++;
3225                walk->anyDate = now;
3226            }
3227        }
3228
3229        if (back < walk->queuePosition)
3230            back = walk->queuePosition;
3231    }
3232
3233    tor->queuePosition = MIN (pos, (back+1));
3234    tor->anyDate = now;
3235
3236    assert (queueIsSequenced (tor->session));
3237}
3238
3239void
3240tr_torrentsQueueMoveTop (tr_torrent ** torrents_in, int n)
3241{
3242    int i;
3243    tr_torrent ** torrents = tr_memdup (torrents_in, sizeof (tr_torrent *) * n);
3244    qsort (torrents, n, sizeof (tr_torrent *), compareTorrentByQueuePosition);
3245    for (i=n-1; i>=0; --i)
3246        tr_torrentSetQueuePosition (torrents[i], 0);
3247    tr_free (torrents);
3248}
3249
3250void
3251tr_torrentsQueueMoveUp (tr_torrent ** torrents_in, int n)
3252{
3253    int i;
3254    tr_torrent ** torrents = tr_memdup (torrents_in, sizeof (tr_torrent *) * n);
3255    qsort (torrents, n, sizeof (tr_torrent *), compareTorrentByQueuePosition);
3256    for (i=0; i<n; ++i)
3257        tr_torrentSetQueuePosition (torrents[i], torrents[i]->queuePosition - 1);
3258    tr_free (torrents);
3259}
3260
3261void
3262tr_torrentsQueueMoveDown (tr_torrent ** torrents_in, int n)
3263{
3264    int i;
3265    tr_torrent ** torrents = tr_memdup (torrents_in, sizeof (tr_torrent *) * n);
3266    qsort (torrents, n, sizeof (tr_torrent *), compareTorrentByQueuePosition);
3267    for (i=n-1; i>=0; --i)
3268        tr_torrentSetQueuePosition (torrents[i], torrents[i]->queuePosition + 1);
3269    tr_free (torrents);
3270}
3271
3272void
3273tr_torrentsQueueMoveBottom (tr_torrent ** torrents_in, int n)
3274{
3275    int i;
3276    tr_torrent ** torrents = tr_memdup (torrents_in, sizeof (tr_torrent *) * n);
3277    qsort (torrents, n, sizeof (tr_torrent *), compareTorrentByQueuePosition);
3278    for (i=0; i<n; ++i)
3279        tr_torrentSetQueuePosition (torrents[i], INT_MAX);
3280    tr_free (torrents);
3281}
3282
3283static void
3284torrentSetQueued (tr_torrent * tor, bool queued)
3285{
3286    assert (tr_isTorrent (tor));
3287    assert (tr_isBool (queued));
3288
3289    if (tr_torrentIsQueued (tor) != queued)
3290    {
3291        tor->isQueued = queued;
3292        tor->anyDate = tr_time ();
3293    }
3294}
3295
3296void
3297tr_torrentSetQueueStartCallback (tr_torrent * torrent, void (*callback)(tr_torrent *, void *), void * user_data)
3298{
3299    torrent->queue_started_callback = callback;
3300    torrent->queue_started_user_data = user_data;
3301}
3302
3303
Note: See TracBrowser for help on using the repository browser.