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.
 
 
 
 
 
 

2332 lines
66 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/fileutl.h>
  17. #include <apt-pkg/strutl.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/sptr.h>
  20. #include <apt-pkg/aptconfiguration.h>
  21. #include <apt-pkg/configuration.h>
  22. #include <apt-pkg/macros.h>
  23. #include <ctype.h>
  24. #include <stdarg.h>
  25. #include <stddef.h>
  26. #include <sys/select.h>
  27. #include <time.h>
  28. #include <string>
  29. #include <vector>
  30. #include <cstdlib>
  31. #include <cstring>
  32. #include <cstdio>
  33. #include <iostream>
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <sys/stat.h>
  37. #include <sys/time.h>
  38. #include <sys/wait.h>
  39. #include <dirent.h>
  40. #include <signal.h>
  41. #include <errno.h>
  42. #include <glob.h>
  43. #include <pwd.h>
  44. #include <grp.h>
  45. #include <set>
  46. #include <algorithm>
  47. #include <memory>
  48. #ifdef HAVE_ZLIB
  49. #include <zlib.h>
  50. #endif
  51. #ifdef HAVE_BZ2
  52. #include <bzlib.h>
  53. #endif
  54. #ifdef HAVE_LZMA
  55. #include <lzma.h>
  56. #endif
  57. #include <endian.h>
  58. #include <stdint.h>
  59. #if __gnu_linux__
  60. #include <sys/prctl.h>
  61. #endif
  62. #include <apti18n.h>
  63. /*}}}*/
  64. using namespace std;
  65. // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
  66. // ---------------------------------------------------------------------
  67. /* */
  68. bool RunScripts(const char *Cnf)
  69. {
  70. Configuration::Item const *Opts = _config->Tree(Cnf);
  71. if (Opts == 0 || Opts->Child == 0)
  72. return true;
  73. Opts = Opts->Child;
  74. // Fork for running the system calls
  75. pid_t Child = ExecFork();
  76. // This is the child
  77. if (Child == 0)
  78. {
  79. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  80. {
  81. std::cerr << "Chrooting into "
  82. << _config->FindDir("DPkg::Chroot-Directory")
  83. << std::endl;
  84. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  85. _exit(100);
  86. }
  87. if (chdir("/tmp/") != 0)
  88. _exit(100);
  89. unsigned int Count = 1;
  90. for (; Opts != 0; Opts = Opts->Next, Count++)
  91. {
  92. if (Opts->Value.empty() == true)
  93. continue;
  94. if(_config->FindB("Debug::RunScripts", false) == true)
  95. std::clog << "Running external script: '"
  96. << Opts->Value << "'" << std::endl;
  97. if (system(Opts->Value.c_str()) != 0)
  98. _exit(100+Count);
  99. }
  100. _exit(0);
  101. }
  102. // Wait for the child
  103. int Status = 0;
  104. while (waitpid(Child,&Status,0) != Child)
  105. {
  106. if (errno == EINTR)
  107. continue;
  108. return _error->Errno("waitpid","Couldn't wait for subprocess");
  109. }
  110. // Restore sig int/quit
  111. signal(SIGQUIT,SIG_DFL);
  112. signal(SIGINT,SIG_DFL);
  113. // Check for an error code.
  114. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  115. {
  116. unsigned int Count = WEXITSTATUS(Status);
  117. if (Count > 100)
  118. {
  119. Count -= 100;
  120. for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
  121. _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
  122. }
  123. return _error->Error("Sub-process returned an error code");
  124. }
  125. return true;
  126. }
  127. /*}}}*/
  128. // CopyFile - Buffered copy of a file /*{{{*/
  129. // ---------------------------------------------------------------------
  130. /* The caller is expected to set things so that failure causes erasure */
  131. bool CopyFile(FileFd &From,FileFd &To)
  132. {
  133. if (From.IsOpen() == false || To.IsOpen() == false ||
  134. From.Failed() == true || To.Failed() == true)
  135. return false;
  136. // Buffered copy between fds
  137. std::unique_ptr<unsigned char[]> Buf(new unsigned char[64000]);
  138. unsigned long long Size = From.Size();
  139. while (Size != 0)
  140. {
  141. unsigned long long ToRead = Size;
  142. if (Size > 64000)
  143. ToRead = 64000;
  144. if (From.Read(Buf.get(),ToRead) == false ||
  145. To.Write(Buf.get(),ToRead) == false)
  146. return false;
  147. Size -= ToRead;
  148. }
  149. return true;
  150. }
  151. /*}}}*/
  152. // GetLock - Gets a lock file /*{{{*/
  153. // ---------------------------------------------------------------------
  154. /* This will create an empty file of the given name and lock it. Once this
  155. is done all other calls to GetLock in any other process will fail with
  156. -1. The return result is the fd of the file, the call should call
  157. close at some time. */
  158. int GetLock(string File,bool Errors)
  159. {
  160. // GetLock() is used in aptitude on directories with public-write access
  161. // Use O_NOFOLLOW here to prevent symlink traversal attacks
  162. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
  163. if (FD < 0)
  164. {
  165. // Read only .. can't have locking problems there.
  166. if (errno == EROFS)
  167. {
  168. _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
  169. return dup(0); // Need something for the caller to close
  170. }
  171. if (Errors == true)
  172. _error->Errno("open",_("Could not open lock file %s"),File.c_str());
  173. // Feh.. We do this to distinguish the lock vs open case..
  174. errno = EPERM;
  175. return -1;
  176. }
  177. SetCloseExec(FD,true);
  178. // Acquire a write lock
  179. struct flock fl;
  180. fl.l_type = F_WRLCK;
  181. fl.l_whence = SEEK_SET;
  182. fl.l_start = 0;
  183. fl.l_len = 0;
  184. if (fcntl(FD,F_SETLK,&fl) == -1)
  185. {
  186. // always close to not leak resources
  187. int Tmp = errno;
  188. close(FD);
  189. errno = Tmp;
  190. if (errno == ENOLCK)
  191. {
  192. _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
  193. return dup(0); // Need something for the caller to close
  194. }
  195. if (Errors == true)
  196. _error->Errno("open",_("Could not get lock %s"),File.c_str());
  197. return -1;
  198. }
  199. return FD;
  200. }
  201. /*}}}*/
  202. // FileExists - Check if a file exists /*{{{*/
  203. // ---------------------------------------------------------------------
  204. /* Beware: Directories are also files! */
  205. bool FileExists(string File)
  206. {
  207. struct stat Buf;
  208. if (stat(File.c_str(),&Buf) != 0)
  209. return false;
  210. return true;
  211. }
  212. /*}}}*/
  213. // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
  214. // ---------------------------------------------------------------------
  215. /* */
  216. bool RealFileExists(string File)
  217. {
  218. struct stat Buf;
  219. if (stat(File.c_str(),&Buf) != 0)
  220. return false;
  221. return ((Buf.st_mode & S_IFREG) != 0);
  222. }
  223. /*}}}*/
  224. // DirectoryExists - Check if a directory exists and is really one /*{{{*/
  225. // ---------------------------------------------------------------------
  226. /* */
  227. bool DirectoryExists(string const &Path)
  228. {
  229. struct stat Buf;
  230. if (stat(Path.c_str(),&Buf) != 0)
  231. return false;
  232. return ((Buf.st_mode & S_IFDIR) != 0);
  233. }
  234. /*}}}*/
  235. // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
  236. // ---------------------------------------------------------------------
  237. /* This method will create all directories needed for path in good old
  238. mkdir -p style but refuses to do this if Parent is not a prefix of
  239. this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
  240. so it will create apt/archives if /var/cache exists - on the other
  241. hand if the parent is /var/lib the creation will fail as this path
  242. is not a parent of the path to be generated. */
  243. bool CreateDirectory(string const &Parent, string const &Path)
  244. {
  245. if (Parent.empty() == true || Path.empty() == true)
  246. return false;
  247. if (DirectoryExists(Path) == true)
  248. return true;
  249. if (DirectoryExists(Parent) == false)
  250. return false;
  251. // we are not going to create directories "into the blue"
  252. if (Path.compare(0, Parent.length(), Parent) != 0)
  253. return false;
  254. vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
  255. string progress = Parent;
  256. for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
  257. {
  258. if (d->empty() == true)
  259. continue;
  260. progress.append("/").append(*d);
  261. if (DirectoryExists(progress) == true)
  262. continue;
  263. if (mkdir(progress.c_str(), 0755) != 0)
  264. return false;
  265. }
  266. return true;
  267. }
  268. /*}}}*/
  269. // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
  270. // ---------------------------------------------------------------------
  271. /* a small wrapper around CreateDirectory to check if it exists and to
  272. remove the trailing "/apt/" from the parent directory if needed */
  273. bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path)
  274. {
  275. if (DirectoryExists(Path) == true)
  276. return true;
  277. size_t const len = Parent.size();
  278. if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
  279. {
  280. if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
  281. return true;
  282. }
  283. else if (CreateDirectory(Parent, Path) == true)
  284. return true;
  285. return false;
  286. }
  287. /*}}}*/
  288. // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
  289. // ---------------------------------------------------------------------
  290. /* If an extension is given only files with this extension are included
  291. in the returned vector, otherwise every "normal" file is included. */
  292. std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
  293. bool const &SortList, bool const &AllowNoExt)
  294. {
  295. std::vector<string> ext;
  296. ext.reserve(2);
  297. if (Ext.empty() == false)
  298. ext.push_back(Ext);
  299. if (AllowNoExt == true && ext.empty() == false)
  300. ext.push_back("");
  301. return GetListOfFilesInDir(Dir, ext, SortList);
  302. }
  303. std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
  304. bool const &SortList)
  305. {
  306. // Attention debuggers: need to be set with the environment config file!
  307. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  308. if (Debug == true)
  309. {
  310. std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
  311. if (Ext.empty() == true)
  312. std::clog << "\tNO extension" << std::endl;
  313. else
  314. for (std::vector<string>::const_iterator e = Ext.begin();
  315. e != Ext.end(); ++e)
  316. std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
  317. }
  318. std::vector<string> List;
  319. if (DirectoryExists(Dir) == false)
  320. {
  321. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  322. return List;
  323. }
  324. Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
  325. DIR *D = opendir(Dir.c_str());
  326. if (D == 0)
  327. {
  328. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  329. return List;
  330. }
  331. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  332. {
  333. // skip "hidden" files
  334. if (Ent->d_name[0] == '.')
  335. continue;
  336. // Make sure it is a file and not something else
  337. string const File = flCombine(Dir,Ent->d_name);
  338. #ifdef _DIRENT_HAVE_D_TYPE
  339. if (Ent->d_type != DT_REG)
  340. #endif
  341. {
  342. if (RealFileExists(File) == false)
  343. {
  344. // do not show ignoration warnings for directories
  345. if (
  346. #ifdef _DIRENT_HAVE_D_TYPE
  347. Ent->d_type == DT_DIR ||
  348. #endif
  349. DirectoryExists(File) == true)
  350. continue;
  351. if (SilentIgnore.Match(Ent->d_name) == false)
  352. _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
  353. continue;
  354. }
  355. }
  356. // check for accepted extension:
  357. // no extension given -> periods are bad as hell!
  358. // extensions given -> "" extension allows no extension
  359. if (Ext.empty() == false)
  360. {
  361. string d_ext = flExtension(Ent->d_name);
  362. if (d_ext == Ent->d_name) // no extension
  363. {
  364. if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
  365. {
  366. if (Debug == true)
  367. std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
  368. if (SilentIgnore.Match(Ent->d_name) == false)
  369. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
  370. continue;
  371. }
  372. }
  373. else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
  374. {
  375. if (Debug == true)
  376. std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
  377. if (SilentIgnore.Match(Ent->d_name) == false)
  378. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
  379. continue;
  380. }
  381. }
  382. // Skip bad filenames ala run-parts
  383. const char *C = Ent->d_name;
  384. for (; *C != 0; ++C)
  385. if (isalpha(*C) == 0 && isdigit(*C) == 0
  386. && *C != '_' && *C != '-' && *C != ':') {
  387. // no required extension -> dot is a bad character
  388. if (*C == '.' && Ext.empty() == false)
  389. continue;
  390. break;
  391. }
  392. // we don't reach the end of the name -> bad character included
  393. if (*C != 0)
  394. {
  395. if (Debug == true)
  396. std::clog << "Bad file: " << Ent->d_name << " → bad character »"
  397. << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
  398. continue;
  399. }
  400. // skip filenames which end with a period. These are never valid
  401. if (*(C - 1) == '.')
  402. {
  403. if (Debug == true)
  404. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  405. continue;
  406. }
  407. if (Debug == true)
  408. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  409. List.push_back(File);
  410. }
  411. closedir(D);
  412. if (SortList == true)
  413. std::sort(List.begin(),List.end());
  414. return List;
  415. }
  416. std::vector<string> GetListOfFilesInDir(string const &Dir, bool SortList)
  417. {
  418. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  419. if (Debug == true)
  420. std::clog << "Accept in " << Dir << " all regular files" << std::endl;
  421. std::vector<string> List;
  422. if (DirectoryExists(Dir) == false)
  423. {
  424. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  425. return List;
  426. }
  427. DIR *D = opendir(Dir.c_str());
  428. if (D == 0)
  429. {
  430. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  431. return List;
  432. }
  433. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  434. {
  435. // skip "hidden" files
  436. if (Ent->d_name[0] == '.')
  437. continue;
  438. // Make sure it is a file and not something else
  439. string const File = flCombine(Dir,Ent->d_name);
  440. #ifdef _DIRENT_HAVE_D_TYPE
  441. if (Ent->d_type != DT_REG)
  442. #endif
  443. {
  444. if (RealFileExists(File) == false)
  445. {
  446. if (Debug == true)
  447. std::clog << "Bad file: " << Ent->d_name << " → it is not a real file" << std::endl;
  448. continue;
  449. }
  450. }
  451. // Skip bad filenames ala run-parts
  452. const char *C = Ent->d_name;
  453. for (; *C != 0; ++C)
  454. if (isalpha(*C) == 0 && isdigit(*C) == 0
  455. && *C != '_' && *C != '-' && *C != '.')
  456. break;
  457. // we don't reach the end of the name -> bad character included
  458. if (*C != 0)
  459. {
  460. if (Debug == true)
  461. std::clog << "Bad file: " << Ent->d_name << " → bad character »" << *C << "« in filename" << std::endl;
  462. continue;
  463. }
  464. // skip filenames which end with a period. These are never valid
  465. if (*(C - 1) == '.')
  466. {
  467. if (Debug == true)
  468. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  469. continue;
  470. }
  471. if (Debug == true)
  472. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  473. List.push_back(File);
  474. }
  475. closedir(D);
  476. if (SortList == true)
  477. std::sort(List.begin(),List.end());
  478. return List;
  479. }
  480. /*}}}*/
  481. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  482. // ---------------------------------------------------------------------
  483. /* We return / on failure. */
  484. string SafeGetCWD()
  485. {
  486. // Stash the current dir.
  487. char S[300];
  488. S[0] = 0;
  489. if (getcwd(S,sizeof(S)-2) == 0)
  490. return "/";
  491. unsigned int Len = strlen(S);
  492. S[Len] = '/';
  493. S[Len+1] = 0;
  494. return S;
  495. }
  496. /*}}}*/
  497. // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
  498. // ---------------------------------------------------------------------
  499. /* We return / on failure. */
  500. time_t GetModificationTime(string const &Path)
  501. {
  502. struct stat St;
  503. if (stat(Path.c_str(), &St) < 0)
  504. return -1;
  505. return St.st_mtime;
  506. }
  507. /*}}}*/
  508. // flNotDir - Strip the directory from the filename /*{{{*/
  509. // ---------------------------------------------------------------------
  510. /* */
  511. string flNotDir(string File)
  512. {
  513. string::size_type Res = File.rfind('/');
  514. if (Res == string::npos)
  515. return File;
  516. Res++;
  517. return string(File,Res,Res - File.length());
  518. }
  519. /*}}}*/
  520. // flNotFile - Strip the file from the directory name /*{{{*/
  521. // ---------------------------------------------------------------------
  522. /* Result ends in a / */
  523. string flNotFile(string File)
  524. {
  525. string::size_type Res = File.rfind('/');
  526. if (Res == string::npos)
  527. return "./";
  528. Res++;
  529. return string(File,0,Res);
  530. }
  531. /*}}}*/
  532. // flExtension - Return the extension for the file /*{{{*/
  533. // ---------------------------------------------------------------------
  534. /* */
  535. string flExtension(string File)
  536. {
  537. string::size_type Res = File.rfind('.');
  538. if (Res == string::npos)
  539. return File;
  540. Res++;
  541. return string(File,Res,Res - File.length());
  542. }
  543. /*}}}*/
  544. // flNoLink - If file is a symlink then deref it /*{{{*/
  545. // ---------------------------------------------------------------------
  546. /* If the name is not a link then the returned path is the input. */
  547. string flNoLink(string File)
  548. {
  549. struct stat St;
  550. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  551. return File;
  552. if (stat(File.c_str(),&St) != 0)
  553. return File;
  554. /* Loop resolving the link. There is no need to limit the number of
  555. loops because the stat call above ensures that the symlink is not
  556. circular */
  557. char Buffer[1024];
  558. string NFile = File;
  559. while (1)
  560. {
  561. // Read the link
  562. ssize_t Res;
  563. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  564. (size_t)Res >= sizeof(Buffer))
  565. return File;
  566. // Append or replace the previous path
  567. Buffer[Res] = 0;
  568. if (Buffer[0] == '/')
  569. NFile = Buffer;
  570. else
  571. NFile = flNotFile(NFile) + Buffer;
  572. // See if we are done
  573. if (lstat(NFile.c_str(),&St) != 0)
  574. return File;
  575. if (S_ISLNK(St.st_mode) == 0)
  576. return NFile;
  577. }
  578. }
  579. /*}}}*/
  580. // flCombine - Combine a file and a directory /*{{{*/
  581. // ---------------------------------------------------------------------
  582. /* If the file is an absolute path then it is just returned, otherwise
  583. the directory is pre-pended to it. */
  584. string flCombine(string Dir,string File)
  585. {
  586. if (File.empty() == true)
  587. return string();
  588. if (File[0] == '/' || Dir.empty() == true)
  589. return File;
  590. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  591. return File;
  592. if (Dir[Dir.length()-1] == '/')
  593. return Dir + File;
  594. return Dir + '/' + File;
  595. }
  596. /*}}}*/
  597. // flAbsPath - Return the absolute path of the filename /*{{{*/
  598. // ---------------------------------------------------------------------
  599. /* */
  600. string flAbsPath(string File)
  601. {
  602. char *p = realpath(File.c_str(), NULL);
  603. if (p == NULL)
  604. {
  605. _error->Errno("realpath", "flAbsPath failed");
  606. return "";
  607. }
  608. std::string AbsPath(p);
  609. free(p);
  610. return AbsPath;
  611. }
  612. /*}}}*/
  613. // SetCloseExec - Set the close on exec flag /*{{{*/
  614. // ---------------------------------------------------------------------
  615. /* */
  616. void SetCloseExec(int Fd,bool Close)
  617. {
  618. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  619. {
  620. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  621. exit(100);
  622. }
  623. }
  624. /*}}}*/
  625. // SetNonBlock - Set the nonblocking flag /*{{{*/
  626. // ---------------------------------------------------------------------
  627. /* */
  628. void SetNonBlock(int Fd,bool Block)
  629. {
  630. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  631. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  632. {
  633. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  634. exit(100);
  635. }
  636. }
  637. /*}}}*/
  638. // WaitFd - Wait for a FD to become readable /*{{{*/
  639. // ---------------------------------------------------------------------
  640. /* This waits for a FD to become readable using select. It is useful for
  641. applications making use of non-blocking sockets. The timeout is
  642. in seconds. */
  643. bool WaitFd(int Fd,bool write,unsigned long timeout)
  644. {
  645. fd_set Set;
  646. struct timeval tv;
  647. FD_ZERO(&Set);
  648. FD_SET(Fd,&Set);
  649. tv.tv_sec = timeout;
  650. tv.tv_usec = 0;
  651. if (write == true)
  652. {
  653. int Res;
  654. do
  655. {
  656. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  657. }
  658. while (Res < 0 && errno == EINTR);
  659. if (Res <= 0)
  660. return false;
  661. }
  662. else
  663. {
  664. int Res;
  665. do
  666. {
  667. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  668. }
  669. while (Res < 0 && errno == EINTR);
  670. if (Res <= 0)
  671. return false;
  672. }
  673. return true;
  674. }
  675. /*}}}*/
  676. // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
  677. // ---------------------------------------------------------------------
  678. /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
  679. * set.
  680. */
  681. void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs)
  682. {
  683. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  684. if (Opts != 0 && Opts->Child != 0)
  685. {
  686. Opts = Opts->Child;
  687. for (; Opts != 0; Opts = Opts->Next)
  688. {
  689. if (Opts->Value.empty() == true)
  690. continue;
  691. int fd = atoi(Opts->Value.c_str());
  692. KeepFDs.insert(fd);
  693. }
  694. }
  695. }
  696. /*}}}*/
  697. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  698. // ---------------------------------------------------------------------
  699. /* This is used if you want to cleanse the environment for the forked
  700. child, it fixes up the important signals and nukes all of the fds,
  701. otherwise acts like normal fork. */
  702. pid_t ExecFork()
  703. {
  704. set<int> KeepFDs;
  705. // we need to merge the Keep-Fds as external tools like
  706. // debconf-apt-progress use it
  707. MergeKeepFdsFromConfiguration(KeepFDs);
  708. return ExecFork(KeepFDs);
  709. }
  710. pid_t ExecFork(std::set<int> KeepFDs)
  711. {
  712. // Fork off the process
  713. pid_t Process = fork();
  714. if (Process < 0)
  715. {
  716. cerr << "FATAL -> Failed to fork." << endl;
  717. exit(100);
  718. }
  719. // Spawn the subprocess
  720. if (Process == 0)
  721. {
  722. // Setup the signals
  723. signal(SIGPIPE,SIG_DFL);
  724. signal(SIGQUIT,SIG_DFL);
  725. signal(SIGINT,SIG_DFL);
  726. signal(SIGWINCH,SIG_DFL);
  727. signal(SIGCONT,SIG_DFL);
  728. signal(SIGTSTP,SIG_DFL);
  729. DIR *dir = opendir("/proc/self/fd");
  730. if (dir != NULL)
  731. {
  732. struct dirent *ent;
  733. while ((ent = readdir(dir)))
  734. {
  735. int fd = atoi(ent->d_name);
  736. // If fd > 0, it was a fd number and not . or ..
  737. if (fd >= 3 && KeepFDs.find(fd) == KeepFDs.end())
  738. fcntl(fd,F_SETFD,FD_CLOEXEC);
  739. }
  740. closedir(dir);
  741. } else {
  742. long ScOpenMax = sysconf(_SC_OPEN_MAX);
  743. // Close all of our FDs - just in case
  744. for (int K = 3; K != ScOpenMax; K++)
  745. {
  746. if(KeepFDs.find(K) == KeepFDs.end())
  747. fcntl(K,F_SETFD,FD_CLOEXEC);
  748. }
  749. }
  750. }
  751. return Process;
  752. }
  753. /*}}}*/
  754. // ExecWait - Fancy waitpid /*{{{*/
  755. // ---------------------------------------------------------------------
  756. /* Waits for the given sub process. If Reap is set then no errors are
  757. generated. Otherwise a failed subprocess will generate a proper descriptive
  758. message */
  759. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  760. {
  761. if (Pid <= 1)
  762. return true;
  763. // Wait and collect the error code
  764. int Status;
  765. while (waitpid(Pid,&Status,0) != Pid)
  766. {
  767. if (errno == EINTR)
  768. continue;
  769. if (Reap == true)
  770. return false;
  771. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  772. }
  773. // Check for an error code.
  774. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  775. {
  776. if (Reap == true)
  777. return false;
  778. if (WIFSIGNALED(Status) != 0)
  779. {
  780. if( WTERMSIG(Status) == SIGSEGV)
  781. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  782. else
  783. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  784. }
  785. if (WIFEXITED(Status) != 0)
  786. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  787. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  788. }
  789. return true;
  790. }
  791. /*}}}*/
  792. // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
  793. bool StartsWithGPGClearTextSignature(string const &FileName)
  794. {
  795. static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
  796. char buffer[strlen(SIGMSG)+1];
  797. FILE* gpg = fopen(FileName.c_str(), "r");
  798. if (gpg == NULL)
  799. return false;
  800. char const * const test = fgets(buffer, sizeof(buffer), gpg);
  801. fclose(gpg);
  802. if (test == NULL || strcmp(buffer, SIGMSG) != 0)
  803. return false;
  804. return true;
  805. }
  806. /*}}}*/
  807. // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
  808. bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
  809. {
  810. if (strcmp(file, "/dev/null") == 0)
  811. return true;
  812. bool Res = true;
  813. if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it
  814. {
  815. // ensure the file is owned by root and has good permissions
  816. struct passwd const * const pw = getpwnam(user);
  817. struct group const * const gr = getgrnam(group);
  818. if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
  819. Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
  820. }
  821. if (chmod(file, mode) != 0)
  822. Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
  823. return Res;
  824. }
  825. /*}}}*/
  826. class FileFdPrivate { /*{{{*/
  827. public:
  828. #ifdef HAVE_ZLIB
  829. gzFile gz;
  830. #endif
  831. #ifdef HAVE_BZ2
  832. BZFILE* bz2;
  833. #endif
  834. #ifdef HAVE_LZMA
  835. struct LZMAFILE {
  836. FILE* file;
  837. uint8_t buffer[4096];
  838. lzma_stream stream;
  839. lzma_ret err;
  840. bool eof;
  841. bool compressing;
  842. LZMAFILE() : file(NULL), eof(false), compressing(false) { buffer[0] = '\0'; }
  843. ~LZMAFILE() {
  844. if (compressing == true)
  845. {
  846. for (;;) {
  847. stream.avail_out = sizeof(buffer)/sizeof(buffer[0]);
  848. stream.next_out = buffer;
  849. err = lzma_code(&stream, LZMA_FINISH);
  850. if (err != LZMA_OK && err != LZMA_STREAM_END)
  851. {
  852. _error->Error("~LZMAFILE: Compress finalisation failed");
  853. break;
  854. }
  855. size_t const n = sizeof(buffer)/sizeof(buffer[0]) - stream.avail_out;
  856. if (n && fwrite(buffer, 1, n, file) != n)
  857. {
  858. _error->Errno("~LZMAFILE",_("Write error"));
  859. break;
  860. }
  861. if (err == LZMA_STREAM_END)
  862. break;
  863. }
  864. }
  865. lzma_end(&stream);
  866. fclose(file);
  867. }
  868. };
  869. LZMAFILE* lzma;
  870. #endif
  871. int compressed_fd;
  872. pid_t compressor_pid;
  873. bool pipe;
  874. APT::Configuration::Compressor compressor;
  875. unsigned int openmode;
  876. unsigned long long seekpos;
  877. FileFdPrivate() :
  878. #ifdef HAVE_ZLIB
  879. gz(NULL),
  880. #endif
  881. #ifdef HAVE_BZ2
  882. bz2(NULL),
  883. #endif
  884. #ifdef HAVE_LZMA
  885. lzma(NULL),
  886. #endif
  887. compressed_fd(-1), compressor_pid(-1), pipe(false),
  888. openmode(0), seekpos(0) {};
  889. bool InternalClose(std::string const &FileName)
  890. {
  891. if (false)
  892. /* dummy so that the rest can be 'else if's */;
  893. #ifdef HAVE_ZLIB
  894. else if (gz != NULL) {
  895. int const e = gzclose(gz);
  896. gz = NULL;
  897. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  898. if (e != 0 && e != Z_BUF_ERROR)
  899. return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  900. }
  901. #endif
  902. #ifdef HAVE_BZ2
  903. else if (bz2 != NULL) {
  904. BZ2_bzclose(bz2);
  905. bz2 = NULL;
  906. }
  907. #endif
  908. #ifdef HAVE_LZMA
  909. else if (lzma != NULL) {
  910. delete lzma;
  911. lzma = NULL;
  912. }
  913. #endif
  914. return true;
  915. }
  916. bool CloseDown(std::string const &FileName)
  917. {
  918. bool const Res = InternalClose(FileName);
  919. if (compressor_pid > 0)
  920. ExecWait(compressor_pid, "FileFdCompressor", true);
  921. compressor_pid = -1;
  922. return Res;
  923. }
  924. bool InternalStream() const {
  925. return false
  926. #ifdef HAVE_BZ2
  927. || bz2 != NULL
  928. #endif
  929. #ifdef HAVE_LZMA
  930. || lzma != NULL
  931. #endif
  932. ;
  933. }
  934. ~FileFdPrivate() { CloseDown(""); }
  935. };
  936. /*}}}*/
  937. // FileFd Constructors /*{{{*/
  938. FileFd::FileFd(std::string FileName,unsigned int const Mode,unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  939. {
  940. Open(FileName,Mode, None, AccessMode);
  941. }
  942. FileFd::FileFd(std::string FileName,unsigned int const Mode, CompressMode Compress, unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  943. {
  944. Open(FileName,Mode, Compress, AccessMode);
  945. }
  946. FileFd::FileFd() : iFd(-1), Flags(AutoClose), d(NULL) {}
  947. FileFd::FileFd(int const Fd, unsigned int const Mode, CompressMode Compress) : iFd(-1), Flags(0), d(NULL)
  948. {
  949. OpenDescriptor(Fd, Mode, Compress);
  950. }
  951. FileFd::FileFd(int const Fd, bool const AutoClose) : iFd(-1), Flags(0), d(NULL)
  952. {
  953. OpenDescriptor(Fd, ReadWrite, None, AutoClose);
  954. }
  955. /*}}}*/
  956. // FileFd::Open - Open a file /*{{{*/
  957. // ---------------------------------------------------------------------
  958. /* The most commonly used open mode combinations are given with Mode */
  959. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
  960. {
  961. if (Mode == ReadOnlyGzip)
  962. return Open(FileName, ReadOnly, Gzip, AccessMode);
  963. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  964. return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  965. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  966. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  967. if (Compress == Auto)
  968. {
  969. for (; compressor != compressors.end(); ++compressor)
  970. {
  971. std::string file = FileName + compressor->Extension;
  972. if (FileExists(file) == false)
  973. continue;
  974. FileName = file;
  975. break;
  976. }
  977. }
  978. else if (Compress == Extension)
  979. {
  980. std::string::size_type const found = FileName.find_last_of('.');
  981. std::string ext;
  982. if (found != std::string::npos)
  983. {
  984. ext = FileName.substr(found);
  985. if (ext == ".new" || ext == ".bak")
  986. {
  987. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  988. if (found2 != std::string::npos)
  989. ext = FileName.substr(found2, found - found2);
  990. else
  991. ext.clear();
  992. }
  993. }
  994. for (; compressor != compressors.end(); ++compressor)
  995. if (ext == compressor->Extension)
  996. break;
  997. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  998. if (compressor == compressors.end())
  999. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  1000. if (compressor->Name == ".")
  1001. break;
  1002. }
  1003. else
  1004. {
  1005. std::string name;
  1006. switch (Compress)
  1007. {
  1008. case None: name = "."; break;
  1009. case Gzip: name = "gzip"; break;
  1010. case Bzip2: name = "bzip2"; break;
  1011. case Lzma: name = "lzma"; break;
  1012. case Xz: name = "xz"; break;
  1013. case Auto:
  1014. case Extension:
  1015. // Unreachable
  1016. return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  1017. }
  1018. for (; compressor != compressors.end(); ++compressor)
  1019. if (compressor->Name == name)
  1020. break;
  1021. if (compressor == compressors.end())
  1022. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  1023. }
  1024. if (compressor == compressors.end())
  1025. return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  1026. return Open(FileName, Mode, *compressor, AccessMode);
  1027. }
  1028. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
  1029. {
  1030. Close();
  1031. Flags = AutoClose;
  1032. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  1033. return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  1034. if ((Mode & ReadWrite) == 0)
  1035. return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
  1036. if ((Mode & Atomic) == Atomic)
  1037. {
  1038. Flags |= Replace;
  1039. }
  1040. else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
  1041. {
  1042. // for atomic, this will be done by rename in Close()
  1043. unlink(FileName.c_str());
  1044. }
  1045. if ((Mode & Empty) == Empty)
  1046. {
  1047. struct stat Buf;
  1048. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  1049. unlink(FileName.c_str());
  1050. }
  1051. int fileflags = 0;
  1052. #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
  1053. if_FLAGGED_SET(ReadWrite, O_RDWR);
  1054. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  1055. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  1056. if_FLAGGED_SET(Create, O_CREAT);
  1057. if_FLAGGED_SET(Empty, O_TRUNC);
  1058. if_FLAGGED_SET(Exclusive, O_EXCL);
  1059. #undef if_FLAGGED_SET
  1060. if ((Mode & Atomic) == Atomic)
  1061. {
  1062. char *name = strdup((FileName + ".XXXXXX").c_str());
  1063. if((iFd = mkstemp(name)) == -1)
  1064. {
  1065. free(name);
  1066. return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
  1067. }
  1068. TemporaryFileName = string(name);
  1069. free(name);
  1070. // umask() will always set the umask and return the previous value, so
  1071. // we first set the umask and then reset it to the old value
  1072. mode_t const CurrentUmask = umask(0);
  1073. umask(CurrentUmask);
  1074. // calculate the actual file permissions (just like open/creat)
  1075. mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
  1076. if(fchmod(iFd, FilePermissions) == -1)
  1077. return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
  1078. }
  1079. else
  1080. iFd = open(FileName.c_str(), fileflags, AccessMode);
  1081. this->FileName = FileName;
  1082. if (iFd == -1 || OpenInternDescriptor(Mode, compressor) == false)
  1083. {
  1084. if (iFd != -1)
  1085. {
  1086. close (iFd);
  1087. iFd = -1;
  1088. }
  1089. return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
  1090. }
  1091. SetCloseExec(iFd,true);
  1092. return true;
  1093. }
  1094. /*}}}*/
  1095. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  1096. // ---------------------------------------------------------------------
  1097. /* */
  1098. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  1099. {
  1100. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  1101. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  1102. std::string name;
  1103. // compat with the old API
  1104. if (Mode == ReadOnlyGzip && Compress == None)
  1105. Compress = Gzip;
  1106. switch (Compress)
  1107. {
  1108. case None: name = "."; break;
  1109. case Gzip: name = "gzip"; break;
  1110. case Bzip2: name = "bzip2"; break;
  1111. case Lzma: name = "lzma"; break;
  1112. case Xz: name = "xz"; break;
  1113. case Auto:
  1114. case Extension:
  1115. if (AutoClose == true && Fd != -1)
  1116. close(Fd);
  1117. return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  1118. }
  1119. for (; compressor != compressors.end(); ++compressor)
  1120. if (compressor->Name == name)
  1121. break;
  1122. if (compressor == compressors.end())
  1123. {
  1124. if (AutoClose == true && Fd != -1)
  1125. close(Fd);
  1126. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  1127. }
  1128. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  1129. }
  1130. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  1131. {
  1132. Close();
  1133. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  1134. iFd = Fd;
  1135. this->FileName = "";
  1136. if (OpenInternDescriptor(Mode, compressor) == false)
  1137. {
  1138. if (iFd != -1 && (
  1139. (Flags & Compressed) == Compressed ||
  1140. AutoClose == true))
  1141. {
  1142. close (iFd);
  1143. iFd = -1;
  1144. }
  1145. return FileFdError(_("Could not open file descriptor %d"), Fd);
  1146. }
  1147. return true;
  1148. }
  1149. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  1150. {
  1151. if (iFd == -1)
  1152. return false;
  1153. if (compressor.Name == "." || compressor.Binary.empty() == true)
  1154. return true;
  1155. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1156. // the API to open files is similar, so setup to avoid code duplicates later
  1157. // and while at it ensure that we close before opening (if its a reopen)
  1158. void* (*compress_open)(int, const char *) = NULL;
  1159. if (false)
  1160. /* dummy so that the rest can be 'else if's */;
  1161. #define APT_COMPRESS_INIT(NAME,OPEN) \
  1162. else if (compressor.Name == NAME) \
  1163. { \
  1164. compress_open = (void*(*)(int, const char *)) OPEN; \
  1165. if (d != NULL) d->InternalClose(FileName); \
  1166. }
  1167. #ifdef HAVE_ZLIB
  1168. APT_COMPRESS_INIT("gzip", gzdopen)
  1169. #endif
  1170. #ifdef HAVE_BZ2
  1171. APT_COMPRESS_INIT("bzip2", BZ2_bzdopen)
  1172. #endif
  1173. #ifdef HAVE_LZMA
  1174. APT_COMPRESS_INIT("xz", fdopen)
  1175. APT_COMPRESS_INIT("lzma", fdopen)
  1176. #endif
  1177. #undef APT_COMPRESS_INIT
  1178. #endif
  1179. if (d == NULL)
  1180. {
  1181. d = new FileFdPrivate();
  1182. d->openmode = Mode;
  1183. d->compressor = compressor;
  1184. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1185. if ((Flags & AutoClose) != AutoClose && compress_open != NULL)
  1186. {
  1187. // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
  1188. int const internFd = dup(iFd);
  1189. if (internFd == -1)
  1190. return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
  1191. iFd = internFd;
  1192. }
  1193. #endif
  1194. }
  1195. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1196. if (compress_open != NULL)
  1197. {
  1198. void* compress_struct = NULL;
  1199. if ((Mode & ReadWrite) == ReadWrite)
  1200. compress_struct = compress_open(iFd, "r+");
  1201. else if ((Mode & WriteOnly) == WriteOnly)
  1202. compress_struct = compress_open(iFd, "w");
  1203. else
  1204. compress_struct = compress_open(iFd, "r");
  1205. if (compress_struct == NULL)
  1206. return false;
  1207. if (false)
  1208. /* dummy so that the rest can be 'else if's */;
  1209. #ifdef HAVE_ZLIB
  1210. else if (compressor.Name == "gzip")
  1211. d->gz = (gzFile) compress_struct;
  1212. #endif
  1213. #ifdef HAVE_BZ2
  1214. else if (compressor.Name == "bzip2")
  1215. d->bz2 = (BZFILE*) compress_struct;
  1216. #endif
  1217. #ifdef HAVE_LZMA
  1218. else if (compressor.Name == "xz" || compressor.Name == "lzma")
  1219. {
  1220. uint32_t const xzlevel = 6;
  1221. uint64_t const memlimit = UINT64_MAX;
  1222. if (d->lzma == NULL)
  1223. d->lzma = new FileFdPrivate::LZMAFILE;
  1224. d->lzma->file = (FILE*) compress_struct;
  1225. lzma_stream tmp_stream = LZMA_STREAM_INIT;
  1226. d->lzma->stream = tmp_stream;
  1227. if ((Mode & ReadWrite) == ReadWrite)
  1228. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1229. if ((Mode & WriteOnly) == WriteOnly)
  1230. {
  1231. if (compressor.Name == "xz")
  1232. {
  1233. if (lzma_easy_encoder(&d->lzma->stream, xzlevel, LZMA_CHECK_CRC32) != LZMA_OK)
  1234. return false;
  1235. }
  1236. else
  1237. {
  1238. lzma_options_lzma options;
  1239. lzma_lzma_preset(&options, xzlevel);
  1240. if (lzma_alone_encoder(&d->lzma->stream, &options) != LZMA_OK)
  1241. return false;
  1242. }
  1243. d->lzma->compressing = true;
  1244. }
  1245. else
  1246. {
  1247. if (compressor.Name == "xz")
  1248. {
  1249. if (lzma_auto_decoder(&d->lzma->stream, memlimit, 0) != LZMA_OK)
  1250. return false;
  1251. }
  1252. else
  1253. {
  1254. if (lzma_alone_decoder(&d->lzma->stream, memlimit) != LZMA_OK)
  1255. return false;
  1256. }
  1257. d->lzma->compressing = false;
  1258. }
  1259. }
  1260. #endif
  1261. Flags |= Compressed;
  1262. return true;
  1263. }
  1264. #endif
  1265. // collect zombies here in case we reopen
  1266. if (d->compressor_pid > 0)
  1267. ExecWait(d->compressor_pid, "FileFdCompressor", true);
  1268. if ((Mode & ReadWrite) == ReadWrite)
  1269. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1270. bool const Comp = (Mode & WriteOnly) == WriteOnly;
  1271. if (Comp == false)
  1272. {
  1273. // Handle 'decompression' of empty files
  1274. struct stat Buf;
  1275. fstat(iFd, &Buf);
  1276. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1277. return true;
  1278. // We don't need the file open - instead let the compressor open it
  1279. // as he properly knows better how to efficiently read from 'his' file
  1280. if (FileName.empty() == false)
  1281. {
  1282. close(iFd);
  1283. iFd = -1;
  1284. }
  1285. }
  1286. // Create a data pipe
  1287. int Pipe[2] = {-1,-1};
  1288. if (pipe(Pipe) != 0)
  1289. return FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1290. for (int J = 0; J != 2; J++)
  1291. SetCloseExec(Pipe[J],true);
  1292. d->compressed_fd = iFd;
  1293. d->pipe = true;
  1294. if (Comp == true)
  1295. iFd = Pipe[1];
  1296. else
  1297. iFd = Pipe[0];
  1298. // The child..
  1299. d->compressor_pid = ExecFork();
  1300. if (d->compressor_pid == 0)
  1301. {
  1302. if (Comp == true)
  1303. {
  1304. dup2(d->compressed_fd,STDOUT_FILENO);
  1305. dup2(Pipe[0],STDIN_FILENO);
  1306. }
  1307. else
  1308. {
  1309. if (d->compressed_fd != -1)
  1310. dup2(d->compressed_fd,STDIN_FILENO);
  1311. dup2(Pipe[1],STDOUT_FILENO);
  1312. }
  1313. int const nullfd = open("/dev/null", O_WRONLY);
  1314. if (nullfd != -1)
  1315. {
  1316. dup2(nullfd,STDERR_FILENO);
  1317. close(nullfd);
  1318. }
  1319. SetCloseExec(STDOUT_FILENO,false);
  1320. SetCloseExec(STDIN_FILENO,false);
  1321. std::vector<char const*> Args;
  1322. Args.push_back(compressor.Binary.c_str());
  1323. std::vector<std::string> const * const addArgs =
  1324. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1325. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1326. a != addArgs->end(); ++a)
  1327. Args.push_back(a->c_str());
  1328. if (Comp == false && FileName.empty() == false)
  1329. {
  1330. // commands not needing arguments, do not need to be told about using standard output
  1331. // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
  1332. if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
  1333. Args.push_back("--stdout");
  1334. if (TemporaryFileName.empty() == false)
  1335. Args.push_back(TemporaryFileName.c_str());
  1336. else
  1337. Args.push_back(FileName.c_str());
  1338. }
  1339. Args.push_back(NULL);
  1340. execvp(Args[0],(char **)&Args[0]);
  1341. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1342. _exit(100);
  1343. }
  1344. if (Comp == true)
  1345. close(Pipe[0]);
  1346. else
  1347. close(Pipe[1]);
  1348. return true;
  1349. }
  1350. /*}}}*/
  1351. // FileFd::~File - Closes the file /*{{{*/
  1352. // ---------------------------------------------------------------------
  1353. /* If the proper modes are selected then we close the Fd and possibly
  1354. unlink the file on error. */
  1355. FileFd::~FileFd()
  1356. {
  1357. Close();
  1358. if (d != NULL)
  1359. d->CloseDown(FileName);
  1360. delete d;
  1361. d = NULL;
  1362. }
  1363. /*}}}*/
  1364. // FileFd::Read - Read a bit of the file /*{{{*/
  1365. // ---------------------------------------------------------------------
  1366. /* We are careful to handle interruption by a signal while reading
  1367. gracefully. */
  1368. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  1369. {
  1370. ssize_t Res;
  1371. errno = 0;
  1372. if (Actual != 0)
  1373. *Actual = 0;
  1374. *((char *)To) = '\0';
  1375. do
  1376. {
  1377. if (false)
  1378. /* dummy so that the rest can be 'else if's */;
  1379. #ifdef HAVE_ZLIB
  1380. else if (d != NULL && d->gz != NULL)
  1381. Res = gzread(d->gz,To,Size);
  1382. #endif
  1383. #ifdef HAVE_BZ2
  1384. else if (d != NULL && d->bz2 != NULL)
  1385. Res = BZ2_bzread(d->bz2,To,Size);
  1386. #endif
  1387. #ifdef HAVE_LZMA
  1388. else if (d != NULL && d->lzma != NULL)
  1389. {
  1390. if (d->lzma->eof == true)
  1391. break;
  1392. d->lzma->stream.next_out = (uint8_t *) To;
  1393. d->lzma->stream.avail_out = Size;
  1394. if (d->lzma->stream.avail_in == 0)
  1395. {
  1396. d->lzma->stream.next_in = d->lzma->buffer;
  1397. d->lzma->stream.avail_in = fread(d->lzma->buffer, 1, sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]), d->lzma->file);
  1398. }
  1399. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1400. if (d->lzma->err == LZMA_STREAM_END)
  1401. {
  1402. d->lzma->eof = true;
  1403. Res = Size - d->lzma->stream.avail_out;
  1404. }
  1405. else if (d->lzma->err != LZMA_OK)
  1406. {
  1407. Res = -1;
  1408. errno = 0;
  1409. }
  1410. else
  1411. {
  1412. Res = Size - d->lzma->stream.avail_out;
  1413. if (Res == 0)
  1414. {
  1415. // lzma run was okay, but produced no output…
  1416. Res = -1;
  1417. errno = EINTR;
  1418. }
  1419. }
  1420. }
  1421. #endif
  1422. else
  1423. Res = read(iFd,To,Size);
  1424. if (Res < 0)
  1425. {
  1426. if (errno == EINTR)
  1427. {
  1428. // trick the while-loop into running again
  1429. Res = 1;
  1430. errno = 0;
  1431. continue;
  1432. }
  1433. if (false)
  1434. /* dummy so that the rest can be 'else if's */;
  1435. #ifdef HAVE_ZLIB
  1436. else if (d != NULL && d->gz != NULL)
  1437. {
  1438. int err;
  1439. char const * const errmsg = gzerror(d->gz, &err);
  1440. if (err != Z_ERRNO)
  1441. return FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1442. }
  1443. #endif
  1444. #ifdef HAVE_BZ2
  1445. else if (d != NULL && d->bz2 != NULL)
  1446. {
  1447. int err;
  1448. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1449. if (err != BZ_IO_ERROR)
  1450. return FileFdError("BZ2_bzread: %s %s (%d: %s)", FileName.c_str(), _("Read error"), err, errmsg);
  1451. }
  1452. #endif
  1453. #ifdef HAVE_LZMA
  1454. else if (d != NULL && d->lzma != NULL)
  1455. return FileFdError("lzma_read: %s (%d)", _("Read error"), d->lzma->err);
  1456. #endif
  1457. return FileFdErrno("read",_("Read error"));
  1458. }
  1459. To = (char *)To + Res;
  1460. Size -= Res;
  1461. if (d != NULL)
  1462. d->seekpos += Res;
  1463. if (Actual != 0)
  1464. *Actual += Res;
  1465. }
  1466. while (Res > 0 && Size > 0);
  1467. if (Size == 0)
  1468. return true;
  1469. // Eof handling
  1470. if (Actual != 0)
  1471. {
  1472. Flags |= HitEof;
  1473. return true;
  1474. }
  1475. return FileFdError(_("read, still have %llu to read but none left"), Size);
  1476. }
  1477. /*}}}*/
  1478. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  1479. // ---------------------------------------------------------------------
  1480. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  1481. files because of the naive implementation! */
  1482. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  1483. {
  1484. *To = '\0';
  1485. #ifdef HAVE_ZLIB
  1486. if (d != NULL && d->gz != NULL)
  1487. return gzgets(d->gz, To, Size);
  1488. #endif
  1489. unsigned long long read = 0;
  1490. while ((Size - 1) != read)
  1491. {
  1492. unsigned long long done = 0;
  1493. if (Read(To + read, 1, &done) == false)
  1494. return NULL;
  1495. if (done == 0)
  1496. break;
  1497. if (To[read++] == '\n')
  1498. break;
  1499. }
  1500. if (read == 0)
  1501. return NULL;
  1502. To[read] = '\0';
  1503. return To;
  1504. }
  1505. /*}}}*/
  1506. // FileFd::Write - Write to the file /*{{{*/
  1507. // ---------------------------------------------------------------------
  1508. /* */
  1509. bool FileFd::Write(const void *From,unsigned long long Size)
  1510. {
  1511. ssize_t Res;
  1512. errno = 0;
  1513. do
  1514. {
  1515. if (false)
  1516. /* dummy so that the rest can be 'else if's */;
  1517. #ifdef HAVE_ZLIB
  1518. else if (d != NULL && d->gz != NULL)
  1519. Res = gzwrite(d->gz,From,Size);
  1520. #endif
  1521. #ifdef HAVE_BZ2
  1522. else if (d != NULL && d->bz2 != NULL)
  1523. Res = BZ2_bzwrite(d->bz2,(void*)From,Size);
  1524. #endif
  1525. #ifdef HAVE_LZMA
  1526. else if (d != NULL && d->lzma != NULL)
  1527. {
  1528. d->lzma->stream.next_in = (uint8_t *)From;
  1529. d->lzma->stream.avail_in = Size;
  1530. d->lzma->stream.next_out = d->lzma->buffer;
  1531. d->lzma->stream.avail_out = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]);
  1532. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1533. if (d->lzma->err != LZMA_OK)
  1534. return false;
  1535. size_t const n = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]) - d->lzma->stream.avail_out;
  1536. size_t const m = (n == 0) ? 0 : fwrite(d->lzma->buffer, 1, n, d->lzma->file);
  1537. if (m != n)
  1538. Res = -1;
  1539. else
  1540. Res = Size - d->lzma->stream.avail_in;
  1541. }
  1542. #endif
  1543. else
  1544. Res = write(iFd,From,Size);
  1545. if (Res < 0 && errno == EINTR)
  1546. continue;
  1547. if (Res < 0)
  1548. {
  1549. if (false)
  1550. /* dummy so that the rest can be 'else if's */;
  1551. #ifdef HAVE_ZLIB
  1552. else if (d != NULL && d->gz != NULL)
  1553. {
  1554. int err;
  1555. char const * const errmsg = gzerror(d->gz, &err);
  1556. if (err != Z_ERRNO)
  1557. return FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1558. }
  1559. #endif
  1560. #ifdef HAVE_BZ2
  1561. else if (d != NULL && d->bz2 != NULL)
  1562. {
  1563. int err;
  1564. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1565. if (err != BZ_IO_ERROR)
  1566. return FileFdError("BZ2_bzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1567. }
  1568. #endif
  1569. #ifdef HAVE_LZMA
  1570. else if (d != NULL && d->lzma != NULL)
  1571. return FileFdErrno("lzma_fwrite", _("Write error"));
  1572. #endif
  1573. return FileFdErrno("write",_("Write error"));
  1574. }
  1575. From = (char const *)From + Res;
  1576. Size -= Res;
  1577. if (d != NULL)
  1578. d->seekpos += Res;
  1579. }
  1580. while (Res > 0 && Size > 0);
  1581. if (Size == 0)
  1582. return true;
  1583. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  1584. }
  1585. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  1586. {
  1587. ssize_t Res;
  1588. errno = 0;
  1589. do
  1590. {
  1591. Res = write(Fd,From,Size);
  1592. if (Res < 0 && errno == EINTR)
  1593. continue;
  1594. if (Res < 0)
  1595. return _error->Errno("write",_("Write error"));
  1596. From = (char const *)From + Res;
  1597. Size -= Res;
  1598. }
  1599. while (Res > 0 && Size > 0);
  1600. if (Size == 0)
  1601. return true;
  1602. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  1603. }
  1604. /*}}}*/
  1605. // FileFd::Seek - Seek in the file /*{{{*/
  1606. // ---------------------------------------------------------------------
  1607. /* */
  1608. bool FileFd::Seek(unsigned long long To)
  1609. {
  1610. Flags &= ~HitEof;
  1611. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1612. {
  1613. // Our poor man seeking in pipes is costly, so try to avoid it
  1614. unsigned long long seekpos = Tell();
  1615. if (seekpos == To)
  1616. return true;
  1617. else if (seekpos < To)
  1618. return Skip(To - seekpos);
  1619. if ((d->openmode & ReadOnly) != ReadOnly)
  1620. return FileFdError("Reopen is only implemented for read-only files!");
  1621. d->InternalClose(FileName);
  1622. if (iFd != -1)
  1623. close(iFd);
  1624. iFd = -1;
  1625. if (TemporaryFileName.empty() == false)
  1626. iFd = open(TemporaryFileName.c_str(), O_RDONLY);
  1627. else if (FileName.empty() == false)
  1628. iFd = open(FileName.c_str(), O_RDONLY);
  1629. else
  1630. {
  1631. if (d->compressed_fd > 0)
  1632. if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
  1633. iFd = d->compressed_fd;
  1634. if (iFd < 0)
  1635. return FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1636. }
  1637. if (OpenInternDescriptor(d->openmode, d->compressor) == false)
  1638. return FileFdError("Seek on file %s because it couldn't be reopened", FileName.c_str());
  1639. if (To != 0)
  1640. return Skip(To);
  1641. d->seekpos = To;
  1642. return true;
  1643. }
  1644. off_t res;
  1645. #ifdef HAVE_ZLIB
  1646. if (d != NULL && d->gz)
  1647. res = gzseek(d->gz,To,SEEK_SET);
  1648. else
  1649. #endif
  1650. res = lseek(iFd,To,SEEK_SET);
  1651. if (res != (off_t)To)
  1652. return FileFdError("Unable to seek to %llu", To);
  1653. if (d != NULL)
  1654. d->seekpos = To;
  1655. return true;
  1656. }
  1657. /*}}}*/
  1658. // FileFd::Skip - Seek in the file /*{{{*/
  1659. // ---------------------------------------------------------------------
  1660. /* */
  1661. bool FileFd::Skip(unsigned long long Over)
  1662. {
  1663. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1664. {
  1665. char buffer[1024];
  1666. while (Over != 0)
  1667. {
  1668. unsigned long long toread = std::min((unsigned long long) sizeof(buffer), Over);
  1669. if (Read(buffer, toread) == false)
  1670. return FileFdError("Unable to seek ahead %llu",Over);
  1671. Over -= toread;
  1672. }
  1673. return true;
  1674. }
  1675. off_t res;
  1676. #ifdef HAVE_ZLIB
  1677. if (d != NULL && d->gz != NULL)
  1678. res = gzseek(d->gz,Over,SEEK_CUR);
  1679. else
  1680. #endif
  1681. res = lseek(iFd,Over,SEEK_CUR);
  1682. if (res < 0)
  1683. return FileFdError("Unable to seek ahead %llu",Over);
  1684. if (d != NULL)
  1685. d->seekpos = res;
  1686. return true;
  1687. }
  1688. /*}}}*/
  1689. // FileFd::Truncate - Truncate the file /*{{{*/
  1690. // ---------------------------------------------------------------------
  1691. /* */
  1692. bool FileFd::Truncate(unsigned long long To)
  1693. {
  1694. // truncating /dev/null is always successful - as we get an error otherwise
  1695. if (To == 0 && FileName == "/dev/null")
  1696. return true;
  1697. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1698. if (d != NULL && (d->InternalStream() == true
  1699. #ifdef HAVE_ZLIB
  1700. || d->gz != NULL
  1701. #endif
  1702. ))
  1703. return FileFdError("Truncating compressed files is not implemented (%s)", FileName.c_str());
  1704. #endif
  1705. if (ftruncate(iFd,To) != 0)
  1706. return FileFdError("Unable to truncate to %llu",To);
  1707. return true;
  1708. }
  1709. /*}}}*/
  1710. // FileFd::Tell - Current seek position /*{{{*/
  1711. // ---------------------------------------------------------------------
  1712. /* */
  1713. unsigned long long FileFd::Tell()
  1714. {
  1715. // In theory, we could just return seekpos here always instead of
  1716. // seeking around, but not all users of FileFd use always Seek() and co
  1717. // so d->seekpos isn't always true and we can just use it as a hint if
  1718. // we have nothing else, but not always as an authority…
  1719. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1720. return d->seekpos;
  1721. off_t Res;
  1722. #ifdef HAVE_ZLIB
  1723. if (d != NULL && d->gz != NULL)
  1724. Res = gztell(d->gz);
  1725. else
  1726. #endif
  1727. Res = lseek(iFd,0,SEEK_CUR);
  1728. if (Res == (off_t)-1)
  1729. FileFdErrno("lseek","Failed to determine the current file position");
  1730. if (d != NULL)
  1731. d->seekpos = Res;
  1732. return Res;
  1733. }
  1734. /*}}}*/
  1735. static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
  1736. {
  1737. bool ispipe = (d != NULL && d->pipe == true);
  1738. if (ispipe == false)
  1739. {
  1740. if (fstat(iFd,&Buf) != 0)
  1741. // higher-level code will generate more meaningful messages,
  1742. // even translated this would be meaningless for users
  1743. return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
  1744. if (FileName.empty() == false)
  1745. ispipe = S_ISFIFO(Buf.st_mode);
  1746. }
  1747. // for compressor pipes st_size is undefined and at 'best' zero
  1748. if (ispipe == true)
  1749. {
  1750. // we set it here, too, as we get the info here for free
  1751. // in theory the Open-methods should take care of it already
  1752. if (d != NULL)
  1753. d->pipe = true;
  1754. if (stat(FileName.c_str(), &Buf) != 0)
  1755. return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
  1756. }
  1757. return true;
  1758. }
  1759. /*}}}*/
  1760. // FileFd::FileSize - Return the size of the file /*{{{*/
  1761. unsigned long long FileFd::FileSize()
  1762. {
  1763. struct stat Buf;
  1764. if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
  1765. {
  1766. Flags |= Fail;
  1767. return 0;
  1768. }
  1769. return Buf.st_size;
  1770. }
  1771. /*}}}*/
  1772. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1773. time_t FileFd::ModificationTime()
  1774. {
  1775. struct stat Buf;
  1776. if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
  1777. {
  1778. Flags |= Fail;
  1779. return 0;
  1780. }
  1781. return Buf.st_mtime;
  1782. }
  1783. /*}}}*/
  1784. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1785. // ---------------------------------------------------------------------
  1786. /* */
  1787. unsigned long long FileFd::Size()
  1788. {
  1789. unsigned long long size = FileSize();
  1790. // for compressor pipes st_size is undefined and at 'best' zero,
  1791. // so we 'read' the content and 'seek' back - see there
  1792. if (d != NULL && (d->pipe == true || (d->InternalStream() == true && size > 0)))
  1793. {
  1794. unsigned long long const oldSeek = Tell();
  1795. char ignore[1000];
  1796. unsigned long long read = 0;
  1797. do {
  1798. if (Read(ignore, sizeof(ignore), &read) == false)
  1799. {
  1800. Seek(oldSeek);
  1801. return 0;
  1802. }
  1803. } while(read != 0);
  1804. size = Tell();
  1805. Seek(oldSeek);
  1806. }
  1807. #ifdef HAVE_ZLIB
  1808. // only check gzsize if we are actually a gzip file, just checking for
  1809. // "gz" is not sufficient as uncompressed files could be opened with
  1810. // gzopen in "direct" mode as well
  1811. else if (d != NULL && d->gz && !gzdirect(d->gz) && size > 0)
  1812. {
  1813. off_t const oldPos = lseek(iFd,0,SEEK_CUR);
  1814. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1815. * this ourselves; the original (uncompressed) file size is the last 32
  1816. * bits of the file */
  1817. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1818. if (lseek(iFd, -4, SEEK_END) < 0)
  1819. {
  1820. FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1821. return 0;
  1822. }
  1823. uint32_t size = 0;
  1824. if (read(iFd, &size, 4) != 4)
  1825. {
  1826. FileFdErrno("read","Unable to read original size of gzipped file");
  1827. return 0;
  1828. }
  1829. size = le32toh(size);
  1830. if (lseek(iFd, oldPos, SEEK_SET) < 0)
  1831. {
  1832. FileFdErrno("lseek","Unable to seek in gzipped file");
  1833. return 0;
  1834. }
  1835. return size;
  1836. }
  1837. #endif
  1838. return size;
  1839. }
  1840. /*}}}*/
  1841. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1842. // ---------------------------------------------------------------------
  1843. /* */
  1844. bool FileFd::Close()
  1845. {
  1846. if (iFd == -1)
  1847. return true;
  1848. bool Res = true;
  1849. if ((Flags & AutoClose) == AutoClose)
  1850. {
  1851. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  1852. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1853. }
  1854. if (d != NULL)
  1855. {
  1856. Res &= d->CloseDown(FileName);
  1857. delete d;
  1858. d = NULL;
  1859. }
  1860. if ((Flags & Replace) == Replace) {
  1861. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1862. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1863. FileName = TemporaryFileName; // for the unlink() below.
  1864. TemporaryFileName.clear();
  1865. }
  1866. iFd = -1;
  1867. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1868. FileName.empty() == false)
  1869. if (unlink(FileName.c_str()) != 0)
  1870. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1871. if (Res == false)
  1872. Flags |= Fail;
  1873. return Res;
  1874. }
  1875. /*}}}*/
  1876. // FileFd::Sync - Sync the file /*{{{*/
  1877. // ---------------------------------------------------------------------
  1878. /* */
  1879. bool FileFd::Sync()
  1880. {
  1881. if (fsync(iFd) != 0)
  1882. return FileFdErrno("sync",_("Problem syncing the file"));
  1883. return true;
  1884. }
  1885. /*}}}*/
  1886. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  1887. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  1888. {
  1889. Flags |= Fail;
  1890. va_list args;
  1891. size_t msgSize = 400;
  1892. int const errsv = errno;
  1893. while (true)
  1894. {
  1895. va_start(args,Description);
  1896. if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
  1897. break;
  1898. va_end(args);
  1899. }
  1900. return false;
  1901. }
  1902. /*}}}*/
  1903. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  1904. bool FileFd::FileFdError(const char *Description,...) {
  1905. Flags |= Fail;
  1906. va_list args;
  1907. size_t msgSize = 400;
  1908. while (true)
  1909. {
  1910. va_start(args,Description);
  1911. if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
  1912. break;
  1913. va_end(args);
  1914. }
  1915. return false;
  1916. }
  1917. /*}}}*/
  1918. APT_DEPRECATED gzFile FileFd::gzFd() {
  1919. #ifdef HAVE_ZLIB
  1920. return d->gz;
  1921. #else
  1922. return NULL;
  1923. #endif
  1924. }
  1925. // Glob - wrapper around "glob()" /*{{{*/
  1926. std::vector<std::string> Glob(std::string const &pattern, int flags)
  1927. {
  1928. std::vector<std::string> result;
  1929. glob_t globbuf;
  1930. int glob_res;
  1931. unsigned int i;
  1932. glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
  1933. if (glob_res != 0)
  1934. {
  1935. if(glob_res != GLOB_NOMATCH) {
  1936. _error->Errno("glob", "Problem with glob");
  1937. return result;
  1938. }
  1939. }
  1940. // append results
  1941. for(i=0;i<globbuf.gl_pathc;i++)
  1942. result.push_back(string(globbuf.gl_pathv[i]));
  1943. globfree(&globbuf);
  1944. return result;
  1945. }
  1946. /*}}}*/
  1947. std::string GetTempDir() /*{{{*/
  1948. {
  1949. const char *tmpdir = getenv("TMPDIR");
  1950. #ifdef P_tmpdir
  1951. if (!tmpdir)
  1952. tmpdir = P_tmpdir;
  1953. #endif
  1954. struct stat st;
  1955. if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set
  1956. stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0 || // exists and is directory
  1957. access(tmpdir, R_OK | W_OK | X_OK) != 0 // current user has rwx access to directory
  1958. )
  1959. tmpdir = "/tmp";
  1960. return string(tmpdir);
  1961. }
  1962. /*}}}*/
  1963. FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink, FileFd * const TmpFd) /*{{{*/
  1964. {
  1965. char fn[512];
  1966. FileFd * const Fd = TmpFd == NULL ? new FileFd() : TmpFd;
  1967. std::string const tempdir = GetTempDir();
  1968. snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
  1969. tempdir.c_str(), Prefix.c_str());
  1970. int const fd = mkstemp(fn);
  1971. if(ImmediateUnlink)
  1972. unlink(fn);
  1973. if (fd < 0)
  1974. {
  1975. _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
  1976. return NULL;
  1977. }
  1978. if (!Fd->OpenDescriptor(fd, FileFd::ReadWrite, FileFd::None, true))
  1979. {
  1980. _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
  1981. return NULL;
  1982. }
  1983. return Fd;
  1984. }
  1985. /*}}}*/
  1986. bool Rename(std::string From, std::string To) /*{{{*/
  1987. {
  1988. if (rename(From.c_str(),To.c_str()) != 0)
  1989. {
  1990. _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
  1991. From.c_str(),To.c_str());
  1992. return false;
  1993. }
  1994. return true;
  1995. }
  1996. /*}}}*/
  1997. bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
  1998. {
  1999. int fd;
  2000. if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
  2001. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  2002. int Pipe[2] = {-1, -1};
  2003. if(pipe(Pipe) != 0)
  2004. return _error->Errno("pipe", _("Failed to create subprocess IPC"));
  2005. std::set<int> keep_fds;
  2006. keep_fds.insert(Pipe[0]);
  2007. keep_fds.insert(Pipe[1]);
  2008. Child = ExecFork(keep_fds);
  2009. if(Child < 0)
  2010. return _error->Errno("fork", "Failed to fork");
  2011. if(Child == 0)
  2012. {
  2013. if(Mode == FileFd::ReadOnly)
  2014. {
  2015. close(Pipe[0]);
  2016. fd = Pipe[1];
  2017. }
  2018. else if(Mode == FileFd::WriteOnly)
  2019. {
  2020. close(Pipe[1]);
  2021. fd = Pipe[0];
  2022. }
  2023. if(Mode == FileFd::ReadOnly)
  2024. {
  2025. dup2(fd, 1);
  2026. dup2(fd, 2);
  2027. } else if(Mode == FileFd::WriteOnly)
  2028. dup2(fd, 0);
  2029. execv(Args[0], (char**)Args);
  2030. _exit(100);
  2031. }
  2032. if(Mode == FileFd::ReadOnly)
  2033. {
  2034. close(Pipe[1]);
  2035. fd = Pipe[0];
  2036. } else if(Mode == FileFd::WriteOnly)
  2037. {
  2038. close(Pipe[0]);
  2039. fd = Pipe[1];
  2040. }
  2041. Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
  2042. return true;
  2043. }
  2044. /*}}}*/
  2045. bool DropPrivileges() /*{{{*/
  2046. {
  2047. if(_config->FindB("Debug::NoDropPrivs", false) == true)
  2048. return true;
  2049. #if __gnu_linux__
  2050. #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
  2051. #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
  2052. #endif
  2053. // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
  2054. int ret = prctl(38, 1, 0, 0, 0);
  2055. // ignore EINVAL - kernel is too old to understand the option
  2056. if(ret < 0 && errno != EINVAL)
  2057. _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
  2058. #endif
  2059. // empty setting disables privilege dropping - this also ensures
  2060. // backward compatibility, see bug #764506
  2061. const std::string toUser = _config->Find("APT::Sandbox::User");
  2062. if (toUser.empty())
  2063. return true;
  2064. // uid will be 0 in the end, but gid might be different anyway
  2065. uid_t const old_uid = getuid();
  2066. gid_t const old_gid = getgid();
  2067. if (old_uid != 0)
  2068. return true;
  2069. struct passwd *pw = getpwnam(toUser.c_str());
  2070. if (pw == NULL)
  2071. return _error->Error("No user %s, can not drop rights", toUser.c_str());
  2072. // Do not change the order here, it might break things
  2073. // Get rid of all our supplementary groups first
  2074. if (setgroups(1, &pw->pw_gid))
  2075. return _error->Errno("setgroups", "Failed to setgroups");
  2076. // Now change the group ids to the new user
  2077. #ifdef HAVE_SETRESGID
  2078. if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
  2079. return _error->Errno("setresgid", "Failed to set new group ids");
  2080. #else
  2081. if (setegid(pw->pw_gid) != 0)
  2082. return _error->Errno("setegid", "Failed to setegid");
  2083. if (setgid(pw->pw_gid) != 0)
  2084. return _error->Errno("setgid", "Failed to setgid");
  2085. #endif
  2086. // Change the user ids to the new user
  2087. #ifdef HAVE_SETRESUID
  2088. if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
  2089. return _error->Errno("setresuid", "Failed to set new user ids");
  2090. #else
  2091. if (setuid(pw->pw_uid) != 0)
  2092. return _error->Errno("setuid", "Failed to setuid");
  2093. if (seteuid(pw->pw_uid) != 0)
  2094. return _error->Errno("seteuid", "Failed to seteuid");
  2095. #endif
  2096. // Verify that the user has only a single group, and the correct one
  2097. gid_t groups[1];
  2098. if (getgroups(1, groups) != 1)
  2099. return _error->Errno("getgroups", "Could not get new groups");
  2100. if (groups[0] != pw->pw_gid)
  2101. return _error->Error("Could not switch group");
  2102. // Verify that gid, egid, uid, and euid changed
  2103. if (getgid() != pw->pw_gid)
  2104. return _error->Error("Could not switch group");
  2105. if (getegid() != pw->pw_gid)
  2106. return _error->Error("Could not switch effective group");
  2107. if (getuid() != pw->pw_uid)
  2108. return _error->Error("Could not switch user");
  2109. if (geteuid() != pw->pw_uid)
  2110. return _error->Error("Could not switch effective user");
  2111. #ifdef HAVE_GETRESUID
  2112. // verify that the saved set-user-id was changed as well
  2113. uid_t ruid = 0;
  2114. uid_t euid = 0;
  2115. uid_t suid = 0;
  2116. if (getresuid(&ruid, &euid, &suid))
  2117. return _error->Errno("getresuid", "Could not get saved set-user-ID");
  2118. if (suid != pw->pw_uid)
  2119. return _error->Error("Could not switch saved set-user-ID");
  2120. #endif
  2121. #ifdef HAVE_GETRESGID
  2122. // verify that the saved set-group-id was changed as well
  2123. gid_t rgid = 0;
  2124. gid_t egid = 0;
  2125. gid_t sgid = 0;
  2126. if (getresgid(&rgid, &egid, &sgid))
  2127. return _error->Errno("getresuid", "Could not get saved set-group-ID");
  2128. if (sgid != pw->pw_gid)
  2129. return _error->Error("Could not switch saved set-group-ID");
  2130. #endif
  2131. // Check that uid and gid changes do not work anymore
  2132. if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
  2133. return _error->Error("Could restore a gid to root, privilege dropping did not work");
  2134. if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
  2135. return _error->Error("Could restore a uid to root, privilege dropping did not work");
  2136. return true;
  2137. }
  2138. /*}}}*/