1 // -*- mode: cpp; mode: fold -*-
2 // Include Files /*{{{*/
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>
29 static char * GenerateTemporaryFileTemplate(const char *basename
) /*{{{*/
32 std::string tmpdir
= GetTempDir();
33 strprintf(out
, "%s/%s.XXXXXX", tmpdir
.c_str(), basename
);
34 return strdup(out
.c_str());
37 // ExecGPGV - returns the command needed for verify /*{{{*/
38 // ---------------------------------------------------------------------
39 /* Generating the commandline for calling gpg is somehow complicated as
40 we need to add multiple keyrings and user supplied options.
41 Also, as gpg has no options to enforce a certain reduced style of
42 clear-signed files (=the complete content of the file is signed and
43 the content isn't encoded) we do a divide and conquer approach here
44 and split up the clear-signed file in message and signature for gpg.
45 And as a cherry on the cake, we use our apt-key wrapper to do part
46 of the lifting in regards to merging keyrings. Fun for the whole family.
48 static bool iovprintf(std::ostream
&out
, const char *format
,
49 va_list &args
, ssize_t
&size
) {
50 char *S
= (char*)malloc(size
);
51 ssize_t
const n
= vsnprintf(S
, size
, format
, args
);
52 if (n
> -1 && n
< size
) {
65 static void APT_PRINTF(4) apt_error(std::ostream
&outterm
, int const statusfd
, int fd
[2], const char *format
, ...)
67 std::ostringstream outstr
;
68 std::ostream
&out
= (statusfd
== -1) ? outterm
: outstr
;
73 va_start(args
,format
);
74 ret
= iovprintf(out
, format
, args
, size
);
81 auto const errtag
= "[APTKEY:] ERROR ";
83 auto const errtext
= outstr
.str();
84 if (FileFd::Write(fd
[1], errtag
, strlen(errtag
)) == false ||
85 FileFd::Write(fd
[1], errtext
.data(), errtext
.size()) == false)
86 outterm
<< errtext
<< std::flush
;
89 void ExecGPGV(std::string
const &File
, std::string
const &FileGPG
,
90 int const &statusfd
, int fd
[2], std::string
const &key
)
93 std::string
const aptkey
= _config
->Find("Dir::Bin::apt-key", CMAKE_INSTALL_FULL_BINDIR
"/apt-key");
95 bool const Debug
= _config
->FindB("Debug::Acquire::gpgv", false);
97 std::vector
<const char *> files
;
98 void operator ()(int code
) APT_NORETURN
{
99 std::for_each(files
.begin(), files
.end(), unlink
);
105 std::vector
<const char *> Args
;
108 Args
.push_back(aptkey
.c_str());
109 Args
.push_back("--quiet");
110 Args
.push_back("--readonly");
111 if (key
.empty() == false)
115 Args
.push_back("--keyring");
116 Args
.push_back(key
.c_str());
120 Args
.push_back("--keyid");
121 Args
.push_back(key
.c_str());
124 Args
.push_back("verify");
126 char statusfdstr
[10];
129 Args
.push_back("--status-fd");
130 snprintf(statusfdstr
, sizeof(statusfdstr
), "%i", statusfd
);
131 Args
.push_back(statusfdstr
);
134 Configuration::Item
const *Opts
;
135 Opts
= _config
->Tree("Acquire::gpgv::Options");
139 for (; Opts
!= 0; Opts
= Opts
->Next
)
141 if (Opts
->Value
.empty() == true)
143 Args
.push_back(Opts
->Value
.c_str());
147 enum { DETACHED
, CLEARSIGNED
} releaseSignature
= (FileGPG
!= File
) ? DETACHED
: CLEARSIGNED
;
150 char * conf
= nullptr;
152 // Dump the configuration so apt-key picks up the correct Dir values
154 conf
= GenerateTemporaryFileTemplate("apt.conf");
155 if (conf
== nullptr) {
156 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfile names for passing config to apt-key");
157 local_exit(EINTERNAL
);
159 int confFd
= mkstemp(conf
);
161 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create temporary file %s for passing config to apt-key", conf
);
162 local_exit(EINTERNAL
);
164 local_exit
.files
.push_back(conf
);
166 std::ofstream
confStream(conf
);
168 _config
->Dump(confStream
);
170 setenv("APT_CONFIG", conf
, 1);
173 if (releaseSignature
== DETACHED
)
175 Args
.push_back(FileGPG
.c_str());
176 Args
.push_back(File
.c_str());
178 else // clear-signed file
180 sig
= GenerateTemporaryFileTemplate("apt.sig");
181 data
= GenerateTemporaryFileTemplate("apt.data");
182 if (sig
== NULL
|| data
== NULL
)
184 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfile names for splitting up %s", File
.c_str());
185 local_exit(EINTERNAL
);
188 int const sigFd
= mkstemp(sig
);
189 int const dataFd
= mkstemp(data
);
191 local_exit
.files
.push_back(data
);
193 local_exit
.files
.push_back(sig
);
194 if (sigFd
== -1 || dataFd
== -1)
196 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfiles for splitting up %s", File
.c_str());
197 local_exit(EINTERNAL
);
201 signature
.OpenDescriptor(sigFd
, FileFd::WriteOnly
, true);
203 message
.OpenDescriptor(dataFd
, FileFd::WriteOnly
, true);
205 if (signature
.Failed() == true || message
.Failed() == true ||
206 SplitClearSignedFile(File
, &message
, nullptr, &signature
) == false)
208 apt_error(std::cerr
, statusfd
, fd
, "Splitting up %s into data and signature failed", File
.c_str());
212 Args
.push_back(data
);
215 Args
.push_back(NULL
);
219 std::clog
<< "Preparing to exec: ";
220 for (std::vector
<const char *>::const_iterator a
= Args
.begin(); *a
!= NULL
; ++a
)
221 std::clog
<< " " << *a
;
222 std::clog
<< std::endl
;
227 int const nullfd
= open("/dev/null", O_WRONLY
);
229 // Redirect output to /dev/null; we read from the status fd
230 if (statusfd
!= STDOUT_FILENO
)
231 dup2(nullfd
, STDOUT_FILENO
);
232 if (statusfd
!= STDERR_FILENO
)
233 dup2(nullfd
, STDERR_FILENO
);
234 // Redirect the pipe to the status fd (3)
235 dup2(fd
[1], statusfd
);
237 putenv((char *)"LANG=");
238 putenv((char *)"LC_ALL=");
239 putenv((char *)"LC_MESSAGES=");
243 // We have created tempfiles we have to clean up
244 // and we do an additional check, so fork yet another time …
245 pid_t pid
= ExecFork();
247 apt_error(std::cerr
, statusfd
, fd
, "Fork failed for %s to check %s", Args
[0], File
.c_str());
248 local_exit(EINTERNAL
);
253 dup2(fd
[1], statusfd
);
254 execvp(Args
[0], (char **) &Args
[0]);
255 apt_error(std::cerr
, statusfd
, fd
, "Couldn't execute %s to check %s", Args
[0], File
.c_str());
256 local_exit(EINTERNAL
);
259 // Wait and collect the error code - taken from WaitPid as we need the exact Status
261 while (waitpid(pid
,&Status
,0) != pid
)
265 apt_error(std::cerr
, statusfd
, fd
, _("Waited for %s but it wasn't there"), "apt-key");
266 local_exit(EINTERNAL
);
269 // check if it exit'ed normally …
270 if (WIFEXITED(Status
) == false)
272 apt_error(std::cerr
, statusfd
, fd
, _("Sub-process %s exited unexpectedly"), "apt-key");
273 local_exit(EINTERNAL
);
276 // … and with a good exit code
277 if (WEXITSTATUS(Status
) != 0)
279 // we forward the statuscode, so don't generate a message on the fd in this case
280 apt_error(std::cerr
, -1, fd
, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status
));
281 local_exit(WEXITSTATUS(Status
));
288 // SplitClearSignedFile - split message into data/signature /*{{{*/
289 static int GetLineErrno(char **lineptr
, size_t *n
, FILE *stream
, std::string
const &InFile
)
294 result
= getline(lineptr
, n
, stream
);
297 _error
->Errno("getline", "Could not read from %s", InFile
.c_str());
303 bool SplitClearSignedFile(std::string
const &InFile
, FileFd
* const ContentFile
,
304 std::vector
<std::string
> * const ContentHeader
, FileFd
* const SignatureFile
)
306 FILE *in
= fopen(InFile
.c_str(), "r");
308 return _error
->Errno("fopen", "can not open %s", InFile
.c_str());
310 bool found_message_start
= false;
311 bool found_message_end
= false;
312 bool skip_until_empty_line
= false;
313 bool found_signature
= false;
314 bool first_line
= true;
315 bool signed_message_not_on_first_line
= false;
316 bool found_garbage
= false;
320 _error
->PushToStack();
321 while (GetLineErrno(&buf
, &buf_size
, in
, InFile
) != -1)
324 if (found_message_start
== false)
326 if (strcmp(buf
, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
328 found_message_start
= true;
329 skip_until_empty_line
= true;
332 signed_message_not_on_first_line
= found_garbage
= true;
334 else if (skip_until_empty_line
== true)
336 if (strlen(buf
) == 0)
337 skip_until_empty_line
= false;
338 // save "Hash" Armor Headers, others aren't allowed
339 else if (ContentHeader
!= NULL
&& strncmp(buf
, "Hash: ", strlen("Hash: ")) == 0)
340 ContentHeader
->push_back(buf
);
342 else if (found_signature
== false)
344 if (strcmp(buf
, "-----BEGIN PGP SIGNATURE-----") == 0)
346 found_signature
= true;
347 found_message_end
= true;
348 if (SignatureFile
!= NULL
)
350 SignatureFile
->Write(buf
, strlen(buf
));
351 SignatureFile
->Write("\n", 1);
354 else if (found_message_end
== false) // we are in the message block
356 // we don't have any fields which need dash-escaped,
357 // but implementations are free to encode all lines …
358 char const * dashfree
= buf
;
359 if (strncmp(dashfree
, "- ", 2) == 0)
361 if(first_line
== true) // first line does not need a newline
363 else if (ContentFile
!= NULL
)
364 ContentFile
->Write("\n", 1);
367 if (ContentFile
!= NULL
)
368 ContentFile
->Write(dashfree
, strlen(dashfree
));
371 found_garbage
= true;
373 else if (found_signature
== true)
375 if (SignatureFile
!= NULL
)
377 SignatureFile
->Write(buf
, strlen(buf
));
378 SignatureFile
->Write("\n", 1);
380 if (strcmp(buf
, "-----END PGP SIGNATURE-----") == 0)
381 found_signature
= false; // look for other signatures
383 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
385 found_garbage
= true;
391 // Flush the files. Errors will be checked below.
392 if (SignatureFile
!= nullptr)
393 SignatureFile
->Flush();
394 if (ContentFile
!= nullptr)
395 ContentFile
->Flush();
397 if (found_message_start
)
399 if (signed_message_not_on_first_line
)
400 _error
->Warning("Clearsigned file '%s' does not start with a signed message block.", InFile
.c_str());
401 else if (found_garbage
)
402 _error
->Warning("Clearsigned file '%s' contains unsigned lines.", InFile
.c_str());
405 // An error occured during reading - propagate it up
406 bool const hasErrored
= _error
->PendingError();
407 _error
->MergeWithStack();
411 if (found_signature
== true)
412 return _error
->Error("Signature in file %s wasn't closed", InFile
.c_str());
414 // if we haven't found any of them, this an unsigned file,
415 // so don't generate an error, but splitting was unsuccessful none-the-less
416 if (first_line
== true && found_message_start
== false && found_message_end
== false)
418 // otherwise one missing indicates a syntax error
419 else if (first_line
== true || found_message_start
== false || found_message_end
== false)
420 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
);
425 bool OpenMaybeClearSignedFile(std::string
const &ClearSignedFileName
, FileFd
&MessageFile
) /*{{{*/
427 char * const message
= GenerateTemporaryFileTemplate("fileutl.message");
428 int const messageFd
= mkstemp(message
);
432 return _error
->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName
.c_str());
434 // we have the fd, thats enough for us
438 MessageFile
.OpenDescriptor(messageFd
, FileFd::ReadWrite
| FileFd::BufferedWrite
, true);
439 if (MessageFile
.Failed() == true)
440 return _error
->Error("Couldn't open temporary file to work with %s", ClearSignedFileName
.c_str());
442 _error
->PushToStack();
443 bool const splitDone
= SplitClearSignedFile(ClearSignedFileName
, &MessageFile
, NULL
, NULL
);
444 bool const errorDone
= _error
->PendingError();
445 _error
->MergeWithStack();
446 if (splitDone
== false)
450 if (errorDone
== true)
453 // we deal with an unsigned file
454 MessageFile
.Open(ClearSignedFileName
, FileFd::ReadOnly
);
458 if (MessageFile
.Seek(0) == false)
459 return _error
->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName
.c_str());
462 return MessageFile
.Failed() == false;