debsystem.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: debsystem.cc,v 1.4 2004/01/26 17:01:53 mdz Exp $
  4. /* ######################################################################
  5. System - Abstraction for running on different systems.
  6. Basic general structure..
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include <config.h>
  11. #include <apt-pkg/debsystem.h>
  12. #include <apt-pkg/debversion.h>
  13. #include <apt-pkg/debindexfile.h>
  14. #include <apt-pkg/dpkgpm.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/error.h>
  17. #include <apt-pkg/fileutl.h>
  18. #include <apt-pkg/pkgcache.h>
  19. #include <apt-pkg/cacheiterators.h>
  20. #include <algorithm>
  21. #include <ctype.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <string>
  25. #include <vector>
  26. #include <unistd.h>
  27. #include <dirent.h>
  28. #include <errno.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <sys/wait.h>
  32. #include <fcntl.h>
  33. #include <apti18n.h>
  34. /*}}}*/
  35. using std::string;
  36. debSystem debSys;
  37. class APT_HIDDEN debSystemPrivate {
  38. public:
  39. debSystemPrivate() : LockFD(-1), LockCount(0), StatusFile(0)
  40. {
  41. }
  42. // For locking support
  43. int LockFD;
  44. unsigned LockCount;
  45. debStatusIndex *StatusFile;
  46. };
  47. // System::debSystem - Constructor /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* */
  50. debSystem::debSystem() : pkgSystem("Debian dpkg interface", &debVS), d(new debSystemPrivate())
  51. {
  52. }
  53. /*}}}*/
  54. // System::~debSystem - Destructor /*{{{*/
  55. // ---------------------------------------------------------------------
  56. /* */
  57. debSystem::~debSystem()
  58. {
  59. delete d->StatusFile;
  60. delete d;
  61. }
  62. /*}}}*/
  63. // System::Lock - Get the lock /*{{{*/
  64. // ---------------------------------------------------------------------
  65. /* This mirrors the operations dpkg does when it starts up. Note the
  66. checking of the updates directory. */
  67. bool debSystem::Lock()
  68. {
  69. // Disable file locking
  70. if (_config->FindB("Debug::NoLocking",false) == true || d->LockCount > 1)
  71. {
  72. d->LockCount++;
  73. return true;
  74. }
  75. // Create the lockfile
  76. string AdminDir = flNotFile(_config->FindFile("Dir::State::status"));
  77. d->LockFD = GetLock(AdminDir + "lock");
  78. if (d->LockFD == -1)
  79. {
  80. if (errno == EACCES || errno == EAGAIN)
  81. return _error->Error(_("Unable to lock the administration directory (%s), "
  82. "is another process using it?"),AdminDir.c_str());
  83. else
  84. return _error->Error(_("Unable to lock the administration directory (%s), "
  85. "are you root?"),AdminDir.c_str());
  86. }
  87. // See if we need to abort with a dirty journal
  88. if (CheckUpdates() == true)
  89. {
  90. close(d->LockFD);
  91. d->LockFD = -1;
  92. const char *cmd;
  93. if (getenv("SUDO_USER") != NULL)
  94. cmd = "sudo dpkg --configure -a";
  95. else
  96. cmd = "dpkg --configure -a";
  97. // TRANSLATORS: the %s contains the recovery command, usually
  98. // dpkg --configure -a
  99. return _error->Error(_("dpkg was interrupted, you must manually "
  100. "run '%s' to correct the problem. "), cmd);
  101. }
  102. d->LockCount++;
  103. return true;
  104. }
  105. /*}}}*/
  106. // System::UnLock - Drop a lock /*{{{*/
  107. // ---------------------------------------------------------------------
  108. /* */
  109. bool debSystem::UnLock(bool NoErrors)
  110. {
  111. if (d->LockCount == 0 && NoErrors == true)
  112. return false;
  113. if (d->LockCount < 1)
  114. return _error->Error(_("Not locked"));
  115. if (--d->LockCount == 0)
  116. {
  117. close(d->LockFD);
  118. d->LockCount = 0;
  119. }
  120. return true;
  121. }
  122. /*}}}*/
  123. // System::CheckUpdates - Check if the updates dir is dirty /*{{{*/
  124. // ---------------------------------------------------------------------
  125. /* This does a check of the updates directory (dpkg journal) to see if it has
  126. any entries in it. */
  127. bool debSystem::CheckUpdates()
  128. {
  129. // Check for updates.. (dirty)
  130. string File = flNotFile(_config->FindFile("Dir::State::status")) + "updates/";
  131. DIR *DirP = opendir(File.c_str());
  132. if (DirP == 0)
  133. return false;
  134. /* We ignore any files that are not all digits, this skips .,.. and
  135. some tmp files dpkg will leave behind.. */
  136. bool Damaged = false;
  137. for (struct dirent *Ent = readdir(DirP); Ent != 0; Ent = readdir(DirP))
  138. {
  139. Damaged = true;
  140. for (unsigned int I = 0; Ent->d_name[I] != 0; I++)
  141. {
  142. // Check if its not a digit..
  143. if (isdigit(Ent->d_name[I]) == 0)
  144. {
  145. Damaged = false;
  146. break;
  147. }
  148. }
  149. if (Damaged == true)
  150. break;
  151. }
  152. closedir(DirP);
  153. return Damaged;
  154. }
  155. /*}}}*/
  156. // System::CreatePM - Create the underlying package manager /*{{{*/
  157. // ---------------------------------------------------------------------
  158. /* */
  159. pkgPackageManager *debSystem::CreatePM(pkgDepCache *Cache) const
  160. {
  161. return new pkgDPkgPM(Cache);
  162. }
  163. /*}}}*/
  164. // System::Initialize - Setup the configuration space.. /*{{{*/
  165. // ---------------------------------------------------------------------
  166. /* These are the Debian specific configuration variables.. */
  167. static std::string getDpkgStatusLocation(Configuration &Cnf) {
  168. auto const cnfstatedir = Cnf.Find("Dir::State", "var/lib/apt/");
  169. std::string statedir;
  170. if (APT::String::Endswith(cnfstatedir, "/apt/"))
  171. statedir.assign(cnfstatedir, 0, cnfstatedir.length() - 5);
  172. else if (APT::String::Endswith(cnfstatedir, "/apt"))
  173. statedir.assign(cnfstatedir, 0, cnfstatedir.length() - 4);
  174. if (statedir.empty())
  175. Cnf.Set("Dir::State", "var/lib/dpkg");
  176. else
  177. Cnf.Set("Dir::State", flCombine(statedir, "dpkg"));
  178. auto const cnfrootdir = Cnf.Find("RootDir");
  179. if (Cnf.Exists("RootDir") == true)
  180. Cnf.Set("RootDir", "");
  181. Cnf.Set("Dir::State::status", "status");
  182. auto const statusfile = Cnf.FindFile("Dir::State::status");
  183. if (cnfrootdir.empty() == false)
  184. Cnf.Set("RootDir", cnfrootdir);
  185. Cnf.Set("Dir::State", cnfstatedir);
  186. return statusfile;
  187. }
  188. bool debSystem::Initialize(Configuration &Cnf)
  189. {
  190. /* These really should be jammed into a generic 'Local Database' engine
  191. which is yet to be determined. The functions in pkgcachegen should
  192. be the only users of these */
  193. Cnf.CndSet("Dir::State::extended_states", "extended_states");
  194. if (Cnf.Exists("Dir::State::status") == false)
  195. Cnf.Set("Dir::State::status", getDpkgStatusLocation(Cnf));
  196. Cnf.CndSet("Dir::Bin::dpkg","/usr/bin/dpkg");
  197. if (d->StatusFile) {
  198. delete d->StatusFile;
  199. d->StatusFile = 0;
  200. }
  201. return true;
  202. }
  203. /*}}}*/
  204. // System::ArchiveSupported - Is a file format supported /*{{{*/
  205. // ---------------------------------------------------------------------
  206. /* The standard name for a deb is 'deb'.. There are no separate versions
  207. of .deb to worry about.. */
  208. APT_PURE bool debSystem::ArchiveSupported(const char *Type)
  209. {
  210. if (strcmp(Type,"deb") == 0)
  211. return true;
  212. return false;
  213. }
  214. /*}}}*/
  215. // System::Score - Determine how 'Debiany' this sys is.. /*{{{*/
  216. // ---------------------------------------------------------------------
  217. /* We check some files that are sure tell signs of this being a Debian
  218. System.. */
  219. signed debSystem::Score(Configuration const &Cnf)
  220. {
  221. signed Score = 0;
  222. if (FileExists(Cnf.FindFile("Dir::State::status","/var/lib/dpkg/status")) == true)
  223. Score += 10;
  224. if (FileExists(Cnf.Find("Dir::Bin::dpkg","/usr/bin/dpkg")) == true)
  225. Score += 10;
  226. if (FileExists("/etc/debian_version") == true)
  227. Score += 10;
  228. return Score;
  229. }
  230. /*}}}*/
  231. // System::AddStatusFiles - Register the status files /*{{{*/
  232. // ---------------------------------------------------------------------
  233. /* */
  234. bool debSystem::AddStatusFiles(std::vector<pkgIndexFile *> &List)
  235. {
  236. if (d->StatusFile == 0)
  237. d->StatusFile = new debStatusIndex(_config->FindFile("Dir::State::status"));
  238. List.push_back(d->StatusFile);
  239. return true;
  240. }
  241. /*}}}*/
  242. // System::FindIndex - Get an index file for status files /*{{{*/
  243. // ---------------------------------------------------------------------
  244. /* */
  245. bool debSystem::FindIndex(pkgCache::PkgFileIterator File,
  246. pkgIndexFile *&Found) const
  247. {
  248. if (d->StatusFile == 0)
  249. return false;
  250. if (d->StatusFile->FindInCache(*File.Cache()) == File)
  251. {
  252. Found = d->StatusFile;
  253. return true;
  254. }
  255. return false;
  256. }
  257. /*}}}*/
  258. std::string debSystem::GetDpkgExecutable() /*{{{*/
  259. {
  260. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  261. string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
  262. size_t dpkgChrootLen = dpkgChrootDir.length();
  263. if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
  264. {
  265. if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
  266. --dpkgChrootLen;
  267. Tmp = Tmp.substr(dpkgChrootLen);
  268. }
  269. return Tmp;
  270. }
  271. /*}}}*/
  272. std::vector<std::string> debSystem::GetDpkgBaseCommand() /*{{{*/
  273. {
  274. // Generate the base argument list for dpkg
  275. std::vector<std::string> Args = { GetDpkgExecutable() };
  276. // Stick in any custom dpkg options
  277. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  278. if (Opts != 0)
  279. {
  280. Opts = Opts->Child;
  281. for (; Opts != 0; Opts = Opts->Next)
  282. {
  283. if (Opts->Value.empty() == true)
  284. continue;
  285. Args.push_back(Opts->Value);
  286. }
  287. }
  288. return Args;
  289. }
  290. /*}}}*/
  291. void debSystem::DpkgChrootDirectory() /*{{{*/
  292. {
  293. std::string const chrootDir = _config->FindDir("DPkg::Chroot-Directory");
  294. if (chrootDir == "/")
  295. return;
  296. std::cerr << "Chrooting into " << chrootDir << std::endl;
  297. if (chroot(chrootDir.c_str()) != 0)
  298. _exit(100);
  299. if (chdir("/") != 0)
  300. _exit(100);
  301. }
  302. /*}}}*/
  303. pid_t debSystem::ExecDpkg(std::vector<std::string> const &sArgs, int * const inputFd, int * const outputFd, bool const DiscardOutput)/*{{{*/
  304. {
  305. std::vector<const char *> Args(sArgs.size(), NULL);
  306. std::transform(sArgs.begin(), sArgs.end(), Args.begin(), [](std::string const &s) { return s.c_str(); });
  307. Args.push_back(NULL);
  308. int external[2] = {-1, -1};
  309. if (inputFd != nullptr || outputFd != nullptr)
  310. if (pipe(external) != 0)
  311. {
  312. _error->WarningE("dpkg", "Can't create IPC pipe for dpkg call");
  313. return -1;
  314. }
  315. pid_t const dpkg = ExecFork();
  316. if (dpkg == 0) {
  317. int const nullfd = open("/dev/null", O_RDONLY);
  318. if (inputFd == nullptr)
  319. dup2(nullfd, STDIN_FILENO);
  320. else
  321. {
  322. close(external[1]);
  323. dup2(external[0], STDIN_FILENO);
  324. }
  325. if (outputFd == nullptr)
  326. dup2(nullfd, STDOUT_FILENO);
  327. else
  328. {
  329. close(external[0]);
  330. dup2(external[1], STDOUT_FILENO);
  331. }
  332. if (DiscardOutput == true)
  333. dup2(nullfd, STDERR_FILENO);
  334. debSystem::DpkgChrootDirectory();
  335. execvp(Args[0], (char**) &Args[0]);
  336. _error->WarningE("dpkg", "Can't execute dpkg!");
  337. _exit(100);
  338. }
  339. if (outputFd != nullptr)
  340. {
  341. close(external[1]);
  342. *outputFd = external[0];
  343. }
  344. else if (inputFd != nullptr)
  345. {
  346. close(external[0]);
  347. *inputFd = external[1];
  348. }
  349. return dpkg;
  350. }
  351. /*}}}*/
  352. bool debSystem::SupportsMultiArch() /*{{{*/
  353. {
  354. std::vector<std::string> Args = GetDpkgBaseCommand();
  355. Args.push_back("--assert-multi-arch");
  356. pid_t const dpkgAssertMultiArch = ExecDpkg(Args, nullptr, nullptr, true);
  357. if (dpkgAssertMultiArch > 0)
  358. {
  359. int Status = 0;
  360. while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
  361. {
  362. if (errno == EINTR)
  363. continue;
  364. _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
  365. break;
  366. }
  367. if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
  368. return true;
  369. }
  370. return false;
  371. }
  372. /*}}}*/
  373. std::vector<std::string> debSystem::SupportedArchitectures() /*{{{*/
  374. {
  375. std::vector<std::string> archs;
  376. {
  377. string const arch = _config->Find("APT::Architecture");
  378. if (arch.empty() == false)
  379. archs.push_back(std::move(arch));
  380. }
  381. std::vector<std::string> sArgs = GetDpkgBaseCommand();
  382. sArgs.push_back("--print-foreign-architectures");
  383. int outputFd = -1;
  384. pid_t const dpkgMultiArch = ExecDpkg(sArgs, nullptr, &outputFd, true);
  385. if (dpkgMultiArch == -1)
  386. return archs;
  387. FILE *dpkg = fdopen(outputFd, "r");
  388. if(dpkg != NULL) {
  389. char* buf = NULL;
  390. size_t bufsize = 0;
  391. while (getline(&buf, &bufsize, dpkg) != -1)
  392. {
  393. char* tok_saveptr;
  394. char* arch = strtok_r(buf, " ", &tok_saveptr);
  395. while (arch != NULL) {
  396. for (; isspace_ascii(*arch) != 0; ++arch);
  397. if (arch[0] != '\0') {
  398. char const* archend = arch;
  399. for (; isspace_ascii(*archend) == 0 && *archend != '\0'; ++archend);
  400. string a(arch, (archend - arch));
  401. if (std::find(archs.begin(), archs.end(), a) == archs.end())
  402. archs.push_back(a);
  403. }
  404. arch = strtok_r(NULL, " ", &tok_saveptr);
  405. }
  406. }
  407. free(buf);
  408. fclose(dpkg);
  409. }
  410. ExecWait(dpkgMultiArch, "dpkg --print-foreign-architectures", true);
  411. return archs;
  412. }
  413. /*}}}*/