fileutl.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: fileutl.cc,v 1.42 2002/09/14 05:29:22 jgg Exp $
  4. /* ######################################################################
  5. File Utilities
  6. CopyFile - Buffered copy of a single file
  7. GetLock - dpkg compatible lock file manipulation (fcntl)
  8. Most of this source is placed in the Public Domain, do with it what
  9. you will
  10. It was originally written by Jason Gunthorpe <jgg@debian.org>.
  11. FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
  12. The exception is RunScripts() it is under the GPLv2
  13. ##################################################################### */
  14. /*}}}*/
  15. // Include Files /*{{{*/
  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/configuration.h>
  21. #include <apti18n.h>
  22. #include <cstdlib>
  23. #include <cstring>
  24. #include <cstdio>
  25. #include <iostream>
  26. #include <unistd.h>
  27. #include <fcntl.h>
  28. #include <sys/stat.h>
  29. #include <sys/types.h>
  30. #include <sys/time.h>
  31. #include <sys/wait.h>
  32. #include <dirent.h>
  33. #include <signal.h>
  34. #include <errno.h>
  35. #include <set>
  36. #include <algorithm>
  37. /*}}}*/
  38. using namespace std;
  39. // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
  40. // ---------------------------------------------------------------------
  41. /* */
  42. bool RunScripts(const char *Cnf)
  43. {
  44. Configuration::Item const *Opts = _config->Tree(Cnf);
  45. if (Opts == 0 || Opts->Child == 0)
  46. return true;
  47. Opts = Opts->Child;
  48. // Fork for running the system calls
  49. pid_t Child = ExecFork();
  50. // This is the child
  51. if (Child == 0)
  52. {
  53. if (chdir("/tmp/") != 0)
  54. _exit(100);
  55. unsigned int Count = 1;
  56. for (; Opts != 0; Opts = Opts->Next, Count++)
  57. {
  58. if (Opts->Value.empty() == true)
  59. continue;
  60. if (system(Opts->Value.c_str()) != 0)
  61. _exit(100+Count);
  62. }
  63. _exit(0);
  64. }
  65. // Wait for the child
  66. int Status = 0;
  67. while (waitpid(Child,&Status,0) != Child)
  68. {
  69. if (errno == EINTR)
  70. continue;
  71. return _error->Errno("waitpid","Couldn't wait for subprocess");
  72. }
  73. // Restore sig int/quit
  74. signal(SIGQUIT,SIG_DFL);
  75. signal(SIGINT,SIG_DFL);
  76. // Check for an error code.
  77. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  78. {
  79. unsigned int Count = WEXITSTATUS(Status);
  80. if (Count > 100)
  81. {
  82. Count -= 100;
  83. for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
  84. _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
  85. }
  86. return _error->Error("Sub-process returned an error code");
  87. }
  88. return true;
  89. }
  90. /*}}}*/
  91. // CopyFile - Buffered copy of a file /*{{{*/
  92. // ---------------------------------------------------------------------
  93. /* The caller is expected to set things so that failure causes erasure */
  94. bool CopyFile(FileFd &From,FileFd &To)
  95. {
  96. if (From.IsOpen() == false || To.IsOpen() == false)
  97. return false;
  98. // Buffered copy between fds
  99. SPtrArray<unsigned char> Buf = new unsigned char[64000];
  100. unsigned long Size = From.Size();
  101. while (Size != 0)
  102. {
  103. unsigned long ToRead = Size;
  104. if (Size > 64000)
  105. ToRead = 64000;
  106. if (From.Read(Buf,ToRead) == false ||
  107. To.Write(Buf,ToRead) == false)
  108. return false;
  109. Size -= ToRead;
  110. }
  111. return true;
  112. }
  113. /*}}}*/
  114. // GetLock - Gets a lock file /*{{{*/
  115. // ---------------------------------------------------------------------
  116. /* This will create an empty file of the given name and lock it. Once this
  117. is done all other calls to GetLock in any other process will fail with
  118. -1. The return result is the fd of the file, the call should call
  119. close at some time. */
  120. int GetLock(string File,bool Errors)
  121. {
  122. // GetLock() is used in aptitude on directories with public-write access
  123. // Use O_NOFOLLOW here to prevent symlink traversal attacks
  124. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
  125. if (FD < 0)
  126. {
  127. // Read only .. cant have locking problems there.
  128. if (errno == EROFS)
  129. {
  130. _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
  131. return dup(0); // Need something for the caller to close
  132. }
  133. if (Errors == true)
  134. _error->Errno("open",_("Could not open lock file %s"),File.c_str());
  135. // Feh.. We do this to distinguish the lock vs open case..
  136. errno = EPERM;
  137. return -1;
  138. }
  139. SetCloseExec(FD,true);
  140. // Aquire a write lock
  141. struct flock fl;
  142. fl.l_type = F_WRLCK;
  143. fl.l_whence = SEEK_SET;
  144. fl.l_start = 0;
  145. fl.l_len = 0;
  146. if (fcntl(FD,F_SETLK,&fl) == -1)
  147. {
  148. if (errno == ENOLCK)
  149. {
  150. _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
  151. return dup(0); // Need something for the caller to close
  152. }
  153. if (Errors == true)
  154. _error->Errno("open",_("Could not get lock %s"),File.c_str());
  155. int Tmp = errno;
  156. close(FD);
  157. errno = Tmp;
  158. return -1;
  159. }
  160. return FD;
  161. }
  162. /*}}}*/
  163. // FileExists - Check if a file exists /*{{{*/
  164. // ---------------------------------------------------------------------
  165. /* Beware: Directories are also files! */
  166. bool FileExists(string File)
  167. {
  168. struct stat Buf;
  169. if (stat(File.c_str(),&Buf) != 0)
  170. return false;
  171. return true;
  172. }
  173. /*}}}*/
  174. // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
  175. // ---------------------------------------------------------------------
  176. /* */
  177. bool RealFileExists(string File)
  178. {
  179. struct stat Buf;
  180. if (stat(File.c_str(),&Buf) != 0)
  181. return false;
  182. return ((Buf.st_mode & S_IFREG) != 0);
  183. }
  184. /*}}}*/
  185. // DirectoryExists - Check if a directory exists and is really one /*{{{*/
  186. // ---------------------------------------------------------------------
  187. /* */
  188. bool DirectoryExists(string const &Path)
  189. {
  190. struct stat Buf;
  191. if (stat(Path.c_str(),&Buf) != 0)
  192. return false;
  193. return ((Buf.st_mode & S_IFDIR) != 0);
  194. }
  195. /*}}}*/
  196. // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
  197. // ---------------------------------------------------------------------
  198. /* This method will create all directories needed for path in good old
  199. mkdir -p style but refuses to do this if Parent is not a prefix of
  200. this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
  201. so it will create apt/archives if /var/cache exists - on the other
  202. hand if the parent is /var/lib the creation will fail as this path
  203. is not a parent of the path to be generated. */
  204. bool CreateDirectory(string const &Parent, string const &Path)
  205. {
  206. if (Parent.empty() == true || Path.empty() == true)
  207. return false;
  208. if (DirectoryExists(Path) == true)
  209. return true;
  210. if (DirectoryExists(Parent) == false)
  211. return false;
  212. // we are not going to create directories "into the blue"
  213. if (Path.find(Parent, 0) != 0)
  214. return false;
  215. vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
  216. string progress = Parent;
  217. for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
  218. {
  219. if (d->empty() == true)
  220. continue;
  221. progress.append("/").append(*d);
  222. if (DirectoryExists(progress) == true)
  223. continue;
  224. if (mkdir(progress.c_str(), 0755) != 0)
  225. return false;
  226. }
  227. return true;
  228. }
  229. /*}}}*/
  230. // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
  231. // ---------------------------------------------------------------------
  232. /* a small wrapper around CreateDirectory to check if it exists and to
  233. remove the trailing "/apt/" from the parent directory if needed */
  234. bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path)
  235. {
  236. if (DirectoryExists(Path) == true)
  237. return true;
  238. size_t const len = Parent.size();
  239. if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
  240. {
  241. if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
  242. return true;
  243. }
  244. else if (CreateDirectory(Parent, Path) == true)
  245. return true;
  246. return false;
  247. }
  248. /*}}}*/
  249. // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
  250. // ---------------------------------------------------------------------
  251. /* If an extension is given only files with this extension are included
  252. in the returned vector, otherwise every "normal" file is included. */
  253. std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
  254. bool const &SortList, bool const &AllowNoExt)
  255. {
  256. std::vector<string> ext;
  257. ext.reserve(2);
  258. if (Ext.empty() == false)
  259. ext.push_back(Ext);
  260. if (AllowNoExt == true && ext.empty() == false)
  261. ext.push_back("");
  262. return GetListOfFilesInDir(Dir, ext, SortList);
  263. }
  264. std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
  265. bool const &SortList)
  266. {
  267. // Attention debuggers: need to be set with the environment config file!
  268. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  269. if (Debug == true)
  270. {
  271. std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
  272. if (Ext.empty() == true)
  273. std::clog << "\tNO extension" << std::endl;
  274. else
  275. for (std::vector<string>::const_iterator e = Ext.begin();
  276. e != Ext.end(); ++e)
  277. std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
  278. }
  279. std::vector<string> List;
  280. if (DirectoryExists(Dir.c_str()) == false)
  281. {
  282. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  283. return List;
  284. }
  285. Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
  286. DIR *D = opendir(Dir.c_str());
  287. if (D == 0)
  288. {
  289. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  290. return List;
  291. }
  292. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  293. {
  294. // skip "hidden" files
  295. if (Ent->d_name[0] == '.')
  296. continue;
  297. // Make sure it is a file and not something else
  298. string const File = flCombine(Dir,Ent->d_name);
  299. #ifdef _DIRENT_HAVE_D_TYPE
  300. if (Ent->d_type != DT_REG)
  301. #endif
  302. {
  303. if (RealFileExists(File.c_str()) == false)
  304. {
  305. if (SilentIgnore.Match(Ent->d_name) == false)
  306. _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
  307. continue;
  308. }
  309. }
  310. // check for accepted extension:
  311. // no extension given -> periods are bad as hell!
  312. // extensions given -> "" extension allows no extension
  313. if (Ext.empty() == false)
  314. {
  315. string d_ext = flExtension(Ent->d_name);
  316. if (d_ext == Ent->d_name) // no extension
  317. {
  318. if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
  319. {
  320. if (Debug == true)
  321. std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
  322. if (SilentIgnore.Match(Ent->d_name) == false)
  323. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
  324. continue;
  325. }
  326. }
  327. else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
  328. {
  329. if (Debug == true)
  330. std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
  331. if (SilentIgnore.Match(Ent->d_name) == false)
  332. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
  333. continue;
  334. }
  335. }
  336. // Skip bad filenames ala run-parts
  337. const char *C = Ent->d_name;
  338. for (; *C != 0; ++C)
  339. if (isalpha(*C) == 0 && isdigit(*C) == 0
  340. && *C != '_' && *C != '-') {
  341. // no required extension -> dot is a bad character
  342. if (*C == '.' && Ext.empty() == false)
  343. continue;
  344. break;
  345. }
  346. // we don't reach the end of the name -> bad character included
  347. if (*C != 0)
  348. {
  349. if (Debug == true)
  350. std::clog << "Bad file: " << Ent->d_name << " → bad character »"
  351. << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
  352. continue;
  353. }
  354. // skip filenames which end with a period. These are never valid
  355. if (*(C - 1) == '.')
  356. {
  357. if (Debug == true)
  358. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  359. continue;
  360. }
  361. if (Debug == true)
  362. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  363. List.push_back(File);
  364. }
  365. closedir(D);
  366. if (SortList == true)
  367. std::sort(List.begin(),List.end());
  368. return List;
  369. }
  370. /*}}}*/
  371. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  372. // ---------------------------------------------------------------------
  373. /* We return / on failure. */
  374. string SafeGetCWD()
  375. {
  376. // Stash the current dir.
  377. char S[300];
  378. S[0] = 0;
  379. if (getcwd(S,sizeof(S)-2) == 0)
  380. return "/";
  381. unsigned int Len = strlen(S);
  382. S[Len] = '/';
  383. S[Len+1] = 0;
  384. return S;
  385. }
  386. /*}}}*/
  387. // flNotDir - Strip the directory from the filename /*{{{*/
  388. // ---------------------------------------------------------------------
  389. /* */
  390. string flNotDir(string File)
  391. {
  392. string::size_type Res = File.rfind('/');
  393. if (Res == string::npos)
  394. return File;
  395. Res++;
  396. return string(File,Res,Res - File.length());
  397. }
  398. /*}}}*/
  399. // flNotFile - Strip the file from the directory name /*{{{*/
  400. // ---------------------------------------------------------------------
  401. /* Result ends in a / */
  402. string flNotFile(string File)
  403. {
  404. string::size_type Res = File.rfind('/');
  405. if (Res == string::npos)
  406. return "./";
  407. Res++;
  408. return string(File,0,Res);
  409. }
  410. /*}}}*/
  411. // flExtension - Return the extension for the file /*{{{*/
  412. // ---------------------------------------------------------------------
  413. /* */
  414. string flExtension(string File)
  415. {
  416. string::size_type Res = File.rfind('.');
  417. if (Res == string::npos)
  418. return File;
  419. Res++;
  420. return string(File,Res,Res - File.length());
  421. }
  422. /*}}}*/
  423. // flNoLink - If file is a symlink then deref it /*{{{*/
  424. // ---------------------------------------------------------------------
  425. /* If the name is not a link then the returned path is the input. */
  426. string flNoLink(string File)
  427. {
  428. struct stat St;
  429. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  430. return File;
  431. if (stat(File.c_str(),&St) != 0)
  432. return File;
  433. /* Loop resolving the link. There is no need to limit the number of
  434. loops because the stat call above ensures that the symlink is not
  435. circular */
  436. char Buffer[1024];
  437. string NFile = File;
  438. while (1)
  439. {
  440. // Read the link
  441. int Res;
  442. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  443. (unsigned)Res >= sizeof(Buffer))
  444. return File;
  445. // Append or replace the previous path
  446. Buffer[Res] = 0;
  447. if (Buffer[0] == '/')
  448. NFile = Buffer;
  449. else
  450. NFile = flNotFile(NFile) + Buffer;
  451. // See if we are done
  452. if (lstat(NFile.c_str(),&St) != 0)
  453. return File;
  454. if (S_ISLNK(St.st_mode) == 0)
  455. return NFile;
  456. }
  457. }
  458. /*}}}*/
  459. // flCombine - Combine a file and a directory /*{{{*/
  460. // ---------------------------------------------------------------------
  461. /* If the file is an absolute path then it is just returned, otherwise
  462. the directory is pre-pended to it. */
  463. string flCombine(string Dir,string File)
  464. {
  465. if (File.empty() == true)
  466. return string();
  467. if (File[0] == '/' || Dir.empty() == true)
  468. return File;
  469. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  470. return File;
  471. if (Dir[Dir.length()-1] == '/')
  472. return Dir + File;
  473. return Dir + '/' + File;
  474. }
  475. /*}}}*/
  476. // SetCloseExec - Set the close on exec flag /*{{{*/
  477. // ---------------------------------------------------------------------
  478. /* */
  479. void SetCloseExec(int Fd,bool Close)
  480. {
  481. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  482. {
  483. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  484. exit(100);
  485. }
  486. }
  487. /*}}}*/
  488. // SetNonBlock - Set the nonblocking flag /*{{{*/
  489. // ---------------------------------------------------------------------
  490. /* */
  491. void SetNonBlock(int Fd,bool Block)
  492. {
  493. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  494. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  495. {
  496. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  497. exit(100);
  498. }
  499. }
  500. /*}}}*/
  501. // WaitFd - Wait for a FD to become readable /*{{{*/
  502. // ---------------------------------------------------------------------
  503. /* This waits for a FD to become readable using select. It is useful for
  504. applications making use of non-blocking sockets. The timeout is
  505. in seconds. */
  506. bool WaitFd(int Fd,bool write,unsigned long timeout)
  507. {
  508. fd_set Set;
  509. struct timeval tv;
  510. FD_ZERO(&Set);
  511. FD_SET(Fd,&Set);
  512. tv.tv_sec = timeout;
  513. tv.tv_usec = 0;
  514. if (write == true)
  515. {
  516. int Res;
  517. do
  518. {
  519. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  520. }
  521. while (Res < 0 && errno == EINTR);
  522. if (Res <= 0)
  523. return false;
  524. }
  525. else
  526. {
  527. int Res;
  528. do
  529. {
  530. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  531. }
  532. while (Res < 0 && errno == EINTR);
  533. if (Res <= 0)
  534. return false;
  535. }
  536. return true;
  537. }
  538. /*}}}*/
  539. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  540. // ---------------------------------------------------------------------
  541. /* This is used if you want to cleanse the environment for the forked
  542. child, it fixes up the important signals and nukes all of the fds,
  543. otherwise acts like normal fork. */
  544. pid_t ExecFork()
  545. {
  546. // Fork off the process
  547. pid_t Process = fork();
  548. if (Process < 0)
  549. {
  550. cerr << "FATAL -> Failed to fork." << endl;
  551. exit(100);
  552. }
  553. // Spawn the subprocess
  554. if (Process == 0)
  555. {
  556. // Setup the signals
  557. signal(SIGPIPE,SIG_DFL);
  558. signal(SIGQUIT,SIG_DFL);
  559. signal(SIGINT,SIG_DFL);
  560. signal(SIGWINCH,SIG_DFL);
  561. signal(SIGCONT,SIG_DFL);
  562. signal(SIGTSTP,SIG_DFL);
  563. set<int> KeepFDs;
  564. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  565. if (Opts != 0 && Opts->Child != 0)
  566. {
  567. Opts = Opts->Child;
  568. for (; Opts != 0; Opts = Opts->Next)
  569. {
  570. if (Opts->Value.empty() == true)
  571. continue;
  572. int fd = atoi(Opts->Value.c_str());
  573. KeepFDs.insert(fd);
  574. }
  575. }
  576. // Close all of our FDs - just in case
  577. for (int K = 3; K != 40; K++)
  578. {
  579. if(KeepFDs.find(K) == KeepFDs.end())
  580. fcntl(K,F_SETFD,FD_CLOEXEC);
  581. }
  582. }
  583. return Process;
  584. }
  585. /*}}}*/
  586. // ExecWait - Fancy waitpid /*{{{*/
  587. // ---------------------------------------------------------------------
  588. /* Waits for the given sub process. If Reap is set then no errors are
  589. generated. Otherwise a failed subprocess will generate a proper descriptive
  590. message */
  591. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  592. {
  593. if (Pid <= 1)
  594. return true;
  595. // Wait and collect the error code
  596. int Status;
  597. while (waitpid(Pid,&Status,0) != Pid)
  598. {
  599. if (errno == EINTR)
  600. continue;
  601. if (Reap == true)
  602. return false;
  603. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  604. }
  605. // Check for an error code.
  606. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  607. {
  608. if (Reap == true)
  609. return false;
  610. if (WIFSIGNALED(Status) != 0)
  611. {
  612. if( WTERMSIG(Status) == SIGSEGV)
  613. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  614. else
  615. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  616. }
  617. if (WIFEXITED(Status) != 0)
  618. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  619. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  620. }
  621. return true;
  622. }
  623. /*}}}*/
  624. // FileFd::Open - Open a file /*{{{*/
  625. // ---------------------------------------------------------------------
  626. /* The most commonly used open mode combinations are given with Mode */
  627. bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms)
  628. {
  629. Close();
  630. Flags = AutoClose;
  631. switch (Mode)
  632. {
  633. case ReadOnly:
  634. iFd = open(FileName.c_str(),O_RDONLY);
  635. break;
  636. case ReadOnlyGzip:
  637. iFd = open(FileName.c_str(),O_RDONLY);
  638. if (iFd > 0) {
  639. gz = gzdopen (iFd, "r");
  640. if (gz == NULL) {
  641. close (iFd);
  642. iFd = -1;
  643. }
  644. }
  645. break;
  646. case WriteAtomic:
  647. {
  648. Flags |= Replace;
  649. char *name = strdup((FileName + ".XXXXXX").c_str());
  650. TemporaryFileName = string(mktemp(name));
  651. iFd = open(TemporaryFileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
  652. free(name);
  653. break;
  654. }
  655. case WriteEmpty:
  656. {
  657. struct stat Buf;
  658. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  659. unlink(FileName.c_str());
  660. iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms);
  661. break;
  662. }
  663. case WriteExists:
  664. iFd = open(FileName.c_str(),O_RDWR);
  665. break;
  666. case WriteAny:
  667. iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
  668. break;
  669. case WriteTemp:
  670. unlink(FileName.c_str());
  671. iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
  672. break;
  673. }
  674. if (iFd < 0)
  675. return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
  676. this->FileName = FileName;
  677. SetCloseExec(iFd,true);
  678. return true;
  679. }
  680. bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, bool AutoClose)
  681. {
  682. Close();
  683. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  684. iFd = Fd;
  685. if (Mode == ReadOnlyGzip) {
  686. gz = gzdopen (iFd, "r");
  687. if (gz == NULL) {
  688. if (AutoClose)
  689. close (iFd);
  690. return _error->Errno("gzdopen",_("Could not open file descriptor %d"),
  691. Fd);
  692. }
  693. }
  694. this->FileName = "";
  695. return true;
  696. }
  697. /*}}}*/
  698. // FileFd::~File - Closes the file /*{{{*/
  699. // ---------------------------------------------------------------------
  700. /* If the proper modes are selected then we close the Fd and possibly
  701. unlink the file on error. */
  702. FileFd::~FileFd()
  703. {
  704. Close();
  705. }
  706. /*}}}*/
  707. // FileFd::Read - Read a bit of the file /*{{{*/
  708. // ---------------------------------------------------------------------
  709. /* We are carefull to handle interruption by a signal while reading
  710. gracefully. */
  711. bool FileFd::Read(void *To,unsigned long Size,unsigned long *Actual)
  712. {
  713. int Res;
  714. errno = 0;
  715. if (Actual != 0)
  716. *Actual = 0;
  717. do
  718. {
  719. if (gz != NULL)
  720. Res = gzread(gz,To,Size);
  721. else
  722. Res = read(iFd,To,Size);
  723. if (Res < 0 && errno == EINTR)
  724. continue;
  725. if (Res < 0)
  726. {
  727. Flags |= Fail;
  728. return _error->Errno("read",_("Read error"));
  729. }
  730. To = (char *)To + Res;
  731. Size -= Res;
  732. if (Actual != 0)
  733. *Actual += Res;
  734. }
  735. while (Res > 0 && Size > 0);
  736. if (Size == 0)
  737. return true;
  738. // Eof handling
  739. if (Actual != 0)
  740. {
  741. Flags |= HitEof;
  742. return true;
  743. }
  744. Flags |= Fail;
  745. return _error->Error(_("read, still have %lu to read but none left"),Size);
  746. }
  747. /*}}}*/
  748. // FileFd::Write - Write to the file /*{{{*/
  749. // ---------------------------------------------------------------------
  750. /* */
  751. bool FileFd::Write(const void *From,unsigned long Size)
  752. {
  753. int Res;
  754. errno = 0;
  755. do
  756. {
  757. if (gz != NULL)
  758. Res = gzwrite(gz,From,Size);
  759. else
  760. Res = write(iFd,From,Size);
  761. if (Res < 0 && errno == EINTR)
  762. continue;
  763. if (Res < 0)
  764. {
  765. Flags |= Fail;
  766. return _error->Errno("write",_("Write error"));
  767. }
  768. From = (char *)From + Res;
  769. Size -= Res;
  770. }
  771. while (Res > 0 && Size > 0);
  772. if (Size == 0)
  773. return true;
  774. Flags |= Fail;
  775. return _error->Error(_("write, still have %lu to write but couldn't"),Size);
  776. }
  777. /*}}}*/
  778. // FileFd::Seek - Seek in the file /*{{{*/
  779. // ---------------------------------------------------------------------
  780. /* */
  781. bool FileFd::Seek(unsigned long To)
  782. {
  783. int res;
  784. if (gz)
  785. res = gzseek(gz,To,SEEK_SET);
  786. else
  787. res = lseek(iFd,To,SEEK_SET);
  788. if (res != (signed)To)
  789. {
  790. Flags |= Fail;
  791. return _error->Error("Unable to seek to %lu",To);
  792. }
  793. return true;
  794. }
  795. /*}}}*/
  796. // FileFd::Skip - Seek in the file /*{{{*/
  797. // ---------------------------------------------------------------------
  798. /* */
  799. bool FileFd::Skip(unsigned long Over)
  800. {
  801. int res;
  802. if (gz)
  803. res = gzseek(gz,Over,SEEK_CUR);
  804. else
  805. res = lseek(iFd,Over,SEEK_CUR);
  806. if (res < 0)
  807. {
  808. Flags |= Fail;
  809. return _error->Error("Unable to seek ahead %lu",Over);
  810. }
  811. return true;
  812. }
  813. /*}}}*/
  814. // FileFd::Truncate - Truncate the file /*{{{*/
  815. // ---------------------------------------------------------------------
  816. /* */
  817. bool FileFd::Truncate(unsigned long To)
  818. {
  819. if (gz)
  820. {
  821. Flags |= Fail;
  822. return _error->Error("Truncating gzipped files is not implemented (%s)", FileName.c_str());
  823. }
  824. if (ftruncate(iFd,To) != 0)
  825. {
  826. Flags |= Fail;
  827. return _error->Error("Unable to truncate to %lu",To);
  828. }
  829. return true;
  830. }
  831. /*}}}*/
  832. // FileFd::Tell - Current seek position /*{{{*/
  833. // ---------------------------------------------------------------------
  834. /* */
  835. unsigned long FileFd::Tell()
  836. {
  837. off_t Res;
  838. if (gz)
  839. Res = gztell(gz);
  840. else
  841. Res = lseek(iFd,0,SEEK_CUR);
  842. if (Res == (off_t)-1)
  843. _error->Errno("lseek","Failed to determine the current file position");
  844. return Res;
  845. }
  846. /*}}}*/
  847. // FileFd::FileSize - Return the size of the file /*{{{*/
  848. // ---------------------------------------------------------------------
  849. /* */
  850. unsigned long FileFd::FileSize()
  851. {
  852. struct stat Buf;
  853. if (fstat(iFd,&Buf) != 0)
  854. return _error->Errno("fstat","Unable to determine the file size");
  855. return Buf.st_size;
  856. }
  857. /*}}}*/
  858. // FileFd::Size - Return the size of the content in the file /*{{{*/
  859. // ---------------------------------------------------------------------
  860. /* */
  861. unsigned long FileFd::Size()
  862. {
  863. unsigned long size = FileSize();
  864. // only check gzsize if we are actually a gzip file, just checking for
  865. // "gz" is not sufficient as uncompressed files will be opened with
  866. // gzopen in "direct" mode as well
  867. if (gz && !gzdirect(gz) && size > 0)
  868. {
  869. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  870. * this ourselves; the original (uncompressed) file size is the last 32
  871. * bits of the file */
  872. off_t orig_pos = lseek(iFd, 0, SEEK_CUR);
  873. if (lseek(iFd, -4, SEEK_END) < 0)
  874. return _error->Errno("lseek","Unable to seek to end of gzipped file");
  875. if (read(iFd, &size, 4) != 4)
  876. return _error->Errno("read","Unable to read original size of gzipped file");
  877. size &= 0xFFFFFFFF;
  878. if (lseek(iFd, orig_pos, SEEK_SET) < 0)
  879. return _error->Errno("lseek","Unable to seek in gzipped file");
  880. return size;
  881. }
  882. return size;
  883. }
  884. /*}}}*/
  885. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  886. // ---------------------------------------------------------------------
  887. /* */
  888. bool FileFd::Close()
  889. {
  890. bool Res = true;
  891. if ((Flags & AutoClose) == AutoClose)
  892. {
  893. if (gz != NULL) {
  894. int const e = gzclose(gz);
  895. // gzdopen() on empty files always fails with "buffer error" here, ignore that
  896. if (e != 0 && e != Z_BUF_ERROR)
  897. Res &= _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  898. } else
  899. if (iFd > 0 && close(iFd) != 0)
  900. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  901. }
  902. if ((Flags & Replace) == Replace && iFd >= 0) {
  903. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  904. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  905. FileName = TemporaryFileName; // for the unlink() below.
  906. }
  907. iFd = -1;
  908. gz = NULL;
  909. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  910. FileName.empty() == false)
  911. if (unlink(FileName.c_str()) != 0)
  912. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  913. return Res;
  914. }
  915. /*}}}*/
  916. // FileFd::Sync - Sync the file /*{{{*/
  917. // ---------------------------------------------------------------------
  918. /* */
  919. bool FileFd::Sync()
  920. {
  921. #ifdef _POSIX_SYNCHRONIZED_IO
  922. if (fsync(iFd) != 0)
  923. return _error->Errno("sync",_("Problem syncing the file"));
  924. #endif
  925. return true;
  926. }
  927. /*}}}*/