forked from microsoft/WSL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrvfs.cpp
More file actions
635 lines (455 loc) · 16.6 KB
/
drvfs.cpp
File metadata and controls
635 lines (455 loc) · 16.6 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
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
drvfs.c
Abstract:
This file contains DrvFs function definitions.
--*/
#include "common.h"
#include <sys/mount.h>
#include <stdarg.h>
#include <mountutilcpp.h>
#include "util.h"
#include "drvfs.h"
#include "config.h"
#include "message.h"
#include <cassert>
#include <optional>
using namespace std::chrono_literals;
#define PLAN9_CASE_OPTION "case="
#define PLAN9_CASE_OPTION_DIR PLAN9_CASE_OPTION "dir"
#define PLAN9_CASE_OPTION_FORCE PLAN9_CASE_OPTION "force"
#define PLAN9_CASE_OPTION_OFF PLAN9_CASE_OPTION "off"
#define PLAN9_SYMLINK_ROOT_OPTION "symlinkroot="
#define PLAN9_UNC_PREFIX_LENGTH (2)
#define LOG_STDERR(_errno) fprintf(stderr, "mount: %s\n", strerror(_errno))
constexpr int c_exitCodeInvalidUsage = 1;
constexpr int c_exitCodeMountFail = 32;
int MountFilesystem(const char* FsType, const char* Source, const char* Target, const char* Options, int* ExitCode = nullptr);
int MountWithRetry(const char* Source, const char* Target, const char* FsType, const char* Options, int* ExitCode = nullptr);
std::pair<std::string, std::string> ConvertDrvfsMountOptionsToPlan9(std::string_view Options, const wsl::linux::WslDistributionConfig& Config)
/*++
Routine Description:
This routine converts each applicable DrvFs mount option into a 9p mount option and splits
non-DrvFs options to a different list.
Arguments:
Options - Supplies the DrvFs mount options.
Return Value:
A pair representing the 9p mount options, and standard mount options.
--*/
{
using wsl::shared::string::StartsWith;
std::string Plan9Options{};
std::string StandardOptions{};
while (!Options.empty())
{
auto Option = UtilStringNextToken(Options, ",");
if ((Option == "metadata") || (StartsWith(Option, PLAN9_CASE_OPTION)) || (StartsWith(Option, "uid=")) ||
(StartsWith(Option, "gid=")) || (StartsWith(Option, "umask=")) || (StartsWith(Option, "dmask=")) ||
(StartsWith(Option, "fmask=")) || (StartsWith(Option, PLAN9_SYMLINK_ROOT_OPTION)))
{
if (Option == PLAN9_CASE_OPTION_FORCE)
{
LOG_WARNING("{} not supported, using {}", PLAN9_CASE_OPTION_FORCE, PLAN9_CASE_OPTION_DIR);
Option = PLAN9_CASE_OPTION_DIR;
}
Plan9Options += ';';
Plan9Options += Option;
}
else if (StartsWith(Option, "fallback="))
{
LOG_WARNING("{} not supported, ignoring...", Option);
}
else
{
StandardOptions += Option;
StandardOptions += ',';
}
}
Plan9Options += ";" PLAN9_SYMLINK_ROOT_OPTION;
Plan9Options += Config.DrvFsPrefix;
return {std::move(Plan9Options), std::move(StandardOptions)};
}
bool IsDrvfsElevated(void)
/*++
Routine Description:
This routine determines whether drvfs mounts should use the elevated server.
Arguments:
None.
Return Value:
True if this process should use the elevated server; otherwise, false.
--*/
{
const char* envFlag = getenv(WSL_DRVFS_ELEVATED_ENV);
if (envFlag != nullptr)
{
if (strcmp(envFlag, "0") == 0)
{
return false;
}
else if (strcmp(envFlag, "1") == 0)
{
return true;
}
LOG_ERROR("Unexpected value for {}: '{}'", WSL_DRVFS_ELEVATED_ENV, envFlag);
}
//
// Establish a connection to the interop server. If the connection cannot
// be established, use the non-admin DrvFs port.
//
wsl::shared::SocketChannel channel{UtilConnectToInteropServer(), "InteropClientDrvfs"};
if (channel.Socket() < 0)
{
return false;
}
//
// Query the interop server for which port to use.
//
MESSAGE_HEADER QueryPortMessage;
QueryPortMessage.MessageType = LxInitMessageQueryDrvfsElevated;
QueryPortMessage.MessageSize = sizeof(QueryPortMessage);
channel.SendMessage(QueryPortMessage);
return channel.ReceiveMessage<RESULT_MESSAGE<bool>>().Result;
}
int MountFilesystem(const char* FsType, const char* Source, const char* Target, const char* Options, int* ExitCode)
/*++
Routine Description:
This routine will perform a mount using the /bin/mount binary.
Arguments:
FsType - Supplies the file system type.
Source - Supplies the mount source.
Target - Supplies the mount target.
Options - Supplies the mount options.
ExitCode - Supplies an optional pointer that receives the exit code.
Return Value:
0 on success, -1 on failure.
--*/
{
const char* const Argv[] = {
MOUNT_COMMAND, MOUNT_INTERNAL_ONLY_ARG, MOUNT_TYPES_ARG, FsType, Source, Target, MOUNT_OPTIONS_ARG, Options, nullptr};
int Status = 0;
const int Result = UtilCreateProcessAndWait(Argv[0], Argv, &Status);
//
// If the mount process failed, make sure its exit code is propagated. If it terminated
// abnormally or could not be launched, just return failure.
//
if (ExitCode != nullptr)
{
if (Result < 0)
{
if (WIFEXITED(Status) && Status != 0)
{
*ExitCode = WEXITSTATUS(Status);
}
else
{
*ExitCode = c_exitCodeMountFail;
}
}
else
{
*ExitCode = 0;
}
}
return Result;
}
int MountWithRetry(const char* Source, const char* Target, const char* FsType, const char* Options, int* ExitCode)
/*++
Routine Description:
This routine will perform a mount using the /bin/mount binary, and will
retry it if it fails.
N.B. This routine is used for virtio-9p and virtiofs which can transiently
fail to mount if the PCI device isn't ready yet.
Arguments:
Source - Supplies the mount source.
Target - Supplies the mount target.
FsType - Supplies the filesystem type.
Options - Supplies the mount options.
ExitCode - Supplies an optional pointer that receives the exit code.
Return Value:
0 on success, -1 on failure.
--*/
try
{
int Result;
try
{
bool PrintWarning = true;
wsl::shared::retry::RetryWithTimeout<void>(
[&]() { THROW_LAST_ERROR_IF(mountutil::MountFilesystem(Source, Target, FsType, Options) < 0); },
std::chrono::milliseconds{100},
std::chrono::seconds{2},
[&]() {
// For virtio-9p, there are two errors that could indicate the PCI device is not ready:
// EBUSY - Returned if all devices with the tag are already in use.
// ENOENT - Returned if there are no devices with the tag, which can happen after the VM first boots.
// In this case, check if the the target exists; if it doesn't, ENOENT is for that and there's no reason to retry.
//
// For virtiofs, EINVAL will be returned if the tag is not ready.
auto savedErrno = wil::ResultFromCaughtException();
if (strcmp(FsType, PLAN9_FS_TYPE) == 0)
{
if (errno != EBUSY && (errno != ENOENT || access(Target, F_OK) != 0))
{
errno = savedErrno;
return false;
}
}
else if ((strcmp(FsType, VIRTIO_FS_TYPE) == 0) && (errno != EINVAL))
{
return false;
}
if (PrintWarning)
{
LOG_WARNING("mount: waiting for virtio device {}", Source);
PrintWarning = false;
}
return true;
});
Result = 0;
}
catch (...)
{
errno = wil::ResultFromCaughtException();
auto parsed = mountutil::MountParseFlags(Options);
LOG_ERROR("mount({}, {}, {}, {:#x}, {}) failed: {}", Source, Target, FsType, parsed.MountFlags, parsed.StringOptions.c_str(), strerror(errno));
Result = -1;
}
if (ExitCode)
{
*ExitCode = Result < 0 ? c_exitCodeMountFail : 0;
}
return Result;
}
CATCH_RETURN_ERRNO()
int MountDrvfs(const char* Source, const char* Target, const char* Options, std::optional<bool> Admin, const wsl::linux::WslDistributionConfig& Config, int* ExitCode)
/*++
Routine Description:
This routine will perform a DrvFs mount.
Arguments:
Source - Supplies the mount source.
Target - Supplies the mount target.
Options - Supplies the mount options.
Admin - Supplies an optional boolean to specify if the admin or non-admin share should be used.
ExitCode - Supplies an optional pointer that receives the exit code.
Return Value:
0 on success, -1 on failure.
--*/
try
{
if (!UtilIsUtilityVm())
{
return MountFilesystem(DRVFS_FS_TYPE, Source, Target, Options, ExitCode);
}
// Use virtiofs if the source of the mount is the root of a drive, otherwise use 9p.
if (WSL_USE_VIRTIO_FS(Config))
{
if (wsl::shared::string::IsDriveRoot(Source))
{
return MountVirtioFs(Source, Target, Options, Admin, Config, ExitCode);
}
LOG_WARNING("virtiofs is only supported for mounting full drives, using 9p to mount {}", Source);
}
//
// Check if the path is a UNC path.
//
const char* Plan9Source;
std::string UncSource;
if ((strlen(Source) >= PLAN9_UNC_PREFIX_LENGTH) && ((Source[0] == '/') || (Source[0] == '\\')) &&
((Source[1] == '/') || (Source[1] == '\\')))
{
UncSource = PLAN9_UNC_TRANSLATED_PREFIX;
UncSource += &Source[PLAN9_UNC_PREFIX_LENGTH];
Plan9Source = UncSource.c_str();
}
else
{
Plan9Source = Source;
}
//
// Check whether to use the elevated or regular 9p server.
//
bool Elevated = Admin.has_value() ? Admin.value() : IsDrvfsElevated();
//
// Initialize mount options.
//
auto Plan9Options = std::format("{};path={}", PLAN9_ANAME_DRVFS, Plan9Source);
//
// N.B. The cache option is added to the start of this so if the user
// specifies one explicitly, it will override the default.
//
std::string MountOptions = "cache=mmap,";
auto ParsedOptions = ConvertDrvfsMountOptionsToPlan9(Options ? Options : "", Config);
Plan9Options += ParsedOptions.first;
MountOptions += ParsedOptions.second;
//
// Append the 9p mount options to the end of the other mount options and perform the mount operation.
//
MountOptions += Plan9Options;
if (MountPlan9Filesystem(Source, Target, MountOptions.c_str(), Elevated, Config, ExitCode) < 0)
{
return -1;
}
return 0;
}
CATCH_RETURN_ERRNO()
int MountDrvfsEntry(int Argc, char* Argv[])
/*++
Routine Description:
This routine is the entrypoint for mount.drvfs.
Arguments:
Argc - Supplies the argument count.
Argv - Supplies the command line arguments.
Return Value:
0 on success, -1 on failure.
--*/
{
if (Argc < 3)
{
LOG_STDERR(EINVAL);
return c_exitCodeInvalidUsage;
}
//
// Handle mount options if provided.
//
auto* Options = "";
if (Argc > 4)
{
Options = Argv[4];
}
int ExitCode = c_exitCodeMountFail;
MountDrvfs(Argv[1], Argv[2], Options, {}, wsl::linux::WslDistributionConfig{CONFIG_FILE}, &ExitCode);
return ExitCode;
}
int MountPlan9Filesystem(const char* Source, const char* Target, const char* Options, bool Admin, const wsl::linux::WslDistributionConfig& Config, int* ExitCode)
/*++
Routine Description:
This routine will perform a plan 9 mount using the /bin/mount binary.
Arguments:
Source - Supplies the mount source.
Target - Supplies the mount target.
Options - Supplies the mount options.
Admin - Supplies a boolean specifying if the admin share should be used.
ExitCode - Supplies an optional pointer that receives the exit code.
Return Value:
0 on success, -1 on failure.
--*/
{
std::string MountOptions;
if (WSL_USE_VIRTIO_9P(Config))
{
Source = Admin ? LX_INIT_DRVFS_ADMIN_VIRTIO_TAG : LX_INIT_DRVFS_VIRTIO_TAG;
MountOptions = std::format("msize=262144,trans=virtio,{}", Options);
return MountWithRetry(Source, Target, PLAN9_FS_TYPE, MountOptions.c_str(), ExitCode);
}
else
{
auto Port = Admin ? LX_INIT_UTILITY_VM_PLAN9_DRVFS_ADMIN_PORT : LX_INIT_UTILITY_VM_PLAN9_DRVFS_PORT;
wil::unique_fd Fd{UtilConnectVsock(Port, false, LX_INIT_UTILITY_VM_PLAN9_BUFFER_SIZE)};
if (!Fd)
{
return -1;
}
MountOptions =
std::format("msize={},trans=fd,rfdno={},wfdno={},{}", LX_INIT_UTILITY_VM_PLAN9_BUFFER_SIZE, Fd.get(), Fd.get(), Options);
return MountFilesystem(PLAN9_FS_TYPE, Source, Target, MountOptions.c_str(), ExitCode);
}
}
int MountVirtioFs(const char* Source, const char* Target, const char* Options, std::optional<bool> Admin, const wsl::linux::WslDistributionConfig& Config, int* ExitCode)
/*++
Routine Description:
This routine mounts a virtiofs share. The DrvFs mount options are converted into 9p mount options
which are used to determine behavior when the device is added to the host.
Arguments:
Source - Supplies the mount source.
Target - Supplies the mount target.
Options - Supplies DrvFs mount options to translate into Plan9 mount
options.
Admin - Supplies an optional boolean to specify if the admin or non-admin server should be used.
ExitCode - Supplies an optional pointer that receives the exit code.
Return Value:
0 on success, -1 on failure.
--*/
try
{
assert(wsl::shared::string::IsDriveRoot(Source));
//
// Check whether to use the elevated or non-elevated virtiofs server.
//
if (!Admin.has_value())
{
Admin = IsDrvfsElevated();
}
//
// Convert the DrvFs mount options.
//
// N.B. Since virtiofs does not allow passing mount options, the 9p mount options are used to specify share
// behavior when creating virtiofs shares on the host.
//
auto [Plan9Options, MountOptions] = ConvertDrvfsMountOptionsToPlan9(Options ? Options : "", Config);
//
// Construct a request to add a virtiofs share.
//
wsl::shared::MessageWriter<LX_INIT_ADD_VIRTIOFS_SHARE_MESSAGE> AddShare(LxInitMessageAddVirtioFsDevice);
AddShare->Admin = Admin.value();
AddShare.WriteString(AddShare->PathOffset, Source);
AddShare.WriteString(AddShare->OptionsOffset, Plan9Options);
//
// Connect to the wsl service to add the virtiofs share.
//
wsl::shared::SocketChannel Channel{UtilConnectVsock(LX_INIT_UTILITY_VM_VIRTIOFS_PORT, true), "VirtoFs"};
if (Channel.Socket() < 0)
{
return -1;
}
gsl::span<gsl::byte> ResponseSpan;
const auto& Response = Channel.Transaction<LX_INIT_ADD_VIRTIOFS_SHARE_MESSAGE>(AddShare.Span(), &ResponseSpan);
if (Response.Result != 0)
{
LOG_ERROR("Add virtiofs share for {} failed {}", Source, Response.Result);
return -1;
}
//
// Perform the mount operation.
//
auto* Tag = wsl::shared::string::FromSpan(ResponseSpan, Response.TagOffset);
return MountWithRetry(Tag, Target, VIRTIO_FS_TYPE, MountOptions.c_str(), ExitCode);
}
CATCH_RETURN_ERRNO()
int RemountVirtioFs(const char* Tag, const char* Target, const char* Options, bool Admin)
/*++
Routine Description:
This routine translates DrvFs mount options into Plan9 mount options and
mounts the share.
Arguments:
Tag - Supplies the virtiofs tag to remount.
Target - Supplies the mount target.
Options - Supplies mount options.
Admin - Supplies a boolean to specify if the admin or non-admin server should be used.
Return Value:
0 on success, -1 on failure.
--*/
try
{
wsl::shared::MessageWriter<LX_INIT_REMOUNT_VIRTIOFS_SHARE_MESSAGE> RemountShare(LxInitMessageRemountVirtioFsDevice);
RemountShare->Admin = Admin;
RemountShare.WriteString(RemountShare->TagOffset, Tag);
//
// Connect to the host and send the remount request.
//
wsl::shared::SocketChannel Channel{UtilConnectVsock(LX_INIT_UTILITY_VM_VIRTIOFS_PORT, true), "RemountVirtioFs"};
if (Channel.Socket() < 0)
{
return -1;
}
gsl::span<gsl::byte> ResponseSpan;
const auto& Response = Channel.Transaction<LX_INIT_REMOUNT_VIRTIOFS_SHARE_MESSAGE>(RemountShare.Span(), &ResponseSpan);
if (Response.Result != 0)
{
LOG_ERROR("Remount virtiofs share for {} failed {}", Tag, Response.Result);
return -1;
}
Tag = wsl::shared::string::FromSpan(ResponseSpan, Response.TagOffset);
return MountWithRetry(Tag, Target, VIRTIO_FS_TYPE, Options);
}
CATCH_RETURN_ERRNO()