fileutl.cc 29 KB

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