fileutl.cc 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  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. // SetCloseExec - Set the close on exec flag /*{{{*/
  592. // ---------------------------------------------------------------------
  593. /* */
  594. void SetCloseExec(int Fd,bool Close)
  595. {
  596. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  597. {
  598. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  599. exit(100);
  600. }
  601. }
  602. /*}}}*/
  603. // SetNonBlock - Set the nonblocking flag /*{{{*/
  604. // ---------------------------------------------------------------------
  605. /* */
  606. void SetNonBlock(int Fd,bool Block)
  607. {
  608. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  609. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  610. {
  611. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  612. exit(100);
  613. }
  614. }
  615. /*}}}*/
  616. // WaitFd - Wait for a FD to become readable /*{{{*/
  617. // ---------------------------------------------------------------------
  618. /* This waits for a FD to become readable using select. It is useful for
  619. applications making use of non-blocking sockets. The timeout is
  620. in seconds. */
  621. bool WaitFd(int Fd,bool write,unsigned long timeout)
  622. {
  623. fd_set Set;
  624. struct timeval tv;
  625. FD_ZERO(&Set);
  626. FD_SET(Fd,&Set);
  627. tv.tv_sec = timeout;
  628. tv.tv_usec = 0;
  629. if (write == true)
  630. {
  631. int Res;
  632. do
  633. {
  634. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  635. }
  636. while (Res < 0 && errno == EINTR);
  637. if (Res <= 0)
  638. return false;
  639. }
  640. else
  641. {
  642. int Res;
  643. do
  644. {
  645. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  646. }
  647. while (Res < 0 && errno == EINTR);
  648. if (Res <= 0)
  649. return false;
  650. }
  651. return true;
  652. }
  653. /*}}}*/
  654. // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
  655. // ---------------------------------------------------------------------
  656. /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
  657. * set.
  658. */
  659. void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs)
  660. {
  661. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  662. if (Opts != 0 && Opts->Child != 0)
  663. {
  664. Opts = Opts->Child;
  665. for (; Opts != 0; Opts = Opts->Next)
  666. {
  667. if (Opts->Value.empty() == true)
  668. continue;
  669. int fd = atoi(Opts->Value.c_str());
  670. KeepFDs.insert(fd);
  671. }
  672. }
  673. }
  674. /*}}}*/
  675. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  676. // ---------------------------------------------------------------------
  677. /* This is used if you want to cleanse the environment for the forked
  678. child, it fixes up the important signals and nukes all of the fds,
  679. otherwise acts like normal fork. */
  680. pid_t ExecFork()
  681. {
  682. set<int> KeepFDs;
  683. // we need to merge the Keep-Fds as external tools like
  684. // debconf-apt-progress use it
  685. MergeKeepFdsFromConfiguration(KeepFDs);
  686. return ExecFork(KeepFDs);
  687. }
  688. pid_t ExecFork(std::set<int> KeepFDs)
  689. {
  690. // Fork off the process
  691. pid_t Process = fork();
  692. if (Process < 0)
  693. {
  694. cerr << "FATAL -> Failed to fork." << endl;
  695. exit(100);
  696. }
  697. // Spawn the subprocess
  698. if (Process == 0)
  699. {
  700. // Setup the signals
  701. signal(SIGPIPE,SIG_DFL);
  702. signal(SIGQUIT,SIG_DFL);
  703. signal(SIGINT,SIG_DFL);
  704. signal(SIGWINCH,SIG_DFL);
  705. signal(SIGCONT,SIG_DFL);
  706. signal(SIGTSTP,SIG_DFL);
  707. // Close all of our FDs - just in case
  708. for (int K = 3; K != sysconf(_SC_OPEN_MAX); K++)
  709. {
  710. if(KeepFDs.find(K) == KeepFDs.end())
  711. fcntl(K,F_SETFD,FD_CLOEXEC);
  712. }
  713. }
  714. return Process;
  715. }
  716. /*}}}*/
  717. // ExecWait - Fancy waitpid /*{{{*/
  718. // ---------------------------------------------------------------------
  719. /* Waits for the given sub process. If Reap is set then no errors are
  720. generated. Otherwise a failed subprocess will generate a proper descriptive
  721. message */
  722. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  723. {
  724. if (Pid <= 1)
  725. return true;
  726. // Wait and collect the error code
  727. int Status;
  728. while (waitpid(Pid,&Status,0) != Pid)
  729. {
  730. if (errno == EINTR)
  731. continue;
  732. if (Reap == true)
  733. return false;
  734. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  735. }
  736. // Check for an error code.
  737. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  738. {
  739. if (Reap == true)
  740. return false;
  741. if (WIFSIGNALED(Status) != 0)
  742. {
  743. if( WTERMSIG(Status) == SIGSEGV)
  744. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  745. else
  746. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  747. }
  748. if (WIFEXITED(Status) != 0)
  749. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  750. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  751. }
  752. return true;
  753. }
  754. /*}}}*/
  755. class FileFdPrivate { /*{{{*/
  756. public:
  757. #ifdef HAVE_ZLIB
  758. gzFile gz;
  759. #endif
  760. #ifdef HAVE_BZ2
  761. BZFILE* bz2;
  762. #endif
  763. #ifdef HAVE_LZMA
  764. struct LZMAFILE {
  765. FILE* file;
  766. uint8_t buffer[4096];
  767. lzma_stream stream;
  768. lzma_ret err;
  769. bool eof;
  770. bool compressing;
  771. LZMAFILE() : file(NULL), eof(false), compressing(false) {}
  772. ~LZMAFILE() {
  773. if (compressing == true)
  774. {
  775. for (;;) {
  776. stream.avail_out = sizeof(buffer)/sizeof(buffer[0]);
  777. stream.next_out = buffer;
  778. err = lzma_code(&stream, LZMA_FINISH);
  779. if (err != LZMA_OK && err != LZMA_STREAM_END)
  780. {
  781. _error->Error("~LZMAFILE: Compress finalisation failed");
  782. break;
  783. }
  784. size_t const n = sizeof(buffer)/sizeof(buffer[0]) - stream.avail_out;
  785. if (n && fwrite(buffer, 1, n, file) != n)
  786. {
  787. _error->Errno("~LZMAFILE",_("Write error"));
  788. break;
  789. }
  790. if (err == LZMA_STREAM_END)
  791. break;
  792. }
  793. }
  794. lzma_end(&stream);
  795. fclose(file);
  796. }
  797. };
  798. LZMAFILE* lzma;
  799. #endif
  800. int compressed_fd;
  801. pid_t compressor_pid;
  802. bool pipe;
  803. APT::Configuration::Compressor compressor;
  804. unsigned int openmode;
  805. unsigned long long seekpos;
  806. FileFdPrivate() :
  807. #ifdef HAVE_ZLIB
  808. gz(NULL),
  809. #endif
  810. #ifdef HAVE_BZ2
  811. bz2(NULL),
  812. #endif
  813. #ifdef HAVE_LZMA
  814. lzma(NULL),
  815. #endif
  816. compressed_fd(-1), compressor_pid(-1), pipe(false),
  817. openmode(0), seekpos(0) {};
  818. bool InternalClose(std::string const &FileName)
  819. {
  820. if (false)
  821. /* dummy so that the rest can be 'else if's */;
  822. #ifdef HAVE_ZLIB
  823. else if (gz != NULL) {
  824. int const e = gzclose(gz);
  825. gz = NULL;
  826. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  827. if (e != 0 && e != Z_BUF_ERROR)
  828. return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  829. }
  830. #endif
  831. #ifdef HAVE_BZ2
  832. else if (bz2 != NULL) {
  833. BZ2_bzclose(bz2);
  834. bz2 = NULL;
  835. }
  836. #endif
  837. #ifdef HAVE_LZMA
  838. else if (lzma != NULL) {
  839. delete lzma;
  840. lzma = NULL;
  841. }
  842. #endif
  843. return true;
  844. }
  845. bool CloseDown(std::string const &FileName)
  846. {
  847. bool const Res = InternalClose(FileName);
  848. if (compressor_pid > 0)
  849. ExecWait(compressor_pid, "FileFdCompressor", true);
  850. compressor_pid = -1;
  851. return Res;
  852. }
  853. bool InternalStream() const {
  854. return false
  855. #ifdef HAVE_BZ2
  856. || bz2 != NULL
  857. #endif
  858. #ifdef HAVE_LZMA
  859. || lzma != NULL
  860. #endif
  861. ;
  862. }
  863. ~FileFdPrivate() { CloseDown(""); }
  864. };
  865. /*}}}*/
  866. // FileFd::Open - Open a file /*{{{*/
  867. // ---------------------------------------------------------------------
  868. /* The most commonly used open mode combinations are given with Mode */
  869. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
  870. {
  871. if (Mode == ReadOnlyGzip)
  872. return Open(FileName, ReadOnly, Gzip, AccessMode);
  873. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  874. return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  875. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  876. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  877. if (Compress == Auto)
  878. {
  879. for (; compressor != compressors.end(); ++compressor)
  880. {
  881. std::string file = FileName + compressor->Extension;
  882. if (FileExists(file) == false)
  883. continue;
  884. FileName = file;
  885. break;
  886. }
  887. }
  888. else if (Compress == Extension)
  889. {
  890. std::string::size_type const found = FileName.find_last_of('.');
  891. std::string ext;
  892. if (found != std::string::npos)
  893. {
  894. ext = FileName.substr(found);
  895. if (ext == ".new" || ext == ".bak")
  896. {
  897. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  898. if (found2 != std::string::npos)
  899. ext = FileName.substr(found2, found - found2);
  900. else
  901. ext.clear();
  902. }
  903. }
  904. for (; compressor != compressors.end(); ++compressor)
  905. if (ext == compressor->Extension)
  906. break;
  907. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  908. if (compressor == compressors.end())
  909. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  910. if (compressor->Name == ".")
  911. break;
  912. }
  913. else
  914. {
  915. std::string name;
  916. switch (Compress)
  917. {
  918. case None: name = "."; break;
  919. case Gzip: name = "gzip"; break;
  920. case Bzip2: name = "bzip2"; break;
  921. case Lzma: name = "lzma"; break;
  922. case Xz: name = "xz"; break;
  923. case Auto:
  924. case Extension:
  925. // Unreachable
  926. return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  927. }
  928. for (; compressor != compressors.end(); ++compressor)
  929. if (compressor->Name == name)
  930. break;
  931. if (compressor == compressors.end())
  932. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  933. }
  934. if (compressor == compressors.end())
  935. return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  936. return Open(FileName, Mode, *compressor, AccessMode);
  937. }
  938. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
  939. {
  940. Close();
  941. Flags = AutoClose;
  942. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  943. return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  944. if ((Mode & ReadWrite) == 0)
  945. return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
  946. if ((Mode & Atomic) == Atomic)
  947. {
  948. Flags |= Replace;
  949. }
  950. else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
  951. {
  952. // for atomic, this will be done by rename in Close()
  953. unlink(FileName.c_str());
  954. }
  955. if ((Mode & Empty) == Empty)
  956. {
  957. struct stat Buf;
  958. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  959. unlink(FileName.c_str());
  960. }
  961. int fileflags = 0;
  962. #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
  963. if_FLAGGED_SET(ReadWrite, O_RDWR);
  964. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  965. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  966. if_FLAGGED_SET(Create, O_CREAT);
  967. if_FLAGGED_SET(Empty, O_TRUNC);
  968. if_FLAGGED_SET(Exclusive, O_EXCL);
  969. #undef if_FLAGGED_SET
  970. if ((Mode & Atomic) == Atomic)
  971. {
  972. char *name = strdup((FileName + ".XXXXXX").c_str());
  973. if((iFd = mkstemp(name)) == -1)
  974. {
  975. free(name);
  976. return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
  977. }
  978. TemporaryFileName = string(name);
  979. free(name);
  980. // umask() will always set the umask and return the previous value, so
  981. // we first set the umask and then reset it to the old value
  982. mode_t const CurrentUmask = umask(0);
  983. umask(CurrentUmask);
  984. // calculate the actual file permissions (just like open/creat)
  985. mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
  986. if(fchmod(iFd, FilePermissions) == -1)
  987. return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
  988. }
  989. else
  990. iFd = open(FileName.c_str(), fileflags, AccessMode);
  991. this->FileName = FileName;
  992. if (iFd == -1 || OpenInternDescriptor(Mode, compressor) == false)
  993. {
  994. if (iFd != -1)
  995. {
  996. close (iFd);
  997. iFd = -1;
  998. }
  999. return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
  1000. }
  1001. SetCloseExec(iFd,true);
  1002. return true;
  1003. }
  1004. /*}}}*/
  1005. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  1006. // ---------------------------------------------------------------------
  1007. /* */
  1008. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  1009. {
  1010. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  1011. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  1012. std::string name;
  1013. // compat with the old API
  1014. if (Mode == ReadOnlyGzip && Compress == None)
  1015. Compress = Gzip;
  1016. switch (Compress)
  1017. {
  1018. case None: name = "."; break;
  1019. case Gzip: name = "gzip"; break;
  1020. case Bzip2: name = "bzip2"; break;
  1021. case Lzma: name = "lzma"; break;
  1022. case Xz: name = "xz"; break;
  1023. case Auto:
  1024. case Extension:
  1025. if (AutoClose == true && Fd != -1)
  1026. close(Fd);
  1027. return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  1028. }
  1029. for (; compressor != compressors.end(); ++compressor)
  1030. if (compressor->Name == name)
  1031. break;
  1032. if (compressor == compressors.end())
  1033. {
  1034. if (AutoClose == true && Fd != -1)
  1035. close(Fd);
  1036. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  1037. }
  1038. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  1039. }
  1040. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  1041. {
  1042. Close();
  1043. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  1044. iFd = Fd;
  1045. this->FileName = "";
  1046. if (OpenInternDescriptor(Mode, compressor) == false)
  1047. {
  1048. if (iFd != -1 && (
  1049. (Flags & Compressed) == Compressed ||
  1050. AutoClose == true))
  1051. {
  1052. close (iFd);
  1053. iFd = -1;
  1054. }
  1055. return FileFdError(_("Could not open file descriptor %d"), Fd);
  1056. }
  1057. return true;
  1058. }
  1059. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  1060. {
  1061. if (iFd == -1)
  1062. return false;
  1063. if (compressor.Name == "." || compressor.Binary.empty() == true)
  1064. return true;
  1065. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1066. // the API to open files is similar, so setup to avoid code duplicates later
  1067. // and while at it ensure that we close before opening (if its a reopen)
  1068. void* (*compress_open)(int, const char *) = NULL;
  1069. if (false)
  1070. /* dummy so that the rest can be 'else if's */;
  1071. #define APT_COMPRESS_INIT(NAME,OPEN) \
  1072. else if (compressor.Name == NAME) \
  1073. { \
  1074. compress_open = (void*(*)(int, const char *)) OPEN; \
  1075. if (d != NULL) d->InternalClose(FileName); \
  1076. }
  1077. #ifdef HAVE_ZLIB
  1078. APT_COMPRESS_INIT("gzip", gzdopen)
  1079. #endif
  1080. #ifdef HAVE_BZ2
  1081. APT_COMPRESS_INIT("bzip2", BZ2_bzdopen)
  1082. #endif
  1083. #ifdef HAVE_LZMA
  1084. APT_COMPRESS_INIT("xz", fdopen)
  1085. APT_COMPRESS_INIT("lzma", fdopen)
  1086. #endif
  1087. #undef APT_COMPRESS_INIT
  1088. #endif
  1089. if (d == NULL)
  1090. {
  1091. d = new FileFdPrivate();
  1092. d->openmode = Mode;
  1093. d->compressor = compressor;
  1094. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1095. if ((Flags & AutoClose) != AutoClose && compress_open != NULL)
  1096. {
  1097. // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
  1098. int const internFd = dup(iFd);
  1099. if (internFd == -1)
  1100. return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
  1101. iFd = internFd;
  1102. }
  1103. #endif
  1104. }
  1105. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1106. if (compress_open != NULL)
  1107. {
  1108. void* compress_struct = NULL;
  1109. if ((Mode & ReadWrite) == ReadWrite)
  1110. compress_struct = compress_open(iFd, "r+");
  1111. else if ((Mode & WriteOnly) == WriteOnly)
  1112. compress_struct = compress_open(iFd, "w");
  1113. else
  1114. compress_struct = compress_open(iFd, "r");
  1115. if (compress_struct == NULL)
  1116. return false;
  1117. if (false)
  1118. /* dummy so that the rest can be 'else if's */;
  1119. #ifdef HAVE_ZLIB
  1120. else if (compressor.Name == "gzip")
  1121. d->gz = (gzFile) compress_struct;
  1122. #endif
  1123. #ifdef HAVE_BZ2
  1124. else if (compressor.Name == "bzip2")
  1125. d->bz2 = (BZFILE*) compress_struct;
  1126. #endif
  1127. #ifdef HAVE_LZMA
  1128. else if (compressor.Name == "xz" || compressor.Name == "lzma")
  1129. {
  1130. uint32_t const xzlevel = 6;
  1131. uint64_t const memlimit = UINT64_MAX;
  1132. if (d->lzma == NULL)
  1133. d->lzma = new FileFdPrivate::LZMAFILE;
  1134. d->lzma->file = (FILE*) compress_struct;
  1135. lzma_stream tmp_stream = LZMA_STREAM_INIT;
  1136. d->lzma->stream = tmp_stream;
  1137. if ((Mode & ReadWrite) == ReadWrite)
  1138. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1139. if ((Mode & WriteOnly) == WriteOnly)
  1140. {
  1141. if (compressor.Name == "xz")
  1142. {
  1143. if (lzma_easy_encoder(&d->lzma->stream, xzlevel, LZMA_CHECK_CRC32) != LZMA_OK)
  1144. return false;
  1145. }
  1146. else
  1147. {
  1148. lzma_options_lzma options;
  1149. lzma_lzma_preset(&options, xzlevel);
  1150. if (lzma_alone_encoder(&d->lzma->stream, &options) != LZMA_OK)
  1151. return false;
  1152. }
  1153. d->lzma->compressing = true;
  1154. }
  1155. else
  1156. {
  1157. if (compressor.Name == "xz")
  1158. {
  1159. if (lzma_auto_decoder(&d->lzma->stream, memlimit, 0) != LZMA_OK)
  1160. return false;
  1161. }
  1162. else
  1163. {
  1164. if (lzma_alone_decoder(&d->lzma->stream, memlimit) != LZMA_OK)
  1165. return false;
  1166. }
  1167. d->lzma->compressing = false;
  1168. }
  1169. }
  1170. #endif
  1171. Flags |= Compressed;
  1172. return true;
  1173. }
  1174. #endif
  1175. // collect zombies here in case we reopen
  1176. if (d->compressor_pid > 0)
  1177. ExecWait(d->compressor_pid, "FileFdCompressor", true);
  1178. if ((Mode & ReadWrite) == ReadWrite)
  1179. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1180. bool const Comp = (Mode & WriteOnly) == WriteOnly;
  1181. if (Comp == false)
  1182. {
  1183. // Handle 'decompression' of empty files
  1184. struct stat Buf;
  1185. fstat(iFd, &Buf);
  1186. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1187. return true;
  1188. // We don't need the file open - instead let the compressor open it
  1189. // as he properly knows better how to efficiently read from 'his' file
  1190. if (FileName.empty() == false)
  1191. {
  1192. close(iFd);
  1193. iFd = -1;
  1194. }
  1195. }
  1196. // Create a data pipe
  1197. int Pipe[2] = {-1,-1};
  1198. if (pipe(Pipe) != 0)
  1199. return FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1200. for (int J = 0; J != 2; J++)
  1201. SetCloseExec(Pipe[J],true);
  1202. d->compressed_fd = iFd;
  1203. d->pipe = true;
  1204. if (Comp == true)
  1205. iFd = Pipe[1];
  1206. else
  1207. iFd = Pipe[0];
  1208. // The child..
  1209. d->compressor_pid = ExecFork();
  1210. if (d->compressor_pid == 0)
  1211. {
  1212. if (Comp == true)
  1213. {
  1214. dup2(d->compressed_fd,STDOUT_FILENO);
  1215. dup2(Pipe[0],STDIN_FILENO);
  1216. }
  1217. else
  1218. {
  1219. if (d->compressed_fd != -1)
  1220. dup2(d->compressed_fd,STDIN_FILENO);
  1221. dup2(Pipe[1],STDOUT_FILENO);
  1222. }
  1223. int const nullfd = open("/dev/null", O_WRONLY);
  1224. if (nullfd != -1)
  1225. {
  1226. dup2(nullfd,STDERR_FILENO);
  1227. close(nullfd);
  1228. }
  1229. SetCloseExec(STDOUT_FILENO,false);
  1230. SetCloseExec(STDIN_FILENO,false);
  1231. std::vector<char const*> Args;
  1232. Args.push_back(compressor.Binary.c_str());
  1233. std::vector<std::string> const * const addArgs =
  1234. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1235. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1236. a != addArgs->end(); ++a)
  1237. Args.push_back(a->c_str());
  1238. if (Comp == false && FileName.empty() == false)
  1239. {
  1240. // commands not needing arguments, do not need to be told about using standard output
  1241. // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
  1242. if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
  1243. Args.push_back("--stdout");
  1244. if (TemporaryFileName.empty() == false)
  1245. Args.push_back(TemporaryFileName.c_str());
  1246. else
  1247. Args.push_back(FileName.c_str());
  1248. }
  1249. Args.push_back(NULL);
  1250. execvp(Args[0],(char **)&Args[0]);
  1251. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1252. _exit(100);
  1253. }
  1254. if (Comp == true)
  1255. close(Pipe[0]);
  1256. else
  1257. close(Pipe[1]);
  1258. return true;
  1259. }
  1260. /*}}}*/
  1261. // FileFd::~File - Closes the file /*{{{*/
  1262. // ---------------------------------------------------------------------
  1263. /* If the proper modes are selected then we close the Fd and possibly
  1264. unlink the file on error. */
  1265. FileFd::~FileFd()
  1266. {
  1267. Close();
  1268. if (d != NULL)
  1269. d->CloseDown(FileName);
  1270. delete d;
  1271. d = NULL;
  1272. }
  1273. /*}}}*/
  1274. // FileFd::Read - Read a bit of the file /*{{{*/
  1275. // ---------------------------------------------------------------------
  1276. /* We are careful to handle interruption by a signal while reading
  1277. gracefully. */
  1278. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  1279. {
  1280. ssize_t Res;
  1281. errno = 0;
  1282. if (Actual != 0)
  1283. *Actual = 0;
  1284. *((char *)To) = '\0';
  1285. do
  1286. {
  1287. if (false)
  1288. /* dummy so that the rest can be 'else if's */;
  1289. #ifdef HAVE_ZLIB
  1290. else if (d != NULL && d->gz != NULL)
  1291. Res = gzread(d->gz,To,Size);
  1292. #endif
  1293. #ifdef HAVE_BZ2
  1294. else if (d != NULL && d->bz2 != NULL)
  1295. Res = BZ2_bzread(d->bz2,To,Size);
  1296. #endif
  1297. #ifdef HAVE_LZMA
  1298. else if (d != NULL && d->lzma != NULL)
  1299. {
  1300. if (d->lzma->eof == true)
  1301. break;
  1302. d->lzma->stream.next_out = (uint8_t *) To;
  1303. d->lzma->stream.avail_out = Size;
  1304. if (d->lzma->stream.avail_in == 0)
  1305. {
  1306. d->lzma->stream.next_in = d->lzma->buffer;
  1307. d->lzma->stream.avail_in = fread(d->lzma->buffer, 1, sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]), d->lzma->file);
  1308. }
  1309. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1310. if (d->lzma->err == LZMA_STREAM_END)
  1311. {
  1312. d->lzma->eof = true;
  1313. Res = Size - d->lzma->stream.avail_out;
  1314. }
  1315. else if (d->lzma->err != LZMA_OK)
  1316. {
  1317. Res = -1;
  1318. errno = 0;
  1319. }
  1320. else
  1321. {
  1322. Res = Size - d->lzma->stream.avail_out;
  1323. if (Res == 0)
  1324. {
  1325. // lzma run was okay, but produced no output…
  1326. Res = -1;
  1327. errno = EINTR;
  1328. }
  1329. }
  1330. }
  1331. #endif
  1332. else
  1333. Res = read(iFd,To,Size);
  1334. if (Res < 0)
  1335. {
  1336. if (errno == EINTR)
  1337. {
  1338. // trick the while-loop into running again
  1339. Res = 1;
  1340. errno = 0;
  1341. continue;
  1342. }
  1343. if (false)
  1344. /* dummy so that the rest can be 'else if's */;
  1345. #ifdef HAVE_ZLIB
  1346. else if (d != NULL && d->gz != NULL)
  1347. {
  1348. int err;
  1349. char const * const errmsg = gzerror(d->gz, &err);
  1350. if (err != Z_ERRNO)
  1351. return FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1352. }
  1353. #endif
  1354. #ifdef HAVE_BZ2
  1355. else if (d != NULL && d->bz2 != NULL)
  1356. {
  1357. int err;
  1358. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1359. if (err != BZ_IO_ERROR)
  1360. return FileFdError("BZ2_bzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1361. }
  1362. #endif
  1363. #ifdef HAVE_LZMA
  1364. else if (d != NULL && d->lzma != NULL)
  1365. return FileFdError("lzma_read: %s (%d)", _("Read error"), d->lzma->err);
  1366. #endif
  1367. return FileFdErrno("read",_("Read error"));
  1368. }
  1369. To = (char *)To + Res;
  1370. Size -= Res;
  1371. if (d != NULL)
  1372. d->seekpos += Res;
  1373. if (Actual != 0)
  1374. *Actual += Res;
  1375. }
  1376. while (Res > 0 && Size > 0);
  1377. if (Size == 0)
  1378. return true;
  1379. // Eof handling
  1380. if (Actual != 0)
  1381. {
  1382. Flags |= HitEof;
  1383. return true;
  1384. }
  1385. return FileFdError(_("read, still have %llu to read but none left"), Size);
  1386. }
  1387. /*}}}*/
  1388. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  1389. // ---------------------------------------------------------------------
  1390. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  1391. files because of the naive implementation! */
  1392. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  1393. {
  1394. *To = '\0';
  1395. #ifdef HAVE_ZLIB
  1396. if (d != NULL && d->gz != NULL)
  1397. return gzgets(d->gz, To, Size);
  1398. #endif
  1399. unsigned long long read = 0;
  1400. while ((Size - 1) != read)
  1401. {
  1402. unsigned long long done = 0;
  1403. if (Read(To + read, 1, &done) == false)
  1404. return NULL;
  1405. if (done == 0)
  1406. break;
  1407. if (To[read++] == '\n')
  1408. break;
  1409. }
  1410. if (read == 0)
  1411. return NULL;
  1412. To[read] = '\0';
  1413. return To;
  1414. }
  1415. /*}}}*/
  1416. // FileFd::Write - Write to the file /*{{{*/
  1417. // ---------------------------------------------------------------------
  1418. /* */
  1419. bool FileFd::Write(const void *From,unsigned long long Size)
  1420. {
  1421. ssize_t Res;
  1422. errno = 0;
  1423. do
  1424. {
  1425. if (false)
  1426. /* dummy so that the rest can be 'else if's */;
  1427. #ifdef HAVE_ZLIB
  1428. else if (d != NULL && d->gz != NULL)
  1429. Res = gzwrite(d->gz,From,Size);
  1430. #endif
  1431. #ifdef HAVE_BZ2
  1432. else if (d != NULL && d->bz2 != NULL)
  1433. Res = BZ2_bzwrite(d->bz2,(void*)From,Size);
  1434. #endif
  1435. #ifdef HAVE_LZMA
  1436. else if (d != NULL && d->lzma != NULL)
  1437. {
  1438. d->lzma->stream.next_in = (uint8_t *)From;
  1439. d->lzma->stream.avail_in = Size;
  1440. d->lzma->stream.next_out = d->lzma->buffer;
  1441. d->lzma->stream.avail_out = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]);
  1442. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1443. if (d->lzma->err != LZMA_OK)
  1444. return false;
  1445. size_t const n = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]) - d->lzma->stream.avail_out;
  1446. size_t const m = (n == 0) ? 0 : fwrite(d->lzma->buffer, 1, n, d->lzma->file);
  1447. if (m != n)
  1448. Res = -1;
  1449. else
  1450. Res = Size - d->lzma->stream.avail_in;
  1451. }
  1452. #endif
  1453. else
  1454. Res = write(iFd,From,Size);
  1455. if (Res < 0 && errno == EINTR)
  1456. continue;
  1457. if (Res < 0)
  1458. {
  1459. if (false)
  1460. /* dummy so that the rest can be 'else if's */;
  1461. #ifdef HAVE_ZLIB
  1462. else if (d != NULL && d->gz != NULL)
  1463. {
  1464. int err;
  1465. char const * const errmsg = gzerror(d->gz, &err);
  1466. if (err != Z_ERRNO)
  1467. return FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1468. }
  1469. #endif
  1470. #ifdef HAVE_BZ2
  1471. else if (d != NULL && d->bz2 != NULL)
  1472. {
  1473. int err;
  1474. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1475. if (err != BZ_IO_ERROR)
  1476. return FileFdError("BZ2_bzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1477. }
  1478. #endif
  1479. #ifdef HAVE_LZMA
  1480. else if (d != NULL && d->lzma != NULL)
  1481. return FileFdErrno("lzma_fwrite", _("Write error"));
  1482. #endif
  1483. return FileFdErrno("write",_("Write error"));
  1484. }
  1485. From = (char const *)From + Res;
  1486. Size -= Res;
  1487. if (d != NULL)
  1488. d->seekpos += Res;
  1489. }
  1490. while (Res > 0 && Size > 0);
  1491. if (Size == 0)
  1492. return true;
  1493. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  1494. }
  1495. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  1496. {
  1497. ssize_t Res;
  1498. errno = 0;
  1499. do
  1500. {
  1501. Res = write(Fd,From,Size);
  1502. if (Res < 0 && errno == EINTR)
  1503. continue;
  1504. if (Res < 0)
  1505. return _error->Errno("write",_("Write error"));
  1506. From = (char const *)From + Res;
  1507. Size -= Res;
  1508. }
  1509. while (Res > 0 && Size > 0);
  1510. if (Size == 0)
  1511. return true;
  1512. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  1513. }
  1514. /*}}}*/
  1515. // FileFd::Seek - Seek in the file /*{{{*/
  1516. // ---------------------------------------------------------------------
  1517. /* */
  1518. bool FileFd::Seek(unsigned long long To)
  1519. {
  1520. Flags &= ~HitEof;
  1521. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1522. {
  1523. // Our poor man seeking in pipes is costly, so try to avoid it
  1524. unsigned long long seekpos = Tell();
  1525. if (seekpos == To)
  1526. return true;
  1527. else if (seekpos < To)
  1528. return Skip(To - seekpos);
  1529. if ((d->openmode & ReadOnly) != ReadOnly)
  1530. return FileFdError("Reopen is only implemented for read-only files!");
  1531. d->InternalClose(FileName);
  1532. if (iFd != -1)
  1533. close(iFd);
  1534. iFd = -1;
  1535. if (TemporaryFileName.empty() == false)
  1536. iFd = open(TemporaryFileName.c_str(), O_RDONLY);
  1537. else if (FileName.empty() == false)
  1538. iFd = open(FileName.c_str(), O_RDONLY);
  1539. else
  1540. {
  1541. if (d->compressed_fd > 0)
  1542. if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
  1543. iFd = d->compressed_fd;
  1544. if (iFd < 0)
  1545. return FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1546. }
  1547. if (OpenInternDescriptor(d->openmode, d->compressor) == false)
  1548. return FileFdError("Seek on file %s because it couldn't be reopened", FileName.c_str());
  1549. if (To != 0)
  1550. return Skip(To);
  1551. d->seekpos = To;
  1552. return true;
  1553. }
  1554. off_t res;
  1555. #ifdef HAVE_ZLIB
  1556. if (d != NULL && d->gz)
  1557. res = gzseek(d->gz,To,SEEK_SET);
  1558. else
  1559. #endif
  1560. res = lseek(iFd,To,SEEK_SET);
  1561. if (res != (off_t)To)
  1562. return FileFdError("Unable to seek to %llu", To);
  1563. if (d != NULL)
  1564. d->seekpos = To;
  1565. return true;
  1566. }
  1567. /*}}}*/
  1568. // FileFd::Skip - Seek in the file /*{{{*/
  1569. // ---------------------------------------------------------------------
  1570. /* */
  1571. bool FileFd::Skip(unsigned long long Over)
  1572. {
  1573. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1574. {
  1575. char buffer[1024];
  1576. while (Over != 0)
  1577. {
  1578. unsigned long long toread = std::min((unsigned long long) sizeof(buffer), Over);
  1579. if (Read(buffer, toread) == false)
  1580. return FileFdError("Unable to seek ahead %llu",Over);
  1581. Over -= toread;
  1582. }
  1583. return true;
  1584. }
  1585. off_t res;
  1586. #ifdef HAVE_ZLIB
  1587. if (d != NULL && d->gz != NULL)
  1588. res = gzseek(d->gz,Over,SEEK_CUR);
  1589. else
  1590. #endif
  1591. res = lseek(iFd,Over,SEEK_CUR);
  1592. if (res < 0)
  1593. return FileFdError("Unable to seek ahead %llu",Over);
  1594. if (d != NULL)
  1595. d->seekpos = res;
  1596. return true;
  1597. }
  1598. /*}}}*/
  1599. // FileFd::Truncate - Truncate the file /*{{{*/
  1600. // ---------------------------------------------------------------------
  1601. /* */
  1602. bool FileFd::Truncate(unsigned long long To)
  1603. {
  1604. // truncating /dev/null is always successful - as we get an error otherwise
  1605. if (To == 0 && FileName == "/dev/null")
  1606. return true;
  1607. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1608. if (d != NULL && (d->InternalStream() == true
  1609. #ifdef HAVE_ZLIB
  1610. || d->gz != NULL
  1611. #endif
  1612. ))
  1613. return FileFdError("Truncating compressed files is not implemented (%s)", FileName.c_str());
  1614. #endif
  1615. if (ftruncate(iFd,To) != 0)
  1616. return FileFdError("Unable to truncate to %llu",To);
  1617. return true;
  1618. }
  1619. /*}}}*/
  1620. // FileFd::Tell - Current seek position /*{{{*/
  1621. // ---------------------------------------------------------------------
  1622. /* */
  1623. unsigned long long FileFd::Tell()
  1624. {
  1625. // In theory, we could just return seekpos here always instead of
  1626. // seeking around, but not all users of FileFd use always Seek() and co
  1627. // so d->seekpos isn't always true and we can just use it as a hint if
  1628. // we have nothing else, but not always as an authority…
  1629. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1630. return d->seekpos;
  1631. off_t Res;
  1632. #ifdef HAVE_ZLIB
  1633. if (d != NULL && d->gz != NULL)
  1634. Res = gztell(d->gz);
  1635. else
  1636. #endif
  1637. Res = lseek(iFd,0,SEEK_CUR);
  1638. if (Res == (off_t)-1)
  1639. FileFdErrno("lseek","Failed to determine the current file position");
  1640. if (d != NULL)
  1641. d->seekpos = Res;
  1642. return Res;
  1643. }
  1644. /*}}}*/
  1645. static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
  1646. {
  1647. bool ispipe = (d != NULL && d->pipe == true);
  1648. if (ispipe == false)
  1649. {
  1650. if (fstat(iFd,&Buf) != 0)
  1651. // higher-level code will generate more meaningful messages,
  1652. // even translated this would be meaningless for users
  1653. return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
  1654. if (FileName.empty() == false)
  1655. ispipe = S_ISFIFO(Buf.st_mode);
  1656. }
  1657. // for compressor pipes st_size is undefined and at 'best' zero
  1658. if (ispipe == true)
  1659. {
  1660. // we set it here, too, as we get the info here for free
  1661. // in theory the Open-methods should take care of it already
  1662. if (d != NULL)
  1663. d->pipe = true;
  1664. if (stat(FileName.c_str(), &Buf) != 0)
  1665. return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
  1666. }
  1667. return true;
  1668. }
  1669. /*}}}*/
  1670. // FileFd::FileSize - Return the size of the file /*{{{*/
  1671. unsigned long long FileFd::FileSize()
  1672. {
  1673. struct stat Buf;
  1674. if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
  1675. {
  1676. Flags |= Fail;
  1677. return 0;
  1678. }
  1679. return Buf.st_size;
  1680. }
  1681. /*}}}*/
  1682. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1683. time_t FileFd::ModificationTime()
  1684. {
  1685. struct stat Buf;
  1686. if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
  1687. {
  1688. Flags |= Fail;
  1689. return 0;
  1690. }
  1691. return Buf.st_mtime;
  1692. }
  1693. /*}}}*/
  1694. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1695. // ---------------------------------------------------------------------
  1696. /* */
  1697. unsigned long long FileFd::Size()
  1698. {
  1699. unsigned long long size = FileSize();
  1700. // for compressor pipes st_size is undefined and at 'best' zero,
  1701. // so we 'read' the content and 'seek' back - see there
  1702. if (d != NULL && (d->pipe == true || (d->InternalStream() == true && size > 0)))
  1703. {
  1704. unsigned long long const oldSeek = Tell();
  1705. char ignore[1000];
  1706. unsigned long long read = 0;
  1707. do {
  1708. if (Read(ignore, sizeof(ignore), &read) == false)
  1709. {
  1710. Seek(oldSeek);
  1711. return 0;
  1712. }
  1713. } while(read != 0);
  1714. size = Tell();
  1715. Seek(oldSeek);
  1716. }
  1717. #ifdef HAVE_ZLIB
  1718. // only check gzsize if we are actually a gzip file, just checking for
  1719. // "gz" is not sufficient as uncompressed files could be opened with
  1720. // gzopen in "direct" mode as well
  1721. else if (d != NULL && d->gz && !gzdirect(d->gz) && size > 0)
  1722. {
  1723. off_t const oldPos = lseek(iFd,0,SEEK_CUR);
  1724. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1725. * this ourselves; the original (uncompressed) file size is the last 32
  1726. * bits of the file */
  1727. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1728. if (lseek(iFd, -4, SEEK_END) < 0)
  1729. {
  1730. FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1731. return 0;
  1732. }
  1733. uint32_t size = 0;
  1734. if (read(iFd, &size, 4) != 4)
  1735. {
  1736. FileFdErrno("read","Unable to read original size of gzipped file");
  1737. return 0;
  1738. }
  1739. size = le32toh(size);
  1740. if (lseek(iFd, oldPos, SEEK_SET) < 0)
  1741. {
  1742. FileFdErrno("lseek","Unable to seek in gzipped file");
  1743. return 0;
  1744. }
  1745. return size;
  1746. }
  1747. #endif
  1748. return size;
  1749. }
  1750. /*}}}*/
  1751. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1752. // ---------------------------------------------------------------------
  1753. /* */
  1754. bool FileFd::Close()
  1755. {
  1756. if (iFd == -1)
  1757. return true;
  1758. bool Res = true;
  1759. if ((Flags & AutoClose) == AutoClose)
  1760. {
  1761. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  1762. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1763. if (d != NULL)
  1764. {
  1765. Res &= d->CloseDown(FileName);
  1766. delete d;
  1767. d = NULL;
  1768. }
  1769. }
  1770. if ((Flags & Replace) == Replace) {
  1771. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1772. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1773. FileName = TemporaryFileName; // for the unlink() below.
  1774. TemporaryFileName.clear();
  1775. }
  1776. iFd = -1;
  1777. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1778. FileName.empty() == false)
  1779. if (unlink(FileName.c_str()) != 0)
  1780. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1781. if (Res == false)
  1782. Flags |= Fail;
  1783. return Res;
  1784. }
  1785. /*}}}*/
  1786. // FileFd::Sync - Sync the file /*{{{*/
  1787. // ---------------------------------------------------------------------
  1788. /* */
  1789. bool FileFd::Sync()
  1790. {
  1791. if (fsync(iFd) != 0)
  1792. return FileFdErrno("sync",_("Problem syncing the file"));
  1793. return true;
  1794. }
  1795. /*}}}*/
  1796. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  1797. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  1798. {
  1799. Flags |= Fail;
  1800. va_list args;
  1801. size_t msgSize = 400;
  1802. int const errsv = errno;
  1803. while (true)
  1804. {
  1805. va_start(args,Description);
  1806. if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
  1807. break;
  1808. va_end(args);
  1809. }
  1810. return false;
  1811. }
  1812. /*}}}*/
  1813. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  1814. bool FileFd::FileFdError(const char *Description,...) {
  1815. Flags |= Fail;
  1816. va_list args;
  1817. size_t msgSize = 400;
  1818. while (true)
  1819. {
  1820. va_start(args,Description);
  1821. if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
  1822. break;
  1823. va_end(args);
  1824. }
  1825. return false;
  1826. }
  1827. /*}}}*/
  1828. APT_DEPRECATED gzFile FileFd::gzFd() {
  1829. #ifdef HAVE_ZLIB
  1830. return d->gz;
  1831. #else
  1832. return NULL;
  1833. #endif
  1834. }
  1835. // Glob - wrapper around "glob()" /*{{{*/
  1836. // ---------------------------------------------------------------------
  1837. /* */
  1838. std::vector<std::string> Glob(std::string const &pattern, int flags)
  1839. {
  1840. std::vector<std::string> result;
  1841. glob_t globbuf;
  1842. int glob_res;
  1843. unsigned int i;
  1844. glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
  1845. if (glob_res != 0)
  1846. {
  1847. if(glob_res != GLOB_NOMATCH) {
  1848. _error->Errno("glob", "Problem with glob");
  1849. return result;
  1850. }
  1851. }
  1852. // append results
  1853. for(i=0;i<globbuf.gl_pathc;i++)
  1854. result.push_back(string(globbuf.gl_pathv[i]));
  1855. globfree(&globbuf);
  1856. return result;
  1857. }
  1858. /*}}}*/
  1859. std::string GetTempDir()
  1860. {
  1861. const char *tmpdir = getenv("TMPDIR");
  1862. #ifdef P_tmpdir
  1863. if (!tmpdir)
  1864. tmpdir = P_tmpdir;
  1865. #endif
  1866. // check that tmpdir is set and exists
  1867. struct stat st;
  1868. if (!tmpdir || strlen(tmpdir) == 0 || stat(tmpdir, &st) != 0)
  1869. tmpdir = "/tmp";
  1870. return string(tmpdir);
  1871. }
  1872. bool Rename(std::string From, std::string To)
  1873. {
  1874. if (rename(From.c_str(),To.c_str()) != 0)
  1875. {
  1876. _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
  1877. From.c_str(),To.c_str());
  1878. return false;
  1879. }
  1880. return true;
  1881. }