Branch data Line data Source code
1 : : /* Retrieve ELF / DWARF / source files from the debuginfod.
2 : : Copyright (C) 2019-2024 Red Hat, Inc.
3 : : Copyright (C) 2021, 2022 Mark J. Wielaard <mark@klomp.org>
4 : : This file is part of elfutils.
5 : :
6 : : This file is free software; you can redistribute it and/or modify
7 : : it under the terms of either
8 : :
9 : : * the GNU Lesser General Public License as published by the Free
10 : : Software Foundation; either version 3 of the License, or (at
11 : : your option) any later version
12 : :
13 : : or
14 : :
15 : : * the GNU General Public License as published by the Free
16 : : Software Foundation; either version 2 of the License, or (at
17 : : your option) any later version
18 : :
19 : : or both in parallel, as here.
20 : :
21 : : elfutils is distributed in the hope that it will be useful, but
22 : : WITHOUT ANY WARRANTY; without even the implied warranty of
23 : : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 : : General Public License for more details.
25 : :
26 : : You should have received copies of the GNU General Public License and
27 : : the GNU Lesser General Public License along with this program. If
28 : : not, see <http://www.gnu.org/licenses/>. */
29 : :
30 : :
31 : : /* cargo-cult from libdwfl linux-kernel-modules.c */
32 : : /* In case we have a bad fts we include this before config.h because it
33 : : can't handle _FILE_OFFSET_BITS.
34 : : Everything we need here is fine if its declarations just come first.
35 : : Also, include sys/types.h before fts. On some systems fts.h is not self
36 : : contained. */
37 : : #ifdef BAD_FTS
38 : : #include <sys/types.h>
39 : : #include <fts.h>
40 : : #endif
41 : :
42 : : #include "config.h"
43 : : #include "debuginfod.h"
44 : : #include "system.h"
45 : : #include <ctype.h>
46 : : #include <errno.h>
47 : : #include <stdlib.h>
48 : : #include <gelf.h>
49 : :
50 : : #ifdef ENABLE_IMA_VERIFICATION
51 : : #include <openssl/sha.h>
52 : : #include <openssl/pem.h>
53 : : #include <openssl/evp.h>
54 : : #include <openssl/x509v3.h>
55 : : #include <arpa/inet.h>
56 : : #include <imaevm.h>
57 : : #endif
58 : : typedef enum {ignore, enforcing, undefined} ima_policy_t;
59 : :
60 : :
61 : : /* We might be building a bootstrap dummy library, which is really simple. */
62 : : #ifdef DUMMY_LIBDEBUGINFOD
63 : :
64 : : debuginfod_client *debuginfod_begin (void) { errno = ENOSYS; return NULL; }
65 : : int debuginfod_find_debuginfo (debuginfod_client *c, const unsigned char *b,
66 : : int s, char **p) { return -ENOSYS; }
67 : : int debuginfod_find_executable (debuginfod_client *c, const unsigned char *b,
68 : : int s, char **p) { return -ENOSYS; }
69 : : int debuginfod_find_source (debuginfod_client *c, const unsigned char *b,
70 : : int s, const char *f, char **p) { return -ENOSYS; }
71 : : int debuginfod_find_section (debuginfod_client *c, const unsigned char *b,
72 : : int s, const char *scn, char **p)
73 : : { return -ENOSYS; }
74 : : int debuginfod_find_metadata (debuginfod_client *c,
75 : : const char *k, const char *v, char **p) { return -ENOSYS; }
76 : : void debuginfod_set_progressfn(debuginfod_client *c,
77 : : debuginfod_progressfn_t fn) { }
78 : : void debuginfod_set_verbose_fd(debuginfod_client *c, int fd) { }
79 : : void debuginfod_set_user_data (debuginfod_client *c, void *d) { }
80 : : void* debuginfod_get_user_data (debuginfod_client *c) { return NULL; }
81 : : const char* debuginfod_get_url (debuginfod_client *c) { return NULL; }
82 : : int debuginfod_add_http_header (debuginfod_client *c,
83 : : const char *h) { return -ENOSYS; }
84 : : const char* debuginfod_get_headers (debuginfod_client *c) { return NULL; }
85 : : int debuginfod_default_progressfn (debuginfod_client *c, long a, long b)
86 : : { return 0; }
87 : :
88 : : void debuginfod_end (debuginfod_client *c) { }
89 : :
90 : : #else /* DUMMY_LIBDEBUGINFOD */
91 : :
92 : : #include <assert.h>
93 : : #include <dirent.h>
94 : : #include <stdio.h>
95 : : #include <errno.h>
96 : : #include <unistd.h>
97 : : #include <fcntl.h>
98 : : #include <fts.h>
99 : : #include <regex.h>
100 : : #include <string.h>
101 : : #include <stdbool.h>
102 : : #include <limits.h>
103 : : #include <time.h>
104 : : #include <utime.h>
105 : : #include <sys/syscall.h>
106 : : #include <sys/types.h>
107 : : #include <sys/stat.h>
108 : : #include <sys/utsname.h>
109 : : #include <curl/curl.h>
110 : : #include <fnmatch.h>
111 : : #include <json-c/json.h>
112 : :
113 : : #ifndef PATH_MAX
114 : : #define PATH_MAX 4096
115 : : #endif
116 : :
117 : : /* If fts.h is included before config.h, its indirect inclusions may not
118 : : give us the right LFS aliases of these functions, so map them manually. */
119 : : #ifdef BAD_FTS
120 : : #ifdef _FILE_OFFSET_BITS
121 : : #define open open64
122 : : #define fopen fopen64
123 : : #endif
124 : : #else
125 : : #include <sys/types.h>
126 : : #include <fts.h>
127 : : #endif
128 : :
129 : : /* Older curl.h don't define CURL_AT_LEAST_VERSION. */
130 : : #ifndef CURL_AT_LEAST_VERSION
131 : : #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
132 : : #define CURL_AT_LEAST_VERSION(x,y,z) \
133 : : (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
134 : : #endif
135 : :
136 : : #include <pthread.h>
137 : :
138 : : static pthread_once_t init_control = PTHREAD_ONCE_INIT;
139 : : static bool curl_has_https; // = false
140 : :
141 : : static void
142 : 524 : libcurl_init(void)
143 : : {
144 : 524 : curl_global_init(CURL_GLOBAL_DEFAULT);
145 : :
146 : 524 : for (const char *const *protocol = curl_version_info(CURLVERSION_NOW)->protocols;
147 [ + + ]: 17292 : *protocol != NULL; ++protocol)
148 : : {
149 [ + + ]: 16768 : if(strcmp("https", *protocol) == 0)
150 : 524 : curl_has_https = true;
151 : : }
152 : 524 : }
153 : :
154 : :
155 : : #ifdef ENABLE_IMA_VERIFICATION
156 : : struct public_key_entry
157 : : {
158 : : struct public_key_entry *next; /* singly-linked list */
159 : : uint32_t keyid; /* last 4 bytes of sha1 of public key */
160 : : EVP_PKEY *key; /* openssl */
161 : : };
162 : : #endif
163 : :
164 : :
165 : : struct debuginfod_client
166 : : {
167 : : /* Progress/interrupt callback function. */
168 : : debuginfod_progressfn_t progressfn;
169 : :
170 : : /* Stores user data. */
171 : : void* user_data;
172 : :
173 : : /* Stores current/last url, if any. */
174 : : char* url;
175 : :
176 : : /* Accumulates outgoing http header names/values. */
177 : : int user_agent_set_p; /* affects add_default_headers */
178 : : struct curl_slist *headers;
179 : :
180 : : /* Flags the default_progressfn having printed something that
181 : : debuginfod_end needs to terminate. */
182 : : int default_progressfn_printed_p;
183 : :
184 : : /* Indicates whether the last query was cancelled by progressfn. */
185 : : bool progressfn_cancel;
186 : :
187 : : /* File descriptor to output any verbose messages if > 0. */
188 : : int verbose_fd;
189 : :
190 : : /* Maintain a long-lived curl multi-handle, which keeps a
191 : : connection/tls/dns cache to recently seen servers. */
192 : : CURLM *server_mhandle;
193 : :
194 : : /* Can contain all other context, like cache_path, server_urls,
195 : : timeout or other info gotten from environment variables, the
196 : : handle data, etc. So those don't have to be reparsed and
197 : : recreated on each request. */
198 : : char * winning_headers;
199 : :
200 : : #ifdef ENABLE_IMA_VERIFICATION
201 : : /* IMA public keys */
202 : : struct public_key_entry *ima_public_keys;
203 : : #endif
204 : : };
205 : :
206 : :
207 : : /* The cache_clean_interval_s file within the debuginfod cache specifies
208 : : how frequently the cache should be cleaned. The file's st_mtime represents
209 : : the time of last cleaning. */
210 : : static const char *cache_clean_interval_filename = "cache_clean_interval_s";
211 : : static const long cache_clean_default_interval_s = 86400; /* 1 day */
212 : :
213 : : /* The cache_miss_default_s within the debuginfod cache specifies how
214 : : frequently the empty file should be released.*/
215 : : static const long cache_miss_default_s = 600; /* 10 min */
216 : : static const char *cache_miss_filename = "cache_miss_s";
217 : :
218 : : /* The cache_max_unused_age_s file within the debuginfod cache specifies the
219 : : the maximum time since last access that a file will remain in the cache. */
220 : : static const char *cache_max_unused_age_filename = "max_unused_age_s";
221 : : static const long cache_default_max_unused_age_s = 604800; /* 1 week */
222 : :
223 : : /* The metadata_retention_default_s file within the debuginfod cache
224 : : specifies how long metadata query results should be cached. */
225 : : static const long metadata_retention_default_s = 3600; /* 1 hour */
226 : : static const char *metadata_retention_filename = "metadata_retention_s";
227 : :
228 : : /* Location of the cache of files downloaded from debuginfods.
229 : : The default parent directory is $HOME, or '/' if $HOME doesn't exist. */
230 : : static const char *cache_default_name = ".debuginfod_client_cache";
231 : : static const char *cache_xdg_name = "debuginfod_client";
232 : :
233 : : /* URLs of debuginfods, separated by url_delim. */
234 : : static const char *url_delim = " ";
235 : :
236 : : /* Timeout for debuginfods, in seconds (to get at least 100K). */
237 : : static const long default_timeout = 90;
238 : :
239 : : /* Default retry count for download error. */
240 : : static const long default_retry_limit = 2;
241 : :
242 : : /* Data associated with a particular CURL easy handle. Passed to
243 : : the write callback. */
244 : : struct handle_data
245 : : {
246 : : /* Cache file to be written to in case query is successful. */
247 : : int fd;
248 : :
249 : : /* URL queried by this handle. */
250 : : char url[PATH_MAX];
251 : :
252 : : /* error buffer for this handle. */
253 : : char errbuf[CURL_ERROR_SIZE];
254 : :
255 : : /* This handle. */
256 : : CURL *handle;
257 : :
258 : : /* The client object whom we're serving. */
259 : : debuginfod_client *client;
260 : :
261 : : /* Pointer to handle that should write to fd. Initially points to NULL,
262 : : then points to the first handle that begins writing the target file
263 : : to the cache. Used to ensure that a file is not downloaded from
264 : : multiple servers unnecessarily. */
265 : : CURL **target_handle;
266 : :
267 : : /* Response http headers for this client handle, sent from the server */
268 : : char *response_data;
269 : : size_t response_data_size;
270 : :
271 : : /* Response metadata values for this client handle, sent from the server */
272 : : char *metadata;
273 : : size_t metadata_size;
274 : : };
275 : :
276 : :
277 : :
278 : : #ifdef ENABLE_IMA_VERIFICATION
279 : : static inline unsigned char hex2dec(char c)
280 : : {
281 : : if (c >= '0' && c <= '9') return (c - '0');
282 : : if (c >= 'a' && c <= 'f') return (c - 'a') + 10;
283 : : if (c >= 'A' && c <= 'F') return (c - 'A') + 10;
284 : : return 0;
285 : : }
286 : :
287 : : static inline ima_policy_t ima_policy_str2enum(const char* ima_pol)
288 : : {
289 : : if (NULL == ima_pol) return undefined;
290 : : if (0 == strcmp(ima_pol, "ignore")) return ignore;
291 : : if (0 == strcmp(ima_pol, "enforcing")) return enforcing;
292 : : return undefined;
293 : : }
294 : :
295 : : static inline const char* ima_policy_enum2str(ima_policy_t ima_pol)
296 : : {
297 : : switch (ima_pol)
298 : : {
299 : : case ignore:
300 : : return "ignore";
301 : : case enforcing:
302 : : return "enforcing";
303 : : case undefined:
304 : : return "undefined";
305 : : }
306 : : return "";
307 : : }
308 : :
309 : :
310 : : static uint32_t extract_skid_pk(EVP_PKEY *pkey) // compute keyid by public key hashing
311 : : {
312 : : if (!pkey) return 0;
313 : : uint32_t keyid = 0;
314 : : X509_PUBKEY *pk = NULL;
315 : : const unsigned char *public_key = NULL;
316 : : int len;
317 : : if (X509_PUBKEY_set(&pk, pkey) &&
318 : : X509_PUBKEY_get0_param(NULL, &public_key, &len, NULL, pk))
319 : : {
320 : : uint8_t sha1[SHA_DIGEST_LENGTH];
321 : : SHA1(public_key, len, sha1);
322 : : memcpy(&keyid, sha1 + 16, 4);
323 : : }
324 : : X509_PUBKEY_free(pk);
325 : : return ntohl(keyid);
326 : : }
327 : :
328 : :
329 : : static uint32_t extract_skid(X509* x509) // compute keyid from cert or its public key
330 : : {
331 : : if (!x509) return 0;
332 : : uint32_t keyid = 0;
333 : : // Attempt to get the skid from the certificate
334 : : const ASN1_OCTET_STRING *skid_asn1_str = X509_get0_subject_key_id(x509);
335 : : if (skid_asn1_str)
336 : : {
337 : : int skid_len = ASN1_STRING_length(skid_asn1_str);
338 : : memcpy(&keyid, ASN1_STRING_get0_data(skid_asn1_str) + skid_len - sizeof(keyid), sizeof(keyid));
339 : : }
340 : : else // compute keyid ourselves by hashing public key
341 : : {
342 : : EVP_PKEY *pkey = X509_get0_pubkey(x509);
343 : : keyid = htonl(extract_skid_pk(pkey));
344 : : }
345 : : return ntohl(keyid);
346 : : }
347 : :
348 : :
349 : : static void load_ima_public_keys (debuginfod_client *c)
350 : : {
351 : : /* Iterate over the directories in DEBUGINFOD_IMA_CERT_PATH. */
352 : : char *cert_paths = getenv(DEBUGINFOD_IMA_CERT_PATH_ENV_VAR);
353 : : if (cert_paths == NULL || cert_paths[0] == '\0')
354 : : return;
355 : : cert_paths = strdup(cert_paths); // Modified during tokenization
356 : : if (cert_paths == NULL)
357 : : return;
358 : :
359 : : char* cert_dir_path;
360 : : DIR *dp;
361 : : struct dirent *entry;
362 : : int vfd = c->verbose_fd;
363 : :
364 : : char *strtok_context = NULL;
365 : : for(cert_dir_path = strtok_r(cert_paths, ":", &strtok_context);
366 : : cert_dir_path != NULL;
367 : : cert_dir_path = strtok_r(NULL, ":", &strtok_context))
368 : : {
369 : : dp = opendir(cert_dir_path);
370 : : if(!dp) continue;
371 : : while((entry = readdir(dp)))
372 : : {
373 : : // Only consider regular files with common x509 cert extensions
374 : : if(entry->d_type != DT_REG || 0 != fnmatch("*.@(der|pem|crt|cer|cert)", entry->d_name, FNM_EXTMATCH)) continue;
375 : : char certfile[PATH_MAX];
376 : : strncpy(certfile, cert_dir_path, PATH_MAX - 1);
377 : : if(certfile[strlen(certfile)-1] != '/') certfile[strlen(certfile)] = '/';
378 : : strncat(certfile, entry->d_name, PATH_MAX - strlen(certfile) - 1);
379 : : certfile[strlen(certfile)] = '\0';
380 : :
381 : : FILE *cert_fp = fopen(certfile, "r");
382 : : if(!cert_fp) continue;
383 : :
384 : : X509 *x509 = NULL;
385 : : EVP_PKEY *pkey = NULL;
386 : : char *fmt = "";
387 : : // Attempt to read the fp as DER
388 : : if(d2i_X509_fp(cert_fp, &x509))
389 : : fmt = "der ";
390 : : // Attempt to read the fp as PEM and assuming the key matches that of the signature add this key to be used
391 : : // Note we fseek since this is the second time we read from the fp
392 : : else if(0 == fseek(cert_fp, 0, SEEK_SET) && PEM_read_X509(cert_fp, &x509, NULL, NULL))
393 : : fmt = "pem "; // PEM with full certificate
394 : : else if(0 == fseek(cert_fp, 0, SEEK_SET) && PEM_read_PUBKEY(cert_fp, &pkey, NULL, NULL))
395 : : fmt = "pem "; // some PEM files have just a PUBLIC KEY in them
396 : : fclose(cert_fp);
397 : :
398 : : if (x509)
399 : : {
400 : : struct public_key_entry *ne = calloc(1, sizeof(struct public_key_entry));
401 : : if (ne)
402 : : {
403 : : ne->key = X509_extract_key(x509);
404 : : ne->keyid = extract_skid(x509);
405 : : ne->next = c->ima_public_keys;
406 : : c->ima_public_keys = ne;
407 : : if (vfd >= 0)
408 : : dprintf(vfd, "Loaded %scertificate %s, keyid = %04x\n", fmt, certfile, ne->keyid);
409 : : }
410 : : X509_free (x509);
411 : : }
412 : : else if (pkey)
413 : : {
414 : : struct public_key_entry *ne = calloc(1, sizeof(struct public_key_entry));
415 : : if (ne)
416 : : {
417 : : ne->key = pkey; // preserve refcount
418 : : ne->keyid = extract_skid_pk(pkey);
419 : : ne->next = c->ima_public_keys;
420 : : c->ima_public_keys = ne;
421 : : if (vfd >= 0)
422 : : dprintf(vfd, "Loaded %spubkey %s, keyid %04x\n", fmt, certfile, ne->keyid);
423 : : }
424 : : }
425 : : else
426 : : {
427 : : if (vfd >= 0)
428 : : dprintf(vfd, "Cannot load certificate %s\n", certfile);
429 : : }
430 : : } /* for each file in directory */
431 : : closedir(dp);
432 : : } /* for each directory */
433 : :
434 : : free(cert_paths);
435 : : }
436 : :
437 : :
438 : : static void free_ima_public_keys (debuginfod_client *c)
439 : : {
440 : : while (c->ima_public_keys)
441 : : {
442 : : EVP_PKEY_free (c->ima_public_keys->key);
443 : : struct public_key_entry *oen = c->ima_public_keys->next;
444 : : free (c->ima_public_keys);
445 : : c->ima_public_keys = oen;
446 : : }
447 : : }
448 : : #endif
449 : :
450 : :
451 : :
452 : : static size_t
453 : 10437 : debuginfod_write_callback (char *ptr, size_t size, size_t nmemb, void *data)
454 : : {
455 : 10437 : ssize_t count = size * nmemb;
456 : :
457 : 10437 : struct handle_data *d = (struct handle_data*)data;
458 : :
459 : : /* Indicate to other handles that they can abort their transfer. */
460 [ + + ]: 10437 : if (*d->target_handle == NULL)
461 : : {
462 : 1460 : *d->target_handle = d->handle;
463 : : /* update the client object */
464 : 1460 : const char *url = NULL;
465 : 1460 : CURLcode curl_res = curl_easy_getinfo (d->handle,
466 : : CURLINFO_EFFECTIVE_URL, &url);
467 [ + - + - ]: 1460 : if (curl_res == CURLE_OK && url)
468 : : {
469 : 1460 : free (d->client->url);
470 : 1460 : d->client->url = strdup(url); /* ok if fails */
471 : : }
472 : : }
473 : :
474 : : /* If this handle isn't the target handle, abort transfer. */
475 [ + - ]: 10437 : if (*d->target_handle != d->handle)
476 : : return -1;
477 : :
478 : 10437 : return (size_t) write(d->fd, (void*)ptr, count);
479 : : }
480 : :
481 : : /* handle config file read and write */
482 : : static int
483 : 2118 : debuginfod_config_cache(debuginfod_client *c, char *config_path,
484 : : long cache_config_default_s,
485 : : struct stat *st)
486 : : {
487 : 2118 : int fd = open(config_path, O_CREAT | O_RDWR, DEFFILEMODE);
488 [ - + ]: 2118 : if (fd < 0)
489 : 0 : return -errno;
490 : :
491 [ - + ]: 2118 : if (fstat (fd, st) < 0)
492 : : {
493 : 0 : int ret = -errno;
494 : 0 : close (fd);
495 : 0 : return ret;
496 : : }
497 : :
498 [ + + ]: 2118 : if (st->st_size == 0)
499 : : {
500 [ - + ]: 82 : if (dprintf(fd, "%ld", cache_config_default_s) < 0)
501 : : {
502 : 0 : int ret = -errno;
503 : 0 : close (fd);
504 : 0 : return ret;
505 : : }
506 : :
507 : 82 : close (fd);
508 : 82 : return cache_config_default_s;
509 : : }
510 : :
511 : 2036 : long cache_config;
512 : : /* PR29696 - NB: When using fdopen, the file descriptor is NOT
513 : : dup'ed and will be closed when the stream is closed. Manually
514 : : closing fd after fclose is called will lead to a race condition
515 : : where, if reused, the file descriptor will compete for its
516 : : regular use before being incorrectly closed here. */
517 : 2036 : FILE *config_file = fdopen(fd, "r");
518 [ + - ]: 2036 : if (config_file)
519 : : {
520 [ - + ]: 2036 : if (fscanf(config_file, "%ld", &cache_config) != 1)
521 : 0 : cache_config = cache_config_default_s;
522 [ - + - - ]: 2036 : if (0 != fclose (config_file) && c->verbose_fd >= 0)
523 : 0 : dprintf (c->verbose_fd, "fclose failed with %s (err=%d)\n",
524 : 0 : strerror (errno), errno);
525 : : }
526 : : else
527 : : {
528 : 0 : cache_config = cache_config_default_s;
529 [ # # # # ]: 0 : if (0 != close (fd) && c->verbose_fd >= 0)
530 : 0 : dprintf (c->verbose_fd, "close failed with %s (err=%d)\n",
531 : 0 : strerror (errno), errno);
532 : : }
533 : 2036 : return cache_config;
534 : : }
535 : :
536 : : /* Delete any files that have been unmodied for a period
537 : : longer than $DEBUGINFOD_CACHE_CLEAN_INTERVAL_S. */
538 : : static int
539 : 2100 : debuginfod_clean_cache(debuginfod_client *c,
540 : : char *cache_path, char *interval_path,
541 : : char *max_unused_path)
542 : : {
543 : 2100 : time_t clean_interval, max_unused_age;
544 : 2100 : int rc = -1;
545 : 2100 : struct stat st;
546 : :
547 : : /* Create new interval file. */
548 : 2100 : rc = debuginfod_config_cache(c, interval_path,
549 : : cache_clean_default_interval_s, &st);
550 [ + - ]: 2100 : if (rc < 0)
551 : : return rc;
552 : 2100 : clean_interval = (time_t)rc;
553 : :
554 : : /* Check timestamp of interval file to see whether cleaning is necessary. */
555 [ + + ]: 2100 : if (time(NULL) - st.st_mtime < clean_interval)
556 : : /* Interval has not passed, skip cleaning. */
557 : : return 0;
558 : :
559 : : /* Update timestamp representing when the cache was last cleaned.
560 : : Do it at the start to reduce the number of threads trying to do a
561 : : cleanup simultaneously. */
562 : 2 : utime (interval_path, NULL);
563 : :
564 : : /* Read max unused age value from config file. */
565 : 2 : rc = debuginfod_config_cache(c, max_unused_path,
566 : : cache_default_max_unused_age_s, &st);
567 [ + - ]: 2 : if (rc < 0)
568 : : return rc;
569 : 2 : max_unused_age = (time_t)rc;
570 : :
571 : 2 : char * const dirs[] = { cache_path, NULL, };
572 : :
573 : 2 : FTS *fts = fts_open(dirs, 0, NULL);
574 [ - + ]: 2 : if (fts == NULL)
575 : 0 : return -errno;
576 : :
577 : 2 : regex_t re;
578 : 2 : const char * pattern = ".*/(metadata.*|[a-f0-9]+(/hdr.*|/debuginfo|/executable|/source.*|))$"; /* include dirs */
579 : : /* NB: also matches .../section/ subdirs, so extracted section files also get cleaned. */
580 [ + - ]: 2 : if (regcomp (&re, pattern, REG_EXTENDED | REG_NOSUB) != 0)
581 : : return -ENOMEM;
582 : :
583 : 2 : FTSENT *f;
584 : 2 : long files = 0;
585 : 2 : time_t now = time(NULL);
586 [ + + ]: 28 : while ((f = fts_read(fts)) != NULL)
587 : : {
588 : : /* ignore any files that do not match the pattern. */
589 [ + + ]: 24 : if (regexec (&re, f->fts_path, 0, NULL, 0) != 0)
590 : 16 : continue;
591 : :
592 : 8 : files++;
593 [ + - ]: 8 : if (c->progressfn) /* inform/check progress callback */
594 [ + - ]: 8 : if ((c->progressfn) (c, files, 0))
595 : : break;
596 : :
597 [ + - + ]: 8 : switch (f->fts_info)
598 : : {
599 : 0 : case FTS_F:
600 : : /* delete file if max_unused_age has been met or exceeded w.r.t. atime. */
601 [ # # ]: 0 : if (now - f->fts_statp->st_atime >= max_unused_age)
602 : 0 : (void) unlink (f->fts_path);
603 : : break;
604 : :
605 : 4 : case FTS_DP:
606 : : /* Remove if old & empty. Weaken race against concurrent creation by
607 : : checking mtime. */
608 [ - + ]: 4 : if (now - f->fts_statp->st_mtime >= max_unused_age)
609 : 4 : (void) rmdir (f->fts_path);
610 : : break;
611 : :
612 : : default:
613 : 26 : ;
614 : : }
615 : : }
616 : 2 : fts_close (fts);
617 : 2 : regfree (&re);
618 : :
619 : 2 : return 0;
620 : : }
621 : :
622 : :
623 : : #define MAX_BUILD_ID_BYTES 64
624 : :
625 : :
626 : : static void
627 : 2124 : add_default_headers(debuginfod_client *client)
628 : : {
629 [ + + ]: 2124 : if (client->user_agent_set_p)
630 : 560 : return;
631 : :
632 : : /* Compute a User-Agent: string to send. The more accurately this
633 : : describes this host, the likelier that the debuginfod servers
634 : : might be able to locate debuginfo for us. */
635 : :
636 : 1564 : char* utspart = NULL;
637 : 1564 : struct utsname uts;
638 : 1564 : int rc = 0;
639 : 1564 : rc = uname (&uts);
640 [ + - ]: 1564 : if (rc == 0)
641 : 1564 : rc = asprintf(& utspart, "%s/%s", uts.sysname, uts.machine);
642 [ - + ]: 1564 : if (rc < 0)
643 : 0 : utspart = NULL;
644 : :
645 : 1564 : FILE *f = fopen ("/etc/os-release", "r");
646 [ - + ]: 1564 : if (f == NULL)
647 : 0 : f = fopen ("/usr/lib/os-release", "r");
648 : 1564 : char *id = NULL;
649 : 1564 : char *version = NULL;
650 [ - + ]: 1564 : if (f != NULL)
651 : : {
652 [ + + ]: 12512 : while (id == NULL || version == NULL)
653 : : {
654 : 10948 : char buf[128];
655 : 10948 : char *s = &buf[0];
656 [ + - ]: 10948 : if (fgets (s, sizeof(buf), f) == NULL)
657 : : break;
658 : :
659 : 10948 : int len = strlen (s);
660 [ - + ]: 10948 : if (len < 3)
661 : 0 : continue;
662 [ + - ]: 10948 : if (s[len - 1] == '\n')
663 : : {
664 : 10948 : s[len - 1] = '\0';
665 : 10948 : len--;
666 : : }
667 : :
668 : 10948 : char *v = strchr (s, '=');
669 [ + - - + ]: 10948 : if (v == NULL || strlen (v) < 2)
670 : 0 : continue;
671 : :
672 : : /* Split var and value. */
673 : 10948 : *v = '\0';
674 : 10948 : v++;
675 : :
676 : : /* Remove optional quotes around value string. */
677 [ + + ]: 10948 : if (*v == '"' || *v == '\'')
678 : : {
679 : 6256 : v++;
680 : 6256 : s[len - 1] = '\0';
681 : : }
682 [ + - + + ]: 10948 : if (id == NULL && strcmp (s, "ID") == 0)
683 : 1564 : id = strdup (v);
684 [ + + + + ]: 10948 : if (version == NULL && strcmp (s, "VERSION_ID") == 0)
685 : 1564 : version = strdup (v);
686 : : }
687 : 1564 : fclose (f);
688 : : }
689 : :
690 : 1564 : char *ua = NULL;
691 [ + - + - ]: 3128 : rc = asprintf(& ua, "User-Agent: %s/%s,%s,%s/%s",
692 : : PACKAGE_NAME, PACKAGE_VERSION,
693 [ - + ]: 1564 : utspart ?: "",
694 : : id ?: "",
695 : : version ?: "");
696 [ - + ]: 1564 : if (rc < 0)
697 : 0 : ua = NULL;
698 : :
699 [ + - ]: 1564 : if (ua)
700 : 1564 : (void) debuginfod_add_http_header (client, ua);
701 : :
702 : 1564 : free (ua);
703 : 1564 : free (id);
704 : 1564 : free (version);
705 : 1564 : free (utspart);
706 : : }
707 : :
708 : : /* Add HTTP headers found in the given file, one per line. Blank lines or invalid
709 : : * headers are ignored.
710 : : */
711 : : static void
712 : 0 : add_headers_from_file(debuginfod_client *client, const char* filename)
713 : : {
714 : 0 : int vds = client->verbose_fd;
715 : 0 : FILE *f = fopen (filename, "r");
716 [ # # ]: 0 : if (f == NULL)
717 : : {
718 [ # # ]: 0 : if (vds >= 0)
719 : 0 : dprintf(vds, "header file %s: %s\n", filename, strerror(errno));
720 : 0 : return;
721 : : }
722 : :
723 : 0 : while (1)
724 : 0 : {
725 : 0 : char buf[8192];
726 : 0 : char *s = &buf[0];
727 [ # # ]: 0 : if (feof(f))
728 : : break;
729 [ # # ]: 0 : if (fgets (s, sizeof(buf), f) == NULL)
730 : : break;
731 [ # # ]: 0 : for (char *c = s; *c != '\0'; ++c)
732 [ # # ]: 0 : if (!isspace(*c))
733 : 0 : goto nonempty;
734 : 0 : continue;
735 : 0 : nonempty:
736 : 0 : ;
737 : 0 : size_t last = strlen(s)-1;
738 [ # # ]: 0 : if (s[last] == '\n')
739 : 0 : s[last] = '\0';
740 : 0 : int rc = debuginfod_add_http_header(client, s);
741 [ # # ]: 0 : if (rc < 0 && vds >= 0)
742 : 0 : dprintf(vds, "skipping bad header: %s\n", strerror(-rc));
743 : : }
744 : 0 : fclose (f);
745 : : }
746 : :
747 : :
748 : : #define xalloc_str(p, fmt, args...) \
749 : : do \
750 : : { \
751 : : if (asprintf (&p, fmt, args) < 0) \
752 : : { \
753 : : p = NULL; \
754 : : rc = -ENOMEM; \
755 : : goto out; \
756 : : } \
757 : : } while (0)
758 : :
759 : :
760 : : /* Offer a basic form of progress tracing */
761 : : int
762 : 2 : debuginfod_default_progressfn (debuginfod_client *c, long a, long b)
763 : : {
764 : 2 : const char* url = debuginfod_get_url (c);
765 : 2 : int len = 0;
766 : :
767 : : /* We prefer to print the host part of the URL to keep the
768 : : message short. */
769 : 2 : if (url != NULL)
770 : : {
771 : 2 : const char* buildid = strstr(url, "buildid/");
772 [ + - ]: 2 : if (buildid != NULL)
773 : 2 : len = (buildid - url);
774 : : else
775 : 0 : len = strlen(url);
776 : : }
777 : :
778 [ - + ]: 2 : if (b == 0 || url==NULL) /* early stage */
779 : 0 : dprintf(STDERR_FILENO,
780 : 0 : "\rDownloading %c", "-/|\\"[a % 4]);
781 [ - + ]: 2 : else if (b < 0) /* download in progress but unknown total length */
782 : 0 : dprintf(STDERR_FILENO,
783 : : "\rDownloading from %.*s %ld",
784 : : len, url, a);
785 : : else /* download in progress, and known total length */
786 : 2 : dprintf(STDERR_FILENO,
787 : : "\rDownloading from %.*s %ld/%ld",
788 : : len, url, a, b);
789 : 2 : c->default_progressfn_printed_p = 1;
790 : :
791 : 2 : return 0;
792 : : }
793 : :
794 : : /* This is a callback function that receives http response headers in buffer for use
795 : : * in this program. https://curl.se/libcurl/c/CURLOPT_HEADERFUNCTION.html is the
796 : : * online documentation.
797 : : */
798 : : static size_t
799 : 13805 : header_callback (char * buffer, size_t size, size_t numitems, void * userdata)
800 : : {
801 : 13805 : struct handle_data *data = (struct handle_data *) userdata;
802 [ - + ]: 13805 : if (size != 1)
803 : : return 0;
804 [ + - ]: 13805 : if (data->client
805 [ + + ]: 13805 : && data->client->verbose_fd >= 0
806 [ + + ]: 9980 : && numitems > 2)
807 : 8870 : dprintf (data->client->verbose_fd, "header %.*s", (int)numitems, buffer);
808 : : // Some basic checks to ensure the headers received are of the expected format
809 [ + + ]: 13805 : if (strncasecmp(buffer, "X-DEBUGINFOD", 11)
810 [ + + ]: 3218 : || buffer[numitems-2] != '\r'
811 [ + - ]: 3216 : || buffer[numitems-1] != '\n'
812 [ - + ]: 3216 : || (buffer == strstr(buffer, ":")) ){
813 : : return numitems;
814 : : }
815 : : /* Temporary buffer for realloc */
816 : 3216 : char *temp = NULL;
817 : 3216 : temp = realloc(data->response_data, data->response_data_size + numitems);
818 [ - + ]: 3216 : if (temp == NULL)
819 : : return 0;
820 : :
821 : 3216 : memcpy(temp + data->response_data_size, buffer, numitems-1);
822 : 3216 : data->response_data = temp;
823 : 3216 : data->response_data_size += numitems-1;
824 : 3216 : data->response_data[data->response_data_size-1] = '\n';
825 : 3216 : data->response_data[data->response_data_size] = '\0';
826 : 3216 : return numitems;
827 : : }
828 : :
829 : :
830 : : static size_t
831 : 20 : metadata_callback (char * buffer, size_t size, size_t numitems, void * userdata)
832 : : {
833 [ - + ]: 20 : if (size != 1)
834 : : return 0;
835 : : /* Temporary buffer for realloc */
836 : 20 : char *temp = NULL;
837 : 20 : struct handle_data *data = (struct handle_data *) userdata;
838 : 20 : temp = realloc(data->metadata, data->metadata_size + numitems + 1);
839 [ - + ]: 20 : if (temp == NULL)
840 : : return 0;
841 : :
842 : 20 : memcpy(temp + data->metadata_size, buffer, numitems);
843 : 20 : data->metadata = temp;
844 : 20 : data->metadata_size += numitems;
845 : 20 : data->metadata[data->metadata_size] = '\0';
846 : 20 : return numitems;
847 : : }
848 : :
849 : :
850 : : /* This function takes a copy of DEBUGINFOD_URLS, server_urls, and
851 : : * separates it into an array of urls to query, each with a
852 : : * corresponding IMA policy. The url_subdir is either 'buildid' or
853 : : * 'metadata', corresponding to the query type. Returns 0 on success
854 : : * and -Posix error on failure.
855 : : */
856 : : static int
857 : 2060 : init_server_urls(char* url_subdir, const char* type,
858 : : char *server_urls, char ***server_url_list, ima_policy_t **url_ima_policies,
859 : : int *num_urls, int vfd)
860 : : {
861 : : /* Initialize the memory to zero */
862 : 2060 : char *strtok_saveptr;
863 : 2060 : ima_policy_t verification_mode = ignore; // The default mode
864 : 2060 : char *server_url = strtok_r(server_urls, url_delim, &strtok_saveptr);
865 : : /* Count number of URLs. */
866 : 2060 : int n = 0;
867 : :
868 [ + + ]: 4186 : while (server_url != NULL)
869 : : {
870 : : // When we encountered a (well-formed) token off the form
871 : : // ima:foo, we update the policy under which results from that
872 : : // server will be ima verified
873 [ - + ]: 2126 : if (startswith(server_url, "ima:"))
874 : : {
875 : : #ifdef ENABLE_IMA_VERIFICATION
876 : : ima_policy_t m = ima_policy_str2enum(server_url + strlen("ima:"));
877 : : if(m != undefined)
878 : : verification_mode = m;
879 : : else if (vfd >= 0)
880 : : dprintf(vfd, "IMA mode not recognized, skipping %s\n", server_url);
881 : : #else
882 [ # # ]: 0 : if (vfd >= 0)
883 : 0 : dprintf(vfd, "IMA signature verification is not enabled, treating %s as ima:ignore\n", server_url);
884 : : #endif
885 : 0 : goto continue_next_url;
886 : : }
887 : :
888 : 2126 : if (verification_mode==enforcing &&
889 : : 0==strcmp(url_subdir, "buildid") &&
890 : : 0==strcmp(type,"section")) // section queries are unsecurable
891 : : {
892 : : if (vfd >= 0)
893 : : dprintf(vfd, "skipping server %s section query in IMA enforcing mode\n", server_url);
894 : : goto continue_next_url;
895 : : }
896 : :
897 : : // Construct actual URL for libcurl
898 : 2126 : int r;
899 : 2126 : char *tmp_url;
900 [ + - + + ]: 2126 : if (strlen(server_url) > 1 && server_url[strlen(server_url)-1] == '/')
901 : 1112 : r = asprintf(&tmp_url, "%s%s", server_url, url_subdir);
902 : : else
903 : 1014 : r = asprintf(&tmp_url, "%s/%s", server_url, url_subdir);
904 : :
905 [ + - ]: 2126 : if (r == -1)
906 : 0 : return -ENOMEM;
907 : :
908 : : /* PR 27983: If the url is duplicate, skip it */
909 : : int url_index;
910 [ + + ]: 2260 : for (url_index = 0; url_index < n; ++url_index)
911 : : {
912 [ + + ]: 138 : if(strcmp(tmp_url, (*server_url_list)[url_index]) == 0)
913 : : {
914 : : url_index = -1;
915 : : break;
916 : : }
917 : : }
918 [ + + ]: 2126 : if (url_index == -1)
919 : : {
920 [ + - ]: 4 : if (vfd >= 0)
921 : 4 : dprintf(vfd, "duplicate url: %s, skipping\n", tmp_url);
922 : 4 : free(tmp_url);
923 : : }
924 : : else
925 : : {
926 : : /* Have unique URL, save it, along with its IMA verification tag. */
927 : 2122 : n ++;
928 [ + - ]: 2122 : if (NULL == (*server_url_list = reallocarray(*server_url_list, n, sizeof(char*)))
929 [ - + ]: 2122 : || NULL == (*url_ima_policies = reallocarray(*url_ima_policies, n, sizeof(ima_policy_t))))
930 : : {
931 : 0 : free (tmp_url);
932 : 0 : return -ENOMEM;
933 : : }
934 : 2122 : (*server_url_list)[n-1] = tmp_url;
935 : 2122 : if(NULL != url_ima_policies) (*url_ima_policies)[n-1] = verification_mode;
936 : : }
937 : :
938 : 2126 : continue_next_url:
939 : 2126 : server_url = strtok_r(NULL, url_delim, &strtok_saveptr);
940 : : }
941 : 2060 : *num_urls = n;
942 : 2060 : return 0;
943 : : }
944 : :
945 : : /* Some boilerplate for checking curl_easy_setopt. */
946 : : #define curl_easy_setopt_ck(H,O,P) do { \
947 : : CURLcode curl_res = curl_easy_setopt (H,O,P); \
948 : : if (curl_res != CURLE_OK) \
949 : : { \
950 : : if (vfd >= 0) \
951 : : dprintf (vfd, \
952 : : "Bad curl_easy_setopt: %s\n", \
953 : : curl_easy_strerror(curl_res)); \
954 : : return -EINVAL; \
955 : : } \
956 : : } while (0)
957 : :
958 : :
959 : : /*
960 : : * This function initializes a CURL handle. It takes optional callbacks for the write
961 : : * function and the header function, which if defined will use userdata of type struct handle_data*.
962 : : * Specifically the data[i] within an array of struct handle_data's.
963 : : * Returns 0 on success and -Posix error on failure.
964 : : */
965 : : static int
966 : 3206 : init_handle(debuginfod_client *client,
967 : : size_t (*w_callback)(char *buffer, size_t size, size_t nitems, void *userdata),
968 : : size_t (*h_callback)(char *buffer, size_t size, size_t nitems, void *userdata),
969 : : struct handle_data *data, int i, long timeout,
970 : : int vfd)
971 : : {
972 : 3206 : data->handle = curl_easy_init();
973 [ + - ]: 3206 : if (data->handle == NULL)
974 : : return -ENETUNREACH;
975 : :
976 [ + + ]: 3206 : if (vfd >= 0)
977 : 1136 : dprintf (vfd, "url %d %s\n", i, data->url);
978 : :
979 : : /* Only allow http:// + https:// + file:// so we aren't being
980 : : redirected to some unsupported protocol.
981 : : libcurl will fail if we request a single protocol that is not
982 : : available. https missing is the most likely issue */
983 : : #if CURL_AT_LEAST_VERSION(7, 85, 0)
984 [ - + - + : 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_PROTOCOLS_STR,
- - ]
985 : : curl_has_https ? "https,http,file" : "http,file");
986 : : #else
987 : : curl_easy_setopt_ck(data->handle, CURLOPT_PROTOCOLS,
988 : : ((curl_has_https ? CURLPROTO_HTTPS : 0) | CURLPROTO_HTTP | CURLPROTO_FILE));
989 : : #endif
990 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_URL, data->url);
991 [ + + ]: 3206 : if (vfd >= 0)
992 [ - + ]: 1136 : curl_easy_setopt_ck(data->handle, CURLOPT_ERRORBUFFER,
993 : : data->errbuf);
994 [ + - ]: 3206 : if (w_callback)
995 : : {
996 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle,
997 : : CURLOPT_WRITEFUNCTION, w_callback);
998 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_WRITEDATA, data);
999 : : }
1000 [ + - ]: 3206 : if (timeout > 0)
1001 : : {
1002 : : /* Make sure there is at least some progress,
1003 : : try to get at least 100K per timeout seconds. */
1004 [ - + - - ]: 3206 : curl_easy_setopt_ck (data->handle, CURLOPT_LOW_SPEED_TIME,
1005 : : timeout);
1006 [ - + - - ]: 3206 : curl_easy_setopt_ck (data->handle, CURLOPT_LOW_SPEED_LIMIT,
1007 : : 100 * 1024L);
1008 : : }
1009 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_FILETIME, (long) 1);
1010 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_FOLLOWLOCATION, (long) 1);
1011 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_MAXREDIRS, (long) 6);
1012 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_FAILONERROR, (long) 1);
1013 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_NOSIGNAL, (long) 1);
1014 [ + - ]: 3206 : if (h_callback)
1015 : : {
1016 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle,
1017 : : CURLOPT_HEADERFUNCTION, h_callback);
1018 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_HEADERDATA, data);
1019 : : }
1020 : : #if LIBCURL_VERSION_NUM >= 0x072a00 /* 7.42.0 */
1021 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_PATH_AS_IS, (long) 1);
1022 : : #else
1023 : : /* On old curl; no big deal, canonicalization here is almost the
1024 : : same, except perhaps for ? # type decorations at the tail. */
1025 : : #endif
1026 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_AUTOREFERER, (long) 1);
1027 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_ACCEPT_ENCODING, "");
1028 [ - + - - ]: 3206 : curl_easy_setopt_ck(data->handle, CURLOPT_HTTPHEADER, client->headers);
1029 : :
1030 : : return 0;
1031 : : }
1032 : :
1033 : :
1034 : : /*
1035 : : * This function busy-waits on one or more curl queries to complete. This can
1036 : : * be controlled via only_one, which, if true, will find the first winner and exit
1037 : : * once found. If positive maxtime and maxsize dictate the maximum allowed wait times
1038 : : * and download sizes respectively. Returns 0 on success and -Posix error on failure.
1039 : : */
1040 : : static int
1041 : 3144 : perform_queries(CURLM *curlm, CURL **target_handle, struct handle_data *data, debuginfod_client *c,
1042 : : int num_urls, long maxtime, long maxsize, bool only_one, int vfd, int *committed_to)
1043 : : {
1044 : 3144 : int still_running = -1;
1045 : 3144 : long loops = 0;
1046 : 3144 : *committed_to = -1;
1047 : 3144 : bool verbose_reported = false;
1048 : 3144 : struct timespec start_time, cur_time;
1049 [ - + ]: 3144 : if (c->winning_headers != NULL)
1050 : : {
1051 : 0 : free (c->winning_headers);
1052 : 0 : c->winning_headers = NULL;
1053 : : }
1054 [ + + - + ]: 3144 : if (maxtime > 0 && clock_gettime(CLOCK_MONOTONIC_RAW, &start_time) == -1)
1055 : 0 : return -errno;
1056 : 7302 : long delta = 0;
1057 : 7302 : do
1058 : : {
1059 : : /* Check to see how long querying is taking. */
1060 [ + + ]: 7302 : if (maxtime > 0)
1061 : : {
1062 [ - + ]: 5 : if (clock_gettime(CLOCK_MONOTONIC_RAW, &cur_time) == -1)
1063 : 0 : return -errno;
1064 : 5 : delta = cur_time.tv_sec - start_time.tv_sec;
1065 [ - + ]: 5 : if ( delta > maxtime)
1066 : : {
1067 : 0 : dprintf(vfd, "Timeout with max time=%lds and transfer time=%lds\n", maxtime, delta );
1068 : 0 : return -ETIME;
1069 : : }
1070 : : }
1071 : : /* Wait 1 second, the minimum DEBUGINFOD_TIMEOUT. */
1072 : 7302 : curl_multi_wait(curlm, NULL, 0, 1000, NULL);
1073 : 7302 : CURLMcode curlm_res = curl_multi_perform(curlm, &still_running);
1074 : :
1075 [ + + ]: 7302 : if (only_one)
1076 : : {
1077 : : /* If the target file has been found, abort the other queries. */
1078 [ + - + + ]: 7232 : if (target_handle && *target_handle != NULL)
1079 : : {
1080 [ + + ]: 5580 : for (int i = 0; i < num_urls; i++)
1081 [ + + ]: 3462 : if (data[i].handle != *target_handle)
1082 : 1344 : curl_multi_remove_handle(curlm, data[i].handle);
1083 : : else
1084 : : {
1085 : 2118 : *committed_to = i;
1086 [ + + ]: 2118 : if (c->winning_headers == NULL)
1087 : : {
1088 : 1460 : c->winning_headers = data[*committed_to].response_data;
1089 [ + + + - ]: 1460 : if (vfd >= 0 && c->winning_headers != NULL)
1090 : 1104 : dprintf(vfd, "\n%s", c->winning_headers);
1091 : 1460 : data[*committed_to].response_data = NULL;
1092 : 1460 : data[*committed_to].response_data_size = 0;
1093 : : }
1094 : : }
1095 : : }
1096 : :
1097 [ + + + + ]: 7232 : if (vfd >= 0 && !verbose_reported && *committed_to >= 0)
1098 : : {
1099 [ - + - - ]: 2208 : bool pnl = (c->default_progressfn_printed_p && vfd == STDERR_FILENO);
1100 : 1104 : dprintf (vfd, "%scommitted to url %d\n", pnl ? "\n" : "",
1101 : : *committed_to);
1102 [ - + ]: 1104 : if (pnl)
1103 : 0 : c->default_progressfn_printed_p = 0;
1104 : : verbose_reported = true;
1105 : : }
1106 : : }
1107 : :
1108 [ - + ]: 7302 : if (curlm_res != CURLM_OK)
1109 : : {
1110 [ # # # ]: 0 : switch (curlm_res)
1111 : : {
1112 : 0 : case CURLM_CALL_MULTI_PERFORM: continue;
1113 : : case CURLM_OUT_OF_MEMORY: return -ENOMEM;
1114 : 0 : default: return -ENETUNREACH;
1115 : : }
1116 : : }
1117 : :
1118 : 7302 : long dl_size = -1;
1119 [ + + + + : 7302 : if (target_handle && *target_handle && (c->progressfn || maxsize > 0))
+ + - + ]
1120 : : {
1121 : : /* Get size of file being downloaded. NB: If going through
1122 : : deflate-compressing proxies, this number is likely to be
1123 : : unavailable, so -1 may show. */
1124 : 1026 : CURLcode curl_res;
1125 : : #if CURL_AT_LEAST_VERSION(7, 55, 0)
1126 : 1026 : curl_off_t cl;
1127 : 1026 : curl_res = curl_easy_getinfo(*target_handle,
1128 : : CURLINFO_CONTENT_LENGTH_DOWNLOAD_T,
1129 : : &cl);
1130 [ + - - + ]: 1026 : if (curl_res == CURLE_OK && cl >= 0)
1131 : : dl_size = (cl > LONG_MAX ? LONG_MAX : (long)cl);
1132 : : #else
1133 : : double cl;
1134 : : curl_res = curl_easy_getinfo(*target_handle,
1135 : : CURLINFO_CONTENT_LENGTH_DOWNLOAD,
1136 : : &cl);
1137 : : if (curl_res == CURLE_OK && cl >= 0)
1138 : : dl_size = (cl >= (double)(LONG_MAX+1UL) ? LONG_MAX : (long)cl);
1139 : : #endif
1140 : : /* If Content-Length is -1, try to get the size from
1141 : : X-Debuginfod-Size */
1142 [ # # ]: 0 : if (dl_size == -1 && c->winning_headers != NULL)
1143 : : {
1144 : 0 : long xdl;
1145 : 0 : char *hdr = strcasestr(c->winning_headers, "x-debuginfod-size");
1146 : 0 : size_t off = strlen("x-debuginfod-size:");
1147 : :
1148 [ # # # # ]: 0 : if (hdr != NULL && sscanf(hdr + off, "%ld", &xdl) == 1)
1149 : 0 : dl_size = xdl;
1150 : : }
1151 : : }
1152 : :
1153 [ + + ]: 7302 : if (c->progressfn) /* inform/check progress callback */
1154 : : {
1155 : 5048 : loops ++;
1156 : 5048 : long pa = loops; /* default param for progress callback */
1157 [ + + + + ]: 5048 : if (target_handle && *target_handle) /* we've committed to a server; report its download progress */
1158 : : {
1159 : : /* PR30809: Check actual size of cached file. This same
1160 : : fd is shared by all the multi-curl handles (but only
1161 : : one will end up writing to it). Another way could be
1162 : : to tabulate totals in debuginfod_write_callback(). */
1163 : 1026 : struct stat cached;
1164 : 1026 : int statrc = fstat(data[*committed_to].fd, &cached);
1165 [ + - ]: 1026 : if (statrc == 0)
1166 : 1026 : pa = (long) cached.st_size;
1167 : : else
1168 : : {
1169 : : /* Otherwise, query libcurl for its tabulated total.
1170 : : However, that counts http body length, not
1171 : : decoded/decompressed content length, so does not
1172 : : measure quite the same thing as dl. */
1173 : 0 : CURLcode curl_res;
1174 : : #if CURL_AT_LEAST_VERSION(7, 55, 0)
1175 : 0 : curl_off_t dl;
1176 : 0 : curl_res = curl_easy_getinfo(target_handle,
1177 : : CURLINFO_SIZE_DOWNLOAD_T,
1178 : : &dl);
1179 [ # # # # ]: 0 : if (curl_res == 0 && dl >= 0)
1180 : 0 : pa = (dl > LONG_MAX ? LONG_MAX : (long)dl);
1181 : : #else
1182 : : double dl;
1183 : : curl_res = curl_easy_getinfo(target_handle,
1184 : : CURLINFO_SIZE_DOWNLOAD,
1185 : : &dl);
1186 : : if (curl_res == 0)
1187 : : pa = (dl >= (double)(LONG_MAX+1UL) ? LONG_MAX : (long)dl);
1188 : : #endif
1189 : : }
1190 : :
1191 [ - + - + ]: 1026 : if ((*c->progressfn) (c, pa, dl_size == -1 ? 0 : dl_size))
1192 : : {
1193 : 0 : c->progressfn_cancel = true;
1194 : 0 : break;
1195 : : }
1196 : : }
1197 : : }
1198 : : /* Check to see if we are downloading something which exceeds maxsize, if set.*/
1199 [ + + + + : 7270 : if (target_handle && *target_handle && dl_size > maxsize && maxsize > 0)
- + ]
1200 : : {
1201 [ # # ]: 0 : if (vfd >=0)
1202 : 0 : dprintf(vfd, "Content-Length too large.\n");
1203 : 0 : return -EFBIG;
1204 : : }
1205 [ + + ]: 7302 : } while (still_running);
1206 : :
1207 : : return 0;
1208 : : }
1209 : :
1210 : :
1211 : : /* Copy SRC to DEST, s,/,#,g */
1212 : :
1213 : : static void
1214 : 1158 : path_escape (const char *src, char *dest, size_t dest_len)
1215 : : {
1216 : : /* PR32218: Reversibly-escaping src character-by-character, for
1217 : : large enough strings, risks ENAMETOOLONG errors. For long names,
1218 : : a simple hash based generated name instead, while still
1219 : : attempting to preserve the as much of the content as possible.
1220 : : It's possible that absurd choices of incoming names will collide
1221 : : or still get truncated, but c'est la vie.
1222 : : */
1223 : :
1224 : : /* Compute a three-way min() for the actual output string generated. */
1225 [ - + ]: 1158 : assert (dest_len > 10); /* Space enough for degenerate case of
1226 : : "HASHHASH-\0". NB: dest_len is not
1227 : : user-controlled. */
1228 : : /* Use only NAME_MAX/2 characters in the output file name.
1229 : : ENAMETOOLONG has been observed even on 300-ish character names on
1230 : : some filesystems. */
1231 : 1158 : const size_t max_dest_len = NAME_MAX/2;
1232 : 1158 : dest_len = dest_len > max_dest_len ? max_dest_len : dest_len;
1233 : : /* Use only strlen(src)+10 bytes, if that's smaller. Yes, we could
1234 : : just fit an entire escaped name in there in theory, without the
1235 : : hash+etc. But then again the hashing protects against #-escape
1236 : : aliasing collisions: "foo[bar" "foo]bar" both escape to
1237 : : "foo#bar", thus aliasing, but have different "HASH-foo#bar".
1238 : : */
1239 : 1158 : const size_t hash_prefix_destlen = strlen(src)+10; /* DEADBEEF-src\0 */
1240 : 1158 : dest_len = dest_len > hash_prefix_destlen ? hash_prefix_destlen : dest_len;
1241 : :
1242 : 1158 : char *dest_write = dest + dest_len - 1;
1243 : 1158 : (*dest_write--) = '\0'; /* Ensure a \0 there. */
1244 : :
1245 : : /* Copy from back toward front, preferring to keep the .extension. */
1246 [ + + ]: 87880 : for (int fi=strlen(src)-1; fi >= 0 && dest_write >= dest; fi--)
1247 : : {
1248 : 86722 : char src_char = src[fi];
1249 [ + + ]: 86722 : switch (src_char)
1250 : : {
1251 : : /* Pass through ordinary identifier chars. */
1252 : 77666 : case '.': case '-': case '_':
1253 : : case 'a'...'z':
1254 : : case 'A'...'Z':
1255 : : case '0'...'9':
1256 : 77666 : *dest_write-- = src_char;
1257 : 77666 : break;
1258 : :
1259 : : /* Replace everything else, esp. security-sensitive /. */
1260 : 9056 : default:
1261 : 9056 : *dest_write-- = '#';
1262 : 9056 : break;
1263 : : }
1264 : : }
1265 : :
1266 : : /* djb2 hash algorithm: DJBX33A */
1267 : : unsigned long hash = 5381;
1268 : : const char *c = src;
1269 [ + + ]: 88682 : while (*c)
1270 : 87524 : hash = ((hash << 5) + hash) + *c++;
1271 : 1158 : char name_hash_str [9];
1272 : : /* Truncate to 4 bytes; along with the remaining hundredish bytes of text,
1273 : : should be ample against accidental collisions. */
1274 : 1158 : snprintf (name_hash_str, sizeof(name_hash_str), "%08x", (unsigned int) hash);
1275 : 1158 : memcpy (&dest[0], name_hash_str, 8); /* Overwrite the first few characters */
1276 : 1158 : dest[8] = '-'; /* Add a bit of punctuation to make hash stand out */
1277 : 1158 : }
1278 : :
1279 : : /* Attempt to update the atime */
1280 : : static void
1281 : 114 : update_atime (int fd)
1282 : : {
1283 : 114 : struct timespec tvs[2];
1284 : :
1285 : 114 : tvs[0].tv_sec = tvs[1].tv_sec = 0;
1286 : 114 : tvs[0].tv_nsec = UTIME_NOW;
1287 : 114 : tvs[1].tv_nsec = UTIME_OMIT;
1288 : :
1289 : 114 : (void) futimens (fd, tvs); /* best effort */
1290 : 114 : }
1291 : :
1292 : : /* Attempt to read an ELF/DWARF section with name SECTION from FD and write
1293 : : it to a separate file in the debuginfod cache. If successful the absolute
1294 : : path of the separate file containing SECTION will be stored in USR_PATH.
1295 : : FD_PATH is the absolute path for FD.
1296 : :
1297 : : If the section cannot be extracted, then return a negative error code.
1298 : : -ENOENT indicates that the parent file was able to be read but the
1299 : : section name was not found. -EEXIST indicates that the section was
1300 : : found but had type SHT_NOBITS. */
1301 : :
1302 : : static int
1303 : 12 : extract_section (int fd, const char *section, char *fd_path, char **usr_path)
1304 : : {
1305 : 12 : elf_version (EV_CURRENT);
1306 : :
1307 : 12 : Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
1308 [ + - ]: 12 : if (elf == NULL)
1309 : : return -EIO;
1310 : :
1311 : 12 : size_t shstrndx;
1312 : 12 : int rc = elf_getshdrstrndx (elf, &shstrndx);
1313 [ - + ]: 12 : if (rc < 0)
1314 : : {
1315 : 0 : rc = -EIO;
1316 : 0 : goto out;
1317 : : }
1318 : :
1319 : 12 : int sec_fd = -1;
1320 : 12 : char *sec_path_tmp = NULL;
1321 : 12 : Elf_Scn *scn = NULL;
1322 : :
1323 : : /* Try to find the target section and copy the contents into a
1324 : : separate file. */
1325 : 424 : while (true)
1326 : 206 : {
1327 : 218 : scn = elf_nextscn (elf, scn);
1328 [ - + ]: 218 : if (scn == NULL)
1329 : : {
1330 : 0 : rc = -ENOENT;
1331 : 4 : goto out;
1332 : : }
1333 : 218 : GElf_Shdr shdr_storage;
1334 : 218 : GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
1335 [ - + ]: 218 : if (shdr == NULL)
1336 : : {
1337 : 0 : rc = -EIO;
1338 : 0 : goto out;
1339 : : }
1340 : :
1341 : 218 : const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
1342 [ - + ]: 218 : if (scn_name == NULL)
1343 : : {
1344 : 0 : rc = -EIO;
1345 : 0 : goto out;
1346 : : }
1347 [ + + ]: 218 : if (strcmp (scn_name, section) == 0)
1348 : : {
1349 : : /* We found the desired section. */
1350 [ + + ]: 12 : if (shdr->sh_type == SHT_NOBITS)
1351 : : {
1352 : 4 : rc = -EEXIST;
1353 : 4 : goto out;
1354 : : }
1355 : :
1356 : 8 : Elf_Data *data = NULL;
1357 : 8 : data = elf_rawdata (scn, NULL);
1358 [ - + ]: 8 : if (data == NULL)
1359 : : {
1360 : 0 : rc = -EIO;
1361 : 0 : goto out;
1362 : : }
1363 : :
1364 [ - + ]: 8 : if (data->d_buf == NULL)
1365 : : {
1366 : 0 : rc = -EIO;
1367 : 0 : goto out;
1368 : : }
1369 : :
1370 : : /* Compute the absolute filename we'll write the section to.
1371 : : Replace the last component of FD_PATH with the path-escaped
1372 : : section filename. */
1373 : 8 : int i = strlen (fd_path);
1374 [ + - ]: 92 : while (i >= 0)
1375 : : {
1376 [ + + ]: 92 : if (fd_path[i] == '/')
1377 : : {
1378 : 8 : fd_path[i] = '\0';
1379 : 8 : break;
1380 : : }
1381 : 84 : --i;
1382 : : }
1383 : :
1384 : 8 : char suffix[NAME_MAX];
1385 : 8 : path_escape (section, suffix, sizeof(suffix));
1386 : 8 : rc = asprintf (&sec_path_tmp, "%s/section-%s.XXXXXX",
1387 : : fd_path, suffix);
1388 [ - + ]: 8 : if (rc == -1)
1389 : : {
1390 : 0 : rc = -ENOMEM;
1391 : 0 : goto out1;
1392 : : }
1393 : :
1394 : 8 : sec_fd = mkstemp (sec_path_tmp);
1395 [ - + ]: 8 : if (sec_fd < 0)
1396 : : {
1397 : 0 : rc = -EIO;
1398 : 8 : goto out2;
1399 : : }
1400 : :
1401 : 8 : ssize_t res = write_retry (sec_fd, data->d_buf, data->d_size);
1402 [ + - - + ]: 8 : if (res < 0 || (size_t) res != data->d_size)
1403 : : {
1404 : 0 : rc = -EIO;
1405 : 0 : goto out3;
1406 : : }
1407 : :
1408 : : /* Success. Rename tmp file and update USR_PATH. */
1409 : 8 : char *sec_path;
1410 [ - + ]: 8 : if (asprintf (&sec_path, "%s/section-%s", fd_path, section) == -1)
1411 : : {
1412 : 0 : rc = -ENOMEM;
1413 : 0 : goto out3;
1414 : : }
1415 : :
1416 : 8 : rc = rename (sec_path_tmp, sec_path);
1417 [ - + ]: 8 : if (rc < 0)
1418 : : {
1419 : 0 : free (sec_path);
1420 : 0 : rc = -EIO;
1421 : 0 : goto out3;
1422 : : }
1423 : :
1424 [ + - ]: 8 : if (usr_path != NULL)
1425 : 8 : *usr_path = sec_path;
1426 : : else
1427 : 0 : free (sec_path);
1428 : 8 : update_atime(fd);
1429 : 8 : rc = sec_fd;
1430 : 8 : goto out2;
1431 : : }
1432 : : }
1433 : :
1434 : 0 : out3:
1435 : 0 : close (sec_fd);
1436 : 0 : unlink (sec_path_tmp);
1437 : :
1438 : 8 : out2:
1439 : 8 : free (sec_path_tmp);
1440 : :
1441 : 12 : out1:
1442 : 12 : out:
1443 : 12 : elf_end (elf);
1444 : 12 : return rc;
1445 : : }
1446 : :
1447 : : /* Search TARGET_CACHE_DIR for a debuginfo or executable file containing
1448 : : an ELF/DWARF section with name SCN_NAME. If found, extract the section
1449 : : to a separate file in TARGET_CACHE_DIR and return a file descriptor
1450 : : for the section file. The path for this file will be stored in USR_PATH.
1451 : : Return a negative errno if unsuccessful. -ENOENT indicates that SCN_NAME
1452 : : is confirmed to not exist. */
1453 : :
1454 : : static int
1455 : 16 : cache_find_section (const char *scn_name, const char *target_cache_dir,
1456 : : char **usr_path)
1457 : : {
1458 : 16 : int debug_fd;
1459 : 16 : int rc = -EEXIST;
1460 : 16 : char parent_path[PATH_MAX];
1461 : :
1462 : : /* Check the debuginfo first. */
1463 : 16 : snprintf (parent_path, PATH_MAX, "%s/debuginfo", target_cache_dir);
1464 : 16 : debug_fd = open (parent_path, O_RDONLY);
1465 [ + + ]: 16 : if (debug_fd >= 0)
1466 : : {
1467 : 8 : rc = extract_section (debug_fd, scn_name, parent_path, usr_path);
1468 : 8 : close (debug_fd);
1469 : : }
1470 : :
1471 : : /* If the debuginfo file couldn't be found or the section type was
1472 : : SHT_NOBITS, check the executable. */
1473 [ + + ]: 8 : if (rc == -EEXIST)
1474 : : {
1475 : 12 : snprintf (parent_path, PATH_MAX, "%s/executable", target_cache_dir);
1476 : 12 : int exec_fd = open (parent_path, O_RDONLY);
1477 : :
1478 [ + + ]: 12 : if (exec_fd >= 0)
1479 : : {
1480 : 4 : rc = extract_section (exec_fd, scn_name, parent_path, usr_path);
1481 : 4 : close (exec_fd);
1482 : :
1483 : : /* Don't return -ENOENT if the debuginfo wasn't opened. The
1484 : : section may exist in the debuginfo but not the executable. */
1485 [ - + ]: 4 : if (debug_fd < 0 && rc == -ENOENT)
1486 : 0 : rc = -EREMOTE;
1487 : : }
1488 : : }
1489 : :
1490 : 16 : return rc;
1491 : : }
1492 : :
1493 : :
1494 : : #ifdef ENABLE_IMA_VERIFICATION
1495 : : /* Extract the hash algorithm name from the signature header, of which
1496 : : there are several types. The name will be used for openssl hashing
1497 : : of the file content. The header doesn't need to be super carefully
1498 : : parsed, because if any part of it is wrong, be it the hash
1499 : : algorithm number or hash value or whatever, it will fail
1500 : : computation or verification. Return NULL in case of error. */
1501 : : static const char*
1502 : : get_signature_params(debuginfod_client *c, unsigned char *bin_sig)
1503 : : {
1504 : : int hashalgo = 0;
1505 : :
1506 : : switch (bin_sig[0])
1507 : : {
1508 : : case EVM_IMA_XATTR_DIGSIG:
1509 : : #ifdef IMA_VERITY_DIGSIG /* missing on debian-i386 trybot */
1510 : : case IMA_VERITY_DIGSIG:
1511 : : #endif
1512 : : break;
1513 : : default:
1514 : : if (c->verbose_fd >= 0)
1515 : : dprintf (c->verbose_fd, "Unknown ima digsig %d\n", (int)bin_sig[0]);
1516 : : return NULL;
1517 : : }
1518 : :
1519 : : switch (bin_sig[1])
1520 : : {
1521 : : case DIGSIG_VERSION_2:
1522 : : {
1523 : : struct signature_v2_hdr hdr_v2;
1524 : : memcpy(& hdr_v2, & bin_sig[1], sizeof(struct signature_v2_hdr));
1525 : : hashalgo = hdr_v2.hash_algo;
1526 : : break;
1527 : : }
1528 : : default:
1529 : : if (c->verbose_fd >= 0)
1530 : : dprintf (c->verbose_fd, "Unknown ima signature version %d\n", (int)bin_sig[1]);
1531 : : return NULL;
1532 : : }
1533 : :
1534 : : switch (hashalgo)
1535 : : {
1536 : : case PKEY_HASH_SHA1: return "sha1";
1537 : : case PKEY_HASH_SHA256: return "sha256";
1538 : : // (could add many others from enum pkey_hash_algo)
1539 : : default:
1540 : : if (c->verbose_fd >= 0)
1541 : : dprintf (c->verbose_fd, "Unknown ima pkey hash %d\n", hashalgo);
1542 : : return NULL;
1543 : : }
1544 : : }
1545 : :
1546 : :
1547 : : /* Verify given hash against given signature blob. Return 0 on ok, -errno otherwise. */
1548 : : static int
1549 : : debuginfod_verify_hash(debuginfod_client *c, const unsigned char *hash, int size,
1550 : : const char *hash_algo, unsigned char *sig, int siglen)
1551 : : {
1552 : : int ret = -EBADMSG;
1553 : : struct public_key_entry *pkey;
1554 : : struct signature_v2_hdr hdr;
1555 : : EVP_PKEY_CTX *ctx;
1556 : : const EVP_MD *md;
1557 : :
1558 : : memcpy(&hdr, sig, sizeof(struct signature_v2_hdr)); /* avoid just aliasing */
1559 : :
1560 : : if (c->verbose_fd >= 0)
1561 : : dprintf (c->verbose_fd, "Searching for ima keyid %04x\n", ntohl(hdr.keyid));
1562 : :
1563 : : /* Find the matching public key. */
1564 : : for (pkey = c->ima_public_keys; pkey != NULL; pkey = pkey->next)
1565 : : if (pkey->keyid == ntohl(hdr.keyid)) break;
1566 : : if (!pkey)
1567 : : return -ENOKEY;
1568 : :
1569 : : if (!(ctx = EVP_PKEY_CTX_new(pkey->key, NULL)))
1570 : : goto err;
1571 : : if (!EVP_PKEY_verify_init(ctx))
1572 : : goto err;
1573 : : if (!(md = EVP_get_digestbyname(hash_algo)))
1574 : : goto err;
1575 : : if (!EVP_PKEY_CTX_set_signature_md(ctx, md))
1576 : : goto err;
1577 : : ret = EVP_PKEY_verify(ctx, sig + sizeof(hdr),
1578 : : siglen - sizeof(hdr), hash, size);
1579 : : if (ret == 1)
1580 : : ret = 0; // success!
1581 : : else if (ret == 0)
1582 : : ret = -EBADMSG;
1583 : : err:
1584 : : EVP_PKEY_CTX_free(ctx);
1585 : : return ret;
1586 : : }
1587 : :
1588 : :
1589 : :
1590 : : /* Validate an IMA file signature.
1591 : : * Returns 0 on signature validity, -EINVAL on signature invalidity, -ENOSYS on undefined imaevm machinery,
1592 : : * -ENOKEY on key issues, or other -errno.
1593 : : */
1594 : :
1595 : : static int
1596 : : debuginfod_validate_imasig (debuginfod_client *c, int fd)
1597 : : {
1598 : : int rc = ENOSYS;
1599 : :
1600 : : char* sig_buf = NULL;
1601 : : EVP_MD_CTX *ctx = NULL;
1602 : : if (!c || !c->winning_headers)
1603 : : {
1604 : : rc = -ENODATA;
1605 : : goto exit_validate;
1606 : : }
1607 : : // Extract the HEX IMA-signature from the header
1608 : : char* hdr_ima_sig = strcasestr(c->winning_headers, "x-debuginfod-imasignature");
1609 : : if (!hdr_ima_sig || 1 != sscanf(hdr_ima_sig + strlen("x-debuginfod-imasignature:"), "%ms", &sig_buf))
1610 : : {
1611 : : rc = -ENODATA;
1612 : : goto exit_validate;
1613 : : }
1614 : : if (strlen(sig_buf) > MAX_SIGNATURE_SIZE) // reject if too long
1615 : : {
1616 : : rc = -EBADMSG;
1617 : : goto exit_validate;
1618 : : }
1619 : : // Convert the hex signature to bin
1620 : : size_t bin_sig_len = strlen(sig_buf)/2;
1621 : : unsigned char bin_sig[MAX_SIGNATURE_SIZE/2];
1622 : : for (size_t b = 0; b < bin_sig_len; b++)
1623 : : bin_sig[b] = (hex2dec(sig_buf[2*b]) << 4) | hex2dec(sig_buf[2*b+1]);
1624 : :
1625 : : // Compute the binary digest of the cached file (with file descriptor fd)
1626 : : ctx = EVP_MD_CTX_new();
1627 : : const char* sighash_name = get_signature_params(c, bin_sig) ?: "";
1628 : : const EVP_MD *md = EVP_get_digestbyname(sighash_name);
1629 : : if (!ctx || !md || !EVP_DigestInit(ctx, md))
1630 : : {
1631 : : rc = -EBADMSG;
1632 : : goto exit_validate;
1633 : : }
1634 : :
1635 : : long data_len;
1636 : : char* hdr_data_len = strcasestr(c->winning_headers, "x-debuginfod-size");
1637 : : if (!hdr_data_len || 1 != sscanf(hdr_data_len + strlen("x-debuginfod-size:") , "%ld", &data_len))
1638 : : {
1639 : : rc = -ENODATA;
1640 : : goto exit_validate;
1641 : : }
1642 : :
1643 : : /* Don't trust the size the server sent us, double check against the
1644 : : file size that we actually got. That way we calculate the hash
1645 : : over the whole file and not a shorter (possibly empty) data size. */
1646 : : struct stat st;
1647 : : if (fstat (fd, &st) == -1)
1648 : : {
1649 : : rc = -errno;
1650 : : goto exit_validate;
1651 : : }
1652 : : if (data_len != st.st_size)
1653 : : {
1654 : : rc = -EBADMSG;
1655 : : goto exit_validate;
1656 : : }
1657 : :
1658 : : char file_data[DATA_SIZE]; // imaevm.h data chunk hash size
1659 : : ssize_t n;
1660 : : for(off_t k = 0; k < data_len; k += n)
1661 : : {
1662 : : if (-1 == (n = pread(fd, file_data, DATA_SIZE, k)))
1663 : : {
1664 : : rc = -errno;
1665 : : goto exit_validate;
1666 : : }
1667 : :
1668 : : if (!EVP_DigestUpdate(ctx, file_data, n))
1669 : : {
1670 : : rc = -EBADMSG;
1671 : : goto exit_validate;
1672 : : }
1673 : : }
1674 : :
1675 : : uint8_t bin_dig[MAX_DIGEST_SIZE];
1676 : : unsigned int bin_dig_len;
1677 : : if (!EVP_DigestFinal(ctx, bin_dig, &bin_dig_len))
1678 : : {
1679 : : rc = -EBADMSG;
1680 : : goto exit_validate;
1681 : : }
1682 : :
1683 : : // XXX: in case of DIGSIG_VERSION_3, need to hash the file hash, yo dawg
1684 : :
1685 : : int res = debuginfod_verify_hash(c,
1686 : : bin_dig, bin_dig_len,
1687 : : sighash_name,
1688 : : & bin_sig[1], bin_sig_len-1); // skip over first byte of signature
1689 : : if (c->verbose_fd >= 0)
1690 : : dprintf (c->verbose_fd, "Computed ima signature verification res=%d\n", res);
1691 : : rc = res;
1692 : :
1693 : : exit_validate:
1694 : : free (sig_buf);
1695 : : EVP_MD_CTX_free(ctx);
1696 : : return rc;
1697 : : }
1698 : : #endif /* ENABLE_IMA_VERIFICATION */
1699 : :
1700 : :
1701 : :
1702 : :
1703 : : /* Helper function to create client cache directory.
1704 : : $XDG_CACHE_HOME takes priority over $HOME/.cache.
1705 : : $DEBUGINFOD_CACHE_PATH takes priority over $HOME/.cache and $XDG_CACHE_HOME.
1706 : :
1707 : : Return resulting path name or NULL on error. Caller must free resulting string.
1708 : : */
1709 : : static char *
1710 : 2134 : make_cache_path(void)
1711 : : {
1712 : 2134 : char* cache_path = NULL;
1713 : 2134 : int rc = 0;
1714 : : /* Determine location of the cache. The path specified by the debuginfod
1715 : : cache environment variable takes priority. */
1716 : 2134 : char *cache_var = getenv(DEBUGINFOD_CACHE_PATH_ENV_VAR);
1717 [ + - + + ]: 2134 : if (cache_var != NULL && strlen (cache_var) > 0)
1718 [ - + ]: 2126 : xalloc_str (cache_path, "%s", cache_var);
1719 : : else
1720 : : {
1721 : : /* If a cache already exists in $HOME ('/' if $HOME isn't set), then use
1722 : : that. Otherwise use the XDG cache directory naming format. */
1723 [ - + - + ]: 16 : xalloc_str (cache_path, "%s/%s", getenv ("HOME") ?: "/", cache_default_name);
1724 : :
1725 : 8 : struct stat st;
1726 [ + + ]: 8 : if (stat (cache_path, &st) < 0)
1727 : : {
1728 : 6 : char cachedir[PATH_MAX];
1729 : 6 : char *xdg = getenv ("XDG_CACHE_HOME");
1730 : :
1731 [ + - + + ]: 6 : if (xdg != NULL && strlen (xdg) > 0)
1732 : 2 : snprintf (cachedir, PATH_MAX, "%s", xdg);
1733 : : else
1734 [ - + ]: 4 : snprintf (cachedir, PATH_MAX, "%s/.cache", getenv ("HOME") ?: "/");
1735 : :
1736 : : /* Create XDG cache directory if it doesn't exist. */
1737 [ + + ]: 6 : if (stat (cachedir, &st) == 0)
1738 : : {
1739 [ - + ]: 2 : if (! S_ISDIR (st.st_mode))
1740 : : {
1741 : 0 : rc = -EEXIST;
1742 : 0 : goto out1;
1743 : : }
1744 : : }
1745 : : else
1746 : : {
1747 : 4 : rc = mkdir (cachedir, 0700);
1748 : :
1749 : : /* Also check for EEXIST and S_ISDIR in case another client just
1750 : : happened to create the cache. */
1751 [ - + ]: 4 : if (rc < 0
1752 [ # # ]: 0 : && (errno != EEXIST
1753 [ # # ]: 0 : || stat (cachedir, &st) != 0
1754 [ # # ]: 0 : || ! S_ISDIR (st.st_mode)))
1755 : : {
1756 : 0 : rc = -errno;
1757 : 0 : goto out1;
1758 : : }
1759 : : }
1760 : :
1761 : 6 : free (cache_path);
1762 [ - + ]: 6 : xalloc_str (cache_path, "%s/%s", cachedir, cache_xdg_name);
1763 : : }
1764 : : }
1765 : :
1766 : 2134 : goto out;
1767 : :
1768 : 0 : out1:
1769 : 0 : (void) rc;
1770 : 0 : free (cache_path);
1771 : 0 : cache_path = NULL;
1772 : :
1773 : 2134 : out:
1774 [ + - ]: 2134 : if (cache_path != NULL)
1775 : 2134 : (void) mkdir (cache_path, 0700); // failures with this mkdir would be caught later too
1776 : 2134 : return cache_path;
1777 : : }
1778 : :
1779 : :
1780 : : /* Query each of the server URLs found in $DEBUGINFOD_URLS for the file
1781 : : with the specified build-id and type (debuginfo, executable, source or
1782 : : section). If type is source, then type_arg should be a filename. If
1783 : : type is section, then type_arg should be the name of an ELF/DWARF
1784 : : section. Otherwise type_arg may be NULL. Return a file descriptor
1785 : : for the target if successful, otherwise return an error code.
1786 : : */
1787 : : static int
1788 : 6518 : debuginfod_query_server_by_buildid (debuginfod_client *c,
1789 : : const unsigned char *build_id,
1790 : : int build_id_len,
1791 : : const char *type,
1792 : : const char *type_arg,
1793 : : char **path)
1794 : : {
1795 : 6518 : char *server_urls;
1796 : 6518 : char *urls_envvar;
1797 : 6518 : const char *section = NULL;
1798 : 6518 : const char *filename = NULL;
1799 : 6518 : char *cache_path = NULL;
1800 : 6518 : char *maxage_path = NULL;
1801 : 6518 : char *interval_path = NULL;
1802 : 6518 : char *cache_miss_path = NULL;
1803 : 6518 : char *target_cache_dir = NULL;
1804 : 6518 : char *target_cache_path = NULL;
1805 : 6518 : char *target_cachehdr_path = NULL;
1806 : 6518 : char *target_cache_tmppath = NULL;
1807 : 6518 : char *target_cachehdr_tmppath = NULL;
1808 : 6518 : char suffix[NAME_MAX];
1809 : 6518 : char build_id_bytes[MAX_BUILD_ID_BYTES * 2 + 1];
1810 : 6518 : int vfd = c->verbose_fd;
1811 : 6518 : int rc, r;
1812 : :
1813 : 6518 : c->progressfn_cancel = false;
1814 : :
1815 [ + + ]: 6518 : if (strcmp (type, "source") == 0)
1816 : : filename = type_arg;
1817 [ + + ]: 1052 : else if (strcmp (type, "section") == 0)
1818 : : {
1819 : 16 : section = type_arg;
1820 [ + - ]: 16 : if (section == NULL)
1821 : : return -EINVAL;
1822 : : }
1823 : :
1824 [ + + ]: 6518 : if (vfd >= 0)
1825 : : {
1826 : 1124 : dprintf (vfd, "debuginfod_find_%s ", type);
1827 [ + + ]: 1124 : if (build_id_len == 0) /* expect clean hexadecimal */
1828 : 32 : dprintf (vfd, "%s", (const char *) build_id);
1829 : : else
1830 [ + + ]: 22932 : for (int i = 0; i < build_id_len; i++)
1831 : 21840 : dprintf (vfd, "%02x", build_id[i]);
1832 [ + + ]: 1124 : if (filename != NULL)
1833 : 1088 : dprintf (vfd, " %s\n", filename);
1834 : 1124 : dprintf (vfd, "\n");
1835 : : }
1836 : :
1837 : : /* Is there any server we can query? If not, don't do any work,
1838 : : just return with ENOSYS. Don't even access the cache. */
1839 : 6518 : urls_envvar = getenv(DEBUGINFOD_URLS_ENV_VAR);
1840 [ + + ]: 6518 : if (vfd >= 0)
1841 [ - + ]: 1124 : dprintf (vfd, "server urls \"%s\"\n",
1842 : : urls_envvar != NULL ? urls_envvar : "");
1843 [ + + + + ]: 6518 : if (urls_envvar == NULL || urls_envvar[0] == '\0')
1844 : : {
1845 : 4418 : rc = -ENOSYS;
1846 : 4418 : goto out;
1847 : : }
1848 : :
1849 : : /* Clear the obsolete data from a previous _find operation. */
1850 : 2100 : free (c->url);
1851 : 2100 : c->url = NULL;
1852 : 2100 : free (c->winning_headers);
1853 : 2100 : c->winning_headers = NULL;
1854 : :
1855 : : /* PR 27982: Add max size if DEBUGINFOD_MAXSIZE is set. */
1856 : 2100 : long maxsize = 0;
1857 : 2100 : const char *maxsize_envvar;
1858 : 2100 : maxsize_envvar = getenv(DEBUGINFOD_MAXSIZE_ENV_VAR);
1859 [ + + ]: 2100 : if (maxsize_envvar != NULL)
1860 : 2 : maxsize = atol (maxsize_envvar);
1861 : :
1862 : : /* PR 27982: Add max time if DEBUGINFOD_MAXTIME is set. */
1863 : 2100 : long maxtime = 0;
1864 : 2100 : const char *maxtime_envvar;
1865 : 2100 : maxtime_envvar = getenv(DEBUGINFOD_MAXTIME_ENV_VAR);
1866 [ + + ]: 2100 : if (maxtime_envvar != NULL)
1867 : 2 : maxtime = atol (maxtime_envvar);
1868 [ + + ]: 2100 : if (maxtime && vfd >= 0)
1869 : 2 : dprintf(vfd, "using max time %lds\n", maxtime);
1870 : :
1871 : 2100 : const char *headers_file_envvar;
1872 : 2100 : headers_file_envvar = getenv(DEBUGINFOD_HEADERS_FILE_ENV_VAR);
1873 [ - + ]: 2100 : if (headers_file_envvar != NULL)
1874 : 0 : add_headers_from_file(c, headers_file_envvar);
1875 : :
1876 : : /* Maxsize is valid*/
1877 [ + + ]: 2100 : if (maxsize > 0)
1878 : : {
1879 [ + - ]: 2 : if (vfd)
1880 : 2 : dprintf (vfd, "using max size %ldB\n", maxsize);
1881 : 2 : char *size_header = NULL;
1882 : 2 : rc = asprintf (&size_header, "X-DEBUGINFOD-MAXSIZE: %ld", maxsize);
1883 [ - + ]: 2 : if (rc < 0)
1884 : : {
1885 : 0 : rc = -ENOMEM;
1886 : 0 : goto out;
1887 : : }
1888 : 2 : rc = debuginfod_add_http_header(c, size_header);
1889 : 2 : free(size_header);
1890 [ - + ]: 2 : if (rc < 0)
1891 : 0 : goto out;
1892 : : }
1893 : 2100 : add_default_headers(c);
1894 : :
1895 : : /* Copy lowercase hex representation of build_id into buf. */
1896 [ + + ]: 2100 : if (vfd >= 0)
1897 : 1124 : dprintf (vfd, "checking build-id\n");
1898 [ + - + + ]: 2100 : if ((build_id_len >= MAX_BUILD_ID_BYTES) ||
1899 : 1006 : (build_id_len == 0 &&
1900 [ - + ]: 1006 : strlen ((const char *) build_id) > MAX_BUILD_ID_BYTES*2))
1901 : : {
1902 : 0 : rc = -EINVAL;
1903 : 0 : goto out;
1904 : : }
1905 : :
1906 [ + + ]: 2100 : if (build_id_len == 0) /* expect clean hexadecimal */
1907 : 1006 : strcpy (build_id_bytes, (const char *) build_id);
1908 : : else
1909 [ + + ]: 22974 : for (int i = 0; i < build_id_len; i++)
1910 : 21880 : sprintf(build_id_bytes + (i * 2), "%02x", build_id[i]);
1911 : :
1912 [ + + ]: 2100 : if (filename != NULL)
1913 : : {
1914 [ + + ]: 1134 : if (vfd >= 0)
1915 : 1088 : dprintf (vfd, "checking filename\n");
1916 [ - + ]: 1134 : if (filename[0] != '/') // must start with /
1917 : : {
1918 : 0 : rc = -EINVAL;
1919 : 0 : goto out;
1920 : : }
1921 : :
1922 : 1134 : path_escape (filename, suffix, sizeof(suffix));
1923 : : /* If the DWARF filenames are super long, this could exceed
1924 : : PATH_MAX and truncate/collide. Oh well, that'll teach
1925 : : them! */
1926 : : }
1927 [ + + ]: 966 : else if (section != NULL)
1928 : 16 : path_escape (section, suffix, sizeof(suffix));
1929 : : else
1930 : 950 : suffix[0] = '\0';
1931 : :
1932 [ + + + + ]: 2100 : if (suffix[0] != '\0' && vfd >= 0)
1933 : 1104 : dprintf (vfd, "suffix %s\n", suffix);
1934 : :
1935 : : /* set paths needed to perform the query
1936 : : example format:
1937 : : cache_path: $HOME/.cache
1938 : : target_cache_dir: $HOME/.cache/0123abcd
1939 : : target_cache_path: $HOME/.cache/0123abcd/debuginfo
1940 : : target_cache_path: $HOME/.cache/0123abcd/executable-.debug_info
1941 : : target_cache_path: $HOME/.cache/0123abcd/source-HASH-#PATH#TO#SOURCE
1942 : : target_cachehdr_path: $HOME/.cache/0123abcd/hdr-debuginfo
1943 : : target_cachehdr_path: $HOME/.cache/0123abcd/hdr-executable...
1944 : : */
1945 : :
1946 : 2100 : cache_path = make_cache_path();
1947 [ - + ]: 2100 : if (!cache_path)
1948 : : {
1949 : 0 : rc = -ENOMEM;
1950 : 0 : goto out;
1951 : : }
1952 [ - + ]: 2100 : xalloc_str (target_cache_dir, "%s/%s", cache_path, build_id_bytes);
1953 : 2100 : (void) mkdir (target_cache_dir, 0700); // failures with this mkdir would be caught later too
1954 : :
1955 [ + + ]: 2100 : if (suffix[0] != '\0') { /* section, source queries */
1956 [ - + ]: 1150 : xalloc_str (target_cache_path, "%s/%s-%s", target_cache_dir, type, suffix);
1957 [ - + ]: 1150 : xalloc_str (target_cachehdr_path, "%s/hdr-%s-%s", target_cache_dir, type, suffix);
1958 : : } else {
1959 [ - + ]: 950 : xalloc_str (target_cache_path, "%s/%s", target_cache_dir, type);
1960 [ - + ]: 950 : xalloc_str (target_cachehdr_path, "%s/hdr-%s", target_cache_dir, type);
1961 : : }
1962 [ - + ]: 2100 : xalloc_str (target_cache_tmppath, "%s.XXXXXX", target_cache_path);
1963 [ - + ]: 2100 : xalloc_str (target_cachehdr_tmppath, "%s.XXXXXX", target_cachehdr_path);
1964 : :
1965 : : /* XXX combine these */
1966 [ - + ]: 2100 : xalloc_str (interval_path, "%s/%s", cache_path, cache_clean_interval_filename);
1967 [ - + ]: 2100 : xalloc_str (cache_miss_path, "%s/%s", cache_path, cache_miss_filename);
1968 [ - + ]: 2100 : xalloc_str (maxage_path, "%s/%s", cache_path, cache_max_unused_age_filename);
1969 : :
1970 [ + + ]: 2100 : if (vfd >= 0)
1971 : 1124 : dprintf (vfd, "checking cache dir %s\n", cache_path);
1972 : :
1973 : : /* Make sure cache dir exists. debuginfo_clean_cache will then make
1974 : : sure the interval, cache_miss and maxage files exist. */
1975 [ + - ]: 2100 : if (mkdir (cache_path, ACCESSPERMS) != 0
1976 [ - + ]: 2100 : && errno != EEXIST)
1977 : : {
1978 : 0 : rc = -errno;
1979 : 0 : goto out;
1980 : : }
1981 : :
1982 : 2100 : rc = debuginfod_clean_cache(c, cache_path, interval_path, maxage_path);
1983 [ - + ]: 2100 : if (rc != 0)
1984 : 0 : goto out;
1985 : :
1986 : : /* Check if the target is already in the cache. */
1987 : 2100 : int fd = open(target_cache_path, O_RDONLY);
1988 [ + + ]: 2100 : if (fd >= 0)
1989 : : {
1990 : 58 : struct stat st;
1991 [ - + ]: 58 : if (fstat(fd, &st) != 0)
1992 : : {
1993 : 0 : rc = -errno;
1994 : 0 : close (fd);
1995 : 56 : goto out;
1996 : : }
1997 : :
1998 : : /* If the file is non-empty, then we are done. */
1999 [ + + ]: 58 : if (st.st_size > 0)
2000 : : {
2001 [ + - ]: 54 : if (path != NULL)
2002 : : {
2003 : 54 : *path = strdup(target_cache_path);
2004 [ - + ]: 54 : if (*path == NULL)
2005 : : {
2006 : 0 : rc = -errno;
2007 : 0 : close (fd);
2008 : 0 : goto out;
2009 : : }
2010 : : }
2011 : : /* Success!!!! */
2012 : 54 : update_atime(fd);
2013 : 54 : rc = fd;
2014 : :
2015 : : /* Attempt to transcribe saved headers. */
2016 : 54 : int fdh = open (target_cachehdr_path, O_RDONLY);
2017 [ + + ]: 54 : if (fdh >= 0)
2018 : : {
2019 [ + - + - ]: 52 : if (fstat (fdh, &st) == 0 && st.st_size > 0)
2020 : : {
2021 : 52 : c->winning_headers = malloc(st.st_size);
2022 [ + - ]: 52 : if (NULL != c->winning_headers)
2023 : : {
2024 : 52 : ssize_t bytes_read = pread_retry(fdh, c->winning_headers, st.st_size, 0);
2025 [ - + ]: 52 : if (bytes_read <= 0)
2026 : : {
2027 : 0 : free (c->winning_headers);
2028 : 0 : c->winning_headers = NULL;
2029 : 0 : (void) unlink (target_cachehdr_path);
2030 : : }
2031 [ + + ]: 52 : if (vfd >= 0)
2032 : 2 : dprintf (vfd, "found %s (bytes=%ld)\n", target_cachehdr_path, (long)bytes_read);
2033 : : }
2034 : : }
2035 : :
2036 : 52 : update_atime (fdh);
2037 : 52 : close (fdh);
2038 : : }
2039 : :
2040 : 54 : goto out;
2041 : : }
2042 : : else
2043 : : {
2044 : : /* The file is empty. Attempt to download only if enough time
2045 : : has passed since the last attempt. */
2046 : 4 : time_t cache_miss;
2047 : 4 : time_t target_mtime = st.st_mtime;
2048 : :
2049 : 4 : close(fd); /* no need to hold onto the negative-hit file descriptor */
2050 : :
2051 : 4 : rc = debuginfod_config_cache(c, cache_miss_path,
2052 : : cache_miss_default_s, &st);
2053 [ - + ]: 4 : if (rc < 0)
2054 : 0 : goto out;
2055 : :
2056 : 4 : cache_miss = (time_t)rc;
2057 [ + + ]: 4 : if (time(NULL) - target_mtime <= cache_miss)
2058 : : {
2059 : 2 : rc = -ENOENT;
2060 : 2 : goto out;
2061 : : }
2062 : : else
2063 : : /* TOCTOU non-problem: if another task races, puts a working
2064 : : download or an empty file in its place, unlinking here just
2065 : : means WE will try to download again as uncached. */
2066 : 2 : (void) unlink(target_cache_path);
2067 : : }
2068 : : }
2069 [ - + ]: 2042 : else if (errno == EACCES)
2070 : : /* Ensure old 000-permission files are not lingering in the cache. */
2071 : 0 : (void) unlink(target_cache_path);
2072 : :
2073 [ + + ]: 2044 : if (section != NULL)
2074 : : {
2075 : : /* Try to extract the section from a cached file before querying
2076 : : any servers. */
2077 : 16 : rc = cache_find_section (section, target_cache_dir, path);
2078 : :
2079 : : /* If the section was found or confirmed to not exist, then we
2080 : : are done. */
2081 [ + + ]: 16 : if (rc >= 0 || rc == -ENOENT)
2082 : 8 : goto out;
2083 : : }
2084 : :
2085 : 2036 : long timeout = default_timeout;
2086 : 2036 : const char* timeout_envvar = getenv(DEBUGINFOD_TIMEOUT_ENV_VAR);
2087 [ - + ]: 2036 : if (timeout_envvar != NULL)
2088 : 0 : timeout = atoi (timeout_envvar);
2089 : :
2090 [ + + ]: 2036 : if (vfd >= 0)
2091 : 1114 : dprintf (vfd, "using timeout %ld\n", timeout);
2092 : :
2093 : : /* make a copy of the envvar so it can be safely modified. */
2094 : 2036 : server_urls = strdup(urls_envvar);
2095 [ - + ]: 2036 : if (server_urls == NULL)
2096 : : {
2097 : 0 : rc = -ENOMEM;
2098 : 0 : goto out;
2099 : : }
2100 : : /* thereafter, goto out0 on error*/
2101 : :
2102 : : /* Because of a race with cache cleanup / rmdir, try to mkdir/mkstemp up to twice. */
2103 [ + - ]: 2036 : for(int i=0; i<2; i++)
2104 : : {
2105 : : /* (re)create target directory in cache */
2106 : 2036 : (void) mkdir(target_cache_dir, 0700); /* files will be 0400 later */
2107 : :
2108 : : /* NB: write to a temporary file first, to avoid race condition of
2109 : : multiple clients checking the cache, while a partially-written or empty
2110 : : file is in there, being written from libcurl. */
2111 : 2036 : fd = mkstemp (target_cache_tmppath);
2112 [ - + ]: 2036 : if (fd >= 0) break;
2113 : : }
2114 [ - + ]: 2036 : if (fd < 0) /* Still failed after two iterations. */
2115 : : {
2116 : 0 : rc = -errno;
2117 : 0 : goto out0;
2118 : : }
2119 : :
2120 : 2036 : char **server_url_list = NULL;
2121 : 2036 : ima_policy_t* url_ima_policies = NULL;
2122 : 2036 : char *server_url;
2123 : 2036 : int num_urls;
2124 : 2036 : r = init_server_urls("buildid", type, server_urls, &server_url_list, &url_ima_policies, &num_urls, vfd);
2125 [ - + ]: 2036 : if (0 != r)
2126 : : {
2127 : 0 : rc = r;
2128 : 0 : goto out1;
2129 : : }
2130 : :
2131 : : /* No URLs survived parsing / filtering? Abort abort abort. */
2132 [ - + ]: 2036 : if (num_urls == 0)
2133 : : {
2134 : 0 : rc = -ENOSYS;
2135 : 0 : goto out1;
2136 : : }
2137 : :
2138 : 2036 : int retry_limit = default_retry_limit;
2139 : 2036 : const char* retry_limit_envvar = getenv(DEBUGINFOD_RETRY_LIMIT_ENV_VAR);
2140 [ + + ]: 2036 : if (retry_limit_envvar != NULL)
2141 : 4 : retry_limit = atoi (retry_limit_envvar);
2142 : :
2143 : 2036 : CURLM *curlm = c->server_mhandle;
2144 : :
2145 : : /* Tracks which handle should write to fd. Set to the first
2146 : : handle that is ready to write the target file to the cache. */
2147 : 2036 : CURL *target_handle = NULL;
2148 : 2036 : struct handle_data *data = malloc(sizeof(struct handle_data) * num_urls);
2149 [ - + ]: 2036 : if (data == NULL)
2150 : : {
2151 : 0 : rc = -ENOMEM;
2152 : 0 : goto out1;
2153 : : }
2154 : :
2155 : : /* thereafter, goto out2 on error. */
2156 : :
2157 : : /*The beginning of goto block query_in_parallel.*/
2158 : 2036 : query_in_parallel:
2159 : 3120 : rc = -ENOENT; /* Reset rc to default.*/
2160 : :
2161 : : /* Initialize handle_data with default values. */
2162 [ + + ]: 6290 : for (int i = 0; i < num_urls; i++)
2163 : : {
2164 : 3170 : data[i].handle = NULL;
2165 : 3170 : data[i].fd = -1;
2166 : 3170 : data[i].errbuf[0] = '\0';
2167 : 3170 : data[i].response_data = NULL;
2168 : 3170 : data[i].response_data_size = 0;
2169 : : }
2170 : :
2171 : 3120 : char *escaped_string = NULL;
2172 : 3120 : size_t escaped_strlen = 0;
2173 [ + + ]: 3120 : if (filename)
2174 : : {
2175 : 1134 : escaped_string = curl_easy_escape(&target_handle, filename+1, 0);
2176 [ - + ]: 1134 : if (!escaped_string)
2177 : : {
2178 : 0 : rc = -ENOMEM;
2179 : 0 : goto out2;
2180 : : }
2181 : 1134 : char *loc = escaped_string;
2182 : 1134 : escaped_strlen = strlen(escaped_string);
2183 [ + + ]: 8828 : while ((loc = strstr(loc, "%2F")))
2184 : : {
2185 : 7694 : loc[0] = '/';
2186 : : //pull the string back after replacement
2187 : : // loc-escaped_string finds the distance from the origin to the new location
2188 : : // - 2 accounts for the 2F which remain and don't need to be measured.
2189 : : // The two above subtracted from escaped_strlen yields the remaining characters
2190 : : // in the string which we want to pull back
2191 : 7694 : memmove(loc+1, loc+3,escaped_strlen - (loc-escaped_string) - 2);
2192 : : //Because the 2F was overwritten in the memmove (as desired) escaped_strlen is
2193 : : // now two shorter.
2194 : 7694 : escaped_strlen -= 2;
2195 : : }
2196 : : }
2197 : : /* Initialize each handle. */
2198 [ + + ]: 6290 : for (int i = 0; i < num_urls; i++)
2199 : : {
2200 [ + - ]: 3170 : if ((server_url = server_url_list[i]) == NULL)
2201 : : break;
2202 [ + + ]: 3170 : if (vfd >= 0)
2203 : : #ifdef ENABLE_IMA_VERIFICATION
2204 : : dprintf (vfd, "init server %d %s [IMA verification policy: %s]\n", i, server_url, ima_policy_enum2str(url_ima_policies[i]));
2205 : : #else
2206 : 1136 : dprintf (vfd, "init server %d %s\n", i, server_url);
2207 : : #endif
2208 : :
2209 : 3170 : data[i].fd = fd;
2210 : 3170 : data[i].target_handle = &target_handle;
2211 : 3170 : data[i].client = c;
2212 : :
2213 [ + + ]: 3170 : if (filename) /* must start with / */
2214 : : {
2215 : : /* PR28034 escape characters in completed url to %hh format. */
2216 : 1134 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
2217 : : build_id_bytes, type, escaped_string);
2218 : : }
2219 [ + + ]: 2036 : else if (section)
2220 : 8 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
2221 : : build_id_bytes, type, section);
2222 : : else
2223 : 2028 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s", server_url, build_id_bytes, type);
2224 : :
2225 : 3170 : r = init_handle(c, debuginfod_write_callback, header_callback, &data[i], i, timeout, vfd);
2226 [ - + ]: 3170 : if (0 != r)
2227 : : {
2228 : 0 : rc = r;
2229 [ # # ]: 0 : if (filename) curl_free (escaped_string);
2230 : 0 : goto out2;
2231 : : }
2232 : :
2233 : 3170 : curl_multi_add_handle(curlm, data[i].handle);
2234 : : }
2235 : :
2236 [ + + ]: 3120 : if (filename) curl_free(escaped_string);
2237 : :
2238 : : /* Query servers in parallel. */
2239 [ + + ]: 3120 : if (vfd >= 0)
2240 : 1134 : dprintf (vfd, "query %d urls in parallel\n", num_urls);
2241 : 3120 : int committed_to;
2242 : 3120 : r = perform_queries(curlm, &target_handle, data, c, num_urls, maxtime, maxsize, true, vfd, &committed_to);
2243 [ - + ]: 3120 : if (0 != r)
2244 : : {
2245 : 0 : rc = r;
2246 : 0 : goto out2;
2247 : : }
2248 : :
2249 : : /* Check whether a query was successful. If so, assign its handle
2250 : : to verified_handle. */
2251 : : int num_msg;
2252 : : rc = -ENOENT;
2253 : 3122 : CURL *verified_handle = NULL;
2254 : 3122 : do
2255 : : {
2256 : 3122 : CURLMsg *msg;
2257 : :
2258 : 3122 : msg = curl_multi_info_read(curlm, &num_msg);
2259 [ + - + - ]: 3122 : if (msg != NULL && msg->msg == CURLMSG_DONE)
2260 : : {
2261 [ + + ]: 3122 : if (vfd >= 0)
2262 : : {
2263 : 2272 : bool pnl = (c->default_progressfn_printed_p
2264 [ - + - - ]: 1136 : && vfd == STDERR_FILENO);
2265 [ + - ]: 1136 : dprintf (vfd, "%sserver response %s\n", pnl ? "\n" : "",
2266 : : curl_easy_strerror (msg->data.result));
2267 [ - + ]: 1136 : if (pnl)
2268 : 0 : c->default_progressfn_printed_p = 0;
2269 [ + - ]: 1138 : for (int i = 0; i < num_urls; i++)
2270 [ + + ]: 1138 : if (msg->easy_handle == data[i].handle)
2271 : : {
2272 [ + + ]: 1136 : if (strlen (data[i].errbuf) > 0)
2273 : 32 : dprintf (vfd, "url %d %s\n", i, data[i].errbuf);
2274 : : break;
2275 : : }
2276 : : }
2277 : :
2278 [ + + ]: 3122 : if (msg->data.result != CURLE_OK)
2279 : : {
2280 : 1662 : long resp_code;
2281 : 1662 : CURLcode ok0;
2282 : : /* Unsuccessful query, determine error code. */
2283 [ - + - - : 1662 : switch (msg->data.result)
- - - - +
+ - ]
2284 : : {
2285 : : case CURLE_COULDNT_RESOLVE_HOST: rc = -EHOSTUNREACH; break; // no NXDOMAIN
2286 : 0 : case CURLE_URL_MALFORMAT: rc = -EINVAL; break;
2287 : 1620 : case CURLE_COULDNT_CONNECT: rc = -ECONNREFUSED; break;
2288 : 1620 : case CURLE_PEER_FAILED_VERIFICATION: rc = -ECONNREFUSED; break;
2289 : 0 : case CURLE_REMOTE_ACCESS_DENIED: rc = -EACCES; break;
2290 : 0 : case CURLE_WRITE_ERROR: rc = -EIO; break;
2291 : 0 : case CURLE_OUT_OF_MEMORY: rc = -ENOMEM; break;
2292 : 0 : case CURLE_TOO_MANY_REDIRECTS: rc = -EMLINK; break;
2293 : 0 : case CURLE_SEND_ERROR: rc = -ECONNRESET; break;
2294 : 0 : case CURLE_RECV_ERROR: rc = -ECONNRESET; break;
2295 : 0 : case CURLE_OPERATION_TIMEDOUT: rc = -ETIME; break;
2296 : : case CURLE_HTTP_RETURNED_ERROR:
2297 : 40 : ok0 = curl_easy_getinfo (msg->easy_handle,
2298 : : CURLINFO_RESPONSE_CODE,
2299 : : &resp_code);
2300 : : /* 406 signals that the requested file was too large */
2301 [ + - + + ]: 40 : if ( ok0 == CURLE_OK && resp_code == 406)
2302 : : rc = -EFBIG;
2303 [ - + - - ]: 38 : else if (section != NULL && resp_code == 503)
2304 : : rc = -EINVAL;
2305 : : else
2306 : 40 : rc = -ENOENT;
2307 : : break;
2308 : 40 : default: rc = -ENOENT; break;
2309 : : }
2310 : : }
2311 : : else
2312 : : {
2313 : : /* Query completed without an error. Confirm that the
2314 : : response code is 200 when using HTTP/HTTPS and 0 when
2315 : : using file:// and set verified_handle. */
2316 : :
2317 [ + - ]: 1460 : if (msg->easy_handle != NULL)
2318 : : {
2319 : 1460 : char *effective_url = NULL;
2320 : 1460 : long resp_code = 500;
2321 : 1460 : CURLcode ok1 = curl_easy_getinfo (target_handle,
2322 : : CURLINFO_EFFECTIVE_URL,
2323 : : &effective_url);
2324 : 1460 : CURLcode ok2 = curl_easy_getinfo (target_handle,
2325 : : CURLINFO_RESPONSE_CODE,
2326 : : &resp_code);
2327 [ + - + - ]: 1460 : if(ok1 == CURLE_OK && ok2 == CURLE_OK && effective_url)
2328 : : {
2329 [ + + ]: 1460 : if (strncasecmp (effective_url, "HTTP", 4) == 0)
2330 [ + - ]: 1458 : if (resp_code == 200)
2331 : : {
2332 : 1458 : verified_handle = msg->easy_handle;
2333 : 1460 : break;
2334 : : }
2335 [ + - ]: 2 : if (strncasecmp (effective_url, "FILE", 4) == 0)
2336 [ + - ]: 2 : if (resp_code == 0)
2337 : : {
2338 : 2 : verified_handle = msg->easy_handle;
2339 : 2 : break;
2340 : : }
2341 : : }
2342 : : /* - libcurl since 7.52.0 version start to support
2343 : : CURLINFO_SCHEME;
2344 : : - before 7.61.0, effective_url would give us a
2345 : : url with upper case SCHEME added in the front;
2346 : : - effective_url between 7.61 and 7.69 can be lack
2347 : : of scheme if the original url doesn't include one;
2348 : : - since version 7.69 effective_url will be provide
2349 : : a scheme in lower case. */
2350 : : #if LIBCURL_VERSION_NUM >= 0x073d00 /* 7.61.0 */
2351 : : #if LIBCURL_VERSION_NUM <= 0x074500 /* 7.69.0 */
2352 : : char *scheme = NULL;
2353 : : CURLcode ok3 = curl_easy_getinfo (target_handle,
2354 : : CURLINFO_SCHEME,
2355 : : &scheme);
2356 : : if(ok3 == CURLE_OK && scheme)
2357 : : {
2358 : : if (startswith (scheme, "HTTP"))
2359 : : if (resp_code == 200)
2360 : : {
2361 : : verified_handle = msg->easy_handle;
2362 : : break;
2363 : : }
2364 : : }
2365 : : #endif
2366 : : #endif
2367 : : }
2368 : : }
2369 : : }
2370 [ + + ]: 1662 : } while (num_msg > 0);
2371 : :
2372 : : /* Create an empty file in the cache if the query fails with ENOENT and
2373 : : it wasn't cancelled early. */
2374 [ + + + - ]: 3120 : if (rc == -ENOENT && !c->progressfn_cancel)
2375 : : {
2376 : 1500 : int efd = open (target_cache_path, O_CREAT|O_EXCL, DEFFILEMODE);
2377 [ + + ]: 1500 : if (efd >= 0)
2378 : 1498 : close(efd);
2379 : : }
2380 [ + + ]: 1620 : else if (rc == -EFBIG)
2381 : 2 : goto out2;
2382 : :
2383 : : /* If the verified_handle is NULL and rc != -ENOENT, the query fails with
2384 : : * an error code other than 404, then do several retry within the retry_limit.
2385 : : * Clean up all old handles and jump back to the beginning of query_in_parallel,
2386 : : * reinitialize handles and query again.*/
2387 [ + + ]: 3118 : if (verified_handle == NULL)
2388 : : {
2389 [ + + + + ]: 1658 : if (rc != -ENOENT && retry_limit-- > 0)
2390 : : {
2391 [ + + ]: 1084 : if (vfd >= 0)
2392 : 20 : dprintf (vfd, "Retry failed query, %d attempt(s) remaining\n", retry_limit);
2393 : : /* remove all handles from multi */
2394 [ + + ]: 2168 : for (int i = 0; i < num_urls; i++)
2395 : : {
2396 : 1084 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2397 : 1084 : curl_easy_cleanup (data[i].handle);
2398 : 1084 : free(data[i].response_data);
2399 : 1084 : data[i].response_data = NULL;
2400 : : }
2401 : 1084 : free(c->winning_headers);
2402 : 1084 : c->winning_headers = NULL;
2403 : 1084 : goto query_in_parallel;
2404 : : }
2405 : : else
2406 : 574 : goto out2;
2407 : : }
2408 : :
2409 [ + + ]: 1460 : if (vfd >= 0)
2410 : : {
2411 [ - + - - ]: 2208 : bool pnl = c->default_progressfn_printed_p && vfd == STDERR_FILENO;
2412 : 1104 : dprintf (vfd, "%sgot file from server\n", pnl ? "\n" : "");
2413 [ - + ]: 1104 : if (pnl)
2414 : 0 : c->default_progressfn_printed_p = 0;
2415 : : }
2416 : :
2417 : : /* we've got one!!!! */
2418 : 1460 : time_t mtime;
2419 : : #if defined(_TIME_BITS) && _TIME_BITS == 64
2420 : : CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME_T, (void*) &mtime);
2421 : : #else
2422 : 1460 : CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME, (void*) &mtime);
2423 : : #endif
2424 [ + - ]: 1460 : if (curl_res == CURLE_OK)
2425 : : {
2426 : 1460 : struct timespec tvs[2];
2427 : 1460 : tvs[0].tv_sec = 0;
2428 : 1460 : tvs[0].tv_nsec = UTIME_OMIT;
2429 : 1460 : tvs[1].tv_sec = mtime;
2430 : 1460 : tvs[1].tv_nsec = 0;
2431 : 1460 : (void) futimens (fd, tvs); /* best effort */
2432 : : }
2433 : :
2434 : : /* PR27571: make cache files casually unwriteable; dirs are already 0700 */
2435 : 1460 : (void) fchmod(fd, 0400);
2436 : : /* PR31248: lseek back to beginning */
2437 : 1460 : (void) lseek(fd, 0, SEEK_SET);
2438 : :
2439 [ + - - + ]: 1460 : if(NULL != url_ima_policies && ignore != url_ima_policies[committed_to])
2440 : : {
2441 : : #ifdef ENABLE_IMA_VERIFICATION
2442 : : int result = debuginfod_validate_imasig(c, fd);
2443 : : #else
2444 : 0 : int result = -ENOSYS;
2445 : : #endif
2446 : 0 : if(0 == result)
2447 : : {
2448 : : if (vfd >= 0) dprintf (vfd, "valid signature\n");
2449 : : }
2450 [ # # ]: 0 : else if (enforcing == url_ima_policies[committed_to])
2451 : : {
2452 : : // All invalid signatures are rejected.
2453 : : // Additionally in enforcing mode any non-valid signature is rejected, so by reaching
2454 : : // this case we do so since we know it is not valid. Note - this not just invalid signatures
2455 : : // but also signatures that cannot be validated
2456 [ # # ]: 0 : if (vfd >= 0) dprintf (vfd, "error: invalid or missing signature (%d)\n", result);
2457 : 0 : rc = result;
2458 : 0 : goto out2;
2459 : : }
2460 : : }
2461 : :
2462 : : /* rename tmp->real */
2463 : 1460 : rc = rename (target_cache_tmppath, target_cache_path);
2464 [ - + ]: 1460 : if (rc < 0)
2465 : : {
2466 : 0 : rc = -errno;
2467 : 0 : goto out2;
2468 : : /* Perhaps we need not give up right away; could retry or something ... */
2469 : : }
2470 : :
2471 : : /* write out the headers, best effort basis */
2472 [ + + ]: 1460 : if (c->winning_headers) {
2473 : 1458 : int fdh = mkstemp (target_cachehdr_tmppath);
2474 [ + - ]: 1458 : if (fdh >= 0) {
2475 : 1458 : size_t bytes_to_write = strlen(c->winning_headers)+1; // include \0
2476 : 1458 : size_t bytes = pwrite_retry (fdh, c->winning_headers, bytes_to_write, 0);
2477 : 1458 : (void) close (fdh);
2478 [ + - ]: 1458 : if (bytes == bytes_to_write)
2479 : 1458 : (void) rename (target_cachehdr_tmppath, target_cachehdr_path);
2480 : : else
2481 : 0 : (void) unlink (target_cachehdr_tmppath);
2482 [ + + ]: 1458 : if (vfd >= 0)
2483 : 1104 : dprintf (vfd, "saved %ld bytes of headers to %s\n", (long)bytes, target_cachehdr_path);
2484 : : }
2485 : : }
2486 : :
2487 : : /* remove all handles from multi */
2488 [ + + ]: 2968 : for (int i = 0; i < num_urls; i++)
2489 : : {
2490 : 1508 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2491 : 1508 : curl_easy_cleanup (data[i].handle);
2492 : 1508 : free (data[i].response_data);
2493 : : }
2494 : :
2495 [ + + ]: 2968 : for (int i = 0; i < num_urls; ++i)
2496 : 1508 : free(server_url_list[i]);
2497 : 1460 : free(server_url_list);
2498 : 1460 : free(url_ima_policies);
2499 : 1460 : free (data);
2500 : 1460 : free (server_urls);
2501 : :
2502 : : /* don't close fd - we're returning it */
2503 : : /* don't unlink the tmppath; it's already been renamed. */
2504 [ + + ]: 1460 : if (path != NULL)
2505 : 374 : *path = strdup(target_cache_path);
2506 : :
2507 : 1460 : rc = fd;
2508 : 1460 : goto out;
2509 : :
2510 : : /* error exits */
2511 : 576 : out2:
2512 : : /* remove all handles from multi */
2513 [ + + ]: 1154 : for (int i = 0; i < num_urls; i++)
2514 : : {
2515 [ + - ]: 578 : if (data[i].handle != NULL)
2516 : : {
2517 : 578 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2518 : 578 : curl_easy_cleanup (data[i].handle);
2519 : 578 : free (data[i].response_data);
2520 : : }
2521 : : }
2522 : :
2523 : 576 : unlink (target_cache_tmppath);
2524 : 576 : close (fd); /* before the rmdir, otherwise it'll fail */
2525 : 576 : (void) rmdir (target_cache_dir); /* nop if not empty */
2526 : 576 : free(data);
2527 : :
2528 : 576 : out1:
2529 [ + + ]: 1154 : for (int i = 0; i < num_urls; ++i)
2530 : 578 : free(server_url_list[i]);
2531 : 576 : free(server_url_list);
2532 : 576 : free(url_ima_policies);
2533 : :
2534 : 576 : out0:
2535 : 576 : free (server_urls);
2536 : :
2537 : : /* general purpose exit */
2538 : 6518 : out:
2539 : : /* Reset sent headers */
2540 : 6518 : curl_slist_free_all (c->headers);
2541 : 6518 : c->headers = NULL;
2542 : 6518 : c->user_agent_set_p = 0;
2543 : :
2544 : : /* Conclude the last \r status line */
2545 : : /* Another possibility is to use the ANSI CSI n K EL "Erase in Line"
2546 : : code. That way, the previously printed messages would be erased,
2547 : : and without a newline. */
2548 [ + + ]: 6518 : if (c->default_progressfn_printed_p)
2549 : 2 : dprintf(STDERR_FILENO, "\n");
2550 : :
2551 [ + + ]: 6518 : if (vfd >= 0)
2552 : : {
2553 [ + + ]: 1124 : if (rc < 0)
2554 : 10 : dprintf (vfd, "not found %s (err=%d)\n", strerror (-rc), rc);
2555 : : else
2556 : 1114 : dprintf (vfd, "found %s (fd=%d)\n", target_cache_path, rc);
2557 : : }
2558 : :
2559 : 6518 : free (cache_path);
2560 : 6518 : free (maxage_path);
2561 : 6518 : free (interval_path);
2562 : 6518 : free (cache_miss_path);
2563 : 6518 : free (target_cache_dir);
2564 : 6518 : free (target_cache_path);
2565 [ + + + + ]: 6518 : if (rc < 0 && target_cache_tmppath != NULL)
2566 : 578 : (void)unlink (target_cache_tmppath);
2567 : 6518 : free (target_cache_tmppath);
2568 [ + + + + ]: 6518 : if (rc < 0 && target_cachehdr_tmppath != NULL)
2569 : 578 : (void)unlink (target_cachehdr_tmppath);
2570 : 6518 : free (target_cachehdr_tmppath);
2571 : 6518 : free (target_cachehdr_path);
2572 : :
2573 : 6518 : return rc;
2574 : : }
2575 : :
2576 : :
2577 : :
2578 : : /* See debuginfod.h */
2579 : : debuginfod_client *
2580 : 528 : debuginfod_begin (void)
2581 : : {
2582 : : /* Initialize libcurl lazily, but only once. */
2583 : 528 : pthread_once (&init_control, libcurl_init);
2584 : :
2585 : 528 : debuginfod_client *client;
2586 : 528 : size_t size = sizeof (struct debuginfod_client);
2587 : 528 : client = calloc (1, size);
2588 : :
2589 [ + - ]: 528 : if (client != NULL)
2590 : : {
2591 [ + + ]: 528 : if (getenv(DEBUGINFOD_PROGRESS_ENV_VAR))
2592 : 4 : client->progressfn = debuginfod_default_progressfn;
2593 [ + + ]: 528 : if (getenv(DEBUGINFOD_VERBOSE_ENV_VAR))
2594 : 6 : client->verbose_fd = STDERR_FILENO;
2595 : : else
2596 : 522 : client->verbose_fd = -1;
2597 : :
2598 : : // allocate 1 curl multi handle
2599 : 528 : client->server_mhandle = curl_multi_init ();
2600 [ - + ]: 528 : if (client->server_mhandle == NULL)
2601 : 0 : goto out1;
2602 : : }
2603 : :
2604 : : #ifdef ENABLE_IMA_VERIFICATION
2605 : : load_ima_public_keys (client);
2606 : : #endif
2607 : :
2608 : : // extra future initialization
2609 : :
2610 : 528 : goto out;
2611 : :
2612 : 0 : out1:
2613 : 0 : free (client);
2614 : 0 : client = NULL;
2615 : :
2616 : 528 : out:
2617 : 528 : return client;
2618 : : }
2619 : :
2620 : : void
2621 : 486 : debuginfod_set_user_data(debuginfod_client *client,
2622 : : void *data)
2623 : : {
2624 : 486 : client->user_data = data;
2625 : 486 : }
2626 : :
2627 : : void *
2628 : 0 : debuginfod_get_user_data(debuginfod_client *client)
2629 : : {
2630 : 0 : return client->user_data;
2631 : : }
2632 : :
2633 : : const char *
2634 : 46 : debuginfod_get_url(debuginfod_client *client)
2635 : : {
2636 [ + - ]: 2 : return client->url;
2637 : : }
2638 : :
2639 : : const char *
2640 : 48 : debuginfod_get_headers(debuginfod_client *client)
2641 : : {
2642 : 48 : return client->winning_headers;
2643 : : }
2644 : :
2645 : : void
2646 : 526 : debuginfod_end (debuginfod_client *client)
2647 : : {
2648 [ + - ]: 526 : if (client == NULL)
2649 : : return;
2650 : :
2651 : 526 : curl_multi_cleanup (client->server_mhandle);
2652 : 526 : curl_slist_free_all (client->headers);
2653 : 526 : free (client->winning_headers);
2654 : 526 : free (client->url);
2655 : : #ifdef ENABLE_IMA_VERIFICATION
2656 : : free_ima_public_keys (client);
2657 : : #endif
2658 : 526 : free (client);
2659 : : }
2660 : :
2661 : : int
2662 : 300 : debuginfod_find_debuginfo (debuginfod_client *client,
2663 : : const unsigned char *build_id, int build_id_len,
2664 : : char **path)
2665 : : {
2666 : 300 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2667 : : "debuginfo", NULL, path);
2668 : : }
2669 : :
2670 : :
2671 : : /* See debuginfod.h */
2672 : : int
2673 : 736 : debuginfod_find_executable(debuginfod_client *client,
2674 : : const unsigned char *build_id, int build_id_len,
2675 : : char **path)
2676 : : {
2677 : 736 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2678 : : "executable", NULL, path);
2679 : : }
2680 : :
2681 : : /* See debuginfod.h */
2682 : 5466 : int debuginfod_find_source(debuginfod_client *client,
2683 : : const unsigned char *build_id, int build_id_len,
2684 : : const char *filename, char **path)
2685 : : {
2686 : 5466 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2687 : : "source", filename, path);
2688 : : }
2689 : :
2690 : : int
2691 : 16 : debuginfod_find_section (debuginfod_client *client,
2692 : : const unsigned char *build_id, int build_id_len,
2693 : : const char *section, char **path)
2694 : : {
2695 : 16 : int rc = debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2696 : : "section", section, path);
2697 [ - + ]: 16 : if (rc != -EINVAL && rc != -ENOSYS)
2698 : : return rc;
2699 : : /* NB: we fall through in case of ima:enforcing-filtered DEBUGINFOD_URLS servers,
2700 : : so we can download the entire file, verify it locally, then slice it. */
2701 : :
2702 : : /* The servers may have lacked support for section queries. Attempt to
2703 : : download the debuginfo or executable containing the section in order
2704 : : to extract it. */
2705 : 0 : rc = -EEXIST;
2706 : 0 : int fd = -1;
2707 : 0 : char *tmp_path = NULL;
2708 : :
2709 : 0 : fd = debuginfod_find_debuginfo (client, build_id, build_id_len, &tmp_path);
2710 [ # # ]: 0 : if (client->progressfn_cancel)
2711 : : {
2712 [ # # ]: 0 : if (fd >= 0)
2713 : : {
2714 : : /* This shouldn't happen, but we'll check this condition
2715 : : just in case. */
2716 : 0 : close (fd);
2717 : 0 : free (tmp_path);
2718 : : }
2719 : 0 : return -ENOENT;
2720 : : }
2721 [ # # ]: 0 : if (fd >= 0)
2722 : : {
2723 : 0 : rc = extract_section (fd, section, tmp_path, path);
2724 : 0 : close (fd);
2725 : : }
2726 : :
2727 [ # # ]: 0 : if (rc == -EEXIST)
2728 : : {
2729 : : /* Either the debuginfo couldn't be found or the section should
2730 : : be in the executable. */
2731 : 0 : fd = debuginfod_find_executable (client, build_id,
2732 : : build_id_len, &tmp_path);
2733 [ # # ]: 0 : if (fd >= 0)
2734 : : {
2735 : 0 : rc = extract_section (fd, section, tmp_path, path);
2736 : 0 : close (fd);
2737 : : }
2738 : : else
2739 : : /* Update rc so that we return the most recent error code. */
2740 : : rc = fd;
2741 : : }
2742 : :
2743 : 0 : free (tmp_path);
2744 : 0 : return rc;
2745 : : }
2746 : :
2747 : :
2748 : 52 : int debuginfod_find_metadata (debuginfod_client *client,
2749 : : const char* key, const char* value, char **path)
2750 : : {
2751 : 52 : char *server_urls = NULL;
2752 : 52 : char *urls_envvar = NULL;
2753 : 52 : char *cache_path = NULL;
2754 : 52 : char *target_cache_dir = NULL;
2755 : 52 : char *target_cache_path = NULL;
2756 : 52 : char *target_cache_tmppath = NULL;
2757 : 52 : char *target_file_name = NULL;
2758 : 52 : char *key_and_value = NULL;
2759 : 52 : int rc = 0, r;
2760 : 52 : int vfd = client->verbose_fd;
2761 : 52 : struct handle_data *data = NULL;
2762 : :
2763 : 52 : client->progressfn_cancel = false;
2764 : :
2765 : 52 : json_object *json_metadata = json_object_new_object();
2766 : 52 : json_bool json_metadata_complete = true;
2767 : 52 : json_object *json_metadata_arr = json_object_new_array();
2768 [ - + ]: 52 : if (NULL == json_metadata)
2769 : : {
2770 : 0 : rc = -ENOMEM;
2771 : 0 : goto out;
2772 : : }
2773 [ - + ]: 52 : json_object_object_add(json_metadata, "results",
2774 : 0 : json_metadata_arr ?: json_object_new_array() /* Empty array */);
2775 : :
2776 [ - + ]: 52 : if (NULL == value || NULL == key)
2777 : : {
2778 : 0 : rc = -EINVAL;
2779 : 0 : goto out;
2780 : : }
2781 : :
2782 [ - + ]: 52 : if (vfd >= 0)
2783 : 0 : dprintf (vfd, "debuginfod_find_metadata %s %s\n", key, value);
2784 : :
2785 : : /* Without query-able URL, we can stop here*/
2786 : 52 : urls_envvar = getenv(DEBUGINFOD_URLS_ENV_VAR);
2787 [ - + ]: 52 : if (vfd >= 0)
2788 [ # # ]: 0 : dprintf (vfd, "server urls \"%s\"\n",
2789 : : urls_envvar != NULL ? urls_envvar : "");
2790 [ + - + + ]: 52 : if (urls_envvar == NULL || urls_envvar[0] == '\0')
2791 : : {
2792 : 18 : rc = -ENOSYS;
2793 : 18 : goto out;
2794 : : }
2795 : :
2796 : : /* set paths needed to perform the query
2797 : : example format:
2798 : : cache_path: $HOME/.cache
2799 : : target_cache_dir: $HOME/.cache/metadata
2800 : : target_cache_path: $HOME/.cache/metadata/KEYENCODED_VALUEENCODED
2801 : : target_cache_path: $HOME/.cache/metadata/KEYENCODED_VALUEENCODED.XXXXXX
2802 : : */
2803 : :
2804 : : // libcurl > 7.62ish has curl_url_set()/etc. to construct these things more properly.
2805 : : // curl_easy_escape() is older
2806 : : {
2807 : 34 : CURL *c = curl_easy_init();
2808 [ - + ]: 34 : if (!c)
2809 : : {
2810 : 0 : rc = -ENOMEM;
2811 : 0 : goto out;
2812 : : }
2813 : 34 : char *key_escaped = curl_easy_escape(c, key, 0);
2814 : 34 : char *value_escaped = curl_easy_escape(c, value, 0);
2815 : :
2816 : : // fallback to unescaped values in unlikely case of error
2817 [ - + - + : 68 : xalloc_str (key_and_value, "key=%s&value=%s", key_escaped ?: key, value_escaped ?: value);
- + ]
2818 [ - + ]: 34 : xalloc_str (target_file_name, "%s_%s", key_escaped ?: key, value_escaped ?: value);
2819 : 34 : curl_free(value_escaped);
2820 : 34 : curl_free(key_escaped);
2821 : 34 : curl_easy_cleanup(c);
2822 : : }
2823 : :
2824 : : /* Check if we have a recent result already in the cache. */
2825 : 34 : cache_path = make_cache_path();
2826 [ - + ]: 34 : if (! cache_path)
2827 : : {
2828 : 0 : rc = -ENOMEM;
2829 : 0 : goto out;
2830 : : }
2831 [ - + ]: 34 : xalloc_str (target_cache_dir, "%s/metadata", cache_path);
2832 : 34 : (void) mkdir (target_cache_dir, 0700);
2833 [ - + ]: 34 : xalloc_str (target_cache_path, "%s/%s", target_cache_dir, target_file_name);
2834 [ - + ]: 34 : xalloc_str (target_cache_tmppath, "%s/%s.XXXXXX", target_cache_dir, target_file_name);
2835 : :
2836 : 34 : int fd = open(target_cache_path, O_RDONLY);
2837 [ + + ]: 34 : if (fd >= 0)
2838 : : {
2839 : 12 : struct stat st;
2840 : 12 : int metadata_retention = 0;
2841 : 12 : time_t now = time(NULL);
2842 : 12 : char *metadata_retention_path = 0;
2843 : :
2844 [ - + ]: 22 : xalloc_str (metadata_retention_path, "%s/%s", cache_path, metadata_retention_filename);
2845 [ + - ]: 12 : if (metadata_retention_path)
2846 : : {
2847 : 12 : rc = debuginfod_config_cache(client, metadata_retention_path,
2848 : : metadata_retention_default_s, &st);
2849 : 12 : free (metadata_retention_path);
2850 [ - + ]: 12 : if (rc < 0)
2851 : 0 : rc = 0;
2852 : : }
2853 : : else
2854 : : rc = 0;
2855 : 12 : metadata_retention = rc;
2856 : :
2857 [ - + ]: 12 : if (fstat(fd, &st) != 0)
2858 : : {
2859 : 0 : rc = -errno;
2860 : 0 : close (fd);
2861 : 0 : goto out;
2862 : : }
2863 : :
2864 [ + + + - ]: 12 : if (metadata_retention > 0 && (now - st.st_mtime <= metadata_retention))
2865 : : {
2866 [ - + ]: 10 : if (client && client->verbose_fd >= 0)
2867 : 0 : dprintf (client->verbose_fd, "cached metadata %s", target_file_name);
2868 : :
2869 [ + - ]: 10 : if (path != NULL)
2870 : : {
2871 : 10 : *path = target_cache_path; // pass over the pointer
2872 : 10 : target_cache_path = NULL; // prevent free() in our own cleanup
2873 : : }
2874 : :
2875 : : /* Success!!!! */
2876 : 10 : rc = fd;
2877 : 10 : goto out;
2878 : : }
2879 : :
2880 : : /* We don't have to clear the likely-expired cached object here
2881 : : by unlinking. We will shortly make a new request and save
2882 : : results right on top. Erasing here could trigger a TOCTOU
2883 : : race with another thread just finishing a query and passing
2884 : : its results back.
2885 : : */
2886 : : // (void) unlink (target_cache_path);
2887 : :
2888 : 2 : close (fd);
2889 : : }
2890 : :
2891 : : /* No valid cached metadata found: time to make the queries. */
2892 : :
2893 : 24 : free (client->url);
2894 : 24 : client->url = NULL;
2895 : :
2896 : 24 : long maxtime = 0;
2897 : 24 : const char *maxtime_envvar;
2898 : 24 : maxtime_envvar = getenv(DEBUGINFOD_MAXTIME_ENV_VAR);
2899 [ - + ]: 24 : if (maxtime_envvar != NULL)
2900 : 0 : maxtime = atol (maxtime_envvar);
2901 [ - + ]: 24 : if (maxtime && vfd >= 0)
2902 : 0 : dprintf(vfd, "using max time %lds\n", maxtime);
2903 : :
2904 : 24 : long timeout = default_timeout;
2905 : 24 : const char* timeout_envvar = getenv(DEBUGINFOD_TIMEOUT_ENV_VAR);
2906 [ - + ]: 24 : if (timeout_envvar != NULL)
2907 : 0 : timeout = atoi (timeout_envvar);
2908 [ - + ]: 24 : if (vfd >= 0)
2909 : 0 : dprintf (vfd, "using timeout %ld\n", timeout);
2910 : :
2911 : 24 : add_default_headers(client);
2912 : :
2913 : : /* Make a copy of the envvar so it can be safely modified. */
2914 : 24 : server_urls = strdup(urls_envvar);
2915 [ - + ]: 24 : if (server_urls == NULL)
2916 : : {
2917 : 0 : rc = -ENOMEM;
2918 : 0 : goto out;
2919 : : }
2920 : :
2921 : : /* Thereafter, goto out1 on error*/
2922 : :
2923 : 24 : char **server_url_list = NULL;
2924 : 24 : ima_policy_t* url_ima_policies = NULL;
2925 : 24 : char *server_url;
2926 : 24 : int num_urls = 0;
2927 : 24 : r = init_server_urls("metadata", NULL, server_urls, &server_url_list, &url_ima_policies, &num_urls, vfd);
2928 [ - + ]: 24 : if (0 != r)
2929 : : {
2930 : 0 : rc = r;
2931 : 0 : goto out1;
2932 : : }
2933 : :
2934 : 24 : CURLM *curlm = client->server_mhandle;
2935 : :
2936 : 24 : CURL *target_handle = NULL;
2937 : 24 : data = malloc(sizeof(struct handle_data) * num_urls);
2938 [ - + ]: 24 : if (data == NULL)
2939 : : {
2940 : 0 : rc = -ENOMEM;
2941 : 0 : goto out1;
2942 : : }
2943 : :
2944 : : /* thereafter, goto out2 on error. */
2945 : :
2946 : : /* Initialize handle_data */
2947 [ + + ]: 60 : for (int i = 0; i < num_urls; i++)
2948 : : {
2949 [ + - ]: 36 : if ((server_url = server_url_list[i]) == NULL)
2950 : : break;
2951 [ - + ]: 36 : if (vfd >= 0)
2952 : 0 : dprintf (vfd, "init server %d %s\n", i, server_url);
2953 : :
2954 : 36 : data[i].errbuf[0] = '\0';
2955 : 36 : data[i].target_handle = &target_handle;
2956 : 36 : data[i].client = client;
2957 : 36 : data[i].metadata = NULL;
2958 : 36 : data[i].metadata_size = 0;
2959 : 36 : data[i].response_data = NULL;
2960 : 36 : data[i].response_data_size = 0;
2961 : :
2962 : 36 : snprintf(data[i].url, PATH_MAX, "%s?%s", server_url, key_and_value);
2963 : :
2964 : 36 : r = init_handle(client, metadata_callback, header_callback, &data[i], i, timeout, vfd);
2965 [ - + ]: 36 : if (0 != r)
2966 : : {
2967 : 0 : rc = r;
2968 : 0 : goto out2;
2969 : : }
2970 : 36 : curl_multi_add_handle(curlm, data[i].handle);
2971 : : }
2972 : :
2973 : : /* Query servers */
2974 [ - + ]: 24 : if (vfd >= 0)
2975 : 0 : dprintf (vfd, "Starting %d queries\n",num_urls);
2976 : 24 : int committed_to;
2977 : 24 : r = perform_queries(curlm, NULL, data, client, num_urls, maxtime, 0, false, vfd, &committed_to);
2978 [ - + ]: 24 : if (0 != r)
2979 : : {
2980 : 0 : rc = r;
2981 : 0 : goto out2;
2982 : : }
2983 : :
2984 : : /* NOTE: We don't check the return codes of the curl messages since
2985 : : a metadata query failing silently is just fine. We want to know what's
2986 : : available from servers which can be connected with no issues.
2987 : : If running with additional verbosity, the failure will be noted in stderr */
2988 : :
2989 : : /* Building the new json array from all the upstream data and
2990 : : cleanup while at it.
2991 : : */
2992 [ + + ]: 60 : for (int i = 0; i < num_urls; i++)
2993 : : {
2994 : 36 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2995 : 36 : curl_easy_cleanup (data[i].handle);
2996 : 36 : free (data[i].response_data);
2997 : :
2998 [ + + ]: 36 : if (NULL == data[i].metadata)
2999 : : {
3000 [ - + ]: 16 : if (vfd >= 0)
3001 : 0 : dprintf (vfd, "Query to %s failed with error message:\n\t\"%s\"\n",
3002 : 0 : data[i].url, data[i].errbuf);
3003 : 16 : json_metadata_complete = false;
3004 : 16 : continue;
3005 : : }
3006 : :
3007 : 20 : json_object *upstream_metadata = json_tokener_parse(data[i].metadata);
3008 : 20 : json_object *upstream_complete;
3009 : 20 : json_object *upstream_metadata_arr;
3010 [ + - + - ]: 40 : if (NULL == upstream_metadata ||
3011 [ - + ]: 40 : !json_object_object_get_ex(upstream_metadata, "results", &upstream_metadata_arr) ||
3012 : 20 : !json_object_object_get_ex(upstream_metadata, "complete", &upstream_complete))
3013 : 0 : continue;
3014 : 20 : json_metadata_complete &= json_object_get_boolean(upstream_complete);
3015 : : // Combine the upstream metadata into the json array
3016 [ + + ]: 38 : for (int j = 0, n = json_object_array_length(upstream_metadata_arr); j < n; j++)
3017 : : {
3018 : 18 : json_object *entry = json_object_array_get_idx(upstream_metadata_arr, j);
3019 : 18 : json_object_get(entry); // increment reference count
3020 : 18 : json_object_array_add(json_metadata_arr, entry);
3021 : : }
3022 : 20 : json_object_put(upstream_metadata);
3023 : :
3024 : 20 : free (data[i].metadata);
3025 : : }
3026 : :
3027 : : /* Because of race with cache cleanup / rmdir, try to mkdir/mkstemp up to twice. */
3028 [ + - ]: 24 : for (int i=0; i<2; i++)
3029 : : {
3030 : : /* (re)create target directory in cache */
3031 : 24 : (void) mkdir(target_cache_dir, 0700); /* files will be 0400 later */
3032 : :
3033 : : /* NB: write to a temporary file first, to avoid race condition of
3034 : : multiple clients checking the cache, while a partially-written or empty
3035 : : file is in there, being written from libcurl. */
3036 : 24 : fd = mkstemp (target_cache_tmppath);
3037 [ - + ]: 24 : if (fd >= 0) break;
3038 : : }
3039 [ - + ]: 24 : if (fd < 0) /* Still failed after two iterations. */
3040 : : {
3041 : 0 : rc = -errno;
3042 : 0 : goto out1;
3043 : : }
3044 : :
3045 : : /* Plop the complete json_metadata object into the cache. */
3046 : 24 : json_object_object_add(json_metadata, "complete", json_object_new_boolean(json_metadata_complete));
3047 : 24 : const char* json_string = json_object_to_json_string_ext(json_metadata, JSON_C_TO_STRING_PRETTY);
3048 [ - + ]: 24 : if (json_string == NULL)
3049 : : {
3050 : 0 : rc = -ENOMEM;
3051 : 0 : goto out1;
3052 : : }
3053 : 24 : ssize_t res = write_retry (fd, json_string, strlen(json_string));
3054 : 24 : (void) lseek(fd, 0, SEEK_SET); // rewind file so client can read it from the top
3055 : :
3056 : : /* NB: json_string is auto deleted when json_metadata object is nuked */
3057 [ + - - + ]: 24 : if (res < 0 || (size_t) res != strlen(json_string))
3058 : : {
3059 : 0 : rc = -EIO;
3060 : 0 : goto out1;
3061 : : }
3062 : : /* PR27571: make cache files casually unwriteable; dirs are already 0700 */
3063 : 24 : (void) fchmod(fd, 0400);
3064 : :
3065 : : /* rename tmp->real */
3066 : 24 : rc = rename (target_cache_tmppath, target_cache_path);
3067 [ - + ]: 24 : if (rc < 0)
3068 : : {
3069 : 0 : rc = -errno;
3070 : 0 : goto out1;
3071 : : /* Perhaps we need not give up right away; could retry or something ... */
3072 : : }
3073 : :
3074 : : /* don't close fd - we're returning it */
3075 : : /* don't unlink the tmppath; it's already been renamed. */
3076 [ + - ]: 24 : if (path != NULL)
3077 : 24 : *path = strdup(target_cache_path);
3078 : :
3079 : 24 : rc = fd;
3080 : 24 : goto out1;
3081 : :
3082 : : /* error exits */
3083 : 0 : out2:
3084 : : /* remove all handles from multi */
3085 [ # # ]: 0 : for (int i = 0; i < num_urls; i++)
3086 : : {
3087 [ # # ]: 0 : if (data[i].handle != NULL)
3088 : : {
3089 : 0 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
3090 : 0 : curl_easy_cleanup (data[i].handle);
3091 : 0 : free (data[i].response_data);
3092 : 0 : free (data[i].metadata);
3093 : : }
3094 : : }
3095 : :
3096 : 0 : out1:
3097 : 24 : free(data);
3098 : :
3099 [ + + ]: 60 : for (int i = 0; i < num_urls; ++i)
3100 : 36 : free(server_url_list[i]);
3101 : 24 : free(server_url_list);
3102 : 24 : free(url_ima_policies);
3103 : :
3104 : 52 : out:
3105 : 52 : free (server_urls);
3106 : 52 : json_object_put(json_metadata);
3107 : : /* Reset sent headers */
3108 : 52 : curl_slist_free_all (client->headers);
3109 : 52 : client->headers = NULL;
3110 : 52 : client->user_agent_set_p = 0;
3111 : :
3112 : 52 : free (target_cache_dir);
3113 : 52 : free (target_cache_path);
3114 : 52 : free (target_cache_tmppath);
3115 : 52 : free (key_and_value);
3116 : 52 : free (target_file_name);
3117 : 52 : free (cache_path);
3118 : :
3119 : 52 : return rc;
3120 : : }
3121 : :
3122 : :
3123 : : /* Add an outgoing HTTP header. */
3124 : 2882 : int debuginfod_add_http_header (debuginfod_client *client, const char* header)
3125 : : {
3126 : : /* Sanity check header value is of the form Header: Value.
3127 : : It should contain at least one colon that isn't the first or
3128 : : last character. */
3129 : 2882 : const char *colon = strchr (header, ':'); /* first colon */
3130 : 2882 : if (colon == NULL /* present */
3131 [ + - ]: 2882 : || colon == header /* not at beginning - i.e., have a header name */
3132 [ + - ]: 2882 : || *(colon + 1) == '\0') /* not at end - i.e., have a value */
3133 : : /* NB: but it's okay for a value to contain other colons! */
3134 : : return -EINVAL;
3135 : :
3136 : 2882 : struct curl_slist *temp = curl_slist_append (client->headers, header);
3137 [ + - ]: 2882 : if (temp == NULL)
3138 : : return -ENOMEM;
3139 : :
3140 : : /* Track if User-Agent: is being set. If so, signal not to add the
3141 : : default one. */
3142 [ + + ]: 2882 : if (startswith (header, "User-Agent:"))
3143 : 2224 : client->user_agent_set_p = 1;
3144 : :
3145 : 2882 : client->headers = temp;
3146 : 2882 : return 0;
3147 : : }
3148 : :
3149 : :
3150 : : void
3151 : 1126 : debuginfod_set_progressfn(debuginfod_client *client,
3152 : : debuginfod_progressfn_t fn)
3153 : : {
3154 : 1126 : client->progressfn = fn;
3155 : 1126 : }
3156 : :
3157 : : void
3158 : 72 : debuginfod_set_verbose_fd(debuginfod_client *client, int fd)
3159 : : {
3160 : 72 : client->verbose_fd = fd;
3161 : 72 : }
3162 : :
3163 : : #endif /* DUMMY_LIBDEBUGINFOD */
|