fileutl.cc 46 KB

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