fileutl.cc 63 KB

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