fileutl.cc 33 KB

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