fileutl.cc 51 KB

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