fileutl.cc 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  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) == 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) == 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) == 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) == 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) == 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 FileFdError("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 FileFdError("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 FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  838. }
  839. if (compressor == compressors.end())
  840. return FileFdError("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 FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  849. if ((Mode & ReadWrite) == 0)
  850. return FileFdError("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 FileFdErrno("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 FileFdError("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 FileFdError("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 FileFdErrno("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. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1008. bool const Comp = (Mode & WriteOnly) == WriteOnly;
  1009. if (Comp == false)
  1010. {
  1011. // Handle 'decompression' of empty files
  1012. struct stat Buf;
  1013. fstat(iFd, &Buf);
  1014. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1015. return true;
  1016. // We don't need the file open - instead let the compressor open it
  1017. // as he properly knows better how to efficiently read from 'his' file
  1018. if (FileName.empty() == false)
  1019. {
  1020. close(iFd);
  1021. iFd = -1;
  1022. }
  1023. }
  1024. // Create a data pipe
  1025. int Pipe[2] = {-1,-1};
  1026. if (pipe(Pipe) != 0)
  1027. return FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1028. for (int J = 0; J != 2; J++)
  1029. SetCloseExec(Pipe[J],true);
  1030. d->compressed_fd = iFd;
  1031. d->pipe = true;
  1032. if (Comp == true)
  1033. iFd = Pipe[1];
  1034. else
  1035. iFd = Pipe[0];
  1036. // The child..
  1037. d->compressor_pid = ExecFork();
  1038. if (d->compressor_pid == 0)
  1039. {
  1040. if (Comp == true)
  1041. {
  1042. dup2(d->compressed_fd,STDOUT_FILENO);
  1043. dup2(Pipe[0],STDIN_FILENO);
  1044. }
  1045. else
  1046. {
  1047. if (FileName.empty() == true)
  1048. dup2(d->compressed_fd,STDIN_FILENO);
  1049. dup2(Pipe[1],STDOUT_FILENO);
  1050. }
  1051. int const nullfd = open("/dev/null", O_WRONLY);
  1052. if (nullfd != -1)
  1053. {
  1054. dup2(nullfd,STDERR_FILENO);
  1055. close(nullfd);
  1056. }
  1057. SetCloseExec(STDOUT_FILENO,false);
  1058. SetCloseExec(STDIN_FILENO,false);
  1059. std::vector<char const*> Args;
  1060. Args.push_back(compressor.Binary.c_str());
  1061. std::vector<std::string> const * const addArgs =
  1062. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1063. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1064. a != addArgs->end(); ++a)
  1065. Args.push_back(a->c_str());
  1066. if (Comp == false && FileName.empty() == false)
  1067. {
  1068. Args.push_back("--stdout");
  1069. if (TemporaryFileName.empty() == false)
  1070. Args.push_back(TemporaryFileName.c_str());
  1071. else
  1072. Args.push_back(FileName.c_str());
  1073. }
  1074. Args.push_back(NULL);
  1075. execvp(Args[0],(char **)&Args[0]);
  1076. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1077. _exit(100);
  1078. }
  1079. if (Comp == true)
  1080. close(Pipe[0]);
  1081. else
  1082. close(Pipe[1]);
  1083. return true;
  1084. }
  1085. /*}}}*/
  1086. // FileFd::~File - Closes the file /*{{{*/
  1087. // ---------------------------------------------------------------------
  1088. /* If the proper modes are selected then we close the Fd and possibly
  1089. unlink the file on error. */
  1090. FileFd::~FileFd()
  1091. {
  1092. Close();
  1093. if (d != NULL)
  1094. {
  1095. d->CloseDown(FileName);
  1096. delete d;
  1097. d = NULL;
  1098. }
  1099. }
  1100. /*}}}*/
  1101. // FileFd::Read - Read a bit of the file /*{{{*/
  1102. // ---------------------------------------------------------------------
  1103. /* We are carefull to handle interruption by a signal while reading
  1104. gracefully. */
  1105. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  1106. {
  1107. int Res;
  1108. errno = 0;
  1109. if (Actual != 0)
  1110. *Actual = 0;
  1111. *((char *)To) = '\0';
  1112. do
  1113. {
  1114. #ifdef HAVE_ZLIB
  1115. if (d != NULL && d->gz != NULL)
  1116. Res = gzread(d->gz,To,Size);
  1117. else
  1118. #endif
  1119. #ifdef HAVE_BZ2
  1120. if (d != NULL && d->bz2 != NULL)
  1121. Res = BZ2_bzread(d->bz2,To,Size);
  1122. else
  1123. #endif
  1124. Res = read(iFd,To,Size);
  1125. if (Res < 0)
  1126. {
  1127. if (errno == EINTR)
  1128. continue;
  1129. #ifdef HAVE_ZLIB
  1130. if (d != NULL && d->gz != NULL)
  1131. {
  1132. int err;
  1133. char const * const errmsg = gzerror(d->gz, &err);
  1134. if (err != Z_ERRNO)
  1135. return FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1136. }
  1137. #endif
  1138. #ifdef HAVE_BZ2
  1139. if (d != NULL && d->bz2 != NULL)
  1140. {
  1141. int err;
  1142. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1143. if (err != BZ_IO_ERROR)
  1144. return FileFdError("BZ2_bzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1145. }
  1146. #endif
  1147. return FileFdErrno("read",_("Read error"));
  1148. }
  1149. To = (char *)To + Res;
  1150. Size -= Res;
  1151. if (d != NULL)
  1152. d->seekpos += Res;
  1153. if (Actual != 0)
  1154. *Actual += Res;
  1155. }
  1156. while (Res > 0 && Size > 0);
  1157. if (Size == 0)
  1158. return true;
  1159. // Eof handling
  1160. if (Actual != 0)
  1161. {
  1162. Flags |= HitEof;
  1163. return true;
  1164. }
  1165. return FileFdError(_("read, still have %llu to read but none left"), Size);
  1166. }
  1167. /*}}}*/
  1168. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  1169. // ---------------------------------------------------------------------
  1170. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  1171. files because of the naive implementation! */
  1172. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  1173. {
  1174. *To = '\0';
  1175. #ifdef HAVE_ZLIB
  1176. if (d != NULL && d->gz != NULL)
  1177. return gzgets(d->gz, To, Size);
  1178. #endif
  1179. unsigned long long read = 0;
  1180. while ((Size - 1) != read)
  1181. {
  1182. unsigned long long done = 0;
  1183. if (Read(To + read, 1, &done) == false)
  1184. return NULL;
  1185. if (done == 0)
  1186. break;
  1187. if (To[read++] == '\n')
  1188. break;
  1189. }
  1190. if (read == 0)
  1191. return NULL;
  1192. To[read] = '\0';
  1193. return To;
  1194. }
  1195. /*}}}*/
  1196. // FileFd::Write - Write to the file /*{{{*/
  1197. // ---------------------------------------------------------------------
  1198. /* */
  1199. bool FileFd::Write(const void *From,unsigned long long Size)
  1200. {
  1201. int Res;
  1202. errno = 0;
  1203. do
  1204. {
  1205. #ifdef HAVE_ZLIB
  1206. if (d != NULL && d->gz != NULL)
  1207. Res = gzwrite(d->gz,From,Size);
  1208. else
  1209. #endif
  1210. #ifdef HAVE_BZ2
  1211. if (d != NULL && d->bz2 != NULL)
  1212. Res = BZ2_bzwrite(d->bz2,(void*)From,Size);
  1213. else
  1214. #endif
  1215. Res = write(iFd,From,Size);
  1216. if (Res < 0 && errno == EINTR)
  1217. continue;
  1218. if (Res < 0)
  1219. {
  1220. #ifdef HAVE_ZLIB
  1221. if (d != NULL && d->gz != NULL)
  1222. {
  1223. int err;
  1224. char const * const errmsg = gzerror(d->gz, &err);
  1225. if (err != Z_ERRNO)
  1226. return FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1227. }
  1228. #endif
  1229. #ifdef HAVE_BZ2
  1230. if (d != NULL && d->bz2 != NULL)
  1231. {
  1232. int err;
  1233. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1234. if (err != BZ_IO_ERROR)
  1235. return FileFdError("BZ2_bzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1236. }
  1237. #endif
  1238. return FileFdErrno("write",_("Write error"));
  1239. }
  1240. From = (char *)From + Res;
  1241. Size -= Res;
  1242. if (d != NULL)
  1243. d->seekpos += Res;
  1244. }
  1245. while (Res > 0 && Size > 0);
  1246. if (Size == 0)
  1247. return true;
  1248. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  1249. }
  1250. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  1251. {
  1252. int Res;
  1253. errno = 0;
  1254. do
  1255. {
  1256. Res = write(Fd,From,Size);
  1257. if (Res < 0 && errno == EINTR)
  1258. continue;
  1259. if (Res < 0)
  1260. return _error->Errno("write",_("Write error"));
  1261. From = (char *)From + Res;
  1262. Size -= Res;
  1263. }
  1264. while (Res > 0 && Size > 0);
  1265. if (Size == 0)
  1266. return true;
  1267. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  1268. }
  1269. /*}}}*/
  1270. // FileFd::Seek - Seek in the file /*{{{*/
  1271. // ---------------------------------------------------------------------
  1272. /* */
  1273. bool FileFd::Seek(unsigned long long To)
  1274. {
  1275. if (d != NULL && (d->pipe == true
  1276. #ifdef HAVE_BZ2
  1277. || d->bz2 != NULL
  1278. #endif
  1279. ))
  1280. {
  1281. // Our poor man seeking in pipes is costly, so try to avoid it
  1282. unsigned long long seekpos = Tell();
  1283. if (seekpos == To)
  1284. return true;
  1285. else if (seekpos < To)
  1286. return Skip(To - seekpos);
  1287. if ((d->openmode & ReadOnly) != ReadOnly)
  1288. return FileFdError("Reopen is only implemented for read-only files!");
  1289. #ifdef HAVE_BZ2
  1290. if (d->bz2 != NULL)
  1291. {
  1292. BZ2_bzclose(d->bz2);
  1293. d->bz2 = NULL;
  1294. }
  1295. #endif
  1296. if (iFd != -1)
  1297. close(iFd);
  1298. iFd = -1;
  1299. if (TemporaryFileName.empty() == false)
  1300. iFd = open(TemporaryFileName.c_str(), O_RDONLY);
  1301. else if (FileName.empty() == false)
  1302. iFd = open(FileName.c_str(), O_RDONLY);
  1303. else
  1304. {
  1305. if (d->compressed_fd > 0)
  1306. if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
  1307. iFd = d->compressed_fd;
  1308. if (iFd < 0)
  1309. return FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1310. }
  1311. if (OpenInternDescriptor(d->openmode, d->compressor) == false)
  1312. return FileFdError("Seek on file %s because it couldn't be reopened", FileName.c_str());
  1313. if (To != 0)
  1314. return Skip(To);
  1315. d->seekpos = To;
  1316. return true;
  1317. }
  1318. int res;
  1319. #ifdef HAVE_ZLIB
  1320. if (d != NULL && d->gz)
  1321. res = gzseek(d->gz,To,SEEK_SET);
  1322. else
  1323. #endif
  1324. res = lseek(iFd,To,SEEK_SET);
  1325. if (res != (signed)To)
  1326. return FileFdError("Unable to seek to %llu", To);
  1327. if (d != NULL)
  1328. d->seekpos = To;
  1329. return true;
  1330. }
  1331. /*}}}*/
  1332. // FileFd::Skip - Seek in the file /*{{{*/
  1333. // ---------------------------------------------------------------------
  1334. /* */
  1335. bool FileFd::Skip(unsigned long long Over)
  1336. {
  1337. if (d != NULL && (d->pipe == true
  1338. #ifdef HAVE_BZ2
  1339. || d->bz2 != NULL
  1340. #endif
  1341. ))
  1342. {
  1343. d->seekpos += Over;
  1344. char buffer[1024];
  1345. while (Over != 0)
  1346. {
  1347. unsigned long long toread = std::min((unsigned long long) sizeof(buffer), Over);
  1348. if (Read(buffer, toread) == false)
  1349. return FileFdError("Unable to seek ahead %llu",Over);
  1350. Over -= toread;
  1351. }
  1352. return true;
  1353. }
  1354. int res;
  1355. #ifdef HAVE_ZLIB
  1356. if (d != NULL && d->gz != NULL)
  1357. res = gzseek(d->gz,Over,SEEK_CUR);
  1358. else
  1359. #endif
  1360. res = lseek(iFd,Over,SEEK_CUR);
  1361. if (res < 0)
  1362. return FileFdError("Unable to seek ahead %llu",Over);
  1363. if (d != NULL)
  1364. d->seekpos = res;
  1365. return true;
  1366. }
  1367. /*}}}*/
  1368. // FileFd::Truncate - Truncate the file /*{{{*/
  1369. // ---------------------------------------------------------------------
  1370. /* */
  1371. bool FileFd::Truncate(unsigned long long To)
  1372. {
  1373. #if defined HAVE_ZLIB || defined HAVE_BZ2
  1374. if (d != NULL && (d->gz != NULL || d->bz2 != NULL))
  1375. return FileFdError("Truncating compressed files is not implemented (%s)", FileName.c_str());
  1376. #endif
  1377. if (ftruncate(iFd,To) != 0)
  1378. return FileFdError("Unable to truncate to %llu",To);
  1379. return true;
  1380. }
  1381. /*}}}*/
  1382. // FileFd::Tell - Current seek position /*{{{*/
  1383. // ---------------------------------------------------------------------
  1384. /* */
  1385. unsigned long long FileFd::Tell()
  1386. {
  1387. // In theory, we could just return seekpos here always instead of
  1388. // seeking around, but not all users of FileFd use always Seek() and co
  1389. // so d->seekpos isn't always true and we can just use it as a hint if
  1390. // we have nothing else, but not always as an authority…
  1391. if (d != NULL && (d->pipe == true
  1392. #ifdef HAVE_BZ2
  1393. || d->bz2 != NULL
  1394. #endif
  1395. ))
  1396. return d->seekpos;
  1397. off_t Res;
  1398. #ifdef HAVE_ZLIB
  1399. if (d != NULL && d->gz != NULL)
  1400. Res = gztell(d->gz);
  1401. else
  1402. #endif
  1403. Res = lseek(iFd,0,SEEK_CUR);
  1404. if (Res == (off_t)-1)
  1405. FileFdErrno("lseek","Failed to determine the current file position");
  1406. if (d != NULL)
  1407. d->seekpos = Res;
  1408. return Res;
  1409. }
  1410. /*}}}*/
  1411. // FileFd::FileSize - Return the size of the file /*{{{*/
  1412. // ---------------------------------------------------------------------
  1413. /* */
  1414. unsigned long long FileFd::FileSize()
  1415. {
  1416. struct stat Buf;
  1417. if ((d == NULL || d->pipe == false) && fstat(iFd,&Buf) != 0)
  1418. return FileFdErrno("fstat","Unable to determine the file size");
  1419. // for compressor pipes st_size is undefined and at 'best' zero
  1420. if ((d != NULL && d->pipe == true) || S_ISFIFO(Buf.st_mode))
  1421. {
  1422. // we set it here, too, as we get the info here for free
  1423. // in theory the Open-methods should take care of it already
  1424. if (d != NULL)
  1425. d->pipe = true;
  1426. if (stat(FileName.c_str(), &Buf) != 0)
  1427. return FileFdErrno("stat","Unable to determine the file size");
  1428. }
  1429. return Buf.st_size;
  1430. }
  1431. /*}}}*/
  1432. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1433. // ---------------------------------------------------------------------
  1434. /* */
  1435. unsigned long long FileFd::Size()
  1436. {
  1437. unsigned long long size = FileSize();
  1438. // for compressor pipes st_size is undefined and at 'best' zero,
  1439. // so we 'read' the content and 'seek' back - see there
  1440. if (d != NULL && (d->pipe == true
  1441. #ifdef HAVE_BZ2
  1442. || (d->bz2 && size > 0)
  1443. #endif
  1444. ))
  1445. {
  1446. unsigned long long const oldSeek = Tell();
  1447. char ignore[1000];
  1448. unsigned long long read = 0;
  1449. do {
  1450. Read(ignore, sizeof(ignore), &read);
  1451. } while(read != 0);
  1452. size = Tell();
  1453. Seek(oldSeek);
  1454. }
  1455. #ifdef HAVE_ZLIB
  1456. // only check gzsize if we are actually a gzip file, just checking for
  1457. // "gz" is not sufficient as uncompressed files could be opened with
  1458. // gzopen in "direct" mode as well
  1459. else if (d != NULL && d->gz && !gzdirect(d->gz) && size > 0)
  1460. {
  1461. off_t const oldPos = lseek(iFd,0,SEEK_CUR);
  1462. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1463. * this ourselves; the original (uncompressed) file size is the last 32
  1464. * bits of the file */
  1465. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1466. if (lseek(iFd, -4, SEEK_END) < 0)
  1467. return FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1468. size = 0L;
  1469. if (read(iFd, &size, 4) != 4)
  1470. return FileFdErrno("read","Unable to read original size of gzipped file");
  1471. #ifdef WORDS_BIGENDIAN
  1472. uint32_t tmp_size = size;
  1473. uint8_t const * const p = (uint8_t const * const) &tmp_size;
  1474. tmp_size = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
  1475. size = tmp_size;
  1476. #endif
  1477. if (lseek(iFd, oldPos, SEEK_SET) < 0)
  1478. return FileFdErrno("lseek","Unable to seek in gzipped file");
  1479. return size;
  1480. }
  1481. #endif
  1482. return size;
  1483. }
  1484. /*}}}*/
  1485. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1486. // ---------------------------------------------------------------------
  1487. /* */
  1488. time_t FileFd::ModificationTime()
  1489. {
  1490. struct stat Buf;
  1491. if ((d == NULL || d->pipe == false) && fstat(iFd,&Buf) != 0)
  1492. {
  1493. FileFdErrno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
  1494. return 0;
  1495. }
  1496. // for compressor pipes st_size is undefined and at 'best' zero
  1497. if ((d != NULL && d->pipe == true) || S_ISFIFO(Buf.st_mode))
  1498. {
  1499. // we set it here, too, as we get the info here for free
  1500. // in theory the Open-methods should take care of it already
  1501. if (d != NULL)
  1502. d->pipe = true;
  1503. if (stat(FileName.c_str(), &Buf) != 0)
  1504. {
  1505. FileFdErrno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
  1506. return 0;
  1507. }
  1508. }
  1509. return Buf.st_mtime;
  1510. }
  1511. /*}}}*/
  1512. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1513. // ---------------------------------------------------------------------
  1514. /* */
  1515. bool FileFd::Close()
  1516. {
  1517. if (iFd == -1)
  1518. return true;
  1519. bool Res = true;
  1520. if ((Flags & AutoClose) == AutoClose)
  1521. {
  1522. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  1523. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1524. if (d != NULL)
  1525. {
  1526. Res &= d->CloseDown(FileName);
  1527. delete d;
  1528. d = NULL;
  1529. }
  1530. }
  1531. if ((Flags & Replace) == Replace) {
  1532. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1533. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1534. FileName = TemporaryFileName; // for the unlink() below.
  1535. TemporaryFileName.clear();
  1536. }
  1537. iFd = -1;
  1538. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1539. FileName.empty() == false)
  1540. if (unlink(FileName.c_str()) != 0)
  1541. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1542. if (Res == false)
  1543. Flags |= Fail;
  1544. return Res;
  1545. }
  1546. /*}}}*/
  1547. // FileFd::Sync - Sync the file /*{{{*/
  1548. // ---------------------------------------------------------------------
  1549. /* */
  1550. bool FileFd::Sync()
  1551. {
  1552. if (fsync(iFd) != 0)
  1553. return FileFdErrno("sync",_("Problem syncing the file"));
  1554. return true;
  1555. }
  1556. /*}}}*/
  1557. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  1558. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  1559. {
  1560. Flags |= Fail;
  1561. va_list args;
  1562. size_t msgSize = 400;
  1563. int const errsv = errno;
  1564. while (true)
  1565. {
  1566. va_start(args,Description);
  1567. if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
  1568. break;
  1569. va_end(args);
  1570. }
  1571. return false;
  1572. }
  1573. /*}}}*/
  1574. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  1575. bool FileFd::FileFdError(const char *Description,...) {
  1576. Flags |= Fail;
  1577. va_list args;
  1578. size_t msgSize = 400;
  1579. while (true)
  1580. {
  1581. va_start(args,Description);
  1582. if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
  1583. break;
  1584. va_end(args);
  1585. }
  1586. return false;
  1587. }
  1588. /*}}}*/
  1589. gzFile FileFd::gzFd() { return (gzFile) d->gz; }