1 // -*- mode: cpp; mode: fold -*-
3 // $Id: fileutl.cc,v 1.42 2002/09/14 05:29:22 jgg Exp $
4 /* ######################################################################
8 CopyFile - Buffered copy of a single file
9 GetLock - dpkg compatible lock file manipulation (fcntl)
11 Most of this source is placed in the Public Domain, do with it what
13 It was originally written by Jason Gunthorpe <jgg@debian.org>.
14 FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
16 The exception is RunScripts() it is under the GPLv2
18 ##################################################################### */
20 // Include Files /*{{{*/
23 #include <apt-pkg/fileutl.h>
24 #include <apt-pkg/strutl.h>
25 #include <apt-pkg/error.h>
26 #include <apt-pkg/sptr.h>
27 #include <apt-pkg/aptconfiguration.h>
28 #include <apt-pkg/configuration.h>
38 #include <sys/types.h>
47 // FIXME: Compressor Fds have some speed disadvantages and are a bit buggy currently,
48 // so while the current implementation satisfies the testcases it is not a real option
49 // to disable it for now
50 #define APT_USE_ZLIB 1
54 #warning "Usage of zlib is DISABLED!"
57 #ifdef WORDS_BIGENDIAN
75 APT::Configuration::Compressor compressor
;
76 unsigned int openmode
;
77 FileFdPrivate() : gz(NULL
), compressor_pid(-1), pipe(false) {};
80 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
81 // ---------------------------------------------------------------------
83 bool RunScripts(const char *Cnf
)
85 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
86 if (Opts
== 0 || Opts
->Child
== 0)
90 // Fork for running the system calls
91 pid_t Child
= ExecFork();
96 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
98 std::cerr
<< "Chrooting into "
99 << _config
->FindDir("DPkg::Chroot-Directory")
101 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
105 if (chdir("/tmp/") != 0)
108 unsigned int Count
= 1;
109 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
111 if (Opts
->Value
.empty() == true)
114 if (system(Opts
->Value
.c_str()) != 0)
120 // Wait for the child
122 while (waitpid(Child
,&Status
,0) != Child
)
126 return _error
->Errno("waitpid","Couldn't wait for subprocess");
129 // Restore sig int/quit
130 signal(SIGQUIT
,SIG_DFL
);
131 signal(SIGINT
,SIG_DFL
);
133 // Check for an error code.
134 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
136 unsigned int Count
= WEXITSTATUS(Status
);
140 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
141 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
144 return _error
->Error("Sub-process returned an error code");
151 // CopyFile - Buffered copy of a file /*{{{*/
152 // ---------------------------------------------------------------------
153 /* The caller is expected to set things so that failure causes erasure */
154 bool CopyFile(FileFd
&From
,FileFd
&To
)
156 if (From
.IsOpen() == false || To
.IsOpen() == false)
159 // Buffered copy between fds
160 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
161 unsigned long long Size
= From
.Size();
164 unsigned long long ToRead
= Size
;
168 if (From
.Read(Buf
,ToRead
) == false ||
169 To
.Write(Buf
,ToRead
) == false)
178 // GetLock - Gets a lock file /*{{{*/
179 // ---------------------------------------------------------------------
180 /* This will create an empty file of the given name and lock it. Once this
181 is done all other calls to GetLock in any other process will fail with
182 -1. The return result is the fd of the file, the call should call
183 close at some time. */
184 int GetLock(string File
,bool Errors
)
186 // GetLock() is used in aptitude on directories with public-write access
187 // Use O_NOFOLLOW here to prevent symlink traversal attacks
188 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
191 // Read only .. cant have locking problems there.
194 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
195 return dup(0); // Need something for the caller to close
199 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
201 // Feh.. We do this to distinguish the lock vs open case..
205 SetCloseExec(FD
,true);
207 // Aquire a write lock
210 fl
.l_whence
= SEEK_SET
;
213 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
217 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
218 return dup(0); // Need something for the caller to close
221 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
232 // FileExists - Check if a file exists /*{{{*/
233 // ---------------------------------------------------------------------
234 /* Beware: Directories are also files! */
235 bool FileExists(string File
)
238 if (stat(File
.c_str(),&Buf
) != 0)
243 // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
244 // ---------------------------------------------------------------------
246 bool RealFileExists(string File
)
249 if (stat(File
.c_str(),&Buf
) != 0)
251 return ((Buf
.st_mode
& S_IFREG
) != 0);
254 // DirectoryExists - Check if a directory exists and is really one /*{{{*/
255 // ---------------------------------------------------------------------
257 bool DirectoryExists(string
const &Path
)
260 if (stat(Path
.c_str(),&Buf
) != 0)
262 return ((Buf
.st_mode
& S_IFDIR
) != 0);
265 // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
266 // ---------------------------------------------------------------------
267 /* This method will create all directories needed for path in good old
268 mkdir -p style but refuses to do this if Parent is not a prefix of
269 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
270 so it will create apt/archives if /var/cache exists - on the other
271 hand if the parent is /var/lib the creation will fail as this path
272 is not a parent of the path to be generated. */
273 bool CreateDirectory(string
const &Parent
, string
const &Path
)
275 if (Parent
.empty() == true || Path
.empty() == true)
278 if (DirectoryExists(Path
) == true)
281 if (DirectoryExists(Parent
) == false)
284 // we are not going to create directories "into the blue"
285 if (Path
.find(Parent
, 0) != 0)
288 vector
<string
> const dirs
= VectorizeString(Path
.substr(Parent
.size()), '/');
289 string progress
= Parent
;
290 for (vector
<string
>::const_iterator d
= dirs
.begin(); d
!= dirs
.end(); ++d
)
292 if (d
->empty() == true)
295 progress
.append("/").append(*d
);
296 if (DirectoryExists(progress
) == true)
299 if (mkdir(progress
.c_str(), 0755) != 0)
305 // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
306 // ---------------------------------------------------------------------
307 /* a small wrapper around CreateDirectory to check if it exists and to
308 remove the trailing "/apt/" from the parent directory if needed */
309 bool CreateAPTDirectoryIfNeeded(string
const &Parent
, string
const &Path
)
311 if (DirectoryExists(Path
) == true)
314 size_t const len
= Parent
.size();
315 if (len
> 5 && Parent
.find("/apt/", len
- 6, 5) == len
- 5)
317 if (CreateDirectory(Parent
.substr(0,len
-5), Path
) == true)
320 else if (CreateDirectory(Parent
, Path
) == true)
326 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
327 // ---------------------------------------------------------------------
328 /* If an extension is given only files with this extension are included
329 in the returned vector, otherwise every "normal" file is included. */
330 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
331 bool const &SortList
, bool const &AllowNoExt
)
333 std::vector
<string
> ext
;
335 if (Ext
.empty() == false)
337 if (AllowNoExt
== true && ext
.empty() == false)
339 return GetListOfFilesInDir(Dir
, ext
, SortList
);
341 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, std::vector
<string
> const &Ext
,
342 bool const &SortList
)
344 // Attention debuggers: need to be set with the environment config file!
345 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
348 std::clog
<< "Accept in " << Dir
<< " only files with the following " << Ext
.size() << " extensions:" << std::endl
;
349 if (Ext
.empty() == true)
350 std::clog
<< "\tNO extension" << std::endl
;
352 for (std::vector
<string
>::const_iterator e
= Ext
.begin();
354 std::clog
<< '\t' << (e
->empty() == true ? "NO" : *e
) << " extension" << std::endl
;
357 std::vector
<string
> List
;
359 if (DirectoryExists(Dir
.c_str()) == false)
361 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
365 Configuration::MatchAgainstConfig
SilentIgnore("Dir::Ignore-Files-Silently");
366 DIR *D
= opendir(Dir
.c_str());
369 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
373 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
375 // skip "hidden" files
376 if (Ent
->d_name
[0] == '.')
379 // Make sure it is a file and not something else
380 string
const File
= flCombine(Dir
,Ent
->d_name
);
381 #ifdef _DIRENT_HAVE_D_TYPE
382 if (Ent
->d_type
!= DT_REG
)
385 if (RealFileExists(File
.c_str()) == false)
387 if (SilentIgnore
.Match(Ent
->d_name
) == false)
388 _error
->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent
->d_name
, Dir
.c_str());
393 // check for accepted extension:
394 // no extension given -> periods are bad as hell!
395 // extensions given -> "" extension allows no extension
396 if (Ext
.empty() == false)
398 string d_ext
= flExtension(Ent
->d_name
);
399 if (d_ext
== Ent
->d_name
) // no extension
401 if (std::find(Ext
.begin(), Ext
.end(), "") == Ext
.end())
404 std::clog
<< "Bad file: " << Ent
->d_name
<< " → no extension" << std::endl
;
405 if (SilentIgnore
.Match(Ent
->d_name
) == false)
406 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent
->d_name
, Dir
.c_str());
410 else if (std::find(Ext
.begin(), Ext
.end(), d_ext
) == Ext
.end())
413 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad extension »" << flExtension(Ent
->d_name
) << "«" << std::endl
;
414 if (SilentIgnore
.Match(Ent
->d_name
) == false)
415 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent
->d_name
, Dir
.c_str());
420 // Skip bad filenames ala run-parts
421 const char *C
= Ent
->d_name
;
423 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
424 && *C
!= '_' && *C
!= '-') {
425 // no required extension -> dot is a bad character
426 if (*C
== '.' && Ext
.empty() == false)
431 // we don't reach the end of the name -> bad character included
435 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »"
436 << *C
<< "« in filename (period allowed: " << (Ext
.empty() ? "no" : "yes") << ")" << std::endl
;
440 // skip filenames which end with a period. These are never valid
444 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
449 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
450 List
.push_back(File
);
454 if (SortList
== true)
455 std::sort(List
.begin(),List
.end());
459 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
460 // ---------------------------------------------------------------------
461 /* We return / on failure. */
464 // Stash the current dir.
467 if (getcwd(S
,sizeof(S
)-2) == 0)
469 unsigned int Len
= strlen(S
);
475 // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
476 // ---------------------------------------------------------------------
477 /* We return / on failure. */
478 time_t GetModificationTime(string
const &Path
)
481 if (stat(Path
.c_str(), &St
) < 0)
486 // flNotDir - Strip the directory from the filename /*{{{*/
487 // ---------------------------------------------------------------------
489 string
flNotDir(string File
)
491 string::size_type Res
= File
.rfind('/');
492 if (Res
== string::npos
)
495 return string(File
,Res
,Res
- File
.length());
498 // flNotFile - Strip the file from the directory name /*{{{*/
499 // ---------------------------------------------------------------------
500 /* Result ends in a / */
501 string
flNotFile(string File
)
503 string::size_type Res
= File
.rfind('/');
504 if (Res
== string::npos
)
507 return string(File
,0,Res
);
510 // flExtension - Return the extension for the file /*{{{*/
511 // ---------------------------------------------------------------------
513 string
flExtension(string File
)
515 string::size_type Res
= File
.rfind('.');
516 if (Res
== string::npos
)
519 return string(File
,Res
,Res
- File
.length());
522 // flNoLink - If file is a symlink then deref it /*{{{*/
523 // ---------------------------------------------------------------------
524 /* If the name is not a link then the returned path is the input. */
525 string
flNoLink(string File
)
528 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
530 if (stat(File
.c_str(),&St
) != 0)
533 /* Loop resolving the link. There is no need to limit the number of
534 loops because the stat call above ensures that the symlink is not
542 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
543 (unsigned)Res
>= sizeof(Buffer
))
546 // Append or replace the previous path
548 if (Buffer
[0] == '/')
551 NFile
= flNotFile(NFile
) + Buffer
;
553 // See if we are done
554 if (lstat(NFile
.c_str(),&St
) != 0)
556 if (S_ISLNK(St
.st_mode
) == 0)
561 // flCombine - Combine a file and a directory /*{{{*/
562 // ---------------------------------------------------------------------
563 /* If the file is an absolute path then it is just returned, otherwise
564 the directory is pre-pended to it. */
565 string
flCombine(string Dir
,string File
)
567 if (File
.empty() == true)
570 if (File
[0] == '/' || Dir
.empty() == true)
572 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
574 if (Dir
[Dir
.length()-1] == '/')
576 return Dir
+ '/' + File
;
579 // SetCloseExec - Set the close on exec flag /*{{{*/
580 // ---------------------------------------------------------------------
582 void SetCloseExec(int Fd
,bool Close
)
584 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
586 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
591 // SetNonBlock - Set the nonblocking flag /*{{{*/
592 // ---------------------------------------------------------------------
594 void SetNonBlock(int Fd
,bool Block
)
596 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
597 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
599 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
604 // WaitFd - Wait for a FD to become readable /*{{{*/
605 // ---------------------------------------------------------------------
606 /* This waits for a FD to become readable using select. It is useful for
607 applications making use of non-blocking sockets. The timeout is
609 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
622 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
624 while (Res
< 0 && errno
== EINTR
);
634 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
636 while (Res
< 0 && errno
== EINTR
);
645 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
646 // ---------------------------------------------------------------------
647 /* This is used if you want to cleanse the environment for the forked
648 child, it fixes up the important signals and nukes all of the fds,
649 otherwise acts like normal fork. */
652 // Fork off the process
653 pid_t Process
= fork();
656 cerr
<< "FATAL -> Failed to fork." << endl
;
660 // Spawn the subprocess
664 signal(SIGPIPE
,SIG_DFL
);
665 signal(SIGQUIT
,SIG_DFL
);
666 signal(SIGINT
,SIG_DFL
);
667 signal(SIGWINCH
,SIG_DFL
);
668 signal(SIGCONT
,SIG_DFL
);
669 signal(SIGTSTP
,SIG_DFL
);
672 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
673 if (Opts
!= 0 && Opts
->Child
!= 0)
676 for (; Opts
!= 0; Opts
= Opts
->Next
)
678 if (Opts
->Value
.empty() == true)
680 int fd
= atoi(Opts
->Value
.c_str());
685 // Close all of our FDs - just in case
686 for (int K
= 3; K
!= 40; K
++)
688 if(KeepFDs
.find(K
) == KeepFDs
.end())
689 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
696 // ExecWait - Fancy waitpid /*{{{*/
697 // ---------------------------------------------------------------------
698 /* Waits for the given sub process. If Reap is set then no errors are
699 generated. Otherwise a failed subprocess will generate a proper descriptive
701 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
706 // Wait and collect the error code
708 while (waitpid(Pid
,&Status
,0) != Pid
)
716 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
720 // Check for an error code.
721 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
725 if (WIFSIGNALED(Status
) != 0)
727 if( WTERMSIG(Status
) == SIGSEGV
)
728 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
730 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
733 if (WIFEXITED(Status
) != 0)
734 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
736 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
743 // ExecCompressor - Open a de/compressor pipe /*{{{*/
744 // ---------------------------------------------------------------------
745 /* This opens the compressor, either in compress mode or decompress
746 mode. FileFd is always the compressor input/output file,
747 OutFd is the created pipe, Input for Compress, Output for Decompress. */
748 bool ExecCompressor(APT::Configuration::Compressor
const &Prog
,
749 pid_t
*Pid
, int const FileFd
, int &OutFd
, bool const Comp
)
755 if (Prog
.Binary
.empty() == true)
761 // Handle 'decompression' of empty files
766 if (Buf
.st_size
== 0 && S_ISFIFO(Buf
.st_mode
) == false)
773 // Create a data pipe
774 int Pipe
[2] = {-1,-1};
776 return _error
->Errno("pipe",_("Failed to create subprocess IPC"));
777 for (int J
= 0; J
!= 2; J
++)
778 SetCloseExec(Pipe
[J
],true);
786 pid_t child
= ExecFork();
793 dup2(FileFd
,STDOUT_FILENO
);
794 dup2(Pipe
[0],STDIN_FILENO
);
798 dup2(FileFd
,STDIN_FILENO
);
799 dup2(Pipe
[1],STDOUT_FILENO
);
802 SetCloseExec(STDOUT_FILENO
,false);
803 SetCloseExec(STDIN_FILENO
,false);
805 std::vector
<char const*> Args
;
806 Args
.push_back(Prog
.Binary
.c_str());
807 std::vector
<std::string
> const * const addArgs
=
808 (Comp
== true) ? &(Prog
.CompressArgs
) : &(Prog
.UncompressArgs
);
809 for (std::vector
<std::string
>::const_iterator a
= addArgs
->begin();
810 a
!= addArgs
->end(); ++a
)
811 Args
.push_back(a
->c_str());
812 Args
.push_back(NULL
);
814 execvp(Args
[0],(char **)&Args
[0]);
815 cerr
<< _("Failed to exec compressor ") << Args
[0] << endl
;
824 ExecWait(child
, Prog
.Binary
.c_str(), true);
828 bool ExecCompressor(APT::Configuration::Compressor
const &Prog
,
829 pid_t
*Pid
, std::string
const &FileName
, int &OutFd
, bool const Comp
)
835 if (Prog
.Binary
.empty() == true)
838 OutFd
= open(FileName
.c_str(), O_WRONLY
, 0666);
840 OutFd
= open(FileName
.c_str(), O_RDONLY
);
844 // Handle 'decompression' of empty files
848 stat(FileName
.c_str(), &Buf
);
849 if (Buf
.st_size
== 0)
851 OutFd
= open(FileName
.c_str(), O_RDONLY
);
856 // Create a data pipe
857 int Pipe
[2] = {-1,-1};
859 return _error
->Errno("pipe",_("Failed to create subprocess IPC"));
860 for (int J
= 0; J
!= 2; J
++)
861 SetCloseExec(Pipe
[J
],true);
867 // FIXME: we should handle openmode and permission from Open() here
868 FileFd
= open(FileName
.c_str(), O_WRONLY
, 0666);
874 pid_t child
= ExecFork();
881 dup2(Pipe
[0],STDIN_FILENO
);
882 dup2(FileFd
,STDOUT_FILENO
);
883 SetCloseExec(STDIN_FILENO
,false);
887 dup2(Pipe
[1],STDOUT_FILENO
);
889 SetCloseExec(STDOUT_FILENO
,false);
891 std::vector
<char const*> Args
;
892 Args
.push_back(Prog
.Binary
.c_str());
893 std::vector
<std::string
> const * const addArgs
=
894 (Comp
== true) ? &(Prog
.CompressArgs
) : &(Prog
.UncompressArgs
);
895 for (std::vector
<std::string
>::const_iterator a
= addArgs
->begin();
896 a
!= addArgs
->end(); ++a
)
897 Args
.push_back(a
->c_str());
900 Args
.push_back("--stdout");
901 Args
.push_back(FileName
.c_str());
903 Args
.push_back(NULL
);
905 execvp(Args
[0],(char **)&Args
[0]);
906 cerr
<< _("Failed to exec compressor ") << Args
[0] << endl
;
918 ExecWait(child
, Prog
.Binary
.c_str(), false);
924 // FileFd::Open - Open a file /*{{{*/
925 // ---------------------------------------------------------------------
926 /* The most commonly used open mode combinations are given with Mode */
927 bool FileFd::Open(string FileName
,unsigned int const Mode
,CompressMode Compress
, unsigned long const Perms
)
929 if (Mode
== ReadOnlyGzip
)
930 return Open(FileName
, ReadOnly
, Gzip
, Perms
);
932 if (Compress
== Auto
&& (Mode
& WriteOnly
) == WriteOnly
)
933 return _error
->Error("Autodetection on %s only works in ReadOnly openmode!", FileName
.c_str());
935 // FIXME: Denote inbuilt compressors somehow - as we don't need to have the binaries for them
936 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
937 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
938 if (Compress
== Auto
)
940 for (; compressor
!= compressors
.end(); ++compressor
)
942 std::string file
= std::string(FileName
).append(compressor
->Extension
);
943 if (FileExists(file
) == false)
949 else if (Compress
== Extension
)
951 std::string::size_type
const found
= FileName
.find_last_of('.');
953 if (found
!= std::string::npos
)
955 ext
= FileName
.substr(found
);
956 if (ext
== ".new" || ext
== ".bak")
958 std::string::size_type
const found2
= FileName
.find_last_of('.', found
- 1);
959 if (found2
!= std::string::npos
)
960 ext
= FileName
.substr(found2
, found
- found2
);
965 for (; compressor
!= compressors
.end(); ++compressor
)
966 if (ext
== compressor
->Extension
)
968 // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
969 if (compressor
== compressors
.end())
970 for (compressor
= compressors
.begin(); compressor
!= compressors
.end(); ++compressor
)
971 if (compressor
->Name
== ".")
979 case None
: name
= "."; break;
980 case Gzip
: name
= "gzip"; break;
981 case Bzip2
: name
= "bzip2"; break;
982 case Lzma
: name
= "lzma"; break;
983 case Xz
: name
= "xz"; break;
987 return _error
->Error("Opening File %s in None, Auto or Extension should be already handled?!?", FileName
.c_str());
989 for (; compressor
!= compressors
.end(); ++compressor
)
990 if (compressor
->Name
== name
)
992 if (compressor
== compressors
.end())
993 return _error
->Error("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
996 if (compressor
== compressors
.end())
997 return _error
->Error("Can't find a match for specified compressor mode for file %s", FileName
.c_str());
998 return Open(FileName
, Mode
, *compressor
, Perms
);
1000 bool FileFd::Open(string FileName
,unsigned int const Mode
,APT::Configuration::Compressor
const &compressor
, unsigned long const Perms
)
1003 d
= new FileFdPrivate
;
1007 if ((Mode
& WriteOnly
) != WriteOnly
&& (Mode
& (Atomic
| Create
| Empty
| Exclusive
)) != 0)
1008 return _error
->Error("ReadOnly mode for %s doesn't accept additional flags!", FileName
.c_str());
1009 if ((Mode
& ReadWrite
) == 0)
1010 return _error
->Error("No openmode provided in FileFd::Open for %s", FileName
.c_str());
1012 if ((Mode
& Atomic
) == Atomic
)
1015 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
1016 TemporaryFileName
= string(mktemp(name
));
1019 else if ((Mode
& (Exclusive
| Create
)) == (Exclusive
| Create
))
1021 // for atomic, this will be done by rename in Close()
1022 unlink(FileName
.c_str());
1024 if ((Mode
& Empty
) == Empty
)
1027 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
1028 unlink(FileName
.c_str());
1031 // if we have them, use inbuilt compressors instead of forking
1032 if (compressor
.Name
!= "."
1034 && compressor
.Name
!= "gzip"
1038 if ((Mode
& ReadWrite
) == ReadWrite
)
1039 return _error
->Error("External compressors like %s do not support readwrite mode for file %s", compressor
.Name
.c_str(), FileName
.c_str());
1041 if ((Mode
& (WriteOnly
| Create
)) == (WriteOnly
| Create
))
1043 if (TemporaryFileName
.empty() == false)
1045 if (RealFileExists(TemporaryFileName
) == false)
1047 iFd
= open(TemporaryFileName
.c_str(), O_WRONLY
| O_CREAT
, Perms
);
1052 else if (RealFileExists(FileName
) == false)
1054 iFd
= open(FileName
.c_str(), O_WRONLY
| O_CREAT
, Perms
);
1060 if (TemporaryFileName
.empty() == false)
1062 if (ExecCompressor(compressor
, &(d
->compressor_pid
), TemporaryFileName
, iFd
, ((Mode
& ReadOnly
) != ReadOnly
)) == false)
1063 return _error
->Error("Forking external compressor %s is not implemented for %s", compressor
.Name
.c_str(), TemporaryFileName
.c_str());
1067 if (ExecCompressor(compressor
, &(d
->compressor_pid
), FileName
, iFd
, ((Mode
& ReadOnly
) != ReadOnly
)) == false)
1068 return _error
->Error("Forking external compressor %s is not implemented for %s", compressor
.Name
.c_str(), FileName
.c_str());
1071 d
->compressor
= compressor
;
1076 #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
1077 if_FLAGGED_SET(ReadWrite
, O_RDWR
);
1078 else if_FLAGGED_SET(ReadOnly
, O_RDONLY
);
1079 else if_FLAGGED_SET(WriteOnly
, O_WRONLY
);
1081 if_FLAGGED_SET(Create
, O_CREAT
);
1082 if_FLAGGED_SET(Exclusive
, O_EXCL
);
1083 else if_FLAGGED_SET(Atomic
, O_EXCL
);
1084 if_FLAGGED_SET(Empty
, O_TRUNC
);
1085 #undef if_FLAGGED_SET
1087 if (TemporaryFileName
.empty() == false)
1088 iFd
= open(TemporaryFileName
.c_str(), fileflags
, Perms
);
1090 iFd
= open(FileName
.c_str(), fileflags
, Perms
);
1094 if (OpenInternDescriptor(Mode
, compressor
) == false)
1103 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
1105 this->FileName
= FileName
;
1106 SetCloseExec(iFd
,true);
1110 // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
1111 // ---------------------------------------------------------------------
1113 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, CompressMode Compress
, bool AutoClose
)
1115 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
1116 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
1120 case None
: name
= "."; break;
1121 case Gzip
: name
= "gzip"; break;
1122 case Bzip2
: name
= "bzip2"; break;
1123 case Lzma
: name
= "lzma"; break;
1124 case Xz
: name
= "xz"; break;
1127 return _error
->Error("Opening Fd %d in Auto or Extension compression mode is not supported", Fd
);
1129 for (; compressor
!= compressors
.end(); ++compressor
)
1130 if (compressor
->Name
== name
)
1132 if (compressor
== compressors
.end())
1133 return _error
->Error("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
1135 return OpenDescriptor(Fd
, Mode
, *compressor
, AutoClose
);
1137 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
, bool AutoClose
)
1140 d
= new FileFdPrivate
;
1142 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
1144 if (OpenInternDescriptor(Mode
, compressor
) == false)
1148 return _error
->Errno("gzdopen",_("Could not open file descriptor %d"), Fd
);
1150 this->FileName
= "";
1153 bool FileFd::OpenInternDescriptor(unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
)
1155 if (compressor
.Name
== ".")
1158 else if (compressor
.Name
== "gzip")
1160 if ((Mode
& ReadWrite
) == ReadWrite
)
1161 d
->gz
= gzdopen(iFd
, "r+");
1162 else if ((Mode
& WriteOnly
) == WriteOnly
)
1163 d
->gz
= gzdopen(iFd
, "w");
1165 d
->gz
= gzdopen (iFd
, "r");
1168 Flags
|= Compressed
;
1172 return _error
->Error("Can't find a match for specified compressor %s for file %s", compressor
.Name
.c_str(), FileName
.c_str());
1176 // FileFd::~File - Closes the file /*{{{*/
1177 // ---------------------------------------------------------------------
1178 /* If the proper modes are selected then we close the Fd and possibly
1179 unlink the file on error. */
1185 // FileFd::Read - Read a bit of the file /*{{{*/
1186 // ---------------------------------------------------------------------
1187 /* We are carefull to handle interruption by a signal while reading
1189 bool FileFd::Read(void *To
,unsigned long long Size
,unsigned long long *Actual
)
1195 *((char *)To
) = '\0';
1200 Res
= gzread(d
->gz
,To
,Size
);
1203 Res
= read(iFd
,To
,Size
);
1204 if (Res
< 0 && errno
== EINTR
)
1209 return _error
->Errno("read",_("Read error"));
1212 To
= (char *)To
+ Res
;
1217 while (Res
> 0 && Size
> 0);
1230 return _error
->Error(_("read, still have %llu to read but none left"), Size
);
1233 // FileFd::ReadLine - Read a complete line from the file /*{{{*/
1234 // ---------------------------------------------------------------------
1235 /* Beware: This method can be quiet slow for big buffers on UNcompressed
1236 files because of the naive implementation! */
1237 char* FileFd::ReadLine(char *To
, unsigned long long const Size
)
1242 return gzgets(d
->gz
, To
, Size
);
1245 unsigned long long read
= 0;
1246 if (Read(To
, Size
, &read
) == false)
1249 for (; *c
!= '\n' && *c
!= '\0' && read
!= 0; --read
, ++c
)
1250 ; // find the end of the line
1254 Seek(Tell() - read
);
1258 // FileFd::Write - Write to the file /*{{{*/
1259 // ---------------------------------------------------------------------
1261 bool FileFd::Write(const void *From
,unsigned long long Size
)
1269 Res
= gzwrite(d
->gz
,From
,Size
);
1272 Res
= write(iFd
,From
,Size
);
1273 if (Res
< 0 && errno
== EINTR
)
1278 return _error
->Errno("write",_("Write error"));
1281 From
= (char *)From
+ Res
;
1284 while (Res
> 0 && Size
> 0);
1290 return _error
->Error(_("write, still have %llu to write but couldn't"), Size
);
1293 // FileFd::Seek - Seek in the file /*{{{*/
1294 // ---------------------------------------------------------------------
1296 bool FileFd::Seek(unsigned long long To
)
1298 if (d
->pipe
== true)
1300 // FIXME: What about OpenDescriptor() stuff here?
1302 bool result
= ExecCompressor(d
->compressor
, NULL
, FileName
, iFd
, (d
->openmode
& ReadOnly
) != ReadOnly
);
1303 if (result
== true && To
!= 0)
1310 res
= gzseek(d
->gz
,To
,SEEK_SET
);
1313 res
= lseek(iFd
,To
,SEEK_SET
);
1314 if (res
!= (signed)To
)
1317 return _error
->Error("Unable to seek to %llu", To
);
1323 // FileFd::Skip - Seek in the file /*{{{*/
1324 // ---------------------------------------------------------------------
1326 bool FileFd::Skip(unsigned long long Over
)
1331 res
= gzseek(d
->gz
,Over
,SEEK_CUR
);
1334 res
= lseek(iFd
,Over
,SEEK_CUR
);
1338 return _error
->Error("Unable to seek ahead %llu",Over
);
1344 // FileFd::Truncate - Truncate the file /*{{{*/
1345 // ---------------------------------------------------------------------
1347 bool FileFd::Truncate(unsigned long long To
)
1352 return _error
->Error("Truncating gzipped files is not implemented (%s)", FileName
.c_str());
1354 if (ftruncate(iFd
,To
) != 0)
1357 return _error
->Error("Unable to truncate to %llu",To
);
1363 // FileFd::Tell - Current seek position /*{{{*/
1364 // ---------------------------------------------------------------------
1366 unsigned long long FileFd::Tell()
1371 Res
= gztell(d
->gz
);
1374 Res
= lseek(iFd
,0,SEEK_CUR
);
1375 if (Res
== (off_t
)-1)
1376 _error
->Errno("lseek","Failed to determine the current file position");
1380 // FileFd::FileSize - Return the size of the file /*{{{*/
1381 // ---------------------------------------------------------------------
1383 unsigned long long FileFd::FileSize()
1386 if (d
->pipe
== false && fstat(iFd
,&Buf
) != 0)
1387 return _error
->Errno("fstat","Unable to determine the file size");
1389 // for compressor pipes st_size is undefined and at 'best' zero
1390 if (d
->pipe
== true || S_ISFIFO(Buf
.st_mode
))
1392 // we set it here, too, as we get the info here for free
1393 // in theory the Open-methods should take care of it already
1395 if (stat(FileName
.c_str(), &Buf
) != 0)
1396 return _error
->Errno("stat","Unable to determine the file size");
1402 // FileFd::Size - Return the size of the content in the file /*{{{*/
1403 // ---------------------------------------------------------------------
1405 unsigned long long FileFd::Size()
1407 unsigned long long size
= FileSize();
1409 // for compressor pipes st_size is undefined and at 'best' zero,
1410 // so we 'read' the content and 'seek' back - see there
1411 if (d
->pipe
== true)
1413 // FIXME: If we have read first and then FileSize() the report is wrong
1416 unsigned long long read
= 0;
1418 Read(ignore
, sizeof(ignore
), &read
);
1424 // only check gzsize if we are actually a gzip file, just checking for
1425 // "gz" is not sufficient as uncompressed files could be opened with
1426 // gzopen in "direct" mode as well
1427 else if (d
->gz
&& !gzdirect(d
->gz
) && size
> 0)
1429 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
1430 * this ourselves; the original (uncompressed) file size is the last 32
1431 * bits of the file */
1432 // FIXME: Size for gz-files is limited by 32bit… no largefile support
1433 off_t orig_pos
= lseek(iFd
, 0, SEEK_CUR
);
1434 if (lseek(iFd
, -4, SEEK_END
) < 0)
1435 return _error
->Errno("lseek","Unable to seek to end of gzipped file");
1437 if (read(iFd
, &size
, 4) != 4)
1438 return _error
->Errno("read","Unable to read original size of gzipped file");
1440 #ifdef WORDS_BIGENDIAN
1441 uint32_t tmp_size
= size
;
1442 uint8_t const * const p
= (uint8_t const * const) &tmp_size
;
1443 tmp_size
= (p
[3] << 24) | (p
[2] << 16) | (p
[1] << 8) | p
[0];
1447 if (lseek(iFd
, orig_pos
, SEEK_SET
) < 0)
1448 return _error
->Errno("lseek","Unable to seek in gzipped file");
1456 // FileFd::ModificationTime - Return the time of last touch /*{{{*/
1457 // ---------------------------------------------------------------------
1459 time_t FileFd::ModificationTime()
1462 if (d
->pipe
== false && fstat(iFd
,&Buf
) != 0)
1464 _error
->Errno("fstat","Unable to determine the modification time of file %s", FileName
.c_str());
1468 // for compressor pipes st_size is undefined and at 'best' zero
1469 if (d
->pipe
== true || S_ISFIFO(Buf
.st_mode
))
1471 // we set it here, too, as we get the info here for free
1472 // in theory the Open-methods should take care of it already
1474 if (stat(FileName
.c_str(), &Buf
) != 0)
1476 _error
->Errno("fstat","Unable to determine the modification time of file %s", FileName
.c_str());
1481 return Buf
.st_mtime
;
1484 // FileFd::Close - Close the file if the close flag is set /*{{{*/
1485 // ---------------------------------------------------------------------
1487 bool FileFd::Close()
1493 if ((Flags
& AutoClose
) == AutoClose
)
1496 if (d
!= NULL
&& d
->gz
!= NULL
) {
1497 int const e
= gzclose(d
->gz
);
1498 // gzdopen() on empty files always fails with "buffer error" here, ignore that
1499 if (e
!= 0 && e
!= Z_BUF_ERROR
)
1500 Res
&= _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
1503 if (iFd
> 0 && close(iFd
) != 0)
1504 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
1507 if ((Flags
& Replace
) == Replace
&& iFd
>= 0) {
1508 if (rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
1509 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
1511 FileName
= TemporaryFileName
; // for the unlink() below.
1512 TemporaryFileName
.clear();
1517 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
1518 FileName
.empty() == false)
1519 if (unlink(FileName
.c_str()) != 0)
1520 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file %s"), FileName
.c_str());
1524 if (d
->compressor_pid
!= -1)
1525 ExecWait(d
->compressor_pid
, "FileFdCompressor", true);
1533 // FileFd::Sync - Sync the file /*{{{*/
1534 // ---------------------------------------------------------------------
1538 #ifdef _POSIX_SYNCHRONIZED_IO
1539 if (fsync(iFd
) != 0)
1540 return _error
->Errno("sync",_("Problem syncing the file"));
1546 gzFile
FileFd::gzFd() { return (gzFile
) d
->gz
; }