LCOV - code coverage report
Current view: top level - debuginfod - debuginfod-client.c (source / functions) Hit Total Coverage
Test: elfutils-0.191 Lines: 928 1182 78.5 %
Date: 2024-07-24 22:43:53 Functions: 30 32 93.8 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 494 841 58.7 %

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

Generated by: LCOV version 1.16