fileutl.cc 41 KB

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