LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Hit Total Coverage
Test: elfutils-0.192 Lines: 2308 2750 83.9 %
Date: 2024-12-10 16:24:23 Functions: 104 115 90.4 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 2868 6826 42.0 %

           Branch data     Line data    Source code
       1                 :            : /* Debuginfo-over-http server.
       2                 :            :    Copyright (C) 2019-2024 Red Hat, Inc.
       3                 :            :    Copyright (C) 2021, 2022 Mark J. Wielaard <mark@klomp.org>
       4                 :            :    This file is part of elfutils.
       5                 :            : 
       6                 :            :    This file is free software; you can redistribute it and/or modify
       7                 :            :    it under the terms of the GNU General Public License as published by
       8                 :            :    the Free Software Foundation; either version 3 of the License, or
       9                 :            :    (at your option) any later version.
      10                 :            : 
      11                 :            :    elfutils is distributed in the hope that it will be useful, but
      12                 :            :    WITHOUT ANY WARRANTY; without even the implied warranty of
      13                 :            :    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      14                 :            :    GNU General Public License for more details.
      15                 :            : 
      16                 :            :    You should have received a copy of the GNU General Public License
      17                 :            :    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
      18                 :            : 
      19                 :            : 
      20                 :            : /* cargo-cult from libdwfl linux-kernel-modules.c */
      21                 :            : /* In case we have a bad fts we include this before config.h because it
      22                 :            :    can't handle _FILE_OFFSET_BITS.
      23                 :            :    Everything we need here is fine if its declarations just come first.
      24                 :            :    Also, include sys/types.h before fts. On some systems fts.h is not self
      25                 :            :    contained. */
      26                 :            : #ifdef BAD_FTS
      27                 :            :   #include <sys/types.h>
      28                 :            :   #include <fts.h>
      29                 :            : #endif
      30                 :            : 
      31                 :            : #ifdef HAVE_CONFIG_H
      32                 :            :   #include "config.h"
      33                 :            : #endif
      34                 :            : 
      35                 :            : // #define _GNU_SOURCE
      36                 :            : #ifdef HAVE_SCHED_H
      37                 :            : extern "C" {
      38                 :            : #include <sched.h>
      39                 :            : }
      40                 :            : #endif
      41                 :            : #ifdef HAVE_SYS_RESOURCE_H
      42                 :            : extern "C" {
      43                 :            : #include <sys/resource.h>
      44                 :            : }
      45                 :            : #endif
      46                 :            : 
      47                 :            : #ifdef HAVE_EXECINFO_H
      48                 :            : extern "C" {
      49                 :            : #include <execinfo.h>
      50                 :            : }
      51                 :            : #endif
      52                 :            : #ifdef HAVE_MALLOC_H
      53                 :            : extern "C" {
      54                 :            : #include <malloc.h>
      55                 :            : }
      56                 :            : #endif
      57                 :            : 
      58                 :            : #include "debuginfod.h"
      59                 :            : #include <dwarf.h>
      60                 :            : 
      61                 :            : #include <argp.h>
      62                 :            : #ifdef __GNUC__
      63                 :            : #undef __attribute__ /* glibc bug - rhbz 1763325 */
      64                 :            : #endif
      65                 :            : 
      66                 :            : #ifdef USE_LZMA
      67                 :            : #include <lzma.h>
      68                 :            : #endif
      69                 :            : 
      70                 :            : #include <unistd.h>
      71                 :            : #include <stdlib.h>
      72                 :            : #include <locale.h>
      73                 :            : #include <pthread.h>
      74                 :            : #include <signal.h>
      75                 :            : #include <sys/stat.h>
      76                 :            : #include <sys/time.h>
      77                 :            : #include <sys/vfs.h>
      78                 :            : #include <unistd.h>
      79                 :            : #include <fcntl.h>
      80                 :            : #include <netdb.h>
      81                 :            : #include <math.h>
      82                 :            : #include <float.h>
      83                 :            : #include <fnmatch.h>
      84                 :            : 
      85                 :            : 
      86                 :            : /* If fts.h is included before config.h, its indirect inclusions may not
      87                 :            :    give us the right LFS aliases of these functions, so map them manually.  */
      88                 :            : #ifdef BAD_FTS
      89                 :            :   #ifdef _FILE_OFFSET_BITS
      90                 :            :     #define open open64
      91                 :            :     #define fopen fopen64
      92                 :            :   #endif
      93                 :            : #else
      94                 :            :   #include <sys/types.h>
      95                 :            :   #include <fts.h>
      96                 :            : #endif
      97                 :            : 
      98                 :            : #include <cstring>
      99                 :            : #include <vector>
     100                 :            : #include <set>
     101                 :            : #include <unordered_set>
     102                 :            : #include <map>
     103                 :            : #include <string>
     104                 :            : #include <iostream>
     105                 :            : #include <iomanip>
     106                 :            : #include <ostream>
     107                 :            : #include <sstream>
     108                 :            : #include <mutex>
     109                 :            : #include <deque>
     110                 :            : #include <condition_variable>
     111                 :            : #include <exception>
     112                 :            : #include <thread>
     113                 :            : // #include <regex> // on rhel7 gcc 4.8, not competent
     114                 :            : #include <regex.h>
     115                 :            : // #include <algorithm>
     116                 :            : using namespace std;
     117                 :            : 
     118                 :            : #include <gelf.h>
     119                 :            : #include <libdwelf.h>
     120                 :            : 
     121                 :            : #include <microhttpd.h>
     122                 :            : 
     123                 :            : #if MHD_VERSION >= 0x00097002
     124                 :            : // libmicrohttpd 0.9.71 broke API
     125                 :            : #define MHD_RESULT enum MHD_Result
     126                 :            : #else
     127                 :            : #define MHD_RESULT int
     128                 :            : #endif
     129                 :            : 
     130                 :            : #ifdef ENABLE_IMA_VERIFICATION
     131                 :            :   #include <rpm/rpmlib.h>
     132                 :            :   #include <rpm/rpmfi.h>
     133                 :            :   #include <rpm/header.h>
     134                 :            :   #include <glob.h>
     135                 :            : #endif
     136                 :            : 
     137                 :            : #include <curl/curl.h>
     138                 :            : #include <archive.h>
     139                 :            : #include <archive_entry.h>
     140                 :            : #include <sqlite3.h>
     141                 :            : 
     142                 :            : #ifdef __linux__
     143                 :            : #include <sys/syscall.h>
     144                 :            : #endif
     145                 :            : 
     146                 :            : #ifdef __linux__
     147                 :            : #define tid() syscall(SYS_gettid)
     148                 :            : #else
     149                 :            : #define tid() pthread_self()
     150                 :            : #endif
     151                 :            : 
     152                 :            : extern "C" {
     153                 :            : #include "printversion.h"
     154                 :            : #include "system.h"
     155                 :            : }
     156                 :            : #include <json-c/json.h>
     157                 :            : 
     158                 :            : 
     159                 :            : inline bool
     160                 :     137044 : string_endswith(const string& haystack, const string& needle)
     161                 :            : {
     162         [ +  + ]:     137044 :   return (haystack.size() >= needle.size() &&
     163                 :     132043 :           equal(haystack.end()-needle.size(), haystack.end(),
     164                 :     137044 :                 needle.begin()));
     165                 :            : }
     166                 :            : 
     167                 :            : 
     168                 :            : // Roll this identifier for every sqlite schema incompatibility.
     169                 :            : #define BUILDIDS "buildids10"
     170                 :            : 
     171                 :            : #if SQLITE_VERSION_NUMBER >= 3008000
     172                 :            : #define WITHOUT_ROWID "without rowid"
     173                 :            : #else
     174                 :            : #define WITHOUT_ROWID ""
     175                 :            : #endif
     176                 :            : 
     177                 :            : static const char DEBUGINFOD_SQLITE_DDL[] =
     178                 :            :   "pragma foreign_keys = on;\n"
     179                 :            :   "pragma synchronous = 0;\n" // disable fsync()s - this cache is disposable across a machine crash
     180                 :            :   "pragma journal_mode = wal;\n" // https://sqlite.org/wal.html
     181                 :            :   "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
     182                 :            :   "pragma journal_size_limit = 0;\n" // limit steady state file (between grooming, which also =truncate's)
     183                 :            :   "pragma auto_vacuum = incremental;\n" // https://sqlite.org/pragma.html
     184                 :            :   "pragma busy_timeout = 1000;\n" // https://sqlite.org/pragma.html
     185                 :            :   // NB: all these are overridable with -D option
     186                 :            : 
     187                 :            :   // Normalization table for interning file names
     188                 :            :   "create table if not exists " BUILDIDS "_fileparts (\n"
     189                 :            :   "        id integer primary key not null,\n"
     190                 :            :   "        name text unique not null\n"
     191                 :            :   "        );\n"
     192                 :            :   "create table if not exists " BUILDIDS "_files (\n"
     193                 :            :   "        id integer primary key not null,\n"
     194                 :            :   "        dirname integer not null,\n"
     195                 :            :   "        basename integer not null,\n"
     196                 :            :   "        unique (dirname, basename),\n"
     197                 :            :   "        foreign key (dirname) references " BUILDIDS "_fileparts(id) on delete cascade,\n"
     198                 :            :   "        foreign key (basename) references " BUILDIDS "_fileparts(id) on delete cascade\n"
     199                 :            :   "        );\n"
     200                 :            :   "create view if not exists " BUILDIDS "_files_v as\n" // a 
     201                 :            :   "        select f.id, n1.name || '/' || n2.name as name\n"
     202                 :            :   "        from " BUILDIDS "_files f, " BUILDIDS "_fileparts n1, " BUILDIDS "_fileparts n2\n"
     203                 :            :   "        where f.dirname = n1.id and f.basename = n2.id;\n"
     204                 :            :   
     205                 :            :   // Normalization table for interning buildids
     206                 :            :   "create table if not exists " BUILDIDS "_buildids (\n"
     207                 :            :   "        id integer primary key not null,\n"
     208                 :            :   "        hex text unique not null);\n"
     209                 :            :   // Track the completion of scanning of a given file & sourcetype at given time
     210                 :            :   "create table if not exists " BUILDIDS "_file_mtime_scanned (\n"
     211                 :            :   "        mtime integer not null,\n"
     212                 :            :   "        file integer not null,\n"
     213                 :            :   "        size integer not null,\n" // in bytes
     214                 :            :   "        sourcetype text(1) not null\n"
     215                 :            :   "            check (sourcetype IN ('F', 'R')),\n"
     216                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     217                 :            :   "        primary key (file, mtime, sourcetype)\n"
     218                 :            :   "        ) " WITHOUT_ROWID ";\n"
     219                 :            :   "create table if not exists " BUILDIDS "_f_de (\n"
     220                 :            :   "        buildid integer not null,\n"
     221                 :            :   "        debuginfo_p integer not null,\n"
     222                 :            :   "        executable_p integer not null,\n"
     223                 :            :   "        file integer not null,\n"
     224                 :            :   "        mtime integer not null,\n"
     225                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     226                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     227                 :            :   "        primary key (buildid, file, mtime)\n"
     228                 :            :   "        ) " WITHOUT_ROWID ";\n"
     229                 :            :   // Index for faster delete by file identifier and metadata searches
     230                 :            :   "create index if not exists " BUILDIDS "_f_de_idx on " BUILDIDS "_f_de (file, mtime);\n"
     231                 :            :   "create table if not exists " BUILDIDS "_f_s (\n"
     232                 :            :   "        buildid integer not null,\n"
     233                 :            :   "        artifactsrc integer not null,\n"
     234                 :            :   "        file integer not null,\n" // NB: not necessarily entered into _mtime_scanned
     235                 :            :   "        mtime integer not null,\n"
     236                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     237                 :            :   "        foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     238                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     239                 :            :   "        primary key (buildid, artifactsrc, file, mtime)\n"
     240                 :            :   "        ) " WITHOUT_ROWID ";\n"
     241                 :            :   "create table if not exists " BUILDIDS "_r_de (\n"
     242                 :            :   "        buildid integer not null,\n"
     243                 :            :   "        debuginfo_p integer not null,\n"
     244                 :            :   "        executable_p integer not null,\n"
     245                 :            :   "        file integer not null,\n"
     246                 :            :   "        mtime integer not null,\n"
     247                 :            :   "        content integer not null,\n"
     248                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     249                 :            :   "        foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     250                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     251                 :            :   "        primary key (buildid, debuginfo_p, executable_p, file, content, mtime)\n"
     252                 :            :   "        ) " WITHOUT_ROWID ";\n"
     253                 :            :   // Index for faster delete by archive file identifier
     254                 :            :   "create index if not exists " BUILDIDS "_r_de_idx on " BUILDIDS "_r_de (file, mtime);\n"
     255                 :            :   // Index for metadata searches
     256                 :            :   "create index if not exists " BUILDIDS "_r_de_idx2 on " BUILDIDS "_r_de (content);\n"  
     257                 :            :   "create table if not exists " BUILDIDS "_r_sref (\n" // outgoing dwarf sourcefile references from rpm
     258                 :            :   "        buildid integer not null,\n"
     259                 :            :   "        artifactsrc integer not null,\n"
     260                 :            :   "        foreign key (artifactsrc) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     261                 :            :   "        foreign key (buildid) references " BUILDIDS "_buildids(id) on update cascade on delete cascade,\n"
     262                 :            :   "        primary key (buildid, artifactsrc)\n"
     263                 :            :   "        ) " WITHOUT_ROWID ";\n"
     264                 :            :   "create table if not exists " BUILDIDS "_r_sdef (\n" // rpm contents that may satisfy sref
     265                 :            :   "        file integer not null,\n"
     266                 :            :   "        mtime integer not null,\n"
     267                 :            :   "        content integer not null,\n"
     268                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     269                 :            :   "        foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     270                 :            :   "        primary key (content, file, mtime)\n"
     271                 :            :   "        ) " WITHOUT_ROWID ";\n"
     272                 :            :   "create table if not exists " BUILDIDS "_r_seekable (\n" // seekable rpm contents
     273                 :            :   "        file integer not null,\n"
     274                 :            :   "        content integer not null,\n"
     275                 :            :   "        type text not null,\n"
     276                 :            :   "        size integer not null,\n"
     277                 :            :   "        offset integer not null,\n"
     278                 :            :   "        mtime integer not null,\n"
     279                 :            :   "        foreign key (file) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     280                 :            :   "        foreign key (content) references " BUILDIDS "_files(id) on update cascade on delete cascade,\n"
     281                 :            :   "        primary key (file, content)\n"
     282                 :            :   "        ) " WITHOUT_ROWID ";\n"
     283                 :            :   // create views to glue together some of the above tables, for webapi D queries
     284                 :            :   // NB: _query_d2 and _query_e2 were added to replace _query_d and _query_e
     285                 :            :   // without updating BUILDIDS.  They can be renamed back the next time BUILDIDS
     286                 :            :   // is updated.
     287                 :            :   "create view if not exists " BUILDIDS "_query_d2 as \n"
     288                 :            :   "select\n"
     289                 :            :   "        b.hex as buildid, 'F' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, null as id1, null as source1\n"
     290                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
     291                 :            :   "        where b.id = n.buildid and f0.id = n.file and n.debuginfo_p = 1\n"
     292                 :            :   "union all select\n"
     293                 :            :   "        b.hex as buildid, 'R' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, n.content as id1, f1.name as source1\n"
     294                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
     295                 :            :   "        where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.debuginfo_p = 1\n"
     296                 :            :   ";"
     297                 :            :   // ... and for E queries
     298                 :            :   "create view if not exists " BUILDIDS "_query_e2 as \n"
     299                 :            :   "select\n"
     300                 :            :   "        b.hex as buildid, 'F' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, null as id1, null as source1\n"
     301                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_f_de n\n"
     302                 :            :   "        where b.id = n.buildid and f0.id = n.file and n.executable_p = 1\n"
     303                 :            :   "union all select\n"
     304                 :            :   "        b.hex as buildid, 'R' as sourcetype, n.file as id0, f0.name as source0, n.mtime as mtime, n.content as id1, f1.name as source1\n"
     305                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_r_de n\n"
     306                 :            :   "        where b.id = n.buildid and f0.id = n.file and f1.id = n.content and n.executable_p = 1\n"
     307                 :            :   ";"
     308                 :            :   // ... and for S queries
     309                 :            :   "create view if not exists " BUILDIDS "_query_s as \n"
     310                 :            :   "select\n"
     311                 :            :   "        b.hex as buildid, fs.name as artifactsrc, 'F' as sourcetype, f0.name as source0, n.mtime as mtime, null as source1, null as source0ref\n"
     312                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v fs, " BUILDIDS "_f_s n\n"
     313                 :            :   "        where b.id = n.buildid and f0.id = n.file and fs.id = n.artifactsrc\n"
     314                 :            :   "union all select\n"
     315                 :            :   "        b.hex as buildid, f1.name as artifactsrc, 'R' as sourcetype, f0.name as source0, sd.mtime as mtime, f1.name as source1, fsref.name as source0ref\n"
     316                 :            :   "        from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f0, " BUILDIDS "_files_v f1, " BUILDIDS "_files_v fsref, "
     317                 :            :   "        " BUILDIDS "_r_sdef sd, " BUILDIDS "_r_sref sr, " BUILDIDS "_r_de sde\n"
     318                 :            :   "        where b.id = sr.buildid and f0.id = sd.file and fsref.id = sde.file and f1.id = sd.content\n"
     319                 :            :   "        and sr.artifactsrc = sd.content and sde.buildid = sr.buildid\n"
     320                 :            :   ";"
     321                 :            :   // and for startup overview counts
     322                 :            :   "drop view if exists " BUILDIDS "_stats;\n"
     323                 :            :   "create view if not exists " BUILDIDS "_stats as\n"
     324                 :            :   "          select 'file d/e' as label,count(*) as quantity from " BUILDIDS "_f_de\n"
     325                 :            :   "union all select 'file s',count(*) from " BUILDIDS "_f_s\n"
     326                 :            :   "union all select 'archive d/e',count(*) from " BUILDIDS "_r_de\n"
     327                 :            :   "union all select 'archive sref',count(*) from " BUILDIDS "_r_sref\n"
     328                 :            :   "union all select 'archive sdef',count(*) from " BUILDIDS "_r_sdef\n"
     329                 :            :   "union all select 'buildids',count(*) from " BUILDIDS "_buildids\n"
     330                 :            :   "union all select 'filenames',count(*) from " BUILDIDS "_files\n"
     331                 :            :   "union all select 'fileparts',count(*) from " BUILDIDS "_fileparts\n"  
     332                 :            :   "union all select 'files scanned (#)',count(*) from " BUILDIDS "_file_mtime_scanned\n"
     333                 :            :   "union all select 'files scanned (mb)',coalesce(sum(size)/1024/1024,0) from " BUILDIDS "_file_mtime_scanned\n"
     334                 :            : #if SQLITE_VERSION_NUMBER >= 3016000
     335                 :            :   "union all select 'index db size (mb)',page_count*page_size/1024/1024 as size FROM pragma_page_count(), pragma_page_size()\n"
     336                 :            : #endif
     337                 :            :   ";\n"
     338                 :            : 
     339                 :            : // schema change history & garbage collection
     340                 :            : //
     341                 :            : // XXX: we could have migration queries here to bring prior-schema
     342                 :            : // data over instead of just dropping it.  But that could incur
     343                 :            : // doubled storage costs.
     344                 :            : //
     345                 :            : // buildids10: split the _files table into _parts
     346                 :            :   "" // <<< we are here
     347                 :            : // buildids9: widen the mtime_scanned table
     348                 :            :   "DROP VIEW IF EXISTS buildids9_stats;\n"
     349                 :            :   "DROP INDEX IF EXISTS buildids9_r_de_idx;\n"
     350                 :            :   "DROP INDEX IF EXISTS buildids9_f_de_idx;\n"
     351                 :            :   "DROP VIEW IF EXISTS buildids9_query_s;\n"
     352                 :            :   "DROP VIEW IF EXISTS buildids9_query_e;\n"
     353                 :            :   "DROP VIEW IF EXISTS buildids9_query_d;\n"
     354                 :            :   "DROP TABLE IF EXISTS buildids9_r_sdef;\n"
     355                 :            :   "DROP TABLE IF EXISTS buildids9_r_sref;\n"
     356                 :            :   "DROP TABLE IF EXISTS buildids9_r_de;\n"
     357                 :            :   "DROP TABLE IF EXISTS buildids9_f_s;\n"
     358                 :            :   "DROP TABLE IF EXISTS buildids9_f_de;\n"
     359                 :            :   "DROP TABLE IF EXISTS buildids9_file_mtime_scanned;\n"
     360                 :            :   "DROP TABLE IF EXISTS buildids9_buildids;\n"
     361                 :            :   "DROP TABLE IF EXISTS buildids9_files;\n"
     362                 :            : // buildids8: slim the sref table
     363                 :            :   "drop table if exists buildids8_f_de;\n"
     364                 :            :   "drop table if exists buildids8_f_s;\n"
     365                 :            :   "drop table if exists buildids8_r_de;\n"
     366                 :            :   "drop table if exists buildids8_r_sref;\n"
     367                 :            :   "drop table if exists buildids8_r_sdef;\n"
     368                 :            :   "drop table if exists buildids8_file_mtime_scanned;\n"
     369                 :            :   "drop table if exists buildids8_files;\n"
     370                 :            :   "drop table if exists buildids8_buildids;\n"
     371                 :            : // buildids7: separate _norm table into dense subtype tables
     372                 :            :   "drop table if exists buildids7_f_de;\n"
     373                 :            :   "drop table if exists buildids7_f_s;\n"
     374                 :            :   "drop table if exists buildids7_r_de;\n"
     375                 :            :   "drop table if exists buildids7_r_sref;\n"
     376                 :            :   "drop table if exists buildids7_r_sdef;\n"
     377                 :            :   "drop table if exists buildids7_file_mtime_scanned;\n"
     378                 :            :   "drop table if exists buildids7_files;\n"
     379                 :            :   "drop table if exists buildids7_buildids;\n"
     380                 :            : // buildids6: drop bolo/rfolo again, represent sources / rpmcontents in main table
     381                 :            :   "drop table if exists buildids6_norm;\n"
     382                 :            :   "drop table if exists buildids6_files;\n"
     383                 :            :   "drop table if exists buildids6_buildids;\n"
     384                 :            :   "drop view if exists buildids6;\n"
     385                 :            : // buildids5: redefine srcfile1 column to be '.'-less (for rpms)
     386                 :            :   "drop table if exists buildids5_norm;\n"
     387                 :            :   "drop table if exists buildids5_files;\n"
     388                 :            :   "drop table if exists buildids5_buildids;\n"
     389                 :            :   "drop table if exists buildids5_bolo;\n"
     390                 :            :   "drop table if exists buildids5_rfolo;\n"
     391                 :            :   "drop view if exists buildids5;\n"
     392                 :            : // buildids4: introduce rpmfile RFOLO
     393                 :            :   "drop table if exists buildids4_norm;\n"
     394                 :            :   "drop table if exists buildids4_files;\n"
     395                 :            :   "drop table if exists buildids4_buildids;\n"
     396                 :            :   "drop table if exists buildids4_bolo;\n"
     397                 :            :   "drop table if exists buildids4_rfolo;\n"
     398                 :            :   "drop view if exists buildids4;\n"
     399                 :            : // buildids3*: split out srcfile BOLO
     400                 :            :   "drop table if exists buildids3_norm;\n"
     401                 :            :   "drop table if exists buildids3_files;\n"
     402                 :            :   "drop table if exists buildids3_buildids;\n"
     403                 :            :   "drop table if exists buildids3_bolo;\n"
     404                 :            :   "drop view if exists buildids3;\n"
     405                 :            : // buildids2: normalized buildid and filenames into interning tables;
     406                 :            :   "drop table if exists buildids2_norm;\n"
     407                 :            :   "drop table if exists buildids2_files;\n"
     408                 :            :   "drop table if exists buildids2_buildids;\n"
     409                 :            :   "drop view if exists buildids2;\n"
     410                 :            :   // buildids1: made buildid and artifacttype NULLable, to represent cached-negative
     411                 :            : //           lookups from sources, e.g. files or rpms that contain no buildid-indexable content
     412                 :            :   "drop table if exists buildids1;\n"
     413                 :            : // buildids: original
     414                 :            :   "drop table if exists buildids;\n"
     415                 :            :   ;
     416                 :            : 
     417                 :            : static const char DEBUGINFOD_SQLITE_CLEANUP_DDL[] =
     418                 :            :   "pragma wal_checkpoint = truncate;\n" // clean out any preexisting wal file
     419                 :            :   ;
     420                 :            : 
     421                 :            : 
     422                 :            : 
     423                 :            : 
     424                 :            : /* Name and version of program.  */
     425                 :            : ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
     426                 :            : 
     427                 :            : /* Bug report address.  */
     428                 :            : ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
     429                 :            : 
     430                 :            : /* Definitions of arguments for argp functions.  */
     431                 :            : static const struct argp_option options[] =
     432                 :            :   {
     433                 :            :    { NULL, 0, NULL, 0, "Scanners:", 1 },
     434                 :            :    { "scan-file-dir", 'F', NULL, 0, "Enable ELF/DWARF file scanning.", 0 },
     435                 :            :    { "scan-rpm-dir", 'R', NULL, 0, "Enable RPM scanning.", 0 },
     436                 :            :    { "scan-deb-dir", 'U', NULL, 0, "Enable DEB scanning.", 0 },
     437                 :            :    { "scan-archive", 'Z', "EXT=CMD", 0, "Enable arbitrary archive scanning.", 0 },
     438                 :            :    // "source-oci-imageregistry"  ...
     439                 :            : 
     440                 :            :    { NULL, 0, NULL, 0, "Options:", 2 },
     441                 :            :    { "logical", 'L', NULL, 0, "Follow symlinks, default=ignore.", 0 },
     442                 :            :    { "rescan-time", 't', "SECONDS", 0, "Number of seconds to wait between rescans, 0=disable.", 0 },
     443                 :            :    { "groom-time", 'g', "SECONDS", 0, "Number of seconds to wait between database grooming, 0=disable.", 0 },
     444                 :            :    { "maxigroom", 'G', NULL, 0, "Run a complete database groom/shrink pass at startup.", 0 },
     445                 :            :    { "concurrency", 'c', "NUM", 0, "Limit scanning thread concurrency to NUM, default=#CPUs.", 0 },
     446                 :            :    { "connection-pool", 'C', "NUM", OPTION_ARG_OPTIONAL,
     447                 :            :      "Use webapi connection pool with NUM threads, default=unlim.", 0 },
     448                 :            :    { "include", 'I', "REGEX", 0, "Include files matching REGEX, default=all.", 0 },
     449                 :            :    { "exclude", 'X', "REGEX", 0, "Exclude files matching REGEX, default=none.", 0 },
     450                 :            :    { "port", 'p', "NUM", 0, "HTTP port to listen on, default 8002.", 0 },
     451                 :            : #define ARGP_KEY_CORS 0x1000
     452                 :            :    { "cors", ARGP_KEY_CORS, NULL, 0, "Add CORS response headers to HTTP queries, default no.", 0 },
     453                 :            :    { "database", 'd', "FILE", 0, "Path to sqlite database.", 0 },
     454                 :            :    { "ddl", 'D', "SQL", 0, "Apply extra sqlite ddl/pragma to connection.", 0 },
     455                 :            :    { "verbose", 'v', NULL, 0, "Increase verbosity.", 0 },
     456                 :            :    { "regex-groom", 'r', NULL, 0,"Uses regexes from -I and -X arguments to groom the database.",0},
     457                 :            : #define ARGP_KEY_FDCACHE_FDS 0x1001
     458                 :            :    { "fdcache-fds", ARGP_KEY_FDCACHE_FDS, "NUM", OPTION_HIDDEN, NULL, 0 },
     459                 :            : #define ARGP_KEY_FDCACHE_MBS 0x1002
     460                 :            :    { "fdcache-mbs", ARGP_KEY_FDCACHE_MBS, "MB", 0, "Maximum total size of archive file fdcache.", 0 },
     461                 :            : #define ARGP_KEY_FDCACHE_PREFETCH 0x1003
     462                 :            :    { "fdcache-prefetch", ARGP_KEY_FDCACHE_PREFETCH, "NUM", 0, "Number of archive files to prefetch into fdcache.", 0 },
     463                 :            : #define ARGP_KEY_FDCACHE_MINTMP 0x1004
     464                 :            :    { "fdcache-mintmp", ARGP_KEY_FDCACHE_MINTMP, "NUM", 0, "Minimum free space% on tmpdir.", 0 },
     465                 :            : #define ARGP_KEY_FDCACHE_PREFETCH_MBS 0x1005
     466                 :            :    { "fdcache-prefetch-mbs", ARGP_KEY_FDCACHE_PREFETCH_MBS, "MB", OPTION_HIDDEN, NULL, 0},
     467                 :            : #define ARGP_KEY_FDCACHE_PREFETCH_FDS 0x1006
     468                 :            :    { "fdcache-prefetch-fds", ARGP_KEY_FDCACHE_PREFETCH_FDS, "NUM", OPTION_HIDDEN, NULL, 0},
     469                 :            : #define ARGP_KEY_FORWARDED_TTL_LIMIT 0x1007
     470                 :            :    {"forwarded-ttl-limit", ARGP_KEY_FORWARDED_TTL_LIMIT, "NUM", 0, "Limit of X-Forwarded-For hops, default 8.", 0},
     471                 :            : #define ARGP_KEY_PASSIVE 0x1008
     472                 :            :    { "passive", ARGP_KEY_PASSIVE, NULL, 0, "Do not scan or groom, read-only database.", 0 },
     473                 :            : #define ARGP_KEY_DISABLE_SOURCE_SCAN 0x1009
     474                 :            :    { "disable-source-scan", ARGP_KEY_DISABLE_SOURCE_SCAN, NULL, 0, "Do not scan dwarf source info.", 0 },
     475                 :            : #define ARGP_SCAN_CHECKPOINT 0x100A
     476                 :            :    { "scan-checkpoint", ARGP_SCAN_CHECKPOINT, "NUM", 0, "Number of files scanned before a WAL checkpoint.", 0 },
     477                 :            : #ifdef ENABLE_IMA_VERIFICATION
     478                 :            : #define ARGP_KEY_KOJI_SIGCACHE 0x100B
     479                 :            :    { "koji-sigcache", ARGP_KEY_KOJI_SIGCACHE, NULL, 0, "Do a koji specific mapping of rpm paths to get IMA signatures.", 0 },
     480                 :            : #endif
     481                 :            : #define ARGP_KEY_METADATA_MAXTIME 0x100C
     482                 :            :    { "metadata-maxtime", ARGP_KEY_METADATA_MAXTIME, "SECONDS", 0,
     483                 :            :      "Number of seconds to limit metadata query run time, 0=unlimited.", 0 },
     484                 :            :    { NULL, 0, NULL, 0, NULL, 0 },
     485                 :            :   };
     486                 :            : 
     487                 :            : /* Short description of program.  */
     488                 :            : static const char doc[] = "Serve debuginfo-related content across HTTP from files under PATHs.";
     489                 :            : 
     490                 :            : /* Strings for arguments in help texts.  */
     491                 :            : static const char args_doc[] = "[PATH ...]";
     492                 :            : 
     493                 :            : /* Prototype for option handler.  */
     494                 :            : static error_t parse_opt (int key, char *arg, struct argp_state *state);
     495                 :            : 
     496                 :            : static unsigned default_concurrency();
     497                 :            : 
     498                 :            : /* Data structure to communicate with argp functions.  */
     499                 :            : static struct argp argp =
     500                 :            :   {
     501                 :            :    options, parse_opt, args_doc, doc, NULL, NULL, NULL
     502                 :            :   };
     503                 :            : 
     504                 :            : 
     505                 :            : static string db_path;
     506                 :            : static sqlite3 *db;  // single connection, serialized across all our threads!
     507                 :            : static sqlite3 *dbq; // webapi query-servicing readonly connection, serialized ditto!
     508                 :            : static unsigned verbose;
     509                 :            : static volatile sig_atomic_t interrupted = 0;
     510                 :            : static volatile sig_atomic_t forced_rescan_count = 0;
     511                 :            : static volatile sig_atomic_t sigusr1 = 0;
     512                 :            : static volatile sig_atomic_t forced_groom_count = 0;
     513                 :            : static volatile sig_atomic_t sigusr2 = 0;
     514                 :            : static unsigned http_port = 8002;
     515                 :            : static bool webapi_cors = false;
     516                 :            : static unsigned rescan_s = 300;
     517                 :            : static unsigned groom_s = 86400;
     518                 :            : static bool maxigroom = false;
     519                 :            : static unsigned concurrency = default_concurrency();
     520                 :            : static int connection_pool = 0;
     521                 :            : static set<string> source_paths;
     522                 :            : static bool scan_files = false;
     523                 :            : static map<string,string> scan_archives;
     524                 :            : static vector<string> extra_ddl;
     525                 :            : static regex_t file_include_regex;
     526                 :            : static regex_t file_exclude_regex;
     527                 :            : static bool regex_groom = false;
     528                 :            : static bool traverse_logical;
     529                 :            : static long fdcache_mbs;
     530                 :            : static long fdcache_prefetch;
     531                 :            : static long fdcache_mintmp;
     532                 :            : static unsigned forwarded_ttl_limit = 8;
     533                 :            : static bool scan_source_info = true;
     534                 :            : static string tmpdir;
     535                 :            : static bool passive_p = false;
     536                 :            : static long scan_checkpoint = 256;
     537                 :            : #ifdef ENABLE_IMA_VERIFICATION
     538                 :            : static bool requires_koji_sigcache_mapping = false;
     539                 :            : #endif
     540                 :            : static unsigned metadata_maxtime_s = 5;
     541                 :            : 
     542                 :            : static void set_metric(const string& key, double value);
     543                 :            : static void inc_metric(const string& key);
     544                 :            : static void add_metric(const string& metric,
     545                 :            :                        double value);
     546                 :            : static void set_metric(const string& metric,
     547                 :            :                        const string& lname, const string& lvalue,
     548                 :            :                        double value);
     549                 :            : static void inc_metric(const string& metric,
     550                 :            :                        const string& lname, const string& lvalue);
     551                 :            : static void add_metric(const string& metric,
     552                 :            :                        const string& lname, const string& lvalue,
     553                 :            :                        double value);
     554                 :            : static void inc_metric(const string& metric,
     555                 :            :                        const string& lname, const string& lvalue,
     556                 :            :                        const string& rname, const string& rvalue);
     557                 :            : static void add_metric(const string& metric,
     558                 :            :                        const string& lname, const string& lvalue,
     559                 :            :                        const string& rname, const string& rvalue,                       
     560                 :            :                        double value);
     561                 :            : 
     562                 :            : 
     563                 :            : class tmp_inc_metric { // a RAII style wrapper for exception-safe scoped increment & decrement
     564                 :            :   string m, n, v;
     565                 :            : public:
     566                 :       3346 :   tmp_inc_metric(const string& mname, const string& lname, const string& lvalue):
     567   [ +  -  +  - ]:       3346 :     m(mname), n(lname), v(lvalue)
     568                 :            :   {
     569         [ +  - ]:       3346 :     add_metric (m, n, v, 1);
     570   [ -  -  -  -  :       3346 :   }
                   -  - ]
     571                 :       3346 :   ~tmp_inc_metric()
     572                 :            :   {
     573                 :       3346 :     add_metric (m, n, v, -1);
     574   [ -  +  -  +  :       3346 :   }
                   -  + ]
     575                 :            : };
     576                 :            : 
     577                 :            : class tmp_ms_metric { // a RAII style wrapper for exception-safe scoped timing
     578                 :            :   string m, n, v;
     579                 :            :   struct timespec ts_start;
     580                 :            : public:
     581                 :     345965 :   tmp_ms_metric(const string& mname, const string& lname, const string& lvalue):
     582   [ +  -  +  - ]:     345965 :     m(mname), n(lname), v(lvalue)
     583                 :            :   {
     584                 :     345941 :     clock_gettime (CLOCK_MONOTONIC, & ts_start);
     585   [ -  -  -  - ]:     346157 :   }
     586                 :     346314 :   ~tmp_ms_metric()
     587                 :            :   {
     588                 :     346314 :     struct timespec ts_end;
     589                 :     346314 :     clock_gettime (CLOCK_MONOTONIC, & ts_end);
     590                 :     346303 :     double deltas = (ts_end.tv_sec - ts_start.tv_sec)
     591                 :     346303 :       + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
     592                 :            : 
     593         [ +  - ]:     346303 :     add_metric (m + "_milliseconds_sum", n, v, (deltas*1000.0));
     594         [ +  + ]:     346327 :     inc_metric (m + "_milliseconds_count", n, v);
     595   [ +  +  -  +  :     639020 :   }
                   -  + ]
     596                 :            : };
     597                 :            : 
     598                 :            : 
     599                 :            : /* Handle program arguments.  */
     600                 :            : static error_t
     601                 :       1232 : parse_opt (int key, char *arg,
     602                 :            :            struct argp_state *state __attribute__ ((unused)))
     603                 :            : {
     604                 :       1232 :   int rc;
     605   [ +  +  +  +  :       1232 :   switch (key)
          +  +  +  +  +  
          +  -  +  +  -  
          -  +  +  +  +  
          +  +  +  +  +  
             +  -  +  -  
                      + ]
     606                 :            :     {
     607                 :        296 :     case 'v': verbose ++; break;
     608                 :         80 :     case 'd':
     609                 :            :       /* When using the in-memory database make sure it is shareable,
     610                 :            :          so we can open it twice as read/write and read-only.  */
     611         [ +  + ]:         80 :       if (strcmp (arg, ":memory:") == 0)
     612                 :       1246 :         db_path = "file::memory:?cache=shared";
     613                 :            :       else
     614         [ +  - ]:        132 :         db_path = string(arg);
     615                 :            :       break;
     616                 :         80 :     case 'p': http_port = (unsigned) atoi(arg);
     617         [ +  - ]:         80 :       if (http_port == 0 || http_port > 65535)
     618                 :          0 :         argp_failure(state, 1, EINVAL, "port number");
     619                 :            :       break;
     620                 :          6 :     case ARGP_KEY_CORS:
     621                 :          6 :       webapi_cors = true;
     622                 :          6 :       break;
     623                 :         50 :     case 'F': scan_files = true; break;
     624                 :         24 :     case 'R':
     625   [ +  -  +  -  :         24 :       scan_archives[".rpm"]="cat"; // libarchive groks rpm natively
                   -  + ]
     626                 :         24 :       break;
     627                 :         18 :     case 'U':
     628   [ +  -  +  -  :         18 :       scan_archives[".deb"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     629   [ +  -  +  -  :         18 :       scan_archives[".ddeb"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     630   [ +  -  +  -  :         18 :       scan_archives[".ipk"]="(bsdtar -O -x -f - data.tar\\*)<";
                   -  + ]
     631                 :            :       // .udeb too?
     632                 :         18 :       break;
     633                 :         40 :     case 'Z':
     634                 :         40 :       {
     635         [ -  + ]:         40 :         char* extension = strchr(arg, '=');
     636         [ -  + ]:         40 :         if (arg[0] == '\0')
     637                 :          0 :           argp_failure(state, 1, EINVAL, "missing EXT");
     638         [ +  + ]:         40 :         else if (extension)
     639   [ +  -  +  -  :         20 :           scan_archives[string(arg, (extension-arg))]=string(extension+1);
          -  +  -  +  -  
                      - ]
     640                 :            :         else
     641   [ +  -  +  -  :         20 :           scan_archives[string(arg)]=string("cat");
          -  +  -  +  -  
                      - ]
     642                 :            :       }
     643                 :            :       break;
     644                 :          8 :     case 'L':
     645         [ -  + ]:          8 :       if (passive_p)
     646                 :          0 :         argp_failure(state, 1, EINVAL, "-L option inconsistent with passive mode");
     647                 :          8 :       traverse_logical = true;
     648                 :          8 :       break;
     649                 :          0 :     case 'D':
     650         [ #  # ]:          0 :       if (passive_p)
     651                 :          0 :         argp_failure(state, 1, EINVAL, "-D option inconsistent with passive mode");
     652         [ #  # ]:          0 :       extra_ddl.push_back(string(arg));
     653                 :          0 :       break;
     654                 :         64 :     case 't':
     655         [ -  + ]:         64 :       if (passive_p)
     656                 :          0 :         argp_failure(state, 1, EINVAL, "-t option inconsistent with passive mode");
     657                 :         64 :       rescan_s = (unsigned) atoi(arg);
     658                 :         64 :       break;
     659                 :         64 :     case 'g':
     660         [ -  + ]:         64 :       if (passive_p)
     661                 :          0 :         argp_failure(state, 1, EINVAL, "-g option inconsistent with passive mode");
     662                 :         64 :       groom_s = (unsigned) atoi(arg);
     663                 :         64 :       break;
     664                 :          0 :     case 'G':
     665         [ #  # ]:          0 :       if (passive_p)
     666                 :          0 :         argp_failure(state, 1, EINVAL, "-G option inconsistent with passive mode");
     667                 :          0 :       maxigroom = true;
     668                 :          0 :       break;
     669                 :          0 :     case 'c':
     670         [ #  # ]:          0 :       if (passive_p)
     671                 :          0 :         argp_failure(state, 1, EINVAL, "-c option inconsistent with passive mode");
     672                 :          0 :       concurrency = (unsigned) atoi(arg);
     673         [ #  # ]:          0 :       if (concurrency < 1) concurrency = 1;
     674                 :            :       break;
     675                 :          6 :     case 'C':
     676         [ +  + ]:          6 :       if (arg)
     677                 :            :         {
     678                 :          4 :           connection_pool = atoi(arg);
     679         [ +  - ]:          4 :           if (connection_pool < 2)
     680                 :          0 :             argp_failure(state, 1, EINVAL, "-C NUM minimum 2");
     681                 :            :         }
     682                 :            :       break;
     683                 :          4 :     case 'I':
     684                 :            :       // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
     685         [ -  + ]:          4 :       if (passive_p)
     686                 :          0 :         argp_failure(state, 1, EINVAL, "-I option inconsistent with passive mode");
     687                 :          4 :       regfree (&file_include_regex);
     688                 :          4 :       rc = regcomp (&file_include_regex, arg, REG_EXTENDED|REG_NOSUB);
     689         [ +  - ]:          4 :       if (rc != 0)
     690                 :          0 :         argp_failure(state, 1, EINVAL, "regular expression");
     691                 :            :       break;
     692                 :          6 :     case 'X':
     693         [ -  + ]:          6 :       if (passive_p)
     694                 :          0 :         argp_failure(state, 1, EINVAL, "-X option inconsistent with passive mode");
     695                 :          6 :       regfree (&file_exclude_regex);
     696                 :          6 :       rc = regcomp (&file_exclude_regex, arg, REG_EXTENDED|REG_NOSUB);
     697         [ +  - ]:          6 :       if (rc != 0)
     698                 :          0 :         argp_failure(state, 1, EINVAL, "regular expression");
     699                 :            :       break;
     700                 :          4 :     case 'r':
     701         [ -  + ]:          4 :       if (passive_p)
     702                 :          0 :         argp_failure(state, 1, EINVAL, "-r option inconsistent with passive mode");
     703                 :          4 :       regex_groom = true;
     704                 :          4 :       break;
     705                 :            :     case ARGP_KEY_FDCACHE_FDS:
     706                 :            :       // deprecated
     707                 :            :       break;
     708                 :          4 :     case ARGP_KEY_FDCACHE_MBS:
     709                 :          4 :       fdcache_mbs = atol (arg);
     710                 :          4 :       break;
     711                 :          4 :     case ARGP_KEY_FDCACHE_PREFETCH:
     712                 :          4 :       fdcache_prefetch = atol (arg);
     713                 :          4 :       break;
     714                 :          4 :     case ARGP_KEY_FDCACHE_MINTMP:
     715                 :          4 :       fdcache_mintmp = atol (arg);
     716         [ +  - ]:          4 :       if( fdcache_mintmp > 100 || fdcache_mintmp < 0 )
     717                 :          0 :         argp_failure(state, 1, EINVAL, "fdcache mintmp percent");
     718                 :            :       break;
     719                 :          4 :     case ARGP_KEY_FORWARDED_TTL_LIMIT:
     720                 :          4 :       forwarded_ttl_limit = (unsigned) atoi(arg);
     721                 :          4 :       break;
     722                 :        110 :     case ARGP_KEY_ARG:
     723         [ +  - ]:        110 :       source_paths.insert(string(arg));
     724                 :        110 :       break;
     725                 :            :     case ARGP_KEY_FDCACHE_PREFETCH_FDS:
     726                 :            :       // deprecated
     727                 :            :       break;
     728                 :            :     case ARGP_KEY_FDCACHE_PREFETCH_MBS:
     729                 :            :       // deprecated
     730                 :            :       break;
     731                 :          2 :     case ARGP_KEY_PASSIVE:
     732                 :          2 :       passive_p = true;
     733         [ +  - ]:          2 :       if (source_paths.size() > 0
     734         [ +  - ]:          2 :           || maxigroom
     735         [ +  - ]:          2 :           || extra_ddl.size() > 0
     736   [ +  -  +  - ]:          4 :           || traverse_logical)
     737                 :            :         // other conflicting options tricky to check
     738                 :          0 :         argp_failure(state, 1, EINVAL, "inconsistent options with passive mode");
     739                 :            :       break;
     740                 :          0 :     case ARGP_KEY_DISABLE_SOURCE_SCAN:
     741                 :          0 :       scan_source_info = false;
     742                 :          0 :       break;
     743                 :          2 :     case ARGP_SCAN_CHECKPOINT:
     744                 :          2 :       scan_checkpoint = atol (arg);
     745         [ +  - ]:          2 :       if (scan_checkpoint < 0)
     746                 :          0 :         argp_failure(state, 1, EINVAL, "scan checkpoint");
     747                 :            :       break;
     748                 :          0 :     case ARGP_KEY_METADATA_MAXTIME:
     749                 :          0 :       metadata_maxtime_s = (unsigned) atoi(arg);
     750                 :          0 :       break;
     751                 :            : #ifdef ENABLE_IMA_VERIFICATION
     752                 :            :     case ARGP_KEY_KOJI_SIGCACHE:
     753                 :            :       requires_koji_sigcache_mapping = true;
     754                 :            :       break;
     755                 :            : #endif
     756                 :            :       // case 'h': argp_state_help (state, stderr, ARGP_HELP_LONG|ARGP_HELP_EXIT_OK);
     757                 :            :     default: return ARGP_ERR_UNKNOWN;
     758                 :            :     }
     759                 :            : 
     760                 :            :   return 0;
     761                 :            : }
     762                 :            : 
     763                 :            : 
     764                 :            : ////////////////////////////////////////////////////////////////////////
     765                 :            : 
     766                 :            : 
     767                 :            : static void add_mhd_response_header (struct MHD_Response *r,
     768                 :            :                                      const char *h, const char *v);
     769                 :            : 
     770                 :            : // represent errors that may get reported to an ostream and/or a libmicrohttpd connection
     771                 :            : 
     772                 :          8 : struct reportable_exception
     773                 :            : {
     774                 :            :   int code;
     775                 :            :   string message;
     776                 :            : 
     777   [ -  -  +  -  :        106 :   reportable_exception(int c, const string& m): code(c), message(m) {}
          -  -  +  -  +  
                      - ]
     778   [ -  -  -  -  :        600 :   reportable_exception(const string& m): code(503), message(m) {}
          -  -  -  -  -  
          -  -  -  +  -  
          -  -  -  -  +  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  +  -  
                   -  - ]
     779                 :            :   reportable_exception(): code(503), message() {}
     780                 :            : 
     781                 :            :   void report(ostream& o) const; // defined under obatched() class below
     782                 :            : 
     783                 :        630 :   MHD_RESULT mhd_send_response(MHD_Connection* c) const {
     784                 :       1260 :     MHD_Response* r = MHD_create_response_from_buffer (message.size(),
     785                 :        630 :                                                        (void*) message.c_str(),
     786                 :            :                                                        MHD_RESPMEM_MUST_COPY);
     787                 :        630 :     add_mhd_response_header (r, "Content-Type", "text/plain");
     788                 :        630 :     MHD_RESULT rc = MHD_queue_response (c, code, r);
     789                 :        630 :     MHD_destroy_response (r);
     790                 :        630 :     return rc;
     791                 :            :   }
     792                 :            : };
     793                 :            : 
     794                 :            : 
     795                 :            : struct sqlite_exception: public reportable_exception
     796                 :            : {
     797                 :          0 :   sqlite_exception(int rc, const string& msg):
     798   [ #  #  #  #  :          0 :     reportable_exception(string("sqlite3 error: ") + msg + ": " + string(sqlite3_errstr(rc) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     799   [ #  #  #  #  :          0 :     inc_metric("error_count","sqlite3",sqlite3_errstr(rc));
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
     800         [ #  # ]:          0 :   }
     801                 :            : };
     802                 :            : 
     803   [ +  -  -  - ]:          4 : struct libc_exception: public reportable_exception
     804                 :            : {
     805                 :        594 :   libc_exception(int rc, const string& msg):
     806   [ -  +  +  -  :       2376 :     reportable_exception(string("libc error: ") + msg + ": " + string(strerror(rc) ?: "?")) {
          +  -  +  -  +  
          -  -  +  -  +  
          -  +  +  -  -  
                      - ]
     807   [ +  -  +  -  :       1188 :     inc_metric("error_count","libc",strerror(rc));
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
     808         [ -  - ]:        594 :   }
     809                 :            : };
     810                 :            : 
     811                 :            : 
     812                 :            : struct archive_exception: public reportable_exception
     813                 :            : {
     814                 :          0 :   archive_exception(const string& msg):
     815   [ #  #  #  #  :          0 :     reportable_exception(string("libarchive error: ") + msg) {
                   #  # ]
     816   [ #  #  #  #  :          0 :       inc_metric("error_count","libarchive",msg);
          #  #  #  #  #  
                      # ]
     817         [ #  # ]:          0 :   }
     818                 :          0 :   archive_exception(struct archive* a, const string& msg):
     819   [ #  #  #  #  :          0 :     reportable_exception(string("libarchive error: ") + msg + ": " + string(archive_error_string(a) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     820   [ #  #  #  #  :          0 :     inc_metric("error_count","libarchive",msg + ": " + string(archive_error_string(a) ?: "?"));
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     821         [ #  # ]:          0 :   }
     822                 :            : };
     823                 :            : 
     824                 :            : 
     825                 :            : struct elfutils_exception: public reportable_exception
     826                 :            : {
     827                 :          0 :   elfutils_exception(int rc, const string& msg):
     828   [ #  #  #  #  :          0 :     reportable_exception(string("elfutils error: ") + msg + ": " + string(elf_errmsg(rc) ?: "?")) {
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     829   [ #  #  #  #  :          0 :     inc_metric("error_count","elfutils",elf_errmsg(rc));
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
     830         [ #  # ]:          0 :   }
     831                 :            : };
     832                 :            : 
     833                 :            : 
     834                 :            : ////////////////////////////////////////////////////////////////////////
     835                 :            : 
     836                 :            : template <typename Payload>
     837                 :            : class workq
     838                 :            : {
     839                 :            :   unordered_set<Payload> q; // eliminate duplicates
     840                 :            :   mutex mtx;
     841                 :            :   condition_variable cv;
     842                 :            :   bool dead;
     843                 :            :   unsigned idlers;   // number of threads busy with wait_idle / done_idle
     844                 :            :   unsigned fronters; // number of threads busy with wait_front / done_front
     845                 :            : 
     846                 :            : public:
     847                 :         80 :   workq() { dead = false; idlers = 0; fronters = 0; }
     848                 :         80 :   ~workq() {}
     849                 :            : 
     850                 :       1306 :   void push_back(const Payload& p)
     851                 :            :   {
     852                 :       1306 :     unique_lock<mutex> lock(mtx);
     853         [ +  - ]:       1306 :     q.insert (p);
     854   [ +  -  +  -  :       2612 :     set_metric("thread_work_pending","role","scan", q.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
     855                 :       1306 :     cv.notify_all();
     856                 :       1306 :   }
     857                 :            : 
     858                 :            :   // kill this workqueue, wake up all idlers / scanners
     859                 :         80 :   void nuke() {
     860                 :         80 :     unique_lock<mutex> lock(mtx);
     861                 :            :     // optional: q.clear();
     862                 :         80 :     dead = true;
     863                 :         80 :     cv.notify_all();
     864                 :         80 :   }
     865                 :            : 
     866                 :            :   // clear the workqueue, when scanning is interrupted with USR2
     867                 :          0 :   void clear() {
     868                 :          0 :     unique_lock<mutex> lock(mtx);
     869                 :          0 :     q.clear();
     870   [ #  #  #  #  :          0 :     set_metric("thread_work_pending","role","scan", q.size());
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     871                 :            :     // NB: there may still be some live fronters
     872                 :          0 :     cv.notify_all(); // maybe wake up waiting idlers
     873                 :          0 :   }
     874                 :            : 
     875                 :            :   // block this scanner thread until there is work to do and no active idler
     876                 :       1594 :   bool wait_front (Payload& p)
     877                 :            :   {
     878                 :       1594 :     unique_lock<mutex> lock(mtx);
     879   [ +  +  +  +  :       5217 :     while (!dead && (q.size() == 0 || idlers > 0))
                   +  + ]
     880         [ +  - ]:       3623 :       cv.wait(lock);
     881         [ +  + ]:       1594 :     if (dead)
     882                 :            :       return false;
     883                 :            :     else
     884                 :            :       {
     885         [ +  - ]:       1306 :         p = * q.begin();
     886                 :       1306 :         q.erase (q.begin());
     887                 :       1306 :         fronters ++; // prevent idlers from starting awhile, even if empty q
     888   [ +  -  +  -  :       2612 :         set_metric("thread_work_pending","role","scan", q.size());
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
     889                 :            :         // NB: don't wake up idlers yet!  The consumer is busy
     890                 :            :         // processing this element until it calls done_front().
     891                 :       1306 :         return true;
     892                 :            :       }
     893                 :       1594 :   }
     894                 :            : 
     895                 :            :   // notify waitq that scanner thread is done with that last item
     896                 :       1306 :   void done_front ()
     897                 :            :   {
     898                 :       1306 :     unique_lock<mutex> lock(mtx);
     899                 :       1306 :     fronters --;
     900   [ +  +  +  + ]:       1306 :     if (q.size() == 0 && fronters == 0)
     901                 :         98 :       cv.notify_all(); // maybe wake up waiting idlers
     902                 :       1306 :   }
     903                 :            :   
     904                 :            :   // block this idler thread until there is no work to do
     905                 :        608 :   void wait_idle ()
     906                 :            :   {
     907                 :        608 :     unique_lock<mutex> lock(mtx);
     908                 :        608 :     cv.notify_all(); // maybe wake up waiting scanners
     909   [ +  +  +  +  :        643 :     while (!dead && ((q.size() != 0) || fronters > 0))
                   +  + ]
     910         [ +  - ]:         35 :       cv.wait(lock);
     911         [ +  - ]:        608 :     idlers ++;
     912                 :        608 :   }
     913                 :            : 
     914                 :        530 :   void done_idle ()
     915                 :            :   {
     916                 :        530 :     unique_lock<mutex> lock(mtx);
     917                 :        530 :     idlers --;
     918                 :        530 :     cv.notify_all(); // maybe wake up waiting scanners, but probably not (shutting down)
     919                 :        530 :   }
     920                 :            : };
     921                 :            : 
     922                 :            : typedef struct stat stat_t;
     923                 :            : typedef pair<string,stat_t> scan_payload;
     924                 :            : inline bool operator< (const scan_payload& a, const scan_payload& b)
     925                 :            : {
     926                 :            :   return a.first < b.first; // don't bother compare the stat fields
     927                 :            : }
     928                 :            : 
     929                 :            : namespace std { // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56480
     930                 :            :   template<> struct hash<::scan_payload>
     931                 :            :   {
     932                 :       5449 :     std::size_t operator() (const ::scan_payload& p) const noexcept
     933                 :            :     {
     934   [ +  +  +  + ]:       5449 :       return hash<string>()(p.first);
     935                 :            :     }
     936                 :            :   };
     937                 :            :   template<> struct equal_to<::scan_payload>
     938                 :            :   {
     939                 :        563 :     std::size_t operator() (const ::scan_payload& a, const ::scan_payload& b) const noexcept
     940                 :            :     {
     941   [ -  +  -  - ]:        563 :       return a.first == b.first;
     942                 :            :     }
     943                 :            :   };
     944                 :            : }
     945                 :            : 
     946                 :            : static workq<scan_payload> scanq; // just a single one
     947                 :            : // producer & idler: thread_main_fts_source_paths()
     948                 :            : // consumer: thread_main_scanner()
     949                 :            : // idler: thread_main_groom()
     950                 :            : 
     951                 :            : 
     952                 :            : ////////////////////////////////////////////////////////////////////////
     953                 :            : 
     954                 :            : // Unique set is a thread-safe structure that lends 'ownership' of a value
     955                 :            : // to a thread.  Other threads requesting the same thing are made to wait.
     956                 :            : // It's like a semaphore-on-demand.
     957                 :            : template <typename T>
     958                 :            : class unique_set
     959                 :            : {
     960                 :            : private:
     961                 :            :   set<T> values;
     962                 :            :   mutex mtx;
     963                 :            :   condition_variable cv;
     964                 :            : public:
     965                 :         60 :   unique_set() {}
     966                 :         60 :   ~unique_set() {}
     967                 :            : 
     968                 :       2570 :   void acquire(const T& value)
     969                 :            :   {
     970                 :       2570 :     unique_lock<mutex> lock(mtx);
     971         [ +  + ]:       2989 :     while (values.find(value) != values.end())
     972         [ +  - ]:        419 :       cv.wait(lock);
     973         [ +  - ]:       2570 :     values.insert(value);
     974                 :       2570 :   }
     975                 :            : 
     976                 :       2570 :   void release(const T& value)
     977                 :            :   {
     978                 :       2570 :     unique_lock<mutex> lock(mtx);
     979                 :            :     // assert (values.find(value) != values.end());
     980                 :       2570 :     values.erase(value);
     981                 :       2570 :     cv.notify_all();
     982                 :       2570 :   }
     983                 :            : };
     984                 :            : 
     985                 :            : 
     986                 :            : // This is the object that's instantiate to uniquely hold a value in a
     987                 :            : // RAII-pattern way.
     988                 :            : template <typename T>
     989                 :            : class unique_set_reserver
     990                 :            : {
     991                 :            : private:
     992                 :            :   unique_set<T>& please_hold;
     993                 :            :   T mine;
     994                 :            : public:
     995                 :       2570 :   unique_set_reserver(unique_set<T>& t, const T& value):
     996   [ +  -  -  - ]:       2570 :     please_hold(t), mine(value)  { please_hold.acquire(mine); }
     997         [ +  - ]:       2570 :   ~unique_set_reserver() { please_hold.release(mine); }
     998                 :            : };
     999                 :            : 
    1000                 :            : 
    1001                 :            : ////////////////////////////////////////////////////////////////////////
    1002                 :            : 
    1003                 :            : // periodic_barrier is a concurrency control object that lets N threads
    1004                 :            : // periodically (based on counter value) agree to wait at a barrier,
    1005                 :            : // let one of them carry out some work, then be set free
    1006                 :            : 
    1007                 :            : class periodic_barrier
    1008                 :            : {
    1009                 :            : private:
    1010                 :            :   unsigned period; // number of count() reports to trigger barrier activation
    1011                 :            :   unsigned threads; // number of threads participating
    1012                 :            :   mutex mtx; // protects all the following fields
    1013                 :            :   unsigned counter; // count of count() reports in the current generation
    1014                 :            :   unsigned generation; // barrier activation generation
    1015                 :            :   unsigned waiting; // number of threads waiting for barrier
    1016                 :            :   bool dead; // bring out your
    1017                 :            :   condition_variable cv;
    1018                 :            : public:
    1019                 :         72 :   periodic_barrier(unsigned t, unsigned p):
    1020                 :         72 :     period(p), threads(t), counter(0), generation(0), waiting(0), dead(false) { }
    1021                 :            :   virtual ~periodic_barrier() {}
    1022                 :            : 
    1023                 :            :   virtual void periodic_barrier_work() noexcept = 0;
    1024                 :         72 :   void nuke() {
    1025                 :         72 :     unique_lock<mutex> lock(mtx);
    1026                 :         72 :     dead = true;
    1027                 :         72 :     cv.notify_all();
    1028                 :         72 :   }
    1029                 :            :   
    1030                 :       1594 :   void count()
    1031                 :            :   {
    1032                 :       1594 :     unique_lock<mutex> lock(mtx);
    1033                 :       1594 :     unsigned prev_generation = this->generation;
    1034         [ +  + ]:       1594 :     if (counter < period-1) // normal case: counter just freely running
    1035                 :            :       {
    1036                 :       1450 :         counter ++;
    1037                 :       1450 :         return;
    1038                 :            :       }
    1039         [ +  + ]:        144 :     else if (counter == period-1) // we're the doer
    1040                 :            :       {
    1041                 :         36 :         counter = period; // entering barrier holding phase
    1042                 :         36 :         cv.notify_all();
    1043   [ +  +  +  - ]:        166 :         while (waiting < threads-1 && !dead)
    1044         [ +  - ]:         94 :           cv.wait(lock);
    1045                 :            :         // all other threads are now stuck in the barrier
    1046                 :         36 :         this->periodic_barrier_work(); // NB: we're holding the mutex the whole time
    1047                 :            :         // reset for next barrier, releasing other waiters
    1048                 :         36 :         counter = 0;
    1049                 :         36 :         generation ++;
    1050                 :         36 :         cv.notify_all();
    1051                 :         36 :         return;
    1052                 :            :       }
    1053         [ +  - ]:        108 :     else if (counter == period) // we're a waiter, in holding phase
    1054                 :            :       {
    1055                 :        108 :         waiting ++;
    1056                 :        108 :         cv.notify_all();
    1057   [ +  +  +  -  :        393 :         while (counter == period && generation == prev_generation && !dead)
                   +  - ]
    1058         [ +  - ]:        177 :           cv.wait(lock);
    1059                 :        108 :         waiting --;
    1060                 :        108 :         return;
    1061                 :            :       }
    1062                 :       1594 :   }
    1063                 :            : };
    1064                 :            : 
    1065                 :            : 
    1066                 :            : 
    1067                 :            : ////////////////////////////////////////////////////////////////////////
    1068                 :            : 
    1069                 :            : 
    1070                 :            : // Print a standard timestamp.
    1071                 :            : static ostream&
    1072                 :      44577 : timestamp (ostream &o)
    1073                 :            : {
    1074                 :      44577 :   char datebuf[80];
    1075                 :      44577 :   char *now2 = NULL;
    1076                 :      44577 :   time_t now_t = time(NULL);
    1077                 :      44576 :   struct tm now;
    1078                 :      44576 :   struct tm *nowp = gmtime_r (&now_t, &now);
    1079         [ +  - ]:      44578 :   if (nowp)
    1080                 :            :     {
    1081                 :      44578 :       (void) strftime (datebuf, sizeof (datebuf), "%c", nowp);
    1082                 :      44578 :       now2 = datebuf;
    1083                 :            :     }
    1084                 :            : 
    1085                 :      44578 :   return o << "[" << (now2 ? now2 : "") << "] "
    1086         [ -  + ]:      44578 :            << "(" << getpid () << "/" << tid() << "): ";
    1087                 :            : }
    1088                 :            : 
    1089                 :            : 
    1090                 :            : // A little class that impersonates an ostream to the extent that it can
    1091                 :            : // take << streaming operations.  It batches up the bits into an internal
    1092                 :            : // stringstream until it is destroyed; then flushes to the original ostream.
    1093                 :            : // It adds a timestamp
    1094                 :            : class obatched
    1095                 :            : {
    1096                 :            : private:
    1097                 :            :   ostream& o;
    1098                 :            :   stringstream stro;
    1099                 :            :   static mutex lock;
    1100                 :            : public:
    1101                 :      44577 :   obatched(ostream& oo, bool timestamp_p = true): o(oo)
    1102                 :            :   {
    1103         [ +  - ]:      44578 :     if (timestamp_p)
    1104         [ +  - ]:      44578 :       timestamp(stro);
    1105                 :      44578 :   }
    1106                 :      44578 :   ~obatched()
    1107                 :            :   {
    1108                 :      44578 :     unique_lock<mutex> do_not_cross_the_streams(obatched::lock);
    1109         [ +  - ]:      44578 :     o << stro.str();
    1110                 :      44578 :     o.flush();
    1111                 :      44578 :   }
    1112                 :            :   operator ostream& () { return stro; }
    1113   [ -  -  +  -  :      34576 :   template <typename T> ostream& operator << (const T& t) { stro << t; return stro; }
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  +  -  -  -  
          +  -  -  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  +  -  -  
          -  +  -  +  -  
          -  -  +  -  +  
          -  -  -  +  -  
          -  -  +  -  -  
          -  -  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             -  -  -  - ]
    1114                 :            : };
    1115                 :            : mutex obatched::lock; // just the one, since cout/cerr iostreams are not thread-safe
    1116                 :            : 
    1117                 :            : 
    1118                 :        692 : void reportable_exception::report(ostream& o) const {
    1119   [ +  -  +  - ]:        692 :   obatched(o) << message << endl;
    1120                 :        692 : }
    1121                 :            : 
    1122                 :            : 
    1123                 :            : ////////////////////////////////////////////////////////////////////////
    1124                 :            : 
    1125                 :            : 
    1126                 :            : // RAII style sqlite prepared-statement holder that matches { } block lifetime
    1127                 :            : 
    1128                 :            : struct sqlite_ps
    1129                 :            : {
    1130                 :            : private:
    1131                 :            :   sqlite3* db;
    1132                 :            :   const string nickname;
    1133                 :            :   const string sql;
    1134                 :            :   sqlite3_stmt *pp;
    1135                 :            :   // for step_timeout()/callback
    1136                 :            :   struct timespec ts_start;
    1137                 :            :   double ts_timeout;
    1138                 :            :   
    1139                 :            :   sqlite_ps(const sqlite_ps&); // make uncopyable
    1140                 :            :   sqlite_ps& operator=(const sqlite_ps &); // make unassignable
    1141                 :            : 
    1142                 :            : public:
    1143   [ +  -  -  - ]:       9143 :   sqlite_ps (sqlite3* d, const string& n, const string& s): db(d), nickname(n), sql(s) {
    1144                 :            :     // tmp_ms_metric tick("sqlite3","prep",nickname);
    1145         [ +  + ]:       9144 :     if (verbose > 4)
    1146   [ +  -  +  -  :        174 :       obatched(clog) << nickname << " prep " << sql << endl;
          +  -  +  -  +  
                -  -  - ]
    1147         [ +  - ]:       9144 :     int rc = sqlite3_prepare_v2 (db, sql.c_str(), -1 /* to \0 */, & this->pp, NULL);
    1148         [ -  + ]:       9144 :     if (rc != SQLITE_OK)
    1149   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "prepare " + sql);
    1150                 :      18288 :     this->reset_timeout(0.0);
    1151                 :          0 :   }
    1152                 :            : 
    1153                 :     190252 :   sqlite_ps& reset()
    1154                 :            :   {
    1155   [ +  -  +  -  :     380482 :     tmp_ms_metric tick("sqlite3","reset",nickname);
             -  +  -  - ]
    1156         [ +  - ]:     190230 :     sqlite3_reset(this->pp);
    1157                 :     190250 :     return *this;
    1158                 :     190249 :   }
    1159                 :            : 
    1160                 :     218103 :   sqlite_ps& bind(int parameter, const string& str)
    1161                 :            :   {
    1162         [ +  + ]:     218103 :     if (verbose > 4)
    1163   [ +  -  +  -  :        196 :       obatched(clog) << nickname << " bind " << parameter << "=" << str << endl;
          +  -  +  -  +  
                -  +  - ]
    1164                 :     218103 :     int rc = sqlite3_bind_text (this->pp, parameter, str.c_str(), -1, SQLITE_TRANSIENT);
    1165         [ -  + ]:     218109 :     if (rc != SQLITE_OK)
    1166   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 bind");
    1167                 :     218109 :     return *this;
    1168                 :            :   }
    1169                 :            : 
    1170                 :      58497 :   sqlite_ps& bind(int parameter, int64_t value)
    1171                 :            :   {
    1172         [ +  + ]:      58497 :     if (verbose > 4)
    1173   [ +  -  +  -  :         64 :       obatched(clog) << nickname << " bind " << parameter << "=" << value << endl;
          +  -  +  -  +  
                -  +  - ]
    1174                 :      58497 :     int rc = sqlite3_bind_int64 (this->pp, parameter, value);
    1175         [ -  + ]:      58501 :     if (rc != SQLITE_OK)
    1176   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 bind");
    1177                 :      58501 :     return *this;
    1178                 :            :   }
    1179                 :            : 
    1180                 :            :   sqlite_ps& bind(int parameter)
    1181                 :            :   {
    1182                 :            :     if (verbose > 4)
    1183                 :            :       obatched(clog) << nickname << " bind " << parameter << "=" << "NULL" << endl;
    1184                 :            :     int rc = sqlite3_bind_null (this->pp, parameter);
    1185                 :            :     if (rc != SQLITE_OK)
    1186                 :            :       throw sqlite_exception(rc, "sqlite3 bind");
    1187                 :            :     return *this;
    1188                 :            :   }
    1189                 :            : 
    1190                 :            : 
    1191                 :     117225 :   void step_ok_done() {
    1192   [ +  -  +  -  :     234414 :     tmp_ms_metric tick("sqlite3","step_done",nickname);
             -  +  -  - ]
    1193         [ +  - ]:     117189 :     int rc = sqlite3_step (this->pp);
    1194         [ +  + ]:     117236 :     if (verbose > 4)
    1195   [ +  -  +  -  :        128 :       obatched(clog) << nickname << " step-ok-done(" << sqlite3_errstr(rc) << ") " << sql << endl;
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1196   [ +  +  -  + ]:     117236 :     if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
    1197   [ #  #  #  # ]:          0 :       throw sqlite_exception(rc, "sqlite3 step");
    1198         [ +  - ]:     117236 :     (void) sqlite3_reset (this->pp);
    1199                 :     117236 :   }
    1200                 :            : 
    1201                 :            : 
    1202                 :      38835 :   int step() {
    1203   [ +  -  +  -  :      77662 :     tmp_ms_metric tick("sqlite3","step",nickname);
             -  +  -  - ]
    1204         [ +  - ]:      38827 :     int rc = sqlite3_step (this->pp);
    1205         [ +  + ]:      38836 :     if (verbose > 4)
    1206   [ +  -  +  -  :         62 :       obatched(clog) << nickname << " step(" << sqlite3_errstr(rc) << ") " << sql << endl;
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1207                 :      38836 :     return rc;
    1208                 :      38836 :   }
    1209                 :            : 
    1210                 :            : 
    1211                 :       9174 :   void reset_timeout(double s) // set starting point for maximum elapsed time in step_timeouts() 
    1212                 :            :   {
    1213                 :       9144 :     clock_gettime (CLOCK_MONOTONIC, &this->ts_start);
    1214                 :       9144 :     this->ts_timeout = s;
    1215                 :            :   }
    1216                 :            : 
    1217                 :            :   
    1218                 :          0 :   static int sqlite3_progress_handler_cb (void *param)
    1219                 :            :   {
    1220                 :          0 :     sqlite_ps *pp = (sqlite_ps*) param;
    1221                 :          0 :     struct timespec ts_end;
    1222                 :          0 :     clock_gettime (CLOCK_MONOTONIC, &ts_end);
    1223                 :          0 :     double deltas = (ts_end.tv_sec - pp->ts_start.tv_sec) + (ts_end.tv_nsec - pp->ts_start.tv_nsec)/1.e9;
    1224   [ #  #  #  # ]:          0 :     return (interrupted || (deltas > pp->ts_timeout)); // non-zero => interrupt sqlite operation in progress
    1225                 :            :   }
    1226                 :            :   
    1227                 :            : 
    1228                 :         48 :   int step_timeout() {
    1229                 :            :     // Do the same thing as step(), except wrapping it into a timeout
    1230                 :            :     // relative to the last reset_timeout() invocation.
    1231                 :            :     //
    1232                 :            :     // Do this by attaching a progress_handler to the database
    1233                 :            :     // connection, for the duration of this operation.  It should be a
    1234                 :            :     // private connection to the calling thread, so other operations
    1235                 :            :     // cannot begin concurrently.
    1236                 :            :     
    1237                 :         48 :     sqlite3_progress_handler(this->db, 10000 /* bytecode insns */,
    1238                 :            :                              & sqlite3_progress_handler_cb, (void*) this);
    1239                 :         48 :     int rc = this->step();
    1240                 :         48 :     sqlite3_progress_handler(this->db, 0, 0, 0); // disable
    1241                 :         48 :     struct timespec ts_end;
    1242                 :         48 :     clock_gettime (CLOCK_MONOTONIC, &ts_end);
    1243                 :         48 :     double deltas = (ts_end.tv_sec - this->ts_start.tv_sec) + (ts_end.tv_nsec - this->ts_start.tv_nsec)/1.e9;
    1244         [ -  + ]:         48 :     if (verbose > 3)
    1245   [ #  #  #  #  :          0 :       obatched(clog) << this->nickname << " progress-delta-final " << deltas << endl;
             #  #  #  # ]
    1246                 :         48 :     return rc;
    1247                 :            :   }
    1248                 :            : 
    1249                 :            :   
    1250   [ +  +  +  + ]:      18126 :   ~sqlite_ps () { sqlite3_finalize (this->pp); }
    1251   [ +  -  +  -  :       6800 :   operator sqlite3_stmt* () { return this->pp; }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
    1252                 :            : };
    1253                 :            : 
    1254                 :            : 
    1255                 :            : ////////////////////////////////////////////////////////////////////////
    1256                 :            : 
    1257                 :            : 
    1258                 :            : struct sqlite_checkpoint_pb: public periodic_barrier
    1259                 :            : {
    1260                 :            :   // NB: don't use sqlite_ps since it can throw exceptions during ctor etc.
    1261                 :         72 :   sqlite_checkpoint_pb(unsigned t, unsigned p):
    1262                 :        144 :     periodic_barrier(t, p) { }
    1263                 :            :   
    1264                 :         36 :   void periodic_barrier_work() noexcept
    1265                 :            :   {
    1266                 :         36 :     (void) sqlite3_exec (db, "pragma wal_checkpoint(truncate);", NULL, NULL, NULL);
    1267                 :         36 :   }
    1268                 :            : };
    1269                 :            :   
    1270                 :            : static periodic_barrier* scan_barrier = 0; // initialized in main()
    1271                 :            : 
    1272                 :            : 
    1273                 :            : ////////////////////////////////////////////////////////////////////////
    1274                 :            : 
    1275                 :            : // RAII style templated autocloser
    1276                 :            : 
    1277                 :            : template <class Payload, class Ignore>
    1278                 :            : struct defer_dtor
    1279                 :            : {
    1280                 :            : public:
    1281                 :            :   typedef Ignore (*dtor_fn) (Payload);
    1282                 :            : 
    1283                 :            : private:
    1284                 :            :   Payload p;
    1285                 :            :   dtor_fn fn;
    1286                 :            : 
    1287                 :            : public:
    1288                 :       5084 :   defer_dtor(Payload _p, dtor_fn _fn): p(_p), fn(_fn) {}
    1289                 :        750 :   ~defer_dtor() { (void) (*fn)(p); }
    1290                 :            : 
    1291                 :            : private:
    1292                 :            :   defer_dtor(const defer_dtor<Payload,Ignore>&); // make uncopyable
    1293                 :            :   defer_dtor& operator=(const defer_dtor<Payload,Ignore> &); // make unassignable
    1294                 :            : };
    1295                 :            : 
    1296                 :            : 
    1297                 :            : 
    1298                 :            : ////////////////////////////////////////////////////////////////////////
    1299                 :            : 
    1300                 :            : 
    1301                 :            : static string
    1302                 :       6704 : header_censor(const string& str)
    1303                 :            : {
    1304                 :       6704 :   string y;
    1305         [ +  + ]:      82800 :   for (auto&& x : str)
    1306                 :            :     {
    1307         [ +  + ]:      76096 :       if (isalnum(x) || x == '/' || x == '.' || x == ',' || x == '_' || x == ':')
    1308         [ +  - ]:     152186 :         y += x;
    1309                 :            :     }
    1310                 :       6704 :   return y;
    1311                 :          0 : }
    1312                 :            : 
    1313                 :            : 
    1314                 :            : static string
    1315                 :       3352 : conninfo (struct MHD_Connection * conn)
    1316                 :            : {
    1317                 :       3352 :   char hostname[256]; // RFC1035
    1318                 :       3352 :   char servname[256];
    1319                 :       3352 :   int sts = -1;
    1320                 :            : 
    1321         [ -  + ]:       3352 :   if (conn == 0)
    1322                 :          0 :     return "internal";
    1323                 :            : 
    1324                 :            :   /* Look up client address data. */
    1325                 :       3352 :   const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
    1326                 :            :                                                                MHD_CONNECTION_INFO_CLIENT_ADDRESS);
    1327         [ +  - ]:       3352 :   struct sockaddr *so = u ? u->client_addr : 0;
    1328                 :            : 
    1329   [ +  -  -  + ]:       3352 :   if (so && so->sa_family == AF_INET) {
    1330                 :          0 :     sts = getnameinfo (so, sizeof (struct sockaddr_in),
    1331                 :            :                        hostname, sizeof (hostname),
    1332                 :            :                        servname, sizeof (servname),
    1333                 :            :                        NI_NUMERICHOST | NI_NUMERICSERV);
    1334         [ +  - ]:       3352 :   } else if (so && so->sa_family == AF_INET6) {
    1335                 :       3352 :     struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
    1336   [ +  -  +  -  :       3352 :     if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
                   -  + ]
    1337                 :       3352 :       struct sockaddr_in addr4;
    1338                 :       3352 :       memset (&addr4, 0, sizeof(addr4));
    1339                 :       3352 :       addr4.sin_family = AF_INET;
    1340                 :       3352 :       addr4.sin_port = addr6->sin6_port;
    1341                 :       3352 :       memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
    1342                 :       3352 :       sts = getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
    1343                 :            :                          hostname, sizeof (hostname),
    1344                 :            :                          servname, sizeof (servname),
    1345                 :            :                          NI_NUMERICHOST | NI_NUMERICSERV);
    1346                 :            :     } else {
    1347                 :          0 :       sts = getnameinfo (so, sizeof (struct sockaddr_in6),
    1348                 :            :                          hostname, sizeof (hostname),
    1349                 :            :                          servname, sizeof (servname),
    1350                 :            :                          NI_NUMERICHOST | NI_NUMERICSERV);
    1351                 :            :     }
    1352                 :            :   }
    1353                 :            :   
    1354         [ -  + ]:       3352 :   if (sts != 0) {
    1355                 :          0 :     hostname[0] = servname[0] = '\0';
    1356                 :            :   }
    1357                 :            : 
    1358                 :            :   // extract headers relevant to administration
    1359         [ -  + ]:       3352 :   const char* user_agent = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
    1360         [ +  + ]:       3352 :   const char* x_forwarded_for = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
    1361                 :            :   // NB: these are untrustworthy, beware if machine-processing log files
    1362                 :            : 
    1363   [ +  -  +  -  :      10056 :   return string(hostname) + string(":") + string(servname) +
          +  -  +  -  +  
          -  +  -  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  -  -  -  -  
                      - ]
    1364   [ +  -  +  -  :      14906 :     string(" UA:") + header_censor(string(user_agent)) +
          +  -  +  -  +  
          -  -  +  +  +  
          -  +  +  +  -  
             +  -  -  -  
                      - ]
    1365   [ +  -  +  -  :      10068 :     string(" XFF:") + header_censor(string(x_forwarded_for));
          +  -  +  +  +  
                +  -  - ]
    1366                 :            : }
    1367                 :            : 
    1368                 :            : 
    1369                 :            : 
    1370                 :            : ////////////////////////////////////////////////////////////////////////
    1371                 :            : 
    1372                 :            : /* Wrapper for MHD_add_response_header that logs an error if we
    1373                 :            :    couldn't add the specified header.  */
    1374                 :            : static void
    1375                 :      13182 : add_mhd_response_header (struct MHD_Response *r,
    1376                 :            :                          const char *h, const char *v)
    1377                 :            : {
    1378         [ -  + ]:      13182 :   if (MHD_add_response_header (r, h, v) == MHD_NO)
    1379   [ #  #  #  #  :          0 :     obatched(clog) << "Error: couldn't add '" << h << "' header" << endl;
                   #  # ]
    1380                 :      13182 : }
    1381                 :            : 
    1382                 :            : static void
    1383                 :       2128 : add_mhd_last_modified (struct MHD_Response *resp, time_t mtime)
    1384                 :            : {
    1385                 :       2128 :   struct tm now;
    1386                 :       2128 :   struct tm *nowp = gmtime_r (&mtime, &now);
    1387         [ +  - ]:       2128 :   if (nowp != NULL)
    1388                 :            :     {
    1389                 :       2128 :       char datebuf[80];
    1390                 :       2128 :       size_t rc = strftime (datebuf, sizeof (datebuf), "%a, %d %b %Y %T GMT",
    1391                 :            :                             nowp);
    1392         [ +  - ]:       2128 :       if (rc > 0 && rc < sizeof (datebuf))
    1393                 :       2128 :         add_mhd_response_header (resp, "Last-Modified", datebuf);
    1394                 :            :     }
    1395                 :            : 
    1396                 :       2128 :   add_mhd_response_header (resp, "Cache-Control", "public");
    1397                 :       2128 : }
    1398                 :            : 
    1399                 :            : // quote all questionable characters of str for safe passage through a sh -c expansion.
    1400                 :            : static string
    1401                 :         64 : shell_escape(const string& str)
    1402                 :            : {
    1403                 :         64 :   string y;
    1404         [ +  + ]:       4478 :   for (auto&& x : str)
    1405                 :            :     {
    1406   [ +  +  +  + ]:       4414 :       if (! isalnum(x) && x != '/')
    1407         [ +  - ]:        586 :         y += "\\";
    1408         [ +  - ]:       8828 :       y += x;
    1409                 :            :     }
    1410                 :         64 :   return y;
    1411                 :          0 : }
    1412                 :            : 
    1413                 :            : 
    1414                 :            : // PR25548: Perform POSIX / RFC3986 style path canonicalization on the input string.
    1415                 :            : //
    1416                 :            : // Namely:
    1417                 :            : //    //         ->   /
    1418                 :            : //    /foo/../   ->   /
    1419                 :            : //    /./        ->   /
    1420                 :            : //
    1421                 :            : // This mapping is done on dwarf-side source path names, which may
    1422                 :            : // include these constructs, so we can deal with debuginfod clients
    1423                 :            : // that accidentally canonicalize the paths.
    1424                 :            : //
    1425                 :            : // realpath(3) is close but not quite right, because it also resolves
    1426                 :            : // symbolic links.  Symlinks at the debuginfod server have nothing to
    1427                 :            : // do with the build-time symlinks, thus they must not be considered.
    1428                 :            : //
    1429                 :            : // see also curl Curl_dedotdotify() aka RFC3986, which we mostly follow here
    1430                 :            : // see also libc __realpath()
    1431                 :            : // see also llvm llvm::sys::path::remove_dots()
    1432                 :            : static string
    1433                 :      16254 : canon_pathname (const string& input)
    1434                 :            : {
    1435                 :      16254 :   string i = input; // 5.2.4 (1)
    1436                 :      16254 :   string o;
    1437                 :            : 
    1438                 :     155004 :   while (i.size() != 0)
    1439                 :            :     {
    1440                 :            :       // 5.2.4 (2) A
    1441   [ +  -  -  +  :     277500 :       if (i.substr(0,3) == "../")
                   -  + ]
    1442   [ #  #  #  # ]:          0 :         i = i.substr(3);
    1443   [ +  -  -  +  :     277500 :       else if(i.substr(0,2) == "./")
                   -  + ]
    1444   [ #  #  #  # ]:          0 :         i = i.substr(2);
    1445                 :            : 
    1446                 :            :       // 5.2.4 (2) B
    1447   [ +  -  -  +  :     277500 :       else if (i.substr(0,3) == "/./")
                   +  + ]
    1448   [ +  -  +  + ]:       2822 :         i = i.substr(2);
    1449         [ -  + ]:     137106 :       else if (i == "/.")
    1450         [ #  # ]:          0 :         i = ""; // no need to handle "/." complete-path-segment case; we're dealing with file names
    1451                 :            : 
    1452                 :            :       // 5.2.4 (2) C
    1453   [ +  -  -  +  :     274212 :       else if (i.substr(0,4) == "/../") {
                   +  + ]
    1454   [ +  -  +  + ]:       2266 :         i = i.substr(3);
    1455                 :       2266 :         string::size_type sl = o.rfind("/");
    1456         [ +  - ]:       2266 :         if (sl != string::npos)
    1457   [ +  -  +  - ]:       4532 :           o = o.substr(0, sl);
    1458                 :            :         else
    1459         [ #  # ]:          0 :           o = "";
    1460         [ -  + ]:     134840 :       } else if (i == "/..")
    1461         [ #  # ]:          0 :         i = ""; // no need to handle "/.." complete-path-segment case; we're dealing with file names
    1462                 :            : 
    1463                 :            :       // 5.2.4 (2) D
    1464                 :            :       // no need to handle these cases; we're dealing with file names
    1465         [ -  + ]:     134840 :       else if (i == ".")
    1466         [ #  # ]:          0 :         i = "";
    1467         [ -  + ]:     134840 :       else if (i == "..")
    1468         [ #  # ]:          0 :         i = "";
    1469                 :            : 
    1470                 :            :       // POSIX special: map // to /
    1471   [ +  -  -  +  :     269680 :       else if (i.substr(0,2) == "//")
                   +  + ]
    1472   [ +  -  +  + ]:        144 :         i = i.substr(1);
    1473                 :            : 
    1474                 :            :       // 5.2.4 (2) E
    1475                 :            :       else {
    1476         [ -  + ]:     134712 :         string::size_type next_slash = i.find("/", (i[0]=='/' ? 1 : 0)); // skip first slash
    1477   [ +  -  +  + ]:     269424 :         o += i.substr(0, next_slash);
    1478         [ +  + ]:     134712 :         if (next_slash == string::npos)
    1479   [ +  -  +  + ]:     171258 :           i = "";
    1480                 :            :         else
    1481   [ +  -  +  +  :     223788 :           i = i.substr(next_slash);
                   -  - ]
    1482                 :            :       }
    1483                 :            :     }
    1484                 :            : 
    1485         [ +  - ]:      16254 :   return o;
    1486                 :      16254 : }
    1487                 :            : 
    1488                 :            : 
    1489                 :            : // Estimate available free space for a given filesystem via statfs(2).
    1490                 :            : // Return true if the free fraction is known to be smaller than the
    1491                 :            : // given minimum percentage.  Also update a related metric.
    1492                 :       2971 : bool statfs_free_enough_p(const string& path, const string& label, long minfree = 0)
    1493                 :            : {
    1494                 :       2971 :   struct statfs sfs;
    1495                 :       2971 :   int rc = statfs(path.c_str(), &sfs);
    1496         [ +  + ]:       2972 :   if (rc == 0)
    1497                 :            :     {
    1498                 :       2898 :       double s = (double) sfs.f_bavail / (double) sfs.f_blocks;
    1499   [ +  -  +  -  :       5796 :       set_metric("filesys_free_ratio","purpose",label, s);
             -  +  -  - ]
    1500                 :       2898 :       return ((s * 100.0) < minfree);
    1501                 :            :     }
    1502                 :            :   return false;
    1503                 :            : }
    1504                 :            : 
    1505                 :            : 
    1506                 :            : 
    1507                 :            : // A map-like class that owns a cache of file descriptors (indexed by
    1508                 :            : // file / content names).
    1509                 :            : //
    1510                 :            : // If only it could use fd's instead of file names ... but we can't
    1511                 :            : // dup(2) to create independent descriptors for the same unlinked
    1512                 :            : // files, so would have to use some goofy linux /proc/self/fd/%d
    1513                 :            : // hack such as the following
    1514                 :            : 
    1515                 :            : #if 0
    1516                 :            : int superdup(int fd)
    1517                 :            : {
    1518                 :            : #ifdef __linux__
    1519                 :            :   char *fdpath = NULL;
    1520                 :            :   int rc = asprintf(& fdpath, "/proc/self/fd/%d", fd);
    1521                 :            :   int newfd;
    1522                 :            :   if (rc >= 0)
    1523                 :            :     newfd = open(fdpath, O_RDONLY);
    1524                 :            :   else
    1525                 :            :     newfd = -1;
    1526                 :            :   free (fdpath);
    1527                 :            :   return newfd;
    1528                 :            : #else
    1529                 :            :   return -1;
    1530                 :            : #endif
    1531                 :            : }
    1532                 :            : #endif
    1533                 :            : 
    1534                 :            : class libarchive_fdcache
    1535                 :            : {
    1536                 :            : private:
    1537                 :            :   mutex fdcache_lock;
    1538                 :            : 
    1539                 :            :   typedef pair<string,string> key; // archive, entry
    1540         [ +  - ]:        282 :   struct fdcache_entry
    1541                 :            :   {
    1542                 :            :     string fd; // file name (probably in $TMPDIR), not an actual open fd (EMFILE)
    1543                 :            :     double fd_size_mb; // slightly rounded up megabytes
    1544                 :            :     time_t freshness; // when was this entry created or requested last
    1545                 :            :     unsigned request_count; // how many requests were made; or 0=prefetch only
    1546                 :            :     double latency; // how many seconds it took to extract the file
    1547                 :            :   };
    1548                 :            : 
    1549                 :            :   map<key,fdcache_entry> entries; // optimized for lookup
    1550                 :            :   time_t last_cleaning;
    1551                 :            :   long max_mbs;
    1552                 :            : 
    1553                 :            : public:
    1554                 :        362 :   void set_metrics()
    1555                 :            :   {
    1556                 :        362 :     double fdcache_mb = 0.0;
    1557                 :        362 :     double prefetch_mb = 0.0;
    1558                 :        362 :     unsigned fdcache_count = 0;
    1559                 :        362 :     unsigned prefetch_count = 0;
    1560         [ +  + ]:       3474 :     for (auto &i : entries) {
    1561         [ +  + ]:       3112 :       if (i.second.request_count) {
    1562                 :       3018 :         fdcache_mb += i.second.fd_size_mb;
    1563                 :       3018 :         fdcache_count ++;
    1564                 :            :       } else {
    1565                 :         94 :         prefetch_mb += i.second.fd_size_mb;
    1566                 :         94 :         prefetch_count ++;
    1567                 :            :       }
    1568                 :            :     }
    1569         [ +  - ]:        362 :     set_metric("fdcache_bytes", fdcache_mb*1024.0*1024.0);
    1570         [ +  - ]:        362 :     set_metric("fdcache_count", fdcache_count);
    1571         [ +  - ]:        362 :     set_metric("fdcache_prefetch_bytes", prefetch_mb*1024.0*1024.0);
    1572         [ +  - ]:        362 :     set_metric("fdcache_prefetch_count", prefetch_count);
    1573                 :        362 :   }
    1574                 :            : 
    1575                 :        284 :   void intern(const string& a, const string& b, string fd, off_t sz,
    1576                 :            :               bool requested_p, double lat)
    1577                 :            :   {
    1578                 :        284 :     {
    1579                 :        284 :       unique_lock<mutex> lock(fdcache_lock);
    1580                 :        284 :       time_t now = time(NULL);
    1581                 :            :       // there is a chance it's already in here, just wasn't found last time
    1582                 :            :       // if so, there's nothing to do but count our luck
    1583         [ +  - ]:        284 :       auto i = entries.find(make_pair(a,b));
    1584         [ +  + ]:        284 :       if (i != entries.end())
    1585                 :            :         {
    1586   [ +  -  +  -  :          4 :           inc_metric("fdcache_op_count","op","redundant_intern");
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    1587         [ +  - ]:          2 :           if (requested_p) i->second.request_count ++; // repeat prefetch doesn't count
    1588                 :          2 :           i->second.freshness = now;
    1589                 :            :           // We need to nuke the temp file, since interning passes
    1590                 :            :           // responsibility over the path to this structure.  It is
    1591                 :            :           // possible that the caller still has an fd open, but that's
    1592                 :            :           // OK.
    1593                 :          2 :           unlink (fd.c_str());
    1594                 :          2 :           return;
    1595                 :            :         }
    1596                 :        282 :       double mb = (sz+65535)/1048576.0; // round up to 64K block
    1597                 :        282 :       fdcache_entry n = { .fd=fd, .fd_size_mb=mb,
    1598                 :        282 :                           .freshness=now, .request_count = requested_p?1U:0U,
    1599   [ +  -  +  + ]:        282 :                           .latency=lat};
    1600   [ +  -  +  -  :        282 :       entries.insert(make_pair(make_pair(a,b),n));
                   +  - ]
    1601                 :            :       
    1602         [ +  + ]:        282 :       if (requested_p)
    1603   [ +  -  +  -  :        472 :         inc_metric("fdcache_op_count","op","enqueue");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1604                 :            :       else
    1605   [ +  -  +  -  :        138 :         inc_metric("fdcache_op_count","op","prefetch_enqueue");
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    1606                 :            :       
    1607         [ +  + ]:        282 :       if (verbose > 3)
    1608   [ +  -  +  -  :        504 :         obatched(clog) << "fdcache interned a=" << a << " b=" << b
                   -  - ]
    1609   [ +  -  +  -  :        168 :                        << " fd=" << fd << " mb=" << mb << " front=" << requested_p
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1610   [ +  -  +  -  :        168 :                        << " latency=" << lat << endl;
                   +  - ]
    1611                 :            :       
    1612         [ +  - ]:        282 :       set_metrics();
    1613                 :        284 :     }
    1614                 :            : 
    1615                 :            :     // NB: we age the cache at lookup time too
    1616   [ +  -  -  +  :        282 :     if (statfs_free_enough_p(tmpdir, "tmpdir", fdcache_mintmp))
                   -  + ]
    1617                 :            :       {
    1618   [ #  #  #  #  :          0 :         inc_metric("fdcache_op_count","op","emerg-flush");
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1619         [ #  # ]:          0 :         obatched(clog) << "fdcache emergency flush for filling tmpdir" << endl;
    1620                 :          0 :         this->limit(0); // emergency flush
    1621                 :            :       }
    1622                 :            :     else // age cache normally
    1623                 :        282 :       this->limit(max_mbs);
    1624                 :            :   }
    1625                 :            : 
    1626                 :       1014 :   int lookup(const string& a, const string& b)
    1627                 :            :   {
    1628                 :       1014 :     int fd = -1;
    1629                 :       1014 :     {
    1630                 :       1014 :       unique_lock<mutex> lock(fdcache_lock);
    1631         [ +  - ]:       1014 :       auto i = entries.find(make_pair(a,b));
    1632         [ +  + ]:       1014 :       if (i != entries.end())
    1633                 :            :         {
    1634         [ +  + ]:        772 :           if (i->second.request_count == 0) // was a prefetch!
    1635                 :            :             {
    1636   [ +  -  +  - ]:         12 :               inc_metric("fdcache_prefetch_saved_milliseconds_count");
    1637   [ +  -  +  - ]:         24 :               add_metric("fdcache_prefetch_saved_milliseconds_sum", i->second.latency*1000.);
    1638                 :            :             }
    1639                 :        772 :           i->second.request_count ++;
    1640                 :        772 :           i->second.freshness = time(NULL);
    1641                 :            :           // brag about our success
    1642   [ +  -  +  -  :       1544 :           inc_metric("fdcache_op_count","op","prefetch_access"); // backward compat
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1643   [ +  -  +  - ]:        772 :           inc_metric("fdcache_saved_milliseconds_count");
    1644   [ +  -  +  - ]:        772 :           add_metric("fdcache_saved_milliseconds_sum", i->second.latency*1000.);
    1645         [ +  - ]:       1014 :           fd = open(i->second.fd.c_str(), O_RDONLY); 
    1646                 :            :         }
    1647                 :          0 :     }
    1648                 :            : 
    1649         [ +  + ]:       1014 :     if (fd >= 0)
    1650   [ +  -  +  -  :       1544 :       inc_metric("fdcache_op_count","op","lookup_hit");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    1651                 :            :     else
    1652   [ +  -  +  -  :        484 :       inc_metric("fdcache_op_count","op","lookup_miss");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    1653                 :            :     
    1654                 :            :     // NB: no need to age the cache after just a lookup
    1655                 :            : 
    1656                 :       1014 :     return fd;
    1657                 :            :   }
    1658                 :            : 
    1659                 :        208 :   int probe(const string& a, const string& b) // just a cache residency check - don't modify state, don't open
    1660                 :            :   {
    1661                 :        208 :     unique_lock<mutex> lock(fdcache_lock);
    1662         [ +  - ]:        208 :     auto i = entries.find(make_pair(a,b));
    1663         [ +  + ]:        208 :     if (i != entries.end()) {
    1664   [ +  -  +  -  :         56 :       inc_metric("fdcache_op_count","op","probe_hit");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1665                 :         28 :       return true;
    1666                 :            :     } else {
    1667   [ +  -  +  -  :        360 :       inc_metric("fdcache_op_count","op","probe_miss");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1668                 :        180 :       return false;
    1669                 :            :    }
    1670                 :        208 :   }
    1671                 :            :   
    1672                 :          0 :   void clear(const string& a, const string& b)
    1673                 :            :   {
    1674                 :          0 :     unique_lock<mutex> lock(fdcache_lock);
    1675         [ #  # ]:          0 :     auto i = entries.find(make_pair(a,b));
    1676         [ #  # ]:          0 :     if (i != entries.end()) {
    1677   [ #  #  #  #  :          0 :       inc_metric("fdcache_op_count","op",
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
    1678         [ #  # ]:          0 :                  i->second.request_count > 0 ? "clear" : "prefetch_clear");
    1679                 :          0 :       unlink (i->second.fd.c_str());
    1680                 :          0 :       entries.erase(i);
    1681         [ #  # ]:          0 :       set_metrics();
    1682                 :          0 :       return;
    1683                 :            :     }
    1684                 :          0 :   }
    1685                 :            : 
    1686                 :        442 :   void limit(long maxmbs, bool metrics_p = true)
    1687                 :            :   {
    1688                 :        442 :     time_t now = time(NULL);
    1689                 :            : 
    1690                 :            :     // avoid overly frequent limit operations
    1691   [ +  +  +  + ]:        442 :     if (maxmbs > 0 && (now - this->last_cleaning) < 10) // probably not worth parametrizing
    1692                 :        282 :       return;
    1693                 :        160 :     this->last_cleaning = now;
    1694                 :            :     
    1695   [ +  +  +  - ]:        160 :     if (verbose > 3 && (this->max_mbs != maxmbs))
    1696   [ +  -  +  - ]:        192 :       obatched(clog) << "fdcache limited to maxmbs=" << maxmbs << endl;
    1697                 :            : 
    1698                 :        160 :     unique_lock<mutex> lock(fdcache_lock);
    1699                 :            :     
    1700                 :        160 :     this->max_mbs = maxmbs;
    1701                 :        160 :     double total_mb = 0.0;
    1702                 :            : 
    1703                 :        160 :     map<double, pair<string,string>> sorted_entries;
    1704         [ +  + ]:        442 :     for (auto &i: entries)
    1705                 :            :       {
    1706                 :        282 :         total_mb += i.second.fd_size_mb;
    1707                 :            : 
    1708                 :            :         // need a scalar quantity that combines these inputs in a sensible way:
    1709                 :            :         //
    1710                 :            :         // 1) freshness of this entry (last time it was accessed)
    1711                 :            :         // 2) size of this entry
    1712                 :            :         // 3) number of times it has been accessed (or if just prefetched with 0 accesses)
    1713                 :            :         // 4) latency it required to extract
    1714                 :            :         //
    1715                 :            :         // The lower the "score", the earlier garbage collection will
    1716                 :            :         // nuke it, so to prioritize entries for preservation, the
    1717                 :            :         // score should be higher, and vice versa.
    1718                 :        282 :         time_t factor_1_freshness = (now - i.second.freshness); // seconds
    1719                 :        282 :         double factor_2_size = i.second.fd_size_mb; // megabytes
    1720                 :        282 :         unsigned factor_3_accesscount = i.second.request_count; // units
    1721                 :        282 :         double factor_4_latency = i.second.latency; // seconds
    1722                 :            : 
    1723                 :            :         #if 0
    1724                 :            :         double score = - factor_1_freshness; // simple LRU
    1725                 :            :         #endif
    1726                 :            : 
    1727         [ +  + ]:        282 :         double score = 0.
    1728                 :        282 :           - log1p(factor_1_freshness)                // penalize old file
    1729                 :        282 :           - log1p(factor_2_size)                     // penalize large file
    1730                 :        282 :           + factor_4_latency * factor_3_accesscount; // reward slow + repeatedly read files
    1731                 :            : 
    1732         [ +  + ]:        282 :         if (verbose > 4)
    1733         [ +  - ]:          8 :           obatched(clog) << "fdcache scored score=" << score
    1734   [ +  -  +  - ]:          8 :                          << " a=" << i.first.first << " b=" << i.first.second
    1735   [ +  -  +  -  :         12 :                          << " f1=" << factor_1_freshness << " f2=" << factor_2_size
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    1736   [ +  -  +  -  :          4 :                          << " f3=" << factor_3_accesscount << " f4=" << factor_4_latency
          +  -  +  -  +  
                      - ]
    1737                 :          4 :                          << endl;
    1738                 :            :         
    1739   [ +  -  +  - ]:        564 :         sorted_entries.insert(make_pair(score, i.first));
    1740                 :            :       }
    1741                 :            : 
    1742                 :        160 :     unsigned cleaned = 0;
    1743                 :        160 :     unsigned entries_original = entries.size();
    1744                 :        160 :     double cleaned_score_min = DBL_MAX;
    1745                 :        160 :     double cleaned_score_max = DBL_MIN;
    1746                 :            :     
    1747                 :            :     // drop as many entries[] as needed to bring total mb down to the threshold
    1748         [ +  + ]:        442 :     for (auto &i: sorted_entries) // in increasing score order!
    1749                 :            :       {
    1750         [ -  + ]:        282 :         if (this->max_mbs > 0 // if this is not a "clear entire table"
    1751         [ #  # ]:          0 :             && total_mb < this->max_mbs) // we've cleared enough to meet threshold
    1752                 :            :           break; // stop clearing
    1753                 :            : 
    1754         [ -  + ]:        282 :         auto j = entries.find(i.second);
    1755         [ -  + ]:        282 :         if (j == entries.end())
    1756                 :          0 :           continue; // should not happen
    1757                 :            : 
    1758         [ +  + ]:        282 :         if (cleaned == 0)
    1759                 :         36 :           cleaned_score_min = i.first;
    1760                 :        282 :         cleaned++;
    1761                 :        282 :         cleaned_score_max = i.first;
    1762                 :            :         
    1763         [ +  + ]:        282 :         if (verbose > 3)
    1764   [ +  -  +  - ]:        504 :           obatched(clog) << "fdcache evicted score=" << i.first
    1765   [ +  -  +  - ]:        336 :                          << " a=" << i.second.first << " b=" << i.second.second
    1766   [ +  -  +  -  :        504 :                          << " fd=" << j->second.fd << " mb=" << j->second.fd_size_mb
          +  -  +  -  +  
                -  +  - ]
    1767   [ +  -  +  -  :        168 :                          << " rq=" << j->second.request_count << " lat=" << j->second.latency
             +  -  +  - ]
    1768   [ +  -  +  -  :        168 :                          << " fr=" << (now - j->second.freshness)
                   +  - ]
    1769                 :        168 :                          << endl;
    1770         [ -  + ]:        282 :         if (metrics_p)
    1771   [ #  #  #  #  :          0 :           inc_metric("fdcache_op_count","op","evict");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    1772                 :            :         
    1773                 :        282 :         total_mb -= j->second.fd_size_mb;
    1774                 :        282 :         unlink (j->second.fd.c_str());
    1775                 :        282 :         entries.erase(j);
    1776                 :            :       }
    1777                 :            : 
    1778         [ +  + ]:        160 :     if (metrics_p)
    1779   [ +  -  +  -  :        160 :       inc_metric("fdcache_op_count","op","evict_cycle");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    1780                 :            :     
    1781   [ +  -  +  + ]:        160 :     if (verbose > 1 && cleaned > 0)
    1782                 :            :       {
    1783   [ +  -  +  -  :        108 :         obatched(clog) << "fdcache evicted num=" << cleaned << " of=" << entries_original
             +  -  +  - ]
    1784   [ +  -  +  -  :         36 :                        << " min=" << cleaned_score_min << " max=" << cleaned_score_max
          +  -  +  -  +  
                      - ]
    1785                 :         36 :                        << endl;
    1786                 :            :       }
    1787                 :            :     
    1788   [ +  +  +  - ]:        160 :     if (metrics_p) set_metrics();
    1789                 :        160 :   }
    1790                 :            : 
    1791                 :            : 
    1792                 :         80 :   ~libarchive_fdcache()
    1793                 :            :   {
    1794                 :            :     // unlink any fdcache entries in $TMPDIR
    1795                 :            :     // don't update metrics; those globals may be already destroyed
    1796                 :         80 :     limit(0, false);
    1797                 :         80 :   }
    1798                 :            : };
    1799                 :            : static libarchive_fdcache fdcache;
    1800                 :            : 
    1801                 :            : /* Search ELF_FD for an ELF/DWARF section with name SECTION.
    1802                 :            :    If found copy the section to a temporary file and return
    1803                 :            :    its file descriptor, otherwise return -1.
    1804                 :            : 
    1805                 :            :    The temporary file's mtime will be set to PARENT_MTIME.
    1806                 :            :    B_SOURCE should be a description of the parent file suitable
    1807                 :            :    for printing to the log.  */
    1808                 :            : 
    1809                 :            : static int
    1810                 :         14 : extract_section (int elf_fd, int64_t parent_mtime,
    1811                 :            :                  const string& b_source, const string& section,
    1812                 :            :                  const timespec& extract_begin)
    1813                 :            : {
    1814                 :            :   /* Search the fdcache.  */
    1815                 :         14 :   struct stat fs;
    1816                 :         14 :   int fd = fdcache.lookup (b_source, section);
    1817         [ -  + ]:         14 :   if (fd >= 0)
    1818                 :            :     {
    1819         [ #  # ]:          0 :       if (fstat (fd, &fs) != 0)
    1820                 :            :         {
    1821         [ #  # ]:          0 :           if (verbose)
    1822         [ #  # ]:          0 :             obatched (clog) << "cannot fstate fdcache "
    1823   [ #  #  #  #  :          0 :                             << b_source << " " << section << endl;
                   #  # ]
    1824                 :          0 :           close (fd);
    1825                 :          0 :           return -1;
    1826                 :            :         }
    1827         [ #  # ]:          0 :       if ((int64_t) fs.st_mtime != parent_mtime)
    1828                 :            :         {
    1829         [ #  # ]:          0 :           if (verbose)
    1830         [ #  # ]:          0 :             obatched(clog) << "mtime mismatch for "
    1831   [ #  #  #  #  :          0 :                            << b_source << " " << section << endl;
                   #  # ]
    1832                 :          0 :           close (fd);
    1833                 :          0 :           return -1;
    1834                 :            :         }
    1835                 :            :       /* Success.  */
    1836                 :            :       return fd;
    1837                 :            :     }
    1838                 :            : 
    1839                 :         14 :   Elf *elf = elf_begin (elf_fd, ELF_C_READ_MMAP_PRIVATE, NULL);
    1840         [ -  + ]:         14 :   if (elf == NULL)
    1841                 :            :     return -1;
    1842                 :            : 
    1843                 :            :   /* Try to find the section and copy the contents into a separate file.  */
    1844                 :         14 :   try
    1845                 :            :     {
    1846                 :         14 :       size_t shstrndx;
    1847         [ +  - ]:         14 :       int rc = elf_getshdrstrndx (elf, &shstrndx);
    1848         [ -  + ]:         14 :       if (rc < 0)
    1849   [ #  #  #  # ]:          0 :         throw elfutils_exception (rc, "getshdrstrndx");
    1850                 :            : 
    1851                 :            :       Elf_Scn *scn = NULL;
    1852                 :        482 :       while (true)
    1853                 :            :         {
    1854         [ +  - ]:        248 :           scn = elf_nextscn (elf, scn);
    1855         [ +  - ]:        248 :           if (scn == NULL)
    1856                 :            :             break;
    1857                 :        248 :           GElf_Shdr shdr_storage;
    1858         [ +  - ]:        248 :           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
    1859         [ +  - ]:        248 :           if (shdr == NULL)
    1860                 :            :             break;
    1861                 :            : 
    1862         [ +  - ]:        248 :           const char *scn_name = elf_strptr (elf, shstrndx, shdr->sh_name);
    1863         [ +  - ]:        248 :           if (scn_name == NULL)
    1864                 :            :             break;
    1865         [ +  + ]:        248 :           if (scn_name == section)
    1866                 :            :             {
    1867                 :         14 :               Elf_Data *data = NULL;
    1868                 :            : 
    1869                 :            :               /* We found the desired section.  */
    1870         [ +  - ]:         14 :               data = elf_rawdata (scn, NULL);
    1871         [ -  + ]:         14 :               if (data == NULL)
    1872   [ #  #  #  #  :          0 :                 throw elfutils_exception (elf_errno (), "elfraw_data");
                   #  # ]
    1873         [ +  + ]:         14 :               if (data->d_buf == NULL)
    1874                 :            :                 {
    1875   [ +  -  +  - ]:         12 :                   obatched(clog) << "section " << section
    1876   [ +  -  +  - ]:          6 :                                  << " is empty" << endl;
    1877                 :          6 :                   break;
    1878                 :            :                 }
    1879                 :            : 
    1880                 :            :               /* Create temporary file containing the section.  */
    1881                 :          8 :               char *tmppath = NULL;
    1882                 :          8 :               rc = asprintf (&tmppath, "%s/debuginfod-section.XXXXXX", tmpdir.c_str());
    1883         [ -  + ]:          8 :               if (rc < 0)
    1884   [ #  #  #  # ]:          0 :                 throw libc_exception (ENOMEM, "cannot allocate tmppath");
    1885                 :          8 :               defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    1886         [ +  - ]:          8 :               fd = mkstemp (tmppath);
    1887         [ -  + ]:          8 :               if (fd < 0)
    1888   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot create temporary file");
    1889                 :            : 
    1890         [ +  - ]:          8 :               ssize_t res = write_retry (fd, data->d_buf, data->d_size);
    1891   [ +  -  -  + ]:          8 :               if (res < 0 || (size_t) res != data->d_size) {
    1892         [ #  # ]:          0 :                 close (fd);
    1893                 :          0 :                 unlink (tmppath);
    1894   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot write to temporary file");
    1895                 :            :               }
    1896                 :            : 
    1897                 :            :               /* Set mtime to be the same as the parent file's mtime.  */
    1898                 :          8 :               struct timespec tvs[2];
    1899         [ -  + ]:          8 :               if (fstat (elf_fd, &fs) != 0) {
    1900         [ #  # ]:          0 :                 close (fd);
    1901                 :          0 :                 unlink (tmppath);
    1902   [ #  #  #  # ]:          0 :                 throw libc_exception (errno, "cannot fstat file");
    1903                 :            :               }
    1904                 :            :               
    1905                 :          8 :               tvs[0].tv_sec = 0;
    1906                 :          8 :               tvs[0].tv_nsec = UTIME_OMIT;
    1907                 :          8 :               tvs[1] = fs.st_mtim;
    1908                 :          8 :               (void) futimens (fd, tvs);
    1909                 :            : 
    1910                 :          8 :               struct timespec extract_end;
    1911                 :          8 :               clock_gettime (CLOCK_MONOTONIC, &extract_end);
    1912                 :          8 :               double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
    1913                 :          8 :                 + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
    1914                 :            :               
    1915                 :            :               /* Add to fdcache.  */
    1916   [ +  -  +  - ]:          8 :               fdcache.intern (b_source, section, tmppath, data->d_size, true, extract_time);
    1917                 :          8 :               break;
    1918                 :         14 :             }
    1919                 :        234 :         }
    1920                 :            :     }
    1921         [ -  - ]:          0 :   catch (const reportable_exception &e)
    1922                 :            :     {
    1923         [ -  - ]:          0 :       e.report (clog);
    1924         [ -  - ]:          0 :       close (fd);
    1925                 :          0 :       fd = -1;
    1926                 :          0 :     }
    1927                 :            : 
    1928                 :         14 :   elf_end (elf);
    1929                 :            :   return fd;
    1930                 :            : }
    1931                 :            : 
    1932                 :            : static struct MHD_Response*
    1933                 :       1128 : handle_buildid_f_match (bool internal_req_t,
    1934                 :            :                         int64_t b_mtime,
    1935                 :            :                         const string& b_source0,
    1936                 :            :                         const string& section,
    1937                 :            :                         int *result_fd)
    1938                 :            : {
    1939                 :       1128 :   (void) internal_req_t; // ignored
    1940                 :            : 
    1941                 :       1128 :   struct timespec extract_begin;
    1942                 :       1128 :   clock_gettime (CLOCK_MONOTONIC, &extract_begin);
    1943                 :            :   
    1944                 :       1128 :   int fd = open(b_source0.c_str(), O_RDONLY);
    1945         [ -  + ]:       1128 :   if (fd < 0)
    1946   [ #  #  #  #  :          0 :     throw libc_exception (errno, string("open ") + b_source0);
             #  #  #  # ]
    1947                 :            :   
    1948                 :            :   // NB: use manual close(2) in error case instead of defer_dtor, because
    1949                 :            :   // in the normal case, we want to hand the fd over to libmicrohttpd for
    1950                 :            :   // file transfer.
    1951                 :            : 
    1952                 :       1128 :   struct stat s;
    1953                 :       1128 :   int rc = fstat(fd, &s);
    1954         [ -  + ]:       1128 :   if (rc < 0)
    1955                 :            :     {
    1956                 :          0 :       close(fd);
    1957   [ #  #  #  #  :          0 :       throw libc_exception (errno, string("fstat ") + b_source0);
             #  #  #  # ]
    1958                 :            :     }
    1959                 :            : 
    1960         [ -  + ]:       1128 :   if ((int64_t) s.st_mtime != b_mtime)
    1961                 :            :     {
    1962         [ #  # ]:          0 :       if (verbose)
    1963   [ #  #  #  # ]:          0 :         obatched(clog) << "mtime mismatch for " << b_source0 << endl;
    1964                 :          0 :       close(fd);
    1965                 :          0 :       return 0;
    1966                 :            :     }
    1967                 :            : 
    1968         [ +  + ]:       1128 :   if (!section.empty ())
    1969                 :            :     {
    1970                 :          6 :       int scn_fd = extract_section (fd, s.st_mtime, b_source0, section, extract_begin);
    1971                 :          6 :       close (fd);
    1972                 :            : 
    1973         [ +  + ]:          6 :       if (scn_fd >= 0)
    1974                 :          4 :         fd = scn_fd;
    1975                 :            :       else
    1976                 :            :         {
    1977         [ +  - ]:          2 :           if (verbose)
    1978         [ +  - ]:          6 :             obatched (clog) << "cannot find section " << section
    1979   [ +  -  +  -  :          2 :                             << " for " << b_source0 << endl;
                   +  - ]
    1980                 :          2 :           return 0;
    1981                 :            :         }
    1982                 :            : 
    1983                 :          4 :       rc = fstat(fd, &s);
    1984         [ -  + ]:          4 :       if (rc < 0)
    1985                 :            :         {
    1986                 :          0 :           close (fd);
    1987   [ #  #  #  #  :          0 :           throw libc_exception (errno, string ("fstat ") + b_source0
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1988   [ #  #  #  #  :          0 :                                        + string (" ") + section);
          #  #  #  #  #  
                      # ]
    1989                 :            :         }
    1990                 :            :     }
    1991                 :            : 
    1992                 :       1126 :   struct MHD_Response* r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
    1993   [ +  -  +  -  :       2252 :   inc_metric ("http_responses_total","result","file");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    1994         [ -  + ]:       1126 :   if (r == 0)
    1995                 :            :     {
    1996         [ #  # ]:          0 :       if (verbose)
    1997         [ #  # ]:          0 :         obatched(clog) << "cannot create fd-response for " << b_source0
    1998   [ #  #  #  #  :          0 :                        << " section=" << section << endl;
                   #  # ]
    1999                 :          0 :       close(fd);
    2000                 :            :     }
    2001                 :            :   else
    2002                 :            :     {
    2003                 :       1126 :       add_mhd_response_header (r, "Content-Type", "application/octet-stream");
    2004         [ +  - ]:       1126 :       add_mhd_response_header (r, "X-DEBUGINFOD-SIZE",
    2005                 :       1126 :                                to_string(s.st_size).c_str());
    2006                 :       1126 :       add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source0.c_str());
    2007                 :       1126 :       add_mhd_last_modified (r, s.st_mtime);
    2008         [ +  - ]:       1126 :       if (verbose > 1)
    2009   [ +  -  +  -  :       2252 :         obatched(clog) << "serving file " << b_source0 << " section=" << section << endl;
             +  -  +  - ]
    2010                 :            :       /* libmicrohttpd will close it. */
    2011         [ -  + ]:       1126 :       if (result_fd)
    2012                 :       1126 :         *result_fd = fd;
    2013                 :            :     }
    2014                 :            : 
    2015                 :            :   return r;
    2016                 :            : }
    2017                 :            : 
    2018                 :            : 
    2019                 :            : #ifdef USE_LZMA
    2020                 :            : struct lzma_exception: public reportable_exception
    2021                 :            : {
    2022                 :          0 :   lzma_exception(int rc, const string& msg):
    2023                 :            :     // liblzma doesn't have a lzma_ret -> string conversion function, so just
    2024                 :            :     // report the value.
    2025   [ #  #  #  #  :          0 :     reportable_exception(string ("lzma error: ") + msg + ": error " + to_string(rc)) {
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
    2026   [ #  #  #  #  :          0 :       inc_metric("error_count","lzma",to_string(rc));
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    2027         [ #  # ]:          0 :     }
    2028                 :            : };
    2029                 :            : 
    2030                 :            : // Neither RPM nor deb files support seeking to a specific file in the package.
    2031                 :            : // Instead, to extract a specific file, we normally need to read the archive
    2032                 :            : // sequentially until we find the file.  This is very slow for files at the end
    2033                 :            : // of a large package with lots of files, like kernel debuginfo.
    2034                 :            : //
    2035                 :            : // However, if the compression format used in the archive supports seeking, we
    2036                 :            : // can accelerate this.  As of July 2024, xz is the only widely-used format that
    2037                 :            : // supports seeking, and usually only in multi-threaded mode.  Luckily, the
    2038                 :            : // kernel-debuginfo package in Fedora and its downstreams, and the
    2039                 :            : // linux-image-*-dbg package in Debian and its downstreams, all happen to use
    2040                 :            : // this.
    2041                 :            : //
    2042                 :            : // The xz format [1] ends with an index of independently compressed blocks in
    2043                 :            : // the stream.  In RPM and deb files, the xz stream is the last thing in the
    2044                 :            : // file, so we assume that the xz Stream Footer is at the end of the package
    2045                 :            : // file and do everything relative to that.  For each file in the archive, we
    2046                 :            : // remember the size and offset of the file data in the uncompressed xz stream,
    2047                 :            : // then we use the index to seek to that offset when we need that file.
    2048                 :            : //
    2049                 :            : // 1: https://xz.tukaani.org/format/xz-file-format.txt
    2050                 :            : 
    2051                 :            : // Return whether an archive supports seeking.
    2052                 :            : static bool
    2053                 :        530 : is_seekable_archive (const string& rps, struct archive* a)
    2054                 :            : {
    2055                 :            :   // Only xz supports seeking.
    2056         [ +  + ]:        530 :   if (archive_filter_code (a, 0) != ARCHIVE_FILTER_XZ)
    2057                 :            :     return false;
    2058                 :            : 
    2059                 :        336 :   int fd = open (rps.c_str(), O_RDONLY);
    2060         [ -  + ]:        336 :   if (fd < 0)
    2061                 :            :     return false;
    2062                 :        336 :   defer_dtor<int,int> fd_closer (fd, close);
    2063                 :            : 
    2064                 :            :   // Seek to the xz Stream Footer.  We assume that it's the last thing in the
    2065                 :            :   // file, which is true for RPM and deb files.
    2066                 :        336 :   off_t footer_pos = -LZMA_STREAM_HEADER_SIZE;
    2067         [ -  + ]:        336 :   if (lseek (fd, footer_pos, SEEK_END) == -1)
    2068                 :            :     return false;
    2069                 :            : 
    2070                 :            :   // Decode the Stream Footer.
    2071                 :            :   uint8_t footer[LZMA_STREAM_HEADER_SIZE];
    2072                 :            :   size_t footer_read = 0;
    2073         [ +  + ]:        672 :   while (footer_read < sizeof (footer))
    2074                 :            :     {
    2075         [ -  + ]:        336 :       ssize_t bytes_read = read (fd, footer + footer_read,
    2076                 :            :                                  sizeof (footer) - footer_read);
    2077         [ -  + ]:        336 :       if (bytes_read < 0)
    2078                 :            :         {
    2079         [ #  # ]:          0 :           if (errno == EINTR)
    2080                 :          0 :             continue;
    2081                 :            :           return false;
    2082                 :            :         }
    2083         [ -  + ]:        336 :       if (bytes_read == 0)
    2084                 :            :         return false;
    2085                 :        336 :       footer_read += bytes_read;
    2086                 :            :     }
    2087                 :            : 
    2088                 :        336 :   lzma_stream_flags stream_flags;
    2089                 :        336 :   lzma_ret ret = lzma_stream_footer_decode (&stream_flags, footer);
    2090         [ -  + ]:        336 :   if (ret != LZMA_OK)
    2091                 :            :     return false;
    2092                 :            : 
    2093                 :            :   // Seek to the xz Index.
    2094         [ -  + ]:        336 :   if (lseek (fd, footer_pos - stream_flags.backward_size, SEEK_END) == -1)
    2095                 :            :     return false;
    2096                 :            : 
    2097                 :            :   // Decode the Number of Records in the Index.  liblzma doesn't have an API for
    2098                 :            :   // this if you don't want to decode the whole Index, so we have to do it
    2099                 :            :   // ourselves.
    2100                 :            :   //
    2101                 :            :   // We need 1 byte for the Index Indicator plus 1-9 bytes for the
    2102                 :            :   // variable-length integer Number of Records.
    2103                 :            :   uint8_t index[10];
    2104                 :            :   size_t index_read = 0;
    2105         [ +  + ]:        672 :   while (index_read == 0) {
    2106         [ +  - ]:        336 :       ssize_t bytes_read = read (fd, index, sizeof (index));
    2107         [ -  + ]:        336 :       if (bytes_read < 0)
    2108                 :            :         {
    2109         [ #  # ]:          0 :           if (errno == EINTR)
    2110                 :          0 :             continue;
    2111                 :            :           return false;
    2112                 :            :         }
    2113         [ -  + ]:        336 :       if (bytes_read == 0)
    2114                 :            :         return false;
    2115                 :        336 :       index_read += bytes_read;
    2116                 :            :   }
    2117                 :            :   // The Index Indicator must be 0.
    2118         [ -  + ]:        336 :   if (index[0] != 0)
    2119                 :            :     return false;
    2120                 :            : 
    2121                 :        336 :   lzma_vli num_records;
    2122                 :        336 :   size_t pos = 0;
    2123                 :        336 :   size_t in_pos = 1;
    2124                 :        336 :   while (true)
    2125                 :            :     {
    2126         [ -  + ]:        336 :       if (in_pos >= index_read)
    2127                 :            :         {
    2128         [ #  # ]:          0 :           ssize_t bytes_read = read (fd, index, sizeof (index));
    2129         [ #  # ]:          0 :           if (bytes_read < 0)
    2130                 :            :           {
    2131         [ #  # ]:          0 :             if (errno == EINTR)
    2132                 :          0 :               continue;
    2133                 :            :             return false;
    2134                 :            :           }
    2135         [ #  # ]:          0 :           if (bytes_read == 0)
    2136                 :            :             return false;
    2137                 :          0 :           index_read = bytes_read;
    2138                 :          0 :           in_pos = 0;
    2139                 :            :         }
    2140                 :        336 :       ret = lzma_vli_decode (&num_records, &pos, index, &in_pos, index_read);
    2141         [ -  + ]:        336 :       if (ret == LZMA_STREAM_END)
    2142                 :            :         break;
    2143         [ #  # ]:          0 :       else if (ret != LZMA_OK)
    2144                 :            :         return false;
    2145                 :            :     }
    2146                 :            : 
    2147         [ +  + ]:        336 :   if (verbose > 3)
    2148   [ +  -  +  -  :        572 :     obatched(clog) << rps << " has " << num_records << " xz Blocks" << endl;
          +  -  +  -  +  
                      - ]
    2149                 :            : 
    2150                 :            :   // The file is only seekable if it has more than one Block.
    2151                 :        336 :   return num_records > 1;
    2152                 :        530 : }
    2153                 :            : 
    2154                 :            : // Read the Index at the end of an xz file.
    2155                 :            : static lzma_index*
    2156                 :         94 : read_xz_index (int fd)
    2157                 :            : {
    2158                 :         94 :   off_t footer_pos = -LZMA_STREAM_HEADER_SIZE;
    2159         [ -  + ]:         94 :   if (lseek (fd, footer_pos, SEEK_END) == -1)
    2160   [ #  #  #  # ]:          0 :     throw libc_exception (errno, "lseek");
    2161                 :            : 
    2162                 :            :   uint8_t footer[LZMA_STREAM_HEADER_SIZE];
    2163                 :            :   size_t footer_read = 0;
    2164         [ +  + ]:        188 :   while (footer_read < sizeof (footer))
    2165                 :            :     {
    2166         [ -  + ]:         94 :       ssize_t bytes_read = read (fd, footer + footer_read,
    2167                 :            :                                  sizeof (footer) - footer_read);
    2168         [ -  + ]:         94 :       if (bytes_read < 0)
    2169                 :            :         {
    2170         [ #  # ]:          0 :           if (errno == EINTR)
    2171                 :          0 :             continue;
    2172   [ #  #  #  # ]:          0 :           throw libc_exception (errno, "read");
    2173                 :            :         }
    2174         [ -  + ]:         94 :       if (bytes_read == 0)
    2175   [ #  #  #  # ]:          0 :         throw reportable_exception ("truncated file");
    2176                 :         94 :       footer_read += bytes_read;
    2177                 :            :     }
    2178                 :            : 
    2179                 :         94 :   lzma_stream_flags stream_flags;
    2180                 :         94 :   lzma_ret ret = lzma_stream_footer_decode (&stream_flags, footer);
    2181         [ -  + ]:         94 :   if (ret != LZMA_OK)
    2182   [ #  #  #  # ]:          0 :     throw lzma_exception (ret, "lzma_stream_footer_decode");
    2183                 :            : 
    2184         [ -  + ]:         94 :   if (lseek (fd, footer_pos - stream_flags.backward_size, SEEK_END) == -1)
    2185   [ #  #  #  # ]:          0 :     throw libc_exception (errno, "lseek");
    2186                 :            : 
    2187                 :         94 :   lzma_stream strm = LZMA_STREAM_INIT;
    2188                 :         94 :   lzma_index* index = NULL;
    2189                 :         94 :   ret = lzma_index_decoder (&strm, &index, UINT64_MAX);
    2190         [ -  + ]:         94 :   if (ret != LZMA_OK)
    2191   [ #  #  #  # ]:          0 :     throw lzma_exception (ret, "lzma_index_decoder");
    2192                 :         94 :   defer_dtor<lzma_stream*,void> strm_ender (&strm, lzma_end);
    2193                 :            : 
    2194                 :         94 :   uint8_t in_buf[4096];
    2195                 :         94 :   while (true)
    2196                 :            :     {
    2197         [ +  - ]:         94 :       if (strm.avail_in == 0)
    2198                 :            :         {
    2199         [ +  - ]:         94 :           ssize_t bytes_read = read (fd, in_buf, sizeof (in_buf));
    2200         [ -  + ]:         94 :           if (bytes_read < 0)
    2201                 :            :             {
    2202         [ #  # ]:          0 :               if (errno == EINTR)
    2203                 :          0 :                 continue;
    2204   [ #  #  #  # ]:          0 :               throw libc_exception (errno, "read");
    2205                 :            :             }
    2206         [ -  + ]:         94 :           if (bytes_read == 0)
    2207   [ #  #  #  # ]:          0 :             throw reportable_exception ("truncated file");
    2208                 :         94 :           strm.avail_in = bytes_read;
    2209                 :         94 :           strm.next_in = in_buf;
    2210                 :            :         }
    2211                 :            : 
    2212                 :         94 :         ret = lzma_code (&strm, LZMA_RUN);
    2213         [ -  + ]:         94 :         if (ret == LZMA_STREAM_END)
    2214                 :            :           break;
    2215         [ #  # ]:          0 :         else if (ret != LZMA_OK)
    2216   [ #  #  #  # ]:          0 :           throw lzma_exception (ret, "lzma_code index");
    2217                 :            :     }
    2218                 :            : 
    2219                 :         94 :   ret = lzma_index_stream_flags (index, &stream_flags);
    2220         [ -  + ]:         94 :   if (ret != LZMA_OK)
    2221                 :            :     {
    2222                 :          0 :       lzma_index_end (index, NULL);
    2223   [ #  #  #  # ]:          0 :       throw lzma_exception (ret, "lzma_index_stream_flags");
    2224                 :            :     }
    2225                 :         94 :   return index;
    2226                 :         94 : }
    2227                 :            : 
    2228                 :            : static void
    2229                 :         94 : my_lzma_index_end (lzma_index* index)
    2230                 :            : {
    2231                 :         94 :   lzma_index_end (index, NULL);
    2232                 :         94 : }
    2233                 :            : 
    2234                 :            : static void
    2235                 :        102 : free_lzma_block_filter_options (lzma_block* block)
    2236                 :            : {
    2237         [ +  + ]:        510 :   for (int i = 0; i < LZMA_FILTERS_MAX; i++)
    2238                 :            :     {
    2239                 :        408 :       free (block->filters[i].options);
    2240                 :        408 :       block->filters[i].options = NULL;
    2241                 :            :     }
    2242                 :        102 : }
    2243                 :            : 
    2244                 :            : static void
    2245                 :         94 : free_lzma_block_filters (lzma_block* block)
    2246                 :            : {
    2247         [ +  - ]:         94 :   if (block->filters != NULL)
    2248                 :            :     {
    2249                 :         94 :       free_lzma_block_filter_options (block);
    2250                 :         94 :       free (block->filters);
    2251                 :            :     }
    2252                 :         94 : }
    2253                 :            : 
    2254                 :            : static void
    2255                 :         94 : extract_xz_blocks_into_fd (const string& srcpath,
    2256                 :            :                            int src,
    2257                 :            :                            int dst,
    2258                 :            :                            lzma_index_iter* iter,
    2259                 :            :                            uint64_t offset,
    2260                 :            :                            uint64_t size)
    2261                 :            : {
    2262                 :            :   // Seek to the Block.  Seeking from the end using the compressed size from the
    2263                 :            :   // footer means we don't need to know where the xz stream starts in the
    2264                 :            :   // archive.
    2265         [ -  + ]:         94 :   if (lseek (src,
    2266                 :         94 :              (off_t) iter->block.compressed_stream_offset
    2267                 :         94 :              - (off_t) iter->stream.compressed_size,
    2268                 :            :              SEEK_END) == -1)
    2269   [ #  #  #  # ]:          0 :     throw libc_exception (errno, "lseek");
    2270                 :            : 
    2271                 :         94 :   offset -= iter->block.uncompressed_file_offset;
    2272                 :            : 
    2273                 :         94 :   lzma_block block{};
    2274                 :         94 :   block.filters = (lzma_filter*) calloc (LZMA_FILTERS_MAX + 1,
    2275                 :            :                                          sizeof (lzma_filter));
    2276         [ -  + ]:         94 :   if (block.filters == NULL)
    2277   [ #  #  #  # ]:          0 :     throw libc_exception (ENOMEM, "cannot allocate lzma_block filters");
    2278                 :         94 :   defer_dtor<lzma_block*,void> filters_freer (&block, free_lzma_block_filters);
    2279                 :            : 
    2280                 :         94 :   uint8_t in_buf[4096];
    2281                 :         94 :   uint8_t out_buf[4096];
    2282                 :         94 :   size_t header_read = 0;
    2283                 :         94 :   bool need_log_extracting = verbose > 3;
    2284                 :            :   while (true)
    2285                 :            :     {
    2286                 :            :       // The first byte of the Block is the encoded Block Header Size.  Read the
    2287                 :            :       // first byte and whatever extra fits in the buffer.
    2288         [ +  + ]:        196 :       while (header_read == 0)
    2289                 :            :         {
    2290         [ +  - ]:         94 :           ssize_t bytes_read = read (src, in_buf, sizeof (in_buf));
    2291         [ -  + ]:         94 :           if (bytes_read < 0)
    2292                 :            :             {
    2293         [ #  # ]:          0 :               if (errno == EINTR)
    2294                 :          0 :                 continue;
    2295   [ #  #  #  # ]:          0 :               throw libc_exception (errno, "read");
    2296                 :            :             }
    2297         [ -  + ]:         94 :           if (bytes_read == 0)
    2298   [ #  #  #  # ]:          0 :             throw reportable_exception ("truncated file");
    2299                 :         94 :           header_read += bytes_read;
    2300                 :            :         }
    2301                 :            : 
    2302                 :        102 :       block.header_size = lzma_block_header_size_decode (in_buf[0]);
    2303                 :            : 
    2304                 :            :       // If we didn't buffer the whole Block Header earlier, get the rest.
    2305                 :        102 :       eu_static_assert (sizeof (in_buf)
    2306                 :            :                         >= lzma_block_header_size_decode (UINT8_MAX));
    2307         [ -  + ]:        102 :       while (header_read < block.header_size)
    2308                 :            :         {
    2309         [ #  # ]:          0 :           ssize_t bytes_read = read (src, in_buf + header_read,
    2310                 :            :                                      sizeof (in_buf) - header_read);
    2311         [ #  # ]:          0 :           if (bytes_read < 0)
    2312                 :            :             {
    2313         [ #  # ]:          0 :               if (errno == EINTR)
    2314                 :          0 :                 continue;
    2315   [ #  #  #  # ]:          0 :               throw libc_exception (errno, "read");
    2316                 :            :             }
    2317         [ #  # ]:          0 :           if (bytes_read == 0)
    2318   [ #  #  #  # ]:          0 :             throw reportable_exception ("truncated file");
    2319                 :          0 :           header_read += bytes_read;
    2320                 :            :         }
    2321                 :            : 
    2322                 :            :       // Decode the Block Header.
    2323                 :        102 :       block.check = iter->stream.flags->check;
    2324                 :        102 :       lzma_ret ret = lzma_block_header_decode (&block, NULL, in_buf);
    2325         [ -  + ]:        102 :       if (ret != LZMA_OK)
    2326   [ #  #  #  # ]:          0 :         throw lzma_exception (ret, "lzma_block_header_decode");
    2327                 :        102 :       ret = lzma_block_compressed_size (&block, iter->block.unpadded_size);
    2328         [ -  + ]:        102 :       if (ret != LZMA_OK)
    2329   [ #  #  #  # ]:          0 :         throw lzma_exception (ret, "lzma_block_compressed_size");
    2330                 :            : 
    2331                 :            :       // Start decoding the Block data.
    2332                 :        102 :       lzma_stream strm = LZMA_STREAM_INIT;
    2333                 :        102 :       ret = lzma_block_decoder (&strm, &block);
    2334         [ -  + ]:        102 :       if (ret != LZMA_OK)
    2335   [ #  #  #  # ]:          0 :         throw lzma_exception (ret, "lzma_block_decoder");
    2336                 :        102 :       defer_dtor<lzma_stream*,void> strm_ender (&strm, lzma_end);
    2337                 :            : 
    2338                 :            :       // We might still have some input buffered from when we read the header.
    2339                 :        102 :       strm.avail_in = header_read - block.header_size;
    2340                 :        102 :       strm.next_in = in_buf + block.header_size;
    2341                 :        102 :       strm.avail_out = sizeof (out_buf);
    2342                 :        102 :       strm.next_out = out_buf;
    2343                 :      11518 :       while (true)
    2344                 :            :         {
    2345         [ +  + ]:      11518 :           if (strm.avail_in == 0)
    2346                 :            :             {
    2347         [ +  - ]:         14 :               ssize_t bytes_read = read (src, in_buf, sizeof (in_buf));
    2348         [ -  + ]:         14 :               if (bytes_read < 0)
    2349                 :            :                 {
    2350         [ #  # ]:          0 :                   if (errno == EINTR)
    2351                 :          0 :                     continue;
    2352   [ #  #  #  # ]:          0 :                   throw libc_exception (errno, "read");
    2353                 :            :                 }
    2354         [ -  + ]:         14 :               if (bytes_read == 0)
    2355   [ #  #  #  # ]:          0 :                 throw reportable_exception ("truncated file");
    2356                 :         14 :               strm.avail_in = bytes_read;
    2357                 :         14 :               strm.next_in = in_buf;
    2358                 :            :             }
    2359                 :            : 
    2360                 :      11518 :           ret = lzma_code (&strm, LZMA_RUN);
    2361         [ -  + ]:      11518 :           if (ret != LZMA_OK && ret != LZMA_STREAM_END)
    2362   [ #  #  #  # ]:          0 :             throw lzma_exception (ret, "lzma_code block");
    2363                 :            : 
    2364                 :            :           // Throw away anything we decode until we reach the offset, then
    2365                 :            :           // start writing to the destination.
    2366         [ +  + ]:      11518 :           if (strm.total_out > offset)
    2367                 :            :             {
    2368                 :       2898 :               size_t bytes_to_write = strm.next_out - out_buf;
    2369                 :       2898 :               uint8_t* buf_to_write = out_buf;
    2370                 :            : 
    2371                 :            :               // Ignore anything in the buffer before the offset.
    2372         [ +  + ]:       2898 :               if (bytes_to_write > strm.total_out - offset)
    2373                 :            :                 {
    2374                 :         88 :                   buf_to_write += bytes_to_write - (strm.total_out - offset);
    2375                 :         88 :                   bytes_to_write = strm.total_out - offset;
    2376                 :            :                 }
    2377                 :            : 
    2378                 :            :               // Ignore anything after the size.
    2379         [ +  + ]:       2898 :               if (strm.total_out - offset >= size)
    2380                 :         94 :                 bytes_to_write -= strm.total_out - offset - size;
    2381                 :            : 
    2382         [ +  + ]:       2898 :               if (need_log_extracting)
    2383                 :            :                 {
    2384   [ +  -  +  - ]:         24 :                   obatched(clog) << "extracting from xz archive " << srcpath
    2385   [ +  -  +  -  :         12 :                                  << " size=" << size << endl;
                   +  - ]
    2386                 :         12 :                   need_log_extracting = false;
    2387                 :            :                 }
    2388                 :            : 
    2389         [ +  + ]:       5796 :               while (bytes_to_write > 0)
    2390                 :            :                 {
    2391         [ +  - ]:       2898 :                   ssize_t written = write (dst, buf_to_write, bytes_to_write);
    2392         [ -  + ]:       2898 :                   if (written < 0)
    2393                 :            :                     {
    2394         [ #  # ]:          0 :                       if (errno == EAGAIN)
    2395                 :          0 :                         continue;
    2396   [ #  #  #  # ]:          0 :                       throw libc_exception (errno, "write");
    2397                 :            :                     }
    2398                 :       2898 :                   bytes_to_write -= written;
    2399                 :       2898 :                   buf_to_write += written;
    2400                 :            :                 }
    2401                 :            : 
    2402                 :            :               // If we reached the size, we're done.
    2403         [ +  + ]:       2898 :               if (strm.total_out - offset >= size)
    2404                 :         94 :                 return;
    2405                 :            :             }
    2406                 :            : 
    2407                 :      11424 :           strm.avail_out = sizeof (out_buf);
    2408                 :      11424 :           strm.next_out = out_buf;
    2409                 :            : 
    2410         [ +  + ]:      11424 :           if (ret == LZMA_STREAM_END)
    2411                 :            :             break;
    2412                 :            :         }
    2413                 :            : 
    2414                 :            :       // This Block didn't have enough data.  Go to the next one.
    2415         [ -  + ]:          8 :       if (lzma_index_iter_next (iter, LZMA_INDEX_ITER_BLOCK))
    2416   [ #  #  #  # ]:          0 :         throw reportable_exception ("no more blocks");
    2417         [ +  - ]:          8 :       if (strm.total_out > offset)
    2418                 :          8 :         size -= strm.total_out - offset;
    2419                 :          8 :       offset = 0;
    2420                 :            :       // If we had any buffered input left, move it to the beginning of the
    2421                 :            :       // buffer to decode the next Block Header.
    2422         [ +  - ]:          8 :       if (strm.avail_in > 0)
    2423                 :            :         {
    2424                 :          8 :           memmove (in_buf, strm.next_in, strm.avail_in);
    2425                 :          8 :           header_read = strm.avail_in;
    2426                 :            :         }
    2427                 :            :       else
    2428                 :            :         header_read = 0;
    2429                 :          8 :       free_lzma_block_filter_options (&block);
    2430                 :        102 :     }
    2431                 :         94 : }
    2432                 :            : 
    2433                 :            : static int
    2434                 :         94 : extract_from_seekable_archive (const string& srcpath,
    2435                 :            :                                char* tmppath,
    2436                 :            :                                uint64_t offset,
    2437                 :            :                                uint64_t size)
    2438                 :            : {
    2439   [ +  -  +  -  :        188 :   inc_metric ("seekable_archive_extraction_attempts","type","xz");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    2440                 :         94 :   try
    2441                 :            :     {
    2442         [ +  - ]:         94 :       int src = open (srcpath.c_str(), O_RDONLY);
    2443         [ -  + ]:         94 :       if (src < 0)
    2444   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("open ") + srcpath);
             #  #  #  # ]
    2445                 :         94 :       defer_dtor<int,int> src_closer (src, close);
    2446                 :            : 
    2447         [ +  - ]:         94 :       lzma_index* index = read_xz_index (src);
    2448                 :         94 :       defer_dtor<lzma_index*,void> index_ender (index, my_lzma_index_end);
    2449                 :            : 
    2450                 :            :       // Find the Block containing the offset.
    2451                 :         94 :       lzma_index_iter iter;
    2452                 :         94 :       lzma_index_iter_init (&iter, index);
    2453         [ -  + ]:         94 :       if (lzma_index_iter_locate (&iter, offset))
    2454   [ #  #  #  # ]:          0 :         throw reportable_exception ("offset not found");
    2455                 :            : 
    2456         [ +  + ]:         94 :       if (verbose > 3)
    2457   [ +  -  +  - ]:         36 :         obatched(clog) << "seeking in xz archive " << srcpath
    2458   [ +  -  +  -  :         12 :                        << " offset=" << offset << " block_offset="
                   +  - ]
    2459   [ +  -  +  - ]:         12 :                        << iter.block.uncompressed_file_offset << endl;
    2460                 :            : 
    2461         [ +  - ]:         94 :       int dst = mkstemp (tmppath);
    2462         [ -  + ]:         94 :       if (dst < 0)
    2463   [ #  #  #  # ]:          0 :         throw libc_exception (errno, "cannot create temporary file");
    2464                 :            : 
    2465                 :         94 :       try
    2466                 :            :         {
    2467         [ +  - ]:         94 :           extract_xz_blocks_into_fd (srcpath, src, dst, &iter, offset, size);
    2468                 :            :         }
    2469                 :          0 :       catch (...)
    2470                 :            :         {
    2471                 :          0 :           unlink (tmppath);
    2472         [ -  - ]:          0 :           close (dst);
    2473                 :          0 :           throw;
    2474                 :          0 :         }
    2475                 :            : 
    2476   [ +  -  +  -  :        188 :       inc_metric ("seekable_archive_extraction_successes","type","xz");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    2477                 :         94 :       return dst;
    2478                 :         94 :     }
    2479         [ -  - ]:          0 :   catch (const reportable_exception &e)
    2480                 :            :     {
    2481   [ -  -  -  -  :          0 :       inc_metric ("seekable_archive_extraction_failures","type","xz");
          -  -  -  -  -  
          -  -  -  -  -  
                   -  - ]
    2482         [ -  - ]:          0 :       if (verbose)
    2483   [ -  -  -  - ]:          0 :         obatched(clog) << "failed to extract from seekable xz archive "
    2484   [ -  -  -  -  :          0 :                        << srcpath << ": " << e.message << endl;
                   -  - ]
    2485                 :          0 :       return -1;
    2486                 :          0 :     }
    2487                 :            : }
    2488                 :            : #else
    2489                 :            : static bool
    2490                 :            : is_seekable_archive (const string& rps __attribute__ ((unused)),
    2491                 :            :                      struct archive* a __attribute__ ((unused)))
    2492                 :            : {
    2493                 :            :   return false;
    2494                 :            : }
    2495                 :            : static int
    2496                 :            : extract_from_seekable_archive (const string& srcpath __attribute__ ((unused)),
    2497                 :            :                                char* tmppath __attribute__ ((unused)),
    2498                 :            :                                uint64_t offset __attribute__ ((unused)),
    2499                 :            :                                uint64_t size __attribute__ ((unused)))
    2500                 :            : {
    2501                 :            :   return -1;
    2502                 :            : }
    2503                 :            : #endif
    2504                 :            : 
    2505                 :            : 
    2506                 :            : // For security/portability reasons, many distro-package archives have
    2507                 :            : // a "./" in front of path names; others have nothing, others have
    2508                 :            : // "/".  Canonicalize them all to a single leading "/", with the
    2509                 :            : // assumption that this matches the dwarf-derived file names too.
    2510                 :       1314 : string canonicalized_archive_entry_pathname(struct archive_entry *e)
    2511                 :            : {
    2512                 :       1314 :   string fn = archive_entry_pathname(e);
    2513         [ -  + ]:       1314 :   if (fn.size() == 0)
    2514                 :          0 :     return fn;
    2515         [ -  + ]:       1314 :   if (fn[0] == '/')
    2516                 :          0 :     return fn;
    2517         [ +  + ]:       1314 :   if (fn[0] == '.')
    2518         [ +  - ]:       1082 :     return fn.substr(1);
    2519                 :            :   else
    2520   [ +  -  +  -  :        464 :     return string("/")+fn;
                   -  - ]
    2521                 :       1314 : }
    2522                 :            : 
    2523                 :            : 
    2524                 :            : // NB: takes ownership of, and may reassign, fd.
    2525                 :            : static struct MHD_Response*
    2526                 :       1002 : create_buildid_r_response (int64_t b_mtime0,
    2527                 :            :                            const string& b_source0,
    2528                 :            :                            const string& b_source1,
    2529                 :            :                            const string& section,
    2530                 :            :                            const string& ima_sig,
    2531                 :            :                            const char* tmppath,
    2532                 :            :                            int& fd,
    2533                 :            :                            off_t size,
    2534                 :            :                            time_t mtime,
    2535                 :            :                            const string& metric,
    2536                 :            :                            const struct timespec& extract_begin)
    2537                 :            : {
    2538         [ +  + ]:       1002 :   if (tmppath != NULL)
    2539                 :            :     {
    2540                 :        230 :       struct timespec extract_end;
    2541                 :        230 :       clock_gettime (CLOCK_MONOTONIC, &extract_end);
    2542                 :        230 :       double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
    2543                 :        230 :         + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
    2544         [ +  - ]:        460 :       fdcache.intern(b_source0, b_source1, tmppath, size, true, extract_time);
    2545                 :            :     }
    2546                 :            : 
    2547         [ +  + ]:       1002 :   if (!section.empty ())
    2548                 :            :     {
    2549   [ +  -  +  - ]:          8 :       int scn_fd = extract_section (fd, b_mtime0,
    2550   [ +  -  -  + ]:         16 :                                     b_source0 + ":" + b_source1,
    2551                 :            :                                     section, extract_begin);
    2552                 :          8 :       close (fd);
    2553         [ +  + ]:          8 :       if (scn_fd >= 0)
    2554                 :          4 :         fd = scn_fd;
    2555                 :            :       else
    2556                 :            :         {
    2557         [ +  - ]:          4 :           if (verbose)
    2558         [ +  - ]:         12 :             obatched (clog) << "cannot find section " << section
    2559                 :            :                             << " for archive " << b_source0
    2560   [ +  -  +  -  :          4 :                             << " file " << b_source1 << endl;
          +  -  +  -  +  
                      - ]
    2561                 :          4 :           return 0;
    2562                 :            :         }
    2563                 :            : 
    2564                 :          4 :       struct stat fs;
    2565         [ -  + ]:          4 :       if (fstat (fd, &fs) < 0)
    2566                 :            :         {
    2567                 :          0 :           close (fd);
    2568   [ #  #  #  # ]:          0 :           throw libc_exception (errno,
    2569   [ #  #  #  #  :          0 :             string ("fstat ") + b_source0 + string (" ") + section);
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
    2570                 :            :         }
    2571                 :          4 :       size = fs.st_size;
    2572                 :            :     }
    2573                 :            : 
    2574                 :        998 :   struct MHD_Response* r = MHD_create_response_from_fd (size, fd);
    2575         [ -  + ]:        998 :   if (r == 0)
    2576                 :            :     {
    2577         [ #  # ]:          0 :       if (verbose)
    2578   [ #  #  #  # ]:          0 :         obatched(clog) << "cannot create fd-response for " << b_source0 << endl;
    2579                 :          0 :       close(fd);
    2580                 :            :     }
    2581                 :            :   else
    2582                 :            :     {
    2583   [ +  -  +  -  :       1996 :       inc_metric ("http_responses_total","result",metric);
             -  +  -  - ]
    2584                 :        998 :       add_mhd_response_header (r, "Content-Type", "application/octet-stream");
    2585         [ +  - ]:        998 :       add_mhd_response_header (r, "X-DEBUGINFOD-SIZE", to_string(size).c_str());
    2586                 :        998 :       add_mhd_response_header (r, "X-DEBUGINFOD-ARCHIVE", b_source0.c_str());
    2587                 :        998 :       add_mhd_response_header (r, "X-DEBUGINFOD-FILE", b_source1.c_str());
    2588         [ -  + ]:        998 :       if(!ima_sig.empty()) add_mhd_response_header(r, "X-DEBUGINFOD-IMASIGNATURE", ima_sig.c_str());
    2589                 :        998 :       add_mhd_last_modified (r, mtime);
    2590         [ -  + ]:        998 :       if (verbose > 1)
    2591         [ +  - ]:       2994 :         obatched(clog) << "serving " << metric << " " << b_source0
    2592                 :            :                        << " file " << b_source1
    2593                 :            :                        << " section=" << section
    2594   [ +  -  +  -  :        998 :                        << " IMA signature=" << ima_sig << endl;
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
    2595                 :            :       /* libmicrohttpd will close fd. */
    2596                 :            :     }
    2597                 :            :   return r;
    2598                 :            : }
    2599                 :            : 
    2600                 :            : static struct MHD_Response*
    2601                 :       1058 : handle_buildid_r_match (bool internal_req_p,
    2602                 :            :                         int64_t b_mtime,
    2603                 :            :                         const string& b_source0,
    2604                 :            :                         const string& b_source1,
    2605                 :            :                         int64_t b_id0,
    2606                 :            :                         int64_t b_id1,
    2607                 :            :                         const string& section,
    2608                 :            :                         int *result_fd)
    2609                 :            : {
    2610                 :       1058 :   struct timespec extract_begin;
    2611                 :       1058 :   clock_gettime (CLOCK_MONOTONIC, &extract_begin);
    2612                 :            : 
    2613                 :       1058 :   struct stat fs;
    2614                 :       1058 :   int rc = stat (b_source0.c_str(), &fs);
    2615         [ +  + ]:       1058 :   if (rc != 0)
    2616   [ +  -  +  -  :        116 :     throw libc_exception (errno, string("stat ") + b_source0);
             +  -  -  + ]
    2617                 :            : 
    2618         [ -  + ]:       1000 :   if ((int64_t) fs.st_mtime != b_mtime)
    2619                 :            :     {
    2620         [ #  # ]:          0 :       if (verbose)
    2621   [ #  #  #  # ]:          0 :         obatched(clog) << "mtime mismatch for " << b_source0 << endl;
    2622                 :          0 :       return 0;
    2623                 :            :     }
    2624                 :            : 
    2625                 :            :   // Extract the IMA per-file signature (if it exists)
    2626                 :       1000 :   string ima_sig = "";
    2627                 :            :   #ifdef ENABLE_IMA_VERIFICATION
    2628                 :            :   do
    2629                 :            :     {
    2630                 :            :       FD_t rpm_fd;
    2631                 :            :       if(!(rpm_fd = Fopen(b_source0.c_str(), "r.ufdio"))) // read, uncompressed, rpm/rpmio.h
    2632                 :            :         {
    2633                 :            :           if (verbose) obatched(clog) << "There was an error while opening " << b_source0 << endl;
    2634                 :            :           break; // Exit IMA extraction
    2635                 :            :         }
    2636                 :            : 
    2637                 :            :       Header rpm_hdr;
    2638                 :            :       if(RPMRC_FAIL == rpmReadPackageFile(NULL, rpm_fd, b_source0.c_str(), &rpm_hdr))
    2639                 :            :         {
    2640                 :            :           if (verbose) obatched(clog) << "There was an error while reading the header of " << b_source0 << endl;
    2641                 :            :           Fclose(rpm_fd);
    2642                 :            :           break; // Exit IMA extraction
    2643                 :            :         }
    2644                 :            : 
    2645                 :            :       // Fill sig_tag_data with an alloc'd copy of the array of IMA signatures (if they exist)
    2646                 :            :       struct rpmtd_s sig_tag_data;
    2647                 :            :       rpmtdReset(&sig_tag_data);
    2648                 :            :       do{ /* A do-while so we can break out of the koji sigcache checking on failure */
    2649                 :            :         if(requires_koji_sigcache_mapping)
    2650                 :            :           {
    2651                 :            :             /* NB: Koji builds result in a directory structure like the following
    2652                 :            :                - PACKAGE/VERSION/RELEASE
    2653                 :            :                - ARCH1
    2654                 :            :                - foo.rpm           // The rpm known by debuginfod
    2655                 :            :                - ...
    2656                 :            :                - ARCHN
    2657                 :            :                - data
    2658                 :            :                - signed            // Periodically purged (and not scanned by debuginfod)
    2659                 :            :                - sigcache
    2660                 :            :                - ARCH1
    2661                 :            :                - foo.rpm.sig   // An empty rpm header
    2662                 :            :                - ...
    2663                 :            :                - ARCHN
    2664                 :            :                - PACKAGE_KEYID1
    2665                 :            :                - ARCH1
    2666                 :            :                - foo.rpm.sig   // The header of the signed rpm. This is the file we need to extract the IMA signatures
    2667                 :            :                - ...
    2668                 :            :                - ARCHN
    2669                 :            :                - ...
    2670                 :            :                - PACKAGE_KEYIDn
    2671                 :            :             
    2672                 :            :                We therefore need to do a mapping:
    2673                 :            :       
    2674                 :            :                P/V/R/A/N-V-R.A.rpm ->
    2675                 :            :                P/V/R/data/sigcache/KEYID/A/N-V-R.A.rpm.sig
    2676                 :            : 
    2677                 :            :                There are 2 key insights here         
    2678                 :            :       
    2679                 :            :                1. We need to go 2 directories down from sigcache to get to the
    2680                 :            :                rpm header. So to distinguish ARCH1/foo.rpm.sig and
    2681                 :            :                PACKAGE_KEYID1/ARCH1/foo.rpm.sig we can look 2 directories down
    2682                 :            :       
    2683                 :            :                2. It's safe to assume that the user will have all of the
    2684                 :            :                required verification certs. So we can pick from any of the
    2685                 :            :                PACKAGE_KEYID* directories.  For simplicity we choose first we
    2686                 :            :                match against
    2687                 :            :       
    2688                 :            :                See: https://pagure.io/koji/issue/3670
    2689                 :            :             */
    2690                 :            : 
    2691                 :            :             // Do the mapping from b_source0 to the koji path for the signed rpm header
    2692                 :            :             string signed_rpm_path = b_source0;
    2693                 :            :             size_t insert_pos = string::npos;
    2694                 :            :             for(int i = 0; i < 2; i++) insert_pos = signed_rpm_path.rfind("/", insert_pos) - 1;
    2695                 :            :             string globbed_path  = signed_rpm_path.insert(insert_pos + 1, "/data/sigcache/*").append(".sig"); // The globbed path we're seeking
    2696                 :            :             glob_t pglob;
    2697                 :            :             int grc;
    2698                 :            :             if(0 != (grc = glob(globbed_path.c_str(), GLOB_NOSORT, NULL, &pglob)))
    2699                 :            :               {
    2700                 :            :                 // Break out, but only report real errors
    2701                 :            :                 if (verbose && grc != GLOB_NOMATCH) obatched(clog) << "There was an error (" << strerror(errno) << ") globbing " << globbed_path << endl;
    2702                 :            :                 break; // Exit koji sigcache check
    2703                 :            :               }
    2704                 :            :             signed_rpm_path = pglob.gl_pathv[0]; // See insight 2 above
    2705                 :            :             globfree(&pglob);
    2706                 :            : 
    2707                 :            :             if (verbose > 2) obatched(clog) << "attempting IMA signature extraction from koji header " << signed_rpm_path << endl;
    2708                 :            : 
    2709                 :            :             FD_t sig_rpm_fd;
    2710                 :            :             if(NULL == (sig_rpm_fd = Fopen(signed_rpm_path.c_str(), "r")))
    2711                 :            :               {
    2712                 :            :                 if (verbose) obatched(clog) << "There was an error while opening " << signed_rpm_path << endl;
    2713                 :            :                 break; // Exit koji sigcache check
    2714                 :            :               }
    2715                 :            : 
    2716                 :            :             Header sig_hdr = headerRead(sig_rpm_fd, HEADER_MAGIC_YES /* Validate magic too */ );
    2717                 :            :             if (!sig_hdr || 1 != headerGet(sig_hdr, RPMSIGTAG_FILESIGNATURES, &sig_tag_data, HEADERGET_ALLOC))
    2718                 :            :               {
    2719                 :            :                 if (verbose) obatched(clog) << "Unable to extract RPMSIGTAG_FILESIGNATURES from " << signed_rpm_path << endl;
    2720                 :            :               }
    2721                 :            :             headerFree(sig_hdr); // We can free here since sig_tag_data has an alloc'd copy of the data
    2722                 :            :             Fclose(sig_rpm_fd);
    2723                 :            :           }
    2724                 :            :       }while(false);
    2725                 :            : 
    2726                 :            :       if(0 == sig_tag_data.count)
    2727                 :            :         {
    2728                 :            :           // In the general case (or a fallback from the koji sigcache mapping not finding signatures)
    2729                 :            :           // we can just (try) extract the signatures from the rpm header
    2730                 :            :           if (1 != headerGet(rpm_hdr, RPMTAG_FILESIGNATURES, &sig_tag_data, HEADERGET_ALLOC))
    2731                 :            :             {
    2732                 :            :               if (verbose) obatched(clog) << "Unable to extract RPMTAG_FILESIGNATURES from " << b_source0 << endl;
    2733                 :            :             }
    2734                 :            :         }
    2735                 :            :       // Search the array for the signature coresponding to b_source1
    2736                 :            :       int idx = -1;
    2737                 :            :       char *sig = NULL;
    2738                 :            :       rpmfi hdr_fi = rpmfiNew(NULL, rpm_hdr, RPMTAG_BASENAMES, RPMFI_FLAGS_QUERY);
    2739                 :            :       do
    2740                 :            :         {
    2741                 :            :           sig = (char*)rpmtdNextString(&sig_tag_data);
    2742                 :            :           idx = rpmfiNext(hdr_fi);
    2743                 :            :         }
    2744                 :            :       while (idx != -1 && 0 != strcmp(b_source1.c_str(), rpmfiFN(hdr_fi)));
    2745                 :            :       rpmfiFree(hdr_fi);
    2746                 :            : 
    2747                 :            :       if(sig && 0 != strlen(sig) && idx != -1)
    2748                 :            :         {
    2749                 :            :           if (verbose > 2) obatched(clog) << "Found IMA signature for " << b_source1 << ":\n" << sig << endl;
    2750                 :            :           ima_sig = sig;
    2751                 :            :           inc_metric("http_responses_total","extra","ima-sigs-extracted");
    2752                 :            :         }
    2753                 :            :       else
    2754                 :            :         {
    2755                 :            :           if (verbose > 2) obatched(clog) << "Could not find IMA signature for " << b_source1 << endl;
    2756                 :            :         }
    2757                 :            : 
    2758                 :            :       rpmtdFreeData (&sig_tag_data);
    2759                 :            :       headerFree(rpm_hdr);
    2760                 :            :       Fclose(rpm_fd);
    2761                 :            :     } while(false);
    2762                 :            :   #endif
    2763                 :            : 
    2764                 :            :   // check for a match in the fdcache first
    2765         [ +  - ]:       1000 :   int fd = fdcache.lookup(b_source0, b_source1);
    2766         [ +  + ]:       1000 :   while (fd >= 0) // got one!; NB: this is really an if() with a possible branch out to the end
    2767                 :            :     {
    2768                 :        772 :       rc = fstat(fd, &fs);
    2769         [ -  + ]:        772 :       if (rc < 0) // disappeared?
    2770                 :            :         {
    2771         [ #  # ]:          0 :           if (verbose)
    2772   [ #  #  #  #  :          0 :             obatched(clog) << "cannot fstat fdcache " << b_source0 << endl;
                   #  # ]
    2773         [ #  # ]:          0 :           close(fd);
    2774         [ #  # ]:          0 :           fdcache.clear(b_source0, b_source1);
    2775                 :            :           break; // branch out of if "loop", to try new libarchive fetch attempt
    2776                 :            :         }
    2777                 :            : 
    2778   [ +  -  +  -  :        772 :       struct MHD_Response* r = create_buildid_r_response (b_mtime, b_source0,
             -  +  -  - ]
    2779                 :            :                                                           b_source1, section,
    2780                 :            :                                                           ima_sig, NULL, fd,
    2781                 :            :                                                           fs.st_size,
    2782                 :            :                                                           fs.st_mtime,
    2783                 :            :                                                           "archive fdcache",
    2784                 :            :                                                           extract_begin);
    2785         [ +  + ]:        772 :       if (r == 0)
    2786                 :            :         break; // branch out of if "loop", to try new libarchive fetch attempt
    2787         [ +  - ]:        770 :       if (result_fd)
    2788                 :        770 :         *result_fd = fd;
    2789                 :            :       return r;
    2790                 :            :       // NB: see, we never go around the 'loop' more than once
    2791                 :            :     }
    2792                 :            : 
    2793                 :            :   // no match ... look for a seekable entry
    2794                 :        230 :   bool populate_seekable = ! passive_p;
    2795                 :        230 :   unique_ptr<sqlite_ps> pp (new sqlite_ps (internal_req_p ? db : dbq,
    2796                 :            :                                            "rpm-seekable-query",
    2797                 :            :                                            "select type, size, offset, mtime from " BUILDIDS "_r_seekable "
    2798   [ +  -  +  -  :        460 :                                            "where file = ? and content = ?"));
          +  -  +  +  +  
          -  +  -  +  -  
                   -  - ]
    2799   [ +  -  +  -  :        230 :   rc = pp->reset().bind(1, b_id0).bind(2, b_id1).step();
             +  -  +  - ]
    2800         [ +  + ]:        230 :   if (rc != SQLITE_DONE)
    2801                 :            :     {
    2802         [ -  + ]:         94 :       if (rc != SQLITE_ROW)
    2803   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    2804                 :            :       // if we found a match in _r_seekable but we fail to extract it, don't
    2805                 :            :       // bother populating it again
    2806                 :         94 :       populate_seekable = false;
    2807         [ +  - ]:         94 :       const char* seekable_type = (const char*) sqlite3_column_text (*pp, 0);
    2808   [ +  -  -  + ]:         94 :       if (seekable_type != NULL && strcmp (seekable_type, "xz") == 0)
    2809                 :            :         {
    2810         [ +  - ]:         94 :           int64_t seekable_size = sqlite3_column_int64 (*pp, 1);
    2811         [ +  - ]:         94 :           int64_t seekable_offset = sqlite3_column_int64 (*pp, 2);
    2812         [ +  - ]:         94 :           int64_t seekable_mtime = sqlite3_column_int64 (*pp, 3);
    2813                 :            : 
    2814                 :         94 :           char* tmppath = NULL;
    2815         [ -  + ]:         94 :           if (asprintf (&tmppath, "%s/debuginfod-fdcache.XXXXXX", tmpdir.c_str()) < 0)
    2816   [ #  #  #  # ]:          0 :             throw libc_exception (ENOMEM, "cannot allocate tmppath");
    2817                 :         94 :           defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    2818                 :            : 
    2819         [ +  - ]:         94 :           fd = extract_from_seekable_archive (b_source0, tmppath,
    2820                 :            :                                               seekable_offset, seekable_size);
    2821         [ +  - ]:         94 :           if (fd >= 0)
    2822                 :            :             {
    2823                 :            :               // Set the mtime so the fdcache file mtimes propagate to future webapi
    2824                 :            :               // clients.
    2825                 :         94 :               struct timespec tvs[2];
    2826                 :         94 :               tvs[0].tv_sec = 0;
    2827                 :         94 :               tvs[0].tv_nsec = UTIME_OMIT;
    2828                 :         94 :               tvs[1].tv_sec = seekable_mtime;
    2829                 :         94 :               tvs[1].tv_nsec = 0;
    2830                 :         94 :               (void) futimens (fd, tvs);  /* best effort */
    2831   [ +  -  +  -  :         94 :               struct MHD_Response* r = create_buildid_r_response (b_mtime,
                   +  - ]
    2832                 :            :                                                                   b_source0,
    2833                 :            :                                                                   b_source1,
    2834                 :            :                                                                   section,
    2835                 :            :                                                                   ima_sig,
    2836                 :            :                                                                   tmppath, fd,
    2837                 :            :                                                                   seekable_size,
    2838                 :            :                                                                   seekable_mtime,
    2839                 :            :                                                                   "seekable xz archive",
    2840                 :            :                                                                   extract_begin);
    2841         [ +  - ]:         94 :               if (r != 0 && result_fd)
    2842                 :         94 :                 *result_fd = fd;
    2843                 :         94 :               return r;
    2844                 :            :             }
    2845                 :         94 :         }
    2846                 :            :     }
    2847                 :        136 :   pp.reset();
    2848                 :            : 
    2849                 :            :   // still no match ... grumble, must process the archive
    2850         [ +  - ]:        136 :   string archive_decoder = "/dev/null";
    2851   [ +  -  -  - ]:        136 :   string archive_extension = "";
    2852         [ +  + ]:        310 :   for (auto&& arch : scan_archives)
    2853         [ +  + ]:        174 :     if (string_endswith(b_source0, arch.first))
    2854                 :            :       {
    2855         [ +  - ]:        136 :         archive_extension = arch.first;
    2856         [ +  - ]:        310 :         archive_decoder = arch.second;
    2857                 :            :       }
    2858                 :        136 :   FILE* fp;
    2859                 :            :   
    2860                 :        136 :   defer_dtor<FILE*,int>::dtor_fn dfn;
    2861         [ +  + ]:        136 :   if (archive_decoder != "cat")
    2862                 :            :     {
    2863   [ +  -  +  -  :         48 :       string popen_cmd = archive_decoder + " " + shell_escape(b_source0);
          +  -  -  +  -  
                -  -  - ]
    2864         [ +  - ]:         24 :       fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
    2865                 :         24 :       dfn = pclose;
    2866         [ -  + ]:         24 :       if (fp == NULL)
    2867   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("popen ") + popen_cmd);
             #  #  #  # ]
    2868                 :         24 :     }
    2869                 :            :   else
    2870                 :            :     {
    2871         [ +  - ]:        112 :       fp = fopen (b_source0.c_str(), "r");
    2872                 :        112 :       dfn = fclose;
    2873         [ -  + ]:        112 :       if (fp == NULL)
    2874   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("fopen ") + b_source0);
             #  #  #  # ]
    2875                 :            :     }
    2876                 :        136 :   defer_dtor<FILE*,int> fp_closer (fp, dfn);
    2877                 :            : 
    2878                 :        136 :   struct archive *a;
    2879         [ +  - ]:        136 :   a = archive_read_new();
    2880         [ -  + ]:        136 :   if (a == NULL)
    2881   [ #  #  #  # ]:          0 :     throw archive_exception("cannot create archive reader");
    2882                 :        136 :   defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
    2883                 :            : 
    2884         [ +  - ]:        136 :   rc = archive_read_support_format_all(a);
    2885         [ -  + ]:        136 :   if (rc != ARCHIVE_OK)
    2886   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all format");
    2887         [ +  - ]:        136 :   rc = archive_read_support_filter_all(a);
    2888         [ -  + ]:        136 :   if (rc != ARCHIVE_OK)
    2889   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all filters");
    2890                 :            : 
    2891         [ +  - ]:        136 :   rc = archive_read_open_FILE (a, fp);
    2892         [ -  + ]:        136 :   if (rc != ARCHIVE_OK)
    2893                 :            :     {
    2894   [ #  #  #  #  :          0 :       obatched(clog) << "cannot open archive from pipe " << b_source0 << endl;
                   #  # ]
    2895   [ #  #  #  # ]:          0 :       throw archive_exception(a, "cannot open archive from pipe");
    2896                 :            :     }
    2897                 :            : 
    2898                 :            :   // If the archive was scanned in a version without _r_seekable, then we may
    2899                 :            :   // need to populate _r_seekable now.  This can be removed the next time
    2900                 :            :   // BUILDIDS is updated.
    2901         [ +  + ]:        136 :   if (populate_seekable)
    2902                 :            :     {
    2903         [ +  - ]:        134 :       populate_seekable = is_seekable_archive (b_source0, a);
    2904         [ +  - ]:        134 :       if (populate_seekable)
    2905                 :            :         {
    2906                 :            :           // NB: the names are already interned
    2907         [ #  # ]:          0 :           pp.reset(new sqlite_ps (db, "rpm-seekable-insert2",
    2908                 :            :                                   "insert or ignore into " BUILDIDS "_r_seekable (file, content, type, size, offset, mtime) "
    2909                 :            :                                   "values (?, "
    2910                 :            :                                   "(select id from " BUILDIDS "_files "
    2911                 :            :                                   "where dirname = (select id from " BUILDIDS "_fileparts where name = ?) "
    2912                 :            :                                   "and basename = (select id from " BUILDIDS "_fileparts where name = ?) "
    2913   [ #  #  #  #  :          0 :                                   "), 'xz', ?, ?, ?)"));
          #  #  #  #  #  
                #  #  # ]
    2914                 :            :         }
    2915                 :            :     }
    2916                 :            : 
    2917                 :            :   // archive traversal is in five stages:
    2918                 :            :   // 1) before we find a matching entry, insert it into _r_seekable if needed or
    2919                 :            :   //    skip it otherwise
    2920                 :            :   // 2) extract the matching entry (set r = result).  Also insert it into
    2921                 :            :   //    _r_seekable if needed
    2922                 :            :   // 3) extract some number of prefetched entries (just into fdcache).  Also
    2923                 :            :   //    insert them into _r_seekable if needed
    2924                 :            :   // 4) if needed, insert all of the remaining entries into _r_seekable
    2925                 :            :   // 5) abort any further processing
    2926                 :        136 :   struct MHD_Response* r = 0;                 // will set in stage 2
    2927         [ +  + ]:        136 :   unsigned prefetch_count =
    2928                 :            :     internal_req_p ? 0 : fdcache_prefetch;    // will decrement in stage 3
    2929                 :            : 
    2930   [ +  +  -  + ]:       1446 :   while(r == 0 || prefetch_count > 0 || populate_seekable) // stage 1-4
    2931                 :            :     {
    2932         [ +  - ]:       1426 :       if (interrupted)
    2933                 :            :         break;
    2934                 :            : 
    2935                 :       1426 :       struct archive_entry *e;
    2936         [ +  - ]:       1426 :       rc = archive_read_next_header (a, &e);
    2937         [ +  + ]:       1426 :       if (rc != ARCHIVE_OK)
    2938                 :            :         break;
    2939                 :            : 
    2940   [ +  -  +  + ]:       1312 :       if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
    2941                 :       1038 :         continue;
    2942                 :            : 
    2943         [ +  - ]:        274 :       string fn = canonicalized_archive_entry_pathname (e);
    2944                 :            : 
    2945         [ -  + ]:        274 :       if (populate_seekable)
    2946                 :            :         {
    2947                 :          0 :           string dn, bn;
    2948                 :          0 :           size_t slash = fn.rfind('/');
    2949         [ #  # ]:          0 :           if (slash == std::string::npos) {
    2950         [ #  # ]:          0 :             dn = "";
    2951         [ #  # ]:          0 :             bn = fn;
    2952                 :            :           } else {
    2953   [ #  #  #  # ]:          0 :             dn = fn.substr(0, slash);
    2954   [ #  #  #  # ]:          0 :             bn = fn.substr(slash + 1);
    2955                 :            :           }
    2956                 :            : 
    2957         [ #  # ]:          0 :           int64_t seekable_size = archive_entry_size (e);
    2958         [ #  # ]:          0 :           int64_t seekable_offset = archive_filter_bytes (a, 0);
    2959         [ #  # ]:          0 :           time_t seekable_mtime = archive_entry_mtime (e);
    2960                 :            : 
    2961         [ #  # ]:          0 :           pp->reset();
    2962         [ #  # ]:          0 :           pp->bind(1, b_id0);
    2963         [ #  # ]:          0 :           pp->bind(2, dn);
    2964         [ #  # ]:          0 :           pp->bind(3, bn);
    2965         [ #  # ]:          0 :           pp->bind(4, seekable_size);
    2966         [ #  # ]:          0 :           pp->bind(5, seekable_offset);
    2967         [ #  # ]:          0 :           pp->bind(6, seekable_mtime);
    2968         [ #  # ]:          0 :           rc = pp->step();
    2969         [ #  # ]:          0 :           if (rc != SQLITE_DONE)
    2970   [ #  #  #  # ]:          0 :             obatched(clog) << "recording seekable file=" << fn
    2971   [ #  #  #  #  :          0 :                            << " sqlite3 error: " << (sqlite3_errstr(rc) ?: "?") << endl;
          #  #  #  #  #  
                      # ]
    2972         [ #  # ]:          0 :           else if (verbose > 2)
    2973   [ #  #  #  #  :          0 :             obatched(clog) << "recorded seekable file=" << fn
                   #  # ]
    2974   [ #  #  #  # ]:          0 :                            << " size=" << seekable_size
    2975   [ #  #  #  # ]:          0 :                            << " offset=" << seekable_offset
    2976   [ #  #  #  #  :          0 :                            << " mtime=" << seekable_mtime << endl;
                   #  # ]
    2977         [ #  # ]:          0 :           if (r != 0 && prefetch_count == 0) // stage 4
    2978         [ #  # ]:          0 :             continue;
    2979   [ #  #  #  # ]:          0 :         }
    2980                 :            : 
    2981   [ +  +  +  + ]:        274 :       if ((r == 0) && (fn != b_source1)) // stage 1
    2982                 :         68 :         continue;
    2983                 :            : 
    2984   [ +  -  +  + ]:        206 :       if (fdcache.probe (b_source0, fn) && // skip if already interned
    2985         [ +  + ]:         26 :           fn != b_source1) // but only if we'd just be prefetching, PR29474
    2986                 :         24 :         continue;
    2987                 :            : 
    2988                 :            :       // extract this file to a temporary file
    2989                 :        182 :       char* tmppath = NULL;
    2990                 :        182 :       rc = asprintf (&tmppath, "%s/debuginfod-fdcache.XXXXXX", tmpdir.c_str());
    2991         [ -  + ]:        182 :       if (rc < 0)
    2992   [ #  #  #  # ]:          0 :         throw libc_exception (ENOMEM, "cannot allocate tmppath");
    2993                 :        182 :       defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    2994         [ +  - ]:        182 :       fd = mkstemp (tmppath);
    2995         [ -  + ]:        182 :       if (fd < 0)
    2996   [ #  #  #  # ]:          0 :         throw libc_exception (errno, "cannot create temporary file");
    2997                 :            :       // NB: don't unlink (tmppath), as fdcache will take charge of it.
    2998                 :            : 
    2999                 :            :       // NB: this can take many uninterruptible seconds for a huge file
    3000         [ +  - ]:        182 :       rc = archive_read_data_into_fd (a, fd);
    3001         [ -  + ]:        182 :       if (rc != ARCHIVE_OK) // e.g. ENOSPC!
    3002                 :            :         {
    3003         [ #  # ]:          0 :           close (fd);
    3004                 :          0 :           unlink (tmppath);
    3005   [ #  #  #  # ]:          0 :           throw archive_exception(a, "cannot extract file");
    3006                 :            :         }
    3007                 :            : 
    3008                 :            :       // Set the mtime so the fdcache file mtimes, even prefetched ones,
    3009                 :            :       // propagate to future webapi clients.
    3010                 :        182 :       struct timespec tvs[2];
    3011                 :        182 :       tvs[0].tv_sec = 0;
    3012                 :        182 :       tvs[0].tv_nsec = UTIME_OMIT;
    3013         [ +  - ]:        182 :       tvs[1].tv_sec = archive_entry_mtime(e);
    3014         [ +  - ]:        182 :       tvs[1].tv_nsec = archive_entry_mtime_nsec(e);
    3015                 :        182 :       (void) futimens (fd, tvs);  /* best effort */
    3016                 :            : 
    3017         [ +  + ]:        182 :       if (r != 0) // stage 3
    3018                 :            :         {
    3019                 :         46 :           struct timespec extract_end;
    3020                 :         46 :           clock_gettime (CLOCK_MONOTONIC, &extract_end);
    3021                 :         46 :           double extract_time = (extract_end.tv_sec - extract_begin.tv_sec)
    3022                 :         46 :             + (extract_end.tv_nsec - extract_begin.tv_nsec)/1.e9;
    3023                 :            :           // NB: now we know we have a complete reusable file; make fdcache
    3024                 :            :           // responsible for unlinking it later.
    3025   [ +  -  +  -  :         46 :           fdcache.intern(b_source0, fn,
                   +  - ]
    3026                 :            :                          tmppath, archive_entry_size(e),
    3027                 :            :                          false, extract_time); // prefetched ones go to the prefetch cache
    3028                 :         46 :           prefetch_count --;
    3029         [ +  - ]:         46 :           close (fd); // we're not saving this fd to make a mhd-response from!
    3030                 :         46 :           continue;
    3031                 :         46 :         }
    3032                 :            : 
    3033   [ +  -  +  -  :        136 :       r = create_buildid_r_response (b_mtime, b_source0, b_source1, section,
             +  -  +  + ]
    3034                 :            :                                      ima_sig, tmppath, fd,
    3035                 :            :                                      archive_entry_size(e),
    3036                 :            :                                      archive_entry_mtime(e),
    3037         [ +  - ]:        136 :                                      archive_extension + " archive",
    3038                 :            :                                      extract_begin);
    3039         [ +  + ]:        136 :       if (r == 0)
    3040                 :            :         break; // assume no chance of better luck around another iteration; no other copies of same file
    3041         [ +  - ]:        134 :       if (result_fd)
    3042                 :        134 :         *result_fd = fd;
    3043   [ +  -  +  -  :       1700 :     }
                   +  + ]
    3044                 :            : 
    3045                 :            :   // XXX: rpm/file not found: delete this R entry?
    3046                 :        136 :   return r;
    3047   [ -  +  +  + ]:       1366 : }
    3048                 :            : 
    3049                 :            : void
    3050                 :        650 : add_client_federation_headers(debuginfod_client *client, MHD_Connection* conn){
    3051                 :            :   // Transcribe incoming User-Agent:
    3052         [ -  + ]:        650 :   string ua = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "User-Agent") ?: "";
    3053   [ +  -  +  -  :        654 :   string ua_complete = string("User-Agent: ") + ua;
                   +  - ]
    3054         [ +  - ]:        650 :   debuginfod_add_http_header (client, ua_complete.c_str());
    3055                 :            : 
    3056                 :            :   // Compute larger XFF:, for avoiding info loss during
    3057                 :            :   // federation, and for future cyclicity detection.
    3058   [ +  -  +  +  :       1278 :   string xff = MHD_lookup_connection_value (conn, MHD_HEADER_KIND, "X-Forwarded-For") ?: "";
             +  -  +  - ]
    3059         [ +  + ]:        650 :   if (xff != "")
    3060   [ +  -  -  + ]:         52 :     xff += string(", "); // comma separated list
    3061                 :            : 
    3062                 :        650 :   unsigned int xff_count = 0;
    3063         [ +  + ]:        978 :   for (auto&& i : xff){
    3064         [ +  + ]:        328 :     if (i == ',') xff_count++;
    3065                 :            :   }
    3066                 :            : 
    3067                 :            :   // if X-Forwarded-For: exceeds N hops,
    3068                 :            :   // do not delegate a local lookup miss to upstream debuginfods.
    3069         [ +  + ]:        650 :   if (xff_count >= forwarded_ttl_limit)
    3070   [ +  -  +  - ]:          8 :     throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found, --forwared-ttl-limit reached \
    3071                 :          8 : and will not query the upstream servers");
    3072                 :            : 
    3073                 :            :   // Compute the client's numeric IP address only - so can't merge with conninfo()
    3074         [ +  - ]:        646 :   const union MHD_ConnectionInfo *u = MHD_get_connection_info (conn,
    3075                 :            :                                                                 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
    3076         [ +  - ]:        646 :   struct sockaddr *so = u ? u->client_addr : 0;
    3077                 :        646 :   char hostname[256] = ""; // RFC1035
    3078   [ +  -  -  + ]:        646 :   if (so && so->sa_family == AF_INET) {
    3079         [ #  # ]:          0 :     (void) getnameinfo (so, sizeof (struct sockaddr_in), hostname, sizeof (hostname), NULL, 0,
    3080                 :            :                         NI_NUMERICHOST);
    3081         [ +  - ]:        646 :   } else if (so && so->sa_family == AF_INET6) {
    3082                 :        646 :     struct sockaddr_in6* addr6 = (struct sockaddr_in6*) so;
    3083   [ +  -  +  -  :        646 :     if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
                   -  + ]
    3084                 :        646 :       struct sockaddr_in addr4;
    3085         [ +  - ]:        646 :       memset (&addr4, 0, sizeof(addr4));
    3086                 :        646 :       addr4.sin_family = AF_INET;
    3087                 :        646 :       addr4.sin_port = addr6->sin6_port;
    3088         [ +  - ]:        646 :       memcpy (&addr4.sin_addr.s_addr, addr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
    3089         [ +  - ]:        646 :       (void) getnameinfo ((struct sockaddr*) &addr4, sizeof (addr4),
    3090                 :            :                           hostname, sizeof (hostname), NULL, 0,
    3091                 :            :                           NI_NUMERICHOST);
    3092                 :            :     } else {
    3093         [ #  # ]:          0 :       (void) getnameinfo (so, sizeof (struct sockaddr_in6), hostname, sizeof (hostname), NULL, 0,
    3094                 :            :                           NI_NUMERICHOST);
    3095                 :            :     }
    3096                 :            :   }
    3097                 :            : 
    3098   [ +  -  +  -  :       1296 :   string xff_complete = string("X-Forwarded-For: ")+xff+string(hostname);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  + ]
    3099         [ +  - ]:        646 :   debuginfod_add_http_header (client, xff_complete.c_str());
    3100   [ +  +  +  -  :       1368 : }
                   +  + ]
    3101                 :            : 
    3102                 :            : static struct MHD_Response*
    3103                 :       2186 : handle_buildid_match (bool internal_req_p,
    3104                 :            :                       int64_t b_mtime,
    3105                 :            :                       const string& b_stype,
    3106                 :            :                       const string& b_source0,
    3107                 :            :                       const string& b_source1,
    3108                 :            :                       int64_t b_id0,
    3109                 :            :                       int64_t b_id1,
    3110                 :            :                       const string& section,
    3111                 :            :                       int *result_fd)
    3112                 :            : {
    3113                 :       2186 :   try
    3114                 :            :     {
    3115         [ +  + ]:       2186 :       if (b_stype == "F")
    3116         [ +  - ]:       1128 :         return handle_buildid_f_match(internal_req_p, b_mtime, b_source0,
    3117                 :            :                                       section, result_fd);
    3118         [ +  - ]:       1058 :       else if (b_stype == "R")
    3119         [ +  + ]:       1058 :         return handle_buildid_r_match(internal_req_p, b_mtime, b_source0,
    3120                 :            :                                       b_source1, b_id0, b_id1, section,
    3121                 :            :                                       result_fd);
    3122                 :            :     }
    3123         [ -  + ]:         58 :   catch (const reportable_exception &e)
    3124                 :            :     {
    3125         [ +  - ]:         58 :       e.report(clog);
    3126                 :            :       // Report but swallow libc etc. errors here; let the caller
    3127                 :            :       // iterate to other matches of the content.
    3128                 :         58 :     }
    3129                 :            : 
    3130                 :            :   return 0;
    3131                 :            : }
    3132                 :            : 
    3133                 :            : 
    3134                 :            : static int
    3135                 :          4 : debuginfod_find_progress (debuginfod_client *, long a, long b)
    3136                 :            : {
    3137         [ -  + ]:          4 :   if (verbose > 4)
    3138   [ #  #  #  #  :          0 :     obatched(clog) << "federated debuginfod progress=" << a << "/" << b << endl;
             #  #  #  # ]
    3139                 :            : 
    3140                 :          4 :   return interrupted;
    3141                 :            : }
    3142                 :            : 
    3143                 :            : 
    3144                 :            : // a little lru pool of debuginfod_client*s for reuse between query threads
    3145                 :            : 
    3146                 :            : mutex dc_pool_lock;
    3147                 :            : deque<debuginfod_client*> dc_pool;
    3148                 :            : 
    3149                 :        670 : debuginfod_client* debuginfod_pool_begin()
    3150                 :            : {
    3151                 :        670 :   unique_lock<mutex> lock(dc_pool_lock);
    3152         [ +  + ]:        670 :   if (dc_pool.size() > 0)
    3153                 :            :     {
    3154   [ +  -  +  -  :       1276 :       inc_metric("dc_pool_op_count","op","begin-reuse");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3155                 :        638 :       debuginfod_client *c = dc_pool.front();
    3156                 :        638 :       dc_pool.pop_front();
    3157                 :        638 :       return c;
    3158                 :            :     }
    3159   [ +  -  +  -  :         64 :   inc_metric("dc_pool_op_count","op","begin-new");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3160         [ +  - ]:         32 :   return debuginfod_begin();
    3161                 :        670 : }
    3162                 :            : 
    3163                 :            : 
    3164                 :        158 : void debuginfod_pool_groom()
    3165                 :            : {
    3166                 :        158 :   unique_lock<mutex> lock(dc_pool_lock);
    3167         [ +  + ]:        190 :   while (dc_pool.size() > 0)
    3168                 :            :     {
    3169   [ +  -  +  -  :         64 :       inc_metric("dc_pool_op_count","op","end");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3170         [ +  - ]:         32 :       debuginfod_end(dc_pool.front());
    3171                 :         32 :       dc_pool.pop_front();
    3172                 :            :     }
    3173                 :        158 : }
    3174                 :            : 
    3175                 :            : 
    3176                 :        670 : void debuginfod_pool_end(debuginfod_client* c)
    3177                 :            : {
    3178                 :        670 :   unique_lock<mutex> lock(dc_pool_lock);
    3179   [ +  -  +  -  :       1340 :   inc_metric("dc_pool_op_count","op","end-save");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3180         [ +  - ]:        670 :   dc_pool.push_front(c); // accelerate reuse, vs. push_back
    3181                 :        670 : }
    3182                 :            : 
    3183                 :            : 
    3184                 :            : static struct MHD_Response*
    3185                 :       2770 : handle_buildid (MHD_Connection* conn,
    3186                 :            :                 const string& buildid /* unsafe */,
    3187                 :            :                 string& artifacttype /* unsafe, cleanse on exception/return */,
    3188                 :            :                 const string& suffix /* unsafe */,
    3189                 :            :                 int *result_fd)
    3190                 :            : {
    3191                 :            :   // validate artifacttype
    3192                 :       2770 :   string atype_code;
    3193   [ +  +  +  - ]:       2770 :   if (artifacttype == "debuginfo") atype_code = "D";
    3194   [ +  +  +  - ]:       1802 :   else if (artifacttype == "executable") atype_code = "E";
    3195   [ +  +  +  - ]:       1114 :   else if (artifacttype == "source") atype_code = "S";
    3196   [ +  +  +  - ]:         12 :   else if (artifacttype == "section") atype_code = "I";
    3197                 :            :   else {
    3198         [ +  - ]:          4 :     artifacttype = "invalid"; // PR28242 ensure http_resposes metrics don't propagate unclean user data 
    3199   [ +  -  +  - ]:         12 :     throw reportable_exception("invalid artifacttype");
    3200                 :            :   }
    3201                 :            : 
    3202         [ +  + ]:       2766 :   if (conn != 0)
    3203   [ +  -  +  -  :       5774 :     inc_metric("http_requests_total", "type", artifacttype);
          +  -  -  +  -  
                -  -  + ]
    3204                 :            : 
    3205                 :       2766 :   string section;
    3206         [ +  + ]:       2766 :   if (atype_code == "I")
    3207                 :            :     {
    3208         [ -  + ]:          8 :       if (suffix.size () < 2)
    3209   [ #  #  #  # ]:          0 :         throw reportable_exception ("invalid section suffix");
    3210                 :            : 
    3211                 :            :       // Remove leading '/'
    3212   [ +  -  -  + ]:          8 :       section = suffix.substr(1);
    3213                 :            :     }
    3214                 :            : 
    3215   [ +  +  -  + ]:       3868 :   if (atype_code == "S" && suffix == "")
    3216   [ #  #  #  # ]:          0 :      throw reportable_exception("invalid source suffix");
    3217                 :            : 
    3218                 :            :   // validate buildid
    3219         [ +  + ]:       2766 :   if ((buildid.size() < 2) || // not empty
    3220   [ +  +  +  -  :       5530 :       (buildid.size() % 2) || // even number
                   +  - ]
    3221                 :       2764 :       (buildid.find_first_not_of("0123456789abcdef") != string::npos)) // pure tasty lowercase hex
    3222   [ +  -  -  + ]:          4 :     throw reportable_exception("invalid buildid");
    3223                 :            : 
    3224         [ +  - ]:       2764 :   if (verbose > 1)
    3225   [ +  -  +  - ]:       8292 :     obatched(clog) << "searching for buildid=" << buildid << " artifacttype=" << artifacttype
    3226   [ +  -  +  -  :       2764 :          << " suffix=" << suffix << endl;
          +  -  +  -  +  
                      - ]
    3227                 :            : 
    3228                 :            :   // If invoked from the scanner threads, use the scanners' read-write
    3229                 :            :   // connection.  Otherwise use the web query threads' read-only connection.
    3230         [ +  + ]:       2764 :   sqlite3 *thisdb = (conn == 0) ? db : dbq;
    3231                 :            : 
    3232                 :       2764 :   sqlite_ps *pp = 0;
    3233                 :            : 
    3234         [ +  + ]:       2764 :   if (atype_code == "D")
    3235                 :            :     {
    3236         [ -  + ]:        968 :       pp = new sqlite_ps (thisdb, "mhd-query-d",
    3237                 :            :                           "select mtime, sourcetype, source0, source1, id0, id1 from " BUILDIDS "_query_d2 where buildid = ? "
    3238   [ +  -  +  -  :       1936 :                           "order by mtime desc");
          +  -  +  -  +  
                -  -  - ]
    3239         [ +  - ]:        968 :       pp->reset();
    3240         [ +  - ]:        968 :       pp->bind(1, buildid);
    3241                 :            :     }
    3242         [ +  + ]:       1796 :   else if (atype_code == "E")
    3243                 :            :     {
    3244         [ -  + ]:        686 :       pp = new sqlite_ps (thisdb, "mhd-query-e",
    3245                 :            :                           "select mtime, sourcetype, source0, source1, id0, id1 from " BUILDIDS "_query_e2 where buildid = ? "
    3246   [ +  -  +  -  :       1372 :                           "order by mtime desc");
          +  -  +  -  +  
                -  -  - ]
    3247         [ +  - ]:        686 :       pp->reset();
    3248         [ +  - ]:        686 :       pp->bind(1, buildid);
    3249                 :            :     }
    3250         [ +  + ]:       1110 :   else if (atype_code == "S")
    3251                 :            :     {
    3252                 :            :       // PR25548
    3253                 :            :       // Incoming source queries may come in with either dwarf-level OR canonicalized paths.
    3254                 :            :       // We let the query pass with either one.
    3255                 :            : 
    3256         [ -  + ]:       1102 :       pp = new sqlite_ps (thisdb, "mhd-query-s",
    3257                 :            :                           "select mtime, sourcetype, source0, source1 from " BUILDIDS "_query_s where buildid = ? and artifactsrc in (?,?) "
    3258   [ +  -  +  -  :       2204 :                           "order by sharedprefix(source0,source0ref) desc, mtime desc");
          +  -  +  -  +  
                -  -  - ]
    3259         [ +  - ]:       1102 :       pp->reset();
    3260         [ +  - ]:       1102 :       pp->bind(1, buildid);
    3261                 :            :       // NB: we don't store the non-canonicalized path names any more, but old databases
    3262                 :            :       // might have them (and no canon ones), so we keep searching for both.
    3263         [ +  - ]:       1102 :       pp->bind(2, suffix);
    3264   [ +  -  +  -  :       2842 :       pp->bind(3, canon_pathname(suffix));
                   -  + ]
    3265                 :            :     }
    3266         [ +  - ]:          8 :   else if (atype_code == "I")
    3267                 :            :     {
    3268         [ -  + ]:          8 :       pp = new sqlite_ps (thisdb, "mhd-query-i",
    3269                 :            :         "select mtime, sourcetype, source0, source1, 1 as debug_p from " BUILDIDS "_query_d2 where buildid = ? "
    3270                 :            :         "union all "
    3271                 :            :         "select mtime, sourcetype, source0, source1, 0 as debug_p from " BUILDIDS "_query_e2 where buildid = ? "
    3272   [ +  -  +  -  :         16 :         "order by debug_p desc, mtime desc");
          +  -  +  -  +  
                -  -  - ]
    3273         [ +  - ]:          8 :       pp->reset();
    3274         [ +  - ]:          8 :       pp->bind(1, buildid);
    3275         [ +  - ]:          8 :       pp->bind(2, buildid);
    3276                 :            :     }
    3277                 :       2764 :   unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
    3278                 :            : 
    3279                 :       2764 :   bool do_upstream_section_query = true;
    3280                 :            : 
    3281                 :            :   // consume all the rows
    3282                 :       2826 :   while (1)
    3283                 :            :     {
    3284         [ +  - ]:       2826 :       int rc = pp->step();
    3285         [ +  + ]:       2826 :       if (rc == SQLITE_DONE) break;
    3286         [ -  + ]:       2186 :       if (rc != SQLITE_ROW)
    3287   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    3288                 :            : 
    3289         [ +  - ]:       2186 :       int64_t b_mtime = sqlite3_column_int64 (*pp, 0);
    3290   [ +  -  -  +  :       2186 :       string b_stype = string((const char*) sqlite3_column_text (*pp, 1) ?: ""); /* by DDL may not be NULL */
                   +  - ]
    3291   [ +  -  -  +  :       2186 :       string b_source0 = string((const char*) sqlite3_column_text (*pp, 2) ?: ""); /* may be NULL */
             +  -  -  - ]
    3292   [ +  -  +  +  :       3314 :       string b_source1 = string((const char*) sqlite3_column_text (*pp, 3) ?: ""); /* may be NULL */
             +  -  -  - ]
    3293                 :       2186 :       int64_t b_id0 = 0, b_id1 = 0;
    3294   [ +  +  +  + ]:       3454 :       if (atype_code == "D" || atype_code == "E")
    3295                 :            :         {
    3296         [ +  - ]:       1070 :           b_id0 = sqlite3_column_int64 (*pp, 4);
    3297         [ +  - ]:       1070 :           b_id1 = sqlite3_column_int64 (*pp, 5);
    3298                 :            :         }
    3299                 :            : 
    3300         [ +  - ]:       2186 :       if (verbose > 1)
    3301   [ +  -  +  -  :       6558 :         obatched(clog) << "found mtime=" << b_mtime << " stype=" << b_stype
                   -  - ]
    3302   [ +  -  +  -  :       2186 :              << " source0=" << b_source0 << " source1=" << b_source1 << endl;
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    3303                 :            : 
    3304                 :            :       // Try accessing the located match.
    3305                 :            :       // XXX: in case of multiple matches, attempt them in parallel?
    3306         [ +  - ]:       2186 :       auto r = handle_buildid_match (conn ? false : true,
    3307                 :            :                                      b_mtime, b_stype, b_source0, b_source1,
    3308                 :            :                                      b_id0, b_id1, section, result_fd);
    3309         [ +  + ]:       2186 :       if (r)
    3310         [ +  + ]:       2124 :         return r;
    3311                 :            : 
    3312                 :            :       // If a debuginfo file matching BUILDID was found but didn't contain
    3313                 :            :       // the desired section, then the section should not exist.  Don't
    3314                 :            :       // bother querying upstream servers.
    3315   [ +  +  +  -  :         62 :       if (!section.empty () && (sqlite3_column_int (*pp, 4) == 1))
                   -  + ]
    3316                 :            :         {
    3317                 :          4 :           struct stat st;
    3318                 :            : 
    3319                 :            :           // For "F" sourcetype, check if the debuginfo exists. For "R"
    3320                 :            :           // sourcetype, check if the debuginfo was interned into the fdcache.
    3321         [ -  + ]:          6 :           if ((b_stype == "F" && (stat (b_source0.c_str (), &st) == 0))
    3322   [ +  +  +  -  :          6 :               || (b_stype == "R" && fdcache.probe (b_source0, b_source1)))
             +  -  -  + ]
    3323                 :            :             do_upstream_section_query = false;
    3324                 :            :         }
    3325   [ +  -  -  +  :       4372 :     }
             +  -  -  + ]
    3326         [ +  - ]:        640 :   pp->reset();
    3327                 :            : 
    3328         [ -  + ]:        640 :   if (!do_upstream_section_query)
    3329   [ #  #  #  # ]:          0 :     throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
    3330                 :            : 
    3331                 :            :   // We couldn't find it in the database.  Last ditch effort
    3332                 :            :   // is to defer to other debuginfo servers.
    3333                 :            : 
    3334                 :        640 :   int fd = -1;
    3335         [ +  - ]:        640 :   debuginfod_client *client = debuginfod_pool_begin ();
    3336         [ -  + ]:        640 :   if (client == NULL)
    3337   [ #  #  #  # ]:          0 :     throw libc_exception(errno, "debuginfod client pool alloc");
    3338                 :        640 :   defer_dtor<debuginfod_client*,void> client_closer (client, debuginfod_pool_end);
    3339                 :            :   
    3340         [ +  - ]:        640 :   debuginfod_set_progressfn (client, & debuginfod_find_progress);
    3341                 :            : 
    3342         [ +  + ]:        640 :   if (conn)
    3343         [ +  + ]:        620 :     add_client_federation_headers(client, conn);
    3344                 :            : 
    3345         [ +  + ]:        636 :   if (artifacttype == "debuginfo")
    3346         [ +  - ]:         88 :     fd = debuginfod_find_debuginfo (client,
    3347         [ +  - ]:         88 :                                     (const unsigned char*) buildid.c_str(),
    3348                 :            :                                     0, NULL);
    3349         [ +  + ]:        548 :   else if (artifacttype == "executable")
    3350         [ +  - ]:        546 :     fd = debuginfod_find_executable (client,
    3351         [ +  - ]:        546 :                                      (const unsigned char*) buildid.c_str(),
    3352                 :            :                                      0, NULL);
    3353         [ +  - ]:          2 :   else if (artifacttype == "source")
    3354         [ +  - ]:          2 :     fd = debuginfod_find_source (client,
    3355         [ +  - ]:          2 :                                  (const unsigned char*) buildid.c_str(),
    3356                 :            :                                  0, suffix.c_str(), NULL);
    3357         [ #  # ]:          0 :   else if (artifacttype == "section")
    3358         [ #  # ]:          0 :     fd = debuginfod_find_section (client,
    3359         [ #  # ]:          0 :                                   (const unsigned char*) buildid.c_str(),
    3360                 :            :                                   0, section.c_str(), NULL);
    3361                 :            :   
    3362         [ +  + ]:        636 :   if (fd >= 0)
    3363                 :            :     {
    3364         [ +  - ]:          4 :       if (conn != 0)
    3365   [ +  -  +  -  :        644 :         inc_metric ("http_responses_total","result","upstream");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3366                 :          4 :       struct stat s;
    3367                 :          4 :       int rc = fstat (fd, &s);
    3368         [ +  - ]:          4 :       if (rc == 0)
    3369                 :            :         {
    3370         [ +  - ]:          4 :           auto r = MHD_create_response_from_fd ((uint64_t) s.st_size, fd);
    3371         [ +  - ]:          4 :           if (r)
    3372                 :            :             {
    3373         [ +  - ]:          4 :               add_mhd_response_header (r, "Content-Type",
    3374                 :            :                                        "application/octet-stream");
    3375                 :            :               // Copy the incoming headers
    3376         [ +  - ]:          4 :               const char * hdrs = debuginfod_get_headers(client);
    3377         [ +  - ]:          4 :               string header_dup;
    3378         [ +  - ]:          4 :               if (hdrs)
    3379   [ +  -  -  + ]:          4 :                 header_dup = string(hdrs);
    3380                 :            :               // Parse the "header: value\n" lines into (h,v) tuples and pass on
    3381                 :         20 :               while(1)
    3382                 :            :                 {
    3383                 :         12 :                   size_t newline = header_dup.find('\n');
    3384         [ +  + ]:         12 :                   if (newline == string::npos) break;
    3385                 :          8 :                   size_t colon = header_dup.find(':');
    3386         [ +  - ]:          8 :                   if (colon == string::npos) break;
    3387         [ +  - ]:          8 :                   string header = header_dup.substr(0,colon);
    3388         [ +  - ]:          8 :                   string value = header_dup.substr(colon+1,newline-colon-1);
    3389                 :            :                   // strip leading spaces from value
    3390                 :          8 :                   size_t nonspace = value.find_first_not_of(" ");
    3391         [ +  - ]:          8 :                   if (nonspace != string::npos)
    3392   [ +  -  +  + ]:         12 :                     value = value.substr(nonspace);
    3393         [ +  - ]:          8 :                   add_mhd_response_header(r, header.c_str(), value.c_str());
    3394   [ +  -  +  +  :         12 :                   header_dup = header_dup.substr(newline+1);
             +  +  -  - ]
    3395         [ +  - ]:         16 :                 }
    3396                 :            : 
    3397         [ +  - ]:          4 :               add_mhd_last_modified (r, s.st_mtime);
    3398         [ +  - ]:          4 :               if (verbose > 1)
    3399   [ +  -  +  -  :          8 :                 obatched(clog) << "serving file from upstream debuginfod/cache" << endl;
                   -  - ]
    3400         [ +  - ]:          4 :               if (result_fd)
    3401                 :          4 :                 *result_fd = fd;
    3402         [ +  - ]:          4 :               return r; // NB: don't close fd; libmicrohttpd will
    3403                 :          4 :             }
    3404                 :            :         }
    3405         [ #  # ]:          0 :       close (fd);
    3406                 :            :     }
    3407                 :            :   else
    3408         [ +  + ]:        632 :     switch(fd)
    3409                 :            :       {
    3410                 :            :       case -ENOSYS:
    3411                 :            :         break;
    3412                 :            :       case -ENOENT:
    3413                 :            :         break;
    3414                 :        532 :       default: // some more tricky error
    3415   [ +  -  +  - ]:       1064 :         throw libc_exception(-fd, "upstream debuginfod query failed");
    3416                 :            :       }
    3417                 :            : 
    3418   [ +  -  -  + ]:        200 :   throw reportable_exception(MHD_HTTP_NOT_FOUND, "not found");
    3419   [ -  +  -  + ]:       3402 : }
    3420                 :            : 
    3421                 :            : 
    3422                 :            : ////////////////////////////////////////////////////////////////////////
    3423                 :            : 
    3424                 :            : static map<string,double> metrics; // arbitrary data for /metrics query
    3425                 :            : // NB: store int64_t since all our metrics are integers; prometheus accepts double
    3426                 :            : static mutex metrics_lock;
    3427                 :            : // NB: these objects get released during the process exit via global dtors
    3428                 :            : // do not call them from within other global dtors
    3429                 :            : 
    3430                 :            : // utility function for assembling prometheus-compatible
    3431                 :            : // name="escaped-value" strings
    3432                 :            : // https://prometheus.io/docs/instrumenting/exposition_formats/
    3433                 :            : static string
    3434                 :     788607 : metric_label(const string& name, const string& value)
    3435                 :            : {
    3436                 :     788607 :   string x = name + "=\"";
    3437         [ +  + ]:   13603502 :   for (auto&& c : value)
    3438   [ -  -  -  + ]:   12815427 :     switch(c)
    3439                 :            :       {
    3440         [ #  # ]:          0 :       case '\\': x += "\\\\"; break;
    3441         [ #  # ]:          0 :       case '\"': x += "\\\""; break;
    3442         [ #  # ]:          0 :       case '\n': x += "\\n"; break;
    3443         [ +  - ]:   25630659 :       default: x += c; break;
    3444                 :            :       }
    3445         [ +  - ]:     788075 :   x += "\"";
    3446                 :     788203 :   return x;
    3447                 :          0 : }
    3448                 :            : 
    3449                 :            : 
    3450                 :            : // add prometheus-format metric name + label tuple (if any) + value
    3451                 :            : 
    3452                 :            : static void
    3453                 :       1608 : set_metric(const string& metric, double value)
    3454                 :            : {
    3455                 :       1608 :   unique_lock<mutex> lock(metrics_lock);
    3456         [ +  - ]:       1608 :   metrics[metric] = value;
    3457                 :       1608 : }
    3458                 :            : static void
    3459                 :        784 : inc_metric(const string& metric)
    3460                 :            : {
    3461                 :        784 :   unique_lock<mutex> lock(metrics_lock);
    3462         [ +  - ]:        784 :   metrics[metric] ++;
    3463                 :        784 : }
    3464                 :            : static void
    3465                 :       7052 : set_metric(const string& metric,
    3466                 :            :            const string& lname, const string& lvalue,
    3467                 :            :            double value)
    3468                 :            : {
    3469   [ +  -  +  -  :      14103 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  -  +  +  
                +  -  - ]
    3470         [ +  - ]:       7051 :   unique_lock<mutex> lock(metrics_lock);
    3471         [ +  - ]:       7052 :   metrics[key] = value;
    3472         [ +  - ]:      14104 : }
    3473                 :            : 
    3474                 :            : static void
    3475                 :     376865 : inc_metric(const string& metric,
    3476                 :            :            const string& lname, const string& lvalue)
    3477                 :            : {
    3478   [ +  -  +  -  :     819691 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  +  +  +  
                +  -  - ]
    3479         [ +  - ]:     376864 :   unique_lock<mutex> lock(metrics_lock);
    3480         [ +  - ]:     376872 :   metrics[key] ++;
    3481         [ +  - ]:     753709 : }
    3482                 :            : static void
    3483                 :     364571 : add_metric(const string& metric,
    3484                 :            :            const string& lname, const string& lvalue,
    3485                 :            :            double value)
    3486                 :            : {
    3487   [ +  -  +  -  :     795103 :   string key = (metric + "{" + metric_label(lname, lvalue) + "}");
          -  +  +  +  +  
                +  -  - ]
    3488         [ +  - ]:     364570 :   unique_lock<mutex> lock(metrics_lock);
    3489         [ +  - ]:     364608 :   metrics[key] += value;
    3490         [ +  - ]:     729210 : }
    3491                 :            : static void
    3492                 :        784 : add_metric(const string& metric,
    3493                 :            :            double value)
    3494                 :            : {
    3495                 :        784 :   unique_lock<mutex> lock(metrics_lock);
    3496         [ +  - ]:        784 :   metrics[metric] += value;
    3497                 :        784 : }
    3498                 :            : 
    3499                 :            : 
    3500                 :            : // and more for higher arity labels if needed
    3501                 :            : 
    3502                 :            : static void
    3503                 :      10056 : inc_metric(const string& metric,
    3504                 :            :            const string& lname, const string& lvalue,
    3505                 :            :            const string& rname, const string& rvalue)
    3506                 :            : {
    3507   [ +  -  -  +  :      20112 :   string key = (metric + "{"
                   -  - ]
    3508   [ +  -  +  -  :      40224 :                 + metric_label(lname, lvalue) + ","
          -  +  -  +  +  
                +  -  - ]
    3509   [ +  -  -  +  :      30168 :                 + metric_label(rname, rvalue) + "}");
                   -  + ]
    3510         [ +  - ]:      10056 :   unique_lock<mutex> lock(metrics_lock);
    3511         [ +  - ]:      10056 :   metrics[key] ++;
    3512         [ +  - ]:      20112 : }
    3513                 :            : static void
    3514                 :      10056 : add_metric(const string& metric,
    3515                 :            :            const string& lname, const string& lvalue,
    3516                 :            :            const string& rname, const string& rvalue,
    3517                 :            :            double value)
    3518                 :            : {
    3519   [ +  -  -  +  :      20112 :   string key = (metric + "{"
                   -  - ]
    3520   [ +  -  +  -  :      40224 :                 + metric_label(lname, lvalue) + ","
          -  +  -  +  +  
                +  -  - ]
    3521   [ +  -  -  +  :      30168 :                 + metric_label(rname, rvalue) + "}");
                   -  + ]
    3522         [ +  - ]:      10056 :   unique_lock<mutex> lock(metrics_lock);
    3523         [ +  - ]:      10056 :   metrics[key] += value;
    3524         [ +  - ]:      20112 : }
    3525                 :            : 
    3526                 :            : static struct MHD_Response*
    3527                 :        746 : handle_metrics (off_t* size)
    3528                 :            : {
    3529                 :        746 :   stringstream o;
    3530                 :        746 :   {
    3531         [ +  - ]:        746 :     unique_lock<mutex> lock(metrics_lock);
    3532         [ +  + ]:      80345 :     for (auto&& i : metrics)
    3533         [ +  - ]:      79599 :       o << i.first
    3534                 :            :         << " "
    3535   [ +  -  +  - ]:      79599 :         << std::setprecision(std::numeric_limits<double>::digits10 + 1)
    3536   [ +  -  +  - ]:      79599 :         << i.second
    3537                 :      79599 :         << endl;
    3538                 :          0 :   }
    3539         [ +  - ]:        746 :   const string& os = o.str();
    3540         [ +  - ]:        746 :   MHD_Response* r = MHD_create_response_from_buffer (os.size(),
    3541         [ +  - ]:        746 :                                                      (void*) os.c_str(),
    3542                 :            :                                                      MHD_RESPMEM_MUST_COPY);
    3543         [ +  - ]:        746 :   if (r != NULL)
    3544                 :            :     {
    3545         [ +  - ]:        746 :       *size = os.size();
    3546         [ +  - ]:        746 :       add_mhd_response_header (r, "Content-Type", "text/plain");
    3547                 :            :     }
    3548         [ +  - ]:       1492 :   return r;
    3549                 :        746 : }
    3550                 :            : 
    3551                 :            : 
    3552                 :            : static struct MHD_Response*
    3553                 :         30 : handle_metadata (MHD_Connection* conn,
    3554                 :            :                  string key, string value, off_t* size)
    3555                 :            : {
    3556                 :         30 :   MHD_Response* r;
    3557                 :            :   // Because this query can take on the order of many seconds, we need
    3558                 :            :   // to prevent DoS against the other normal quick queries, so we use
    3559                 :            :   // a dedicated database connection.
    3560                 :         30 :   sqlite3 *thisdb = 0;
    3561                 :         30 :   int rc = sqlite3_open_v2 (db_path.c_str(), &thisdb, (SQLITE_OPEN_READONLY
    3562                 :            :                                                        |SQLITE_OPEN_URI
    3563                 :            :                                                        |SQLITE_OPEN_PRIVATECACHE
    3564                 :            :                                                        |SQLITE_OPEN_NOMUTEX), /* private to us */
    3565                 :            :                             NULL);
    3566         [ -  + ]:         30 :   if (rc)
    3567   [ #  #  #  # ]:          0 :     throw sqlite_exception(rc, "cannot open database for metadata query");
    3568                 :         30 :   defer_dtor<sqlite3*,int> sqlite_db_closer (thisdb, sqlite3_close_v2);
    3569                 :            :                                            
    3570                 :            :   // Query locally for matching e, d files
    3571                 :         30 :   string op;
    3572         [ +  + ]:         30 :   if (key == "glob")
    3573         [ +  - ]:         26 :     op = "glob";
    3574         [ +  - ]:          4 :   else if (key == "file")
    3575         [ +  - ]:          4 :     op = "=";
    3576                 :            :   else
    3577   [ #  #  #  # ]:          0 :     throw reportable_exception("/metadata webapi error, unsupported key");
    3578                 :            : 
    3579                 :            :   // Since PR30378, the file names are segmented into two tables.  We
    3580                 :            :   // could do a glob/= search over the _files_v view that combines
    3581                 :            :   // them, but that means that the entire _files_v thing has to be
    3582                 :            :   // materialized & scanned to do the query.  Slow!  Instead, we can
    3583                 :            :   // segment the incoming file/glob pattern into dirname / basename
    3584                 :            :   // parts, and apply them to the corresponding table.  This is done
    3585                 :            :   // by splitting the value at the last "/".  If absent, the same
    3586                 :            :   // convention as is used in register_file_name().
    3587                 :            : 
    3588                 :         30 :   string dirname, bname; // basename is a "poisoned" identifier on some distros
    3589                 :         30 :   size_t slash = value.rfind('/');
    3590         [ -  + ]:         30 :   if (slash == std::string::npos) {
    3591         [ #  # ]:          0 :     dirname = "";
    3592         [ #  # ]:          0 :     bname = value;
    3593                 :            :   } else {
    3594   [ +  -  -  + ]:         30 :     dirname = value.substr(0, slash);
    3595   [ +  -  -  + ]:         30 :     bname = value.substr(slash+1);
    3596                 :            :   }
    3597                 :            : 
    3598                 :            :   // NB: further optimization is possible: replacing the 'glob' op
    3599                 :            :   // with simple equality, if the corresponding value segment lacks
    3600                 :            :   // metacharacters.  sqlite may or may not be smart enough to do so,
    3601                 :            :   // so we help out.
    3602   [ +  -  -  - ]:         30 :   string metacharacters = "[]*?";
    3603   [ +  +  +  +  :         56 :   string dop = (op == "glob" && dirname.find_first_of(metacharacters) == string::npos) ? "=" : op;
          +  -  +  -  -  
                      - ]
    3604   [ +  +  -  +  :         56 :   string bop = (op == "glob" && bname.find_first_of(metacharacters) == string::npos) ? "=" : op;
          -  -  +  -  -  
                      - ]
    3605                 :            :   
    3606                 :         30 :   string sql = string(
    3607                 :            :                       // explicit query r_de and f_de once here, rather than the query_d and query_e
    3608                 :            :                       // separately, because they scan the same tables, so we'd double the work
    3609                 :            :                       "select d1.executable_p, d1.debuginfo_p, 0 as source_p, "
    3610                 :            :                       "       b1.hex, f1d.name || '/' || f1b.name as file, a1.name as archive "
    3611                 :            :                       "from " BUILDIDS "_r_de d1, " BUILDIDS "_files f1, " BUILDIDS "_fileparts f1b, " BUILDIDS "_fileparts f1d, "
    3612                 :            :                       BUILDIDS "_buildids b1, " BUILDIDS "_files_v a1 "
    3613                 :            :                       "where f1.id = d1.content and a1.id = d1.file and d1.buildid = b1.id "
    3614   [ +  -  +  -  :         90 :                       "      and f1d.name " + dop + " ? and f1b.name " + bop + " ? and f1.dirname = f1d.id and f1.basename = f1b.id "
          -  +  -  +  -  
                      + ]
    3615                 :            :                       "union all \n"
    3616                 :            :                       "select d2.executable_p, d2.debuginfo_p, 0, "
    3617                 :            :                       "       b2.hex, f2d.name || '/' || f2b.name, NULL "
    3618                 :            :                       "from " BUILDIDS "_f_de d2, " BUILDIDS "_files f2, " BUILDIDS "_fileparts f2b, " BUILDIDS "_fileparts f2d, "
    3619                 :            :                       BUILDIDS "_buildids b2 "
    3620                 :            :                       "where f2.id = d2.file and d2.buildid = b2.id "
    3621   [ +  -  +  -  :         90 :                       "      and f2d.name " + dop + " ? and f2b.name " + bop + " ? "
          -  +  -  +  -  
                +  -  - ]
    3622         [ -  + ]:         30 :                       "      and f2.dirname = f2d.id and f2.basename = f2b.id");
    3623                 :            :   
    3624                 :            :   // NB: we could query source file names too, thusly:
    3625                 :            :   //
    3626                 :            :   //    select * from " BUILDIDS "_buildids b, " BUILDIDS "_files_v f1, " BUILDIDS "_r_sref sr
    3627                 :            :   //    where b.id = sr.buildid and f1.id = sr.artifactsrc and f1.name " + op + "?"
    3628                 :            :   //    UNION ALL something with BUILDIDS "_f_s"
    3629                 :            :   //
    3630                 :            :   // But the first part of this query cannot run fast without the same index temp-created
    3631                 :            :   // during "maxigroom":
    3632                 :            :   //    create index " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);
    3633                 :            :   // and unfortunately this index is HUGE.  It's similar to the size of the _r_sref
    3634                 :            :   // table, which is already the largest part of a debuginfod index.  Adding that index
    3635                 :            :   // would nearly double the .sqlite db size.
    3636                 :            :                       
    3637   [ +  -  +  -  :         30 :   sqlite_ps *pp = new sqlite_ps (thisdb, "mhd-query-meta-glob", sql);
             +  -  +  - ]
    3638         [ +  - ]:         30 :   pp->reset();
    3639         [ +  - ]:         30 :   pp->bind(1, dirname);
    3640         [ +  - ]:         30 :   pp->bind(2, bname);
    3641         [ +  - ]:         30 :   pp->bind(3, dirname);
    3642         [ +  - ]:         30 :   pp->bind(4, bname);
    3643                 :         30 :   unique_ptr<sqlite_ps> ps_closer(pp); // release pp if exception or return
    3644                 :         30 :   pp->reset_timeout(metadata_maxtime_s);
    3645                 :            :       
    3646         [ +  - ]:         30 :   json_object *metadata = json_object_new_object();
    3647   [ -  +  -  -  :         30 :   if (!metadata) throw libc_exception(ENOMEM, "json allocation");
                   -  - ]
    3648                 :         30 :   defer_dtor<json_object*,int> metadata_d(metadata, json_object_put);
    3649         [ +  - ]:         30 :   json_object *metadata_arr = json_object_new_array();
    3650   [ -  +  -  -  :         30 :   if (!metadata_arr) throw libc_exception(ENOMEM, "json allocation");
                   -  - ]
    3651         [ +  - ]:         30 :   json_object_object_add(metadata, "results", metadata_arr);
    3652                 :            :   // consume all the rows
    3653                 :            :   
    3654                 :         48 :   bool metadata_complete = true;
    3655                 :         48 :   while (1)
    3656                 :            :     {
    3657         [ +  - ]:         48 :       rc = pp->step_timeout();
    3658         [ +  + ]:         48 :       if (rc == SQLITE_DONE) // success
    3659                 :            :         break;
    3660         [ +  - ]:         18 :       if (rc == SQLITE_ABORT || rc == SQLITE_INTERRUPT) // interrupted such as by timeout
    3661                 :            :         {
    3662                 :            :           metadata_complete = false;
    3663                 :            :           break;
    3664                 :            :         }
    3665         [ -  + ]:         18 :       if (rc != SQLITE_ROW) // error
    3666   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    3667                 :            : 
    3668         [ +  - ]:         18 :       int m_executable_p = sqlite3_column_int (*pp, 0);
    3669         [ +  - ]:         18 :       int m_debuginfo_p  = sqlite3_column_int (*pp, 1);
    3670         [ +  - ]:         18 :       int m_source_p     = sqlite3_column_int (*pp, 2);
    3671   [ +  -  -  +  :         18 :       string m_buildid   = (const char*) sqlite3_column_text (*pp, 3) ?: ""; // should always be non-null
                   +  - ]
    3672   [ +  -  -  +  :         18 :       string m_file      = (const char*) sqlite3_column_text (*pp, 4) ?: "";
             +  -  -  - ]
    3673   [ +  -  -  +  :         18 :       string m_archive   = (const char*) sqlite3_column_text (*pp, 5) ?: "";      
             +  -  -  - ]
    3674                 :            : 
    3675                 :            :       // Confirm that m_file matches in the fnmatch(FNM_PATHNAME)
    3676                 :            :       // sense, since sqlite's GLOB operator is a looser filter.
    3677   [ +  -  +  -  :         18 :       if (key == "glob" && fnmatch(value.c_str(), m_file.c_str(), FNM_PATHNAME) != 0)
                   -  + ]
    3678         [ #  # ]:          0 :         continue;
    3679                 :            :       
    3680                 :         54 :       auto add_metadata = [metadata_arr, m_buildid, m_file, m_archive](const string& type) {
    3681                 :         18 :         json_object* entry = json_object_new_object();
    3682   [ -  +  -  -  :         18 :         if (NULL == entry) throw libc_exception (ENOMEM, "cannot allocate json");
                   -  - ]
    3683                 :         18 :         defer_dtor<json_object*,int> entry_d(entry, json_object_put);
    3684                 :            :         
    3685                 :        162 :         auto add_entry_metadata = [entry](const char* k, string v) {
    3686                 :         72 :           json_object* s;
    3687         [ +  - ]:         72 :           if(v != "") {
    3688                 :         72 :             s = json_object_new_string(v.c_str());
    3689   [ -  +  -  -  :         72 :             if (NULL == s) throw libc_exception (ENOMEM, "cannot allocate json");
                   -  - ]
    3690                 :         72 :             json_object_object_add(entry, k, s);
    3691                 :            :           }
    3692                 :         72 :         };
    3693                 :            :         
    3694   [ +  -  +  - ]:         18 :         add_entry_metadata("type", type.c_str());
    3695   [ +  -  +  - ]:         18 :         add_entry_metadata("buildid", m_buildid);
    3696   [ +  -  +  - ]:         18 :         add_entry_metadata("file", m_file);
    3697   [ +  -  +  -  :         36 :         if (m_archive != "") add_entry_metadata("archive", m_archive);        
                   +  - ]
    3698         [ -  + ]:         18 :         if (verbose > 3)
    3699         [ #  # ]:          0 :           obatched(clog) << "metadata found local "
    3700                 :            :                          << json_object_to_json_string_ext(entry,
    3701   [ #  #  #  #  :          0 :                                                            JSON_C_TO_STRING_PRETTY)
                   #  # ]
    3702                 :          0 :                          << endl;
    3703                 :            :         
    3704                 :            :         // Increase ref count to switch its ownership
    3705   [ +  -  +  - ]:         18 :         json_object_array_add(metadata_arr, json_object_get(entry));
    3706   [ +  -  +  -  :         36 :       };
                   +  - ]
    3707                 :            : 
    3708   [ +  -  +  -  :         36 :       if (m_executable_p) add_metadata("executable");
                   +  - ]
    3709   [ -  +  -  -  :         18 :       if (m_debuginfo_p) add_metadata("debuginfo");      
                   -  - ]
    3710   [ -  +  -  -  :         18 :       if (m_source_p) add_metadata("source");              
                   -  - ]
    3711   [ -  -  -  -  :         72 :     }
          +  -  +  -  +  
                      - ]
    3712         [ +  - ]:         30 :   pp->reset();
    3713                 :            : 
    3714         [ +  - ]:         30 :   unsigned num_local_results = json_object_array_length(metadata_arr);
    3715                 :            :   
    3716                 :            :   // Query upstream as well
    3717         [ +  - ]:         30 :   debuginfod_client *client = debuginfod_pool_begin();
    3718         [ +  - ]:         30 :   if (client != NULL)
    3719                 :            :   {
    3720         [ +  - ]:         30 :     add_client_federation_headers(client, conn);
    3721                 :            : 
    3722                 :         30 :     int upstream_metadata_fd;
    3723                 :         30 :     char *upstream_metadata_file = NULL;
    3724         [ +  - ]:         30 :     upstream_metadata_fd = debuginfod_find_metadata(client, key.c_str(), (char*)value.c_str(),
    3725                 :            :                                                     &upstream_metadata_file);
    3726         [ +  + ]:         30 :     if (upstream_metadata_fd >= 0) {
    3727                 :            :        /* json-c >= 0.13 has json_object_from_fd(). */
    3728         [ +  - ]:         18 :       json_object *upstream_metadata_json = json_object_from_file(upstream_metadata_file);
    3729                 :         18 :       free (upstream_metadata_file);
    3730                 :         18 :       json_object *upstream_metadata_json_arr;
    3731                 :         18 :       json_object *upstream_complete;
    3732         [ -  + ]:         18 :       if (NULL != upstream_metadata_json &&
    3733   [ +  -  +  -  :         36 :           json_object_object_get_ex(upstream_metadata_json, "results", &upstream_metadata_json_arr) &&
                   -  + ]
    3734         [ +  - ]:         18 :           json_object_object_get_ex(upstream_metadata_json, "complete", &upstream_complete))
    3735                 :            :         {
    3736         [ +  - ]:         18 :           metadata_complete &= json_object_get_boolean(upstream_complete);
    3737   [ +  -  +  + ]:         22 :           for (int i = 0, n = json_object_array_length(upstream_metadata_json_arr); i < n; i++)
    3738                 :            :             {
    3739         [ +  - ]:          4 :               json_object *entry = json_object_array_get_idx(upstream_metadata_json_arr, i);
    3740         [ -  + ]:          4 :               if (verbose > 3)
    3741         [ #  # ]:          0 :                 obatched(clog) << "metadata found remote "
    3742                 :            :                                << json_object_to_json_string_ext(entry,
    3743   [ #  #  #  #  :          0 :                                                                  JSON_C_TO_STRING_PRETTY)
                   #  # ]
    3744                 :          0 :                                << endl;
    3745                 :            :               
    3746         [ +  - ]:          4 :               json_object_get(entry); // increment reference count
    3747         [ +  - ]:          4 :               json_object_array_add(metadata_arr, entry);
    3748                 :            :             }
    3749         [ +  - ]:         18 :           json_object_put(upstream_metadata_json);
    3750                 :            :         }
    3751         [ +  - ]:         18 :       close(upstream_metadata_fd);
    3752                 :            :     }
    3753         [ +  - ]:         30 :     debuginfod_pool_end (client);
    3754                 :            :   }
    3755                 :            : 
    3756         [ +  - ]:         30 :   unsigned num_total_results = json_object_array_length(metadata_arr);
    3757                 :            : 
    3758         [ +  - ]:         30 :   if (verbose > 2)
    3759   [ +  -  +  - ]:         90 :     obatched(clog) << "metadata found local=" << num_local_results
    3760   [ +  -  +  - ]:         30 :                    << " remote=" << (num_total_results-num_local_results)
    3761   [ +  -  +  -  :         30 :                    << " total=" << num_total_results
                   +  - ]
    3762                 :         30 :                    << endl;
    3763                 :            :   
    3764   [ +  -  +  - ]:         30 :   json_object_object_add(metadata, "complete", json_object_new_boolean(metadata_complete));
    3765         [ +  - ]:         30 :   const char* metadata_str = json_object_to_json_string(metadata);
    3766         [ -  + ]:         30 :   if (!metadata_str)
    3767   [ #  #  #  # ]:          0 :     throw libc_exception (ENOMEM, "cannot allocate json");
    3768         [ +  - ]:         30 :   r = MHD_create_response_from_buffer (strlen(metadata_str),
    3769                 :            :                                        (void*) metadata_str,
    3770                 :            :                                        MHD_RESPMEM_MUST_COPY);
    3771                 :         30 :   *size = strlen(metadata_str);
    3772         [ +  - ]:         30 :   if (r)
    3773         [ +  - ]:         30 :     add_mhd_response_header(r, "Content-Type", "application/json");
    3774                 :         30 :   return r;
    3775   [ +  -  -  +  :         60 : }
          -  +  -  +  -  
             +  -  +  -  
                      + ]
    3776                 :            : 
    3777                 :            : 
    3778                 :            : static struct MHD_Response*
    3779                 :          0 : handle_root (off_t* size)
    3780                 :            : {
    3781   [ #  #  #  #  :          0 :   static string version = "debuginfod (" + string (PACKAGE_NAME) + ") "
          #  #  #  #  #  
                #  #  # ]
    3782   [ #  #  #  #  :          0 :                           + string (PACKAGE_VERSION);
          #  #  #  #  #  
                      # ]
    3783                 :          0 :   MHD_Response* r = MHD_create_response_from_buffer (version.size (),
    3784                 :          0 :                                                      (void *) version.c_str (),
    3785                 :            :                                                      MHD_RESPMEM_PERSISTENT);
    3786         [ #  # ]:          0 :   if (r != NULL)
    3787                 :            :     {
    3788                 :          0 :       *size = version.size ();
    3789                 :          0 :       add_mhd_response_header (r, "Content-Type", "text/plain");
    3790                 :            :     }
    3791                 :          0 :   return r;
    3792                 :            : }
    3793                 :            : 
    3794                 :            : 
    3795                 :            : static struct MHD_Response*
    3796                 :          2 : handle_options (off_t* size)
    3797                 :            : {
    3798                 :          2 :   static char empty_body[] = " ";
    3799                 :          2 :   MHD_Response* r = MHD_create_response_from_buffer (1, empty_body,
    3800                 :            :                                                      MHD_RESPMEM_PERSISTENT);
    3801         [ +  - ]:          2 :   if (r != NULL)
    3802                 :            :     {
    3803                 :          2 :       *size = 1;
    3804                 :          2 :       add_mhd_response_header (r, "Access-Control-Allow-Origin", "*");
    3805                 :          2 :       add_mhd_response_header (r, "Access-Control-Allow-Methods", "GET, OPTIONS");
    3806                 :          2 :       add_mhd_response_header (r, "Access-Control-Allow-Headers", "cache-control");
    3807                 :            :     }
    3808                 :          2 :   return r;
    3809                 :            : }
    3810                 :            : 
    3811                 :            : 
    3812                 :            : ////////////////////////////////////////////////////////////////////////
    3813                 :            : 
    3814                 :            : 
    3815                 :            : /* libmicrohttpd callback */
    3816                 :            : static MHD_RESULT
    3817                 :       6708 : handler_cb (void * /*cls*/,
    3818                 :            :             struct MHD_Connection *connection,
    3819                 :            :             const char *url,
    3820                 :            :             const char *method,
    3821                 :            :             const char * /*version*/,
    3822                 :            :             const char * /*upload_data*/,
    3823                 :            :             size_t * /*upload_data_size*/,
    3824                 :            :             void ** ptr)
    3825                 :            : {
    3826                 :       6708 :   struct MHD_Response *r = NULL;
    3827                 :       6708 :   string url_copy = url;
    3828                 :            : 
    3829                 :            :   /* libmicrohttpd always makes (at least) two callbacks: once just
    3830                 :            :      past the headers, and one after the request body is finished
    3831                 :            :      being received.  If we process things early (first callback) and
    3832                 :            :      queue a response, libmicrohttpd would suppress http keep-alive
    3833                 :            :      (via connection->read_closed = true). */
    3834                 :       6708 :   static int aptr; /* just some random object to use as a flag */
    3835         [ +  + ]:       6708 :   if (&aptr != *ptr)
    3836                 :            :     {
    3837                 :            :       /* do never respond on first call */
    3838                 :       3354 :       *ptr = &aptr;
    3839                 :       3354 :       return MHD_YES;
    3840                 :            :     }
    3841                 :       3354 :   *ptr = NULL;                     /* reset when done */
    3842                 :            :   
    3843         [ +  - ]:       3354 :   const char *maxsize_string = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "X-DEBUGINFOD-MAXSIZE");
    3844                 :       3354 :   long maxsize = 0;
    3845   [ +  +  +  - ]:       3354 :   if (maxsize_string != NULL && maxsize_string[0] != '\0')
    3846                 :          2 :     maxsize = atol(maxsize_string);
    3847                 :            :   else
    3848                 :            :     maxsize = 0;
    3849                 :            : 
    3850                 :            : #if MHD_VERSION >= 0x00097002
    3851                 :       3354 :   enum MHD_Result rc;
    3852                 :            : #else
    3853                 :            :   int rc = MHD_NO; // mhd
    3854                 :            : #endif
    3855                 :       3354 :   int http_code = 500;
    3856                 :       3354 :   off_t http_size = -1;
    3857                 :       3354 :   struct timespec ts_start, ts_end;
    3858                 :       3354 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    3859                 :       3353 :   double afteryou = 0.0;
    3860         [ +  + ]:       3353 :   string artifacttype, suffix;
    3861                 :       3353 :   string urlargs; // for logging
    3862                 :            : 
    3863                 :       3353 :   try
    3864                 :            :     {
    3865   [ +  +  +  -  :       4703 :       if (webapi_cors && method == string("OPTIONS"))
          +  +  +  +  +  
                      + ]
    3866                 :            :         {
    3867   [ +  -  +  -  :          4 :           inc_metric("http_requests_total", "type", method);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3868         [ +  - ]:          2 :           r = handle_options(& http_size);
    3869         [ +  - ]:          2 :           rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
    3870                 :          2 :           http_code = MHD_HTTP_OK;
    3871         [ +  - ]:          2 :           MHD_destroy_response (r);
    3872                 :          2 :           return rc;
    3873                 :            :         }
    3874   [ +  -  -  +  :       7332 :       else if (string(method) != "GET")
                   -  + ]
    3875   [ #  #  #  # ]:          0 :         throw reportable_exception(400, "we support OPTIONS+GET only");
    3876                 :            : 
    3877                 :            :       /* Start decoding the URL. */
    3878                 :       3351 :       size_t slash1 = url_copy.find('/', 1);
    3879         [ +  - ]:       3352 :       string url1 = url_copy.substr(0, slash1); // ok even if slash1 not found
    3880                 :            : 
    3881   [ +  +  +  + ]:       5922 :       if (slash1 != string::npos && url1 == "/buildid")
    3882                 :            :         {
    3883                 :            :           // PR27863: block this thread awhile if another thread is already busy
    3884                 :            :           // fetching the exact same thing.  This is better for Everyone.
    3885                 :            :           // The latecomer says "... after you!" and waits.
    3886   [ +  -  +  -  :       5761 :           add_metric ("thread_busy", "role", "http-buildid-after-you", 1);
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    3887                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    3888                 :       2570 :           (void) pthread_setname_np (pthread_self(), "mhd-buildid-after-you");
    3889                 :            : #endif
    3890                 :       2570 :           struct timespec tsay_start, tsay_end;
    3891                 :       2570 :           clock_gettime (CLOCK_MONOTONIC, &tsay_start);
    3892   [ +  +  +  + ]:       2570 :           static unique_set<string> busy_urls;
    3893         [ +  - ]:       2570 :           unique_set_reserver<string> after_you(busy_urls, url_copy);
    3894                 :       2570 :           clock_gettime (CLOCK_MONOTONIC, &tsay_end);
    3895                 :       2570 :           afteryou = (tsay_end.tv_sec - tsay_start.tv_sec) + (tsay_end.tv_nsec - tsay_start.tv_nsec)/1.e9;
    3896   [ +  -  +  -  :       5140 :           add_metric ("thread_busy", "role", "http-buildid-after-you", -1);
          +  -  +  -  -  
          +  +  -  -  -  
                   -  - ]
    3897                 :            :           
    3898   [ +  -  +  -  :       5140 :           tmp_inc_metric m ("thread_busy", "role", "http-buildid");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3899                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    3900                 :       2570 :           (void) pthread_setname_np (pthread_self(), "mhd-buildid");
    3901                 :            : #endif
    3902                 :       2570 :           size_t slash2 = url_copy.find('/', slash1+1);
    3903         [ -  + ]:       2570 :           if (slash2 == string::npos)
    3904   [ #  #  #  # ]:          0 :             throw reportable_exception("/buildid/ webapi error, need buildid");
    3905                 :            : 
    3906         [ +  - ]:       2570 :           string buildid = url_copy.substr(slash1+1, slash2-slash1-1);
    3907                 :            : 
    3908                 :       2570 :           size_t slash3 = url_copy.find('/', slash2+1);
    3909                 :            : 
    3910         [ +  + ]:       2570 :           if (slash3 == string::npos)
    3911                 :            :             {
    3912   [ +  -  -  + ]:       1460 :               artifacttype = url_copy.substr(slash2+1);
    3913         [ +  - ]:       1460 :               suffix = "";
    3914                 :            :             }
    3915                 :            :           else
    3916                 :            :             {
    3917   [ +  -  -  + ]:       1110 :               artifacttype = url_copy.substr(slash2+1, slash3-slash2-1);
    3918   [ +  -  -  +  :       1732 :               suffix = url_copy.substr(slash3); // include the slash in the suffix
                   +  + ]
    3919                 :            :             }
    3920                 :            : 
    3921                 :            :           // get the resulting fd so we can report its size
    3922                 :       2570 :           int fd;
    3923         [ +  + ]:       2570 :           r = handle_buildid (connection, buildid, artifacttype, suffix, &fd);
    3924         [ +  - ]:       1948 :           if (r)
    3925                 :            :             {
    3926                 :       1948 :               struct stat fs;
    3927         [ +  - ]:       1948 :               if (fstat(fd, &fs) == 0)
    3928                 :       1948 :                 http_size = fs.st_size;
    3929                 :            :               // libmicrohttpd will close (fd);
    3930                 :            :             }
    3931                 :       3192 :         }
    3932         [ +  + ]:        783 :       else if (url1 == "/metrics")
    3933                 :            :         {
    3934   [ +  -  +  -  :       1492 :           tmp_inc_metric m ("thread_busy", "role", "http-metrics");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3935         [ +  - ]:        746 :           artifacttype = "metrics";
    3936   [ +  -  +  -  :       1492 :           inc_metric("http_requests_total", "type", artifacttype);
          +  -  -  +  -  
                      - ]
    3937         [ +  - ]:        746 :           r = handle_metrics(& http_size);
    3938                 :        746 :         }
    3939         [ +  + ]:         36 :       else if (url1 == "/metadata")
    3940                 :            :         {
    3941   [ +  -  +  -  :         60 :           tmp_inc_metric m ("thread_busy", "role", "http-metadata");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3942         [ +  - ]:         30 :           const char* key = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "key");
    3943         [ +  - ]:         30 :           const char* value = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "value");
    3944         [ -  + ]:         30 :           if (NULL == value || NULL == key)
    3945   [ #  #  #  # ]:          0 :             throw reportable_exception("/metadata webapi error, need key and value");
    3946                 :            : 
    3947   [ +  -  +  -  :         30 :           urlargs = string("?key=") + string(key) + string("&value=") + string(value); // apprx., for logging
          +  -  +  -  +  
          -  +  -  +  -  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  -  
             -  -  -  -  
                      - ]
    3948         [ +  - ]:         30 :           artifacttype = "metadata";
    3949   [ +  -  +  -  :         60 :           inc_metric("http_requests_total", "type", artifacttype);
          +  -  -  +  -  
                      - ]
    3950   [ +  -  +  -  :         30 :           r = handle_metadata(connection, key, value, &http_size);
          +  -  -  +  +  
                +  -  - ]
    3951                 :         30 :         }
    3952         [ -  + ]:          6 :       else if (url1 == "/")
    3953                 :            :         {
    3954         [ #  # ]:          0 :           artifacttype = "/";
    3955   [ -  -  -  -  :        630 :           inc_metric("http_requests_total", "type", artifacttype);
          -  -  -  -  -  
                -  -  + ]
    3956         [ #  # ]:          0 :           r = handle_root(& http_size);
    3957                 :            :         }
    3958                 :            :       else
    3959   [ +  -  +  -  :         18 :         throw reportable_exception("webapi error, unrecognized '" + url1 + "'");
             +  -  -  + ]
    3960                 :            : 
    3961         [ -  + ]:       2724 :       if (r == 0)
    3962   [ #  #  #  # ]:          0 :         throw reportable_exception("internal error, missing response");
    3963                 :            : 
    3964   [ +  +  +  - ]:       2724 :       if (maxsize > 0 && http_size > maxsize)
    3965                 :            :         {
    3966         [ +  - ]:          2 :           MHD_destroy_response(r);
    3967   [ +  -  +  -  :          6 :           throw reportable_exception(406, "File too large, max size=" + std::to_string(maxsize));
             +  -  -  + ]
    3968                 :            :         }
    3969                 :            : 
    3970         [ +  + ]:       2722 :       if (webapi_cors)
    3971                 :            :         // add ACAO header for all successful requests
    3972         [ +  - ]:        132 :         add_mhd_response_header (r, "Access-Control-Allow-Origin", "*");
    3973         [ +  - ]:       2722 :       rc = MHD_queue_response (connection, MHD_HTTP_OK, r);
    3974                 :       2722 :       http_code = MHD_HTTP_OK;
    3975         [ +  - ]:       2722 :       MHD_destroy_response (r);
    3976                 :       3352 :     }
    3977         [ -  + ]:        630 :   catch (const reportable_exception& e)
    3978                 :            :     {
    3979   [ +  -  +  -  :       1260 :       inc_metric("http_responses_total","result","error");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3980         [ +  - ]:        630 :       e.report(clog);
    3981                 :        630 :       http_code = e.code;
    3982         [ +  - ]:        630 :       http_size = e.message.size();
    3983         [ +  - ]:        630 :       rc = e.mhd_send_response (connection);
    3984                 :        630 :     }
    3985                 :            : 
    3986                 :       3352 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    3987                 :       3352 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    3988                 :            :   // afteryou: delay waiting for other client's identical query to complete
    3989                 :            :   // deltas: total latency, including afteryou waiting
    3990   [ +  -  +  -  :       6704 :   obatched(clog) << conninfo(connection)
                   -  - ]
    3991                 :            :                  << ' ' << method << ' ' << url << urlargs
    3992   [ +  -  +  -  :       3352 :                  << ' ' << http_code << ' ' << http_size
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    3993   [ +  -  +  -  :       3352 :                  << ' ' << (int)(afteryou*1000) << '+' << (int)((deltas-afteryou)*1000) << "ms"
          +  -  +  -  +  
             -  +  -  +  
                      - ]
    3994         [ +  - ]:       3352 :                  << endl;
    3995                 :            : 
    3996                 :            :   // related prometheus metrics
    3997                 :       3352 :   string http_code_str = to_string(http_code);
    3998   [ +  -  +  -  :       6704 :   add_metric("http_responses_transfer_bytes_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    3999                 :            :              "code", http_code_str, "type", artifacttype, http_size);
    4000   [ +  -  +  -  :       6704 :   inc_metric("http_responses_transfer_bytes_count",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4001                 :            :              "code", http_code_str, "type", artifacttype);
    4002                 :            : 
    4003   [ +  -  +  -  :       6704 :   add_metric("http_responses_duration_milliseconds_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4004                 :            :              "code", http_code_str, "type", artifacttype, deltas*1000); // prometheus prefers _seconds and floating point
    4005   [ +  -  +  -  :       6704 :   inc_metric("http_responses_duration_milliseconds_count",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4006                 :            :              "code", http_code_str, "type", artifacttype);
    4007                 :            : 
    4008   [ +  -  +  -  :       6704 :   add_metric("http_responses_after_you_milliseconds_sum",
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4009                 :            :              "code", http_code_str, "type", artifacttype, afteryou*1000);
    4010   [ +  -  +  -  :       6704 :   inc_metric("http_responses_after_you_milliseconds_count",
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
    4011                 :            :              "code", http_code_str, "type", artifacttype);
    4012                 :            : 
    4013         [ -  + ]:       3352 :   return rc;
    4014   [ +  +  +  +  :      16334 : }
             -  +  +  + ]
    4015                 :            : 
    4016                 :            : 
    4017                 :            : ////////////////////////////////////////////////////////////////////////
    4018                 :            : // borrowed originally from src/nm.c get_local_names()
    4019                 :            : 
    4020                 :            : static void
    4021                 :        412 : dwarf_extract_source_paths (Elf *elf, set<string>& debug_sourcefiles)
    4022                 :            :   noexcept // no exceptions - so we can simplify the altdbg resource release at end
    4023                 :            : {
    4024                 :        412 :   Dwarf* dbg = dwarf_begin_elf (elf, DWARF_C_READ, NULL);
    4025         [ -  + ]:        412 :   if (dbg == NULL)
    4026                 :          0 :     return;
    4027                 :            : 
    4028                 :        412 :   Dwarf* altdbg = NULL;
    4029                 :        412 :   int    altdbg_fd = -1;
    4030                 :            : 
    4031                 :            :   // DWZ handling: if we have an unsatisfied debug-alt-link, add an
    4032                 :            :   // empty string into the outgoing sourcefiles set, so the caller
    4033                 :            :   // should know that our data is incomplete.
    4034                 :        412 :   const char *alt_name_p;
    4035                 :        412 :   const void *alt_build_id; // elfutils-owned memory
    4036                 :        412 :   ssize_t sz = dwelf_dwarf_gnu_debugaltlink (dbg, &alt_name_p, &alt_build_id);
    4037         [ +  + ]:        412 :   if (sz > 0) // got one!
    4038                 :            :     {
    4039                 :        200 :       string buildid;
    4040                 :        200 :       unsigned char* build_id_bytes = (unsigned char*) alt_build_id;
    4041         [ +  + ]:       4200 :       for (ssize_t idx=0; idx<sz; idx++)
    4042                 :            :         {
    4043                 :       4000 :           buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
    4044                 :       4000 :           buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
    4045                 :            :         }
    4046                 :            : 
    4047         [ +  + ]:        200 :       if (verbose > 3)
    4048                 :        156 :         obatched(clog) << "Need altdebug buildid=" << buildid << endl;
    4049                 :            : 
    4050                 :            :       // but is it unsatisfied the normal elfutils ways?
    4051                 :        200 :       Dwarf* alt = dwarf_getalt (dbg);
    4052         [ +  - ]:        200 :       if (alt == NULL)
    4053                 :            :         {
    4054                 :            :           // Yup, unsatisfied the normal way.  Maybe we can satisfy it
    4055                 :            :           // from our own debuginfod database.
    4056                 :        200 :           int alt_fd;
    4057                 :        200 :           struct MHD_Response *r = 0;
    4058                 :        200 :           try
    4059                 :            :             {
    4060         [ +  - ]:        200 :               string artifacttype = "debuginfo";
    4061   [ +  -  +  +  :        220 :               r = handle_buildid (0, buildid, artifacttype, "", &alt_fd);
          -  +  -  +  -  
                      + ]
    4062                 :            :               // NB: no need for ACAO etc. headers; this is not getting sent to a client 
    4063                 :         20 :             }
    4064         [ -  + ]:         20 :           catch (const reportable_exception& e)
    4065                 :            :             {
    4066                 :            :               // swallow exceptions
    4067                 :         20 :             }
    4068                 :            : 
    4069                 :            :           // NB: this is not actually recursive!  This invokes the web-query
    4070                 :            :           // path, which cannot get back into the scan code paths.
    4071         [ +  - ]:        180 :           if (r)
    4072                 :            :             {
    4073                 :            :               // Found it!
    4074                 :        180 :               altdbg_fd = dup(alt_fd); // ok if this fails, downstream failures ok
    4075                 :        180 :               alt = altdbg = dwarf_begin (altdbg_fd, DWARF_C_READ);
    4076                 :            :               // NB: must close this dwarf and this fd at the bottom of the function!
    4077                 :        180 :               MHD_destroy_response (r); // will close alt_fd
    4078         [ +  - ]:        180 :               if (alt)
    4079                 :        180 :                 dwarf_setalt (dbg, alt);
    4080                 :            :             }
    4081                 :            :         }
    4082                 :            :       else
    4083                 :            :         {
    4084                 :            :           // NB: dwarf_setalt(alt) inappropriate - already done!
    4085                 :            :           // NB: altdbg will stay 0 so nothing tries to redundantly dealloc.
    4086                 :            :         }
    4087                 :            : 
    4088         [ +  + ]:        200 :       if (alt)
    4089                 :            :         {
    4090         [ +  + ]:        180 :           if (verbose > 3)
    4091                 :        156 :             obatched(clog) << "Resolved altdebug buildid=" << buildid << endl;
    4092                 :            :         }
    4093                 :            :       else // (alt == NULL) - signal possible presence of poor debuginfo
    4094                 :            :         {
    4095         [ -  + ]:         20 :           debug_sourcefiles.insert("");
    4096         [ -  + ]:         20 :           if (verbose > 3)
    4097                 :          0 :             obatched(clog) << "Unresolved altdebug buildid=" << buildid << endl;
    4098                 :            :         }
    4099                 :        200 :     }
    4100                 :            : 
    4101                 :        412 :   Dwarf_Off offset = 0;
    4102                 :        412 :   Dwarf_Off old_offset;
    4103                 :        412 :   size_t hsize;
    4104                 :            : 
    4105         [ +  + ]:       9260 :   while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL, NULL) == 0)
    4106                 :            :     {
    4107                 :       8848 :       Dwarf_Die cudie_mem;
    4108                 :       8848 :       Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
    4109                 :            : 
    4110         [ -  + ]:       8848 :       if (cudie == NULL)
    4111                 :         36 :         continue;
    4112         [ +  + ]:       8848 :       if (dwarf_tag (cudie) != DW_TAG_compile_unit)
    4113                 :         36 :         continue;
    4114                 :            : 
    4115         [ -  + ]:       8812 :       const char *cuname = dwarf_diename(cudie) ?: "unknown";
    4116                 :            : 
    4117                 :       8812 :       Dwarf_Files *files;
    4118                 :       8812 :       size_t nfiles;
    4119         [ -  + ]:       8812 :       if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
    4120                 :          0 :         continue;
    4121                 :            : 
    4122                 :            :       // extract DW_AT_comp_dir to resolve relative file names
    4123                 :       8812 :       const char *comp_dir = "";
    4124                 :       8812 :       const char *const *dirs;
    4125                 :       8812 :       size_t ndirs;
    4126         [ -  + ]:       8812 :       if (dwarf_getsrcdirs (files, &dirs, &ndirs) == 0 &&
    4127         [ -  + ]:       8811 :           dirs[0] != NULL)
    4128                 :            :         comp_dir = dirs[0];
    4129                 :            :       if (comp_dir == NULL)
    4130                 :            :         comp_dir = "";
    4131                 :            : 
    4132         [ +  + ]:       8811 :       if (verbose > 3)
    4133                 :      13555 :         obatched(clog) << "searching for sources for cu=" << cuname << " comp_dir=" << comp_dir
    4134                 :       6778 :                        << " #files=" << nfiles << " #dirs=" << ndirs << endl;
    4135                 :            : 
    4136   [ +  -  -  - ]:       8812 :       if (comp_dir[0] == '\0' && cuname[0] != '/')
    4137                 :            :         {
    4138         [ #  # ]:          0 :           if (verbose > 3)
    4139                 :          0 :             obatched(clog) << "skipping cu=" << cuname << " due to empty comp_dir" << endl;
    4140                 :          0 :           continue;
    4141                 :            :         }
    4142                 :            : 
    4143         [ +  + ]:     143479 :       for (size_t f = 1; f < nfiles; f++)
    4144                 :            :         {
    4145                 :     134667 :           const char *hat = dwarf_filesrc (files, f, NULL, NULL);
    4146         [ -  + ]:     134692 :           if (hat == NULL)
    4147                 :          0 :             continue;
    4148                 :            : 
    4149         [ +  + ]:     134691 :           if (string(hat) == "<built-in>"
    4150   [ +  #  +  #  :     404048 :               || string_endswith(hat, "<built-in>")) // gcc intrinsics, don't bother record
             +  #  +  + ]
    4151                 :       1686 :             continue;
    4152                 :            : 
    4153         [ +  + ]:     133005 :           string waldo;
    4154         [ +  + ]:     133005 :           if (hat[0] == '/') // absolute
    4155         [ -  + ]:      81716 :             waldo = (string (hat));
    4156         [ +  - ]:      51289 :           else if (comp_dir[0] != '\0') // comp_dir relative
    4157   [ -  +  -  +  :      89562 :             waldo = (string (comp_dir) + string("/") + string (hat));
          -  +  -  +  +  
                      + ]
    4158                 :            :           else
    4159                 :            :            {
    4160         [ #  # ]:          0 :              if (verbose > 3)
    4161                 :          0 :                obatched(clog) << "skipping hat=" << hat << " due to empty comp_dir" << endl;
    4162         [ #  # ]:          0 :              continue;
    4163                 :            :            }
    4164                 :            : 
    4165                 :            :           // NB: this is the 'waldo' that a dbginfo client will have
    4166                 :            :           // to supply for us to give them the file The comp_dir
    4167                 :            :           // prefixing is a definite complication.  Otherwise we'd
    4168                 :            :           // have to return a setof comp_dirs (one per CU!) with
    4169                 :            :           // corresponding filesrc[] names, instead of one absolute
    4170                 :            :           // resoved set.  Maybe we'll have to do that anyway.  XXX
    4171                 :            : 
    4172         [ +  + ]:     133004 :           if (verbose > 4)
    4173         [ -  + ]:         32 :             obatched(clog) << waldo
    4174         [ -  + ]:         16 :                            << (debug_sourcefiles.find(waldo)==debug_sourcefiles.end() ? " new" : " dup") <<  endl;
    4175                 :            : 
    4176         [ +  - ]:     133004 :           debug_sourcefiles.insert (waldo);
    4177                 :     134667 :         }
    4178                 :            :     }
    4179                 :            : 
    4180                 :        412 :   dwarf_end(dbg);
    4181         [ +  + ]:        412 :   if (altdbg)
    4182                 :        180 :     dwarf_end(altdbg);
    4183         [ +  + ]:        412 :   if (altdbg_fd >= 0)
    4184                 :        180 :     close(altdbg_fd);
    4185                 :            : }
    4186                 :            : 
    4187                 :            : 
    4188                 :            : 
    4189                 :            : static void
    4190                 :       1700 : elf_classify (int fd, bool &executable_p, bool &debuginfo_p, string &buildid, set<string>& debug_sourcefiles)
    4191                 :            : {
    4192                 :       1700 :   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP_PRIVATE, NULL);
    4193         [ +  - ]:       1700 :   if (elf == NULL)
    4194                 :            :     return;
    4195                 :            : 
    4196                 :       1700 :   try // catch our types of errors and clean up the Elf* object
    4197                 :            :     {
    4198   [ +  -  +  + ]:       1700 :       if (elf_kind (elf) != ELF_K_ELF)
    4199                 :            :         {
    4200         [ +  - ]:        898 :           elf_end (elf);
    4201                 :        938 :           return;
    4202                 :            :         }
    4203                 :            : 
    4204                 :        802 :       GElf_Ehdr ehdr_storage;
    4205         [ +  - ]:        802 :       GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_storage);
    4206         [ -  + ]:        802 :       if (ehdr == NULL)
    4207                 :            :         {
    4208         [ #  # ]:          0 :           elf_end (elf);
    4209                 :            :           return;
    4210                 :            :         }
    4211                 :        802 :       auto elf_type = ehdr->e_type;
    4212                 :            : 
    4213                 :        802 :       const void *build_id; // elfutils-owned memory
    4214         [ +  - ]:        802 :       ssize_t sz = dwelf_elf_gnu_build_id (elf, & build_id);
    4215         [ +  + ]:        802 :       if (sz <= 0)
    4216                 :            :         {
    4217                 :            :           // It's not a diagnostic-worthy error for an elf file to lack build-id.
    4218                 :            :           // It might just be very old.
    4219         [ +  - ]:         40 :           elf_end (elf);
    4220                 :            :           return;
    4221                 :            :         }
    4222                 :            : 
    4223                 :            :       // build_id is a raw byte array; convert to hexadecimal *lowercase*
    4224                 :        762 :       unsigned char* build_id_bytes = (unsigned char*) build_id;
    4225         [ +  + ]:      15995 :       for (ssize_t idx=0; idx<sz; idx++)
    4226                 :            :         {
    4227         [ +  - ]:      15233 :           buildid += "0123456789abcdef"[build_id_bytes[idx] >> 4];
    4228         [ +  - ]:      30465 :           buildid += "0123456789abcdef"[build_id_bytes[idx] & 0xf];
    4229                 :            :         }
    4230                 :            : 
    4231                 :            :       // now decide whether it's an executable - namely, any allocatable section has
    4232                 :            :       // PROGBITS;
    4233         [ +  + ]:        762 :       if (elf_type == ET_EXEC || elf_type == ET_DYN)
    4234                 :            :         {
    4235                 :        700 :           size_t shnum;
    4236         [ +  - ]:        700 :           int rc = elf_getshdrnum (elf, &shnum);
    4237         [ -  + ]:        700 :           if (rc < 0)
    4238   [ #  #  #  # ]:          0 :             throw elfutils_exception(rc, "getshdrnum");
    4239                 :            : 
    4240                 :        700 :           executable_p = false;
    4241         [ +  + ]:      13196 :           for (size_t sc = 0; sc < shnum; sc++)
    4242                 :            :             {
    4243         [ +  - ]:      12870 :               Elf_Scn *scn = elf_getscn (elf, sc);
    4244         [ -  + ]:      12870 :               if (scn == NULL)
    4245                 :          0 :                 continue;
    4246                 :            : 
    4247                 :      12870 :               GElf_Shdr shdr_mem;
    4248         [ +  - ]:      12870 :               GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
    4249         [ -  + ]:      12870 :               if (shdr == NULL)
    4250                 :          0 :                 continue;
    4251                 :            : 
    4252                 :            :               // allocated (loadable / vm-addr-assigned) section with available content?
    4253   [ +  +  +  + ]:      12870 :               if ((shdr->sh_type == SHT_PROGBITS) && (shdr->sh_flags & SHF_ALLOC))
    4254                 :            :                 {
    4255         [ -  + ]:        374 :                   if (verbose > 4)
    4256   [ #  #  #  #  :          0 :                     obatched(clog) << "executable due to SHF_ALLOC SHT_PROGBITS sc=" << sc << endl;
                   #  # ]
    4257                 :        374 :                   executable_p = true;
    4258                 :        374 :                   break; // no need to keep looking for others
    4259                 :            :                 }
    4260                 :            :             } // iterate over sections
    4261                 :            :         } // executable_p classification
    4262                 :            : 
    4263                 :            :       // now decide whether it's a debuginfo - namely, if it has any .debug* or .zdebug* sections
    4264                 :            :       // logic mostly stolen from fweimer@redhat.com's elfclassify drafts
    4265                 :        762 :       size_t shstrndx;
    4266         [ +  - ]:        762 :       int rc = elf_getshdrstrndx (elf, &shstrndx);
    4267         [ -  + ]:        762 :       if (rc < 0)
    4268   [ #  #  #  # ]:          0 :         throw elfutils_exception(rc, "getshdrstrndx");
    4269                 :            : 
    4270                 :            :       Elf_Scn *scn = NULL;
    4271                 :            :       bool symtab_p = false;
    4272                 :            :       bool bits_alloc_p = false;
    4273                 :      40858 :       while (true)
    4274                 :            :         {
    4275         [ +  - ]:      20810 :           scn = elf_nextscn (elf, scn);
    4276         [ +  + ]:      20781 :           if (scn == NULL)
    4277                 :            :             break;
    4278                 :      20431 :           GElf_Shdr shdr_storage;
    4279         [ +  - ]:      20431 :           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_storage);
    4280         [ -  + ]:      20429 :           if (shdr == NULL)
    4281                 :            :             break;
    4282         [ +  - ]:      20429 :           const char *section_name = elf_strptr (elf, shstrndx, shdr->sh_name);
    4283         [ -  + ]:      20460 :           if (section_name == NULL)
    4284                 :            :             break;
    4285         [ +  + ]:      20460 :           if (startswith (section_name, ".debug_line") ||
    4286         [ -  + ]:      20048 :               startswith (section_name, ".zdebug_line"))
    4287                 :            :             {
    4288                 :        412 :               debuginfo_p = true;
    4289         [ +  - ]:        412 :               if (scan_source_info)
    4290                 :        412 :                 dwarf_extract_source_paths (elf, debug_sourcefiles);
    4291                 :            :               break; // expecting only one .*debug_line, so no need to look for others
    4292                 :            :             }
    4293         [ +  + ]:      20048 :           else if (startswith (section_name, ".debug_") ||
    4294         [ +  # ]:      18780 :                    startswith (section_name, ".zdebug_"))
    4295                 :            :             {
    4296                 :       1250 :               debuginfo_p = true;
    4297                 :            :               // NB: don't break; need to parse .debug_line for sources
    4298                 :            :             }
    4299         [ +  + ]:      18798 :           else if (shdr->sh_type == SHT_SYMTAB)
    4300                 :            :             {
    4301                 :            :               symtab_p = true;
    4302                 :            :             }
    4303                 :      18774 :           else if (shdr->sh_type != SHT_NOBITS
    4304         [ +  + ]:      18774 :                    && shdr->sh_type != SHT_NOTE
    4305         [ +  + ]:       9186 :                    && (shdr->sh_flags & SHF_ALLOC) != 0)
    4306                 :            :             {
    4307                 :      20048 :               bits_alloc_p = true;
    4308                 :            :             }
    4309                 :      20048 :         }
    4310                 :            : 
    4311                 :            :       // For more expansive elf/split-debuginfo classification, we
    4312                 :            :       // want to identify as debuginfo "strip -s"-produced files
    4313                 :            :       // without .debug_info* (like libicudata), but we don't want to
    4314                 :            :       // identify "strip -g" executables (with .symtab left there).
    4315         [ -  + ]:        762 :       if (symtab_p && !bits_alloc_p)
    4316                 :          0 :         debuginfo_p = true;
    4317                 :            :     }
    4318         [ #  # ]:          0 :   catch (const reportable_exception& e)
    4319                 :            :     {
    4320         [ #  # ]:          0 :       e.report(clog);
    4321                 :          0 :     }
    4322                 :        762 :   elf_end (elf);
    4323                 :            : }
    4324                 :            : 
    4325                 :            : 
    4326                 :            : // Intern the given file name in two parts (dirname & basename) and
    4327                 :            : // return the resulting file's id.
    4328                 :            : static int64_t
    4329                 :      32725 : register_file_name(sqlite_ps& ps_upsert_fileparts,
    4330                 :            :                    sqlite_ps& ps_upsert_file,
    4331                 :            :                    sqlite_ps& ps_lookup_file,
    4332                 :            :                    const string& name)
    4333                 :            : {
    4334                 :      32725 :   std::size_t slash = name.rfind('/');
    4335         [ +  + ]:      32725 :   string dirname, filename;
    4336         [ +  + ]:      32725 :   if (slash == std::string::npos)
    4337                 :            :     {
    4338         [ +  - ]:         90 :       dirname = "";
    4339         [ +  - ]:         90 :       filename = name;
    4340                 :            :     }
    4341                 :            :   else
    4342                 :            :     {
    4343   [ +  -  -  + ]:      32635 :       dirname = name.substr(0, slash);
    4344   [ +  -  -  +  :      32635 :       filename = name.substr(slash+1);
                   -  - ]
    4345                 :            :     }
    4346                 :            :   // NB: see also handle_metadata()
    4347                 :            : 
    4348                 :            :   // intern the two substrings
    4349                 :      32726 :   ps_upsert_fileparts
    4350         [ +  - ]:      32726 :     .reset()
    4351         [ +  - ]:      32725 :     .bind(1, dirname)
    4352         [ +  - ]:      32721 :     .step_ok_done();
    4353                 :      32726 :   ps_upsert_fileparts
    4354         [ +  - ]:      32726 :     .reset()
    4355         [ +  - ]:      32726 :     .bind(1, filename)
    4356         [ +  - ]:      32726 :     .step_ok_done();
    4357                 :            : 
    4358                 :            :   // intern the tuple
    4359                 :      32726 :   ps_upsert_file
    4360         [ +  - ]:      32726 :     .reset()
    4361         [ +  - ]:      32726 :     .bind(1, dirname)
    4362         [ +  - ]:      32725 :     .bind(2, filename)
    4363         [ +  - ]:      32726 :     .step_ok_done();
    4364                 :            : 
    4365                 :            :   // look up the tuple's id
    4366                 :      32726 :   ps_lookup_file
    4367         [ +  - ]:      32726 :     .reset()
    4368         [ +  - ]:      32726 :     .bind(1, dirname)
    4369         [ +  - ]:      32726 :     .bind(2, filename);
    4370         [ +  - ]:      32726 :   int rc = ps_lookup_file.step();
    4371   [ -  +  -  -  :      32726 :   if (rc != SQLITE_ROW) throw sqlite_exception(rc, "step");
                   -  - ]
    4372                 :            :   
    4373         [ +  - ]:      32726 :   int64_t id = sqlite3_column_int64 (ps_lookup_file, 0);
    4374         [ +  - ]:      32725 :   ps_lookup_file.reset();
    4375         [ +  + ]:      32726 :   return id;
    4376         [ +  + ]:      63128 : }
    4377                 :            : 
    4378                 :            : 
    4379                 :            : 
    4380                 :            : static void
    4381                 :       1098 : scan_source_file (const string& rps, const stat_t& st,
    4382                 :            :                   sqlite_ps& ps_upsert_buildids,
    4383                 :            :                   sqlite_ps& ps_upsert_fileparts,
    4384                 :            :                   sqlite_ps& ps_upsert_file,
    4385                 :            :                   sqlite_ps& ps_lookup_file,
    4386                 :            :                   sqlite_ps& ps_upsert_de,
    4387                 :            :                   sqlite_ps& ps_upsert_s,
    4388                 :            :                   sqlite_ps& ps_query,
    4389                 :            :                   sqlite_ps& ps_scan_done,
    4390                 :            :                   unsigned& fts_cached,
    4391                 :            :                   unsigned& fts_executable,
    4392                 :            :                   unsigned& fts_debuginfo,
    4393                 :            :                   unsigned& fts_sourcefiles)
    4394                 :            : {
    4395                 :       1098 :   int64_t fileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
    4396                 :            : 
    4397                 :            :   /* See if we know of it already. */
    4398                 :       1098 :   int rc = ps_query
    4399                 :       1098 :     .reset()
    4400                 :       1098 :     .bind(1, fileid)
    4401                 :       1098 :     .bind(2, st.st_mtime)
    4402                 :       1098 :     .step();
    4403                 :       1098 :   ps_query.reset();
    4404         [ +  + ]:       1098 :   if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
    4405                 :            :     // no need to recheck a file/version we already know
    4406                 :            :     // specifically, no need to elf-begin a file we already determined is non-elf
    4407                 :            :     // (so is stored with buildid=NULL)
    4408                 :            :     {
    4409                 :        438 :       fts_cached++;
    4410                 :        438 :       return;
    4411                 :            :     }
    4412                 :            : 
    4413                 :        660 :   bool executable_p = false, debuginfo_p = false; // E and/or D
    4414         [ +  - ]:        660 :   string buildid;
    4415         [ +  - ]:        660 :   set<string> sourcefiles;
    4416                 :            : 
    4417         [ +  - ]:        660 :   int fd = open (rps.c_str(), O_RDONLY);
    4418                 :        660 :   try
    4419                 :            :     {
    4420         [ +  - ]:        660 :       if (fd >= 0)
    4421         [ +  - ]:        660 :         elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
    4422                 :            :       else
    4423   [ #  #  #  #  :          0 :         throw libc_exception(errno, string("open ") + rps);
             #  #  #  # ]
    4424   [ +  -  +  -  :       1320 :       add_metric ("scanned_bytes_total","source","file",
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    4425         [ +  - ]:        660 :                   st.st_size);
    4426   [ +  -  +  -  :       1320 :       inc_metric ("scanned_files_total","source","file");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4427                 :            :     }
    4428                 :            :   // NB: we catch exceptions here too, so that we can
    4429                 :            :   // cache the corrupt-elf case (!executable_p &&
    4430                 :            :   // !debuginfo_p) just below, just as if we had an
    4431                 :            :   // EPERM error from open(2).
    4432         [ -  - ]:          0 :   catch (const reportable_exception& e)
    4433                 :            :     {
    4434         [ -  - ]:          0 :       e.report(clog);
    4435                 :          0 :     }
    4436                 :            : 
    4437         [ +  - ]:        660 :   if (fd >= 0)
    4438         [ +  - ]:        660 :     close (fd);
    4439                 :            : 
    4440         [ +  + ]:        660 :   if (buildid == "")
    4441                 :            :     {
    4442                 :            :       // no point storing an elf file without buildid
    4443                 :        564 :       executable_p = false;
    4444                 :        564 :       debuginfo_p = false;
    4445                 :            :     }
    4446                 :            :   else
    4447                 :            :     {
    4448                 :            :       // register this build-id in the interning table
    4449                 :         96 :       ps_upsert_buildids
    4450         [ +  - ]:         96 :         .reset()
    4451         [ +  - ]:         96 :         .bind(1, buildid)
    4452         [ +  - ]:         96 :         .step_ok_done();
    4453                 :            :     }
    4454                 :            : 
    4455         [ +  + ]:        660 :   if (executable_p)
    4456                 :         72 :     fts_executable ++;
    4457         [ +  + ]:        660 :   if (debuginfo_p)
    4458                 :         72 :     fts_debuginfo ++;
    4459   [ +  +  +  + ]:        660 :   if (executable_p || debuginfo_p)
    4460                 :            :     {
    4461                 :         96 :       ps_upsert_de
    4462         [ +  - ]:         96 :         .reset()
    4463         [ +  - ]:         96 :         .bind(1, buildid)
    4464   [ +  +  +  - ]:        120 :         .bind(2, debuginfo_p ? 1 : 0)
    4465   [ +  +  +  - ]:        120 :         .bind(3, executable_p ? 1 : 0)
    4466         [ +  - ]:         96 :         .bind(4, fileid)
    4467         [ +  - ]:         96 :         .bind(5, st.st_mtime)
    4468         [ +  - ]:         96 :         .step_ok_done();
    4469                 :            :     }
    4470         [ +  + ]:        660 :   if (executable_p)
    4471   [ +  -  +  -  :        144 :     inc_metric("found_executable_total","source","files");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4472         [ +  + ]:        660 :   if (debuginfo_p)
    4473   [ +  -  +  -  :        144 :     inc_metric("found_debuginfo_total","source","files");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4474                 :            : 
    4475   [ +  +  +  - ]:        732 :   if (sourcefiles.size() && buildid != "")
    4476                 :            :     {
    4477                 :         72 :       fts_sourcefiles += sourcefiles.size();
    4478                 :            : 
    4479         [ +  + ]:      14746 :       for (auto&& dwarfsrc : sourcefiles)
    4480                 :            :         {
    4481         [ +  - ]:      14674 :           char *srp = realpath(dwarfsrc.c_str(), NULL);
    4482         [ -  + ]:      14674 :           if (srp == NULL) // also if DWZ unresolved dwarfsrc=""
    4483                 :          0 :             continue; // unresolvable files are not a serious problem
    4484                 :            :           // throw libc_exception(errno, "fts/file realpath " + srcpath);
    4485         [ +  - ]:      14674 :           string srps = string(srp);
    4486                 :      14674 :           free (srp);
    4487                 :            : 
    4488                 :      14674 :           struct stat sfs;
    4489                 :      14674 :           rc = stat(srps.c_str(), &sfs);
    4490         [ -  + ]:      14674 :           if (rc != 0)
    4491         [ #  # ]:          0 :             continue;
    4492                 :            : 
    4493         [ +  - ]:      14674 :           if (verbose > 2)
    4494   [ +  -  +  -  :      44022 :             obatched(clog) << "recorded buildid=" << buildid << " file=" << srps
                   -  - ]
    4495   [ +  -  +  -  :      14674 :                            << " mtime=" << sfs.st_mtime
             +  -  +  - ]
    4496   [ +  -  +  -  :      14674 :                            << " as source " << dwarfsrc << endl;
                   +  - ]
    4497                 :            : 
    4498                 :            :           // PR25548: store canonicalized dwarfsrc path
    4499         [ +  - ]:      14674 :           string dwarfsrc_canon = canon_pathname (dwarfsrc);
    4500         [ +  + ]:      14674 :           if (dwarfsrc_canon != dwarfsrc)
    4501                 :            :             {
    4502         [ +  + ]:       2636 :               if (verbose > 3)
    4503   [ +  -  +  -  :       4168 :                 obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
          +  -  +  -  +  
                      - ]
    4504                 :            :             }
    4505                 :            : 
    4506         [ +  - ]:      14674 :           int64_t fileid1 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, dwarfsrc_canon);
    4507         [ +  - ]:      14674 :           int64_t fileid2 = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, srps);
    4508                 :            : 
    4509                 :      14674 :           ps_upsert_s
    4510         [ +  - ]:      14674 :             .reset()
    4511         [ +  - ]:      14674 :             .bind(1, buildid)
    4512         [ +  - ]:      14674 :             .bind(2, fileid1)
    4513         [ +  - ]:      14673 :             .bind(3, fileid2)
    4514         [ +  - ]:      14673 :             .bind(4, sfs.st_mtime)
    4515         [ +  - ]:      14674 :             .step_ok_done();
    4516                 :            : 
    4517   [ +  -  +  -  :      29348 :           inc_metric("found_sourcerefs_total","source","files");
          +  -  +  -  -  
          +  -  +  +  -  
          -  -  -  -  -  
                      - ]
    4518         [ +  - ]:      29348 :         }
    4519                 :            :     }
    4520                 :            : 
    4521                 :        660 :   ps_scan_done
    4522         [ +  - ]:        660 :     .reset()
    4523         [ +  - ]:        660 :     .bind(1, fileid)
    4524         [ +  - ]:        660 :     .bind(2, st.st_mtime)
    4525         [ +  - ]:        660 :     .bind(3, st.st_size)
    4526         [ +  - ]:        660 :     .step_ok_done();
    4527                 :            : 
    4528         [ +  - ]:        660 :   if (verbose > 2)
    4529   [ +  -  +  - ]:       1980 :     obatched(clog) << "recorded buildid=" << buildid << " file=" << rps
    4530   [ +  -  +  -  :        660 :                    << " mtime=" << st.st_mtime << " atype="
             +  -  +  - ]
    4531                 :            :                    << (executable_p ? "E" : "")
    4532   [ +  -  +  +  :       1836 :                    << (debuginfo_p ? "D" : "") << endl;
          +  -  +  +  +  
                -  +  - ]
    4533         [ +  + ]:        756 : }
    4534                 :            : 
    4535                 :            : 
    4536                 :            : 
    4537                 :            : 
    4538                 :            : 
    4539                 :            : // Analyze given archive file of given age; record buildids / exec/debuginfo-ness of its
    4540                 :            : // constituent files with given upsert statements.
    4541                 :            : static void
    4542                 :        396 : archive_classify (const string& rps, string& archive_extension, int64_t archiveid,
    4543                 :            :                   sqlite_ps& ps_upsert_buildids, sqlite_ps& ps_upsert_fileparts, sqlite_ps& ps_upsert_file,
    4544                 :            :                   sqlite_ps& ps_lookup_file,
    4545                 :            :                   sqlite_ps& ps_upsert_de, sqlite_ps& ps_upsert_sref, sqlite_ps& ps_upsert_sdef,
    4546                 :            :                   sqlite_ps& ps_upsert_seekable,
    4547                 :            :                   time_t mtime,
    4548                 :            :                   unsigned& fts_executable, unsigned& fts_debuginfo, unsigned& fts_sref, unsigned& fts_sdef,
    4549                 :            :                   bool& fts_sref_complete_p)
    4550                 :            : {
    4551                 :        396 :   string archive_decoder = "/dev/null";
    4552         [ +  + ]:       1024 :   for (auto&& arch : scan_archives)
    4553         [ +  + ]:        628 :     if (string_endswith(rps, arch.first))
    4554                 :            :       {
    4555         [ +  - ]:        396 :         archive_extension = arch.first;
    4556         [ +  - ]:       1024 :         archive_decoder = arch.second;
    4557                 :            :       }
    4558                 :            : 
    4559                 :        396 :   FILE* fp;
    4560                 :        396 :   defer_dtor<FILE*,int>::dtor_fn dfn;
    4561         [ +  + ]:        396 :   if (archive_decoder != "cat")
    4562                 :            :     {
    4563   [ +  -  +  -  :         80 :       string popen_cmd = archive_decoder + " " + shell_escape(rps);
          +  -  -  +  -  
                -  -  - ]
    4564         [ +  - ]:         40 :       fp = popen (popen_cmd.c_str(), "r"); // "e" O_CLOEXEC?
    4565                 :         40 :       dfn = pclose;
    4566         [ -  + ]:         40 :       if (fp == NULL)
    4567   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("popen ") + popen_cmd);
             #  #  #  # ]
    4568                 :         40 :     }
    4569                 :            :   else
    4570                 :            :     {
    4571         [ +  - ]:        356 :       fp = fopen (rps.c_str(), "r");
    4572                 :        356 :       dfn = fclose;
    4573         [ -  + ]:        356 :       if (fp == NULL)
    4574   [ #  #  #  #  :          0 :         throw libc_exception (errno, string("fopen ") + rps);
             #  #  #  # ]
    4575                 :            :     }
    4576                 :        396 :   defer_dtor<FILE*,int> fp_closer (fp, dfn);
    4577                 :            : 
    4578                 :        396 :   struct archive *a;
    4579         [ +  - ]:        396 :   a = archive_read_new();
    4580         [ -  + ]:        396 :   if (a == NULL)
    4581   [ #  #  #  # ]:          0 :     throw archive_exception("cannot create archive reader");
    4582                 :        396 :   defer_dtor<struct archive*,int> archive_closer (a, archive_read_free);
    4583                 :            : 
    4584         [ +  - ]:        396 :   int rc = archive_read_support_format_all(a);
    4585         [ -  + ]:        396 :   if (rc != ARCHIVE_OK)
    4586   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all formats");
    4587         [ +  - ]:        396 :   rc = archive_read_support_filter_all(a);
    4588         [ -  + ]:        396 :   if (rc != ARCHIVE_OK)
    4589   [ #  #  #  # ]:          0 :     throw archive_exception(a, "cannot select all filters");
    4590                 :            : 
    4591         [ +  - ]:        396 :   rc = archive_read_open_FILE (a, fp);
    4592         [ -  + ]:        396 :   if (rc != ARCHIVE_OK)
    4593                 :            :     {
    4594   [ #  #  #  #  :          0 :       obatched(clog) << "cannot open archive from pipe " << rps << endl;
                   #  # ]
    4595   [ #  #  #  # ]:          0 :       throw archive_exception(a, "cannot open archive from pipe");
    4596                 :            :     }
    4597                 :            : 
    4598         [ +  + ]:        396 :   if (verbose > 3)
    4599   [ +  -  +  -  :        712 :     obatched(clog) << "libarchive scanning " << rps << " id " << archiveid << endl;
          +  -  +  -  +  
                      - ]
    4600                 :            : 
    4601         [ +  - ]:        396 :   bool seekable = is_seekable_archive (rps, a);
    4602   [ +  -  +  + ]:        396 :   if (verbose> 2 && seekable)
    4603   [ +  -  +  -  :         64 :     obatched(clog) << rps << " is seekable" << endl;
                   +  - ]
    4604                 :            : 
    4605                 :            :   bool any_exceptions = false;
    4606                 :       3774 :   while(1) // parse archive entries
    4607                 :            :     {
    4608         [ +  - ]:       3774 :     if (interrupted)
    4609                 :            :       break;
    4610                 :            : 
    4611                 :       3774 :     try
    4612                 :            :         {
    4613                 :       3774 :           struct archive_entry *e;
    4614         [ +  - ]:       3774 :           rc = archive_read_next_header (a, &e);
    4615         [ +  + ]:       3774 :           if (rc != ARCHIVE_OK)
    4616                 :            :             break;
    4617                 :            : 
    4618   [ +  -  +  + ]:       3378 :           if (! S_ISREG(archive_entry_mode (e))) // skip non-files completely
    4619                 :       2338 :             continue;
    4620                 :            : 
    4621         [ +  - ]:       1040 :           string fn = canonicalized_archive_entry_pathname (e);
    4622                 :            : 
    4623         [ +  + ]:       1040 :           if (verbose > 3)
    4624   [ +  -  +  -  :       1756 :             obatched(clog) << "libarchive checking " << fn << endl;
             +  -  -  - ]
    4625                 :            : 
    4626         [ +  - ]:       1040 :           int64_t seekable_size = archive_entry_size (e);
    4627         [ +  - ]:       1040 :           int64_t seekable_offset = archive_filter_bytes (a, 0);
    4628         [ +  - ]:       1040 :           time_t seekable_mtime = archive_entry_mtime (e);
    4629                 :            : 
    4630                 :            :           // extract this file to a temporary file
    4631                 :       1040 :           char* tmppath = NULL;
    4632                 :       1040 :           rc = asprintf (&tmppath, "%s/debuginfod-classify.XXXXXX", tmpdir.c_str());
    4633         [ -  + ]:       1040 :           if (rc < 0)
    4634   [ #  #  #  # ]:          0 :             throw libc_exception (ENOMEM, "cannot allocate tmppath");
    4635                 :       1040 :           defer_dtor<void*,void> tmmpath_freer (tmppath, free);
    4636         [ +  - ]:       1040 :           int fd = mkstemp (tmppath);
    4637         [ -  + ]:       1040 :           if (fd < 0)
    4638   [ #  #  #  # ]:          0 :             throw libc_exception (errno, "cannot create temporary file");
    4639                 :       1040 :           unlink (tmppath); // unlink now so OS will release the file as soon as we close the fd
    4640                 :       1040 :           defer_dtor<int,int> minifd_closer (fd, close);
    4641                 :            : 
    4642         [ +  - ]:       1040 :           rc = archive_read_data_into_fd (a, fd);
    4643         [ -  + ]:       1040 :           if (rc != ARCHIVE_OK) {
    4644         [ #  # ]:          0 :             close (fd);
    4645   [ #  #  #  # ]:          0 :             throw archive_exception(a, "cannot extract file");
    4646                 :            :           }
    4647                 :            : 
    4648                 :            :           // finally ... time to run elf_classify on this bad boy and update the database
    4649                 :       1040 :           bool executable_p = false, debuginfo_p = false;
    4650         [ +  - ]:       1040 :           string buildid;
    4651         [ +  - ]:       1040 :           set<string> sourcefiles;
    4652         [ +  - ]:       1040 :           elf_classify (fd, executable_p, debuginfo_p, buildid, sourcefiles);
    4653                 :            :           // NB: might throw
    4654                 :            : 
    4655         [ +  + ]:       1040 :           if (buildid != "") // intern buildid
    4656                 :            :             {
    4657                 :        666 :               ps_upsert_buildids
    4658         [ +  - ]:        666 :                 .reset()
    4659         [ +  - ]:        666 :                 .bind(1, buildid)
    4660         [ +  - ]:        666 :                 .step_ok_done();
    4661                 :            :             }
    4662                 :            : 
    4663         [ +  - ]:       1040 :           int64_t fileid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, fn);
    4664                 :            : 
    4665         [ +  + ]:       1040 :           if (sourcefiles.size() > 0) // sref records needed
    4666                 :            :             {
    4667                 :            :               // NB: we intern each source file once.  Once raw, as it
    4668                 :            :               // appears in the DWARF file list coming back from
    4669                 :            :               // elf_classify() - because it'll end up in the
    4670                 :            :               // _norm.artifactsrc column.  We don't also put another
    4671                 :            :               // version with a '.' at the front, even though that's
    4672                 :            :               // how rpm/cpio packs names, because we hide that from
    4673                 :            :               // the database for storage efficiency.
    4674                 :            : 
    4675         [ +  + ]:        802 :               for (auto&& s : sourcefiles)
    4676                 :            :                 {
    4677         [ +  + ]:        498 :                   if (s == "")
    4678                 :            :                     {
    4679                 :         20 :                       fts_sref_complete_p = false;
    4680                 :         20 :                       continue;
    4681                 :            :                     }
    4682                 :            : 
    4683                 :            :                   // PR25548: store canonicalized source path
    4684                 :        478 :                   const string& dwarfsrc = s;
    4685         [ +  - ]:        478 :                   string dwarfsrc_canon = canon_pathname (dwarfsrc);
    4686         [ +  + ]:        478 :                   if (dwarfsrc_canon != dwarfsrc)
    4687                 :            :                     {
    4688         [ +  - ]:         28 :                       if (verbose > 3)
    4689   [ +  -  +  -  :         56 :                         obatched(clog) << "canonicalized src=" << dwarfsrc << " alias=" << dwarfsrc_canon << endl;
          +  -  +  -  +  
                -  -  - ]
    4690                 :            :                     }
    4691                 :            : 
    4692         [ +  - ]:        478 :                   int64_t srcfileid = register_file_name(ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
    4693                 :            :                                                          dwarfsrc_canon);
    4694                 :            :                 
    4695                 :        478 :                   ps_upsert_sref
    4696         [ +  - ]:        478 :                     .reset()
    4697         [ +  - ]:        478 :                     .bind(1, buildid)
    4698         [ +  - ]:        478 :                     .bind(2, srcfileid)
    4699         [ +  - ]:        478 :                     .step_ok_done();
    4700                 :            : 
    4701         [ +  - ]:        478 :                   fts_sref ++;
    4702                 :        478 :                 }
    4703                 :            :             }
    4704                 :            : 
    4705         [ +  + ]:       1040 :           if (executable_p)
    4706                 :        302 :             fts_executable ++;
    4707         [ +  + ]:       1040 :           if (debuginfo_p)
    4708                 :        366 :             fts_debuginfo ++;
    4709                 :            : 
    4710   [ +  +  +  + ]:       1040 :           if (executable_p || debuginfo_p)
    4711                 :            :             {
    4712                 :        666 :               ps_upsert_de
    4713         [ +  - ]:        666 :                 .reset()
    4714         [ +  - ]:        666 :                 .bind(1, buildid)
    4715   [ +  +  +  - ]:        966 :                 .bind(2, debuginfo_p ? 1 : 0)
    4716   [ +  +  +  - ]:       1030 :                 .bind(3, executable_p ? 1 : 0)
    4717         [ +  - ]:        666 :                 .bind(4, archiveid)
    4718         [ +  - ]:        666 :                 .bind(5, mtime)
    4719         [ +  - ]:        666 :                 .bind(6, fileid)
    4720         [ +  - ]:        666 :                 .step_ok_done();
    4721         [ +  + ]:        666 :               if (seekable)
    4722                 :        336 :                 ps_upsert_seekable
    4723         [ +  - ]:        336 :                   .reset()
    4724         [ +  - ]:        336 :                   .bind(1, archiveid)
    4725         [ +  - ]:        336 :                   .bind(2, fileid)
    4726         [ +  - ]:        336 :                   .bind(3, seekable_size)
    4727         [ +  - ]:        336 :                   .bind(4, seekable_offset)
    4728         [ +  - ]:        336 :                   .bind(5, seekable_mtime)
    4729         [ +  - ]:        336 :                   .step_ok_done();
    4730                 :            :             }
    4731                 :            :           else // potential source - sdef record
    4732                 :            :             {
    4733                 :        374 :               fts_sdef ++;
    4734                 :        374 :               ps_upsert_sdef
    4735         [ +  - ]:        374 :                 .reset()
    4736         [ +  - ]:        374 :                 .bind(1, archiveid)
    4737         [ +  - ]:        374 :                 .bind(2, mtime)
    4738         [ +  - ]:        374 :                 .bind(3, fileid)
    4739         [ +  - ]:        374 :                 .step_ok_done();
    4740                 :            :             }
    4741                 :            : 
    4742   [ +  -  +  +  :       1040 :           if ((verbose > 2) && (executable_p || debuginfo_p))
                   +  + ]
    4743                 :            :             {
    4744         [ +  - ]:        666 :               obatched ob(clog);
    4745   [ +  -  +  - ]:        666 :               auto& o = ob << "recorded buildid=" << buildid << " rpm=" << rps << " file=" << fn
    4746   [ +  -  +  -  :        666 :                            << " mtime=" << mtime << " atype="
          +  -  +  -  +  
                -  +  - ]
    4747                 :            :                            << (executable_p ? "E" : "")
    4748                 :            :                            << (debuginfo_p ? "D" : "")
    4749   [ +  -  +  +  :       1330 :                            << " sourcefiles=" << sourcefiles.size();
          +  -  +  +  +  
             -  +  -  +  
                      - ]
    4750         [ +  + ]:        666 :               if (seekable)
    4751   [ +  -  +  - ]:        336 :                 o << " seekable size=" << seekable_size
    4752   [ +  -  +  - ]:        336 :                   << " offset=" << seekable_offset
    4753   [ +  -  +  - ]:        336 :                   << " mtime=" << seekable_mtime;
    4754         [ +  - ]:        666 :               o << endl;
    4755                 :        666 :             }
    4756                 :            : 
    4757   [ +  +  +  + ]:       2584 :         }
    4758         [ -  - ]:          0 :       catch (const reportable_exception& e)
    4759                 :            :         {
    4760         [ -  - ]:          0 :           e.report(clog);
    4761                 :          0 :           any_exceptions = true;
    4762                 :            :           // NB: but we allow the libarchive iteration to continue, in
    4763                 :            :           // case we can still gather some useful information.  That
    4764                 :            :           // would allow some webapi queries to work, until later when
    4765                 :            :           // this archive is rescanned.  (Its vitals won't go into the
    4766                 :            :           // _file_mtime_scanned table until after a successful scan.)
    4767                 :          0 :         }
    4768                 :            :     }
    4769                 :            : 
    4770         [ -  + ]:        396 :   if (any_exceptions)
    4771   [ #  #  #  # ]:          0 :     throw reportable_exception("exceptions encountered during archive scan");
    4772         [ +  + ]:        420 : }
    4773                 :            : 
    4774                 :            : 
    4775                 :            : 
    4776                 :            : // scan for archive files such as .rpm
    4777                 :            : static void
    4778                 :        762 : scan_archive_file (const string& rps, const stat_t& st,
    4779                 :            :                    sqlite_ps& ps_upsert_buildids,
    4780                 :            :                    sqlite_ps& ps_upsert_fileparts,
    4781                 :            :                    sqlite_ps& ps_upsert_file,
    4782                 :            :                    sqlite_ps& ps_lookup_file,
    4783                 :            :                    sqlite_ps& ps_upsert_de,
    4784                 :            :                    sqlite_ps& ps_upsert_sref,
    4785                 :            :                    sqlite_ps& ps_upsert_sdef,
    4786                 :            :                    sqlite_ps& ps_upsert_seekable,
    4787                 :            :                    sqlite_ps& ps_query,
    4788                 :            :                    sqlite_ps& ps_scan_done,
    4789                 :            :                    unsigned& fts_cached,
    4790                 :            :                    unsigned& fts_executable,
    4791                 :            :                    unsigned& fts_debuginfo,
    4792                 :            :                    unsigned& fts_sref,
    4793                 :            :                    unsigned& fts_sdef)
    4794                 :            : {
    4795                 :            :   // intern the archive file name
    4796                 :        762 :   int64_t archiveid = register_file_name (ps_upsert_fileparts, ps_upsert_file, ps_lookup_file, rps);
    4797                 :            : 
    4798                 :            :   /* See if we know of it already. */
    4799                 :        762 :   int rc = ps_query
    4800                 :        762 :     .reset()
    4801                 :        762 :     .bind(1, archiveid)
    4802                 :        762 :     .bind(2, st.st_mtime)
    4803                 :        762 :     .step();
    4804                 :        762 :   ps_query.reset();
    4805         [ +  + ]:        762 :   if (rc == SQLITE_ROW) // i.e., a result, as opposed to DONE (no results)
    4806                 :            :     // no need to recheck a file/version we already know
    4807                 :            :     // specifically, no need to parse this archive again, since we already have
    4808                 :            :     // it as a D or E or S record,
    4809                 :            :     // (so is stored with buildid=NULL)
    4810                 :            :     {
    4811                 :        366 :       fts_cached ++;
    4812                 :        366 :       return;
    4813                 :            :     }
    4814                 :            : 
    4815                 :            :   // extract the archive contents
    4816                 :        396 :   unsigned my_fts_executable = 0, my_fts_debuginfo = 0, my_fts_sref = 0, my_fts_sdef = 0;
    4817                 :        396 :   bool my_fts_sref_complete_p = true;
    4818                 :        396 :   bool any_exceptions = false;
    4819                 :        396 :   try
    4820                 :            :     {
    4821         [ +  - ]:        396 :       string archive_extension;
    4822                 :        396 :       archive_classify (rps, archive_extension, archiveid,
    4823                 :            :                         ps_upsert_buildids, ps_upsert_fileparts, ps_upsert_file, ps_lookup_file,
    4824                 :            :                         ps_upsert_de, ps_upsert_sref, ps_upsert_sdef, ps_upsert_seekable, // dalt
    4825         [ +  - ]:        396 :                         st.st_mtime,
    4826                 :            :                         my_fts_executable, my_fts_debuginfo, my_fts_sref, my_fts_sdef,
    4827                 :            :                         my_fts_sref_complete_p);
    4828   [ +  -  +  -  :        792 :       add_metric ("scanned_bytes_total","source",archive_extension + " archive",
          +  -  -  +  +  
             +  -  -  -  
                      - ]
    4829         [ +  - ]:        396 :                   st.st_size);
    4830   [ +  -  +  -  :        792 :       inc_metric ("scanned_files_total","source",archive_extension + " archive");
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    4831   [ +  -  +  -  :        792 :       add_metric("found_debuginfo_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    4832                 :            :                  my_fts_debuginfo);
    4833   [ +  -  +  -  :        792 :       add_metric("found_executable_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  -  
                   -  - ]
    4834                 :            :                  my_fts_executable);
    4835   [ +  -  +  -  :        808 :       add_metric("found_sourcerefs_total","source",archive_extension + " archive",
          +  -  +  -  -  
          +  +  +  -  +  
          -  -  -  -  -  
                      - ]
    4836                 :            :                  my_fts_sref);
    4837                 :        396 :     }
    4838         [ -  - ]:          0 :   catch (const reportable_exception& e)
    4839                 :            :     {
    4840         [ -  - ]:          0 :       e.report(clog);
    4841                 :          0 :       any_exceptions = true;
    4842                 :          0 :     }
    4843                 :            : 
    4844         [ +  - ]:        396 :   if (verbose > 2)
    4845         [ +  - ]:       1188 :     obatched(clog) << "scanned archive=" << rps
    4846   [ +  -  +  - ]:        396 :                    << " mtime=" << st.st_mtime
    4847         [ +  - ]:        396 :                    << " executables=" << my_fts_executable
    4848   [ +  -  +  - ]:        396 :                    << " debuginfos=" << my_fts_debuginfo
    4849   [ +  -  +  - ]:        396 :                    << " srefs=" << my_fts_sref
    4850   [ +  -  +  - ]:        396 :                    << " sdefs=" << my_fts_sdef
    4851   [ +  -  +  -  :        396 :                    << " exceptions=" << any_exceptions
             +  -  +  - ]
    4852                 :        396 :                    << endl;
    4853                 :            : 
    4854                 :        396 :   fts_executable += my_fts_executable;
    4855                 :        396 :   fts_debuginfo += my_fts_debuginfo;
    4856                 :        396 :   fts_sref += my_fts_sref;
    4857                 :        396 :   fts_sdef += my_fts_sdef;
    4858                 :            : 
    4859         [ -  + ]:        396 :   if (any_exceptions)
    4860   [ #  #  #  # ]:          0 :     throw reportable_exception("exceptions encountered during archive scan");
    4861                 :            : 
    4862         [ +  + ]:        396 :   if (my_fts_sref_complete_p) // leave incomplete?
    4863                 :        394 :     ps_scan_done
    4864                 :        394 :       .reset()
    4865                 :        394 :       .bind(1, archiveid)
    4866                 :        394 :       .bind(2, st.st_mtime)
    4867                 :        394 :       .bind(3, st.st_size)
    4868                 :        394 :       .step_ok_done();
    4869                 :            : }
    4870                 :            : 
    4871                 :            : 
    4872                 :            : 
    4873                 :            : ////////////////////////////////////////////////////////////////////////
    4874                 :            : 
    4875                 :            : 
    4876                 :            : 
    4877                 :            : // The thread that consumes file names off of the scanq.  We hold
    4878                 :            : // the persistent sqlite_ps's at this level and delegate file/archive
    4879                 :            : // scanning to other functions.
    4880                 :            : static void
    4881                 :        288 : scan ()
    4882                 :            : {
    4883                 :            :   // all the prepared statements fit to use, the _f_ set:
    4884   [ +  -  +  -  :        576 :   sqlite_ps ps_f_upsert_buildids (db, "file-buildids-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
             +  -  -  - ]
    4885   [ +  -  +  -  :        576 :   sqlite_ps ps_f_upsert_fileparts (db, "file-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    4886         [ +  - ]:        288 :   sqlite_ps ps_f_upsert_file (db, "file-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
    4887                 :            :                               "(select id from " BUILDIDS "_fileparts where name = ?),\n"
    4888   [ +  -  +  -  :        576 :                               "(select id from " BUILDIDS "_fileparts where name = ?));");
          +  -  +  -  -  
                      - ]
    4889         [ +  - ]:        288 :   sqlite_ps ps_f_lookup_file (db, "file-file-lookup",
    4890                 :            :                               "select f.id\n"
    4891                 :            :                               " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
    4892   [ +  -  +  -  :        576 :                               " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
          +  -  +  -  -  
                      - ]
    4893         [ +  - ]:        288 :   sqlite_ps ps_f_upsert_de (db, "file-de-upsert",
    4894                 :            :                           "insert or ignore into " BUILDIDS "_f_de "
    4895                 :            :                           "(buildid, debuginfo_p, executable_p, file, mtime) "
    4896                 :            :                           "values ((select id from " BUILDIDS "_buildids where hex = ?),"
    4897   [ +  -  +  -  :        576 :                             "        ?,?,?,?);");
          +  -  +  -  -  
                      - ]
    4898         [ +  - ]:        288 :   sqlite_ps ps_f_upsert_s (db, "file-s-upsert",
    4899                 :            :                          "insert or ignore into " BUILDIDS "_f_s "
    4900                 :            :                          "(buildid, artifactsrc, file, mtime) "
    4901                 :            :                          "values ((select id from " BUILDIDS "_buildids where hex = ?),"
    4902   [ +  -  +  -  :        576 :                          "      ?,?,?);");
          +  -  +  -  -  
                      - ]
    4903         [ +  - ]:        288 :   sqlite_ps ps_f_query (db, "file-negativehit-find",
    4904                 :            :                         "select 1 from " BUILDIDS "_file_mtime_scanned where sourcetype = 'F' "
    4905   [ +  -  +  -  :        576 :                         "and file = ? and mtime = ?;");
          +  -  +  -  -  
                      - ]
    4906         [ +  - ]:        288 :   sqlite_ps ps_f_scan_done (db, "file-scanned",
    4907                 :            :                           "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
    4908   [ +  -  +  -  :        576 :                           "values ('F', ?,?,?);");
          +  -  +  -  -  
                      - ]
    4909                 :            : 
    4910                 :            :   // and now for the _r_ set
    4911   [ +  -  +  -  :        576 :   sqlite_ps ps_r_upsert_buildids (db, "rpm-buildid-intern", "insert or ignore into " BUILDIDS "_buildids VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    4912   [ +  -  +  -  :        576 :   sqlite_ps ps_r_upsert_fileparts (db, "rpm-fileparts-intern", "insert or ignore into " BUILDIDS "_fileparts VALUES (NULL, ?);");
          +  -  +  -  -  
                      - ]
    4913         [ +  - ]:        288 :   sqlite_ps ps_r_upsert_file (db, "rpm-file-intern", "insert or ignore into " BUILDIDS "_files VALUES (NULL, \n"
    4914                 :            :                               "(select id from " BUILDIDS "_fileparts where name = ?),\n"
    4915   [ +  -  +  -  :        576 :                               "(select id from " BUILDIDS "_fileparts where name = ?));");
          +  -  +  -  -  
                      - ]
    4916         [ +  - ]:        288 :   sqlite_ps ps_r_lookup_file (db, "rpm-file-lookup",
    4917                 :            :                               "select f.id\n"
    4918                 :            :                               " from " BUILDIDS "_files f, " BUILDIDS "_fileparts p1, " BUILDIDS "_fileparts p2 \n"
    4919   [ +  -  +  -  :        576 :                               " where f.dirname = p1.id and f.basename = p2.id and p1.name = ? and p2.name = ?;\n");
          +  -  +  -  -  
                      - ]
    4920         [ +  - ]:        288 :   sqlite_ps ps_r_upsert_de (db, "rpm-de-insert",
    4921                 :            :                           "insert or ignore into " BUILDIDS "_r_de (buildid, debuginfo_p, executable_p, file, mtime, content) values ("
    4922   [ +  -  +  -  :        576 :                           "(select id from " BUILDIDS "_buildids where hex = ?), ?, ?, ?, ?, ?);");
          +  -  +  -  -  
                      - ]
    4923         [ +  - ]:        288 :   sqlite_ps ps_r_upsert_sref (db, "rpm-sref-insert",
    4924                 :            :                             "insert or ignore into " BUILDIDS "_r_sref (buildid, artifactsrc) values ("
    4925                 :            :                             "(select id from " BUILDIDS "_buildids where hex = ?), "
    4926   [ +  -  +  -  :        576 :                             "?);");
          +  -  +  -  -  
                      - ]
    4927         [ +  - ]:        288 :   sqlite_ps ps_r_upsert_sdef (db, "rpm-sdef-insert",
    4928                 :            :                             "insert or ignore into " BUILDIDS "_r_sdef (file, mtime, content) values ("
    4929   [ +  -  +  -  :        576 :                             "?, ?, ?);");
          +  -  +  -  -  
                      - ]
    4930         [ +  - ]:        288 :   sqlite_ps ps_r_upsert_seekable (db, "rpm-seekable-insert",
    4931                 :            :                                   "insert or ignore into " BUILDIDS "_r_seekable (file, content, type, size, offset, mtime) "
    4932   [ +  -  +  -  :        576 :                                   "values (?, ?, 'xz', ?, ?, ?);");
          +  -  +  -  -  
                      - ]
    4933         [ +  - ]:        288 :   sqlite_ps ps_r_query (db, "rpm-negativehit-query",
    4934                 :            :                       "select 1 from " BUILDIDS "_file_mtime_scanned where "
    4935   [ +  -  +  -  :        576 :                       "sourcetype = 'R' and file = ? and mtime = ?;");
          +  -  +  -  -  
                      - ]
    4936         [ +  - ]:        288 :   sqlite_ps ps_r_scan_done (db, "rpm-scanned",
    4937                 :            :                           "insert or ignore into " BUILDIDS "_file_mtime_scanned (sourcetype, file, mtime, size)"
    4938   [ +  -  +  -  :        576 :                           "values ('R', ?, ?, ?);");
          +  -  +  -  -  
                      - ]
    4939                 :            :   
    4940                 :            : 
    4941                 :        288 :   unsigned fts_cached = 0, fts_executable = 0, fts_debuginfo = 0, fts_sourcefiles = 0;
    4942                 :        288 :   unsigned fts_sref = 0, fts_sdef = 0;
    4943                 :            : 
    4944   [ +  -  +  -  :        576 :   add_metric("thread_count", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4945   [ +  -  +  -  :        576 :   add_metric("thread_busy", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4946         [ +  + ]:       1882 :   while (! interrupted)
    4947                 :            :     {
    4948         [ +  - ]:       1594 :       scan_payload p;
    4949                 :            : 
    4950   [ +  -  +  -  :       3188 :       add_metric("thread_busy", "role", "scan", -1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4951                 :            :       // NB: threads may be blocked within either of these two waiting
    4952                 :            :       // states, if the work queue happens to run dry.  That's OK.
    4953   [ +  -  +  - ]:       1594 :       if (scan_barrier) scan_barrier->count();
    4954         [ +  - ]:       1594 :       bool gotone = scanq.wait_front(p);
    4955   [ +  -  +  -  :       3188 :       add_metric("thread_busy", "role", "scan", 1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    4956                 :            : 
    4957   [ +  +  -  + ]:       1594 :       if (! gotone) continue; // go back to waiting
    4958                 :            : 
    4959                 :       1306 :       try
    4960                 :            :         {
    4961                 :       1306 :           bool scan_archive = false;
    4962         [ +  + ]:       2878 :           for (auto&& arch : scan_archives)
    4963         [ +  + ]:       1572 :             if (string_endswith(p.first, arch.first))
    4964                 :        762 :               scan_archive = true;
    4965                 :            : 
    4966         [ +  + ]:       1306 :           if (scan_archive)
    4967         [ +  - ]:        762 :             scan_archive_file (p.first, p.second,
    4968                 :            :                                ps_r_upsert_buildids,
    4969                 :            :                                ps_r_upsert_fileparts,
    4970                 :            :                                ps_r_upsert_file,
    4971                 :            :                                ps_r_lookup_file,
    4972                 :            :                                ps_r_upsert_de,
    4973                 :            :                                ps_r_upsert_sref,
    4974                 :            :                                ps_r_upsert_sdef,
    4975                 :            :                                ps_r_upsert_seekable,
    4976                 :            :                                ps_r_query,
    4977                 :            :                                ps_r_scan_done,
    4978                 :            :                                fts_cached,
    4979                 :            :                                fts_executable,
    4980                 :            :                                fts_debuginfo,
    4981                 :            :                                fts_sref,
    4982                 :            :                                fts_sdef);
    4983                 :            : 
    4984         [ +  + ]:       1306 :           if (scan_files) // NB: maybe "else if" ?
    4985         [ +  - ]:       1098 :             scan_source_file (p.first, p.second,
    4986                 :            :                               ps_f_upsert_buildids,
    4987                 :            :                               ps_f_upsert_fileparts,
    4988                 :            :                               ps_f_upsert_file,
    4989                 :            :                               ps_f_lookup_file,
    4990                 :            :                               ps_f_upsert_de,
    4991                 :            :                               ps_f_upsert_s,
    4992                 :            :                               ps_f_query,
    4993                 :            :                               ps_f_scan_done,
    4994                 :            :                               fts_cached, fts_executable, fts_debuginfo, fts_sourcefiles);
    4995                 :            :         }
    4996         [ -  - ]:          0 :       catch (const reportable_exception& e)
    4997                 :            :         {
    4998         [ -  - ]:          0 :           e.report(cerr);
    4999                 :          0 :         }
    5000                 :            : 
    5001         [ +  - ]:       1306 :       scanq.done_front(); // let idlers run
    5002                 :            :       
    5003                 :       1306 :       if (fts_cached || fts_executable || fts_debuginfo || fts_sourcefiles || fts_sref || fts_sdef)
    5004                 :            :         {} // NB: not just if a successful scan - we might have encountered -ENOSPC & failed
    5005   [ +  -  +  - ]:       1306 :       (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
    5006   [ +  -  +  - ]:       1306 :       (void) statfs_free_enough_p(tmpdir, "tmpdir"); // this too, in case of fdcache/tmpfile usage
    5007                 :            : 
    5008                 :            :       // finished a scanning step -- not a "loop", because we just
    5009                 :            :       // consume the traversal loop's work, whenever
    5010   [ +  -  +  -  :       2612 :       inc_metric("thread_work_total","role","scan");
          +  -  +  -  -  
          +  -  +  +  -  
          -  -  -  -  -  
                      - ]
    5011                 :       1594 :     }
    5012                 :            : 
    5013   [ +  -  +  -  :        576 :   add_metric("thread_busy", "role", "scan", -1);
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5014                 :        288 : }
    5015                 :            : 
    5016                 :            : 
    5017                 :            : // Use this function as the thread entry point, so it can catch our
    5018                 :            : // fleet of exceptions (incl. the sqlite_ps ctors) and report.
    5019                 :            : static void*
    5020                 :        288 : thread_main_scanner (void* arg)
    5021                 :            : {
    5022                 :        288 :   (void) arg;
    5023         [ +  + ]:        864 :   while (! interrupted)
    5024                 :        288 :     try
    5025                 :            :       {
    5026         [ +  - ]:        288 :         scan();
    5027                 :            :       }
    5028         [ -  - ]:          0 :     catch (const reportable_exception& e)
    5029                 :            :       {
    5030         [ -  - ]:          0 :         e.report(cerr);
    5031                 :          0 :       }
    5032                 :        288 :   return 0;
    5033                 :            : }
    5034                 :            : 
    5035                 :            : 
    5036                 :            : 
    5037                 :            : // The thread that traverses all the source_paths and enqueues all the
    5038                 :            : // matching files into the file/archive scan queue.
    5039                 :            : static void
    5040                 :        126 : scan_source_paths()
    5041                 :            : {
    5042                 :            :   // NB: fedora 31 glibc/fts(3) crashes inside fts_read() on empty
    5043                 :            :   // path list.
    5044         [ +  + ]:        126 :   if (source_paths.empty())
    5045                 :          2 :     return;
    5046                 :            : 
    5047                 :            :   // Turn the source_paths into an fts(3)-compatible char**.  Since
    5048                 :            :   // source_paths[] does not change after argv processing, the
    5049                 :            :   // c_str()'s are safe to keep around awile.
    5050                 :        124 :   vector<const char *> sps;
    5051         [ +  + ]:        332 :   for (auto&& sp: source_paths)
    5052         [ +  - ]:        208 :     sps.push_back(sp.c_str());
    5053   [ +  -  -  - ]:        124 :   sps.push_back(NULL);
    5054                 :            : 
    5055   [ +  +  +  - ]:        234 :   FTS *fts = fts_open ((char * const *)sps.data(),
    5056                 :            :                       (traverse_logical ? FTS_LOGICAL : FTS_PHYSICAL|FTS_XDEV)
    5057                 :            :                       | FTS_NOCHDIR /* multithreaded */,
    5058                 :            :                       NULL);
    5059         [ -  + ]:        124 :   if (fts == NULL)
    5060   [ #  #  #  # ]:          0 :     throw libc_exception(errno, "cannot fts_open");
    5061                 :        124 :   defer_dtor<FTS*,int> fts_cleanup (fts, fts_close);
    5062                 :            : 
    5063                 :        124 :   struct timespec ts_start, ts_end;
    5064                 :        124 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    5065                 :        124 :   unsigned fts_scanned = 0, fts_regex = 0;
    5066                 :            : 
    5067                 :        124 :   FTSENT *f;
    5068   [ +  -  +  + ]:       2636 :   while ((f = fts_read (fts)) != NULL)
    5069                 :            :   {
    5070         [ +  - ]:       2388 :     if (interrupted) break;
    5071                 :            : 
    5072         [ -  + ]:       2388 :     if (sigusr2 != forced_groom_count) // stop early if groom triggered
    5073                 :            :       {
    5074         [ #  # ]:          0 :         scanq.clear(); // clear previously issued work for scanner threads
    5075                 :            :         break;
    5076                 :            :       }
    5077                 :            : 
    5078                 :       2388 :     fts_scanned ++;
    5079                 :            : 
    5080         [ +  - ]:       2388 :     if (verbose > 2)
    5081   [ +  -  +  -  :       4776 :       obatched(clog) << "fts traversing " << f->fts_path << endl;
                   +  - ]
    5082                 :            : 
    5083   [ +  +  +  +  :       2388 :     switch (f->fts_info)
                      + ]
    5084                 :            :       {
    5085                 :       1416 :       case FTS_F:
    5086                 :       1416 :         {
    5087                 :            :           /* Found a file.  Convert it to an absolute path, so
    5088                 :            :              the buildid database does not have relative path
    5089                 :            :              names that are unresolvable from a subsequent run
    5090                 :            :              in a different cwd. */
    5091         [ +  - ]:       1416 :           char *rp = realpath(f->fts_path, NULL);
    5092         [ -  + ]:       1416 :           if (rp == NULL)
    5093                 :          0 :             continue; // ignore dangling symlink or such
    5094         [ +  - ]:       1416 :           string rps = string(rp);
    5095                 :       1416 :           free (rp);
    5096                 :            : 
    5097         [ +  - ]:       1416 :           bool ri = !regexec (&file_include_regex, rps.c_str(), 0, 0, 0);
    5098         [ +  - ]:       1416 :           bool rx = !regexec (&file_exclude_regex, rps.c_str(), 0, 0, 0);
    5099         [ +  + ]:       1416 :           if (!ri || rx)
    5100                 :            :             {
    5101         [ +  - ]:        110 :               if (verbose > 3)
    5102         [ +  - ]:        220 :                 obatched(clog) << "fts skipped by regex "
    5103   [ +  +  +  -  :        134 :                                << (!ri ? "I" : "") << (rx ? "X" : "") << endl;
          +  +  +  -  +  
                      - ]
    5104                 :        110 :               fts_regex ++;
    5105         [ +  + ]:        110 :               if (!ri)
    5106   [ +  -  +  -  :         24 :                 inc_metric("traversed_total","type","file-skipped-I");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5107         [ +  + ]:        110 :               if (rx)
    5108   [ +  -  +  -  :        196 :                 inc_metric("traversed_total","type","file-skipped-X");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5109                 :            :             }
    5110                 :            :           else
    5111                 :            :             {
    5112   [ +  -  +  - ]:       1306 :               scanq.push_back (make_pair(rps, *f->fts_statp));
    5113   [ +  -  +  -  :       2612 :               inc_metric("traversed_total","type","file");
          +  -  +  -  -  
          +  -  +  -  -  
             -  -  -  - ]
    5114                 :            :             }
    5115                 :          0 :         }
    5116                 :       1416 :         break;
    5117                 :            : 
    5118                 :          4 :       case FTS_ERR:
    5119                 :          4 :       case FTS_NS:
    5120                 :            :         // report on some types of errors because they may reflect fixable misconfiguration
    5121                 :          4 :         {
    5122   [ +  -  +  -  :          8 :           auto x = libc_exception(f->fts_errno, string("fts traversal ") + string(f->fts_path));
          +  -  +  -  -  
             +  -  +  -  
                      - ]
    5123         [ +  - ]:          4 :           x.report(cerr);
    5124                 :          0 :         }
    5125   [ +  -  +  -  :          8 :         inc_metric("traversed_total","type","error");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5126                 :          4 :         break;
    5127                 :            : 
    5128                 :         32 :       case FTS_SL: // ignore, but count because debuginfod -L would traverse these
    5129   [ +  -  +  -  :         64 :         inc_metric("traversed_total","type","symlink");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5130                 :         32 :         break;
    5131                 :            : 
    5132                 :        468 :       case FTS_D: // ignore
    5133   [ +  -  +  -  :        936 :         inc_metric("traversed_total","type","directory");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5134                 :        468 :         break;
    5135                 :            : 
    5136                 :        468 :       default: // ignore
    5137   [ +  -  +  -  :        936 :         inc_metric("traversed_total","type","other");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5138                 :        468 :         break;
    5139                 :            :       }
    5140                 :            :   }
    5141                 :        124 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    5142                 :        124 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    5143                 :            : 
    5144   [ +  -  +  -  :        372 :   obatched(clog) << "fts traversed source paths in " << deltas << "s, scanned=" << fts_scanned
             +  -  +  - ]
    5145   [ +  -  +  -  :        124 :                  << ", regex-skipped=" << fts_regex << endl;
                   +  - ]
    5146         [ +  - ]:        248 : }
    5147                 :            : 
    5148                 :            : 
    5149                 :            : static void*
    5150                 :         72 : thread_main_fts_source_paths (void* arg)
    5151                 :            : {
    5152                 :         72 :   (void) arg; // ignore; we operate on global data
    5153                 :            : 
    5154   [ +  -  +  -  :        144 :   set_metric("thread_tid", "role","traverse", tid());
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5155   [ +  -  +  -  :        144 :   add_metric("thread_count", "role", "traverse", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5156                 :            : 
    5157                 :         72 :   time_t last_rescan = 0;
    5158                 :            : 
    5159         [ +  - ]:        300 :   while (! interrupted)
    5160                 :            :     {
    5161                 :        300 :       sleep (1);
    5162                 :        300 :       scanq.wait_idle(); // don't start a new traversal while scanners haven't finished the job
    5163                 :        300 :       scanq.done_idle(); // release the hounds
    5164         [ +  + ]:        300 :       if (interrupted) break;
    5165                 :            : 
    5166                 :        228 :       time_t now = time(NULL);
    5167                 :        228 :       bool rescan_now = false;
    5168         [ +  + ]:        228 :       if (last_rescan == 0) // at least one initial rescan is documented even for -t0
    5169                 :         70 :         rescan_now = true;
    5170   [ +  +  +  + ]:        228 :       if (rescan_s > 0 && (long)now > (long)(last_rescan + rescan_s))
    5171                 :        228 :         rescan_now = true;
    5172         [ +  + ]:        228 :       if (sigusr1 != forced_rescan_count)
    5173                 :            :         {
    5174                 :         58 :           forced_rescan_count = sigusr1;
    5175                 :         58 :           rescan_now = true;
    5176                 :            :         }
    5177         [ +  + ]:        228 :       if (rescan_now)
    5178                 :            :         {
    5179   [ +  -  +  -  :        252 :           set_metric("thread_busy", "role","traverse", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5180                 :        126 :           try
    5181                 :            :             {
    5182         [ +  - ]:        126 :               scan_source_paths();
    5183                 :            :             }
    5184         [ -  - ]:          0 :           catch (const reportable_exception& e)
    5185                 :            :             {
    5186         [ -  - ]:          0 :               e.report(cerr);
    5187                 :          0 :             }
    5188                 :        126 :           last_rescan = time(NULL); // NB: now was before scanning
    5189                 :            :           // finished a traversal loop
    5190   [ +  -  +  -  :        252 :           inc_metric("thread_work_total", "role","traverse");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5191   [ +  -  +  -  :        252 :           set_metric("thread_busy", "role","traverse", 0);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5192                 :            :         }
    5193                 :            :     }
    5194                 :            : 
    5195                 :         72 :   return 0;
    5196                 :            : }
    5197                 :            : 
    5198                 :            : 
    5199                 :            : 
    5200                 :            : ////////////////////////////////////////////////////////////////////////
    5201                 :            : 
    5202                 :            : static void
    5203                 :         78 : database_stats_report()
    5204                 :            : {
    5205                 :         78 :   sqlite_ps ps_query (db, "database-overview",
    5206   [ +  -  +  -  :        156 :                       "select label,quantity from " BUILDIDS "_stats");
             +  -  -  - ]
    5207                 :            : 
    5208   [ +  -  +  - ]:        156 :   obatched(clog) << "database record counts:" << endl;
    5209                 :       1794 :   while (1)
    5210                 :            :     {
    5211         [ +  - ]:        936 :       if (interrupted) break;
    5212         [ +  - ]:        936 :       if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    5213                 :            :         break;
    5214                 :            : 
    5215         [ +  - ]:        936 :       int rc = ps_query.step();
    5216         [ +  + ]:        936 :       if (rc == SQLITE_DONE) break;
    5217         [ -  + ]:        858 :       if (rc != SQLITE_ROW)
    5218   [ #  #  #  # ]:          0 :         throw sqlite_exception(rc, "step");
    5219                 :            : 
    5220         [ +  - ]:        858 :       obatched(clog)
    5221   [ +  -  -  +  :        858 :         << ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL")
                   +  - ]
    5222                 :            :         << " "
    5223   [ +  -  +  -  :       1716 :         << (sqlite3_column_text(ps_query, 1) ?: (const unsigned char*) "NULL")
             -  +  +  - ]
    5224                 :        858 :         << endl;
    5225                 :            : 
    5226   [ +  -  +  -  :       1716 :       set_metric("groom", "statistic",
          -  +  +  -  +  
          -  +  -  +  -  
          -  +  +  +  -  
                -  -  - ]
    5227         [ +  - ]:        858 :                  ((const char*) sqlite3_column_text(ps_query, 0) ?: (const char*) "NULL"),
    5228                 :            :                  (sqlite3_column_double(ps_query, 1)));
    5229                 :        858 :     }
    5230                 :         78 : }
    5231                 :            : 
    5232                 :            : 
    5233                 :            : // Do a round of database grooming that might take many minutes to run.
    5234                 :         78 : void groom()
    5235                 :            : {
    5236         [ +  - ]:        156 :   obatched(clog) << "grooming database" << endl;
    5237                 :            : 
    5238                 :         78 :   struct timespec ts_start, ts_end;
    5239                 :         78 :   clock_gettime (CLOCK_MONOTONIC, &ts_start);
    5240                 :            : 
    5241                 :            :   // scan for files that have disappeared
    5242                 :         78 :   sqlite_ps files (db, "check old files",
    5243                 :            :                    "select distinct s.mtime, s.file, f.name from "
    5244                 :            :                    BUILDIDS "_file_mtime_scanned s, " BUILDIDS "_files_v f "
    5245   [ +  -  +  -  :        156 :                    "where f.id = s.file");
             +  -  -  - ]
    5246                 :            :   // NB: Because _ftime_mtime_scanned can contain both F and
    5247                 :            :   // R records for the same file, this query would return duplicates if the
    5248                 :            :   // DISTINCT qualifier were not there.
    5249         [ +  - ]:         78 :   files.reset();
    5250                 :            : 
    5251                 :            :   // DECISION TIME - we enumerate stale fileids/mtimes
    5252         [ +  - ]:         78 :   deque<pair<int64_t,int64_t> > stale_fileid_mtime;
    5253                 :            :   
    5254                 :         78 :   time_t time_start = time(NULL);
    5255                 :        342 :   while(1)
    5256                 :            :     {
    5257                 :            :       // PR28514: limit grooming iteration to O(rescan time), to avoid
    5258                 :            :       // slow filesystem tests over many files locking out rescans for
    5259                 :            :       // too long.
    5260   [ +  +  -  + ]:        210 :       if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
    5261                 :            :         {
    5262   [ #  #  #  #  :          0 :           inc_metric("groomed_total", "decision", "aborted");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    5263                 :          0 :           break;
    5264                 :            :         }
    5265                 :            : 
    5266         [ +  - ]:        210 :       if (interrupted) break;
    5267                 :            : 
    5268         [ +  - ]:        210 :       int rc = files.step();
    5269         [ +  + ]:        210 :       if (rc != SQLITE_ROW)
    5270                 :            :         break;
    5271                 :            : 
    5272         [ +  - ]:        132 :       int64_t mtime = sqlite3_column_int64 (files, 0);
    5273         [ +  - ]:        132 :       int64_t fileid = sqlite3_column_int64 (files, 1);
    5274   [ +  -  -  + ]:        132 :       const char* filename = ((const char*) sqlite3_column_text (files, 2) ?: "");
    5275                 :        132 :       struct stat s;
    5276                 :        132 :       bool regex_file_drop = 0;
    5277                 :            : 
    5278         [ +  + ]:        132 :       if (regex_groom)
    5279                 :            :         {
    5280         [ +  - ]:         16 :           bool reg_include = !regexec (&file_include_regex, filename, 0, 0, 0);
    5281         [ +  - ]:         16 :           bool reg_exclude = !regexec (&file_exclude_regex, filename, 0, 0, 0);
    5282                 :         16 :           regex_file_drop = !reg_include || reg_exclude; // match logic of scan_source_paths  
    5283                 :            :         }
    5284                 :            : 
    5285                 :        132 :       rc = stat(filename, &s);
    5286   [ +  +  -  + ]:        132 :       if ( regex_file_drop ||  rc < 0 || (mtime != (int64_t) s.st_mtime) )
    5287                 :            :         {
    5288         [ +  - ]:         24 :           if (verbose > 2)
    5289   [ +  -  +  -  :         48 :             obatched(clog) << "groom: stale file=" << filename << " mtime=" << mtime << endl;
          +  -  +  -  +  
                      - ]
    5290         [ +  - ]:         24 :           stale_fileid_mtime.push_back(make_pair(fileid,mtime));
    5291   [ +  -  +  -  :         48 :           inc_metric("groomed_total", "decision", "stale");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5292   [ +  -  +  -  :         48 :           set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5293                 :            :         }
    5294                 :            :       else
    5295   [ +  -  +  -  :        216 :         inc_metric("groomed_total", "decision", "fresh");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5296                 :            :       
    5297         [ +  - ]:        132 :       if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    5298                 :            :         break;
    5299                 :        132 :     }
    5300         [ +  - ]:         78 :   files.reset();
    5301                 :            : 
    5302                 :            :   // ACTION TIME
    5303                 :            : 
    5304                 :            :   // Now that we know which file/mtime tuples are stale, actually do
    5305                 :            :   // the deletion from the database.  Doing this during the SELECT
    5306                 :            :   // iteration above results in undefined behaviour in sqlite, as per
    5307                 :            :   // https://www.sqlite.org/isolation.html
    5308                 :            : 
    5309                 :            :   // We could shuffle stale_fileid_mtime[] here.  It'd let aborted
    5310                 :            :   // sequences of nuke operations resume at random locations, instead
    5311                 :            :   // of just starting over.  But it doesn't matter much either way,
    5312                 :            :   // as long as we make progress.
    5313                 :            : 
    5314   [ +  -  +  -  :        156 :   sqlite_ps files_del_f_de (db, "nuke f_de", "delete from " BUILDIDS "_f_de where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    5315   [ +  -  +  -  :        156 :   sqlite_ps files_del_r_de (db, "nuke r_de", "delete from " BUILDIDS "_r_de where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    5316         [ +  - ]:         78 :   sqlite_ps files_del_scan (db, "nuke f_m_s", "delete from " BUILDIDS "_file_mtime_scanned "
    5317   [ +  -  +  -  :        156 :                             "where file = ? and mtime = ?");
          +  -  +  -  -  
                      - ]
    5318                 :            : 
    5319         [ +  + ]:        102 :   while (! stale_fileid_mtime.empty())
    5320                 :            :     {
    5321                 :         24 :       auto stale = stale_fileid_mtime.front();
    5322                 :         24 :       stale_fileid_mtime.pop_front();
    5323   [ +  -  +  -  :         48 :       set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5324                 :            : 
    5325                 :            :       // PR28514: limit grooming iteration to O(rescan time), to avoid
    5326                 :            :       // slow nuke_* queries over many files locking out rescans for too
    5327                 :            :       // long.  We iterate over the files in random() sequence to avoid
    5328                 :            :       // partial checks going over the same set.
    5329   [ -  +  -  - ]:         24 :       if (rescan_s > 0 && (long)time(NULL) > (long)(time_start + rescan_s))
    5330                 :            :         {
    5331   [ #  #  #  #  :          0 :           inc_metric("groomed_total", "action", "aborted");
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
    5332                 :          0 :           break;
    5333                 :            :         }
    5334                 :            : 
    5335         [ +  - ]:         24 :       if (interrupted) break;
    5336                 :            : 
    5337                 :         24 :       int64_t fileid = stale.first;
    5338                 :         24 :       int64_t mtime = stale.second;
    5339   [ +  -  +  -  :         24 :       files_del_f_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    5340   [ +  -  +  -  :         24 :       files_del_r_de.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    5341   [ +  -  +  -  :         24 :       files_del_scan.reset().bind(1,fileid).bind(2,mtime).step_ok_done();
             +  -  +  - ]
    5342   [ +  -  +  -  :         48 :       inc_metric("groomed_total", "action", "cleaned");
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5343                 :            :       
    5344         [ +  - ]:         24 :        if (sigusr1 != forced_rescan_count) // stop early if scan triggered
    5345                 :            :         break;
    5346                 :            :     }
    5347                 :         78 :   stale_fileid_mtime.clear(); // no need for this any longer
    5348   [ +  -  +  -  :        156 :   set_metric("thread_work_pending","role","groom", stale_fileid_mtime.size());
          +  -  +  -  -  
          +  -  +  -  -  
                   -  - ]
    5349                 :            :       
    5350                 :            :   // delete buildids with no references in _r_de or _f_de tables;
    5351                 :            :   // cascades to _r_sref & _f_s records
    5352         [ +  - ]:         78 :   sqlite_ps buildids_del (db, "nuke orphan buildids",
    5353                 :            :                           "delete from " BUILDIDS "_buildids "
    5354                 :            :                           "where not exists (select 1 from " BUILDIDS "_f_de d where " BUILDIDS "_buildids.id = d.buildid) "
    5355   [ +  -  +  -  :        156 :                           "and not exists (select 1 from " BUILDIDS "_r_de d where " BUILDIDS "_buildids.id = d.buildid)");
          +  -  +  -  -  
                      - ]
    5356   [ +  -  +  - ]:         78 :   buildids_del.reset().step_ok_done();
    5357                 :            : 
    5358         [ -  + ]:         78 :   if (interrupted) return;
    5359                 :            : 
    5360                 :            :   // NB: "vacuum" is too heavy for even daily runs: it rewrites the entire db, so is done as maxigroom -G
    5361   [ +  -  +  -  :        234 :   { sqlite_ps g (db, "incremental vacuum", "pragma incremental_vacuum"); g.reset().step_ok_done(); }
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    5362                 :            :   // https://www.sqlite.org/lang_analyze.html#approx
    5363   [ +  -  +  -  :        234 :   { sqlite_ps g (db, "analyze setup", "pragma analysis_limit = 1000;\n"); g.reset().step_ok_done(); }
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    5364   [ +  -  +  -  :        156 :   { sqlite_ps g (db, "analyze", "analyze"); g.reset().step_ok_done(); }
          +  -  -  +  +  
             -  +  -  -  
                      - ]
    5365   [ +  -  +  -  :        234 :   { sqlite_ps g (db, "analyze reload", "analyze sqlite_schema"); g.reset().step_ok_done(); } 
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    5366   [ +  -  +  -  :        156 :   { sqlite_ps g (db, "optimize", "pragma optimize"); g.reset().step_ok_done(); }
          +  -  -  +  +  
             -  +  -  -  
                      - ]
    5367   [ +  -  +  -  :        234 :   { sqlite_ps g (db, "wal checkpoint", "pragma wal_checkpoint=truncate"); g.reset().step_ok_done(); }
          +  -  +  -  +  
             -  +  -  -  
                      - ]
    5368                 :            : 
    5369         [ +  - ]:         78 :   database_stats_report();
    5370                 :            : 
    5371   [ +  -  +  - ]:         78 :   (void) statfs_free_enough_p(db_path, "database"); // report sqlite filesystem size
    5372                 :            : 
    5373         [ +  - ]:         78 :   sqlite3_db_release_memory(db); // shrink the process if possible
    5374         [ +  - ]:         78 :   sqlite3_db_release_memory(dbq); // ... for both connections
    5375         [ +  - ]:         78 :   debuginfod_pool_groom(); // and release any debuginfod_client objects we've been holding onto
    5376                 :            : #if HAVE_MALLOC_TRIM
    5377                 :         78 :   malloc_trim(0); // PR31103: release memory allocated for temporary purposes
    5378                 :            : #endif
    5379                 :            :   
    5380                 :            : #if 0 /* PR31265: don't jettison cache unnecessarily */
    5381                 :            :   fdcache.limit(0); // release the fdcache contents
    5382                 :            :   fdcache.limit(fdcache_mbs); // restore status quo parameters
    5383                 :            : #endif
    5384                 :            :   
    5385                 :         78 :   clock_gettime (CLOCK_MONOTONIC, &ts_end);
    5386                 :         78 :   double deltas = (ts_end.tv_sec - ts_start.tv_sec) + (ts_end.tv_nsec - ts_start.tv_nsec)/1.e9;
    5387                 :            : 
    5388   [ +  -  +  -  :        156 :   obatched(clog) << "groomed database in " << deltas << "s" << endl;
             +  -  +  - ]
    5389                 :         78 : }
    5390                 :            : 
    5391                 :            : 
    5392                 :            : static void*
    5393                 :         78 : thread_main_groom (void* /*arg*/)
    5394                 :            : {
    5395   [ +  -  +  -  :        156 :   set_metric("thread_tid", "role", "groom", tid());
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5396   [ +  -  +  -  :        156 :   add_metric("thread_count", "role", "groom", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5397                 :            : 
    5398                 :         78 :   time_t last_groom = 0;
    5399                 :            : 
    5400                 :        538 :   while (1)
    5401                 :            :     {
    5402                 :        308 :       sleep (1);
    5403                 :        308 :       scanq.wait_idle(); // PR25394: block scanners during grooming!
    5404         [ +  + ]:        308 :       if (interrupted) break;
    5405                 :            : 
    5406                 :        230 :       time_t now = time(NULL);
    5407                 :        230 :       bool groom_now = false;
    5408         [ +  + ]:        230 :       if (last_groom == 0) // at least one initial groom is documented even for -g0
    5409                 :         72 :         groom_now = true;
    5410   [ +  +  +  + ]:        230 :       if (groom_s > 0 && (long)now > (long)(last_groom + groom_s))
    5411                 :        230 :         groom_now = true;
    5412         [ +  + ]:        230 :       if (sigusr2 != forced_groom_count)
    5413                 :            :         {
    5414                 :          6 :           forced_groom_count = sigusr2;
    5415                 :          6 :           groom_now = true;
    5416                 :            :         }
    5417         [ +  + ]:        230 :       if (groom_now)
    5418                 :            :         {
    5419   [ +  -  +  -  :        156 :           set_metric("thread_busy", "role", "groom", 1);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5420                 :         78 :           try
    5421                 :            :             {
    5422         [ +  - ]:         78 :               groom ();
    5423                 :            :             }
    5424         [ -  - ]:          0 :           catch (const sqlite_exception& e)
    5425                 :            :             {
    5426   [ -  -  -  -  :          0 :               obatched(cerr) << e.message << endl;
                   -  - ]
    5427                 :          0 :             }
    5428                 :         78 :           last_groom = time(NULL); // NB: now was before grooming
    5429                 :            :           // finished a grooming loop
    5430   [ +  -  +  -  :        156 :           inc_metric("thread_work_total", "role", "groom");
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5431   [ +  -  +  -  :        156 :           set_metric("thread_busy", "role", "groom", 0);
          +  -  -  +  -  
             +  -  -  -  
                      - ]
    5432                 :            :         }
    5433                 :            : 
    5434                 :        230 :       scanq.done_idle();
    5435                 :        230 :     }
    5436                 :            : 
    5437                 :         78 :   return 0;
    5438                 :            : }
    5439                 :            : 
    5440                 :            : 
    5441                 :            : ////////////////////////////////////////////////////////////////////////
    5442                 :            : 
    5443                 :            : 
    5444                 :            : static void
    5445                 :         80 : signal_handler (int /* sig */)
    5446                 :            : {
    5447                 :         80 :   interrupted ++;
    5448                 :            : 
    5449         [ +  + ]:         80 :   if (db)
    5450                 :         78 :     sqlite3_interrupt (db);
    5451         [ +  - ]:         80 :   if (dbq)
    5452                 :         80 :     sqlite3_interrupt (dbq);
    5453                 :            : 
    5454                 :            :   // NB: don't do anything else in here
    5455                 :         80 : }
    5456                 :            : 
    5457                 :            : static void
    5458                 :         58 : sigusr1_handler (int /* sig */)
    5459                 :            : {
    5460                 :         58 :    sigusr1 ++;
    5461                 :            :   // NB: don't do anything else in here
    5462                 :         58 : }
    5463                 :            : 
    5464                 :            : static void
    5465                 :          6 : sigusr2_handler (int /* sig */)
    5466                 :            : {
    5467                 :          6 :    sigusr2 ++;
    5468                 :            :   // NB: don't do anything else in here
    5469                 :          6 : }
    5470                 :            : 
    5471                 :            : 
    5472                 :            : static void // error logging callback from libmicrohttpd internals
    5473                 :          0 : error_cb (void *arg, const char *fmt, va_list ap)
    5474                 :            : {
    5475                 :          0 :   (void) arg;
    5476   [ #  #  #  #  :          0 :   inc_metric("error_count","libmicrohttpd",fmt);
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    5477                 :          0 :   char errmsg[512];
    5478                 :          0 :   (void) vsnprintf (errmsg, sizeof(errmsg), fmt, ap); // ok if slightly truncated
    5479         [ #  # ]:          0 :   obatched(cerr) << "libmicrohttpd error: " << errmsg; // MHD_DLOG calls already include \n
    5480                 :          0 : }
    5481                 :            : 
    5482                 :            : 
    5483                 :            : // A user-defined sqlite function, to score the sharedness of the
    5484                 :            : // prefix of two strings.  This is used to compare candidate debuginfo
    5485                 :            : // / source-rpm names, so that the closest match
    5486                 :            : // (directory-topology-wise closest) is found.  This is important in
    5487                 :            : // case the same sref (source file name) is in many -debuginfo or
    5488                 :            : // -debugsource RPMs, such as when multiple versions/releases of the
    5489                 :            : // same package are in the database.
    5490                 :            : 
    5491                 :       1320 : static void sqlite3_sharedprefix_fn (sqlite3_context* c, int argc, sqlite3_value** argv)
    5492                 :            : {
    5493         [ -  + ]:       1320 :   if (argc != 2)
    5494                 :          0 :     sqlite3_result_error(c, "expect 2 string arguments", -1);
    5495   [ +  -  +  + ]:       2640 :   else if ((sqlite3_value_type(argv[0]) != SQLITE_TEXT) ||
    5496                 :       1320 :            (sqlite3_value_type(argv[1]) != SQLITE_TEXT))
    5497                 :       1058 :     sqlite3_result_null(c);
    5498                 :            :   else
    5499                 :            :     {
    5500                 :        262 :       const unsigned char* a = sqlite3_value_text (argv[0]);
    5501                 :        262 :       const unsigned char* b = sqlite3_value_text (argv[1]);
    5502                 :        262 :       int i = 0;
    5503   [ +  +  +  -  :      16570 :       while (*a != '\0' && *b != '\0' && *a++ == *b++)
             +  +  +  + ]
    5504                 :      15822 :         i++;
    5505                 :        262 :       sqlite3_result_int (c, i);
    5506                 :            :     }
    5507                 :       1320 : }
    5508                 :            : 
    5509                 :            : 
    5510                 :            : static unsigned
    5511                 :        156 : default_concurrency() // guaranteed >= 1
    5512                 :            : {
    5513                 :            :   // Prior to PR29975 & PR29976, we'd just use this: 
    5514                 :        156 :   unsigned sth = std::thread::hardware_concurrency();
    5515                 :            :   // ... but on many-CPU boxes, admins or distros may throttle
    5516                 :            :   // resources in such a way that debuginfod would mysteriously fail.
    5517                 :            :   // So we reduce the defaults:
    5518                 :            : 
    5519                 :        156 :   unsigned aff = 0;
    5520                 :            : #ifdef HAVE_SCHED_GETAFFINITY
    5521                 :        156 :   {
    5522                 :        156 :     int ret;
    5523                 :        156 :     cpu_set_t mask;
    5524                 :        156 :     CPU_ZERO(&mask);
    5525                 :        156 :     ret = sched_getaffinity(0, sizeof(mask), &mask);
    5526         [ +  - ]:        156 :     if (ret == 0)
    5527                 :        156 :       aff = CPU_COUNT(&mask);
    5528                 :            :   }
    5529                 :            : #endif
    5530                 :            :   
    5531                 :        156 :   unsigned fn = 0;
    5532                 :            : #ifdef HAVE_GETRLIMIT
    5533                 :        156 :   {
    5534                 :        156 :     struct rlimit rlim;
    5535                 :        156 :     int rc = getrlimit(RLIMIT_NOFILE, &rlim);
    5536         [ +  - ]:        156 :     if (rc == 0)
    5537         [ +  - ]:        312 :       fn = max((rlim_t)1, (rlim.rlim_cur - 100) / 4);
    5538                 :            :     // at least 2 fds are used by each listener thread etc.
    5539                 :            :     // plus a bunch to account for shared libraries and such
    5540                 :            :   }
    5541                 :            : #endif
    5542                 :            : 
    5543   [ -  +  -  +  :        156 :   unsigned d = min(max(sth, 1U),
                   -  + ]
    5544         [ -  + ]:        156 :                    min(max(aff, 1U),
    5545         [ -  + ]:        156 :                        max(fn, 1U)));
    5546                 :        156 :   return d;
    5547                 :            : }
    5548                 :            : 
    5549                 :            : 
    5550                 :            : // 30879: Something to help out in case of an uncaught exception.
    5551                 :          0 : void my_terminate_handler()
    5552                 :            : {
    5553                 :            : #if defined(__GLIBC__)
    5554                 :          0 :   void *array[40];
    5555                 :          0 :   int size = backtrace (array, 40);
    5556                 :          0 :   backtrace_symbols_fd (array, size, STDERR_FILENO);
    5557                 :            : #endif
    5558                 :            : #if defined(__GLIBCXX__) || defined(__GLIBCPP__)
    5559                 :          0 :   __gnu_cxx::__verbose_terminate_handler();
    5560                 :            : #endif
    5561                 :          0 :   abort();
    5562                 :            : }
    5563                 :            : 
    5564                 :            : 
    5565                 :            : int
    5566                 :         80 : main (int argc, char *argv[])
    5567                 :            : {
    5568                 :         80 :   (void) setlocale (LC_ALL, "");
    5569                 :         80 :   (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
    5570                 :         80 :   (void) textdomain (PACKAGE_TARNAME);
    5571                 :            : 
    5572                 :         80 :   std::set_terminate(& my_terminate_handler);
    5573                 :            : 
    5574                 :            :   /* Tell the library which version we are expecting.  */
    5575                 :         80 :   elf_version (EV_CURRENT);
    5576                 :            : 
    5577   [ +  -  -  + ]:        160 :   tmpdir = string(getenv("TMPDIR") ?: "/tmp");
    5578                 :            : 
    5579                 :            :   /* Set computed default values. */
    5580   [ -  +  +  -  :         80 :   db_path = string(getenv("HOME") ?: "/") + string("/.debuginfod.sqlite"); /* XDG? */
          +  -  -  +  -  
             +  +  -  -  
                      - ]
    5581                 :         80 :   int rc = regcomp (& file_include_regex, ".*", REG_EXTENDED|REG_NOSUB); // match everything
    5582         [ -  + ]:         80 :   if (rc != 0)
    5583                 :          0 :     error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
    5584                 :         80 :   rc = regcomp (& file_exclude_regex, "^$", REG_EXTENDED|REG_NOSUB); // match nothing
    5585         [ -  + ]:         80 :   if (rc != 0)
    5586                 :          0 :     error (EXIT_FAILURE, 0, "regcomp failure: %d", rc);
    5587                 :            : 
    5588                 :            :   // default parameters for fdcache are computed from system stats
    5589                 :         80 :   struct statfs sfs;
    5590                 :         80 :   rc = statfs(tmpdir.c_str(), &sfs);
    5591         [ -  + ]:         80 :   if (rc < 0)
    5592                 :          0 :     fdcache_mbs = 1024; // 1 gigabyte
    5593                 :            :   else
    5594                 :         80 :     fdcache_mbs = sfs.f_bavail * sfs.f_bsize / 1024 / 1024 / 4; // 25% of free space
    5595                 :         80 :   fdcache_mintmp = 25; // emergency flush at 25% remaining (75% full)
    5596                 :         80 :   fdcache_prefetch = 64; // guesstimate storage is this much less costly than re-decompression
    5597                 :            : 
    5598                 :            :   /* Parse and process arguments.  */
    5599                 :         80 :   int remaining;
    5600                 :         80 :   (void) argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
    5601         [ -  + ]:         80 :   if (remaining != argc)
    5602                 :          0 :       error (EXIT_FAILURE, 0,
    5603                 :          0 :              "unexpected argument: %s", argv[remaining]);
    5604                 :            : 
    5605   [ +  +  +  +  :         80 :   if (scan_archives.size()==0 && !scan_files && source_paths.size()>0)
                   -  + ]
    5606         [ #  # ]:          0 :     obatched(clog) << "warning: without -F -R -U -Z, ignoring PATHs" << endl;
    5607                 :            : 
    5608                 :         80 :   fdcache.limit(fdcache_mbs);
    5609                 :            : 
    5610                 :         80 :   (void) signal (SIGPIPE, SIG_IGN); // microhttpd can generate it incidentally, ignore
    5611                 :         80 :   (void) signal (SIGINT, signal_handler); // ^C
    5612                 :         80 :   (void) signal (SIGHUP, signal_handler); // EOF
    5613                 :         80 :   (void) signal (SIGTERM, signal_handler); // systemd
    5614                 :         80 :   (void) signal (SIGUSR1, sigusr1_handler); // end-user
    5615                 :         80 :   (void) signal (SIGUSR2, sigusr2_handler); // end-user
    5616                 :            : 
    5617                 :            :   /* Get database ready. */
    5618         [ +  + ]:         80 :   if (! passive_p)
    5619                 :            :     {
    5620                 :         78 :       rc = sqlite3_open_v2 (db_path.c_str(), &db, (SQLITE_OPEN_READWRITE
    5621                 :            :                                                    |SQLITE_OPEN_URI
    5622                 :            :                                                    |SQLITE_OPEN_PRIVATECACHE
    5623                 :            :                                                    |SQLITE_OPEN_CREATE
    5624                 :            :                                                    |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
    5625                 :            :                             NULL);
    5626         [ -  + ]:         78 :       if (rc == SQLITE_CORRUPT)
    5627                 :            :         {
    5628                 :          0 :           (void) unlink (db_path.c_str());
    5629                 :          0 :           error (EXIT_FAILURE, 0,
    5630                 :            :                  "cannot open %s, deleted database: %s", db_path.c_str(), sqlite3_errmsg(db));
    5631                 :            :         }
    5632         [ -  + ]:         78 :       else if (rc)
    5633                 :            :         {
    5634                 :          0 :           error (EXIT_FAILURE, 0,
    5635                 :            :                  "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(db));
    5636                 :            :         }
    5637                 :            :     }
    5638                 :            : 
    5639                 :            :   // open the readonly query variant
    5640                 :            :   // NB: PRIVATECACHE allows web queries to operate in parallel with
    5641                 :            :   // much other grooming/scanning operation.
    5642                 :         80 :   rc = sqlite3_open_v2 (db_path.c_str(), &dbq, (SQLITE_OPEN_READONLY
    5643                 :            :                                                 |SQLITE_OPEN_URI
    5644                 :            :                                                 |SQLITE_OPEN_PRIVATECACHE
    5645                 :            :                                                 |SQLITE_OPEN_FULLMUTEX), /* thread-safe */
    5646                 :            :                         NULL);
    5647         [ -  + ]:         80 :   if (rc)
    5648                 :            :     {
    5649                 :          0 :       error (EXIT_FAILURE, 0,
    5650                 :            :              "cannot open %s, consider deleting database: %s", db_path.c_str(), sqlite3_errmsg(dbq));
    5651                 :            :     }
    5652                 :            : 
    5653                 :            : 
    5654         [ +  - ]:        160 :   obatched(clog) << "opened database " << db_path
    5655   [ +  +  +  -  :         82 :                  << (db?" rw":"") << (dbq?" ro":"") << endl;
          -  +  +  -  +  
                      - ]
    5656   [ +  -  +  - ]:        160 :   obatched(clog) << "sqlite version " << sqlite3_version << endl;
    5657   [ +  +  +  -  :        238 :   obatched(clog) << "service mode " << (passive_p ? "passive":"active") << endl;
                   +  - ]
    5658                 :            : 
    5659                 :            :   // add special string-prefix-similarity function used in rpm sref/sdef resolution
    5660                 :         80 :   rc = sqlite3_create_function(dbq, "sharedprefix", 2, SQLITE_UTF8, NULL,
    5661                 :            :                                & sqlite3_sharedprefix_fn, NULL, NULL);
    5662         [ -  + ]:         80 :   if (rc != SQLITE_OK)
    5663                 :          0 :     error (EXIT_FAILURE, 0,
    5664                 :            :            "cannot create sharedprefix function: %s", sqlite3_errmsg(dbq));
    5665                 :            : 
    5666         [ +  + ]:         80 :   if (! passive_p)
    5667                 :            :     {
    5668         [ +  + ]:         78 :       if (verbose > 3)
    5669   [ +  -  +  - ]:         92 :         obatched(clog) << "ddl: " << DEBUGINFOD_SQLITE_DDL << endl;
    5670                 :         78 :       rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_DDL, NULL, NULL, NULL);
    5671         [ -  + ]:         78 :       if (rc != SQLITE_OK)
    5672                 :            :         {
    5673                 :          0 :           error (EXIT_FAILURE, 0,
    5674                 :            :                  "cannot run database schema ddl: %s", sqlite3_errmsg(db));
    5675                 :            :         }
    5676                 :            :     }
    5677                 :            : 
    5678   [ +  -  +  -  :        160 :   obatched(clog) << "libmicrohttpd version " << MHD_get_version() << endl;
                   +  - ]
    5679                 :            :   
    5680                 :            :   /* If '-C' wasn't given or was given with no arg, pick a reasonable default
    5681                 :            :      for the number of worker threads.  */
    5682         [ +  + ]:         80 :   if (connection_pool == 0)
    5683                 :         76 :     connection_pool = default_concurrency();
    5684                 :            : 
    5685                 :            :   /* Note that MHD_USE_EPOLL and MHD_USE_THREAD_PER_CONNECTION don't
    5686                 :            :      work together.  */
    5687                 :         80 :   unsigned int use_epoll = 0;
    5688                 :            : #if MHD_VERSION >= 0x00095100
    5689                 :         80 :   use_epoll = MHD_USE_EPOLL;
    5690                 :            : #endif
    5691                 :            : 
    5692                 :         80 :   unsigned int mhd_flags = (
    5693                 :            : #if MHD_VERSION >= 0x00095300
    5694                 :            :                             MHD_USE_INTERNAL_POLLING_THREAD
    5695                 :            : #else
    5696                 :            :                             MHD_USE_SELECT_INTERNALLY
    5697                 :            : #endif
    5698                 :            :                             | MHD_USE_DUAL_STACK
    5699                 :            :                             | use_epoll
    5700                 :            : #if MHD_VERSION >= 0x00095200
    5701                 :            :                             | MHD_USE_ITC
    5702                 :            : #endif
    5703                 :            :                             | MHD_USE_DEBUG); /* report errors to stderr */
    5704                 :            : 
    5705                 :            :   // Start httpd server threads.  Use a single dual-homed pool.
    5706                 :         80 :   MHD_Daemon *d46 = MHD_start_daemon (mhd_flags, http_port,
    5707                 :            :                                       NULL, NULL, /* default accept policy */
    5708                 :            :                                       handler_cb, NULL, /* handler callback */
    5709                 :            :                                       MHD_OPTION_EXTERNAL_LOGGER,
    5710                 :            :                                       error_cb, NULL,
    5711                 :            :                                       MHD_OPTION_THREAD_POOL_SIZE,
    5712                 :            :                                       (int)connection_pool,
    5713                 :            :                                       MHD_OPTION_END);
    5714                 :            : 
    5715                 :         80 :   MHD_Daemon *d4 = NULL;
    5716         [ -  + ]:         80 :   if (d46 == NULL)
    5717                 :            :     {
    5718                 :            :       // Cannot use dual_stack, use ipv4 only
    5719                 :          0 :       mhd_flags &= ~(MHD_USE_DUAL_STACK);
    5720         [ #  # ]:          0 :       d4 = MHD_start_daemon (mhd_flags, http_port,
    5721                 :            :                              NULL, NULL, /* default accept policy */
    5722                 :            :                              handler_cb, NULL, /* handler callback */
    5723                 :            :                              MHD_OPTION_EXTERNAL_LOGGER,
    5724                 :            :                              error_cb, NULL,
    5725                 :            :                              (connection_pool
    5726                 :            :                               ? MHD_OPTION_THREAD_POOL_SIZE
    5727                 :            :                               : MHD_OPTION_END),
    5728                 :            :                              (connection_pool
    5729                 :            :                               ? (int)connection_pool
    5730                 :            :                               : MHD_OPTION_END),
    5731                 :            :                              MHD_OPTION_END);
    5732         [ #  # ]:          0 :       if (d4 == NULL)
    5733                 :            :         {
    5734                 :          0 :           sqlite3 *database = db;
    5735                 :          0 :           sqlite3 *databaseq = dbq;
    5736                 :          0 :           db = dbq = 0; // for signal_handler not to freak
    5737                 :          0 :           sqlite3_close (databaseq);
    5738                 :          0 :           sqlite3_close (database);
    5739                 :          0 :           error (EXIT_FAILURE, 0, "cannot start http server at port %d",
    5740                 :            :                  http_port);
    5741                 :            :         }
    5742                 :            : 
    5743                 :            :     }
    5744                 :         80 :   obatched(clog) << "started http server on"
    5745                 :            :                  << (d4 != NULL ? " IPv4 " : " IPv4 IPv6 ")
    5746   [ +  -  +  -  :        160 :                  << "port=" << http_port
                   +  - ]
    5747   [ +  -  +  +  :        154 :                  << (webapi_cors ? " with cors" : "")
             +  -  +  - ]
    5748                 :         80 :                  << endl;
    5749                 :            : 
    5750                 :            :   // add maxigroom sql if -G given
    5751         [ -  + ]:         80 :   if (maxigroom)
    5752                 :            :     {
    5753         [ #  # ]:          0 :       obatched(clog) << "maxigrooming database, please wait." << endl;
    5754                 :            :       // NB: this index alone can nearly double the database size!
    5755                 :            :       // NB: this index would be necessary to run source-file metadata searches fast
    5756         [ #  # ]:          0 :       extra_ddl.push_back("create index if not exists " BUILDIDS "_r_sref_arc on " BUILDIDS "_r_sref(artifactsrc);");
    5757         [ #  # ]:          0 :       extra_ddl.push_back("delete from " BUILDIDS "_r_sdef where not exists (select 1 from " BUILDIDS "_r_sref b where " BUILDIDS "_r_sdef.content = b.artifactsrc);");
    5758         [ #  # ]:          0 :       extra_ddl.push_back("drop index if exists " BUILDIDS "_r_sref_arc;");
    5759                 :            : 
    5760                 :            :       // NB: we don't maxigroom the _files interning table.  It'd require a temp index on all the
    5761                 :            :       // tables that have file foreign-keys, which is a lot.
    5762                 :            : 
    5763                 :            :       // NB: with =delete, may take up 3x disk space total during vacuum process
    5764                 :            :       //     vs.  =off (only 2x but may corrupt database if program dies mid-vacuum)
    5765                 :            :       //     vs.  =wal (>3x observed, but safe)
    5766         [ #  # ]:          0 :       extra_ddl.push_back("pragma journal_mode=delete;");
    5767         [ #  # ]:          0 :       extra_ddl.push_back("vacuum;");
    5768         [ #  # ]:          0 :       extra_ddl.push_back("pragma journal_mode=wal;");
    5769                 :            :     }
    5770                 :            : 
    5771                 :            :   // run extra -D sql if given
    5772         [ +  + ]:         80 :   if (! passive_p)
    5773         [ -  + ]:         78 :     for (auto&& i: extra_ddl)
    5774                 :            :       {
    5775         [ #  # ]:          0 :         if (verbose > 1)
    5776   [ #  #  #  # ]:          0 :           obatched(clog) << "extra ddl:\n" << i << endl;
    5777                 :          0 :         rc = sqlite3_exec (db, i.c_str(), NULL, NULL, NULL);
    5778   [ #  #  #  # ]:          0 :         if (rc != SQLITE_OK && rc != SQLITE_DONE && rc != SQLITE_ROW)
    5779                 :          0 :           error (0, 0,
    5780                 :            :                  "warning: cannot run database extra ddl %s: %s", i.c_str(), sqlite3_errmsg(db));
    5781                 :            : 
    5782         [ #  # ]:          0 :         if (maxigroom)
    5783         [ #  # ]:          0 :           obatched(clog) << "maxigroomed database" << endl;
    5784                 :            :       }
    5785                 :            : 
    5786         [ +  + ]:         80 :   if (! passive_p)
    5787   [ +  -  +  - ]:        156 :     obatched(clog) << "search concurrency " << concurrency << endl;
    5788                 :         80 :   obatched(clog) << "webapi connection pool " << connection_pool
    5789   [ +  -  -  +  :         80 :                  << (connection_pool ? "" : " (unlimited)") << endl;
             +  -  +  - ]
    5790         [ +  + ]:         80 :   if (! passive_p) {
    5791   [ +  -  +  - ]:        156 :     obatched(clog) << "rescan time " << rescan_s << endl;
    5792   [ +  -  +  - ]:        156 :     obatched(clog) << "scan checkpoint " << scan_checkpoint << endl;
    5793                 :            :   }
    5794   [ +  -  +  - ]:        160 :   obatched(clog) << "fdcache mbs " << fdcache_mbs << endl;
    5795   [ +  -  +  - ]:        160 :   obatched(clog) << "fdcache prefetch " << fdcache_prefetch << endl;
    5796   [ +  -  +  - ]:        160 :   obatched(clog) << "fdcache tmpdir " << tmpdir << endl;
    5797   [ +  -  +  - ]:        160 :   obatched(clog) << "fdcache tmpdir min% " << fdcache_mintmp << endl;
    5798         [ +  + ]:         80 :   if (! passive_p)
    5799   [ +  -  +  - ]:        156 :     obatched(clog) << "groom time " << groom_s << endl;
    5800   [ +  -  +  - ]:        160 :   obatched(clog) << "forwarded ttl limit " << forwarded_ttl_limit << endl;
    5801                 :            : 
    5802         [ +  + ]:         80 :   if (scan_archives.size()>0)
    5803                 :            :     {
    5804                 :         56 :       obatched ob(clog);
    5805         [ +  - ]:         56 :       auto& o = ob << "accepting archive types ";
    5806         [ +  + ]:        174 :       for (auto&& arch : scan_archives)
    5807   [ +  -  +  -  :        118 :         o << arch.first << "(" << arch.second << ") ";
             +  -  +  - ]
    5808         [ +  - ]:         56 :       o << endl;
    5809                 :         56 :     }
    5810                 :         80 :   const char* du = getenv(DEBUGINFOD_URLS_ENV_VAR);
    5811   [ +  +  +  + ]:         80 :   if (du && du[0] != '\0') // set to non-empty string?
    5812   [ +  -  +  - ]:         32 :     obatched(clog) << "upstream debuginfod servers: " << du << endl;
    5813                 :            : 
    5814         [ +  + ]:         80 :   vector<pthread_t> all_threads;
    5815                 :            : 
    5816         [ +  + ]:         80 :   if (! passive_p)
    5817                 :            :     {
    5818                 :         78 :       pthread_t pt;
    5819                 :         78 :       rc = pthread_create (& pt, NULL, thread_main_groom, NULL);
    5820         [ -  + ]:         78 :       if (rc)
    5821                 :          0 :         error (EXIT_FAILURE, rc, "cannot spawn thread to groom database\n");
    5822                 :            :       else
    5823                 :            :         {
    5824                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    5825                 :         78 :           (void) pthread_setname_np (pt, "groom");
    5826                 :            : #endif
    5827         [ +  - ]:         78 :           all_threads.push_back(pt);
    5828                 :            :         }
    5829                 :            : 
    5830   [ +  +  +  + ]:         78 :       if (scan_files || scan_archives.size() > 0)
    5831                 :            :         {
    5832         [ +  - ]:         72 :           if (scan_checkpoint > 0)
    5833         [ +  - ]:         72 :             scan_barrier = new sqlite_checkpoint_pb(concurrency, (unsigned) scan_checkpoint);
    5834                 :            : 
    5835                 :         72 :           rc = pthread_create (& pt, NULL, thread_main_fts_source_paths, NULL);
    5836         [ -  + ]:         72 :           if (rc)
    5837                 :          0 :             error (EXIT_FAILURE, rc, "cannot spawn thread to traverse source paths\n");
    5838                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    5839                 :         72 :           (void) pthread_setname_np (pt, "traverse");
    5840                 :            : #endif
    5841         [ +  - ]:         72 :           all_threads.push_back(pt);
    5842                 :            : 
    5843         [ +  + ]:        360 :           for (unsigned i=0; i<concurrency; i++)
    5844                 :            :             {
    5845                 :        288 :               rc = pthread_create (& pt, NULL, thread_main_scanner, NULL);
    5846         [ -  + ]:        288 :               if (rc)
    5847                 :          0 :                 error (EXIT_FAILURE, rc, "cannot spawn thread to scan source files / archives\n");
    5848                 :            : #ifdef HAVE_PTHREAD_SETNAME_NP
    5849                 :        288 :               (void) pthread_setname_np (pt, "scan");
    5850                 :            : #endif
    5851         [ +  - ]:        288 :               all_threads.push_back(pt);
    5852                 :            :             }
    5853                 :            :         }
    5854                 :            :     }
    5855                 :            :   
    5856                 :            :   /* Trivial main loop! */
    5857   [ +  -  +  - ]:         80 :   set_metric("ready", 1);
    5858         [ +  + ]:        224 :   while (! interrupted)
    5859         [ +  - ]:        144 :     pause ();
    5860         [ +  - ]:         80 :   scanq.nuke(); // wake up any remaining scanq-related threads, let them die
    5861   [ +  +  +  - ]:         80 :   if (scan_barrier) scan_barrier->nuke(); // ... in case they're stuck in a barrier
    5862   [ +  -  +  - ]:         80 :   set_metric("ready", 0);
    5863                 :            : 
    5864         [ +  - ]:         80 :   if (verbose)
    5865   [ +  -  +  -  :        160 :     obatched(clog) << "stopping" << endl;
                   -  - ]
    5866                 :            : 
    5867                 :            :   /* Join all our threads. */
    5868         [ +  + ]:        518 :   for (auto&& it : all_threads)
    5869         [ +  - ]:        438 :     pthread_join (it, NULL);
    5870                 :            : 
    5871                 :            :   /* Stop all the web service threads. */
    5872   [ +  -  +  - ]:         80 :   if (d46) MHD_stop_daemon (d46);
    5873   [ -  +  -  - ]:         80 :   if (d4) MHD_stop_daemon (d4);
    5874                 :            : 
    5875         [ +  + ]:         80 :   if (! passive_p)
    5876                 :            :     {
    5877                 :            :       /* With all threads known dead, we can clean up the global resources. */
    5878         [ +  - ]:         78 :       rc = sqlite3_exec (db, DEBUGINFOD_SQLITE_CLEANUP_DDL, NULL, NULL, NULL);
    5879         [ -  + ]:         78 :       if (rc != SQLITE_OK)
    5880                 :            :         {
    5881   [ #  #  #  # ]:          0 :           error (0, 0,
    5882                 :            :                  "warning: cannot run database cleanup ddl: %s", sqlite3_errmsg(db));
    5883                 :            :         }
    5884                 :            :     }
    5885                 :            : 
    5886         [ +  - ]:         80 :   debuginfod_pool_groom ();
    5887         [ +  + ]:         80 :   delete scan_barrier;
    5888                 :            : 
    5889                 :            :   // NB: no problem with unconditional free here - an earlier failed regcomp would exit program
    5890         [ +  - ]:         80 :   (void) regfree (& file_include_regex);
    5891         [ +  - ]:         80 :   (void) regfree (& file_exclude_regex);
    5892                 :            : 
    5893                 :         80 :   sqlite3 *database = db;
    5894                 :         80 :   sqlite3 *databaseq = dbq;
    5895                 :         80 :   db = dbq = 0; // for signal_handler not to freak
    5896         [ +  - ]:         80 :   (void) sqlite3_close (databaseq);
    5897         [ +  + ]:         80 :   if (! passive_p)
    5898         [ +  - ]:         78 :     (void) sqlite3_close (database);
    5899                 :            : 
    5900         [ +  + ]:         80 :   return 0;
    5901                 :         80 : }

Generated by: LCOV version 1.16