source: trunk/libtransmission/torrent.c @ 14083

Last change on this file since 14083 was 14083, checked in by jordan, 9 years ago

(trunk, libT) fix tr_torrentStat() regression in the nightlies reported in #5294 by mw3demo

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