fileutl.cc 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  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. long ScOpenMax = sysconf(_SC_OPEN_MAX);
  729. // Close all of our FDs - just in case
  730. for (int K = 3; K != ScOpenMax; K++)
  731. {
  732. if(KeepFDs.find(K) == KeepFDs.end())
  733. fcntl(K,F_SETFD,FD_CLOEXEC);
  734. }
  735. }
  736. return Process;
  737. }
  738. /*}}}*/
  739. // ExecWait - Fancy waitpid /*{{{*/
  740. // ---------------------------------------------------------------------
  741. /* Waits for the given sub process. If Reap is set then no errors are
  742. generated. Otherwise a failed subprocess will generate a proper descriptive
  743. message */
  744. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  745. {
  746. if (Pid <= 1)
  747. return true;
  748. // Wait and collect the error code
  749. int Status;
  750. while (waitpid(Pid,&Status,0) != Pid)
  751. {
  752. if (errno == EINTR)
  753. continue;
  754. if (Reap == true)
  755. return false;
  756. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  757. }
  758. // Check for an error code.
  759. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  760. {
  761. if (Reap == true)
  762. return false;
  763. if (WIFSIGNALED(Status) != 0)
  764. {
  765. if( WTERMSIG(Status) == SIGSEGV)
  766. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  767. else
  768. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  769. }
  770. if (WIFEXITED(Status) != 0)
  771. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  772. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  773. }
  774. return true;
  775. }
  776. /*}}}*/
  777. // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
  778. bool StartsWithGPGClearTextSignature(string const &FileName)
  779. {
  780. static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
  781. char buffer[strlen(SIGMSG)+1];
  782. FILE* gpg = fopen(FileName.c_str(), "r");
  783. if (gpg == NULL)
  784. return false;
  785. char const * const test = fgets(buffer, sizeof(buffer), gpg);
  786. fclose(gpg);
  787. if (test == NULL || strcmp(buffer, SIGMSG) != 0)
  788. return false;
  789. return true;
  790. }
  791. /*}}}*/
  792. // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
  793. bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
  794. {
  795. if (strcmp(file, "/dev/null") == 0)
  796. return true;
  797. bool Res = true;
  798. if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it
  799. {
  800. // ensure the file is owned by root and has good permissions
  801. struct passwd const * const pw = getpwnam(user);
  802. struct group const * const gr = getgrnam(group);
  803. if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
  804. Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
  805. }
  806. if (chmod(file, mode) != 0)
  807. Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
  808. return Res;
  809. }
  810. /*}}}*/
  811. class FileFdPrivate { /*{{{*/
  812. public:
  813. #ifdef HAVE_ZLIB
  814. gzFile gz;
  815. #endif
  816. #ifdef HAVE_BZ2
  817. BZFILE* bz2;
  818. #endif
  819. #ifdef HAVE_LZMA
  820. struct LZMAFILE {
  821. FILE* file;
  822. uint8_t buffer[4096];
  823. lzma_stream stream;
  824. lzma_ret err;
  825. bool eof;
  826. bool compressing;
  827. LZMAFILE() : file(NULL), eof(false), compressing(false) { buffer[0] = '\0'; }
  828. ~LZMAFILE() {
  829. if (compressing == true)
  830. {
  831. for (;;) {
  832. stream.avail_out = sizeof(buffer)/sizeof(buffer[0]);
  833. stream.next_out = buffer;
  834. err = lzma_code(&stream, LZMA_FINISH);
  835. if (err != LZMA_OK && err != LZMA_STREAM_END)
  836. {
  837. _error->Error("~LZMAFILE: Compress finalisation failed");
  838. break;
  839. }
  840. size_t const n = sizeof(buffer)/sizeof(buffer[0]) - stream.avail_out;
  841. if (n && fwrite(buffer, 1, n, file) != n)
  842. {
  843. _error->Errno("~LZMAFILE",_("Write error"));
  844. break;
  845. }
  846. if (err == LZMA_STREAM_END)
  847. break;
  848. }
  849. }
  850. lzma_end(&stream);
  851. fclose(file);
  852. }
  853. };
  854. LZMAFILE* lzma;
  855. #endif
  856. int compressed_fd;
  857. pid_t compressor_pid;
  858. bool pipe;
  859. APT::Configuration::Compressor compressor;
  860. unsigned int openmode;
  861. unsigned long long seekpos;
  862. FileFdPrivate() :
  863. #ifdef HAVE_ZLIB
  864. gz(NULL),
  865. #endif
  866. #ifdef HAVE_BZ2
  867. bz2(NULL),
  868. #endif
  869. #ifdef HAVE_LZMA
  870. lzma(NULL),
  871. #endif
  872. compressed_fd(-1), compressor_pid(-1), pipe(false),
  873. openmode(0), seekpos(0) {};
  874. bool InternalClose(std::string const &FileName)
  875. {
  876. if (false)
  877. /* dummy so that the rest can be 'else if's */;
  878. #ifdef HAVE_ZLIB
  879. else if (gz != NULL) {
  880. int const e = gzclose(gz);
  881. gz = NULL;
  882. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  883. if (e != 0 && e != Z_BUF_ERROR)
  884. return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  885. }
  886. #endif
  887. #ifdef HAVE_BZ2
  888. else if (bz2 != NULL) {
  889. BZ2_bzclose(bz2);
  890. bz2 = NULL;
  891. }
  892. #endif
  893. #ifdef HAVE_LZMA
  894. else if (lzma != NULL) {
  895. delete lzma;
  896. lzma = NULL;
  897. }
  898. #endif
  899. return true;
  900. }
  901. bool CloseDown(std::string const &FileName)
  902. {
  903. bool const Res = InternalClose(FileName);
  904. if (compressor_pid > 0)
  905. ExecWait(compressor_pid, "FileFdCompressor", true);
  906. compressor_pid = -1;
  907. return Res;
  908. }
  909. bool InternalStream() const {
  910. return false
  911. #ifdef HAVE_BZ2
  912. || bz2 != NULL
  913. #endif
  914. #ifdef HAVE_LZMA
  915. || lzma != NULL
  916. #endif
  917. ;
  918. }
  919. ~FileFdPrivate() { CloseDown(""); }
  920. };
  921. /*}}}*/
  922. // FileFd::Open - Open a file /*{{{*/
  923. // ---------------------------------------------------------------------
  924. /* The most commonly used open mode combinations are given with Mode */
  925. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
  926. {
  927. if (Mode == ReadOnlyGzip)
  928. return Open(FileName, ReadOnly, Gzip, AccessMode);
  929. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  930. return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  931. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  932. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  933. if (Compress == Auto)
  934. {
  935. for (; compressor != compressors.end(); ++compressor)
  936. {
  937. std::string file = FileName + compressor->Extension;
  938. if (FileExists(file) == false)
  939. continue;
  940. FileName = file;
  941. break;
  942. }
  943. }
  944. else if (Compress == Extension)
  945. {
  946. std::string::size_type const found = FileName.find_last_of('.');
  947. std::string ext;
  948. if (found != std::string::npos)
  949. {
  950. ext = FileName.substr(found);
  951. if (ext == ".new" || ext == ".bak")
  952. {
  953. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  954. if (found2 != std::string::npos)
  955. ext = FileName.substr(found2, found - found2);
  956. else
  957. ext.clear();
  958. }
  959. }
  960. for (; compressor != compressors.end(); ++compressor)
  961. if (ext == compressor->Extension)
  962. break;
  963. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  964. if (compressor == compressors.end())
  965. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  966. if (compressor->Name == ".")
  967. break;
  968. }
  969. else
  970. {
  971. std::string name;
  972. switch (Compress)
  973. {
  974. case None: name = "."; break;
  975. case Gzip: name = "gzip"; break;
  976. case Bzip2: name = "bzip2"; break;
  977. case Lzma: name = "lzma"; break;
  978. case Xz: name = "xz"; break;
  979. case Auto:
  980. case Extension:
  981. // Unreachable
  982. return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  983. }
  984. for (; compressor != compressors.end(); ++compressor)
  985. if (compressor->Name == name)
  986. break;
  987. if (compressor == compressors.end())
  988. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  989. }
  990. if (compressor == compressors.end())
  991. return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  992. return Open(FileName, Mode, *compressor, AccessMode);
  993. }
  994. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
  995. {
  996. Close();
  997. Flags = AutoClose;
  998. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  999. return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  1000. if ((Mode & ReadWrite) == 0)
  1001. return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
  1002. if ((Mode & Atomic) == Atomic)
  1003. {
  1004. Flags |= Replace;
  1005. }
  1006. else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
  1007. {
  1008. // for atomic, this will be done by rename in Close()
  1009. unlink(FileName.c_str());
  1010. }
  1011. if ((Mode & Empty) == Empty)
  1012. {
  1013. struct stat Buf;
  1014. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  1015. unlink(FileName.c_str());
  1016. }
  1017. int fileflags = 0;
  1018. #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
  1019. if_FLAGGED_SET(ReadWrite, O_RDWR);
  1020. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  1021. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  1022. if_FLAGGED_SET(Create, O_CREAT);
  1023. if_FLAGGED_SET(Empty, O_TRUNC);
  1024. if_FLAGGED_SET(Exclusive, O_EXCL);
  1025. #undef if_FLAGGED_SET
  1026. if ((Mode & Atomic) == Atomic)
  1027. {
  1028. char *name = strdup((FileName + ".XXXXXX").c_str());
  1029. if((iFd = mkstemp(name)) == -1)
  1030. {
  1031. free(name);
  1032. return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
  1033. }
  1034. TemporaryFileName = string(name);
  1035. free(name);
  1036. // umask() will always set the umask and return the previous value, so
  1037. // we first set the umask and then reset it to the old value
  1038. mode_t const CurrentUmask = umask(0);
  1039. umask(CurrentUmask);
  1040. // calculate the actual file permissions (just like open/creat)
  1041. mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
  1042. if(fchmod(iFd, FilePermissions) == -1)
  1043. return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
  1044. }
  1045. else
  1046. iFd = open(FileName.c_str(), fileflags, AccessMode);
  1047. this->FileName = FileName;
  1048. if (iFd == -1 || OpenInternDescriptor(Mode, compressor) == false)
  1049. {
  1050. if (iFd != -1)
  1051. {
  1052. close (iFd);
  1053. iFd = -1;
  1054. }
  1055. return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
  1056. }
  1057. SetCloseExec(iFd,true);
  1058. return true;
  1059. }
  1060. /*}}}*/
  1061. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  1062. // ---------------------------------------------------------------------
  1063. /* */
  1064. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  1065. {
  1066. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  1067. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  1068. std::string name;
  1069. // compat with the old API
  1070. if (Mode == ReadOnlyGzip && Compress == None)
  1071. Compress = Gzip;
  1072. switch (Compress)
  1073. {
  1074. case None: name = "."; break;
  1075. case Gzip: name = "gzip"; break;
  1076. case Bzip2: name = "bzip2"; break;
  1077. case Lzma: name = "lzma"; break;
  1078. case Xz: name = "xz"; break;
  1079. case Auto:
  1080. case Extension:
  1081. if (AutoClose == true && Fd != -1)
  1082. close(Fd);
  1083. return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  1084. }
  1085. for (; compressor != compressors.end(); ++compressor)
  1086. if (compressor->Name == name)
  1087. break;
  1088. if (compressor == compressors.end())
  1089. {
  1090. if (AutoClose == true && Fd != -1)
  1091. close(Fd);
  1092. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  1093. }
  1094. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  1095. }
  1096. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  1097. {
  1098. Close();
  1099. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  1100. iFd = Fd;
  1101. this->FileName = "";
  1102. if (OpenInternDescriptor(Mode, compressor) == false)
  1103. {
  1104. if (iFd != -1 && (
  1105. (Flags & Compressed) == Compressed ||
  1106. AutoClose == true))
  1107. {
  1108. close (iFd);
  1109. iFd = -1;
  1110. }
  1111. return FileFdError(_("Could not open file descriptor %d"), Fd);
  1112. }
  1113. return true;
  1114. }
  1115. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  1116. {
  1117. if (iFd == -1)
  1118. return false;
  1119. if (compressor.Name == "." || compressor.Binary.empty() == true)
  1120. return true;
  1121. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1122. // the API to open files is similar, so setup to avoid code duplicates later
  1123. // and while at it ensure that we close before opening (if its a reopen)
  1124. void* (*compress_open)(int, const char *) = NULL;
  1125. if (false)
  1126. /* dummy so that the rest can be 'else if's */;
  1127. #define APT_COMPRESS_INIT(NAME,OPEN) \
  1128. else if (compressor.Name == NAME) \
  1129. { \
  1130. compress_open = (void*(*)(int, const char *)) OPEN; \
  1131. if (d != NULL) d->InternalClose(FileName); \
  1132. }
  1133. #ifdef HAVE_ZLIB
  1134. APT_COMPRESS_INIT("gzip", gzdopen)
  1135. #endif
  1136. #ifdef HAVE_BZ2
  1137. APT_COMPRESS_INIT("bzip2", BZ2_bzdopen)
  1138. #endif
  1139. #ifdef HAVE_LZMA
  1140. APT_COMPRESS_INIT("xz", fdopen)
  1141. APT_COMPRESS_INIT("lzma", fdopen)
  1142. #endif
  1143. #undef APT_COMPRESS_INIT
  1144. #endif
  1145. if (d == NULL)
  1146. {
  1147. d = new FileFdPrivate();
  1148. d->openmode = Mode;
  1149. d->compressor = compressor;
  1150. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1151. if ((Flags & AutoClose) != AutoClose && compress_open != NULL)
  1152. {
  1153. // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
  1154. int const internFd = dup(iFd);
  1155. if (internFd == -1)
  1156. return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
  1157. iFd = internFd;
  1158. }
  1159. #endif
  1160. }
  1161. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1162. if (compress_open != NULL)
  1163. {
  1164. void* compress_struct = NULL;
  1165. if ((Mode & ReadWrite) == ReadWrite)
  1166. compress_struct = compress_open(iFd, "r+");
  1167. else if ((Mode & WriteOnly) == WriteOnly)
  1168. compress_struct = compress_open(iFd, "w");
  1169. else
  1170. compress_struct = compress_open(iFd, "r");
  1171. if (compress_struct == NULL)
  1172. return false;
  1173. if (false)
  1174. /* dummy so that the rest can be 'else if's */;
  1175. #ifdef HAVE_ZLIB
  1176. else if (compressor.Name == "gzip")
  1177. d->gz = (gzFile) compress_struct;
  1178. #endif
  1179. #ifdef HAVE_BZ2
  1180. else if (compressor.Name == "bzip2")
  1181. d->bz2 = (BZFILE*) compress_struct;
  1182. #endif
  1183. #ifdef HAVE_LZMA
  1184. else if (compressor.Name == "xz" || compressor.Name == "lzma")
  1185. {
  1186. uint32_t const xzlevel = 6;
  1187. uint64_t const memlimit = UINT64_MAX;
  1188. if (d->lzma == NULL)
  1189. d->lzma = new FileFdPrivate::LZMAFILE;
  1190. d->lzma->file = (FILE*) compress_struct;
  1191. lzma_stream tmp_stream = LZMA_STREAM_INIT;
  1192. d->lzma->stream = tmp_stream;
  1193. if ((Mode & ReadWrite) == ReadWrite)
  1194. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1195. if ((Mode & WriteOnly) == WriteOnly)
  1196. {
  1197. if (compressor.Name == "xz")
  1198. {
  1199. if (lzma_easy_encoder(&d->lzma->stream, xzlevel, LZMA_CHECK_CRC32) != LZMA_OK)
  1200. return false;
  1201. }
  1202. else
  1203. {
  1204. lzma_options_lzma options;
  1205. lzma_lzma_preset(&options, xzlevel);
  1206. if (lzma_alone_encoder(&d->lzma->stream, &options) != LZMA_OK)
  1207. return false;
  1208. }
  1209. d->lzma->compressing = true;
  1210. }
  1211. else
  1212. {
  1213. if (compressor.Name == "xz")
  1214. {
  1215. if (lzma_auto_decoder(&d->lzma->stream, memlimit, 0) != LZMA_OK)
  1216. return false;
  1217. }
  1218. else
  1219. {
  1220. if (lzma_alone_decoder(&d->lzma->stream, memlimit) != LZMA_OK)
  1221. return false;
  1222. }
  1223. d->lzma->compressing = false;
  1224. }
  1225. }
  1226. #endif
  1227. Flags |= Compressed;
  1228. return true;
  1229. }
  1230. #endif
  1231. // collect zombies here in case we reopen
  1232. if (d->compressor_pid > 0)
  1233. ExecWait(d->compressor_pid, "FileFdCompressor", true);
  1234. if ((Mode & ReadWrite) == ReadWrite)
  1235. return FileFdError("ReadWrite mode is not supported for file %s", FileName.c_str());
  1236. bool const Comp = (Mode & WriteOnly) == WriteOnly;
  1237. if (Comp == false)
  1238. {
  1239. // Handle 'decompression' of empty files
  1240. struct stat Buf;
  1241. fstat(iFd, &Buf);
  1242. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1243. return true;
  1244. // We don't need the file open - instead let the compressor open it
  1245. // as he properly knows better how to efficiently read from 'his' file
  1246. if (FileName.empty() == false)
  1247. {
  1248. close(iFd);
  1249. iFd = -1;
  1250. }
  1251. }
  1252. // Create a data pipe
  1253. int Pipe[2] = {-1,-1};
  1254. if (pipe(Pipe) != 0)
  1255. return FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1256. for (int J = 0; J != 2; J++)
  1257. SetCloseExec(Pipe[J],true);
  1258. d->compressed_fd = iFd;
  1259. d->pipe = true;
  1260. if (Comp == true)
  1261. iFd = Pipe[1];
  1262. else
  1263. iFd = Pipe[0];
  1264. // The child..
  1265. d->compressor_pid = ExecFork();
  1266. if (d->compressor_pid == 0)
  1267. {
  1268. if (Comp == true)
  1269. {
  1270. dup2(d->compressed_fd,STDOUT_FILENO);
  1271. dup2(Pipe[0],STDIN_FILENO);
  1272. }
  1273. else
  1274. {
  1275. if (d->compressed_fd != -1)
  1276. dup2(d->compressed_fd,STDIN_FILENO);
  1277. dup2(Pipe[1],STDOUT_FILENO);
  1278. }
  1279. int const nullfd = open("/dev/null", O_WRONLY);
  1280. if (nullfd != -1)
  1281. {
  1282. dup2(nullfd,STDERR_FILENO);
  1283. close(nullfd);
  1284. }
  1285. SetCloseExec(STDOUT_FILENO,false);
  1286. SetCloseExec(STDIN_FILENO,false);
  1287. std::vector<char const*> Args;
  1288. Args.push_back(compressor.Binary.c_str());
  1289. std::vector<std::string> const * const addArgs =
  1290. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1291. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1292. a != addArgs->end(); ++a)
  1293. Args.push_back(a->c_str());
  1294. if (Comp == false && FileName.empty() == false)
  1295. {
  1296. // commands not needing arguments, do not need to be told about using standard output
  1297. // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
  1298. if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
  1299. Args.push_back("--stdout");
  1300. if (TemporaryFileName.empty() == false)
  1301. Args.push_back(TemporaryFileName.c_str());
  1302. else
  1303. Args.push_back(FileName.c_str());
  1304. }
  1305. Args.push_back(NULL);
  1306. execvp(Args[0],(char **)&Args[0]);
  1307. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1308. _exit(100);
  1309. }
  1310. if (Comp == true)
  1311. close(Pipe[0]);
  1312. else
  1313. close(Pipe[1]);
  1314. return true;
  1315. }
  1316. /*}}}*/
  1317. // FileFd::~File - Closes the file /*{{{*/
  1318. // ---------------------------------------------------------------------
  1319. /* If the proper modes are selected then we close the Fd and possibly
  1320. unlink the file on error. */
  1321. FileFd::~FileFd()
  1322. {
  1323. Close();
  1324. if (d != NULL)
  1325. d->CloseDown(FileName);
  1326. delete d;
  1327. d = NULL;
  1328. }
  1329. /*}}}*/
  1330. // FileFd::Read - Read a bit of the file /*{{{*/
  1331. // ---------------------------------------------------------------------
  1332. /* We are careful to handle interruption by a signal while reading
  1333. gracefully. */
  1334. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  1335. {
  1336. ssize_t Res;
  1337. errno = 0;
  1338. if (Actual != 0)
  1339. *Actual = 0;
  1340. *((char *)To) = '\0';
  1341. do
  1342. {
  1343. if (false)
  1344. /* dummy so that the rest can be 'else if's */;
  1345. #ifdef HAVE_ZLIB
  1346. else if (d != NULL && d->gz != NULL)
  1347. Res = gzread(d->gz,To,Size);
  1348. #endif
  1349. #ifdef HAVE_BZ2
  1350. else if (d != NULL && d->bz2 != NULL)
  1351. Res = BZ2_bzread(d->bz2,To,Size);
  1352. #endif
  1353. #ifdef HAVE_LZMA
  1354. else if (d != NULL && d->lzma != NULL)
  1355. {
  1356. if (d->lzma->eof == true)
  1357. break;
  1358. d->lzma->stream.next_out = (uint8_t *) To;
  1359. d->lzma->stream.avail_out = Size;
  1360. if (d->lzma->stream.avail_in == 0)
  1361. {
  1362. d->lzma->stream.next_in = d->lzma->buffer;
  1363. d->lzma->stream.avail_in = fread(d->lzma->buffer, 1, sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]), d->lzma->file);
  1364. }
  1365. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1366. if (d->lzma->err == LZMA_STREAM_END)
  1367. {
  1368. d->lzma->eof = true;
  1369. Res = Size - d->lzma->stream.avail_out;
  1370. }
  1371. else if (d->lzma->err != LZMA_OK)
  1372. {
  1373. Res = -1;
  1374. errno = 0;
  1375. }
  1376. else
  1377. {
  1378. Res = Size - d->lzma->stream.avail_out;
  1379. if (Res == 0)
  1380. {
  1381. // lzma run was okay, but produced no output…
  1382. Res = -1;
  1383. errno = EINTR;
  1384. }
  1385. }
  1386. }
  1387. #endif
  1388. else
  1389. Res = read(iFd,To,Size);
  1390. if (Res < 0)
  1391. {
  1392. if (errno == EINTR)
  1393. {
  1394. // trick the while-loop into running again
  1395. Res = 1;
  1396. errno = 0;
  1397. continue;
  1398. }
  1399. if (false)
  1400. /* dummy so that the rest can be 'else if's */;
  1401. #ifdef HAVE_ZLIB
  1402. else if (d != NULL && d->gz != NULL)
  1403. {
  1404. int err;
  1405. char const * const errmsg = gzerror(d->gz, &err);
  1406. if (err != Z_ERRNO)
  1407. return FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1408. }
  1409. #endif
  1410. #ifdef HAVE_BZ2
  1411. else if (d != NULL && d->bz2 != NULL)
  1412. {
  1413. int err;
  1414. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1415. if (err != BZ_IO_ERROR)
  1416. return FileFdError("BZ2_bzread: %s %s (%d: %s)", FileName.c_str(), _("Read error"), err, errmsg);
  1417. }
  1418. #endif
  1419. #ifdef HAVE_LZMA
  1420. else if (d != NULL && d->lzma != NULL)
  1421. return FileFdError("lzma_read: %s (%d)", _("Read error"), d->lzma->err);
  1422. #endif
  1423. return FileFdErrno("read",_("Read error"));
  1424. }
  1425. To = (char *)To + Res;
  1426. Size -= Res;
  1427. if (d != NULL)
  1428. d->seekpos += Res;
  1429. if (Actual != 0)
  1430. *Actual += Res;
  1431. }
  1432. while (Res > 0 && Size > 0);
  1433. if (Size == 0)
  1434. return true;
  1435. // Eof handling
  1436. if (Actual != 0)
  1437. {
  1438. Flags |= HitEof;
  1439. return true;
  1440. }
  1441. return FileFdError(_("read, still have %llu to read but none left"), Size);
  1442. }
  1443. /*}}}*/
  1444. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  1445. // ---------------------------------------------------------------------
  1446. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  1447. files because of the naive implementation! */
  1448. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  1449. {
  1450. *To = '\0';
  1451. #ifdef HAVE_ZLIB
  1452. if (d != NULL && d->gz != NULL)
  1453. return gzgets(d->gz, To, Size);
  1454. #endif
  1455. unsigned long long read = 0;
  1456. while ((Size - 1) != read)
  1457. {
  1458. unsigned long long done = 0;
  1459. if (Read(To + read, 1, &done) == false)
  1460. return NULL;
  1461. if (done == 0)
  1462. break;
  1463. if (To[read++] == '\n')
  1464. break;
  1465. }
  1466. if (read == 0)
  1467. return NULL;
  1468. To[read] = '\0';
  1469. return To;
  1470. }
  1471. /*}}}*/
  1472. // FileFd::Write - Write to the file /*{{{*/
  1473. // ---------------------------------------------------------------------
  1474. /* */
  1475. bool FileFd::Write(const void *From,unsigned long long Size)
  1476. {
  1477. ssize_t Res;
  1478. errno = 0;
  1479. do
  1480. {
  1481. if (false)
  1482. /* dummy so that the rest can be 'else if's */;
  1483. #ifdef HAVE_ZLIB
  1484. else if (d != NULL && d->gz != NULL)
  1485. Res = gzwrite(d->gz,From,Size);
  1486. #endif
  1487. #ifdef HAVE_BZ2
  1488. else if (d != NULL && d->bz2 != NULL)
  1489. Res = BZ2_bzwrite(d->bz2,(void*)From,Size);
  1490. #endif
  1491. #ifdef HAVE_LZMA
  1492. else if (d != NULL && d->lzma != NULL)
  1493. {
  1494. d->lzma->stream.next_in = (uint8_t *)From;
  1495. d->lzma->stream.avail_in = Size;
  1496. d->lzma->stream.next_out = d->lzma->buffer;
  1497. d->lzma->stream.avail_out = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]);
  1498. d->lzma->err = lzma_code(&d->lzma->stream, LZMA_RUN);
  1499. if (d->lzma->err != LZMA_OK)
  1500. return false;
  1501. size_t const n = sizeof(d->lzma->buffer)/sizeof(d->lzma->buffer[0]) - d->lzma->stream.avail_out;
  1502. size_t const m = (n == 0) ? 0 : fwrite(d->lzma->buffer, 1, n, d->lzma->file);
  1503. if (m != n)
  1504. Res = -1;
  1505. else
  1506. Res = Size - d->lzma->stream.avail_in;
  1507. }
  1508. #endif
  1509. else
  1510. Res = write(iFd,From,Size);
  1511. if (Res < 0 && errno == EINTR)
  1512. continue;
  1513. if (Res < 0)
  1514. {
  1515. if (false)
  1516. /* dummy so that the rest can be 'else if's */;
  1517. #ifdef HAVE_ZLIB
  1518. else if (d != NULL && d->gz != NULL)
  1519. {
  1520. int err;
  1521. char const * const errmsg = gzerror(d->gz, &err);
  1522. if (err != Z_ERRNO)
  1523. return FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1524. }
  1525. #endif
  1526. #ifdef HAVE_BZ2
  1527. else if (d != NULL && d->bz2 != NULL)
  1528. {
  1529. int err;
  1530. char const * const errmsg = BZ2_bzerror(d->bz2, &err);
  1531. if (err != BZ_IO_ERROR)
  1532. return FileFdError("BZ2_bzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1533. }
  1534. #endif
  1535. #ifdef HAVE_LZMA
  1536. else if (d != NULL && d->lzma != NULL)
  1537. return FileFdErrno("lzma_fwrite", _("Write error"));
  1538. #endif
  1539. return FileFdErrno("write",_("Write error"));
  1540. }
  1541. From = (char const *)From + Res;
  1542. Size -= Res;
  1543. if (d != NULL)
  1544. d->seekpos += Res;
  1545. }
  1546. while (Res > 0 && Size > 0);
  1547. if (Size == 0)
  1548. return true;
  1549. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  1550. }
  1551. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  1552. {
  1553. ssize_t Res;
  1554. errno = 0;
  1555. do
  1556. {
  1557. Res = write(Fd,From,Size);
  1558. if (Res < 0 && errno == EINTR)
  1559. continue;
  1560. if (Res < 0)
  1561. return _error->Errno("write",_("Write error"));
  1562. From = (char const *)From + Res;
  1563. Size -= Res;
  1564. }
  1565. while (Res > 0 && Size > 0);
  1566. if (Size == 0)
  1567. return true;
  1568. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  1569. }
  1570. /*}}}*/
  1571. // FileFd::Seek - Seek in the file /*{{{*/
  1572. // ---------------------------------------------------------------------
  1573. /* */
  1574. bool FileFd::Seek(unsigned long long To)
  1575. {
  1576. Flags &= ~HitEof;
  1577. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1578. {
  1579. // Our poor man seeking in pipes is costly, so try to avoid it
  1580. unsigned long long seekpos = Tell();
  1581. if (seekpos == To)
  1582. return true;
  1583. else if (seekpos < To)
  1584. return Skip(To - seekpos);
  1585. if ((d->openmode & ReadOnly) != ReadOnly)
  1586. return FileFdError("Reopen is only implemented for read-only files!");
  1587. d->InternalClose(FileName);
  1588. if (iFd != -1)
  1589. close(iFd);
  1590. iFd = -1;
  1591. if (TemporaryFileName.empty() == false)
  1592. iFd = open(TemporaryFileName.c_str(), O_RDONLY);
  1593. else if (FileName.empty() == false)
  1594. iFd = open(FileName.c_str(), O_RDONLY);
  1595. else
  1596. {
  1597. if (d->compressed_fd > 0)
  1598. if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
  1599. iFd = d->compressed_fd;
  1600. if (iFd < 0)
  1601. return FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1602. }
  1603. if (OpenInternDescriptor(d->openmode, d->compressor) == false)
  1604. return FileFdError("Seek on file %s because it couldn't be reopened", FileName.c_str());
  1605. if (To != 0)
  1606. return Skip(To);
  1607. d->seekpos = To;
  1608. return true;
  1609. }
  1610. off_t res;
  1611. #ifdef HAVE_ZLIB
  1612. if (d != NULL && d->gz)
  1613. res = gzseek(d->gz,To,SEEK_SET);
  1614. else
  1615. #endif
  1616. res = lseek(iFd,To,SEEK_SET);
  1617. if (res != (off_t)To)
  1618. return FileFdError("Unable to seek to %llu", To);
  1619. if (d != NULL)
  1620. d->seekpos = To;
  1621. return true;
  1622. }
  1623. /*}}}*/
  1624. // FileFd::Skip - Seek in the file /*{{{*/
  1625. // ---------------------------------------------------------------------
  1626. /* */
  1627. bool FileFd::Skip(unsigned long long Over)
  1628. {
  1629. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1630. {
  1631. char buffer[1024];
  1632. while (Over != 0)
  1633. {
  1634. unsigned long long toread = std::min((unsigned long long) sizeof(buffer), Over);
  1635. if (Read(buffer, toread) == false)
  1636. return FileFdError("Unable to seek ahead %llu",Over);
  1637. Over -= toread;
  1638. }
  1639. return true;
  1640. }
  1641. off_t res;
  1642. #ifdef HAVE_ZLIB
  1643. if (d != NULL && d->gz != NULL)
  1644. res = gzseek(d->gz,Over,SEEK_CUR);
  1645. else
  1646. #endif
  1647. res = lseek(iFd,Over,SEEK_CUR);
  1648. if (res < 0)
  1649. return FileFdError("Unable to seek ahead %llu",Over);
  1650. if (d != NULL)
  1651. d->seekpos = res;
  1652. return true;
  1653. }
  1654. /*}}}*/
  1655. // FileFd::Truncate - Truncate the file /*{{{*/
  1656. // ---------------------------------------------------------------------
  1657. /* */
  1658. bool FileFd::Truncate(unsigned long long To)
  1659. {
  1660. // truncating /dev/null is always successful - as we get an error otherwise
  1661. if (To == 0 && FileName == "/dev/null")
  1662. return true;
  1663. #if defined HAVE_ZLIB || defined HAVE_BZ2 || defined HAVE_LZMA
  1664. if (d != NULL && (d->InternalStream() == true
  1665. #ifdef HAVE_ZLIB
  1666. || d->gz != NULL
  1667. #endif
  1668. ))
  1669. return FileFdError("Truncating compressed files is not implemented (%s)", FileName.c_str());
  1670. #endif
  1671. if (ftruncate(iFd,To) != 0)
  1672. return FileFdError("Unable to truncate to %llu",To);
  1673. return true;
  1674. }
  1675. /*}}}*/
  1676. // FileFd::Tell - Current seek position /*{{{*/
  1677. // ---------------------------------------------------------------------
  1678. /* */
  1679. unsigned long long FileFd::Tell()
  1680. {
  1681. // In theory, we could just return seekpos here always instead of
  1682. // seeking around, but not all users of FileFd use always Seek() and co
  1683. // so d->seekpos isn't always true and we can just use it as a hint if
  1684. // we have nothing else, but not always as an authority…
  1685. if (d != NULL && (d->pipe == true || d->InternalStream() == true))
  1686. return d->seekpos;
  1687. off_t Res;
  1688. #ifdef HAVE_ZLIB
  1689. if (d != NULL && d->gz != NULL)
  1690. Res = gztell(d->gz);
  1691. else
  1692. #endif
  1693. Res = lseek(iFd,0,SEEK_CUR);
  1694. if (Res == (off_t)-1)
  1695. FileFdErrno("lseek","Failed to determine the current file position");
  1696. if (d != NULL)
  1697. d->seekpos = Res;
  1698. return Res;
  1699. }
  1700. /*}}}*/
  1701. static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
  1702. {
  1703. bool ispipe = (d != NULL && d->pipe == true);
  1704. if (ispipe == false)
  1705. {
  1706. if (fstat(iFd,&Buf) != 0)
  1707. // higher-level code will generate more meaningful messages,
  1708. // even translated this would be meaningless for users
  1709. return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
  1710. if (FileName.empty() == false)
  1711. ispipe = S_ISFIFO(Buf.st_mode);
  1712. }
  1713. // for compressor pipes st_size is undefined and at 'best' zero
  1714. if (ispipe == true)
  1715. {
  1716. // we set it here, too, as we get the info here for free
  1717. // in theory the Open-methods should take care of it already
  1718. if (d != NULL)
  1719. d->pipe = true;
  1720. if (stat(FileName.c_str(), &Buf) != 0)
  1721. return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
  1722. }
  1723. return true;
  1724. }
  1725. /*}}}*/
  1726. // FileFd::FileSize - Return the size of the file /*{{{*/
  1727. unsigned long long FileFd::FileSize()
  1728. {
  1729. struct stat Buf;
  1730. if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
  1731. {
  1732. Flags |= Fail;
  1733. return 0;
  1734. }
  1735. return Buf.st_size;
  1736. }
  1737. /*}}}*/
  1738. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1739. time_t FileFd::ModificationTime()
  1740. {
  1741. struct stat Buf;
  1742. if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
  1743. {
  1744. Flags |= Fail;
  1745. return 0;
  1746. }
  1747. return Buf.st_mtime;
  1748. }
  1749. /*}}}*/
  1750. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1751. // ---------------------------------------------------------------------
  1752. /* */
  1753. unsigned long long FileFd::Size()
  1754. {
  1755. unsigned long long size = FileSize();
  1756. // for compressor pipes st_size is undefined and at 'best' zero,
  1757. // so we 'read' the content and 'seek' back - see there
  1758. if (d != NULL && (d->pipe == true || (d->InternalStream() == true && size > 0)))
  1759. {
  1760. unsigned long long const oldSeek = Tell();
  1761. char ignore[1000];
  1762. unsigned long long read = 0;
  1763. do {
  1764. if (Read(ignore, sizeof(ignore), &read) == false)
  1765. {
  1766. Seek(oldSeek);
  1767. return 0;
  1768. }
  1769. } while(read != 0);
  1770. size = Tell();
  1771. Seek(oldSeek);
  1772. }
  1773. #ifdef HAVE_ZLIB
  1774. // only check gzsize if we are actually a gzip file, just checking for
  1775. // "gz" is not sufficient as uncompressed files could be opened with
  1776. // gzopen in "direct" mode as well
  1777. else if (d != NULL && d->gz && !gzdirect(d->gz) && size > 0)
  1778. {
  1779. off_t const oldPos = lseek(iFd,0,SEEK_CUR);
  1780. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1781. * this ourselves; the original (uncompressed) file size is the last 32
  1782. * bits of the file */
  1783. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1784. if (lseek(iFd, -4, SEEK_END) < 0)
  1785. {
  1786. FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1787. return 0;
  1788. }
  1789. uint32_t size = 0;
  1790. if (read(iFd, &size, 4) != 4)
  1791. {
  1792. FileFdErrno("read","Unable to read original size of gzipped file");
  1793. return 0;
  1794. }
  1795. size = le32toh(size);
  1796. if (lseek(iFd, oldPos, SEEK_SET) < 0)
  1797. {
  1798. FileFdErrno("lseek","Unable to seek in gzipped file");
  1799. return 0;
  1800. }
  1801. return size;
  1802. }
  1803. #endif
  1804. return size;
  1805. }
  1806. /*}}}*/
  1807. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1808. // ---------------------------------------------------------------------
  1809. /* */
  1810. bool FileFd::Close()
  1811. {
  1812. if (iFd == -1)
  1813. return true;
  1814. bool Res = true;
  1815. if ((Flags & AutoClose) == AutoClose)
  1816. {
  1817. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  1818. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1819. if (d != NULL)
  1820. {
  1821. Res &= d->CloseDown(FileName);
  1822. delete d;
  1823. d = NULL;
  1824. }
  1825. }
  1826. if ((Flags & Replace) == Replace) {
  1827. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1828. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1829. FileName = TemporaryFileName; // for the unlink() below.
  1830. TemporaryFileName.clear();
  1831. }
  1832. iFd = -1;
  1833. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1834. FileName.empty() == false)
  1835. if (unlink(FileName.c_str()) != 0)
  1836. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1837. if (Res == false)
  1838. Flags |= Fail;
  1839. return Res;
  1840. }
  1841. /*}}}*/
  1842. // FileFd::Sync - Sync the file /*{{{*/
  1843. // ---------------------------------------------------------------------
  1844. /* */
  1845. bool FileFd::Sync()
  1846. {
  1847. if (fsync(iFd) != 0)
  1848. return FileFdErrno("sync",_("Problem syncing the file"));
  1849. return true;
  1850. }
  1851. /*}}}*/
  1852. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  1853. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  1854. {
  1855. Flags |= Fail;
  1856. va_list args;
  1857. size_t msgSize = 400;
  1858. int const errsv = errno;
  1859. while (true)
  1860. {
  1861. va_start(args,Description);
  1862. if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
  1863. break;
  1864. va_end(args);
  1865. }
  1866. return false;
  1867. }
  1868. /*}}}*/
  1869. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  1870. bool FileFd::FileFdError(const char *Description,...) {
  1871. Flags |= Fail;
  1872. va_list args;
  1873. size_t msgSize = 400;
  1874. while (true)
  1875. {
  1876. va_start(args,Description);
  1877. if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
  1878. break;
  1879. va_end(args);
  1880. }
  1881. return false;
  1882. }
  1883. /*}}}*/
  1884. APT_DEPRECATED gzFile FileFd::gzFd() {
  1885. #ifdef HAVE_ZLIB
  1886. return d->gz;
  1887. #else
  1888. return NULL;
  1889. #endif
  1890. }
  1891. // Glob - wrapper around "glob()" /*{{{*/
  1892. std::vector<std::string> Glob(std::string const &pattern, int flags)
  1893. {
  1894. std::vector<std::string> result;
  1895. glob_t globbuf;
  1896. int glob_res;
  1897. unsigned int i;
  1898. glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
  1899. if (glob_res != 0)
  1900. {
  1901. if(glob_res != GLOB_NOMATCH) {
  1902. _error->Errno("glob", "Problem with glob");
  1903. return result;
  1904. }
  1905. }
  1906. // append results
  1907. for(i=0;i<globbuf.gl_pathc;i++)
  1908. result.push_back(string(globbuf.gl_pathv[i]));
  1909. globfree(&globbuf);
  1910. return result;
  1911. }
  1912. /*}}}*/
  1913. std::string GetTempDir() /*{{{*/
  1914. {
  1915. const char *tmpdir = getenv("TMPDIR");
  1916. #ifdef P_tmpdir
  1917. if (!tmpdir)
  1918. tmpdir = P_tmpdir;
  1919. #endif
  1920. struct stat st;
  1921. if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set
  1922. stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0 || // exists and is directory
  1923. access(tmpdir, R_OK | W_OK | X_OK) != 0 // current user has rwx access to directory
  1924. )
  1925. tmpdir = "/tmp";
  1926. return string(tmpdir);
  1927. }
  1928. /*}}}*/
  1929. FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink) /*{{{*/
  1930. {
  1931. char fn[512];
  1932. FileFd *Fd = new FileFd();
  1933. std::string tempdir = GetTempDir();
  1934. snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
  1935. tempdir.c_str(), Prefix.c_str());
  1936. int fd = mkstemp(fn);
  1937. if(ImmediateUnlink)
  1938. unlink(fn);
  1939. if (fd < 0)
  1940. {
  1941. _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
  1942. return NULL;
  1943. }
  1944. if (!Fd->OpenDescriptor(fd, FileFd::WriteOnly, FileFd::None, true))
  1945. {
  1946. _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
  1947. return NULL;
  1948. }
  1949. return Fd;
  1950. }
  1951. /*}}}*/
  1952. bool Rename(std::string From, std::string To) /*{{{*/
  1953. {
  1954. if (rename(From.c_str(),To.c_str()) != 0)
  1955. {
  1956. _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
  1957. From.c_str(),To.c_str());
  1958. return false;
  1959. }
  1960. return true;
  1961. }
  1962. /*}}}*/
  1963. bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
  1964. {
  1965. int fd;
  1966. if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
  1967. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  1968. int Pipe[2] = {-1, -1};
  1969. if(pipe(Pipe) != 0)
  1970. return _error->Errno("pipe", _("Failed to create subprocess IPC"));
  1971. std::set<int> keep_fds;
  1972. keep_fds.insert(Pipe[0]);
  1973. keep_fds.insert(Pipe[1]);
  1974. Child = ExecFork(keep_fds);
  1975. if(Child < 0)
  1976. return _error->Errno("fork", "Failed to fork");
  1977. if(Child == 0)
  1978. {
  1979. if(Mode == FileFd::ReadOnly)
  1980. {
  1981. close(Pipe[0]);
  1982. fd = Pipe[1];
  1983. }
  1984. else if(Mode == FileFd::WriteOnly)
  1985. {
  1986. close(Pipe[1]);
  1987. fd = Pipe[0];
  1988. }
  1989. if(Mode == FileFd::ReadOnly)
  1990. {
  1991. dup2(fd, 1);
  1992. dup2(fd, 2);
  1993. } else if(Mode == FileFd::WriteOnly)
  1994. dup2(fd, 0);
  1995. execv(Args[0], (char**)Args);
  1996. _exit(100);
  1997. }
  1998. if(Mode == FileFd::ReadOnly)
  1999. {
  2000. close(Pipe[1]);
  2001. fd = Pipe[0];
  2002. } else if(Mode == FileFd::WriteOnly)
  2003. {
  2004. close(Pipe[0]);
  2005. fd = Pipe[1];
  2006. }
  2007. Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
  2008. return true;
  2009. }
  2010. /*}}}*/
  2011. bool DropPrivileges() /*{{{*/
  2012. {
  2013. if(_config->FindB("Debug::NoDropPrivs", false) == true)
  2014. return true;
  2015. #if __gnu_linux__
  2016. #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
  2017. #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
  2018. #endif
  2019. // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
  2020. int ret = prctl(38, 1, 0, 0, 0);
  2021. // ignore EINVAL - kernel is too old to understand the option
  2022. if(ret < 0 && errno != EINVAL)
  2023. _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
  2024. #endif
  2025. // empty setting disables privilege dropping - this also ensures
  2026. // backward compatibility, see bug #764506
  2027. const std::string toUser = _config->Find("APT::Sandbox::User");
  2028. if (toUser.empty())
  2029. return true;
  2030. // uid will be 0 in the end, but gid might be different anyway
  2031. uid_t const old_uid = getuid();
  2032. gid_t const old_gid = getgid();
  2033. if (old_uid != 0)
  2034. return true;
  2035. struct passwd *pw = getpwnam(toUser.c_str());
  2036. if (pw == NULL)
  2037. return _error->Error("No user %s, can not drop rights", toUser.c_str());
  2038. // Do not change the order here, it might break things
  2039. if (setgroups(1, &pw->pw_gid))
  2040. return _error->Errno("setgroups", "Failed to setgroups");
  2041. if (setegid(pw->pw_gid) != 0)
  2042. return _error->Errno("setegid", "Failed to setegid");
  2043. if (setgid(pw->pw_gid) != 0)
  2044. return _error->Errno("setgid", "Failed to setgid");
  2045. if (setuid(pw->pw_uid) != 0)
  2046. return _error->Errno("setuid", "Failed to setuid");
  2047. // the seteuid() is probably uneeded (at least thats what the linux
  2048. // man-page says about setuid(2)) but we cargo culted it anyway
  2049. if (seteuid(pw->pw_uid) != 0)
  2050. return _error->Errno("seteuid", "Failed to seteuid");
  2051. // Verify that the user has only a single group, and the correct one
  2052. gid_t groups[1];
  2053. if (getgroups(1, groups) != 1)
  2054. return _error->Errno("getgroups", "Could not get new groups");
  2055. if (groups[0] != pw->pw_gid)
  2056. return _error->Error("Could not switch group");
  2057. // Verify that gid, egid, uid, and euid changed
  2058. if (getgid() != pw->pw_gid)
  2059. return _error->Error("Could not switch group");
  2060. if (getegid() != pw->pw_gid)
  2061. return _error->Error("Could not switch effective group");
  2062. if (getuid() != pw->pw_uid)
  2063. return _error->Error("Could not switch user");
  2064. if (geteuid() != pw->pw_uid)
  2065. return _error->Error("Could not switch effective user");
  2066. #ifdef HAVE_GETRESUID
  2067. // verify that the saved set-user-id was changed as well
  2068. uid_t ruid = 0;
  2069. uid_t euid = 0;
  2070. uid_t suid = 0;
  2071. if (getresuid(&ruid, &euid, &suid))
  2072. return _error->Errno("getresuid", "Could not get saved set-user-ID");
  2073. if (suid != pw->pw_uid)
  2074. return _error->Error("Could not switch saved set-user-ID");
  2075. #endif
  2076. #ifdef HAVE_GETRESGID
  2077. // verify that the saved set-group-id was changed as well
  2078. gid_t rgid = 0;
  2079. gid_t egid = 0;
  2080. gid_t sgid = 0;
  2081. if (getresgid(&rgid, &egid, &sgid))
  2082. return _error->Errno("getresuid", "Could not get saved set-group-ID");
  2083. if (sgid != pw->pw_gid)
  2084. return _error->Error("Could not switch saved set-group-ID");
  2085. #endif
  2086. // Check that uid and gid changes do not work anymore
  2087. if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
  2088. return _error->Error("Could restore a gid to root, privilege dropping did not work");
  2089. if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
  2090. return _error->Error("Could restore a uid to root, privilege dropping did not work");
  2091. return true;
  2092. }
  2093. /*}}}*/