LCOV - code coverage report
Current view: top level - debuginfod - debuginfod.cxx (source / functions) Hit Total Coverage
Test: elfutils-0.191 Lines: 1908 2245 85.0 %
Date: 2024-05-10 18:10:01 Functions: 90 99 90.9 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 2465 5752 42.9 %

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

Generated by: LCOV version 1.16