LCOV - code coverage report
Current view: top level - debuginfod - debuginfod-client.c (source / functions) Hit Total Coverage
Test: elfutils-0.189 Lines: 715 897 79.7 %
Date: 2023-06-16 16:35:50 Functions: 24 26 92.3 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 400 663 60.3 %

           Branch data     Line data    Source code
       1                 :            : /* Retrieve ELF / DWARF / source files from the debuginfod.
       2                 :            :    Copyright (C) 2019-2021 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                 :            : /* We might be building a bootstrap dummy library, which is really simple. */
      51                 :            : #ifdef DUMMY_LIBDEBUGINFOD
      52                 :            : 
      53                 :            : debuginfod_client *debuginfod_begin (void) { errno = ENOSYS; return NULL; }
      54                 :            : int debuginfod_find_debuginfo (debuginfod_client *c, const unsigned char *b,
      55                 :            :                                int s, char **p) { return -ENOSYS; }
      56                 :            : int debuginfod_find_executable (debuginfod_client *c, const unsigned char *b,
      57                 :            :                                 int s, char **p) { return -ENOSYS; }
      58                 :            : int debuginfod_find_source (debuginfod_client *c, const unsigned char *b,
      59                 :            :                             int s, const char *f, char **p)  { return -ENOSYS; }
      60                 :            : int debuginfod_find_section (debuginfod_client *c, const unsigned char *b,
      61                 :            :                              int s, const char *scn, char **p)
      62                 :            :                               { return -ENOSYS; }
      63                 :            : void debuginfod_set_progressfn(debuginfod_client *c,
      64                 :            :                                debuginfod_progressfn_t fn) { }
      65                 :            : void debuginfod_set_verbose_fd(debuginfod_client *c, int fd) { }
      66                 :            : void debuginfod_set_user_data (debuginfod_client *c, void *d) { }
      67                 :            : void* debuginfod_get_user_data (debuginfod_client *c) { return NULL; }
      68                 :            : const char* debuginfod_get_url (debuginfod_client *c) { return NULL; }
      69                 :            : int debuginfod_add_http_header (debuginfod_client *c,
      70                 :            :                                 const char *h) { return -ENOSYS; }
      71                 :            : const char* debuginfod_get_headers (debuginfod_client *c) { return NULL; }
      72                 :            : 
      73                 :            : void debuginfod_end (debuginfod_client *c) { }
      74                 :            : 
      75                 :            : #else /* DUMMY_LIBDEBUGINFOD */
      76                 :            : 
      77                 :            : #include <assert.h>
      78                 :            : #include <dirent.h>
      79                 :            : #include <stdio.h>
      80                 :            : #include <errno.h>
      81                 :            : #include <unistd.h>
      82                 :            : #include <fcntl.h>
      83                 :            : #include <fts.h>
      84                 :            : #include <regex.h>
      85                 :            : #include <string.h>
      86                 :            : #include <stdbool.h>
      87                 :            : #include <linux/limits.h>
      88                 :            : #include <time.h>
      89                 :            : #include <utime.h>
      90                 :            : #include <sys/syscall.h>
      91                 :            : #include <sys/types.h>
      92                 :            : #include <sys/stat.h>
      93                 :            : #include <sys/utsname.h>
      94                 :            : #include <curl/curl.h>
      95                 :            : 
      96                 :            : /* If fts.h is included before config.h, its indirect inclusions may not
      97                 :            :    give us the right LFS aliases of these functions, so map them manually.  */
      98                 :            : #ifdef BAD_FTS
      99                 :            :   #ifdef _FILE_OFFSET_BITS
     100                 :            :     #define open open64
     101                 :            :     #define fopen fopen64
     102                 :            :   #endif
     103                 :            : #else
     104                 :            :   #include <sys/types.h>
     105                 :            :   #include <fts.h>
     106                 :            : #endif
     107                 :            : 
     108                 :            : /* Older curl.h don't define CURL_AT_LEAST_VERSION.  */
     109                 :            : #ifndef CURL_AT_LEAST_VERSION
     110                 :            :   #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
     111                 :            :   #define CURL_AT_LEAST_VERSION(x,y,z) \
     112                 :            :     (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
     113                 :            : #endif
     114                 :            : 
     115                 :            : #include <pthread.h>
     116                 :            : 
     117                 :            : static pthread_once_t init_control = PTHREAD_ONCE_INIT;
     118                 :            : 
     119                 :            : static void
     120                 :        187 : libcurl_init(void)
     121                 :            : {
     122                 :        187 :   curl_global_init(CURL_GLOBAL_DEFAULT);
     123                 :        187 : }
     124                 :            : 
     125                 :            : struct debuginfod_client
     126                 :            : {
     127                 :            :   /* Progress/interrupt callback function. */
     128                 :            :   debuginfod_progressfn_t progressfn;
     129                 :            : 
     130                 :            :   /* Stores user data. */
     131                 :            :   void* user_data;
     132                 :            : 
     133                 :            :   /* Stores current/last url, if any. */
     134                 :            :   char* url;
     135                 :            : 
     136                 :            :   /* Accumulates outgoing http header names/values. */
     137                 :            :   int user_agent_set_p; /* affects add_default_headers */
     138                 :            :   struct curl_slist *headers;
     139                 :            : 
     140                 :            :   /* Flags the default_progressfn having printed something that
     141                 :            :      debuginfod_end needs to terminate. */
     142                 :            :   int default_progressfn_printed_p;
     143                 :            : 
     144                 :            :   /* Indicates whether the last query was cancelled by progressfn.  */
     145                 :            :   bool progressfn_cancel;
     146                 :            : 
     147                 :            :   /* File descriptor to output any verbose messages if > 0.  */
     148                 :            :   int verbose_fd;
     149                 :            : 
     150                 :            :   /* Maintain a long-lived curl multi-handle, which keeps a
     151                 :            :      connection/tls/dns cache to recently seen servers. */
     152                 :            :   CURLM *server_mhandle;
     153                 :            :   
     154                 :            :   /* Can contain all other context, like cache_path, server_urls,
     155                 :            :      timeout or other info gotten from environment variables, the
     156                 :            :      handle data, etc. So those don't have to be reparsed and
     157                 :            :      recreated on each request.  */
     158                 :            :   char * winning_headers;
     159                 :            : };
     160                 :            : 
     161                 :            : /* The cache_clean_interval_s file within the debuginfod cache specifies
     162                 :            :    how frequently the cache should be cleaned. The file's st_mtime represents
     163                 :            :    the time of last cleaning.  */
     164                 :            : static const char *cache_clean_interval_filename = "cache_clean_interval_s";
     165                 :            : static const long cache_clean_default_interval_s = 86400; /* 1 day */
     166                 :            : 
     167                 :            : /* The cache_miss_default_s within the debuginfod cache specifies how
     168                 :            :    frequently the empty file should be released.*/
     169                 :            : static const long cache_miss_default_s = 600; /* 10 min */
     170                 :            : static const char *cache_miss_filename = "cache_miss_s";
     171                 :            : 
     172                 :            : /* The cache_max_unused_age_s file within the debuginfod cache specifies the
     173                 :            :    the maximum time since last access that a file will remain in the cache.  */
     174                 :            : static const char *cache_max_unused_age_filename = "max_unused_age_s";
     175                 :            : static const long cache_default_max_unused_age_s = 604800; /* 1 week */
     176                 :            : 
     177                 :            : /* Location of the cache of files downloaded from debuginfods.
     178                 :            :    The default parent directory is $HOME, or '/' if $HOME doesn't exist.  */
     179                 :            : static const char *cache_default_name = ".debuginfod_client_cache";
     180                 :            : static const char *cache_xdg_name = "debuginfod_client";
     181                 :            : 
     182                 :            : /* URLs of debuginfods, separated by url_delim. */
     183                 :            : static const char *url_delim =  " ";
     184                 :            : 
     185                 :            : /* Timeout for debuginfods, in seconds (to get at least 100K). */
     186                 :            : static const long default_timeout = 90;
     187                 :            : 
     188                 :            : /* Default retry count for download error. */
     189                 :            : static const long default_retry_limit = 2;
     190                 :            : 
     191                 :            : /* Data associated with a particular CURL easy handle. Passed to
     192                 :            :    the write callback.  */
     193                 :            : struct handle_data
     194                 :            : {
     195                 :            :   /* Cache file to be written to in case query is successful.  */
     196                 :            :   int fd;
     197                 :            : 
     198                 :            :   /* URL queried by this handle.  */
     199                 :            :   char url[PATH_MAX];
     200                 :            : 
     201                 :            :   /* error buffer for this handle.  */
     202                 :            :   char errbuf[CURL_ERROR_SIZE];
     203                 :            : 
     204                 :            :   /* This handle.  */
     205                 :            :   CURL *handle;
     206                 :            : 
     207                 :            :   /* The client object whom we're serving. */
     208                 :            :   debuginfod_client *client;
     209                 :            : 
     210                 :            :   /* Pointer to handle that should write to fd. Initially points to NULL,
     211                 :            :      then points to the first handle that begins writing the target file
     212                 :            :      to the cache. Used to ensure that a file is not downloaded from
     213                 :            :      multiple servers unnecessarily.  */
     214                 :            :   CURL **target_handle;
     215                 :            :   /* Response http headers for this client handle, sent from the server */
     216                 :            :   char *response_data;
     217                 :            :   size_t response_data_size;
     218                 :            : };
     219                 :            : 
     220                 :            : static size_t
     221                 :       3415 : debuginfod_write_callback (char *ptr, size_t size, size_t nmemb, void *data)
     222                 :            : {
     223                 :       3415 :   ssize_t count = size * nmemb;
     224                 :            : 
     225                 :       3415 :   struct handle_data *d = (struct handle_data*)data;
     226                 :            : 
     227                 :            :   /* Indicate to other handles that they can abort their transfer.  */
     228         [ +  + ]:       3415 :   if (*d->target_handle == NULL)
     229                 :            :     {
     230                 :        121 :       *d->target_handle = d->handle;
     231                 :            :       /* update the client object */
     232                 :        121 :       const char *url = NULL;
     233                 :        121 :       CURLcode curl_res = curl_easy_getinfo (d->handle,
     234                 :            :                                              CURLINFO_EFFECTIVE_URL, &url);
     235   [ +  -  +  - ]:        121 :       if (curl_res == CURLE_OK && url)
     236                 :            :         {
     237                 :        121 :           free (d->client->url);
     238                 :        121 :           d->client->url = strdup(url); /* ok if fails */
     239                 :            :         }
     240                 :            :     }
     241                 :            : 
     242                 :            :   /* If this handle isn't the target handle, abort transfer.  */
     243         [ +  - ]:       3415 :   if (*d->target_handle != d->handle)
     244                 :            :     return -1;
     245                 :            : 
     246                 :       3415 :   return (size_t) write(d->fd, (void*)ptr, count);
     247                 :            : }
     248                 :            : 
     249                 :            : /* handle config file read and write */
     250                 :            : static int
     251                 :        452 : debuginfod_config_cache(debuginfod_client *c, char *config_path,
     252                 :            :                         long cache_config_default_s,
     253                 :            :                         struct stat *st)
     254                 :            : {
     255                 :        452 :   int fd = open(config_path, O_CREAT | O_RDWR, DEFFILEMODE);
     256         [ -  + ]:        452 :   if (fd < 0)
     257                 :          0 :     return -errno;
     258                 :            : 
     259         [ -  + ]:        452 :   if (fstat (fd, st) < 0)
     260                 :            :     {
     261                 :          0 :       int ret = -errno;
     262                 :          0 :       close (fd);
     263                 :          0 :       return ret;
     264                 :            :     }
     265                 :            : 
     266         [ +  + ]:        452 :   if (st->st_size == 0)
     267                 :            :     {
     268         [ -  + ]:         38 :       if (dprintf(fd, "%ld", cache_config_default_s) < 0)
     269                 :            :         {
     270                 :          0 :           int ret = -errno;
     271                 :          0 :           close (fd);
     272                 :          0 :           return ret;
     273                 :            :         }
     274                 :            : 
     275                 :         38 :       close (fd);
     276                 :         38 :       return cache_config_default_s;
     277                 :            :     }
     278                 :            : 
     279                 :        414 :   long cache_config;
     280                 :            :   /* PR29696 - NB: When using fdopen, the file descriptor is NOT dup'ed and will
     281                 :            :   be closed when the stream is closed. Manually closing fd after fclose
     282                 :            :   is called will lead to a race condition where, if reused, the file descriptor will
     283                 :            :   compete for its regular use before being incorrectly closed here.
     284                 :            :   */
     285                 :        414 :   FILE *config_file = fdopen(fd, "r");
     286         [ +  - ]:        414 :   if (config_file)
     287                 :            :   {
     288         [ -  + ]:        414 :     if (fscanf(config_file, "%ld", &cache_config) != 1)
     289                 :          0 :       cache_config = cache_config_default_s;
     290   [ -  +  -  - ]:        414 :     if(0 != fclose(config_file) && c->verbose_fd >= 0)
     291                 :          0 :       dprintf (c->verbose_fd, "fclose failed with %s (err=%d)\n", strerror (errno), errno);
     292                 :            :   }else{
     293                 :          0 :     cache_config = cache_config_default_s;
     294   [ #  #  #  # ]:          0 :     if(0 != close(fd) && c->verbose_fd >= 0)
     295                 :          0 :       dprintf (c->verbose_fd, "close failed with %s (err=%d)\n", strerror (errno), errno);
     296                 :            :   }
     297                 :        414 :   return cache_config;
     298                 :            : }
     299                 :            : 
     300                 :            : /* Delete any files that have been unmodied for a period
     301                 :            :    longer than $DEBUGINFOD_CACHE_CLEAN_INTERVAL_S.  */
     302                 :            : static int
     303                 :        449 : debuginfod_clean_cache(debuginfod_client *c,
     304                 :            :                        char *cache_path, char *interval_path,
     305                 :            :                        char *max_unused_path)
     306                 :            : {
     307                 :        449 :   time_t clean_interval, max_unused_age;
     308                 :        449 :   int rc = -1;
     309                 :        449 :   struct stat st;
     310                 :            : 
     311                 :            :   /* Create new interval file.  */
     312                 :        449 :   rc = debuginfod_config_cache(c, interval_path,
     313                 :            :                                cache_clean_default_interval_s, &st);
     314         [ +  - ]:        449 :   if (rc < 0)
     315                 :            :     return rc;
     316                 :        449 :   clean_interval = (time_t)rc;
     317                 :            : 
     318                 :            :   /* Check timestamp of interval file to see whether cleaning is necessary.  */
     319         [ +  + ]:        449 :   if (time(NULL) - st.st_mtime < clean_interval)
     320                 :            :     /* Interval has not passed, skip cleaning.  */
     321                 :            :     return 0;
     322                 :            : 
     323                 :            :   /* Update timestamp representing when the cache was last cleaned.
     324                 :            :      Do it at the start to reduce the number of threads trying to do a
     325                 :            :      cleanup simultaneously.  */
     326                 :          1 :   utime (interval_path, NULL);
     327                 :            : 
     328                 :            :   /* Read max unused age value from config file.  */
     329                 :          1 :   rc = debuginfod_config_cache(c, max_unused_path,
     330                 :            :                                cache_default_max_unused_age_s, &st);
     331         [ +  - ]:          1 :   if (rc < 0)
     332                 :            :     return rc;
     333                 :          1 :   max_unused_age = (time_t)rc;
     334                 :            : 
     335                 :          1 :   char * const dirs[] = { cache_path, NULL, };
     336                 :            : 
     337                 :          1 :   FTS *fts = fts_open(dirs, 0, NULL);
     338         [ -  + ]:          1 :   if (fts == NULL)
     339                 :          0 :     return -errno;
     340                 :            : 
     341                 :          1 :   regex_t re;
     342                 :          1 :   const char * pattern = ".*/[a-f0-9]+(/debuginfo|/executable|/source.*|)$"; /* include dirs */
     343         [ +  - ]:          1 :   if (regcomp (&re, pattern, REG_EXTENDED | REG_NOSUB) != 0)
     344                 :            :     return -ENOMEM;
     345                 :            : 
     346                 :          1 :   FTSENT *f;
     347                 :          1 :   long files = 0;
     348                 :          1 :   time_t now = time(NULL);
     349         [ +  + ]:         12 :   while ((f = fts_read(fts)) != NULL)
     350                 :            :     {
     351                 :            :       /* ignore any files that do not match the pattern.  */
     352         [ +  + ]:         10 :       if (regexec (&re, f->fts_path, 0, NULL, 0) != 0)
     353                 :          8 :         continue;
     354                 :            : 
     355                 :          2 :       files++;
     356         [ -  + ]:          2 :       if (c->progressfn) /* inform/check progress callback */
     357         [ #  # ]:          0 :         if ((c->progressfn) (c, files, 0))
     358                 :            :           break;
     359                 :            : 
     360      [ +  -  + ]:          2 :       switch (f->fts_info)
     361                 :            :         {
     362                 :          0 :         case FTS_F:
     363                 :            :           /* delete file if max_unused_age has been met or exceeded w.r.t. atime.  */
     364         [ #  # ]:          0 :           if (now - f->fts_statp->st_atime >= max_unused_age)
     365                 :          0 :             (void) unlink (f->fts_path);
     366                 :            :           break;
     367                 :            : 
     368                 :          1 :         case FTS_DP:
     369                 :            :           /* Remove if old & empty.  Weaken race against concurrent creation by 
     370                 :            :              checking mtime. */
     371         [ -  + ]:          1 :           if (now - f->fts_statp->st_mtime >= max_unused_age)
     372                 :          1 :             (void) rmdir (f->fts_path);
     373                 :            :           break;
     374                 :            : 
     375                 :            :         default:
     376                 :         11 :           ;
     377                 :            :         }
     378                 :            :     }
     379                 :          1 :   fts_close (fts);
     380                 :          1 :   regfree (&re);
     381                 :            : 
     382                 :          1 :   return 0;
     383                 :            : }
     384                 :            : 
     385                 :            : 
     386                 :            : #define MAX_BUILD_ID_BYTES 64
     387                 :            : 
     388                 :            : 
     389                 :            : static void
     390                 :        449 : add_default_headers(debuginfod_client *client)
     391                 :            : {
     392         [ +  + ]:        449 :   if (client->user_agent_set_p)
     393                 :        274 :     return;
     394                 :            : 
     395                 :            :   /* Compute a User-Agent: string to send.  The more accurately this
     396                 :            :      describes this host, the likelier that the debuginfod servers
     397                 :            :      might be able to locate debuginfo for us. */
     398                 :            : 
     399                 :        175 :   char* utspart = NULL;
     400                 :        175 :   struct utsname uts;
     401                 :        175 :   int rc = 0;
     402                 :        175 :   rc = uname (&uts);
     403         [ +  - ]:        175 :   if (rc == 0)
     404                 :        175 :     rc = asprintf(& utspart, "%s/%s", uts.sysname, uts.machine);
     405         [ -  + ]:        175 :   if (rc < 0)
     406                 :          0 :     utspart = NULL;
     407                 :            : 
     408                 :        175 :   FILE *f = fopen ("/etc/os-release", "r");
     409         [ -  + ]:        175 :   if (f == NULL)
     410                 :          0 :     f = fopen ("/usr/lib/os-release", "r");
     411                 :        175 :   char *id = NULL;
     412                 :        175 :   char *version = NULL;
     413         [ +  - ]:        175 :   if (f != NULL)
     414                 :            :     {
     415         [ +  + ]:       1225 :       while (id == NULL || version == NULL)
     416                 :            :         {
     417                 :       1050 :           char buf[128];
     418                 :       1050 :           char *s = &buf[0];
     419         [ +  - ]:       1050 :           if (fgets (s, sizeof(buf), f) == NULL)
     420                 :            :             break;
     421                 :            : 
     422                 :       1050 :           int len = strlen (s);
     423         [ -  + ]:       1050 :           if (len < 3)
     424                 :          0 :             continue;
     425         [ +  - ]:       1050 :           if (s[len - 1] == '\n')
     426                 :            :             {
     427                 :       1050 :               s[len - 1] = '\0';
     428                 :       1050 :               len--;
     429                 :            :             }
     430                 :            : 
     431                 :       1050 :           char *v = strchr (s, '=');
     432   [ +  -  -  + ]:       1050 :           if (v == NULL || strlen (v) < 2)
     433                 :          0 :             continue;
     434                 :            : 
     435                 :            :           /* Split var and value. */
     436                 :       1050 :           *v = '\0';
     437                 :       1050 :           v++;
     438                 :            : 
     439                 :            :           /* Remove optional quotes around value string. */
     440         [ +  + ]:       1050 :           if (*v == '"' || *v == '\'')
     441                 :            :             {
     442                 :        700 :               v++;
     443                 :        700 :               s[len - 1] = '\0';
     444                 :            :             }
     445         [ +  + ]:       1050 :           if (strcmp (s, "ID") == 0)
     446                 :        175 :             id = strdup (v);
     447         [ +  + ]:       1050 :           if (strcmp (s, "VERSION_ID") == 0)
     448                 :        175 :             version = strdup (v);
     449                 :            :         }
     450                 :        175 :       fclose (f);
     451                 :            :     }
     452                 :            : 
     453                 :        175 :   char *ua = NULL;
     454   [ +  -  +  - ]:        350 :   rc = asprintf(& ua, "User-Agent: %s/%s,%s,%s/%s",
     455                 :            :                 PACKAGE_NAME, PACKAGE_VERSION,
     456         [ -  + ]:        175 :                 utspart ?: "",
     457                 :            :                 id ?: "",
     458                 :            :                 version ?: "");
     459         [ -  + ]:        175 :   if (rc < 0)
     460                 :          0 :     ua = NULL;
     461                 :            : 
     462         [ +  - ]:        175 :   if (ua)
     463                 :        175 :     (void) debuginfod_add_http_header (client, ua);
     464                 :            : 
     465                 :        175 :   free (ua);
     466                 :        175 :   free (id);
     467                 :        175 :   free (version);
     468                 :        175 :   free (utspart);
     469                 :            : }
     470                 :            : 
     471                 :            : /* Add HTTP headers found in the given file, one per line. Blank lines or invalid
     472                 :            :  * headers are ignored.
     473                 :            :  */
     474                 :            : static void
     475                 :          0 : add_headers_from_file(debuginfod_client *client, const char* filename)
     476                 :            : {
     477                 :          0 :   int vds = client->verbose_fd;
     478                 :          0 :   FILE *f = fopen (filename, "r");
     479         [ #  # ]:          0 :   if (f == NULL)
     480                 :            :     {
     481         [ #  # ]:          0 :       if (vds >= 0)
     482                 :          0 :         dprintf(vds, "header file %s: %s\n", filename, strerror(errno));
     483                 :          0 :       return;
     484                 :            :     }
     485                 :            : 
     486                 :          0 :   while (1)
     487                 :          0 :     {
     488                 :          0 :       char buf[8192];
     489                 :          0 :       char *s = &buf[0];
     490         [ #  # ]:          0 :       if (feof(f))
     491                 :            :         break;
     492         [ #  # ]:          0 :       if (fgets (s, sizeof(buf), f) == NULL)
     493                 :            :         break;
     494         [ #  # ]:          0 :       for (char *c = s; *c != '\0'; ++c)
     495         [ #  # ]:          0 :         if (!isspace(*c))
     496                 :          0 :           goto nonempty;
     497                 :          0 :       continue;
     498                 :          0 :     nonempty:
     499                 :          0 :       ;
     500                 :          0 :       size_t last = strlen(s)-1;
     501         [ #  # ]:          0 :       if (s[last] == '\n')
     502                 :          0 :         s[last] = '\0';
     503                 :          0 :       int rc = debuginfod_add_http_header(client, s);
     504         [ #  # ]:          0 :       if (rc < 0 && vds >= 0)
     505                 :          0 :         dprintf(vds, "skipping bad header: %s\n", strerror(-rc));
     506                 :            :     }
     507                 :          0 :   fclose (f);
     508                 :            : }
     509                 :            : 
     510                 :            : 
     511                 :            : #define xalloc_str(p, fmt, args...)        \
     512                 :            :   do                                       \
     513                 :            :     {                                      \
     514                 :            :       if (asprintf (&p, fmt, args) < 0)    \
     515                 :            :         {                                  \
     516                 :            :           p = NULL;                        \
     517                 :            :           rc = -ENOMEM;                    \
     518                 :            :           goto out;                        \
     519                 :            :         }                                  \
     520                 :            :     } while (0)
     521                 :            : 
     522                 :            : 
     523                 :            : /* Offer a basic form of progress tracing */
     524                 :            : static int
     525                 :          3 : default_progressfn (debuginfod_client *c, long a, long b)
     526                 :            : {
     527                 :          3 :   const char* url = debuginfod_get_url (c);
     528                 :          3 :   int len = 0;
     529                 :            : 
     530                 :            :   /* We prefer to print the host part of the URL to keep the
     531                 :            :      message short. */
     532                 :          3 :   if (url != NULL)
     533                 :            :     {
     534                 :          1 :       const char* buildid = strstr(url, "buildid/");
     535         [ +  - ]:          1 :       if (buildid != NULL)
     536                 :          1 :         len = (buildid - url);
     537                 :            :       else
     538                 :          0 :         len = strlen(url);
     539                 :            :     }
     540                 :            : 
     541         [ +  + ]:          3 :   if (b == 0 || url==NULL) /* early stage */
     542                 :          5 :     dprintf(STDERR_FILENO,
     543                 :          2 :             "\rDownloading %c", "-/|\\"[a % 4]);
     544         [ -  + ]:          1 :   else if (b < 0) /* download in progress but unknown total length */
     545                 :          0 :     dprintf(STDERR_FILENO,
     546                 :            :             "\rDownloading from %.*s %ld",
     547                 :            :             len, url, a);
     548                 :            :   else /* download in progress, and known total length */
     549                 :          1 :     dprintf(STDERR_FILENO,
     550                 :            :             "\rDownloading from %.*s %ld/%ld",
     551                 :            :             len, url, a, b);
     552                 :          3 :   c->default_progressfn_printed_p = 1;
     553                 :            : 
     554                 :          3 :   return 0;
     555                 :            : }
     556                 :            : 
     557                 :            : /* This is a callback function that receives http response headers in buffer for use
     558                 :            :  * in this program. https://curl.se/libcurl/c/CURLOPT_HEADERFUNCTION.html is the
     559                 :            :  * online documentation.
     560                 :            :  */
     561                 :            : static size_t
     562                 :       1318 : header_callback (char * buffer, size_t size, size_t numitems, void * userdata)
     563                 :            : {
     564                 :       1318 :   struct handle_data *data = (struct handle_data *) userdata;
     565         [ -  + ]:       1318 :   if (size != 1)
     566                 :            :     return 0;
     567   [ +  -  +  + ]:       1318 :   if (data->client && data->client->verbose_fd >= 0)
     568                 :        111 :     dprintf (data->client->verbose_fd, "header %.*s", (int)numitems, buffer);
     569                 :            :   // Some basic checks to ensure the headers received are of the expected format
     570         [ +  + ]:       1318 :   if (strncasecmp(buffer, "X-DEBUGINFOD", 11)
     571         [ +  + ]:        324 :       || buffer[numitems-2] != '\r'
     572         [ +  - ]:        323 :       || buffer[numitems-1] != '\n'
     573         [ -  + ]:        323 :       || (buffer == strstr(buffer, ":")) ){
     574                 :            :     return numitems;
     575                 :            :   }
     576                 :            :   /* Temporary buffer for realloc */
     577                 :        323 :   char *temp = NULL;
     578         [ +  + ]:        323 :   if (data->response_data == NULL)
     579                 :            :     {
     580                 :        120 :       temp = malloc(numitems);
     581         [ -  + ]:        120 :       if (temp == NULL)
     582                 :            :         return 0;
     583                 :            :     }
     584                 :            :   else
     585                 :            :     {
     586                 :        203 :       temp = realloc(data->response_data, data->response_data_size + numitems);
     587         [ -  + ]:        203 :       if (temp == NULL)
     588                 :            :         return 0;
     589                 :            :     }
     590                 :            : 
     591                 :        323 :   memcpy(temp + data->response_data_size, buffer, numitems-1);
     592                 :        323 :   data->response_data = temp;
     593                 :        323 :   data->response_data_size += numitems-1;
     594                 :        323 :   data->response_data[data->response_data_size-1] = '\n';
     595                 :        323 :   data->response_data[data->response_data_size] = '\0';
     596                 :        323 :   return numitems;
     597                 :            : }
     598                 :            : 
     599                 :            : /* Copy SRC to DEST, s,/,#,g */
     600                 :            : 
     601                 :            : static void
     602                 :         42 : path_escape (const char *src, char *dest)
     603                 :            : {
     604                 :         42 :   unsigned q = 0;
     605                 :            : 
     606         [ +  - ]:       1495 :   for (unsigned fi=0; q < PATH_MAX-2; fi++) /* -2, escape is 2 chars.  */
     607   [ +  +  +  + ]:       1495 :     switch (src[fi])
     608                 :            :       {
     609                 :         42 :       case '\0':
     610                 :         42 :         dest[q] = '\0';
     611                 :         42 :         return;
     612                 :        196 :       case '/': /* escape / to prevent dir escape */
     613                 :        196 :         dest[q++]='#';
     614                 :        196 :         dest[q++]='#';
     615                 :        196 :         break;
     616                 :          1 :       case '#': /* escape # to prevent /# vs #/ collisions */
     617                 :          1 :         dest[q++]='#';
     618                 :          1 :         dest[q++]='_';
     619                 :          1 :         break;
     620                 :       1256 :       default:
     621                 :       1256 :         dest[q++]=src[fi];
     622                 :            :       }
     623                 :            : 
     624                 :          0 :   dest[q] = '\0';
     625                 :            : }
     626                 :            : 
     627                 :            : /* Attempt to update the atime */
     628                 :            : static void
     629                 :         39 : update_atime (int fd)
     630                 :            : {
     631                 :         39 :   struct timespec tvs[2];
     632                 :            : 
     633                 :         39 :   tvs[0].tv_sec = tvs[1].tv_sec = 0;
     634                 :         39 :   tvs[0].tv_nsec = UTIME_NOW;
     635                 :         39 :   tvs[1].tv_nsec = UTIME_OMIT;
     636                 :            : 
     637                 :         39 :   (void) futimens (fd, tvs);  /* best effort */
     638                 :         39 : }
     639                 :            : 
     640                 :            : /* Attempt to read an ELF/DWARF section with name SECTION from FD and write
     641                 :            :    it to a separate file in the debuginfod cache.  If successful the absolute
     642                 :            :    path of the separate file containing SECTION will be stored in USR_PATH.
     643                 :            :    FD_PATH is the absolute path for FD.
     644                 :            : 
     645                 :            :    If the section cannot be extracted, then return a negative error code.
     646                 :            :    -ENOENT indicates that the parent file was able to be read but the
     647                 :            :    section name was not found.  -EEXIST indicates that the section was
     648                 :            :    found but had type SHT_NOBITS.  */
     649                 :            : 
     650                 :            : static int
     651                 :          6 : extract_section (int fd, const char *section, char *fd_path, char **usr_path)
     652                 :            : {
     653                 :          6 :   elf_version (EV_CURRENT);
     654                 :            : 
     655                 :          6 :   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
     656         [ +  - ]:          6 :   if (elf == NULL)
     657                 :            :     return -EIO;
     658                 :            : 
     659                 :          6 :   size_t shstrndx;
     660                 :          6 :   int rc = elf_getshdrstrndx (elf, &shstrndx);
     661         [ -  + ]:          6 :   if (rc < 0)
     662                 :            :     {
     663                 :          0 :       rc = -EIO;
     664                 :          0 :       goto out;
     665                 :            :     }
     666                 :            : 
     667                 :          6 :   int sec_fd = -1;
     668                 :          6 :   char *escaped_name = NULL;
     669                 :          6 :   char *sec_path_tmp = NULL;
     670                 :          6 :   Elf_Scn *scn = NULL;
     671                 :            : 
     672                 :            :   /* Try to find the target section and copy the contents into a
     673                 :            :      separate file.  */
     674                 :        216 :   while (true)
     675                 :        105 :     {
     676                 :        111 :       scn = elf_nextscn (elf, scn);
     677         [ -  + ]:        111 :       if (scn == NULL)
     678                 :            :         {
     679                 :          0 :           rc = -ENOENT;
     680                 :          2 :           goto out;
     681                 :            :         }
     682                 :        111 :       GElf_Shdr shdr_storage;
     683                 :        111 :       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
     684         [ -  + ]:        111 :       if (shdr == NULL)
     685                 :            :         {
     686                 :          0 :           rc = -EIO;
     687                 :          0 :           goto out;
     688                 :            :         }
     689                 :            : 
     690                 :        111 :       const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
     691         [ -  + ]:        111 :       if (scn_name == NULL)
     692                 :            :         {
     693                 :          0 :           rc = -EIO;
     694                 :          0 :           goto out;
     695                 :            :         }
     696         [ +  + ]:        111 :       if (strcmp (scn_name, section) == 0)
     697                 :            :         {
     698                 :            :           /* We found the desired section.  */
     699         [ +  + ]:          6 :           if (shdr->sh_type == SHT_NOBITS)
     700                 :            :             {
     701                 :          2 :               rc = -EEXIST;
     702                 :          2 :               goto out;
     703                 :            :             }
     704                 :            : 
     705                 :          4 :           Elf_Data *data = NULL;
     706                 :          4 :           data = elf_rawdata (scn, NULL);
     707         [ -  + ]:          4 :           if (data == NULL)
     708                 :            :             {
     709                 :          0 :               rc = -EIO;
     710                 :          0 :               goto out;
     711                 :            :             }
     712                 :            : 
     713         [ -  + ]:          4 :           if (data->d_buf == NULL)
     714                 :            :             {
     715                 :          0 :               rc = -EIO;
     716                 :          0 :               goto out;
     717                 :            :             }
     718                 :            : 
     719                 :            :           /* Compute the absolute filename we'll write the section to.
     720                 :            :              Replace the last component of FD_PATH with the path-escaped
     721                 :            :              section filename.  */
     722                 :          4 :           int i = strlen (fd_path);
     723         [ +  - ]:         46 :           while (i >= 0)
     724                 :            :             {
     725         [ +  + ]:         46 :               if (fd_path[i] == '/')
     726                 :            :                 {
     727                 :          4 :                   fd_path[i] = '\0';
     728                 :          4 :                   break;
     729                 :            :                 }
     730                 :         42 :               --i;
     731                 :            :             }
     732                 :            : 
     733                 :          4 :           escaped_name = malloc (strlen (section) * 2 + 1);
     734         [ -  + ]:          4 :           if (escaped_name == NULL)
     735                 :            :             {
     736                 :          0 :               rc = -ENOMEM;
     737                 :          0 :               goto out;
     738                 :            :             }
     739                 :          4 :           path_escape (section, escaped_name);
     740                 :            : 
     741                 :          4 :           rc = asprintf (&sec_path_tmp, "%s/section-%s.XXXXXX",
     742                 :            :                          fd_path, escaped_name);
     743         [ -  + ]:          4 :           if (rc == -1)
     744                 :            :             {
     745                 :          0 :               rc = -ENOMEM;
     746                 :          0 :               goto out1;
     747                 :            :             }
     748                 :            : 
     749                 :          4 :           sec_fd = mkstemp (sec_path_tmp);
     750         [ -  + ]:          4 :           if (sec_fd < 0)
     751                 :            :             {
     752                 :          0 :               rc = -EIO;
     753                 :          4 :               goto out2;
     754                 :            :             }
     755                 :            : 
     756                 :          4 :           ssize_t res = write_retry (sec_fd, data->d_buf, data->d_size);
     757   [ +  -  -  + ]:          4 :           if (res < 0 || (size_t) res != data->d_size)
     758                 :            :             {
     759                 :          0 :               rc = -EIO;
     760                 :          0 :               goto out3;
     761                 :            :             }
     762                 :            : 
     763                 :            :           /* Success.  Rename tmp file and update USR_PATH.  */
     764                 :          4 :           char *sec_path;
     765         [ -  + ]:          4 :           if (asprintf (&sec_path, "%s/section-%s", fd_path, section) == -1)
     766                 :            :             {
     767                 :          0 :               rc = -ENOMEM;
     768                 :          0 :               goto out3;
     769                 :            :             }
     770                 :            : 
     771                 :          4 :           rc = rename (sec_path_tmp, sec_path);
     772         [ -  + ]:          4 :           if (rc < 0)
     773                 :            :             {
     774                 :          0 :               free (sec_path);
     775                 :          0 :               rc = -EIO;
     776                 :          0 :               goto out3;
     777                 :            :             }
     778                 :            : 
     779         [ +  - ]:          4 :           if (usr_path != NULL)
     780                 :          4 :             *usr_path = sec_path;
     781                 :            :           else
     782                 :          0 :             free (sec_path);
     783                 :          4 :           update_atime(fd);
     784                 :          4 :           rc = sec_fd;
     785                 :          4 :           goto out2;
     786                 :            :         }
     787                 :            :     }
     788                 :            : 
     789                 :          0 : out3:
     790                 :          0 :   close (sec_fd);
     791                 :          0 :   unlink (sec_path_tmp);
     792                 :            : 
     793                 :          4 : out2:
     794                 :          4 :   free (sec_path_tmp);
     795                 :            : 
     796                 :          4 : out1:
     797                 :          4 :   free (escaped_name);
     798                 :            : 
     799                 :          6 : out:
     800                 :          6 :   elf_end (elf);
     801                 :          6 :   return rc;
     802                 :            : }
     803                 :            : 
     804                 :            : /* Search TARGET_CACHE_DIR for a debuginfo or executable file containing
     805                 :            :    an ELF/DWARF section with name SCN_NAME.  If found, extract the section
     806                 :            :    to a separate file in TARGET_CACHE_DIR and return a file descriptor
     807                 :            :    for the section file. The path for this file will be stored in USR_PATH.
     808                 :            :    Return a negative errno if unsuccessful.  -ENOENT indicates that SCN_NAME
     809                 :            :    is confirmed to not exist.  */
     810                 :            : 
     811                 :            : static int
     812                 :          8 : cache_find_section (const char *scn_name, const char *target_cache_dir,
     813                 :            :                     char **usr_path)
     814                 :            : {
     815                 :          8 :   int debug_fd;
     816                 :          8 :   int rc = -EEXIST;
     817                 :          8 :   char parent_path[PATH_MAX];
     818                 :            : 
     819                 :            :   /* Check the debuginfo first.  */
     820                 :          8 :   snprintf (parent_path, PATH_MAX, "%s/debuginfo", target_cache_dir);
     821                 :          8 :   debug_fd = open (parent_path, O_RDONLY);
     822         [ +  + ]:          8 :   if (debug_fd >= 0)
     823                 :            :     {
     824                 :          4 :       rc = extract_section (debug_fd, scn_name, parent_path, usr_path);
     825                 :          4 :       close (debug_fd);
     826                 :            :     }
     827                 :            : 
     828                 :            :   /* If the debuginfo file couldn't be found or the section type was
     829                 :            :      SHT_NOBITS, check the executable.  */
     830         [ +  + ]:          4 :   if (rc == -EEXIST)
     831                 :            :     {
     832                 :          6 :       snprintf (parent_path, PATH_MAX, "%s/executable", target_cache_dir);
     833                 :          6 :       int exec_fd = open (parent_path, O_RDONLY);
     834                 :            : 
     835         [ +  + ]:          6 :       if (exec_fd >= 0)
     836                 :            :         {
     837                 :          2 :           rc = extract_section (exec_fd, scn_name, parent_path, usr_path);
     838                 :          2 :           close (exec_fd);
     839                 :            : 
     840                 :            :           /* Don't return -ENOENT if the debuginfo wasn't opened.  The
     841                 :            :              section may exist in the debuginfo but not the executable.  */
     842         [ -  + ]:          2 :           if (debug_fd < 0 && rc == -ENOENT)
     843                 :          0 :             rc = -EREMOTE;
     844                 :            :         }
     845                 :            :     }
     846                 :            : 
     847                 :          8 :   return rc;
     848                 :            : }
     849                 :            : 
     850                 :            : /* Query each of the server URLs found in $DEBUGINFOD_URLS for the file
     851                 :            :    with the specified build-id and type (debuginfo, executable, source or
     852                 :            :    section).  If type is source, then type_arg should be a filename.  If
     853                 :            :    type is section, then type_arg should be the name of an ELF/DWARF
     854                 :            :    section.  Otherwise type_arg may be NULL.  Return a file descriptor
     855                 :            :    for the target if successful, otherwise return an error code.
     856                 :            : */
     857                 :            : static int
     858                 :        484 : debuginfod_query_server (debuginfod_client *c,
     859                 :            :                          const unsigned char *build_id,
     860                 :            :                          int build_id_len,
     861                 :            :                          const char *type,
     862                 :            :                          const char *type_arg,
     863                 :            :                          char **path)
     864                 :            : {
     865                 :        484 :   char *server_urls;
     866                 :        484 :   char *urls_envvar;
     867                 :        484 :   const char *section = NULL;
     868                 :        484 :   const char *filename = NULL;
     869                 :        484 :   char *cache_path = NULL;
     870                 :        484 :   char *maxage_path = NULL;
     871                 :        484 :   char *interval_path = NULL;
     872                 :        484 :   char *cache_miss_path = NULL;
     873                 :        484 :   char *target_cache_dir = NULL;
     874                 :        484 :   char *target_cache_path = NULL;
     875                 :        484 :   char *target_cache_tmppath = NULL;
     876                 :        484 :   char suffix[PATH_MAX + 1]; /* +1 for zero terminator.  */
     877                 :        484 :   char build_id_bytes[MAX_BUILD_ID_BYTES * 2 + 1];
     878                 :        484 :   int vfd = c->verbose_fd;
     879                 :        484 :   int rc;
     880                 :            : 
     881                 :        484 :   c->progressfn_cancel = false;
     882                 :            : 
     883         [ +  + ]:        484 :   if (strcmp (type, "source") == 0)
     884                 :            :     filename = type_arg;
     885         [ +  + ]:        452 :   else if (strcmp (type, "section") == 0)
     886                 :            :     {
     887                 :          8 :       section = type_arg;
     888         [ +  - ]:          8 :       if (section == NULL)
     889                 :            :         return -EINVAL;
     890                 :            :     }
     891                 :            : 
     892         [ +  + ]:        484 :   if (vfd >= 0)
     893                 :            :     {
     894                 :         18 :       dprintf (vfd, "debuginfod_find_%s ", type);
     895         [ +  + ]:         18 :       if (build_id_len == 0) /* expect clean hexadecimal */
     896                 :         13 :         dprintf (vfd, "%s", (const char *) build_id);
     897                 :            :       else
     898         [ +  + ]:        105 :         for (int i = 0; i < build_id_len; i++)
     899                 :        100 :           dprintf (vfd, "%02x", build_id[i]);
     900         [ +  + ]:         18 :       if (filename != NULL)
     901                 :          1 :         dprintf (vfd, " %s\n", filename);
     902                 :         18 :       dprintf (vfd, "\n");
     903                 :            :     }
     904                 :            : 
     905                 :            :   /* Is there any server we can query?  If not, don't do any work,
     906                 :            :      just return with ENOSYS.  Don't even access the cache.  */
     907                 :        484 :   urls_envvar = getenv(DEBUGINFOD_URLS_ENV_VAR);
     908         [ +  + ]:        484 :   if (vfd >= 0)
     909         [ -  + ]:         18 :     dprintf (vfd, "server urls \"%s\"\n",
     910                 :            :              urls_envvar != NULL ? urls_envvar : "");
     911   [ +  +  +  + ]:        484 :   if (urls_envvar == NULL || urls_envvar[0] == '\0')
     912                 :            :     {
     913                 :         35 :       rc = -ENOSYS;
     914                 :         35 :       goto out;
     915                 :            :     }
     916                 :            : 
     917                 :            :   /* Clear the obsolete data from a previous _find operation. */
     918                 :        449 :   free (c->url);
     919                 :        449 :   c->url = NULL;
     920                 :        449 :   free (c->winning_headers);
     921                 :        449 :   c->winning_headers = NULL;
     922                 :            : 
     923                 :            :   /* PR 27982: Add max size if DEBUGINFOD_MAXSIZE is set. */
     924                 :        449 :   long maxsize = 0;
     925                 :        449 :   const char *maxsize_envvar;
     926                 :        449 :   maxsize_envvar = getenv(DEBUGINFOD_MAXSIZE_ENV_VAR);
     927         [ +  + ]:        449 :   if (maxsize_envvar != NULL)
     928                 :          1 :     maxsize = atol (maxsize_envvar);
     929                 :            : 
     930                 :            :   /* PR 27982: Add max time if DEBUGINFOD_MAXTIME is set. */
     931                 :        449 :   long maxtime = 0;
     932                 :        449 :   const char *maxtime_envvar;
     933                 :        449 :   maxtime_envvar = getenv(DEBUGINFOD_MAXTIME_ENV_VAR);
     934         [ +  + ]:        449 :   if (maxtime_envvar != NULL)
     935                 :          1 :     maxtime = atol (maxtime_envvar);
     936         [ +  + ]:        449 :   if (maxtime && vfd >= 0)
     937                 :          1 :     dprintf(vfd, "using max time %lds\n", maxtime);
     938                 :            : 
     939                 :        449 :   const char *headers_file_envvar;
     940                 :        449 :   headers_file_envvar = getenv(DEBUGINFOD_HEADERS_FILE_ENV_VAR);
     941         [ -  + ]:        449 :   if (headers_file_envvar != NULL)
     942                 :          0 :     add_headers_from_file(c, headers_file_envvar);
     943                 :            : 
     944                 :            :   /* Maxsize is valid*/
     945         [ +  + ]:        449 :   if (maxsize > 0)
     946                 :            :     {
     947         [ +  - ]:          1 :       if (vfd)
     948                 :          1 :         dprintf (vfd, "using max size %ldB\n", maxsize);
     949                 :          1 :       char *size_header = NULL;
     950                 :          1 :       rc = asprintf (&size_header, "X-DEBUGINFOD-MAXSIZE: %ld", maxsize);
     951         [ -  + ]:          1 :       if (rc < 0)
     952                 :            :         {
     953                 :          0 :           rc = -ENOMEM;
     954                 :          0 :           goto out;
     955                 :            :         }
     956                 :          1 :       rc = debuginfod_add_http_header(c, size_header);
     957                 :          1 :       free(size_header);
     958         [ -  + ]:          1 :       if (rc < 0)
     959                 :          0 :         goto out;
     960                 :            :     }
     961                 :        449 :   add_default_headers(c);
     962                 :            : 
     963                 :            :   /* Copy lowercase hex representation of build_id into buf.  */
     964         [ +  + ]:        449 :   if (vfd >= 0)
     965                 :         18 :     dprintf (vfd, "checking build-id\n");
     966   [ +  -  +  + ]:        449 :   if ((build_id_len >= MAX_BUILD_ID_BYTES) ||
     967                 :        443 :       (build_id_len == 0 &&
     968         [ -  + ]:        443 :        strlen ((const char *) build_id) > MAX_BUILD_ID_BYTES*2))
     969                 :            :     {
     970                 :          0 :       rc = -EINVAL;
     971                 :          0 :       goto out;
     972                 :            :     }
     973                 :            : 
     974         [ +  + ]:        449 :   if (build_id_len == 0) /* expect clean hexadecimal */
     975                 :        443 :     strcpy (build_id_bytes, (const char *) build_id);
     976                 :            :   else
     977         [ +  + ]:        126 :     for (int i = 0; i < build_id_len; i++)
     978                 :        120 :       sprintf(build_id_bytes + (i * 2), "%02x", build_id[i]);
     979                 :            : 
     980         [ +  + ]:        449 :   if (filename != NULL)
     981                 :            :     {
     982         [ +  + ]:         30 :       if (vfd >= 0)
     983                 :          1 :         dprintf (vfd, "checking filename\n");
     984         [ -  + ]:         30 :       if (filename[0] != '/') // must start with /
     985                 :            :         {
     986                 :          0 :           rc = -EINVAL;
     987                 :          0 :           goto out;
     988                 :            :         }
     989                 :            : 
     990                 :         30 :       path_escape (filename, suffix);
     991                 :            :       /* If the DWARF filenames are super long, this could exceed
     992                 :            :          PATH_MAX and truncate/collide.  Oh well, that'll teach
     993                 :            :          them! */
     994                 :            :     }
     995         [ +  + ]:        419 :   else if (section != NULL)
     996                 :          8 :     path_escape (section, suffix);
     997                 :            :   else
     998                 :        411 :     suffix[0] = '\0';
     999                 :            : 
    1000   [ +  +  +  + ]:        449 :   if (suffix[0] != '\0' && vfd >= 0)
    1001                 :          9 :     dprintf (vfd, "suffix %s\n", suffix);
    1002                 :            : 
    1003                 :            :   /* set paths needed to perform the query
    1004                 :            : 
    1005                 :            :      example format
    1006                 :            :      cache_path:        $HOME/.cache
    1007                 :            :      target_cache_dir:  $HOME/.cache/0123abcd
    1008                 :            :      target_cache_path: $HOME/.cache/0123abcd/debuginfo
    1009                 :            :      target_cache_path: $HOME/.cache/0123abcd/source#PATH#TO#SOURCE ?
    1010                 :            : 
    1011                 :            :      $XDG_CACHE_HOME takes priority over $HOME/.cache.
    1012                 :            :      $DEBUGINFOD_CACHE_PATH takes priority over $HOME/.cache and $XDG_CACHE_HOME.
    1013                 :            :   */
    1014                 :            : 
    1015                 :            :   /* Determine location of the cache. The path specified by the debuginfod
    1016                 :            :      cache environment variable takes priority.  */
    1017                 :        449 :   char *cache_var = getenv(DEBUGINFOD_CACHE_PATH_ENV_VAR);
    1018   [ +  -  +  + ]:        449 :   if (cache_var != NULL && strlen (cache_var) > 0)
    1019         [ -  + ]:        445 :     xalloc_str (cache_path, "%s", cache_var);
    1020                 :            :   else
    1021                 :            :     {
    1022                 :            :       /* If a cache already exists in $HOME ('/' if $HOME isn't set), then use
    1023                 :            :          that. Otherwise use the XDG cache directory naming format.  */
    1024   [ -  +  -  + ]:          8 :       xalloc_str (cache_path, "%s/%s", getenv ("HOME") ?: "/", cache_default_name);
    1025                 :            : 
    1026                 :          4 :       struct stat st;
    1027         [ +  + ]:          4 :       if (stat (cache_path, &st) < 0)
    1028                 :            :         {
    1029                 :          3 :           char cachedir[PATH_MAX];
    1030                 :          3 :           char *xdg = getenv ("XDG_CACHE_HOME");
    1031                 :            : 
    1032   [ +  -  +  + ]:          3 :           if (xdg != NULL && strlen (xdg) > 0)
    1033                 :          1 :             snprintf (cachedir, PATH_MAX, "%s", xdg);
    1034                 :            :           else
    1035         [ -  + ]:          2 :             snprintf (cachedir, PATH_MAX, "%s/.cache", getenv ("HOME") ?: "/");
    1036                 :            : 
    1037                 :            :           /* Create XDG cache directory if it doesn't exist.  */
    1038         [ +  + ]:          3 :           if (stat (cachedir, &st) == 0)
    1039                 :            :             {
    1040         [ -  + ]:          1 :               if (! S_ISDIR (st.st_mode))
    1041                 :            :                 {
    1042                 :          0 :                   rc = -EEXIST;
    1043                 :          0 :                   goto out;
    1044                 :            :                 }
    1045                 :            :             }
    1046                 :            :           else
    1047                 :            :             {
    1048                 :          2 :               rc = mkdir (cachedir, 0700);
    1049                 :            : 
    1050                 :            :               /* Also check for EEXIST and S_ISDIR in case another client just
    1051                 :            :                  happened to create the cache.  */
    1052         [ -  + ]:          2 :               if (rc < 0
    1053         [ #  # ]:          0 :                   && (errno != EEXIST
    1054         [ #  # ]:          0 :                       || stat (cachedir, &st) != 0
    1055         [ #  # ]:          0 :                       || ! S_ISDIR (st.st_mode)))
    1056                 :            :                 {
    1057                 :          0 :                   rc = -errno;
    1058                 :          0 :                   goto out;
    1059                 :            :                 }
    1060                 :            :             }
    1061                 :            : 
    1062                 :          3 :           free (cache_path);
    1063         [ -  + ]:          3 :           xalloc_str (cache_path, "%s/%s", cachedir, cache_xdg_name);
    1064                 :            :         }
    1065                 :            :     }
    1066                 :            : 
    1067         [ -  + ]:        449 :   xalloc_str (target_cache_dir, "%s/%s", cache_path, build_id_bytes);
    1068         [ +  + ]:        449 :   if (section != NULL)
    1069         [ -  + ]:          8 :     xalloc_str (target_cache_path, "%s/%s-%s", target_cache_dir, type, suffix);
    1070                 :            :   else
    1071         [ -  + ]:        441 :     xalloc_str (target_cache_path, "%s/%s%s", target_cache_dir, type, suffix);
    1072         [ -  + ]:        449 :   xalloc_str (target_cache_tmppath, "%s.XXXXXX", target_cache_path);
    1073                 :            : 
    1074                 :            :   /* XXX combine these */
    1075         [ -  + ]:        449 :   xalloc_str (interval_path, "%s/%s", cache_path, cache_clean_interval_filename);
    1076         [ -  + ]:        449 :   xalloc_str (cache_miss_path, "%s/%s", cache_path, cache_miss_filename);
    1077         [ -  + ]:        449 :   xalloc_str (maxage_path, "%s/%s", cache_path, cache_max_unused_age_filename);
    1078                 :            : 
    1079         [ +  + ]:        449 :   if (vfd >= 0)
    1080                 :         18 :     dprintf (vfd, "checking cache dir %s\n", cache_path);
    1081                 :            : 
    1082                 :            :   /* Make sure cache dir exists. debuginfo_clean_cache will then make
    1083                 :            :      sure the interval, cache_miss and maxage files exist.  */
    1084         [ +  + ]:        449 :   if (mkdir (cache_path, ACCESSPERMS) != 0
    1085         [ -  + ]:        419 :       && errno != EEXIST)
    1086                 :            :     {
    1087                 :          0 :       rc = -errno;
    1088                 :          0 :       goto out;
    1089                 :            :     }
    1090                 :            : 
    1091                 :        449 :   rc = debuginfod_clean_cache(c, cache_path, interval_path, maxage_path);
    1092         [ -  + ]:        449 :   if (rc != 0)
    1093                 :          0 :     goto out;
    1094                 :            : 
    1095                 :            :   /* Check if the target is already in the cache. */
    1096                 :        449 :   int fd = open(target_cache_path, O_RDONLY);
    1097         [ +  + ]:        449 :   if (fd >= 0)
    1098                 :            :     {
    1099                 :         37 :       struct stat st;
    1100         [ -  + ]:         37 :       if (fstat(fd, &st) != 0)
    1101                 :            :         {
    1102                 :          0 :           rc = -errno;
    1103                 :          0 :           close (fd);
    1104                 :         36 :           goto out;
    1105                 :            :         }
    1106                 :            : 
    1107                 :            :       /* If the file is non-empty, then we are done. */
    1108         [ +  + ]:         37 :       if (st.st_size > 0)
    1109                 :            :         {
    1110         [ +  - ]:         35 :           if (path != NULL)
    1111                 :            :             {
    1112                 :         35 :               *path = strdup(target_cache_path);
    1113         [ -  + ]:         35 :               if (*path == NULL)
    1114                 :            :                 {
    1115                 :          0 :                   rc = -errno;
    1116                 :          0 :                   close (fd);
    1117                 :          0 :                   goto out;
    1118                 :            :                 }
    1119                 :            :             }
    1120                 :            :           /* Success!!!! */
    1121                 :         35 :           update_atime(fd);
    1122                 :         35 :           rc = fd;
    1123                 :         35 :           goto out;
    1124                 :            :         }
    1125                 :            :       else
    1126                 :            :         {
    1127                 :            :           /* The file is empty. Attempt to download only if enough time
    1128                 :            :              has passed since the last attempt. */
    1129                 :          2 :           time_t cache_miss;
    1130                 :          2 :           time_t target_mtime = st.st_mtime;
    1131                 :            : 
    1132                 :          2 :           close(fd); /* no need to hold onto the negative-hit file descriptor */
    1133                 :            :           
    1134                 :          2 :           rc = debuginfod_config_cache(c, cache_miss_path,
    1135                 :            :                                        cache_miss_default_s, &st);
    1136         [ -  + ]:          2 :           if (rc < 0)
    1137                 :          0 :             goto out;
    1138                 :            : 
    1139                 :          2 :           cache_miss = (time_t)rc;
    1140         [ +  + ]:          2 :           if (time(NULL) - target_mtime <= cache_miss)
    1141                 :            :             {
    1142                 :          1 :               rc = -ENOENT;
    1143                 :          1 :               goto out;
    1144                 :            :             }
    1145                 :            :           else
    1146                 :            :             /* TOCTOU non-problem: if another task races, puts a working
    1147                 :            :                download or an empty file in its place, unlinking here just
    1148                 :            :                means WE will try to download again as uncached. */
    1149                 :          1 :             unlink(target_cache_path);
    1150                 :            :         }
    1151                 :            :     }
    1152         [ -  + ]:        412 :   else if (errno == EACCES)
    1153                 :            :     /* Ensure old 000-permission files are not lingering in the cache. */
    1154                 :          0 :     unlink(target_cache_path);
    1155                 :            : 
    1156         [ +  + ]:        413 :   if (section != NULL)
    1157                 :            :     {
    1158                 :            :       /* Try to extract the section from a cached file before querying
    1159                 :            :          any servers.  */
    1160                 :          8 :       rc = cache_find_section (section, target_cache_dir, path);
    1161                 :            : 
    1162                 :            :       /* If the section was found or confirmed to not exist, then we
    1163                 :            :          are done.  */
    1164         [ +  + ]:          8 :       if (rc >= 0 || rc == -ENOENT)
    1165                 :          4 :         goto out;
    1166                 :            :     }
    1167                 :            : 
    1168                 :        409 :   long timeout = default_timeout;
    1169                 :        409 :   const char* timeout_envvar = getenv(DEBUGINFOD_TIMEOUT_ENV_VAR);
    1170         [ -  + ]:        409 :   if (timeout_envvar != NULL)
    1171                 :          0 :     timeout = atoi (timeout_envvar);
    1172                 :            : 
    1173         [ +  + ]:        409 :   if (vfd >= 0)
    1174                 :         14 :     dprintf (vfd, "using timeout %ld\n", timeout);
    1175                 :            : 
    1176                 :            :   /* make a copy of the envvar so it can be safely modified.  */
    1177                 :        409 :   server_urls = strdup(urls_envvar);
    1178         [ -  + ]:        409 :   if (server_urls == NULL)
    1179                 :            :     {
    1180                 :          0 :       rc = -ENOMEM;
    1181                 :          0 :       goto out;
    1182                 :            :     }
    1183                 :            :   /* thereafter, goto out0 on error*/
    1184                 :            : 
    1185                 :            :   /* Because of a race with cache cleanup / rmdir, try to mkdir/mkstemp up to twice. */
    1186         [ +  - ]:        409 :   for(int i=0; i<2; i++) {
    1187                 :            :     /* (re)create target directory in cache */
    1188                 :        409 :     (void) mkdir(target_cache_dir, 0700); /* files will be 0400 later */
    1189                 :            : 
    1190                 :            :     /* NB: write to a temporary file first, to avoid race condition of
    1191                 :            :        multiple clients checking the cache, while a partially-written or empty
    1192                 :            :        file is in there, being written from libcurl. */
    1193                 :        409 :     fd = mkstemp (target_cache_tmppath);
    1194         [ -  + ]:        409 :     if (fd >= 0) break;
    1195                 :            :   }
    1196         [ -  + ]:        409 :   if (fd < 0) /* Still failed after two iterations. */
    1197                 :            :     {
    1198                 :          0 :       rc = -errno;
    1199                 :          0 :       goto out0;
    1200                 :            :     }
    1201                 :            : 
    1202                 :            :   /* Initialize the memory to zero */
    1203                 :        409 :   char *strtok_saveptr;
    1204                 :        409 :   char **server_url_list = NULL;
    1205                 :        409 :   char *server_url = strtok_r(server_urls, url_delim, &strtok_saveptr);
    1206                 :            :   /* Count number of URLs.  */
    1207                 :        409 :   int num_urls = 0;
    1208                 :            : 
    1209         [ +  + ]:        845 :   while (server_url != NULL)
    1210                 :            :     {
    1211                 :            :       /* PR 27983: If the url is already set to be used use, skip it */
    1212                 :        436 :       char *slashbuildid;
    1213   [ +  -  +  + ]:        436 :       if (strlen(server_url) > 1 && server_url[strlen(server_url)-1] == '/')
    1214                 :            :         slashbuildid = "buildid";
    1215                 :            :       else
    1216                 :        406 :         slashbuildid = "/buildid";
    1217                 :            : 
    1218                 :        436 :       char *tmp_url;
    1219         [ -  + ]:        436 :       if (asprintf(&tmp_url, "%s%s", server_url, slashbuildid) == -1)
    1220                 :            :         {
    1221                 :          0 :           rc = -ENOMEM;
    1222                 :          0 :           goto out1;
    1223                 :            :         }
    1224                 :            :       int url_index;
    1225         [ +  + ]:        497 :       for (url_index = 0; url_index < num_urls; ++url_index)
    1226                 :            :         {
    1227         [ +  + ]:         63 :           if(strcmp(tmp_url, server_url_list[url_index]) == 0)
    1228                 :            :             {
    1229                 :            :               url_index = -1;
    1230                 :            :               break;
    1231                 :            :             }
    1232                 :            :         }
    1233         [ +  + ]:        436 :       if (url_index == -1)
    1234                 :            :         {
    1235         [ +  - ]:          2 :           if (vfd >= 0)
    1236                 :          2 :             dprintf(vfd, "duplicate url: %s, skipping\n", tmp_url);
    1237                 :          2 :           free(tmp_url);
    1238                 :            :         }
    1239                 :            :       else
    1240                 :            :         {
    1241                 :        434 :           num_urls++;
    1242                 :        434 :           char ** realloc_ptr;
    1243                 :        434 :           realloc_ptr = reallocarray(server_url_list, num_urls,
    1244                 :            :                                          sizeof(char*));
    1245         [ -  + ]:        434 :           if (realloc_ptr == NULL)
    1246                 :            :             {
    1247                 :          0 :               free (tmp_url);
    1248                 :          0 :               rc = -ENOMEM;
    1249                 :          0 :               goto out1;
    1250                 :            :             }
    1251                 :        434 :           server_url_list = realloc_ptr;
    1252                 :        434 :           server_url_list[num_urls-1] = tmp_url;
    1253                 :            :         }
    1254                 :        436 :       server_url = strtok_r(NULL, url_delim, &strtok_saveptr);
    1255                 :            :     }
    1256                 :            : 
    1257                 :        409 :   int retry_limit = default_retry_limit;
    1258                 :        409 :   const char* retry_limit_envvar = getenv(DEBUGINFOD_RETRY_LIMIT_ENV_VAR);
    1259         [ +  + ]:        409 :   if (retry_limit_envvar != NULL)
    1260                 :          2 :     retry_limit = atoi (retry_limit_envvar);
    1261                 :            : 
    1262                 :        409 :   CURLM *curlm = c->server_mhandle;
    1263         [ -  + ]:        409 :   assert (curlm != NULL);
    1264                 :            : 
    1265                 :            :   /* Tracks which handle should write to fd. Set to the first
    1266                 :            :      handle that is ready to write the target file to the cache.  */
    1267                 :        409 :   CURL *target_handle = NULL;
    1268                 :        409 :   struct handle_data *data = malloc(sizeof(struct handle_data) * num_urls);
    1269         [ -  + ]:        409 :   if (data == NULL)
    1270                 :            :     {
    1271                 :          0 :       rc = -ENOMEM;
    1272                 :          0 :       goto out1;
    1273                 :            :     }
    1274                 :            : 
    1275                 :            :   /* thereafter, goto out2 on error.  */
    1276                 :            : 
    1277                 :            :  /*The beginning of goto block query_in_parallel.*/
    1278                 :        409 :  query_in_parallel:
    1279                 :        953 :   rc = -ENOENT; /* Reset rc to default.*/
    1280                 :            : 
    1281                 :            :   /* Initialize handle_data with default values. */
    1282         [ +  + ]:       1933 :   for (int i = 0; i < num_urls; i++)
    1283                 :            :     {
    1284                 :        980 :       data[i].handle = NULL;
    1285                 :        980 :       data[i].fd = -1;
    1286                 :        980 :       data[i].errbuf[0] = '\0';
    1287                 :        980 :       data[i].response_data = NULL;
    1288                 :        980 :       data[i].response_data_size = 0;
    1289                 :            :     }
    1290                 :            : 
    1291                 :        953 :   char *escaped_string = NULL;
    1292                 :        953 :   size_t escaped_strlen = 0;
    1293         [ +  + ]:        953 :   if (filename)
    1294                 :            :     {
    1295                 :         29 :       escaped_string = curl_easy_escape(&target_handle, filename+1, 0);
    1296         [ -  + ]:         29 :       if (!escaped_string)
    1297                 :            :         {
    1298                 :          0 :           rc = -ENOMEM;
    1299                 :          0 :           goto out2;
    1300                 :            :         }
    1301                 :         29 :       char *loc = escaped_string;
    1302                 :         29 :       escaped_strlen = strlen(escaped_string);
    1303         [ +  + ]:        191 :       while ((loc = strstr(loc, "%2F")))
    1304                 :            :         {
    1305                 :        162 :           loc[0] = '/';
    1306                 :            :           //pull the string back after replacement
    1307                 :            :           // loc-escaped_string finds the distance from the origin to the new location
    1308                 :            :           // - 2 accounts for the 2F which remain and don't need to be measured.
    1309                 :            :           // The two above subtracted from escaped_strlen yields the remaining characters
    1310                 :            :           // in the string which we want to pull back
    1311                 :        162 :           memmove(loc+1, loc+3,escaped_strlen - (loc-escaped_string) - 2);
    1312                 :            :           //Because the 2F was overwritten in the memmove (as desired) escaped_strlen is
    1313                 :            :           // now two shorter.
    1314                 :        162 :           escaped_strlen -= 2;
    1315                 :            :         }
    1316                 :            :     }
    1317                 :            :   /* Initialize each handle.  */
    1318         [ +  + ]:       1933 :   for (int i = 0; i < num_urls; i++)
    1319                 :            :     {
    1320         [ +  - ]:        980 :       if ((server_url = server_url_list[i]) == NULL)
    1321                 :            :         break;
    1322         [ +  + ]:        980 :       if (vfd >= 0)
    1323                 :         29 :         dprintf (vfd, "init server %d %s\n", i, server_url);
    1324                 :            : 
    1325                 :        980 :       data[i].fd = fd;
    1326                 :        980 :       data[i].target_handle = &target_handle;
    1327                 :        980 :       data[i].handle = curl_easy_init();
    1328         [ -  + ]:        980 :       if (data[i].handle == NULL)
    1329                 :            :         {
    1330         [ #  # ]:          0 :           if (filename) curl_free (escaped_string);
    1331                 :          0 :           rc = -ENETUNREACH;
    1332                 :          0 :           goto out2;
    1333                 :            :         }
    1334                 :        980 :       data[i].client = c;
    1335                 :            : 
    1336         [ +  + ]:        980 :       if (filename) /* must start with / */
    1337                 :            :         {
    1338                 :            :           /* PR28034 escape characters in completed url to %hh format. */
    1339                 :         29 :           snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
    1340                 :            :                    build_id_bytes, type, escaped_string);
    1341                 :            :         }
    1342         [ +  + ]:        951 :       else if (section)
    1343                 :          4 :         snprintf(data[i].url, PATH_MAX, "%s/%s/%s/%s", server_url,
    1344                 :            :                  build_id_bytes, type, section);
    1345                 :            :       else
    1346                 :        947 :         snprintf(data[i].url, PATH_MAX, "%s/%s/%s", server_url, build_id_bytes, type);
    1347         [ +  + ]:        980 :       if (vfd >= 0)
    1348                 :         29 :         dprintf (vfd, "url %d %s\n", i, data[i].url);
    1349                 :            : 
    1350                 :            :       /* Some boilerplate for checking curl_easy_setopt.  */
    1351                 :            : #define curl_easy_setopt_ck(H,O,P) do {                 \
    1352                 :            :       CURLcode curl_res = curl_easy_setopt (H,O,P);     \
    1353                 :            :       if (curl_res != CURLE_OK)                         \
    1354                 :            :         {                                               \
    1355                 :            :           if (vfd >= 0)                                      \
    1356                 :            :             dprintf (vfd,                               \
    1357                 :            :                      "Bad curl_easy_setopt: %s\n",    \
    1358                 :            :                      curl_easy_strerror(curl_res));     \
    1359                 :            :           rc = -EINVAL;                                 \
    1360                 :            :           goto out2;                                    \
    1361                 :            :         }                                               \
    1362                 :            :       } while (0)
    1363                 :            : 
    1364                 :            :       /* Only allow http:// + https:// + file:// so we aren't being
    1365                 :            :          redirected to some unsupported protocol.  */
    1366                 :            : #if CURL_AT_LEAST_VERSION(7, 85, 0)
    1367   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_PROTOCOLS_STR,
    1368                 :            :                           "http,https,file");
    1369                 :            : #else
    1370                 :            :       curl_easy_setopt_ck(data[i].handle, CURLOPT_PROTOCOLS,
    1371                 :            :                           (CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FILE));
    1372                 :            : #endif
    1373   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_URL, data[i].url);
    1374         [ +  + ]:        980 :       if (vfd >= 0)
    1375         [ -  + ]:         29 :         curl_easy_setopt_ck(data[i].handle, CURLOPT_ERRORBUFFER,
    1376                 :            :                             data[i].errbuf);
    1377   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle,
    1378                 :            :                           CURLOPT_WRITEFUNCTION,
    1379                 :            :                           debuginfod_write_callback);
    1380   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_WRITEDATA, (void*)&data[i]);
    1381         [ +  - ]:        980 :       if (timeout > 0)
    1382                 :            :         {
    1383                 :            :           /* Make sure there is at least some progress,
    1384                 :            :              try to get at least 100K per timeout seconds.  */
    1385   [ -  +  -  - ]:        980 :           curl_easy_setopt_ck (data[i].handle, CURLOPT_LOW_SPEED_TIME,
    1386                 :            :                                timeout);
    1387   [ -  +  -  - ]:        980 :           curl_easy_setopt_ck (data[i].handle, CURLOPT_LOW_SPEED_LIMIT,
    1388                 :            :                                100 * 1024L);
    1389                 :            :         }
    1390   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_FILETIME, (long) 1);
    1391   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_FOLLOWLOCATION, (long) 1);
    1392   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_FAILONERROR, (long) 1);
    1393   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_NOSIGNAL, (long) 1);
    1394   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_HEADERFUNCTION,
    1395                 :            :                           header_callback);
    1396   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_HEADERDATA,
    1397                 :            :                           (void *) &(data[i]));
    1398                 :            : #if LIBCURL_VERSION_NUM >= 0x072a00 /* 7.42.0 */
    1399   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_PATH_AS_IS, (long) 1);
    1400                 :            : #else
    1401                 :            :       /* On old curl; no big deal, canonicalization here is almost the
    1402                 :            :          same, except perhaps for ? # type decorations at the tail. */
    1403                 :            : #endif
    1404   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_AUTOREFERER, (long) 1);
    1405   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_ACCEPT_ENCODING, "");
    1406   [ -  +  -  - ]:        980 :       curl_easy_setopt_ck(data[i].handle, CURLOPT_HTTPHEADER, c->headers);
    1407                 :            : 
    1408                 :        980 :       curl_multi_add_handle(curlm, data[i].handle);
    1409                 :            :     }
    1410                 :            : 
    1411         [ +  + ]:        953 :   if (filename) curl_free(escaped_string);
    1412                 :            :   /* Query servers in parallel.  */
    1413         [ +  + ]:        953 :   if (vfd >= 0)
    1414                 :         26 :     dprintf (vfd, "query %d urls in parallel\n", num_urls);
    1415                 :        953 :   int still_running;
    1416                 :        953 :   long loops = 0;
    1417                 :        953 :   int committed_to = -1;
    1418                 :        953 :   bool verbose_reported = false;
    1419                 :        953 :   struct timespec start_time, cur_time;
    1420                 :            : 
    1421                 :        953 :   free (c->winning_headers);
    1422                 :        953 :   c->winning_headers = NULL;
    1423   [ +  +  -  + ]:        953 :   if ( maxtime > 0 && clock_gettime(CLOCK_MONOTONIC_RAW, &start_time) == -1)
    1424                 :            :     {
    1425                 :          0 :       rc = -errno;
    1426                 :          0 :       goto out2;
    1427                 :            :     }
    1428                 :       2018 :   long delta = 0;
    1429                 :       2018 :   do
    1430                 :            :     {
    1431                 :            :       /* Check to see how long querying is taking. */
    1432         [ +  + ]:       2018 :       if (maxtime > 0)
    1433                 :            :         {
    1434         [ -  + ]:          3 :           if (clock_gettime(CLOCK_MONOTONIC_RAW, &cur_time) == -1)
    1435                 :            :             {
    1436                 :          0 :               rc = -errno;
    1437                 :          0 :               goto out2;
    1438                 :            :             }
    1439                 :          3 :           delta = cur_time.tv_sec - start_time.tv_sec;
    1440         [ -  + ]:          3 :           if ( delta >  maxtime)
    1441                 :            :             {
    1442                 :          0 :               dprintf(vfd, "Timeout with max time=%lds and transfer time=%lds\n", maxtime, delta );
    1443                 :          0 :               rc = -ETIME;
    1444                 :          0 :               goto out2;
    1445                 :            :             }
    1446                 :            :         }
    1447                 :            :       /* Wait 1 second, the minimum DEBUGINFOD_TIMEOUT.  */
    1448                 :       2018 :       curl_multi_wait(curlm, NULL, 0, 1000, NULL);
    1449                 :       2018 :       CURLMcode curlm_res = curl_multi_perform(curlm, &still_running);
    1450                 :            : 
    1451                 :            :       /* If the target file has been found, abort the other queries.  */
    1452         [ +  + ]:       2018 :       if (target_handle != NULL)
    1453                 :            :         {
    1454         [ +  + ]:        366 :           for (int i = 0; i < num_urls; i++)
    1455         [ +  + ]:        219 :             if (data[i].handle != target_handle)
    1456                 :         72 :               curl_multi_remove_handle(curlm, data[i].handle);
    1457                 :            :             else
    1458                 :            :               {
    1459                 :        147 :                 committed_to = i;
    1460         [ +  + ]:        147 :                 if (c->winning_headers == NULL)
    1461                 :            :                   {
    1462                 :        121 :                     c->winning_headers = data[committed_to].response_data;
    1463                 :        121 :                     data[committed_to].response_data = NULL;
    1464                 :        121 :                     data[committed_to].response_data_size = 0;
    1465                 :            :                   }
    1466                 :            : 
    1467                 :            :               }
    1468                 :            :         }
    1469                 :            : 
    1470   [ +  +  +  + ]:       2018 :       if (vfd >= 0 && !verbose_reported && committed_to >= 0)
    1471                 :            :         {
    1472   [ -  +  -  - ]:         18 :           bool pnl = (c->default_progressfn_printed_p && vfd == STDERR_FILENO);
    1473                 :          9 :           dprintf (vfd, "%scommitted to url %d\n", pnl ? "\n" : "",
    1474                 :            :                    committed_to);
    1475         [ -  + ]:          9 :           if (pnl)
    1476                 :          0 :             c->default_progressfn_printed_p = 0;
    1477                 :            :           verbose_reported = true;
    1478                 :            :         }
    1479                 :            : 
    1480         [ -  + ]:       2018 :       if (curlm_res != CURLM_OK)
    1481                 :            :         {
    1482      [ #  #  # ]:          0 :           switch (curlm_res)
    1483                 :            :             {
    1484                 :          0 :             case CURLM_CALL_MULTI_PERFORM: continue;
    1485                 :            :             case CURLM_OUT_OF_MEMORY: rc = -ENOMEM; break;
    1486                 :          0 :             default: rc = -ENETUNREACH; break;
    1487                 :            :             }
    1488                 :          0 :           goto out2;
    1489                 :            :         }
    1490                 :            : 
    1491                 :       2018 :       long dl_size = -1;
    1492   [ +  +  +  +  :       2018 :       if (target_handle && (c->progressfn || maxsize > 0))
                   -  + ]
    1493                 :            :         {
    1494                 :            :           /* Get size of file being downloaded. NB: If going through
    1495                 :            :              deflate-compressing proxies, this number is likely to be
    1496                 :            :              unavailable, so -1 may show. */
    1497                 :         13 :           CURLcode curl_res;
    1498                 :            : #if CURL_AT_LEAST_VERSION(7, 55, 0)
    1499                 :         13 :           curl_off_t cl;
    1500                 :         13 :           curl_res = curl_easy_getinfo(target_handle,
    1501                 :            :                                        CURLINFO_CONTENT_LENGTH_DOWNLOAD_T,
    1502                 :            :                                        &cl);
    1503   [ +  -  -  + ]:         13 :           if (curl_res == CURLE_OK && cl >= 0)
    1504                 :            :             dl_size = (cl > LONG_MAX ? LONG_MAX : (long)cl);
    1505                 :            : #else
    1506                 :            :           double cl;
    1507                 :            :           curl_res = curl_easy_getinfo(target_handle,
    1508                 :            :                                        CURLINFO_CONTENT_LENGTH_DOWNLOAD,
    1509                 :            :                                        &cl);
    1510                 :            :           if (curl_res == CURLE_OK && cl >= 0)
    1511                 :            :             dl_size = (cl >= (double)(LONG_MAX+1UL) ? LONG_MAX : (long)cl);
    1512                 :            : #endif
    1513                 :            :           /* If Content-Length is -1, try to get the size from
    1514                 :            :              X-Debuginfod-Size */
    1515         [ #  # ]:          0 :           if (dl_size == -1 && c->winning_headers != NULL)
    1516                 :            :             {
    1517                 :          0 :               long xdl;
    1518                 :          0 :               char *hdr = strcasestr(c->winning_headers, "x-debuginfod-size");
    1519                 :          0 :               size_t off = strlen("x-debuginfod-size:");
    1520                 :            : 
    1521   [ #  #  #  # ]:          0 :               if (hdr != NULL && sscanf(hdr + off, "%ld", &xdl) == 1)
    1522                 :          0 :                 dl_size = xdl;
    1523                 :            :             }
    1524                 :            :         }
    1525                 :            : 
    1526         [ +  + ]:       2018 :       if (c->progressfn) /* inform/check progress callback */
    1527                 :            :         {
    1528                 :       1665 :           loops ++;
    1529                 :       1665 :           long pa = loops; /* default param for progress callback */
    1530         [ +  + ]:       1665 :           if (target_handle) /* we've committed to a server; report its download progress */
    1531                 :            :             {
    1532                 :         13 :               CURLcode curl_res;
    1533                 :            : #if CURL_AT_LEAST_VERSION(7, 55, 0)
    1534                 :         13 :               curl_off_t dl;
    1535                 :         13 :               curl_res = curl_easy_getinfo(target_handle,
    1536                 :            :                                            CURLINFO_SIZE_DOWNLOAD_T,
    1537                 :            :                                            &dl);
    1538   [ -  +  -  + ]:         13 :               if (curl_res == 0 && dl >= 0)
    1539                 :         13 :                 pa = (dl > LONG_MAX ? LONG_MAX : (long)dl);
    1540                 :            : #else
    1541                 :            :               double dl;
    1542                 :            :               curl_res = curl_easy_getinfo(target_handle,
    1543                 :            :                                            CURLINFO_SIZE_DOWNLOAD,
    1544                 :            :                                            &dl);
    1545                 :            :               if (curl_res == 0)
    1546                 :            :                 pa = (dl >= (double)(LONG_MAX+1UL) ? LONG_MAX : (long)dl);
    1547                 :            : #endif
    1548                 :            : 
    1549                 :            :             }
    1550                 :            : 
    1551   [ +  +  -  + ]:       3317 :           if ((*c->progressfn) (c, pa, dl_size == -1 ? 0 : dl_size))
    1552                 :            :             {
    1553                 :          0 :               c->progressfn_cancel = true;
    1554                 :          0 :               break;
    1555                 :            :             }
    1556                 :            :         }
    1557                 :            : 
    1558                 :            :       /* Check to see if we are downloading something which exceeds maxsize, if set.*/
    1559   [ +  +  -  + ]:       2018 :       if (target_handle && dl_size > maxsize && maxsize > 0)
    1560                 :            :         {
    1561         [ #  # ]:          0 :           if (vfd >=0)
    1562                 :          0 :             dprintf(vfd, "Content-Length too large.\n");
    1563                 :          0 :           rc = -EFBIG;
    1564                 :          0 :           goto out2;
    1565                 :            :         }
    1566         [ +  + ]:       2018 :     } while (still_running);
    1567                 :            : 
    1568                 :            :   /* Check whether a query was successful. If so, assign its handle
    1569                 :            :      to verified_handle.  */
    1570                 :            :   int num_msg;
    1571                 :            :   rc = -ENOENT;
    1572                 :        956 :   CURL *verified_handle = NULL;
    1573                 :        956 :   do
    1574                 :            :     {
    1575                 :        956 :       CURLMsg *msg;
    1576                 :            : 
    1577                 :        956 :       msg = curl_multi_info_read(curlm, &num_msg);
    1578   [ +  -  +  - ]:        956 :       if (msg != NULL && msg->msg == CURLMSG_DONE)
    1579                 :            :         {
    1580         [ +  + ]:        956 :           if (vfd >= 0)
    1581                 :            :             {
    1582                 :         58 :               bool pnl = (c->default_progressfn_printed_p
    1583   [ -  +  -  - ]:         29 :                           && vfd == STDERR_FILENO);
    1584         [ +  - ]:         29 :               dprintf (vfd, "%sserver response %s\n", pnl ? "\n" : "",
    1585                 :            :                        curl_easy_strerror (msg->data.result));
    1586         [ -  + ]:         29 :               if (pnl)
    1587                 :          0 :                 c->default_progressfn_printed_p = 0;
    1588         [ +  - ]:         32 :               for (int i = 0; i < num_urls; i++)
    1589         [ +  + ]:         32 :                 if (msg->easy_handle == data[i].handle)
    1590                 :            :                   {
    1591         [ +  + ]:         29 :                     if (strlen (data[i].errbuf) > 0)
    1592                 :         19 :                       dprintf (vfd, "url %d %s\n", i, data[i].errbuf);
    1593                 :            :                     break;
    1594                 :            :                   }
    1595                 :            :             }
    1596                 :            : 
    1597         [ +  + ]:        956 :           if (msg->data.result != CURLE_OK)
    1598                 :            :             {
    1599                 :        835 :               long resp_code;
    1600                 :        835 :               CURLcode ok0;
    1601                 :            :               /* Unsuccessful query, determine error code.  */
    1602   [ -  +  -  -  :        835 :               switch (msg->data.result)
          -  -  -  -  +  
                   +  - ]
    1603                 :            :                 {
    1604                 :            :                 case CURLE_COULDNT_RESOLVE_HOST: rc = -EHOSTUNREACH; break; // no NXDOMAIN
    1605                 :          0 :                 case CURLE_URL_MALFORMAT: rc = -EINVAL; break;
    1606                 :        812 :                 case CURLE_COULDNT_CONNECT: rc = -ECONNREFUSED; break;
    1607                 :        812 :                 case CURLE_PEER_FAILED_VERIFICATION: rc = -ECONNREFUSED; break;
    1608                 :          0 :                 case CURLE_REMOTE_ACCESS_DENIED: rc = -EACCES; break;
    1609                 :          0 :                 case CURLE_WRITE_ERROR: rc = -EIO; break;
    1610                 :          0 :                 case CURLE_OUT_OF_MEMORY: rc = -ENOMEM; break;
    1611                 :          0 :                 case CURLE_TOO_MANY_REDIRECTS: rc = -EMLINK; break;
    1612                 :          0 :                 case CURLE_SEND_ERROR: rc = -ECONNRESET; break;
    1613                 :          0 :                 case CURLE_RECV_ERROR: rc = -ECONNRESET; break;
    1614                 :          0 :                 case CURLE_OPERATION_TIMEDOUT: rc = -ETIME; break;
    1615                 :            :                 case CURLE_HTTP_RETURNED_ERROR:
    1616                 :         22 :                   ok0 = curl_easy_getinfo (msg->easy_handle,
    1617                 :            :                                           CURLINFO_RESPONSE_CODE,
    1618                 :            :                                           &resp_code);
    1619                 :            :                   /* 406 signals that the requested file was too large */
    1620   [ +  -  +  + ]:         22 :                   if ( ok0 == CURLE_OK && resp_code == 406)
    1621                 :            :                     rc = -EFBIG;
    1622   [ -  +  -  - ]:         21 :                   else if (section != NULL && resp_code == 503)
    1623                 :            :                     rc = -EINVAL;
    1624                 :            :                   else
    1625                 :         22 :                     rc = -ENOENT;
    1626                 :            :                   break;
    1627                 :         22 :                 default: rc = -ENOENT; break;
    1628                 :            :                 }
    1629                 :            :             }
    1630                 :            :           else
    1631                 :            :             {
    1632                 :            :               /* Query completed without an error. Confirm that the
    1633                 :            :                  response code is 200 when using HTTP/HTTPS and 0 when
    1634                 :            :                  using file:// and set verified_handle.  */
    1635                 :            : 
    1636         [ +  - ]:        121 :               if (msg->easy_handle != NULL)
    1637                 :            :                 {
    1638                 :        121 :                   char *effective_url = NULL;
    1639                 :        121 :                   long resp_code = 500;
    1640                 :        121 :                   CURLcode ok1 = curl_easy_getinfo (target_handle,
    1641                 :            :                                                     CURLINFO_EFFECTIVE_URL,
    1642                 :            :                                                     &effective_url);
    1643                 :        121 :                   CURLcode ok2 = curl_easy_getinfo (target_handle,
    1644                 :            :                                                     CURLINFO_RESPONSE_CODE,
    1645                 :            :                                                     &resp_code);
    1646   [ +  -  +  - ]:        121 :                   if(ok1 == CURLE_OK && ok2 == CURLE_OK && effective_url)
    1647                 :            :                     {
    1648         [ +  + ]:        121 :                       if (strncasecmp (effective_url, "HTTP", 4) == 0)
    1649         [ +  - ]:        120 :                         if (resp_code == 200)
    1650                 :            :                           {
    1651                 :        120 :                             verified_handle = msg->easy_handle;
    1652                 :        121 :                             break;
    1653                 :            :                           }
    1654         [ +  - ]:          1 :                       if (strncasecmp (effective_url, "FILE", 4) == 0)
    1655         [ +  - ]:          1 :                         if (resp_code == 0)
    1656                 :            :                           {
    1657                 :          1 :                             verified_handle = msg->easy_handle;
    1658                 :          1 :                             break;
    1659                 :            :                           }
    1660                 :            :                     }
    1661                 :            :                   /* - libcurl since 7.52.0 version start to support
    1662                 :            :                        CURLINFO_SCHEME;
    1663                 :            :                      - before 7.61.0, effective_url would give us a
    1664                 :            :                        url with upper case SCHEME added in the front;
    1665                 :            :                      - effective_url between 7.61 and 7.69 can be lack
    1666                 :            :                        of scheme if the original url doesn't include one;
    1667                 :            :                      - since version 7.69 effective_url will be provide
    1668                 :            :                        a scheme in lower case.  */
    1669                 :            :                   #if LIBCURL_VERSION_NUM >= 0x073d00 /* 7.61.0 */
    1670                 :            :                   #if LIBCURL_VERSION_NUM <= 0x074500 /* 7.69.0 */
    1671                 :            :                   char *scheme = NULL;
    1672                 :            :                   CURLcode ok3 = curl_easy_getinfo (target_handle,
    1673                 :            :                                                     CURLINFO_SCHEME,
    1674                 :            :                                                     &scheme);
    1675                 :            :                   if(ok3 == CURLE_OK && scheme)
    1676                 :            :                     {
    1677                 :            :                       if (startswith (scheme, "HTTP"))
    1678                 :            :                         if (resp_code == 200)
    1679                 :            :                           {
    1680                 :            :                             verified_handle = msg->easy_handle;
    1681                 :            :                             break;
    1682                 :            :                           }
    1683                 :            :                     }
    1684                 :            :                   #endif
    1685                 :            :                   #endif
    1686                 :            :                 }
    1687                 :            :             }
    1688                 :            :         }
    1689         [ +  + ]:        835 :     } while (num_msg > 0);
    1690                 :            : 
    1691                 :            :   /* Create an empty file in the cache if the query fails with ENOENT and
    1692                 :            :      it wasn't cancelled early.  */
    1693   [ +  +  +  - ]:        953 :   if (rc == -ENOENT && !c->progressfn_cancel)
    1694                 :            :     {
    1695                 :        140 :       int efd = open (target_cache_path, O_CREAT|O_EXCL, DEFFILEMODE);
    1696         [ +  + ]:        140 :       if (efd >= 0)
    1697                 :        139 :         close(efd);
    1698                 :            :     }
    1699         [ +  + ]:        813 :   else if (rc == -EFBIG)
    1700                 :          1 :     goto out2;
    1701                 :            : 
    1702                 :            :   /* If the verified_handle is NULL and rc != -ENOENT, the query fails with
    1703                 :            :    * an error code other than 404, then do several retry within the retry_limit.
    1704                 :            :    * Clean up all old handles and jump back to the beginning of query_in_parallel,
    1705                 :            :    * reinitialize handles and query again.*/
    1706         [ +  + ]:        952 :   if (verified_handle == NULL)
    1707                 :            :     {
    1708   [ +  +  +  + ]:        831 :       if (rc != -ENOENT && retry_limit-- > 0)
    1709                 :            :         {
    1710         [ +  + ]:        544 :           if (vfd >= 0)
    1711                 :         12 :             dprintf (vfd, "Retry failed query, %d attempt(s) remaining\n", retry_limit);
    1712                 :            :           /* remove all handles from multi */
    1713         [ +  + ]:       1090 :           for (int i = 0; i < num_urls; i++)
    1714                 :            :             {
    1715                 :        546 :               curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
    1716                 :        546 :               curl_easy_cleanup (data[i].handle);
    1717                 :        546 :               free(data[i].response_data);
    1718                 :            :             }
    1719                 :        544 :             free(c->winning_headers);
    1720                 :        544 :             c->winning_headers = NULL;
    1721                 :        544 :             goto query_in_parallel;
    1722                 :            :         }
    1723                 :            :       else
    1724                 :        287 :         goto out2;
    1725                 :            :     }
    1726                 :            : 
    1727         [ +  + ]:        121 :   if (vfd >= 0)
    1728                 :            :     {
    1729   [ +  -  -  - ]:         18 :       bool pnl = c->default_progressfn_printed_p && vfd == STDERR_FILENO;
    1730                 :          9 :       dprintf (vfd, "%sgot file from server\n", pnl ? "\n" : "");
    1731         [ -  + ]:          9 :       if (pnl)
    1732                 :          0 :         c->default_progressfn_printed_p = 0;
    1733                 :            :     }
    1734                 :            : 
    1735                 :            :   /* we've got one!!!! */
    1736                 :        121 :   time_t mtime;
    1737                 :            : #if defined(_TIME_BITS) && _TIME_BITS == 64
    1738                 :            :   CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME_T, (void*) &mtime);
    1739                 :            : #else
    1740                 :        121 :   CURLcode curl_res = curl_easy_getinfo(verified_handle, CURLINFO_FILETIME, (void*) &mtime);
    1741                 :            : #endif
    1742         [ +  - ]:        121 :   if (curl_res == CURLE_OK)
    1743                 :            :     {
    1744                 :        121 :       struct timespec tvs[2];
    1745                 :        121 :       tvs[0].tv_sec = 0;
    1746                 :        121 :       tvs[0].tv_nsec = UTIME_OMIT;
    1747                 :        121 :       tvs[1].tv_sec = mtime;
    1748                 :        121 :       tvs[1].tv_nsec = 0;
    1749                 :        121 :       (void) futimens (fd, tvs);  /* best effort */
    1750                 :            :     }
    1751                 :            : 
    1752                 :            :   /* PR27571: make cache files casually unwriteable; dirs are already 0700 */
    1753                 :        121 :   (void) fchmod(fd, 0400);
    1754                 :            :                 
    1755                 :            :   /* rename tmp->real */
    1756                 :        121 :   rc = rename (target_cache_tmppath, target_cache_path);
    1757         [ -  + ]:        121 :   if (rc < 0)
    1758                 :            :     {
    1759                 :          0 :       rc = -errno;
    1760                 :          0 :       goto out2;
    1761                 :            :       /* Perhaps we need not give up right away; could retry or something ... */
    1762                 :            :     }
    1763                 :            : 
    1764                 :            :   /* remove all handles from multi */
    1765         [ +  + ]:        266 :   for (int i = 0; i < num_urls; i++)
    1766                 :            :     {
    1767                 :        145 :       curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
    1768                 :        145 :       curl_easy_cleanup (data[i].handle);
    1769                 :        145 :       free (data[i].response_data);
    1770                 :            :     }
    1771                 :            : 
    1772         [ +  + ]:        266 :   for (int i = 0; i < num_urls; ++i)
    1773                 :        145 :     free(server_url_list[i]);
    1774                 :        121 :   free(server_url_list);
    1775                 :        121 :   free (data);
    1776                 :        121 :   free (server_urls);
    1777                 :            : 
    1778                 :            :   /* don't close fd - we're returning it */
    1779                 :            :   /* don't unlink the tmppath; it's already been renamed. */
    1780         [ +  + ]:        121 :   if (path != NULL)
    1781                 :        119 :    *path = strdup(target_cache_path);
    1782                 :            : 
    1783                 :        121 :   rc = fd;
    1784                 :        121 :   goto out;
    1785                 :            : 
    1786                 :            : /* error exits */
    1787                 :        288 :  out2:
    1788                 :            :   /* remove all handles from multi */
    1789         [ +  + ]:        577 :   for (int i = 0; i < num_urls; i++)
    1790                 :            :     {
    1791         [ +  - ]:        289 :       if (data[i].handle != NULL)
    1792                 :            :         {
    1793                 :        289 :           curl_multi_remove_handle(curlm, data[i].handle); /* ok to repeat */
    1794                 :        289 :           curl_easy_cleanup (data[i].handle);
    1795                 :        289 :           free (data[i].response_data);
    1796                 :            :         }
    1797                 :            :     }
    1798                 :            : 
    1799                 :        288 :   unlink (target_cache_tmppath);
    1800                 :        288 :   close (fd); /* before the rmdir, otherwise it'll fail */
    1801                 :        288 :   (void) rmdir (target_cache_dir); /* nop if not empty */
    1802                 :        288 :   free(data);
    1803                 :            : 
    1804                 :        288 :  out1:
    1805         [ +  + ]:        577 :   for (int i = 0; i < num_urls; ++i)
    1806                 :        289 :     free(server_url_list[i]);
    1807                 :        288 :   free(server_url_list);
    1808                 :            : 
    1809                 :        288 :  out0:
    1810                 :        288 :   free (server_urls);
    1811                 :            : 
    1812                 :            : /* general purpose exit */
    1813                 :        484 :  out:
    1814                 :            :   /* Reset sent headers */
    1815                 :        484 :   curl_slist_free_all (c->headers);
    1816                 :        484 :   c->headers = NULL;
    1817                 :        484 :   c->user_agent_set_p = 0;
    1818                 :            :   
    1819                 :            :   /* Conclude the last \r status line */
    1820                 :            :   /* Another possibility is to use the ANSI CSI n K EL "Erase in Line"
    1821                 :            :      code.  That way, the previously printed messages would be erased,
    1822                 :            :      and without a newline. */
    1823         [ +  + ]:        484 :   if (c->default_progressfn_printed_p)
    1824                 :          1 :     dprintf(STDERR_FILENO, "\n");
    1825                 :            : 
    1826         [ +  + ]:        484 :   if (vfd >= 0)
    1827                 :            :     {
    1828         [ +  + ]:         18 :       if (rc < 0)
    1829                 :          5 :         dprintf (vfd, "not found %s (err=%d)\n", strerror (-rc), rc);
    1830                 :            :       else
    1831                 :         13 :         dprintf (vfd, "found %s (fd=%d)\n", target_cache_path, rc);
    1832                 :            :     }
    1833                 :            : 
    1834                 :        484 :   free (cache_path);
    1835                 :        484 :   free (maxage_path);
    1836                 :        484 :   free (interval_path);
    1837                 :        484 :   free (cache_miss_path);
    1838                 :        484 :   free (target_cache_dir);
    1839                 :        484 :   free (target_cache_path);
    1840                 :        484 :   free (target_cache_tmppath);
    1841                 :        484 :   return rc;
    1842                 :            : }
    1843                 :            : 
    1844                 :            : 
    1845                 :            : 
    1846                 :            : /* See debuginfod.h  */
    1847                 :            : debuginfod_client  *
    1848                 :        189 : debuginfod_begin (void)
    1849                 :            : {
    1850                 :            :   /* Initialize libcurl lazily, but only once.  */
    1851                 :        189 :   pthread_once (&init_control, libcurl_init);
    1852                 :            : 
    1853                 :        189 :   debuginfod_client *client;
    1854                 :        189 :   size_t size = sizeof (struct debuginfod_client);
    1855                 :        189 :   client = calloc (1, size);
    1856                 :            : 
    1857         [ +  - ]:        189 :   if (client != NULL)
    1858                 :            :     {
    1859         [ +  + ]:        189 :       if (getenv(DEBUGINFOD_PROGRESS_ENV_VAR))
    1860                 :          1 :         client->progressfn = default_progressfn;
    1861         [ +  + ]:        189 :       if (getenv(DEBUGINFOD_VERBOSE_ENV_VAR))
    1862                 :          1 :         client->verbose_fd = STDERR_FILENO;
    1863                 :            :       else
    1864                 :        188 :         client->verbose_fd = -1;
    1865                 :            : 
    1866                 :            :       // allocate 1 curl multi handle
    1867                 :        189 :       client->server_mhandle = curl_multi_init ();
    1868         [ -  + ]:        189 :       if (client->server_mhandle == NULL)
    1869                 :          0 :         goto out1;
    1870                 :            :     }
    1871                 :            : 
    1872                 :            :   // extra future initialization
    1873                 :            :   
    1874                 :        189 :   goto out;
    1875                 :            : 
    1876                 :          0 :  out1:
    1877                 :          0 :   free (client);
    1878                 :          0 :   client = NULL;
    1879                 :            : 
    1880                 :        189 :  out:  
    1881                 :        189 :   return client;
    1882                 :            : }
    1883                 :            : 
    1884                 :            : void
    1885                 :        176 : debuginfod_set_user_data(debuginfod_client *client,
    1886                 :            :                          void *data)
    1887                 :            : {
    1888                 :        176 :   client->user_data = data;
    1889                 :        176 : }
    1890                 :            : 
    1891                 :            : void *
    1892                 :          0 : debuginfod_get_user_data(debuginfod_client *client)
    1893                 :            : {
    1894                 :          0 :   return client->user_data;
    1895                 :            : }
    1896                 :            : 
    1897                 :            : const char *
    1898                 :         21 : debuginfod_get_url(debuginfod_client *client)
    1899                 :            : {
    1900         [ +  + ]:          3 :   return client->url;
    1901                 :            : }
    1902                 :            : 
    1903                 :            : const char *
    1904                 :         20 : debuginfod_get_headers(debuginfod_client *client)
    1905                 :            : {
    1906                 :         20 :   return client->winning_headers;
    1907                 :            : }
    1908                 :            : 
    1909                 :            : void
    1910                 :        189 : debuginfod_end (debuginfod_client *client)
    1911                 :            : {
    1912         [ +  - ]:        189 :   if (client == NULL)
    1913                 :            :     return;
    1914                 :            : 
    1915                 :        189 :   curl_multi_cleanup (client->server_mhandle);
    1916                 :        189 :   curl_slist_free_all (client->headers);
    1917                 :        189 :   free (client->winning_headers);
    1918                 :        189 :   free (client->url);
    1919                 :        189 :   free (client);
    1920                 :            : }
    1921                 :            : 
    1922                 :            : int
    1923                 :        105 : debuginfod_find_debuginfo (debuginfod_client *client,
    1924                 :            :                            const unsigned char *build_id, int build_id_len,
    1925                 :            :                            char **path)
    1926                 :            : {
    1927                 :        105 :   return debuginfod_query_server(client, build_id, build_id_len,
    1928                 :            :                                  "debuginfo", NULL, path);
    1929                 :            : }
    1930                 :            : 
    1931                 :            : 
    1932                 :            : /* See debuginfod.h  */
    1933                 :            : int
    1934                 :        339 : debuginfod_find_executable(debuginfod_client *client,
    1935                 :            :                            const unsigned char *build_id, int build_id_len,
    1936                 :            :                            char **path)
    1937                 :            : {
    1938                 :        339 :   return debuginfod_query_server(client, build_id, build_id_len,
    1939                 :            :                                  "executable", NULL, path);
    1940                 :            : }
    1941                 :            : 
    1942                 :            : /* See debuginfod.h  */
    1943                 :         32 : int debuginfod_find_source(debuginfod_client *client,
    1944                 :            :                            const unsigned char *build_id, int build_id_len,
    1945                 :            :                            const char *filename, char **path)
    1946                 :            : {
    1947                 :         32 :   return debuginfod_query_server(client, build_id, build_id_len,
    1948                 :            :                                  "source", filename, path);
    1949                 :            : }
    1950                 :            : 
    1951                 :            : int
    1952                 :          8 : debuginfod_find_section (debuginfod_client *client,
    1953                 :            :                          const unsigned char *build_id, int build_id_len,
    1954                 :            :                          const char *section, char **path)
    1955                 :            : {
    1956                 :          8 :   int rc = debuginfod_query_server(client, build_id, build_id_len,
    1957                 :            :                                    "section", section, path);
    1958         [ -  + ]:          8 :   if (rc != -EINVAL)
    1959                 :            :     return rc;
    1960                 :            : 
    1961                 :            :   /* The servers may have lacked support for section queries.  Attempt to
    1962                 :            :      download the debuginfo or executable containing the section in order
    1963                 :            :      to extract it.  */
    1964                 :          0 :   rc = -EEXIST;
    1965                 :          0 :   int fd = -1;
    1966                 :          0 :   char *tmp_path = NULL;
    1967                 :            : 
    1968                 :          0 :   fd = debuginfod_find_debuginfo (client, build_id, build_id_len, &tmp_path);
    1969         [ #  # ]:          0 :   if (client->progressfn_cancel)
    1970                 :            :     {
    1971         [ #  # ]:          0 :       if (fd >= 0)
    1972                 :            :         {
    1973                 :            :           /* This shouldn't happen, but we'll check this condition
    1974                 :            :              just in case.  */
    1975                 :          0 :           close (fd);
    1976                 :          0 :           free (tmp_path);
    1977                 :            :         }
    1978                 :          0 :       return -ENOENT;
    1979                 :            :     }
    1980         [ #  # ]:          0 :   if (fd >= 0)
    1981                 :            :     {
    1982                 :          0 :       rc = extract_section (fd, section, tmp_path, path);
    1983                 :          0 :       close (fd);
    1984                 :            :     }
    1985                 :            : 
    1986         [ #  # ]:          0 :   if (rc == -EEXIST)
    1987                 :            :     {
    1988                 :            :       /* Either the debuginfo couldn't be found or the section should
    1989                 :            :          be in the executable.  */
    1990                 :          0 :       fd = debuginfod_find_executable (client, build_id,
    1991                 :            :                                        build_id_len, &tmp_path);
    1992         [ #  # ]:          0 :       if (fd >= 0)
    1993                 :            :         {
    1994                 :          0 :           rc = extract_section (fd, section, tmp_path, path);
    1995                 :          0 :           close (fd);
    1996                 :            :         }
    1997                 :            :       else
    1998                 :            :         /* Update rc so that we return the most recent error code.  */
    1999                 :            :         rc = fd;
    2000                 :            :     }
    2001                 :            : 
    2002                 :          0 :   free (tmp_path);
    2003                 :          0 :   return rc;
    2004                 :            : }
    2005                 :            : 
    2006                 :            : /* Add an outgoing HTTP header.  */
    2007                 :        794 : int debuginfod_add_http_header (debuginfod_client *client, const char* header)
    2008                 :            : {
    2009                 :            :   /* Sanity check header value is of the form Header: Value.
    2010                 :            :      It should contain at least one colon that isn't the first or
    2011                 :            :      last character.  */
    2012                 :        794 :   char *colon = strchr (header, ':'); /* first colon */
    2013                 :        794 :   if (colon == NULL /* present */
    2014         [ +  - ]:        794 :       || colon == header /* not at beginning - i.e., have a header name */
    2015         [ +  - ]:        794 :       || *(colon + 1) == '\0') /* not at end - i.e., have a value */
    2016                 :            :     /* NB: but it's okay for a value to contain other colons! */
    2017                 :            :     return -EINVAL;
    2018                 :            : 
    2019                 :        794 :   struct curl_slist *temp = curl_slist_append (client->headers, header);
    2020         [ +  - ]:        794 :   if (temp == NULL)
    2021                 :            :     return -ENOMEM;
    2022                 :            : 
    2023                 :            :   /* Track if User-Agent: is being set.  If so, signal not to add the
    2024                 :            :      default one. */
    2025         [ +  + ]:        794 :   if (startswith (header, "User-Agent:"))
    2026                 :        485 :     client->user_agent_set_p = 1;
    2027                 :            : 
    2028                 :        794 :   client->headers = temp;
    2029                 :        794 :   return 0;
    2030                 :            : }
    2031                 :            : 
    2032                 :            : 
    2033                 :            : void
    2034                 :        360 : debuginfod_set_progressfn(debuginfod_client *client,
    2035                 :            :                           debuginfod_progressfn_t fn)
    2036                 :            : {
    2037                 :        360 :   client->progressfn = fn;
    2038                 :        360 : }
    2039                 :            : 
    2040                 :            : void
    2041                 :         32 : debuginfod_set_verbose_fd(debuginfod_client *client, int fd)
    2042                 :            : {
    2043                 :         32 :   client->verbose_fd = fd;
    2044                 :         32 : }
    2045                 :            : 
    2046                 :            : #endif /* DUMMY_LIBDEBUGINFOD */

Generated by: LCOV version 1.16