1 // -*- mode: cpp; mode: fold -*-
3 /* ######################################################################
7 CopyFile - Buffered copy of a single file
8 GetLock - dpkg compatible lock file manipulation (fcntl)
10 Most of this source is placed in the Public Domain, do with it what
12 It was originally written by Jason Gunthorpe <jgg@debian.org>.
13 FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
15 The exception is RunScripts() it is under the GPLv2
17 ##################################################################### */
19 // Include Files /*{{{*/
22 #include <apt-pkg/fileutl.h>
23 #include <apt-pkg/strutl.h>
24 #include <apt-pkg/error.h>
25 #include <apt-pkg/sptr.h>
26 #include <apt-pkg/aptconfiguration.h>
27 #include <apt-pkg/configuration.h>
28 #include <apt-pkg/macros.h>
33 #include <sys/select.h>
73 #include <sys/prctl.h>
81 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
82 // ---------------------------------------------------------------------
84 bool RunScripts(const char *Cnf
)
86 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
87 if (Opts
== 0 || Opts
->Child
== 0)
91 // Fork for running the system calls
92 pid_t Child
= ExecFork();
97 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
99 std::cerr
<< "Chrooting into "
100 << _config
->FindDir("DPkg::Chroot-Directory")
102 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
106 if (chdir("/tmp/") != 0)
109 unsigned int Count
= 1;
110 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
112 if (Opts
->Value
.empty() == true)
115 if(_config
->FindB("Debug::RunScripts", false) == true)
116 std::clog
<< "Running external script: '"
117 << Opts
->Value
<< "'" << std::endl
;
119 if (system(Opts
->Value
.c_str()) != 0)
125 // Wait for the child
127 while (waitpid(Child
,&Status
,0) != Child
)
131 return _error
->Errno("waitpid","Couldn't wait for subprocess");
134 // Restore sig int/quit
135 signal(SIGQUIT
,SIG_DFL
);
136 signal(SIGINT
,SIG_DFL
);
138 // Check for an error code.
139 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
141 unsigned int Count
= WEXITSTATUS(Status
);
145 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
146 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
149 return _error
->Error("Sub-process returned an error code");
156 // CopyFile - Buffered copy of a file /*{{{*/
157 // ---------------------------------------------------------------------
158 /* The caller is expected to set things so that failure causes erasure */
159 bool CopyFile(FileFd
&From
,FileFd
&To
)
161 if (From
.IsOpen() == false || To
.IsOpen() == false ||
162 From
.Failed() == true || To
.Failed() == true)
165 // Buffered copy between fds
166 constexpr size_t BufSize
= 64000;
167 std::unique_ptr
<unsigned char[]> Buf(new unsigned char[BufSize
]);
168 unsigned long long ToRead
= 0;
170 if (From
.Read(Buf
.get(),BufSize
, &ToRead
) == false ||
171 To
.Write(Buf
.get(),ToRead
) == false)
173 } while (ToRead
!= 0);
178 bool RemoveFile(char const * const Function
, std::string
const &FileName
)/*{{{*/
180 if (FileName
== "/dev/null")
183 if (unlink(FileName
.c_str()) != 0)
188 return _error
->WarningE(Function
,_("Problem unlinking the file %s"), FileName
.c_str());
193 // GetLock - Gets a lock file /*{{{*/
194 // ---------------------------------------------------------------------
195 /* This will create an empty file of the given name and lock it. Once this
196 is done all other calls to GetLock in any other process will fail with
197 -1. The return result is the fd of the file, the call should call
198 close at some time. */
199 int GetLock(string File
,bool Errors
)
201 // GetLock() is used in aptitude on directories with public-write access
202 // Use O_NOFOLLOW here to prevent symlink traversal attacks
203 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
206 // Read only .. can't have locking problems there.
209 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
210 return dup(0); // Need something for the caller to close
214 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
216 // Feh.. We do this to distinguish the lock vs open case..
220 SetCloseExec(FD
,true);
222 // Acquire a write lock
225 fl
.l_whence
= SEEK_SET
;
228 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
230 // always close to not leak resources
237 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
238 return dup(0); // Need something for the caller to close
242 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
250 // FileExists - Check if a file exists /*{{{*/
251 // ---------------------------------------------------------------------
252 /* Beware: Directories are also files! */
253 bool FileExists(string File
)
256 if (stat(File
.c_str(),&Buf
) != 0)
261 // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
262 // ---------------------------------------------------------------------
264 bool RealFileExists(string File
)
267 if (stat(File
.c_str(),&Buf
) != 0)
269 return ((Buf
.st_mode
& S_IFREG
) != 0);
272 // DirectoryExists - Check if a directory exists and is really one /*{{{*/
273 // ---------------------------------------------------------------------
275 bool DirectoryExists(string
const &Path
)
278 if (stat(Path
.c_str(),&Buf
) != 0)
280 return ((Buf
.st_mode
& S_IFDIR
) != 0);
283 // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
284 // ---------------------------------------------------------------------
285 /* This method will create all directories needed for path in good old
286 mkdir -p style but refuses to do this if Parent is not a prefix of
287 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
288 so it will create apt/archives if /var/cache exists - on the other
289 hand if the parent is /var/lib the creation will fail as this path
290 is not a parent of the path to be generated. */
291 bool CreateDirectory(string
const &Parent
, string
const &Path
)
293 if (Parent
.empty() == true || Path
.empty() == true)
296 if (DirectoryExists(Path
) == true)
299 if (DirectoryExists(Parent
) == false)
302 // we are not going to create directories "into the blue"
303 if (Path
.compare(0, Parent
.length(), Parent
) != 0)
306 vector
<string
> const dirs
= VectorizeString(Path
.substr(Parent
.size()), '/');
307 string progress
= Parent
;
308 for (vector
<string
>::const_iterator d
= dirs
.begin(); d
!= dirs
.end(); ++d
)
310 if (d
->empty() == true)
313 progress
.append("/").append(*d
);
314 if (DirectoryExists(progress
) == true)
317 if (mkdir(progress
.c_str(), 0755) != 0)
323 // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
324 // ---------------------------------------------------------------------
325 /* a small wrapper around CreateDirectory to check if it exists and to
326 remove the trailing "/apt/" from the parent directory if needed */
327 bool CreateAPTDirectoryIfNeeded(string
const &Parent
, string
const &Path
)
329 if (DirectoryExists(Path
) == true)
332 size_t const len
= Parent
.size();
333 if (len
> 5 && Parent
.find("/apt/", len
- 6, 5) == len
- 5)
335 if (CreateDirectory(Parent
.substr(0,len
-5), Path
) == true)
338 else if (CreateDirectory(Parent
, Path
) == true)
344 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
345 // ---------------------------------------------------------------------
346 /* If an extension is given only files with this extension are included
347 in the returned vector, otherwise every "normal" file is included. */
348 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
349 bool const &SortList
, bool const &AllowNoExt
)
351 std::vector
<string
> ext
;
353 if (Ext
.empty() == false)
355 if (AllowNoExt
== true && ext
.empty() == false)
357 return GetListOfFilesInDir(Dir
, ext
, SortList
);
359 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, std::vector
<string
> const &Ext
,
360 bool const &SortList
)
362 // Attention debuggers: need to be set with the environment config file!
363 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
366 std::clog
<< "Accept in " << Dir
<< " only files with the following " << Ext
.size() << " extensions:" << std::endl
;
367 if (Ext
.empty() == true)
368 std::clog
<< "\tNO extension" << std::endl
;
370 for (std::vector
<string
>::const_iterator e
= Ext
.begin();
372 std::clog
<< '\t' << (e
->empty() == true ? "NO" : *e
) << " extension" << std::endl
;
375 std::vector
<string
> List
;
377 if (DirectoryExists(Dir
) == false)
379 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
383 Configuration::MatchAgainstConfig
SilentIgnore("Dir::Ignore-Files-Silently");
384 DIR *D
= opendir(Dir
.c_str());
387 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
391 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
393 // skip "hidden" files
394 if (Ent
->d_name
[0] == '.')
397 // Make sure it is a file and not something else
398 string
const File
= flCombine(Dir
,Ent
->d_name
);
399 #ifdef _DIRENT_HAVE_D_TYPE
400 if (Ent
->d_type
!= DT_REG
)
403 if (RealFileExists(File
) == false)
405 // do not show ignoration warnings for directories
407 #ifdef _DIRENT_HAVE_D_TYPE
408 Ent
->d_type
== DT_DIR
||
410 DirectoryExists(File
) == true)
412 if (SilentIgnore
.Match(Ent
->d_name
) == false)
413 _error
->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent
->d_name
, Dir
.c_str());
418 // check for accepted extension:
419 // no extension given -> periods are bad as hell!
420 // extensions given -> "" extension allows no extension
421 if (Ext
.empty() == false)
423 string d_ext
= flExtension(Ent
->d_name
);
424 if (d_ext
== Ent
->d_name
) // no extension
426 if (std::find(Ext
.begin(), Ext
.end(), "") == Ext
.end())
429 std::clog
<< "Bad file: " << Ent
->d_name
<< " → no extension" << std::endl
;
430 if (SilentIgnore
.Match(Ent
->d_name
) == false)
431 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent
->d_name
, Dir
.c_str());
435 else if (std::find(Ext
.begin(), Ext
.end(), d_ext
) == Ext
.end())
438 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad extension »" << flExtension(Ent
->d_name
) << "«" << std::endl
;
439 if (SilentIgnore
.Match(Ent
->d_name
) == false)
440 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent
->d_name
, Dir
.c_str());
445 // Skip bad filenames ala run-parts
446 const char *C
= Ent
->d_name
;
448 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
449 && *C
!= '_' && *C
!= '-' && *C
!= ':') {
450 // no required extension -> dot is a bad character
451 if (*C
== '.' && Ext
.empty() == false)
456 // we don't reach the end of the name -> bad character included
460 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »"
461 << *C
<< "« in filename (period allowed: " << (Ext
.empty() ? "no" : "yes") << ")" << std::endl
;
465 // skip filenames which end with a period. These are never valid
469 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
474 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
475 List
.push_back(File
);
479 if (SortList
== true)
480 std::sort(List
.begin(),List
.end());
483 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, bool SortList
)
485 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
487 std::clog
<< "Accept in " << Dir
<< " all regular files" << std::endl
;
489 std::vector
<string
> List
;
491 if (DirectoryExists(Dir
) == false)
493 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
497 DIR *D
= opendir(Dir
.c_str());
500 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
504 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
506 // skip "hidden" files
507 if (Ent
->d_name
[0] == '.')
510 // Make sure it is a file and not something else
511 string
const File
= flCombine(Dir
,Ent
->d_name
);
512 #ifdef _DIRENT_HAVE_D_TYPE
513 if (Ent
->d_type
!= DT_REG
)
516 if (RealFileExists(File
) == false)
519 std::clog
<< "Bad file: " << Ent
->d_name
<< " → it is not a real file" << std::endl
;
524 // Skip bad filenames ala run-parts
525 const char *C
= Ent
->d_name
;
527 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
528 && *C
!= '_' && *C
!= '-' && *C
!= '.')
531 // we don't reach the end of the name -> bad character included
535 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »" << *C
<< "« in filename" << std::endl
;
539 // skip filenames which end with a period. These are never valid
543 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
548 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
549 List
.push_back(File
);
553 if (SortList
== true)
554 std::sort(List
.begin(),List
.end());
558 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
559 // ---------------------------------------------------------------------
560 /* We return / on failure. */
563 // Stash the current dir.
566 if (getcwd(S
,sizeof(S
)-2) == 0)
568 unsigned int Len
= strlen(S
);
574 // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
575 // ---------------------------------------------------------------------
576 /* We return / on failure. */
577 time_t GetModificationTime(string
const &Path
)
580 if (stat(Path
.c_str(), &St
) < 0)
585 // flNotDir - Strip the directory from the filename /*{{{*/
586 // ---------------------------------------------------------------------
588 string
flNotDir(string File
)
590 string::size_type Res
= File
.rfind('/');
591 if (Res
== string::npos
)
594 return string(File
,Res
,Res
- File
.length());
597 // flNotFile - Strip the file from the directory name /*{{{*/
598 // ---------------------------------------------------------------------
599 /* Result ends in a / */
600 string
flNotFile(string File
)
602 string::size_type Res
= File
.rfind('/');
603 if (Res
== string::npos
)
606 return string(File
,0,Res
);
609 // flExtension - Return the extension for the file /*{{{*/
610 // ---------------------------------------------------------------------
612 string
flExtension(string File
)
614 string::size_type Res
= File
.rfind('.');
615 if (Res
== string::npos
)
618 return string(File
,Res
,Res
- File
.length());
621 // flNoLink - If file is a symlink then deref it /*{{{*/
622 // ---------------------------------------------------------------------
623 /* If the name is not a link then the returned path is the input. */
624 string
flNoLink(string File
)
627 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
629 if (stat(File
.c_str(),&St
) != 0)
632 /* Loop resolving the link. There is no need to limit the number of
633 loops because the stat call above ensures that the symlink is not
641 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
642 (size_t)Res
>= sizeof(Buffer
))
645 // Append or replace the previous path
647 if (Buffer
[0] == '/')
650 NFile
= flNotFile(NFile
) + Buffer
;
652 // See if we are done
653 if (lstat(NFile
.c_str(),&St
) != 0)
655 if (S_ISLNK(St
.st_mode
) == 0)
660 // flCombine - Combine a file and a directory /*{{{*/
661 // ---------------------------------------------------------------------
662 /* If the file is an absolute path then it is just returned, otherwise
663 the directory is pre-pended to it. */
664 string
flCombine(string Dir
,string File
)
666 if (File
.empty() == true)
669 if (File
[0] == '/' || Dir
.empty() == true)
671 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
673 if (Dir
[Dir
.length()-1] == '/')
675 return Dir
+ '/' + File
;
678 // flAbsPath - Return the absolute path of the filename /*{{{*/
679 // ---------------------------------------------------------------------
681 string
flAbsPath(string File
)
683 char *p
= realpath(File
.c_str(), NULL
);
686 _error
->Errno("realpath", "flAbsPath on %s failed", File
.c_str());
689 std::string
AbsPath(p
);
694 // SetCloseExec - Set the close on exec flag /*{{{*/
695 // ---------------------------------------------------------------------
697 void SetCloseExec(int Fd
,bool Close
)
699 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
701 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
706 // SetNonBlock - Set the nonblocking flag /*{{{*/
707 // ---------------------------------------------------------------------
709 void SetNonBlock(int Fd
,bool Block
)
711 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
712 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
714 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
719 // WaitFd - Wait for a FD to become readable /*{{{*/
720 // ---------------------------------------------------------------------
721 /* This waits for a FD to become readable using select. It is useful for
722 applications making use of non-blocking sockets. The timeout is
724 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
737 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
739 while (Res
< 0 && errno
== EINTR
);
749 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
751 while (Res
< 0 && errno
== EINTR
);
760 // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
761 // ---------------------------------------------------------------------
762 /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
765 void MergeKeepFdsFromConfiguration(std::set
<int> &KeepFDs
)
767 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
768 if (Opts
!= 0 && Opts
->Child
!= 0)
771 for (; Opts
!= 0; Opts
= Opts
->Next
)
773 if (Opts
->Value
.empty() == true)
775 int fd
= atoi(Opts
->Value
.c_str());
781 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
782 // ---------------------------------------------------------------------
783 /* This is used if you want to cleanse the environment for the forked
784 child, it fixes up the important signals and nukes all of the fds,
785 otherwise acts like normal fork. */
789 // we need to merge the Keep-Fds as external tools like
790 // debconf-apt-progress use it
791 MergeKeepFdsFromConfiguration(KeepFDs
);
792 return ExecFork(KeepFDs
);
795 pid_t
ExecFork(std::set
<int> KeepFDs
)
797 // Fork off the process
798 pid_t Process
= fork();
801 cerr
<< "FATAL -> Failed to fork." << endl
;
805 // Spawn the subprocess
809 signal(SIGPIPE
,SIG_DFL
);
810 signal(SIGQUIT
,SIG_DFL
);
811 signal(SIGINT
,SIG_DFL
);
812 signal(SIGWINCH
,SIG_DFL
);
813 signal(SIGCONT
,SIG_DFL
);
814 signal(SIGTSTP
,SIG_DFL
);
816 DIR *dir
= opendir("/proc/self/fd");
820 while ((ent
= readdir(dir
)))
822 int fd
= atoi(ent
->d_name
);
823 // If fd > 0, it was a fd number and not . or ..
824 if (fd
>= 3 && KeepFDs
.find(fd
) == KeepFDs
.end())
825 fcntl(fd
,F_SETFD
,FD_CLOEXEC
);
829 long ScOpenMax
= sysconf(_SC_OPEN_MAX
);
830 // Close all of our FDs - just in case
831 for (int K
= 3; K
!= ScOpenMax
; K
++)
833 if(KeepFDs
.find(K
) == KeepFDs
.end())
834 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
842 // ExecWait - Fancy waitpid /*{{{*/
843 // ---------------------------------------------------------------------
844 /* Waits for the given sub process. If Reap is set then no errors are
845 generated. Otherwise a failed subprocess will generate a proper descriptive
847 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
852 // Wait and collect the error code
854 while (waitpid(Pid
,&Status
,0) != Pid
)
862 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
866 // Check for an error code.
867 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
871 if (WIFSIGNALED(Status
) != 0)
873 if( WTERMSIG(Status
) == SIGSEGV
)
874 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
876 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
879 if (WIFEXITED(Status
) != 0)
880 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
882 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
888 // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
889 bool StartsWithGPGClearTextSignature(string
const &FileName
)
891 static const char* SIGMSG
= "-----BEGIN PGP SIGNED MESSAGE-----\n";
892 char buffer
[strlen(SIGMSG
)+1];
893 FILE* gpg
= fopen(FileName
.c_str(), "r");
897 char const * const test
= fgets(buffer
, sizeof(buffer
), gpg
);
899 if (test
== NULL
|| strcmp(buffer
, SIGMSG
) != 0)
905 // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
906 bool ChangeOwnerAndPermissionOfFile(char const * const requester
, char const * const file
, char const * const user
, char const * const group
, mode_t
const mode
)
908 if (strcmp(file
, "/dev/null") == 0)
911 if (getuid() == 0 && strlen(user
) != 0 && strlen(group
) != 0) // if we aren't root, we can't chown, so don't try it
913 // ensure the file is owned by root and has good permissions
914 struct passwd
const * const pw
= getpwnam(user
);
915 struct group
const * const gr
= getgrnam(group
);
916 if (pw
!= NULL
&& gr
!= NULL
&& chown(file
, pw
->pw_uid
, gr
->gr_gid
) != 0)
917 Res
&= _error
->WarningE(requester
, "chown to %s:%s of file %s failed", user
, group
, file
);
919 if (chmod(file
, mode
) != 0)
920 Res
&= _error
->WarningE(requester
, "chmod 0%o of file %s failed", mode
, file
);
925 struct APT_HIDDEN simple_buffer
{ /*{{{*/
926 size_t buffersize_max
= 0;
927 unsigned long long bufferstart
= 0;
928 unsigned long long bufferend
= 0;
929 char *buffer
= nullptr;
938 const char *get() const { return buffer
+ bufferstart
; }
939 char *get() { return buffer
+ bufferstart
; }
940 const char *getend() const { return buffer
+ bufferend
; }
941 char *getend() { return buffer
+ bufferend
; }
942 bool empty() const { return bufferend
<= bufferstart
; }
943 bool full() const { return bufferend
== buffersize_max
; }
944 unsigned long long free() const { return buffersize_max
- bufferend
; }
945 unsigned long long size() const { return bufferend
-bufferstart
; }
946 void reset(size_t size
)
948 if (size
> buffersize_max
) {
950 buffersize_max
= size
;
951 buffer
= new char[size
];
955 void reset() { bufferend
= bufferstart
= 0; }
956 ssize_t
read(void *to
, unsigned long long requested_size
) APT_MUSTCHECK
958 if (size() < requested_size
)
959 requested_size
= size();
960 memcpy(to
, buffer
+ bufferstart
, requested_size
);
961 bufferstart
+= requested_size
;
962 if (bufferstart
== bufferend
)
963 bufferstart
= bufferend
= 0;
964 return requested_size
;
966 ssize_t
write(const void *from
, unsigned long long requested_size
) APT_MUSTCHECK
968 if (buffersize_max
- size() < requested_size
)
969 requested_size
= buffersize_max
- size();
970 memcpy(buffer
+ bufferend
, from
, requested_size
);
971 bufferend
+= requested_size
;
972 if (bufferstart
== bufferend
)
973 bufferstart
= bufferend
= 0;
974 return requested_size
;
979 class APT_HIDDEN FileFdPrivate
{ /*{{{*/
980 friend class BufferedWriteFileFdPrivate
;
982 FileFd
* const filefd
;
983 simple_buffer buffer
;
985 pid_t compressor_pid
;
987 APT::Configuration::Compressor compressor
;
988 unsigned int openmode
;
989 unsigned long long seekpos
;
992 explicit FileFdPrivate(FileFd
* const pfilefd
) : filefd(pfilefd
),
993 compressed_fd(-1), compressor_pid(-1), is_pipe(false),
994 openmode(0), seekpos(0) {};
995 virtual APT::Configuration::Compressor
get_compressor() const
999 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
)
1001 this->compressor
= compressor
;
1003 virtual unsigned int get_openmode() const
1007 virtual void set_openmode(unsigned int openmode
)
1009 this->openmode
= openmode
;
1011 virtual bool get_is_pipe() const
1015 virtual void set_is_pipe(bool is_pipe
)
1017 this->is_pipe
= is_pipe
;
1019 virtual unsigned long long get_seekpos() const
1023 virtual void set_seekpos(unsigned long long seekpos
)
1025 this->seekpos
= seekpos
;
1028 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) = 0;
1029 ssize_t
InternalRead(void * To
, unsigned long long Size
)
1031 // Drain the buffer if needed.
1032 if (buffer
.empty() == false)
1034 return buffer
.read(To
, Size
);
1036 return InternalUnbufferedRead(To
, Size
);
1038 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) = 0;
1039 virtual bool InternalReadError() { return filefd
->FileFdErrno("read",_("Read error")); }
1040 virtual char * InternalReadLine(char * To
, unsigned long long Size
)
1042 if (unlikely(Size
== 0))
1044 // Read one byte less than buffer size to have space for trailing 0.
1047 char * const InitialTo
= To
;
1050 if (buffer
.empty() == true)
1053 unsigned long long actualread
= 0;
1054 if (filefd
->Read(buffer
.get(), buffer
.buffersize_max
, &actualread
) == false)
1056 buffer
.bufferend
= actualread
;
1057 if (buffer
.size() == 0)
1059 if (To
== InitialTo
)
1063 filefd
->Flags
&= ~FileFd::HitEof
;
1066 unsigned long long const OutputSize
= std::min(Size
, buffer
.size());
1067 char const * const newline
= static_cast<char const * const>(memchr(buffer
.get(), '\n', OutputSize
));
1068 // Read until end of line or up to Size bytes from the buffer.
1069 unsigned long long actualread
= buffer
.read(To
,
1070 (newline
!= nullptr)
1071 ? (newline
- buffer
.get()) + 1
1075 if (newline
!= nullptr)
1081 virtual bool InternalFlush()
1085 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) = 0;
1086 virtual bool InternalWriteError() { return filefd
->FileFdErrno("write",_("Write error")); }
1087 virtual bool InternalSeek(unsigned long long const To
)
1089 // Our poor man seeking is costly, so try to avoid it
1090 unsigned long long const iseekpos
= filefd
->Tell();
1093 else if (iseekpos
< To
)
1094 return filefd
->Skip(To
- iseekpos
);
1096 if ((openmode
& FileFd::ReadOnly
) != FileFd::ReadOnly
)
1097 return filefd
->FileFdError("Reopen is only implemented for read-only files!");
1098 InternalClose(filefd
->FileName
);
1099 if (filefd
->iFd
!= -1)
1102 if (filefd
->TemporaryFileName
.empty() == false)
1103 filefd
->iFd
= open(filefd
->TemporaryFileName
.c_str(), O_RDONLY
);
1104 else if (filefd
->FileName
.empty() == false)
1105 filefd
->iFd
= open(filefd
->FileName
.c_str(), O_RDONLY
);
1108 if (compressed_fd
> 0)
1109 if (lseek(compressed_fd
, 0, SEEK_SET
) != 0)
1110 filefd
->iFd
= compressed_fd
;
1111 if (filefd
->iFd
< 0)
1112 return filefd
->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
1115 if (filefd
->OpenInternDescriptor(openmode
, compressor
) == false)
1116 return filefd
->FileFdError("Seek on file %s because it couldn't be reopened", filefd
->FileName
.c_str());
1120 return filefd
->Skip(To
);
1125 virtual bool InternalSkip(unsigned long long Over
)
1127 unsigned long long constexpr buffersize
= 1024;
1128 char buffer
[buffersize
];
1131 unsigned long long toread
= std::min(buffersize
, Over
);
1132 if (filefd
->Read(buffer
, toread
) == false)
1133 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1138 virtual bool InternalTruncate(unsigned long long const)
1140 return filefd
->FileFdError("Truncating compressed files is not implemented (%s)", filefd
->FileName
.c_str());
1142 virtual unsigned long long InternalTell()
1144 // In theory, we could just return seekpos here always instead of
1145 // seeking around, but not all users of FileFd use always Seek() and co
1146 // so d->seekpos isn't always true and we can just use it as a hint if
1147 // we have nothing else, but not always as an authority…
1148 return seekpos
- buffer
.size();
1150 virtual unsigned long long InternalSize()
1152 unsigned long long size
= 0;
1153 unsigned long long const oldSeek
= filefd
->Tell();
1154 unsigned long long constexpr ignoresize
= 1024;
1155 char ignore
[ignoresize
];
1156 unsigned long long read
= 0;
1158 if (filefd
->Read(ignore
, ignoresize
, &read
) == false)
1160 filefd
->Seek(oldSeek
);
1164 size
= filefd
->Tell();
1165 filefd
->Seek(oldSeek
);
1168 virtual bool InternalClose(std::string
const &FileName
) = 0;
1169 virtual bool InternalStream() const { return false; }
1170 virtual bool InternalAlwaysAutoClose() const { return true; }
1172 virtual ~FileFdPrivate() {}
1175 class APT_HIDDEN BufferedWriteFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1177 FileFdPrivate
*wrapped
;
1178 simple_buffer writebuffer
;
1182 explicit BufferedWriteFileFdPrivate(FileFdPrivate
*Priv
) :
1183 FileFdPrivate(Priv
->filefd
), wrapped(Priv
) {};
1185 virtual APT::Configuration::Compressor
get_compressor() const override
1187 return wrapped
->get_compressor();
1189 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
) override
1191 return wrapped
->set_compressor(compressor
);
1193 virtual unsigned int get_openmode() const override
1195 return wrapped
->get_openmode();
1197 virtual void set_openmode(unsigned int openmode
) override
1199 return wrapped
->set_openmode(openmode
);
1201 virtual bool get_is_pipe() const override
1203 return wrapped
->get_is_pipe();
1205 virtual void set_is_pipe(bool is_pipe
) override
1207 FileFdPrivate::set_is_pipe(is_pipe
);
1208 wrapped
->set_is_pipe(is_pipe
);
1210 virtual unsigned long long get_seekpos() const override
1212 return wrapped
->get_seekpos();
1214 virtual void set_seekpos(unsigned long long seekpos
) override
1216 return wrapped
->set_seekpos(seekpos
);
1218 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1220 if (InternalFlush() == false)
1222 return wrapped
->InternalOpen(iFd
, Mode
);
1224 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1226 if (InternalFlush() == false)
1228 return wrapped
->InternalUnbufferedRead(To
, Size
);
1231 virtual bool InternalReadError() override
1233 return wrapped
->InternalReadError();
1235 virtual char * InternalReadLine(char * To
, unsigned long long Size
) override
1237 if (InternalFlush() == false)
1239 return wrapped
->InternalReadLine(To
, Size
);
1241 virtual bool InternalFlush() override
1243 while (writebuffer
.empty() == false) {
1244 auto written
= wrapped
->InternalWrite(writebuffer
.get(),
1245 writebuffer
.size());
1246 // Ignore interrupted syscalls
1247 if (written
< 0 && errno
== EINTR
)
1252 writebuffer
.bufferstart
+= written
;
1255 writebuffer
.reset();
1258 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1262 while (written
< Size
) {
1263 auto buffered
= writebuffer
.write(static_cast<char const*>(From
) + written
, Size
- written
);
1265 written
+= buffered
;
1267 if (writebuffer
.full() && InternalFlush() == false)
1273 virtual bool InternalWriteError()
1275 return wrapped
->InternalWriteError();
1277 virtual bool InternalSeek(unsigned long long const To
)
1279 if (InternalFlush() == false)
1281 return wrapped
->InternalSeek(To
);
1283 virtual bool InternalSkip(unsigned long long Over
)
1285 if (InternalFlush() == false)
1287 return wrapped
->InternalSkip(Over
);
1289 virtual bool InternalTruncate(unsigned long long const Size
)
1291 if (InternalFlush() == false)
1293 return wrapped
->InternalTruncate(Size
);
1295 virtual unsigned long long InternalTell()
1297 if (InternalFlush() == false)
1299 return wrapped
->InternalTell();
1301 virtual unsigned long long InternalSize()
1303 if (InternalFlush() == false)
1305 return wrapped
->InternalSize();
1307 virtual bool InternalClose(std::string
const &FileName
)
1309 return wrapped
->InternalClose(FileName
);
1311 virtual bool InternalAlwaysAutoClose() const
1313 return wrapped
->InternalAlwaysAutoClose();
1315 virtual ~BufferedWriteFileFdPrivate()
1321 class APT_HIDDEN GzipFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1325 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1327 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1328 gz
= gzdopen(iFd
, "r+");
1329 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1330 gz
= gzdopen(iFd
, "w");
1332 gz
= gzdopen(iFd
, "r");
1333 filefd
->Flags
|= FileFd::Compressed
;
1334 return gz
!= nullptr;
1336 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1338 return gzread(gz
, To
, Size
);
1340 virtual bool InternalReadError() override
1343 char const * const errmsg
= gzerror(gz
, &err
);
1345 return filefd
->FileFdError("gzread: %s (%d: %s)", _("Read error"), err
, errmsg
);
1346 return FileFdPrivate::InternalReadError();
1348 virtual char * InternalReadLine(char * To
, unsigned long long Size
) override
1350 return gzgets(gz
, To
, Size
);
1352 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1354 return gzwrite(gz
,From
,Size
);
1356 virtual bool InternalWriteError() override
1359 char const * const errmsg
= gzerror(gz
, &err
);
1361 return filefd
->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err
, errmsg
);
1362 return FileFdPrivate::InternalWriteError();
1364 virtual bool InternalSeek(unsigned long long const To
) override
1366 off_t
const res
= gzseek(gz
, To
, SEEK_SET
);
1367 if (res
!= (off_t
)To
)
1368 return filefd
->FileFdError("Unable to seek to %llu", To
);
1373 virtual bool InternalSkip(unsigned long long Over
) override
1375 if (Over
>= buffer
.size())
1377 Over
-= buffer
.size();
1382 buffer
.bufferstart
+= Over
;
1387 off_t
const res
= gzseek(gz
, Over
, SEEK_CUR
);
1389 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1393 virtual unsigned long long InternalTell() override
1395 return gztell(gz
) - buffer
.size();
1397 virtual unsigned long long InternalSize() override
1399 unsigned long long filesize
= FileFdPrivate::InternalSize();
1400 // only check gzsize if we are actually a gzip file, just checking for
1401 // "gz" is not sufficient as uncompressed files could be opened with
1402 // gzopen in "direct" mode as well
1403 if (filesize
== 0 || gzdirect(gz
))
1406 off_t
const oldPos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
1407 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
1408 * this ourselves; the original (uncompressed) file size is the last 32
1409 * bits of the file */
1410 // FIXME: Size for gz-files is limited by 32bit… no largefile support
1411 if (lseek(filefd
->iFd
, -4, SEEK_END
) < 0)
1413 filefd
->FileFdErrno("lseek","Unable to seek to end of gzipped file");
1417 if (read(filefd
->iFd
, &size
, 4) != 4)
1419 filefd
->FileFdErrno("read","Unable to read original size of gzipped file");
1422 size
= le32toh(size
);
1424 if (lseek(filefd
->iFd
, oldPos
, SEEK_SET
) < 0)
1426 filefd
->FileFdErrno("lseek","Unable to seek in gzipped file");
1431 virtual bool InternalClose(std::string
const &FileName
) override
1435 int const e
= gzclose(gz
);
1437 // gzdclose() on empty files always fails with "buffer error" here, ignore that
1438 if (e
!= 0 && e
!= Z_BUF_ERROR
)
1439 return _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
1443 explicit GzipFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), gz(nullptr) {}
1444 virtual ~GzipFileFdPrivate() { InternalClose(""); }
1448 class APT_HIDDEN Bz2FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1452 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1454 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1455 bz2
= BZ2_bzdopen(iFd
, "r+");
1456 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1457 bz2
= BZ2_bzdopen(iFd
, "w");
1459 bz2
= BZ2_bzdopen(iFd
, "r");
1460 filefd
->Flags
|= FileFd::Compressed
;
1461 return bz2
!= nullptr;
1463 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1465 return BZ2_bzread(bz2
, To
, Size
);
1467 virtual bool InternalReadError() override
1470 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1471 if (err
!= BZ_IO_ERROR
)
1472 return filefd
->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Read error"), err
, errmsg
);
1473 return FileFdPrivate::InternalReadError();
1475 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1477 return BZ2_bzwrite(bz2
, (void*)From
, Size
);
1479 virtual bool InternalWriteError() override
1482 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1483 if (err
!= BZ_IO_ERROR
)
1484 return filefd
->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Write error"), err
, errmsg
);
1485 return FileFdPrivate::InternalWriteError();
1487 virtual bool InternalStream() const override
{ return true; }
1488 virtual bool InternalClose(std::string
const &) override
1497 explicit Bz2FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), bz2(nullptr) {}
1498 virtual ~Bz2FileFdPrivate() { InternalClose(""); }
1502 class APT_HIDDEN Lz4FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1503 static constexpr unsigned long long BLK_SIZE
= 64 * 1024;
1504 static constexpr unsigned long long LZ4_HEADER_SIZE
= 19;
1505 static constexpr unsigned long long LZ4_FOOTER_SIZE
= 4;
1507 LZ4F_decompressionContext_t dctx
;
1508 LZ4F_compressionContext_t cctx
;
1509 LZ4F_errorCode_t res
;
1511 simple_buffer lz4_buffer
;
1512 // Count of bytes that the decompressor expects to read next, or buffer size.
1513 size_t next_to_load
= BLK_SIZE
;
1515 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1517 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1518 return _error
->Error("lz4 only supports write or read mode");
1520 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
) {
1521 res
= LZ4F_createCompressionContext(&cctx
, LZ4F_VERSION
);
1522 lz4_buffer
.reset(LZ4F_compressBound(BLK_SIZE
, nullptr)
1523 + LZ4_HEADER_SIZE
+ LZ4_FOOTER_SIZE
);
1525 res
= LZ4F_createDecompressionContext(&dctx
, LZ4F_VERSION
);
1526 lz4_buffer
.reset(64 * 1024);
1529 filefd
->Flags
|= FileFd::Compressed
;
1531 if (LZ4F_isError(res
))
1534 unsigned int flags
= (Mode
& (FileFd::WriteOnly
|FileFd::ReadOnly
));
1535 if (backend
.OpenDescriptor(iFd
, flags
) == false)
1538 // Write the file header
1539 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1541 res
= LZ4F_compressBegin(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1542 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1548 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1550 /* Keep reading as long as the compressor still wants to read */
1551 while (next_to_load
) {
1552 // Fill compressed buffer;
1553 if (lz4_buffer
.empty()) {
1554 unsigned long long read
;
1555 /* Reset - if LZ4 decompressor wants to read more, allocate more */
1556 lz4_buffer
.reset(next_to_load
);
1557 if (backend
.Read(lz4_buffer
.getend(), lz4_buffer
.free(), &read
) == false)
1559 lz4_buffer
.bufferend
+= read
;
1564 return filefd
->FileFdError("LZ4F: %s %s",
1565 filefd
->FileName
.c_str(),
1566 _("Unexpected end of file")), -1;
1569 // Drain compressed buffer as far as possible.
1570 size_t in
= lz4_buffer
.size();
1573 res
= LZ4F_decompress(dctx
, To
, &out
, lz4_buffer
.get(), &in
, nullptr);
1574 if (LZ4F_isError(res
))
1578 lz4_buffer
.bufferstart
+= in
;
1586 virtual bool InternalReadError() override
1588 char const * const errmsg
= LZ4F_getErrorName(res
);
1590 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Read error"), res
, errmsg
);
1592 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1594 unsigned long long const towrite
= std::min(BLK_SIZE
, Size
);
1596 res
= LZ4F_compressUpdate(cctx
,
1597 lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
,
1598 From
, towrite
, nullptr);
1600 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1605 virtual bool InternalWriteError() override
1607 char const * const errmsg
= LZ4F_getErrorName(res
);
1609 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Write error"), res
, errmsg
);
1611 virtual bool InternalStream() const override
{ return true; }
1613 virtual bool InternalFlush() override
1615 return backend
.Flush();
1618 virtual bool InternalClose(std::string
const &) override
1620 /* Reset variables */
1622 next_to_load
= BLK_SIZE
;
1624 if (cctx
!= nullptr)
1626 res
= LZ4F_compressEnd(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1627 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1629 if (!backend
.Flush())
1631 if (!backend
.Close())
1634 res
= LZ4F_freeCompressionContext(cctx
);
1638 if (dctx
!= nullptr)
1640 res
= LZ4F_freeDecompressionContext(dctx
);
1644 return LZ4F_isError(res
) == false;
1647 explicit Lz4FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), dctx(nullptr), cctx(nullptr) {}
1648 virtual ~Lz4FileFdPrivate() {
1654 class APT_HIDDEN LzmaFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1658 uint8_t buffer
[4096];
1664 LZMAFILE() : file(nullptr), eof(false), compressing(false) { buffer
[0] = '\0'; }
1667 if (compressing
== true)
1669 size_t constexpr buffersize
= sizeof(buffer
)/sizeof(buffer
[0]);
1672 stream
.avail_out
= buffersize
;
1673 stream
.next_out
= buffer
;
1674 err
= lzma_code(&stream
, LZMA_FINISH
);
1675 if (err
!= LZMA_OK
&& err
!= LZMA_STREAM_END
)
1677 _error
->Error("~LZMAFILE: Compress finalisation failed");
1680 size_t const n
= buffersize
- stream
.avail_out
;
1681 if (n
&& fwrite(buffer
, 1, n
, file
) != n
)
1683 _error
->Errno("~LZMAFILE",_("Write error"));
1686 if (err
== LZMA_STREAM_END
)
1695 static uint32_t findXZlevel(std::vector
<std::string
> const &Args
)
1697 for (auto a
= Args
.rbegin(); a
!= Args
.rend(); ++a
)
1698 if (a
->empty() == false && (*a
)[0] == '-' && (*a
)[1] != '-')
1700 auto const number
= a
->find_last_of("0123456789");
1701 if (number
== std::string::npos
)
1703 auto const extreme
= a
->find("e", number
);
1704 uint32_t level
= (extreme
!= std::string::npos
) ? LZMA_PRESET_EXTREME
: 0;
1705 switch ((*a
)[number
])
1707 case '0': return level
| 0;
1708 case '1': return level
| 1;
1709 case '2': return level
| 2;
1710 case '3': return level
| 3;
1711 case '4': return level
| 4;
1712 case '5': return level
| 5;
1713 case '6': return level
| 6;
1714 case '7': return level
| 7;
1715 case '8': return level
| 8;
1716 case '9': return level
| 9;
1722 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1724 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1725 return filefd
->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd
->FileName
.c_str());
1727 if (lzma
== nullptr)
1728 lzma
= new LzmaFileFdPrivate::LZMAFILE
;
1729 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1730 lzma
->file
= fdopen(iFd
, "w");
1732 lzma
->file
= fdopen(iFd
, "r");
1733 filefd
->Flags
|= FileFd::Compressed
;
1734 if (lzma
->file
== nullptr)
1737 lzma_stream tmp_stream
= LZMA_STREAM_INIT
;
1738 lzma
->stream
= tmp_stream
;
1740 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1742 uint32_t const xzlevel
= findXZlevel(compressor
.CompressArgs
);
1743 if (compressor
.Name
== "xz")
1745 if (lzma_easy_encoder(&lzma
->stream
, xzlevel
, LZMA_CHECK_CRC64
) != LZMA_OK
)
1750 lzma_options_lzma options
;
1751 lzma_lzma_preset(&options
, xzlevel
);
1752 if (lzma_alone_encoder(&lzma
->stream
, &options
) != LZMA_OK
)
1755 lzma
->compressing
= true;
1759 uint64_t const memlimit
= UINT64_MAX
;
1760 if (compressor
.Name
== "xz")
1762 if (lzma_auto_decoder(&lzma
->stream
, memlimit
, 0) != LZMA_OK
)
1767 if (lzma_alone_decoder(&lzma
->stream
, memlimit
) != LZMA_OK
)
1770 lzma
->compressing
= false;
1774 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1777 if (lzma
->eof
== true)
1780 lzma
->stream
.next_out
= (uint8_t *) To
;
1781 lzma
->stream
.avail_out
= Size
;
1782 if (lzma
->stream
.avail_in
== 0)
1784 lzma
->stream
.next_in
= lzma
->buffer
;
1785 lzma
->stream
.avail_in
= fread(lzma
->buffer
, 1, sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]), lzma
->file
);
1787 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1788 if (lzma
->err
== LZMA_STREAM_END
)
1791 Res
= Size
- lzma
->stream
.avail_out
;
1793 else if (lzma
->err
!= LZMA_OK
)
1800 Res
= Size
- lzma
->stream
.avail_out
;
1803 // lzma run was okay, but produced no output…
1810 virtual bool InternalReadError() override
1812 return filefd
->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma
->err
);
1814 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1816 lzma
->stream
.next_in
= (uint8_t *)From
;
1817 lzma
->stream
.avail_in
= Size
;
1818 lzma
->stream
.next_out
= lzma
->buffer
;
1819 lzma
->stream
.avail_out
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]);
1820 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1821 if (lzma
->err
!= LZMA_OK
)
1823 size_t const n
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]) - lzma
->stream
.avail_out
;
1824 size_t const m
= (n
== 0) ? 0 : fwrite(lzma
->buffer
, 1, n
, lzma
->file
);
1828 return Size
- lzma
->stream
.avail_in
;
1830 virtual bool InternalWriteError() override
1832 return filefd
->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma
->err
);
1834 virtual bool InternalStream() const override
{ return true; }
1835 virtual bool InternalClose(std::string
const &) override
1842 explicit LzmaFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), lzma(nullptr) {}
1843 virtual ~LzmaFileFdPrivate() { InternalClose(""); }
1847 class APT_HIDDEN PipedFileFdPrivate
: public FileFdPrivate
/*{{{*/
1848 /* if we don't have a specific class dealing with library calls, we (un)compress
1849 by executing a specified binary and pipe in/out what we need */
1852 virtual bool InternalOpen(int const, unsigned int const Mode
) override
1854 // collect zombies here in case we reopen
1855 if (compressor_pid
> 0)
1856 ExecWait(compressor_pid
, "FileFdCompressor", true);
1858 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1859 return filefd
->FileFdError("ReadWrite mode is not supported for file %s", filefd
->FileName
.c_str());
1861 bool const Comp
= (Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
;
1864 // Handle 'decompression' of empty files
1866 fstat(filefd
->iFd
, &Buf
);
1867 if (Buf
.st_size
== 0 && S_ISFIFO(Buf
.st_mode
) == false)
1870 // We don't need the file open - instead let the compressor open it
1871 // as he properly knows better how to efficiently read from 'his' file
1872 if (filefd
->FileName
.empty() == false)
1879 // Create a data pipe
1880 int Pipe
[2] = {-1,-1};
1881 if (pipe(Pipe
) != 0)
1882 return filefd
->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
1883 for (int J
= 0; J
!= 2; J
++)
1884 SetCloseExec(Pipe
[J
],true);
1886 compressed_fd
= filefd
->iFd
;
1890 filefd
->iFd
= Pipe
[1];
1892 filefd
->iFd
= Pipe
[0];
1895 compressor_pid
= ExecFork();
1896 if (compressor_pid
== 0)
1900 dup2(compressed_fd
,STDOUT_FILENO
);
1901 dup2(Pipe
[0],STDIN_FILENO
);
1905 if (compressed_fd
!= -1)
1906 dup2(compressed_fd
,STDIN_FILENO
);
1907 dup2(Pipe
[1],STDOUT_FILENO
);
1909 int const nullfd
= open("/dev/null", O_WRONLY
);
1912 dup2(nullfd
,STDERR_FILENO
);
1916 SetCloseExec(STDOUT_FILENO
,false);
1917 SetCloseExec(STDIN_FILENO
,false);
1919 std::vector
<char const*> Args
;
1920 Args
.push_back(compressor
.Binary
.c_str());
1921 std::vector
<std::string
> const * const addArgs
=
1922 (Comp
== true) ? &(compressor
.CompressArgs
) : &(compressor
.UncompressArgs
);
1923 for (std::vector
<std::string
>::const_iterator a
= addArgs
->begin();
1924 a
!= addArgs
->end(); ++a
)
1925 Args
.push_back(a
->c_str());
1926 if (Comp
== false && filefd
->FileName
.empty() == false)
1928 // commands not needing arguments, do not need to be told about using standard output
1929 // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
1930 if (compressor
.CompressArgs
.empty() == false && compressor
.UncompressArgs
.empty() == false)
1931 Args
.push_back("--stdout");
1932 if (filefd
->TemporaryFileName
.empty() == false)
1933 Args
.push_back(filefd
->TemporaryFileName
.c_str());
1935 Args
.push_back(filefd
->FileName
.c_str());
1937 Args
.push_back(NULL
);
1939 execvp(Args
[0],(char **)&Args
[0]);
1940 cerr
<< _("Failed to exec compressor ") << Args
[0] << endl
;
1950 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1952 return read(filefd
->iFd
, To
, Size
);
1954 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1956 return write(filefd
->iFd
, From
, Size
);
1958 virtual bool InternalClose(std::string
const &) override
1961 if (compressor_pid
> 0)
1962 Ret
&= ExecWait(compressor_pid
, "FileFdCompressor", true);
1963 compressor_pid
= -1;
1966 explicit PipedFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
1967 virtual ~PipedFileFdPrivate() { InternalClose(""); }
1970 class APT_HIDDEN DirectFileFdPrivate
: public FileFdPrivate
/*{{{*/
1973 virtual bool InternalOpen(int const, unsigned int const) override
{ return true; }
1974 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1976 return read(filefd
->iFd
, To
, Size
);
1978 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1980 // files opened read+write are strange and only really "supported" for direct files
1981 if (buffer
.size() != 0)
1983 lseek(filefd
->iFd
, -buffer
.size(), SEEK_CUR
);
1986 return write(filefd
->iFd
, From
, Size
);
1988 virtual bool InternalSeek(unsigned long long const To
) override
1990 off_t
const res
= lseek(filefd
->iFd
, To
, SEEK_SET
);
1991 if (res
!= (off_t
)To
)
1992 return filefd
->FileFdError("Unable to seek to %llu", To
);
1997 virtual bool InternalSkip(unsigned long long Over
) override
1999 if (Over
>= buffer
.size())
2001 Over
-= buffer
.size();
2006 buffer
.bufferstart
+= Over
;
2011 off_t
const res
= lseek(filefd
->iFd
, Over
, SEEK_CUR
);
2013 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
2017 virtual bool InternalTruncate(unsigned long long const To
) override
2019 if (buffer
.size() != 0)
2021 unsigned long long const seekpos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
2022 if ((seekpos
- buffer
.size()) >= To
)
2024 else if (seekpos
>= To
)
2025 buffer
.bufferend
= (To
- seekpos
) + buffer
.bufferstart
;
2029 if (ftruncate(filefd
->iFd
, To
) != 0)
2030 return filefd
->FileFdError("Unable to truncate to %llu",To
);
2033 virtual unsigned long long InternalTell() override
2035 return lseek(filefd
->iFd
,0,SEEK_CUR
) - buffer
.size();
2037 virtual unsigned long long InternalSize() override
2039 return filefd
->FileSize();
2041 virtual bool InternalClose(std::string
const &) override
{ return true; }
2042 virtual bool InternalAlwaysAutoClose() const override
{ return false; }
2044 explicit DirectFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
2045 virtual ~DirectFileFdPrivate() { InternalClose(""); }
2048 // FileFd Constructors /*{{{*/
2049 FileFd::FileFd(std::string FileName
,unsigned int const Mode
,unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2051 Open(FileName
,Mode
, None
, AccessMode
);
2053 FileFd::FileFd(std::string FileName
,unsigned int const Mode
, CompressMode Compress
, unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2055 Open(FileName
,Mode
, Compress
, AccessMode
);
2057 FileFd::FileFd() : iFd(-1), Flags(AutoClose
), d(NULL
) {}
2058 FileFd::FileFd(int const Fd
, unsigned int const Mode
, CompressMode Compress
) : iFd(-1), Flags(0), d(NULL
)
2060 OpenDescriptor(Fd
, Mode
, Compress
);
2062 FileFd::FileFd(int const Fd
, bool const AutoClose
) : iFd(-1), Flags(0), d(NULL
)
2064 OpenDescriptor(Fd
, ReadWrite
, None
, AutoClose
);
2067 // FileFd::Open - Open a file /*{{{*/
2068 // ---------------------------------------------------------------------
2069 /* The most commonly used open mode combinations are given with Mode */
2070 bool FileFd::Open(string FileName
,unsigned int const Mode
,CompressMode Compress
, unsigned long const AccessMode
)
2072 if (Mode
== ReadOnlyGzip
)
2073 return Open(FileName
, ReadOnly
, Gzip
, AccessMode
);
2075 if (Compress
== Auto
&& (Mode
& WriteOnly
) == WriteOnly
)
2076 return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName
.c_str());
2078 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2079 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2080 if (Compress
== Auto
)
2082 for (; compressor
!= compressors
.end(); ++compressor
)
2084 std::string file
= FileName
+ compressor
->Extension
;
2085 if (FileExists(file
) == false)
2091 else if (Compress
== Extension
)
2093 std::string::size_type
const found
= FileName
.find_last_of('.');
2095 if (found
!= std::string::npos
)
2097 ext
= FileName
.substr(found
);
2098 if (ext
== ".new" || ext
== ".bak")
2100 std::string::size_type
const found2
= FileName
.find_last_of('.', found
- 1);
2101 if (found2
!= std::string::npos
)
2102 ext
= FileName
.substr(found2
, found
- found2
);
2107 for (; compressor
!= compressors
.end(); ++compressor
)
2108 if (ext
== compressor
->Extension
)
2110 // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
2111 if (compressor
== compressors
.end())
2112 for (compressor
= compressors
.begin(); compressor
!= compressors
.end(); ++compressor
)
2113 if (compressor
->Name
== ".")
2121 case None
: name
= "."; break;
2122 case Gzip
: name
= "gzip"; break;
2123 case Bzip2
: name
= "bzip2"; break;
2124 case Lzma
: name
= "lzma"; break;
2125 case Xz
: name
= "xz"; break;
2126 case Lz4
: name
= "lz4"; break;
2130 return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName
.c_str());
2132 for (; compressor
!= compressors
.end(); ++compressor
)
2133 if (compressor
->Name
== name
)
2135 if (compressor
== compressors
.end())
2136 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2139 if (compressor
== compressors
.end())
2140 return FileFdError("Can't find a match for specified compressor mode for file %s", FileName
.c_str());
2141 return Open(FileName
, Mode
, *compressor
, AccessMode
);
2143 bool FileFd::Open(string FileName
,unsigned int const Mode
,APT::Configuration::Compressor
const &compressor
, unsigned long const AccessMode
)
2148 if ((Mode
& WriteOnly
) != WriteOnly
&& (Mode
& (Atomic
| Create
| Empty
| Exclusive
)) != 0)
2149 return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName
.c_str());
2150 if ((Mode
& ReadWrite
) == 0)
2151 return FileFdError("No openmode provided in FileFd::Open for %s", FileName
.c_str());
2153 unsigned int OpenMode
= Mode
;
2154 if (FileName
== "/dev/null")
2155 OpenMode
= OpenMode
& ~(Atomic
| Exclusive
| Create
| Empty
);
2157 if ((OpenMode
& Atomic
) == Atomic
)
2161 else if ((OpenMode
& (Exclusive
| Create
)) == (Exclusive
| Create
))
2163 // for atomic, this will be done by rename in Close()
2164 RemoveFile("FileFd::Open", FileName
);
2166 if ((OpenMode
& Empty
) == Empty
)
2169 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
2170 RemoveFile("FileFd::Open", FileName
);
2174 #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
2175 if_FLAGGED_SET(ReadWrite
, O_RDWR
);
2176 else if_FLAGGED_SET(ReadOnly
, O_RDONLY
);
2177 else if_FLAGGED_SET(WriteOnly
, O_WRONLY
);
2179 if_FLAGGED_SET(Create
, O_CREAT
);
2180 if_FLAGGED_SET(Empty
, O_TRUNC
);
2181 if_FLAGGED_SET(Exclusive
, O_EXCL
);
2182 #undef if_FLAGGED_SET
2184 if ((OpenMode
& Atomic
) == Atomic
)
2186 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
2188 if((iFd
= mkstemp(name
)) == -1)
2191 return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName
.c_str());
2194 TemporaryFileName
= string(name
);
2197 // umask() will always set the umask and return the previous value, so
2198 // we first set the umask and then reset it to the old value
2199 mode_t
const CurrentUmask
= umask(0);
2200 umask(CurrentUmask
);
2201 // calculate the actual file permissions (just like open/creat)
2202 mode_t
const FilePermissions
= (AccessMode
& ~CurrentUmask
);
2204 if(fchmod(iFd
, FilePermissions
) == -1)
2205 return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName
.c_str());
2208 iFd
= open(FileName
.c_str(), fileflags
, AccessMode
);
2210 this->FileName
= FileName
;
2211 if (iFd
== -1 || OpenInternDescriptor(OpenMode
, compressor
) == false)
2218 return FileFdErrno("open",_("Could not open file %s"), FileName
.c_str());
2221 SetCloseExec(iFd
,true);
2225 // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
2226 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, CompressMode Compress
, bool AutoClose
)
2228 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2229 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2232 // compat with the old API
2233 if (Mode
== ReadOnlyGzip
&& Compress
== None
)
2238 case None
: name
= "."; break;
2239 case Gzip
: name
= "gzip"; break;
2240 case Bzip2
: name
= "bzip2"; break;
2241 case Lzma
: name
= "lzma"; break;
2242 case Xz
: name
= "xz"; break;
2243 case Lz4
: name
= "lz4"; break;
2246 if (AutoClose
== true && Fd
!= -1)
2248 return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd
);
2250 for (; compressor
!= compressors
.end(); ++compressor
)
2251 if (compressor
->Name
== name
)
2253 if (compressor
== compressors
.end())
2255 if (AutoClose
== true && Fd
!= -1)
2257 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2259 return OpenDescriptor(Fd
, Mode
, *compressor
, AutoClose
);
2261 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
, bool AutoClose
)
2264 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
2266 this->FileName
= "";
2267 if (OpenInternDescriptor(Mode
, compressor
) == false)
2270 (Flags
& Compressed
) == Compressed
||
2276 return FileFdError(_("Could not open file descriptor %d"), Fd
);
2280 bool FileFd::OpenInternDescriptor(unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
)
2286 d
->InternalClose(FileName
);
2291 /* dummy so that the rest can be 'else if's */;
2292 #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
2293 else if (compressor.Name == NAME) \
2294 d = new CONSTRUCTOR(this)
2296 APT_COMPRESS_INIT("gzip", GzipFileFdPrivate
);
2299 APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate
);
2302 APT_COMPRESS_INIT("xz", LzmaFileFdPrivate
);
2303 APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate
);
2306 APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate
);
2308 #undef APT_COMPRESS_INIT
2309 else if (compressor
.Name
== "." || compressor
.Binary
.empty() == true)
2310 d
= new DirectFileFdPrivate(this);
2312 d
= new PipedFileFdPrivate(this);
2314 if (Mode
& BufferedWrite
)
2315 d
= new BufferedWriteFileFdPrivate(d
);
2317 d
->set_openmode(Mode
);
2318 d
->set_compressor(compressor
);
2319 if ((Flags
& AutoClose
) != AutoClose
&& d
->InternalAlwaysAutoClose())
2321 // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
2322 int const internFd
= dup(iFd
);
2324 return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd
);
2328 return d
->InternalOpen(iFd
, Mode
);
2331 // FileFd::~File - Closes the file /*{{{*/
2332 // ---------------------------------------------------------------------
2333 /* If the proper modes are selected then we close the Fd and possibly
2334 unlink the file on error. */
2339 d
->InternalClose(FileName
);
2344 // FileFd::Read - Read a bit of the file /*{{{*/
2345 // ---------------------------------------------------------------------
2346 /* We are careful to handle interruption by a signal while reading
2348 bool FileFd::Read(void *To
,unsigned long long Size
,unsigned long long *Actual
)
2356 *((char *)To
) = '\0';
2357 while (Res
> 0 && Size
> 0)
2359 Res
= d
->InternalRead(To
, Size
);
2365 // trick the while-loop into running again
2370 return d
->InternalReadError();
2373 To
= (char *)To
+ Res
;
2376 d
->set_seekpos(d
->get_seekpos() + Res
);
2391 return FileFdError(_("read, still have %llu to read but none left"), Size
);
2394 // FileFd::ReadLine - Read a complete line from the file /*{{{*/
2395 // ---------------------------------------------------------------------
2396 /* Beware: This method can be quite slow for big buffers on UNcompressed
2397 files because of the naive implementation! */
2398 char* FileFd::ReadLine(char *To
, unsigned long long const Size
)
2403 return d
->InternalReadLine(To
, Size
);
2406 // FileFd::Flush - Flush the file /*{{{*/
2407 bool FileFd::Flush()
2412 return d
->InternalFlush();
2415 // FileFd::Write - Write to the file /*{{{*/
2416 bool FileFd::Write(const void *From
,unsigned long long Size
)
2422 while (Res
> 0 && Size
> 0)
2424 Res
= d
->InternalWrite(From
, Size
);
2425 if (Res
< 0 && errno
== EINTR
)
2428 return d
->InternalWriteError();
2430 From
= (char const *)From
+ Res
;
2433 d
->set_seekpos(d
->get_seekpos() + Res
);
2439 return FileFdError(_("write, still have %llu to write but couldn't"), Size
);
2441 bool FileFd::Write(int Fd
, const void *From
, unsigned long long Size
)
2445 while (Res
> 0 && Size
> 0)
2447 Res
= write(Fd
,From
,Size
);
2448 if (Res
< 0 && errno
== EINTR
)
2451 return _error
->Errno("write",_("Write error"));
2453 From
= (char const *)From
+ Res
;
2460 return _error
->Error(_("write, still have %llu to write but couldn't"), Size
);
2463 // FileFd::Seek - Seek in the file /*{{{*/
2464 bool FileFd::Seek(unsigned long long To
)
2469 return d
->InternalSeek(To
);
2472 // FileFd::Skip - Skip over data in the file /*{{{*/
2473 bool FileFd::Skip(unsigned long long Over
)
2477 return d
->InternalSkip(Over
);
2480 // FileFd::Truncate - Truncate the file /*{{{*/
2481 bool FileFd::Truncate(unsigned long long To
)
2485 // truncating /dev/null is always successful - as we get an error otherwise
2486 if (To
== 0 && FileName
== "/dev/null")
2488 return d
->InternalTruncate(To
);
2491 // FileFd::Tell - Current seek position /*{{{*/
2492 // ---------------------------------------------------------------------
2494 unsigned long long FileFd::Tell()
2498 off_t
const Res
= d
->InternalTell();
2499 if (Res
== (off_t
)-1)
2500 FileFdErrno("lseek","Failed to determine the current file position");
2501 d
->set_seekpos(Res
);
2505 static bool StatFileFd(char const * const msg
, int const iFd
, std::string
const &FileName
, struct stat
&Buf
, FileFdPrivate
* const d
) /*{{{*/
2507 bool ispipe
= (d
!= NULL
&& d
->get_is_pipe() == true);
2508 if (ispipe
== false)
2510 if (fstat(iFd
,&Buf
) != 0)
2511 // higher-level code will generate more meaningful messages,
2512 // even translated this would be meaningless for users
2513 return _error
->Errno("fstat", "Unable to determine %s for fd %i", msg
, iFd
);
2514 if (FileName
.empty() == false)
2515 ispipe
= S_ISFIFO(Buf
.st_mode
);
2518 // for compressor pipes st_size is undefined and at 'best' zero
2521 // we set it here, too, as we get the info here for free
2522 // in theory the Open-methods should take care of it already
2524 d
->set_is_pipe(true);
2525 if (stat(FileName
.c_str(), &Buf
) != 0)
2526 return _error
->Errno("fstat", "Unable to determine %s for file %s", msg
, FileName
.c_str());
2531 // FileFd::FileSize - Return the size of the file /*{{{*/
2532 unsigned long long FileFd::FileSize()
2535 if (StatFileFd("file size", iFd
, FileName
, Buf
, d
) == false)
2543 // FileFd::ModificationTime - Return the time of last touch /*{{{*/
2544 time_t FileFd::ModificationTime()
2547 if (StatFileFd("modification time", iFd
, FileName
, Buf
, d
) == false)
2552 return Buf
.st_mtime
;
2555 // FileFd::Size - Return the size of the content in the file /*{{{*/
2556 unsigned long long FileFd::Size()
2560 return d
->InternalSize();
2563 // FileFd::Close - Close the file if the close flag is set /*{{{*/
2564 // ---------------------------------------------------------------------
2566 bool FileFd::Close()
2568 if (Flush() == false)
2574 if ((Flags
& AutoClose
) == AutoClose
)
2576 if ((Flags
& Compressed
) != Compressed
&& iFd
> 0 && close(iFd
) != 0)
2577 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
2582 Res
&= d
->InternalClose(FileName
);
2587 if ((Flags
& Replace
) == Replace
) {
2588 if (rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
2589 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
2591 FileName
= TemporaryFileName
; // for the unlink() below.
2592 TemporaryFileName
.clear();
2597 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
2598 FileName
.empty() == false)
2599 Res
&= RemoveFile("FileFd::Close", FileName
);
2606 // FileFd::Sync - Sync the file /*{{{*/
2607 // ---------------------------------------------------------------------
2611 if (fsync(iFd
) != 0)
2612 return FileFdErrno("sync",_("Problem syncing the file"));
2616 // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
2617 bool FileFd::FileFdErrno(const char *Function
, const char *Description
,...)
2621 size_t msgSize
= 400;
2622 int const errsv
= errno
;
2625 va_start(args
,Description
);
2626 if (_error
->InsertErrno(GlobalError::ERROR
, Function
, Description
, args
, errsv
, msgSize
) == false)
2633 // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
2634 bool FileFd::FileFdError(const char *Description
,...) {
2637 size_t msgSize
= 400;
2640 va_start(args
,Description
);
2641 if (_error
->Insert(GlobalError::ERROR
, Description
, args
, msgSize
) == false)
2648 gzFile
FileFd::gzFd() { /*{{{*/
2650 GzipFileFdPrivate
* const gzipd
= dynamic_cast<GzipFileFdPrivate
*>(d
);
2651 if (gzipd
== nullptr)
2661 // Glob - wrapper around "glob()" /*{{{*/
2662 std::vector
<std::string
> Glob(std::string
const &pattern
, int flags
)
2664 std::vector
<std::string
> result
;
2669 glob_res
= glob(pattern
.c_str(), flags
, NULL
, &globbuf
);
2673 if(glob_res
!= GLOB_NOMATCH
) {
2674 _error
->Errno("glob", "Problem with glob");
2680 for(i
=0;i
<globbuf
.gl_pathc
;i
++)
2681 result
.push_back(string(globbuf
.gl_pathv
[i
]));
2687 std::string
GetTempDir() /*{{{*/
2689 const char *tmpdir
= getenv("TMPDIR");
2697 if (!tmpdir
|| strlen(tmpdir
) == 0 || // tmpdir is set
2698 stat(tmpdir
, &st
) != 0 || (st
.st_mode
& S_IFDIR
) == 0) // exists and is directory
2700 else if (geteuid() != 0 && // root can do everything anyway
2701 faccessat(-1, tmpdir
, R_OK
| W_OK
| X_OK
, AT_EACCESS
| AT_SYMLINK_NOFOLLOW
) != 0) // current user has rwx access to directory
2704 return string(tmpdir
);
2706 std::string
GetTempDir(std::string
const &User
)
2708 // no need/possibility to drop privs
2709 if(getuid() != 0 || User
.empty() || User
== "root")
2710 return GetTempDir();
2712 struct passwd
const * const pw
= getpwnam(User
.c_str());
2714 return GetTempDir();
2716 gid_t
const old_euid
= geteuid();
2717 gid_t
const old_egid
= getegid();
2718 if (setegid(pw
->pw_gid
) != 0)
2719 _error
->Errno("setegid", "setegid %u failed", pw
->pw_gid
);
2720 if (seteuid(pw
->pw_uid
) != 0)
2721 _error
->Errno("seteuid", "seteuid %u failed", pw
->pw_uid
);
2723 std::string
const tmp
= GetTempDir();
2725 if (seteuid(old_euid
) != 0)
2726 _error
->Errno("seteuid", "seteuid %u failed", old_euid
);
2727 if (setegid(old_egid
) != 0)
2728 _error
->Errno("setegid", "setegid %u failed", old_egid
);
2733 FileFd
* GetTempFile(std::string
const &Prefix
, bool ImmediateUnlink
, FileFd
* const TmpFd
) /*{{{*/
2736 FileFd
* const Fd
= TmpFd
== NULL
? new FileFd() : TmpFd
;
2738 std::string
const tempdir
= GetTempDir();
2739 snprintf(fn
, sizeof(fn
), "%s/%s.XXXXXX",
2740 tempdir
.c_str(), Prefix
.c_str());
2741 int const fd
= mkstemp(fn
);
2746 _error
->Errno("GetTempFile",_("Unable to mkstemp %s"), fn
);
2749 if (!Fd
->OpenDescriptor(fd
, FileFd::ReadWrite
, FileFd::None
, true))
2751 _error
->Errno("GetTempFile",_("Unable to write to %s"),fn
);
2757 bool Rename(std::string From
, std::string To
) /*{{{*/
2759 if (rename(From
.c_str(),To
.c_str()) != 0)
2761 _error
->Error(_("rename failed, %s (%s -> %s)."),strerror(errno
),
2762 From
.c_str(),To
.c_str());
2768 bool Popen(const char* Args
[], FileFd
&Fd
, pid_t
&Child
, FileFd::OpenMode Mode
)/*{{{*/
2771 if (Mode
!= FileFd::ReadOnly
&& Mode
!= FileFd::WriteOnly
)
2772 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2774 int Pipe
[2] = {-1, -1};
2776 return _error
->Errno("pipe", _("Failed to create subprocess IPC"));
2778 std::set
<int> keep_fds
;
2779 keep_fds
.insert(Pipe
[0]);
2780 keep_fds
.insert(Pipe
[1]);
2781 Child
= ExecFork(keep_fds
);
2783 return _error
->Errno("fork", "Failed to fork");
2786 if(Mode
== FileFd::ReadOnly
)
2791 else if(Mode
== FileFd::WriteOnly
)
2797 if(Mode
== FileFd::ReadOnly
)
2801 } else if(Mode
== FileFd::WriteOnly
)
2804 execv(Args
[0], (char**)Args
);
2807 if(Mode
== FileFd::ReadOnly
)
2812 else if(Mode
== FileFd::WriteOnly
)
2818 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2819 Fd
.OpenDescriptor(fd
, Mode
, FileFd::None
, true);
2824 bool DropPrivileges() /*{{{*/
2826 if(_config
->FindB("Debug::NoDropPrivs", false) == true)
2830 #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
2831 #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
2833 // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
2834 int ret
= prctl(38, 1, 0, 0, 0);
2835 // ignore EINVAL - kernel is too old to understand the option
2836 if(ret
< 0 && errno
!= EINVAL
)
2837 _error
->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret
);
2840 // empty setting disables privilege dropping - this also ensures
2841 // backward compatibility, see bug #764506
2842 const std::string toUser
= _config
->Find("APT::Sandbox::User");
2843 if (toUser
.empty() || toUser
== "root")
2846 // a lot can go wrong trying to drop privileges completely,
2847 // so ideally we would like to verify that we have done it –
2848 // but the verify asks for too much in case of fakeroot (and alike)
2849 // [Specific checks can be overridden with dedicated options]
2850 bool const VerifySandboxing
= _config
->FindB("APT::Sandbox::Verify", false);
2852 // uid will be 0 in the end, but gid might be different anyway
2853 uid_t
const old_uid
= getuid();
2854 gid_t
const old_gid
= getgid();
2859 struct passwd
*pw
= getpwnam(toUser
.c_str());
2861 return _error
->Error("No user %s, can not drop rights", toUser
.c_str());
2863 // Do not change the order here, it might break things
2864 // Get rid of all our supplementary groups first
2865 if (setgroups(1, &pw
->pw_gid
))
2866 return _error
->Errno("setgroups", "Failed to setgroups");
2868 // Now change the group ids to the new user
2869 #ifdef HAVE_SETRESGID
2870 if (setresgid(pw
->pw_gid
, pw
->pw_gid
, pw
->pw_gid
) != 0)
2871 return _error
->Errno("setresgid", "Failed to set new group ids");
2873 if (setegid(pw
->pw_gid
) != 0)
2874 return _error
->Errno("setegid", "Failed to setegid");
2876 if (setgid(pw
->pw_gid
) != 0)
2877 return _error
->Errno("setgid", "Failed to setgid");
2880 // Change the user ids to the new user
2881 #ifdef HAVE_SETRESUID
2882 if (setresuid(pw
->pw_uid
, pw
->pw_uid
, pw
->pw_uid
) != 0)
2883 return _error
->Errno("setresuid", "Failed to set new user ids");
2885 if (setuid(pw
->pw_uid
) != 0)
2886 return _error
->Errno("setuid", "Failed to setuid");
2887 if (seteuid(pw
->pw_uid
) != 0)
2888 return _error
->Errno("seteuid", "Failed to seteuid");
2891 // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
2892 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Groups", false) == true)
2894 // Verify that the user isn't still in any supplementary groups
2895 long const ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
2896 std::unique_ptr
<gid_t
[]> gidlist(new gid_t
[ngroups_max
]);
2897 if (unlikely(gidlist
== NULL
))
2898 return _error
->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max
);
2900 if ((gidlist_nr
= getgroups(ngroups_max
, gidlist
.get())) < 0)
2901 return _error
->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max
);
2902 for (ssize_t i
= 0; i
< gidlist_nr
; ++i
)
2903 if (gidlist
[i
] != pw
->pw_gid
)
2904 return _error
->Error("Could not switch group, user %s is still in group %d", toUser
.c_str(), gidlist
[i
]);
2907 // enabled by default as all fakeroot-lookalikes should fake that accordingly
2908 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::IDs", true) == true)
2910 // Verify that gid, egid, uid, and euid changed
2911 if (getgid() != pw
->pw_gid
)
2912 return _error
->Error("Could not switch group");
2913 if (getegid() != pw
->pw_gid
)
2914 return _error
->Error("Could not switch effective group");
2915 if (getuid() != pw
->pw_uid
)
2916 return _error
->Error("Could not switch user");
2917 if (geteuid() != pw
->pw_uid
)
2918 return _error
->Error("Could not switch effective user");
2920 #ifdef HAVE_GETRESUID
2921 // verify that the saved set-user-id was changed as well
2925 if (getresuid(&ruid
, &euid
, &suid
))
2926 return _error
->Errno("getresuid", "Could not get saved set-user-ID");
2927 if (suid
!= pw
->pw_uid
)
2928 return _error
->Error("Could not switch saved set-user-ID");
2931 #ifdef HAVE_GETRESGID
2932 // verify that the saved set-group-id was changed as well
2936 if (getresgid(&rgid
, &egid
, &sgid
))
2937 return _error
->Errno("getresuid", "Could not get saved set-group-ID");
2938 if (sgid
!= pw
->pw_gid
)
2939 return _error
->Error("Could not switch saved set-group-ID");
2943 // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
2944 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Regain", false) == true)
2946 // Check that uid and gid changes do not work anymore
2947 if (pw
->pw_gid
!= old_gid
&& (setgid(old_gid
) != -1 || setegid(old_gid
) != -1))
2948 return _error
->Error("Could restore a gid to root, privilege dropping did not work");
2950 if (pw
->pw_uid
!= old_uid
&& (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1))
2951 return _error
->Error("Could restore a uid to root, privilege dropping did not work");