fileutl.cc 51 KB

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