You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3392 lines
99 KiB

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