LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Coverage Total Hit
Test: elfutils-0.194 Lines: 84.0 % 2795 2347
Test Date: 2025-12-05 15:45:14 Functions: 91.3 % 115 105
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 46.6 % 5269 2455

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

Generated by: LCOV version 2.0-1