LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Hit Total Coverage
Test: elfutils-0.191 Lines: 2272 2707 83.9 %
Date: 2024-08-16 23:34:33 Functions: 102 112 91.1 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 2839 6767 42.0 %

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

Generated by: LCOV version 1.16