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