]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/gpgv.cc
4247a1562073e983901cb997ba28d641810b3c51
[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
179 // We have created tempfiles we have to clean up
180 // and we do an additional check, so fork yet another time …
181 pid_t pid = ExecFork();
182 if(pid < 0) {
183 ioprintf(std::cerr, "Fork failed for %s to check %s", Args[0], File.c_str());
184 local_exit(EINTERNAL);
185 }
186 if(pid == 0)
187 {
188 if (statusfd != -1)
189 dup2(fd[1], statusfd);
190 execvp(Args[0], (char **) &Args[0]);
191 ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
192 local_exit(EINTERNAL);
193 }
194
195 // Wait and collect the error code - taken from WaitPid as we need the exact Status
196 int Status;
197 while (waitpid(pid,&Status,0) != pid)
198 {
199 if (errno == EINTR)
200 continue;
201 ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "apt-key");
202 local_exit(EINTERNAL);
203 }
204
205 // check if it exit'ed normally …
206 if (WIFEXITED(Status) == false)
207 {
208 ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "apt-key");
209 local_exit(EINTERNAL);
210 }
211
212 // … and with a good exit code
213 if (WEXITSTATUS(Status) != 0)
214 {
215 ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
216 local_exit(WEXITSTATUS(Status));
217 }
218
219 // everything fine
220 local_exit(0);
221 }
222 /*}}}*/
223 // SplitClearSignedFile - split message into data/signature /*{{{*/
224 bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
225 std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
226 {
227 FILE *in = fopen(InFile.c_str(), "r");
228 if (in == NULL)
229 return _error->Errno("fopen", "can not open %s", InFile.c_str());
230
231 bool found_message_start = false;
232 bool found_message_end = false;
233 bool skip_until_empty_line = false;
234 bool found_signature = false;
235 bool first_line = true;
236
237 char *buf = NULL;
238 size_t buf_size = 0;
239 while (getline(&buf, &buf_size, in) != -1)
240 {
241 _strrstrip(buf);
242 if (found_message_start == false)
243 {
244 if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
245 {
246 found_message_start = true;
247 skip_until_empty_line = true;
248 }
249 }
250 else if (skip_until_empty_line == true)
251 {
252 if (strlen(buf) == 0)
253 skip_until_empty_line = false;
254 // save "Hash" Armor Headers, others aren't allowed
255 else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
256 ContentHeader->push_back(buf);
257 }
258 else if (found_signature == false)
259 {
260 if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
261 {
262 found_signature = true;
263 found_message_end = true;
264 if (SignatureFile != NULL)
265 {
266 SignatureFile->Write(buf, strlen(buf));
267 SignatureFile->Write("\n", 1);
268 }
269 }
270 else if (found_message_end == false) // we are in the message block
271 {
272 // we don't have any fields which need dash-escaped,
273 // but implementations are free to encode all lines …
274 char const * dashfree = buf;
275 if (strncmp(dashfree, "- ", 2) == 0)
276 dashfree += 2;
277 if(first_line == true) // first line does not need a newline
278 first_line = false;
279 else if (ContentFile != NULL)
280 ContentFile->Write("\n", 1);
281 else
282 continue;
283 if (ContentFile != NULL)
284 ContentFile->Write(dashfree, strlen(dashfree));
285 }
286 }
287 else if (found_signature == true)
288 {
289 if (SignatureFile != NULL)
290 {
291 SignatureFile->Write(buf, strlen(buf));
292 SignatureFile->Write("\n", 1);
293 }
294 if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
295 found_signature = false; // look for other signatures
296 }
297 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
298 }
299 fclose(in);
300 if (buf != NULL)
301 free(buf);
302
303 if (found_signature == true)
304 return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
305
306 // if we haven't found any of them, this an unsigned file,
307 // so don't generate an error, but splitting was unsuccessful none-the-less
308 if (first_line == true && found_message_start == false && found_message_end == false)
309 return false;
310 // otherwise one missing indicates a syntax error
311 else if (first_line == true || found_message_start == false || found_message_end == false)
312 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);
313
314 return true;
315 }
316 /*}}}*/
317 bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
318 {
319 char * const message = GenerateTemporaryFileTemplate("fileutl.message");
320 int const messageFd = mkstemp(message);
321 if (messageFd == -1)
322 {
323 free(message);
324 return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
325 }
326 // we have the fd, thats enough for us
327 unlink(message);
328 free(message);
329
330 MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
331 if (MessageFile.Failed() == true)
332 return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
333
334 _error->PushToStack();
335 bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
336 bool const errorDone = _error->PendingError();
337 _error->MergeWithStack();
338 if (splitDone == false)
339 {
340 MessageFile.Close();
341
342 if (errorDone == true)
343 return false;
344
345 // we deal with an unsigned file
346 MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
347 }
348 else // clear-signed
349 {
350 if (MessageFile.Seek(0) == false)
351 return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
352 }
353
354 return MessageFile.Failed() == false;
355 }
356 /*}}}*/