fileutl.cc 57 KB

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