fileutl.cc 67 KB

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