fileutl.cc 48 KB

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