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 std::string
flNormalize(std::string file
) /*{{{*/
701 // do some normalisation by removing // and /./ from the path
702 size_t found
= string::npos
;
703 while ((found
= file
.find("/./")) != string::npos
)
704 file
.replace(found
, 3, "/");
705 while ((found
= file
.find("//")) != string::npos
)
706 file
.replace(found
, 2, "/");
708 if (APT::String::Startswith(file
, "/dev/null"))
710 file
.erase(strlen("/dev/null"));
716 // SetCloseExec - Set the close on exec flag /*{{{*/
717 // ---------------------------------------------------------------------
719 void SetCloseExec(int Fd
,bool Close
)
721 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
723 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
728 // SetNonBlock - Set the nonblocking flag /*{{{*/
729 // ---------------------------------------------------------------------
731 void SetNonBlock(int Fd
,bool Block
)
733 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
734 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
736 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
741 // WaitFd - Wait for a FD to become readable /*{{{*/
742 // ---------------------------------------------------------------------
743 /* This waits for a FD to become readable using select. It is useful for
744 applications making use of non-blocking sockets. The timeout is
746 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
759 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
761 while (Res
< 0 && errno
== EINTR
);
771 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
773 while (Res
< 0 && errno
== EINTR
);
782 // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
783 // ---------------------------------------------------------------------
784 /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
787 void MergeKeepFdsFromConfiguration(std::set
<int> &KeepFDs
)
789 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
790 if (Opts
!= 0 && Opts
->Child
!= 0)
793 for (; Opts
!= 0; Opts
= Opts
->Next
)
795 if (Opts
->Value
.empty() == true)
797 int fd
= atoi(Opts
->Value
.c_str());
803 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
804 // ---------------------------------------------------------------------
805 /* This is used if you want to cleanse the environment for the forked
806 child, it fixes up the important signals and nukes all of the fds,
807 otherwise acts like normal fork. */
811 // we need to merge the Keep-Fds as external tools like
812 // debconf-apt-progress use it
813 MergeKeepFdsFromConfiguration(KeepFDs
);
814 return ExecFork(KeepFDs
);
817 pid_t
ExecFork(std::set
<int> KeepFDs
)
819 // Fork off the process
820 pid_t Process
= fork();
823 cerr
<< "FATAL -> Failed to fork." << endl
;
827 // Spawn the subprocess
831 signal(SIGPIPE
,SIG_DFL
);
832 signal(SIGQUIT
,SIG_DFL
);
833 signal(SIGINT
,SIG_DFL
);
834 signal(SIGWINCH
,SIG_DFL
);
835 signal(SIGCONT
,SIG_DFL
);
836 signal(SIGTSTP
,SIG_DFL
);
838 DIR *dir
= opendir("/proc/self/fd");
842 while ((ent
= readdir(dir
)))
844 int fd
= atoi(ent
->d_name
);
845 // If fd > 0, it was a fd number and not . or ..
846 if (fd
>= 3 && KeepFDs
.find(fd
) == KeepFDs
.end())
847 fcntl(fd
,F_SETFD
,FD_CLOEXEC
);
851 long ScOpenMax
= sysconf(_SC_OPEN_MAX
);
852 // Close all of our FDs - just in case
853 for (int K
= 3; K
!= ScOpenMax
; K
++)
855 if(KeepFDs
.find(K
) == KeepFDs
.end())
856 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
864 // ExecWait - Fancy waitpid /*{{{*/
865 // ---------------------------------------------------------------------
866 /* Waits for the given sub process. If Reap is set then no errors are
867 generated. Otherwise a failed subprocess will generate a proper descriptive
869 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
874 // Wait and collect the error code
876 while (waitpid(Pid
,&Status
,0) != Pid
)
884 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
888 // Check for an error code.
889 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
893 if (WIFSIGNALED(Status
) != 0)
895 if( WTERMSIG(Status
) == SIGSEGV
)
896 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
898 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
901 if (WIFEXITED(Status
) != 0)
902 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
904 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
910 // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
911 bool StartsWithGPGClearTextSignature(string
const &FileName
)
913 static const char* SIGMSG
= "-----BEGIN PGP SIGNED MESSAGE-----\n";
914 char buffer
[strlen(SIGMSG
)+1];
915 FILE* gpg
= fopen(FileName
.c_str(), "r");
919 char const * const test
= fgets(buffer
, sizeof(buffer
), gpg
);
921 if (test
== NULL
|| strcmp(buffer
, SIGMSG
) != 0)
927 // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
928 bool ChangeOwnerAndPermissionOfFile(char const * const requester
, char const * const file
, char const * const user
, char const * const group
, mode_t
const mode
)
930 if (strcmp(file
, "/dev/null") == 0)
933 if (getuid() == 0 && strlen(user
) != 0 && strlen(group
) != 0) // if we aren't root, we can't chown, so don't try it
935 // ensure the file is owned by root and has good permissions
936 struct passwd
const * const pw
= getpwnam(user
);
937 struct group
const * const gr
= getgrnam(group
);
938 if (pw
!= NULL
&& gr
!= NULL
&& lchown(file
, pw
->pw_uid
, gr
->gr_gid
) != 0)
939 Res
&= _error
->WarningE(requester
, "chown to %s:%s of file %s failed", user
, group
, file
);
942 if (lstat(file
, &Buf
) != 0 || S_ISLNK(Buf
.st_mode
))
944 if (chmod(file
, mode
) != 0)
945 Res
&= _error
->WarningE(requester
, "chmod 0%o of file %s failed", mode
, file
);
950 struct APT_HIDDEN simple_buffer
{ /*{{{*/
951 size_t buffersize_max
= 0;
952 unsigned long long bufferstart
= 0;
953 unsigned long long bufferend
= 0;
954 char *buffer
= nullptr;
963 const char *get() const { return buffer
+ bufferstart
; }
964 char *get() { return buffer
+ bufferstart
; }
965 const char *getend() const { return buffer
+ bufferend
; }
966 char *getend() { return buffer
+ bufferend
; }
967 bool empty() const { return bufferend
<= bufferstart
; }
968 bool full() const { return bufferend
== buffersize_max
; }
969 unsigned long long free() const { return buffersize_max
- bufferend
; }
970 unsigned long long size() const { return bufferend
-bufferstart
; }
971 void reset(size_t size
)
973 if (size
> buffersize_max
) {
975 buffersize_max
= size
;
976 buffer
= new char[size
];
980 void reset() { bufferend
= bufferstart
= 0; }
981 ssize_t
read(void *to
, unsigned long long requested_size
) APT_MUSTCHECK
983 if (size() < requested_size
)
984 requested_size
= size();
985 memcpy(to
, buffer
+ bufferstart
, requested_size
);
986 bufferstart
+= requested_size
;
987 if (bufferstart
== bufferend
)
988 bufferstart
= bufferend
= 0;
989 return requested_size
;
991 ssize_t
write(const void *from
, unsigned long long requested_size
) APT_MUSTCHECK
993 if (free() < requested_size
)
994 requested_size
= free();
995 memcpy(getend(), from
, requested_size
);
996 bufferend
+= requested_size
;
997 if (bufferstart
== bufferend
)
998 bufferstart
= bufferend
= 0;
999 return requested_size
;
1004 class APT_HIDDEN FileFdPrivate
{ /*{{{*/
1005 friend class BufferedWriteFileFdPrivate
;
1007 FileFd
* const filefd
;
1008 simple_buffer buffer
;
1010 pid_t compressor_pid
;
1012 APT::Configuration::Compressor compressor
;
1013 unsigned int openmode
;
1014 unsigned long long seekpos
;
1017 explicit FileFdPrivate(FileFd
* const pfilefd
) : filefd(pfilefd
),
1018 compressed_fd(-1), compressor_pid(-1), is_pipe(false),
1019 openmode(0), seekpos(0) {};
1020 virtual APT::Configuration::Compressor
get_compressor() const
1024 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
)
1026 this->compressor
= compressor
;
1028 virtual unsigned int get_openmode() const
1032 virtual void set_openmode(unsigned int openmode
)
1034 this->openmode
= openmode
;
1036 virtual bool get_is_pipe() const
1040 virtual void set_is_pipe(bool is_pipe
)
1042 this->is_pipe
= is_pipe
;
1044 virtual unsigned long long get_seekpos() const
1048 virtual void set_seekpos(unsigned long long seekpos
)
1050 this->seekpos
= seekpos
;
1053 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) = 0;
1054 ssize_t
InternalRead(void * To
, unsigned long long Size
)
1056 // Drain the buffer if needed.
1057 if (buffer
.empty() == false)
1059 return buffer
.read(To
, Size
);
1061 return InternalUnbufferedRead(To
, Size
);
1063 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) = 0;
1064 virtual bool InternalReadError() { return filefd
->FileFdErrno("read",_("Read error")); }
1065 virtual char * InternalReadLine(char * To
, unsigned long long Size
)
1067 if (unlikely(Size
== 0))
1069 // Read one byte less than buffer size to have space for trailing 0.
1072 char * const InitialTo
= To
;
1075 if (buffer
.empty() == true)
1078 unsigned long long actualread
= 0;
1079 if (filefd
->Read(buffer
.getend(), buffer
.free(), &actualread
) == false)
1081 buffer
.bufferend
= actualread
;
1082 if (buffer
.size() == 0)
1084 if (To
== InitialTo
)
1088 filefd
->Flags
&= ~FileFd::HitEof
;
1091 unsigned long long const OutputSize
= std::min(Size
, buffer
.size());
1092 char const * const newline
= static_cast<char const * const>(memchr(buffer
.get(), '\n', OutputSize
));
1093 // Read until end of line or up to Size bytes from the buffer.
1094 unsigned long long actualread
= buffer
.read(To
,
1095 (newline
!= nullptr)
1096 ? (newline
- buffer
.get()) + 1
1100 if (newline
!= nullptr)
1106 virtual bool InternalFlush()
1110 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) = 0;
1111 virtual bool InternalWriteError() { return filefd
->FileFdErrno("write",_("Write error")); }
1112 virtual bool InternalSeek(unsigned long long const To
)
1114 // Our poor man seeking is costly, so try to avoid it
1115 unsigned long long const iseekpos
= filefd
->Tell();
1118 else if (iseekpos
< To
)
1119 return filefd
->Skip(To
- iseekpos
);
1121 if ((openmode
& FileFd::ReadOnly
) != FileFd::ReadOnly
)
1122 return filefd
->FileFdError("Reopen is only implemented for read-only files!");
1123 InternalClose(filefd
->FileName
);
1124 if (filefd
->iFd
!= -1)
1127 if (filefd
->TemporaryFileName
.empty() == false)
1128 filefd
->iFd
= open(filefd
->TemporaryFileName
.c_str(), O_RDONLY
);
1129 else if (filefd
->FileName
.empty() == false)
1130 filefd
->iFd
= open(filefd
->FileName
.c_str(), O_RDONLY
);
1133 if (compressed_fd
> 0)
1134 if (lseek(compressed_fd
, 0, SEEK_SET
) != 0)
1135 filefd
->iFd
= compressed_fd
;
1136 if (filefd
->iFd
< 0)
1137 return filefd
->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
1140 if (filefd
->OpenInternDescriptor(openmode
, compressor
) == false)
1141 return filefd
->FileFdError("Seek on file %s because it couldn't be reopened", filefd
->FileName
.c_str());
1146 return filefd
->Skip(To
);
1151 virtual bool InternalSkip(unsigned long long Over
)
1153 unsigned long long constexpr buffersize
= 1024;
1154 char buffer
[buffersize
];
1157 unsigned long long toread
= std::min(buffersize
, Over
);
1158 if (filefd
->Read(buffer
, toread
) == false)
1159 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1164 virtual bool InternalTruncate(unsigned long long const)
1166 return filefd
->FileFdError("Truncating compressed files is not implemented (%s)", filefd
->FileName
.c_str());
1168 virtual unsigned long long InternalTell()
1170 // In theory, we could just return seekpos here always instead of
1171 // seeking around, but not all users of FileFd use always Seek() and co
1172 // so d->seekpos isn't always true and we can just use it as a hint if
1173 // we have nothing else, but not always as an authority…
1174 return seekpos
- buffer
.size();
1176 virtual unsigned long long InternalSize()
1178 unsigned long long size
= 0;
1179 unsigned long long const oldSeek
= filefd
->Tell();
1180 unsigned long long constexpr ignoresize
= 1024;
1181 char ignore
[ignoresize
];
1182 unsigned long long read
= 0;
1184 if (filefd
->Read(ignore
, ignoresize
, &read
) == false)
1186 filefd
->Seek(oldSeek
);
1190 size
= filefd
->Tell();
1191 filefd
->Seek(oldSeek
);
1194 virtual bool InternalClose(std::string
const &FileName
) = 0;
1195 virtual bool InternalStream() const { return false; }
1196 virtual bool InternalAlwaysAutoClose() const { return true; }
1198 virtual ~FileFdPrivate() {}
1201 class APT_HIDDEN BufferedWriteFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1203 FileFdPrivate
*wrapped
;
1204 simple_buffer writebuffer
;
1208 explicit BufferedWriteFileFdPrivate(FileFdPrivate
*Priv
) :
1209 FileFdPrivate(Priv
->filefd
), wrapped(Priv
) {};
1211 virtual APT::Configuration::Compressor
get_compressor() const APT_OVERRIDE
1213 return wrapped
->get_compressor();
1215 virtual void set_compressor(APT::Configuration::Compressor
const &compressor
) APT_OVERRIDE
1217 return wrapped
->set_compressor(compressor
);
1219 virtual unsigned int get_openmode() const APT_OVERRIDE
1221 return wrapped
->get_openmode();
1223 virtual void set_openmode(unsigned int openmode
) APT_OVERRIDE
1225 return wrapped
->set_openmode(openmode
);
1227 virtual bool get_is_pipe() const APT_OVERRIDE
1229 return wrapped
->get_is_pipe();
1231 virtual void set_is_pipe(bool is_pipe
) APT_OVERRIDE
1233 FileFdPrivate::set_is_pipe(is_pipe
);
1234 wrapped
->set_is_pipe(is_pipe
);
1236 virtual unsigned long long get_seekpos() const APT_OVERRIDE
1238 return wrapped
->get_seekpos();
1240 virtual void set_seekpos(unsigned long long seekpos
) APT_OVERRIDE
1242 return wrapped
->set_seekpos(seekpos
);
1244 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) APT_OVERRIDE
1246 if (InternalFlush() == false)
1248 return wrapped
->InternalOpen(iFd
, Mode
);
1250 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
1252 if (InternalFlush() == false)
1254 return wrapped
->InternalUnbufferedRead(To
, Size
);
1257 virtual bool InternalReadError() APT_OVERRIDE
1259 return wrapped
->InternalReadError();
1261 virtual char * InternalReadLine(char * To
, unsigned long long Size
) APT_OVERRIDE
1263 if (InternalFlush() == false)
1265 return wrapped
->InternalReadLine(To
, Size
);
1267 virtual bool InternalFlush() APT_OVERRIDE
1269 while (writebuffer
.empty() == false) {
1270 auto written
= wrapped
->InternalWrite(writebuffer
.get(),
1271 writebuffer
.size());
1272 // Ignore interrupted syscalls
1273 if (written
< 0 && errno
== EINTR
)
1276 return wrapped
->InternalWriteError();
1278 writebuffer
.bufferstart
+= written
;
1280 writebuffer
.reset();
1281 return wrapped
->InternalFlush();
1283 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
1285 // Optimisation: If the buffer is empty and we have more to write than
1286 // would fit in the buffer (or equal number of bytes), write directly.
1287 if (writebuffer
.empty() == true && Size
>= writebuffer
.free())
1288 return wrapped
->InternalWrite(From
, Size
);
1290 // Write as much into the buffer as possible and then flush if needed
1291 auto written
= writebuffer
.write(From
, Size
);
1293 if (writebuffer
.full() && InternalFlush() == false)
1298 virtual bool InternalWriteError() APT_OVERRIDE
1300 return wrapped
->InternalWriteError();
1302 virtual bool InternalSeek(unsigned long long const To
) APT_OVERRIDE
1304 if (InternalFlush() == false)
1306 return wrapped
->InternalSeek(To
);
1308 virtual bool InternalSkip(unsigned long long Over
) APT_OVERRIDE
1310 if (InternalFlush() == false)
1312 return wrapped
->InternalSkip(Over
);
1314 virtual bool InternalTruncate(unsigned long long const Size
) APT_OVERRIDE
1316 if (InternalFlush() == false)
1318 return wrapped
->InternalTruncate(Size
);
1320 virtual unsigned long long InternalTell() APT_OVERRIDE
1322 if (InternalFlush() == false)
1324 return wrapped
->InternalTell();
1326 virtual unsigned long long InternalSize() APT_OVERRIDE
1328 if (InternalFlush() == false)
1330 return wrapped
->InternalSize();
1332 virtual bool InternalClose(std::string
const &FileName
) APT_OVERRIDE
1334 return wrapped
->InternalClose(FileName
);
1336 virtual bool InternalAlwaysAutoClose() const APT_OVERRIDE
1338 return wrapped
->InternalAlwaysAutoClose();
1340 virtual ~BufferedWriteFileFdPrivate()
1346 class APT_HIDDEN GzipFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1350 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) APT_OVERRIDE
1352 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1353 gz
= gzdopen(iFd
, "r+");
1354 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1355 gz
= gzdopen(iFd
, "w");
1357 gz
= gzdopen(iFd
, "r");
1358 filefd
->Flags
|= FileFd::Compressed
;
1359 return gz
!= nullptr;
1361 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
1363 return gzread(gz
, To
, Size
);
1365 virtual bool InternalReadError() APT_OVERRIDE
1368 char const * const errmsg
= gzerror(gz
, &err
);
1370 return filefd
->FileFdError("gzread: %s (%d: %s)", _("Read error"), err
, errmsg
);
1371 return FileFdPrivate::InternalReadError();
1373 virtual char * InternalReadLine(char * To
, unsigned long long Size
) APT_OVERRIDE
1375 return gzgets(gz
, To
, Size
);
1377 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
1379 return gzwrite(gz
,From
,Size
);
1381 virtual bool InternalWriteError() APT_OVERRIDE
1384 char const * const errmsg
= gzerror(gz
, &err
);
1386 return filefd
->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err
, errmsg
);
1387 return FileFdPrivate::InternalWriteError();
1389 virtual bool InternalSeek(unsigned long long const To
) APT_OVERRIDE
1391 off_t
const res
= gzseek(gz
, To
, SEEK_SET
);
1392 if (res
!= (off_t
)To
)
1393 return filefd
->FileFdError("Unable to seek to %llu", To
);
1398 virtual bool InternalSkip(unsigned long long Over
) APT_OVERRIDE
1400 if (Over
>= buffer
.size())
1402 Over
-= buffer
.size();
1407 buffer
.bufferstart
+= Over
;
1412 off_t
const res
= gzseek(gz
, Over
, SEEK_CUR
);
1414 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
1418 virtual unsigned long long InternalTell() APT_OVERRIDE
1420 return gztell(gz
) - buffer
.size();
1422 virtual unsigned long long InternalSize() APT_OVERRIDE
1424 unsigned long long filesize
= FileFdPrivate::InternalSize();
1425 // only check gzsize if we are actually a gzip file, just checking for
1426 // "gz" is not sufficient as uncompressed files could be opened with
1427 // gzopen in "direct" mode as well
1428 if (filesize
== 0 || gzdirect(gz
))
1431 off_t
const oldPos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
1432 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
1433 * this ourselves; the original (uncompressed) file size is the last 32
1434 * bits of the file */
1435 // FIXME: Size for gz-files is limited by 32bit… no largefile support
1436 if (lseek(filefd
->iFd
, -4, SEEK_END
) < 0)
1438 filefd
->FileFdErrno("lseek","Unable to seek to end of gzipped file");
1442 if (read(filefd
->iFd
, &size
, 4) != 4)
1444 filefd
->FileFdErrno("read","Unable to read original size of gzipped file");
1447 size
= le32toh(size
);
1449 if (lseek(filefd
->iFd
, oldPos
, SEEK_SET
) < 0)
1451 filefd
->FileFdErrno("lseek","Unable to seek in gzipped file");
1456 virtual bool InternalClose(std::string
const &FileName
) APT_OVERRIDE
1460 int const e
= gzclose(gz
);
1462 // gzdclose() on empty files always fails with "buffer error" here, ignore that
1463 if (e
!= 0 && e
!= Z_BUF_ERROR
)
1464 return _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
1468 explicit GzipFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), gz(nullptr) {}
1469 virtual ~GzipFileFdPrivate() { InternalClose(""); }
1473 class APT_HIDDEN Bz2FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1477 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) APT_OVERRIDE
1479 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1480 bz2
= BZ2_bzdopen(iFd
, "r+");
1481 else if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1482 bz2
= BZ2_bzdopen(iFd
, "w");
1484 bz2
= BZ2_bzdopen(iFd
, "r");
1485 filefd
->Flags
|= FileFd::Compressed
;
1486 return bz2
!= nullptr;
1488 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
1490 return BZ2_bzread(bz2
, To
, Size
);
1492 virtual bool InternalReadError() APT_OVERRIDE
1495 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1496 if (err
!= BZ_IO_ERROR
)
1497 return filefd
->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Read error"), err
, errmsg
);
1498 return FileFdPrivate::InternalReadError();
1500 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
1502 return BZ2_bzwrite(bz2
, (void*)From
, Size
);
1504 virtual bool InternalWriteError() APT_OVERRIDE
1507 char const * const errmsg
= BZ2_bzerror(bz2
, &err
);
1508 if (err
!= BZ_IO_ERROR
)
1509 return filefd
->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd
->FileName
.c_str(), _("Write error"), err
, errmsg
);
1510 return FileFdPrivate::InternalWriteError();
1512 virtual bool InternalStream() const APT_OVERRIDE
{ return true; }
1513 virtual bool InternalClose(std::string
const &) APT_OVERRIDE
1522 explicit Bz2FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), bz2(nullptr) {}
1523 virtual ~Bz2FileFdPrivate() { InternalClose(""); }
1527 class APT_HIDDEN Lz4FileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1528 static constexpr unsigned long long LZ4_HEADER_SIZE
= 19;
1529 static constexpr unsigned long long LZ4_FOOTER_SIZE
= 4;
1531 LZ4F_decompressionContext_t dctx
;
1532 LZ4F_compressionContext_t cctx
;
1533 LZ4F_errorCode_t res
;
1535 simple_buffer lz4_buffer
;
1536 // Count of bytes that the decompressor expects to read next, or buffer size.
1537 size_t next_to_load
= APT_BUFFER_SIZE
;
1539 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) APT_OVERRIDE
1541 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1542 return _error
->Error("lz4 only supports write or read mode");
1544 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
) {
1545 res
= LZ4F_createCompressionContext(&cctx
, LZ4F_VERSION
);
1546 lz4_buffer
.reset(LZ4F_compressBound(APT_BUFFER_SIZE
, nullptr)
1547 + LZ4_HEADER_SIZE
+ LZ4_FOOTER_SIZE
);
1549 res
= LZ4F_createDecompressionContext(&dctx
, LZ4F_VERSION
);
1550 lz4_buffer
.reset(APT_BUFFER_SIZE
);
1553 filefd
->Flags
|= FileFd::Compressed
;
1555 if (LZ4F_isError(res
))
1558 unsigned int flags
= (Mode
& (FileFd::WriteOnly
|FileFd::ReadOnly
));
1559 if (backend
.OpenDescriptor(iFd
, flags
, FileFd::None
, true) == false)
1562 // Write the file header
1563 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1565 res
= LZ4F_compressBegin(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1566 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1572 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
1574 /* Keep reading as long as the compressor still wants to read */
1575 while (next_to_load
) {
1576 // Fill compressed buffer;
1577 if (lz4_buffer
.empty()) {
1578 unsigned long long read
;
1579 /* Reset - if LZ4 decompressor wants to read more, allocate more */
1580 lz4_buffer
.reset(next_to_load
);
1581 if (backend
.Read(lz4_buffer
.getend(), lz4_buffer
.free(), &read
) == false)
1583 lz4_buffer
.bufferend
+= read
;
1588 return filefd
->FileFdError("LZ4F: %s %s",
1589 filefd
->FileName
.c_str(),
1590 _("Unexpected end of file")), -1;
1593 // Drain compressed buffer as far as possible.
1594 size_t in
= lz4_buffer
.size();
1597 res
= LZ4F_decompress(dctx
, To
, &out
, lz4_buffer
.get(), &in
, nullptr);
1598 if (LZ4F_isError(res
))
1602 lz4_buffer
.bufferstart
+= in
;
1610 virtual bool InternalReadError() APT_OVERRIDE
1612 char const * const errmsg
= LZ4F_getErrorName(res
);
1614 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Read error"), res
, errmsg
);
1616 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
1618 unsigned long long const towrite
= std::min(APT_BUFFER_SIZE
, Size
);
1620 res
= LZ4F_compressUpdate(cctx
,
1621 lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
,
1622 From
, towrite
, nullptr);
1624 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1629 virtual bool InternalWriteError() APT_OVERRIDE
1631 char const * const errmsg
= LZ4F_getErrorName(res
);
1633 return filefd
->FileFdError("LZ4F: %s %s (%zu: %s)", filefd
->FileName
.c_str(), _("Write error"), res
, errmsg
);
1635 virtual bool InternalStream() const APT_OVERRIDE
{ return true; }
1637 virtual bool InternalFlush() APT_OVERRIDE
1639 return backend
.Flush();
1642 virtual bool InternalClose(std::string
const &) APT_OVERRIDE
1644 /* Reset variables */
1646 next_to_load
= APT_BUFFER_SIZE
;
1648 if (cctx
!= nullptr)
1650 if (filefd
->Failed() == false)
1652 res
= LZ4F_compressEnd(cctx
, lz4_buffer
.buffer
, lz4_buffer
.buffersize_max
, nullptr);
1653 if (LZ4F_isError(res
) || backend
.Write(lz4_buffer
.buffer
, res
) == false)
1655 if (!backend
.Flush())
1658 if (!backend
.Close())
1661 res
= LZ4F_freeCompressionContext(cctx
);
1665 if (dctx
!= nullptr)
1667 res
= LZ4F_freeDecompressionContext(dctx
);
1670 if (backend
.IsOpen())
1676 return LZ4F_isError(res
) == false;
1679 explicit Lz4FileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), dctx(nullptr), cctx(nullptr) {}
1680 virtual ~Lz4FileFdPrivate() {
1686 class APT_HIDDEN LzmaFileFdPrivate
: public FileFdPrivate
{ /*{{{*/
1690 FileFd
* const filefd
;
1691 uint8_t buffer
[4096];
1697 LZMAFILE(FileFd
* const fd
) : file(nullptr), filefd(fd
), eof(false), compressing(false) { buffer
[0] = '\0'; }
1700 if (compressing
== true && filefd
->Failed() == false)
1702 size_t constexpr buffersize
= sizeof(buffer
)/sizeof(buffer
[0]);
1705 stream
.avail_out
= buffersize
;
1706 stream
.next_out
= buffer
;
1707 err
= lzma_code(&stream
, LZMA_FINISH
);
1708 if (err
!= LZMA_OK
&& err
!= LZMA_STREAM_END
)
1710 _error
->Error("~LZMAFILE: Compress finalisation failed");
1713 size_t const n
= buffersize
- stream
.avail_out
;
1714 if (n
&& fwrite(buffer
, 1, n
, file
) != n
)
1716 _error
->Errno("~LZMAFILE",_("Write error"));
1719 if (err
== LZMA_STREAM_END
)
1728 static uint32_t findXZlevel(std::vector
<std::string
> const &Args
)
1730 for (auto a
= Args
.rbegin(); a
!= Args
.rend(); ++a
)
1731 if (a
->empty() == false && (*a
)[0] == '-' && (*a
)[1] != '-')
1733 auto const number
= a
->find_last_of("0123456789");
1734 if (number
== std::string::npos
)
1736 auto const extreme
= a
->find("e", number
);
1737 uint32_t level
= (extreme
!= std::string::npos
) ? LZMA_PRESET_EXTREME
: 0;
1738 switch ((*a
)[number
])
1740 case '0': return level
| 0;
1741 case '1': return level
| 1;
1742 case '2': return level
| 2;
1743 case '3': return level
| 3;
1744 case '4': return level
| 4;
1745 case '5': return level
| 5;
1746 case '6': return level
| 6;
1747 case '7': return level
| 7;
1748 case '8': return level
| 8;
1749 case '9': return level
| 9;
1755 virtual bool InternalOpen(int const iFd
, unsigned int const Mode
) APT_OVERRIDE
1757 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1758 return filefd
->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd
->FileName
.c_str());
1760 if (lzma
== nullptr)
1761 lzma
= new LzmaFileFdPrivate::LZMAFILE(filefd
);
1762 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1763 lzma
->file
= fdopen(iFd
, "w");
1765 lzma
->file
= fdopen(iFd
, "r");
1766 filefd
->Flags
|= FileFd::Compressed
;
1767 if (lzma
->file
== nullptr)
1770 lzma_stream tmp_stream
= LZMA_STREAM_INIT
;
1771 lzma
->stream
= tmp_stream
;
1773 if ((Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
)
1775 uint32_t const xzlevel
= findXZlevel(compressor
.CompressArgs
);
1776 if (compressor
.Name
== "xz")
1778 if (lzma_easy_encoder(&lzma
->stream
, xzlevel
, LZMA_CHECK_CRC64
) != LZMA_OK
)
1783 lzma_options_lzma options
;
1784 lzma_lzma_preset(&options
, xzlevel
);
1785 if (lzma_alone_encoder(&lzma
->stream
, &options
) != LZMA_OK
)
1788 lzma
->compressing
= true;
1792 uint64_t const memlimit
= UINT64_MAX
;
1793 if (compressor
.Name
== "xz")
1795 if (lzma_auto_decoder(&lzma
->stream
, memlimit
, 0) != LZMA_OK
)
1800 if (lzma_alone_decoder(&lzma
->stream
, memlimit
) != LZMA_OK
)
1803 lzma
->compressing
= false;
1807 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
1810 if (lzma
->eof
== true)
1813 lzma
->stream
.next_out
= (uint8_t *) To
;
1814 lzma
->stream
.avail_out
= Size
;
1815 if (lzma
->stream
.avail_in
== 0)
1817 lzma
->stream
.next_in
= lzma
->buffer
;
1818 lzma
->stream
.avail_in
= fread(lzma
->buffer
, 1, sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]), lzma
->file
);
1820 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1821 if (lzma
->err
== LZMA_STREAM_END
)
1824 Res
= Size
- lzma
->stream
.avail_out
;
1826 else if (lzma
->err
!= LZMA_OK
)
1833 Res
= Size
- lzma
->stream
.avail_out
;
1836 // lzma run was okay, but produced no output…
1843 virtual bool InternalReadError() APT_OVERRIDE
1845 return filefd
->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma
->err
);
1847 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
1850 lzma
->stream
.next_in
= (uint8_t *)From
;
1851 lzma
->stream
.avail_in
= Size
;
1852 lzma
->stream
.next_out
= lzma
->buffer
;
1853 lzma
->stream
.avail_out
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]);
1854 lzma
->err
= lzma_code(&lzma
->stream
, LZMA_RUN
);
1855 if (lzma
->err
!= LZMA_OK
)
1857 size_t const n
= sizeof(lzma
->buffer
)/sizeof(lzma
->buffer
[0]) - lzma
->stream
.avail_out
;
1858 size_t const m
= (n
== 0) ? 0 : fwrite(lzma
->buffer
, 1, n
, lzma
->file
);
1866 Res
= Size
- lzma
->stream
.avail_in
;
1869 // lzma run was okay, but produced no output…
1876 virtual bool InternalWriteError() APT_OVERRIDE
1878 return filefd
->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma
->err
);
1880 virtual bool InternalStream() const APT_OVERRIDE
{ return true; }
1881 virtual bool InternalClose(std::string
const &) APT_OVERRIDE
1888 explicit LzmaFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
), lzma(nullptr) {}
1889 virtual ~LzmaFileFdPrivate() { InternalClose(""); }
1893 class APT_HIDDEN PipedFileFdPrivate
: public FileFdPrivate
/*{{{*/
1894 /* if we don't have a specific class dealing with library calls, we (un)compress
1895 by executing a specified binary and pipe in/out what we need */
1898 virtual bool InternalOpen(int const, unsigned int const Mode
) APT_OVERRIDE
1900 // collect zombies here in case we reopen
1901 if (compressor_pid
> 0)
1902 ExecWait(compressor_pid
, "FileFdCompressor", true);
1904 if ((Mode
& FileFd::ReadWrite
) == FileFd::ReadWrite
)
1905 return filefd
->FileFdError("ReadWrite mode is not supported for file %s", filefd
->FileName
.c_str());
1906 if (compressor
.Binary
== "false")
1907 return filefd
->FileFdError("libapt has inbuilt support for the %s compression,"
1908 " but was forced to ignore it in favor of an external binary – which isn't installed.", compressor
.Name
.c_str());
1910 bool const Comp
= (Mode
& FileFd::WriteOnly
) == FileFd::WriteOnly
;
1911 if (Comp
== false && filefd
->iFd
!= -1)
1913 // Handle 'decompression' of empty files
1915 if (fstat(filefd
->iFd
, &Buf
) != 0)
1916 return filefd
->FileFdErrno("fstat", "Could not stat fd %d for file %s", filefd
->iFd
, filefd
->FileName
.c_str());
1917 if (Buf
.st_size
== 0 && S_ISFIFO(Buf
.st_mode
) == false)
1920 // We don't need the file open - instead let the compressor open it
1921 // as he properly knows better how to efficiently read from 'his' file
1922 if (filefd
->FileName
.empty() == false)
1929 // Create a data pipe
1930 int Pipe
[2] = {-1,-1};
1931 if (pipe(Pipe
) != 0)
1932 return filefd
->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
1933 for (int J
= 0; J
!= 2; J
++)
1934 SetCloseExec(Pipe
[J
],true);
1936 compressed_fd
= filefd
->iFd
;
1940 filefd
->iFd
= Pipe
[1];
1942 filefd
->iFd
= Pipe
[0];
1945 compressor_pid
= ExecFork();
1946 if (compressor_pid
== 0)
1950 dup2(compressed_fd
,STDOUT_FILENO
);
1951 dup2(Pipe
[0],STDIN_FILENO
);
1955 if (compressed_fd
!= -1)
1956 dup2(compressed_fd
,STDIN_FILENO
);
1957 dup2(Pipe
[1],STDOUT_FILENO
);
1959 int const nullfd
= open("/dev/null", O_WRONLY
);
1962 dup2(nullfd
,STDERR_FILENO
);
1966 SetCloseExec(STDOUT_FILENO
,false);
1967 SetCloseExec(STDIN_FILENO
,false);
1969 std::vector
<char const*> Args
;
1970 Args
.push_back(compressor
.Binary
.c_str());
1971 std::vector
<std::string
> const * const addArgs
=
1972 (Comp
== true) ? &(compressor
.CompressArgs
) : &(compressor
.UncompressArgs
);
1973 for (std::vector
<std::string
>::const_iterator a
= addArgs
->begin();
1974 a
!= addArgs
->end(); ++a
)
1975 Args
.push_back(a
->c_str());
1976 if (Comp
== false && filefd
->FileName
.empty() == false)
1978 // commands not needing arguments, do not need to be told about using standard output
1979 // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
1980 if (compressor
.CompressArgs
.empty() == false && compressor
.UncompressArgs
.empty() == false)
1981 Args
.push_back("--stdout");
1982 if (filefd
->TemporaryFileName
.empty() == false)
1983 Args
.push_back(filefd
->TemporaryFileName
.c_str());
1985 Args
.push_back(filefd
->FileName
.c_str());
1987 Args
.push_back(NULL
);
1989 execvp(Args
[0],(char **)&Args
[0]);
1990 cerr
<< _("Failed to exec compressor ") << Args
[0] << endl
;
2000 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
2002 return read(filefd
->iFd
, To
, Size
);
2004 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
2006 return write(filefd
->iFd
, From
, Size
);
2008 virtual bool InternalClose(std::string
const &) APT_OVERRIDE
2011 if (filefd
->iFd
!= -1)
2016 if (compressor_pid
> 0)
2017 Ret
&= ExecWait(compressor_pid
, "FileFdCompressor", true);
2018 compressor_pid
= -1;
2021 explicit PipedFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
2022 virtual ~PipedFileFdPrivate() { InternalClose(""); }
2025 class APT_HIDDEN DirectFileFdPrivate
: public FileFdPrivate
/*{{{*/
2028 virtual bool InternalOpen(int const, unsigned int const) APT_OVERRIDE
{ return true; }
2029 virtual ssize_t
InternalUnbufferedRead(void * const To
, unsigned long long const Size
) APT_OVERRIDE
2031 return read(filefd
->iFd
, To
, Size
);
2033 virtual ssize_t
InternalWrite(void const * const From
, unsigned long long const Size
) APT_OVERRIDE
2035 // files opened read+write are strange and only really "supported" for direct files
2036 if (buffer
.size() != 0)
2038 lseek(filefd
->iFd
, -buffer
.size(), SEEK_CUR
);
2041 return write(filefd
->iFd
, From
, Size
);
2043 virtual bool InternalSeek(unsigned long long const To
) APT_OVERRIDE
2045 off_t
const res
= lseek(filefd
->iFd
, To
, SEEK_SET
);
2046 if (res
!= (off_t
)To
)
2047 return filefd
->FileFdError("Unable to seek to %llu", To
);
2052 virtual bool InternalSkip(unsigned long long Over
) APT_OVERRIDE
2054 if (Over
>= buffer
.size())
2056 Over
-= buffer
.size();
2061 buffer
.bufferstart
+= Over
;
2066 off_t
const res
= lseek(filefd
->iFd
, Over
, SEEK_CUR
);
2068 return filefd
->FileFdError("Unable to seek ahead %llu",Over
);
2072 virtual bool InternalTruncate(unsigned long long const To
) APT_OVERRIDE
2074 if (buffer
.size() != 0)
2076 unsigned long long const seekpos
= lseek(filefd
->iFd
, 0, SEEK_CUR
);
2077 if ((seekpos
- buffer
.size()) >= To
)
2079 else if (seekpos
>= To
)
2080 buffer
.bufferend
= (To
- seekpos
) + buffer
.bufferstart
;
2084 if (ftruncate(filefd
->iFd
, To
) != 0)
2085 return filefd
->FileFdError("Unable to truncate to %llu",To
);
2088 virtual unsigned long long InternalTell() APT_OVERRIDE
2090 return lseek(filefd
->iFd
,0,SEEK_CUR
) - buffer
.size();
2092 virtual unsigned long long InternalSize() APT_OVERRIDE
2094 return filefd
->FileSize();
2096 virtual bool InternalClose(std::string
const &) APT_OVERRIDE
{ return true; }
2097 virtual bool InternalAlwaysAutoClose() const APT_OVERRIDE
{ return false; }
2099 explicit DirectFileFdPrivate(FileFd
* const filefd
) : FileFdPrivate(filefd
) {}
2100 virtual ~DirectFileFdPrivate() { InternalClose(""); }
2103 // FileFd Constructors /*{{{*/
2104 FileFd::FileFd(std::string FileName
,unsigned int const Mode
,unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2106 Open(FileName
,Mode
, None
, AccessMode
);
2108 FileFd::FileFd(std::string FileName
,unsigned int const Mode
, CompressMode Compress
, unsigned long AccessMode
) : iFd(-1), Flags(0), d(NULL
)
2110 Open(FileName
,Mode
, Compress
, AccessMode
);
2112 FileFd::FileFd() : iFd(-1), Flags(AutoClose
), d(NULL
) {}
2113 FileFd::FileFd(int const Fd
, unsigned int const Mode
, CompressMode Compress
) : iFd(-1), Flags(0), d(NULL
)
2115 OpenDescriptor(Fd
, Mode
, Compress
);
2117 FileFd::FileFd(int const Fd
, bool const AutoClose
) : iFd(-1), Flags(0), d(NULL
)
2119 OpenDescriptor(Fd
, ReadWrite
, None
, AutoClose
);
2122 // FileFd::Open - Open a file /*{{{*/
2123 // ---------------------------------------------------------------------
2124 /* The most commonly used open mode combinations are given with Mode */
2125 bool FileFd::Open(string FileName
,unsigned int const Mode
,CompressMode Compress
, unsigned long const AccessMode
)
2127 if (Mode
== ReadOnlyGzip
)
2128 return Open(FileName
, ReadOnly
, Gzip
, AccessMode
);
2130 if (Compress
== Auto
&& (Mode
& WriteOnly
) == WriteOnly
)
2131 return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName
.c_str());
2133 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2134 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2135 if (Compress
== Auto
)
2137 for (; compressor
!= compressors
.end(); ++compressor
)
2139 std::string file
= FileName
+ compressor
->Extension
;
2140 if (FileExists(file
) == false)
2146 else if (Compress
== Extension
)
2148 std::string::size_type
const found
= FileName
.find_last_of('.');
2150 if (found
!= std::string::npos
)
2152 ext
= FileName
.substr(found
);
2153 if (ext
== ".new" || ext
== ".bak")
2155 std::string::size_type
const found2
= FileName
.find_last_of('.', found
- 1);
2156 if (found2
!= std::string::npos
)
2157 ext
= FileName
.substr(found2
, found
- found2
);
2162 for (; compressor
!= compressors
.end(); ++compressor
)
2163 if (ext
== compressor
->Extension
)
2165 // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
2166 if (compressor
== compressors
.end())
2167 for (compressor
= compressors
.begin(); compressor
!= compressors
.end(); ++compressor
)
2168 if (compressor
->Name
== ".")
2176 case None
: name
= "."; break;
2177 case Gzip
: name
= "gzip"; break;
2178 case Bzip2
: name
= "bzip2"; break;
2179 case Lzma
: name
= "lzma"; break;
2180 case Xz
: name
= "xz"; break;
2181 case Lz4
: name
= "lz4"; break;
2185 return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName
.c_str());
2187 for (; compressor
!= compressors
.end(); ++compressor
)
2188 if (compressor
->Name
== name
)
2190 if (compressor
== compressors
.end())
2191 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2194 if (compressor
== compressors
.end())
2195 return FileFdError("Can't find a match for specified compressor mode for file %s", FileName
.c_str());
2196 return Open(FileName
, Mode
, *compressor
, AccessMode
);
2198 bool FileFd::Open(string FileName
,unsigned int const Mode
,APT::Configuration::Compressor
const &compressor
, unsigned long const AccessMode
)
2203 if ((Mode
& WriteOnly
) != WriteOnly
&& (Mode
& (Atomic
| Create
| Empty
| Exclusive
)) != 0)
2204 return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName
.c_str());
2205 if ((Mode
& ReadWrite
) == 0)
2206 return FileFdError("No openmode provided in FileFd::Open for %s", FileName
.c_str());
2208 unsigned int OpenMode
= Mode
;
2209 if (FileName
== "/dev/null")
2210 OpenMode
= OpenMode
& ~(Atomic
| Exclusive
| Create
| Empty
);
2212 if ((OpenMode
& Atomic
) == Atomic
)
2216 else if ((OpenMode
& (Exclusive
| Create
)) == (Exclusive
| Create
))
2218 // for atomic, this will be done by rename in Close()
2219 RemoveFile("FileFd::Open", FileName
);
2221 if ((OpenMode
& Empty
) == Empty
)
2224 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
2225 RemoveFile("FileFd::Open", FileName
);
2229 #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
2230 if_FLAGGED_SET(ReadWrite
, O_RDWR
);
2231 else if_FLAGGED_SET(ReadOnly
, O_RDONLY
);
2232 else if_FLAGGED_SET(WriteOnly
, O_WRONLY
);
2234 if_FLAGGED_SET(Create
, O_CREAT
);
2235 if_FLAGGED_SET(Empty
, O_TRUNC
);
2236 if_FLAGGED_SET(Exclusive
, O_EXCL
);
2237 #undef if_FLAGGED_SET
2239 if ((OpenMode
& Atomic
) == Atomic
)
2241 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
2243 if((iFd
= mkstemp(name
)) == -1)
2246 return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName
.c_str());
2249 TemporaryFileName
= string(name
);
2252 // umask() will always set the umask and return the previous value, so
2253 // we first set the umask and then reset it to the old value
2254 mode_t
const CurrentUmask
= umask(0);
2255 umask(CurrentUmask
);
2256 // calculate the actual file permissions (just like open/creat)
2257 mode_t
const FilePermissions
= (AccessMode
& ~CurrentUmask
);
2259 if(fchmod(iFd
, FilePermissions
) == -1)
2260 return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName
.c_str());
2263 iFd
= open(FileName
.c_str(), fileflags
, AccessMode
);
2265 this->FileName
= FileName
;
2266 if (iFd
== -1 || OpenInternDescriptor(OpenMode
, compressor
) == false)
2273 return FileFdErrno("open",_("Could not open file %s"), FileName
.c_str());
2276 SetCloseExec(iFd
,true);
2280 // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
2281 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, CompressMode Compress
, bool AutoClose
)
2283 std::vector
<APT::Configuration::Compressor
> const compressors
= APT::Configuration::getCompressors();
2284 std::vector
<APT::Configuration::Compressor
>::const_iterator compressor
= compressors
.begin();
2287 // compat with the old API
2288 if (Mode
== ReadOnlyGzip
&& Compress
== None
)
2293 case None
: name
= "."; break;
2294 case Gzip
: name
= "gzip"; break;
2295 case Bzip2
: name
= "bzip2"; break;
2296 case Lzma
: name
= "lzma"; break;
2297 case Xz
: name
= "xz"; break;
2298 case Lz4
: name
= "lz4"; break;
2301 if (AutoClose
== true && Fd
!= -1)
2303 return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd
);
2305 for (; compressor
!= compressors
.end(); ++compressor
)
2306 if (compressor
->Name
== name
)
2308 if (compressor
== compressors
.end())
2310 if (AutoClose
== true && Fd
!= -1)
2312 return FileFdError("Can't find a configured compressor %s for file %s", name
.c_str(), FileName
.c_str());
2314 return OpenDescriptor(Fd
, Mode
, *compressor
, AutoClose
);
2316 bool FileFd::OpenDescriptor(int Fd
, unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
, bool AutoClose
)
2319 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
2321 this->FileName
= "";
2322 if (OpenInternDescriptor(Mode
, compressor
) == false)
2325 (Flags
& Compressed
) == Compressed
||
2331 return FileFdError(_("Could not open file descriptor %d"), Fd
);
2335 bool FileFd::OpenInternDescriptor(unsigned int const Mode
, APT::Configuration::Compressor
const &compressor
)
2341 d
->InternalClose(FileName
);
2346 /* dummy so that the rest can be 'else if's */;
2347 #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
2348 else if (compressor.Name == NAME) \
2349 d = new CONSTRUCTOR(this)
2351 APT_COMPRESS_INIT("gzip", GzipFileFdPrivate
);
2354 APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate
);
2357 APT_COMPRESS_INIT("xz", LzmaFileFdPrivate
);
2358 APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate
);
2361 APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate
);
2363 #undef APT_COMPRESS_INIT
2364 else if (compressor
.Name
== "." || compressor
.Binary
.empty() == true)
2365 d
= new DirectFileFdPrivate(this);
2367 d
= new PipedFileFdPrivate(this);
2369 if (Mode
& BufferedWrite
)
2370 d
= new BufferedWriteFileFdPrivate(d
);
2372 d
->set_openmode(Mode
);
2373 d
->set_compressor(compressor
);
2374 if ((Flags
& AutoClose
) != AutoClose
&& d
->InternalAlwaysAutoClose())
2376 // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
2377 int const internFd
= dup(iFd
);
2379 return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd
);
2383 return d
->InternalOpen(iFd
, Mode
);
2386 // FileFd::~File - Closes the file /*{{{*/
2387 // ---------------------------------------------------------------------
2388 /* If the proper modes are selected then we close the Fd and possibly
2389 unlink the file on error. */
2394 d
->InternalClose(FileName
);
2399 // FileFd::Read - Read a bit of the file /*{{{*/
2400 // ---------------------------------------------------------------------
2401 /* We are careful to handle interruption by a signal while reading
2403 bool FileFd::Read(void *To
,unsigned long long Size
,unsigned long long *Actual
)
2405 if (d
== nullptr || Failed())
2411 *((char *)To
) = '\0';
2412 while (Res
> 0 && Size
> 0)
2414 Res
= d
->InternalRead(To
, Size
);
2420 // trick the while-loop into running again
2425 return d
->InternalReadError();
2428 To
= (char *)To
+ Res
;
2431 d
->set_seekpos(d
->get_seekpos() + Res
);
2446 return FileFdError(_("read, still have %llu to read but none left"), Size
);
2448 bool FileFd::Read(int const Fd
, void *To
, unsigned long long Size
, unsigned long long * const Actual
)
2452 if (Actual
!= nullptr)
2454 *static_cast<char *>(To
) = '\0';
2455 while (Res
> 0 && Size
> 0)
2457 Res
= read(Fd
, To
, Size
);
2466 return _error
->Errno("read", _("Read error"));
2468 To
= static_cast<char *>(To
) + Res
;
2475 if (Actual
!= nullptr)
2477 return _error
->Error(_("read, still have %llu to read but none left"), Size
);
2480 // FileFd::ReadLine - Read a complete line from the file /*{{{*/
2481 // ---------------------------------------------------------------------
2482 /* Beware: This method can be quite slow for big buffers on UNcompressed
2483 files because of the naive implementation! */
2484 char* FileFd::ReadLine(char *To
, unsigned long long const Size
)
2487 if (d
== nullptr || Failed())
2489 return d
->InternalReadLine(To
, Size
);
2492 // FileFd::Flush - Flush the file /*{{{*/
2493 bool FileFd::Flush()
2500 return d
->InternalFlush();
2503 // FileFd::Write - Write to the file /*{{{*/
2504 bool FileFd::Write(const void *From
,unsigned long long Size
)
2506 if (d
== nullptr || Failed())
2510 while (Res
> 0 && Size
> 0)
2512 Res
= d
->InternalWrite(From
, Size
);
2518 // trick the while-loop into running again
2523 return d
->InternalWriteError();
2526 From
= (char const *)From
+ Res
;
2529 d
->set_seekpos(d
->get_seekpos() + Res
);
2535 return FileFdError(_("write, still have %llu to write but couldn't"), Size
);
2537 bool FileFd::Write(int Fd
, const void *From
, unsigned long long Size
)
2541 while (Res
> 0 && Size
> 0)
2543 Res
= write(Fd
,From
,Size
);
2544 if (Res
< 0 && errno
== EINTR
)
2547 return _error
->Errno("write",_("Write error"));
2549 From
= (char const *)From
+ Res
;
2556 return _error
->Error(_("write, still have %llu to write but couldn't"), Size
);
2559 // FileFd::Seek - Seek in the file /*{{{*/
2560 bool FileFd::Seek(unsigned long long To
)
2562 if (d
== nullptr || Failed())
2565 return d
->InternalSeek(To
);
2568 // FileFd::Skip - Skip over data in the file /*{{{*/
2569 bool FileFd::Skip(unsigned long long Over
)
2571 if (d
== nullptr || Failed())
2573 return d
->InternalSkip(Over
);
2576 // FileFd::Truncate - Truncate the file /*{{{*/
2577 bool FileFd::Truncate(unsigned long long To
)
2579 if (d
== nullptr || Failed())
2581 // truncating /dev/null is always successful - as we get an error otherwise
2582 if (To
== 0 && FileName
== "/dev/null")
2584 return d
->InternalTruncate(To
);
2587 // FileFd::Tell - Current seek position /*{{{*/
2588 // ---------------------------------------------------------------------
2590 unsigned long long FileFd::Tell()
2592 if (d
== nullptr || Failed())
2594 off_t
const Res
= d
->InternalTell();
2595 if (Res
== (off_t
)-1)
2596 FileFdErrno("lseek","Failed to determine the current file position");
2597 d
->set_seekpos(Res
);
2601 static bool StatFileFd(char const * const msg
, int const iFd
, std::string
const &FileName
, struct stat
&Buf
, FileFdPrivate
* const d
) /*{{{*/
2603 bool ispipe
= (d
!= NULL
&& d
->get_is_pipe() == true);
2604 if (ispipe
== false)
2606 if (fstat(iFd
,&Buf
) != 0)
2607 // higher-level code will generate more meaningful messages,
2608 // even translated this would be meaningless for users
2609 return _error
->Errno("fstat", "Unable to determine %s for fd %i", msg
, iFd
);
2610 if (FileName
.empty() == false)
2611 ispipe
= S_ISFIFO(Buf
.st_mode
);
2614 // for compressor pipes st_size is undefined and at 'best' zero
2617 // we set it here, too, as we get the info here for free
2618 // in theory the Open-methods should take care of it already
2620 d
->set_is_pipe(true);
2621 if (stat(FileName
.c_str(), &Buf
) != 0)
2622 return _error
->Errno("fstat", "Unable to determine %s for file %s", msg
, FileName
.c_str());
2627 // FileFd::FileSize - Return the size of the file /*{{{*/
2628 unsigned long long FileFd::FileSize()
2631 if (StatFileFd("file size", iFd
, FileName
, Buf
, d
) == false)
2639 // FileFd::ModificationTime - Return the time of last touch /*{{{*/
2640 time_t FileFd::ModificationTime()
2643 if (StatFileFd("modification time", iFd
, FileName
, Buf
, d
) == false)
2648 return Buf
.st_mtime
;
2651 // FileFd::Size - Return the size of the content in the file /*{{{*/
2652 unsigned long long FileFd::Size()
2656 return d
->InternalSize();
2659 // FileFd::Close - Close the file if the close flag is set /*{{{*/
2660 // ---------------------------------------------------------------------
2662 bool FileFd::Close()
2664 if (Failed() == false && Flush() == false)
2670 if ((Flags
& AutoClose
) == AutoClose
)
2672 if ((Flags
& Compressed
) != Compressed
&& iFd
> 0 && close(iFd
) != 0)
2673 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
2678 Res
&= d
->InternalClose(FileName
);
2683 if ((Flags
& Replace
) == Replace
) {
2684 if (Failed() == false && rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
2685 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
2687 FileName
= TemporaryFileName
; // for the unlink() below.
2688 TemporaryFileName
.clear();
2693 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
2694 FileName
.empty() == false)
2695 Res
&= RemoveFile("FileFd::Close", FileName
);
2702 // FileFd::Sync - Sync the file /*{{{*/
2703 // ---------------------------------------------------------------------
2707 if (fsync(iFd
) != 0)
2708 return FileFdErrno("sync",_("Problem syncing the file"));
2712 // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
2713 bool FileFd::FileFdErrno(const char *Function
, const char *Description
,...)
2717 size_t msgSize
= 400;
2718 int const errsv
= errno
;
2721 va_start(args
,Description
);
2722 retry
= _error
->InsertErrno(GlobalError::ERROR
, Function
, Description
, args
, errsv
, msgSize
);
2728 // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
2729 bool FileFd::FileFdError(const char *Description
,...) {
2732 size_t msgSize
= 400;
2735 va_start(args
,Description
);
2736 retry
= _error
->Insert(GlobalError::ERROR
, Description
, args
, msgSize
);
2742 gzFile
FileFd::gzFd() { /*{{{*/
2744 GzipFileFdPrivate
* const gzipd
= dynamic_cast<GzipFileFdPrivate
*>(d
);
2745 if (gzipd
== nullptr)
2755 // Glob - wrapper around "glob()" /*{{{*/
2756 std::vector
<std::string
> Glob(std::string
const &pattern
, int flags
)
2758 std::vector
<std::string
> result
;
2763 glob_res
= glob(pattern
.c_str(), flags
, NULL
, &globbuf
);
2767 if(glob_res
!= GLOB_NOMATCH
) {
2768 _error
->Errno("glob", "Problem with glob");
2774 for(i
=0;i
<globbuf
.gl_pathc
;i
++)
2775 result
.push_back(string(globbuf
.gl_pathv
[i
]));
2781 static std::string
APT_NONNULL(1) GetTempDirEnv(char const * const env
) /*{{{*/
2783 const char *tmpdir
= getenv(env
);
2791 if (!tmpdir
|| strlen(tmpdir
) == 0 || // tmpdir is set
2792 stat(tmpdir
, &st
) != 0 || (st
.st_mode
& S_IFDIR
) == 0) // exists and is directory
2794 else if (geteuid() != 0 && // root can do everything anyway
2795 faccessat(-1, tmpdir
, R_OK
| W_OK
| X_OK
, AT_EACCESS
| AT_SYMLINK_NOFOLLOW
) != 0) // current user has rwx access to directory
2798 return string(tmpdir
);
2801 std::string
GetTempDir() /*{{{*/
2803 return GetTempDirEnv("TMPDIR");
2805 std::string
GetTempDir(std::string
const &User
)
2807 // no need/possibility to drop privs
2808 if(getuid() != 0 || User
.empty() || User
== "root")
2809 return GetTempDir();
2811 struct passwd
const * const pw
= getpwnam(User
.c_str());
2813 return GetTempDir();
2815 gid_t
const old_euid
= geteuid();
2816 gid_t
const old_egid
= getegid();
2817 if (setegid(pw
->pw_gid
) != 0)
2818 _error
->Errno("setegid", "setegid %u failed", pw
->pw_gid
);
2819 if (seteuid(pw
->pw_uid
) != 0)
2820 _error
->Errno("seteuid", "seteuid %u failed", pw
->pw_uid
);
2822 std::string
const tmp
= GetTempDir();
2824 if (seteuid(old_euid
) != 0)
2825 _error
->Errno("seteuid", "seteuid %u failed", old_euid
);
2826 if (setegid(old_egid
) != 0)
2827 _error
->Errno("setegid", "setegid %u failed", old_egid
);
2832 FileFd
* GetTempFile(std::string
const &Prefix
, bool ImmediateUnlink
, FileFd
* const TmpFd
) /*{{{*/
2835 FileFd
* const Fd
= TmpFd
== NULL
? new FileFd() : TmpFd
;
2837 std::string
const tempdir
= GetTempDir();
2838 snprintf(fn
, sizeof(fn
), "%s/%s.XXXXXX",
2839 tempdir
.c_str(), Prefix
.c_str());
2840 int const fd
= mkstemp(fn
);
2845 _error
->Errno("GetTempFile",_("Unable to mkstemp %s"), fn
);
2848 if (!Fd
->OpenDescriptor(fd
, FileFd::ReadWrite
, FileFd::None
, true))
2850 _error
->Errno("GetTempFile",_("Unable to write to %s"),fn
);
2856 bool Rename(std::string From
, std::string To
) /*{{{*/
2858 if (rename(From
.c_str(),To
.c_str()) != 0)
2860 _error
->Error(_("rename failed, %s (%s -> %s)."),strerror(errno
),
2861 From
.c_str(),To
.c_str());
2867 bool Popen(const char* Args
[], FileFd
&Fd
, pid_t
&Child
, FileFd::OpenMode Mode
)/*{{{*/
2869 return Popen(Args
, Fd
, Child
, Mode
, true);
2872 bool Popen(const char* Args
[], FileFd
&Fd
, pid_t
&Child
, FileFd::OpenMode Mode
, bool CaptureStderr
)/*{{{*/
2875 if (Mode
!= FileFd::ReadOnly
&& Mode
!= FileFd::WriteOnly
)
2876 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2878 int Pipe
[2] = {-1, -1};
2880 return _error
->Errno("pipe", _("Failed to create subprocess IPC"));
2882 std::set
<int> keep_fds
;
2883 keep_fds
.insert(Pipe
[0]);
2884 keep_fds
.insert(Pipe
[1]);
2885 Child
= ExecFork(keep_fds
);
2887 return _error
->Errno("fork", "Failed to fork");
2890 if(Mode
== FileFd::ReadOnly
)
2895 else if(Mode
== FileFd::WriteOnly
)
2901 if(Mode
== FileFd::ReadOnly
)
2904 if (CaptureStderr
== true)
2906 } else if(Mode
== FileFd::WriteOnly
)
2909 execv(Args
[0], (char**)Args
);
2912 if(Mode
== FileFd::ReadOnly
)
2917 else if(Mode
== FileFd::WriteOnly
)
2923 return _error
->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2924 Fd
.OpenDescriptor(fd
, Mode
, FileFd::None
, true);
2929 bool DropPrivileges() /*{{{*/
2931 if(_config
->FindB("Debug::NoDropPrivs", false) == true)
2935 #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
2936 #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
2938 // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
2939 int ret
= prctl(38, 1, 0, 0, 0);
2940 // ignore EINVAL - kernel is too old to understand the option
2941 if(ret
< 0 && errno
!= EINVAL
)
2942 _error
->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret
);
2945 // empty setting disables privilege dropping - this also ensures
2946 // backward compatibility, see bug #764506
2947 const std::string toUser
= _config
->Find("APT::Sandbox::User");
2948 if (toUser
.empty() || toUser
== "root")
2951 // a lot can go wrong trying to drop privileges completely,
2952 // so ideally we would like to verify that we have done it –
2953 // but the verify asks for too much in case of fakeroot (and alike)
2954 // [Specific checks can be overridden with dedicated options]
2955 bool const VerifySandboxing
= _config
->FindB("APT::Sandbox::Verify", false);
2957 // uid will be 0 in the end, but gid might be different anyway
2958 uid_t
const old_uid
= getuid();
2959 gid_t
const old_gid
= getgid();
2964 struct passwd
*pw
= getpwnam(toUser
.c_str());
2966 return _error
->Error("No user %s, can not drop rights", toUser
.c_str());
2968 // Do not change the order here, it might break things
2969 // Get rid of all our supplementary groups first
2970 if (setgroups(1, &pw
->pw_gid
))
2971 return _error
->Errno("setgroups", "Failed to setgroups");
2973 // Now change the group ids to the new user
2974 #ifdef HAVE_SETRESGID
2975 if (setresgid(pw
->pw_gid
, pw
->pw_gid
, pw
->pw_gid
) != 0)
2976 return _error
->Errno("setresgid", "Failed to set new group ids");
2978 if (setegid(pw
->pw_gid
) != 0)
2979 return _error
->Errno("setegid", "Failed to setegid");
2981 if (setgid(pw
->pw_gid
) != 0)
2982 return _error
->Errno("setgid", "Failed to setgid");
2985 // Change the user ids to the new user
2986 #ifdef HAVE_SETRESUID
2987 if (setresuid(pw
->pw_uid
, pw
->pw_uid
, pw
->pw_uid
) != 0)
2988 return _error
->Errno("setresuid", "Failed to set new user ids");
2990 if (setuid(pw
->pw_uid
) != 0)
2991 return _error
->Errno("setuid", "Failed to setuid");
2992 if (seteuid(pw
->pw_uid
) != 0)
2993 return _error
->Errno("seteuid", "Failed to seteuid");
2996 // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
2997 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Groups", false) == true)
2999 // Verify that the user isn't still in any supplementary groups
3000 long const ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
3001 std::unique_ptr
<gid_t
[]> gidlist(new gid_t
[ngroups_max
]);
3002 if (unlikely(gidlist
== NULL
))
3003 return _error
->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max
);
3005 if ((gidlist_nr
= getgroups(ngroups_max
, gidlist
.get())) < 0)
3006 return _error
->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max
);
3007 for (ssize_t i
= 0; i
< gidlist_nr
; ++i
)
3008 if (gidlist
[i
] != pw
->pw_gid
)
3009 return _error
->Error("Could not switch group, user %s is still in group %d", toUser
.c_str(), gidlist
[i
]);
3012 // enabled by default as all fakeroot-lookalikes should fake that accordingly
3013 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::IDs", true) == true)
3015 // Verify that gid, egid, uid, and euid changed
3016 if (getgid() != pw
->pw_gid
)
3017 return _error
->Error("Could not switch group");
3018 if (getegid() != pw
->pw_gid
)
3019 return _error
->Error("Could not switch effective group");
3020 if (getuid() != pw
->pw_uid
)
3021 return _error
->Error("Could not switch user");
3022 if (geteuid() != pw
->pw_uid
)
3023 return _error
->Error("Could not switch effective user");
3025 #ifdef HAVE_GETRESUID
3026 // verify that the saved set-user-id was changed as well
3030 if (getresuid(&ruid
, &euid
, &suid
))
3031 return _error
->Errno("getresuid", "Could not get saved set-user-ID");
3032 if (suid
!= pw
->pw_uid
)
3033 return _error
->Error("Could not switch saved set-user-ID");
3036 #ifdef HAVE_GETRESGID
3037 // verify that the saved set-group-id was changed as well
3041 if (getresgid(&rgid
, &egid
, &sgid
))
3042 return _error
->Errno("getresuid", "Could not get saved set-group-ID");
3043 if (sgid
!= pw
->pw_gid
)
3044 return _error
->Error("Could not switch saved set-group-ID");
3048 // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
3049 if (VerifySandboxing
== true || _config
->FindB("APT::Sandbox::Verify::Regain", false) == true)
3051 // Check that uid and gid changes do not work anymore
3052 if (pw
->pw_gid
!= old_gid
&& (setgid(old_gid
) != -1 || setegid(old_gid
) != -1))
3053 return _error
->Error("Could restore a gid to root, privilege dropping did not work");
3055 if (pw
->pw_uid
!= old_uid
&& (setuid(old_uid
) != -1 || seteuid(old_uid
) != -1))
3056 return _error
->Error("Could restore a uid to root, privilege dropping did not work");
3059 if (_config
->FindB("APT::Sandbox::ResetEnvironment", true))
3061 setenv("HOME", pw
->pw_dir
, 1);
3062 setenv("USER", pw
->pw_name
, 1);
3063 setenv("USERNAME", pw
->pw_name
, 1);
3064 setenv("LOGNAME", pw
->pw_name
, 1);
3065 auto const shell
= flNotDir(pw
->pw_shell
);
3066 if (shell
== "false" || shell
== "nologin")
3067 setenv("SHELL", "/bin/sh", 1);
3069 setenv("SHELL", pw
->pw_shell
, 1);
3070 auto const apt_setenv_tmp
= [](char const * const env
) {
3071 auto const tmpdir
= getenv(env
);
3072 if (tmpdir
!= nullptr)
3074 auto const ourtmpdir
= GetTempDirEnv(env
);
3075 if (ourtmpdir
!= tmpdir
)
3076 setenv(env
, ourtmpdir
.c_str(), 1);
3079 apt_setenv_tmp("TMPDIR");
3080 apt_setenv_tmp("TEMPDIR");
3081 apt_setenv_tmp("TMP");
3082 apt_setenv_tmp("TEMP");