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 /* Should be a multiple of the common page size (4096) */
82 static constexpr unsigned long long APT_BUFFER_SIZE
= 64 * 1024;
84 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
85 // ---------------------------------------------------------------------
87 bool RunScripts(const char *Cnf
)
89 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
90 if (Opts
== 0 || Opts
->Child
== 0)
94 // Fork for running the system calls
95 pid_t Child
= ExecFork();
100 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
102 std::cerr
<< "Chrooting into "
103 << _config
->FindDir("DPkg::Chroot-Directory")
105 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
109 if (chdir("/tmp/") != 0)
112 unsigned int Count
= 1;
113 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
115 if (Opts
->Value
.empty() == true)
118 if(_config
->FindB("Debug::RunScripts", false) == true)
119 std::clog
<< "Running external script: '"
120 << Opts
->Value
<< "'" << std::endl
;
122 if (system(Opts
->Value
.c_str()) != 0)
128 // Wait for the child
130 while (waitpid(Child
,&Status
,0) != Child
)
134 return _error
->Errno("waitpid","Couldn't wait for subprocess");
137 // Restore sig int/quit
138 signal(SIGQUIT
,SIG_DFL
);
139 signal(SIGINT
,SIG_DFL
);
141 // Check for an error code.
142 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
144 unsigned int Count
= WEXITSTATUS(Status
);
148 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
149 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
152 return _error
->Error("Sub-process returned an error code");
159 // CopyFile - Buffered copy of a file /*{{{*/
160 // ---------------------------------------------------------------------
161 /* The caller is expected to set things so that failure causes erasure */
162 bool CopyFile(FileFd
&From
,FileFd
&To
)
164 if (From
.IsOpen() == false || To
.IsOpen() == false ||
165 From
.Failed() == true || To
.Failed() == true)
168 // Buffered copy between fds
169 constexpr size_t BufSize
= APT_BUFFER_SIZE
;
170 std::unique_ptr
<unsigned char[]> Buf(new unsigned char[BufSize
]);
171 unsigned long long ToRead
= 0;
173 if (From
.Read(Buf
.get(),BufSize
, &ToRead
) == false ||
174 To
.Write(Buf
.get(),ToRead
) == false)
176 } while (ToRead
!= 0);
181 bool RemoveFile(char const * const Function
, std::string
const &FileName
)/*{{{*/
183 if (FileName
== "/dev/null")
186 if (unlink(FileName
.c_str()) != 0)
191 return _error
->WarningE(Function
,_("Problem unlinking the file %s"), FileName
.c_str());
196 // GetLock - Gets a lock file /*{{{*/
197 // ---------------------------------------------------------------------
198 /* This will create an empty file of the given name and lock it. Once this
199 is done all other calls to GetLock in any other process will fail with
200 -1. The return result is the fd of the file, the call should call
201 close at some time. */
202 int GetLock(string File
,bool Errors
)
204 // GetLock() is used in aptitude on directories with public-write access
205 // Use O_NOFOLLOW here to prevent symlink traversal attacks
206 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
209 // Read only .. can't have locking problems there.
212 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
213 return dup(0); // Need something for the caller to close
217 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
219 // Feh.. We do this to distinguish the lock vs open case..
223 SetCloseExec(FD
,true);
225 // Acquire a write lock
228 fl
.l_whence
= SEEK_SET
;
231 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
233 // always close to not leak resources
240 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
241 return dup(0); // Need something for the caller to close
245 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
253 // FileExists - Check if a file exists /*{{{*/
254 // ---------------------------------------------------------------------
255 /* Beware: Directories are also files! */
256 bool FileExists(string File
)
259 if (stat(File
.c_str(),&Buf
) != 0)
264 // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
265 // ---------------------------------------------------------------------
267 bool RealFileExists(string File
)
270 if (stat(File
.c_str(),&Buf
) != 0)
272 return ((Buf
.st_mode
& S_IFREG
) != 0);
275 // DirectoryExists - Check if a directory exists and is really one /*{{{*/
276 // ---------------------------------------------------------------------
278 bool DirectoryExists(string
const &Path
)
281 if (stat(Path
.c_str(),&Buf
) != 0)
283 return ((Buf
.st_mode
& S_IFDIR
) != 0);
286 // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
287 // ---------------------------------------------------------------------
288 /* This method will create all directories needed for path in good old
289 mkdir -p style but refuses to do this if Parent is not a prefix of
290 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
291 so it will create apt/archives if /var/cache exists - on the other
292 hand if the parent is /var/lib the creation will fail as this path
293 is not a parent of the path to be generated. */
294 bool CreateDirectory(string
const &Parent
, string
const &Path
)
296 if (Parent
.empty() == true || Path
.empty() == true)
299 if (DirectoryExists(Path
) == true)
302 if (DirectoryExists(Parent
) == false)
305 // we are not going to create directories "into the blue"
306 if (Path
.compare(0, Parent
.length(), Parent
) != 0)
309 vector
<string
> const dirs
= VectorizeString(Path
.substr(Parent
.size()), '/');
310 string progress
= Parent
;
311 for (vector
<string
>::const_iterator d
= dirs
.begin(); d
!= dirs
.end(); ++d
)
313 if (d
->empty() == true)
316 progress
.append("/").append(*d
);
317 if (DirectoryExists(progress
) == true)
320 if (mkdir(progress
.c_str(), 0755) != 0)
326 // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
327 // ---------------------------------------------------------------------
328 /* a small wrapper around CreateDirectory to check if it exists and to
329 remove the trailing "/apt/" from the parent directory if needed */
330 bool CreateAPTDirectoryIfNeeded(string
const &Parent
, string
const &Path
)
332 if (DirectoryExists(Path
) == true)
335 size_t const len
= Parent
.size();
336 if (len
> 5 && Parent
.find("/apt/", len
- 6, 5) == len
- 5)
338 if (CreateDirectory(Parent
.substr(0,len
-5), Path
) == true)
341 else if (CreateDirectory(Parent
, Path
) == true)
347 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
348 // ---------------------------------------------------------------------
349 /* If an extension is given only files with this extension are included
350 in the returned vector, otherwise every "normal" file is included. */
351 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
352 bool const &SortList
, bool const &AllowNoExt
)
354 std::vector
<string
> ext
;
356 if (Ext
.empty() == false)
358 if (AllowNoExt
== true && ext
.empty() == false)
360 return GetListOfFilesInDir(Dir
, ext
, SortList
);
362 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, std::vector
<string
> const &Ext
,
363 bool const &SortList
)
365 // Attention debuggers: need to be set with the environment config file!
366 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
369 std::clog
<< "Accept in " << Dir
<< " only files with the following " << Ext
.size() << " extensions:" << std::endl
;
370 if (Ext
.empty() == true)
371 std::clog
<< "\tNO extension" << std::endl
;
373 for (std::vector
<string
>::const_iterator e
= Ext
.begin();
375 std::clog
<< '\t' << (e
->empty() == true ? "NO" : *e
) << " extension" << std::endl
;
378 std::vector
<string
> List
;
380 if (DirectoryExists(Dir
) == false)
382 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
386 Configuration::MatchAgainstConfig
SilentIgnore("Dir::Ignore-Files-Silently");
387 DIR *D
= opendir(Dir
.c_str());
390 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
394 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
396 // skip "hidden" files
397 if (Ent
->d_name
[0] == '.')
400 // Make sure it is a file and not something else
401 string
const File
= flCombine(Dir
,Ent
->d_name
);
402 #ifdef _DIRENT_HAVE_D_TYPE
403 if (Ent
->d_type
!= DT_REG
)
406 if (RealFileExists(File
) == false)
408 // do not show ignoration warnings for directories
410 #ifdef _DIRENT_HAVE_D_TYPE
411 Ent
->d_type
== DT_DIR
||
413 DirectoryExists(File
) == true)
415 if (SilentIgnore
.Match(Ent
->d_name
) == false)
416 _error
->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent
->d_name
, Dir
.c_str());
421 // check for accepted extension:
422 // no extension given -> periods are bad as hell!
423 // extensions given -> "" extension allows no extension
424 if (Ext
.empty() == false)
426 string d_ext
= flExtension(Ent
->d_name
);
427 if (d_ext
== Ent
->d_name
) // no extension
429 if (std::find(Ext
.begin(), Ext
.end(), "") == Ext
.end())
432 std::clog
<< "Bad file: " << Ent
->d_name
<< " → no extension" << std::endl
;
433 if (SilentIgnore
.Match(Ent
->d_name
) == false)
434 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent
->d_name
, Dir
.c_str());
438 else if (std::find(Ext
.begin(), Ext
.end(), d_ext
) == Ext
.end())
441 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad extension »" << flExtension(Ent
->d_name
) << "«" << std::endl
;
442 if (SilentIgnore
.Match(Ent
->d_name
) == false)
443 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent
->d_name
, Dir
.c_str());
448 // Skip bad filenames ala run-parts
449 const char *C
= Ent
->d_name
;
451 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
452 && *C
!= '_' && *C
!= '-' && *C
!= ':') {
453 // no required extension -> dot is a bad character
454 if (*C
== '.' && Ext
.empty() == false)
459 // we don't reach the end of the name -> bad character included
463 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »"
464 << *C
<< "« in filename (period allowed: " << (Ext
.empty() ? "no" : "yes") << ")" << std::endl
;
468 // skip filenames which end with a period. These are never valid
472 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
477 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
478 List
.push_back(File
);
482 if (SortList
== true)
483 std::sort(List
.begin(),List
.end());
486 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, bool SortList
)
488 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
490 std::clog
<< "Accept in " << Dir
<< " all regular files" << std::endl
;
492 std::vector
<string
> List
;
494 if (DirectoryExists(Dir
) == false)
496 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
500 DIR *D
= opendir(Dir
.c_str());
503 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
507 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
509 // skip "hidden" files
510 if (Ent
->d_name
[0] == '.')
513 // Make sure it is a file and not something else
514 string
const File
= flCombine(Dir
,Ent
->d_name
);
515 #ifdef _DIRENT_HAVE_D_TYPE
516 if (Ent
->d_type
!= DT_REG
)
519 if (RealFileExists(File
) == false)
522 std::clog
<< "Bad file: " << Ent
->d_name
<< " → it is not a real file" << std::endl
;
527 // Skip bad filenames ala run-parts
528 const char *C
= Ent
->d_name
;
530 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
531 && *C
!= '_' && *C
!= '-' && *C
!= '.')
534 // we don't reach the end of the name -> bad character included
538 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »" << *C
<< "« in filename" << std::endl
;
542 // skip filenames which end with a period. These are never valid
546 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
551 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
552 List
.push_back(File
);
556 if (SortList
== true)
557 std::sort(List
.begin(),List
.end());
561 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
562 // ---------------------------------------------------------------------
563 /* We return / on failure. */
566 // Stash the current dir.
569 if (getcwd(S
,sizeof(S
)-2) == 0)
571 unsigned int Len
= strlen(S
);
577 // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
578 // ---------------------------------------------------------------------
579 /* We return / on failure. */
580 time_t GetModificationTime(string
const &Path
)
583 if (stat(Path
.c_str(), &St
) < 0)
588 // flNotDir - Strip the directory from the filename /*{{{*/
589 // ---------------------------------------------------------------------
591 string
flNotDir(string File
)
593 string::size_type Res
= File
.rfind('/');
594 if (Res
== string::npos
)
597 return string(File
,Res
,Res
- File
.length());
600 // flNotFile - Strip the file from the directory name /*{{{*/
601 // ---------------------------------------------------------------------
602 /* Result ends in a / */
603 string
flNotFile(string File
)
605 string::size_type Res
= File
.rfind('/');
606 if (Res
== string::npos
)
609 return string(File
,0,Res
);
612 // flExtension - Return the extension for the file /*{{{*/
613 // ---------------------------------------------------------------------
615 string
flExtension(string File
)
617 string::size_type Res
= File
.rfind('.');
618 if (Res
== string::npos
)
621 return string(File
,Res
,Res
- File
.length());
624 // flNoLink - If file is a symlink then deref it /*{{{*/
625 // ---------------------------------------------------------------------
626 /* If the name is not a link then the returned path is the input. */
627 string
flNoLink(string File
)
630 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
632 if (stat(File
.c_str(),&St
) != 0)
635 /* Loop resolving the link. There is no need to limit the number of
636 loops because the stat call above ensures that the symlink is not
644 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
645 (size_t)Res
>= sizeof(Buffer
))
648 // Append or replace the previous path
650 if (Buffer
[0] == '/')
653 NFile
= flNotFile(NFile
) + Buffer
;
655 // See if we are done
656 if (lstat(NFile
.c_str(),&St
) != 0)
658 if (S_ISLNK(St
.st_mode
) == 0)
663 // flCombine - Combine a file and a directory /*{{{*/
664 // ---------------------------------------------------------------------
665 /* If the file is an absolute path then it is just returned, otherwise
666 the directory is pre-pended to it. */
667 string
flCombine(string Dir
,string File
)
669 if (File
.empty() == true)
672 if (File
[0] == '/' || Dir
.empty() == true)
674 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
676 if (Dir
[Dir
.length()-1] == '/')
678 return Dir
+ '/' + File
;
681 // flAbsPath - Return the absolute path of the filename /*{{{*/
682 // ---------------------------------------------------------------------
684 string
flAbsPath(string File
)
686 char *p
= realpath(File
.c_str(), NULL
);
689 _error
->Errno("realpath", "flAbsPath on %s failed", File
.c_str());
692 std::string
AbsPath(p
);
697 // SetCloseExec - Set the close on exec flag /*{{{*/
698 // ---------------------------------------------------------------------
700 void SetCloseExec(int Fd
,bool Close
)
702 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
704 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
709 // SetNonBlock - Set the nonblocking flag /*{{{*/
710 // ---------------------------------------------------------------------
712 void SetNonBlock(int Fd
,bool Block
)
714 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
715 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
717 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
722 // WaitFd - Wait for a FD to become readable /*{{{*/
723 // ---------------------------------------------------------------------
724 /* This waits for a FD to become readable using select. It is useful for
725 applications making use of non-blocking sockets. The timeout is
727 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
740 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
742 while (Res
< 0 && errno
== EINTR
);
752 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
754 while (Res
< 0 && errno
== EINTR
);
763 // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
764 // ---------------------------------------------------------------------
765 /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
768 void MergeKeepFdsFromConfiguration(std::set
<int> &KeepFDs
)
770 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
771 if (Opts
!= 0 && Opts
->Child
!= 0)
774 for (; Opts
!= 0; Opts
= Opts
->Next
)
776 if (Opts
->Value
.empty() == true)
778 int fd
= atoi(Opts
->Value
.c_str());
784 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
785 // ---------------------------------------------------------------------
786 /* This is used if you want to cleanse the environment for the forked
787 child, it fixes up the important signals and nukes all of the fds,
788 otherwise acts like normal fork. */
792 // we need to merge the Keep-Fds as external tools like
793 // debconf-apt-progress use it
794 MergeKeepFdsFromConfiguration(KeepFDs
);
795 return ExecFork(KeepFDs
);
798 pid_t
ExecFork(std::set
<int> KeepFDs
)
800 // Fork off the process
801 pid_t Process
= fork();
804 cerr
<< "FATAL -> Failed to fork." << endl
;
808 // Spawn the subprocess
812 signal(SIGPIPE
,SIG_DFL
);
813 signal(SIGQUIT
,SIG_DFL
);
814 signal(SIGINT
,SIG_DFL
);
815 signal(SIGWINCH
,SIG_DFL
);
816 signal(SIGCONT
,SIG_DFL
);
817 signal(SIGTSTP
,SIG_DFL
);
819 DIR *dir
= opendir("/proc/self/fd");
823 while ((ent
= readdir(dir
)))
825 int fd
= atoi(ent
->d_name
);
826 // If fd > 0, it was a fd number and not . or ..
827 if (fd
>= 3 && KeepFDs
.find(fd
) == KeepFDs
.end())
828 fcntl(fd
,F_SETFD
,FD_CLOEXEC
);
832 long ScOpenMax
= sysconf(_SC_OPEN_MAX
);
833 // Close all of our FDs - just in case
834 for (int K
= 3; K
!= ScOpenMax
; K
++)
836 if(KeepFDs
.find(K
) == KeepFDs
.end())
837 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
845 // ExecWait - Fancy waitpid /*{{{*/
846 // ---------------------------------------------------------------------
847 /* Waits for the given sub process. If Reap is set then no errors are
848 generated. Otherwise a failed subprocess will generate a proper descriptive
850 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
855 // Wait and collect the error code
857 while (waitpid(Pid
,&Status
,0) != Pid
)
865 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
869 // Check for an error code.
870 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
874 if (WIFSIGNALED(Status
) != 0)
876 if( WTERMSIG(Status
) == SIGSEGV
)
877 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
879 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
882 if (WIFEXITED(Status
) != 0)
883 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
885 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
891 // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
892 bool StartsWithGPGClearTextSignature(string
const &FileName
)
894 static const char* SIGMSG
= "-----BEGIN PGP SIGNED MESSAGE-----\n";
895 char buffer
[strlen(SIGMSG
)+1];
896 FILE* gpg
= fopen(FileName
.c_str(), "r");
900 char const * const test
= fgets(buffer
, sizeof(buffer
), gpg
);
902 if (test
== NULL
|| strcmp(buffer
, SIGMSG
) != 0)
908 // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
909 bool ChangeOwnerAndPermissionOfFile(char const * const requester
, char const * const file
, char const * const user
, char const * const group
, mode_t
const mode
)
911 if (strcmp(file
, "/dev/null") == 0)
914 if (getuid() == 0 && strlen(user
) != 0 && strlen(group
) != 0) // if we aren't root, we can't chown, so don't try it
916 // ensure the file is owned by root and has good permissions
917 struct passwd
const * const pw
= getpwnam(user
);
918 struct group
const * const gr
= getgrnam(group
);
919 if (pw
!= NULL
&& gr
!= NULL
&& chown(file
, pw
->pw_uid
, gr
->gr_gid
) != 0)
920 Res
&= _error
->WarningE(requester
, "chown to %s:%s of file %s failed", user
, group
, file
);
922 if (chmod(file
, mode
) != 0)
923 Res
&= _error
->WarningE(requester
, "chmod 0%o of file %s failed", mode
, file
);
928 struct APT_HIDDEN simple_buffer
{ /*{{{*/
929 size_t buffersize_max
= 0;
930 unsigned long long bufferstart
= 0;
931 unsigned long long bufferend
= 0;
932 char *buffer
= nullptr;
941 const char *get() const { return buffer
+ bufferstart
; }
942 char *get() { return buffer
+ bufferstart
; }
943 const char *getend() const { return buffer
+ bufferend
; }
944 char *getend() { return buffer
+ bufferend
; }
945 bool empty() const { return bufferend
<= bufferstart
; }
946 bool full() const { return bufferend
== buffersize_max
; }
947 unsigned long long free() const { return buffersize_max
- bufferend
; }
948 unsigned long long size() const { return bufferend
-bufferstart
; }
949 void reset(size_t size
)
951 if (size
> buffersize_max
) {
953 buffersize_max
= size
;
954 buffer
= new char[size
];
958 void reset() { bufferend
= bufferstart
= 0; }
959 ssize_t
read(void *to
, unsigned long long requested_size
) APT_MUSTCHECK
961 if (size() < requested_size
)
962 requested_size
= size();
963 memcpy(to
, buffer
+ bufferstart
, requested_size
);
964 bufferstart
+= requested_size
;
965 if (bufferstart
== bufferend
)
966 bufferstart
= bufferend
= 0;
967 return requested_size
;
969 ssize_t
write(const void *from
, unsigned long long requested_size
) APT_MUSTCHECK
971 if (free() < requested_size
)
972 requested_size
= free();
973 memcpy(getend(), from
, requested_size
);
974 bufferend
+= requested_size
;
975 if (bufferstart
== bufferend
)
976 bufferstart
= bufferend
= 0;
977 return requested_size
;
982 class APT_HIDDEN FileFdPrivate
{ /*{{{*/
983 friend class BufferedWriteFileFdPrivate
;
985 FileFd
* const filefd
;
986 simple_buffer buffer
;
988 pid_t compressor_pid
;
990 APT::Configuration::Compressor compressor
;
991 unsigned int openmode
;
992 unsigned long long seekpos
;
995 explicit FileFdPrivate(FileFd
* const pfilefd
) : filefd(pfilefd
),
996 compressed_fd(-1), compressor_pid(-1), is_pipe(false),
997 openmode(0), seekpos(0) {};
998 virtual APT::Configuration::Compressor
get_compressor() const
1002 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
)
1004 this->compressor
= compressor
;
1006 virtual unsigned int get_openmode() const
1010 virtual void set_openmode(unsigned int openmode
)
1012 this->openmode
= openmode
;
1014 virtual bool get_is_pipe() const
1018 virtual void set_is_pipe(bool is_pipe
)
1020 this->is_pipe
= is_pipe
;
1022 virtual unsigned long long get_seekpos() const
1026 virtual void set_seekpos(unsigned long long seekpos
)
1028 this->seekpos
= seekpos
;
1031 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) = 0;
1032 ssize_t
InternalRead(void * To
, unsigned long long Size
)
1034 // Drain the buffer if needed.
1035 if (buffer
.empty() == false)
1037 return buffer
.read(To
, Size
);
1039 return InternalUnbufferedRead(To
, Size
);
1041 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) = 0;
1042 virtual bool InternalReadError() { return filefd
->FileFdErrno("read",_("Read error")); }
1043 virtual char * InternalReadLine(char * To
, unsigned long long Size
)
1045 if (unlikely(Size
== 0))
1047 // Read one byte less than buffer size to have space for trailing 0.
1050 char * const InitialTo
= To
;
1053 if (buffer
.empty() == true)
1056 unsigned long long actualread
= 0;
1057 if (filefd
->Read(buffer
.get(), buffer
.buffersize_max
, &actualread
) == false)
1059 buffer
.bufferend
= actualread
;
1060 if (buffer
.size() == 0)
1062 if (To
== InitialTo
)
1066 filefd
->Flags
&= ~FileFd::HitEof
;
1069 unsigned long long const OutputSize
= std::min(Size
, buffer
.size());
1070 char const * const newline
= static_cast<char const * const>(memchr(buffer
.get(), '\n', OutputSize
));
1071 // Read until end of line or up to Size bytes from the buffer.
1072 unsigned long long actualread
= buffer
.read(To
,
1073 (newline
!= nullptr)
1074 ? (newline
- buffer
.get()) + 1
1078 if (newline
!= nullptr)
1084 virtual bool InternalFlush()
1088 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) = 0;
1089 virtual bool InternalWriteError() { return filefd
->FileFdErrno("write",_("Write error")); }
1090 virtual bool InternalSeek(unsigned long long const To
)
1092 // Our poor man seeking is costly, so try to avoid it
1093 unsigned long long const iseekpos
= filefd
->Tell();
1096 else if (iseekpos
< To
)
1097 return filefd
->Skip(To
- iseekpos
);
1099 if ((openmode
& FileFd::ReadOnly
) != FileFd::ReadOnly
)
1100 return filefd
->FileFdError("Reopen is only implemented for read-only files!");
1101 InternalClose(filefd
->FileName
);
1102 if (filefd
->iFd
!= -1)
1105 if (filefd
->TemporaryFileName
.empty() == false)
1106 filefd
->iFd
= open(filefd
->TemporaryFileName
.c_str(), O_RDONLY
);
1107 else if (filefd
->FileName
.empty() == false)
1108 filefd
->iFd
= open(filefd
->FileName
.c_str(), O_RDONLY
);
1111 if (compressed_fd
> 0)
1112 if (lseek(compressed_fd
, 0, SEEK_SET
) != 0)
1113 filefd
->iFd
= compressed_fd
;
1114 if (filefd
->iFd
< 0)
1115 return filefd
->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
1118 if (filefd
->OpenInternDescriptor(openmode
, compressor
) == false)
1119 return filefd
->FileFdError("Seek on file %s because it couldn't be reopened", filefd
->FileName
.c_str());
1123 return filefd
->Skip(To
);
1128 virtual bool InternalSkip(unsigned long long Over
)
1130 unsigned long long constexpr buffersize
= 1024;
1131 char buffer
[buffersize
];
1134 unsigned long long toread
= std::min(buffersize
, Over
);
1135 if (filefd
->Read(buffer
, toread
) == false)
1136 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1141 virtual bool InternalTruncate(unsigned long long const)
1143 return filefd
->FileFdError("Truncating compressed files is not implemented (%s)", filefd
->FileName
.c_str());
1145 virtual unsigned long long InternalTell()
1147 // In theory, we could just return seekpos here always instead of
1148 // seeking around, but not all users of FileFd use always Seek() and co
1149 // so d->seekpos isn't always true and we can just use it as a hint if
1150 // we have nothing else, but not always as an authority…
1151 return seekpos
- buffer
.size();
1153 virtual unsigned long long InternalSize()
1155 unsigned long long size
= 0;
1156 unsigned long long const oldSeek
= filefd
->Tell();
1157 unsigned long long constexpr ignoresize
= 1024;
1158 char ignore
[ignoresize
];
1159 unsigned long long read
= 0;
1161 if (filefd
->Read(ignore
, ignoresize
, &read
) == false)
1163 filefd
->Seek(oldSeek
);
1167 size
= filefd
->Tell();
1168 filefd
->Seek(oldSeek
);
1171 virtual bool InternalClose(std::string
const &FileName
) = 0;
1172 virtual bool InternalStream() const { return false; }
1173 virtual bool InternalAlwaysAutoClose() const { return true; }
1175 virtual ~FileFdPrivate() {}
1178 class APT_HIDDEN BufferedWriteFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1180 FileFdPrivate
*wrapped
;
1181 simple_buffer writebuffer
;
1185 explicit BufferedWriteFileFdPrivate(FileFdPrivate
*Priv
) :
1186 FileFdPrivate(Priv
->filefd
), wrapped(Priv
) {};
1188 virtual APT::Configuration::Compressor
get_compressor() const override
1190 return wrapped
->get_compressor();
1192 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
) override
1194 return wrapped
->set_compressor(compressor
);
1196 virtual unsigned int get_openmode() const override
1198 return wrapped
->get_openmode();
1200 virtual void set_openmode(unsigned int openmode
) override
1202 return wrapped
->set_openmode(openmode
);
1204 virtual bool get_is_pipe() const override
1206 return wrapped
->get_is_pipe();
1208 virtual void set_is_pipe(bool is_pipe
) override
1210 FileFdPrivate::set_is_pipe(is_pipe
);
1211 wrapped
->set_is_pipe(is_pipe
);
1213 virtual unsigned long long get_seekpos() const override
1215 return wrapped
->get_seekpos();
1217 virtual void set_seekpos(unsigned long long seekpos
) override
1219 return wrapped
->set_seekpos(seekpos
);
1221 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1223 if (InternalFlush() == false)
1225 return wrapped
->InternalOpen(iFd
, Mode
);
1227 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1229 if (InternalFlush() == false)
1231 return wrapped
->InternalUnbufferedRead(To
, Size
);
1234 virtual bool InternalReadError() override
1236 return wrapped
->InternalReadError();
1238 virtual char * InternalReadLine(char * To
, unsigned long long Size
) override
1240 if (InternalFlush() == false)
1242 return wrapped
->InternalReadLine(To
, Size
);
1244 virtual bool InternalFlush() override
1246 while (writebuffer
.empty() == false) {
1247 auto written
= wrapped
->InternalWrite(writebuffer
.get(),
1248 writebuffer
.size());
1249 // Ignore interrupted syscalls
1250 if (written
< 0 && errno
== EINTR
)
1255 writebuffer
.bufferstart
+= written
;
1258 writebuffer
.reset();
1261 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1263 auto written
= writebuffer
.write(From
, Size
);
1265 if (writebuffer
.full() && InternalFlush() == false)
1270 virtual bool InternalWriteError()
1272 return wrapped
->InternalWriteError();
1274 virtual bool InternalSeek(unsigned long long const To
)
1276 if (InternalFlush() == false)
1278 return wrapped
->InternalSeek(To
);
1280 virtual bool InternalSkip(unsigned long long Over
)
1282 if (InternalFlush() == false)
1284 return wrapped
->InternalSkip(Over
);
1286 virtual bool InternalTruncate(unsigned long long const Size
)
1288 if (InternalFlush() == false)
1290 return wrapped
->InternalTruncate(Size
);
1292 virtual unsigned long long InternalTell()
1294 if (InternalFlush() == false)
1296 return wrapped
->InternalTell();
1298 virtual unsigned long long InternalSize()
1300 if (InternalFlush() == false)
1302 return wrapped
->InternalSize();
1304 virtual bool InternalClose(std::string
const &FileName
)
1306 return wrapped
->InternalClose(FileName
);
1308 virtual bool InternalAlwaysAutoClose() const
1310 return wrapped
->InternalAlwaysAutoClose();
1312 virtual ~BufferedWriteFileFdPrivate()
1318 class APT_HIDDEN GzipFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1322 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1324 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1325 gz
= gzdopen(iFd
, "r+");
1326 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1327 gz
= gzdopen(iFd
, "w");
1329 gz
= gzdopen(iFd
, "r");
1330 filefd
->Flags
|= FileFd::Compressed
;
1331 return gz
!= nullptr;
1333 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1335 return gzread(gz
, To
, Size
);
1337 virtual bool InternalReadError() override
1340 char const * const errmsg
= gzerror(gz
, &err
);
1342 return filefd
->FileFdError("gzread: %s (%d: %s)", _("Read error"), err
, errmsg
);
1343 return FileFdPrivate::InternalReadError();
1345 virtual char * InternalReadLine(char * To
, unsigned long long Size
) override
1347 return gzgets(gz
, To
, Size
);
1349 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1351 return gzwrite(gz
,From
,Size
);
1353 virtual bool InternalWriteError() override
1356 char const * const errmsg
= gzerror(gz
, &err
);
1358 return filefd
->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err
, errmsg
);
1359 return FileFdPrivate::InternalWriteError();
1361 virtual bool InternalSeek(unsigned long long const To
) override
1363 off_t
const res
= gzseek(gz
, To
, SEEK_SET
);
1364 if (res
!= (off_t
)To
)
1365 return filefd
->FileFdError("Unable to seek to %llu", To
);
1370 virtual bool InternalSkip(unsigned long long Over
) override
1372 if (Over
>= buffer
.size())
1374 Over
-= buffer
.size();
1379 buffer
.bufferstart
+= Over
;
1384 off_t
const res
= gzseek(gz
, Over
, SEEK_CUR
);
1386 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1390 virtual unsigned long long InternalTell() override
1392 return gztell(gz
) - buffer
.size();
1394 virtual unsigned long long InternalSize() override
1396 unsigned long long filesize
= FileFdPrivate::InternalSize();
1397 // only check gzsize if we are actually a gzip file, just checking for
1398 // "gz" is not sufficient as uncompressed files could be opened with
1399 // gzopen in "direct" mode as well
1400 if (filesize
== 0 || gzdirect(gz
))
1403 off_t
const oldPos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
1404 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
1405 * this ourselves; the original (uncompressed) file size is the last 32
1406 * bits of the file */
1407 // FIXME: Size for gz-files is limited by 32bit… no largefile support
1408 if (lseek(filefd
->iFd
, -4, SEEK_END
) < 0)
1410 filefd
->FileFdErrno("lseek","Unable to seek to end of gzipped file");
1414 if (read(filefd
->iFd
, &size
, 4) != 4)
1416 filefd
->FileFdErrno("read","Unable to read original size of gzipped file");
1419 size
= le32toh(size
);
1421 if (lseek(filefd
->iFd
, oldPos
, SEEK_SET
) < 0)
1423 filefd
->FileFdErrno("lseek","Unable to seek in gzipped file");
1428 virtual bool InternalClose(std::string
const &FileName
) override
1432 int const e
= gzclose(gz
);
1434 // gzdclose() on empty files always fails with "buffer error" here, ignore that
1435 if (e
!= 0 && e
!= Z_BUF_ERROR
)
1436 return _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
1440 explicit GzipFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), gz(nullptr) {}
1441 virtual ~GzipFileFdPrivate() { InternalClose(""); }
1445 class APT_HIDDEN Bz2FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1449 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1451 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1452 bz2
= BZ2_bzdopen(iFd
, "r+");
1453 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1454 bz2
= BZ2_bzdopen(iFd
, "w");
1456 bz2
= BZ2_bzdopen(iFd
, "r");
1457 filefd
->Flags
|= FileFd::Compressed
;
1458 return bz2
!= nullptr;
1460 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1462 return BZ2_bzread(bz2
, To
, Size
);
1464 virtual bool InternalReadError() override
1467 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1468 if (err
!= BZ_IO_ERROR
)
1469 return filefd
->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Read error"), err
, errmsg
);
1470 return FileFdPrivate::InternalReadError();
1472 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1474 return BZ2_bzwrite(bz2
, (void*)From
, Size
);
1476 virtual bool InternalWriteError() override
1479 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1480 if (err
!= BZ_IO_ERROR
)
1481 return filefd
->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Write error"), err
, errmsg
);
1482 return FileFdPrivate::InternalWriteError();
1484 virtual bool InternalStream() const override
{ return true; }
1485 virtual bool InternalClose(std::string
const &) override
1494 explicit Bz2FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), bz2(nullptr) {}
1495 virtual ~Bz2FileFdPrivate() { InternalClose(""); }
1499 class APT_HIDDEN Lz4FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1500 static constexpr unsigned long long LZ4_HEADER_SIZE
= 19;
1501 static constexpr unsigned long long LZ4_FOOTER_SIZE
= 4;
1503 LZ4F_decompressionContext_t dctx
;
1504 LZ4F_compressionContext_t cctx
;
1505 LZ4F_errorCode_t res
;
1507 simple_buffer lz4_buffer
;
1508 // Count of bytes that the decompressor expects to read next, or buffer size.
1509 size_t next_to_load
= APT_BUFFER_SIZE
;
1511 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1513 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1514 return _error
->Error("lz4 only supports write or read mode");
1516 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
) {
1517 res
= LZ4F_createCompressionContext(&cctx
, LZ4F_VERSION
);
1518 lz4_buffer
.reset(LZ4F_compressBound(APT_BUFFER_SIZE
, nullptr)
1519 + LZ4_HEADER_SIZE
+ LZ4_FOOTER_SIZE
);
1521 res
= LZ4F_createDecompressionContext(&dctx
, LZ4F_VERSION
);
1522 lz4_buffer
.reset(APT_BUFFER_SIZE
);
1525 filefd
->Flags
|= FileFd::Compressed
;
1527 if (LZ4F_isError(res
))
1530 unsigned int flags
= (Mode
& (FileFd::WriteOnly
|FileFd::ReadOnly
));
1531 if (backend
.OpenDescriptor(iFd
, flags
) == false)
1534 // Write the file header
1535 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1537 res
= LZ4F_compressBegin(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1538 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1544 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1546 /* Keep reading as long as the compressor still wants to read */
1547 while (next_to_load
) {
1548 // Fill compressed buffer;
1549 if (lz4_buffer
.empty()) {
1550 unsigned long long read
;
1551 /* Reset - if LZ4 decompressor wants to read more, allocate more */
1552 lz4_buffer
.reset(next_to_load
);
1553 if (backend
.Read(lz4_buffer
.getend(), lz4_buffer
.free(), &read
) == false)
1555 lz4_buffer
.bufferend
+= read
;
1560 return filefd
->FileFdError("LZ4F: %s %s",
1561 filefd
->FileName
.c_str(),
1562 _("Unexpected end of file")), -1;
1565 // Drain compressed buffer as far as possible.
1566 size_t in
= lz4_buffer
.size();
1569 res
= LZ4F_decompress(dctx
, To
, &out
, lz4_buffer
.get(), &in
, nullptr);
1570 if (LZ4F_isError(res
))
1574 lz4_buffer
.bufferstart
+= in
;
1582 virtual bool InternalReadError() override
1584 char const * const errmsg
= LZ4F_getErrorName(res
);
1586 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Read error"), res
, errmsg
);
1588 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1590 unsigned long long const towrite
= std::min(APT_BUFFER_SIZE
, Size
);
1592 res
= LZ4F_compressUpdate(cctx
,
1593 lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
,
1594 From
, towrite
, nullptr);
1596 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1601 virtual bool InternalWriteError() override
1603 char const * const errmsg
= LZ4F_getErrorName(res
);
1605 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Write error"), res
, errmsg
);
1607 virtual bool InternalStream() const override
{ return true; }
1609 virtual bool InternalFlush() override
1611 return backend
.Flush();
1614 virtual bool InternalClose(std::string
const &) override
1616 /* Reset variables */
1618 next_to_load
= APT_BUFFER_SIZE
;
1620 if (cctx
!= nullptr)
1622 res
= LZ4F_compressEnd(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1623 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1625 if (!backend
.Flush())
1627 if (!backend
.Close())
1630 res
= LZ4F_freeCompressionContext(cctx
);
1634 if (dctx
!= nullptr)
1636 res
= LZ4F_freeDecompressionContext(dctx
);
1640 return LZ4F_isError(res
) == false;
1643 explicit Lz4FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), dctx(nullptr), cctx(nullptr) {}
1644 virtual ~Lz4FileFdPrivate() {
1650 class APT_HIDDEN LzmaFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1654 uint8_t buffer
[4096];
1660 LZMAFILE() : file(nullptr), eof(false), compressing(false) { buffer
[0] = '\0'; }
1663 if (compressing
== true)
1665 size_t constexpr buffersize
= sizeof(buffer
)/sizeof(buffer
[0]);
1668 stream
.avail_out
= buffersize
;
1669 stream
.next_out
= buffer
;
1670 err
= lzma_code(&stream
, LZMA_FINISH
);
1671 if (err
!= LZMA_OK
&& err
!= LZMA_STREAM_END
)
1673 _error
->Error("~LZMAFILE: Compress finalisation failed");
1676 size_t const n
= buffersize
- stream
.avail_out
;
1677 if (n
&& fwrite(buffer
, 1, n
, file
) != n
)
1679 _error
->Errno("~LZMAFILE",_("Write error"));
1682 if (err
== LZMA_STREAM_END
)
1691 static uint32_t findXZlevel(std::vector
<std::string
> const &Args
)
1693 for (auto a
= Args
.rbegin(); a
!= Args
.rend(); ++a
)
1694 if (a
->empty() == false && (*a
)[0] == '-' && (*a
)[1] != '-')
1696 auto const number
= a
->find_last_of("0123456789");
1697 if (number
== std::string::npos
)
1699 auto const extreme
= a
->find("e", number
);
1700 uint32_t level
= (extreme
!= std::string::npos
) ? LZMA_PRESET_EXTREME
: 0;
1701 switch ((*a
)[number
])
1703 case '0': return level
| 0;
1704 case '1': return level
| 1;
1705 case '2': return level
| 2;
1706 case '3': return level
| 3;
1707 case '4': return level
| 4;
1708 case '5': return level
| 5;
1709 case '6': return level
| 6;
1710 case '7': return level
| 7;
1711 case '8': return level
| 8;
1712 case '9': return level
| 9;
1718 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) override
1720 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1721 return filefd
->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd
->FileName
.c_str());
1723 if (lzma
== nullptr)
1724 lzma
= new LzmaFileFdPrivate::LZMAFILE
;
1725 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1726 lzma
->file
= fdopen(iFd
, "w");
1728 lzma
->file
= fdopen(iFd
, "r");
1729 filefd
->Flags
|= FileFd::Compressed
;
1730 if (lzma
->file
== nullptr)
1733 lzma_stream tmp_stream
= LZMA_STREAM_INIT
;
1734 lzma
->stream
= tmp_stream
;
1736 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1738 uint32_t const xzlevel
= findXZlevel(compressor
.CompressArgs
);
1739 if (compressor
.Name
== "xz")
1741 if (lzma_easy_encoder(&lzma
->stream
, xzlevel
, LZMA_CHECK_CRC64
) != LZMA_OK
)
1746 lzma_options_lzma options
;
1747 lzma_lzma_preset(&options
, xzlevel
);
1748 if (lzma_alone_encoder(&lzma
->stream
, &options
) != LZMA_OK
)
1751 lzma
->compressing
= true;
1755 uint64_t const memlimit
= UINT64_MAX
;
1756 if (compressor
.Name
== "xz")
1758 if (lzma_auto_decoder(&lzma
->stream
, memlimit
, 0) != LZMA_OK
)
1763 if (lzma_alone_decoder(&lzma
->stream
, memlimit
) != LZMA_OK
)
1766 lzma
->compressing
= false;
1770 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1773 if (lzma
->eof
== true)
1776 lzma
->stream
.next_out
= (uint8_t *) To
;
1777 lzma
->stream
.avail_out
= Size
;
1778 if (lzma
->stream
.avail_in
== 0)
1780 lzma
->stream
.next_in
= lzma
->buffer
;
1781 lzma
->stream
.avail_in
= fread(lzma
->buffer
, 1, sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]), lzma
->file
);
1783 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1784 if (lzma
->err
== LZMA_STREAM_END
)
1787 Res
= Size
- lzma
->stream
.avail_out
;
1789 else if (lzma
->err
!= LZMA_OK
)
1796 Res
= Size
- lzma
->stream
.avail_out
;
1799 // lzma run was okay, but produced no output…
1806 virtual bool InternalReadError() override
1808 return filefd
->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma
->err
);
1810 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1812 lzma
->stream
.next_in
= (uint8_t *)From
;
1813 lzma
->stream
.avail_in
= Size
;
1814 lzma
->stream
.next_out
= lzma
->buffer
;
1815 lzma
->stream
.avail_out
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]);
1816 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1817 if (lzma
->err
!= LZMA_OK
)
1819 size_t const n
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]) - lzma
->stream
.avail_out
;
1820 size_t const m
= (n
== 0) ? 0 : fwrite(lzma
->buffer
, 1, n
, lzma
->file
);
1824 return Size
- lzma
->stream
.avail_in
;
1826 virtual bool InternalWriteError() override
1828 return filefd
->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma
->err
);
1830 virtual bool InternalStream() const override
{ return true; }
1831 virtual bool InternalClose(std::string
const &) override
1838 explicit LzmaFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), lzma(nullptr) {}
1839 virtual ~LzmaFileFdPrivate() { InternalClose(""); }
1843 class APT_HIDDEN PipedFileFdPrivate
: public FileFdPrivate
/*{{{*/
1844 /* if we don't have a specific class dealing with library calls, we (un)compress
1845 by executing a specified binary and pipe in/out what we need */
1848 virtual bool InternalOpen(int const, unsigned int const Mode
) override
1850 // collect zombies here in case we reopen
1851 if (compressor_pid
> 0)
1852 ExecWait(compressor_pid
, "FileFdCompressor", true);
1854 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1855 return filefd
->FileFdError("ReadWrite mode is not supported for file %s", filefd
->FileName
.c_str());
1857 bool const Comp
= (Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
;
1860 // Handle 'decompression' of empty files
1862 fstat(filefd
->iFd
, &Buf
);
1863 if (Buf
.st_size
== 0 && S_ISFIFO(Buf
.st_mode
) == false)
1866 // We don't need the file open - instead let the compressor open it
1867 // as he properly knows better how to efficiently read from 'his' file
1868 if (filefd
->FileName
.empty() == false)
1875 // Create a data pipe
1876 int Pipe
[2] = {-1,-1};
1877 if (pipe(Pipe
) != 0)
1878 return filefd
->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
1879 for (int J
= 0; J
!= 2; J
++)
1880 SetCloseExec(Pipe
[J
],true);
1882 compressed_fd
= filefd
->iFd
;
1886 filefd
->iFd
= Pipe
[1];
1888 filefd
->iFd
= Pipe
[0];
1891 compressor_pid
= ExecFork();
1892 if (compressor_pid
== 0)
1896 dup2(compressed_fd
,STDOUT_FILENO
);
1897 dup2(Pipe
[0],STDIN_FILENO
);
1901 if (compressed_fd
!= -1)
1902 dup2(compressed_fd
,STDIN_FILENO
);
1903 dup2(Pipe
[1],STDOUT_FILENO
);
1905 int const nullfd
= open("/dev/null", O_WRONLY
);
1908 dup2(nullfd
,STDERR_FILENO
);
1912 SetCloseExec(STDOUT_FILENO
,false);
1913 SetCloseExec(STDIN_FILENO
,false);
1915 std::vector
<char const*> Args
;
1916 Args
.push_back(compressor
.Binary
.c_str());
1917 std::vector
<std::string
> const * const addArgs
=
1918 (Comp
== true) ? &(compressor
.CompressArgs
) : &(compressor
.UncompressArgs
);
1919 for (std::vector
<std::string
>::const_iterator a
= addArgs
->begin();
1920 a
!= addArgs
->end(); ++a
)
1921 Args
.push_back(a
->c_str());
1922 if (Comp
== false && filefd
->FileName
.empty() == false)
1924 // commands not needing arguments, do not need to be told about using standard output
1925 // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
1926 if (compressor
.CompressArgs
.empty() == false && compressor
.UncompressArgs
.empty() == false)
1927 Args
.push_back("--stdout");
1928 if (filefd
->TemporaryFileName
.empty() == false)
1929 Args
.push_back(filefd
->TemporaryFileName
.c_str());
1931 Args
.push_back(filefd
->FileName
.c_str());
1933 Args
.push_back(NULL
);
1935 execvp(Args
[0],(char **)&Args
[0]);
1936 cerr
<< _("Failed to exec compressor ") << Args
[0] << endl
;
1946 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1948 return read(filefd
->iFd
, To
, Size
);
1950 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1952 return write(filefd
->iFd
, From
, Size
);
1954 virtual bool InternalClose(std::string
const &) override
1957 if (compressor_pid
> 0)
1958 Ret
&= ExecWait(compressor_pid
, "FileFdCompressor", true);
1959 compressor_pid
= -1;
1962 explicit PipedFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
1963 virtual ~PipedFileFdPrivate() { InternalClose(""); }
1966 class APT_HIDDEN DirectFileFdPrivate
: public FileFdPrivate
/*{{{*/
1969 virtual bool InternalOpen(int const, unsigned int const) override
{ return true; }
1970 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) override
1972 return read(filefd
->iFd
, To
, Size
);
1974 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) override
1976 // files opened read+write are strange and only really "supported" for direct files
1977 if (buffer
.size() != 0)
1979 lseek(filefd
->iFd
, -buffer
.size(), SEEK_CUR
);
1982 return write(filefd
->iFd
, From
, Size
);
1984 virtual bool InternalSeek(unsigned long long const To
) override
1986 off_t
const res
= lseek(filefd
->iFd
, To
, SEEK_SET
);
1987 if (res
!= (off_t
)To
)
1988 return filefd
->FileFdError("Unable to seek to %llu", To
);
1993 virtual bool InternalSkip(unsigned long long Over
) override
1995 if (Over
>= buffer
.size())
1997 Over
-= buffer
.size();
2002 buffer
.bufferstart
+= Over
;
2007 off_t
const res
= lseek(filefd
->iFd
, Over
, SEEK_CUR
);
2009 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
2013 virtual bool InternalTruncate(unsigned long long const To
) override
2015 if (buffer
.size() != 0)
2017 unsigned long long const seekpos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
2018 if ((seekpos
- buffer
.size()) >= To
)
2020 else if (seekpos
>= To
)
2021 buffer
.bufferend
= (To
- seekpos
) + buffer
.bufferstart
;
2025 if (ftruncate(filefd
->iFd
, To
) != 0)
2026 return filefd
->FileFdError("Unable to truncate to %llu",To
);
2029 virtual unsigned long long InternalTell() override
2031 return lseek(filefd
->iFd
,0,SEEK_CUR
) - buffer
.size();
2033 virtual unsigned long long InternalSize() override
2035 return filefd
->FileSize();
2037 virtual bool InternalClose(std::string
const &) override
{ return true; }
2038 virtual bool InternalAlwaysAutoClose() const override
{ return false; }
2040 explicit DirectFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
2041 virtual ~DirectFileFdPrivate() { InternalClose(""); }
2044 // FileFd Constructors /*{{{*/
2045 FileFd::FileFd(std::string FileName
,unsigned int const Mode
,unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2047 Open(FileName
,Mode
, None
, AccessMode
);
2049 FileFd::FileFd(std::string FileName
,unsigned int const Mode
, CompressMode Compress
, unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2051 Open(FileName
,Mode
, Compress
, AccessMode
);
2053 FileFd::FileFd() : iFd(-1), Flags(AutoClose
), d(NULL
) {}
2054 FileFd::FileFd(int const Fd
, unsigned int const Mode
, CompressMode Compress
) : iFd(-1), Flags(0), d(NULL
)
2056 OpenDescriptor(Fd
, Mode
, Compress
);
2058 FileFd::FileFd(int const Fd
, bool const AutoClose
) : iFd(-1), Flags(0), d(NULL
)
2060 OpenDescriptor(Fd
, ReadWrite
, None
, AutoClose
);
2063 // FileFd::Open - Open a file /*{{{*/
2064 // ---------------------------------------------------------------------
2065 /* The most commonly used open mode combinations are given with Mode */
2066 bool FileFd::Open(string FileName
,unsigned int const Mode
,CompressMode Compress
, unsigned long const AccessMode
)
2068 if (Mode
== ReadOnlyGzip
)
2069 return Open(FileName
, ReadOnly
, Gzip
, AccessMode
);
2071 if (Compress
== Auto
&& (Mode
& WriteOnly
) == WriteOnly
)
2072 return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName
.c_str());
2074 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2075 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2076 if (Compress
== Auto
)
2078 for (; compressor
!= compressors
.end(); ++compressor
)
2080 std::string file
= FileName
+ compressor
->Extension
;
2081 if (FileExists(file
) == false)
2087 else if (Compress
== Extension
)
2089 std::string::size_type
const found
= FileName
.find_last_of('.');
2091 if (found
!= std::string::npos
)
2093 ext
= FileName
.substr(found
);
2094 if (ext
== ".new" || ext
== ".bak")
2096 std::string::size_type
const found2
= FileName
.find_last_of('.', found
- 1);
2097 if (found2
!= std::string::npos
)
2098 ext
= FileName
.substr(found2
, found
- found2
);
2103 for (; compressor
!= compressors
.end(); ++compressor
)
2104 if (ext
== compressor
->Extension
)
2106 // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
2107 if (compressor
== compressors
.end())
2108 for (compressor
= compressors
.begin(); compressor
!= compressors
.end(); ++compressor
)
2109 if (compressor
->Name
== ".")
2117 case None
: name
= "."; break;
2118 case Gzip
: name
= "gzip"; break;
2119 case Bzip2
: name
= "bzip2"; break;
2120 case Lzma
: name
= "lzma"; break;
2121 case Xz
: name
= "xz"; break;
2122 case Lz4
: name
= "lz4"; break;
2126 return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName
.c_str());
2128 for (; compressor
!= compressors
.end(); ++compressor
)
2129 if (compressor
->Name
== name
)
2131 if (compressor
== compressors
.end())
2132 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2135 if (compressor
== compressors
.end())
2136 return FileFdError("Can't find a match for specified compressor mode for file %s", FileName
.c_str());
2137 return Open(FileName
, Mode
, *compressor
, AccessMode
);
2139 bool FileFd::Open(string FileName
,unsigned int const Mode
,APT::Configuration::Compressor
const &compressor
, unsigned long const AccessMode
)
2144 if ((Mode
& WriteOnly
) != WriteOnly
&& (Mode
& (Atomic
| Create
| Empty
| Exclusive
)) != 0)
2145 return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName
.c_str());
2146 if ((Mode
& ReadWrite
) == 0)
2147 return FileFdError("No openmode provided in FileFd::Open for %s", FileName
.c_str());
2149 unsigned int OpenMode
= Mode
;
2150 if (FileName
== "/dev/null")
2151 OpenMode
= OpenMode
& ~(Atomic
| Exclusive
| Create
| Empty
);
2153 if ((OpenMode
& Atomic
) == Atomic
)
2157 else if ((OpenMode
& (Exclusive
| Create
)) == (Exclusive
| Create
))
2159 // for atomic, this will be done by rename in Close()
2160 RemoveFile("FileFd::Open", FileName
);
2162 if ((OpenMode
& Empty
) == Empty
)
2165 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
2166 RemoveFile("FileFd::Open", FileName
);
2170 #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
2171 if_FLAGGED_SET(ReadWrite
, O_RDWR
);
2172 else if_FLAGGED_SET(ReadOnly
, O_RDONLY
);
2173 else if_FLAGGED_SET(WriteOnly
, O_WRONLY
);
2175 if_FLAGGED_SET(Create
, O_CREAT
);
2176 if_FLAGGED_SET(Empty
, O_TRUNC
);
2177 if_FLAGGED_SET(Exclusive
, O_EXCL
);
2178 #undef if_FLAGGED_SET
2180 if ((OpenMode
& Atomic
) == Atomic
)
2182 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
2184 if((iFd
= mkstemp(name
)) == -1)
2187 return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName
.c_str());
2190 TemporaryFileName
= string(name
);
2193 // umask() will always set the umask and return the previous value, so
2194 // we first set the umask and then reset it to the old value
2195 mode_t
const CurrentUmask
= umask(0);
2196 umask(CurrentUmask
);
2197 // calculate the actual file permissions (just like open/creat)
2198 mode_t
const FilePermissions
= (AccessMode
& ~CurrentUmask
);
2200 if(fchmod(iFd
, FilePermissions
) == -1)
2201 return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName
.c_str());
2204 iFd
= open(FileName
.c_str(), fileflags
, AccessMode
);
2206 this->FileName
= FileName
;
2207 if (iFd
== -1 || OpenInternDescriptor(OpenMode
, compressor
) == false)
2214 return FileFdErrno("open",_("Could not open file %s"), FileName
.c_str());
2217 SetCloseExec(iFd
,true);
2221 // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
2222 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, CompressMode Compress
, bool AutoClose
)
2224 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2225 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2228 // compat with the old API
2229 if (Mode
== ReadOnlyGzip
&& Compress
== None
)
2234 case None
: name
= "."; break;
2235 case Gzip
: name
= "gzip"; break;
2236 case Bzip2
: name
= "bzip2"; break;
2237 case Lzma
: name
= "lzma"; break;
2238 case Xz
: name
= "xz"; break;
2239 case Lz4
: name
= "lz4"; break;
2242 if (AutoClose
== true && Fd
!= -1)
2244 return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd
);
2246 for (; compressor
!= compressors
.end(); ++compressor
)
2247 if (compressor
->Name
== name
)
2249 if (compressor
== compressors
.end())
2251 if (AutoClose
== true && Fd
!= -1)
2253 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2255 return OpenDescriptor(Fd
, Mode
, *compressor
, AutoClose
);
2257 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
, bool AutoClose
)
2260 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
2262 this->FileName
= "";
2263 if (OpenInternDescriptor(Mode
, compressor
) == false)
2266 (Flags
& Compressed
) == Compressed
||
2272 return FileFdError(_("Could not open file descriptor %d"), Fd
);
2276 bool FileFd::OpenInternDescriptor(unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
)
2282 d
->InternalClose(FileName
);
2287 /* dummy so that the rest can be 'else if's */;
2288 #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
2289 else if (compressor.Name == NAME) \
2290 d = new CONSTRUCTOR(this)
2292 APT_COMPRESS_INIT("gzip", GzipFileFdPrivate
);
2295 APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate
);
2298 APT_COMPRESS_INIT("xz", LzmaFileFdPrivate
);
2299 APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate
);
2302 APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate
);
2304 #undef APT_COMPRESS_INIT
2305 else if (compressor
.Name
== "." || compressor
.Binary
.empty() == true)
2306 d
= new DirectFileFdPrivate(this);
2308 d
= new PipedFileFdPrivate(this);
2310 if (Mode
& BufferedWrite
)
2311 d
= new BufferedWriteFileFdPrivate(d
);
2313 d
->set_openmode(Mode
);
2314 d
->set_compressor(compressor
);
2315 if ((Flags
& AutoClose
) != AutoClose
&& d
->InternalAlwaysAutoClose())
2317 // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
2318 int const internFd
= dup(iFd
);
2320 return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd
);
2324 return d
->InternalOpen(iFd
, Mode
);
2327 // FileFd::~File - Closes the file /*{{{*/
2328 // ---------------------------------------------------------------------
2329 /* If the proper modes are selected then we close the Fd and possibly
2330 unlink the file on error. */
2335 d
->InternalClose(FileName
);
2340 // FileFd::Read - Read a bit of the file /*{{{*/
2341 // ---------------------------------------------------------------------
2342 /* We are careful to handle interruption by a signal while reading
2344 bool FileFd::Read(void *To
,unsigned long long Size
,unsigned long long *Actual
)
2352 *((char *)To
) = '\0';
2353 while (Res
> 0 && Size
> 0)
2355 Res
= d
->InternalRead(To
, Size
);
2361 // trick the while-loop into running again
2366 return d
->InternalReadError();
2369 To
= (char *)To
+ Res
;
2372 d
->set_seekpos(d
->get_seekpos() + Res
);
2387 return FileFdError(_("read, still have %llu to read but none left"), Size
);
2390 // FileFd::ReadLine - Read a complete line from the file /*{{{*/
2391 // ---------------------------------------------------------------------
2392 /* Beware: This method can be quite slow for big buffers on UNcompressed
2393 files because of the naive implementation! */
2394 char* FileFd::ReadLine(char *To
, unsigned long long const Size
)
2399 return d
->InternalReadLine(To
, Size
);
2402 // FileFd::Flush - Flush the file /*{{{*/
2403 bool FileFd::Flush()
2408 return d
->InternalFlush();
2411 // FileFd::Write - Write to the file /*{{{*/
2412 bool FileFd::Write(const void *From
,unsigned long long Size
)
2418 while (Res
> 0 && Size
> 0)
2420 Res
= d
->InternalWrite(From
, Size
);
2421 if (Res
< 0 && errno
== EINTR
)
2424 return d
->InternalWriteError();
2426 From
= (char const *)From
+ Res
;
2429 d
->set_seekpos(d
->get_seekpos() + Res
);
2435 return FileFdError(_("write, still have %llu to write but couldn't"), Size
);
2437 bool FileFd::Write(int Fd
, const void *From
, unsigned long long Size
)
2441 while (Res
> 0 && Size
> 0)
2443 Res
= write(Fd
,From
,Size
);
2444 if (Res
< 0 && errno
== EINTR
)
2447 return _error
->Errno("write",_("Write error"));
2449 From
= (char const *)From
+ Res
;
2456 return _error
->Error(_("write, still have %llu to write but couldn't"), Size
);
2459 // FileFd::Seek - Seek in the file /*{{{*/
2460 bool FileFd::Seek(unsigned long long To
)
2465 return d
->InternalSeek(To
);
2468 // FileFd::Skip - Skip over data in the file /*{{{*/
2469 bool FileFd::Skip(unsigned long long Over
)
2473 return d
->InternalSkip(Over
);
2476 // FileFd::Truncate - Truncate the file /*{{{*/
2477 bool FileFd::Truncate(unsigned long long To
)
2481 // truncating /dev/null is always successful - as we get an error otherwise
2482 if (To
== 0 && FileName
== "/dev/null")
2484 return d
->InternalTruncate(To
);
2487 // FileFd::Tell - Current seek position /*{{{*/
2488 // ---------------------------------------------------------------------
2490 unsigned long long FileFd::Tell()
2494 off_t
const Res
= d
->InternalTell();
2495 if (Res
== (off_t
)-1)
2496 FileFdErrno("lseek","Failed to determine the current file position");
2497 d
->set_seekpos(Res
);
2501 static bool StatFileFd(char const * const msg
, int const iFd
, std::string
const &FileName
, struct stat
&Buf
, FileFdPrivate
* const d
) /*{{{*/
2503 bool ispipe
= (d
!= NULL
&& d
->get_is_pipe() == true);
2504 if (ispipe
== false)
2506 if (fstat(iFd
,&Buf
) != 0)
2507 // higher-level code will generate more meaningful messages,
2508 // even translated this would be meaningless for users
2509 return _error
->Errno("fstat", "Unable to determine %s for fd %i", msg
, iFd
);
2510 if (FileName
.empty() == false)
2511 ispipe
= S_ISFIFO(Buf
.st_mode
);
2514 // for compressor pipes st_size is undefined and at 'best' zero
2517 // we set it here, too, as we get the info here for free
2518 // in theory the Open-methods should take care of it already
2520 d
->set_is_pipe(true);
2521 if (stat(FileName
.c_str(), &Buf
) != 0)
2522 return _error
->Errno("fstat", "Unable to determine %s for file %s", msg
, FileName
.c_str());
2527 // FileFd::FileSize - Return the size of the file /*{{{*/
2528 unsigned long long FileFd::FileSize()
2531 if (StatFileFd("file size", iFd
, FileName
, Buf
, d
) == false)
2539 // FileFd::ModificationTime - Return the time of last touch /*{{{*/
2540 time_t FileFd::ModificationTime()
2543 if (StatFileFd("modification time", iFd
, FileName
, Buf
, d
) == false)
2548 return Buf
.st_mtime
;
2551 // FileFd::Size - Return the size of the content in the file /*{{{*/
2552 unsigned long long FileFd::Size()
2556 return d
->InternalSize();
2559 // FileFd::Close - Close the file if the close flag is set /*{{{*/
2560 // ---------------------------------------------------------------------
2562 bool FileFd::Close()
2564 if (Flush() == false)
2570 if ((Flags
& AutoClose
) == AutoClose
)
2572 if ((Flags
& Compressed
) != Compressed
&& iFd
> 0 && close(iFd
) != 0)
2573 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
2578 Res
&= d
->InternalClose(FileName
);
2583 if ((Flags
& Replace
) == Replace
) {
2584 if (rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
2585 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
2587 FileName
= TemporaryFileName
; // for the unlink() below.
2588 TemporaryFileName
.clear();
2593 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
2594 FileName
.empty() == false)
2595 Res
&= RemoveFile("FileFd::Close", FileName
);
2602 // FileFd::Sync - Sync the file /*{{{*/
2603 // ---------------------------------------------------------------------
2607 if (fsync(iFd
) != 0)
2608 return FileFdErrno("sync",_("Problem syncing the file"));
2612 // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
2613 bool FileFd::FileFdErrno(const char *Function
, const char *Description
,...)
2617 size_t msgSize
= 400;
2618 int const errsv
= errno
;
2621 va_start(args
,Description
);
2622 if (_error
->InsertErrno(GlobalError::ERROR
, Function
, Description
, args
, errsv
, msgSize
) == false)
2629 // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
2630 bool FileFd::FileFdError(const char *Description
,...) {
2633 size_t msgSize
= 400;
2636 va_start(args
,Description
);
2637 if (_error
->Insert(GlobalError::ERROR
, Description
, args
, msgSize
) == false)
2644 gzFile
FileFd::gzFd() { /*{{{*/
2646 GzipFileFdPrivate
* const gzipd
= dynamic_cast<GzipFileFdPrivate
*>(d
);
2647 if (gzipd
== nullptr)
2657 // Glob - wrapper around "glob()" /*{{{*/
2658 std::vector
<std::string
> Glob(std::string
const &pattern
, int flags
)
2660 std::vector
<std::string
> result
;
2665 glob_res
= glob(pattern
.c_str(), flags
, NULL
, &globbuf
);
2669 if(glob_res
!= GLOB_NOMATCH
) {
2670 _error
->Errno("glob", "Problem with glob");
2676 for(i
=0;i
<globbuf
.gl_pathc
;i
++)
2677 result
.push_back(string(globbuf
.gl_pathv
[i
]));
2683 std::string
GetTempDir() /*{{{*/
2685 const char *tmpdir
= getenv("TMPDIR");
2693 if (!tmpdir
|| strlen(tmpdir
) == 0 || // tmpdir is set
2694 stat(tmpdir
, &st
) != 0 || (st
.st_mode
& S_IFDIR
) == 0) // exists and is directory
2696 else if (geteuid() != 0 && // root can do everything anyway
2697 faccessat(-1, tmpdir
, R_OK
| W_OK
| X_OK
, AT_EACCESS
| AT_SYMLINK_NOFOLLOW
) != 0) // current user has rwx access to directory
2700 return string(tmpdir
);
2702 std::string
GetTempDir(std::string
const &User
)
2704 // no need/possibility to drop privs
2705 if(getuid() != 0 || User
.empty() || User
== "root")
2706 return GetTempDir();
2708 struct passwd
const * const pw
= getpwnam(User
.c_str());
2710 return GetTempDir();
2712 gid_t
const old_euid
= geteuid();
2713 gid_t
const old_egid
= getegid();
2714 if (setegid(pw
->pw_gid
) != 0)
2715 _error
->Errno("setegid", "setegid %u failed", pw
->pw_gid
);
2716 if (seteuid(pw
->pw_uid
) != 0)
2717 _error
->Errno("seteuid", "seteuid %u failed", pw
->pw_uid
);
2719 std::string
const tmp
= GetTempDir();
2721 if (seteuid(old_euid
) != 0)
2722 _error
->Errno("seteuid", "seteuid %u failed", old_euid
);
2723 if (setegid(old_egid
) != 0)
2724 _error
->Errno("setegid", "setegid %u failed", old_egid
);
2729 FileFd
* GetTempFile(std::string
const &Prefix
, bool ImmediateUnlink
, FileFd
* const TmpFd
) /*{{{*/
2732 FileFd
* const Fd
= TmpFd
== NULL
? new FileFd() : TmpFd
;
2734 std::string
const tempdir
= GetTempDir();
2735 snprintf(fn
, sizeof(fn
), "%s/%s.XXXXXX",
2736 tempdir
.c_str(), Prefix
.c_str());
2737 int const fd
= mkstemp(fn
);
2742 _error
->Errno("GetTempFile",_("Unable to mkstemp %s"), fn
);
2745 if (!Fd
->OpenDescriptor(fd
, FileFd::ReadWrite
, FileFd::None
, true))
2747 _error
->Errno("GetTempFile",_("Unable to write to %s"),fn
);
2753 bool Rename(std::string From
, std::string To
) /*{{{*/
2755 if (rename(From
.c_str(),To
.c_str()) != 0)
2757 _error
->Error(_("rename failed, %s (%s -> %s)."),strerror(errno
),
2758 From
.c_str(),To
.c_str());
2764 bool Popen(const char* Args
[], FileFd
&Fd
, pid_t
&Child
, FileFd::OpenMode Mode
)/*{{{*/
2767 if (Mode
!= FileFd::ReadOnly
&& Mode
!= FileFd::WriteOnly
)
2768 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2770 int Pipe
[2] = {-1, -1};
2772 return _error
->Errno("pipe", _("Failed to create subprocess IPC"));
2774 std::set
<int> keep_fds
;
2775 keep_fds
.insert(Pipe
[0]);
2776 keep_fds
.insert(Pipe
[1]);
2777 Child
= ExecFork(keep_fds
);
2779 return _error
->Errno("fork", "Failed to fork");
2782 if(Mode
== FileFd::ReadOnly
)
2787 else if(Mode
== FileFd::WriteOnly
)
2793 if(Mode
== FileFd::ReadOnly
)
2797 } else if(Mode
== FileFd::WriteOnly
)
2800 execv(Args
[0], (char**)Args
);
2803 if(Mode
== FileFd::ReadOnly
)
2808 else if(Mode
== FileFd::WriteOnly
)
2814 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2815 Fd
.OpenDescriptor(fd
, Mode
, FileFd::None
, true);
2820 bool DropPrivileges() /*{{{*/
2822 if(_config
->FindB("Debug::NoDropPrivs", false) == true)
2826 #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
2827 #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
2829 // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
2830 int ret
= prctl(38, 1, 0, 0, 0);
2831 // ignore EINVAL - kernel is too old to understand the option
2832 if(ret
< 0 && errno
!= EINVAL
)
2833 _error
->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret
);
2836 // empty setting disables privilege dropping - this also ensures
2837 // backward compatibility, see bug #764506
2838 const std::string toUser
= _config
->Find("APT::Sandbox::User");
2839 if (toUser
.empty() || toUser
== "root")
2842 // a lot can go wrong trying to drop privileges completely,
2843 // so ideally we would like to verify that we have done it –
2844 // but the verify asks for too much in case of fakeroot (and alike)
2845 // [Specific checks can be overridden with dedicated options]
2846 bool const VerifySandboxing
= _config
->FindB("APT::Sandbox::Verify", false);
2848 // uid will be 0 in the end, but gid might be different anyway
2849 uid_t
const old_uid
= getuid();
2850 gid_t
const old_gid
= getgid();
2855 struct passwd
*pw
= getpwnam(toUser
.c_str());
2857 return _error
->Error("No user %s, can not drop rights", toUser
.c_str());
2859 // Do not change the order here, it might break things
2860 // Get rid of all our supplementary groups first
2861 if (setgroups(1, &pw
->pw_gid
))
2862 return _error
->Errno("setgroups", "Failed to setgroups");
2864 // Now change the group ids to the new user
2865 #ifdef HAVE_SETRESGID
2866 if (setresgid(pw
->pw_gid
, pw
->pw_gid
, pw
->pw_gid
) != 0)
2867 return _error
->Errno("setresgid", "Failed to set new group ids");
2869 if (setegid(pw
->pw_gid
) != 0)
2870 return _error
->Errno("setegid", "Failed to setegid");
2872 if (setgid(pw
->pw_gid
) != 0)
2873 return _error
->Errno("setgid", "Failed to setgid");
2876 // Change the user ids to the new user
2877 #ifdef HAVE_SETRESUID
2878 if (setresuid(pw
->pw_uid
, pw
->pw_uid
, pw
->pw_uid
) != 0)
2879 return _error
->Errno("setresuid", "Failed to set new user ids");
2881 if (setuid(pw
->pw_uid
) != 0)
2882 return _error
->Errno("setuid", "Failed to setuid");
2883 if (seteuid(pw
->pw_uid
) != 0)
2884 return _error
->Errno("seteuid", "Failed to seteuid");
2887 // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
2888 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Groups", false) == true)
2890 // Verify that the user isn't still in any supplementary groups
2891 long const ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
2892 std::unique_ptr
<gid_t
[]> gidlist(new gid_t
[ngroups_max
]);
2893 if (unlikely(gidlist
== NULL
))
2894 return _error
->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max
);
2896 if ((gidlist_nr
= getgroups(ngroups_max
, gidlist
.get())) < 0)
2897 return _error
->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max
);
2898 for (ssize_t i
= 0; i
< gidlist_nr
; ++i
)
2899 if (gidlist
[i
] != pw
->pw_gid
)
2900 return _error
->Error("Could not switch group, user %s is still in group %d", toUser
.c_str(), gidlist
[i
]);
2903 // enabled by default as all fakeroot-lookalikes should fake that accordingly
2904 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::IDs", true) == true)
2906 // Verify that gid, egid, uid, and euid changed
2907 if (getgid() != pw
->pw_gid
)
2908 return _error
->Error("Could not switch group");
2909 if (getegid() != pw
->pw_gid
)
2910 return _error
->Error("Could not switch effective group");
2911 if (getuid() != pw
->pw_uid
)
2912 return _error
->Error("Could not switch user");
2913 if (geteuid() != pw
->pw_uid
)
2914 return _error
->Error("Could not switch effective user");
2916 #ifdef HAVE_GETRESUID
2917 // verify that the saved set-user-id was changed as well
2921 if (getresuid(&ruid
, &euid
, &suid
))
2922 return _error
->Errno("getresuid", "Could not get saved set-user-ID");
2923 if (suid
!= pw
->pw_uid
)
2924 return _error
->Error("Could not switch saved set-user-ID");
2927 #ifdef HAVE_GETRESGID
2928 // verify that the saved set-group-id was changed as well
2932 if (getresgid(&rgid
, &egid
, &sgid
))
2933 return _error
->Errno("getresuid", "Could not get saved set-group-ID");
2934 if (sgid
!= pw
->pw_gid
)
2935 return _error
->Error("Could not switch saved set-group-ID");
2939 // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
2940 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Regain", false) == true)
2942 // Check that uid and gid changes do not work anymore
2943 if (pw
->pw_gid
!= old_gid
&& (setgid(old_gid
) != -1 || setegid(old_gid
) != -1))
2944 return _error
->Error("Could restore a gid to root, privilege dropping did not work");
2946 if (pw
->pw_uid
!= old_uid
&& (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1))
2947 return _error
->Error("Could restore a uid to root, privilege dropping did not work");