summaryrefslogtreecommitdiff
path: root/methods/copy.cc
blob: 9a8665446d56e99862baa4151737a87b8db65851 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// -*- mode: cpp; mode: fold -*-
// Description								/*{{{*/
/* ######################################################################

   Copy URI - This method takes a uri like a file: uri and copies it
   to the destination file.
   
   ##################################################################### */
									/*}}}*/
// Include Files							/*{{{*/
#include <config.h>

#include "aptmethod.h"
#include <apt-pkg/configuration.h>
#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/hashes.h>
#include <apt-pkg/strutl.h>

#include <string>
#include <sys/stat.h>
#include <sys/time.h>

#include <apti18n.h>
									/*}}}*/

class CopyMethod : public aptMethod
{
   virtual bool Fetch(FetchItem *Itm) APT_OVERRIDE;

   public:
   CopyMethod() : aptMethod("copy", "1.0", SingleInstance | SendConfig)
   {
      SeccompFlags = aptMethod::BASE;
   }
};

// CopyMethod::Fetch - Fetch a file					/*{{{*/
// ---------------------------------------------------------------------
/* */
bool CopyMethod::Fetch(FetchItem *Itm)
{
   // this ensures that relative paths work in copy
   std::string const File = Itm->Uri.substr(Itm->Uri.find(':')+1);

   // Stat the file and send a start message
   struct stat Buf;
   if (stat(File.c_str(),&Buf) != 0)
      return _error->Errno("stat",_("Failed to stat"));

   // Forumulate a result and send a start message
   FetchResult Res;
   Res.Size = Buf.st_size;
   Res.Filename = Itm->DestFile;
   Res.LastModified = Buf.st_mtime;
   Res.IMSHit = false;
   URIStart(Res);

   // just calc the hashes if the source and destination are identical
   if (File == Itm->DestFile || Itm->DestFile == "/dev/null")
   {
      CalculateHashes(Itm, Res);
      URIDone(Res);
      return true;
   }

   // See if the file exists
   FileFd From(File,FileFd::ReadOnly);
   FileFd To(Itm->DestFile,FileFd::WriteAtomic);
   To.EraseOnFailure();

   // Copy the file
   if (CopyFile(From,To) == false)
   {
      To.OpFail();
      return false;
   }

   From.Close();
   To.Close();

   if (TransferModificationTimes(File.c_str(), Res.Filename.c_str(), Res.LastModified) == false)
      return false;

   CalculateHashes(Itm, Res);
   URIDone(Res);
   return true;
}
									/*}}}*/

int main()
{
   return CopyMethod().Run();
}