fileutl.cc 49 KB

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