fileutl.cc 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077
  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. #include <memory>
  48. #ifdef HAVE_ZLIB
  49. #include <zlib.h>
  50. #endif
  51. #ifdef HAVE_BZ2
  52. #include <bzlib.h>
  53. #endif
  54. #ifdef HAVE_LZMA
  55. #include <lzma.h>
  56. #endif
  57. #ifdef HAVE_LZ4
  58. #include <lz4frame.h>
  59. #endif
  60. #include <endian.h>
  61. #include <stdint.h>
  62. #if __gnu_linux__
  63. #include <sys/prctl.h>
  64. #endif
  65. #include <apti18n.h>
  66. /*}}}*/
  67. using namespace std;
  68. /* Should be a multiple of the common page size (4096) */
  69. static constexpr unsigned long long APT_BUFFER_SIZE = 64 * 1024;
  70. // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
  71. // ---------------------------------------------------------------------
  72. /* */
  73. bool RunScripts(const char *Cnf)
  74. {
  75. Configuration::Item const *Opts = _config->Tree(Cnf);
  76. if (Opts == 0 || Opts->Child == 0)
  77. return true;
  78. Opts = Opts->Child;
  79. // Fork for running the system calls
  80. pid_t Child = ExecFork();
  81. // This is the child
  82. if (Child == 0)
  83. {
  84. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  85. {
  86. std::cerr << "Chrooting into "
  87. << _config->FindDir("DPkg::Chroot-Directory")
  88. << std::endl;
  89. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  90. _exit(100);
  91. }
  92. if (chdir("/tmp/") != 0)
  93. _exit(100);
  94. unsigned int Count = 1;
  95. for (; Opts != 0; Opts = Opts->Next, Count++)
  96. {
  97. if (Opts->Value.empty() == true)
  98. continue;
  99. if(_config->FindB("Debug::RunScripts", false) == true)
  100. std::clog << "Running external script: '"
  101. << Opts->Value << "'" << std::endl;
  102. if (system(Opts->Value.c_str()) != 0)
  103. _exit(100+Count);
  104. }
  105. _exit(0);
  106. }
  107. // Wait for the child
  108. int Status = 0;
  109. while (waitpid(Child,&Status,0) != Child)
  110. {
  111. if (errno == EINTR)
  112. continue;
  113. return _error->Errno("waitpid","Couldn't wait for subprocess");
  114. }
  115. // Restore sig int/quit
  116. signal(SIGQUIT,SIG_DFL);
  117. signal(SIGINT,SIG_DFL);
  118. // Check for an error code.
  119. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  120. {
  121. unsigned int Count = WEXITSTATUS(Status);
  122. if (Count > 100)
  123. {
  124. Count -= 100;
  125. for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
  126. _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
  127. }
  128. return _error->Error("Sub-process returned an error code");
  129. }
  130. return true;
  131. }
  132. /*}}}*/
  133. // CopyFile - Buffered copy of a file /*{{{*/
  134. // ---------------------------------------------------------------------
  135. /* The caller is expected to set things so that failure causes erasure */
  136. bool CopyFile(FileFd &From,FileFd &To)
  137. {
  138. if (From.IsOpen() == false || To.IsOpen() == false ||
  139. From.Failed() == true || To.Failed() == true)
  140. return false;
  141. // Buffered copy between fds
  142. constexpr size_t BufSize = APT_BUFFER_SIZE;
  143. std::unique_ptr<unsigned char[]> Buf(new unsigned char[BufSize]);
  144. unsigned long long ToRead = 0;
  145. do {
  146. if (From.Read(Buf.get(),BufSize, &ToRead) == false ||
  147. To.Write(Buf.get(),ToRead) == false)
  148. return false;
  149. } while (ToRead != 0);
  150. return true;
  151. }
  152. /*}}}*/
  153. bool RemoveFile(char const * const Function, std::string const &FileName)/*{{{*/
  154. {
  155. if (FileName == "/dev/null")
  156. return true;
  157. errno = 0;
  158. if (unlink(FileName.c_str()) != 0)
  159. {
  160. if (errno == ENOENT)
  161. return true;
  162. return _error->WarningE(Function,_("Problem unlinking the file %s"), FileName.c_str());
  163. }
  164. return true;
  165. }
  166. /*}}}*/
  167. // GetLock - Gets a lock file /*{{{*/
  168. // ---------------------------------------------------------------------
  169. /* This will create an empty file of the given name and lock it. Once this
  170. is done all other calls to GetLock in any other process will fail with
  171. -1. The return result is the fd of the file, the call should call
  172. close at some time. */
  173. int GetLock(string File,bool Errors)
  174. {
  175. // GetLock() is used in aptitude on directories with public-write access
  176. // Use O_NOFOLLOW here to prevent symlink traversal attacks
  177. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
  178. if (FD < 0)
  179. {
  180. // Read only .. can't have locking problems there.
  181. if (errno == EROFS)
  182. {
  183. _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
  184. return dup(0); // Need something for the caller to close
  185. }
  186. if (Errors == true)
  187. _error->Errno("open",_("Could not open lock file %s"),File.c_str());
  188. // Feh.. We do this to distinguish the lock vs open case..
  189. errno = EPERM;
  190. return -1;
  191. }
  192. SetCloseExec(FD,true);
  193. // Acquire a write lock
  194. struct flock fl;
  195. fl.l_type = F_WRLCK;
  196. fl.l_whence = SEEK_SET;
  197. fl.l_start = 0;
  198. fl.l_len = 0;
  199. if (fcntl(FD,F_SETLK,&fl) == -1)
  200. {
  201. // always close to not leak resources
  202. int Tmp = errno;
  203. close(FD);
  204. errno = Tmp;
  205. if (errno == ENOLCK)
  206. {
  207. _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
  208. return dup(0); // Need something for the caller to close
  209. }
  210. if (Errors == true)
  211. _error->Errno("open",_("Could not get lock %s"),File.c_str());
  212. return -1;
  213. }
  214. return FD;
  215. }
  216. /*}}}*/
  217. // FileExists - Check if a file exists /*{{{*/
  218. // ---------------------------------------------------------------------
  219. /* Beware: Directories are also files! */
  220. bool FileExists(string File)
  221. {
  222. struct stat Buf;
  223. if (stat(File.c_str(),&Buf) != 0)
  224. return false;
  225. return true;
  226. }
  227. /*}}}*/
  228. // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
  229. // ---------------------------------------------------------------------
  230. /* */
  231. bool RealFileExists(string File)
  232. {
  233. struct stat Buf;
  234. if (stat(File.c_str(),&Buf) != 0)
  235. return false;
  236. return ((Buf.st_mode & S_IFREG) != 0);
  237. }
  238. /*}}}*/
  239. // DirectoryExists - Check if a directory exists and is really one /*{{{*/
  240. // ---------------------------------------------------------------------
  241. /* */
  242. bool DirectoryExists(string const &Path)
  243. {
  244. struct stat Buf;
  245. if (stat(Path.c_str(),&Buf) != 0)
  246. return false;
  247. return ((Buf.st_mode & S_IFDIR) != 0);
  248. }
  249. /*}}}*/
  250. // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
  251. // ---------------------------------------------------------------------
  252. /* This method will create all directories needed for path in good old
  253. mkdir -p style but refuses to do this if Parent is not a prefix of
  254. this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
  255. so it will create apt/archives if /var/cache exists - on the other
  256. hand if the parent is /var/lib the creation will fail as this path
  257. is not a parent of the path to be generated. */
  258. bool CreateDirectory(string const &Parent, string const &Path)
  259. {
  260. if (Parent.empty() == true || Path.empty() == true)
  261. return false;
  262. if (DirectoryExists(Path) == true)
  263. return true;
  264. if (DirectoryExists(Parent) == false)
  265. return false;
  266. // we are not going to create directories "into the blue"
  267. if (Path.compare(0, Parent.length(), Parent) != 0)
  268. return false;
  269. vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
  270. string progress = Parent;
  271. for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
  272. {
  273. if (d->empty() == true)
  274. continue;
  275. progress.append("/").append(*d);
  276. if (DirectoryExists(progress) == true)
  277. continue;
  278. if (mkdir(progress.c_str(), 0755) != 0)
  279. return false;
  280. }
  281. return true;
  282. }
  283. /*}}}*/
  284. // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
  285. // ---------------------------------------------------------------------
  286. /* a small wrapper around CreateDirectory to check if it exists and to
  287. remove the trailing "/apt/" from the parent directory if needed */
  288. bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path)
  289. {
  290. if (DirectoryExists(Path) == true)
  291. return true;
  292. size_t const len = Parent.size();
  293. if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
  294. {
  295. if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
  296. return true;
  297. }
  298. else if (CreateDirectory(Parent, Path) == true)
  299. return true;
  300. return false;
  301. }
  302. /*}}}*/
  303. // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
  304. // ---------------------------------------------------------------------
  305. /* If an extension is given only files with this extension are included
  306. in the returned vector, otherwise every "normal" file is included. */
  307. std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
  308. bool const &SortList, bool const &AllowNoExt)
  309. {
  310. std::vector<string> ext;
  311. ext.reserve(2);
  312. if (Ext.empty() == false)
  313. ext.push_back(Ext);
  314. if (AllowNoExt == true && ext.empty() == false)
  315. ext.push_back("");
  316. return GetListOfFilesInDir(Dir, ext, SortList);
  317. }
  318. std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
  319. bool const &SortList)
  320. {
  321. // Attention debuggers: need to be set with the environment config file!
  322. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  323. if (Debug == true)
  324. {
  325. std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
  326. if (Ext.empty() == true)
  327. std::clog << "\tNO extension" << std::endl;
  328. else
  329. for (std::vector<string>::const_iterator e = Ext.begin();
  330. e != Ext.end(); ++e)
  331. std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
  332. }
  333. std::vector<string> List;
  334. if (DirectoryExists(Dir) == false)
  335. {
  336. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  337. return List;
  338. }
  339. Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
  340. DIR *D = opendir(Dir.c_str());
  341. if (D == 0)
  342. {
  343. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  344. return List;
  345. }
  346. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  347. {
  348. // skip "hidden" files
  349. if (Ent->d_name[0] == '.')
  350. continue;
  351. // Make sure it is a file and not something else
  352. string const File = flCombine(Dir,Ent->d_name);
  353. #ifdef _DIRENT_HAVE_D_TYPE
  354. if (Ent->d_type != DT_REG)
  355. #endif
  356. {
  357. if (RealFileExists(File) == false)
  358. {
  359. // do not show ignoration warnings for directories
  360. if (
  361. #ifdef _DIRENT_HAVE_D_TYPE
  362. Ent->d_type == DT_DIR ||
  363. #endif
  364. DirectoryExists(File) == true)
  365. continue;
  366. if (SilentIgnore.Match(Ent->d_name) == false)
  367. _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
  368. continue;
  369. }
  370. }
  371. // check for accepted extension:
  372. // no extension given -> periods are bad as hell!
  373. // extensions given -> "" extension allows no extension
  374. if (Ext.empty() == false)
  375. {
  376. string d_ext = flExtension(Ent->d_name);
  377. if (d_ext == Ent->d_name) // no extension
  378. {
  379. if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
  380. {
  381. if (Debug == true)
  382. std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
  383. if (SilentIgnore.Match(Ent->d_name) == false)
  384. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
  385. continue;
  386. }
  387. }
  388. else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
  389. {
  390. if (Debug == true)
  391. std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
  392. if (SilentIgnore.Match(Ent->d_name) == false)
  393. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
  394. continue;
  395. }
  396. }
  397. // Skip bad filenames ala run-parts
  398. const char *C = Ent->d_name;
  399. for (; *C != 0; ++C)
  400. if (isalpha(*C) == 0 && isdigit(*C) == 0
  401. && *C != '_' && *C != '-' && *C != ':') {
  402. // no required extension -> dot is a bad character
  403. if (*C == '.' && Ext.empty() == false)
  404. continue;
  405. break;
  406. }
  407. // we don't reach the end of the name -> bad character included
  408. if (*C != 0)
  409. {
  410. if (Debug == true)
  411. std::clog << "Bad file: " << Ent->d_name << " → bad character »"
  412. << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
  413. continue;
  414. }
  415. // skip filenames which end with a period. These are never valid
  416. if (*(C - 1) == '.')
  417. {
  418. if (Debug == true)
  419. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  420. continue;
  421. }
  422. if (Debug == true)
  423. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  424. List.push_back(File);
  425. }
  426. closedir(D);
  427. if (SortList == true)
  428. std::sort(List.begin(),List.end());
  429. return List;
  430. }
  431. std::vector<string> GetListOfFilesInDir(string const &Dir, bool SortList)
  432. {
  433. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  434. if (Debug == true)
  435. std::clog << "Accept in " << Dir << " all regular files" << std::endl;
  436. std::vector<string> List;
  437. if (DirectoryExists(Dir) == false)
  438. {
  439. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  440. return List;
  441. }
  442. DIR *D = opendir(Dir.c_str());
  443. if (D == 0)
  444. {
  445. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  446. return List;
  447. }
  448. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  449. {
  450. // skip "hidden" files
  451. if (Ent->d_name[0] == '.')
  452. continue;
  453. // Make sure it is a file and not something else
  454. string const File = flCombine(Dir,Ent->d_name);
  455. #ifdef _DIRENT_HAVE_D_TYPE
  456. if (Ent->d_type != DT_REG)
  457. #endif
  458. {
  459. if (RealFileExists(File) == false)
  460. {
  461. if (Debug == true)
  462. std::clog << "Bad file: " << Ent->d_name << " → it is not a real file" << std::endl;
  463. continue;
  464. }
  465. }
  466. // Skip bad filenames ala run-parts
  467. const char *C = Ent->d_name;
  468. for (; *C != 0; ++C)
  469. if (isalpha(*C) == 0 && isdigit(*C) == 0
  470. && *C != '_' && *C != '-' && *C != '.')
  471. break;
  472. // we don't reach the end of the name -> bad character included
  473. if (*C != 0)
  474. {
  475. if (Debug == true)
  476. std::clog << "Bad file: " << Ent->d_name << " → bad character »" << *C << "« in filename" << std::endl;
  477. continue;
  478. }
  479. // skip filenames which end with a period. These are never valid
  480. if (*(C - 1) == '.')
  481. {
  482. if (Debug == true)
  483. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  484. continue;
  485. }
  486. if (Debug == true)
  487. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  488. List.push_back(File);
  489. }
  490. closedir(D);
  491. if (SortList == true)
  492. std::sort(List.begin(),List.end());
  493. return List;
  494. }
  495. /*}}}*/
  496. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  497. // ---------------------------------------------------------------------
  498. /* We return / on failure. */
  499. string SafeGetCWD()
  500. {
  501. // Stash the current dir.
  502. char S[300];
  503. S[0] = 0;
  504. if (getcwd(S,sizeof(S)-2) == 0)
  505. return "/";
  506. unsigned int Len = strlen(S);
  507. S[Len] = '/';
  508. S[Len+1] = 0;
  509. return S;
  510. }
  511. /*}}}*/
  512. // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
  513. // ---------------------------------------------------------------------
  514. /* We return / on failure. */
  515. time_t GetModificationTime(string const &Path)
  516. {
  517. struct stat St;
  518. if (stat(Path.c_str(), &St) < 0)
  519. return -1;
  520. return St.st_mtime;
  521. }
  522. /*}}}*/
  523. // flNotDir - Strip the directory from the filename /*{{{*/
  524. // ---------------------------------------------------------------------
  525. /* */
  526. string flNotDir(string File)
  527. {
  528. string::size_type Res = File.rfind('/');
  529. if (Res == string::npos)
  530. return File;
  531. Res++;
  532. return string(File,Res,Res - File.length());
  533. }
  534. /*}}}*/
  535. // flNotFile - Strip the file from the directory name /*{{{*/
  536. // ---------------------------------------------------------------------
  537. /* Result ends in a / */
  538. string flNotFile(string File)
  539. {
  540. string::size_type Res = File.rfind('/');
  541. if (Res == string::npos)
  542. return "./";
  543. Res++;
  544. return string(File,0,Res);
  545. }
  546. /*}}}*/
  547. // flExtension - Return the extension for the file /*{{{*/
  548. // ---------------------------------------------------------------------
  549. /* */
  550. string flExtension(string File)
  551. {
  552. string::size_type Res = File.rfind('.');
  553. if (Res == string::npos)
  554. return File;
  555. Res++;
  556. return string(File,Res,Res - File.length());
  557. }
  558. /*}}}*/
  559. // flNoLink - If file is a symlink then deref it /*{{{*/
  560. // ---------------------------------------------------------------------
  561. /* If the name is not a link then the returned path is the input. */
  562. string flNoLink(string File)
  563. {
  564. struct stat St;
  565. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  566. return File;
  567. if (stat(File.c_str(),&St) != 0)
  568. return File;
  569. /* Loop resolving the link. There is no need to limit the number of
  570. loops because the stat call above ensures that the symlink is not
  571. circular */
  572. char Buffer[1024];
  573. string NFile = File;
  574. while (1)
  575. {
  576. // Read the link
  577. ssize_t Res;
  578. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  579. (size_t)Res >= sizeof(Buffer))
  580. return File;
  581. // Append or replace the previous path
  582. Buffer[Res] = 0;
  583. if (Buffer[0] == '/')
  584. NFile = Buffer;
  585. else
  586. NFile = flNotFile(NFile) + Buffer;
  587. // See if we are done
  588. if (lstat(NFile.c_str(),&St) != 0)
  589. return File;
  590. if (S_ISLNK(St.st_mode) == 0)
  591. return NFile;
  592. }
  593. }
  594. /*}}}*/
  595. // flCombine - Combine a file and a directory /*{{{*/
  596. // ---------------------------------------------------------------------
  597. /* If the file is an absolute path then it is just returned, otherwise
  598. the directory is pre-pended to it. */
  599. string flCombine(string Dir,string File)
  600. {
  601. if (File.empty() == true)
  602. return string();
  603. if (File[0] == '/' || Dir.empty() == true)
  604. return File;
  605. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  606. return File;
  607. if (Dir[Dir.length()-1] == '/')
  608. return Dir + File;
  609. return Dir + '/' + File;
  610. }
  611. /*}}}*/
  612. // flAbsPath - Return the absolute path of the filename /*{{{*/
  613. // ---------------------------------------------------------------------
  614. /* */
  615. string flAbsPath(string File)
  616. {
  617. char *p = realpath(File.c_str(), NULL);
  618. if (p == NULL)
  619. {
  620. _error->Errno("realpath", "flAbsPath on %s failed", File.c_str());
  621. return "";
  622. }
  623. std::string AbsPath(p);
  624. free(p);
  625. return AbsPath;
  626. }
  627. /*}}}*/
  628. std::string flNormalize(std::string file) /*{{{*/
  629. {
  630. if (file.empty())
  631. return file;
  632. // do some normalisation by removing // and /./ from the path
  633. size_t found = string::npos;
  634. while ((found = file.find("/./")) != string::npos)
  635. file.replace(found, 3, "/");
  636. while ((found = file.find("//")) != string::npos)
  637. file.replace(found, 2, "/");
  638. if (APT::String::Startswith(file, "/dev/null"))
  639. {
  640. file.erase(strlen("/dev/null"));
  641. return file;
  642. }
  643. return file;
  644. }
  645. /*}}}*/
  646. // SetCloseExec - Set the close on exec flag /*{{{*/
  647. // ---------------------------------------------------------------------
  648. /* */
  649. void SetCloseExec(int Fd,bool Close)
  650. {
  651. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  652. {
  653. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  654. exit(100);
  655. }
  656. }
  657. /*}}}*/
  658. // SetNonBlock - Set the nonblocking flag /*{{{*/
  659. // ---------------------------------------------------------------------
  660. /* */
  661. void SetNonBlock(int Fd,bool Block)
  662. {
  663. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  664. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  665. {
  666. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  667. exit(100);
  668. }
  669. }
  670. /*}}}*/
  671. // WaitFd - Wait for a FD to become readable /*{{{*/
  672. // ---------------------------------------------------------------------
  673. /* This waits for a FD to become readable using select. It is useful for
  674. applications making use of non-blocking sockets. The timeout is
  675. in seconds. */
  676. bool WaitFd(int Fd,bool write,unsigned long timeout)
  677. {
  678. fd_set Set;
  679. struct timeval tv;
  680. FD_ZERO(&Set);
  681. FD_SET(Fd,&Set);
  682. tv.tv_sec = timeout;
  683. tv.tv_usec = 0;
  684. if (write == true)
  685. {
  686. int Res;
  687. do
  688. {
  689. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  690. }
  691. while (Res < 0 && errno == EINTR);
  692. if (Res <= 0)
  693. return false;
  694. }
  695. else
  696. {
  697. int Res;
  698. do
  699. {
  700. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  701. }
  702. while (Res < 0 && errno == EINTR);
  703. if (Res <= 0)
  704. return false;
  705. }
  706. return true;
  707. }
  708. /*}}}*/
  709. // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
  710. // ---------------------------------------------------------------------
  711. /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
  712. * set.
  713. */
  714. void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs)
  715. {
  716. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  717. if (Opts != 0 && Opts->Child != 0)
  718. {
  719. Opts = Opts->Child;
  720. for (; Opts != 0; Opts = Opts->Next)
  721. {
  722. if (Opts->Value.empty() == true)
  723. continue;
  724. int fd = atoi(Opts->Value.c_str());
  725. KeepFDs.insert(fd);
  726. }
  727. }
  728. }
  729. /*}}}*/
  730. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  731. // ---------------------------------------------------------------------
  732. /* This is used if you want to cleanse the environment for the forked
  733. child, it fixes up the important signals and nukes all of the fds,
  734. otherwise acts like normal fork. */
  735. pid_t ExecFork()
  736. {
  737. set<int> KeepFDs;
  738. // we need to merge the Keep-Fds as external tools like
  739. // debconf-apt-progress use it
  740. MergeKeepFdsFromConfiguration(KeepFDs);
  741. return ExecFork(KeepFDs);
  742. }
  743. pid_t ExecFork(std::set<int> KeepFDs)
  744. {
  745. // Fork off the process
  746. pid_t Process = fork();
  747. if (Process < 0)
  748. {
  749. cerr << "FATAL -> Failed to fork." << endl;
  750. exit(100);
  751. }
  752. // Spawn the subprocess
  753. if (Process == 0)
  754. {
  755. // Setup the signals
  756. signal(SIGPIPE,SIG_DFL);
  757. signal(SIGQUIT,SIG_DFL);
  758. signal(SIGINT,SIG_DFL);
  759. signal(SIGWINCH,SIG_DFL);
  760. signal(SIGCONT,SIG_DFL);
  761. signal(SIGTSTP,SIG_DFL);
  762. DIR *dir = opendir("/proc/self/fd");
  763. if (dir != NULL)
  764. {
  765. struct dirent *ent;
  766. while ((ent = readdir(dir)))
  767. {
  768. int fd = atoi(ent->d_name);
  769. // If fd > 0, it was a fd number and not . or ..
  770. if (fd >= 3 && KeepFDs.find(fd) == KeepFDs.end())
  771. fcntl(fd,F_SETFD,FD_CLOEXEC);
  772. }
  773. closedir(dir);
  774. } else {
  775. long ScOpenMax = sysconf(_SC_OPEN_MAX);
  776. // Close all of our FDs - just in case
  777. for (int K = 3; K != ScOpenMax; K++)
  778. {
  779. if(KeepFDs.find(K) == KeepFDs.end())
  780. fcntl(K,F_SETFD,FD_CLOEXEC);
  781. }
  782. }
  783. }
  784. return Process;
  785. }
  786. /*}}}*/
  787. // ExecWait - Fancy waitpid /*{{{*/
  788. // ---------------------------------------------------------------------
  789. /* Waits for the given sub process. If Reap is set then no errors are
  790. generated. Otherwise a failed subprocess will generate a proper descriptive
  791. message */
  792. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  793. {
  794. if (Pid <= 1)
  795. return true;
  796. // Wait and collect the error code
  797. int Status;
  798. while (waitpid(Pid,&Status,0) != Pid)
  799. {
  800. if (errno == EINTR)
  801. continue;
  802. if (Reap == true)
  803. return false;
  804. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  805. }
  806. // Check for an error code.
  807. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  808. {
  809. if (Reap == true)
  810. return false;
  811. if (WIFSIGNALED(Status) != 0)
  812. {
  813. if( WTERMSIG(Status) == SIGSEGV)
  814. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  815. else
  816. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  817. }
  818. if (WIFEXITED(Status) != 0)
  819. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  820. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  821. }
  822. return true;
  823. }
  824. /*}}}*/
  825. // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
  826. bool StartsWithGPGClearTextSignature(string const &FileName)
  827. {
  828. static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
  829. char buffer[strlen(SIGMSG)+1];
  830. FILE* gpg = fopen(FileName.c_str(), "r");
  831. if (gpg == NULL)
  832. return false;
  833. char const * const test = fgets(buffer, sizeof(buffer), gpg);
  834. fclose(gpg);
  835. if (test == NULL || strcmp(buffer, SIGMSG) != 0)
  836. return false;
  837. return true;
  838. }
  839. /*}}}*/
  840. // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
  841. bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
  842. {
  843. if (strcmp(file, "/dev/null") == 0)
  844. return true;
  845. bool Res = true;
  846. if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it
  847. {
  848. // ensure the file is owned by root and has good permissions
  849. struct passwd const * const pw = getpwnam(user);
  850. struct group const * const gr = getgrnam(group);
  851. if (pw != NULL && gr != NULL && lchown(file, pw->pw_uid, gr->gr_gid) != 0)
  852. Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
  853. }
  854. struct stat Buf;
  855. if (lstat(file, &Buf) != 0 || S_ISLNK(Buf.st_mode))
  856. return Res;
  857. if (chmod(file, mode) != 0)
  858. Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
  859. return Res;
  860. }
  861. /*}}}*/
  862. struct APT_HIDDEN simple_buffer { /*{{{*/
  863. size_t buffersize_max = 0;
  864. unsigned long long bufferstart = 0;
  865. unsigned long long bufferend = 0;
  866. char *buffer = nullptr;
  867. simple_buffer() {
  868. reset(4096);
  869. }
  870. ~simple_buffer() {
  871. delete[] buffer;
  872. }
  873. const char *get() const { return buffer + bufferstart; }
  874. char *get() { return buffer + bufferstart; }
  875. const char *getend() const { return buffer + bufferend; }
  876. char *getend() { return buffer + bufferend; }
  877. bool empty() const { return bufferend <= bufferstart; }
  878. bool full() const { return bufferend == buffersize_max; }
  879. unsigned long long free() const { return buffersize_max - bufferend; }
  880. unsigned long long size() const { return bufferend-bufferstart; }
  881. void reset(size_t size)
  882. {
  883. if (size > buffersize_max) {
  884. delete[] buffer;
  885. buffersize_max = size;
  886. buffer = new char[size];
  887. }
  888. reset();
  889. }
  890. void reset() { bufferend = bufferstart = 0; }
  891. ssize_t read(void *to, unsigned long long requested_size) APT_MUSTCHECK
  892. {
  893. if (size() < requested_size)
  894. requested_size = size();
  895. memcpy(to, buffer + bufferstart, requested_size);
  896. bufferstart += requested_size;
  897. if (bufferstart == bufferend)
  898. bufferstart = bufferend = 0;
  899. return requested_size;
  900. }
  901. ssize_t write(const void *from, unsigned long long requested_size) APT_MUSTCHECK
  902. {
  903. if (free() < requested_size)
  904. requested_size = free();
  905. memcpy(getend(), from, requested_size);
  906. bufferend += requested_size;
  907. if (bufferstart == bufferend)
  908. bufferstart = bufferend = 0;
  909. return requested_size;
  910. }
  911. };
  912. /*}}}*/
  913. class APT_HIDDEN FileFdPrivate { /*{{{*/
  914. friend class BufferedWriteFileFdPrivate;
  915. protected:
  916. FileFd * const filefd;
  917. simple_buffer buffer;
  918. int compressed_fd;
  919. pid_t compressor_pid;
  920. bool is_pipe;
  921. APT::Configuration::Compressor compressor;
  922. unsigned int openmode;
  923. unsigned long long seekpos;
  924. public:
  925. explicit FileFdPrivate(FileFd * const pfilefd) : filefd(pfilefd),
  926. compressed_fd(-1), compressor_pid(-1), is_pipe(false),
  927. openmode(0), seekpos(0) {};
  928. virtual APT::Configuration::Compressor get_compressor() const
  929. {
  930. return compressor;
  931. }
  932. virtual void set_compressor(APT::Configuration::Compressor const &compressor)
  933. {
  934. this->compressor = compressor;
  935. }
  936. virtual unsigned int get_openmode() const
  937. {
  938. return openmode;
  939. }
  940. virtual void set_openmode(unsigned int openmode)
  941. {
  942. this->openmode = openmode;
  943. }
  944. virtual bool get_is_pipe() const
  945. {
  946. return is_pipe;
  947. }
  948. virtual void set_is_pipe(bool is_pipe)
  949. {
  950. this->is_pipe = is_pipe;
  951. }
  952. virtual unsigned long long get_seekpos() const
  953. {
  954. return seekpos;
  955. }
  956. virtual void set_seekpos(unsigned long long seekpos)
  957. {
  958. this->seekpos = seekpos;
  959. }
  960. virtual bool InternalOpen(int const iFd, unsigned int const Mode) = 0;
  961. ssize_t InternalRead(void * To, unsigned long long Size)
  962. {
  963. // Drain the buffer if needed.
  964. if (buffer.empty() == false)
  965. {
  966. return buffer.read(To, Size);
  967. }
  968. return InternalUnbufferedRead(To, Size);
  969. }
  970. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) = 0;
  971. virtual bool InternalReadError() { return filefd->FileFdErrno("read",_("Read error")); }
  972. virtual char * InternalReadLine(char * To, unsigned long long Size)
  973. {
  974. if (unlikely(Size == 0))
  975. return nullptr;
  976. // Read one byte less than buffer size to have space for trailing 0.
  977. --Size;
  978. char * const InitialTo = To;
  979. while (Size > 0) {
  980. if (buffer.empty() == true)
  981. {
  982. buffer.reset();
  983. unsigned long long actualread = 0;
  984. if (filefd->Read(buffer.getend(), buffer.free(), &actualread) == false)
  985. return nullptr;
  986. buffer.bufferend = actualread;
  987. if (buffer.size() == 0)
  988. {
  989. if (To == InitialTo)
  990. return nullptr;
  991. break;
  992. }
  993. filefd->Flags &= ~FileFd::HitEof;
  994. }
  995. unsigned long long const OutputSize = std::min(Size, buffer.size());
  996. char const * const newline = static_cast<char const * const>(memchr(buffer.get(), '\n', OutputSize));
  997. // Read until end of line or up to Size bytes from the buffer.
  998. unsigned long long actualread = buffer.read(To,
  999. (newline != nullptr)
  1000. ? (newline - buffer.get()) + 1
  1001. : OutputSize);
  1002. To += actualread;
  1003. Size -= actualread;
  1004. if (newline != nullptr)
  1005. break;
  1006. }
  1007. *To = '\0';
  1008. return InitialTo;
  1009. }
  1010. virtual bool InternalFlush()
  1011. {
  1012. return true;
  1013. }
  1014. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) = 0;
  1015. virtual bool InternalWriteError() { return filefd->FileFdErrno("write",_("Write error")); }
  1016. virtual bool InternalSeek(unsigned long long const To)
  1017. {
  1018. // Our poor man seeking is costly, so try to avoid it
  1019. unsigned long long const iseekpos = filefd->Tell();
  1020. if (iseekpos == To)
  1021. return true;
  1022. else if (iseekpos < To)
  1023. return filefd->Skip(To - iseekpos);
  1024. if ((openmode & FileFd::ReadOnly) != FileFd::ReadOnly)
  1025. return filefd->FileFdError("Reopen is only implemented for read-only files!");
  1026. InternalClose(filefd->FileName);
  1027. if (filefd->iFd != -1)
  1028. close(filefd->iFd);
  1029. filefd->iFd = -1;
  1030. if (filefd->TemporaryFileName.empty() == false)
  1031. filefd->iFd = open(filefd->TemporaryFileName.c_str(), O_RDONLY);
  1032. else if (filefd->FileName.empty() == false)
  1033. filefd->iFd = open(filefd->FileName.c_str(), O_RDONLY);
  1034. else
  1035. {
  1036. if (compressed_fd > 0)
  1037. if (lseek(compressed_fd, 0, SEEK_SET) != 0)
  1038. filefd->iFd = compressed_fd;
  1039. if (filefd->iFd < 0)
  1040. return filefd->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1041. }
  1042. if (filefd->OpenInternDescriptor(openmode, compressor) == false)
  1043. return filefd->FileFdError("Seek on file %s because it couldn't be reopened", filefd->FileName.c_str());
  1044. buffer.reset();
  1045. set_seekpos(0);
  1046. if (To != 0)
  1047. return filefd->Skip(To);
  1048. seekpos = To;
  1049. return true;
  1050. }
  1051. virtual bool InternalSkip(unsigned long long Over)
  1052. {
  1053. unsigned long long constexpr buffersize = 1024;
  1054. char buffer[buffersize];
  1055. while (Over != 0)
  1056. {
  1057. unsigned long long toread = std::min(buffersize, Over);
  1058. if (filefd->Read(buffer, toread) == false)
  1059. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1060. Over -= toread;
  1061. }
  1062. return true;
  1063. }
  1064. virtual bool InternalTruncate(unsigned long long const)
  1065. {
  1066. return filefd->FileFdError("Truncating compressed files is not implemented (%s)", filefd->FileName.c_str());
  1067. }
  1068. virtual unsigned long long InternalTell()
  1069. {
  1070. // In theory, we could just return seekpos here always instead of
  1071. // seeking around, but not all users of FileFd use always Seek() and co
  1072. // so d->seekpos isn't always true and we can just use it as a hint if
  1073. // we have nothing else, but not always as an authority…
  1074. return seekpos - buffer.size();
  1075. }
  1076. virtual unsigned long long InternalSize()
  1077. {
  1078. unsigned long long size = 0;
  1079. unsigned long long const oldSeek = filefd->Tell();
  1080. unsigned long long constexpr ignoresize = 1024;
  1081. char ignore[ignoresize];
  1082. unsigned long long read = 0;
  1083. do {
  1084. if (filefd->Read(ignore, ignoresize, &read) == false)
  1085. {
  1086. filefd->Seek(oldSeek);
  1087. return 0;
  1088. }
  1089. } while(read != 0);
  1090. size = filefd->Tell();
  1091. filefd->Seek(oldSeek);
  1092. return size;
  1093. }
  1094. virtual bool InternalClose(std::string const &FileName) = 0;
  1095. virtual bool InternalStream() const { return false; }
  1096. virtual bool InternalAlwaysAutoClose() const { return true; }
  1097. virtual ~FileFdPrivate() {}
  1098. };
  1099. /*}}}*/
  1100. class APT_HIDDEN BufferedWriteFileFdPrivate : public FileFdPrivate { /*{{{*/
  1101. protected:
  1102. FileFdPrivate *wrapped;
  1103. simple_buffer writebuffer;
  1104. public:
  1105. explicit BufferedWriteFileFdPrivate(FileFdPrivate *Priv) :
  1106. FileFdPrivate(Priv->filefd), wrapped(Priv) {};
  1107. virtual APT::Configuration::Compressor get_compressor() const APT_OVERRIDE
  1108. {
  1109. return wrapped->get_compressor();
  1110. }
  1111. virtual void set_compressor(APT::Configuration::Compressor const &compressor) APT_OVERRIDE
  1112. {
  1113. return wrapped->set_compressor(compressor);
  1114. }
  1115. virtual unsigned int get_openmode() const APT_OVERRIDE
  1116. {
  1117. return wrapped->get_openmode();
  1118. }
  1119. virtual void set_openmode(unsigned int openmode) APT_OVERRIDE
  1120. {
  1121. return wrapped->set_openmode(openmode);
  1122. }
  1123. virtual bool get_is_pipe() const APT_OVERRIDE
  1124. {
  1125. return wrapped->get_is_pipe();
  1126. }
  1127. virtual void set_is_pipe(bool is_pipe) APT_OVERRIDE
  1128. {
  1129. FileFdPrivate::set_is_pipe(is_pipe);
  1130. wrapped->set_is_pipe(is_pipe);
  1131. }
  1132. virtual unsigned long long get_seekpos() const APT_OVERRIDE
  1133. {
  1134. return wrapped->get_seekpos();
  1135. }
  1136. virtual void set_seekpos(unsigned long long seekpos) APT_OVERRIDE
  1137. {
  1138. return wrapped->set_seekpos(seekpos);
  1139. }
  1140. virtual bool InternalOpen(int const iFd, unsigned int const Mode) APT_OVERRIDE
  1141. {
  1142. if (InternalFlush() == false)
  1143. return false;
  1144. return wrapped->InternalOpen(iFd, Mode);
  1145. }
  1146. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1147. {
  1148. if (InternalFlush() == false)
  1149. return -1;
  1150. return wrapped->InternalUnbufferedRead(To, Size);
  1151. }
  1152. virtual bool InternalReadError() APT_OVERRIDE
  1153. {
  1154. return wrapped->InternalReadError();
  1155. }
  1156. virtual char * InternalReadLine(char * To, unsigned long long Size) APT_OVERRIDE
  1157. {
  1158. if (InternalFlush() == false)
  1159. return nullptr;
  1160. return wrapped->InternalReadLine(To, Size);
  1161. }
  1162. virtual bool InternalFlush() APT_OVERRIDE
  1163. {
  1164. while (writebuffer.empty() == false) {
  1165. auto written = wrapped->InternalWrite(writebuffer.get(),
  1166. writebuffer.size());
  1167. // Ignore interrupted syscalls
  1168. if (written < 0 && errno == EINTR)
  1169. continue;
  1170. if (written < 0)
  1171. return wrapped->InternalWriteError();
  1172. writebuffer.bufferstart += written;
  1173. }
  1174. writebuffer.reset();
  1175. return wrapped->InternalFlush();
  1176. }
  1177. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1178. {
  1179. // Optimisation: If the buffer is empty and we have more to write than
  1180. // would fit in the buffer (or equal number of bytes), write directly.
  1181. if (writebuffer.empty() == true && Size >= writebuffer.free())
  1182. return wrapped->InternalWrite(From, Size);
  1183. // Write as much into the buffer as possible and then flush if needed
  1184. auto written = writebuffer.write(From, Size);
  1185. if (writebuffer.full() && InternalFlush() == false)
  1186. return -1;
  1187. return written;
  1188. }
  1189. virtual bool InternalWriteError() APT_OVERRIDE
  1190. {
  1191. return wrapped->InternalWriteError();
  1192. }
  1193. virtual bool InternalSeek(unsigned long long const To) APT_OVERRIDE
  1194. {
  1195. if (InternalFlush() == false)
  1196. return false;
  1197. return wrapped->InternalSeek(To);
  1198. }
  1199. virtual bool InternalSkip(unsigned long long Over) APT_OVERRIDE
  1200. {
  1201. if (InternalFlush() == false)
  1202. return false;
  1203. return wrapped->InternalSkip(Over);
  1204. }
  1205. virtual bool InternalTruncate(unsigned long long const Size) APT_OVERRIDE
  1206. {
  1207. if (InternalFlush() == false)
  1208. return false;
  1209. return wrapped->InternalTruncate(Size);
  1210. }
  1211. virtual unsigned long long InternalTell() APT_OVERRIDE
  1212. {
  1213. if (InternalFlush() == false)
  1214. return -1;
  1215. return wrapped->InternalTell();
  1216. }
  1217. virtual unsigned long long InternalSize() APT_OVERRIDE
  1218. {
  1219. if (InternalFlush() == false)
  1220. return -1;
  1221. return wrapped->InternalSize();
  1222. }
  1223. virtual bool InternalClose(std::string const &FileName) APT_OVERRIDE
  1224. {
  1225. return wrapped->InternalClose(FileName);
  1226. }
  1227. virtual bool InternalAlwaysAutoClose() const APT_OVERRIDE
  1228. {
  1229. return wrapped->InternalAlwaysAutoClose();
  1230. }
  1231. virtual ~BufferedWriteFileFdPrivate()
  1232. {
  1233. delete wrapped;
  1234. }
  1235. };
  1236. /*}}}*/
  1237. class APT_HIDDEN GzipFileFdPrivate: public FileFdPrivate { /*{{{*/
  1238. #ifdef HAVE_ZLIB
  1239. public:
  1240. gzFile gz;
  1241. virtual bool InternalOpen(int const iFd, unsigned int const Mode) APT_OVERRIDE
  1242. {
  1243. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1244. gz = gzdopen(iFd, "r+");
  1245. else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1246. gz = gzdopen(iFd, "w");
  1247. else
  1248. gz = gzdopen(iFd, "r");
  1249. filefd->Flags |= FileFd::Compressed;
  1250. return gz != nullptr;
  1251. }
  1252. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1253. {
  1254. return gzread(gz, To, Size);
  1255. }
  1256. virtual bool InternalReadError() APT_OVERRIDE
  1257. {
  1258. int err;
  1259. char const * const errmsg = gzerror(gz, &err);
  1260. if (err != Z_ERRNO)
  1261. return filefd->FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1262. return FileFdPrivate::InternalReadError();
  1263. }
  1264. virtual char * InternalReadLine(char * To, unsigned long long Size) APT_OVERRIDE
  1265. {
  1266. return gzgets(gz, To, Size);
  1267. }
  1268. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1269. {
  1270. return gzwrite(gz,From,Size);
  1271. }
  1272. virtual bool InternalWriteError() APT_OVERRIDE
  1273. {
  1274. int err;
  1275. char const * const errmsg = gzerror(gz, &err);
  1276. if (err != Z_ERRNO)
  1277. return filefd->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1278. return FileFdPrivate::InternalWriteError();
  1279. }
  1280. virtual bool InternalSeek(unsigned long long const To) APT_OVERRIDE
  1281. {
  1282. off_t const res = gzseek(gz, To, SEEK_SET);
  1283. if (res != (off_t)To)
  1284. return filefd->FileFdError("Unable to seek to %llu", To);
  1285. seekpos = To;
  1286. buffer.reset();
  1287. return true;
  1288. }
  1289. virtual bool InternalSkip(unsigned long long Over) APT_OVERRIDE
  1290. {
  1291. if (Over >= buffer.size())
  1292. {
  1293. Over -= buffer.size();
  1294. buffer.reset();
  1295. }
  1296. else
  1297. {
  1298. buffer.bufferstart += Over;
  1299. return true;
  1300. }
  1301. if (Over == 0)
  1302. return true;
  1303. off_t const res = gzseek(gz, Over, SEEK_CUR);
  1304. if (res < 0)
  1305. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1306. seekpos = res;
  1307. return true;
  1308. }
  1309. virtual unsigned long long InternalTell() APT_OVERRIDE
  1310. {
  1311. return gztell(gz) - buffer.size();
  1312. }
  1313. virtual unsigned long long InternalSize() APT_OVERRIDE
  1314. {
  1315. unsigned long long filesize = FileFdPrivate::InternalSize();
  1316. // only check gzsize if we are actually a gzip file, just checking for
  1317. // "gz" is not sufficient as uncompressed files could be opened with
  1318. // gzopen in "direct" mode as well
  1319. if (filesize == 0 || gzdirect(gz))
  1320. return filesize;
  1321. off_t const oldPos = lseek(filefd->iFd, 0, SEEK_CUR);
  1322. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1323. * this ourselves; the original (uncompressed) file size is the last 32
  1324. * bits of the file */
  1325. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1326. if (lseek(filefd->iFd, -4, SEEK_END) < 0)
  1327. {
  1328. filefd->FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1329. return 0;
  1330. }
  1331. uint32_t size = 0;
  1332. if (read(filefd->iFd, &size, 4) != 4)
  1333. {
  1334. filefd->FileFdErrno("read","Unable to read original size of gzipped file");
  1335. return 0;
  1336. }
  1337. size = le32toh(size);
  1338. if (lseek(filefd->iFd, oldPos, SEEK_SET) < 0)
  1339. {
  1340. filefd->FileFdErrno("lseek","Unable to seek in gzipped file");
  1341. return 0;
  1342. }
  1343. return size;
  1344. }
  1345. virtual bool InternalClose(std::string const &FileName) APT_OVERRIDE
  1346. {
  1347. if (gz == nullptr)
  1348. return true;
  1349. int const e = gzclose(gz);
  1350. gz = nullptr;
  1351. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  1352. if (e != 0 && e != Z_BUF_ERROR)
  1353. return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  1354. return true;
  1355. }
  1356. explicit GzipFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), gz(nullptr) {}
  1357. virtual ~GzipFileFdPrivate() { InternalClose(""); }
  1358. #endif
  1359. };
  1360. /*}}}*/
  1361. class APT_HIDDEN Bz2FileFdPrivate: public FileFdPrivate { /*{{{*/
  1362. #ifdef HAVE_BZ2
  1363. BZFILE* bz2;
  1364. public:
  1365. virtual bool InternalOpen(int const iFd, unsigned int const Mode) APT_OVERRIDE
  1366. {
  1367. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1368. bz2 = BZ2_bzdopen(iFd, "r+");
  1369. else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1370. bz2 = BZ2_bzdopen(iFd, "w");
  1371. else
  1372. bz2 = BZ2_bzdopen(iFd, "r");
  1373. filefd->Flags |= FileFd::Compressed;
  1374. return bz2 != nullptr;
  1375. }
  1376. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1377. {
  1378. return BZ2_bzread(bz2, To, Size);
  1379. }
  1380. virtual bool InternalReadError() APT_OVERRIDE
  1381. {
  1382. int err;
  1383. char const * const errmsg = BZ2_bzerror(bz2, &err);
  1384. if (err != BZ_IO_ERROR)
  1385. return filefd->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd->FileName.c_str(), _("Read error"), err, errmsg);
  1386. return FileFdPrivate::InternalReadError();
  1387. }
  1388. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1389. {
  1390. return BZ2_bzwrite(bz2, (void*)From, Size);
  1391. }
  1392. virtual bool InternalWriteError() APT_OVERRIDE
  1393. {
  1394. int err;
  1395. char const * const errmsg = BZ2_bzerror(bz2, &err);
  1396. if (err != BZ_IO_ERROR)
  1397. return filefd->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd->FileName.c_str(), _("Write error"), err, errmsg);
  1398. return FileFdPrivate::InternalWriteError();
  1399. }
  1400. virtual bool InternalStream() const APT_OVERRIDE { return true; }
  1401. virtual bool InternalClose(std::string const &) APT_OVERRIDE
  1402. {
  1403. if (bz2 == nullptr)
  1404. return true;
  1405. BZ2_bzclose(bz2);
  1406. bz2 = nullptr;
  1407. return true;
  1408. }
  1409. explicit Bz2FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), bz2(nullptr) {}
  1410. virtual ~Bz2FileFdPrivate() { InternalClose(""); }
  1411. #endif
  1412. };
  1413. /*}}}*/
  1414. class APT_HIDDEN Lz4FileFdPrivate: public FileFdPrivate { /*{{{*/
  1415. static constexpr unsigned long long LZ4_HEADER_SIZE = 19;
  1416. static constexpr unsigned long long LZ4_FOOTER_SIZE = 4;
  1417. #ifdef HAVE_LZ4
  1418. LZ4F_decompressionContext_t dctx;
  1419. LZ4F_compressionContext_t cctx;
  1420. LZ4F_errorCode_t res;
  1421. FileFd backend;
  1422. simple_buffer lz4_buffer;
  1423. // Count of bytes that the decompressor expects to read next, or buffer size.
  1424. size_t next_to_load = APT_BUFFER_SIZE;
  1425. public:
  1426. virtual bool InternalOpen(int const iFd, unsigned int const Mode) APT_OVERRIDE
  1427. {
  1428. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1429. return _error->Error("lz4 only supports write or read mode");
  1430. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) {
  1431. res = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
  1432. lz4_buffer.reset(LZ4F_compressBound(APT_BUFFER_SIZE, nullptr)
  1433. + LZ4_HEADER_SIZE + LZ4_FOOTER_SIZE);
  1434. } else {
  1435. res = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION);
  1436. lz4_buffer.reset(APT_BUFFER_SIZE);
  1437. }
  1438. filefd->Flags |= FileFd::Compressed;
  1439. if (LZ4F_isError(res))
  1440. return false;
  1441. unsigned int flags = (Mode & (FileFd::WriteOnly|FileFd::ReadOnly));
  1442. if (backend.OpenDescriptor(iFd, flags, FileFd::None, true) == false)
  1443. return false;
  1444. // Write the file header
  1445. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1446. {
  1447. res = LZ4F_compressBegin(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr);
  1448. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1449. return false;
  1450. }
  1451. return true;
  1452. }
  1453. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1454. {
  1455. /* Keep reading as long as the compressor still wants to read */
  1456. while (next_to_load) {
  1457. // Fill compressed buffer;
  1458. if (lz4_buffer.empty()) {
  1459. unsigned long long read;
  1460. /* Reset - if LZ4 decompressor wants to read more, allocate more */
  1461. lz4_buffer.reset(next_to_load);
  1462. if (backend.Read(lz4_buffer.getend(), lz4_buffer.free(), &read) == false)
  1463. return -1;
  1464. lz4_buffer.bufferend += read;
  1465. /* Expected EOF */
  1466. if (read == 0) {
  1467. res = -1;
  1468. return filefd->FileFdError("LZ4F: %s %s",
  1469. filefd->FileName.c_str(),
  1470. _("Unexpected end of file")), -1;
  1471. }
  1472. }
  1473. // Drain compressed buffer as far as possible.
  1474. size_t in = lz4_buffer.size();
  1475. size_t out = Size;
  1476. res = LZ4F_decompress(dctx, To, &out, lz4_buffer.get(), &in, nullptr);
  1477. if (LZ4F_isError(res))
  1478. return -1;
  1479. next_to_load = res;
  1480. lz4_buffer.bufferstart += in;
  1481. if (out != 0)
  1482. return out;
  1483. }
  1484. return 0;
  1485. }
  1486. virtual bool InternalReadError() APT_OVERRIDE
  1487. {
  1488. char const * const errmsg = LZ4F_getErrorName(res);
  1489. return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Read error"), res, errmsg);
  1490. }
  1491. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1492. {
  1493. unsigned long long const towrite = std::min(APT_BUFFER_SIZE, Size);
  1494. res = LZ4F_compressUpdate(cctx,
  1495. lz4_buffer.buffer, lz4_buffer.buffersize_max,
  1496. From, towrite, nullptr);
  1497. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1498. return -1;
  1499. return towrite;
  1500. }
  1501. virtual bool InternalWriteError() APT_OVERRIDE
  1502. {
  1503. char const * const errmsg = LZ4F_getErrorName(res);
  1504. return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Write error"), res, errmsg);
  1505. }
  1506. virtual bool InternalStream() const APT_OVERRIDE { return true; }
  1507. virtual bool InternalFlush() APT_OVERRIDE
  1508. {
  1509. return backend.Flush();
  1510. }
  1511. virtual bool InternalClose(std::string const &) APT_OVERRIDE
  1512. {
  1513. /* Reset variables */
  1514. res = 0;
  1515. next_to_load = APT_BUFFER_SIZE;
  1516. if (cctx != nullptr)
  1517. {
  1518. if (filefd->Failed() == false)
  1519. {
  1520. res = LZ4F_compressEnd(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr);
  1521. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1522. return false;
  1523. if (!backend.Flush())
  1524. return false;
  1525. }
  1526. if (!backend.Close())
  1527. return false;
  1528. res = LZ4F_freeCompressionContext(cctx);
  1529. cctx = nullptr;
  1530. }
  1531. if (dctx != nullptr)
  1532. {
  1533. res = LZ4F_freeDecompressionContext(dctx);
  1534. dctx = nullptr;
  1535. }
  1536. if (backend.IsOpen())
  1537. {
  1538. backend.Close();
  1539. filefd->iFd = -1;
  1540. }
  1541. return LZ4F_isError(res) == false;
  1542. }
  1543. explicit Lz4FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), dctx(nullptr), cctx(nullptr) {}
  1544. virtual ~Lz4FileFdPrivate() {
  1545. InternalClose("");
  1546. }
  1547. #endif
  1548. };
  1549. /*}}}*/
  1550. class APT_HIDDEN LzmaFileFdPrivate: public FileFdPrivate { /*{{{*/
  1551. #ifdef HAVE_LZMA
  1552. struct LZMAFILE {
  1553. FILE* file;
  1554. FileFd * const filefd;
  1555. uint8_t buffer[4096];
  1556. lzma_stream stream;
  1557. lzma_ret err;
  1558. bool eof;
  1559. bool compressing;
  1560. LZMAFILE(FileFd * const fd) : file(nullptr), filefd(fd), eof(false), compressing(false) { buffer[0] = '\0'; }
  1561. ~LZMAFILE()
  1562. {
  1563. if (compressing == true && filefd->Failed() == false)
  1564. {
  1565. size_t constexpr buffersize = sizeof(buffer)/sizeof(buffer[0]);
  1566. while(true)
  1567. {
  1568. stream.avail_out = buffersize;
  1569. stream.next_out = buffer;
  1570. err = lzma_code(&stream, LZMA_FINISH);
  1571. if (err != LZMA_OK && err != LZMA_STREAM_END)
  1572. {
  1573. _error->Error("~LZMAFILE: Compress finalisation failed");
  1574. break;
  1575. }
  1576. size_t const n = buffersize - stream.avail_out;
  1577. if (n && fwrite(buffer, 1, n, file) != n)
  1578. {
  1579. _error->Errno("~LZMAFILE",_("Write error"));
  1580. break;
  1581. }
  1582. if (err == LZMA_STREAM_END)
  1583. break;
  1584. }
  1585. }
  1586. lzma_end(&stream);
  1587. fclose(file);
  1588. }
  1589. };
  1590. LZMAFILE* lzma;
  1591. static uint32_t findXZlevel(std::vector<std::string> const &Args)
  1592. {
  1593. for (auto a = Args.rbegin(); a != Args.rend(); ++a)
  1594. if (a->empty() == false && (*a)[0] == '-' && (*a)[1] != '-')
  1595. {
  1596. auto const number = a->find_last_of("0123456789");
  1597. if (number == std::string::npos)
  1598. continue;
  1599. auto const extreme = a->find("e", number);
  1600. uint32_t level = (extreme != std::string::npos) ? LZMA_PRESET_EXTREME : 0;
  1601. switch ((*a)[number])
  1602. {
  1603. case '0': return level | 0;
  1604. case '1': return level | 1;
  1605. case '2': return level | 2;
  1606. case '3': return level | 3;
  1607. case '4': return level | 4;
  1608. case '5': return level | 5;
  1609. case '6': return level | 6;
  1610. case '7': return level | 7;
  1611. case '8': return level | 8;
  1612. case '9': return level | 9;
  1613. }
  1614. }
  1615. return 6;
  1616. }
  1617. public:
  1618. virtual bool InternalOpen(int const iFd, unsigned int const Mode) APT_OVERRIDE
  1619. {
  1620. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1621. return filefd->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd->FileName.c_str());
  1622. if (lzma == nullptr)
  1623. lzma = new LzmaFileFdPrivate::LZMAFILE(filefd);
  1624. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1625. lzma->file = fdopen(iFd, "w");
  1626. else
  1627. lzma->file = fdopen(iFd, "r");
  1628. filefd->Flags |= FileFd::Compressed;
  1629. if (lzma->file == nullptr)
  1630. return false;
  1631. lzma_stream tmp_stream = LZMA_STREAM_INIT;
  1632. lzma->stream = tmp_stream;
  1633. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1634. {
  1635. uint32_t const xzlevel = findXZlevel(compressor.CompressArgs);
  1636. if (compressor.Name == "xz")
  1637. {
  1638. if (lzma_easy_encoder(&lzma->stream, xzlevel, LZMA_CHECK_CRC64) != LZMA_OK)
  1639. return false;
  1640. }
  1641. else
  1642. {
  1643. lzma_options_lzma options;
  1644. lzma_lzma_preset(&options, xzlevel);
  1645. if (lzma_alone_encoder(&lzma->stream, &options) != LZMA_OK)
  1646. return false;
  1647. }
  1648. lzma->compressing = true;
  1649. }
  1650. else
  1651. {
  1652. uint64_t const memlimit = UINT64_MAX;
  1653. if (compressor.Name == "xz")
  1654. {
  1655. if (lzma_auto_decoder(&lzma->stream, memlimit, 0) != LZMA_OK)
  1656. return false;
  1657. }
  1658. else
  1659. {
  1660. if (lzma_alone_decoder(&lzma->stream, memlimit) != LZMA_OK)
  1661. return false;
  1662. }
  1663. lzma->compressing = false;
  1664. }
  1665. return true;
  1666. }
  1667. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1668. {
  1669. ssize_t Res;
  1670. if (lzma->eof == true)
  1671. return 0;
  1672. lzma->stream.next_out = (uint8_t *) To;
  1673. lzma->stream.avail_out = Size;
  1674. if (lzma->stream.avail_in == 0)
  1675. {
  1676. lzma->stream.next_in = lzma->buffer;
  1677. lzma->stream.avail_in = fread(lzma->buffer, 1, sizeof(lzma->buffer)/sizeof(lzma->buffer[0]), lzma->file);
  1678. }
  1679. lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
  1680. if (lzma->err == LZMA_STREAM_END)
  1681. {
  1682. lzma->eof = true;
  1683. Res = Size - lzma->stream.avail_out;
  1684. }
  1685. else if (lzma->err != LZMA_OK)
  1686. {
  1687. Res = -1;
  1688. errno = 0;
  1689. }
  1690. else
  1691. {
  1692. Res = Size - lzma->stream.avail_out;
  1693. if (Res == 0)
  1694. {
  1695. // lzma run was okay, but produced no output…
  1696. Res = -1;
  1697. errno = EINTR;
  1698. }
  1699. }
  1700. return Res;
  1701. }
  1702. virtual bool InternalReadError() APT_OVERRIDE
  1703. {
  1704. return filefd->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma->err);
  1705. }
  1706. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1707. {
  1708. ssize_t Res;
  1709. lzma->stream.next_in = (uint8_t *)From;
  1710. lzma->stream.avail_in = Size;
  1711. lzma->stream.next_out = lzma->buffer;
  1712. lzma->stream.avail_out = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]);
  1713. lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
  1714. if (lzma->err != LZMA_OK)
  1715. return -1;
  1716. size_t const n = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]) - lzma->stream.avail_out;
  1717. size_t const m = (n == 0) ? 0 : fwrite(lzma->buffer, 1, n, lzma->file);
  1718. if (m != n)
  1719. {
  1720. Res = -1;
  1721. errno = 0;
  1722. }
  1723. else
  1724. {
  1725. Res = Size - lzma->stream.avail_in;
  1726. if (Res == 0)
  1727. {
  1728. // lzma run was okay, but produced no output…
  1729. Res = -1;
  1730. errno = EINTR;
  1731. }
  1732. }
  1733. return Res;
  1734. }
  1735. virtual bool InternalWriteError() APT_OVERRIDE
  1736. {
  1737. return filefd->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma->err);
  1738. }
  1739. virtual bool InternalStream() const APT_OVERRIDE { return true; }
  1740. virtual bool InternalClose(std::string const &) APT_OVERRIDE
  1741. {
  1742. delete lzma;
  1743. lzma = nullptr;
  1744. return true;
  1745. }
  1746. explicit LzmaFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), lzma(nullptr) {}
  1747. virtual ~LzmaFileFdPrivate() { InternalClose(""); }
  1748. #endif
  1749. };
  1750. /*}}}*/
  1751. class APT_HIDDEN PipedFileFdPrivate: public FileFdPrivate /*{{{*/
  1752. /* if we don't have a specific class dealing with library calls, we (un)compress
  1753. by executing a specified binary and pipe in/out what we need */
  1754. {
  1755. public:
  1756. virtual bool InternalOpen(int const, unsigned int const Mode) APT_OVERRIDE
  1757. {
  1758. // collect zombies here in case we reopen
  1759. if (compressor_pid > 0)
  1760. ExecWait(compressor_pid, "FileFdCompressor", true);
  1761. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1762. return filefd->FileFdError("ReadWrite mode is not supported for file %s", filefd->FileName.c_str());
  1763. if (compressor.Binary == "false")
  1764. return filefd->FileFdError("libapt has inbuilt support for the %s compression,"
  1765. " but was forced to ignore it in favor of an external binary – which isn't installed.", compressor.Name.c_str());
  1766. bool const Comp = (Mode & FileFd::WriteOnly) == FileFd::WriteOnly;
  1767. if (Comp == false && filefd->iFd != -1)
  1768. {
  1769. // Handle 'decompression' of empty files
  1770. struct stat Buf;
  1771. if (fstat(filefd->iFd, &Buf) != 0)
  1772. return filefd->FileFdErrno("fstat", "Could not stat fd %d for file %s", filefd->iFd, filefd->FileName.c_str());
  1773. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1774. return true;
  1775. // We don't need the file open - instead let the compressor open it
  1776. // as he properly knows better how to efficiently read from 'his' file
  1777. if (filefd->FileName.empty() == false)
  1778. {
  1779. close(filefd->iFd);
  1780. filefd->iFd = -1;
  1781. }
  1782. }
  1783. // Create a data pipe
  1784. int Pipe[2] = {-1,-1};
  1785. if (pipe(Pipe) != 0)
  1786. return filefd->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1787. for (int J = 0; J != 2; J++)
  1788. SetCloseExec(Pipe[J],true);
  1789. compressed_fd = filefd->iFd;
  1790. set_is_pipe(true);
  1791. if (Comp == true)
  1792. filefd->iFd = Pipe[1];
  1793. else
  1794. filefd->iFd = Pipe[0];
  1795. // The child..
  1796. compressor_pid = ExecFork();
  1797. if (compressor_pid == 0)
  1798. {
  1799. if (Comp == true)
  1800. {
  1801. dup2(compressed_fd,STDOUT_FILENO);
  1802. dup2(Pipe[0],STDIN_FILENO);
  1803. }
  1804. else
  1805. {
  1806. if (compressed_fd != -1)
  1807. dup2(compressed_fd,STDIN_FILENO);
  1808. dup2(Pipe[1],STDOUT_FILENO);
  1809. }
  1810. int const nullfd = open("/dev/null", O_WRONLY);
  1811. if (nullfd != -1)
  1812. {
  1813. dup2(nullfd,STDERR_FILENO);
  1814. close(nullfd);
  1815. }
  1816. SetCloseExec(STDOUT_FILENO,false);
  1817. SetCloseExec(STDIN_FILENO,false);
  1818. std::vector<char const*> Args;
  1819. Args.push_back(compressor.Binary.c_str());
  1820. std::vector<std::string> const * const addArgs =
  1821. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1822. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1823. a != addArgs->end(); ++a)
  1824. Args.push_back(a->c_str());
  1825. if (Comp == false && filefd->FileName.empty() == false)
  1826. {
  1827. // commands not needing arguments, do not need to be told about using standard output
  1828. // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
  1829. if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
  1830. Args.push_back("--stdout");
  1831. if (filefd->TemporaryFileName.empty() == false)
  1832. Args.push_back(filefd->TemporaryFileName.c_str());
  1833. else
  1834. Args.push_back(filefd->FileName.c_str());
  1835. }
  1836. Args.push_back(NULL);
  1837. execvp(Args[0],(char **)&Args[0]);
  1838. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1839. _exit(100);
  1840. }
  1841. if (Comp == true)
  1842. close(Pipe[0]);
  1843. else
  1844. close(Pipe[1]);
  1845. return true;
  1846. }
  1847. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1848. {
  1849. return read(filefd->iFd, To, Size);
  1850. }
  1851. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1852. {
  1853. return write(filefd->iFd, From, Size);
  1854. }
  1855. virtual bool InternalClose(std::string const &) APT_OVERRIDE
  1856. {
  1857. bool Ret = true;
  1858. if (filefd->iFd != -1)
  1859. {
  1860. close(filefd->iFd);
  1861. filefd->iFd = -1;
  1862. }
  1863. if (compressor_pid > 0)
  1864. Ret &= ExecWait(compressor_pid, "FileFdCompressor", true);
  1865. compressor_pid = -1;
  1866. return Ret;
  1867. }
  1868. explicit PipedFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
  1869. virtual ~PipedFileFdPrivate() { InternalClose(""); }
  1870. };
  1871. /*}}}*/
  1872. class APT_HIDDEN DirectFileFdPrivate: public FileFdPrivate /*{{{*/
  1873. {
  1874. public:
  1875. virtual bool InternalOpen(int const, unsigned int const) APT_OVERRIDE { return true; }
  1876. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) APT_OVERRIDE
  1877. {
  1878. return read(filefd->iFd, To, Size);
  1879. }
  1880. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) APT_OVERRIDE
  1881. {
  1882. // files opened read+write are strange and only really "supported" for direct files
  1883. if (buffer.size() != 0)
  1884. {
  1885. lseek(filefd->iFd, -buffer.size(), SEEK_CUR);
  1886. buffer.reset();
  1887. }
  1888. return write(filefd->iFd, From, Size);
  1889. }
  1890. virtual bool InternalSeek(unsigned long long const To) APT_OVERRIDE
  1891. {
  1892. off_t const res = lseek(filefd->iFd, To, SEEK_SET);
  1893. if (res != (off_t)To)
  1894. return filefd->FileFdError("Unable to seek to %llu", To);
  1895. seekpos = To;
  1896. buffer.reset();
  1897. return true;
  1898. }
  1899. virtual bool InternalSkip(unsigned long long Over) APT_OVERRIDE
  1900. {
  1901. if (Over >= buffer.size())
  1902. {
  1903. Over -= buffer.size();
  1904. buffer.reset();
  1905. }
  1906. else
  1907. {
  1908. buffer.bufferstart += Over;
  1909. return true;
  1910. }
  1911. if (Over == 0)
  1912. return true;
  1913. off_t const res = lseek(filefd->iFd, Over, SEEK_CUR);
  1914. if (res < 0)
  1915. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1916. seekpos = res;
  1917. return true;
  1918. }
  1919. virtual bool InternalTruncate(unsigned long long const To) APT_OVERRIDE
  1920. {
  1921. if (buffer.size() != 0)
  1922. {
  1923. unsigned long long const seekpos = lseek(filefd->iFd, 0, SEEK_CUR);
  1924. if ((seekpos - buffer.size()) >= To)
  1925. buffer.reset();
  1926. else if (seekpos >= To)
  1927. buffer.bufferend = (To - seekpos) + buffer.bufferstart;
  1928. else
  1929. buffer.reset();
  1930. }
  1931. if (ftruncate(filefd->iFd, To) != 0)
  1932. return filefd->FileFdError("Unable to truncate to %llu",To);
  1933. return true;
  1934. }
  1935. virtual unsigned long long InternalTell() APT_OVERRIDE
  1936. {
  1937. return lseek(filefd->iFd,0,SEEK_CUR) - buffer.size();
  1938. }
  1939. virtual unsigned long long InternalSize() APT_OVERRIDE
  1940. {
  1941. return filefd->FileSize();
  1942. }
  1943. virtual bool InternalClose(std::string const &) APT_OVERRIDE { return true; }
  1944. virtual bool InternalAlwaysAutoClose() const APT_OVERRIDE { return false; }
  1945. explicit DirectFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
  1946. virtual ~DirectFileFdPrivate() { InternalClose(""); }
  1947. };
  1948. /*}}}*/
  1949. // FileFd Constructors /*{{{*/
  1950. FileFd::FileFd(std::string FileName,unsigned int const Mode,unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  1951. {
  1952. Open(FileName,Mode, None, AccessMode);
  1953. }
  1954. FileFd::FileFd(std::string FileName,unsigned int const Mode, CompressMode Compress, unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  1955. {
  1956. Open(FileName,Mode, Compress, AccessMode);
  1957. }
  1958. FileFd::FileFd() : iFd(-1), Flags(AutoClose), d(NULL) {}
  1959. FileFd::FileFd(int const Fd, unsigned int const Mode, CompressMode Compress) : iFd(-1), Flags(0), d(NULL)
  1960. {
  1961. OpenDescriptor(Fd, Mode, Compress);
  1962. }
  1963. FileFd::FileFd(int const Fd, bool const AutoClose) : iFd(-1), Flags(0), d(NULL)
  1964. {
  1965. OpenDescriptor(Fd, ReadWrite, None, AutoClose);
  1966. }
  1967. /*}}}*/
  1968. // FileFd::Open - Open a file /*{{{*/
  1969. // ---------------------------------------------------------------------
  1970. /* The most commonly used open mode combinations are given with Mode */
  1971. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
  1972. {
  1973. if (Mode == ReadOnlyGzip)
  1974. return Open(FileName, ReadOnly, Gzip, AccessMode);
  1975. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  1976. return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  1977. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  1978. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  1979. if (Compress == Auto)
  1980. {
  1981. for (; compressor != compressors.end(); ++compressor)
  1982. {
  1983. std::string file = FileName + compressor->Extension;
  1984. if (FileExists(file) == false)
  1985. continue;
  1986. FileName = file;
  1987. break;
  1988. }
  1989. }
  1990. else if (Compress == Extension)
  1991. {
  1992. std::string::size_type const found = FileName.find_last_of('.');
  1993. std::string ext;
  1994. if (found != std::string::npos)
  1995. {
  1996. ext = FileName.substr(found);
  1997. if (ext == ".new" || ext == ".bak")
  1998. {
  1999. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  2000. if (found2 != std::string::npos)
  2001. ext = FileName.substr(found2, found - found2);
  2002. else
  2003. ext.clear();
  2004. }
  2005. }
  2006. for (; compressor != compressors.end(); ++compressor)
  2007. if (ext == compressor->Extension)
  2008. break;
  2009. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  2010. if (compressor == compressors.end())
  2011. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  2012. if (compressor->Name == ".")
  2013. break;
  2014. }
  2015. else
  2016. {
  2017. std::string name;
  2018. switch (Compress)
  2019. {
  2020. case None: name = "."; break;
  2021. case Gzip: name = "gzip"; break;
  2022. case Bzip2: name = "bzip2"; break;
  2023. case Lzma: name = "lzma"; break;
  2024. case Xz: name = "xz"; break;
  2025. case Lz4: name = "lz4"; break;
  2026. case Auto:
  2027. case Extension:
  2028. // Unreachable
  2029. return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  2030. }
  2031. for (; compressor != compressors.end(); ++compressor)
  2032. if (compressor->Name == name)
  2033. break;
  2034. if (compressor == compressors.end())
  2035. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  2036. }
  2037. if (compressor == compressors.end())
  2038. return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  2039. return Open(FileName, Mode, *compressor, AccessMode);
  2040. }
  2041. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
  2042. {
  2043. Close();
  2044. Flags = AutoClose;
  2045. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  2046. return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  2047. if ((Mode & ReadWrite) == 0)
  2048. return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
  2049. unsigned int OpenMode = Mode;
  2050. if (FileName == "/dev/null")
  2051. OpenMode = OpenMode & ~(Atomic | Exclusive | Create | Empty);
  2052. if ((OpenMode & Atomic) == Atomic)
  2053. {
  2054. Flags |= Replace;
  2055. }
  2056. else if ((OpenMode & (Exclusive | Create)) == (Exclusive | Create))
  2057. {
  2058. // for atomic, this will be done by rename in Close()
  2059. RemoveFile("FileFd::Open", FileName);
  2060. }
  2061. if ((OpenMode & Empty) == Empty)
  2062. {
  2063. struct stat Buf;
  2064. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  2065. RemoveFile("FileFd::Open", FileName);
  2066. }
  2067. int fileflags = 0;
  2068. #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
  2069. if_FLAGGED_SET(ReadWrite, O_RDWR);
  2070. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  2071. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  2072. if_FLAGGED_SET(Create, O_CREAT);
  2073. if_FLAGGED_SET(Empty, O_TRUNC);
  2074. if_FLAGGED_SET(Exclusive, O_EXCL);
  2075. #undef if_FLAGGED_SET
  2076. if ((OpenMode & Atomic) == Atomic)
  2077. {
  2078. char *name = strdup((FileName + ".XXXXXX").c_str());
  2079. if((iFd = mkstemp(name)) == -1)
  2080. {
  2081. free(name);
  2082. return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
  2083. }
  2084. TemporaryFileName = string(name);
  2085. free(name);
  2086. // umask() will always set the umask and return the previous value, so
  2087. // we first set the umask and then reset it to the old value
  2088. mode_t const CurrentUmask = umask(0);
  2089. umask(CurrentUmask);
  2090. // calculate the actual file permissions (just like open/creat)
  2091. mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
  2092. if(fchmod(iFd, FilePermissions) == -1)
  2093. return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
  2094. }
  2095. else
  2096. iFd = open(FileName.c_str(), fileflags, AccessMode);
  2097. this->FileName = FileName;
  2098. if (iFd == -1 || OpenInternDescriptor(OpenMode, compressor) == false)
  2099. {
  2100. if (iFd != -1)
  2101. {
  2102. close (iFd);
  2103. iFd = -1;
  2104. }
  2105. return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
  2106. }
  2107. SetCloseExec(iFd,true);
  2108. return true;
  2109. }
  2110. /*}}}*/
  2111. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  2112. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  2113. {
  2114. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  2115. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  2116. std::string name;
  2117. // compat with the old API
  2118. if (Mode == ReadOnlyGzip && Compress == None)
  2119. Compress = Gzip;
  2120. switch (Compress)
  2121. {
  2122. case None: name = "."; break;
  2123. case Gzip: name = "gzip"; break;
  2124. case Bzip2: name = "bzip2"; break;
  2125. case Lzma: name = "lzma"; break;
  2126. case Xz: name = "xz"; break;
  2127. case Lz4: name = "lz4"; break;
  2128. case Auto:
  2129. case Extension:
  2130. if (AutoClose == true && Fd != -1)
  2131. close(Fd);
  2132. return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  2133. }
  2134. for (; compressor != compressors.end(); ++compressor)
  2135. if (compressor->Name == name)
  2136. break;
  2137. if (compressor == compressors.end())
  2138. {
  2139. if (AutoClose == true && Fd != -1)
  2140. close(Fd);
  2141. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  2142. }
  2143. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  2144. }
  2145. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  2146. {
  2147. Close();
  2148. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  2149. iFd = Fd;
  2150. this->FileName = "";
  2151. if (OpenInternDescriptor(Mode, compressor) == false)
  2152. {
  2153. if (iFd != -1 && (
  2154. (Flags & Compressed) == Compressed ||
  2155. AutoClose == true))
  2156. {
  2157. close (iFd);
  2158. iFd = -1;
  2159. }
  2160. return FileFdError(_("Could not open file descriptor %d"), Fd);
  2161. }
  2162. return true;
  2163. }
  2164. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  2165. {
  2166. if (iFd == -1)
  2167. return false;
  2168. if (d != nullptr)
  2169. d->InternalClose(FileName);
  2170. if (d == nullptr)
  2171. {
  2172. if (false)
  2173. /* dummy so that the rest can be 'else if's */;
  2174. #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
  2175. else if (compressor.Name == NAME) \
  2176. d = new CONSTRUCTOR(this)
  2177. #ifdef HAVE_ZLIB
  2178. APT_COMPRESS_INIT("gzip", GzipFileFdPrivate);
  2179. #endif
  2180. #ifdef HAVE_BZ2
  2181. APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate);
  2182. #endif
  2183. #ifdef HAVE_LZMA
  2184. APT_COMPRESS_INIT("xz", LzmaFileFdPrivate);
  2185. APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate);
  2186. #endif
  2187. #ifdef HAVE_LZ4
  2188. APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate);
  2189. #endif
  2190. #undef APT_COMPRESS_INIT
  2191. else if (compressor.Name == "." || compressor.Binary.empty() == true)
  2192. d = new DirectFileFdPrivate(this);
  2193. else
  2194. d = new PipedFileFdPrivate(this);
  2195. if (Mode & BufferedWrite)
  2196. d = new BufferedWriteFileFdPrivate(d);
  2197. d->set_openmode(Mode);
  2198. d->set_compressor(compressor);
  2199. if ((Flags & AutoClose) != AutoClose && d->InternalAlwaysAutoClose())
  2200. {
  2201. // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
  2202. int const internFd = dup(iFd);
  2203. if (internFd == -1)
  2204. return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
  2205. iFd = internFd;
  2206. }
  2207. }
  2208. return d->InternalOpen(iFd, Mode);
  2209. }
  2210. /*}}}*/
  2211. // FileFd::~File - Closes the file /*{{{*/
  2212. // ---------------------------------------------------------------------
  2213. /* If the proper modes are selected then we close the Fd and possibly
  2214. unlink the file on error. */
  2215. FileFd::~FileFd()
  2216. {
  2217. Close();
  2218. if (d != NULL)
  2219. d->InternalClose(FileName);
  2220. delete d;
  2221. d = NULL;
  2222. }
  2223. /*}}}*/
  2224. // FileFd::Read - Read a bit of the file /*{{{*/
  2225. // ---------------------------------------------------------------------
  2226. /* We are careful to handle interruption by a signal while reading
  2227. gracefully. */
  2228. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  2229. {
  2230. if (d == nullptr || Failed())
  2231. return false;
  2232. ssize_t Res = 1;
  2233. errno = 0;
  2234. if (Actual != 0)
  2235. *Actual = 0;
  2236. *((char *)To) = '\0';
  2237. while (Res > 0 && Size > 0)
  2238. {
  2239. Res = d->InternalRead(To, Size);
  2240. if (Res < 0)
  2241. {
  2242. if (errno == EINTR)
  2243. {
  2244. // trick the while-loop into running again
  2245. Res = 1;
  2246. errno = 0;
  2247. continue;
  2248. }
  2249. return d->InternalReadError();
  2250. }
  2251. To = (char *)To + Res;
  2252. Size -= Res;
  2253. if (d != NULL)
  2254. d->set_seekpos(d->get_seekpos() + Res);
  2255. if (Actual != 0)
  2256. *Actual += Res;
  2257. }
  2258. if (Size == 0)
  2259. return true;
  2260. // Eof handling
  2261. if (Actual != 0)
  2262. {
  2263. Flags |= HitEof;
  2264. return true;
  2265. }
  2266. return FileFdError(_("read, still have %llu to read but none left"), Size);
  2267. }
  2268. bool FileFd::Read(int const Fd, void *To, unsigned long long Size, unsigned long long * const Actual)
  2269. {
  2270. ssize_t Res = 1;
  2271. errno = 0;
  2272. if (Actual != nullptr)
  2273. *Actual = 0;
  2274. *static_cast<char *>(To) = '\0';
  2275. while (Res > 0 && Size > 0)
  2276. {
  2277. Res = read(Fd, To, Size);
  2278. if (Res < 0)
  2279. {
  2280. if (errno == EINTR)
  2281. {
  2282. Res = 1;
  2283. errno = 0;
  2284. continue;
  2285. }
  2286. return _error->Errno("read", _("Read error"));
  2287. }
  2288. To = static_cast<char *>(To) + Res;
  2289. Size -= Res;
  2290. if (Actual != 0)
  2291. *Actual += Res;
  2292. }
  2293. if (Size == 0)
  2294. return true;
  2295. if (Actual != nullptr)
  2296. return true;
  2297. return _error->Error(_("read, still have %llu to read but none left"), Size);
  2298. }
  2299. /*}}}*/
  2300. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  2301. // ---------------------------------------------------------------------
  2302. /* Beware: This method can be quite slow for big buffers on UNcompressed
  2303. files because of the naive implementation! */
  2304. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  2305. {
  2306. *To = '\0';
  2307. if (d == nullptr || Failed())
  2308. return nullptr;
  2309. return d->InternalReadLine(To, Size);
  2310. }
  2311. /*}}}*/
  2312. // FileFd::Flush - Flush the file /*{{{*/
  2313. bool FileFd::Flush()
  2314. {
  2315. if (Failed())
  2316. return false;
  2317. if (d == nullptr)
  2318. return true;
  2319. return d->InternalFlush();
  2320. }
  2321. /*}}}*/
  2322. // FileFd::Write - Write to the file /*{{{*/
  2323. bool FileFd::Write(const void *From,unsigned long long Size)
  2324. {
  2325. if (d == nullptr || Failed())
  2326. return false;
  2327. ssize_t Res = 1;
  2328. errno = 0;
  2329. while (Res > 0 && Size > 0)
  2330. {
  2331. Res = d->InternalWrite(From, Size);
  2332. if (Res < 0)
  2333. {
  2334. if (errno == EINTR)
  2335. {
  2336. // trick the while-loop into running again
  2337. Res = 1;
  2338. errno = 0;
  2339. continue;
  2340. }
  2341. return d->InternalWriteError();
  2342. }
  2343. From = (char const *)From + Res;
  2344. Size -= Res;
  2345. if (d != NULL)
  2346. d->set_seekpos(d->get_seekpos() + Res);
  2347. }
  2348. if (Size == 0)
  2349. return true;
  2350. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  2351. }
  2352. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  2353. {
  2354. ssize_t Res = 1;
  2355. errno = 0;
  2356. while (Res > 0 && Size > 0)
  2357. {
  2358. Res = write(Fd,From,Size);
  2359. if (Res < 0 && errno == EINTR)
  2360. continue;
  2361. if (Res < 0)
  2362. return _error->Errno("write",_("Write error"));
  2363. From = (char const *)From + Res;
  2364. Size -= Res;
  2365. }
  2366. if (Size == 0)
  2367. return true;
  2368. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  2369. }
  2370. /*}}}*/
  2371. // FileFd::Seek - Seek in the file /*{{{*/
  2372. bool FileFd::Seek(unsigned long long To)
  2373. {
  2374. if (d == nullptr || Failed())
  2375. return false;
  2376. Flags &= ~HitEof;
  2377. return d->InternalSeek(To);
  2378. }
  2379. /*}}}*/
  2380. // FileFd::Skip - Skip over data in the file /*{{{*/
  2381. bool FileFd::Skip(unsigned long long Over)
  2382. {
  2383. if (d == nullptr || Failed())
  2384. return false;
  2385. return d->InternalSkip(Over);
  2386. }
  2387. /*}}}*/
  2388. // FileFd::Truncate - Truncate the file /*{{{*/
  2389. bool FileFd::Truncate(unsigned long long To)
  2390. {
  2391. if (d == nullptr || Failed())
  2392. return false;
  2393. // truncating /dev/null is always successful - as we get an error otherwise
  2394. if (To == 0 && FileName == "/dev/null")
  2395. return true;
  2396. return d->InternalTruncate(To);
  2397. }
  2398. /*}}}*/
  2399. // FileFd::Tell - Current seek position /*{{{*/
  2400. // ---------------------------------------------------------------------
  2401. /* */
  2402. unsigned long long FileFd::Tell()
  2403. {
  2404. if (d == nullptr || Failed())
  2405. return false;
  2406. off_t const Res = d->InternalTell();
  2407. if (Res == (off_t)-1)
  2408. FileFdErrno("lseek","Failed to determine the current file position");
  2409. d->set_seekpos(Res);
  2410. return Res;
  2411. }
  2412. /*}}}*/
  2413. static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
  2414. {
  2415. bool ispipe = (d != NULL && d->get_is_pipe() == true);
  2416. if (ispipe == false)
  2417. {
  2418. if (fstat(iFd,&Buf) != 0)
  2419. // higher-level code will generate more meaningful messages,
  2420. // even translated this would be meaningless for users
  2421. return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
  2422. if (FileName.empty() == false)
  2423. ispipe = S_ISFIFO(Buf.st_mode);
  2424. }
  2425. // for compressor pipes st_size is undefined and at 'best' zero
  2426. if (ispipe == true)
  2427. {
  2428. // we set it here, too, as we get the info here for free
  2429. // in theory the Open-methods should take care of it already
  2430. if (d != NULL)
  2431. d->set_is_pipe(true);
  2432. if (stat(FileName.c_str(), &Buf) != 0)
  2433. return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
  2434. }
  2435. return true;
  2436. }
  2437. /*}}}*/
  2438. // FileFd::FileSize - Return the size of the file /*{{{*/
  2439. unsigned long long FileFd::FileSize()
  2440. {
  2441. struct stat Buf;
  2442. if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
  2443. {
  2444. Flags |= Fail;
  2445. return 0;
  2446. }
  2447. return Buf.st_size;
  2448. }
  2449. /*}}}*/
  2450. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  2451. time_t FileFd::ModificationTime()
  2452. {
  2453. struct stat Buf;
  2454. if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
  2455. {
  2456. Flags |= Fail;
  2457. return 0;
  2458. }
  2459. return Buf.st_mtime;
  2460. }
  2461. /*}}}*/
  2462. // FileFd::Size - Return the size of the content in the file /*{{{*/
  2463. unsigned long long FileFd::Size()
  2464. {
  2465. if (d == nullptr)
  2466. return 0;
  2467. return d->InternalSize();
  2468. }
  2469. /*}}}*/
  2470. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  2471. // ---------------------------------------------------------------------
  2472. /* */
  2473. bool FileFd::Close()
  2474. {
  2475. if (Failed() == false && Flush() == false)
  2476. return false;
  2477. if (iFd == -1)
  2478. return true;
  2479. bool Res = true;
  2480. if ((Flags & AutoClose) == AutoClose)
  2481. {
  2482. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  2483. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  2484. }
  2485. if (d != NULL)
  2486. {
  2487. Res &= d->InternalClose(FileName);
  2488. delete d;
  2489. d = NULL;
  2490. }
  2491. if ((Flags & Replace) == Replace) {
  2492. if (Failed() == false && rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  2493. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  2494. FileName = TemporaryFileName; // for the unlink() below.
  2495. TemporaryFileName.clear();
  2496. }
  2497. iFd = -1;
  2498. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  2499. FileName.empty() == false)
  2500. Res &= RemoveFile("FileFd::Close", FileName);
  2501. if (Res == false)
  2502. Flags |= Fail;
  2503. return Res;
  2504. }
  2505. /*}}}*/
  2506. // FileFd::Sync - Sync the file /*{{{*/
  2507. // ---------------------------------------------------------------------
  2508. /* */
  2509. bool FileFd::Sync()
  2510. {
  2511. if (fsync(iFd) != 0)
  2512. return FileFdErrno("sync",_("Problem syncing the file"));
  2513. return true;
  2514. }
  2515. /*}}}*/
  2516. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  2517. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  2518. {
  2519. Flags |= Fail;
  2520. va_list args;
  2521. size_t msgSize = 400;
  2522. int const errsv = errno;
  2523. bool retry;
  2524. do {
  2525. va_start(args,Description);
  2526. retry = _error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize);
  2527. va_end(args);
  2528. } while (retry);
  2529. return false;
  2530. }
  2531. /*}}}*/
  2532. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  2533. bool FileFd::FileFdError(const char *Description,...) {
  2534. Flags |= Fail;
  2535. va_list args;
  2536. size_t msgSize = 400;
  2537. bool retry;
  2538. do {
  2539. va_start(args,Description);
  2540. retry = _error->Insert(GlobalError::ERROR, Description, args, msgSize);
  2541. va_end(args);
  2542. } while (retry);
  2543. return false;
  2544. }
  2545. /*}}}*/
  2546. gzFile FileFd::gzFd() { /*{{{*/
  2547. #ifdef HAVE_ZLIB
  2548. GzipFileFdPrivate * const gzipd = dynamic_cast<GzipFileFdPrivate*>(d);
  2549. if (gzipd == nullptr)
  2550. return nullptr;
  2551. else
  2552. return gzipd->gz;
  2553. #else
  2554. return nullptr;
  2555. #endif
  2556. }
  2557. /*}}}*/
  2558. // Glob - wrapper around "glob()" /*{{{*/
  2559. std::vector<std::string> Glob(std::string const &pattern, int flags)
  2560. {
  2561. std::vector<std::string> result;
  2562. glob_t globbuf;
  2563. int glob_res;
  2564. unsigned int i;
  2565. glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
  2566. if (glob_res != 0)
  2567. {
  2568. if(glob_res != GLOB_NOMATCH) {
  2569. _error->Errno("glob", "Problem with glob");
  2570. return result;
  2571. }
  2572. }
  2573. // append results
  2574. for(i=0;i<globbuf.gl_pathc;i++)
  2575. result.push_back(string(globbuf.gl_pathv[i]));
  2576. globfree(&globbuf);
  2577. return result;
  2578. }
  2579. /*}}}*/
  2580. std::string GetTempDir() /*{{{*/
  2581. {
  2582. const char *tmpdir = getenv("TMPDIR");
  2583. #ifdef P_tmpdir
  2584. if (!tmpdir)
  2585. tmpdir = P_tmpdir;
  2586. #endif
  2587. struct stat st;
  2588. if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set
  2589. stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0) // exists and is directory
  2590. tmpdir = "/tmp";
  2591. else if (geteuid() != 0 && // root can do everything anyway
  2592. faccessat(-1, tmpdir, R_OK | W_OK | X_OK, AT_EACCESS | AT_SYMLINK_NOFOLLOW) != 0) // current user has rwx access to directory
  2593. tmpdir = "/tmp";
  2594. return string(tmpdir);
  2595. }
  2596. std::string GetTempDir(std::string const &User)
  2597. {
  2598. // no need/possibility to drop privs
  2599. if(getuid() != 0 || User.empty() || User == "root")
  2600. return GetTempDir();
  2601. struct passwd const * const pw = getpwnam(User.c_str());
  2602. if (pw == NULL)
  2603. return GetTempDir();
  2604. gid_t const old_euid = geteuid();
  2605. gid_t const old_egid = getegid();
  2606. if (setegid(pw->pw_gid) != 0)
  2607. _error->Errno("setegid", "setegid %u failed", pw->pw_gid);
  2608. if (seteuid(pw->pw_uid) != 0)
  2609. _error->Errno("seteuid", "seteuid %u failed", pw->pw_uid);
  2610. std::string const tmp = GetTempDir();
  2611. if (seteuid(old_euid) != 0)
  2612. _error->Errno("seteuid", "seteuid %u failed", old_euid);
  2613. if (setegid(old_egid) != 0)
  2614. _error->Errno("setegid", "setegid %u failed", old_egid);
  2615. return tmp;
  2616. }
  2617. /*}}}*/
  2618. FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink, FileFd * const TmpFd) /*{{{*/
  2619. {
  2620. char fn[512];
  2621. FileFd * const Fd = TmpFd == NULL ? new FileFd() : TmpFd;
  2622. std::string const tempdir = GetTempDir();
  2623. snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
  2624. tempdir.c_str(), Prefix.c_str());
  2625. int const fd = mkstemp(fn);
  2626. if(ImmediateUnlink)
  2627. unlink(fn);
  2628. if (fd < 0)
  2629. {
  2630. _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
  2631. return NULL;
  2632. }
  2633. if (!Fd->OpenDescriptor(fd, FileFd::ReadWrite, FileFd::None, true))
  2634. {
  2635. _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
  2636. return NULL;
  2637. }
  2638. return Fd;
  2639. }
  2640. /*}}}*/
  2641. bool Rename(std::string From, std::string To) /*{{{*/
  2642. {
  2643. if (rename(From.c_str(),To.c_str()) != 0)
  2644. {
  2645. _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
  2646. From.c_str(),To.c_str());
  2647. return false;
  2648. }
  2649. return true;
  2650. }
  2651. /*}}}*/
  2652. bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
  2653. {
  2654. return Popen(Args, Fd, Child, Mode, true);
  2655. }
  2656. /*}}}*/
  2657. bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode, bool CaptureStderr)/*{{{*/
  2658. {
  2659. int fd;
  2660. if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
  2661. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  2662. int Pipe[2] = {-1, -1};
  2663. if(pipe(Pipe) != 0)
  2664. return _error->Errno("pipe", _("Failed to create subprocess IPC"));
  2665. std::set<int> keep_fds;
  2666. keep_fds.insert(Pipe[0]);
  2667. keep_fds.insert(Pipe[1]);
  2668. Child = ExecFork(keep_fds);
  2669. if(Child < 0)
  2670. return _error->Errno("fork", "Failed to fork");
  2671. if(Child == 0)
  2672. {
  2673. if(Mode == FileFd::ReadOnly)
  2674. {
  2675. close(Pipe[0]);
  2676. fd = Pipe[1];
  2677. }
  2678. else if(Mode == FileFd::WriteOnly)
  2679. {
  2680. close(Pipe[1]);
  2681. fd = Pipe[0];
  2682. }
  2683. if(Mode == FileFd::ReadOnly)
  2684. {
  2685. dup2(fd, 1);
  2686. if (CaptureStderr == true)
  2687. dup2(fd, 2);
  2688. } else if(Mode == FileFd::WriteOnly)
  2689. dup2(fd, 0);
  2690. execv(Args[0], (char**)Args);
  2691. _exit(100);
  2692. }
  2693. if(Mode == FileFd::ReadOnly)
  2694. {
  2695. close(Pipe[1]);
  2696. fd = Pipe[0];
  2697. }
  2698. else if(Mode == FileFd::WriteOnly)
  2699. {
  2700. close(Pipe[0]);
  2701. fd = Pipe[1];
  2702. }
  2703. else
  2704. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  2705. Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
  2706. return true;
  2707. }
  2708. /*}}}*/
  2709. bool DropPrivileges() /*{{{*/
  2710. {
  2711. if(_config->FindB("Debug::NoDropPrivs", false) == true)
  2712. return true;
  2713. #if __gnu_linux__
  2714. #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
  2715. #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
  2716. #endif
  2717. // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
  2718. int ret = prctl(38, 1, 0, 0, 0);
  2719. // ignore EINVAL - kernel is too old to understand the option
  2720. if(ret < 0 && errno != EINVAL)
  2721. _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
  2722. #endif
  2723. // empty setting disables privilege dropping - this also ensures
  2724. // backward compatibility, see bug #764506
  2725. const std::string toUser = _config->Find("APT::Sandbox::User");
  2726. if (toUser.empty() || toUser == "root")
  2727. return true;
  2728. // a lot can go wrong trying to drop privileges completely,
  2729. // so ideally we would like to verify that we have done it –
  2730. // but the verify asks for too much in case of fakeroot (and alike)
  2731. // [Specific checks can be overridden with dedicated options]
  2732. bool const VerifySandboxing = _config->FindB("APT::Sandbox::Verify", false);
  2733. // uid will be 0 in the end, but gid might be different anyway
  2734. uid_t const old_uid = getuid();
  2735. gid_t const old_gid = getgid();
  2736. if (old_uid != 0)
  2737. return true;
  2738. struct passwd *pw = getpwnam(toUser.c_str());
  2739. if (pw == NULL)
  2740. return _error->Error("No user %s, can not drop rights", toUser.c_str());
  2741. // Do not change the order here, it might break things
  2742. // Get rid of all our supplementary groups first
  2743. if (setgroups(1, &pw->pw_gid))
  2744. return _error->Errno("setgroups", "Failed to setgroups");
  2745. // Now change the group ids to the new user
  2746. #ifdef HAVE_SETRESGID
  2747. if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
  2748. return _error->Errno("setresgid", "Failed to set new group ids");
  2749. #else
  2750. if (setegid(pw->pw_gid) != 0)
  2751. return _error->Errno("setegid", "Failed to setegid");
  2752. if (setgid(pw->pw_gid) != 0)
  2753. return _error->Errno("setgid", "Failed to setgid");
  2754. #endif
  2755. // Change the user ids to the new user
  2756. #ifdef HAVE_SETRESUID
  2757. if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
  2758. return _error->Errno("setresuid", "Failed to set new user ids");
  2759. #else
  2760. if (setuid(pw->pw_uid) != 0)
  2761. return _error->Errno("setuid", "Failed to setuid");
  2762. if (seteuid(pw->pw_uid) != 0)
  2763. return _error->Errno("seteuid", "Failed to seteuid");
  2764. #endif
  2765. // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
  2766. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Groups", false) == true)
  2767. {
  2768. // Verify that the user isn't still in any supplementary groups
  2769. long const ngroups_max = sysconf(_SC_NGROUPS_MAX);
  2770. std::unique_ptr<gid_t[]> gidlist(new gid_t[ngroups_max]);
  2771. if (unlikely(gidlist == NULL))
  2772. return _error->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max);
  2773. ssize_t gidlist_nr;
  2774. if ((gidlist_nr = getgroups(ngroups_max, gidlist.get())) < 0)
  2775. return _error->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max);
  2776. for (ssize_t i = 0; i < gidlist_nr; ++i)
  2777. if (gidlist[i] != pw->pw_gid)
  2778. return _error->Error("Could not switch group, user %s is still in group %d", toUser.c_str(), gidlist[i]);
  2779. }
  2780. // enabled by default as all fakeroot-lookalikes should fake that accordingly
  2781. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::IDs", true) == true)
  2782. {
  2783. // Verify that gid, egid, uid, and euid changed
  2784. if (getgid() != pw->pw_gid)
  2785. return _error->Error("Could not switch group");
  2786. if (getegid() != pw->pw_gid)
  2787. return _error->Error("Could not switch effective group");
  2788. if (getuid() != pw->pw_uid)
  2789. return _error->Error("Could not switch user");
  2790. if (geteuid() != pw->pw_uid)
  2791. return _error->Error("Could not switch effective user");
  2792. #ifdef HAVE_GETRESUID
  2793. // verify that the saved set-user-id was changed as well
  2794. uid_t ruid = 0;
  2795. uid_t euid = 0;
  2796. uid_t suid = 0;
  2797. if (getresuid(&ruid, &euid, &suid))
  2798. return _error->Errno("getresuid", "Could not get saved set-user-ID");
  2799. if (suid != pw->pw_uid)
  2800. return _error->Error("Could not switch saved set-user-ID");
  2801. #endif
  2802. #ifdef HAVE_GETRESGID
  2803. // verify that the saved set-group-id was changed as well
  2804. gid_t rgid = 0;
  2805. gid_t egid = 0;
  2806. gid_t sgid = 0;
  2807. if (getresgid(&rgid, &egid, &sgid))
  2808. return _error->Errno("getresuid", "Could not get saved set-group-ID");
  2809. if (sgid != pw->pw_gid)
  2810. return _error->Error("Could not switch saved set-group-ID");
  2811. #endif
  2812. }
  2813. // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
  2814. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Regain", false) == true)
  2815. {
  2816. // Check that uid and gid changes do not work anymore
  2817. if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
  2818. return _error->Error("Could restore a gid to root, privilege dropping did not work");
  2819. if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
  2820. return _error->Error("Could restore a uid to root, privilege dropping did not work");
  2821. }
  2822. if (_config->FindB("APT::Sandbox::ResetEnvironment", true))
  2823. {
  2824. setenv("HOME", pw->pw_dir, 1);
  2825. setenv("USER", pw->pw_name, 1);
  2826. setenv("USERNAME", pw->pw_name, 1);
  2827. setenv("LOGNAME", pw->pw_name, 1);
  2828. auto const shell = flNotDir(pw->pw_shell);
  2829. if (shell == "false" || shell == "nologin")
  2830. setenv("SHELL", "/bin/sh", 1);
  2831. else
  2832. setenv("SHELL", pw->pw_shell, 1);
  2833. auto const tmpdir = getenv("TMPDIR");
  2834. if (tmpdir != nullptr)
  2835. {
  2836. auto const ourtmpdir = GetTempDir();
  2837. if (ourtmpdir != tmpdir)
  2838. setenv("TMPDIR", ourtmpdir.c_str(), 1);
  2839. }
  2840. }
  2841. return true;
  2842. }
  2843. /*}}}*/