fileutl.cc 60 KB

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