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
;
148 std::vector
<std::string
> dataHeader
;
151 char * conf
= nullptr;
153 // Dump the configuration so apt-key picks up the correct Dir values
155 conf
= GenerateTemporaryFileTemplate("apt.conf");
156 if (conf
== nullptr) {
157 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfile names for passing config to apt-key");
158 local_exit(EINTERNAL
);
160 int confFd
= mkstemp(conf
);
162 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create temporary file %s for passing config to apt-key", conf
);
163 local_exit(EINTERNAL
);
165 local_exit
.files
.push_back(conf
);
167 std::ofstream
confStream(conf
);
169 _config
->Dump(confStream
);
171 setenv("APT_CONFIG", conf
, 1);
174 if (releaseSignature
== DETACHED
)
176 Args
.push_back(FileGPG
.c_str());
177 Args
.push_back(File
.c_str());
179 else // clear-signed file
181 sig
= GenerateTemporaryFileTemplate("apt.sig");
182 data
= GenerateTemporaryFileTemplate("apt.data");
183 if (sig
== NULL
|| data
== NULL
)
185 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfile names for splitting up %s", File
.c_str());
186 local_exit(EINTERNAL
);
189 int const sigFd
= mkstemp(sig
);
190 int const dataFd
= mkstemp(data
);
192 local_exit
.files
.push_back(data
);
194 local_exit
.files
.push_back(sig
);
195 if (sigFd
== -1 || dataFd
== -1)
197 apt_error(std::cerr
, statusfd
, fd
, "Couldn't create tempfiles for splitting up %s", File
.c_str());
198 local_exit(EINTERNAL
);
202 signature
.OpenDescriptor(sigFd
, FileFd::WriteOnly
, true);
204 message
.OpenDescriptor(dataFd
, FileFd::WriteOnly
, true);
206 if (signature
.Failed() == true || message
.Failed() == true ||
207 SplitClearSignedFile(File
, &message
, &dataHeader
, &signature
) == false)
209 apt_error(std::cerr
, statusfd
, fd
, "Splitting up %s into data and signature failed", File
.c_str());
213 Args
.push_back(data
);
216 Args
.push_back(NULL
);
220 std::clog
<< "Preparing to exec: ";
221 for (std::vector
<const char *>::const_iterator a
= Args
.begin(); *a
!= NULL
; ++a
)
222 std::clog
<< " " << *a
;
223 std::clog
<< std::endl
;
228 int const nullfd
= open("/dev/null", O_WRONLY
);
230 // Redirect output to /dev/null; we read from the status fd
231 if (statusfd
!= STDOUT_FILENO
)
232 dup2(nullfd
, STDOUT_FILENO
);
233 if (statusfd
!= STDERR_FILENO
)
234 dup2(nullfd
, STDERR_FILENO
);
235 // Redirect the pipe to the status fd (3)
236 dup2(fd
[1], statusfd
);
238 putenv((char *)"LANG=");
239 putenv((char *)"LC_ALL=");
240 putenv((char *)"LC_MESSAGES=");
244 // We have created tempfiles we have to clean up
245 // and we do an additional check, so fork yet another time …
246 pid_t pid
= ExecFork();
248 apt_error(std::cerr
, statusfd
, fd
, "Fork failed for %s to check %s", Args
[0], File
.c_str());
249 local_exit(EINTERNAL
);
254 dup2(fd
[1], statusfd
);
255 execvp(Args
[0], (char **) &Args
[0]);
256 apt_error(std::cerr
, statusfd
, fd
, "Couldn't execute %s to check %s", Args
[0], File
.c_str());
257 local_exit(EINTERNAL
);
260 // Wait and collect the error code - taken from WaitPid as we need the exact Status
262 while (waitpid(pid
,&Status
,0) != pid
)
266 apt_error(std::cerr
, statusfd
, fd
, _("Waited for %s but it wasn't there"), "apt-key");
267 local_exit(EINTERNAL
);
270 // check if it exit'ed normally …
271 if (WIFEXITED(Status
) == false)
273 apt_error(std::cerr
, statusfd
, fd
, _("Sub-process %s exited unexpectedly"), "apt-key");
274 local_exit(EINTERNAL
);
277 // … and with a good exit code
278 if (WEXITSTATUS(Status
) != 0)
280 // we forward the statuscode, so don't generate a message on the fd in this case
281 apt_error(std::cerr
, -1, fd
, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status
));
282 local_exit(WEXITSTATUS(Status
));
289 // SplitClearSignedFile - split message into data/signature /*{{{*/
290 bool SplitClearSignedFile(std::string
const &InFile
, FileFd
* const ContentFile
,
291 std::vector
<std::string
> * const ContentHeader
, FileFd
* const SignatureFile
)
293 FILE *in
= fopen(InFile
.c_str(), "r");
295 return _error
->Errno("fopen", "can not open %s", InFile
.c_str());
297 bool found_message_start
= false;
298 bool found_message_end
= false;
299 bool skip_until_empty_line
= false;
300 bool found_signature
= false;
301 bool first_line
= true;
305 while (getline(&buf
, &buf_size
, in
) != -1)
308 if (found_message_start
== false)
310 if (strcmp(buf
, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
312 found_message_start
= true;
313 skip_until_empty_line
= true;
316 else if (skip_until_empty_line
== true)
318 if (strlen(buf
) == 0)
319 skip_until_empty_line
= false;
320 // save "Hash" Armor Headers, others aren't allowed
321 else if (ContentHeader
!= NULL
&& strncmp(buf
, "Hash: ", strlen("Hash: ")) == 0)
322 ContentHeader
->push_back(buf
);
324 else if (found_signature
== false)
326 if (strcmp(buf
, "-----BEGIN PGP SIGNATURE-----") == 0)
328 found_signature
= true;
329 found_message_end
= true;
330 if (SignatureFile
!= NULL
)
332 SignatureFile
->Write(buf
, strlen(buf
));
333 SignatureFile
->Write("\n", 1);
336 else if (found_message_end
== false) // we are in the message block
338 // we don't have any fields which need dash-escaped,
339 // but implementations are free to encode all lines …
340 char const * dashfree
= buf
;
341 if (strncmp(dashfree
, "- ", 2) == 0)
343 if(first_line
== true) // first line does not need a newline
345 else if (ContentFile
!= NULL
)
346 ContentFile
->Write("\n", 1);
349 if (ContentFile
!= NULL
)
350 ContentFile
->Write(dashfree
, strlen(dashfree
));
353 else if (found_signature
== true)
355 if (SignatureFile
!= NULL
)
357 SignatureFile
->Write(buf
, strlen(buf
));
358 SignatureFile
->Write("\n", 1);
360 if (strcmp(buf
, "-----END PGP SIGNATURE-----") == 0)
361 found_signature
= false; // look for other signatures
363 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
369 if (found_signature
== true)
370 return _error
->Error("Signature in file %s wasn't closed", InFile
.c_str());
372 // if we haven't found any of them, this an unsigned file,
373 // so don't generate an error, but splitting was unsuccessful none-the-less
374 if (first_line
== true && found_message_start
== false && found_message_end
== false)
376 // otherwise one missing indicates a syntax error
377 else if (first_line
== true || found_message_start
== false || found_message_end
== false)
378 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
);
383 bool OpenMaybeClearSignedFile(std::string
const &ClearSignedFileName
, FileFd
&MessageFile
) /*{{{*/
385 char * const message
= GenerateTemporaryFileTemplate("fileutl.message");
386 int const messageFd
= mkstemp(message
);
390 return _error
->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName
.c_str());
392 // we have the fd, thats enough for us
396 MessageFile
.OpenDescriptor(messageFd
, FileFd::ReadWrite
| FileFd::BufferedWrite
, true);
397 if (MessageFile
.Failed() == true)
398 return _error
->Error("Couldn't open temporary file to work with %s", ClearSignedFileName
.c_str());
400 _error
->PushToStack();
401 bool const splitDone
= SplitClearSignedFile(ClearSignedFileName
, &MessageFile
, NULL
, NULL
);
402 bool const errorDone
= _error
->PendingError();
403 _error
->MergeWithStack();
404 if (splitDone
== false)
408 if (errorDone
== true)
411 // we deal with an unsigned file
412 MessageFile
.Open(ClearSignedFileName
, FileFd::ReadOnly
);
416 if (MessageFile
.Seek(0) == false)
417 return _error
->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName
.c_str());
420 return MessageFile
.Failed() == false;