fileutl.cc 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  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. // SetCloseExec - Set the close on exec flag /*{{{*/
  629. // ---------------------------------------------------------------------
  630. /* */
  631. void SetCloseExec(int Fd,bool Close)
  632. {
  633. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  634. {
  635. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  636. exit(100);
  637. }
  638. }
  639. /*}}}*/
  640. // SetNonBlock - Set the nonblocking flag /*{{{*/
  641. // ---------------------------------------------------------------------
  642. /* */
  643. void SetNonBlock(int Fd,bool Block)
  644. {
  645. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  646. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  647. {
  648. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  649. exit(100);
  650. }
  651. }
  652. /*}}}*/
  653. // WaitFd - Wait for a FD to become readable /*{{{*/
  654. // ---------------------------------------------------------------------
  655. /* This waits for a FD to become readable using select. It is useful for
  656. applications making use of non-blocking sockets. The timeout is
  657. in seconds. */
  658. bool WaitFd(int Fd,bool write,unsigned long timeout)
  659. {
  660. fd_set Set;
  661. struct timeval tv;
  662. FD_ZERO(&Set);
  663. FD_SET(Fd,&Set);
  664. tv.tv_sec = timeout;
  665. tv.tv_usec = 0;
  666. if (write == true)
  667. {
  668. int Res;
  669. do
  670. {
  671. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  672. }
  673. while (Res < 0 && errno == EINTR);
  674. if (Res <= 0)
  675. return false;
  676. }
  677. else
  678. {
  679. int Res;
  680. do
  681. {
  682. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  683. }
  684. while (Res < 0 && errno == EINTR);
  685. if (Res <= 0)
  686. return false;
  687. }
  688. return true;
  689. }
  690. /*}}}*/
  691. // MergeKeepFdsFromConfiguration - Merge APT::Keep-Fds configuration /*{{{*/
  692. // ---------------------------------------------------------------------
  693. /* This is used to merge the APT::Keep-Fds with the provided KeepFDs
  694. * set.
  695. */
  696. void MergeKeepFdsFromConfiguration(std::set<int> &KeepFDs)
  697. {
  698. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  699. if (Opts != 0 && Opts->Child != 0)
  700. {
  701. Opts = Opts->Child;
  702. for (; Opts != 0; Opts = Opts->Next)
  703. {
  704. if (Opts->Value.empty() == true)
  705. continue;
  706. int fd = atoi(Opts->Value.c_str());
  707. KeepFDs.insert(fd);
  708. }
  709. }
  710. }
  711. /*}}}*/
  712. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  713. // ---------------------------------------------------------------------
  714. /* This is used if you want to cleanse the environment for the forked
  715. child, it fixes up the important signals and nukes all of the fds,
  716. otherwise acts like normal fork. */
  717. pid_t ExecFork()
  718. {
  719. set<int> KeepFDs;
  720. // we need to merge the Keep-Fds as external tools like
  721. // debconf-apt-progress use it
  722. MergeKeepFdsFromConfiguration(KeepFDs);
  723. return ExecFork(KeepFDs);
  724. }
  725. pid_t ExecFork(std::set<int> KeepFDs)
  726. {
  727. // Fork off the process
  728. pid_t Process = fork();
  729. if (Process < 0)
  730. {
  731. cerr << "FATAL -> Failed to fork." << endl;
  732. exit(100);
  733. }
  734. // Spawn the subprocess
  735. if (Process == 0)
  736. {
  737. // Setup the signals
  738. signal(SIGPIPE,SIG_DFL);
  739. signal(SIGQUIT,SIG_DFL);
  740. signal(SIGINT,SIG_DFL);
  741. signal(SIGWINCH,SIG_DFL);
  742. signal(SIGCONT,SIG_DFL);
  743. signal(SIGTSTP,SIG_DFL);
  744. DIR *dir = opendir("/proc/self/fd");
  745. if (dir != NULL)
  746. {
  747. struct dirent *ent;
  748. while ((ent = readdir(dir)))
  749. {
  750. int fd = atoi(ent->d_name);
  751. // If fd > 0, it was a fd number and not . or ..
  752. if (fd >= 3 && KeepFDs.find(fd) == KeepFDs.end())
  753. fcntl(fd,F_SETFD,FD_CLOEXEC);
  754. }
  755. closedir(dir);
  756. } else {
  757. long ScOpenMax = sysconf(_SC_OPEN_MAX);
  758. // Close all of our FDs - just in case
  759. for (int K = 3; K != ScOpenMax; K++)
  760. {
  761. if(KeepFDs.find(K) == KeepFDs.end())
  762. fcntl(K,F_SETFD,FD_CLOEXEC);
  763. }
  764. }
  765. }
  766. return Process;
  767. }
  768. /*}}}*/
  769. // ExecWait - Fancy waitpid /*{{{*/
  770. // ---------------------------------------------------------------------
  771. /* Waits for the given sub process. If Reap is set then no errors are
  772. generated. Otherwise a failed subprocess will generate a proper descriptive
  773. message */
  774. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  775. {
  776. if (Pid <= 1)
  777. return true;
  778. // Wait and collect the error code
  779. int Status;
  780. while (waitpid(Pid,&Status,0) != Pid)
  781. {
  782. if (errno == EINTR)
  783. continue;
  784. if (Reap == true)
  785. return false;
  786. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  787. }
  788. // Check for an error code.
  789. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  790. {
  791. if (Reap == true)
  792. return false;
  793. if (WIFSIGNALED(Status) != 0)
  794. {
  795. if( WTERMSIG(Status) == SIGSEGV)
  796. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  797. else
  798. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  799. }
  800. if (WIFEXITED(Status) != 0)
  801. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  802. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  803. }
  804. return true;
  805. }
  806. /*}}}*/
  807. // StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
  808. bool StartsWithGPGClearTextSignature(string const &FileName)
  809. {
  810. static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
  811. char buffer[strlen(SIGMSG)+1];
  812. FILE* gpg = fopen(FileName.c_str(), "r");
  813. if (gpg == NULL)
  814. return false;
  815. char const * const test = fgets(buffer, sizeof(buffer), gpg);
  816. fclose(gpg);
  817. if (test == NULL || strcmp(buffer, SIGMSG) != 0)
  818. return false;
  819. return true;
  820. }
  821. /*}}}*/
  822. // ChangeOwnerAndPermissionOfFile - set file attributes to requested values /*{{{*/
  823. bool ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
  824. {
  825. if (strcmp(file, "/dev/null") == 0)
  826. return true;
  827. bool Res = true;
  828. if (getuid() == 0 && strlen(user) != 0 && strlen(group) != 0) // if we aren't root, we can't chown, so don't try it
  829. {
  830. // ensure the file is owned by root and has good permissions
  831. struct passwd const * const pw = getpwnam(user);
  832. struct group const * const gr = getgrnam(group);
  833. if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
  834. Res &= _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
  835. }
  836. if (chmod(file, mode) != 0)
  837. Res &= _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
  838. return Res;
  839. }
  840. /*}}}*/
  841. struct APT_HIDDEN simple_buffer { /*{{{*/
  842. size_t buffersize_max = 0;
  843. unsigned long long bufferstart = 0;
  844. unsigned long long bufferend = 0;
  845. char *buffer = nullptr;
  846. simple_buffer() {
  847. reset(4096);
  848. }
  849. ~simple_buffer() {
  850. delete buffer;
  851. }
  852. const char *get() const { return buffer + bufferstart; }
  853. char *get() { return buffer + bufferstart; }
  854. const char *getend() const { return buffer + bufferend; }
  855. char *getend() { return buffer + bufferend; }
  856. bool empty() const { return bufferend <= bufferstart; }
  857. bool full() const { return bufferend == buffersize_max; }
  858. unsigned long long free() const { return buffersize_max - bufferend; }
  859. unsigned long long size() const { return bufferend-bufferstart; }
  860. void reset(size_t size)
  861. {
  862. if (size > buffersize_max) {
  863. delete[] buffer;
  864. buffersize_max = size;
  865. buffer = new char[size];
  866. }
  867. reset();
  868. }
  869. void reset() { bufferend = bufferstart = 0; }
  870. ssize_t read(void *to, unsigned long long requested_size) APT_MUSTCHECK
  871. {
  872. if (size() < requested_size)
  873. requested_size = size();
  874. memcpy(to, buffer + bufferstart, requested_size);
  875. bufferstart += requested_size;
  876. if (bufferstart == bufferend)
  877. bufferstart = bufferend = 0;
  878. return requested_size;
  879. }
  880. ssize_t write(const void *from, unsigned long long requested_size) APT_MUSTCHECK
  881. {
  882. if (buffersize_max - size() < requested_size)
  883. requested_size = buffersize_max - size();
  884. memcpy(buffer + bufferend, from, requested_size);
  885. bufferend += requested_size;
  886. if (bufferstart == bufferend)
  887. bufferstart = bufferend = 0;
  888. return requested_size;
  889. }
  890. };
  891. /*}}}*/
  892. class APT_HIDDEN FileFdPrivate { /*{{{*/
  893. friend class BufferedWriteFileFdPrivate;
  894. protected:
  895. FileFd * const filefd;
  896. simple_buffer buffer;
  897. int compressed_fd;
  898. pid_t compressor_pid;
  899. bool is_pipe;
  900. APT::Configuration::Compressor compressor;
  901. unsigned int openmode;
  902. unsigned long long seekpos;
  903. public:
  904. explicit FileFdPrivate(FileFd * const pfilefd) : filefd(pfilefd),
  905. compressed_fd(-1), compressor_pid(-1), is_pipe(false),
  906. openmode(0), seekpos(0) {};
  907. virtual APT::Configuration::Compressor get_compressor() const
  908. {
  909. return compressor;
  910. }
  911. virtual void set_compressor(APT::Configuration::Compressor const &compressor)
  912. {
  913. this->compressor = compressor;
  914. }
  915. virtual unsigned int get_openmode() const
  916. {
  917. return openmode;
  918. }
  919. virtual void set_openmode(unsigned int openmode)
  920. {
  921. this->openmode = openmode;
  922. }
  923. virtual bool get_is_pipe() const
  924. {
  925. return is_pipe;
  926. }
  927. virtual void set_is_pipe(bool is_pipe)
  928. {
  929. this->is_pipe = is_pipe;
  930. }
  931. virtual unsigned long long get_seekpos() const
  932. {
  933. return seekpos;
  934. }
  935. virtual void set_seekpos(unsigned long long seekpos)
  936. {
  937. this->seekpos = seekpos;
  938. }
  939. virtual bool InternalOpen(int const iFd, unsigned int const Mode) = 0;
  940. ssize_t InternalRead(void * To, unsigned long long Size)
  941. {
  942. // Drain the buffer if needed.
  943. if (buffer.empty() == false)
  944. {
  945. return buffer.read(To, Size);
  946. }
  947. return InternalUnbufferedRead(To, Size);
  948. }
  949. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) = 0;
  950. virtual bool InternalReadError() { return filefd->FileFdErrno("read",_("Read error")); }
  951. virtual char * InternalReadLine(char * To, unsigned long long Size)
  952. {
  953. if (unlikely(Size == 0))
  954. return nullptr;
  955. // Read one byte less than buffer size to have space for trailing 0.
  956. --Size;
  957. char * const InitialTo = To;
  958. while (Size > 0) {
  959. if (buffer.empty() == true)
  960. {
  961. buffer.reset();
  962. unsigned long long actualread = 0;
  963. if (filefd->Read(buffer.get(), buffer.buffersize_max, &actualread) == false)
  964. return nullptr;
  965. buffer.bufferend = actualread;
  966. if (buffer.size() == 0)
  967. {
  968. if (To == InitialTo)
  969. return nullptr;
  970. break;
  971. }
  972. filefd->Flags &= ~FileFd::HitEof;
  973. }
  974. unsigned long long const OutputSize = std::min(Size, buffer.size());
  975. char const * const newline = static_cast<char const * const>(memchr(buffer.get(), '\n', OutputSize));
  976. // Read until end of line or up to Size bytes from the buffer.
  977. unsigned long long actualread = buffer.read(To,
  978. (newline != nullptr)
  979. ? (newline - buffer.get()) + 1
  980. : OutputSize);
  981. To += actualread;
  982. Size -= actualread;
  983. if (newline != nullptr)
  984. break;
  985. }
  986. *To = '\0';
  987. return InitialTo;
  988. }
  989. virtual bool InternalFlush()
  990. {
  991. return true;
  992. }
  993. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) = 0;
  994. virtual bool InternalWriteError() { return filefd->FileFdErrno("write",_("Write error")); }
  995. virtual bool InternalSeek(unsigned long long const To)
  996. {
  997. // Our poor man seeking is costly, so try to avoid it
  998. unsigned long long const iseekpos = filefd->Tell();
  999. if (iseekpos == To)
  1000. return true;
  1001. else if (iseekpos < To)
  1002. return filefd->Skip(To - iseekpos);
  1003. if ((openmode & FileFd::ReadOnly) != FileFd::ReadOnly)
  1004. return filefd->FileFdError("Reopen is only implemented for read-only files!");
  1005. InternalClose(filefd->FileName);
  1006. if (filefd->iFd != -1)
  1007. close(filefd->iFd);
  1008. filefd->iFd = -1;
  1009. if (filefd->TemporaryFileName.empty() == false)
  1010. filefd->iFd = open(filefd->TemporaryFileName.c_str(), O_RDONLY);
  1011. else if (filefd->FileName.empty() == false)
  1012. filefd->iFd = open(filefd->FileName.c_str(), O_RDONLY);
  1013. else
  1014. {
  1015. if (compressed_fd > 0)
  1016. if (lseek(compressed_fd, 0, SEEK_SET) != 0)
  1017. filefd->iFd = compressed_fd;
  1018. if (filefd->iFd < 0)
  1019. return filefd->FileFdError("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
  1020. }
  1021. if (filefd->OpenInternDescriptor(openmode, compressor) == false)
  1022. return filefd->FileFdError("Seek on file %s because it couldn't be reopened", filefd->FileName.c_str());
  1023. buffer.reset();
  1024. if (To != 0)
  1025. return filefd->Skip(To);
  1026. seekpos = To;
  1027. return true;
  1028. }
  1029. virtual bool InternalSkip(unsigned long long Over)
  1030. {
  1031. unsigned long long constexpr buffersize = 1024;
  1032. char buffer[buffersize];
  1033. while (Over != 0)
  1034. {
  1035. unsigned long long toread = std::min(buffersize, Over);
  1036. if (filefd->Read(buffer, toread) == false)
  1037. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1038. Over -= toread;
  1039. }
  1040. return true;
  1041. }
  1042. virtual bool InternalTruncate(unsigned long long const)
  1043. {
  1044. return filefd->FileFdError("Truncating compressed files is not implemented (%s)", filefd->FileName.c_str());
  1045. }
  1046. virtual unsigned long long InternalTell()
  1047. {
  1048. // In theory, we could just return seekpos here always instead of
  1049. // seeking around, but not all users of FileFd use always Seek() and co
  1050. // so d->seekpos isn't always true and we can just use it as a hint if
  1051. // we have nothing else, but not always as an authority…
  1052. return seekpos - buffer.size();
  1053. }
  1054. virtual unsigned long long InternalSize()
  1055. {
  1056. unsigned long long size = 0;
  1057. unsigned long long const oldSeek = filefd->Tell();
  1058. unsigned long long constexpr ignoresize = 1024;
  1059. char ignore[ignoresize];
  1060. unsigned long long read = 0;
  1061. do {
  1062. if (filefd->Read(ignore, ignoresize, &read) == false)
  1063. {
  1064. filefd->Seek(oldSeek);
  1065. return 0;
  1066. }
  1067. } while(read != 0);
  1068. size = filefd->Tell();
  1069. filefd->Seek(oldSeek);
  1070. return size;
  1071. }
  1072. virtual bool InternalClose(std::string const &FileName) = 0;
  1073. virtual bool InternalStream() const { return false; }
  1074. virtual bool InternalAlwaysAutoClose() const { return true; }
  1075. virtual ~FileFdPrivate() {}
  1076. };
  1077. /*}}}*/
  1078. class APT_HIDDEN BufferedWriteFileFdPrivate : public FileFdPrivate { /*{{{*/
  1079. protected:
  1080. FileFdPrivate *wrapped;
  1081. simple_buffer writebuffer;
  1082. public:
  1083. explicit BufferedWriteFileFdPrivate(FileFdPrivate *Priv) :
  1084. FileFdPrivate(Priv->filefd), wrapped(Priv) {};
  1085. virtual APT::Configuration::Compressor get_compressor() const override
  1086. {
  1087. return wrapped->get_compressor();
  1088. }
  1089. virtual void set_compressor(APT::Configuration::Compressor const &compressor) override
  1090. {
  1091. return wrapped->set_compressor(compressor);
  1092. }
  1093. virtual unsigned int get_openmode() const override
  1094. {
  1095. return wrapped->get_openmode();
  1096. }
  1097. virtual void set_openmode(unsigned int openmode) override
  1098. {
  1099. return wrapped->set_openmode(openmode);
  1100. }
  1101. virtual bool get_is_pipe() const override
  1102. {
  1103. return wrapped->get_is_pipe();
  1104. }
  1105. virtual void set_is_pipe(bool is_pipe) override
  1106. {
  1107. FileFdPrivate::set_is_pipe(is_pipe);
  1108. wrapped->set_is_pipe(is_pipe);
  1109. }
  1110. virtual unsigned long long get_seekpos() const override
  1111. {
  1112. return wrapped->get_seekpos();
  1113. }
  1114. virtual void set_seekpos(unsigned long long seekpos) override
  1115. {
  1116. return wrapped->set_seekpos(seekpos);
  1117. }
  1118. virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
  1119. {
  1120. if (InternalFlush() == false)
  1121. return false;
  1122. return wrapped->InternalOpen(iFd, Mode);
  1123. }
  1124. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1125. {
  1126. if (InternalFlush() == false)
  1127. return -1;
  1128. return wrapped->InternalUnbufferedRead(To, Size);
  1129. }
  1130. virtual bool InternalReadError() override
  1131. {
  1132. return wrapped->InternalReadError();
  1133. }
  1134. virtual char * InternalReadLine(char * To, unsigned long long Size) override
  1135. {
  1136. if (InternalFlush() == false)
  1137. return nullptr;
  1138. return wrapped->InternalReadLine(To, Size);
  1139. }
  1140. virtual bool InternalFlush() override
  1141. {
  1142. while (writebuffer.empty() == false) {
  1143. auto written = wrapped->InternalWrite(writebuffer.get(),
  1144. writebuffer.size());
  1145. // Ignore interrupted syscalls
  1146. if (written < 0 && errno == EINTR)
  1147. continue;
  1148. if (written < 0)
  1149. return false;
  1150. writebuffer.bufferstart += written;
  1151. }
  1152. writebuffer.reset();
  1153. return true;
  1154. }
  1155. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1156. {
  1157. size_t written = 0;
  1158. while (written < Size) {
  1159. auto buffered = writebuffer.write(static_cast<char const*>(From) + written, Size - written);
  1160. written += buffered;
  1161. if (writebuffer.full() && InternalFlush() == false)
  1162. return -1;
  1163. }
  1164. return written;
  1165. }
  1166. virtual bool InternalWriteError()
  1167. {
  1168. return wrapped->InternalWriteError();
  1169. }
  1170. virtual bool InternalSeek(unsigned long long const To)
  1171. {
  1172. if (InternalFlush() == false)
  1173. return false;
  1174. return wrapped->InternalSeek(To);
  1175. }
  1176. virtual bool InternalSkip(unsigned long long Over)
  1177. {
  1178. if (InternalFlush() == false)
  1179. return false;
  1180. return wrapped->InternalSkip(Over);
  1181. }
  1182. virtual bool InternalTruncate(unsigned long long const Size)
  1183. {
  1184. if (InternalFlush() == false)
  1185. return false;
  1186. return wrapped->InternalTruncate(Size);
  1187. }
  1188. virtual unsigned long long InternalTell()
  1189. {
  1190. if (InternalFlush() == false)
  1191. return -1;
  1192. return wrapped->InternalTell();
  1193. }
  1194. virtual unsigned long long InternalSize()
  1195. {
  1196. if (InternalFlush() == false)
  1197. return -1;
  1198. return wrapped->InternalSize();
  1199. }
  1200. virtual bool InternalClose(std::string const &FileName)
  1201. {
  1202. return wrapped->InternalClose(FileName);
  1203. }
  1204. virtual bool InternalAlwaysAutoClose() const
  1205. {
  1206. return wrapped->InternalAlwaysAutoClose();
  1207. }
  1208. virtual ~BufferedWriteFileFdPrivate()
  1209. {
  1210. delete wrapped;
  1211. }
  1212. };
  1213. /*}}}*/
  1214. class APT_HIDDEN GzipFileFdPrivate: public FileFdPrivate { /*{{{*/
  1215. #ifdef HAVE_ZLIB
  1216. public:
  1217. gzFile gz;
  1218. virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
  1219. {
  1220. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1221. gz = gzdopen(iFd, "r+");
  1222. else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1223. gz = gzdopen(iFd, "w");
  1224. else
  1225. gz = gzdopen(iFd, "r");
  1226. filefd->Flags |= FileFd::Compressed;
  1227. return gz != nullptr;
  1228. }
  1229. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1230. {
  1231. return gzread(gz, To, Size);
  1232. }
  1233. virtual bool InternalReadError() override
  1234. {
  1235. int err;
  1236. char const * const errmsg = gzerror(gz, &err);
  1237. if (err != Z_ERRNO)
  1238. return filefd->FileFdError("gzread: %s (%d: %s)", _("Read error"), err, errmsg);
  1239. return FileFdPrivate::InternalReadError();
  1240. }
  1241. virtual char * InternalReadLine(char * To, unsigned long long Size) override
  1242. {
  1243. return gzgets(gz, To, Size);
  1244. }
  1245. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1246. {
  1247. return gzwrite(gz,From,Size);
  1248. }
  1249. virtual bool InternalWriteError() override
  1250. {
  1251. int err;
  1252. char const * const errmsg = gzerror(gz, &err);
  1253. if (err != Z_ERRNO)
  1254. return filefd->FileFdError("gzwrite: %s (%d: %s)", _("Write error"), err, errmsg);
  1255. return FileFdPrivate::InternalWriteError();
  1256. }
  1257. virtual bool InternalSeek(unsigned long long const To) override
  1258. {
  1259. off_t const res = gzseek(gz, To, SEEK_SET);
  1260. if (res != (off_t)To)
  1261. return filefd->FileFdError("Unable to seek to %llu", To);
  1262. seekpos = To;
  1263. buffer.reset();
  1264. return true;
  1265. }
  1266. virtual bool InternalSkip(unsigned long long Over) override
  1267. {
  1268. if (Over >= buffer.size())
  1269. {
  1270. Over -= buffer.size();
  1271. buffer.reset();
  1272. }
  1273. else
  1274. {
  1275. buffer.bufferstart += Over;
  1276. return true;
  1277. }
  1278. if (Over == 0)
  1279. return true;
  1280. off_t const res = gzseek(gz, Over, SEEK_CUR);
  1281. if (res < 0)
  1282. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1283. seekpos = res;
  1284. return true;
  1285. }
  1286. virtual unsigned long long InternalTell() override
  1287. {
  1288. return gztell(gz) - buffer.size();
  1289. }
  1290. virtual unsigned long long InternalSize() override
  1291. {
  1292. unsigned long long filesize = FileFdPrivate::InternalSize();
  1293. // only check gzsize if we are actually a gzip file, just checking for
  1294. // "gz" is not sufficient as uncompressed files could be opened with
  1295. // gzopen in "direct" mode as well
  1296. if (filesize == 0 || gzdirect(gz))
  1297. return filesize;
  1298. off_t const oldPos = lseek(filefd->iFd, 0, SEEK_CUR);
  1299. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1300. * this ourselves; the original (uncompressed) file size is the last 32
  1301. * bits of the file */
  1302. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1303. if (lseek(filefd->iFd, -4, SEEK_END) < 0)
  1304. {
  1305. filefd->FileFdErrno("lseek","Unable to seek to end of gzipped file");
  1306. return 0;
  1307. }
  1308. uint32_t size = 0;
  1309. if (read(filefd->iFd, &size, 4) != 4)
  1310. {
  1311. filefd->FileFdErrno("read","Unable to read original size of gzipped file");
  1312. return 0;
  1313. }
  1314. size = le32toh(size);
  1315. if (lseek(filefd->iFd, oldPos, SEEK_SET) < 0)
  1316. {
  1317. filefd->FileFdErrno("lseek","Unable to seek in gzipped file");
  1318. return 0;
  1319. }
  1320. return size;
  1321. }
  1322. virtual bool InternalClose(std::string const &FileName) override
  1323. {
  1324. if (gz == nullptr)
  1325. return true;
  1326. int const e = gzclose(gz);
  1327. gz = nullptr;
  1328. // gzdclose() on empty files always fails with "buffer error" here, ignore that
  1329. if (e != 0 && e != Z_BUF_ERROR)
  1330. return _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  1331. return true;
  1332. }
  1333. explicit GzipFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), gz(nullptr) {}
  1334. virtual ~GzipFileFdPrivate() { InternalClose(""); }
  1335. #endif
  1336. };
  1337. /*}}}*/
  1338. class APT_HIDDEN Bz2FileFdPrivate: public FileFdPrivate { /*{{{*/
  1339. #ifdef HAVE_BZ2
  1340. BZFILE* bz2;
  1341. public:
  1342. virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
  1343. {
  1344. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1345. bz2 = BZ2_bzdopen(iFd, "r+");
  1346. else if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1347. bz2 = BZ2_bzdopen(iFd, "w");
  1348. else
  1349. bz2 = BZ2_bzdopen(iFd, "r");
  1350. filefd->Flags |= FileFd::Compressed;
  1351. return bz2 != nullptr;
  1352. }
  1353. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1354. {
  1355. return BZ2_bzread(bz2, To, Size);
  1356. }
  1357. virtual bool InternalReadError() override
  1358. {
  1359. int err;
  1360. char const * const errmsg = BZ2_bzerror(bz2, &err);
  1361. if (err != BZ_IO_ERROR)
  1362. return filefd->FileFdError("BZ2_bzread: %s %s (%d: %s)", filefd->FileName.c_str(), _("Read error"), err, errmsg);
  1363. return FileFdPrivate::InternalReadError();
  1364. }
  1365. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1366. {
  1367. return BZ2_bzwrite(bz2, (void*)From, Size);
  1368. }
  1369. virtual bool InternalWriteError() override
  1370. {
  1371. int err;
  1372. char const * const errmsg = BZ2_bzerror(bz2, &err);
  1373. if (err != BZ_IO_ERROR)
  1374. return filefd->FileFdError("BZ2_bzwrite: %s %s (%d: %s)", filefd->FileName.c_str(), _("Write error"), err, errmsg);
  1375. return FileFdPrivate::InternalWriteError();
  1376. }
  1377. virtual bool InternalStream() const override { return true; }
  1378. virtual bool InternalClose(std::string const &) override
  1379. {
  1380. if (bz2 == nullptr)
  1381. return true;
  1382. BZ2_bzclose(bz2);
  1383. bz2 = nullptr;
  1384. return true;
  1385. }
  1386. explicit Bz2FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), bz2(nullptr) {}
  1387. virtual ~Bz2FileFdPrivate() { InternalClose(""); }
  1388. #endif
  1389. };
  1390. /*}}}*/
  1391. class APT_HIDDEN Lz4FileFdPrivate: public FileFdPrivate { /*{{{*/
  1392. static constexpr unsigned long long LZ4_HEADER_SIZE = 19;
  1393. static constexpr unsigned long long LZ4_FOOTER_SIZE = 4;
  1394. #ifdef HAVE_LZ4
  1395. LZ4F_decompressionContext_t dctx;
  1396. LZ4F_compressionContext_t cctx;
  1397. LZ4F_errorCode_t res;
  1398. FileFd backend;
  1399. simple_buffer lz4_buffer;
  1400. // Count of bytes that the decompressor expects to read next, or buffer size.
  1401. size_t next_to_load = APT_BUFFER_SIZE;
  1402. public:
  1403. virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
  1404. {
  1405. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1406. return _error->Error("lz4 only supports write or read mode");
  1407. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly) {
  1408. res = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
  1409. lz4_buffer.reset(LZ4F_compressBound(APT_BUFFER_SIZE, nullptr)
  1410. + LZ4_HEADER_SIZE + LZ4_FOOTER_SIZE);
  1411. } else {
  1412. res = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION);
  1413. lz4_buffer.reset(APT_BUFFER_SIZE);
  1414. }
  1415. filefd->Flags |= FileFd::Compressed;
  1416. if (LZ4F_isError(res))
  1417. return false;
  1418. unsigned int flags = (Mode & (FileFd::WriteOnly|FileFd::ReadOnly));
  1419. if (backend.OpenDescriptor(iFd, flags) == false)
  1420. return false;
  1421. // Write the file header
  1422. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1423. {
  1424. res = LZ4F_compressBegin(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr);
  1425. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1426. return false;
  1427. }
  1428. return true;
  1429. }
  1430. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1431. {
  1432. /* Keep reading as long as the compressor still wants to read */
  1433. while (next_to_load) {
  1434. // Fill compressed buffer;
  1435. if (lz4_buffer.empty()) {
  1436. unsigned long long read;
  1437. /* Reset - if LZ4 decompressor wants to read more, allocate more */
  1438. lz4_buffer.reset(next_to_load);
  1439. if (backend.Read(lz4_buffer.getend(), lz4_buffer.free(), &read) == false)
  1440. return -1;
  1441. lz4_buffer.bufferend += read;
  1442. /* Expected EOF */
  1443. if (read == 0) {
  1444. res = -1;
  1445. return filefd->FileFdError("LZ4F: %s %s",
  1446. filefd->FileName.c_str(),
  1447. _("Unexpected end of file")), -1;
  1448. }
  1449. }
  1450. // Drain compressed buffer as far as possible.
  1451. size_t in = lz4_buffer.size();
  1452. size_t out = Size;
  1453. res = LZ4F_decompress(dctx, To, &out, lz4_buffer.get(), &in, nullptr);
  1454. if (LZ4F_isError(res))
  1455. return -1;
  1456. next_to_load = res;
  1457. lz4_buffer.bufferstart += in;
  1458. if (out != 0)
  1459. return out;
  1460. }
  1461. return 0;
  1462. }
  1463. virtual bool InternalReadError() override
  1464. {
  1465. char const * const errmsg = LZ4F_getErrorName(res);
  1466. return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Read error"), res, errmsg);
  1467. }
  1468. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1469. {
  1470. unsigned long long const towrite = std::min(APT_BUFFER_SIZE, Size);
  1471. res = LZ4F_compressUpdate(cctx,
  1472. lz4_buffer.buffer, lz4_buffer.buffersize_max,
  1473. From, towrite, nullptr);
  1474. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1475. return -1;
  1476. return towrite;
  1477. }
  1478. virtual bool InternalWriteError() override
  1479. {
  1480. char const * const errmsg = LZ4F_getErrorName(res);
  1481. return filefd->FileFdError("LZ4F: %s %s (%zu: %s)", filefd->FileName.c_str(), _("Write error"), res, errmsg);
  1482. }
  1483. virtual bool InternalStream() const override { return true; }
  1484. virtual bool InternalFlush() override
  1485. {
  1486. return backend.Flush();
  1487. }
  1488. virtual bool InternalClose(std::string const &) override
  1489. {
  1490. /* Reset variables */
  1491. res = 0;
  1492. next_to_load = APT_BUFFER_SIZE;
  1493. if (cctx != nullptr)
  1494. {
  1495. res = LZ4F_compressEnd(cctx, lz4_buffer.buffer, lz4_buffer.buffersize_max, nullptr);
  1496. if (LZ4F_isError(res) || backend.Write(lz4_buffer.buffer, res) == false)
  1497. return false;
  1498. if (!backend.Flush())
  1499. return false;
  1500. if (!backend.Close())
  1501. return false;
  1502. res = LZ4F_freeCompressionContext(cctx);
  1503. cctx = nullptr;
  1504. }
  1505. if (dctx != nullptr)
  1506. {
  1507. res = LZ4F_freeDecompressionContext(dctx);
  1508. dctx = nullptr;
  1509. }
  1510. return LZ4F_isError(res) == false;
  1511. }
  1512. explicit Lz4FileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), dctx(nullptr), cctx(nullptr) {}
  1513. virtual ~Lz4FileFdPrivate() {
  1514. InternalClose("");
  1515. }
  1516. #endif
  1517. };
  1518. /*}}}*/
  1519. class APT_HIDDEN LzmaFileFdPrivate: public FileFdPrivate { /*{{{*/
  1520. #ifdef HAVE_LZMA
  1521. struct LZMAFILE {
  1522. FILE* file;
  1523. uint8_t buffer[4096];
  1524. lzma_stream stream;
  1525. lzma_ret err;
  1526. bool eof;
  1527. bool compressing;
  1528. LZMAFILE() : file(nullptr), eof(false), compressing(false) { buffer[0] = '\0'; }
  1529. ~LZMAFILE()
  1530. {
  1531. if (compressing == true)
  1532. {
  1533. size_t constexpr buffersize = sizeof(buffer)/sizeof(buffer[0]);
  1534. while(true)
  1535. {
  1536. stream.avail_out = buffersize;
  1537. stream.next_out = buffer;
  1538. err = lzma_code(&stream, LZMA_FINISH);
  1539. if (err != LZMA_OK && err != LZMA_STREAM_END)
  1540. {
  1541. _error->Error("~LZMAFILE: Compress finalisation failed");
  1542. break;
  1543. }
  1544. size_t const n = buffersize - stream.avail_out;
  1545. if (n && fwrite(buffer, 1, n, file) != n)
  1546. {
  1547. _error->Errno("~LZMAFILE",_("Write error"));
  1548. break;
  1549. }
  1550. if (err == LZMA_STREAM_END)
  1551. break;
  1552. }
  1553. }
  1554. lzma_end(&stream);
  1555. fclose(file);
  1556. }
  1557. };
  1558. LZMAFILE* lzma;
  1559. static uint32_t findXZlevel(std::vector<std::string> const &Args)
  1560. {
  1561. for (auto a = Args.rbegin(); a != Args.rend(); ++a)
  1562. if (a->empty() == false && (*a)[0] == '-' && (*a)[1] != '-')
  1563. {
  1564. auto const number = a->find_last_of("0123456789");
  1565. if (number == std::string::npos)
  1566. continue;
  1567. auto const extreme = a->find("e", number);
  1568. uint32_t level = (extreme != std::string::npos) ? LZMA_PRESET_EXTREME : 0;
  1569. switch ((*a)[number])
  1570. {
  1571. case '0': return level | 0;
  1572. case '1': return level | 1;
  1573. case '2': return level | 2;
  1574. case '3': return level | 3;
  1575. case '4': return level | 4;
  1576. case '5': return level | 5;
  1577. case '6': return level | 6;
  1578. case '7': return level | 7;
  1579. case '8': return level | 8;
  1580. case '9': return level | 9;
  1581. }
  1582. }
  1583. return 6;
  1584. }
  1585. public:
  1586. virtual bool InternalOpen(int const iFd, unsigned int const Mode) override
  1587. {
  1588. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1589. return filefd->FileFdError("ReadWrite mode is not supported for lzma/xz files %s", filefd->FileName.c_str());
  1590. if (lzma == nullptr)
  1591. lzma = new LzmaFileFdPrivate::LZMAFILE;
  1592. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1593. lzma->file = fdopen(iFd, "w");
  1594. else
  1595. lzma->file = fdopen(iFd, "r");
  1596. filefd->Flags |= FileFd::Compressed;
  1597. if (lzma->file == nullptr)
  1598. return false;
  1599. lzma_stream tmp_stream = LZMA_STREAM_INIT;
  1600. lzma->stream = tmp_stream;
  1601. if ((Mode & FileFd::WriteOnly) == FileFd::WriteOnly)
  1602. {
  1603. uint32_t const xzlevel = findXZlevel(compressor.CompressArgs);
  1604. if (compressor.Name == "xz")
  1605. {
  1606. if (lzma_easy_encoder(&lzma->stream, xzlevel, LZMA_CHECK_CRC64) != LZMA_OK)
  1607. return false;
  1608. }
  1609. else
  1610. {
  1611. lzma_options_lzma options;
  1612. lzma_lzma_preset(&options, xzlevel);
  1613. if (lzma_alone_encoder(&lzma->stream, &options) != LZMA_OK)
  1614. return false;
  1615. }
  1616. lzma->compressing = true;
  1617. }
  1618. else
  1619. {
  1620. uint64_t const memlimit = UINT64_MAX;
  1621. if (compressor.Name == "xz")
  1622. {
  1623. if (lzma_auto_decoder(&lzma->stream, memlimit, 0) != LZMA_OK)
  1624. return false;
  1625. }
  1626. else
  1627. {
  1628. if (lzma_alone_decoder(&lzma->stream, memlimit) != LZMA_OK)
  1629. return false;
  1630. }
  1631. lzma->compressing = false;
  1632. }
  1633. return true;
  1634. }
  1635. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1636. {
  1637. ssize_t Res;
  1638. if (lzma->eof == true)
  1639. return 0;
  1640. lzma->stream.next_out = (uint8_t *) To;
  1641. lzma->stream.avail_out = Size;
  1642. if (lzma->stream.avail_in == 0)
  1643. {
  1644. lzma->stream.next_in = lzma->buffer;
  1645. lzma->stream.avail_in = fread(lzma->buffer, 1, sizeof(lzma->buffer)/sizeof(lzma->buffer[0]), lzma->file);
  1646. }
  1647. lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
  1648. if (lzma->err == LZMA_STREAM_END)
  1649. {
  1650. lzma->eof = true;
  1651. Res = Size - lzma->stream.avail_out;
  1652. }
  1653. else if (lzma->err != LZMA_OK)
  1654. {
  1655. Res = -1;
  1656. errno = 0;
  1657. }
  1658. else
  1659. {
  1660. Res = Size - lzma->stream.avail_out;
  1661. if (Res == 0)
  1662. {
  1663. // lzma run was okay, but produced no output…
  1664. Res = -1;
  1665. errno = EINTR;
  1666. }
  1667. }
  1668. return Res;
  1669. }
  1670. virtual bool InternalReadError() override
  1671. {
  1672. return filefd->FileFdError("lzma_read: %s (%d)", _("Read error"), lzma->err);
  1673. }
  1674. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1675. {
  1676. lzma->stream.next_in = (uint8_t *)From;
  1677. lzma->stream.avail_in = Size;
  1678. lzma->stream.next_out = lzma->buffer;
  1679. lzma->stream.avail_out = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]);
  1680. lzma->err = lzma_code(&lzma->stream, LZMA_RUN);
  1681. if (lzma->err != LZMA_OK)
  1682. return -1;
  1683. size_t const n = sizeof(lzma->buffer)/sizeof(lzma->buffer[0]) - lzma->stream.avail_out;
  1684. size_t const m = (n == 0) ? 0 : fwrite(lzma->buffer, 1, n, lzma->file);
  1685. if (m != n)
  1686. return -1;
  1687. else
  1688. return Size - lzma->stream.avail_in;
  1689. }
  1690. virtual bool InternalWriteError() override
  1691. {
  1692. return filefd->FileFdError("lzma_write: %s (%d)", _("Write error"), lzma->err);
  1693. }
  1694. virtual bool InternalStream() const override { return true; }
  1695. virtual bool InternalClose(std::string const &) override
  1696. {
  1697. delete lzma;
  1698. lzma = nullptr;
  1699. return true;
  1700. }
  1701. explicit LzmaFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd), lzma(nullptr) {}
  1702. virtual ~LzmaFileFdPrivate() { InternalClose(""); }
  1703. #endif
  1704. };
  1705. /*}}}*/
  1706. class APT_HIDDEN PipedFileFdPrivate: public FileFdPrivate /*{{{*/
  1707. /* if we don't have a specific class dealing with library calls, we (un)compress
  1708. by executing a specified binary and pipe in/out what we need */
  1709. {
  1710. public:
  1711. virtual bool InternalOpen(int const, unsigned int const Mode) override
  1712. {
  1713. // collect zombies here in case we reopen
  1714. if (compressor_pid > 0)
  1715. ExecWait(compressor_pid, "FileFdCompressor", true);
  1716. if ((Mode & FileFd::ReadWrite) == FileFd::ReadWrite)
  1717. return filefd->FileFdError("ReadWrite mode is not supported for file %s", filefd->FileName.c_str());
  1718. bool const Comp = (Mode & FileFd::WriteOnly) == FileFd::WriteOnly;
  1719. if (Comp == false)
  1720. {
  1721. // Handle 'decompression' of empty files
  1722. struct stat Buf;
  1723. fstat(filefd->iFd, &Buf);
  1724. if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
  1725. return true;
  1726. // We don't need the file open - instead let the compressor open it
  1727. // as he properly knows better how to efficiently read from 'his' file
  1728. if (filefd->FileName.empty() == false)
  1729. {
  1730. close(filefd->iFd);
  1731. filefd->iFd = -1;
  1732. }
  1733. }
  1734. // Create a data pipe
  1735. int Pipe[2] = {-1,-1};
  1736. if (pipe(Pipe) != 0)
  1737. return filefd->FileFdErrno("pipe",_("Failed to create subprocess IPC"));
  1738. for (int J = 0; J != 2; J++)
  1739. SetCloseExec(Pipe[J],true);
  1740. compressed_fd = filefd->iFd;
  1741. set_is_pipe(true);
  1742. if (Comp == true)
  1743. filefd->iFd = Pipe[1];
  1744. else
  1745. filefd->iFd = Pipe[0];
  1746. // The child..
  1747. compressor_pid = ExecFork();
  1748. if (compressor_pid == 0)
  1749. {
  1750. if (Comp == true)
  1751. {
  1752. dup2(compressed_fd,STDOUT_FILENO);
  1753. dup2(Pipe[0],STDIN_FILENO);
  1754. }
  1755. else
  1756. {
  1757. if (compressed_fd != -1)
  1758. dup2(compressed_fd,STDIN_FILENO);
  1759. dup2(Pipe[1],STDOUT_FILENO);
  1760. }
  1761. int const nullfd = open("/dev/null", O_WRONLY);
  1762. if (nullfd != -1)
  1763. {
  1764. dup2(nullfd,STDERR_FILENO);
  1765. close(nullfd);
  1766. }
  1767. SetCloseExec(STDOUT_FILENO,false);
  1768. SetCloseExec(STDIN_FILENO,false);
  1769. std::vector<char const*> Args;
  1770. Args.push_back(compressor.Binary.c_str());
  1771. std::vector<std::string> const * const addArgs =
  1772. (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
  1773. for (std::vector<std::string>::const_iterator a = addArgs->begin();
  1774. a != addArgs->end(); ++a)
  1775. Args.push_back(a->c_str());
  1776. if (Comp == false && filefd->FileName.empty() == false)
  1777. {
  1778. // commands not needing arguments, do not need to be told about using standard output
  1779. // in reality, only testcases with tools like cat, rev, rot13, … are able to trigger this
  1780. if (compressor.CompressArgs.empty() == false && compressor.UncompressArgs.empty() == false)
  1781. Args.push_back("--stdout");
  1782. if (filefd->TemporaryFileName.empty() == false)
  1783. Args.push_back(filefd->TemporaryFileName.c_str());
  1784. else
  1785. Args.push_back(filefd->FileName.c_str());
  1786. }
  1787. Args.push_back(NULL);
  1788. execvp(Args[0],(char **)&Args[0]);
  1789. cerr << _("Failed to exec compressor ") << Args[0] << endl;
  1790. _exit(100);
  1791. }
  1792. if (Comp == true)
  1793. close(Pipe[0]);
  1794. else
  1795. close(Pipe[1]);
  1796. return true;
  1797. }
  1798. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1799. {
  1800. return read(filefd->iFd, To, Size);
  1801. }
  1802. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1803. {
  1804. return write(filefd->iFd, From, Size);
  1805. }
  1806. virtual bool InternalClose(std::string const &) override
  1807. {
  1808. bool Ret = true;
  1809. if (compressor_pid > 0)
  1810. Ret &= ExecWait(compressor_pid, "FileFdCompressor", true);
  1811. compressor_pid = -1;
  1812. return Ret;
  1813. }
  1814. explicit PipedFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
  1815. virtual ~PipedFileFdPrivate() { InternalClose(""); }
  1816. };
  1817. /*}}}*/
  1818. class APT_HIDDEN DirectFileFdPrivate: public FileFdPrivate /*{{{*/
  1819. {
  1820. public:
  1821. virtual bool InternalOpen(int const, unsigned int const) override { return true; }
  1822. virtual ssize_t InternalUnbufferedRead(void * const To, unsigned long long const Size) override
  1823. {
  1824. return read(filefd->iFd, To, Size);
  1825. }
  1826. virtual ssize_t InternalWrite(void const * const From, unsigned long long const Size) override
  1827. {
  1828. // files opened read+write are strange and only really "supported" for direct files
  1829. if (buffer.size() != 0)
  1830. {
  1831. lseek(filefd->iFd, -buffer.size(), SEEK_CUR);
  1832. buffer.reset();
  1833. }
  1834. return write(filefd->iFd, From, Size);
  1835. }
  1836. virtual bool InternalSeek(unsigned long long const To) override
  1837. {
  1838. off_t const res = lseek(filefd->iFd, To, SEEK_SET);
  1839. if (res != (off_t)To)
  1840. return filefd->FileFdError("Unable to seek to %llu", To);
  1841. seekpos = To;
  1842. buffer.reset();
  1843. return true;
  1844. }
  1845. virtual bool InternalSkip(unsigned long long Over) override
  1846. {
  1847. if (Over >= buffer.size())
  1848. {
  1849. Over -= buffer.size();
  1850. buffer.reset();
  1851. }
  1852. else
  1853. {
  1854. buffer.bufferstart += Over;
  1855. return true;
  1856. }
  1857. if (Over == 0)
  1858. return true;
  1859. off_t const res = lseek(filefd->iFd, Over, SEEK_CUR);
  1860. if (res < 0)
  1861. return filefd->FileFdError("Unable to seek ahead %llu",Over);
  1862. seekpos = res;
  1863. return true;
  1864. }
  1865. virtual bool InternalTruncate(unsigned long long const To) override
  1866. {
  1867. if (buffer.size() != 0)
  1868. {
  1869. unsigned long long const seekpos = lseek(filefd->iFd, 0, SEEK_CUR);
  1870. if ((seekpos - buffer.size()) >= To)
  1871. buffer.reset();
  1872. else if (seekpos >= To)
  1873. buffer.bufferend = (To - seekpos) + buffer.bufferstart;
  1874. else
  1875. buffer.reset();
  1876. }
  1877. if (ftruncate(filefd->iFd, To) != 0)
  1878. return filefd->FileFdError("Unable to truncate to %llu",To);
  1879. return true;
  1880. }
  1881. virtual unsigned long long InternalTell() override
  1882. {
  1883. return lseek(filefd->iFd,0,SEEK_CUR) - buffer.size();
  1884. }
  1885. virtual unsigned long long InternalSize() override
  1886. {
  1887. return filefd->FileSize();
  1888. }
  1889. virtual bool InternalClose(std::string const &) override { return true; }
  1890. virtual bool InternalAlwaysAutoClose() const override { return false; }
  1891. explicit DirectFileFdPrivate(FileFd * const filefd) : FileFdPrivate(filefd) {}
  1892. virtual ~DirectFileFdPrivate() { InternalClose(""); }
  1893. };
  1894. /*}}}*/
  1895. // FileFd Constructors /*{{{*/
  1896. FileFd::FileFd(std::string FileName,unsigned int const Mode,unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  1897. {
  1898. Open(FileName,Mode, None, AccessMode);
  1899. }
  1900. FileFd::FileFd(std::string FileName,unsigned int const Mode, CompressMode Compress, unsigned long AccessMode) : iFd(-1), Flags(0), d(NULL)
  1901. {
  1902. Open(FileName,Mode, Compress, AccessMode);
  1903. }
  1904. FileFd::FileFd() : iFd(-1), Flags(AutoClose), d(NULL) {}
  1905. FileFd::FileFd(int const Fd, unsigned int const Mode, CompressMode Compress) : iFd(-1), Flags(0), d(NULL)
  1906. {
  1907. OpenDescriptor(Fd, Mode, Compress);
  1908. }
  1909. FileFd::FileFd(int const Fd, bool const AutoClose) : iFd(-1), Flags(0), d(NULL)
  1910. {
  1911. OpenDescriptor(Fd, ReadWrite, None, AutoClose);
  1912. }
  1913. /*}}}*/
  1914. // FileFd::Open - Open a file /*{{{*/
  1915. // ---------------------------------------------------------------------
  1916. /* The most commonly used open mode combinations are given with Mode */
  1917. bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const AccessMode)
  1918. {
  1919. if (Mode == ReadOnlyGzip)
  1920. return Open(FileName, ReadOnly, Gzip, AccessMode);
  1921. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  1922. return FileFdError("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  1923. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  1924. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  1925. if (Compress == Auto)
  1926. {
  1927. for (; compressor != compressors.end(); ++compressor)
  1928. {
  1929. std::string file = FileName + compressor->Extension;
  1930. if (FileExists(file) == false)
  1931. continue;
  1932. FileName = file;
  1933. break;
  1934. }
  1935. }
  1936. else if (Compress == Extension)
  1937. {
  1938. std::string::size_type const found = FileName.find_last_of('.');
  1939. std::string ext;
  1940. if (found != std::string::npos)
  1941. {
  1942. ext = FileName.substr(found);
  1943. if (ext == ".new" || ext == ".bak")
  1944. {
  1945. std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
  1946. if (found2 != std::string::npos)
  1947. ext = FileName.substr(found2, found - found2);
  1948. else
  1949. ext.clear();
  1950. }
  1951. }
  1952. for (; compressor != compressors.end(); ++compressor)
  1953. if (ext == compressor->Extension)
  1954. break;
  1955. // no matching extension - assume uncompressed (imagine files like 'example.org_Packages')
  1956. if (compressor == compressors.end())
  1957. for (compressor = compressors.begin(); compressor != compressors.end(); ++compressor)
  1958. if (compressor->Name == ".")
  1959. break;
  1960. }
  1961. else
  1962. {
  1963. std::string name;
  1964. switch (Compress)
  1965. {
  1966. case None: name = "."; break;
  1967. case Gzip: name = "gzip"; break;
  1968. case Bzip2: name = "bzip2"; break;
  1969. case Lzma: name = "lzma"; break;
  1970. case Xz: name = "xz"; break;
  1971. case Lz4: name = "lz4"; break;
  1972. case Auto:
  1973. case Extension:
  1974. // Unreachable
  1975. return FileFdError("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
  1976. }
  1977. for (; compressor != compressors.end(); ++compressor)
  1978. if (compressor->Name == name)
  1979. break;
  1980. if (compressor == compressors.end())
  1981. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  1982. }
  1983. if (compressor == compressors.end())
  1984. return FileFdError("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  1985. return Open(FileName, Mode, *compressor, AccessMode);
  1986. }
  1987. bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const AccessMode)
  1988. {
  1989. Close();
  1990. Flags = AutoClose;
  1991. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  1992. return FileFdError("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  1993. if ((Mode & ReadWrite) == 0)
  1994. return FileFdError("No openmode provided in FileFd::Open for %s", FileName.c_str());
  1995. unsigned int OpenMode = Mode;
  1996. if (FileName == "/dev/null")
  1997. OpenMode = OpenMode & ~(Atomic | Exclusive | Create | Empty);
  1998. if ((OpenMode & Atomic) == Atomic)
  1999. {
  2000. Flags |= Replace;
  2001. }
  2002. else if ((OpenMode & (Exclusive | Create)) == (Exclusive | Create))
  2003. {
  2004. // for atomic, this will be done by rename in Close()
  2005. RemoveFile("FileFd::Open", FileName);
  2006. }
  2007. if ((OpenMode & Empty) == Empty)
  2008. {
  2009. struct stat Buf;
  2010. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  2011. RemoveFile("FileFd::Open", FileName);
  2012. }
  2013. int fileflags = 0;
  2014. #define if_FLAGGED_SET(FLAG, MODE) if ((OpenMode & FLAG) == FLAG) fileflags |= MODE
  2015. if_FLAGGED_SET(ReadWrite, O_RDWR);
  2016. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  2017. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  2018. if_FLAGGED_SET(Create, O_CREAT);
  2019. if_FLAGGED_SET(Empty, O_TRUNC);
  2020. if_FLAGGED_SET(Exclusive, O_EXCL);
  2021. #undef if_FLAGGED_SET
  2022. if ((OpenMode & Atomic) == Atomic)
  2023. {
  2024. char *name = strdup((FileName + ".XXXXXX").c_str());
  2025. if((iFd = mkstemp(name)) == -1)
  2026. {
  2027. free(name);
  2028. return FileFdErrno("mkstemp", "Could not create temporary file for %s", FileName.c_str());
  2029. }
  2030. TemporaryFileName = string(name);
  2031. free(name);
  2032. // umask() will always set the umask and return the previous value, so
  2033. // we first set the umask and then reset it to the old value
  2034. mode_t const CurrentUmask = umask(0);
  2035. umask(CurrentUmask);
  2036. // calculate the actual file permissions (just like open/creat)
  2037. mode_t const FilePermissions = (AccessMode & ~CurrentUmask);
  2038. if(fchmod(iFd, FilePermissions) == -1)
  2039. return FileFdErrno("fchmod", "Could not change permissions for temporary file %s", TemporaryFileName.c_str());
  2040. }
  2041. else
  2042. iFd = open(FileName.c_str(), fileflags, AccessMode);
  2043. this->FileName = FileName;
  2044. if (iFd == -1 || OpenInternDescriptor(OpenMode, compressor) == false)
  2045. {
  2046. if (iFd != -1)
  2047. {
  2048. close (iFd);
  2049. iFd = -1;
  2050. }
  2051. return FileFdErrno("open",_("Could not open file %s"), FileName.c_str());
  2052. }
  2053. SetCloseExec(iFd,true);
  2054. return true;
  2055. }
  2056. /*}}}*/
  2057. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  2058. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
  2059. {
  2060. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  2061. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  2062. std::string name;
  2063. // compat with the old API
  2064. if (Mode == ReadOnlyGzip && Compress == None)
  2065. Compress = Gzip;
  2066. switch (Compress)
  2067. {
  2068. case None: name = "."; break;
  2069. case Gzip: name = "gzip"; break;
  2070. case Bzip2: name = "bzip2"; break;
  2071. case Lzma: name = "lzma"; break;
  2072. case Xz: name = "xz"; break;
  2073. case Lz4: name = "lz4"; break;
  2074. case Auto:
  2075. case Extension:
  2076. if (AutoClose == true && Fd != -1)
  2077. close(Fd);
  2078. return FileFdError("Opening Fd %d in Auto or Extension compression mode is not supported", Fd);
  2079. }
  2080. for (; compressor != compressors.end(); ++compressor)
  2081. if (compressor->Name == name)
  2082. break;
  2083. if (compressor == compressors.end())
  2084. {
  2085. if (AutoClose == true && Fd != -1)
  2086. close(Fd);
  2087. return FileFdError("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  2088. }
  2089. return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
  2090. }
  2091. bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
  2092. {
  2093. Close();
  2094. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  2095. iFd = Fd;
  2096. this->FileName = "";
  2097. if (OpenInternDescriptor(Mode, compressor) == false)
  2098. {
  2099. if (iFd != -1 && (
  2100. (Flags & Compressed) == Compressed ||
  2101. AutoClose == true))
  2102. {
  2103. close (iFd);
  2104. iFd = -1;
  2105. }
  2106. return FileFdError(_("Could not open file descriptor %d"), Fd);
  2107. }
  2108. return true;
  2109. }
  2110. bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
  2111. {
  2112. if (iFd == -1)
  2113. return false;
  2114. if (d != nullptr)
  2115. d->InternalClose(FileName);
  2116. if (d == nullptr)
  2117. {
  2118. if (false)
  2119. /* dummy so that the rest can be 'else if's */;
  2120. #define APT_COMPRESS_INIT(NAME, CONSTRUCTOR) \
  2121. else if (compressor.Name == NAME) \
  2122. d = new CONSTRUCTOR(this)
  2123. #ifdef HAVE_ZLIB
  2124. APT_COMPRESS_INIT("gzip", GzipFileFdPrivate);
  2125. #endif
  2126. #ifdef HAVE_BZ2
  2127. APT_COMPRESS_INIT("bzip2", Bz2FileFdPrivate);
  2128. #endif
  2129. #ifdef HAVE_LZMA
  2130. APT_COMPRESS_INIT("xz", LzmaFileFdPrivate);
  2131. APT_COMPRESS_INIT("lzma", LzmaFileFdPrivate);
  2132. #endif
  2133. #ifdef HAVE_LZ4
  2134. APT_COMPRESS_INIT("lz4", Lz4FileFdPrivate);
  2135. #endif
  2136. #undef APT_COMPRESS_INIT
  2137. else if (compressor.Name == "." || compressor.Binary.empty() == true)
  2138. d = new DirectFileFdPrivate(this);
  2139. else
  2140. d = new PipedFileFdPrivate(this);
  2141. if (Mode & BufferedWrite)
  2142. d = new BufferedWriteFileFdPrivate(d);
  2143. d->set_openmode(Mode);
  2144. d->set_compressor(compressor);
  2145. if ((Flags & AutoClose) != AutoClose && d->InternalAlwaysAutoClose())
  2146. {
  2147. // Need to duplicate fd here or gz/bz2 close for cleanup will close the fd as well
  2148. int const internFd = dup(iFd);
  2149. if (internFd == -1)
  2150. return FileFdErrno("OpenInternDescriptor", _("Could not open file descriptor %d"), iFd);
  2151. iFd = internFd;
  2152. }
  2153. }
  2154. return d->InternalOpen(iFd, Mode);
  2155. }
  2156. /*}}}*/
  2157. // FileFd::~File - Closes the file /*{{{*/
  2158. // ---------------------------------------------------------------------
  2159. /* If the proper modes are selected then we close the Fd and possibly
  2160. unlink the file on error. */
  2161. FileFd::~FileFd()
  2162. {
  2163. Close();
  2164. if (d != NULL)
  2165. d->InternalClose(FileName);
  2166. delete d;
  2167. d = NULL;
  2168. }
  2169. /*}}}*/
  2170. // FileFd::Read - Read a bit of the file /*{{{*/
  2171. // ---------------------------------------------------------------------
  2172. /* We are careful to handle interruption by a signal while reading
  2173. gracefully. */
  2174. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  2175. {
  2176. if (d == nullptr)
  2177. return false;
  2178. ssize_t Res = 1;
  2179. errno = 0;
  2180. if (Actual != 0)
  2181. *Actual = 0;
  2182. *((char *)To) = '\0';
  2183. while (Res > 0 && Size > 0)
  2184. {
  2185. Res = d->InternalRead(To, Size);
  2186. if (Res < 0)
  2187. {
  2188. if (errno == EINTR)
  2189. {
  2190. // trick the while-loop into running again
  2191. Res = 1;
  2192. errno = 0;
  2193. continue;
  2194. }
  2195. return d->InternalReadError();
  2196. }
  2197. To = (char *)To + Res;
  2198. Size -= Res;
  2199. if (d != NULL)
  2200. d->set_seekpos(d->get_seekpos() + Res);
  2201. if (Actual != 0)
  2202. *Actual += Res;
  2203. }
  2204. if (Size == 0)
  2205. return true;
  2206. // Eof handling
  2207. if (Actual != 0)
  2208. {
  2209. Flags |= HitEof;
  2210. return true;
  2211. }
  2212. return FileFdError(_("read, still have %llu to read but none left"), Size);
  2213. }
  2214. /*}}}*/
  2215. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  2216. // ---------------------------------------------------------------------
  2217. /* Beware: This method can be quite slow for big buffers on UNcompressed
  2218. files because of the naive implementation! */
  2219. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  2220. {
  2221. *To = '\0';
  2222. if (d == nullptr)
  2223. return nullptr;
  2224. return d->InternalReadLine(To, Size);
  2225. }
  2226. /*}}}*/
  2227. // FileFd::Flush - Flush the file /*{{{*/
  2228. bool FileFd::Flush()
  2229. {
  2230. if (d == nullptr)
  2231. return true;
  2232. return d->InternalFlush();
  2233. }
  2234. /*}}}*/
  2235. // FileFd::Write - Write to the file /*{{{*/
  2236. bool FileFd::Write(const void *From,unsigned long long Size)
  2237. {
  2238. if (d == nullptr)
  2239. return false;
  2240. ssize_t Res = 1;
  2241. errno = 0;
  2242. while (Res > 0 && Size > 0)
  2243. {
  2244. Res = d->InternalWrite(From, Size);
  2245. if (Res < 0 && errno == EINTR)
  2246. continue;
  2247. if (Res < 0)
  2248. return d->InternalWriteError();
  2249. From = (char const *)From + Res;
  2250. Size -= Res;
  2251. if (d != NULL)
  2252. d->set_seekpos(d->get_seekpos() + Res);
  2253. }
  2254. if (Size == 0)
  2255. return true;
  2256. return FileFdError(_("write, still have %llu to write but couldn't"), Size);
  2257. }
  2258. bool FileFd::Write(int Fd, const void *From, unsigned long long Size)
  2259. {
  2260. ssize_t Res = 1;
  2261. errno = 0;
  2262. while (Res > 0 && Size > 0)
  2263. {
  2264. Res = write(Fd,From,Size);
  2265. if (Res < 0 && errno == EINTR)
  2266. continue;
  2267. if (Res < 0)
  2268. return _error->Errno("write",_("Write error"));
  2269. From = (char const *)From + Res;
  2270. Size -= Res;
  2271. }
  2272. if (Size == 0)
  2273. return true;
  2274. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  2275. }
  2276. /*}}}*/
  2277. // FileFd::Seek - Seek in the file /*{{{*/
  2278. bool FileFd::Seek(unsigned long long To)
  2279. {
  2280. if (d == nullptr)
  2281. return false;
  2282. Flags &= ~HitEof;
  2283. return d->InternalSeek(To);
  2284. }
  2285. /*}}}*/
  2286. // FileFd::Skip - Skip over data in the file /*{{{*/
  2287. bool FileFd::Skip(unsigned long long Over)
  2288. {
  2289. if (d == nullptr)
  2290. return false;
  2291. return d->InternalSkip(Over);
  2292. }
  2293. /*}}}*/
  2294. // FileFd::Truncate - Truncate the file /*{{{*/
  2295. bool FileFd::Truncate(unsigned long long To)
  2296. {
  2297. if (d == nullptr)
  2298. return false;
  2299. // truncating /dev/null is always successful - as we get an error otherwise
  2300. if (To == 0 && FileName == "/dev/null")
  2301. return true;
  2302. return d->InternalTruncate(To);
  2303. }
  2304. /*}}}*/
  2305. // FileFd::Tell - Current seek position /*{{{*/
  2306. // ---------------------------------------------------------------------
  2307. /* */
  2308. unsigned long long FileFd::Tell()
  2309. {
  2310. if (d == nullptr)
  2311. return false;
  2312. off_t const Res = d->InternalTell();
  2313. if (Res == (off_t)-1)
  2314. FileFdErrno("lseek","Failed to determine the current file position");
  2315. d->set_seekpos(Res);
  2316. return Res;
  2317. }
  2318. /*}}}*/
  2319. static bool StatFileFd(char const * const msg, int const iFd, std::string const &FileName, struct stat &Buf, FileFdPrivate * const d) /*{{{*/
  2320. {
  2321. bool ispipe = (d != NULL && d->get_is_pipe() == true);
  2322. if (ispipe == false)
  2323. {
  2324. if (fstat(iFd,&Buf) != 0)
  2325. // higher-level code will generate more meaningful messages,
  2326. // even translated this would be meaningless for users
  2327. return _error->Errno("fstat", "Unable to determine %s for fd %i", msg, iFd);
  2328. if (FileName.empty() == false)
  2329. ispipe = S_ISFIFO(Buf.st_mode);
  2330. }
  2331. // for compressor pipes st_size is undefined and at 'best' zero
  2332. if (ispipe == true)
  2333. {
  2334. // we set it here, too, as we get the info here for free
  2335. // in theory the Open-methods should take care of it already
  2336. if (d != NULL)
  2337. d->set_is_pipe(true);
  2338. if (stat(FileName.c_str(), &Buf) != 0)
  2339. return _error->Errno("fstat", "Unable to determine %s for file %s", msg, FileName.c_str());
  2340. }
  2341. return true;
  2342. }
  2343. /*}}}*/
  2344. // FileFd::FileSize - Return the size of the file /*{{{*/
  2345. unsigned long long FileFd::FileSize()
  2346. {
  2347. struct stat Buf;
  2348. if (StatFileFd("file size", iFd, FileName, Buf, d) == false)
  2349. {
  2350. Flags |= Fail;
  2351. return 0;
  2352. }
  2353. return Buf.st_size;
  2354. }
  2355. /*}}}*/
  2356. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  2357. time_t FileFd::ModificationTime()
  2358. {
  2359. struct stat Buf;
  2360. if (StatFileFd("modification time", iFd, FileName, Buf, d) == false)
  2361. {
  2362. Flags |= Fail;
  2363. return 0;
  2364. }
  2365. return Buf.st_mtime;
  2366. }
  2367. /*}}}*/
  2368. // FileFd::Size - Return the size of the content in the file /*{{{*/
  2369. unsigned long long FileFd::Size()
  2370. {
  2371. if (d == nullptr)
  2372. return false;
  2373. return d->InternalSize();
  2374. }
  2375. /*}}}*/
  2376. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  2377. // ---------------------------------------------------------------------
  2378. /* */
  2379. bool FileFd::Close()
  2380. {
  2381. if (Flush() == false)
  2382. return false;
  2383. if (iFd == -1)
  2384. return true;
  2385. bool Res = true;
  2386. if ((Flags & AutoClose) == AutoClose)
  2387. {
  2388. if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
  2389. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  2390. }
  2391. if (d != NULL)
  2392. {
  2393. Res &= d->InternalClose(FileName);
  2394. delete d;
  2395. d = NULL;
  2396. }
  2397. if ((Flags & Replace) == Replace) {
  2398. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  2399. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  2400. FileName = TemporaryFileName; // for the unlink() below.
  2401. TemporaryFileName.clear();
  2402. }
  2403. iFd = -1;
  2404. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  2405. FileName.empty() == false)
  2406. Res &= RemoveFile("FileFd::Close", FileName);
  2407. if (Res == false)
  2408. Flags |= Fail;
  2409. return Res;
  2410. }
  2411. /*}}}*/
  2412. // FileFd::Sync - Sync the file /*{{{*/
  2413. // ---------------------------------------------------------------------
  2414. /* */
  2415. bool FileFd::Sync()
  2416. {
  2417. if (fsync(iFd) != 0)
  2418. return FileFdErrno("sync",_("Problem syncing the file"));
  2419. return true;
  2420. }
  2421. /*}}}*/
  2422. // FileFd::FileFdErrno - set Fail and call _error->Errno *{{{*/
  2423. bool FileFd::FileFdErrno(const char *Function, const char *Description,...)
  2424. {
  2425. Flags |= Fail;
  2426. va_list args;
  2427. size_t msgSize = 400;
  2428. int const errsv = errno;
  2429. while (true)
  2430. {
  2431. va_start(args,Description);
  2432. if (_error->InsertErrno(GlobalError::ERROR, Function, Description, args, errsv, msgSize) == false)
  2433. break;
  2434. va_end(args);
  2435. }
  2436. return false;
  2437. }
  2438. /*}}}*/
  2439. // FileFd::FileFdError - set Fail and call _error->Error *{{{*/
  2440. bool FileFd::FileFdError(const char *Description,...) {
  2441. Flags |= Fail;
  2442. va_list args;
  2443. size_t msgSize = 400;
  2444. while (true)
  2445. {
  2446. va_start(args,Description);
  2447. if (_error->Insert(GlobalError::ERROR, Description, args, msgSize) == false)
  2448. break;
  2449. va_end(args);
  2450. }
  2451. return false;
  2452. }
  2453. /*}}}*/
  2454. gzFile FileFd::gzFd() { /*{{{*/
  2455. #ifdef HAVE_ZLIB
  2456. GzipFileFdPrivate * const gzipd = dynamic_cast<GzipFileFdPrivate*>(d);
  2457. if (gzipd == nullptr)
  2458. return nullptr;
  2459. else
  2460. return gzipd->gz;
  2461. #else
  2462. return nullptr;
  2463. #endif
  2464. }
  2465. /*}}}*/
  2466. // Glob - wrapper around "glob()" /*{{{*/
  2467. std::vector<std::string> Glob(std::string const &pattern, int flags)
  2468. {
  2469. std::vector<std::string> result;
  2470. glob_t globbuf;
  2471. int glob_res;
  2472. unsigned int i;
  2473. glob_res = glob(pattern.c_str(), flags, NULL, &globbuf);
  2474. if (glob_res != 0)
  2475. {
  2476. if(glob_res != GLOB_NOMATCH) {
  2477. _error->Errno("glob", "Problem with glob");
  2478. return result;
  2479. }
  2480. }
  2481. // append results
  2482. for(i=0;i<globbuf.gl_pathc;i++)
  2483. result.push_back(string(globbuf.gl_pathv[i]));
  2484. globfree(&globbuf);
  2485. return result;
  2486. }
  2487. /*}}}*/
  2488. std::string GetTempDir() /*{{{*/
  2489. {
  2490. const char *tmpdir = getenv("TMPDIR");
  2491. #ifdef P_tmpdir
  2492. if (!tmpdir)
  2493. tmpdir = P_tmpdir;
  2494. #endif
  2495. struct stat st;
  2496. if (!tmpdir || strlen(tmpdir) == 0 || // tmpdir is set
  2497. stat(tmpdir, &st) != 0 || (st.st_mode & S_IFDIR) == 0) // exists and is directory
  2498. tmpdir = "/tmp";
  2499. else if (geteuid() != 0 && // root can do everything anyway
  2500. faccessat(-1, tmpdir, R_OK | W_OK | X_OK, AT_EACCESS | AT_SYMLINK_NOFOLLOW) != 0) // current user has rwx access to directory
  2501. tmpdir = "/tmp";
  2502. return string(tmpdir);
  2503. }
  2504. std::string GetTempDir(std::string const &User)
  2505. {
  2506. // no need/possibility to drop privs
  2507. if(getuid() != 0 || User.empty() || User == "root")
  2508. return GetTempDir();
  2509. struct passwd const * const pw = getpwnam(User.c_str());
  2510. if (pw == NULL)
  2511. return GetTempDir();
  2512. gid_t const old_euid = geteuid();
  2513. gid_t const old_egid = getegid();
  2514. if (setegid(pw->pw_gid) != 0)
  2515. _error->Errno("setegid", "setegid %u failed", pw->pw_gid);
  2516. if (seteuid(pw->pw_uid) != 0)
  2517. _error->Errno("seteuid", "seteuid %u failed", pw->pw_uid);
  2518. std::string const tmp = GetTempDir();
  2519. if (seteuid(old_euid) != 0)
  2520. _error->Errno("seteuid", "seteuid %u failed", old_euid);
  2521. if (setegid(old_egid) != 0)
  2522. _error->Errno("setegid", "setegid %u failed", old_egid);
  2523. return tmp;
  2524. }
  2525. /*}}}*/
  2526. FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink, FileFd * const TmpFd) /*{{{*/
  2527. {
  2528. char fn[512];
  2529. FileFd * const Fd = TmpFd == NULL ? new FileFd() : TmpFd;
  2530. std::string const tempdir = GetTempDir();
  2531. snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
  2532. tempdir.c_str(), Prefix.c_str());
  2533. int const fd = mkstemp(fn);
  2534. if(ImmediateUnlink)
  2535. unlink(fn);
  2536. if (fd < 0)
  2537. {
  2538. _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
  2539. return NULL;
  2540. }
  2541. if (!Fd->OpenDescriptor(fd, FileFd::ReadWrite, FileFd::None, true))
  2542. {
  2543. _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
  2544. return NULL;
  2545. }
  2546. return Fd;
  2547. }
  2548. /*}}}*/
  2549. bool Rename(std::string From, std::string To) /*{{{*/
  2550. {
  2551. if (rename(From.c_str(),To.c_str()) != 0)
  2552. {
  2553. _error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
  2554. From.c_str(),To.c_str());
  2555. return false;
  2556. }
  2557. return true;
  2558. }
  2559. /*}}}*/
  2560. bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
  2561. {
  2562. int fd;
  2563. if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
  2564. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  2565. int Pipe[2] = {-1, -1};
  2566. if(pipe(Pipe) != 0)
  2567. return _error->Errno("pipe", _("Failed to create subprocess IPC"));
  2568. std::set<int> keep_fds;
  2569. keep_fds.insert(Pipe[0]);
  2570. keep_fds.insert(Pipe[1]);
  2571. Child = ExecFork(keep_fds);
  2572. if(Child < 0)
  2573. return _error->Errno("fork", "Failed to fork");
  2574. if(Child == 0)
  2575. {
  2576. if(Mode == FileFd::ReadOnly)
  2577. {
  2578. close(Pipe[0]);
  2579. fd = Pipe[1];
  2580. }
  2581. else if(Mode == FileFd::WriteOnly)
  2582. {
  2583. close(Pipe[1]);
  2584. fd = Pipe[0];
  2585. }
  2586. if(Mode == FileFd::ReadOnly)
  2587. {
  2588. dup2(fd, 1);
  2589. dup2(fd, 2);
  2590. } else if(Mode == FileFd::WriteOnly)
  2591. dup2(fd, 0);
  2592. execv(Args[0], (char**)Args);
  2593. _exit(100);
  2594. }
  2595. if(Mode == FileFd::ReadOnly)
  2596. {
  2597. close(Pipe[1]);
  2598. fd = Pipe[0];
  2599. }
  2600. else if(Mode == FileFd::WriteOnly)
  2601. {
  2602. close(Pipe[0]);
  2603. fd = Pipe[1];
  2604. }
  2605. else
  2606. return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
  2607. Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
  2608. return true;
  2609. }
  2610. /*}}}*/
  2611. bool DropPrivileges() /*{{{*/
  2612. {
  2613. if(_config->FindB("Debug::NoDropPrivs", false) == true)
  2614. return true;
  2615. #if __gnu_linux__
  2616. #if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
  2617. #error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
  2618. #endif
  2619. // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
  2620. int ret = prctl(38, 1, 0, 0, 0);
  2621. // ignore EINVAL - kernel is too old to understand the option
  2622. if(ret < 0 && errno != EINVAL)
  2623. _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
  2624. #endif
  2625. // empty setting disables privilege dropping - this also ensures
  2626. // backward compatibility, see bug #764506
  2627. const std::string toUser = _config->Find("APT::Sandbox::User");
  2628. if (toUser.empty() || toUser == "root")
  2629. return true;
  2630. // a lot can go wrong trying to drop privileges completely,
  2631. // so ideally we would like to verify that we have done it –
  2632. // but the verify asks for too much in case of fakeroot (and alike)
  2633. // [Specific checks can be overridden with dedicated options]
  2634. bool const VerifySandboxing = _config->FindB("APT::Sandbox::Verify", false);
  2635. // uid will be 0 in the end, but gid might be different anyway
  2636. uid_t const old_uid = getuid();
  2637. gid_t const old_gid = getgid();
  2638. if (old_uid != 0)
  2639. return true;
  2640. struct passwd *pw = getpwnam(toUser.c_str());
  2641. if (pw == NULL)
  2642. return _error->Error("No user %s, can not drop rights", toUser.c_str());
  2643. // Do not change the order here, it might break things
  2644. // Get rid of all our supplementary groups first
  2645. if (setgroups(1, &pw->pw_gid))
  2646. return _error->Errno("setgroups", "Failed to setgroups");
  2647. // Now change the group ids to the new user
  2648. #ifdef HAVE_SETRESGID
  2649. if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
  2650. return _error->Errno("setresgid", "Failed to set new group ids");
  2651. #else
  2652. if (setegid(pw->pw_gid) != 0)
  2653. return _error->Errno("setegid", "Failed to setegid");
  2654. if (setgid(pw->pw_gid) != 0)
  2655. return _error->Errno("setgid", "Failed to setgid");
  2656. #endif
  2657. // Change the user ids to the new user
  2658. #ifdef HAVE_SETRESUID
  2659. if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
  2660. return _error->Errno("setresuid", "Failed to set new user ids");
  2661. #else
  2662. if (setuid(pw->pw_uid) != 0)
  2663. return _error->Errno("setuid", "Failed to setuid");
  2664. if (seteuid(pw->pw_uid) != 0)
  2665. return _error->Errno("seteuid", "Failed to seteuid");
  2666. #endif
  2667. // disabled by default as fakeroot doesn't implement getgroups currently (#806521)
  2668. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Groups", false) == true)
  2669. {
  2670. // Verify that the user isn't still in any supplementary groups
  2671. long const ngroups_max = sysconf(_SC_NGROUPS_MAX);
  2672. std::unique_ptr<gid_t[]> gidlist(new gid_t[ngroups_max]);
  2673. if (unlikely(gidlist == NULL))
  2674. return _error->Error("Allocation of a list of size %lu for getgroups failed", ngroups_max);
  2675. ssize_t gidlist_nr;
  2676. if ((gidlist_nr = getgroups(ngroups_max, gidlist.get())) < 0)
  2677. return _error->Errno("getgroups", "Could not get new groups (%lu)", ngroups_max);
  2678. for (ssize_t i = 0; i < gidlist_nr; ++i)
  2679. if (gidlist[i] != pw->pw_gid)
  2680. return _error->Error("Could not switch group, user %s is still in group %d", toUser.c_str(), gidlist[i]);
  2681. }
  2682. // enabled by default as all fakeroot-lookalikes should fake that accordingly
  2683. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::IDs", true) == true)
  2684. {
  2685. // Verify that gid, egid, uid, and euid changed
  2686. if (getgid() != pw->pw_gid)
  2687. return _error->Error("Could not switch group");
  2688. if (getegid() != pw->pw_gid)
  2689. return _error->Error("Could not switch effective group");
  2690. if (getuid() != pw->pw_uid)
  2691. return _error->Error("Could not switch user");
  2692. if (geteuid() != pw->pw_uid)
  2693. return _error->Error("Could not switch effective user");
  2694. #ifdef HAVE_GETRESUID
  2695. // verify that the saved set-user-id was changed as well
  2696. uid_t ruid = 0;
  2697. uid_t euid = 0;
  2698. uid_t suid = 0;
  2699. if (getresuid(&ruid, &euid, &suid))
  2700. return _error->Errno("getresuid", "Could not get saved set-user-ID");
  2701. if (suid != pw->pw_uid)
  2702. return _error->Error("Could not switch saved set-user-ID");
  2703. #endif
  2704. #ifdef HAVE_GETRESGID
  2705. // verify that the saved set-group-id was changed as well
  2706. gid_t rgid = 0;
  2707. gid_t egid = 0;
  2708. gid_t sgid = 0;
  2709. if (getresgid(&rgid, &egid, &sgid))
  2710. return _error->Errno("getresuid", "Could not get saved set-group-ID");
  2711. if (sgid != pw->pw_gid)
  2712. return _error->Error("Could not switch saved set-group-ID");
  2713. #endif
  2714. }
  2715. // disabled as fakeroot doesn't forbid (by design) (re)gaining root from unprivileged
  2716. if (VerifySandboxing == true || _config->FindB("APT::Sandbox::Verify::Regain", false) == true)
  2717. {
  2718. // Check that uid and gid changes do not work anymore
  2719. if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
  2720. return _error->Error("Could restore a gid to root, privilege dropping did not work");
  2721. if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
  2722. return _error->Error("Could restore a uid to root, privilege dropping did not work");
  2723. }
  2724. return true;
  2725. }
  2726. /*}}}*/