fileutl.cc 56 KB

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