fileutl.cc 57 KB

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