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