fileutl.cc 67 KB

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