fileutl.cc 49 KB

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