]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/gpgv.cc
ExecGPGV: Rework file removal on exit()
[apt.git] / apt-pkg / contrib / gpgv.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Include Files /*{{{*/
3 #include<config.h>
4
5 #include<apt-pkg/configuration.h>
6 #include<apt-pkg/error.h>
7 #include<apt-pkg/strutl.h>
8 #include<apt-pkg/fileutl.h>
9 #include<apt-pkg/gpgv.h>
10
11 #include <errno.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <fcntl.h>
16 #include <sys/wait.h>
17 #include <unistd.h>
18 #include <stddef.h>
19
20 #include <algorithm>
21 #include <iostream>
22 #include <string>
23 #include <vector>
24
25 #include <apti18n.h>
26 /*}}}*/
27 static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
28 {
29 std::string out;
30 std::string tmpdir = GetTempDir();
31 strprintf(out, "%s/%s.XXXXXX", tmpdir.c_str(), basename);
32 return strdup(out.c_str());
33 }
34 /*}}}*/
35 // ExecGPGV - returns the command needed for verify /*{{{*/
36 // ---------------------------------------------------------------------
37 /* Generating the commandline for calling gpg is somehow complicated as
38 we need to add multiple keyrings and user supplied options.
39 Also, as gpg has no options to enforce a certain reduced style of
40 clear-signed files (=the complete content of the file is signed and
41 the content isn't encoded) we do a divide and conquer approach here
42 and split up the clear-signed file in message and signature for gpg.
43 And as a cherry on the cake, we use our apt-key wrapper to do part
44 of the lifting in regards to merging keyrings. Fun for the whole family.
45 */
46 void ExecGPGV(std::string const &File, std::string const &FileGPG,
47 int const &statusfd, int fd[2], std::string const &key)
48 {
49 #define EINTERNAL 111
50 std::string const aptkey = _config->Find("Dir::Bin::apt-key", "/usr/bin/apt-key");
51
52 bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
53 struct exiter {
54 std::vector<const char *> files;
55 void operator ()(int code) APT_NORETURN {
56 std::for_each(files.begin(), files.end(), unlink);
57 exit(code);
58 }
59 } local_exit;
60
61
62 std::vector<const char *> Args;
63 Args.reserve(10);
64
65 Args.push_back(aptkey.c_str());
66 Args.push_back("--quiet");
67 Args.push_back("--readonly");
68 if (key.empty() == false)
69 {
70 if (key[0] == '/')
71 {
72 Args.push_back("--keyring");
73 Args.push_back(key.c_str());
74 }
75 else
76 {
77 Args.push_back("--keyid");
78 Args.push_back(key.c_str());
79 }
80 }
81 Args.push_back("verify");
82
83 char statusfdstr[10];
84 if (statusfd != -1)
85 {
86 Args.push_back("--status-fd");
87 snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
88 Args.push_back(statusfdstr);
89 }
90
91 Configuration::Item const *Opts;
92 Opts = _config->Tree("Acquire::gpgv::Options");
93 if (Opts != 0)
94 {
95 Opts = Opts->Child;
96 for (; Opts != 0; Opts = Opts->Next)
97 {
98 if (Opts->Value.empty() == true)
99 continue;
100 Args.push_back(Opts->Value.c_str());
101 }
102 }
103
104 enum { DETACHED, CLEARSIGNED } releaseSignature = (FileGPG != File) ? DETACHED : CLEARSIGNED;
105 std::vector<std::string> dataHeader;
106 char * sig = NULL;
107 char * data = NULL;
108
109 if (releaseSignature == DETACHED)
110 {
111 Args.push_back(FileGPG.c_str());
112 Args.push_back(File.c_str());
113 }
114 else // clear-signed file
115 {
116 sig = GenerateTemporaryFileTemplate("apt.sig");
117 data = GenerateTemporaryFileTemplate("apt.data");
118 if (sig == NULL || data == NULL)
119 {
120 ioprintf(std::cerr, "Couldn't create tempfile names for splitting up %s", File.c_str());
121 local_exit(EINTERNAL);
122 }
123
124 int const sigFd = mkstemp(sig);
125 int const dataFd = mkstemp(data);
126 if (dataFd != -1)
127 local_exit.files.push_back(data);
128 if (sigFd != -1)
129 local_exit.files.push_back(sig);
130 if (sigFd == -1 || dataFd == -1)
131 {
132 ioprintf(std::cerr, "Couldn't create tempfiles for splitting up %s", File.c_str());
133 local_exit(EINTERNAL);
134 }
135
136 FileFd signature;
137 signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
138 FileFd message;
139 message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
140
141 if (signature.Failed() == true || message.Failed() == true ||
142 SplitClearSignedFile(File, &message, &dataHeader, &signature) == false)
143 {
144 ioprintf(std::cerr, "Splitting up %s into data and signature failed", File.c_str());
145 local_exit(112);
146 }
147 Args.push_back(sig);
148 Args.push_back(data);
149 }
150
151 Args.push_back(NULL);
152
153 if (Debug == true)
154 {
155 std::clog << "Preparing to exec: ";
156 for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
157 std::clog << " " << *a;
158 std::clog << std::endl;
159 }
160
161 if (statusfd != -1)
162 {
163 int const nullfd = open("/dev/null", O_WRONLY);
164 close(fd[0]);
165 // Redirect output to /dev/null; we read from the status fd
166 if (statusfd != STDOUT_FILENO)
167 dup2(nullfd, STDOUT_FILENO);
168 if (statusfd != STDERR_FILENO)
169 dup2(nullfd, STDERR_FILENO);
170 // Redirect the pipe to the status fd (3)
171 dup2(fd[1], statusfd);
172
173 putenv((char *)"LANG=");
174 putenv((char *)"LC_ALL=");
175 putenv((char *)"LC_MESSAGES=");
176 }
177
178 if (releaseSignature == DETACHED)
179 {
180 execvp(Args[0], (char **) &Args[0]);
181 ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
182 local_exit(EINTERNAL);
183 }
184 else
185 {
186 // for clear-signed files we have created tempfiles we have to clean up
187 // and we do an additional check, so fork yet another time …
188 pid_t pid = ExecFork();
189 if(pid < 0) {
190 ioprintf(std::cerr, "Fork failed for %s to check %s", Args[0], File.c_str());
191 local_exit(EINTERNAL);
192 }
193 if(pid == 0)
194 {
195 if (statusfd != -1)
196 dup2(fd[1], statusfd);
197 execvp(Args[0], (char **) &Args[0]);
198 ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
199 local_exit(EINTERNAL);
200 }
201
202 // Wait and collect the error code - taken from WaitPid as we need the exact Status
203 int Status;
204 while (waitpid(pid,&Status,0) != pid)
205 {
206 if (errno == EINTR)
207 continue;
208 ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "apt-key");
209 local_exit(EINTERNAL);
210 }
211
212 // check if it exit'ed normally …
213 if (WIFEXITED(Status) == false)
214 {
215 ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "apt-key");
216 local_exit(EINTERNAL);
217 }
218
219 // … and with a good exit code
220 if (WEXITSTATUS(Status) != 0)
221 {
222 ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
223 local_exit(WEXITSTATUS(Status));
224 }
225
226 // everything fine
227 local_exit(0);
228 }
229 local_exit(EINTERNAL); // unreachable safe-guard
230 }
231 /*}}}*/
232 // SplitClearSignedFile - split message into data/signature /*{{{*/
233 bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
234 std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
235 {
236 FILE *in = fopen(InFile.c_str(), "r");
237 if (in == NULL)
238 return _error->Errno("fopen", "can not open %s", InFile.c_str());
239
240 bool found_message_start = false;
241 bool found_message_end = false;
242 bool skip_until_empty_line = false;
243 bool found_signature = false;
244 bool first_line = true;
245
246 char *buf = NULL;
247 size_t buf_size = 0;
248 while (getline(&buf, &buf_size, in) != -1)
249 {
250 _strrstrip(buf);
251 if (found_message_start == false)
252 {
253 if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
254 {
255 found_message_start = true;
256 skip_until_empty_line = true;
257 }
258 }
259 else if (skip_until_empty_line == true)
260 {
261 if (strlen(buf) == 0)
262 skip_until_empty_line = false;
263 // save "Hash" Armor Headers, others aren't allowed
264 else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
265 ContentHeader->push_back(buf);
266 }
267 else if (found_signature == false)
268 {
269 if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
270 {
271 found_signature = true;
272 found_message_end = true;
273 if (SignatureFile != NULL)
274 {
275 SignatureFile->Write(buf, strlen(buf));
276 SignatureFile->Write("\n", 1);
277 }
278 }
279 else if (found_message_end == false) // we are in the message block
280 {
281 // we don't have any fields which need dash-escaped,
282 // but implementations are free to encode all lines …
283 char const * dashfree = buf;
284 if (strncmp(dashfree, "- ", 2) == 0)
285 dashfree += 2;
286 if(first_line == true) // first line does not need a newline
287 first_line = false;
288 else if (ContentFile != NULL)
289 ContentFile->Write("\n", 1);
290 else
291 continue;
292 if (ContentFile != NULL)
293 ContentFile->Write(dashfree, strlen(dashfree));
294 }
295 }
296 else if (found_signature == true)
297 {
298 if (SignatureFile != NULL)
299 {
300 SignatureFile->Write(buf, strlen(buf));
301 SignatureFile->Write("\n", 1);
302 }
303 if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
304 found_signature = false; // look for other signatures
305 }
306 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
307 }
308 fclose(in);
309 if (buf != NULL)
310 free(buf);
311
312 if (found_signature == true)
313 return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
314
315 // if we haven't found any of them, this an unsigned file,
316 // so don't generate an error, but splitting was unsuccessful none-the-less
317 if (first_line == true && found_message_start == false && found_message_end == false)
318 return false;
319 // otherwise one missing indicates a syntax error
320 else if (first_line == true || found_message_start == false || found_message_end == false)
321 return _error->Error("Splitting of file %s failed as it doesn't contain all expected parts %i %i %i", InFile.c_str(), first_line, found_message_start, found_message_end);
322
323 return true;
324 }
325 /*}}}*/
326 bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
327 {
328 char * const message = GenerateTemporaryFileTemplate("fileutl.message");
329 int const messageFd = mkstemp(message);
330 if (messageFd == -1)
331 {
332 free(message);
333 return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
334 }
335 // we have the fd, thats enough for us
336 unlink(message);
337 free(message);
338
339 MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
340 if (MessageFile.Failed() == true)
341 return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
342
343 _error->PushToStack();
344 bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
345 bool const errorDone = _error->PendingError();
346 _error->MergeWithStack();
347 if (splitDone == false)
348 {
349 MessageFile.Close();
350
351 if (errorDone == true)
352 return false;
353
354 // we deal with an unsigned file
355 MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
356 }
357 else // clear-signed
358 {
359 if (MessageFile.Seek(0) == false)
360 return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
361 }
362
363 return MessageFile.Failed() == false;
364 }
365 /*}}}*/