]> git.saurik.com Git - apt.git/blame - apt-pkg/contrib/fileutl.cc
strutl.cc: Add declarations for the compat _ascii() functions
[apt.git] / apt-pkg / contrib / fileutl.cc
CommitLineData
578bfd0a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
578bfd0a
AL
3/* ######################################################################
4
5 File Utilities
6
7 CopyFile - Buffered copy of a single file
8 GetLock - dpkg compatible lock file manipulation (fcntl)
9
614adaa0
MV
10 Most of this source is placed in the Public Domain, do with it what
11 you will
7da2b375 12 It was originally written by Jason Gunthorpe <jgg@debian.org>.
a3a03f5d 13 FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
578bfd0a 14
614adaa0
MV
15 The exception is RunScripts() it is under the GPLv2
16
578bfd0a
AL
17 ##################################################################### */
18 /*}}}*/
19// Include Files /*{{{*/
ea542140
DK
20#include <config.h>
21
094a497d 22#include <apt-pkg/fileutl.h>
1cd1c398 23#include <apt-pkg/strutl.h>
094a497d 24#include <apt-pkg/error.h>
b2e465d6 25#include <apt-pkg/sptr.h>
468720c5 26#include <apt-pkg/aptconfiguration.h>
75ef8f14 27#include <apt-pkg/configuration.h>
453b82a3 28#include <apt-pkg/macros.h>
b2e465d6 29
453b82a3
DK
30#include <ctype.h>
31#include <stdarg.h>
32#include <stddef.h>
33#include <sys/select.h>
34#include <time.h>
35#include <string>
36#include <vector>
152ab79e 37#include <cstdlib>
4f333a8b 38#include <cstring>
3010fb0e 39#include <cstdio>
4d055c05 40#include <iostream>
578bfd0a 41#include <unistd.h>
2c206aa4 42#include <fcntl.h>
578bfd0a 43#include <sys/stat.h>
cc2313b7 44#include <sys/time.h>
1ae93c94 45#include <sys/wait.h>
46e39c8e 46#include <dirent.h>
54676e1a 47#include <signal.h>
65a1e968 48#include <errno.h>
8d01b9d6 49#include <glob.h>
fc1a78d8 50#include <pwd.h>
3927c6da 51#include <grp.h>
8d01b9d6 52
75ef8f14 53#include <set>
46e39c8e 54#include <algorithm>
98cc7fd2 55#include <memory>
2cae0ccb 56
7efb8c8e
DK
57#ifdef HAVE_ZLIB
58 #include <zlib.h>
699b209e 59#endif
c4997486
DK
60#ifdef HAVE_BZ2
61 #include <bzlib.h>
62#endif
7f350a37
DK
63#ifdef HAVE_LZMA
64 #include <lzma.h>
2cae0ccb 65#endif
05eab8af
AC
66#include <endian.h>
67#include <stdint.h>
ea542140 68
3927c6da
MV
69#if __gnu_linux__
70#include <sys/prctl.h>
71#endif
72
ea542140 73#include <apti18n.h>
578bfd0a
AL
74 /*}}}*/
75
4d055c05
AL
76using namespace std;
77
614adaa0
MV
78// RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
79// ---------------------------------------------------------------------
80/* */
81bool RunScripts(const char *Cnf)
82{
83 Configuration::Item const *Opts = _config->Tree(Cnf);
84 if (Opts == 0 || Opts->Child == 0)
85 return true;
86 Opts = Opts->Child;
87
88 // Fork for running the system calls
89 pid_t Child = ExecFork();
90
91 // This is the child
92 if (Child == 0)
93 {
cfba4f69
MV
94 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
95 {
96 std::cerr << "Chrooting into "
97 << _config->FindDir("DPkg::Chroot-Directory")
98 << std::endl;
99 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
100 _exit(100);
101 }
102
614adaa0
MV
103 if (chdir("/tmp/") != 0)
104 _exit(100);
105
106 unsigned int Count = 1;
107 for (; Opts != 0; Opts = Opts->Next, Count++)
108 {
109 if (Opts->Value.empty() == true)
110 continue;
e5b7e019
MV
111
112 if(_config->FindB("Debug::RunScripts", false) == true)
113 std::clog << "Running external script: '"
114 << Opts->Value << "'" << std::endl;
115
614adaa0
MV
116 if (system(Opts->Value.c_str()) != 0)
117 _exit(100+Count);
118 }
119 _exit(0);
120 }
121
122 // Wait for the child
123 int Status = 0;
124 while (waitpid(Child,&Status,0) != Child)
125 {
126 if (errno == EINTR)
127 continue;
128 return _error->Errno("waitpid","Couldn't wait for subprocess");
129 }
130
131 // Restore sig int/quit
132 signal(SIGQUIT,SIG_DFL);
133 signal(SIGINT,SIG_DFL);
134
135 // Check for an error code.
136 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
137 {
138 unsigned int Count = WEXITSTATUS(Status);
139 if (Count > 100)
140 {
141 Count -= 100;
142 for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
143 _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
144 }
145
146 return _error->Error("Sub-process returned an error code");
147 }
148
149 return true;
150}
151 /*}}}*/
152
578bfd0a
AL
153// CopyFile - Buffered copy of a file /*{{{*/
154// ---------------------------------------------------------------------
155/* The caller is expected to set things so that failure causes erasure */
8b89e57f 156bool CopyFile(FileFd &From,FileFd &To)
578bfd0a 157{
2128d3fc
DK
158 if (From.IsOpen() == false || To.IsOpen() == false ||
159 From.Failed() == true || To.Failed() == true)
578bfd0a 160 return false;
e977b8b9 161
578bfd0a 162 // Buffered copy between fds
0c93e388
PT
163 constexpr size_t BufSize = 64000;
164 std::unique_ptr<unsigned char[]> Buf(new unsigned char[BufSize]);
e977b8b9
DK
165 unsigned long long ToRead = 0;
166 do {
167 if (From.Read(Buf.get(),BufSize, &ToRead) == false ||
5df91bc7 168 To.Write(Buf.get(),ToRead) == false)
578bfd0a 169 return false;
e977b8b9 170 } while (ToRead != 0);
578bfd0a 171
ce1f3a2c
DK
172 return true;
173}
174 /*}}}*/
175bool RemoveFile(char const * const Function, std::string const &FileName)/*{{{*/
176{
177 if (FileName == "/dev/null")
178 return true;
179 errno = 0;
180 if (unlink(FileName.c_str()) != 0)
181 {
182 if (errno == ENOENT)
183 return true;
184
185 return _error->WarningE(Function,_("Problem unlinking the file %s"), FileName.c_str());
186 }
e977b8b9 187 return true;
578bfd0a
AL
188}
189 /*}}}*/
190// GetLock - Gets a lock file /*{{{*/
191// ---------------------------------------------------------------------
192/* This will create an empty file of the given name and lock it. Once this
193 is done all other calls to GetLock in any other process will fail with
194 -1. The return result is the fd of the file, the call should call
195 close at some time. */
196int GetLock(string File,bool Errors)
197{
f659b39a
OS
198 // GetLock() is used in aptitude on directories with public-write access
199 // Use O_NOFOLLOW here to prevent symlink traversal attacks
200 int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
578bfd0a
AL
201 if (FD < 0)
202 {
1e3f4083 203 // Read only .. can't have locking problems there.
b2e465d6
AL
204 if (errno == EROFS)
205 {
206 _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
207 return dup(0); // Need something for the caller to close
208 }
209
578bfd0a 210 if (Errors == true)
b2e465d6
AL
211 _error->Errno("open",_("Could not open lock file %s"),File.c_str());
212
213 // Feh.. We do this to distinguish the lock vs open case..
214 errno = EPERM;
578bfd0a
AL
215 return -1;
216 }
b2e465d6
AL
217 SetCloseExec(FD,true);
218
1e3f4083 219 // Acquire a write lock
578bfd0a 220 struct flock fl;
c71bc556
AL
221 fl.l_type = F_WRLCK;
222 fl.l_whence = SEEK_SET;
223 fl.l_start = 0;
224 fl.l_len = 0;
578bfd0a
AL
225 if (fcntl(FD,F_SETLK,&fl) == -1)
226 {
3d165906
MV
227 // always close to not leak resources
228 int Tmp = errno;
229 close(FD);
230 errno = Tmp;
231
d89df07a
AL
232 if (errno == ENOLCK)
233 {
b2e465d6
AL
234 _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
235 return dup(0); // Need something for the caller to close
3d165906
MV
236 }
237
578bfd0a 238 if (Errors == true)
b2e465d6
AL
239 _error->Errno("open",_("Could not get lock %s"),File.c_str());
240
578bfd0a
AL
241 return -1;
242 }
243
244 return FD;
245}
246 /*}}}*/
247// FileExists - Check if a file exists /*{{{*/
248// ---------------------------------------------------------------------
36f1098a 249/* Beware: Directories are also files! */
578bfd0a
AL
250bool FileExists(string File)
251{
252 struct stat Buf;
253 if (stat(File.c_str(),&Buf) != 0)
254 return false;
255 return true;
256}
257 /*}}}*/
36f1098a
DK
258// RealFileExists - Check if a file exists and if it is really a file /*{{{*/
259// ---------------------------------------------------------------------
260/* */
261bool RealFileExists(string File)
262{
263 struct stat Buf;
264 if (stat(File.c_str(),&Buf) != 0)
265 return false;
266 return ((Buf.st_mode & S_IFREG) != 0);
267}
268 /*}}}*/
1cd1c398
DK
269// DirectoryExists - Check if a directory exists and is really one /*{{{*/
270// ---------------------------------------------------------------------
271/* */
272bool DirectoryExists(string const &Path)
273{
274 struct stat Buf;
275 if (stat(Path.c_str(),&Buf) != 0)
276 return false;
277 return ((Buf.st_mode & S_IFDIR) != 0);
278}
279 /*}}}*/
280// CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
281// ---------------------------------------------------------------------
282/* This method will create all directories needed for path in good old
283 mkdir -p style but refuses to do this if Parent is not a prefix of
284 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
285 so it will create apt/archives if /var/cache exists - on the other
286 hand if the parent is /var/lib the creation will fail as this path
287 is not a parent of the path to be generated. */
288bool CreateDirectory(string const &Parent, string const &Path)
289{
290 if (Parent.empty() == true || Path.empty() == true)
291 return false;
292
293 if (DirectoryExists(Path) == true)
294 return true;
295
296 if (DirectoryExists(Parent) == false)
297 return false;
298
299 // we are not going to create directories "into the blue"
9ce3cfc9 300 if (Path.compare(0, Parent.length(), Parent) != 0)
1cd1c398
DK
301 return false;
302
303 vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
304 string progress = Parent;
305 for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
306 {
307 if (d->empty() == true)
308 continue;
309
310 progress.append("/").append(*d);
311 if (DirectoryExists(progress) == true)
312 continue;
313
314 if (mkdir(progress.c_str(), 0755) != 0)
315 return false;
316 }
317 return true;
318}
319 /*}}}*/
7753e468 320// CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
b29c3712
DK
321// ---------------------------------------------------------------------
322/* a small wrapper around CreateDirectory to check if it exists and to
323 remove the trailing "/apt/" from the parent directory if needed */
7753e468 324bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path)
b29c3712
DK
325{
326 if (DirectoryExists(Path) == true)
327 return true;
328
329 size_t const len = Parent.size();
330 if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
331 {
332 if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
333 return true;
334 }
335 else if (CreateDirectory(Parent, Path) == true)
336 return true;
337
338 return false;
339}
340 /*}}}*/
46e39c8e
MV
341// GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
342// ---------------------------------------------------------------------
343/* If an extension is given only files with this extension are included
344 in the returned vector, otherwise every "normal" file is included. */
b39c1859
MV
345std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
346 bool const &SortList, bool const &AllowNoExt)
347{
348 std::vector<string> ext;
349 ext.reserve(2);
350 if (Ext.empty() == false)
351 ext.push_back(Ext);
352 if (AllowNoExt == true && ext.empty() == false)
353 ext.push_back("");
354 return GetListOfFilesInDir(Dir, ext, SortList);
355}
356std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
357 bool const &SortList)
358{
359 // Attention debuggers: need to be set with the environment config file!
360 bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
361 if (Debug == true)
362 {
363 std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
364 if (Ext.empty() == true)
365 std::clog << "\tNO extension" << std::endl;
366 else
367 for (std::vector<string>::const_iterator e = Ext.begin();
368 e != Ext.end(); ++e)
369 std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
370 }
371
46e39c8e 372 std::vector<string> List;
36f1098a 373
69c2ecbd 374 if (DirectoryExists(Dir) == false)
36f1098a
DK
375 {
376 _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
377 return List;
378 }
379
1408e219 380 Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
46e39c8e
MV
381 DIR *D = opendir(Dir.c_str());
382 if (D == 0)
383 {
384 _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
385 return List;
386 }
387
388 for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
389 {
b39c1859 390 // skip "hidden" files
46e39c8e
MV
391 if (Ent->d_name[0] == '.')
392 continue;
393
491058e3
DK
394 // Make sure it is a file and not something else
395 string const File = flCombine(Dir,Ent->d_name);
396#ifdef _DIRENT_HAVE_D_TYPE
397 if (Ent->d_type != DT_REG)
398#endif
399 {
69c2ecbd 400 if (RealFileExists(File) == false)
491058e3 401 {
84e254d6
DK
402 // do not show ignoration warnings for directories
403 if (
404#ifdef _DIRENT_HAVE_D_TYPE
405 Ent->d_type == DT_DIR ||
406#endif
69c2ecbd 407 DirectoryExists(File) == true)
84e254d6 408 continue;
491058e3
DK
409 if (SilentIgnore.Match(Ent->d_name) == false)
410 _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
411 continue;
412 }
413 }
414
b39c1859
MV
415 // check for accepted extension:
416 // no extension given -> periods are bad as hell!
417 // extensions given -> "" extension allows no extension
418 if (Ext.empty() == false)
419 {
420 string d_ext = flExtension(Ent->d_name);
421 if (d_ext == Ent->d_name) // no extension
422 {
423 if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
424 {
425 if (Debug == true)
426 std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
5edc3966 427 if (SilentIgnore.Match(Ent->d_name) == false)
491058e3 428 _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
b39c1859
MV
429 continue;
430 }
431 }
432 else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
433 {
434 if (Debug == true)
435 std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
1408e219 436 if (SilentIgnore.Match(Ent->d_name) == false)
491058e3 437 _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
b39c1859
MV
438 continue;
439 }
440 }
46e39c8e 441
b39c1859 442 // Skip bad filenames ala run-parts
46e39c8e
MV
443 const char *C = Ent->d_name;
444 for (; *C != 0; ++C)
445 if (isalpha(*C) == 0 && isdigit(*C) == 0
9d39208a 446 && *C != '_' && *C != '-' && *C != ':') {
b39c1859
MV
447 // no required extension -> dot is a bad character
448 if (*C == '.' && Ext.empty() == false)
449 continue;
46e39c8e 450 break;
b39c1859 451 }
46e39c8e 452
b39c1859 453 // we don't reach the end of the name -> bad character included
46e39c8e 454 if (*C != 0)
b39c1859
MV
455 {
456 if (Debug == true)
457 std::clog << "Bad file: " << Ent->d_name << " → bad character »"
458 << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
459 continue;
460 }
461
fbb2c7e0
DK
462 // skip filenames which end with a period. These are never valid
463 if (*(C - 1) == '.')
464 {
465 if (Debug == true)
466 std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
467 continue;
468 }
469
470 if (Debug == true)
471 std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
472 List.push_back(File);
473 }
474 closedir(D);
475
476 if (SortList == true)
477 std::sort(List.begin(),List.end());
478 return List;
479}
480std::vector<string> GetListOfFilesInDir(string const &Dir, bool SortList)
481{
482 bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
483 if (Debug == true)
484 std::clog << "Accept in " << Dir << " all regular files" << std::endl;
485
486 std::vector<string> List;
487
69c2ecbd 488 if (DirectoryExists(Dir) == false)
fbb2c7e0
DK
489 {
490 _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
491 return List;
492 }
493
494 DIR *D = opendir(Dir.c_str());
495 if (D == 0)
496 {
497 _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
498 return List;
499 }
500
501 for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
502 {
503 // skip "hidden" files
504 if (Ent->d_name[0] == '.')
505 continue;
506
507 // Make sure it is a file and not something else
508 string const File = flCombine(Dir,Ent->d_name);
509#ifdef _DIRENT_HAVE_D_TYPE
510 if (Ent->d_type != DT_REG)
511#endif
512 {
69c2ecbd 513 if (RealFileExists(File) == false)
fbb2c7e0
DK
514 {
515 if (Debug == true)
516 std::clog << "Bad file: " << Ent->d_name << " → it is not a real file" << std::endl;
517 continue;
518 }
519 }
520
521 // Skip bad filenames ala run-parts
522 const char *C = Ent->d_name;
523 for (; *C != 0; ++C)
524 if (isalpha(*C) == 0 && isdigit(*C) == 0
525 && *C != '_' && *C != '-' && *C != '.')
526 break;
527
528 // we don't reach the end of the name -> bad character included
529 if (*C != 0)
530 {
531 if (Debug == true)
532 std::clog << "Bad file: " << Ent->d_name << " → bad character »" << *C << "« in filename" << std::endl;
533 continue;
534 }
535
b39c1859
MV
536 // skip filenames which end with a period. These are never valid
537 if (*(C - 1) == '.')
538 {
539 if (Debug == true)
540 std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
46e39c8e 541 continue;
b39c1859 542 }
46e39c8e 543
b39c1859
MV
544 if (Debug == true)
545 std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
46e39c8e
MV
546 List.push_back(File);
547 }
548 closedir(D);
549
550 if (SortList == true)
551 std::sort(List.begin(),List.end());
552 return List;
553}
554 /*}}}*/
578bfd0a
AL
555// SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
556// ---------------------------------------------------------------------
557/* We return / on failure. */
558string SafeGetCWD()
559{
560 // Stash the current dir.
561 char S[300];
562 S[0] = 0;
7f25bdff 563 if (getcwd(S,sizeof(S)-2) == 0)
578bfd0a 564 return "/";
7f25bdff
AL
565 unsigned int Len = strlen(S);
566 S[Len] = '/';
567 S[Len+1] = 0;
578bfd0a
AL
568 return S;
569}
570 /*}}}*/
2ec858bc
MV
571// GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
572// ---------------------------------------------------------------------
573/* We return / on failure. */
574time_t GetModificationTime(string const &Path)
575{
576 struct stat St;
577 if (stat(Path.c_str(), &St) < 0)
578 return -1;
579 return St.st_mtime;
580}
581 /*}}}*/
8ce4327b
AL
582// flNotDir - Strip the directory from the filename /*{{{*/
583// ---------------------------------------------------------------------
584/* */
585string flNotDir(string File)
586{
587 string::size_type Res = File.rfind('/');
588 if (Res == string::npos)
589 return File;
590 Res++;
591 return string(File,Res,Res - File.length());
592}
593 /*}}}*/
d38b7b3d
AL
594// flNotFile - Strip the file from the directory name /*{{{*/
595// ---------------------------------------------------------------------
171c45bc 596/* Result ends in a / */
d38b7b3d
AL
597string flNotFile(string File)
598{
599 string::size_type Res = File.rfind('/');
600 if (Res == string::npos)
171c45bc 601 return "./";
d38b7b3d
AL
602 Res++;
603 return string(File,0,Res);
604}
605 /*}}}*/
b2e465d6
AL
606// flExtension - Return the extension for the file /*{{{*/
607// ---------------------------------------------------------------------
608/* */
609string flExtension(string File)
610{
611 string::size_type Res = File.rfind('.');
612 if (Res == string::npos)
613 return File;
614 Res++;
615 return string(File,Res,Res - File.length());
616}
617 /*}}}*/
421c8d10
AL
618// flNoLink - If file is a symlink then deref it /*{{{*/
619// ---------------------------------------------------------------------
620/* If the name is not a link then the returned path is the input. */
621string flNoLink(string File)
622{
623 struct stat St;
624 if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
625 return File;
626 if (stat(File.c_str(),&St) != 0)
627 return File;
628
629 /* Loop resolving the link. There is no need to limit the number of
630 loops because the stat call above ensures that the symlink is not
631 circular */
632 char Buffer[1024];
633 string NFile = File;
634 while (1)
635 {
636 // Read the link
3286ad13 637 ssize_t Res;
421c8d10 638 if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
3286ad13 639 (size_t)Res >= sizeof(Buffer))
421c8d10
AL
640 return File;
641
642 // Append or replace the previous path
643 Buffer[Res] = 0;
644 if (Buffer[0] == '/')
645 NFile = Buffer;
646 else
647 NFile = flNotFile(NFile) + Buffer;
648
649 // See if we are done
650 if (lstat(NFile.c_str(),&St) != 0)
651 return File;
652 if (S_ISLNK(St.st_mode) == 0)
653 return NFile;
654 }
655}
656 /*}}}*/
b2e465d6
AL
657// flCombine - Combine a file and a directory /*{{{*/
658// ---------------------------------------------------------------------
659/* If the file is an absolute path then it is just returned, otherwise
660 the directory is pre-pended to it. */
661string flCombine(string Dir,string File)
662{
663 if (File.empty() == true)
664 return string();
665
666 if (File[0] == '/' || Dir.empty() == true)
667 return File;
668 if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
669 return File;
670 if (Dir[Dir.length()-1] == '/')
671 return Dir + File;
672 return Dir + '/' + File;
673}
674 /*}}}*/
53ac87ac
MV
675// flAbsPath - Return the absolute path of the filename /*{{{*/
676// ---------------------------------------------------------------------
677/* */
678string flAbsPath(string File)
679{
680 char *p = realpath(File.c_str(), NULL);
681 if (p == NULL)
682 {
95278287 683 _error->Errno("realpath", "flAbsPath on %s failed", File.c_str());
53ac87ac
MV
684 return "";
685 }
686 std::string AbsPath(p);
687 free(p);
688 return AbsPath;
689}
690 /*}}}*/
3b5421b4
AL
691// SetCloseExec - Set the close on exec flag /*{{{*/
692// ---------------------------------------------------------------------
693/* */
694void SetCloseExec(int Fd,bool Close)
695{
696 if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
697 {
698 cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
699 exit(100);
700 }
701}
702 /*}}}*/
703// SetNonBlock - Set the nonblocking flag /*{{{*/
704// ---------------------------------------------------------------------
705/* */
706void SetNonBlock(int Fd,bool Block)
707{
0a8a80e5
AL
708 int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
709 if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
3b5421b4
AL
710 {
711 cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
712 exit(100);
713 }
714}
715 /*}}}*/
716// WaitFd - Wait for a FD to become readable /*{{{*/
717// ---------------------------------------------------------------------
b2e465d6 718/* This waits for a FD to become readable using select. It is useful for
6d5dd02a
AL
719 applications making use of non-blocking sockets. The timeout is
720 in seconds. */
1084d58a 721bool WaitFd(int Fd,bool write,unsigned long timeout)
3b5421b4
AL
722{
723 fd_set Set;
cc2313b7 724 struct timeval tv;
3b5421b4
AL
725 FD_ZERO(&Set);
726 FD_SET(Fd,&Set);
6d5dd02a
AL
727 tv.tv_sec = timeout;
728 tv.tv_usec = 0;
1084d58a 729 if (write == true)
b0db36b1
AL
730 {
731 int Res;
732 do
733 {
734 Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
735 }
736 while (Res < 0 && errno == EINTR);
737
738 if (Res <= 0)
739 return false;
1084d58a
AL
740 }
741 else
742 {
b0db36b1
AL
743 int Res;
744 do
745 {
746 Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
747 }
748 while (Res < 0 && errno == EINTR);
749
750 if (Res <= 0)
751 return false;
cc2313b7 752 }
1084d58a 753
3b5421b4
AL
754 return true;
755}
756 /*}}}*/
96ae6de5 757// MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
54676e1a 758// ---------------------------------------------------------------------
96ae6de5
MV
759/* This is used to merge the APT::Keep-Fds with the provided KeepFDs
760 * set.
761 */
762void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs)
e45c4617 763{
e45c4617
MV
764 Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
765 if (Opts != 0 && Opts->Child != 0)
766 {
767 Opts = Opts->Child;
768 for (; Opts != 0; Opts = Opts->Next)
769 {
770 if (Opts->Value.empty() == true)
771 continue;
772 int fd = atoi(Opts->Value.c_str());
773 KeepFDs.insert(fd);
774 }
775 }
96ae6de5
MV
776}
777 /*}}}*/
54676e1a
AL
778// ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
779// ---------------------------------------------------------------------
780/* This is used if you want to cleanse the environment for the forked
781 child, it fixes up the important signals and nukes all of the fds,
782 otherwise acts like normal fork. */
75ef8f14 783pid_t ExecFork()
96ae6de5
MV
784{
785 set<int> KeepFDs;
786 // we need to merge the Keep-Fds as external tools like
787 // debconf-apt-progress use it
788 MergeKeepFdsFromConfiguration(KeepFDs);
e45c4617
MV
789 return ExecFork(KeepFDs);
790}
791
792pid_t ExecFork(std::set<int> KeepFDs)
54676e1a
AL
793{
794 // Fork off the process
795 pid_t Process = fork();
796 if (Process < 0)
797 {
798 cerr << "FATAL -> Failed to fork." << endl;
799 exit(100);
800 }
801
802 // Spawn the subprocess
803 if (Process == 0)
804 {
805 // Setup the signals
806 signal(SIGPIPE,SIG_DFL);
807 signal(SIGQUIT,SIG_DFL);
808 signal(SIGINT,SIG_DFL);
809 signal(SIGWINCH,SIG_DFL);
810 signal(SIGCONT,SIG_DFL);
811 signal(SIGTSTP,SIG_DFL);
75ef8f14 812
be4d908f
JAK
813 DIR *dir = opendir("/proc/self/fd");
814 if (dir != NULL)
75ef8f14 815 {
be4d908f
JAK
816 struct dirent *ent;
817 while ((ent = readdir(dir)))
818 {
819 int fd = atoi(ent->d_name);
820 // If fd > 0, it was a fd number and not . or ..
821 if (fd >= 3 && KeepFDs.find(fd) == KeepFDs.end())
822 fcntl(fd,F_SETFD,FD_CLOEXEC);
823 }
824 closedir(dir);
825 } else {
826 long ScOpenMax = sysconf(_SC_OPEN_MAX);
827 // Close all of our FDs - just in case
828 for (int K = 3; K != ScOpenMax; K++)
829 {
830 if(KeepFDs.find(K) == KeepFDs.end())
831 fcntl(K,F_SETFD,FD_CLOEXEC);
832 }
75ef8f14 833 }
54676e1a
AL
834 }
835
836 return Process;
837}
838 /*}}}*/
ddc1d8d0
AL
839// ExecWait - Fancy waitpid /*{{{*/
840// ---------------------------------------------------------------------
2c9a72d1 841/* Waits for the given sub process. If Reap is set then no errors are
ddc1d8d0
AL
842 generated. Otherwise a failed subprocess will generate a proper descriptive
843 message */
3826564e 844bool ExecWait(pid_t Pid,const char *Name,bool Reap)
ddc1d8d0
AL
845{
846 if (Pid <= 1)
847 return true;
848
849 // Wait and collect the error code
850 int Status;
851 while (waitpid(Pid,&Status,0) != Pid)
852 {
853 if (errno == EINTR)
854 continue;
855
856 if (Reap == true)
857 return false;
858
db0db9fe 859 return _error->Error(_("Waited for %s but it wasn't there"),Name);
ddc1d8d0
AL
860 }
861
862
863 // Check for an error code.
864 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
865 {
866 if (Reap == true)
867 return false;
ab7f4d7c 868 if (WIFSIGNALED(Status) != 0)
40e7fe0e 869 {
ab7f4d7c
MV
870 if( WTERMSIG(Status) == SIGSEGV)
871 return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
872 else
873 return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
40e7fe0e 874 }
ddc1d8d0
AL
875
876 if (WIFEXITED(Status) != 0)
b2e465d6 877 return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
ddc1d8d0 878
b2e465d6 879 return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
ddc1d8d0
AL
880 }
881
882 return true;
883}
884 /*}}}*/
f8aba23f 885// StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
fe5804fc 886bool StartsWithGPGClearTextSignature(string const &FileName)
0854ad8b
MV
887{
888 static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
1c89c98a 889 char buffer[strlen(SIGMSG)+1];
0854ad8b
MV
890 FILE* gpg = fopen(FileName.c_str(), "r");
891 if (gpg == NULL)
892 return false;
893
894 char const * const test = fgets(buffer, sizeof(buffer), gpg);
895 fclose(gpg);
896 if (test == NULL || strcmp(buffer, SIGMSG) != 0)
897 return false;
898
899 return true;
900}
f8aba23f 901 /*}}}*/
d84da499
DK
902// ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
903bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
904{
905 if (strcmp(file, "/dev/null") == 0)
906 return true;
907 bool Res = true;
908 if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it
909 {
910 // ensure the file is owned by root and has good permissions
911 struct passwd const * const pw = getpwnam(user);
912 struct group const * const gr = getgrnam(group);
913 if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
914 Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
915 }
916 if (chmod(file, mode) != 0)
917 Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
918 return Res;
919}
920 /*}}}*/
0854ad8b 921
38dba8cd
JAK
922struct APT_HIDDEN simple_buffer { /*{{{*/
923 static constexpr size_t buffersize_max = 4096;
924 unsigned long long bufferstart = 0;
925 unsigned long long bufferend = 0;
926 char buffer[buffersize_max];
927
ea58d39e 928 const char *get() const { return buffer + bufferstart; }
38dba8cd 929 char *get() { return buffer + bufferstart; }
ea58d39e 930 bool empty() const { return bufferend <= bufferstart; }
c368b3ab 931 bool full() const { return bufferend == buffersize_max; }
ea58d39e 932 unsigned long long size() const { return bufferend-bufferstart; }
38dba8cd
JAK
933 void reset() { bufferend = bufferstart = 0; }
934 ssize_t read(void *to, unsigned long long requested_size) APT_MUSTCHECK
935 {
936 if (size() < requested_size)
937 requested_size = size();
938 memcpy(to, buffer + bufferstart, requested_size);
939 bufferstart += requested_size;
940 if (bufferstart == bufferend)
941 bufferstart = bufferend = 0;
942 return requested_size;
943 }
c368b3ab
JAK
944 ssize_t write(const void *from, unsigned long long requested_size) APT_MUSTCHECK
945 {
946 if (buffersize_max - size() < requested_size)
947 requested_size = buffersize_max - size();
948 memcpy(buffer + bufferend, from, requested_size);
949 bufferend += requested_size;
950 if (bufferstart == bufferend)
951 bufferstart = bufferend = 0;
952 return requested_size;
953 }
38dba8cd
JAK
954};
955 /*}}}*/
956
65ac6aad 957class APT_HIDDEN FileFdPrivate { /*{{{*/
88749b5d 958 friend class BufferedWriteFileFdPrivate;
fa89055f
DK
959protected:
960 FileFd * const filefd;
38dba8cd 961 simple_buffer buffer;
fa89055f
DK
962 int compressed_fd;
963 pid_t compressor_pid;
964 bool is_pipe;
965 APT::Configuration::Compressor compressor;
966 unsigned int openmode;
967 unsigned long long seekpos;
1d68256d
JAK
968public:
969
83e22e26 970 explicit FileFdPrivate(FileFd * const pfilefd) : filefd(pfilefd),
fa89055f
DK
971 compressed_fd(-1), compressor_pid(-1), is_pipe(false),
972 openmode(0), seekpos(0) {};
1d68256d
JAK
973 virtual APT::Configuration::Compressor get_compressor() const
974 {
975 return compressor;
976 }
977 virtual void set_compressor(APT::Configuration::Compressor const &compressor)
978 {
979 this->compressor = compressor;
980 }
981 virtual unsigned int get_openmode() const
982 {
983 return openmode;
984 }
985 virtual void set_openmode(unsigned int openmode)
986 {
987 this->openmode = openmode;
988 }
989 virtual bool get_is_pipe() const
990 {
991 return is_pipe;
992 }
993 virtual void set_is_pipe(bool is_pipe)
994 {
995 this->is_pipe = is_pipe;
996 }
997 virtual unsigned long long get_seekpos() const
998 {
999 return seekpos;
1000 }
1001 virtual void set_seekpos(unsigned long long seekpos)
1002 {
1003 this->seekpos = seekpos;
1004 }
fa89055f
DK
1005
1006 virtual bool InternalOpen(int const iFd, unsigned int const Mode) = 0;
f63123c3 1007 ssize_t InternalRead(void * To, unsigned long long Size)
fa89055f 1008 {
83e22e26
JAK
1009 // Drain the buffer if needed.
1010 if (buffer.empty() == false)
fa89055f 1011 {
83e22e26 1012 return buffer.read(To, Size);
fa89055f 1013 }
83e22e26 1014 return InternalUnbufferedRead(To, Size);
f63123c3
DK
1015 }
1016 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) = 0;
1017 virtual bool InternalReadError() { return filefd->FileFdErrno("read",_("Read error")); }
1018 virtual char * InternalReadLine(char * To, unsigned long long Size)
1019 {
1020 if (unlikely(Size == 0))
1021 return nullptr;
01152444 1022 // Read one byte less than buffer size to have space for trailing 0.
f63123c3 1023 --Size;
01152444 1024
f63123c3
DK
1025 char * const InitialTo = To;
1026
01152444 1027 while (Size > 0) {
83e22e26 1028 if (buffer.empty() == true)
f63123c3 1029 {
83e22e26 1030 buffer.reset();
f63123c3 1031 unsigned long long actualread = 0;
83e22e26 1032 if (filefd->Read(buffer.get(), buffer.buffersize_max, &actualread) == false)
f63123c3 1033 return nullptr;
83e22e26
JAK
1034 buffer.bufferend = actualread;
1035 if (buffer.size() == 0)
f63123c3
DK
1036 {
1037 if (To == InitialTo)
1038 return nullptr;
1039 break;
1040 }
1041 filefd->Flags &= ~FileFd::HitEof;
1042 }
1043
83e22e26 1044 unsigned long long const OutputSize = std::min(Size, buffer.size());
b3db9d81 1045 char const * const newline = static_cast<char const * const>(memchr(buffer.get(), '\n', OutputSize));
a9024b1b
JAK
1046 // Read until end of line or up to Size bytes from the buffer.
1047 unsigned long long actualread = buffer.read(To,
1048 (newline != nullptr)
1049 ? (newline - buffer.get()) + 1
1050 : OutputSize);
1051 To += actualread;
1052 Size -= actualread;
f63123c3 1053 if (newline != nullptr)
f63123c3 1054 break;
01152444 1055 }
f63123c3
DK
1056 *To = '\0';
1057 return InitialTo;
fa89055f 1058 }
766761fd
JAK
1059 virtual bool InternalFlush()
1060 {
1061 return true;
1062 }
fa89055f
DK
1063 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) = 0;
1064 virtual bool InternalWriteError() { return filefd->FileFdErrno("write",_("Write error")); }
1065 virtual bool InternalSeek(unsigned long long const To)
1066 {
1067 // Our poor man seeking is costly, so try to avoid it
1068 unsigned long long const iseekpos = filefd->Tell();
1069 if (iseekpos == To)
1070 return true;
1071 else if (iseekpos < To)
1072 return filefd->Skip(To - iseekpos);
1073
1074 if ((openmode & FileFd::ReadOnly) != FileFd::ReadOnly)
1075 return filefd->FileFdError("Reopen is only implemented for read-only files!");
1076 InternalClose(filefd->FileName);
1077 if (filefd->iFd != -1)
1078 close(filefd->iFd);
1079 filefd->iFd = -1;
1080 if (filefd->TemporaryFileName.empty() == false)
1081 filefd->iFd = open(filefd->TemporaryFileName.c_str(), O_RDONLY);
1082 else if (filefd->FileName.empty() == false)
1083 filefd->iFd = open(filefd->FileName.c_str(), O_RDONLY);
1084 else
1085 {
1086 if (compressed_fd > 0)
1087 if (lseek(compressed_fd, 0, SEEK_SET) != 0)
1088 filefd->iFd = compressed_fd;
1089 if (filefd->iFd < 0)
1090 return filefd->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
1091 }
1092
1093 if (filefd->OpenInternDescriptor(openmode, compressor) == false)
1094 return filefd->FileFdError("Seek on file %s because it couldn't be reopened", filefd->FileName.c_str());
1095
83e22e26 1096 buffer.reset();
fa89055f
DK
1097 if (To != 0)
1098 return filefd->Skip(To);
1099
1100 seekpos = To;
1101 return true;
1102 }
1103 virtual bool InternalSkip(unsigned long long Over)
1104 {
1105 unsigned long long constexpr buffersize = 1024;
1106 char buffer[buffersize];
1107 while (Over != 0)
1108 {
1109 unsigned long long toread = std::min(buffersize, Over);
1110 if (filefd->Read(buffer, toread) == false)
1111 return filefd->FileFdError("Unable to seek ahead %llu",Over);
1112 Over -= toread;
1113 }
1114 return true;
1115 }
1116 virtual bool InternalTruncate(unsigned long long const)
1117 {
1118 return filefd->FileFdError("Truncating compressed files is not implemented (%s)", filefd->FileName.c_str());
1119 }
1120 virtual unsigned long long InternalTell()
1121 {
1122 // In theory, we could just return seekpos here always instead of
1123 // seeking around, but not all users of FileFd use always Seek() and co
1124 // so d->seekpos isn't always true and we can just use it as a hint if
1125 // we have nothing else, but not always as an authority…
83e22e26 1126 return seekpos - buffer.size();
fa89055f
DK
1127 }
1128 virtual unsigned long long InternalSize()
1129 {
1130 unsigned long long size = 0;
1131 unsigned long long const oldSeek = filefd->Tell();
1132 unsigned long long constexpr ignoresize = 1024;
1133 char ignore[ignoresize];
1134 unsigned long long read = 0;
1135 do {
1136 if (filefd->Read(ignore, ignoresize, &read) == false)
1137 {
1138 filefd->Seek(oldSeek);
1139 return 0;
1140 }
1141 } while(read != 0);
1142 size = filefd->Tell();
1143 filefd->Seek(oldSeek);
1144 return size;
1145 }
1146 virtual bool InternalClose(std::string const &FileName) = 0;
1147 virtual bool InternalStream() const { return false; }
1148 virtual bool InternalAlwaysAutoClose() const { return true; }
1149
1150 virtual ~FileFdPrivate() {}
1151};
1152 /*}}}*/
88749b5d
JAK
1153class APT_HIDDEN BufferedWriteFileFdPrivate : public FileFdPrivate { /*{{{*/
1154protected:
1155 FileFdPrivate *wrapped;
1156 simple_buffer writebuffer;
1157
1158public:
1159
1160 explicit BufferedWriteFileFdPrivate(FileFdPrivate *Priv) :
1161 FileFdPrivate(Priv->filefd), wrapped(Priv) {};
1162
1163 virtual APT::Configuration::Compressor get_compressor() const override
1164 {
1165 return wrapped->get_compressor();
1166 }
1167 virtual void set_compressor(APT::Configuration::Compressor const &compressor) override
1168 {
1169 return wrapped->set_compressor(compressor);
1170 }
1171 virtual unsigned int get_openmode() const override
1172 {
1173 return wrapped->get_openmode();
1174 }
1175 virtual void set_openmode(unsigned int openmode) override
1176 {
1177 return wrapped->set_openmode(openmode);
1178 }
1179 virtual bool get_is_pipe() const override
1180 {
1181 return wrapped->get_is_pipe();
1182 }
1183 virtual void set_is_pipe(bool is_pipe) override
1184 {
1185 FileFdPrivate::set_is_pipe(is_pipe);
1186 wrapped->set_is_pipe(is_pipe);
1187 }
1188 virtual unsigned long long get_seekpos() const override
1189 {
1190 return wrapped->get_seekpos();
1191 }
1192 virtual void set_seekpos(unsigned long long seekpos) override
1193 {
1194 return wrapped->set_seekpos(seekpos);
1195 }
1196 virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
1197 {
1198 if (InternalFlush() == false)
1199 return false;
1200 return wrapped->InternalOpen(iFd, Mode);
1201 }
1202 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
1203 {
1204 if (InternalFlush() == false)
1205 return -1;
1206 return wrapped->InternalUnbufferedRead(To, Size);
1207
1208 }
1209 virtual bool InternalReadError() override
1210 {
1211 return wrapped->InternalReadError();
1212 }
1213 virtual char * InternalReadLine(char * To, unsigned long long Size) override
1214 {
1215 if (InternalFlush() == false)
1216 return nullptr;
1217 return wrapped->InternalReadLine(To, Size);
1218 }
1219 virtual bool InternalFlush() override
1220 {
1f5062f6
JAK
1221 while (writebuffer.empty() == false) {
1222 auto written = wrapped->InternalWrite(writebuffer.get(),
1223 writebuffer.size());
1224 // Ignore interrupted syscalls
1225 if (written < 0 && errno == EINTR)
1226 continue;
1227 if (written < 0)
88749b5d 1228 return false;
88749b5d 1229
1f5062f6 1230 writebuffer.bufferstart += written;
88749b5d
JAK
1231 }
1232
1233 writebuffer.reset();
1234 return true;
1235 }
1236 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1237 {
1238 size_t written = 0;
1239
1240 while (written < Size) {
1241 auto buffered = writebuffer.write(static_cast<char const*>(From) + written, Size - written);
1242
1243 written += buffered;
1244
1245 if (writebuffer.full() && InternalFlush() == false)
1246 return -1;
1247 }
1248
1249 return written;
1250 }
1251 virtual bool InternalWriteError()
1252 {
1253 return wrapped->InternalWriteError();
1254 }
1255 virtual bool InternalSeek(unsigned long long const To)
1256 {
1257 if (InternalFlush() == false)
1258 return false;
1259 return wrapped->InternalSeek(To);
1260 }
1261 virtual bool InternalSkip(unsigned long long Over)
1262 {
1263 if (InternalFlush() == false)
1264 return false;
1265 return wrapped->InternalSkip(Over);
1266 }
1267 virtual bool InternalTruncate(unsigned long long const Size)
1268 {
1269 if (InternalFlush() == false)
1270 return false;
1271 return wrapped->InternalTruncate(Size);
1272 }
1273 virtual unsigned long long InternalTell()
1274 {
1275 if (InternalFlush() == false)
1276 return -1;
1277 return wrapped->InternalTell();
1278 }
1279 virtual unsigned long long InternalSize()
1280 {
1281 if (InternalFlush() == false)
1282 return -1;
1283 return wrapped->InternalSize();
1284 }
1285 virtual bool InternalClose(std::string const &FileName)
1286 {
1287 return wrapped->InternalClose(FileName);
1288 }
1289 virtual bool InternalAlwaysAutoClose() const
1290 {
1291 return wrapped->InternalAlwaysAutoClose();
1292 }
1293 virtual ~BufferedWriteFileFdPrivate()
1294 {
1295 delete wrapped;
1296 }
1297};
1298 /*}}}*/
65ac6aad 1299class APT_HIDDEN GzipFileFdPrivate: public FileFdPrivate { /*{{{*/
4239dbca 1300#ifdef HAVE_ZLIB
fa89055f
DK
1301public:
1302 gzFile gz;
1303 virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
1304 {
1305 if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
1306 gz = gzdopen(iFd, "r+");
1307 else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
1308 gz = gzdopen(iFd, "w");
1309 else
1310 gz = gzdopen(iFd, "r");
1311 filefd->Flags |= FileFd::Compressed;
1312 return gz != nullptr;
1313 }
f63123c3 1314 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
fa89055f
DK
1315 {
1316 return gzread(gz, To, Size);
1317 }
1318 virtual bool InternalReadError() override
1319 {
1320 int err;
1321 char const * const errmsg = gzerror(gz, &err);
1322 if (err != Z_ERRNO)
1323 return filefd->FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
1324 return FileFdPrivate::InternalReadError();
1325 }
f63123c3 1326 virtual char * InternalReadLine(char * To, unsigned long long Size) override
fa89055f
DK
1327 {
1328 return gzgets(gz, To, Size);
1329 }
1330 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1331 {
1332 return gzwrite(gz,From,Size);
1333 }
1334 virtual bool InternalWriteError() override
1335 {
1336 int err;
1337 char const * const errmsg = gzerror(gz, &err);
1338 if (err != Z_ERRNO)
1339 return filefd->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
1340 return FileFdPrivate::InternalWriteError();
1341 }
1342 virtual bool InternalSeek(unsigned long long const To) override
1343 {
1344 off_t const res = gzseek(gz, To, SEEK_SET);
1345 if (res != (off_t)To)
1346 return filefd->FileFdError("Unable to seek to %llu", To);
fa89055f 1347 seekpos = To;
83e22e26 1348 buffer.reset();
fa89055f
DK
1349 return true;
1350 }
1351 virtual bool InternalSkip(unsigned long long Over) override
1352 {
83e22e26 1353 if (Over >= buffer.size())
f63123c3 1354 {
83e22e26
JAK
1355 Over -= buffer.size();
1356 buffer.reset();
f63123c3
DK
1357 }
1358 else
1359 {
83e22e26 1360 buffer.bufferstart += Over;
f63123c3
DK
1361 return true;
1362 }
1363 if (Over == 0)
1364 return true;
fa89055f
DK
1365 off_t const res = gzseek(gz, Over, SEEK_CUR);
1366 if (res < 0)
1367 return filefd->FileFdError("Unable to seek ahead %llu",Over);
1368 seekpos = res;
1369 return true;
1370 }
1371 virtual unsigned long long InternalTell() override
1372 {
83e22e26 1373 return gztell(gz) - buffer.size();
fa89055f
DK
1374 }
1375 virtual unsigned long long InternalSize() override
1376 {
1377 unsigned long long filesize = FileFdPrivate::InternalSize();
1378 // only check gzsize if we are actually a gzip file, just checking for
1379 // "gz" is not sufficient as uncompressed files could be opened with
1380 // gzopen in "direct" mode as well
1381 if (filesize == 0 || gzdirect(gz))
1382 return filesize;
1383
1384 off_t const oldPos = lseek(filefd->iFd, 0, SEEK_CUR);
1385 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
1386 * this ourselves; the original (uncompressed) file size is the last 32
1387 * bits of the file */
1388 // FIXME: Size for gz-files is limited by 32bit… no largefile support
1389 if (lseek(filefd->iFd, -4, SEEK_END) < 0)
1390 {
1391 filefd->FileFdErrno("lseek","Unable to seek to end of gzipped file");
1392 return 0;
1393 }
1394 uint32_t size = 0;
1395 if (read(filefd->iFd, &size, 4) != 4)
1396 {
1397 filefd->FileFdErrno("read","Unable to read original size of gzipped file");
1398 return 0;
1399 }
1400 size = le32toh(size);
1401
1402 if (lseek(filefd->iFd, oldPos, SEEK_SET) < 0)
1403 {
1404 filefd->FileFdErrno("lseek","Unable to seek in gzipped file");
1405 return 0;
1406 }
1407 return size;
1408 }
1409 virtual bool InternalClose(std::string const &FileName) override
1410 {
1411 if (gz == nullptr)
1412 return true;
1413 int const e = gzclose(gz);
1414 gz = nullptr;
1415 // gzdclose() on empty files always fails with "buffer error" here, ignore that
1416 if (e != 0 && e != Z_BUF_ERROR)
1417 return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
1418 return true;
1419 }
1420
11755147 1421 explicit GzipFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), gz(nullptr) {}
fa89055f 1422 virtual ~GzipFileFdPrivate() { InternalClose(""); }
4239dbca 1423#endif
fa89055f
DK
1424};
1425 /*}}}*/
65ac6aad 1426class APT_HIDDEN Bz2FileFdPrivate: public FileFdPrivate { /*{{{*/
4239dbca 1427#ifdef HAVE_BZ2
fa89055f
DK
1428 BZFILE* bz2;
1429public:
1430 virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
1431 {
1432 if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
1433 bz2 = BZ2_bzdopen(iFd, "r+");
1434 else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
1435 bz2 = BZ2_bzdopen(iFd, "w");
1436 else
1437 bz2 = BZ2_bzdopen(iFd, "r");
1438 filefd->Flags |= FileFd::Compressed;
1439 return bz2 != nullptr;
1440 }
f63123c3 1441 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
fa89055f
DK
1442 {
1443 return BZ2_bzread(bz2, To, Size);
1444 }
1445 virtual bool InternalReadError() override
1446 {
1447 int err;
1448 char const * const errmsg = BZ2_bzerror(bz2, &err);
1449 if (err != BZ_IO_ERROR)
1450 return filefd->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd->FileName.c_str(), _("Read error"), err, errmsg);
1451 return FileFdPrivate::InternalReadError();
1452 }
1453 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1454 {
1455 return BZ2_bzwrite(bz2, (void*)From, Size);
1456 }
1457 virtual bool InternalWriteError() override
1458 {
1459 int err;
1460 char const * const errmsg = BZ2_bzerror(bz2, &err);
1461 if (err != BZ_IO_ERROR)
1462 return filefd->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd->FileName.c_str(), _("Write error"), err, errmsg);
1463 return FileFdPrivate::InternalWriteError();
1464 }
1465 virtual bool InternalStream() const override { return true; }
1466 virtual bool InternalClose(std::string const &) override
1467 {
1468 if (bz2 == nullptr)
1469 return true;
1470 BZ2_bzclose(bz2);
1471 bz2 = nullptr;
1472 return true;
1473 }
1474
11755147 1475 explicit Bz2FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), bz2(nullptr) {}
fa89055f 1476 virtual ~Bz2FileFdPrivate() { InternalClose(""); }
4239dbca 1477#endif
fa89055f
DK
1478};
1479 /*}}}*/
65ac6aad 1480class APT_HIDDEN LzmaFileFdPrivate: public FileFdPrivate { /*{{{*/
4239dbca 1481#ifdef HAVE_LZMA
fa89055f
DK
1482 struct LZMAFILE {
1483 FILE* file;
1484 uint8_t buffer[4096];
1485 lzma_stream stream;
1486 lzma_ret err;
1487 bool eof;
1488 bool compressing;
1489
1490 LZMAFILE() : file(nullptr), eof(false), compressing(false) { buffer[0] = '\0'; }
1491 ~LZMAFILE()
1492 {
1493 if (compressing == true)
1494 {
1495 size_t constexpr buffersize = sizeof(buffer)/sizeof(buffer[0]);
1496 while(true)
1497 {
1498 stream.avail_out = buffersize;
1499 stream.next_out = buffer;
1500 err = lzma_code(&stream, LZMA_FINISH);
1501 if (err != LZMA_OK && err != LZMA_STREAM_END)
1502 {
1503 _error->Error("~LZMAFILE: Compress finalisation failed");
1504 break;
1505 }
1506 size_t const n = buffersize - stream.avail_out;
1507 if (n && fwrite(buffer, 1, n, file) != n)
1508 {
1509 _error->Errno("~LZMAFILE",_("Write error"));
1510 break;
1511 }
1512 if (err == LZMA_STREAM_END)
1513 break;
1514 }
1515 }
1516 lzma_end(&stream);
1517 fclose(file);
1518 }
1519 };
1520 LZMAFILE* lzma;
7a68effc
DK
1521 static uint32_t findXZlevel(std::vector<std::string> const &Args)
1522 {
1523 for (auto a = Args.rbegin(); a != Args.rend(); ++a)
1524 if (a->empty() == false && (*a)[0] == '-' && (*a)[1] != '-')
1525 {
1526 auto const number = a->find_last_of("0123456789");
1527 if (number == std::string::npos)
1528 continue;
1529 auto const extreme = a->find("e", number);
1530 uint32_t level = (extreme != std::string::npos) ? LZMA_PRESET_EXTREME : 0;
1531 switch ((*a)[number])
1532 {
1533 case '0': return level | 0;
1534 case '1': return level | 1;
1535 case '2': return level | 2;
1536 case '3': return level | 3;
1537 case '4': return level | 4;
1538 case '5': return level | 5;
1539 case '6': return level | 6;
1540 case '7': return level | 7;
1541 case '8': return level | 8;
1542 case '9': return level | 9;
1543 }
1544 }
1545 return 6;
1546 }
fa89055f
DK
1547public:
1548 virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
1549 {
1550 if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
1551 return filefd->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd->FileName.c_str());
1552
1553 if (lzma == nullptr)
1554 lzma = new LzmaFileFdPrivate::LZMAFILE;
1555 if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
1556 lzma->file = fdopen(iFd, "w");
1557 else
1558 lzma->file = fdopen(iFd, "r");
1559 filefd->Flags |= FileFd::Compressed;
1560 if (lzma->file == nullptr)
1561 return false;
1562
fa89055f
DK
1563 lzma_stream tmp_stream = LZMA_STREAM_INIT;
1564 lzma->stream = tmp_stream;
1565
1566 if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
1567 {
7a68effc 1568 uint32_t const xzlevel = findXZlevel(compressor.CompressArgs);
fa89055f
DK
1569 if (compressor.Name == "xz")
1570 {
885a1ffd 1571 if (lzma_easy_encoder(&lzma->stream, xzlevel, LZMA_CHECK_CRC64) != LZMA_OK)
fa89055f
DK
1572 return false;
1573 }
1574 else
1575 {
1576 lzma_options_lzma options;
1577 lzma_lzma_preset(&options, xzlevel);
1578 if (lzma_alone_encoder(&lzma->stream, &options) != LZMA_OK)
1579 return false;
1580 }
1581 lzma->compressing = true;
1582 }
1583 else
1584 {
7a68effc 1585 uint64_t const memlimit = UINT64_MAX;
fa89055f
DK
1586 if (compressor.Name == "xz")
1587 {
1588 if (lzma_auto_decoder(&lzma->stream, memlimit, 0) != LZMA_OK)
1589 return false;
1590 }
1591 else
1592 {
1593 if (lzma_alone_decoder(&lzma->stream, memlimit) != LZMA_OK)
1594 return false;
1595 }
1596 lzma->compressing = false;
1597 }
1598 return true;
1599 }
f63123c3 1600 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
fa89055f
DK
1601 {
1602 ssize_t Res;
1603 if (lzma->eof == true)
1604 return 0;
1605
1606 lzma->stream.next_out = (uint8_t *) To;
1607 lzma->stream.avail_out = Size;
1608 if (lzma->stream.avail_in == 0)
1609 {
1610 lzma->stream.next_in = lzma->buffer;
1611 lzma->stream.avail_in = fread(lzma->buffer, 1, sizeof(lzma->buffer)/sizeof(lzma->buffer[0]), lzma->file);
1612 }
1613 lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
1614 if (lzma->err == LZMA_STREAM_END)
1615 {
1616 lzma->eof = true;
1617 Res = Size - lzma->stream.avail_out;
1618 }
1619 else if (lzma->err != LZMA_OK)
1620 {
1621 Res = -1;
1622 errno = 0;
1623 }
1624 else
1625 {
1626 Res = Size - lzma->stream.avail_out;
1627 if (Res == 0)
1628 {
1629 // lzma run was okay, but produced no output…
1630 Res = -1;
1631 errno = EINTR;
1632 }
1633 }
1634 return Res;
1635 }
1636 virtual bool InternalReadError() override
1637 {
1638 return filefd->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma->err);
1639 }
1640 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1641 {
1642 lzma->stream.next_in = (uint8_t *)From;
1643 lzma->stream.avail_in = Size;
1644 lzma->stream.next_out = lzma->buffer;
1645 lzma->stream.avail_out = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]);
1646 lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
1647 if (lzma->err != LZMA_OK)
1648 return -1;
1649 size_t const n = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]) - lzma->stream.avail_out;
1650 size_t const m = (n == 0) ? 0 : fwrite(lzma->buffer, 1, n, lzma->file);
1651 if (m != n)
1652 return -1;
1653 else
1654 return Size - lzma->stream.avail_in;
1655 }
1656 virtual bool InternalWriteError() override
1657 {
1658 return filefd->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma->err);
1659 }
1660 virtual bool InternalStream() const override { return true; }
1661 virtual bool InternalClose(std::string const &) override
1662 {
1663 delete lzma;
1664 lzma = nullptr;
1665 return true;
1666 }
1667
11755147 1668 explicit LzmaFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), lzma(nullptr) {}
fa89055f 1669 virtual ~LzmaFileFdPrivate() { InternalClose(""); }
4239dbca 1670#endif
fa89055f
DK
1671};
1672 /*}}}*/
65ac6aad 1673class APT_HIDDEN PipedFileFdPrivate: public FileFdPrivate /*{{{*/
fa89055f
DK
1674/* if we don't have a specific class dealing with library calls, we (un)compress
1675 by executing a specified binary and pipe in/out what we need */
1676{
1677public:
1678 virtual bool InternalOpen(int const, unsigned int const Mode) override
1679 {
1680 // collect zombies here in case we reopen
1681 if (compressor_pid > 0)
1682 ExecWait(compressor_pid, "FileFdCompressor", true);
1683
1684 if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
1685 return filefd->FileFdError("ReadWrite mode is not supported for file %s", filefd->FileName.c_str());
4239dbca 1686
fa89055f
DK
1687 bool const Comp = (Mode & FileFd::WriteOnly) == FileFd::WriteOnly;
1688 if (Comp == false)
1689 {
1690 // Handle 'decompression' of empty files
1691 struct stat Buf;
1692 fstat(filefd->iFd, &Buf);
1693 if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
1694 return true;
1695
1696 // We don't need the file open - instead let the compressor open it
1697 // as he properly knows better how to efficiently read from 'his' file
1698 if (filefd->FileName.empty() == false)
1699 {
1700 close(filefd->iFd);
1701 filefd->iFd = -1;
1702 }
1703 }
1704
1705 // Create a data pipe
1706 int Pipe[2] = {-1,-1};
1707 if (pipe(Pipe) != 0)
1708 return filefd->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
1709 for (int J = 0; J != 2; J++)
1710 SetCloseExec(Pipe[J],true);
1711
1712 compressed_fd = filefd->iFd;
1d68256d 1713 set_is_pipe(true);
fa89055f
DK
1714
1715 if (Comp == true)
1716 filefd->iFd = Pipe[1];
1717 else
1718 filefd->iFd = Pipe[0];
1719
1720 // The child..
1721 compressor_pid = ExecFork();
1722 if (compressor_pid == 0)
1723 {
1724 if (Comp == true)
1725 {
1726 dup2(compressed_fd,STDOUT_FILENO);
1727 dup2(Pipe[0],STDIN_FILENO);
1728 }
1729 else
1730 {
1731 if (compressed_fd != -1)
1732 dup2(compressed_fd,STDIN_FILENO);
1733 dup2(Pipe[1],STDOUT_FILENO);
1734 }
1735 int const nullfd = open("/dev/null", O_WRONLY);
1736 if (nullfd != -1)
1737 {
1738 dup2(nullfd,STDERR_FILENO);
1739 close(nullfd);
1740 }
1741
1742 SetCloseExec(STDOUT_FILENO,false);
1743 SetCloseExec(STDIN_FILENO,false);
1744
1745 std::vector<char const*> Args;
1746 Args.push_back(compressor.Binary.c_str());
1747 std::vector<std::string> const * const addArgs =
1748 (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
1749 for (std::vector<std::string>::const_iterator a = addArgs->begin();
1750 a != addArgs->end(); ++a)
1751 Args.push_back(a->c_str());
1752 if (Comp == false && filefd->FileName.empty() == false)
1753 {
1754 // commands not needing arguments, do not need to be told about using standard output
1755 // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
1756 if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
1757 Args.push_back("--stdout");
1758 if (filefd->TemporaryFileName.empty() == false)
1759 Args.push_back(filefd->TemporaryFileName.c_str());
1760 else
1761 Args.push_back(filefd->FileName.c_str());
1762 }
1763 Args.push_back(NULL);
1764
1765 execvp(Args[0],(char **)&Args[0]);
1766 cerr << _("Failed to exec compressor ") << Args[0] << endl;
1767 _exit(100);
1768 }
1769 if (Comp == true)
1770 close(Pipe[0]);
1771 else
1772 close(Pipe[1]);
1773
1774 return true;
1775 }
f63123c3 1776 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
fa89055f
DK
1777 {
1778 return read(filefd->iFd, To, Size);
1779 }
1780 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1781 {
1782 return write(filefd->iFd, From, Size);
1783 }
1784 virtual bool InternalClose(std::string const &) override
1785 {
1786 bool Ret = true;
1787 if (compressor_pid > 0)
1788 Ret &= ExecWait(compressor_pid, "FileFdCompressor", true);
1789 compressor_pid = -1;
1790 return Ret;
1791 }
11755147 1792 explicit PipedFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
fa89055f
DK
1793 virtual ~PipedFileFdPrivate() { InternalClose(""); }
1794};
1795 /*}}}*/
65ac6aad 1796class APT_HIDDEN DirectFileFdPrivate: public FileFdPrivate /*{{{*/
fa89055f
DK
1797{
1798public:
1799 virtual bool InternalOpen(int const, unsigned int const) override { return true; }
f63123c3 1800 virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
fa89055f
DK
1801 {
1802 return read(filefd->iFd, To, Size);
1803 }
fa89055f
DK
1804 virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
1805 {
f63123c3 1806 // files opened read+write are strange and only really "supported" for direct files
83e22e26 1807 if (buffer.size() != 0)
f63123c3 1808 {
83e22e26
JAK
1809 lseek(filefd->iFd, -buffer.size(), SEEK_CUR);
1810 buffer.reset();
f63123c3 1811 }
fa89055f
DK
1812 return write(filefd->iFd, From, Size);
1813 }
1814 virtual bool InternalSeek(unsigned long long const To) override
1815 {
1816 off_t const res = lseek(filefd->iFd, To, SEEK_SET);
1817 if (res != (off_t)To)
1818 return filefd->FileFdError("Unable to seek to %llu", To);
1819 seekpos = To;
83e22e26 1820 buffer.reset();
fa89055f
DK
1821 return true;
1822 }
1823 virtual bool InternalSkip(unsigned long long Over) override
1824 {
83e22e26 1825 if (Over >= buffer.size())
f63123c3 1826 {
83e22e26
JAK
1827 Over -= buffer.size();
1828 buffer.reset();
f63123c3
DK
1829 }
1830 else
1831 {
83e22e26 1832 buffer.bufferstart += Over;
f63123c3
DK
1833 return true;
1834 }
1835 if (Over == 0)
1836 return true;
fa89055f
DK
1837 off_t const res = lseek(filefd->iFd, Over, SEEK_CUR);
1838 if (res < 0)
1839 return filefd->FileFdError("Unable to seek ahead %llu",Over);
1840 seekpos = res;
1841 return true;
1842 }
1843 virtual bool InternalTruncate(unsigned long long const To) override
1844 {
83e22e26 1845 if (buffer.size() != 0)
f63123c3
DK
1846 {
1847 unsigned long long const seekpos = lseek(filefd->iFd, 0, SEEK_CUR);
83e22e26
JAK
1848 if ((seekpos - buffer.size()) >= To)
1849 buffer.reset();
f63123c3 1850 else if (seekpos >= To)
83e22e26 1851 buffer.bufferend = (To - seekpos) + buffer.bufferstart;
f63123c3 1852 else
83e22e26 1853 buffer.reset();
f63123c3 1854 }
fa89055f
DK
1855 if (ftruncate(filefd->iFd, To) != 0)
1856 return filefd->FileFdError("Unable to truncate to %llu",To);
1857 return true;
1858 }
1859 virtual unsigned long long InternalTell() override
1860 {
83e22e26 1861 return lseek(filefd->iFd,0,SEEK_CUR) - buffer.size();
fa89055f
DK
1862 }
1863 virtual unsigned long long InternalSize() override
1864 {
1865 return filefd->FileSize();
1866 }
1867 virtual bool InternalClose(std::string const &) override { return true; }
1868 virtual bool InternalAlwaysAutoClose() const override { return false; }
1869
11755147 1870 explicit DirectFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
fa89055f 1871 virtual ~DirectFileFdPrivate() { InternalClose(""); }
4239dbca
DK
1872};
1873 /*}}}*/
6c55f07a
DK
1874// FileFd Constructors /*{{{*/
1875FileFd::FileFd(std::string FileName,unsigned int const Mode,unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
1876{
1877 Open(FileName,Mode, None, AccessMode);
1878}
1879FileFd::FileFd(std::string FileName,unsigned int const Mode, CompressMode Compress, unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
1880{
1881 Open(FileName,Mode, Compress, AccessMode);
1882}
1883FileFd::FileFd() : iFd(-1), Flags(AutoClose), d(NULL) {}
1884FileFd::FileFd(int const Fd, unsigned int const Mode, CompressMode Compress) : iFd(-1), Flags(0), d(NULL)
1885{
1886 OpenDescriptor(Fd, Mode, Compress);
1887}
1888FileFd::FileFd(int const Fd, bool const AutoClose) : iFd(-1), Flags(0), d(NULL)
1889{
1890 OpenDescriptor(Fd, ReadWrite, None, AutoClose);
1891}
1892 /*}}}*/
13d87e2e 1893// FileFd::Open - Open a file /*{{{*/
578bfd0a
AL
1894// ---------------------------------------------------------------------
1895/* The most commonly used open mode combinations are given with Mode */
e5f3f8c1 1896bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
578bfd0a 1897{
257e8d66 1898 if (Mode == ReadOnlyGzip)
e5f3f8c1 1899 return Open(FileName, ReadOnly, Gzip, AccessMode);
257e8d66 1900
468720c5 1901 if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
ae635e3c 1902 return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
257e8d66 1903
468720c5
DK
1904 std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
1905 std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
1906 if (Compress == Auto)
1907 {
468720c5
DK
1908 for (; compressor != compressors.end(); ++compressor)
1909 {
e788a834 1910 std::string file = FileName + compressor->Extension;
468720c5
DK
1911 if (FileExists(file) == false)
1912 continue;
1913 FileName = file;
468720c5
DK
1914 break;
1915 }
1916 }
1917 else if (Compress == Extension)
1918 {
52b47296
DK
1919 std::string::size_type const found = FileName.find_last_of('.');
1920 std::string ext;
1921 if (found != std::string::npos)
1922 {
1923 ext = FileName.substr(found);
1924 if (ext == ".new" || ext == ".bak")
1925 {
1926 std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
1927 if (found2 != std::string::npos)
1928 ext = FileName.substr(found2, found - found2);
1929 else
1930 ext.clear();
1931 }
1932 }
aee1aac6
DK
1933 for (; compressor != compressors.end(); ++compressor)
1934 if (ext == compressor->Extension)
1935 break;
1936 // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
1937 if (compressor == compressors.end())
1938 for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
1939 if (compressor->Name == ".")
468720c5 1940 break;
468720c5 1941 }
aee1aac6 1942 else
468720c5
DK
1943 {
1944 std::string name;
1945 switch (Compress)
1946 {
aee1aac6 1947 case None: name = "."; break;
468720c5
DK
1948 case Gzip: name = "gzip"; break;
1949 case Bzip2: name = "bzip2"; break;
1950 case Lzma: name = "lzma"; break;
1951 case Xz: name = "xz"; break;
aee1aac6
DK
1952 case Auto:
1953 case Extension:
52b47296 1954 // Unreachable
ae635e3c 1955 return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
468720c5
DK
1956 }
1957 for (; compressor != compressors.end(); ++compressor)
1958 if (compressor->Name == name)
1959 break;
aee1aac6 1960 if (compressor == compressors.end())
ae635e3c 1961 return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
468720c5
DK
1962 }
1963
aee1aac6 1964 if (compressor == compressors.end())
ae635e3c 1965 return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
e5f3f8c1 1966 return Open(FileName, Mode, *compressor, AccessMode);
aee1aac6 1967}
e5f3f8c1 1968bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
aee1aac6
DK
1969{
1970 Close();
aee1aac6
DK
1971 Flags = AutoClose;
1972
1973 if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
ae635e3c 1974 return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
aee1aac6 1975 if ((Mode & ReadWrite) == 0)
ae635e3c 1976 return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
468720c5 1977
cd46d4eb
DK
1978 unsigned int OpenMode = Mode;
1979 if (FileName == "/dev/null")
1980 OpenMode = OpenMode & ~(Atomic | Exclusive | Create | Empty);
1981
1982 if ((OpenMode & Atomic) == Atomic)
257e8d66
DK
1983 {
1984 Flags |= Replace;
257e8d66 1985 }
cd46d4eb 1986 else if ((OpenMode & (Exclusive | Create)) == (Exclusive | Create))
257e8d66
DK
1987 {
1988 // for atomic, this will be done by rename in Close()
ce1f3a2c 1989 RemoveFile("FileFd::Open", FileName);
257e8d66 1990 }
cd46d4eb 1991 if ((OpenMode & Empty) == Empty)
578bfd0a 1992 {
257e8d66
DK
1993 struct stat Buf;
1994 if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
ce1f3a2c 1995 RemoveFile("FileFd::Open", FileName);
257e8d66 1996 }
c4fc2fd7 1997
561f860a 1998 int fileflags = 0;
cd46d4eb 1999 #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
561f860a
DK
2000 if_FLAGGED_SET(ReadWrite, O_RDWR);
2001 else if_FLAGGED_SET(ReadOnly, O_RDONLY);
2002 else if_FLAGGED_SET(WriteOnly, O_WRONLY);
4a9db827 2003
561f860a
DK
2004 if_FLAGGED_SET(Create, O_CREAT);
2005 if_FLAGGED_SET(Empty, O_TRUNC);
2006 if_FLAGGED_SET(Exclusive, O_EXCL);
561f860a 2007 #undef if_FLAGGED_SET
52b47296 2008
cd46d4eb 2009 if ((OpenMode & Atomic) == Atomic)
7335eebe
AGM
2010 {
2011 char *name = strdup((FileName + ".XXXXXX").c_str());
2012
dc545c0b 2013 if((iFd = mkstemp(name)) == -1)
7335eebe
AGM
2014 {
2015 free(name);
98b69f9d 2016 return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
7335eebe
AGM
2017 }
2018
2019 TemporaryFileName = string(name);
7335eebe 2020 free(name);
dc545c0b 2021
230e69d7
DK
2022 // umask() will always set the umask and return the previous value, so
2023 // we first set the umask and then reset it to the old value
2024 mode_t const CurrentUmask = umask(0);
2025 umask(CurrentUmask);
2026 // calculate the actual file permissions (just like open/creat)
2027 mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
2028
2029 if(fchmod(iFd, FilePermissions) == -1)
dc545c0b 2030 return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
7335eebe 2031 }
468720c5 2032 else
230e69d7 2033 iFd = open(FileName.c_str(), fileflags, AccessMode);
468720c5 2034
b711c01e 2035 this->FileName = FileName;
cd46d4eb 2036 if (iFd == -1 || OpenInternDescriptor(OpenMode, compressor) == false)
561f860a 2037 {
468720c5 2038 if (iFd != -1)
fc81e8f2 2039 {
561f860a
DK
2040 close (iFd);
2041 iFd = -1;
fc81e8f2 2042 }
ae635e3c 2043 return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
257e8d66 2044 }
578bfd0a 2045
13d87e2e
AL
2046 SetCloseExec(iFd,true);
2047 return true;
578bfd0a 2048}
257e8d66
DK
2049 /*}}}*/
2050// FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
52b47296 2051bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
aee1aac6
DK
2052{
2053 std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
2054 std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
2055 std::string name;
bce778a3
MV
2056
2057 // compat with the old API
2058 if (Mode == ReadOnlyGzip && Compress == None)
2059 Compress = Gzip;
2060
aee1aac6
DK
2061 switch (Compress)
2062 {
2063 case None: name = "."; break;
2064 case Gzip: name = "gzip"; break;
2065 case Bzip2: name = "bzip2"; break;
2066 case Lzma: name = "lzma"; break;
2067 case Xz: name = "xz"; break;
2068 case Auto:
2069 case Extension:
f97bb523
DK
2070 if (AutoClose == true && Fd != -1)
2071 close(Fd);
ae635e3c 2072 return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
aee1aac6
DK
2073 }
2074 for (; compressor != compressors.end(); ++compressor)
2075 if (compressor->Name == name)
2076 break;
2077 if (compressor == compressors.end())
f97bb523
DK
2078 {
2079 if (AutoClose == true && Fd != -1)
2080 close(Fd);
ae635e3c 2081 return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
f97bb523 2082 }
aee1aac6
DK
2083 return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
2084}
52b47296 2085bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
144c0969
JAK
2086{
2087 Close();
2088 Flags = (AutoClose) ? FileFd::AutoClose : 0;
84baaae9 2089 iFd = Fd;
b711c01e 2090 this->FileName = "";
84baaae9 2091 if (OpenInternDescriptor(Mode, compressor) == false)
468720c5 2092 {
f97bb523 2093 if (iFd != -1 && (
84baaae9 2094 (Flags & Compressed) == Compressed ||
f97bb523
DK
2095 AutoClose == true))
2096 {
468720c5 2097 close (iFd);
f97bb523
DK
2098 iFd = -1;
2099 }
2100 return FileFdError(_("Could not open file descriptor %d"), Fd);
144c0969 2101 }
144c0969 2102 return true;
468720c5 2103}
52b47296 2104bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
468720c5 2105{
84baaae9
DK
2106 if (iFd == -1)
2107 return false;
ff477ee1 2108
fa89055f
DK
2109 if (d != nullptr)
2110 d->InternalClose(FileName);
2111
2112 if (d == nullptr)
2113 {
2114 if (false)
2115 /* dummy so that the rest can be 'else if's */;
2116#define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
2117 else if (compressor.Name == NAME) \
2118 d = new CONSTRUCTOR(this)
69d6988a 2119#ifdef HAVE_ZLIB
fa89055f 2120 APT_COMPRESS_INIT("gzip", GzipFileFdPrivate);
69d6988a
DK
2121#endif
2122#ifdef HAVE_BZ2
fa89055f 2123 APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate);
69d6988a 2124#endif
7f350a37 2125#ifdef HAVE_LZMA
fa89055f
DK
2126 APT_COMPRESS_INIT("xz", LzmaFileFdPrivate);
2127 APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate);
7f350a37 2128#endif
69d6988a 2129#undef APT_COMPRESS_INIT
fa89055f
DK
2130 else if (compressor.Name == "." || compressor.Binary.empty() == true)
2131 d = new DirectFileFdPrivate(this);
2132 else
2133 d = new PipedFileFdPrivate(this);
69d6988a 2134
88749b5d
JAK
2135 if (Mode & BufferedWrite)
2136 d = new BufferedWriteFileFdPrivate(d);
2137
1d68256d
JAK
2138 d->set_openmode(Mode);
2139 d->set_compressor(compressor);
fa89055f 2140 if ((Flags & AutoClose) != AutoClose && d->InternalAlwaysAutoClose())
84baaae9
DK
2141 {
2142 // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
2143 int const internFd = dup(iFd);
2144 if (internFd == -1)
2145 return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
2146 iFd = internFd;
2147 }
561f860a 2148 }
fa89055f 2149 return d->InternalOpen(iFd, Mode);
144c0969 2150}
578bfd0a 2151 /*}}}*/
8e06abb2 2152// FileFd::~File - Closes the file /*{{{*/
578bfd0a
AL
2153// ---------------------------------------------------------------------
2154/* If the proper modes are selected then we close the Fd and possibly
2155 unlink the file on error. */
8e06abb2 2156FileFd::~FileFd()
578bfd0a
AL
2157{
2158 Close();
500400fe 2159 if (d != NULL)
fa89055f 2160 d->InternalClose(FileName);
96ab3c6f
MV
2161 delete d;
2162 d = NULL;
578bfd0a
AL
2163}
2164 /*}}}*/
8e06abb2 2165// FileFd::Read - Read a bit of the file /*{{{*/
578bfd0a 2166// ---------------------------------------------------------------------
1e3f4083 2167/* We are careful to handle interruption by a signal while reading
b0db36b1 2168 gracefully. */
650faab0 2169bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
578bfd0a 2170{
fa89055f
DK
2171 if (d == nullptr)
2172 return false;
39e77e45 2173 ssize_t Res = 1;
b0db36b1 2174 errno = 0;
f604cf55
AL
2175 if (Actual != 0)
2176 *Actual = 0;
699b209e 2177 *((char *)To) = '\0';
39e77e45 2178 while (Res > 0 && Size > 0)
578bfd0a 2179 {
fa89055f 2180 Res = d->InternalRead(To, Size);
b711c01e 2181
b0db36b1
AL
2182 if (Res < 0)
2183 {
b711c01e 2184 if (errno == EINTR)
c4b113e6
DK
2185 {
2186 // trick the while-loop into running again
2187 Res = 1;
2188 errno = 0;
b711c01e 2189 continue;
c4b113e6 2190 }
fa89055f 2191 return d->InternalReadError();
b0db36b1 2192 }
578bfd0a 2193
b0db36b1
AL
2194 To = (char *)To + Res;
2195 Size -= Res;
ff477ee1 2196 if (d != NULL)
1d68256d 2197 d->set_seekpos(d->get_seekpos() + Res);
f604cf55
AL
2198 if (Actual != 0)
2199 *Actual += Res;
b0db36b1 2200 }
b0db36b1
AL
2201
2202 if (Size == 0)
2203 return true;
2204
ddc1d8d0 2205 // Eof handling
f604cf55 2206 if (Actual != 0)
ddc1d8d0
AL
2207 {
2208 Flags |= HitEof;
2209 return true;
2210 }
ae635e3c
DK
2211
2212 return FileFdError(_("read, still have %llu to read but none left"), Size);
578bfd0a
AL
2213}
2214 /*}}}*/
032bd56f
DK
2215// FileFd::ReadLine - Read a complete line from the file /*{{{*/
2216// ---------------------------------------------------------------------
fa89055f 2217/* Beware: This method can be quite slow for big buffers on UNcompressed
032bd56f
DK
2218 files because of the naive implementation! */
2219char* FileFd::ReadLine(char *To, unsigned long long const Size)
2220{
699b209e 2221 *To = '\0';
fa89055f
DK
2222 if (d == nullptr)
2223 return nullptr;
2224 return d->InternalReadLine(To, Size);
032bd56f
DK
2225}
2226 /*}}}*/
766761fd
JAK
2227// FileFd::Flush - Flush the file /*{{{*/
2228bool FileFd::Flush()
2229{
2230 if (d == nullptr)
2231 return true;
2232
2233 return d->InternalFlush();
2234}
2235 /*}}}*/
8e06abb2 2236// FileFd::Write - Write to the file /*{{{*/
650faab0 2237bool FileFd::Write(const void *From,unsigned long long Size)
578bfd0a 2238{
fa89055f
DK
2239 if (d == nullptr)
2240 return false;
5df91bc7 2241 ssize_t Res = 1;
b0db36b1 2242 errno = 0;
5df91bc7 2243 while (Res > 0 && Size > 0)
578bfd0a 2244 {
fa89055f 2245 Res = d->InternalWrite(From, Size);
b0db36b1
AL
2246 if (Res < 0 && errno == EINTR)
2247 continue;
2248 if (Res < 0)
fa89055f
DK
2249 return d->InternalWriteError();
2250
cf4ff3b7 2251 From = (char const *)From + Res;
b0db36b1 2252 Size -= Res;
ff477ee1 2253 if (d != NULL)
1d68256d 2254 d->set_seekpos(d->get_seekpos() + Res);
578bfd0a 2255 }
fa89055f 2256
b0db36b1
AL
2257 if (Size == 0)
2258 return true;
ae635e3c
DK
2259
2260 return FileFdError(_("write, still have %llu to write but couldn't"), Size);
d68d65ad
DK
2261}
2262bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
2263{
5df91bc7 2264 ssize_t Res = 1;
d68d65ad 2265 errno = 0;
5df91bc7 2266 while (Res > 0 && Size > 0)
d68d65ad
DK
2267 {
2268 Res = write(Fd,From,Size);
2269 if (Res < 0 && errno == EINTR)
2270 continue;
2271 if (Res < 0)
2272 return _error->Errno("write",_("Write error"));
2273
cf4ff3b7 2274 From = (char const *)From + Res;
d68d65ad
DK
2275 Size -= Res;
2276 }
d68d65ad
DK
2277
2278 if (Size == 0)
2279 return true;
2280
2281 return _error->Error(_("write, still have %llu to write but couldn't"), Size);
578bfd0a
AL
2282}
2283 /*}}}*/
8e06abb2 2284// FileFd::Seek - Seek in the file /*{{{*/
650faab0 2285bool FileFd::Seek(unsigned long long To)
578bfd0a 2286{
fa89055f
DK
2287 if (d == nullptr)
2288 return false;
bb93178b 2289 Flags &= ~HitEof;
fa89055f 2290 return d->InternalSeek(To);
727f18af
AL
2291}
2292 /*}}}*/
fa89055f 2293// FileFd::Skip - Skip over data in the file /*{{{*/
650faab0 2294bool FileFd::Skip(unsigned long long Over)
727f18af 2295{
fa89055f
DK
2296 if (d == nullptr)
2297 return false;
2298 return d->InternalSkip(Over);
6d5dd02a
AL
2299}
2300 /*}}}*/
fa89055f 2301// FileFd::Truncate - Truncate the file /*{{{*/
650faab0 2302bool FileFd::Truncate(unsigned long long To)
6d5dd02a 2303{
fa89055f
DK
2304 if (d == nullptr)
2305 return false;
ad5051ef
DK
2306 // truncating /dev/null is always successful - as we get an error otherwise
2307 if (To == 0 && FileName == "/dev/null")
2308 return true;
fa89055f 2309 return d->InternalTruncate(To);
578bfd0a
AL
2310}
2311 /*}}}*/
7f25bdff
AL
2312// FileFd::Tell - Current seek position /*{{{*/
2313// ---------------------------------------------------------------------
2314/* */
650faab0 2315unsigned long long FileFd::Tell()
7f25bdff 2316{
fa89055f
DK
2317 if (d == nullptr)
2318 return false;
2319 off_t const Res = d->InternalTell();
7f25bdff 2320 if (Res == (off_t)-1)
ae635e3c 2321 FileFdErrno("lseek","Failed to determine the current file position");
1d68256d 2322 d->set_seekpos(Res);
7f25bdff
AL
2323 return Res;
2324}
2325 /*}}}*/
8190b07a 2326static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
578bfd0a 2327{
1d68256d 2328 bool ispipe = (d != NULL && d->get_is_pipe() == true);
6008b79a
DK
2329 if (ispipe == false)
2330 {
2331 if (fstat(iFd,&Buf) != 0)
8190b07a
DK
2332 // higher-level code will generate more meaningful messages,
2333 // even translated this would be meaningless for users
2334 return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
003c40d3
DK
2335 if (FileName.empty() == false)
2336 ispipe = S_ISFIFO(Buf.st_mode);
6008b79a 2337 }
699b209e
DK
2338
2339 // for compressor pipes st_size is undefined and at 'best' zero
6008b79a 2340 if (ispipe == true)
699b209e
DK
2341 {
2342 // we set it here, too, as we get the info here for free
2343 // in theory the Open-methods should take care of it already
ff477ee1 2344 if (d != NULL)
1d68256d 2345 d->set_is_pipe(true);
699b209e 2346 if (stat(FileName.c_str(), &Buf) != 0)
8190b07a
DK
2347 return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
2348 }
2349 return true;
2350}
2351 /*}}}*/
2352// FileFd::FileSize - Return the size of the file /*{{{*/
2353unsigned long long FileFd::FileSize()
2354{
2355 struct stat Buf;
2356 if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
2357 {
2358 Flags |= Fail;
2359 return 0;
699b209e 2360 }
4260fd39
DK
2361 return Buf.st_size;
2362}
2363 /*}}}*/
8190b07a
DK
2364// FileFd::ModificationTime - Return the time of last touch /*{{{*/
2365time_t FileFd::ModificationTime()
2366{
2367 struct stat Buf;
2368 if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
2369 {
2370 Flags |= Fail;
2371 return 0;
2372 }
2373 return Buf.st_mtime;
2374}
2375 /*}}}*/
4260fd39 2376// FileFd::Size - Return the size of the content in the file /*{{{*/
650faab0 2377unsigned long long FileFd::Size()
4260fd39 2378{
fa89055f
DK
2379 if (d == nullptr)
2380 return false;
2381 return d->InternalSize();
578bfd0a
AL
2382}
2383 /*}}}*/
8e06abb2 2384// FileFd::Close - Close the file if the close flag is set /*{{{*/
578bfd0a
AL
2385// ---------------------------------------------------------------------
2386/* */
8e06abb2 2387bool FileFd::Close()
578bfd0a 2388{
766761fd
JAK
2389 if (Flush() == false)
2390 return false;
032bd56f
DK
2391 if (iFd == -1)
2392 return true;
2393
578bfd0a
AL
2394 bool Res = true;
2395 if ((Flags & AutoClose) == AutoClose)
d13c2d3f 2396 {
500400fe
DK
2397 if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
2398 Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
2da8aae5
JAK
2399 }
2400
2401 if (d != NULL)
2402 {
fa89055f 2403 Res &= d->InternalClose(FileName);
2da8aae5
JAK
2404 delete d;
2405 d = NULL;
d13c2d3f 2406 }
3010fb0e 2407
d3aac32e 2408 if ((Flags & Replace) == Replace) {
3010fb0e 2409 if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
62d073d9
DK
2410 Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
2411
fd3b761e 2412 FileName = TemporaryFileName; // for the unlink() below.
257e8d66 2413 TemporaryFileName.clear();
3010fb0e 2414 }
62d073d9
DK
2415
2416 iFd = -1;
2417
578bfd0a
AL
2418 if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
2419 FileName.empty() == false)
ce1f3a2c 2420 Res &= RemoveFile("FileFd::Close", FileName);
3010fb0e 2421
fbb89d94
DK
2422 if (Res == false)
2423 Flags |= Fail;
578bfd0a
AL
2424 return Res;
2425}
2426 /*}}}*/
b2e465d6
AL
2427// FileFd::Sync - Sync the file /*{{{*/
2428// ---------------------------------------------------------------------
2429/* */
2430bool FileFd::Sync()
2431{
b2e465d6 2432 if (fsync(iFd) != 0)
ae635e3c
DK
2433 return FileFdErrno("sync",_("Problem syncing the file"));
2434 return true;
2435}
2436 /*}}}*/
2437// FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
2438bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
2439{
2440 Flags |= Fail;
2441 va_list args;
2442 size_t msgSize = 400;
2443 int const errsv = errno;
2444 while (true)
fbb89d94 2445 {
ae635e3c
DK
2446 va_start(args,Description);
2447 if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
2448 break;
2449 va_end(args);
fbb89d94 2450 }
ae635e3c
DK
2451 return false;
2452}
2453 /*}}}*/
2454// FileFd::FileFdError - set Fail and call _error->Error *{{{*/
2455bool FileFd::FileFdError(const char *Description,...) {
2456 Flags |= Fail;
2457 va_list args;
2458 size_t msgSize = 400;
2459 while (true)
2460 {
2461 va_start(args,Description);
2462 if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
2463 break;
2464 va_end(args);
2465 }
2466 return false;
b2e465d6
AL
2467}
2468 /*}}}*/
fa89055f 2469gzFile FileFd::gzFd() { /*{{{*/
7f350a37 2470#ifdef HAVE_ZLIB
fa89055f
DK
2471 GzipFileFdPrivate * const gzipd = dynamic_cast<GzipFileFdPrivate*>(d);
2472 if (gzipd == nullptr)
2473 return nullptr;
2474 else
2475 return gzipd->gz;
7f350a37 2476#else
fa89055f 2477 return nullptr;
7f350a37
DK
2478#endif
2479}
fa89055f 2480 /*}}}*/
8d01b9d6 2481
f8aba23f 2482// Glob - wrapper around "glob()" /*{{{*/
8d01b9d6
MV
2483std::vector<std::string> Glob(std::string const &pattern, int flags)
2484{
2485 std::vector<std::string> result;
2486 glob_t globbuf;
ec4835a1
ÁGM
2487 int glob_res;
2488 unsigned int i;
8d01b9d6
MV
2489
2490 glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
2491
2492 if (glob_res != 0)
2493 {
2494 if(glob_res != GLOB_NOMATCH) {
2495 _error->Errno("glob", "Problem with glob");
2496 return result;
2497 }
2498 }
2499
2500 // append results
2501 for(i=0;i<globbuf.gl_pathc;i++)
2502 result.push_back(string(globbuf.gl_pathv[i]));
2503
2504 globfree(&globbuf);
2505 return result;
2506}
2507 /*}}}*/
f8aba23f 2508std::string GetTempDir() /*{{{*/
68e01721
MV
2509{
2510 const char *tmpdir = getenv("TMPDIR");
2511
2512#ifdef P_tmpdir
2513 if (!tmpdir)
2514 tmpdir = P_tmpdir;
2515#endif
2516
68e01721 2517 struct stat st;
0d303f17 2518 if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set
dd6da7d2
DK
2519 stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0) // exists and is directory
2520 tmpdir = "/tmp";
2521 else if (geteuid() != 0 && // root can do everything anyway
2522 faccessat(-1, tmpdir, R_OK | W_OK | X_OK, AT_EACCESS | AT_SYMLINK_NOFOLLOW) != 0) // current user has rwx access to directory
68e01721
MV
2523 tmpdir = "/tmp";
2524
2525 return string(tmpdir);
dd6da7d2
DK
2526}
2527std::string GetTempDir(std::string const &User)
2528{
2529 // no need/possibility to drop privs
2530 if(getuid() != 0 || User.empty() || User == "root")
2531 return GetTempDir();
2532
2533 struct passwd const * const pw = getpwnam(User.c_str());
2534 if (pw == NULL)
2535 return GetTempDir();
2536
226c0f64
DK
2537 gid_t const old_euid = geteuid();
2538 gid_t const old_egid = getegid();
dd6da7d2
DK
2539 if (setegid(pw->pw_gid) != 0)
2540 _error->Errno("setegid", "setegid %u failed", pw->pw_gid);
2541 if (seteuid(pw->pw_uid) != 0)
2542 _error->Errno("seteuid", "seteuid %u failed", pw->pw_uid);
2543
2544 std::string const tmp = GetTempDir();
2545
226c0f64
DK
2546 if (seteuid(old_euid) != 0)
2547 _error->Errno("seteuid", "seteuid %u failed", old_euid);
2548 if (setegid(old_egid) != 0)
2549 _error->Errno("setegid", "setegid %u failed", old_egid);
dd6da7d2
DK
2550
2551 return tmp;
68e01721 2552}
f8aba23f 2553 /*}}}*/
c9443c01 2554FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink, FileFd * const TmpFd) /*{{{*/
0d29b9d4
MV
2555{
2556 char fn[512];
c9443c01 2557 FileFd * const Fd = TmpFd == NULL ? new FileFd() : TmpFd;
0d29b9d4 2558
c9443c01
DK
2559 std::string const tempdir = GetTempDir();
2560 snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
0d29b9d4 2561 tempdir.c_str(), Prefix.c_str());
c9443c01 2562 int const fd = mkstemp(fn);
0d29b9d4
MV
2563 if(ImmediateUnlink)
2564 unlink(fn);
c9443c01 2565 if (fd < 0)
0d29b9d4
MV
2566 {
2567 _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
2568 return NULL;
2569 }
c9443c01 2570 if (!Fd->OpenDescriptor(fd, FileFd::ReadWrite, FileFd::None, true))
0d29b9d4
MV
2571 {
2572 _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
2573 return NULL;
2574 }
0d29b9d4
MV
2575 return Fd;
2576}
f8aba23f
DK
2577 /*}}}*/
2578bool Rename(std::string From, std::string To) /*{{{*/
c1409d1b
MV
2579{
2580 if (rename(From.c_str(),To.c_str()) != 0)
2581 {
2582 _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
2583 From.c_str(),To.c_str());
2584 return false;
f8aba23f 2585 }
c1409d1b
MV
2586 return true;
2587}
f8aba23f
DK
2588 /*}}}*/
2589bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
7ad2a347
MV
2590{
2591 int fd;
2592 if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
2593 return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
2594
2595 int Pipe[2] = {-1, -1};
2596 if(pipe(Pipe) != 0)
7ad2a347 2597 return _error->Errno("pipe", _("Failed to create subprocess IPC"));
5e49cbb7 2598
7ad2a347
MV
2599 std::set<int> keep_fds;
2600 keep_fds.insert(Pipe[0]);
2601 keep_fds.insert(Pipe[1]);
2602 Child = ExecFork(keep_fds);
2603 if(Child < 0)
2604 return _error->Errno("fork", "Failed to fork");
2605 if(Child == 0)
2606 {
2607 if(Mode == FileFd::ReadOnly)
2608 {
2609 close(Pipe[0]);
2610 fd = Pipe[1];
2611 }
2612 else if(Mode == FileFd::WriteOnly)
2613 {
2614 close(Pipe[1]);
2615 fd = Pipe[0];
2616 }
2617
2618 if(Mode == FileFd::ReadOnly)
2619 {
2620 dup2(fd, 1);
2621 dup2(fd, 2);
2622 } else if(Mode == FileFd::WriteOnly)
2623 dup2(fd, 0);
2624
2625 execv(Args[0], (char**)Args);
2626 _exit(100);
2627 }
2628 if(Mode == FileFd::ReadOnly)
2629 {
2630 close(Pipe[1]);
2631 fd = Pipe[0];
8f5b67ae
DK
2632 }
2633 else if(Mode == FileFd::WriteOnly)
7ad2a347
MV
2634 {
2635 close(Pipe[0]);
2636 fd = Pipe[1];
2637 }
8f5b67ae
DK
2638 else
2639 return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
7ad2a347
MV
2640 Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
2641
2642 return true;
2643}
f8aba23f
DK
2644 /*}}}*/
2645bool DropPrivileges() /*{{{*/
fc1a78d8 2646{
8f45798d
DK
2647 if(_config->FindB("Debug::NoDropPrivs", false) == true)
2648 return true;
2649
2650#if __gnu_linux__
2651#if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
2652#error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
2653#endif
2654 // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
2655 int ret = prctl(38, 1, 0, 0, 0);
2656 // ignore EINVAL - kernel is too old to understand the option
2657 if(ret < 0 && errno != EINVAL)
2658 _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
2659#endif
2660
990dd78a
DK
2661 // empty setting disables privilege dropping - this also ensures
2662 // backward compatibility, see bug #764506
2663 const std::string toUser = _config->Find("APT::Sandbox::User");
514a25cb 2664 if (toUser.empty() || toUser == "root")
990dd78a
DK
2665 return true;
2666
ebca2f25
DK
2667 // a lot can go wrong trying to drop privileges completely,
2668 // so ideally we would like to verify that we have done it –
2669 // but the verify asks for too much in case of fakeroot (and alike)
2670 // [Specific checks can be overridden with dedicated options]
2671 bool const VerifySandboxing = _config->FindB("APT::Sandbox::Verify", false);
2672
f1e3c8f0 2673 // uid will be 0 in the end, but gid might be different anyway
8f45798d
DK
2674 uid_t const old_uid = getuid();
2675 gid_t const old_gid = getgid();
fc1a78d8 2676
5f2047ec
JAK
2677 if (old_uid != 0)
2678 return true;
3927c6da 2679
b8dae9a1 2680 struct passwd *pw = getpwnam(toUser.c_str());
fc1a78d8 2681 if (pw == NULL)
b8dae9a1 2682 return _error->Error("No user %s, can not drop rights", toUser.c_str());
3927c6da 2683
f1e3c8f0 2684 // Do not change the order here, it might break things
5a326439 2685 // Get rid of all our supplementary groups first
3b084f06 2686 if (setgroups(1, &pw->pw_gid))
3927c6da
MV
2687 return _error->Errno("setgroups", "Failed to setgroups");
2688
5a326439
JAK
2689 // Now change the group ids to the new user
2690#ifdef HAVE_SETRESGID
2691 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
2692 return _error->Errno("setresgid", "Failed to set new group ids");
2693#else
3927c6da 2694 if (setegid(pw->pw_gid) != 0)
5f2047ec
JAK
2695 return _error->Errno("setegid", "Failed to setegid");
2696
fc1a78d8
MV
2697 if (setgid(pw->pw_gid) != 0)
2698 return _error->Errno("setgid", "Failed to setgid");
5a326439 2699#endif
5f2047ec 2700
5a326439
JAK
2701 // Change the user ids to the new user
2702#ifdef HAVE_SETRESUID
2703 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
2704 return _error->Errno("setresuid", "Failed to set new user ids");
2705#else
fc1a78d8
MV
2706 if (setuid(pw->pw_uid) != 0)
2707 return _error->Errno("setuid", "Failed to setuid");
5f2047ec
JAK
2708 if (seteuid(pw->pw_uid) != 0)
2709 return _error->Errno("seteuid", "Failed to seteuid");
5a326439 2710#endif
5f2047ec 2711
ebca2f25
DK
2712 // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
2713 if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Groups", false) == true)
2714 {
2715 // Verify that the user isn't still in any supplementary groups
2716 long const ngroups_max = sysconf(_SC_NGROUPS_MAX);
2717 std::unique_ptr<gid_t[]> gidlist(new gid_t[ngroups_max]);
2718 if (unlikely(gidlist == NULL))
2719 return _error->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max);
2720 ssize_t gidlist_nr;
2721 if ((gidlist_nr = getgroups(ngroups_max, gidlist.get())) < 0)
2722 return _error->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max);
2723 for (ssize_t i = 0; i < gidlist_nr; ++i)
2724 if (gidlist[i] != pw->pw_gid)
2725 return _error->Error("Could not switch group, user %s is still in group %d", toUser.c_str(), gidlist[i]);
2726 }
2727
2728 // enabled by default as all fakeroot-lookalikes should fake that accordingly
2729 if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::IDs", true) == true)
2730 {
2731 // Verify that gid, egid, uid, and euid changed
2732 if (getgid() != pw->pw_gid)
2733 return _error->Error("Could not switch group");
2734 if (getegid() != pw->pw_gid)
2735 return _error->Error("Could not switch effective group");
2736 if (getuid() != pw->pw_uid)
2737 return _error->Error("Could not switch user");
2738 if (geteuid() != pw->pw_uid)
2739 return _error->Error("Could not switch effective user");
5f2047ec 2740
550ab420 2741#ifdef HAVE_GETRESUID
ebca2f25
DK
2742 // verify that the saved set-user-id was changed as well
2743 uid_t ruid = 0;
2744 uid_t euid = 0;
2745 uid_t suid = 0;
2746 if (getresuid(&ruid, &euid, &suid))
2747 return _error->Errno("getresuid", "Could not get saved set-user-ID");
2748 if (suid != pw->pw_uid)
2749 return _error->Error("Could not switch saved set-user-ID");
550ab420
JAK
2750#endif
2751
2752#ifdef HAVE_GETRESGID
ebca2f25
DK
2753 // verify that the saved set-group-id was changed as well
2754 gid_t rgid = 0;
2755 gid_t egid = 0;
2756 gid_t sgid = 0;
2757 if (getresgid(&rgid, &egid, &sgid))
2758 return _error->Errno("getresuid", "Could not get saved set-group-ID");
2759 if (sgid != pw->pw_gid)
2760 return _error->Error("Could not switch saved set-group-ID");
550ab420 2761#endif
ebca2f25 2762 }
550ab420 2763
ebca2f25
DK
2764 // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
2765 if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Regain", false) == true)
2766 {
2767 // Check that uid and gid changes do not work anymore
2768 if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
2769 return _error->Error("Could restore a gid to root, privilege dropping did not work");
bdc00df5 2770
ebca2f25
DK
2771 if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
2772 return _error->Error("Could restore a uid to root, privilege dropping did not work");
2773 }
bdc00df5 2774
fc1a78d8
MV
2775 return true;
2776}
f8aba23f 2777 /*}}}*/