forked from microsoft/WSL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.cpp
More file actions
2711 lines (2106 loc) · 72.7 KB
/
Copy pathconfig.cpp
File metadata and controls
2711 lines (2106 loc) · 72.7 KB
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 (c) Microsoft. All rights reserved.
Module Name:
config.c
Abstract:
This file contains methods for configuring a running instance.
--*/
#include <bitset>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/sysmacros.h>
#include <pwd.h>
#include <future>
#include <signal.h>
#include <pty.h>
#include <lxbusapi.h>
#include "common.h"
#include "mountutilcpp.h"
#include "config.h"
#include "util.h"
#include "configfile.h"
#include "binfmt.h"
#include "wslpath.h"
#include "wslinfo.h"
#include "drvfs.h"
#include "timezone.h"
#include "message.h"
#include "WslDistributionConfig.h"
#include "lxfsshares.h"
#include "plan9.h"
#define AUTO_MOUNT_PARENT_MODE 0755
#define CGROUP_DEVICE "cgroup"
#define CGROUPS_FILE "/proc/cgroups"
#define CGROUPS_NO_V1 "cgroup_no_v1="
#define DEFAULT_CWD "/"
#define DRVFS_MOUNT_OPTIONS (MS_NOATIME)
#define DRVFS_SOURCE " :\\"
#define DRVFS_TARGET_MODE 0777
#define DRVFS_OPTIONS_BUFFER_LENGTH 38
#define ETC_DEFAULT_FOLDER ETC_FOLDER "default/"
#define HOSTNAME_FILE_PATH ETC_FOLDER "hostname"
#define HOSTNAME_FILE_MODE 0644
#define HOSTS_FILE_MODE 0644
#define HOSTS_FILE_PATH ETC_FOLDER "hosts"
#define LANG_ENV "LANG"
#define LOCALE_FILE_PATH ETC_DEFAULT_FOLDER "locale"
#define PATH_ENV "PATH"
#define RESOLV_CONF_DIRECTORY_MODE 0755
#define RESOLV_CONF_FILE_MODE 0644
#define RESOLV_CONF_FILE_NAME "resolv.conf"
#define RESOLV_CONF_FILE_PATH ETC_FOLDER RESOLV_CONF_FILE_NAME
#define RESOLV_CONF_FOLDER RUN_FOLDER "/resolvconf"
#define RESOLV_CONF_SYMLINK_TARGET ".." RESOLV_CONF_FOLDER "/" RESOLV_CONF_FILE_NAME
#define RESOLV_CONF_SYMLINK_WSL_MOUNT_SUFFIX SHARED_MOUNT_FOLDER "/" RESOLV_CONF_FILE_NAME
#define RUN_FOLDER "/run"
#define SHARED_MOUNT_FOLDER "wsl"
#define USER_MOUNT_FOLDER "user"
#define WINDOWS_LD_CONF_FILE "/etc/ld.so.conf.d/ld.wsl.conf"
#define WINDOWS_LD_CONF_FILE_MODE 0644
#define MOUNTS_FILE "/proc/self/mounts"
#define MOUNTS_FIELD_SEPARATOR ' '
#define MOUNTS_LINE_SEPARATOR '\n'
#define MOUNTS_DEVICE_FIELD 0
#define MOUNTS_FSTYPE_FIELD 2
static void ConfigApplyWindowsLibPath(const wsl::linux::WslDistributionConfig& Config);
class RemoveMountAndEnvironmentOnScopeExit
{
public:
RemoveMountAndEnvironmentOnScopeExit() = default;
RemoveMountAndEnvironmentOnScopeExit(const char* EnvironmentName) : m_environmentName(EnvironmentName)
{
m_mountPath = getenv(m_environmentName);
}
RemoveMountAndEnvironmentOnScopeExit& operator=(const RemoveMountAndEnvironmentOnScopeExit&) = delete;
RemoveMountAndEnvironmentOnScopeExit(const RemoveMountAndEnvironmentOnScopeExit&) = delete;
RemoveMountAndEnvironmentOnScopeExit(RemoveMountAndEnvironmentOnScopeExit&& Other)
{
*this = std::move(Other);
}
RemoveMountAndEnvironmentOnScopeExit& operator=(RemoveMountAndEnvironmentOnScopeExit&& Other)
{
m_environmentName = Other.m_environmentName;
Other.m_environmentName = nullptr;
m_mountPath = Other.m_mountPath;
Other.m_mountPath = nullptr;
return *this;
}
~RemoveMountAndEnvironmentOnScopeExit()
{
if (m_environmentName != nullptr)
{
if (unsetenv(m_environmentName) < 0)
{
LOG_ERROR("unsetenv({}) failed {}", m_environmentName, errno);
}
}
if (m_mountPath != nullptr)
{
if (umount2(m_mountPath, MNT_DETACH) < 0)
{
LOG_ERROR("umount2({}, MNT_DETACH) failed {}", m_mountPath, errno);
return;
}
if (rmdir(m_mountPath) < 0)
{
LOG_ERROR("rmdir({}) failed {}", m_mountPath, errno);
}
}
}
operator bool() const
{
return m_mountPath;
}
const char* MountPath() const
{
return m_mountPath;
}
bool MoveMount(const char* Target)
{
if (m_mountPath == nullptr)
{
return false;
}
if (UtilMount(m_mountPath, Target, nullptr, (MS_MOVE | MS_REC), nullptr) < 0)
{
return false;
}
if (rmdir(m_mountPath) < 0)
{
LOG_ERROR("rmdir({}) failed {}", m_mountPath, errno);
}
m_mountPath = nullptr;
return true;
}
private:
const char* m_environmentName = nullptr;
const char* m_mountPath = nullptr;
};
constexpr auto HostsFileFormatString = LX_INIT_AUTO_GENERATED_FILE_HEADER
"# [network]\n"
"# generateHosts = false\n"
"127.0.0.1\tlocalhost\n"
"127.0.1.1\t{}.{}\t{}\n"
"{}\n"
"# The following lines are desirable for IPv6 capable hosts\n"
"::1 ip6-localhost ip6-loopback\n"
"fe00::0 ip6-localnet\n"
"ff00::0 ip6-mcastprefix\n"
"ff02::1 ip6-allnodes\n"
"ff02::2 ip6-allrouters\n";
constexpr auto WindowsLibSearchFileHeaderString = LX_INIT_AUTO_GENERATED_FILE_HEADER
"# [automount]\n"
"# ldconfig = false\n";
const INIT_STARTUP_ANY LxssStartupCommon[] = {
INIT_ANY_DIRECTORY("/sys", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_DEVICE("/sys", "sysfs", "sysfs", (MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_SHARED)),
INIT_ANY_DIRECTORY("/proc", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_DEVICE("/proc", "proc", "proc", (MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_SHARED)),
INIT_ANY_DIRECTORY("/dev/block", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_SYMLINK("/dev/fd", "/proc/self/fd"),
INIT_ANY_SYMLINK("/dev/stdin", "/proc/self/fd/0"),
INIT_ANY_SYMLINK("/dev/stdout", "/proc/self/fd/1"),
INIT_ANY_SYMLINK("/dev/stderr", "/proc/self/fd/2"),
INIT_ANY_DIRECTORY("/dev/pts", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_DEVICE_OPTION("/dev/pts", "devpts", "devpts", "gid=5,mode=620", MS_NOATIME | MS_NOSUID | MS_NOEXEC),
INIT_ANY_DIRECTORY("/run", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_OPTION("/run", "tmpfs", "mode=755", (MS_NODEV | MS_STRICTATIME | MS_NOSUID | MS_SHARED)),
INIT_ANY_DIRECTORY("/run/lock", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT("/run/lock", "tmpfs", MS_NOATIME | MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_SHARED),
INIT_ANY_DIRECTORY("/run/shm", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT("/run/shm", "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV | MS_SHARED),
INIT_ANY_DIRECTORY("/dev/shm", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_DEVICE("/dev/shm", nullptr, "/run/shm", MS_BIND),
INIT_ANY_DIRECTORY("/run/user", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_OPTION("/run/user", "tmpfs", "mode=755", MS_NOATIME | MS_NOSUID | MS_NOEXEC | MS_NODEV),
INIT_ANY_DIRECTORY("/bin", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_SYMLINK("/bin/" WSLINFO_NAME, "/init"),
INIT_ANY_SYMLINK("/bin/" WSLPATH_NAME, "/init"),
INIT_ANY_DIRECTORY("/sbin", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_SYMLINK("/sbin/" MOUNT_DRVFS_NAME, "/init"),
INIT_ANY_MOUNT_DEVICE(BINFMT_MISC_MOUNT_TARGET, "binfmt_misc", "binfmt_misc", MS_RELATIME),
INIT_ANY_DIRECTORY("/tmp", ROOT_UID, ROOT_GID, S_IFDIR | S_ISVTX | 0777)};
const INIT_STARTUP_ANY LxssStartupLoggingVmMode[] = {
INIT_ANY_DIRECTORY("/dev", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_OPTION("/dev", "devtmpfs", "mode=755", (MS_NOSUID | MS_RELATIME | MS_SHARED))};
const INIT_STARTUP_ANY LxssStartupLoggingWsl[] = {
INIT_ANY_DIRECTORY("/dev", ROOT_UID, ROOT_GID, S_IFDIR | 0755),
INIT_ANY_MOUNT_OPTION("/dev", "tmpfs", "mode=755", MS_NOATIME | MS_SHARED),
INIT_ANY_NODE("/dev/kmsg", ROOT_UID, ROOT_GID, S_IFCHR | 0644, INIT_DEV_LOG_KMSG_MAJOR_NUMBER, INIT_DEV_LOG_KMSG_MINOR_NUMBER)};
const INIT_STARTUP_ANY LxssStartupWsl[] = {
INIT_ANY_NODE("/dev/ptmx", ROOT_UID, TTY_GID, S_IFCHR | 0666, INIT_DEV_PTM_MAJOR_NUMBER, INIT_DEV_PTM_MINOR_NUMBER),
INIT_ANY_NODE("/dev/random", ROOT_UID, ROOT_GID, S_IFCHR | 0666, INIT_DEV_RANDOM_MAJOR_NUMBER, INIT_DEV_RANDOM_MINOR_NUMBER),
INIT_ANY_NODE("/dev/urandom", ROOT_UID, ROOT_GID, S_IFCHR | 0666, INIT_DEV_URANDOM_MAJOR_NUMBER, INIT_DEV_URANDOM_MINOR_NUMBER),
INIT_ANY_NODE("/dev/null", ROOT_UID, ROOT_GID, S_IFCHR | 0666, INIT_DEV_NULL_MAJOR_NUMBER, INIT_DEV_NULL_MINOR_NUMBER),
INIT_ANY_NODE("/dev/tty", ROOT_UID, TTY_GID, S_IFCHR | 0666, INIT_DEV_TTYCT_MAJOR_NUMBER, INIT_DEV_TTYCT_MINOR_NUMBER),
INIT_ANY_NODE("/dev/tty0", ROOT_UID, TTY_GID, S_IFCHR | 0620, INIT_DEV_TTY_MAJOR_NUMBER, INIT_DEV_TTY0_MINOR_NUMBER),
INIT_ANY_NODE("/dev/zero", ROOT_UID, ROOT_GID, S_IFCHR | 0666, INIT_DEV_ZERO_MAJOR_NUMBER, INIT_DEV_ZERO_MINOR_NUMBER),
INIT_ANY_NODE(LXBUS_DEVICE_NAME, ROOT_UID, ROOT_GID, S_IFCHR | 0666, INIT_DEV_LXBUS_MAJOR_NUMBER, INIT_DEV_LXBUS_MINOR_NUMBER)};
//
// Mount namespace file descriptors for VM mode.
//
int g_ElevatedMountNamespace = -1;
int g_NonElevatedMountNamespace = -1;
//
// Boot state bookkeeping.
//
extern wsl::shared::SocketChannel g_plan9ControlChannel;
void ConfigAppendNtPath(EnvironmentBlock& Environment, char* NtPath)
/*++
Routine Description:
This routine updates the $PATH variable of the provided environment block.
Arguments:
Environment - Supplies the environment block to update.
NtPath - Supplies a semicolon-separated list of NT paths to translate and
append to the $PATH variable. If no $PATH variable exists, one is
created.
Return Value:
None.
--*/
try
{
auto TranslatedPath = UtilTranslatePathList(NtPath, true);
if (!TranslatedPath.has_value())
{
return;
}
ConfigAppendToPath(Environment, TranslatedPath.value());
return;
}
CATCH_LOG()
void ConfigAppendToPath(EnvironmentBlock& Environment, std::string_view PathElement)
/*++
Routine Description:
This routine adds the specified path element to the $PATH variable of the
supplied environment block.
Arguments:
Environment - Supplies the environment block to update.
PathElement - Supplies a path element to add to the $PATH variable. If no
$PATH variable exists, one is created.
Return Value:
None.
--*/
try
{
//
// If no PATH variable is present, create a new variable. If a PATH is
// present, add the path element onto the end of the existing value.
//
auto Path = Environment.GetVariable(PATH_ENV);
if (Path.empty())
{
Environment.AddVariable(PATH_ENV, PathElement);
}
else
{
std::string NewPath{Path};
if (NewPath.back() != ':')
{
NewPath += ':';
}
NewPath += PathElement;
Environment.AddVariable(PATH_ENV, NewPath);
}
return;
}
CATCH_LOG()
void ConfigHandleInteropMessage(
wsl::shared::SocketChannel& ResponseChannel,
wsl::shared::SocketChannel& InteropChannel,
bool Elevated,
gsl::span<gsl::byte> Message,
const MESSAGE_HEADER* Header,
const wsl::linux::WslDistributionConfig& Config)
/*++
Routine Description:
This routine handles a message received from a Linux client using init's
interop socket.
Arguments:
ResponseChannel - Supplies channel used to send responses.
InteropChannel - Supplies a channel to the host to be used for create
process requests.
Elevated - Supplies a boolean specifying if the elevated DrvFs share should be used.
Message - Supplies the message buffer.
Header- Supplies the message Header.
Return Value:
None.
--*/
try
{
switch (Header->MessageType)
{
case LxInitMessageCreateProcessUtilityVm:
if (InteropChannel.Socket() > 0)
{
InteropChannel.SendMessage<LX_INIT_CREATE_NT_PROCESS_UTILITY_VM>(Message);
}
break;
case LxInitMessageQueryDrvfsElevated:
{
ResponseChannel.SendResultMessage<bool>(Elevated);
break;
}
case LxInitMessageQueryEnvironmentVariable:
{
auto* Query = gslhelpers::try_get_struct<LX_INIT_QUERY_ENVIRONMENT_VARIABLE>(Message);
if (!Query)
{
LOG_ERROR("Unexpected MessageSize {}", Message.size());
return;
}
auto Value = UtilGetEnvironmentVariable(Query->Buffer);
wsl::shared::MessageWriter<LX_INIT_QUERY_ENVIRONMENT_VARIABLE> Response(LxInitMessageQueryEnvironmentVariable);
Response.WriteString(Value);
ResponseChannel.SendMessage<LX_INIT_QUERY_ENVIRONMENT_VARIABLE>(Response.Span());
}
break;
case LxInitMessageQueryFeatureFlags:
{
assert(Config.FeatureFlags.has_value());
ResponseChannel.SendResultMessage<int32_t>(Config.FeatureFlags.value());
break;
}
case LxInitMessageCreateLoginSession:
{
auto* CreateSession = gslhelpers::try_get_struct<LX_INIT_CREATE_LOGIN_SESSION>(Message);
if (!CreateSession)
{
LOG_ERROR("Unexpected MessageSize {}", Message.size());
return;
}
if (!Config.BootInit || Config.InitPid.value_or(0) != getpid())
{
LOG_ERROR("Unexpected LxInitMessageCreateLoginSession message");
return;
}
static std::mutex LoginSessionsLock;
static std::map<uid_t, int> LoginSessions;
// Keep track of login sessions that have been created.
LoginSessionsLock.lock();
auto Unlock = wil::scope_exit([&]() { LoginSessionsLock.unlock(); });
if (LoginSessions.contains(CreateSession->Uid))
{
return;
}
// Symlink the content of the WSLG XDG runtime dir onto the user's runtime path and
// create a login session to initialize PAM for the user.
if (Config.GuiAppsEnabled)
{
auto* RuntimeDir = getenv(XDG_RUNTIME_DIR_ENV);
if (RuntimeDir)
{
// Create a tmpfs mount point for the user directory.
auto userFolder = std::format("/run/user/{}", CreateSession->Uid);
UtilMount("tmpfs", userFolder.c_str(), "tmpfs", (MS_NOSUID | MS_NODEV | MS_NOEXEC), "mode=755");
// Create the directory structure for wslg's symlinks.
for (const auto* e : {"/", "/dbus-1", "/dbus-1/service", "/pulse"})
{
auto target = userFolder + e;
UtilMkdir(target.c_str(), 0777);
if (chown(target.c_str(), CreateSession->Uid, CreateSession->Gid) < 0)
{
LOG_ERROR("chown({}, {}, {}) failed {}", target, CreateSession->Uid, CreateSession->Gid, errno);
}
}
// Create the actual symlinks.
for (const auto* e : {"wayland-0", "wayland-0.lock", "pulse/native", "pulse/pid"})
{
auto link = std::format("{}/{}", userFolder, e);
if (unlink(link.c_str()) < 0 && errno != ENOENT)
{
LOG_ERROR("unlink({}) failed {}", link, errno);
}
auto target = RuntimeDir + std::string("/") + e;
if (symlink(target.c_str(), link.c_str()) < 0)
{
LOG_ERROR("symlink({}, {}) failed {}", target, link, errno);
}
}
}
else
{
LOG_ERROR("getenv({}) failed {}", XDG_RUNTIME_DIR_ENV, errno);
}
}
int LoginLeader;
const int Result = forkpty(&LoginLeader, nullptr, nullptr, nullptr);
if (Result < 0)
{
LOG_ERROR("forkpty failed {}", errno);
return;
}
else if (Result == 0)
{
Unlock.reset();
_exit(execl("/bin/login", "/bin/login", "-f", CreateSession->Buffer, nullptr));
}
LoginSessions.emplace(CreateSession->Uid, LoginLeader);
break;
}
case LxInitMessageQueryNetworkingMode:
assert(Config.NetworkingMode.has_value());
ResponseChannel.SendResultMessage<uint8_t>(static_cast<uint8_t>(Config.NetworkingMode.value()));
break;
default:
LOG_ERROR("unexpected message {}", Header->MessageType);
break;
}
}
CATCH_LOG()
wsl::linux::WslDistributionConfig ConfigInitializeCommon(struct sigaction* SavedSignalActions)
/*++
Routine Description:
This routine sets up common devices and mounts.
Arguments:
SavedSignalActions - Supplies an array to save default signal actions.
Return Value:
0 on success, -1 on failure.
--*/
{
wil::unique_fd DevNullFd;
unsigned int Index;
//
// Set the umask to 0 to ensure that devices and files that init creates
// have the correct mode.
//
umask(0);
//
// Perform initialization required for logging to kmsg.
//
if (!UtilIsUtilityVm())
{
for (Index = 0; Index < COUNT_OF(LxssStartupLoggingWsl); Index += 1)
{
THROW_LAST_ERROR_IF(ConfigInitializeEntry(&LxssStartupLoggingWsl[Index]) < 0);
}
}
else
{
for (Index = 0; Index < COUNT_OF(LxssStartupLoggingVmMode); Index += 1)
{
THROW_LAST_ERROR_IF(ConfigInitializeEntry(&LxssStartupLoggingVmMode[Index]) < 0);
}
}
//
// Open /dev/kmsg for logging.
//
THROW_LAST_ERROR_IF(InitializeLogging(true) < 0);
//
// Ignore all signals except SIGHUP and signals that cannot be ignored.
//
// N.B. Ignoring SIGCHLD automatically reaps zombie processes.
//
// N.B. Child processes reset signals to default before calling execv.
//
THROW_LAST_ERROR_IF(UtilSaveSignalHandlers(SavedSignalActions) < 0);
THROW_LAST_ERROR_IF(UtilSetSignalHandlers(SavedSignalActions, true) < 0);
//
// Load the configuration file.
//
wsl::linux::WslDistributionConfig Config{CONFIG_FILE};
//
// Initialize the static entries.
//
for (Index = 0; Index < COUNT_OF(LxssStartupCommon); Index += 1)
{
THROW_LAST_ERROR_IF(ConfigInitializeEntry(&LxssStartupCommon[Index]) < 0);
}
//
// Initialize WSL1 and WSL2 specific environment.
//
if (!UtilIsUtilityVm())
{
THROW_LAST_ERROR_IF(ConfigInitializeWsl() < 0);
}
//
// Open /dev/null for the stdin and stdout in case libraries try to use
// them (but keep stderr open for kmsg logging).
//
DevNullFd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
THROW_LAST_ERROR_IF(!DevNullFd);
for (const auto& Fd : {STDIN_FILENO, STDOUT_FILENO})
{
THROW_LAST_ERROR_IF(dup2(DevNullFd.get(), Fd) < 0);
}
//
// Initialize cgroups based on what the kernel supports.
//
ConfigInitializeCgroups();
//
// Attempt to register the NT interop binfmt extension.
//
// N.B. Registration for VM mode is done by mini_init.
//
if ((!UtilIsUtilityVm()) && (Config.InteropEnabled))
{
ConfigRegisterBinfmtInterpreter();
}
//
// Ensure the target for automounts exists.
//
if ((Config.AutoMount) || ((UtilIsUtilityVm())))
{
UtilMkdirPath(Config.DrvFsPrefix.c_str(), AUTO_MOUNT_PARENT_MODE, false);
}
//
// Initialization successful.
//
return Config;
}
void ConfigInitializeX11(const wsl::linux::WslDistributionConfig& Config)
try
{
auto socketPath = "/tmp/" X11_SOCKET_NAME;
THROW_LAST_ERROR_IF(UtilMkdir(socketPath, 0775) < 0);
std::string source{Config.DrvFsPrefix};
source += WSLG_SHARED_FOLDER;
source += "/" X11_SOCKET_NAME;
THROW_LAST_ERROR_IF(mount(source.c_str(), socketPath, NULL, (MS_BIND | MS_REC), NULL) < 0);
// The .X11-unix folder is mounted read-only so the socket file can't be removed.
// It's left writable in the system distro since wslg is supposed to write to that folder to create it.
if (WI_IsFlagClear(Config.FeatureFlags.value(), LxInitFeatureSystemDistro))
{
THROW_LAST_ERROR_IF(mount("none", socketPath, NULL, (MS_RDONLY | MS_REMOUNT | MS_BIND), NULL) < 0);
}
}
CATCH_LOG()
int ConfigInitializeInstance(wsl::shared::SocketChannel& Channel, gsl::span<gsl::byte> Buffer, wsl::linux::WslDistributionConfig& Config)
/*++
Routine Description:
This routine initializes the instance's externally controlled state, which
is received from the service.
N.B. When setting these values errors are treated as non-fatal to account
for unexpected distro state.
Arguments:
MessageFd - Supplies a file descriptor to send the response message.
Buffer - Supplies the message buffer.
Return Value:
0 on success, -1 on failure.
--*/
try
{
//
// Validate input parameters.
//
const auto* Message = gslhelpers::try_get_struct<const LX_INIT_CONFIGURATION_INFORMATION>(Buffer);
if (!Message)
{
FATAL_ERROR("Unexpected configuration size {}", Buffer.size());
}
//
// Set the host name and domain name buffers.
//
std::string Hostname = wsl::shared::string::FromSpan(Buffer, Message->HostnameOffset);
auto* Domainname = wsl::shared::string::FromSpan(Buffer, Message->DomainnameOffset);
auto* WindowsHosts = wsl::shared::string::FromSpan(Buffer, Message->WindowsHostsOffset);
auto* DistributionName = wsl::shared::string::FromSpan(Buffer, Message->DistributionNameOffset);
auto* Plan9SocketPath = wsl::shared::string::FromSpan(Buffer, Message->Plan9SocketOffset);
auto* Timezone = wsl::shared::string::FromSpan(Buffer, Message->TimezoneOffset);
bool Elevated = Message->DrvfsMount == LxInitDrvfsMountElevated;
const std::string ThreadName = std::format("{}({})", (Config.BootInit ? "init-systemd" : "init"), DistributionName);
UtilSetThreadName(ThreadName.c_str());
//
// Store feature flags for future use.
//
// N.B. This is also stored in an environment variable so that mount.drvfs, when launched
// through fstab mounting below, can use that. This is needed because mount.drvfs won't
// be able to connect to init during this call. This environment variable is not present
// for user-launched processes.
//
Config.FeatureFlags = Message->FeatureFlags;
char FeatureFlagsString[10];
snprintf(FeatureFlagsString, sizeof(FeatureFlagsString), "%x", Config.FeatureFlags.value());
if (setenv(WSL_FEATURE_FLAGS_ENV, FeatureFlagsString, 1) < 0)
{
LOG_ERROR("setenv failed {}", errno);
}
//
// Determine the default UID which can be specified in /etc/wsl.conf.
//
uid_t DefaultUid = Message->DrvFsDefaultOwner;
if (Config.DefaultUser.has_value())
{
passwd* PasswordEntry = getpwnam(Config.DefaultUser->c_str());
if (PasswordEntry == nullptr)
{
LOG_ERROR("getpwnam({}) failed {}", Config.DefaultUser->c_str(), errno);
}
else
{
DefaultUid = PasswordEntry->pw_uid;
}
}
//
// Process the /etc/fstab file.
//
// N.B. This must happen before mounting DrvFs volumes because the user may
// have specified DrvFs mounts in /etc/fstab and they should overwrite defaults.
//
if (Config.MountFsTab)
{
ConfigMountFsTab(Elevated);
}
//
// Perform additional WSL2-specific mounts.
//
if (UtilIsUtilityVm())
{
if (ConfigInitializeVmMode(Elevated, Config) < 0)
{
FATAL_ERROR("ConfigInitializeVmMode");
}
}
if (Config.AutoMount && (Message->DrvfsMount != LxInitDrvfsMountNone))
{
ConfigMountDrvFsVolumes(Message->DrvFsVolumesBitmap, DefaultUid, Elevated, Config);
}
//
// If a hostname was specified in /etc/wsl.conf, use it.
//
if (Config.HostName.has_value())
{
Hostname = Config.HostName.value();
LOG_WARNING("hostname set to {} in {}", Hostname.c_str(), CONFIG_FILE);
}
//
// Sanitize the hostname.
//
// N.B. If systemd is enabled, systemd-hostnamed will cleanup the
// hostname, which can lead to a disconnect if that doesn't match
// what we write in /etc/hostname & /etc/hosts, so to hostname needs
// to be cleaned up before being passed to systemd.
//
// N.B. While the Windows UI doesn't let the user set an invalid hostname
// (from systemd-hostnamed's perspective), it's possible to override that
// via Rename-Computer.
Hostname = wsl::shared::string::CleanHostname(Hostname);
//
// Update the host and domain name.
//
if (sethostname(Hostname.c_str(), Hostname.size()) < 0)
{
LOG_ERROR("sethostname({}) failed {}", Hostname.c_str(), errno);
Hostname = wsl::shared::string::c_defaultHostName;
if (sethostname(Hostname.c_str(), Hostname.size()) < 0)
{
LOG_ERROR("sethostname({}) failed {}", Hostname.c_str(), errno);
}
}
if (setenv(NAME_ENV, Hostname.c_str(), 1) < 0)
{
LOG_ERROR("setenv({}, {}) failed {}", NAME_ENV, Hostname.c_str(), errno);
}
//
// Update the domain name.
//
if (setdomainname(Domainname, strlen(Domainname)) < 0)
{
LOG_ERROR("setdomainname({}) failed {}", Domainname, errno);
}
//
// Generate and write /etc/hostname.
//
wil::unique_fd HostnameFd{TEMP_FAILURE_RETRY(creat(HOSTNAME_FILE_PATH, HOSTNAME_FILE_MODE))};
if (!HostnameFd)
{
LOG_ERROR("creat {} failed: {}", HOSTNAME_FILE_PATH, errno);
}
else
{
try
{
auto FileContents = std::format("{}\n", Hostname);
if (UtilWriteStringView(HostnameFd.get(), FileContents) < 0)
{
LOG_ERROR("write failed {}", errno);
}
}
CATCH_LOG()
}
HostnameFd.reset();
//
// Generate and write /etc/hosts.
//
if (Config.GenerateHosts)
{
wil::unique_fd HostsFd{TEMP_FAILURE_RETRY(creat(HOSTS_FILE_PATH, HOSTS_FILE_MODE))};
if (!HostsFd)
{
LOG_ERROR("creat {} failed {}", HOSTS_FILE_PATH, errno);
}
else
{
try
{
auto FileContents = std::format(HostsFileFormatString, Hostname.c_str(), Domainname, Hostname.c_str(), WindowsHosts);
if (UtilWriteStringView(HostsFd.get(), FileContents) < 0)
{
LOG_ERROR("write failed {}", errno);
}
}
CATCH_LOG()
}
}
else
{
LOG_WARNING("{} updating disabled in {}", HOSTS_FILE_PATH, CONFIG_FILE);
}
//
// Store the distribution name.
//
if (setenv(WSL_DISTRO_NAME_ENV, DistributionName, 1) < 0)
{
LOG_ERROR("setenv({}, {}, 1) failed {}", WSL_DISTRO_NAME_ENV, DistributionName, errno);
}
//
// Run the Plan 9 server. This requires a DrvFs mount for the socket file,
// so either fstab or automount must be enabled to have a chance the mount
// exists.
//
// N.B. Failure to start the server is non-fatal.
//
unsigned int Plan9Port = LX_INIT_UTILITY_VM_INVALID_PORT;
if ((WI_IsFlagClear(Config.FeatureFlags.value(), LxInitFeatureDisable9pServer)) && (Config.Plan9Enabled) &&
(Config.AutoMount || Config.MountFsTab))
{
std::tie(Plan9Port, Config.Plan9ControlChannel) = StartPlan9Server(Plan9SocketPath, Config);
}
//
// If the root filesystem is compressed, log a warning.
//
if (WI_IsFlagSet(Config.FeatureFlags.value(), LxInitFeatureRootfsCompressed))
{
LOG_WARNING("{} root file system is compressed, performance may be severly impacted.", DistributionName);
}
//
// Update the timezone.
//
UpdateTimezone(Timezone, Config);
if (Config.BootInit)
{
try
{
// Create the /run/user bind mount.
// This mount is required because systemd will mount a tmpfs on each /run/user/<uid> folder
// so /run/user need to be in the global mount namespace so both elevated and non elevated processes see it.
const auto UserMountTarget = Config.DrvFsPrefix + WSLG_SHARED_FOLDER "/run/user";
THROW_LAST_ERROR_IF(UtilMkdirPath(UserMountTarget.c_str(), 0755) < 0);
THROW_LAST_ERROR_IF(UtilMount(UserMountTarget.c_str(), RUN_FOLDER "/" USER_MOUNT_FOLDER, nullptr, MS_BIND, nullptr) < 0)
}
CATCH_LOG();
}
//
// Create a listening hvsocket for interop if the feature is enabled.
//
wil::unique_fd ListenSocket{};
sockaddr_vm SocketAddress{};
if (UtilIsUtilityVm() && Config.InteropEnabled)
{
ListenSocket = UtilListenVsockAnyPort(&SocketAddress, 1);
}
//
// Send the config response to the service.
//
wsl::shared::MessageWriter<LX_INIT_CONFIGURATION_INFORMATION_RESPONSE> Response(LxInitMessageInitializeResponse);
Response->Plan9Port = Plan9Port;
Response->DefaultUid = DefaultUid;
Response->InteropPort = ListenSocket ? SocketAddress.svm_port : LX_INIT_UTILITY_VM_INVALID_PORT;
Response->SystemdEnabled = Config.BootInit;
struct stat PidNamespaceInfo = {};
THROW_LAST_ERROR_IF(stat("/proc/self/ns/pid", &PidNamespaceInfo));
Response->PidNamespace = PidNamespaceInfo.st_ino;
static_assert(sizeof(Response->PidNamespace) == sizeof(PidNamespaceInfo.st_ino));
auto [Flavor, Version] = UtilReadFlavorAndVersion("/etc/os-release");
if (Flavor.has_value())
{
Response.WriteString(Response->FlavorIndex, Flavor->c_str());
}
if (Version.has_value())
{
Response.WriteString(Response->VersionIndex, Version->c_str());
}
Channel.SendMessage<LX_INIT_CONFIGURATION_INFORMATION_RESPONSE>(Response.Span());
//
// Accept the interop connection.
//
wsl::shared::SocketChannel InteropChannel;
if (ListenSocket)
{
InteropChannel = {UtilAcceptVsock(ListenSocket.get(), SocketAddress, INTEROP_TIMEOUT_MS), "Interop"};
}
//
// Create a thread to handle interop requests.
//
InteropServer InteropServer;
if (InteropServer.Create() < 0)
{
FATAL_ERROR("Could not create init interop server");
}
//
// If init is not running as pid 1, create a symlink to the interop server that was created.
//
if (Config.InitPid.has_value())
try