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 : 10439 : debuginfod_write_callback (char *ptr, size_t size, size_t nmemb, void *data)
454 : : {
455 : 10439 : ssize_t count = size * nmemb;
456 : :
457 : 10439 : struct handle_data *d = (struct handle_data*)data;
458 : :
459 : : /* Indicate to other handles that they can abort their transfer. */
460 [ + + ]: 10439 : 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 [ + - ]: 10439 : if (*d->target_handle != d->handle)
476 : : return -1;
477 : :
478 : 10439 : 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 : 13800 : header_callback (char * buffer, size_t size, size_t numitems, void * userdata)
800 : : {
801 : 13800 : struct handle_data *data = (struct handle_data *) userdata;
802 [ - + ]: 13800 : if (size != 1)
803 : : return 0;
804 [ + - ]: 13800 : if (data->client
805 [ + + ]: 13800 : && 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 [ + + ]: 13800 : 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 : 7259 : long delta = 0;
1057 : 7259 : do
1058 : : {
1059 : : /* Check to see how long querying is taking. */
1060 [ + + ]: 7259 : 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 : 7259 : curl_multi_wait(curlm, NULL, 0, 1000, NULL);
1073 : 7259 : CURLMcode curlm_res = curl_multi_perform(curlm, &still_running);
1074 : :
1075 [ + + ]: 7259 : if (only_one)
1076 : : {
1077 : : /* If the target file has been found, abort the other queries. */
1078 [ + - + + ]: 7189 : if (target_handle && *target_handle != NULL)
1079 : : {
1080 [ + + ]: 5582 : for (int i = 0; i < num_urls; i++)
1081 [ + + ]: 3463 : if (data[i].handle != *target_handle)
1082 : 1344 : curl_multi_remove_handle(curlm, data[i].handle);
1083 : : else
1084 : : {
1085 : 2119 : *committed_to = i;
1086 [ + + ]: 2119 : 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 [ + + + + ]: 7189 : 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 [ - + ]: 7259 : 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 : 7259 : long dl_size = -1;
1119 [ + + + + : 7259 : 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 : 1027 : CURLcode curl_res;
1125 : : #if CURL_AT_LEAST_VERSION(7, 55, 0)
1126 : 1027 : curl_off_t cl;
1127 : 1027 : curl_res = curl_easy_getinfo(*target_handle,
1128 : : CURLINFO_CONTENT_LENGTH_DOWNLOAD_T,
1129 : : &cl);
1130 [ + - - + ]: 1027 : 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 [ + + ]: 7259 : if (c->progressfn) /* inform/check progress callback */
1154 : : {
1155 : 4973 : loops ++;
1156 : 4973 : long pa = loops; /* default param for progress callback */
1157 [ + + + + ]: 4973 : 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 : 1027 : struct stat cached;
1164 : 1027 : int statrc = fstat(data[*committed_to].fd, &cached);
1165 [ + - ]: 1027 : if (statrc == 0)
1166 : 1027 : 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 [ - + - + ]: 1027 : 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 [ + + + + : 7227 : 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 [ + + ]: 7259 : } 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 : : char file_data[DATA_SIZE]; // imaevm.h data chunk hash size
1644 : : ssize_t n;
1645 : : for(off_t k = 0; k < data_len; k += n)
1646 : : {
1647 : : if (-1 == (n = pread(fd, file_data, DATA_SIZE, k)))
1648 : : {
1649 : : rc = -errno;
1650 : : goto exit_validate;
1651 : : }
1652 : :
1653 : : if (!EVP_DigestUpdate(ctx, file_data, n))
1654 : : {
1655 : : rc = -EBADMSG;
1656 : : goto exit_validate;
1657 : : }
1658 : : }
1659 : :
1660 : : uint8_t bin_dig[MAX_DIGEST_SIZE];
1661 : : unsigned int bin_dig_len;
1662 : : if (!EVP_DigestFinal(ctx, bin_dig, &bin_dig_len))
1663 : : {
1664 : : rc = -EBADMSG;
1665 : : goto exit_validate;
1666 : : }
1667 : :
1668 : : // XXX: in case of DIGSIG_VERSION_3, need to hash the file hash, yo dawg
1669 : :
1670 : : int res = debuginfod_verify_hash(c,
1671 : : bin_dig, bin_dig_len,
1672 : : sighash_name,
1673 : : & bin_sig[1], bin_sig_len-1); // skip over first byte of signature
1674 : : if (c->verbose_fd >= 0)
1675 : : dprintf (c->verbose_fd, "Computed ima signature verification res=%d\n", res);
1676 : : rc = res;
1677 : :
1678 : : exit_validate:
1679 : : free (sig_buf);
1680 : : EVP_MD_CTX_free(ctx);
1681 : : return rc;
1682 : : }
1683 : : #endif /* ENABLE_IMA_VERIFICATION */
1684 : :
1685 : :
1686 : :
1687 : :
1688 : : /* Helper function to create client cache directory.
1689 : : $XDG_CACHE_HOME takes priority over $HOME/.cache.
1690 : : $DEBUGINFOD_CACHE_PATH takes priority over $HOME/.cache and $XDG_CACHE_HOME.
1691 : :
1692 : : Return resulting path name or NULL on error. Caller must free resulting string.
1693 : : */
1694 : : static char *
1695 : 2134 : make_cache_path(void)
1696 : : {
1697 : 2134 : char* cache_path = NULL;
1698 : 2134 : int rc = 0;
1699 : : /* Determine location of the cache. The path specified by the debuginfod
1700 : : cache environment variable takes priority. */
1701 : 2134 : char *cache_var = getenv(DEBUGINFOD_CACHE_PATH_ENV_VAR);
1702 [ + - + + ]: 2134 : if (cache_var != NULL && strlen (cache_var) > 0)
1703 [ - + ]: 2126 : xalloc_str (cache_path, "%s", cache_var);
1704 : : else
1705 : : {
1706 : : /* If a cache already exists in $HOME ('/' if $HOME isn't set), then use
1707 : : that. Otherwise use the XDG cache directory naming format. */
1708 [ - + - + ]: 16 : xalloc_str (cache_path, "%s/%s", getenv ("HOME") ?: "/", cache_default_name);
1709 : :
1710 : 8 : struct stat st;
1711 [ + + ]: 8 : if (stat (cache_path, &st) < 0)
1712 : : {
1713 : 6 : char cachedir[PATH_MAX];
1714 : 6 : char *xdg = getenv ("XDG_CACHE_HOME");
1715 : :
1716 [ + - + + ]: 6 : if (xdg != NULL && strlen (xdg) > 0)
1717 : 2 : snprintf (cachedir, PATH_MAX, "%s", xdg);
1718 : : else
1719 [ - + ]: 4 : snprintf (cachedir, PATH_MAX, "%s/.cache", getenv ("HOME") ?: "/");
1720 : :
1721 : : /* Create XDG cache directory if it doesn't exist. */
1722 [ + + ]: 6 : if (stat (cachedir, &st) == 0)
1723 : : {
1724 [ - + ]: 2 : if (! S_ISDIR (st.st_mode))
1725 : : {
1726 : 0 : rc = -EEXIST;
1727 : 0 : goto out1;
1728 : : }
1729 : : }
1730 : : else
1731 : : {
1732 : 4 : rc = mkdir (cachedir, 0700);
1733 : :
1734 : : /* Also check for EEXIST and S_ISDIR in case another client just
1735 : : happened to create the cache. */
1736 [ - + ]: 4 : if (rc < 0
1737 [ # # ]: 0 : && (errno != EEXIST
1738 [ # # ]: 0 : || stat (cachedir, &st) != 0
1739 [ # # ]: 0 : || ! S_ISDIR (st.st_mode)))
1740 : : {
1741 : 0 : rc = -errno;
1742 : 0 : goto out1;
1743 : : }
1744 : : }
1745 : :
1746 : 6 : free (cache_path);
1747 [ - + ]: 6 : xalloc_str (cache_path, "%s/%s", cachedir, cache_xdg_name);
1748 : : }
1749 : : }
1750 : :
1751 : 2134 : goto out;
1752 : :
1753 : 0 : out1:
1754 : 0 : (void) rc;
1755 : 0 : free (cache_path);
1756 : 0 : cache_path = NULL;
1757 : :
1758 : 2134 : out:
1759 [ + - ]: 2134 : if (cache_path != NULL)
1760 : 2134 : (void) mkdir (cache_path, 0700); // failures with this mkdir would be caught later too
1761 : 2134 : return cache_path;
1762 : : }
1763 : :
1764 : :
1765 : : /* Query each of the server URLs found in $DEBUGINFOD_URLS for the file
1766 : : with the specified build-id and type (debuginfo, executable, source or
1767 : : section). If type is source, then type_arg should be a filename. If
1768 : : type is section, then type_arg should be the name of an ELF/DWARF
1769 : : section. Otherwise type_arg may be NULL. Return a file descriptor
1770 : : for the target if successful, otherwise return an error code.
1771 : : */
1772 : : static int
1773 : 6518 : debuginfod_query_server_by_buildid (debuginfod_client *c,
1774 : : const unsigned char *build_id,
1775 : : int build_id_len,
1776 : : const char *type,
1777 : : const char *type_arg,
1778 : : char **path)
1779 : : {
1780 : 6518 : char *server_urls;
1781 : 6518 : char *urls_envvar;
1782 : 6518 : const char *section = NULL;
1783 : 6518 : const char *filename = NULL;
1784 : 6518 : char *cache_path = NULL;
1785 : 6518 : char *maxage_path = NULL;
1786 : 6518 : char *interval_path = NULL;
1787 : 6518 : char *cache_miss_path = NULL;
1788 : 6518 : char *target_cache_dir = NULL;
1789 : 6518 : char *target_cache_path = NULL;
1790 : 6518 : char *target_cachehdr_path = NULL;
1791 : 6518 : char *target_cache_tmppath = NULL;
1792 : 6518 : char *target_cachehdr_tmppath = NULL;
1793 : 6518 : char suffix[NAME_MAX];
1794 : 6518 : char build_id_bytes[MAX_BUILD_ID_BYTES * 2 + 1];
1795 : 6518 : int vfd = c->verbose_fd;
1796 : 6518 : int rc, r;
1797 : :
1798 : 6518 : c->progressfn_cancel = false;
1799 : :
1800 [ + + ]: 6518 : if (strcmp (type, "source") == 0)
1801 : : filename = type_arg;
1802 [ + + ]: 1052 : else if (strcmp (type, "section") == 0)
1803 : : {
1804 : 16 : section = type_arg;
1805 [ + - ]: 16 : if (section == NULL)
1806 : : return -EINVAL;
1807 : : }
1808 : :
1809 [ + + ]: 6518 : if (vfd >= 0)
1810 : : {
1811 : 1124 : dprintf (vfd, "debuginfod_find_%s ", type);
1812 [ + + ]: 1124 : if (build_id_len == 0) /* expect clean hexadecimal */
1813 : 32 : dprintf (vfd, "%s", (const char *) build_id);
1814 : : else
1815 [ + + ]: 22932 : for (int i = 0; i < build_id_len; i++)
1816 : 21840 : dprintf (vfd, "%02x", build_id[i]);
1817 [ + + ]: 1124 : if (filename != NULL)
1818 : 1088 : dprintf (vfd, " %s\n", filename);
1819 : 1124 : dprintf (vfd, "\n");
1820 : : }
1821 : :
1822 : : /* Is there any server we can query? If not, don't do any work,
1823 : : just return with ENOSYS. Don't even access the cache. */
1824 : 6518 : urls_envvar = getenv(DEBUGINFOD_URLS_ENV_VAR);
1825 [ + + ]: 6518 : if (vfd >= 0)
1826 [ - + ]: 1124 : dprintf (vfd, "server urls \"%s\"\n",
1827 : : urls_envvar != NULL ? urls_envvar : "");
1828 [ + + + + ]: 6518 : if (urls_envvar == NULL || urls_envvar[0] == '\0')
1829 : : {
1830 : 4418 : rc = -ENOSYS;
1831 : 4418 : goto out;
1832 : : }
1833 : :
1834 : : /* Clear the obsolete data from a previous _find operation. */
1835 : 2100 : free (c->url);
1836 : 2100 : c->url = NULL;
1837 : 2100 : free (c->winning_headers);
1838 : 2100 : c->winning_headers = NULL;
1839 : :
1840 : : /* PR 27982: Add max size if DEBUGINFOD_MAXSIZE is set. */
1841 : 2100 : long maxsize = 0;
1842 : 2100 : const char *maxsize_envvar;
1843 : 2100 : maxsize_envvar = getenv(DEBUGINFOD_MAXSIZE_ENV_VAR);
1844 [ + + ]: 2100 : if (maxsize_envvar != NULL)
1845 : 2 : maxsize = atol (maxsize_envvar);
1846 : :
1847 : : /* PR 27982: Add max time if DEBUGINFOD_MAXTIME is set. */
1848 : 2100 : long maxtime = 0;
1849 : 2100 : const char *maxtime_envvar;
1850 : 2100 : maxtime_envvar = getenv(DEBUGINFOD_MAXTIME_ENV_VAR);
1851 [ + + ]: 2100 : if (maxtime_envvar != NULL)
1852 : 2 : maxtime = atol (maxtime_envvar);
1853 [ + + ]: 2100 : if (maxtime && vfd >= 0)
1854 : 2 : dprintf(vfd, "using max time %lds\n", maxtime);
1855 : :
1856 : 2100 : const char *headers_file_envvar;
1857 : 2100 : headers_file_envvar = getenv(DEBUGINFOD_HEADERS_FILE_ENV_VAR);
1858 [ - + ]: 2100 : if (headers_file_envvar != NULL)
1859 : 0 : add_headers_from_file(c, headers_file_envvar);
1860 : :
1861 : : /* Maxsize is valid*/
1862 [ + + ]: 2100 : if (maxsize > 0)
1863 : : {
1864 [ + - ]: 2 : if (vfd)
1865 : 2 : dprintf (vfd, "using max size %ldB\n", maxsize);
1866 : 2 : char *size_header = NULL;
1867 : 2 : rc = asprintf (&size_header, "X-DEBUGINFOD-MAXSIZE: %ld", maxsize);
1868 [ - + ]: 2 : if (rc < 0)
1869 : : {
1870 : 0 : rc = -ENOMEM;
1871 : 0 : goto out;
1872 : : }
1873 : 2 : rc = debuginfod_add_http_header(c, size_header);
1874 : 2 : free(size_header);
1875 [ - + ]: 2 : if (rc < 0)
1876 : 0 : goto out;
1877 : : }
1878 : 2100 : add_default_headers(c);
1879 : :
1880 : : /* Copy lowercase hex representation of build_id into buf. */
1881 [ + + ]: 2100 : if (vfd >= 0)
1882 : 1124 : dprintf (vfd, "checking build-id\n");
1883 [ + - + + ]: 2100 : if ((build_id_len >= MAX_BUILD_ID_BYTES) ||
1884 : 1006 : (build_id_len == 0 &&
1885 [ - + ]: 1006 : strlen ((const char *) build_id) > MAX_BUILD_ID_BYTES*2))
1886 : : {
1887 : 0 : rc = -EINVAL;
1888 : 0 : goto out;
1889 : : }
1890 : :
1891 [ + + ]: 2100 : if (build_id_len == 0) /* expect clean hexadecimal */
1892 : 1006 : strcpy (build_id_bytes, (const char *) build_id);
1893 : : else
1894 [ + + ]: 22974 : for (int i = 0; i < build_id_len; i++)
1895 : 21880 : sprintf(build_id_bytes + (i * 2), "%02x", build_id[i]);
1896 : :
1897 [ + + ]: 2100 : if (filename != NULL)
1898 : : {
1899 [ + + ]: 1134 : if (vfd >= 0)
1900 : 1088 : dprintf (vfd, "checking filename\n");
1901 [ - + ]: 1134 : if (filename[0] != '/') // must start with /
1902 : : {
1903 : 0 : rc = -EINVAL;
1904 : 0 : goto out;
1905 : : }
1906 : :
1907 : 1134 : path_escape (filename, suffix, sizeof(suffix));
1908 : : /* If the DWARF filenames are super long, this could exceed
1909 : : PATH_MAX and truncate/collide. Oh well, that'll teach
1910 : : them! */
1911 : : }
1912 [ + + ]: 966 : else if (section != NULL)
1913 : 16 : path_escape (section, suffix, sizeof(suffix));
1914 : : else
1915 : 950 : suffix[0] = '\0';
1916 : :
1917 [ + + + + ]: 2100 : if (suffix[0] != '\0' && vfd >= 0)
1918 : 1104 : dprintf (vfd, "suffix %s\n", suffix);
1919 : :
1920 : : /* set paths needed to perform the query
1921 : : example format:
1922 : : cache_path: $HOME/.cache
1923 : : target_cache_dir: $HOME/.cache/0123abcd
1924 : : target_cache_path: $HOME/.cache/0123abcd/debuginfo
1925 : : target_cache_path: $HOME/.cache/0123abcd/executable-.debug_info
1926 : : target_cache_path: $HOME/.cache/0123abcd/source-HASH-#PATH#TO#SOURCE
1927 : : target_cachehdr_path: $HOME/.cache/0123abcd/hdr-debuginfo
1928 : : target_cachehdr_path: $HOME/.cache/0123abcd/hdr-executable...
1929 : : */
1930 : :
1931 : 2100 : cache_path = make_cache_path();
1932 [ - + ]: 2100 : if (!cache_path)
1933 : : {
1934 : 0 : rc = -ENOMEM;
1935 : 0 : goto out;
1936 : : }
1937 [ - + ]: 2100 : xalloc_str (target_cache_dir, "%s/%s", cache_path, build_id_bytes);
1938 : 2100 : (void) mkdir (target_cache_dir, 0700); // failures with this mkdir would be caught later too
1939 : :
1940 [ + + ]: 2100 : if (suffix[0] != '\0') { /* section, source queries */
1941 [ - + ]: 1150 : xalloc_str (target_cache_path, "%s/%s-%s", target_cache_dir, type, suffix);
1942 [ - + ]: 1150 : xalloc_str (target_cachehdr_path, "%s/hdr-%s-%s", target_cache_dir, type, suffix);
1943 : : } else {
1944 [ - + ]: 950 : xalloc_str (target_cache_path, "%s/%s", target_cache_dir, type);
1945 [ - + ]: 950 : xalloc_str (target_cachehdr_path, "%s/hdr-%s", target_cache_dir, type);
1946 : : }
1947 [ - + ]: 2100 : xalloc_str (target_cache_tmppath, "%s.XXXXXX", target_cache_path);
1948 [ - + ]: 2100 : xalloc_str (target_cachehdr_tmppath, "%s.XXXXXX", target_cachehdr_path);
1949 : :
1950 : : /* XXX combine these */
1951 [ - + ]: 2100 : xalloc_str (interval_path, "%s/%s", cache_path, cache_clean_interval_filename);
1952 [ - + ]: 2100 : xalloc_str (cache_miss_path, "%s/%s", cache_path, cache_miss_filename);
1953 [ - + ]: 2100 : xalloc_str (maxage_path, "%s/%s", cache_path, cache_max_unused_age_filename);
1954 : :
1955 [ + + ]: 2100 : if (vfd >= 0)
1956 : 1124 : dprintf (vfd, "checking cache dir %s\n", cache_path);
1957 : :
1958 : : /* Make sure cache dir exists. debuginfo_clean_cache will then make
1959 : : sure the interval, cache_miss and maxage files exist. */
1960 [ + - ]: 2100 : if (mkdir (cache_path, ACCESSPERMS) != 0
1961 [ - + ]: 2100 : && errno != EEXIST)
1962 : : {
1963 : 0 : rc = -errno;
1964 : 0 : goto out;
1965 : : }
1966 : :
1967 : 2100 : rc = debuginfod_clean_cache(c, cache_path, interval_path, maxage_path);
1968 [ - + ]: 2100 : if (rc != 0)
1969 : 0 : goto out;
1970 : :
1971 : : /* Check if the target is already in the cache. */
1972 : 2100 : int fd = open(target_cache_path, O_RDONLY);
1973 [ + + ]: 2100 : if (fd >= 0)
1974 : : {
1975 : 58 : struct stat st;
1976 [ - + ]: 58 : if (fstat(fd, &st) != 0)
1977 : : {
1978 : 0 : rc = -errno;
1979 : 0 : close (fd);
1980 : 56 : goto out;
1981 : : }
1982 : :
1983 : : /* If the file is non-empty, then we are done. */
1984 [ + + ]: 58 : if (st.st_size > 0)
1985 : : {
1986 [ + - ]: 54 : if (path != NULL)
1987 : : {
1988 : 54 : *path = strdup(target_cache_path);
1989 [ - + ]: 54 : if (*path == NULL)
1990 : : {
1991 : 0 : rc = -errno;
1992 : 0 : close (fd);
1993 : 0 : goto out;
1994 : : }
1995 : : }
1996 : : /* Success!!!! */
1997 : 54 : update_atime(fd);
1998 : 54 : rc = fd;
1999 : :
2000 : : /* Attempt to transcribe saved headers. */
2001 : 54 : int fdh = open (target_cachehdr_path, O_RDONLY);
2002 [ + + ]: 54 : if (fdh >= 0)
2003 : : {
2004 [ + - + - ]: 52 : if (fstat (fdh, &st) == 0 && st.st_size > 0)
2005 : : {
2006 : 52 : c->winning_headers = malloc(st.st_size);
2007 [ + - ]: 52 : if (NULL != c->winning_headers)
2008 : : {
2009 : 52 : ssize_t bytes_read = pread_retry(fdh, c->winning_headers, st.st_size, 0);
2010 [ - + ]: 52 : if (bytes_read <= 0)
2011 : : {
2012 : 0 : free (c->winning_headers);
2013 : 0 : c->winning_headers = NULL;
2014 : 0 : (void) unlink (target_cachehdr_path);
2015 : : }
2016 [ + + ]: 52 : if (vfd >= 0)
2017 : 2 : dprintf (vfd, "found %s (bytes=%ld)\n", target_cachehdr_path, (long)bytes_read);
2018 : : }
2019 : : }
2020 : :
2021 : 52 : update_atime (fdh);
2022 : 52 : close (fdh);
2023 : : }
2024 : :
2025 : 54 : goto out;
2026 : : }
2027 : : else
2028 : : {
2029 : : /* The file is empty. Attempt to download only if enough time
2030 : : has passed since the last attempt. */
2031 : 4 : time_t cache_miss;
2032 : 4 : time_t target_mtime = st.st_mtime;
2033 : :
2034 : 4 : close(fd); /* no need to hold onto the negative-hit file descriptor */
2035 : :
2036 : 4 : rc = debuginfod_config_cache(c, cache_miss_path,
2037 : : cache_miss_default_s, &st);
2038 [ - + ]: 4 : if (rc < 0)
2039 : 0 : goto out;
2040 : :
2041 : 4 : cache_miss = (time_t)rc;
2042 [ + + ]: 4 : if (time(NULL) - target_mtime <= cache_miss)
2043 : : {
2044 : 2 : rc = -ENOENT;
2045 : 2 : goto out;
2046 : : }
2047 : : else
2048 : : /* TOCTOU non-problem: if another task races, puts a working
2049 : : download or an empty file in its place, unlinking here just
2050 : : means WE will try to download again as uncached. */
2051 : 2 : (void) unlink(target_cache_path);
2052 : : }
2053 : : }
2054 [ - + ]: 2042 : else if (errno == EACCES)
2055 : : /* Ensure old 000-permission files are not lingering in the cache. */
2056 : 0 : (void) unlink(target_cache_path);
2057 : :
2058 [ + + ]: 2044 : if (section != NULL)
2059 : : {
2060 : : /* Try to extract the section from a cached file before querying
2061 : : any servers. */
2062 : 16 : rc = cache_find_section (section, target_cache_dir, path);
2063 : :
2064 : : /* If the section was found or confirmed to not exist, then we
2065 : : are done. */
2066 [ + + ]: 16 : if (rc >= 0 || rc == -ENOENT)
2067 : 8 : goto out;
2068 : : }
2069 : :
2070 : 2036 : long timeout = default_timeout;
2071 : 2036 : const char* timeout_envvar = getenv(DEBUGINFOD_TIMEOUT_ENV_VAR);
2072 [ - + ]: 2036 : if (timeout_envvar != NULL)
2073 : 0 : timeout = atoi (timeout_envvar);
2074 : :
2075 [ + + ]: 2036 : if (vfd >= 0)
2076 : 1114 : dprintf (vfd, "using timeout %ld\n", timeout);
2077 : :
2078 : : /* make a copy of the envvar so it can be safely modified. */
2079 : 2036 : server_urls = strdup(urls_envvar);
2080 [ - + ]: 2036 : if (server_urls == NULL)
2081 : : {
2082 : 0 : rc = -ENOMEM;
2083 : 0 : goto out;
2084 : : }
2085 : : /* thereafter, goto out0 on error*/
2086 : :
2087 : : /* Because of a race with cache cleanup / rmdir, try to mkdir/mkstemp up to twice. */
2088 [ + - ]: 2036 : for(int i=0; i<2; i++)
2089 : : {
2090 : : /* (re)create target directory in cache */
2091 : 2036 : (void) mkdir(target_cache_dir, 0700); /* files will be 0400 later */
2092 : :
2093 : : /* NB: write to a temporary file first, to avoid race condition of
2094 : : multiple clients checking the cache, while a partially-written or empty
2095 : : file is in there, being written from libcurl. */
2096 : 2036 : fd = mkstemp (target_cache_tmppath);
2097 [ - + ]: 2036 : if (fd >= 0) break;
2098 : : }
2099 [ - + ]: 2036 : if (fd < 0) /* Still failed after two iterations. */
2100 : : {
2101 : 0 : rc = -errno;
2102 : 0 : goto out0;
2103 : : }
2104 : :
2105 : 2036 : char **server_url_list = NULL;
2106 : 2036 : ima_policy_t* url_ima_policies = NULL;
2107 : 2036 : char *server_url;
2108 : 2036 : int num_urls;
2109 : 2036 : r = init_server_urls("buildid", type, server_urls, &server_url_list, &url_ima_policies, &num_urls, vfd);
2110 [ - + ]: 2036 : if (0 != r)
2111 : : {
2112 : 0 : rc = r;
2113 : 0 : goto out1;
2114 : : }
2115 : :
2116 : : /* No URLs survived parsing / filtering? Abort abort abort. */
2117 [ - + ]: 2036 : if (num_urls == 0)
2118 : : {
2119 : 0 : rc = -ENOSYS;
2120 : 0 : goto out1;
2121 : : }
2122 : :
2123 : 2036 : int retry_limit = default_retry_limit;
2124 : 2036 : const char* retry_limit_envvar = getenv(DEBUGINFOD_RETRY_LIMIT_ENV_VAR);
2125 [ + + ]: 2036 : if (retry_limit_envvar != NULL)
2126 : 4 : retry_limit = atoi (retry_limit_envvar);
2127 : :
2128 : 2036 : CURLM *curlm = c->server_mhandle;
2129 : :
2130 : : /* Tracks which handle should write to fd. Set to the first
2131 : : handle that is ready to write the target file to the cache. */
2132 : 2036 : CURL *target_handle = NULL;
2133 : 2036 : struct handle_data *data = malloc(sizeof(struct handle_data) * num_urls);
2134 [ - + ]: 2036 : if (data == NULL)
2135 : : {
2136 : 0 : rc = -ENOMEM;
2137 : 0 : goto out1;
2138 : : }
2139 : :
2140 : : /* thereafter, goto out2 on error. */
2141 : :
2142 : : /*The beginning of goto block query_in_parallel.*/
2143 : 2036 : query_in_parallel:
2144 : 3120 : rc = -ENOENT; /* Reset rc to default.*/
2145 : :
2146 : : /* Initialize handle_data with default values. */
2147 [ + + ]: 6290 : for (int i = 0; i < num_urls; i++)
2148 : : {
2149 : 3170 : data[i].handle = NULL;
2150 : 3170 : data[i].fd = -1;
2151 : 3170 : data[i].errbuf[0] = '\0';
2152 : 3170 : data[i].response_data = NULL;
2153 : 3170 : data[i].response_data_size = 0;
2154 : : }
2155 : :
2156 : 3120 : char *escaped_string = NULL;
2157 : 3120 : size_t escaped_strlen = 0;
2158 [ + + ]: 3120 : if (filename)
2159 : : {
2160 : 1134 : escaped_string = curl_easy_escape(&target_handle, filename+1, 0);
2161 [ - + ]: 1134 : if (!escaped_string)
2162 : : {
2163 : 0 : rc = -ENOMEM;
2164 : 0 : goto out2;
2165 : : }
2166 : 1134 : char *loc = escaped_string;
2167 : 1134 : escaped_strlen = strlen(escaped_string);
2168 [ + + ]: 8828 : while ((loc = strstr(loc, "%2F")))
2169 : : {
2170 : 7694 : loc[0] = '/';
2171 : : //pull the string back after replacement
2172 : : // loc-escaped_string finds the distance from the origin to the new location
2173 : : // - 2 accounts for the 2F which remain and don't need to be measured.
2174 : : // The two above subtracted from escaped_strlen yields the remaining characters
2175 : : // in the string which we want to pull back
2176 : 7694 : memmove(loc+1, loc+3,escaped_strlen - (loc-escaped_string) - 2);
2177 : : //Because the 2F was overwritten in the memmove (as desired) escaped_strlen is
2178 : : // now two shorter.
2179 : 7694 : escaped_strlen -= 2;
2180 : : }
2181 : : }
2182 : : /* Initialize each handle. */
2183 [ + + ]: 6290 : for (int i = 0; i < num_urls; i++)
2184 : : {
2185 [ + - ]: 3170 : if ((server_url = server_url_list[i]) == NULL)
2186 : : break;
2187 [ + + ]: 3170 : if (vfd >= 0)
2188 : : #ifdef ENABLE_IMA_VERIFICATION
2189 : : dprintf (vfd, "init server %d %s [IMA verification policy: %s]\n", i, server_url, ima_policy_enum2str(url_ima_policies[i]));
2190 : : #else
2191 : 1136 : dprintf (vfd, "init server %d %s\n", i, server_url);
2192 : : #endif
2193 : :
2194 : 3170 : data[i].fd = fd;
2195 : 3170 : data[i].target_handle = &target_handle;
2196 : 3170 : data[i].client = c;
2197 : :
2198 [ + + ]: 3170 : if (filename) /* must start with / */
2199 : : {
2200 : : /* PR28034 escape characters in completed url to %hh format. */
2201 : 1134 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
2202 : : build_id_bytes, type, escaped_string);
2203 : : }
2204 [ + + ]: 2036 : else if (section)
2205 : 8 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
2206 : : build_id_bytes, type, section);
2207 : : else
2208 : 2028 : snprintf(data[i].url, PATH_MAX, "%s/%s/%s", server_url, build_id_bytes, type);
2209 : :
2210 : 3170 : r = init_handle(c, debuginfod_write_callback, header_callback, &data[i], i, timeout, vfd);
2211 [ - + ]: 3170 : if (0 != r)
2212 : : {
2213 : 0 : rc = r;
2214 [ # # ]: 0 : if (filename) curl_free (escaped_string);
2215 : 0 : goto out2;
2216 : : }
2217 : :
2218 : 3170 : curl_multi_add_handle(curlm, data[i].handle);
2219 : : }
2220 : :
2221 [ + + ]: 3120 : if (filename) curl_free(escaped_string);
2222 : :
2223 : : /* Query servers in parallel. */
2224 [ + + ]: 3120 : if (vfd >= 0)
2225 : 1134 : dprintf (vfd, "query %d urls in parallel\n", num_urls);
2226 : 3120 : int committed_to;
2227 : 3120 : r = perform_queries(curlm, &target_handle, data, c, num_urls, maxtime, maxsize, true, vfd, &committed_to);
2228 [ - + ]: 3120 : if (0 != r)
2229 : : {
2230 : 0 : rc = r;
2231 : 0 : goto out2;
2232 : : }
2233 : :
2234 : : /* Check whether a query was successful. If so, assign its handle
2235 : : to verified_handle. */
2236 : : int num_msg;
2237 : : rc = -ENOENT;
2238 : 3122 : CURL *verified_handle = NULL;
2239 : 3122 : do
2240 : : {
2241 : 3122 : CURLMsg *msg;
2242 : :
2243 : 3122 : msg = curl_multi_info_read(curlm, &num_msg);
2244 [ + - + - ]: 3122 : if (msg != NULL && msg->msg == CURLMSG_DONE)
2245 : : {
2246 [ + + ]: 3122 : if (vfd >= 0)
2247 : : {
2248 : 2272 : bool pnl = (c->default_progressfn_printed_p
2249 [ - + - - ]: 1136 : && vfd == STDERR_FILENO);
2250 [ + - ]: 1136 : dprintf (vfd, "%sserver response %s\n", pnl ? "\n" : "",
2251 : : curl_easy_strerror (msg->data.result));
2252 [ - + ]: 1136 : if (pnl)
2253 : 0 : c->default_progressfn_printed_p = 0;
2254 [ + - ]: 1138 : for (int i = 0; i < num_urls; i++)
2255 [ + + ]: 1138 : if (msg->easy_handle == data[i].handle)
2256 : : {
2257 [ + + ]: 1136 : if (strlen (data[i].errbuf) > 0)
2258 : 32 : dprintf (vfd, "url %d %s\n", i, data[i].errbuf);
2259 : : break;
2260 : : }
2261 : : }
2262 : :
2263 [ + + ]: 3122 : if (msg->data.result != CURLE_OK)
2264 : : {
2265 : 1662 : long resp_code;
2266 : 1662 : CURLcode ok0;
2267 : : /* Unsuccessful query, determine error code. */
2268 [ - + - - : 1662 : switch (msg->data.result)
- - - - +
+ - ]
2269 : : {
2270 : : case CURLE_COULDNT_RESOLVE_HOST: rc = -EHOSTUNREACH; break; // no NXDOMAIN
2271 : 0 : case CURLE_URL_MALFORMAT: rc = -EINVAL; break;
2272 : 1620 : case CURLE_COULDNT_CONNECT: rc = -ECONNREFUSED; break;
2273 : 1620 : case CURLE_PEER_FAILED_VERIFICATION: rc = -ECONNREFUSED; break;
2274 : 0 : case CURLE_REMOTE_ACCESS_DENIED: rc = -EACCES; break;
2275 : 0 : case CURLE_WRITE_ERROR: rc = -EIO; break;
2276 : 0 : case CURLE_OUT_OF_MEMORY: rc = -ENOMEM; break;
2277 : 0 : case CURLE_TOO_MANY_REDIRECTS: rc = -EMLINK; break;
2278 : 0 : case CURLE_SEND_ERROR: rc = -ECONNRESET; break;
2279 : 0 : case CURLE_RECV_ERROR: rc = -ECONNRESET; break;
2280 : 0 : case CURLE_OPERATION_TIMEDOUT: rc = -ETIME; break;
2281 : : case CURLE_HTTP_RETURNED_ERROR:
2282 : 40 : ok0 = curl_easy_getinfo (msg->easy_handle,
2283 : : CURLINFO_RESPONSE_CODE,
2284 : : &resp_code);
2285 : : /* 406 signals that the requested file was too large */
2286 [ + - + + ]: 40 : if ( ok0 == CURLE_OK && resp_code == 406)
2287 : : rc = -EFBIG;
2288 [ - + - - ]: 38 : else if (section != NULL && resp_code == 503)
2289 : : rc = -EINVAL;
2290 : : else
2291 : 40 : rc = -ENOENT;
2292 : : break;
2293 : 40 : default: rc = -ENOENT; break;
2294 : : }
2295 : : }
2296 : : else
2297 : : {
2298 : : /* Query completed without an error. Confirm that the
2299 : : response code is 200 when using HTTP/HTTPS and 0 when
2300 : : using file:// and set verified_handle. */
2301 : :
2302 [ + - ]: 1460 : if (msg->easy_handle != NULL)
2303 : : {
2304 : 1460 : char *effective_url = NULL;
2305 : 1460 : long resp_code = 500;
2306 : 1460 : CURLcode ok1 = curl_easy_getinfo (target_handle,
2307 : : CURLINFO_EFFECTIVE_URL,
2308 : : &effective_url);
2309 : 1460 : CURLcode ok2 = curl_easy_getinfo (target_handle,
2310 : : CURLINFO_RESPONSE_CODE,
2311 : : &resp_code);
2312 [ + - + - ]: 1460 : if(ok1 == CURLE_OK && ok2 == CURLE_OK && effective_url)
2313 : : {
2314 [ + + ]: 1460 : if (strncasecmp (effective_url, "HTTP", 4) == 0)
2315 [ + - ]: 1458 : if (resp_code == 200)
2316 : : {
2317 : 1458 : verified_handle = msg->easy_handle;
2318 : 1460 : break;
2319 : : }
2320 [ + - ]: 2 : if (strncasecmp (effective_url, "FILE", 4) == 0)
2321 [ + - ]: 2 : if (resp_code == 0)
2322 : : {
2323 : 2 : verified_handle = msg->easy_handle;
2324 : 2 : break;
2325 : : }
2326 : : }
2327 : : /* - libcurl since 7.52.0 version start to support
2328 : : CURLINFO_SCHEME;
2329 : : - before 7.61.0, effective_url would give us a
2330 : : url with upper case SCHEME added in the front;
2331 : : - effective_url between 7.61 and 7.69 can be lack
2332 : : of scheme if the original url doesn't include one;
2333 : : - since version 7.69 effective_url will be provide
2334 : : a scheme in lower case. */
2335 : : #if LIBCURL_VERSION_NUM >= 0x073d00 /* 7.61.0 */
2336 : : #if LIBCURL_VERSION_NUM <= 0x074500 /* 7.69.0 */
2337 : : char *scheme = NULL;
2338 : : CURLcode ok3 = curl_easy_getinfo (target_handle,
2339 : : CURLINFO_SCHEME,
2340 : : &scheme);
2341 : : if(ok3 == CURLE_OK && scheme)
2342 : : {
2343 : : if (startswith (scheme, "HTTP"))
2344 : : if (resp_code == 200)
2345 : : {
2346 : : verified_handle = msg->easy_handle;
2347 : : break;
2348 : : }
2349 : : }
2350 : : #endif
2351 : : #endif
2352 : : }
2353 : : }
2354 : : }
2355 [ + + ]: 1662 : } while (num_msg > 0);
2356 : :
2357 : : /* Create an empty file in the cache if the query fails with ENOENT and
2358 : : it wasn't cancelled early. */
2359 [ + + + - ]: 3120 : if (rc == -ENOENT && !c->progressfn_cancel)
2360 : : {
2361 : 1500 : int efd = open (target_cache_path, O_CREAT|O_EXCL, DEFFILEMODE);
2362 [ + + ]: 1500 : if (efd >= 0)
2363 : 1498 : close(efd);
2364 : : }
2365 [ + + ]: 1620 : else if (rc == -EFBIG)
2366 : 2 : goto out2;
2367 : :
2368 : : /* If the verified_handle is NULL and rc != -ENOENT, the query fails with
2369 : : * an error code other than 404, then do several retry within the retry_limit.
2370 : : * Clean up all old handles and jump back to the beginning of query_in_parallel,
2371 : : * reinitialize handles and query again.*/
2372 [ + + ]: 3118 : if (verified_handle == NULL)
2373 : : {
2374 [ + + + + ]: 1658 : if (rc != -ENOENT && retry_limit-- > 0)
2375 : : {
2376 [ + + ]: 1084 : if (vfd >= 0)
2377 : 20 : dprintf (vfd, "Retry failed query, %d attempt(s) remaining\n", retry_limit);
2378 : : /* remove all handles from multi */
2379 [ + + ]: 2168 : for (int i = 0; i < num_urls; i++)
2380 : : {
2381 : 1084 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2382 : 1084 : curl_easy_cleanup (data[i].handle);
2383 : 1084 : free(data[i].response_data);
2384 : 1084 : data[i].response_data = NULL;
2385 : : }
2386 : 1084 : free(c->winning_headers);
2387 : 1084 : c->winning_headers = NULL;
2388 : 1084 : goto query_in_parallel;
2389 : : }
2390 : : else
2391 : 574 : goto out2;
2392 : : }
2393 : :
2394 [ + + ]: 1460 : if (vfd >= 0)
2395 : : {
2396 [ - + - - ]: 2208 : bool pnl = c->default_progressfn_printed_p && vfd == STDERR_FILENO;
2397 : 1104 : dprintf (vfd, "%sgot file from server\n", pnl ? "\n" : "");
2398 [ - + ]: 1104 : if (pnl)
2399 : 0 : c->default_progressfn_printed_p = 0;
2400 : : }
2401 : :
2402 : : /* we've got one!!!! */
2403 : 1460 : time_t mtime;
2404 : : #if defined(_TIME_BITS) && _TIME_BITS == 64
2405 : : CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME_T, (void*) &mtime);
2406 : : #else
2407 : 1460 : CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME, (void*) &mtime);
2408 : : #endif
2409 [ + - ]: 1460 : if (curl_res == CURLE_OK)
2410 : : {
2411 : 1460 : struct timespec tvs[2];
2412 : 1460 : tvs[0].tv_sec = 0;
2413 : 1460 : tvs[0].tv_nsec = UTIME_OMIT;
2414 : 1460 : tvs[1].tv_sec = mtime;
2415 : 1460 : tvs[1].tv_nsec = 0;
2416 : 1460 : (void) futimens (fd, tvs); /* best effort */
2417 : : }
2418 : :
2419 : : /* PR27571: make cache files casually unwriteable; dirs are already 0700 */
2420 : 1460 : (void) fchmod(fd, 0400);
2421 : : /* PR31248: lseek back to beginning */
2422 : 1460 : (void) lseek(fd, 0, SEEK_SET);
2423 : :
2424 [ + - - + ]: 1460 : if(NULL != url_ima_policies && ignore != url_ima_policies[committed_to])
2425 : : {
2426 : : #ifdef ENABLE_IMA_VERIFICATION
2427 : : int result = debuginfod_validate_imasig(c, fd);
2428 : : #else
2429 : 0 : int result = -ENOSYS;
2430 : : #endif
2431 : 0 : if(0 == result)
2432 : : {
2433 : : if (vfd >= 0) dprintf (vfd, "valid signature\n");
2434 : : }
2435 [ # # ]: 0 : else if (enforcing == url_ima_policies[committed_to])
2436 : : {
2437 : : // All invalid signatures are rejected.
2438 : : // Additionally in enforcing mode any non-valid signature is rejected, so by reaching
2439 : : // this case we do so since we know it is not valid. Note - this not just invalid signatures
2440 : : // but also signatures that cannot be validated
2441 [ # # ]: 0 : if (vfd >= 0) dprintf (vfd, "error: invalid or missing signature (%d)\n", result);
2442 : 0 : rc = result;
2443 : 0 : goto out2;
2444 : : }
2445 : : }
2446 : :
2447 : : /* rename tmp->real */
2448 : 1460 : rc = rename (target_cache_tmppath, target_cache_path);
2449 [ - + ]: 1460 : if (rc < 0)
2450 : : {
2451 : 0 : rc = -errno;
2452 : 0 : goto out2;
2453 : : /* Perhaps we need not give up right away; could retry or something ... */
2454 : : }
2455 : :
2456 : : /* write out the headers, best effort basis */
2457 [ + + ]: 1460 : if (c->winning_headers) {
2458 : 1458 : int fdh = mkstemp (target_cachehdr_tmppath);
2459 [ + - ]: 1458 : if (fdh >= 0) {
2460 : 1458 : size_t bytes_to_write = strlen(c->winning_headers)+1; // include \0
2461 : 1458 : size_t bytes = pwrite_retry (fdh, c->winning_headers, bytes_to_write, 0);
2462 : 1458 : (void) close (fdh);
2463 [ + - ]: 1458 : if (bytes == bytes_to_write)
2464 : 1458 : (void) rename (target_cachehdr_tmppath, target_cachehdr_path);
2465 : : else
2466 : 0 : (void) unlink (target_cachehdr_tmppath);
2467 [ + + ]: 1458 : if (vfd >= 0)
2468 : 1104 : dprintf (vfd, "saved %ld bytes of headers to %s\n", (long)bytes, target_cachehdr_path);
2469 : : }
2470 : : }
2471 : :
2472 : : /* remove all handles from multi */
2473 [ + + ]: 2968 : for (int i = 0; i < num_urls; i++)
2474 : : {
2475 : 1508 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2476 : 1508 : curl_easy_cleanup (data[i].handle);
2477 : 1508 : free (data[i].response_data);
2478 : : }
2479 : :
2480 [ + + ]: 2968 : for (int i = 0; i < num_urls; ++i)
2481 : 1508 : free(server_url_list[i]);
2482 : 1460 : free(server_url_list);
2483 : 1460 : free(url_ima_policies);
2484 : 1460 : free (data);
2485 : 1460 : free (server_urls);
2486 : :
2487 : : /* don't close fd - we're returning it */
2488 : : /* don't unlink the tmppath; it's already been renamed. */
2489 [ + + ]: 1460 : if (path != NULL)
2490 : 374 : *path = strdup(target_cache_path);
2491 : :
2492 : 1460 : rc = fd;
2493 : 1460 : goto out;
2494 : :
2495 : : /* error exits */
2496 : 576 : out2:
2497 : : /* remove all handles from multi */
2498 [ + + ]: 1154 : for (int i = 0; i < num_urls; i++)
2499 : : {
2500 [ + - ]: 578 : if (data[i].handle != NULL)
2501 : : {
2502 : 578 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2503 : 578 : curl_easy_cleanup (data[i].handle);
2504 : 578 : free (data[i].response_data);
2505 : : }
2506 : : }
2507 : :
2508 : 576 : unlink (target_cache_tmppath);
2509 : 576 : close (fd); /* before the rmdir, otherwise it'll fail */
2510 : 576 : (void) rmdir (target_cache_dir); /* nop if not empty */
2511 : 576 : free(data);
2512 : :
2513 : 576 : out1:
2514 [ + + ]: 1154 : for (int i = 0; i < num_urls; ++i)
2515 : 578 : free(server_url_list[i]);
2516 : 576 : free(server_url_list);
2517 : 576 : free(url_ima_policies);
2518 : :
2519 : 576 : out0:
2520 : 576 : free (server_urls);
2521 : :
2522 : : /* general purpose exit */
2523 : 6518 : out:
2524 : : /* Reset sent headers */
2525 : 6518 : curl_slist_free_all (c->headers);
2526 : 6518 : c->headers = NULL;
2527 : 6518 : c->user_agent_set_p = 0;
2528 : :
2529 : : /* Conclude the last \r status line */
2530 : : /* Another possibility is to use the ANSI CSI n K EL "Erase in Line"
2531 : : code. That way, the previously printed messages would be erased,
2532 : : and without a newline. */
2533 [ + + ]: 6518 : if (c->default_progressfn_printed_p)
2534 : 2 : dprintf(STDERR_FILENO, "\n");
2535 : :
2536 [ + + ]: 6518 : if (vfd >= 0)
2537 : : {
2538 [ + + ]: 1124 : if (rc < 0)
2539 : 10 : dprintf (vfd, "not found %s (err=%d)\n", strerror (-rc), rc);
2540 : : else
2541 : 1114 : dprintf (vfd, "found %s (fd=%d)\n", target_cache_path, rc);
2542 : : }
2543 : :
2544 : 6518 : free (cache_path);
2545 : 6518 : free (maxage_path);
2546 : 6518 : free (interval_path);
2547 : 6518 : free (cache_miss_path);
2548 : 6518 : free (target_cache_dir);
2549 : 6518 : free (target_cache_path);
2550 [ + + + + ]: 6518 : if (rc < 0 && target_cache_tmppath != NULL)
2551 : 578 : (void)unlink (target_cache_tmppath);
2552 : 6518 : free (target_cache_tmppath);
2553 [ + + + + ]: 6518 : if (rc < 0 && target_cachehdr_tmppath != NULL)
2554 : 578 : (void)unlink (target_cachehdr_tmppath);
2555 : 6518 : free (target_cachehdr_tmppath);
2556 : 6518 : free (target_cachehdr_path);
2557 : :
2558 : 6518 : return rc;
2559 : : }
2560 : :
2561 : :
2562 : :
2563 : : /* See debuginfod.h */
2564 : : debuginfod_client *
2565 : 528 : debuginfod_begin (void)
2566 : : {
2567 : : /* Initialize libcurl lazily, but only once. */
2568 : 528 : pthread_once (&init_control, libcurl_init);
2569 : :
2570 : 528 : debuginfod_client *client;
2571 : 528 : size_t size = sizeof (struct debuginfod_client);
2572 : 528 : client = calloc (1, size);
2573 : :
2574 [ + - ]: 528 : if (client != NULL)
2575 : : {
2576 [ + + ]: 528 : if (getenv(DEBUGINFOD_PROGRESS_ENV_VAR))
2577 : 4 : client->progressfn = debuginfod_default_progressfn;
2578 [ + + ]: 528 : if (getenv(DEBUGINFOD_VERBOSE_ENV_VAR))
2579 : 6 : client->verbose_fd = STDERR_FILENO;
2580 : : else
2581 : 522 : client->verbose_fd = -1;
2582 : :
2583 : : // allocate 1 curl multi handle
2584 : 528 : client->server_mhandle = curl_multi_init ();
2585 [ - + ]: 528 : if (client->server_mhandle == NULL)
2586 : 0 : goto out1;
2587 : : }
2588 : :
2589 : : #ifdef ENABLE_IMA_VERIFICATION
2590 : : load_ima_public_keys (client);
2591 : : #endif
2592 : :
2593 : : // extra future initialization
2594 : :
2595 : 528 : goto out;
2596 : :
2597 : 0 : out1:
2598 : 0 : free (client);
2599 : 0 : client = NULL;
2600 : :
2601 : 528 : out:
2602 : 528 : return client;
2603 : : }
2604 : :
2605 : : void
2606 : 486 : debuginfod_set_user_data(debuginfod_client *client,
2607 : : void *data)
2608 : : {
2609 : 486 : client->user_data = data;
2610 : 486 : }
2611 : :
2612 : : void *
2613 : 0 : debuginfod_get_user_data(debuginfod_client *client)
2614 : : {
2615 : 0 : return client->user_data;
2616 : : }
2617 : :
2618 : : const char *
2619 : 46 : debuginfod_get_url(debuginfod_client *client)
2620 : : {
2621 [ + - ]: 2 : return client->url;
2622 : : }
2623 : :
2624 : : const char *
2625 : 48 : debuginfod_get_headers(debuginfod_client *client)
2626 : : {
2627 : 48 : return client->winning_headers;
2628 : : }
2629 : :
2630 : : void
2631 : 526 : debuginfod_end (debuginfod_client *client)
2632 : : {
2633 [ + - ]: 526 : if (client == NULL)
2634 : : return;
2635 : :
2636 : 526 : curl_multi_cleanup (client->server_mhandle);
2637 : 526 : curl_slist_free_all (client->headers);
2638 : 526 : free (client->winning_headers);
2639 : 526 : free (client->url);
2640 : : #ifdef ENABLE_IMA_VERIFICATION
2641 : : free_ima_public_keys (client);
2642 : : #endif
2643 : 526 : free (client);
2644 : : }
2645 : :
2646 : : int
2647 : 300 : debuginfod_find_debuginfo (debuginfod_client *client,
2648 : : const unsigned char *build_id, int build_id_len,
2649 : : char **path)
2650 : : {
2651 : 300 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2652 : : "debuginfo", NULL, path);
2653 : : }
2654 : :
2655 : :
2656 : : /* See debuginfod.h */
2657 : : int
2658 : 736 : debuginfod_find_executable(debuginfod_client *client,
2659 : : const unsigned char *build_id, int build_id_len,
2660 : : char **path)
2661 : : {
2662 : 736 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2663 : : "executable", NULL, path);
2664 : : }
2665 : :
2666 : : /* See debuginfod.h */
2667 : 5466 : int debuginfod_find_source(debuginfod_client *client,
2668 : : const unsigned char *build_id, int build_id_len,
2669 : : const char *filename, char **path)
2670 : : {
2671 : 5466 : return debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2672 : : "source", filename, path);
2673 : : }
2674 : :
2675 : : int
2676 : 16 : debuginfod_find_section (debuginfod_client *client,
2677 : : const unsigned char *build_id, int build_id_len,
2678 : : const char *section, char **path)
2679 : : {
2680 : 16 : int rc = debuginfod_query_server_by_buildid(client, build_id, build_id_len,
2681 : : "section", section, path);
2682 [ - + ]: 16 : if (rc != -EINVAL && rc != -ENOSYS)
2683 : : return rc;
2684 : : /* NB: we fall through in case of ima:enforcing-filtered DEBUGINFOD_URLS servers,
2685 : : so we can download the entire file, verify it locally, then slice it. */
2686 : :
2687 : : /* The servers may have lacked support for section queries. Attempt to
2688 : : download the debuginfo or executable containing the section in order
2689 : : to extract it. */
2690 : 0 : rc = -EEXIST;
2691 : 0 : int fd = -1;
2692 : 0 : char *tmp_path = NULL;
2693 : :
2694 : 0 : fd = debuginfod_find_debuginfo (client, build_id, build_id_len, &tmp_path);
2695 [ # # ]: 0 : if (client->progressfn_cancel)
2696 : : {
2697 [ # # ]: 0 : if (fd >= 0)
2698 : : {
2699 : : /* This shouldn't happen, but we'll check this condition
2700 : : just in case. */
2701 : 0 : close (fd);
2702 : 0 : free (tmp_path);
2703 : : }
2704 : 0 : return -ENOENT;
2705 : : }
2706 [ # # ]: 0 : if (fd >= 0)
2707 : : {
2708 : 0 : rc = extract_section (fd, section, tmp_path, path);
2709 : 0 : close (fd);
2710 : : }
2711 : :
2712 [ # # ]: 0 : if (rc == -EEXIST)
2713 : : {
2714 : : /* Either the debuginfo couldn't be found or the section should
2715 : : be in the executable. */
2716 : 0 : fd = debuginfod_find_executable (client, build_id,
2717 : : build_id_len, &tmp_path);
2718 [ # # ]: 0 : if (fd >= 0)
2719 : : {
2720 : 0 : rc = extract_section (fd, section, tmp_path, path);
2721 : 0 : close (fd);
2722 : : }
2723 : : else
2724 : : /* Update rc so that we return the most recent error code. */
2725 : : rc = fd;
2726 : : }
2727 : :
2728 : 0 : free (tmp_path);
2729 : 0 : return rc;
2730 : : }
2731 : :
2732 : :
2733 : 52 : int debuginfod_find_metadata (debuginfod_client *client,
2734 : : const char* key, const char* value, char **path)
2735 : : {
2736 : 52 : char *server_urls = NULL;
2737 : 52 : char *urls_envvar = NULL;
2738 : 52 : char *cache_path = NULL;
2739 : 52 : char *target_cache_dir = NULL;
2740 : 52 : char *target_cache_path = NULL;
2741 : 52 : char *target_cache_tmppath = NULL;
2742 : 52 : char *target_file_name = NULL;
2743 : 52 : char *key_and_value = NULL;
2744 : 52 : int rc = 0, r;
2745 : 52 : int vfd = client->verbose_fd;
2746 : 52 : struct handle_data *data = NULL;
2747 : :
2748 : 52 : client->progressfn_cancel = false;
2749 : :
2750 : 52 : json_object *json_metadata = json_object_new_object();
2751 : 52 : json_bool json_metadata_complete = true;
2752 : 52 : json_object *json_metadata_arr = json_object_new_array();
2753 [ - + ]: 52 : if (NULL == json_metadata)
2754 : : {
2755 : 0 : rc = -ENOMEM;
2756 : 0 : goto out;
2757 : : }
2758 [ - + ]: 52 : json_object_object_add(json_metadata, "results",
2759 : 0 : json_metadata_arr ?: json_object_new_array() /* Empty array */);
2760 : :
2761 [ - + ]: 52 : if (NULL == value || NULL == key)
2762 : : {
2763 : 0 : rc = -EINVAL;
2764 : 0 : goto out;
2765 : : }
2766 : :
2767 [ - + ]: 52 : if (vfd >= 0)
2768 : 0 : dprintf (vfd, "debuginfod_find_metadata %s %s\n", key, value);
2769 : :
2770 : : /* Without query-able URL, we can stop here*/
2771 : 52 : urls_envvar = getenv(DEBUGINFOD_URLS_ENV_VAR);
2772 [ - + ]: 52 : if (vfd >= 0)
2773 [ # # ]: 0 : dprintf (vfd, "server urls \"%s\"\n",
2774 : : urls_envvar != NULL ? urls_envvar : "");
2775 [ + - + + ]: 52 : if (urls_envvar == NULL || urls_envvar[0] == '\0')
2776 : : {
2777 : 18 : rc = -ENOSYS;
2778 : 18 : goto out;
2779 : : }
2780 : :
2781 : : /* set paths needed to perform the query
2782 : : example format:
2783 : : cache_path: $HOME/.cache
2784 : : target_cache_dir: $HOME/.cache/metadata
2785 : : target_cache_path: $HOME/.cache/metadata/KEYENCODED_VALUEENCODED
2786 : : target_cache_path: $HOME/.cache/metadata/KEYENCODED_VALUEENCODED.XXXXXX
2787 : : */
2788 : :
2789 : : // libcurl > 7.62ish has curl_url_set()/etc. to construct these things more properly.
2790 : : // curl_easy_escape() is older
2791 : : {
2792 : 34 : CURL *c = curl_easy_init();
2793 [ - + ]: 34 : if (!c)
2794 : : {
2795 : 0 : rc = -ENOMEM;
2796 : 0 : goto out;
2797 : : }
2798 : 34 : char *key_escaped = curl_easy_escape(c, key, 0);
2799 : 34 : char *value_escaped = curl_easy_escape(c, value, 0);
2800 : :
2801 : : // fallback to unescaped values in unlikely case of error
2802 [ - + - + : 68 : xalloc_str (key_and_value, "key=%s&value=%s", key_escaped ?: key, value_escaped ?: value);
- + ]
2803 [ - + ]: 34 : xalloc_str (target_file_name, "%s_%s", key_escaped ?: key, value_escaped ?: value);
2804 : 34 : curl_free(value_escaped);
2805 : 34 : curl_free(key_escaped);
2806 : 34 : curl_easy_cleanup(c);
2807 : : }
2808 : :
2809 : : /* Check if we have a recent result already in the cache. */
2810 : 34 : cache_path = make_cache_path();
2811 [ - + ]: 34 : if (! cache_path)
2812 : : {
2813 : 0 : rc = -ENOMEM;
2814 : 0 : goto out;
2815 : : }
2816 [ - + ]: 34 : xalloc_str (target_cache_dir, "%s/metadata", cache_path);
2817 : 34 : (void) mkdir (target_cache_dir, 0700);
2818 [ - + ]: 34 : xalloc_str (target_cache_path, "%s/%s", target_cache_dir, target_file_name);
2819 [ - + ]: 34 : xalloc_str (target_cache_tmppath, "%s/%s.XXXXXX", target_cache_dir, target_file_name);
2820 : :
2821 : 34 : int fd = open(target_cache_path, O_RDONLY);
2822 [ + + ]: 34 : if (fd >= 0)
2823 : : {
2824 : 12 : struct stat st;
2825 : 12 : int metadata_retention = 0;
2826 : 12 : time_t now = time(NULL);
2827 : 12 : char *metadata_retention_path = 0;
2828 : :
2829 [ - + ]: 22 : xalloc_str (metadata_retention_path, "%s/%s", cache_path, metadata_retention_filename);
2830 [ + - ]: 12 : if (metadata_retention_path)
2831 : : {
2832 : 12 : rc = debuginfod_config_cache(client, metadata_retention_path,
2833 : : metadata_retention_default_s, &st);
2834 : 12 : free (metadata_retention_path);
2835 [ - + ]: 12 : if (rc < 0)
2836 : 0 : rc = 0;
2837 : : }
2838 : : else
2839 : : rc = 0;
2840 : 12 : metadata_retention = rc;
2841 : :
2842 [ - + ]: 12 : if (fstat(fd, &st) != 0)
2843 : : {
2844 : 0 : rc = -errno;
2845 : 0 : close (fd);
2846 : 0 : goto out;
2847 : : }
2848 : :
2849 [ + + + - ]: 12 : if (metadata_retention > 0 && (now - st.st_mtime <= metadata_retention))
2850 : : {
2851 [ - + ]: 10 : if (client && client->verbose_fd >= 0)
2852 : 0 : dprintf (client->verbose_fd, "cached metadata %s", target_file_name);
2853 : :
2854 [ + - ]: 10 : if (path != NULL)
2855 : : {
2856 : 10 : *path = target_cache_path; // pass over the pointer
2857 : 10 : target_cache_path = NULL; // prevent free() in our own cleanup
2858 : : }
2859 : :
2860 : : /* Success!!!! */
2861 : 10 : rc = fd;
2862 : 10 : goto out;
2863 : : }
2864 : :
2865 : : /* We don't have to clear the likely-expired cached object here
2866 : : by unlinking. We will shortly make a new request and save
2867 : : results right on top. Erasing here could trigger a TOCTOU
2868 : : race with another thread just finishing a query and passing
2869 : : its results back.
2870 : : */
2871 : : // (void) unlink (target_cache_path);
2872 : :
2873 : 2 : close (fd);
2874 : : }
2875 : :
2876 : : /* No valid cached metadata found: time to make the queries. */
2877 : :
2878 : 24 : free (client->url);
2879 : 24 : client->url = NULL;
2880 : :
2881 : 24 : long maxtime = 0;
2882 : 24 : const char *maxtime_envvar;
2883 : 24 : maxtime_envvar = getenv(DEBUGINFOD_MAXTIME_ENV_VAR);
2884 [ - + ]: 24 : if (maxtime_envvar != NULL)
2885 : 0 : maxtime = atol (maxtime_envvar);
2886 [ - + ]: 24 : if (maxtime && vfd >= 0)
2887 : 0 : dprintf(vfd, "using max time %lds\n", maxtime);
2888 : :
2889 : 24 : long timeout = default_timeout;
2890 : 24 : const char* timeout_envvar = getenv(DEBUGINFOD_TIMEOUT_ENV_VAR);
2891 [ - + ]: 24 : if (timeout_envvar != NULL)
2892 : 0 : timeout = atoi (timeout_envvar);
2893 [ - + ]: 24 : if (vfd >= 0)
2894 : 0 : dprintf (vfd, "using timeout %ld\n", timeout);
2895 : :
2896 : 24 : add_default_headers(client);
2897 : :
2898 : : /* Make a copy of the envvar so it can be safely modified. */
2899 : 24 : server_urls = strdup(urls_envvar);
2900 [ - + ]: 24 : if (server_urls == NULL)
2901 : : {
2902 : 0 : rc = -ENOMEM;
2903 : 0 : goto out;
2904 : : }
2905 : :
2906 : : /* Thereafter, goto out1 on error*/
2907 : :
2908 : 24 : char **server_url_list = NULL;
2909 : 24 : ima_policy_t* url_ima_policies = NULL;
2910 : 24 : char *server_url;
2911 : 24 : int num_urls = 0;
2912 : 24 : r = init_server_urls("metadata", NULL, server_urls, &server_url_list, &url_ima_policies, &num_urls, vfd);
2913 [ - + ]: 24 : if (0 != r)
2914 : : {
2915 : 0 : rc = r;
2916 : 0 : goto out1;
2917 : : }
2918 : :
2919 : 24 : CURLM *curlm = client->server_mhandle;
2920 : :
2921 : 24 : CURL *target_handle = NULL;
2922 : 24 : data = malloc(sizeof(struct handle_data) * num_urls);
2923 [ - + ]: 24 : if (data == NULL)
2924 : : {
2925 : 0 : rc = -ENOMEM;
2926 : 0 : goto out1;
2927 : : }
2928 : :
2929 : : /* thereafter, goto out2 on error. */
2930 : :
2931 : : /* Initialize handle_data */
2932 [ + + ]: 60 : for (int i = 0; i < num_urls; i++)
2933 : : {
2934 [ + - ]: 36 : if ((server_url = server_url_list[i]) == NULL)
2935 : : break;
2936 [ - + ]: 36 : if (vfd >= 0)
2937 : 0 : dprintf (vfd, "init server %d %s\n", i, server_url);
2938 : :
2939 : 36 : data[i].errbuf[0] = '\0';
2940 : 36 : data[i].target_handle = &target_handle;
2941 : 36 : data[i].client = client;
2942 : 36 : data[i].metadata = NULL;
2943 : 36 : data[i].metadata_size = 0;
2944 : 36 : data[i].response_data = NULL;
2945 : 36 : data[i].response_data_size = 0;
2946 : :
2947 : 36 : snprintf(data[i].url, PATH_MAX, "%s?%s", server_url, key_and_value);
2948 : :
2949 : 36 : r = init_handle(client, metadata_callback, header_callback, &data[i], i, timeout, vfd);
2950 [ - + ]: 36 : if (0 != r)
2951 : : {
2952 : 0 : rc = r;
2953 : 0 : goto out2;
2954 : : }
2955 : 36 : curl_multi_add_handle(curlm, data[i].handle);
2956 : : }
2957 : :
2958 : : /* Query servers */
2959 [ - + ]: 24 : if (vfd >= 0)
2960 : 0 : dprintf (vfd, "Starting %d queries\n",num_urls);
2961 : 24 : int committed_to;
2962 : 24 : r = perform_queries(curlm, NULL, data, client, num_urls, maxtime, 0, false, vfd, &committed_to);
2963 [ - + ]: 24 : if (0 != r)
2964 : : {
2965 : 0 : rc = r;
2966 : 0 : goto out2;
2967 : : }
2968 : :
2969 : : /* NOTE: We don't check the return codes of the curl messages since
2970 : : a metadata query failing silently is just fine. We want to know what's
2971 : : available from servers which can be connected with no issues.
2972 : : If running with additional verbosity, the failure will be noted in stderr */
2973 : :
2974 : : /* Building the new json array from all the upstream data and
2975 : : cleanup while at it.
2976 : : */
2977 [ + + ]: 60 : for (int i = 0; i < num_urls; i++)
2978 : : {
2979 : 36 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
2980 : 36 : curl_easy_cleanup (data[i].handle);
2981 : 36 : free (data[i].response_data);
2982 : :
2983 [ + + ]: 36 : if (NULL == data[i].metadata)
2984 : : {
2985 [ - + ]: 16 : if (vfd >= 0)
2986 : 0 : dprintf (vfd, "Query to %s failed with error message:\n\t\"%s\"\n",
2987 : 0 : data[i].url, data[i].errbuf);
2988 : 16 : json_metadata_complete = false;
2989 : 16 : continue;
2990 : : }
2991 : :
2992 : 20 : json_object *upstream_metadata = json_tokener_parse(data[i].metadata);
2993 : 20 : json_object *upstream_complete;
2994 : 20 : json_object *upstream_metadata_arr;
2995 [ + - + - ]: 40 : if (NULL == upstream_metadata ||
2996 [ - + ]: 40 : !json_object_object_get_ex(upstream_metadata, "results", &upstream_metadata_arr) ||
2997 : 20 : !json_object_object_get_ex(upstream_metadata, "complete", &upstream_complete))
2998 : 0 : continue;
2999 : 20 : json_metadata_complete &= json_object_get_boolean(upstream_complete);
3000 : : // Combine the upstream metadata into the json array
3001 [ + + ]: 38 : for (int j = 0, n = json_object_array_length(upstream_metadata_arr); j < n; j++)
3002 : : {
3003 : 18 : json_object *entry = json_object_array_get_idx(upstream_metadata_arr, j);
3004 : 18 : json_object_get(entry); // increment reference count
3005 : 18 : json_object_array_add(json_metadata_arr, entry);
3006 : : }
3007 : 20 : json_object_put(upstream_metadata);
3008 : :
3009 : 20 : free (data[i].metadata);
3010 : : }
3011 : :
3012 : : /* Because of race with cache cleanup / rmdir, try to mkdir/mkstemp up to twice. */
3013 [ + - ]: 24 : for (int i=0; i<2; i++)
3014 : : {
3015 : : /* (re)create target directory in cache */
3016 : 24 : (void) mkdir(target_cache_dir, 0700); /* files will be 0400 later */
3017 : :
3018 : : /* NB: write to a temporary file first, to avoid race condition of
3019 : : multiple clients checking the cache, while a partially-written or empty
3020 : : file is in there, being written from libcurl. */
3021 : 24 : fd = mkstemp (target_cache_tmppath);
3022 [ - + ]: 24 : if (fd >= 0) break;
3023 : : }
3024 [ - + ]: 24 : if (fd < 0) /* Still failed after two iterations. */
3025 : : {
3026 : 0 : rc = -errno;
3027 : 0 : goto out1;
3028 : : }
3029 : :
3030 : : /* Plop the complete json_metadata object into the cache. */
3031 : 24 : json_object_object_add(json_metadata, "complete", json_object_new_boolean(json_metadata_complete));
3032 : 24 : const char* json_string = json_object_to_json_string_ext(json_metadata, JSON_C_TO_STRING_PRETTY);
3033 [ - + ]: 24 : if (json_string == NULL)
3034 : : {
3035 : 0 : rc = -ENOMEM;
3036 : 0 : goto out1;
3037 : : }
3038 : 24 : ssize_t res = write_retry (fd, json_string, strlen(json_string));
3039 : 24 : (void) lseek(fd, 0, SEEK_SET); // rewind file so client can read it from the top
3040 : :
3041 : : /* NB: json_string is auto deleted when json_metadata object is nuked */
3042 [ + - - + ]: 24 : if (res < 0 || (size_t) res != strlen(json_string))
3043 : : {
3044 : 0 : rc = -EIO;
3045 : 0 : goto out1;
3046 : : }
3047 : : /* PR27571: make cache files casually unwriteable; dirs are already 0700 */
3048 : 24 : (void) fchmod(fd, 0400);
3049 : :
3050 : : /* rename tmp->real */
3051 : 24 : rc = rename (target_cache_tmppath, target_cache_path);
3052 [ - + ]: 24 : if (rc < 0)
3053 : : {
3054 : 0 : rc = -errno;
3055 : 0 : goto out1;
3056 : : /* Perhaps we need not give up right away; could retry or something ... */
3057 : : }
3058 : :
3059 : : /* don't close fd - we're returning it */
3060 : : /* don't unlink the tmppath; it's already been renamed. */
3061 [ + - ]: 24 : if (path != NULL)
3062 : 24 : *path = strdup(target_cache_path);
3063 : :
3064 : 24 : rc = fd;
3065 : 24 : goto out1;
3066 : :
3067 : : /* error exits */
3068 : 0 : out2:
3069 : : /* remove all handles from multi */
3070 [ # # ]: 0 : for (int i = 0; i < num_urls; i++)
3071 : : {
3072 [ # # ]: 0 : if (data[i].handle != NULL)
3073 : : {
3074 : 0 : curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
3075 : 0 : curl_easy_cleanup (data[i].handle);
3076 : 0 : free (data[i].response_data);
3077 : 0 : free (data[i].metadata);
3078 : : }
3079 : : }
3080 : :
3081 : 0 : out1:
3082 : 24 : free(data);
3083 : :
3084 [ + + ]: 60 : for (int i = 0; i < num_urls; ++i)
3085 : 36 : free(server_url_list[i]);
3086 : 24 : free(server_url_list);
3087 : 24 : free(url_ima_policies);
3088 : :
3089 : 52 : out:
3090 : 52 : free (server_urls);
3091 : 52 : json_object_put(json_metadata);
3092 : : /* Reset sent headers */
3093 : 52 : curl_slist_free_all (client->headers);
3094 : 52 : client->headers = NULL;
3095 : 52 : client->user_agent_set_p = 0;
3096 : :
3097 : 52 : free (target_cache_dir);
3098 : 52 : free (target_cache_path);
3099 : 52 : free (target_cache_tmppath);
3100 : 52 : free (key_and_value);
3101 : 52 : free (target_file_name);
3102 : 52 : free (cache_path);
3103 : :
3104 : 52 : return rc;
3105 : : }
3106 : :
3107 : :
3108 : : /* Add an outgoing HTTP header. */
3109 : 2882 : int debuginfod_add_http_header (debuginfod_client *client, const char* header)
3110 : : {
3111 : : /* Sanity check header value is of the form Header: Value.
3112 : : It should contain at least one colon that isn't the first or
3113 : : last character. */
3114 : 2882 : const char *colon = strchr (header, ':'); /* first colon */
3115 : 2882 : if (colon == NULL /* present */
3116 [ + - ]: 2882 : || colon == header /* not at beginning - i.e., have a header name */
3117 [ + - ]: 2882 : || *(colon + 1) == '\0') /* not at end - i.e., have a value */
3118 : : /* NB: but it's okay for a value to contain other colons! */
3119 : : return -EINVAL;
3120 : :
3121 : 2882 : struct curl_slist *temp = curl_slist_append (client->headers, header);
3122 [ + - ]: 2882 : if (temp == NULL)
3123 : : return -ENOMEM;
3124 : :
3125 : : /* Track if User-Agent: is being set. If so, signal not to add the
3126 : : default one. */
3127 [ + + ]: 2882 : if (startswith (header, "User-Agent:"))
3128 : 2224 : client->user_agent_set_p = 1;
3129 : :
3130 : 2882 : client->headers = temp;
3131 : 2882 : return 0;
3132 : : }
3133 : :
3134 : :
3135 : : void
3136 : 1126 : debuginfod_set_progressfn(debuginfod_client *client,
3137 : : debuginfod_progressfn_t fn)
3138 : : {
3139 : 1126 : client->progressfn = fn;
3140 : 1126 : }
3141 : :
3142 : : void
3143 : 72 : debuginfod_set_verbose_fd(debuginfod_client *client, int fd)
3144 : : {
3145 : 72 : client->verbose_fd = fd;
3146 : 72 : }
3147 : :
3148 : : #endif /* DUMMY_LIBDEBUGINFOD */
|