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.
 
 
 
 
 
 

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