LCOV - code coverage report
Current view: top level - debuginfod - debuginfod-client.c (source / functions) Hit Total Coverage
Test: elfutils-0.189 Lines: 715 894 80.0 %
Date: 2023-04-14 15:57:06 Functions: 24 26 92.3 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 401 661 60.7 %

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

Generated by: LCOV version 1.14