fileutl.cc 60 KB

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