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