-
-
Notifications
You must be signed in to change notification settings - Fork 708
/
Copy pathrun-bundle.c++
3430 lines (2933 loc) · 124 KB
/
run-bundle.c++
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
// Sandstorm - Personal Cloud Sandbox
// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <kj/main.h>
#include <kj/debug.h>
#include <kj/io.h>
#include <kj/parse/common.h>
#include <kj/parse/char.h>
#include <kj/encoding.h>
#include <capnp/schema.h>
#include <capnp/dynamic.h>
#include <capnp/serialize.h>
#include <capnp/compat/json.h>
#include <sandstorm/package.capnp.h>
#include <sandstorm/update-tool.capnp.h>
#include <sodium/randombytes.h>
#include <sodium/crypto_sign_ed25519.h>
#include <stdlib.h>
#include <signal.h>
#include <limits.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/signalfd.h>
#include <sys/wait.h>
#include <sys/sendfile.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
#include <sys/capability.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <linux/securebits.h>
#include <sched.h>
#include <grp.h>
#include <errno.h>
#include <fcntl.h>
#include <ctype.h>
#include <time.h>
#include <stdio.h> // rename()
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <dirent.h>
#include <arpa/inet.h>
#include "version.h"
#include "send-fd.h"
#include "supervisor.h"
#include "util.h"
#include "spk.h"
#include "backend.h"
#include "backup.h"
#include "gateway.h"
#include "config.h"
namespace sandstorm {
// We use SIGALRM to timeout waitpid()s.
static bool alarmed = false;
void alarmHandler(int) {
alarmed = true;
}
void registerAlarmHandler() {
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = &alarmHandler;
KJ_SYSCALL(sigaction(SIGALRM, &action, nullptr));
}
kj::AutoCloseFd prepareMonitoringLoop() {
// Prepare to run a loop where we monitor some children and also receive signals. Returns a
// signalfd.
// Set up signal mask to catch events that should lead to shutdown.
sigset_t sigmask;
KJ_SYSCALL(sigemptyset(&sigmask));
KJ_SYSCALL(sigaddset(&sigmask, SIGTERM));
KJ_SYSCALL(sigaddset(&sigmask, SIGINT)); // request front-end shutdown
KJ_SYSCALL(sigaddset(&sigmask, SIGCHLD));
KJ_SYSCALL(sigaddset(&sigmask, SIGHUP));
KJ_SYSCALL(sigprocmask(SIG_BLOCK, &sigmask, nullptr));
// Receive signals on a signalfd.
int sigfd;
KJ_SYSCALL(sigfd = signalfd(-1, &sigmask, SFD_CLOEXEC));
return kj::AutoCloseFd(sigfd);
}
static bool symlinkPointsInto(kj::StringPtr symlink, kj::StringPtr targetPrefix) {
// Returns true if the given path names a symlink whose target has the given prefix, false if
// it points elsewhere or doesn't exist or isn't a symlink.
retry:
char buffer[PATH_MAX];
ssize_t n = readlink(symlink.cStr(), buffer, sizeof(buffer) - 1);
if (n < 0) {
int error = errno;
switch (error) {
case ENOENT:
case ENOTDIR:
case EINVAL:
// File (or parent directory) dosen't exist or isn't a symlink.
return false;
case EINTR:
goto retry;
default:
KJ_FAIL_SYSCALL("readlink(symlink)", error, symlink);
}
} else {
buffer[n] = '\0';
return kj::StringPtr(buffer, n).startsWith(targetPrefix);
}
}
static bool fileHasLine(kj::StringPtr filename, kj::StringPtr expectedLine) {
// Returns true if the given text file contains a line matching exactly the given string.
auto file = raiiOpenIfExists(filename, O_RDONLY | O_CLOEXEC);
KJ_IF_MAYBE(f, file) {
for (auto& line: splitLines(readAll(*f))) {
if (line == expectedLine) {
return true;
}
}
// File doesn't contain line.
return false;
} else {
// File doesn't exist at all.
return false;
}
}
// =======================================================================================
// Process name setting.
//
// TODO(cleanup): Move this somewhere more reusable, maybe in KJ?
namespace {
// HACK: We grab the global argv pointer at startup so that we can overwrite argv[0] to set the
// process name.
kj::ArrayPtr<char> globalArgv;
__attribute__((constructor)) void stuff(int argc, char **argv) {
globalArgv = kj::arrayPtr(argv[0], argv[argc - 1] + strlen(argv[argc - 1]));
}
} // namespace
static void setProcessName(kj::StringPtr topSuffix, kj::StringPtr psSuffix) {
// Set process name as seen in "top". We only have 15 bytes to work with here (16 with NUL).
char oldname[16];
prctl(PR_GET_NAME, oldname);
char* slashPos = strchr(oldname, '/');
if (slashPos != nullptr) *slashPos = '\0';
prctl(PR_SET_NAME, kj::str(oldname, '/', topSuffix).cStr());
// Set process name as seen in "ps". This is weird because we have to overwrite the argv
// buffer, and we can only really be sure that the buffer is large enough to hold the args
// passed to the original process. Here we try to overwrite argv[1] through the end of the
// buffer with the suffix, but if we don't have enough space we cut it short or don't make
// any change. Note that args in the argv buffer are separated by NUL bytes.
size_t argv1Pos = strlen(globalArgv.begin()) + 1;
if (argv1Pos < globalArgv.size()) {
memcpy(globalArgv.begin() + argv1Pos, psSuffix.begin(),
kj::min(psSuffix.size(), globalArgv.size() - argv1Pos));
}
if (argv1Pos + psSuffix.size() < globalArgv.size()) {
memset(globalArgv.begin() + argv1Pos + psSuffix.size(), 0,
globalArgv.size() - argv1Pos - psSuffix.size());
}
}
// =======================================================================================
struct KernelVersion {
uint major;
uint minor;
};
KernelVersion getKernelVersion() {
struct utsname uts;
KJ_SYSCALL(uname(&uts));
kj::StringPtr release = uts.release;
auto parser = kj::parse::transform(kj::parse::sequence(
kj::parse::oneOrMore(kj::parse::digit),
kj::parse::exactChar<'.'>(),
kj::parse::oneOrMore(kj::parse::digit)),
[](kj::Array<char> major, kj::Array<char> minor) {
return KernelVersion {
KJ_ASSERT_NONNULL(parseUInt(kj::heapString(major), 10)),
KJ_ASSERT_NONNULL(parseUInt(kj::heapString(minor), 10))
};
});
kj::parse::IteratorInput<char, const char*> input(release.begin(), release.end());
KJ_IF_MAYBE(version, parser(input)) {
return *version;
} else {
KJ_FAIL_ASSERT("Couldn't parse kernel version.", release);
}
}
bool isKernelNewEnough() {
auto version = getKernelVersion();
if (version.major < 3 || (version.major == 3 && version.minor < 10)) {
// Insufficient kernel version.
return false;
}
return true;
}
bool isUserNsAvailable() {
Subprocess child([]() {
if (getuid() == 0) {
if (setuid(1000) < 0) {
// setuid() failed?
return 2;
}
}
if (unshare(CLONE_NEWUSER) < 0) {
return 1;
}
return 0;
});
int status = child.waitForExit();
switch (status) {
case 0:
return true;
case 1:
return false;
case 2:
KJ_LOG(ERROR, "setuid() failed when trying to test if unprivileged userns works");
return true;
default:
KJ_LOG(ERROR, "userns test process exited with unexpected status code", status);
return true;
}
}
class CurlRequest {
public:
explicit CurlRequest(kj::StringPtr url): url(kj::heapString(url)) {
int pipeFds[2];
KJ_SYSCALL(pipe(pipeFds));
kj::AutoCloseFd pipeInput(pipeFds[0]), pipeOutput(pipeFds[1]);
KJ_SYSCALL(pid = fork());
if (pid == 0) {
KJ_SYSCALL(dup2(pipeOutput, STDOUT_FILENO));
pipeInput = nullptr;
pipeOutput = nullptr;
KJ_SYSCALL(execlp("curl", "curl", isatty(STDERR_FILENO) ? "-f" : "-fs",
url.cStr(), EXEC_END_ARGS), url);
KJ_UNREACHABLE;
} else {
pipeFd = kj::mv(pipeInput);
}
}
explicit CurlRequest(kj::StringPtr url, int outFd): url(kj::heapString(url)) {
KJ_SYSCALL(pid = fork());
if (pid == 0) {
KJ_SYSCALL(dup2(outFd, STDOUT_FILENO));
KJ_SYSCALL(execlp("curl", "curl", isatty(STDERR_FILENO) ? "-f" : "-fs",
url.cStr(), EXEC_END_ARGS), url);
KJ_UNREACHABLE;
}
}
~CurlRequest() noexcept(false) {
if (pid == 0) return;
// Close the pipe first, in case the child is waiting for that.
pipeFd = nullptr;
int status;
KJ_SYSCALL(waitpid(pid, &status, 0)) { return; }
if (WIFEXITED(status)) {
int exitCode = WEXITSTATUS(status);
if (exitCode != 0) {
KJ_FAIL_ASSERT("curl failed", url, exitCode) { return; }
}
} else if (WIFSIGNALED(status)) {
int signalNumber = WTERMSIG(status);
KJ_FAIL_ASSERT("curl crashed", url, signalNumber) { return; }
} else {
KJ_FAIL_ASSERT("curl failed", url) { return; }
}
}
int getPipe() { return pipeFd; }
KJ_DISALLOW_COPY(CurlRequest);
private:
kj::AutoCloseFd pipeFd;
pid_t pid;
kj::String url;
};
// =======================================================================================
class RunBundleMain {
// Main class for the Sandstorm bundle runner. This is a convenience tool for running the
// Sandstorm binary bundle, which is a packaged chroot environment containing everything needed
// to run a Sandstorm server. Just unpack and run!
public:
RunBundleMain(kj::ProcessContext& context): context(context) {
// Make sure we didn't inherit a weird signal mask from the parent process.
clearSignalMask();
umask(0022);
if (!isKernelNewEnough()) {
context.exitError(
"ERROR: Your Linux kernel is too old. You need at least kernel version 3.10.");
}
}
kj::MainFunc getMain() {
static const char* VERSION = "Sandstorm version " SANDSTORM_VERSION;
{
auto programName = context.getProgramName();
if (programName.endsWith("supervisor")) { // historically "sandstorm-supervisor"
alternateMain = kj::heap<SupervisorMain>(context);
return alternateMain->getMain();
} else if (programName == "spk" || programName.endsWith("/spk")) {
alternateMain = getSpkMain(context);
return alternateMain->getMain();
} else if (programName == "backup" || programName.endsWith("/backup")) {
alternateMain = kj::heap<BackupMain>(context);
return alternateMain->getMain();
}
}
return kj::MainBuilder(context, VERSION,
"Controls the Sandstorm server.\n\n"
"Something not working? Check the logs in SANDSTORM_HOME/var/log.")
.addSubCommand("start",
[this]() {
return kj::MainBuilder(context, VERSION, "Starts the Sandstorm server (default).")
.callAfterParsing(KJ_BIND_METHOD(*this, start))
.build();
},
"Start the sandstorm server.")
.addSubCommand("stop",
[this]() {
return kj::MainBuilder(context, VERSION, "Stops the Sandstorm server.")
.callAfterParsing(KJ_BIND_METHOD(*this, stop))
.build();
},
"Stop the sandstorm server.")
.addSubCommand("status",
[this]() {
return kj::MainBuilder(context, VERSION,
"Checks whether Sandstorm is running. Prints the pid and exits successfully "
"if so; exits with an error otherwise.")
.callAfterParsing(KJ_BIND_METHOD(*this, status))
.build();
},
"Check if Sandstorm is running.")
.addSubCommand("restart",
[this]() {
return kj::MainBuilder(context, VERSION, "Restarts Sandstorm server.")
.callAfterParsing(KJ_BIND_METHOD(*this, restart))
.build();
},
"Restart Sandstorm server.")
.addSubCommand("mongo",
[this]() {
return kj::MainBuilder(context, VERSION,
"Runs MongoDB shell, connecting to the already-running Sandstorm server.")
.callAfterParsing(KJ_BIND_METHOD(*this, mongo))
.build();
},
"Run MongoDB shell.")
.addSubCommand("update",
[this]() {
return kj::MainBuilder(context, VERSION,
"Updates the Sandstorm platform to a new version. If <release> is provided "
"and specifies a bundle file (something like sandstorm-1234.tar.xz) it is "
"used as the update. If <release> is a channel name, e.g. \"dev\", we "
"securely check the web for an update. If <release> is not provided, we "
"use the channel specified in the config file.")
.expectOptionalArg("<release>", KJ_BIND_METHOD(*this, setUpdateFile))
.callAfterParsing(KJ_BIND_METHOD(*this, update))
.build();
},
"Update the Sandstorm platform.")
.addSubCommand("spk",
[this]() {
alternateMain = getSpkMain(context);
return alternateMain->getMain();
},
"Manipulate spk files.")
.addSubCommand("continue",
[this]() {
return kj::MainBuilder(context, VERSION,
"For internal use only: Continues running Sandstorm after an update. "
"This command is invoked by the Sandstorm server itself. Do not run it "
"directly.")
.addOption({"userns"}, [this]() { unsharedUidNamespace = true; return true; },
"Pass this flag if the parent has already set up and entered a UID "
"namespace.")
.expectArg("<pidfile-fd>", KJ_BIND_METHOD(*this, inheritPidfileFd))
.expectZeroOrMoreArgs("<fd>:tcp:<port>", KJ_BIND_METHOD(*this, inheritFd))
.callAfterParsing(KJ_BIND_METHOD(*this, continue_))
.build();
},
"For internal use only.")
.addSubCommand("dev",
[this]() {
return kj::MainBuilder(context, VERSION,
"For internal use only: Runs an app in dev mode. This command is "
"invoked by the `spk` tool. Do not run it directly.")
.callAfterParsing(KJ_BIND_METHOD(*this, dev))
.build();
},
"For internal use only.")
.addSubCommand("dev-shell",
[this]() {
return kj::MainBuilder(context, VERSION,
"Runs the Sandstorm shell in development mode. For use in developing "
"Sandstorm itself. Must be run from the `shell` subdirectory of the "
"Sandstorm source code.")
.expectZeroOrMoreArgs("<meteor-arg>", KJ_BIND_METHOD(*this, addMeteorArg))
.callAfterParsing(KJ_BIND_METHOD(*this, devShell))
.build();
},
"For developing Sandstorm itself.")
.addSubCommand("admin-token",
[this]() {
return kj::MainBuilder(context, VERSION,
"Generates a new admin token that you can use to access the admin settings "
"page. This is meant for initial setup, or if an admin account is locked out.")
.addOption({'q', "quiet"}, [this]() { shortOutput = true; return true; },
"Output only the token.")
.callAfterParsing(KJ_BIND_METHOD(*this, adminToken))
.build();
},
"Generate admin token.")
.addSubCommand("uninstall",
[this]() {
return kj::MainBuilder(context, VERSION,
"Uninstalls Sandstorm.")
.addOption({"delete-user-data"}, [this]() { deleteUserData = true; return true; },
"Also delete all user data.")
.callAfterParsing(KJ_BIND_METHOD(*this, uninstall))
.build();
},
"Uninstall Sandstorm.")
.addSubCommand("create-acme-account",
[this]() {
return kj::MainBuilder(context, VERSION,
"Instructs Sandstorm to register an ACME account (e.g. Let's Encrypt) "
"using the given email address. The ACME account can be used to obtain "
"TLS certificates.")
.addOptionWithArg({"directory"}, KJ_BIND_METHOD(*this, setAcmeDirectory),
"<url>", "Set the ACME service directory URL. Defaults to Let's Encrypt.")
.addOption({"accept-terms"}, [this]() { acceptedAcmeTos = true; return true; },
"Indicates that you accept the ACME service's terms of service.")
.expectArg("<email>", KJ_BIND_METHOD(*this, createAcmeAccount))
.build();
},
"Create ACME (Let's Encrypt) account.")
.addSubCommand("configure-acme-challenge",
[this]() {
return kj::MainBuilder(context, VERSION,
"Configures Sandstorm with information about your DNS provider to be "
"used to pass ACME challenges in order to issue TLS certificates. "
"The npm module `acme-dns-01-<module>` shall be used to pass challenges, "
"with <json> (a JSON string) parsed and passed to the module's constructor. "
"Only certain modules are supported; see the documentation for info. "
"This command is not necessary for sandcats.io users.")
.expectArg("<module>", KJ_BIND_METHOD(*this, setAcmeChallengeModule))
.expectArg("<json>", KJ_BIND_METHOD(*this, configureAcmeChallenge))
.build();
},
"Configure DNS provider for ACME challenges.")
.addSubCommand("renew-certificate",
[this]() {
return kj::MainBuilder(context, VERSION,
"Try to renew the server's certificate with ACME right now. ACME renewal "
"usually happens automatically in the background; you should only use this "
"command if you have recently changed your ACME config and want to "
"get a certificate immediately.")
.callAfterParsing(KJ_BIND_METHOD(*this, renewCertificateNow))
.build();
},
"Renew the server's SSL/TLS certificate with ACME.")
.build();
}
kj::MainBuilder::Validity start() {
changeToInstallDir();
const Config config = readConfig();
// Check / lock the pidfile.
auto pidfile = raiiOpen("../var/pid/sandstorm.pid", O_RDWR | O_CREAT | O_CLOEXEC, 0660);
{
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // entire file
if (fcntl(pidfile, F_SETLK, &lock) < 0) {
int error = errno;
if (error == EACCES || error == EAGAIN) {
context.exitInfo(kj::str("Sandstorm is already running. PID = ", readAll(pidfile)));
} else {
KJ_FAIL_SYSCALL("fcntl(pidfile, F_SETLK)", error);
}
}
// It's ours. Truncate for now so we can write in the new PID later.
KJ_SYSCALL(ftruncate(pidfile, 0));
}
if (!runningAsRoot) unshareUidNamespaceOnce();
// Unshare PID namespace so that daemon process becomes the root process of its own PID
// namespace and therefore if it dies the whole namespace is killed.
KJ_SYSCALL(unshare(CLONE_NEWPID));
// Daemonize ourselves.
pid_t mainPid; // PID of the main process as seen *outside* the PID namespace.
{
auto pipe = Pipe::make();
KJ_SYSCALL(mainPid = fork());
if (mainPid != 0) {
// Tell the child process its own PID, since being in a PID namespace its own getpid() will
// unhelpfully return 1.
pipe.readEnd = nullptr;
kj::FdOutputStream(kj::mv(pipe.writeEnd)).write(&mainPid, sizeof(mainPid));
// Write the pidfile before exiting.
{
auto pidstr = kj::str(mainPid, '\n');
kj::FdOutputStream((int)pidfile).write(pidstr.begin(), pidstr.size());
}
// Exit success.
context.exitInfo(kj::str("Sandstorm started. PID = ", mainPid));
return true;
}
// Read our (global) PID in from the parent process.
pipe.writeEnd = nullptr;
kj::FdInputStream(kj::mv(pipe.readEnd)).read(&mainPid, sizeof(mainPid));
}
// Since we unshared the PID namespace, the first fork() should have produced pid 1 in the
// new namespace. That means that if this pid ever exits, everything under it dies. That's
// perfect! Otherwise we'd have to carefully kill node and mongo separately.
KJ_ASSERT(getpid() == 1, "unshare(CLONE_NEWPID) didn't do what I expected.", getpid());
// Lock the pidfile and make sure it still belongs to us.
//
// We need to wait for the parent process to release its lock, so we use F_SETLKW.
// However, if another Sandstorm server is started simultaneously and manages to steal
// ownership, we want to detect this and exit, so we take a shared (read-only) lock.
{
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // entire file
KJ_SYSCALL(fcntl(pidfile, F_SETLKW, &lock));
// Verify that we still own the file.
KJ_SYSCALL(lseek(pidfile, 0, SEEK_SET));
pid_t pidfilePid = KJ_ASSERT_NONNULL(parseUInt(trim(readAll(pidfile)), 10));
if (pidfilePid != mainPid) {
context.exitInfo(kj::str(
"Oops, Sandstorm PID ", pidfilePid, " just started. "
"PID ", mainPid, " exiting in deference."));
}
}
// Redirect stdio.
{
auto logFd = raiiOpen("../var/log/sandstorm.log", O_WRONLY | O_APPEND | O_CREAT, 0660);
if (runningAsRoot) { KJ_SYSCALL(fchown(logFd, config.uids.uid, config.uids.gid)); }
KJ_SYSCALL(dup2(logFd, STDOUT_FILENO));
KJ_SYSCALL(dup2(logFd, STDERR_FILENO));
}
{
auto nullFd = raiiOpen("/dev/null", O_RDONLY);
KJ_SYSCALL(dup2(nullFd, STDIN_FILENO));
}
// Write time to log.
time_t now;
time(&now);
context.warning(kj::str("** Starting Sandstorm at: ", ctime(&now)));
// Detach from controlling terminal and make ourselves session leader.
KJ_SYSCALL(setsid());
FdBundle fdBundle(config);
runUpdateMonitor(config, fdBundle, pidfile);
}
kj::MainBuilder::Validity inheritFd(kj::StringPtr mapping) {
auto parts = split(mapping, ':');
if (parts.size() != 3) {
return "invalid syntax for port mapping";
}
int fd;
KJ_IF_MAYBE(p, parseUInt(kj::str(parts[0]), 10)) {
fd = *p;
} else {
return "invalid fd";
}
kj::String type = kj::str(parts[1]);
if (type != "tcp") {
return "invalid type";
}
uint port;
KJ_IF_MAYBE(p, parseUInt(kj::str(parts[2]), 10)) {
port = *p;
} else {
return "invalid port";
}
KJ_SYSCALL(ioctl(fd, FIOCLEX)); // set CLOEXEC
if (!inheritedTcpPorts.insert(std::make_pair(port, kj::AutoCloseFd(fd))).second) {
return "duplicate port";
}
return true;
}
kj::MainBuilder::Validity inheritPidfileFd(kj::StringPtr pidfileFdStr) {
KJ_IF_MAYBE(p, parseUInt(pidfileFdStr, 10)) {
inheritedPidfile = kj::AutoCloseFd(*p);
KJ_SYSCALL(ioctl(inheritedPidfile, FIOCLEX)); // set CLOEXEC
return true;
} else {
return "invalid fd";
}
}
kj::MainBuilder::Validity continue_() {
if (getpid() != 1) {
return "This command is for internal use only.";
}
if (unsharedUidNamespace) {
// Even if getuid() return zero, we aren't really root, it's just that we mapped our UID to
// zero in the UID namespace.
runningAsRoot = false;
}
changeToInstallDir();
Config config = readConfig();
FdBundle fdBundle(config, kj::mv(inheritedTcpPorts));
runUpdateMonitor(config, fdBundle, inheritedPidfile);
}
bool doStop() {
// Stop Sandstorm. Don't return until it's stopped. Returns false if it wasn't running to start
// with.
KJ_ASSERT(changedDir);
registerAlarmHandler();
kj::AutoCloseFd pidfile = nullptr;
KJ_IF_MAYBE(pf, openPidfile()) {
pidfile = kj::mv(*pf);
} else {
return false;
}
pid_t pid;
KJ_IF_MAYBE(p, getRunningPid(pidfile)) {
pid = *p;
} else {
return false;
}
context.warning(kj::str("Waiting for PID ", pid, " to terminate..."));
KJ_SYSCALL(kill(pid, SIGTERM));
// Timeout if not dead within 10 seconds.
uint timeout = 10;
KJ_SYSCALL(alarm(timeout));
// Take write lock on pidfile as a way to wait for exit.
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // entire file
for (;;) {
if (fcntl(pidfile, F_SETLKW, &lock) >= 0) {
// Success.
break;
}
int error = errno;
if (error == EINTR) {
if (alarmed) {
context.warning(kj::str("Did not terminate after ", timeout, " seconds; killing..."));
KJ_SYSCALL(kill(pid, SIGKILL));
alarmed = false;
} else {
// Ignore signal.
}
} else {
KJ_FAIL_SYSCALL("fcntl(pidfile, F_SETLKW)", error);
}
}
KJ_SYSCALL(alarm(0));
return true;
}
kj::MainBuilder::Validity stop() {
changeToInstallDir();
if (doStop()) {
context.exitInfo("Sandstorm server stopped.");
} else {
context.exitInfo("Sandstorm is not running.");
}
}
kj::MainBuilder::Validity status() {
changeToInstallDir();
KJ_IF_MAYBE(pid, getRunningPid()) {
context.exitInfo(kj::str("Sandstorm is running; PID = ", *pid));
} else {
context.exitError("Sandstorm is not running.");
}
}
kj::MainBuilder::Validity restart() {
changeToInstallDir();
KJ_IF_MAYBE(pid, getRunningPid()) {
KJ_SYSCALL(kill(*pid, SIGHUP));
context.exitInfo("Restart request sent.");
} else {
context.exitError("Sandstorm is not running.");
}
}
kj::MainBuilder::Validity mongo() {
changeToInstallDir();
// Verify that Sandstorm is running.
if (getRunningPid() == nullptr) {
context.exitError("Sandstorm is not running.");
}
const Config config = readConfig();
// We'll run under the chroot.
enterChroot(nullptr, false);
// Don't run as root.
dropPrivs(config.uids);
// OK, run the Mongo client!
execMongoClient(config, {}, {});
KJ_UNREACHABLE;
}
kj::MainBuilder::Validity update() {
changeToInstallDir();
const Config config = readConfig();
if (updateFile == nullptr) {
if (config.updateChannel == nullptr) {
return "You must specify a channel.";
}
if (!checkForUpdates(config.updateChannel, "manual", config)) {
context.exit();
}
} else {
if (config.updateChannel != nullptr) {
return "You currently have auto-updates enabled. Please disable it before updating "
"manually, otherwise you'll just be switched back at the next update. Set "
"UPDATE_CHANNEL to \"none\" to disable. Or, if you want to manually apply "
"the latest update from the configured channel, run `sandstorm update` with "
"no argument.";
}
if (!updateFileIsChannel) {
unpackUpdate(raiiOpen(updateFile, O_RDONLY));
} else if (!checkForUpdates(updateFile, "manual", config)) {
context.exit();
}
}
KJ_IF_MAYBE(pid, getRunningPid()) {
KJ_SYSCALL(kill(*pid, SIGHUP));
context.exitInfo("Update complete; restarting Sandstorm.");
} else {
context.exitInfo("Update complete.");
}
}
kj::MainBuilder::Validity adminToken() {
changeToInstallDir();
checkAccess();
// Get 20 random bytes for token.
kj::byte bytes[20];
randombytes_buf(bytes, sizeof(bytes));
auto hexString = kj::encodeHex(bytes);
auto config = readConfig();
// Remove old token if present.
unlink("../var/sandstorm/adminToken");
{
auto tokenFd = raiiOpen("../var/sandstorm/adminToken",
O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0640);
kj::FdOutputStream tokenFile(tokenFd.get());
KJ_SYSCALL(fchown(tokenFd, -1, config.uids.gid));
tokenFile.write(hexString.begin(), hexString.size());
}
if (shortOutput) {
context.exitInfo(hexString);
} else {
context.exitInfo(kj::str("Generated new admin token. Please proceed to:\n\n",
config.rootUrl, "/setup/token/", hexString, "\n\n"
"Here you can access the admin settings page and configure "
"your login system. You must visit the link within 15 minutes, after which you will have "
"24 hours to complete the setup process. If you need more time, you can always generate "
"a new token with `sandstorm admin-token`."));
}
}
kj::MainBuilder::Validity uninstall() {
auto bundleDir = getInstallDir();
auto sandstormHome = kj::str(bundleDir.slice(0, KJ_ASSERT_NONNULL(bundleDir.findLast('/'))));
changeToInstallDir();
checkAccess();
// Make sure server is stopped.
if (doStop()) {
context.warning("Sandstorm stopped.");
} else {
context.warning("Sandstorm is not running.");
}
KJ_SYSCALL(chdir(sandstormHome.cStr()));
// Make extra-sure we're in a Sandstorm directory.
KJ_ASSERT(access("sandstorm", F_OK) >= 0 &&
access("sandstorm.conf", F_OK) >= 0 &&
access("latest", F_OK) >= 0 &&
sandstormHome != "/" &&
sandstormHome != "/usr",
"uninstaller is confused; bailing out to avoid doing any damage", sandstormHome);
bool hasCustomUser = fileHasLine("sandstorm.conf", "SERVER_USER=sandstorm");
// Delete Sandstorm bundles.
context.warning("Deleting installed Sandstorm bundles...");
static const kj::StringPtr BUNDLE_PREFIX = "sandstorm-";
for (auto& file: listDirectory(".")) {
if (file.startsWith(BUNDLE_PREFIX)) {
auto suffix = file.slice(BUNDLE_PREFIX.size());
if (parseUInt(suffix, 10) != nullptr || suffix.startsWith("custom.")) {
// Delete bundle.
recursivelyDelete(file);
}
}
}
// Delete symlinks.
KJ_SYSCALL(unlink("sandstorm"));
KJ_SYSCALL(unlink("latest"));
if (access("tmp", F_OK) >= 0) {
// Delete tmp since it's obviously not needed.
context.warning("Deleting temporary files...");
recursivelyDelete("tmp");
}
if (access("var", F_OK) >= 0) {
if (deleteUserData) {
// User wants to delete their user data... OK then.
context.warning("Deleting user data (per your request)...");
recursivelyDelete("var");
KJ_SYSCALL(unlink("sandstorm.conf"));
} else {
context.warning(kj::str("NOT deleting user data. Left at: ", sandstormHome, "/var"));
}
}
if (runningAsRoot) {
// Delete system-installed stuff. Be careful to verify that these files actually point at
// the installation of Sandstorm that we're removing, not some other installation that might
// be present on the machine.
bool seemsLikePrimarySandstorm = false;
// Remove `sandstorm` and `spk` command prefixes. Note that for historical reasons there are
// a few different places these might point, so we only check that they point somewhere under
// our Sandstorm install directory.
auto symlinkTargetPrefix = kj::str(sandstormHome, "/");
static const kj::StringPtr SANDSTORM_SYMLINK = "/usr/local/bin/sandstorm";
if (symlinkPointsInto(SANDSTORM_SYMLINK, symlinkTargetPrefix)) {
context.warning("Removing sandstorm command...");
KJ_SYSCALL(unlink(SANDSTORM_SYMLINK.cStr()));
seemsLikePrimarySandstorm = true;
}
static const kj::StringPtr SPK_SYMLINK = "/usr/local/bin/spk";
if (symlinkPointsInto(SPK_SYMLINK, symlinkTargetPrefix)) {
context.warning("Removing spk command...");
KJ_SYSCALL(unlink(SPK_SYMLINK.cStr()));
}
// SysV initscript. Remove if it inits this Sandstorm installation.
static const kj::StringPtr INITSCRIPT_FILE = "/etc/init.d/sandstorm";
auto initscriptLine = kj::str("DAEMON=", sandstormHome, "/sandstorm");
if (fileHasLine(INITSCRIPT_FILE, initscriptLine)) {
context.warning("Removing SysV initscript...");
KJ_SYSCALL(unlink(INITSCRIPT_FILE.cStr()));
system("update-rc.d sandstorm remove");
}
// systemd service file. Remove if it inits this Sandstorm installation.
static const kj::StringPtr SYSTEMD_FILE = "/etc/systemd/system/sandstorm.service";
auto systemdLine = kj::str("ExecStart=", sandstormHome, "/sandstorm start");
if (fileHasLine(SYSTEMD_FILE, systemdLine)) {
context.warning("Removing systemd service...");
system("systemctl disable sandstorm.service");
KJ_SYSCALL(unlink(SYSTEMD_FILE.cStr()));
system("systemctl daemon-reload");
}
if (seemsLikePrimarySandstorm) {
// Remove the sysctl modifications. Unfortunately this will break any other Sandstorm
// installations on the server, but it _looks_ like we're removing the primary
// installation.
kj::StringPtr SYSCTL_CONF = "/etc/sysctl.d/50-sandstorm.conf";
if (access(SYSCTL_CONF.cStr(), F_OK) >= 0) {
context.warning("Removing sysctl modifications...");
unlink(SYSCTL_CONF.cStr());
}
// Also check if the non-sysctl.d sysctl.conf was modified.
if (fileHasLine("/etc/sysctl.conf",
"# Enable non-root users to create sandboxes (needed by Sandstorm).")) {
context.warning("WARNING: /etc/sysctl.conf was modified by Sandstorm. Please edit "
"it manually if you wish to undo these changes.");
}
if (hasCustomUser) {
context.warning("WARNING: A user account and group named 'sandstorm' were created to "
"run the server. You may want to delete these manually if they are no "
"longer needed. On most systems you can use these commands:\n\n"
" userdel sandstorm\n"
" groupdel sandstorm");
}
}
}
// Attempt to remove the Sandstorm home directory. This will fail if it isn't empty, but that's
// fine.