fileutl.cc 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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. if (SilentIgnore.Match(Ent->d_name) == false)
  344. _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
  345. continue;
  346. }
  347. }
  348. // check for accepted extension:
  349. // no extension given -> periods are bad as hell!
  350. // extensions given -> "" extension allows no extension
  351. if (Ext.empty() == false)
  352. {
  353. string d_ext = flExtension(Ent->d_name);
  354. if (d_ext == Ent->d_name) // no extension
  355. {
  356. if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
  357. {
  358. if (Debug == true)
  359. std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
  360. if (SilentIgnore.Match(Ent->d_name) == false)
  361. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
  362. continue;
  363. }
  364. }
  365. else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
  366. {
  367. if (Debug == true)
  368. std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
  369. if (SilentIgnore.Match(Ent->d_name) == false)
  370. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
  371. continue;
  372. }
  373. }
  374. // Skip bad filenames ala run-parts
  375. const char *C = Ent->d_name;
  376. for (; *C != 0; ++C)
  377. if (isalpha(*C) == 0 && isdigit(*C) == 0
  378. && *C != '_' && *C != '-') {
  379. // no required extension -> dot is a bad character
  380. if (*C == '.' && Ext.empty() == false)
  381. continue;
  382. break;
  383. }
  384. // we don't reach the end of the name -> bad character included
  385. if (*C != 0)
  386. {
  387. if (Debug == true)
  388. std::clog << "Bad file: " << Ent->d_name << " → bad character »"
  389. << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
  390. continue;
  391. }
  392. // skip filenames which end with a period. These are never valid
  393. if (*(C - 1) == '.')
  394. {
  395. if (Debug == true)
  396. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  397. continue;
  398. }
  399. if (Debug == true)
  400. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  401. List.push_back(File);
  402. }
  403. closedir(D);
  404. if (SortList == true)
  405. std::sort(List.begin(),List.end());
  406. return List;
  407. }
  408. /*}}}*/
  409. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  410. // ---------------------------------------------------------------------
  411. /* We return / on failure. */
  412. string SafeGetCWD()
  413. {
  414. // Stash the current dir.
  415. char S[300];
  416. S[0] = 0;
  417. if (getcwd(S,sizeof(S)-2) == 0)
  418. return "/";
  419. unsigned int Len = strlen(S);
  420. S[Len] = '/';
  421. S[Len+1] = 0;
  422. return S;
  423. }
  424. /*}}}*/
  425. // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
  426. // ---------------------------------------------------------------------
  427. /* We return / on failure. */
  428. time_t GetModificationTime(string const &Path)
  429. {
  430. struct stat St;
  431. if (stat(Path.c_str(), &St) < 0)
  432. return -1;
  433. return St.st_mtime;
  434. }
  435. /*}}}*/
  436. // flNotDir - Strip the directory from the filename /*{{{*/
  437. // ---------------------------------------------------------------------
  438. /* */
  439. string flNotDir(string File)
  440. {
  441. string::size_type Res = File.rfind('/');
  442. if (Res == string::npos)
  443. return File;
  444. Res++;
  445. return string(File,Res,Res - File.length());
  446. }
  447. /*}}}*/
  448. // flNotFile - Strip the file from the directory name /*{{{*/
  449. // ---------------------------------------------------------------------
  450. /* Result ends in a / */
  451. string flNotFile(string File)
  452. {
  453. string::size_type Res = File.rfind('/');
  454. if (Res == string::npos)
  455. return "./";
  456. Res++;
  457. return string(File,0,Res);
  458. }
  459. /*}}}*/
  460. // flExtension - Return the extension for the file /*{{{*/
  461. // ---------------------------------------------------------------------
  462. /* */
  463. string flExtension(string File)
  464. {
  465. string::size_type Res = File.rfind('.');
  466. if (Res == string::npos)
  467. return File;
  468. Res++;
  469. return string(File,Res,Res - File.length());
  470. }
  471. /*}}}*/
  472. // flNoLink - If file is a symlink then deref it /*{{{*/
  473. // ---------------------------------------------------------------------
  474. /* If the name is not a link then the returned path is the input. */
  475. string flNoLink(string File)
  476. {
  477. struct stat St;
  478. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  479. return File;
  480. if (stat(File.c_str(),&St) != 0)
  481. return File;
  482. /* Loop resolving the link. There is no need to limit the number of
  483. loops because the stat call above ensures that the symlink is not
  484. circular */
  485. char Buffer[1024];
  486. string NFile = File;
  487. while (1)
  488. {
  489. // Read the link
  490. int Res;
  491. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  492. (unsigned)Res >= sizeof(Buffer))
  493. return File;
  494. // Append or replace the previous path
  495. Buffer[Res] = 0;
  496. if (Buffer[0] == '/')
  497. NFile = Buffer;
  498. else
  499. NFile = flNotFile(NFile) + Buffer;
  500. // See if we are done
  501. if (lstat(NFile.c_str(),&St) != 0)
  502. return File;
  503. if (S_ISLNK(St.st_mode) == 0)
  504. return NFile;
  505. }
  506. }
  507. /*}}}*/
  508. // flCombine - Combine a file and a directory /*{{{*/
  509. // ---------------------------------------------------------------------
  510. /* If the file is an absolute path then it is just returned, otherwise
  511. the directory is pre-pended to it. */
  512. string flCombine(string Dir,string File)
  513. {
  514. if (File.empty() == true)
  515. return string();
  516. if (File[0] == '/' || Dir.empty() == true)
  517. return File;
  518. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  519. return File;
  520. if (Dir[Dir.length()-1] == '/')
  521. return Dir + File;
  522. return Dir + '/' + File;
  523. }
  524. /*}}}*/
  525. // SetCloseExec - Set the close on exec flag /*{{{*/
  526. // ---------------------------------------------------------------------
  527. /* */
  528. void SetCloseExec(int Fd,bool Close)
  529. {
  530. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  531. {
  532. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  533. exit(100);
  534. }
  535. }
  536. /*}}}*/
  537. // SetNonBlock - Set the nonblocking flag /*{{{*/
  538. // ---------------------------------------------------------------------
  539. /* */
  540. void SetNonBlock(int Fd,bool Block)
  541. {
  542. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  543. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  544. {
  545. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  546. exit(100);
  547. }
  548. }
  549. /*}}}*/
  550. // WaitFd - Wait for a FD to become readable /*{{{*/
  551. // ---------------------------------------------------------------------
  552. /* This waits for a FD to become readable using select. It is useful for
  553. applications making use of non-blocking sockets. The timeout is
  554. in seconds. */
  555. bool WaitFd(int Fd,bool write,unsigned long timeout)
  556. {
  557. fd_set Set;
  558. struct timeval tv;
  559. FD_ZERO(&Set);
  560. FD_SET(Fd,&Set);
  561. tv.tv_sec = timeout;
  562. tv.tv_usec = 0;
  563. if (write == true)
  564. {
  565. int Res;
  566. do
  567. {
  568. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  569. }
  570. while (Res < 0 && errno == EINTR);
  571. if (Res <= 0)
  572. return false;
  573. }
  574. else
  575. {
  576. int Res;
  577. do
  578. {
  579. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  580. }
  581. while (Res < 0 && errno == EINTR);
  582. if (Res <= 0)
  583. return false;
  584. }
  585. return true;
  586. }
  587. /*}}}*/
  588. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* This is used if you want to cleanse the environment for the forked
  591. child, it fixes up the important signals and nukes all of the fds,
  592. otherwise acts like normal fork. */
  593. pid_t ExecFork()
  594. {
  595. // Fork off the process
  596. pid_t Process = fork();
  597. if (Process < 0)
  598. {
  599. cerr << "FATAL -> Failed to fork." << endl;
  600. exit(100);
  601. }
  602. // Spawn the subprocess
  603. if (Process == 0)
  604. {
  605. // Setup the signals
  606. signal(SIGPIPE,SIG_DFL);
  607. signal(SIGQUIT,SIG_DFL);
  608. signal(SIGINT,SIG_DFL);
  609. signal(SIGWINCH,SIG_DFL);
  610. signal(SIGCONT,SIG_DFL);
  611. signal(SIGTSTP,SIG_DFL);
  612. set<int> KeepFDs;
  613. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  614. if (Opts != 0 && Opts->Child != 0)
  615. {
  616. Opts = Opts->Child;
  617. for (; Opts != 0; Opts = Opts->Next)
  618. {
  619. if (Opts->Value.empty() == true)
  620. continue;
  621. int fd = atoi(Opts->Value.c_str());
  622. KeepFDs.insert(fd);
  623. }
  624. }
  625. // Close all of our FDs - just in case
  626. for (int K = 3; K != 40; K++)
  627. {
  628. if(KeepFDs.find(K) == KeepFDs.end())
  629. fcntl(K,F_SETFD,FD_CLOEXEC);
  630. }
  631. }
  632. return Process;
  633. }
  634. /*}}}*/
  635. // ExecWait - Fancy waitpid /*{{{*/
  636. // ---------------------------------------------------------------------
  637. /* Waits for the given sub process. If Reap is set then no errors are
  638. generated. Otherwise a failed subprocess will generate a proper descriptive
  639. message */
  640. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  641. {
  642. if (Pid <= 1)
  643. return true;
  644. // Wait and collect the error code
  645. int Status;
  646. while (waitpid(Pid,&Status,0) != Pid)
  647. {
  648. if (errno == EINTR)
  649. continue;
  650. if (Reap == true)
  651. return false;
  652. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  653. }
  654. // Check for an error code.
  655. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  656. {
  657. if (Reap == true)
  658. return false;
  659. if (WIFSIGNALED(Status) != 0)
  660. {
  661. if( WTERMSIG(Status) == SIGSEGV)
  662. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  663. else
  664. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  665. }
  666. if (WIFEXITED(Status) != 0)
  667. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  668. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  669. }
  670. return true;
  671. }
  672. /*}}}*/
  673. // FileFd::Open - Open a file /*{{{*/
  674. // ---------------------------------------------------------------------
  675. /* The most commonly used open mode combinations are given with Mode */
  676. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const Perms)
  677. {
  678. if (Mode == ReadOnlyGzip)
  679. return Open(FileName, ReadOnly, Gzip, Perms);
  680. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  681. return _error->Error("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  682. // FIXME: Denote inbuilt compressors somehow - as we don't need to have the binaries for them
  683. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  684. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  685. if (Compress == Auto)
  686. {
  687. for (; compressor != compressors.end(); ++compressor)
  688. {
  689. std::string file = std::string(FileName).append(compressor->Extension);
  690. if (FileExists(file) == false)
  691. continue;
  692. FileName = file;
  693. break;
  694. }
  695. }
  696. else if (Compress == Extension)
  697. {
  698. std::string::size_type const found = FileName.find_last_of('.');
  699. std::string ext;
  700. if (found != std::string::npos)
  701. {
  702. ext = FileName.substr(found);
  703. if (ext == ".new" || ext == ".bak")
  704. {
  705. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  706. if (found2 != std::string::npos)
  707. ext = FileName.substr(found2, found - found2);
  708. else
  709. ext.clear();
  710. }
  711. }
  712. for (; compressor != compressors.end(); ++compressor)
  713. if (ext == compressor->Extension)
  714. break;
  715. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  716. if (compressor == compressors.end())
  717. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  718. if (compressor->Name == ".")
  719. break;
  720. }
  721. else
  722. {
  723. std::string name;
  724. switch (Compress)
  725. {
  726. case None: name = "."; break;
  727. case Gzip: name = "gzip"; break;
  728. case Bzip2: name = "bzip2"; break;
  729. case Lzma: name = "lzma"; break;
  730. case Xz: name = "xz"; break;
  731. case Auto:
  732. case Extension:
  733. // Unreachable
  734. return _error->Error("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  735. }
  736. for (; compressor != compressors.end(); ++compressor)
  737. if (compressor->Name == name)
  738. break;
  739. if (compressor == compressors.end())
  740. return _error->Error("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  741. }
  742. if (compressor == compressors.end())
  743. return _error->Error("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  744. return Open(FileName, Mode, *compressor, Perms);
  745. }
  746. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const Perms)
  747. {
  748. Close();
  749. d = new FileFdPrivate;
  750. d->openmode = Mode;
  751. Flags = AutoClose;
  752. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  753. return _error->Error("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  754. if ((Mode & ReadWrite) == 0)
  755. return _error->Error("No openmode provided in FileFd::Open for %s", FileName.c_str());
  756. if ((Mode & Atomic) == Atomic)
  757. {
  758. Flags |= Replace;
  759. char *name = strdup((FileName + ".XXXXXX").c_str());
  760. TemporaryFileName = string(mktemp(name));
  761. free(name);
  762. }
  763. else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
  764. {
  765. // for atomic, this will be done by rename in Close()
  766. unlink(FileName.c_str());
  767. }
  768. if ((Mode & Empty) == Empty)
  769. {
  770. struct stat Buf;
  771. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  772. unlink(FileName.c_str());
  773. }
  774. int fileflags = 0;
  775. #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
  776. if_FLAGGED_SET(ReadWrite, O_RDWR);
  777. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  778. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  779. if_FLAGGED_SET(Create, O_CREAT);
  780. if_FLAGGED_SET(Empty, O_TRUNC);
  781. if_FLAGGED_SET(Exclusive, O_EXCL);
  782. else if_FLAGGED_SET(Atomic, O_EXCL);
  783. #undef if_FLAGGED_SET
  784. if (TemporaryFileName.empty() == false)
  785. iFd = open(TemporaryFileName.c_str(), fileflags, Perms);
  786. else
  787. iFd = open(FileName.c_str(), fileflags, Perms);
  788. this->FileName = FileName;
  789. if (iFd == -1 || OpenInternDescriptor(Mode, compressor) == false)
  790. {
  791. if (iFd != -1)
  792. {
  793. close (iFd);
  794. iFd = -1;
  795. }
  796. return _error->Errno("open",_("Could not open file %s"), FileName.c_str());
  797. }
  798. SetCloseExec(iFd,true);
  799. return true;
  800. }
  801. /*}}}*/
  802. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  803. // ---------------------------------------------------------------------
  804. /* */
  805. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  806. {
  807. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  808. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  809. std::string name;
  810. switch (Compress)
  811. {
  812. case None: name = "."; break;
  813. case Gzip: name = "gzip"; break;
  814. case Bzip2: name = "bzip2"; break;
  815. case Lzma: name = "lzma"; break;
  816. case Xz: name = "xz"; break;
  817. case Auto:
  818. case Extension:
  819. return _error->Error("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  820. }
  821. for (; compressor != compressors.end(); ++compressor)
  822. if (compressor->Name == name)
  823. break;
  824. if (compressor == compressors.end())
  825. return _error->Error("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  826. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  827. }
  828. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  829. {
  830. Close();
  831. d = new FileFdPrivate;
  832. d->openmode = Mode;
  833. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  834. iFd = Fd;
  835. this->FileName = "";
  836. if (OpenInternDescriptor(Mode, compressor) == false)
  837. {
  838. if (AutoClose)
  839. close (iFd);
  840. return _error->Errno("gzdopen",_("Could not open file descriptor %d"), Fd);
  841. }
  842. return true;
  843. }
  844. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  845. {
  846. d->compressor = compressor;
  847. if (compressor.Name == "." || compressor.Binary.empty() == true)
  848. return true;
  849. #if APT_USE_ZLIB
  850. else if (compressor.Name == "gzip")
  851. {
  852. if ((Mode & ReadWrite) == ReadWrite)
  853. d->gz = gzdopen(iFd, "r+");
  854. else if ((Mode & WriteOnly) == WriteOnly)
  855. d->gz = gzdopen(iFd, "w");
  856. else
  857. d->gz = gzdopen (iFd, "r");
  858. if (d->gz == NULL)
  859. return false;
  860. Flags |= Compressed;
  861. return true;
  862. }
  863. #endif
  864. if ((Mode & ReadWrite) == ReadWrite)
  865. return _error->Error("ReadWrite mode is not supported for file %s", FileName.c_str());
  866. bool const Comp = (Mode & WriteOnly) == WriteOnly;
  867. // Handle 'decompression' of empty files
  868. if (Comp == false)
  869. {
  870. struct stat Buf;
  871. fstat(iFd, &Buf);
  872. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  873. return true;
  874. // We don't need the file open - instead let the compressor open it
  875. // as he properly knows better how to efficiently read from 'his' file
  876. if (FileName.empty() == false)
  877. close(iFd);
  878. }
  879. // Create a data pipe
  880. int Pipe[2] = {-1,-1};
  881. if (pipe(Pipe) != 0)
  882. return _error->Errno("pipe",_("Failed to create subprocess IPC"));
  883. for (int J = 0; J != 2; J++)
  884. SetCloseExec(Pipe[J],true);
  885. d->compressed_fd = iFd;
  886. d->pipe = true;
  887. if (Comp == true)
  888. iFd = Pipe[1];
  889. else
  890. iFd = Pipe[0];
  891. // The child..
  892. d->compressor_pid = ExecFork();
  893. if (d->compressor_pid == 0)
  894. {
  895. if (Comp == true)
  896. {
  897. dup2(d->compressed_fd,STDOUT_FILENO);
  898. dup2(Pipe[0],STDIN_FILENO);
  899. }
  900. else
  901. {
  902. if (FileName.empty() == true)
  903. dup2(d->compressed_fd,STDIN_FILENO);
  904. dup2(Pipe[1],STDOUT_FILENO);
  905. }
  906. SetCloseExec(STDOUT_FILENO,false);
  907. SetCloseExec(STDIN_FILENO,false);
  908. std::vector<char const*> Args;
  909. Args.push_back(compressor.Binary.c_str());
  910. std::vector<std::string> const * const addArgs =
  911. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  912. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  913. a != addArgs->end(); ++a)
  914. Args.push_back(a->c_str());
  915. if (Comp == false && FileName.empty() == false)
  916. {
  917. Args.push_back("--stdout");
  918. if (TemporaryFileName.empty() == false)
  919. Args.push_back(TemporaryFileName.c_str());
  920. else
  921. Args.push_back(FileName.c_str());
  922. }
  923. Args.push_back(NULL);
  924. execvp(Args[0],(char **)&Args[0]);
  925. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  926. _exit(100);
  927. }
  928. if (Comp == true)
  929. close(Pipe[0]);
  930. else
  931. close(Pipe[1]);
  932. if (Comp == true || FileName.empty() == true)
  933. close(d->compressed_fd);
  934. return true;
  935. }
  936. /*}}}*/
  937. // FileFd::~File - Closes the file /*{{{*/
  938. // ---------------------------------------------------------------------
  939. /* If the proper modes are selected then we close the Fd and possibly
  940. unlink the file on error. */
  941. FileFd::~FileFd()
  942. {
  943. Close();
  944. }
  945. /*}}}*/
  946. // FileFd::Read - Read a bit of the file /*{{{*/
  947. // ---------------------------------------------------------------------
  948. /* We are carefull to handle interruption by a signal while reading
  949. gracefully. */
  950. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  951. {
  952. int Res;
  953. errno = 0;
  954. if (Actual != 0)
  955. *Actual = 0;
  956. *((char *)To) = '\0';
  957. do
  958. {
  959. #if APT_USE_ZLIB
  960. if (d->gz != NULL)
  961. Res = gzread(d->gz,To,Size);
  962. else
  963. #endif
  964. Res = read(iFd,To,Size);
  965. if (Res < 0)
  966. {
  967. if (errno == EINTR)
  968. continue;
  969. Flags |= Fail;
  970. #if APT_USE_ZLIB
  971. if (d->gz != NULL)
  972. {
  973. int err;
  974. char const * const errmsg = gzerror(d->gz, &err);
  975. if (err != Z_ERRNO)
  976. return _error->Error("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  977. }
  978. #endif
  979. return _error->Errno("read",_("Read error"));
  980. }
  981. To = (char *)To + Res;
  982. Size -= Res;
  983. d->seekpos += Res;
  984. if (Actual != 0)
  985. *Actual += Res;
  986. }
  987. while (Res > 0 && Size > 0);
  988. if (Size == 0)
  989. return true;
  990. // Eof handling
  991. if (Actual != 0)
  992. {
  993. Flags |= HitEof;
  994. return true;
  995. }
  996. Flags |= Fail;
  997. return _error->Error(_("read, still have %llu to read but none left"), Size);
  998. }
  999. /*}}}*/
  1000. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  1001. // ---------------------------------------------------------------------
  1002. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  1003. files because of the naive implementation! */
  1004. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  1005. {
  1006. *To = '\0';
  1007. #if APT_USE_ZLIB
  1008. if (d->gz != NULL)
  1009. return gzgets(d->gz, To, Size);
  1010. #endif
  1011. unsigned long long read = 0;
  1012. while ((Size - 1) != read)
  1013. {
  1014. unsigned long long done = 0;
  1015. if (Read(To + read, 1, &done) == false)
  1016. return NULL;
  1017. if (done == 0)
  1018. break;
  1019. if (To[read++] == '\n')
  1020. break;
  1021. }
  1022. if (read == 0)
  1023. return NULL;
  1024. To[read] = '\0';
  1025. return To;
  1026. }
  1027. /*}}}*/
  1028. // FileFd::Write - Write to the file /*{{{*/
  1029. // ---------------------------------------------------------------------
  1030. /* */
  1031. bool FileFd::Write(const void *From,unsigned long long Size)
  1032. {
  1033. int Res;
  1034. errno = 0;
  1035. do
  1036. {
  1037. #if APT_USE_ZLIB
  1038. if (d->gz != NULL)
  1039. Res = gzwrite(d->gz,From,Size);
  1040. else
  1041. #endif
  1042. Res = write(iFd,From,Size);
  1043. if (Res < 0 && errno == EINTR)
  1044. continue;
  1045. if (Res < 0)
  1046. {
  1047. Flags |= Fail;
  1048. return _error->Errno("write",_("Write error"));
  1049. }
  1050. From = (char *)From + Res;
  1051. Size -= Res;
  1052. d->seekpos += Res;
  1053. }
  1054. while (Res > 0 && Size > 0);
  1055. if (Size == 0)
  1056. return true;
  1057. Flags |= Fail;
  1058. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  1059. }
  1060. /*}}}*/
  1061. // FileFd::Seek - Seek in the file /*{{{*/
  1062. // ---------------------------------------------------------------------
  1063. /* */
  1064. bool FileFd::Seek(unsigned long long To)
  1065. {
  1066. if (d->pipe == true)
  1067. {
  1068. // Our poor man seeking in pipes is costly, so try to avoid it
  1069. unsigned long long seekpos = Tell();
  1070. if (seekpos == To)
  1071. return true;
  1072. else if (seekpos < To)
  1073. return Skip(To - seekpos);
  1074. if ((d->openmode & ReadOnly) != ReadOnly)
  1075. return _error->Error("Reopen is only implemented for read-only files!");
  1076. close(iFd);
  1077. iFd = 0;
  1078. if (TemporaryFileName.empty() == false)
  1079. iFd = open(TemporaryFileName.c_str(), O_RDONLY);
  1080. else if (FileName.empty() == false)
  1081. iFd = open(FileName.c_str(), O_RDONLY);
  1082. else
  1083. {
  1084. if (d->compressed_fd > 0)
  1085. if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
  1086. iFd = d->compressed_fd;
  1087. if (iFd <= 0)
  1088. return _error->Error("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1089. }
  1090. if (OpenInternDescriptor(d->openmode, d->compressor) == false)
  1091. return _error->Error("Seek on file %s because it couldn't be reopened", FileName.c_str());
  1092. if (To != 0)
  1093. return Skip(To);
  1094. d->seekpos = To;
  1095. return true;
  1096. }
  1097. int res;
  1098. #if APT_USE_ZLIB
  1099. if (d->gz)
  1100. res = gzseek(d->gz,To,SEEK_SET);
  1101. else
  1102. #endif
  1103. res = lseek(iFd,To,SEEK_SET);
  1104. if (res != (signed)To)
  1105. {
  1106. Flags |= Fail;
  1107. return _error->Error("Unable to seek to %llu", To);
  1108. }
  1109. d->seekpos = To;
  1110. return true;
  1111. }
  1112. /*}}}*/
  1113. // FileFd::Skip - Seek in the file /*{{{*/
  1114. // ---------------------------------------------------------------------
  1115. /* */
  1116. bool FileFd::Skip(unsigned long long Over)
  1117. {
  1118. if (d->pipe == true)
  1119. {
  1120. d->seekpos += Over;
  1121. char buffer[1024];
  1122. while (Over != 0)
  1123. {
  1124. unsigned long long toread = std::min((unsigned long long) sizeof(buffer), Over);
  1125. if (Read(buffer, toread) == false)
  1126. return _error->Error("Unable to seek ahead %llu",Over);
  1127. Over -= toread;
  1128. }
  1129. return true;
  1130. }
  1131. int res;
  1132. #if APT_USE_ZLIB
  1133. if (d->gz != NULL)
  1134. res = gzseek(d->gz,Over,SEEK_CUR);
  1135. else
  1136. #endif
  1137. res = lseek(iFd,Over,SEEK_CUR);
  1138. if (res < 0)
  1139. {
  1140. Flags |= Fail;
  1141. return _error->Error("Unable to seek ahead %llu",Over);
  1142. }
  1143. d->seekpos = res;
  1144. return true;
  1145. }
  1146. /*}}}*/
  1147. // FileFd::Truncate - Truncate the file /*{{{*/
  1148. // ---------------------------------------------------------------------
  1149. /* */
  1150. bool FileFd::Truncate(unsigned long long To)
  1151. {
  1152. if (d->gz != NULL)
  1153. {
  1154. Flags |= Fail;
  1155. return _error->Error("Truncating gzipped files is not implemented (%s)", FileName.c_str());
  1156. }
  1157. if (ftruncate(iFd,To) != 0)
  1158. {
  1159. Flags |= Fail;
  1160. return _error->Error("Unable to truncate to %llu",To);
  1161. }
  1162. return true;
  1163. }
  1164. /*}}}*/
  1165. // FileFd::Tell - Current seek position /*{{{*/
  1166. // ---------------------------------------------------------------------
  1167. /* */
  1168. unsigned long long FileFd::Tell()
  1169. {
  1170. // In theory, we could just return seekpos here always instead of
  1171. // seeking around, but not all users of FileFd use always Seek() and co
  1172. // so d->seekpos isn't always true and we can just use it as a hint if
  1173. // we have nothing else, but not always as an authority…
  1174. if (d->pipe == true)
  1175. return d->seekpos;
  1176. off_t Res;
  1177. #if APT_USE_ZLIB
  1178. if (d->gz != NULL)
  1179. Res = gztell(d->gz);
  1180. else
  1181. #endif
  1182. Res = lseek(iFd,0,SEEK_CUR);
  1183. if (Res == (off_t)-1)
  1184. _error->Errno("lseek","Failed to determine the current file position");
  1185. d->seekpos = Res;
  1186. return Res;
  1187. }
  1188. /*}}}*/
  1189. // FileFd::FileSize - Return the size of the file /*{{{*/
  1190. // ---------------------------------------------------------------------
  1191. /* */
  1192. unsigned long long FileFd::FileSize()
  1193. {
  1194. struct stat Buf;
  1195. if (d->pipe == false && fstat(iFd,&Buf) != 0)
  1196. return _error->Errno("fstat","Unable to determine the file size");
  1197. // for compressor pipes st_size is undefined and at 'best' zero
  1198. if (d->pipe == true || S_ISFIFO(Buf.st_mode))
  1199. {
  1200. // we set it here, too, as we get the info here for free
  1201. // in theory the Open-methods should take care of it already
  1202. d->pipe = true;
  1203. if (stat(FileName.c_str(), &Buf) != 0)
  1204. return _error->Errno("stat","Unable to determine the file size");
  1205. }
  1206. return Buf.st_size;
  1207. }
  1208. /*}}}*/
  1209. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1210. // ---------------------------------------------------------------------
  1211. /* */
  1212. unsigned long long FileFd::Size()
  1213. {
  1214. unsigned long long size = FileSize();
  1215. // for compressor pipes st_size is undefined and at 'best' zero,
  1216. // so we 'read' the content and 'seek' back - see there
  1217. if (d->pipe == true)
  1218. {
  1219. unsigned long long const oldSeek = Tell();
  1220. char ignore[1000];
  1221. unsigned long long read = 0;
  1222. do {
  1223. Read(ignore, sizeof(ignore), &read);
  1224. } while(read != 0);
  1225. size = Tell();
  1226. Seek(oldSeek);
  1227. }
  1228. #if APT_USE_ZLIB
  1229. // only check gzsize if we are actually a gzip file, just checking for
  1230. // "gz" is not sufficient as uncompressed files could be opened with
  1231. // gzopen in "direct" mode as well
  1232. else if (d->gz && !gzdirect(d->gz) && size > 0)
  1233. {
  1234. off_t const oldPos = lseek(iFd,0,SEEK_CUR);
  1235. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1236. * this ourselves; the original (uncompressed) file size is the last 32
  1237. * bits of the file */
  1238. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1239. if (lseek(iFd, -4, SEEK_END) < 0)
  1240. return _error->Errno("lseek","Unable to seek to end of gzipped file");
  1241. size = 0L;
  1242. if (read(iFd, &size, 4) != 4)
  1243. return _error->Errno("read","Unable to read original size of gzipped file");
  1244. #ifdef WORDS_BIGENDIAN
  1245. uint32_t tmp_size = size;
  1246. uint8_t const * const p = (uint8_t const * const) &tmp_size;
  1247. tmp_size = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
  1248. size = tmp_size;
  1249. #endif
  1250. if (lseek(iFd, oldPos, SEEK_SET) < 0)
  1251. return _error->Errno("lseek","Unable to seek in gzipped file");
  1252. return size;
  1253. }
  1254. #endif
  1255. return size;
  1256. }
  1257. /*}}}*/
  1258. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1259. // ---------------------------------------------------------------------
  1260. /* */
  1261. time_t FileFd::ModificationTime()
  1262. {
  1263. struct stat Buf;
  1264. if (d->pipe == false && fstat(iFd,&Buf) != 0)
  1265. {
  1266. _error->Errno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
  1267. return 0;
  1268. }
  1269. // for compressor pipes st_size is undefined and at 'best' zero
  1270. if (d->pipe == true || S_ISFIFO(Buf.st_mode))
  1271. {
  1272. // we set it here, too, as we get the info here for free
  1273. // in theory the Open-methods should take care of it already
  1274. d->pipe = true;
  1275. if (stat(FileName.c_str(), &Buf) != 0)
  1276. {
  1277. _error->Errno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
  1278. return 0;
  1279. }
  1280. }
  1281. return Buf.st_mtime;
  1282. }
  1283. /*}}}*/
  1284. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1285. // ---------------------------------------------------------------------
  1286. /* */
  1287. bool FileFd::Close()
  1288. {
  1289. if (iFd == -1)
  1290. return true;
  1291. bool Res = true;
  1292. if ((Flags & AutoClose) == AutoClose)
  1293. {
  1294. #if APT_USE_ZLIB
  1295. if (d != NULL && d->gz != NULL) {
  1296. int const e = gzclose(d->gz);
  1297. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  1298. if (e != 0 && e != Z_BUF_ERROR)
  1299. Res &= _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  1300. } else
  1301. #endif
  1302. if (iFd > 0 && close(iFd) != 0)
  1303. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1304. }
  1305. if ((Flags & Replace) == Replace && iFd >= 0) {
  1306. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1307. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1308. FileName = TemporaryFileName; // for the unlink() below.
  1309. TemporaryFileName.clear();
  1310. }
  1311. iFd = -1;
  1312. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1313. FileName.empty() == false)
  1314. if (unlink(FileName.c_str()) != 0)
  1315. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1316. if (d != NULL)
  1317. {
  1318. if (d->compressor_pid > 0)
  1319. ExecWait(d->compressor_pid, "FileFdCompressor", true);
  1320. delete d;
  1321. d = NULL;
  1322. }
  1323. return Res;
  1324. }
  1325. /*}}}*/
  1326. // FileFd::Sync - Sync the file /*{{{*/
  1327. // ---------------------------------------------------------------------
  1328. /* */
  1329. bool FileFd::Sync()
  1330. {
  1331. #ifdef _POSIX_SYNCHRONIZED_IO
  1332. if (fsync(iFd) != 0)
  1333. return _error->Errno("sync",_("Problem syncing the file"));
  1334. #endif
  1335. return true;
  1336. }
  1337. /*}}}*/
  1338. gzFile FileFd::gzFd() { return (gzFile) d->gz; }