fileutl.cc 44 KB

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