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