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