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