fileutl.cc 48 KB

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