forked from h4ck3rm1k3/systemtap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstap-serverd.cxx
2641 lines (2355 loc) · 78 KB
/
stap-serverd.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
SSL server program listens on a port, accepts client connection, reads
the data into a temporary file, calls the systemtap translator and
then transmits the resulting file back to the client.
Copyright (C) 2011-2014 Red Hat Inc.
This file is part of systemtap, and is free software. You can
redistribute it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <fstream>
#include <string>
#include <cerrno>
#include <cassert>
#include <climits>
#include <iostream>
#include <map>
extern "C" {
#include <unistd.h>
#include <getopt.h>
#include <wordexp.h>
#include <glob.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <pwd.h>
#include <semaphore.h>
#include <nspr.h>
#include <ssl.h>
#include <nss.h>
#include <keyhi.h>
#include <regex.h>
#include <dirent.h>
#include <string.h>
#include <sys/ioctl.h>
#if HAVE_AVAHI
#include <avahi-client/publish.h>
#include <avahi-common/alternative.h>
#include <avahi-common/thread-watch.h>
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>
#include <avahi-common/domain.h>
#include <sys/inotify.h>
#endif
}
#include "util.h"
#include "nsscommon.h"
#include "cscommon.h"
#include "cmdline.h"
using namespace std;
static void cleanup ();
static PRStatus spawn_and_wait (const vector<string> &argv, int *result,
const char* fd0, const char* fd1, const char* fd2,
const char *pwd, const vector<string>& envVec = vector<string> ());
#define MOK_PUBLIC_CERT_NAME "signing_key.x509"
#define MOK_PUBLIC_CERT_FILE "/" MOK_PUBLIC_CERT_NAME
#define MOK_PRIVATE_CERT_NAME "signing_key.priv"
#define MOK_PRIVATE_CERT_FILE "/" MOK_PRIVATE_CERT_NAME
#define MOK_CONFIG_FILE "/x509.genkey"
// MOK_CONFIG_TEXT is the default MOK config text used when creating
// new MOKs. This text is saved to the MOK config file. Once we've
// created it, the server administrator can modify it.
#define MOK_CONFIG_TEXT \
"[ req ]\n" \
"default_bits = 4096\n" \
"distinguished_name = req_distinguished_name\n" \
"prompt = no\n" \
"x509_extensions = myexts\n" \
"\n" \
"[ req_distinguished_name ]\n" \
"O = Systemtap\n" \
"CN = Systemtap module signing key\n" \
"\n" \
"[ myexts ]\n" \
"basicConstraints=critical,CA:FALSE\n" \
"keyUsage=digitalSignature\n" \
"subjectKeyIdentifier=hash\n" \
"authorityKeyIdentifier=keyid\n"
/* getopt variables */
extern int optind;
/* File scope statics. Set during argument parsing and initialization. */
static bool use_db_password;
static unsigned short port;
static long max_threads;
static string cert_db_path;
static string stap_options;
static string uname_r;
static string kernel_build_tree;
static string arch;
static string cert_serial_number;
static string B_options;
static string I_options;
static string R_option;
static string D_options;
static bool keep_temp;
static string mok_path;
sem_t sem_client;
static int pending_interrupts;
#define CONCURRENCY_TIMEOUT_S 3
// Message handling.
// Server_error messages are printed to stderr and logged, if requested.
static void
server_error (const string &msg, int logit = true)
{
cerr << msg << endl << flush;
// Log it, but avoid repeated messages to the terminal.
if (logit && log_ok ())
log (msg);
}
// client_error messages are treated as server errors and also printed to the client's stderr.
static void
client_error (const string &msg, string stapstderr)
{
server_error (msg);
if (! stapstderr.empty ())
{
ofstream errfile;
errfile.open (stapstderr.c_str (), ios_base::app);
if (! errfile.good ())
server_error (_F("Could not open client stderr file %s: %s", stapstderr.c_str (),
strerror (errno)));
else
errfile << "Server: " << msg << endl;
// NB: No need to close errfile
}
}
// Messages from the nss common code are treated as server errors.
extern "C"
void
nsscommon_error (const char *msg, int logit)
{
server_error (msg, logit);
}
// Fatal errors are treated as server errors but also result in termination
// of the server.
static void
fatal (const string &msg)
{
server_error (msg);
cleanup ();
exit (1);
}
// Argument handling
static void
process_a (const string &arg)
{
arch = arg;
stap_options += " -a " + arg;
}
static void
process_r (const string &arg)
{
if (arg[0] == '/') // fully specified path
{
kernel_build_tree = arg;
uname_r = kernel_release_from_build_tree (arg);
}
else
{
kernel_build_tree = "/lib/modules/" + arg + "/build";
uname_r = arg;
}
stap_options += " -r " + arg; // Pass the argument to stap directly.
}
static void
process_log (const char *arg)
{
start_log (arg);
}
static void
parse_options (int argc, char **argv)
{
// Examine the command line. This is the command line for us (stap-serverd) not the command
// line for spawned stap instances.
optind = 1;
while (true)
{
char *num_endptr;
long port_tmp;
// NB: The values of these enumerators must not conflict with the values of ordinary
// characters, since those are returned by getopt_long for short options.
enum {
LONG_OPT_PORT = 256,
LONG_OPT_SSL,
LONG_OPT_LOG,
LONG_OPT_MAXTHREADS
};
static struct option long_options[] = {
{ "port", 1, NULL, LONG_OPT_PORT },
{ "ssl", 1, NULL, LONG_OPT_SSL },
{ "log", 1, NULL, LONG_OPT_LOG },
{ "max-threads", 1, NULL, LONG_OPT_MAXTHREADS },
{ NULL, 0, NULL, 0 }
};
int grc = getopt_long (argc, argv, "a:B:D:I:kPr:R:", long_options, NULL);
if (grc < 0)
break;
switch (grc)
{
case 'a':
process_a (optarg);
break;
case 'B':
B_options += string (" -") + (char)grc + optarg;
stap_options += string (" -") + (char)grc + optarg;
break;
case 'D':
D_options += string (" -") + (char)grc + optarg;
stap_options += string (" -") + (char)grc + optarg;
break;
case 'I':
I_options += string (" -") + (char)grc + optarg;
stap_options += string (" -") + (char)grc + optarg;
break;
case 'k':
keep_temp = true;
break;
case 'P':
use_db_password = true;
break;
case 'r':
process_r (optarg);
break;
case 'R':
R_option = string (" -") + (char)grc + optarg;
stap_options += string (" -") + (char)grc + optarg;
break;
case LONG_OPT_PORT:
port_tmp = strtol (optarg, &num_endptr, 10);
if (*num_endptr != '\0')
fatal (_F("%s: cannot parse number '--port=%s'", argv[0], optarg));
else if (port_tmp < 0 || port_tmp > 65535)
fatal (_F("%s: invalid entry: port must be between 0 and 65535 '--port=%s'", argv[0],
optarg));
else
port = (unsigned short) port_tmp;
break;
case LONG_OPT_SSL:
cert_db_path = optarg;
break;
case LONG_OPT_LOG:
process_log (optarg);
break;
case LONG_OPT_MAXTHREADS:
max_threads = strtol (optarg, &num_endptr, 0);
if (*num_endptr != '\0')
fatal (_F("%s: cannot parse number '--max-threads=%s'", argv[0], optarg));
else if (max_threads < 0)
fatal (_F("%s: invalid entry: max threads must not be negative '--max-threads=%s'",
argv[0], optarg));
break;
case '?':
// Invalid/unrecognized option given. Message has already been issued.
break;
default:
// Reached when one added a getopt option but not a corresponding switch/case:
if (optarg)
server_error (_F("%s: unhandled option '%c %s'", argv[0], (char)grc, optarg));
else
server_error (_F("%s: unhandled option '%c'", argv[0], (char)grc));
break;
}
}
for (int i = optind; i < argc; i++)
server_error (_F("%s: unrecognized argument '%s'", argv[0], argv[i]));
}
static string
server_cert_file ()
{
return server_cert_db_path () + "/stap.cert";
}
// Signal handling. When an interrupt is received, kill any spawned processes
// and exit.
extern "C"
void
handle_interrupt (int sig)
{
pending_interrupts++;
if(pending_interrupts >= 2)
{
log (_F("Received another signal %d, exiting (forced)", sig));
_exit(0);
}
log (_F("Received signal %d, exiting", sig));
}
static void
setup_signals (sighandler_t handler)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler;
sigemptyset (&sa.sa_mask);
if (handler != SIG_IGN)
{
sigaddset (&sa.sa_mask, SIGHUP);
sigaddset (&sa.sa_mask, SIGPIPE);
sigaddset (&sa.sa_mask, SIGINT);
sigaddset (&sa.sa_mask, SIGTERM);
sigaddset (&sa.sa_mask, SIGTTIN);
sigaddset (&sa.sa_mask, SIGTTOU);
sigaddset (&sa.sa_mask, SIGXFSZ);
sigaddset (&sa.sa_mask, SIGXCPU);
}
sa.sa_flags = SA_RESTART;
sigaction (SIGHUP, &sa, NULL);
sigaction (SIGPIPE, &sa, NULL);
sigaction (SIGINT, &sa, NULL);
sigaction (SIGTERM, &sa, NULL);
sigaction (SIGTTIN, &sa, NULL);
sigaction (SIGTTOU, &sa, NULL);
sigaction (SIGXFSZ, &sa, NULL);
sigaction (SIGXCPU, &sa, NULL);
}
// Does the server contain a valid directory for the MOK fingerprint?
bool
mok_dir_valid_p (string mok_fingerprint, bool verbose)
{
string mok_dir = mok_path + "/" + mok_fingerprint;
DIR *dirp = opendir (mok_dir.c_str());
if (dirp == NULL)
{
// We can't open the directory. Just quit.
if (verbose)
server_error (_F("Could not open server MOK fingerprint directory %s: %s",
mok_dir.c_str(), strerror(errno)));
return false;
}
// Find both the x509 certificate and private key files.
bool priv_found = false;
bool cert_found = false;
struct dirent *direntp;
while ((direntp = readdir (dirp)) != NULL)
{
bool reg_file = false;
if (direntp->d_type == DT_REG)
reg_file = true;
else if (direntp->d_type == DT_UNKNOWN)
{
struct stat tmpstat;
// If the filesystem doesn't support d_type, we'll have to
// call stat().
stat((mok_dir + "/" + direntp->d_name).c_str (), &tmpstat);
if (S_ISREG(tmpstat.st_mode))
reg_file = true;
}
if (! priv_found && reg_file
&& strcmp (direntp->d_name, MOK_PRIVATE_CERT_NAME) == 0)
{
priv_found = true;
continue;
}
if (! cert_found && reg_file
&& strcmp (direntp->d_name, MOK_PUBLIC_CERT_NAME) == 0)
{
cert_found = true;
continue;
}
if (priv_found && cert_found)
break;
}
closedir (dirp);
if (! priv_found || ! cert_found)
{
// We didn't find one (or both) of the required files. Quit.
if (verbose)
server_error (_F("Could not find server MOK files in directory %s",
mok_dir.c_str ()));
return false;
}
// Grab info from the cert.
string fingerprint;
if (read_cert_info_from_file (mok_dir + MOK_PUBLIC_CERT_FILE, fingerprint)
== SECSuccess)
{
// Make sure the fingerprint from the certificate matches the
// directory name.
if (fingerprint != mok_fingerprint)
{
if (verbose)
server_error (_F("Server MOK directory name '%s' doesn't match fingerprint from certificate %s",
mok_dir.c_str(), fingerprint.c_str()));
return false;
}
}
return true;
}
// Get the list of MOK fingerprints on the server. If
// 'only_one_needed' is true, just return the first MOK.
static void
get_server_mok_fingerprints(vector<string> &mok_fingerprints, bool verbose,
bool only_one_needed)
{
DIR *dirp;
struct dirent *direntp;
vector<string> temp;
// Clear the vector.
mok_fingerprints.clear ();
// The directory of machine owner keys (MOK) is optional, so if it
// doesn't exist, we don't worry about it.
dirp = opendir (mok_path.c_str ());
if (dirp == NULL)
{
// If the error isn't ENOENT (Directory does not exist), we've got
// a non-fatal error.
if (errno != ENOENT)
server_error (_F("Could not open server MOK directory %s: %s",
mok_path.c_str (), strerror (errno)));
return;
}
// Create a regular expression object to verify MOK fingerprints
// directory name.
regex_t checkre;
if ((regcomp (&checkre, "^[0-9a-f]{2}(:[0-9a-f]{2})+$",
REG_EXTENDED | REG_NOSUB) != 0))
{
// Not fatal, just ignore the MOK fingerprints.
server_error (_F("Error in MOK fingerprint regcomp: %s",
strerror (errno)));
closedir (dirp);
return;
}
// We've opened the directory, so read all the directory names from
// it.
while ((direntp = readdir (dirp)) != NULL)
{
// We're only interested in directories (of key files).
if (direntp->d_type != DT_DIR)
{
if (direntp->d_type == DT_UNKNOWN)
{
// If the filesystem doesn't support d_type, we'll have to
// call stat().
struct stat tmpstat;
stat((mok_path + "/" + direntp->d_name).c_str (), &tmpstat);
if (!S_ISDIR(tmpstat.st_mode))
continue;
}
else
continue;
}
// We've got a directory. If the directory name isn't in the right
// format for a MOK fingerprint, skip it.
if ((regexec (&checkre, direntp->d_name, (size_t) 0, NULL, 0) != 0))
continue;
// OK, we've got a directory name in the right format, so save it.
temp.push_back (string (direntp->d_name));
}
regfree (&checkre);
closedir (dirp);
// At this point, we've got a list of directories with names in the
// proper format. Make sure each directory contains a x509
// certificate and private key file.
vector<string>::const_iterator it;
for (it = temp.begin (); it != temp.end (); it++)
{
if (mok_dir_valid_p (*it, true))
{
// Save the info.
mok_fingerprints.push_back (*it);
if (verbose)
server_error (_F("Found MOK with fingerprint '%s'", it->c_str ()));
if (only_one_needed)
break;
}
}
return;
}
#if HAVE_AVAHI
static AvahiEntryGroup *avahi_group = NULL;
static AvahiThreadedPoll *avahi_threaded_poll = NULL;
static char *avahi_service_name = NULL;
static const char * const avahi_service_tag = "_stap._tcp";
static AvahiClient *avahi_client = 0;
static int avahi_collisions = 0;
static int inotify_fd = -1;
static AvahiWatch *avahi_inotify_watch = NULL;
static void create_services (AvahiClient *c);
static int
rename_service ()
{
/*
* Each service must have a unique name on the local network.
* When there is a collision, we try to rename the service.
* However, we need to limit the number of attempts, since the
* service namespace could be maliciously flooded with service
* names designed to maximize collisions.
* Arbitrarily choose a limit of 65535, which is the number of
* TCP ports.
*/
++avahi_collisions;
if (avahi_collisions >= 65535) {
server_error (_F("Too many service name collisions for Avahi service %s",
avahi_service_tag));
return -EBUSY;
}
/*
* Use the avahi-supplied function to generate a new service name.
*/
char *n = avahi_alternative_service_name(avahi_service_name);
server_error (_F("Avahi service name collision, renaming service '%s' to '%s'",
avahi_service_name, n));
avahi_free(avahi_service_name);
avahi_service_name = n;
return 0;
}
static void
entry_group_callback (
AvahiEntryGroup *g,
AvahiEntryGroupState state,
AVAHI_GCC_UNUSED void *userdata
) {
assert(g == avahi_group || avahi_group == NULL);
avahi_group = g;
// Called whenever the entry group state changes.
switch (state)
{
case AVAHI_ENTRY_GROUP_ESTABLISHED:
// The entry group has been established successfully.
log (_F("Avahi service '%s' successfully established.", avahi_service_name));
break;
case AVAHI_ENTRY_GROUP_COLLISION:
// A service name collision with a remote service happened.
// Unfortunately, we don't know which entry collided.
// We need to rename them all and recreate the services.
if (rename_service () == 0)
create_services (avahi_entry_group_get_client (g));
break;
case AVAHI_ENTRY_GROUP_FAILURE:
// Some kind of failure happened.
server_error (_F("Avahi entry group failure: %s",
avahi_strerror (avahi_client_errno (avahi_entry_group_get_client (g)))));
break;
case AVAHI_ENTRY_GROUP_UNCOMMITED:
case AVAHI_ENTRY_GROUP_REGISTERING:
break;
}
}
static void
create_services (AvahiClient *c)
{
assert (c);
// Create a new entry group, if necessary, or reset the existing one.
if (! avahi_group)
{
if (! (avahi_group = avahi_entry_group_new (c, entry_group_callback, NULL)))
{
server_error (_F("avahi_entry_group_new () failed: %s",
avahi_strerror (avahi_client_errno (c))));
return;
}
}
else
avahi_entry_group_reset(avahi_group);
// Contruct the information needed for our service.
log (_F("Adding Avahi service '%s'", avahi_service_name));
// Create the txt tags that will be registered with our service.
string sysinfo = "sysinfo=" + uname_r + " " + arch;
string certinfo = "certinfo=" + cert_serial_number;
string version = string ("version=") + CURRENT_CS_PROTOCOL_VERSION;;
string optinfo = "optinfo=";
string separator;
// These option strings already have a leading space.
if (! R_option.empty ())
{
optinfo += R_option.substr(1);
separator = " ";
}
if (! B_options.empty ())
{
optinfo += separator + B_options.substr(1);
separator = " ";
}
if (! D_options.empty ())
{
optinfo += separator + D_options.substr(1);
separator = " ";
}
if (! I_options.empty ())
optinfo += separator + I_options.substr(1);
// Create an avahi string list with the info we have so far.
vector<string> mok_fingerprints;
AvahiStringList *strlst = avahi_string_list_new(sysinfo.c_str (),
optinfo.c_str (),
version.c_str (),
certinfo.c_str (), NULL);
if (strlst == NULL)
{
server_error (_("Failed to allocate string list"));
goto fail;
}
// Add server MOK info, if available.
get_server_mok_fingerprints (mok_fingerprints, true, false);
if (! mok_fingerprints.empty())
{
vector<string>::const_iterator it;
for (it = mok_fingerprints.begin(); it != mok_fingerprints.end(); it++)
{
string tmp = "mok_info=" + *it;
strlst = avahi_string_list_add(strlst, tmp.c_str ());
if (strlst == NULL)
{
server_error (_("Failed to add a string to the list"));
goto fail;
}
}
}
// We will now add our service to the entry group.
// Loop until no collisions.
int ret;
for (;;) {
ret = avahi_entry_group_add_service_strlst (avahi_group,
AVAHI_IF_UNSPEC,
AVAHI_PROTO_UNSPEC,
(AvahiPublishFlags)0,
avahi_service_name,
avahi_service_tag,
NULL, NULL, port, strlst);
if (ret == AVAHI_OK)
break; // success!
if (ret == AVAHI_ERR_COLLISION)
{
// A service name collision with a local service happened.
// Pick a new name.
if (rename_service () < 0) {
// Too many collisions. Message already issued.
goto fail;
}
continue; // try again.
}
server_error (_F("Failed to add %s service: %s",
avahi_service_tag, avahi_strerror (ret)));
goto fail;
}
// Tell the server to register the service.
if ((ret = avahi_entry_group_commit (avahi_group)) < 0)
{
server_error (_F("Failed to commit avahi entry group: %s", avahi_strerror (ret)));
goto fail;
}
avahi_string_list_free(strlst);
return;
fail:
avahi_entry_group_reset (avahi_group);
avahi_string_list_free(strlst);
}
static void avahi_cleanup_client () {
// This also frees the entry group, if any
if (avahi_client) {
avahi_client_free (avahi_client);
avahi_client = 0;
avahi_group = 0;
}
}
static void
client_callback (AvahiClient *c, AvahiClientState state, AVAHI_GCC_UNUSED void * userdata)
{
assert(c);
// Called whenever the client or server state changes.
switch (state)
{
case AVAHI_CLIENT_S_RUNNING:
// The server has startup successfully and registered its host
// name on the network, so it's time to create our services.
create_services (c);
break;
case AVAHI_CLIENT_FAILURE:
server_error (_F("Avahi client failure: %s", avahi_strerror (avahi_client_errno (c))));
if (avahi_client_errno (c) == AVAHI_ERR_DISCONNECTED)
{
// The client has been disconnected; probably because the avahi daemon has been
// restarted. We can free the client here and try to reconnect using a new one.
// Passing AVAHI_CLIENT_NO_FAIL allows the new client to be
// created, even if the avahi daemon is not running. Our service will be advertised
// if/when the daemon is started.
avahi_cleanup_client ();
int error;
avahi_client = avahi_client_new (avahi_threaded_poll_get (avahi_threaded_poll),
(AvahiClientFlags)AVAHI_CLIENT_NO_FAIL,
client_callback, NULL, & error);
}
break;
case AVAHI_CLIENT_S_COLLISION:
// Let's drop our registered services. When the server is back
// in AVAHI_SERVER_RUNNING state we will register them
// again with the new host name.
// Fall through ...
case AVAHI_CLIENT_S_REGISTERING:
// The server records are now being established. This
// might be caused by a host name change. We need to wait
// for our own records to register until the host name is
// properly esatblished.
if (avahi_group)
avahi_entry_group_reset (avahi_group);
break;
case AVAHI_CLIENT_CONNECTING:
// The avahi-daemon is not currently running. Our service will be advertised
// if/when the deamon is started.
server_error (_F("The Avahi daemon is not running. Avahi service '%s' will be established when the deamon is started", avahi_service_name));
break;
}
}
static void
inotify_callback (AvahiWatch *w, int fd, AvahiWatchEvent event, void *userdata)
{
struct inotify_event in_events[10];
ssize_t rc;
// Drain the inotify file. Notice we don't really care what changed,
// we just needed to know that something changed.
do
{
rc = read (fd, in_events, sizeof (in_events));
} while (rc > 0);
// Re-create the services.
if (avahi_client && (avahi_client_get_state (avahi_client)
== AVAHI_CLIENT_S_RUNNING))
create_services (avahi_client);
}
static void
avahi_cleanup ()
{
if (avahi_service_name)
log (_F("Removing Avahi service '%s'", avahi_service_name));
// Stop the avahi client, if it's running
if (avahi_threaded_poll)
avahi_threaded_poll_stop (avahi_threaded_poll);
// Clean up the avahi objects. The order of freeing these is significant.
avahi_cleanup_client ();
if (avahi_inotify_watch)
{
const AvahiPoll *poll = avahi_threaded_poll_get (avahi_threaded_poll);
if (poll)
poll->watch_free (avahi_inotify_watch);
avahi_inotify_watch = NULL;
}
if (inotify_fd >= 0)
{
close (inotify_fd);
inotify_fd = -1;
}
if (avahi_threaded_poll) {
avahi_threaded_poll_free (avahi_threaded_poll);
avahi_threaded_poll = 0;
}
if (avahi_service_name) {
avahi_free (avahi_service_name);
avahi_service_name = 0;
}
}
// The entry point for the avahi client thread.
static void
avahi_publish_service (CERTCertificate *cert)
{
// Get the certificate serial number.
cert_serial_number = get_cert_serial_number (cert);
// Construct the Avahi service name.
char host[HOST_NAME_MAX + 1];
gethostname (host, sizeof(host));
host[sizeof(host) - 1] = '\0';
string buf;
buf = string ("Systemtap Compile Server on ") + host;
// Make sure the service name is valid
const char *initial_service_name = buf.c_str ();
if (! avahi_is_valid_service_name (initial_service_name)) {
// The only restriction on service names is that the buffer must not exceed
// AVAHI_LABEL_MAX in size, which means that the name cannot be longer than
// AVAHI_LABEL_MAX-1 in length.
assert (strlen (initial_service_name) >= AVAHI_LABEL_MAX);
buf = buf.substr (0, AVAHI_LABEL_MAX - 1);
initial_service_name = buf.c_str ();
assert (avahi_is_valid_service_name (initial_service_name));
}
avahi_service_name = avahi_strdup (initial_service_name);
// Allocate main loop object.
if (! (avahi_threaded_poll = avahi_threaded_poll_new ()))
{
server_error (_("Failed to create avahi threaded poll object."));
return;
}
// Always allocate a new client. Passing AVAHI_CLIENT_NO_FAIL allows the client to be
// created, even if the avahi daemon is not running. Our service will be advertised
// if/when the daemon is started.
int error;
avahi_client = avahi_client_new (avahi_threaded_poll_get (avahi_threaded_poll),
(AvahiClientFlags)AVAHI_CLIENT_NO_FAIL,
client_callback, NULL, & error);
// Check whether creating the client object succeeded.
if (! avahi_client)
{
server_error (_F("Failed to create avahi client: %s", avahi_strerror(error)));
return;
}
// Watch the server MOK directory for any changes.
#if defined(IN_CLOEXEC) && defined(IN_NONBLOCK)
inotify_fd = inotify_init1 (IN_CLOEXEC|IN_NONBLOCK);
#else
if ((inotify_fd = inotify_init ()) >= 0)
{
fcntl(inotify_fd, F_SETFD, FD_CLOEXEC);
fcntl(inotify_fd, F_SETFL, O_NONBLOCK);
}
#endif
if (inotify_fd < 0)
server_error (_F("Failed to initialize inotify: %s", strerror (errno)));
else
{
// We want to watch for new or removed MOK directories
// underneath mok_path. But, to do that, mok_path must exist.
if (create_dir (mok_path.c_str (), 0755) != 0)
server_error (_F("Unable to find or create the MOK directory %s: %s",
mok_path.c_str (), strerror (errno)));
// Watch mok_path for changes.
else if (inotify_add_watch (inotify_fd, mok_path.c_str (),
#ifdef IN_ONLYDIR
IN_ONLYDIR|
#endif
IN_CLOSE_WRITE|IN_DELETE|IN_DELETE_SELF|IN_MOVE)
< 0)
server_error (_F("Failed to add inotify watch: %s", strerror (errno)));
else
{
// When mok_path changes, call inotify_callback().
const AvahiPoll *poll = avahi_threaded_poll_get (avahi_threaded_poll);
if (!poll
|| ! (avahi_inotify_watch = poll->watch_new (poll, inotify_fd,
AVAHI_WATCH_IN,
inotify_callback,
NULL)))
server_error (_("Failed to create inotify watcher"));
}
}
// Run the main loop.
avahi_threaded_poll_start (avahi_threaded_poll);
return;
}
#endif // HAVE_AVAHI
static void
advertise_presence (CERTCertificate *cert __attribute ((unused)))
{
#if HAVE_AVAHI
avahi_publish_service (cert);
#else
server_error (_("Unable to advertise presence on the network. Avahi is not available"));
#endif
}
static void
unadvertise_presence ()
{
#if HAVE_AVAHI
avahi_cleanup ();
#endif
}
static void
initialize (int argc, char **argv) {
pending_interrupts = 0;
setup_signals (& handle_interrupt);
// Seed the random number generator. Used to generate noise used during key generation.
srand (time (NULL));
// Initial values.
use_db_password = false;
port = 0;
max_threads = sysconf( _SC_NPROCESSORS_ONLN ); // Default to number of processors
keep_temp = false;
struct utsname utsname;
uname (& utsname);
uname_r = utsname.release;
kernel_build_tree = "/lib/modules/" + uname_r + "/build";
arch = normalize_machine (utsname.machine);
// Parse the arguments. This also starts the server log, if any, and should be done before
// any messages are issued.
parse_options (argc, argv);
// PR11197: security prophylactics.
// Reject use as root, except via a special environment variable.
if (! getenv ("STAP_PR11197_OVERRIDE")) {
if (geteuid () == 0)
fatal ("For security reasons, invocation of stap-serverd as root is not supported.");
}
struct passwd *pw = getpwuid (geteuid ());
if (! pw)
fatal (_F("Unable to determine effective user name: %s", strerror (errno)));
string username = pw->pw_name;
pid_t pid = getpid ();
log (_F("===== compile server pid %d starting as %s =====", pid, username.c_str ()));
// Where is the ssl certificate/key database?
if (cert_db_path.empty ())
cert_db_path = server_cert_db_path ();
// Make sure NSPR is initialized. Must be done before NSS is initialized
PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
/* Set the cert database password callback. */
PK11_SetPasswordFunc (nssPasswordCallback);
// Where are the optional machine owner keys (MOK) this server
// knows about?
mok_path = server_cert_db_path() + "/moks";