fileutl.cc 63 KB

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