forked from facebook/watchman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1445 lines (1304 loc) · 38.1 KB
/
main.cpp
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
/* Copyright 2012-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
#include "ChildProcess.h"
#include "LogConfig.h"
#include "Logging.h"
#include "ThreadPool.h"
#ifdef _WIN32
#include <Lmcons.h>
#include <Shlobj.h>
#endif
#ifndef _WIN32
#include <poll.h>
#endif
#include <folly/Exception.h>
#include <folly/ScopeGuard.h>
#include <folly/Singleton.h>
#include <folly/SocketAddress.h>
#include <folly/String.h>
#include <folly/net/NetworkSocket.h>
#ifdef _WIN32
#include <deelevate.h>
#endif
using watchman::ChildProcess;
using watchman::FileDescriptor;
using Options = ChildProcess::Options;
using namespace watchman;
static int show_help = 0;
static int show_version = 0;
static int enable_tcp = 0;
static std::string tcp_host;
static enum w_pdu_type server_pdu = is_bser;
static enum w_pdu_type output_pdu = is_json_pretty;
static uint32_t server_capabilities = 0;
static uint32_t output_capabilities = 0;
static std::string server_encoding;
static std::string output_encoding;
static std::string test_state_dir;
static std::string pid_file;
static char** daemon_argv = NULL;
static int persistent = 0;
static int foreground = 0;
static int no_pretty = 0;
static int no_spawn = 0;
static int no_local = 0;
static int no_site_spawner = 0;
#ifndef _WIN32
static int inetd_style = 0;
#endif
static struct sockaddr_un un;
static int json_input_arg = 0;
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
static std::string compute_user_name(void);
static void compute_file_name(
std::string& str,
const std::string& user,
const char* suffix,
const char* what);
static bool lock_pidfile(void) {
// We defer computing this path until we're in the server context because
// eager evaluation can trigger integration test failures unless all clients
// are aware of both the pidfile and the sockpath being used in the tests.
compute_file_name(pid_file, compute_user_name(), "pid", "pidfile");
#if !defined(_WIN32)
struct flock lock;
pid_t mypid;
mypid = getpid();
memset(&lock, 0, sizeof(lock));
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
FileDescriptor fd(
open(pid_file.c_str(), O_RDWR | O_CREAT, 0644),
FileDescriptor::FDType::Generic);
if (!fd) {
log(ERR,
"Failed to open pidfile ",
pid_file,
" for write: ",
folly::errnoStr(errno),
"\n");
return false;
}
// Ensure that no children inherit the locked pidfile descriptor
fd.setCloExec();
if (fcntl(fd.fd(), F_SETLK, &lock) != 0) {
char pidstr[32];
int len;
len = read(fd.fd(), pidstr, sizeof(pidstr) - 1);
pidstr[len] = '\0';
log(ERR,
"Failed to lock pidfile ",
pid_file,
": process ",
pidstr,
" owns it: ",
folly::errnoStr(errno),
"\n");
return false;
}
// Replace contents of the pidfile with our pid string
if (ftruncate(fd.fd(), 0)) {
log(ERR,
"Failed to truncate pidfile ",
pid_file,
": ",
folly::errnoStr(errno),
"\n");
return false;
}
auto pidString = folly::to<std::string>(mypid);
ignore_result(write(fd.fd(), pidString.data(), pidString.size()));
fsync(fd.fd());
/* We are intentionally not closing the fd and intentionally not storing
* a reference to it anywhere: the intention is that it remain locked
* for the rest of the lifetime of our process.
* close(fd); // NOPE!
*/
fd.release();
return true;
#else
// One does not simply, and without risk of races, write a pidfile
// on win32. Instead we're using a named mutex in the global namespace.
// This gives us a very simple way to exclusively claim ownership of
// the lock for this user. To make things a little more complicated,
// since we scope our locks based on the state dir location and require
// this to work for our integration tests, we need to create a unique
// name per state dir. This is made even more interesting because
// we are forbidden from using windows directory separator characters
// in the name, so we cannot simply concatenate the state dir path
// with a watchman specific prefix. Instead we iterate the path
// and rewrite any backslashes with forward slashes and use that
// for the name.
// Using a mutex for this does make it more awkward to discover
// the process id of the exclusive owner, but that's not critically
// important; it is possible to connect to the instance and issue
// a get-pid command if that is needed.
// We use the global namespace so that we ensure that we have one
// watchman process per user per state dir location. If we didn't
// use the Global namespace we'd end using a local namespace scoped
// to the user session and that might cause confusion/insanity if
// they are doing something elaborate like being logged in via
// ssh in multiple sessions and expecting to share state.
std::string name("Global\\Watchman-");
for (const auto& it : pid_file) {
if (it == '\\') {
// We're not allowed to use backslash in the name, so normalize
// to forward slashes.
name.append("/");
} else {
name.push_back(it);
}
}
auto mutex = CreateMutexA(nullptr, true, name.c_str());
if (!mutex) {
log(ERR,
"Failed to create mutex named: ",
name,
": ",
GetLastError(),
"\n");
return false;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
log(ERR,
"Failed to acquire mutex named: ",
name,
"; watchman is already running for this context\n");
return false;
}
/* We are intentionally not closing the mutex and intentionally not storing
* a reference to it anywhere: the intention is that it remain locked
* for the rest of the lifetime of our process.
* CloseHandle(mutex); // NOPE!
*/
return true;
#endif
}
#ifndef _WIN32
// Returns the current process priority aka `nice` level.
// Since `-1` is a valid nice level, in order to detect an
// error we clear errno first and then test whether it is
// non-zero after we have retrieved the nice value.
static int get_nice_value() {
errno = 0;
auto value = nice(0);
folly::checkPosixError(errno, "failed to get `nice` value");
return value;
}
static void check_nice_value() {
if (get_nice_value() > cfg_get_int("min_acceptable_nice_value", 0)) {
log(watchman::FATAL,
"Watchman is running at a lower than normal priority. Since that "
"results in poor performance that is otherwise very difficult to "
"trace, diagnose and debug, Watchman is refusing to start.\n");
}
}
#endif
[[noreturn]] static void run_service() {
int fd;
bool res;
#ifndef _WIN32
// Before we redirect stdin/stdout to the log files, move any inetd-provided
// socket to a different descriptor number.
if (inetd_style) {
w_listener_prep_inetd();
}
if (isatty(0)) {
// This case can happen when a user is running watchman using
// the `--foreground` switch.
// Check and raise this error before we detach from the terminal
check_nice_value();
}
#endif
// redirect std{in,out,err}
fd = ::open("/dev/null", O_RDONLY);
if (fd != -1) {
ignore_result(::dup2(fd, STDIN_FILENO));
::close(fd);
}
fd = open(log_name.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0600);
if (fd != -1) {
ignore_result(::dup2(fd, STDOUT_FILENO));
ignore_result(::dup2(fd, STDERR_FILENO));
::close(fd);
}
#ifndef _WIN32
// If we weren't attached to a tty, check this now that we've opened
// the log files so that we can log the problem there.
check_nice_value();
#endif
if (!lock_pidfile()) {
exit(1);
}
#ifndef _WIN32
/* we are the child, let's set things up */
ignore_result(chdir("/"));
#endif
w_set_thread_name("listener");
{
char hostname[256];
gethostname(hostname, sizeof(hostname));
hostname[sizeof(hostname) - 1] = '\0';
logf(
ERR,
"Watchman {} {} starting up on {}\n",
PACKAGE_VERSION,
#ifdef WATCHMAN_BUILD_INFO
WATCHMAN_BUILD_INFO,
#else
"<no build info set>",
#endif
hostname);
}
#ifndef _WIN32
// Block SIGCHLD by default; we only want it to be delivered
// to the reaper thread and only when it is ready to reap.
// This MUST happen before we spawn any threads so that they
// can pick up our default blocked signal mask.
{
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigset, NULL);
}
#endif
watchman::getThreadPool().start(
cfg_get_int("thread_pool_worker_threads", 16),
cfg_get_int("thread_pool_max_items", 1024 * 1024));
ClockSpec::init();
w_state_load();
res = w_start_listener();
w_root_free_watched_roots();
perf_shutdown();
cfg_shutdown();
log(ERR, "Exiting from service with res=", res, "\n");
if (res) {
exit(0);
}
exit(1);
}
#ifndef _WIN32
// close any random descriptors that we may have inherited,
// leaving only the main stdio descriptors open, if we execute a
// child process.
static void close_random_fds(void) {
struct rlimit limit;
long open_max = 0;
int max_fd;
// Deduce the upper bound for number of descriptors
limit.rlim_cur = 0;
#ifdef RLIMIT_NOFILE
if (getrlimit(RLIMIT_NOFILE, &limit) != 0) {
limit.rlim_cur = 0;
}
#elif defined(RLIM_OFILE)
if (getrlimit(RLIMIT_OFILE, &limit) != 0) {
limit.rlim_cur = 0;
}
#endif
#ifdef _SC_OPEN_MAX
open_max = sysconf(_SC_OPEN_MAX);
#endif
if (open_max <= 0) {
open_max = 36; /* POSIX_OPEN_MAX (20) + some padding */
}
if (limit.rlim_cur == RLIM_INFINITY || limit.rlim_cur > INT_MAX) {
// "no limit", which seems unlikely
limit.rlim_cur = INT_MAX;
}
// Take the larger of the two values we compute
if (limit.rlim_cur > (rlim_t)open_max) {
open_max = limit.rlim_cur;
}
for (max_fd = open_max; max_fd > STDERR_FILENO; --max_fd) {
close(max_fd);
}
}
#endif
#if !defined(_WIN32)
static void daemonize(void) {
// Make sure we're not about to inherit an undesirable nice value
check_nice_value();
close_random_fds();
// the double-fork-and-setsid trick establishes a
// child process that runs in its own process group
// with its own session and that won't get killed
// off when your shell exits (for example).
if (fork()) {
// The parent of the first fork is the client
// process that is being run by the user, and
// we want to allow that to continue.
return;
}
setsid();
if (fork()) {
// The parent of the second fork has served its
// purpose, so we simply exit here, otherwise
// we'll duplicate the effort of either the
// client or the server depending on if we
// return or not.
_exit(0);
}
// we are the child, let's set things up
run_service();
}
#endif
#ifdef _WIN32
static void spawn_win32(void) {
char module_name[WATCHMAN_NAME_MAX];
GetModuleFileName(NULL, module_name, sizeof(module_name));
Options opts;
opts.setFlags(POSIX_SPAWN_SETPGROUP);
opts.open(STDIN_FILENO, "/dev/null", O_RDONLY, 0666);
opts.open(
STDOUT_FILENO, log_name.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0600);
opts.dup2(STDOUT_FILENO, STDERR_FILENO);
std::vector<w_string_piece> args{module_name, "--foreground"};
for (size_t i = 0; daemon_argv[i]; i++) {
args.push_back(daemon_argv[i]);
}
ChildProcess proc(args, std::move(opts));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (proc.terminated()) {
logf(
ERR,
"Failed to spawn watchman server; it exited with code {}.\n"
"Check the log file at {} for more information\n",
proc.wait(),
log_name);
exit(1);
}
proc.disown();
}
#endif
#ifndef _WIN32
// Spawn watchman via a site-specific spawn helper program.
// We'll pass along any daemon-appropriate arguments that
// we noticed during argument parsing.
static void spawn_site_specific(const char* spawner) {
std::vector<w_string_piece> args{
spawner,
};
for (size_t i = 0; daemon_argv[i]; i++) {
args.push_back(daemon_argv[i]);
}
close_random_fds();
// Note that we're not setting up the output to go to the log files
// here. This is intentional; we'd like any failures in the spawner
// to bubble up to the user as having things silently fail and get
// logged to the server log doesn't provide any obvious cues to the
// user about what went wrong. Watchman will open and redirect output
// to its log files when it ultimately is launched and enters the
// run_service() function above.
// However, we do need to make sure that any output from both stdout
// and stderr goes to stderr of the end user.
Options opts;
opts.open(STDIN_FILENO, "/dev/null", O_RDONLY, 0666);
opts.dup2(STDERR_FILENO, STDOUT_FILENO);
opts.dup2(STDERR_FILENO, STDERR_FILENO);
try {
ChildProcess proc(args, std::move(opts));
auto res = proc.wait();
if (WIFEXITED(res) && WEXITSTATUS(res) == 0) {
return;
}
if (WIFEXITED(res)) {
log(FATAL, spawner, ": exited with status ", WEXITSTATUS(res), "\n");
} else if (WIFSIGNALED(res)) {
log(FATAL, spawner, ": signaled with ", WTERMSIG(res), "\n");
}
log(FATAL, spawner, ": failed to start, exit status ", res, "\n");
} catch (const std::exception& exc) {
log(FATAL,
"Failed to spawn watchman via `",
spawner,
"': ",
exc.what(),
"\n");
}
}
#endif
#ifdef __APPLE__
static void spawn_via_launchd(void) {
char watchman_path[WATCHMAN_NAME_MAX];
uint32_t size = sizeof(watchman_path);
char plist_path[WATCHMAN_NAME_MAX];
FILE* fp;
struct passwd* pw;
uid_t uid;
close_random_fds();
if (_NSGetExecutablePath(watchman_path, &size) == -1) {
log(FATAL, "_NSGetExecutablePath: path too long; size ", size, "\n");
}
uid = getuid();
pw = getpwuid(uid);
if (!pw) {
log(FATAL,
"getpwuid(",
uid,
") failed: ",
folly::errnoStr(errno),
". I don't know who you are\n");
}
snprintf(
plist_path, sizeof(plist_path), "%s/Library/LaunchAgents", pw->pw_dir);
// Best effort attempt to ensure that the agents dir exists. We'll detect
// and report the failure in the fopen call below.
mkdir(plist_path, 0755);
snprintf(
plist_path,
sizeof(plist_path),
"%s/Library/LaunchAgents/com.github.facebook.watchman.plist",
pw->pw_dir);
if (access(plist_path, R_OK) == 0) {
// Unload any that may already exist, as it is likely wrong
ChildProcess unload_proc(
{"/bin/launchctl", "unload", "-F", plist_path}, Options());
unload_proc.wait();
// Forcibly remove the plist. In some cases it may have some attributes
// set that prevent launchd from loading it. This can happen where
// the system was re-imaged or restored from a backup
unlink(plist_path);
}
fp = fopen(plist_path, "w");
if (!fp) {
log(FATAL,
"Failed to open ",
plist_path,
" for write: ",
folly::errnoStr(errno),
"\n");
}
compute_file_name(pid_file, compute_user_name(), "pid", "pidfile");
auto plist_content = folly::to<std::string>(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" "
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
"<plist version=\"1.0\">\n"
"<dict>\n"
" <key>Label</key>\n"
" <string>com.github.facebook.watchman</string>\n"
" <key>Disabled</key>\n"
" <false/>\n"
" <key>ProgramArguments</key>\n"
" <array>\n"
" <string>",
watchman_path,
"</string>\n"
" <string>--foreground</string>\n"
" <string>--logfile=",
log_name,
"</string>\n"
" <string>--log-level=",
log_level,
"</string>\n"
// TODO: switch from `--sockname` to `--unix-listener-path`
// after a grace period to allow for sane results if we
// roll back to an earlier version
" <string>--sockname=",
get_unix_sock_name(),
"</string>\n"
" <string>--statefile=",
watchman_state_file,
"</string>\n"
" <string>--pidfile=",
pid_file,
"</string>\n"
" </array>\n"
" <key>KeepAlive</key>\n"
" <dict>\n"
" <key>Crashed</key>\n"
" <true/>\n"
" </dict>\n"
" <key>RunAtLoad</key>\n"
" <true/>\n"
" <key>EnvironmentVariables</key>\n"
" <dict>\n"
" <key>PATH</key>\n"
" <string><![CDATA[",
getenv("PATH"),
"]]></string>\n"
" </dict>\n"
" <key>ProcessType</key>\n"
" <string>Interactive</string>\n"
" <key>Nice</key>\n"
" <integer>-5</integer>\n"
"</dict>\n"
"</plist>\n");
fwrite(plist_content.data(), 1, plist_content.size(), fp);
fclose(fp);
// Don't rely on umask, ensure we have the correct perms
chmod(plist_path, 0644);
ChildProcess load_proc(
{"/bin/launchctl", "load", "-F", plist_path}, Options());
auto res = load_proc.wait();
if (WIFEXITED(res) && WEXITSTATUS(res) == 0) {
return;
}
// Most likely cause is "headless" operation with no GUI context
if (WIFEXITED(res)) {
logf(ERR, "launchctl: exited with status {}\n", WEXITSTATUS(res));
} else if (WIFSIGNALED(res)) {
logf(ERR, "launchctl: signaled with {}\n", WTERMSIG(res));
}
logf(ERR, "Falling back to daemonize\n");
daemonize();
}
#endif
static void parse_encoding(const std::string& enc, enum w_pdu_type* pdu) {
if (enc.empty()) {
return;
}
if (enc == "json") {
*pdu = is_json_compact;
return;
}
if (enc == "bser") {
*pdu = is_bser;
return;
}
if (enc == "bser-v2") {
*pdu = is_bser_v2;
return;
}
log(ERR, "Invalid encoding '", enc, "', use one of json, bser or bser-v2\n");
exit(EX_USAGE);
}
static const char* get_env_with_fallback(
const char* name1,
const char* name2,
const char* fallback) {
const char* val;
val = getenv(name1);
if (!val || *val == 0) {
val = getenv(name2);
}
if (!val || *val == 0) {
val = fallback;
}
return val;
}
static void verify_dir_ownership(const std::string& state_dir) {
#ifndef _WIN32
// verify ownership
struct stat st;
int dir_fd;
int ret = 0;
uid_t euid = geteuid();
// TODO: also allow a gid to be specified here
const char* sock_group_name = cfg_get_string("sock_group", nullptr);
// S_ISGID is set so that files inside this directory inherit the group
// name
mode_t dir_perms =
cfg_get_perms(
"sock_access", false /* write bits */, true /* execute bits */) |
S_ISGID;
auto dirp = w_dir_open(
state_dir.c_str(), false /* don't need strict symlink rules */);
dir_fd = dirp->getFd();
if (dir_fd == -1) {
log(ERR, "dirfd(", state_dir, "): ", folly::errnoStr(errno), "\n");
goto bail;
}
if (fstat(dir_fd, &st) != 0) {
log(ERR, "fstat(", state_dir, "): ", folly::errnoStr(errno), "\n");
ret = 1;
goto bail;
}
if (euid != st.st_uid) {
log(ERR,
"the owner of ",
state_dir,
" is uid ",
st.st_uid,
" and doesn't match your euid ",
euid,
"\n");
ret = 1;
goto bail;
}
if (st.st_mode & 0022) {
log(ERR,
"the permissions on ",
state_dir,
" allow others to write to it. "
"Verify that you own the contents and then fix its "
"permissions by running `chmod 0700 '",
state_dir,
"'`\n");
ret = 1;
goto bail;
}
if (sock_group_name) {
const struct group* sock_group = w_get_group(sock_group_name);
if (!sock_group) {
ret = 1;
goto bail;
}
if (fchown(dir_fd, -1, sock_group->gr_gid) == -1) {
log(ERR,
"setting up group '",
sock_group_name,
"' failed: ",
folly::errnoStr(errno),
"\n");
ret = 1;
goto bail;
}
}
// Depending on group and world accessibility, change permissions on the
// directory. We can't leave the directory open and set permissions on the
// socket because not all POSIX systems respect permissions on UNIX domain
// sockets, but all POSIX systems respect permissions on the containing
// directory.
logf(DBG, "Setting permissions on state dir to {:o}\n", dir_perms);
if (fchmod(dir_fd, dir_perms) == -1) {
logf(
ERR,
"fchmod({}, {:o}): {}\n",
state_dir,
dir_perms,
folly::errnoStr(errno));
ret = 1;
goto bail;
}
bail:
if (ret) {
exit(ret);
}
#endif
}
#ifdef _WIN32
static std::string get_watchman_appdata_path() {
PWSTR local_app_data = nullptr;
auto res =
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &local_app_data);
if (res != S_OK) {
logf(
FATAL,
"SHGetKnownFolderPath FOLDERID_LocalAppData failed: {}\n",
win32_strerror(res));
}
SCOPE_EXIT {
CoTaskMemFree(local_app_data);
};
// Perform path mapping from wide string to our preferred UTF8
w_string temp_location(local_app_data, wcslen(local_app_data));
// and use the watchman subdir of LOCALAPPDATA
auto watchmanDir = folly::to<std::string>(temp_location, "/watchman");
if (mkdir(watchmanDir.c_str(), 0700) == 0 || errno == EEXIST) {
return watchmanDir;
}
logf(
ERR,
"failed to create directory {}: {}\n",
watchmanDir,
folly::errnoStr(errno));
exit(1);
}
static const std::string& cached_watchman_appdata_path() {
static std::string path = get_watchman_appdata_path();
return path;
}
#endif
static std::string compute_per_user_state_dir(const std::string& user) {
if (!test_state_dir.empty()) {
return folly::to<std::string>(test_state_dir, "/", user, "-state");
}
#ifdef _WIN32
return cached_watchman_appdata_path();
#else
auto state_parent =
#ifdef WATCHMAN_STATE_DIR
WATCHMAN_STATE_DIR
#else
watchman_tmp_dir.c_str()
#endif
;
return folly::to<std::string>(state_parent, "/", user, "-state");
#endif
}
static void compute_file_name(
std::string& str,
const std::string& user,
const char* suffix,
const char* what) {
bool str_computed = false;
if (str.empty()) {
str_computed = true;
/* We'll put our various artifacts in a user specific dir
* within the state dir location */
auto state_dir = compute_per_user_state_dir(user);
if (mkdir(state_dir.c_str(), 0700) == 0 || errno == EEXIST) {
verify_dir_ownership(state_dir.c_str());
} else {
log(ERR,
"while computing ",
what,
": failed to create ",
state_dir,
": ",
folly::errnoStr(errno),
"\n");
exit(1);
}
str = folly::to<std::string>(state_dir, "/", suffix);
}
#ifndef _WIN32
if (!w_string_piece(str).pathIsAbsolute()) {
log(FATAL,
what,
" must be an absolute file path but ",
str,
" was",
str_computed ? " computed." : " provided.",
"\n");
}
#endif
}
static std::string compute_user_name(void) {
#ifdef _WIN32
// We don't trust the environment on win32 because in some situations
// the environment may contain the domain name like `WORKGROUP\user`
// which can confuse some path construction we do later on.
WCHAR userW[1 + UNLEN];
DWORD size = std::size(userW);
if (GetUserNameW(userW, &size) && size > 0) {
// Constructing a w_string from a WCHAR* will convert to UTF-8
w_string user(userW, size);
return folly::to<std::string>(user);
}
log(FATAL,
"GetUserName failed: ",
win32_strerror(GetLastError()),
". I don't know who you are!?\n");
#else
const char* user = get_env_with_fallback("USER", "LOGNAME", NULL);
if (!user) {
uid_t uid = getuid();
struct passwd* pw;
pw = getpwuid(uid);
if (!pw) {
log(FATAL,
"getpwuid(",
uid,
") failed: ",
folly::errnoStr(errno),
". I don't know who you are\n");
}
user = pw->pw_name;
if (!user) {
log(FATAL, "watchman requires that you set $USER in your env\n");
}
}
return user;
#endif
}
#ifdef _WIN32
bool initialize_winsock() {
WSADATA wsaData;
if ((WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ||
(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)) {
return false;
}
return true;
}
bool initialize_uds() {
if (!initialize_winsock()) {
log(DBG, "unable to initialize winsock, disabling UDS support\n");
}
// Test if UDS support is present
FileDescriptor fd(
::socket(PF_LOCAL, SOCK_STREAM, 0), FileDescriptor::FDType::Socket);
bool fd_initialized = (bool)fd;
if (!fd_initialized) {
log(DBG, "unable to create UNIX domain socket, disabling UDS support\n");
return false;
}
return true;
}
#endif
static void setup_sock_name(void) {
#ifdef _WIN32
if (!initialize_uds()) {
// if we can't create UNIX domain socket, disable it.
disable_unix_socket = true;
}
#endif
auto user = compute_user_name();
#ifdef _WIN32
if (!test_state_dir.empty()) {
watchman_tmp_dir = test_state_dir;
} else {
watchman_tmp_dir = cached_watchman_appdata_path();
}
#else
watchman_tmp_dir = get_env_with_fallback("TMPDIR", "TMP", "/tmp");
#endif
#ifdef _WIN32
// On Windows, if an application uses --sockname to override the named
// pipe path so that it can isolate its watchman integration tests,
// but doesn't also specify --unix-listener-path then we need to
// take care to prevent using the default unix domain path which would
// otherwise break their isolation.
// If either option is specified without the other, then we disable
// the use of the other.
if (!named_pipe_path.empty() || !unix_sock_name.empty()) {
disable_named_pipe = named_pipe_path.empty();
disable_unix_socket = unix_sock_name.empty();
}
if (named_pipe_path.empty()) {
named_pipe_path = folly::to<std::string>("\\\\.\\pipe\\watchman-", user);
}
#endif
compute_file_name(unix_sock_name, user, "sock", "sockname");
compute_file_name(watchman_state_file, user, "state", "statefile");
compute_file_name(log_name, user, "log", "logfile");
if (unix_sock_name.size() >= sizeof(un.sun_path) - 1) {
log(FATAL, unix_sock_name, ": path is too long\n");
}
un.sun_family = PF_LOCAL;
memcpy(un.sun_path, unix_sock_name.c_str(), unix_sock_name.size() + 1);
}
static bool should_start(int err) {
if (err == ECONNREFUSED) {
return true;
}
if (err == ENOENT) {
return true;
}
return false;
}
static bool try_command(json_t* cmd, int timeout) {
auto client = w_stm_connect(timeout * 1000);
if (!client) {
return false;
}
// Start in a well-defined non-blocking state as we can't tell
// what mode we're in on windows until we've set it to something
// explicitly at least once before!
client->setNonBlock(false);
if (!cmd) {
return true;