forked from microsoft/WSL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.cpp
More file actions
3362 lines (2459 loc) · 74.8 KB
/
Copy pathutil.cpp
File metadata and controls
3362 lines (2459 loc) · 74.8 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:
util.c
Abstract:
This file utility function definitions.
--*/
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <grp.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <ctype.h>
#include <optional>
#include <fstream>
#include <iostream>
#include <sstream>
#include <regex>
#include "common.h"
#include "wslpath.h"
#include "util.h"
#include "drvfs.h"
#include "escape.h"
#include "config.h"
#include "mountutilcpp.h"
#include "message.h"
#include "RuntimeErrorWithSourceLocation.h"
#include "SocketChannel.h"
#include "Localization.h"
#define INITIAL_MESSAGE_BUFFER_SIZE (0x1000)
#define PLAN9_RDR_PREFIX "\\\\wsl.localhost\\"
#define PLAN9_RDR_COMPAT_PREFIX "\\\\wsl$\\"
#define WSLENV_ENV "WSLENV"
#define WSL_CGROUPS_FIELD_ENABLED (3)
#define WSL_CGROUPS_FIELD_MAX WSL_CGROUPS_FIELD_ENABLED
#define WSL_CGROUPS_FIELD_SEP '\t'
#define WSL_CGROUPS_FIELD_SUBSYSTEM (0)
#define WSL_MOUNT_OPTION_SEP ','
int g_IsVmMode = -1;
static sigset_t g_originalSignals;
thread_local std::string g_threadName;
namespace wil {
thread_local std::optional<std::stringstream> ScopedWarningsCollector::g_collectedWarnings;
}
int InteropServer::Create()
/*++
Routine Description:
This routine creates an interop server unix socket and starts listening on it.
Arguments:
None.
Return Value:
0 on success, -1 on failure.
--*/
{
if (!m_InteropSocketPath.empty())
{
LOG_ERROR("Interop server already created");
return -1;
}
//
// Generate a unique name to be used for the interop socket path.
//
m_InteropSocketPath = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, getpid(), WSL_INTEROP_SOCKET);
//
// Ensure the WSL temp folder exists and has the correct mode.
//
if (UtilMkdir(WSL_TEMP_FOLDER, WSL_TEMP_FOLDER_MODE) < 0)
{
return -1;
}
//
// Create a unix socket to handle interop requests.
//
// N.B. This is done before the child process is created to ensure that
// the socket is ready for connections.
//
m_InteropSocket.reset(socket(AF_UNIX, (SOCK_STREAM | SOCK_CLOEXEC), 0));
if (!m_InteropSocket)
{
LOG_ERROR("socket failed {}", errno);
return -1;
}
sockaddr_un InteropSocketAddress{};
InteropSocketAddress.sun_family = AF_UNIX;
strncpy(InteropSocketAddress.sun_path, m_InteropSocketPath.c_str(), (sizeof(InteropSocketAddress.sun_path) - 1));
auto Result = bind(m_InteropSocket.get(), reinterpret_cast<sockaddr*>(&InteropSocketAddress), sizeof(InteropSocketAddress));
if (Result < 0)
{
LOG_ERROR("bind failed {}", errno);
return -1;
}
Result = listen(m_InteropSocket.get(), -1);
if (Result < 0)
{
LOG_ERROR("listen failed {}", errno);
return -1;
}
//
// Ensure that any users can connect to the interop socket.
//
Result = chmod(m_InteropSocketPath.c_str(), 0777);
if (Result < 0)
{
LOG_ERROR("chmod failed {}", errno);
return -1;
}
return 0;
}
wil::unique_fd InteropServer::Accept() const
/*++
Routine Description:
This routine accepts a connection on the interop server.
Arguments:
None.
Return Value:
The socket.
--*/
{
wil::unique_fd InteropConnection{accept4(m_InteropSocket.get(), nullptr, nullptr, SOCK_CLOEXEC)};
if (!InteropConnection)
{
LOG_ERROR("accept4 failed {}", errno);
}
timeval Timeout{};
Timeout.tv_sec = INTEROP_TIMEOUT_SEC;
if (setsockopt(InteropConnection.get(), SOL_SOCKET, SO_RCVTIMEO, &Timeout, sizeof(Timeout)) < 0)
{
LOG_ERROR("setsockopt(SO_RCVTIMEO) failed {}", errno);
}
return InteropConnection;
}
void InteropServer::Reset()
{
if (!m_InteropSocketPath.empty())
{
unlink(m_InteropSocketPath.c_str());
m_InteropSocketPath = {};
}
}
InteropServer::~InteropServer()
{
Reset();
}
int UtilAcceptVsock(int SocketFd, sockaddr_vm SocketAddress, int Timeout)
/*++
Routine Description:
This routine accepts a socket connection.
Arguments:
SocketFd - Supplies a socket file descriptor.
SocketAddress - Supplies the socket address. This is passed by value instead
of by reference because accept4 modifies the structure to contain the
address of the peer socket.
Timeout - Supplies a timeout.
Return Value:
A file descriptor representing the socket, -1 on failure.
--*/
{
//
// If a timeout was specified, use a pollfd to wait for the accept.
//
int Result = 0;
if (Timeout == -1)
{
pollfd PollDescriptor{SocketFd, POLLIN, 0};
while (true)
{
Result = poll(&PollDescriptor, 1, 60 * 1000);
if (Result < 0)
{
LOG_ERROR("poll({}) failed, {}", SocketFd, errno);
return Result;
}
else if ((Result == 0) || ((PollDescriptor.revents & POLLIN) == 0))
{
LOG_ERROR("Waiting for abnormally long accept({})", SocketFd);
}
else
{
break;
}
}
}
else
{
pollfd PollDescriptor{SocketFd, POLLIN, 0};
Result = poll(&PollDescriptor, 1, Timeout);
if ((Result <= 0) || ((PollDescriptor.revents & POLLIN) == 0))
{
errno = ETIMEDOUT;
Result = -1;
}
}
if (Result != -1)
{
socklen_t SocketAddressSize = sizeof(SocketAddress);
Result = accept4(SocketFd, reinterpret_cast<sockaddr*>(&SocketAddress), &SocketAddressSize, SOCK_CLOEXEC);
}
if (Result < 0)
{
LOG_ERROR("accept4 failed {}", errno);
}
return Result;
}
int UtilBindVsockAnyPort(struct sockaddr_vm* SocketAddress, int Type)
/*++
Routine Description:
This routine creates a bound vsock socket an available port.
Arguments:
SocketAddress - Supplies a buffer to receive the socket address of the
socket.
Type - Supplies the socket type.
Return Value:
A file descriptor representing the bound socket, -1 on failure.
--*/
{
int Result;
socklen_t SocketAddressSize;
int SocketFd;
SocketFd = socket(AF_VSOCK, Type, 0);
if (SocketFd < 0)
{
Result = -1;
LOG_ERROR("socket failed {}", errno);
goto BindVsockAnyPortExit;
}
memset(SocketAddress, 0, sizeof(*SocketAddress));
SocketAddress->svm_family = AF_VSOCK;
SocketAddress->svm_cid = VMADDR_CID_ANY;
SocketAddress->svm_port = VMADDR_PORT_ANY;
SocketAddressSize = sizeof(*SocketAddress);
Result = bind(SocketFd, (const struct sockaddr*)SocketAddress, SocketAddressSize);
if (Result < 0)
{
LOG_ERROR("bind failed {}", errno);
goto BindVsockAnyPortExit;
}
//
// Query the socket name to get the assigned port.
//
Result = getsockname(SocketFd, (struct sockaddr*)SocketAddress, &SocketAddressSize);
if (Result < 0)
{
LOG_ERROR("getsockname failed {}", errno);
goto BindVsockAnyPortExit;
}
Result = SocketFd;
SocketFd = -1;
BindVsockAnyPortExit:
if (SocketFd != -1)
{
CLOSE(SocketFd);
}
return Result;
}
size_t UtilCanonicalisePathSeparator(char* Path, char Separator)
/*++
Routine Description:
This routine ensures all separators in Path use the specified separator.
Arguments:
Path - Supplies the path to canonicalise.
Separator - Supplies the separator character to be used.
Return Value:
The size of the new string.
--*/
{
size_t DestIndex;
size_t PathLength;
size_t SourceIndex;
DestIndex = 0;
SourceIndex = 0;
PathLength = strlen(Path);
//
// Iterate through the path, replacing all separators.
//
for (; SourceIndex < PathLength; SourceIndex++)
{
if (Path[SourceIndex] == PATH_SEP || Path[SourceIndex] == PATH_SEP_NT)
{
//
// Don't add a separator if previous char already is a separator.
// Also handle the special case where 'Path' is a UNC path (\\X or //X)
// where both separators should be kept.
//
if (DestIndex > 1 && Path[DestIndex - 1] == Separator)
{
continue;
}
Path[DestIndex] = Separator;
}
else
{
Path[DestIndex] = Path[SourceIndex];
}
DestIndex++;
}
Path[DestIndex] = '\0';
return DestIndex;
}
void UtilCanonicalisePathSeparator(std::string& Path, char Separator)
/*++
Routine Description:
This routine ensures all separators in Path use the specified separator.
Arguments:
Path - Supplies the path to canonicalise.
Separator - Supplies the separator character to be used.
Return Value:
None.
--*/
{
Path.resize(UtilCanonicalisePathSeparator(Path.data(), Separator));
}
wil::unique_fd UtilConnectToInteropServer(std::optional<pid_t> Pid)
/*++
Routine Description:
This routine connects to the interop server of the current client process.
Arguments:
Pid - Supplies an optional process ID to connect to.
Return Value:
A file descriptor representing the connected socket, -1 on failure.
--*/
try
{
char* InteropSocketPath;
std::string Path;
if (Pid.has_value())
{
Path = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, Pid.value(), WSL_INTEROP_SOCKET);
InteropSocketPath = Path.data();
}
else
{
//
// Query the interop server environment variable. If the process does not
// have the environment variable, or if the socket does not exists, search through parent process tree for an
// interop server.
//
InteropSocketPath = getenv(WSL_INTEROP_ENV);
if (InteropSocketPath == nullptr || (access(InteropSocketPath, F_OK) < 0 && errno == ENOENT))
{
pid_t Parent = getppid();
while (Parent > 0)
{
Path = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, Parent, WSL_INTEROP_SOCKET);
if (access(Path.c_str(), F_OK) == 0)
{
InteropSocketPath = Path.data();
break;
}
Parent = UtilGetPpid(Parent);
}
if (InteropSocketPath == nullptr)
{
return {};
}
setenv(WSL_INTEROP_ENV, InteropSocketPath, 1);
}
}
//
// Connect to the server and return the connected socket to the caller.
//
return UtilConnectUnix(InteropSocketPath);
}
CATCH_RETURN_ERRNO()
wil::unique_fd UtilConnectUnix(const char* Path)
/*++
Routine Description:
This routine connects to the specified unix socket path.
Arguments:
Path - Supplies the path of the unix socket.
Return Value:
The connected socket, or a default-initialized value on failure.
--*/
{
wil::unique_fd Socket{socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)};
if (!Socket)
{
LOG_ERROR("socket failed {}", errno);
return {};
}
sockaddr_un SocketAddress{};
SocketAddress.sun_family = AF_UNIX;
strncpy(SocketAddress.sun_path, Path, sizeof(SocketAddress.sun_path) - 1);
if (connect(Socket.get(), reinterpret_cast<sockaddr*>(&SocketAddress), sizeof(SocketAddress)) < 0)
{
LOG_ERROR("connect failed {}", errno);
return {};
}
return Socket;
}
wil::unique_fd UtilConnectVsock(unsigned int Port, bool CloseOnExec, std::optional<int> SocketBuffer) noexcept
/*++
Routine Description:
This routine connects to a vsock with the specified port.
Arguments:
Port - Supplies the port to connect to.
CloseOnExec - Supplies a boolean specifying if the socket file descriptor should be closed on exec.
SocketBuffer - Optionally supplies the size to use for the socket send and receive buffers.
Return Value:
A file descriptor representing the connected socket, -1 on failure.
--*/
{
int Type = SOCK_STREAM;
WI_SetFlagIf(Type, SOCK_CLOEXEC, CloseOnExec);
wil::unique_fd SocketFd{socket(AF_VSOCK, Type, 0)};
if (!SocketFd)
{
LOG_ERROR("socket failed {}", errno);
return {};
}
//
// Set the socket connect timeout.
//
timeval Timeout{};
Timeout.tv_sec = LX_INIT_HVSOCKET_TIMEOUT_SECONDS;
if (setsockopt(SocketFd.get(), AF_VSOCK, SO_VM_SOCKETS_CONNECT_TIMEOUT, &Timeout, sizeof(Timeout)) < 0)
{
LOG_ERROR("setsockopt SO_VM_SOCKETS_CONNECT_TIMEOUT failed {}", errno);
return {};
}
if (SocketBuffer)
{
int BufferSize = *SocketBuffer;
if (setsockopt(SocketFd.get(), SOL_SOCKET, SO_SNDBUF, &BufferSize, sizeof(BufferSize)) < 0)
{
LOG_ERROR("setsockopt(SO_SNDBUF, {}) failed {}", BufferSize, errno);
return {};
}
if (setsockopt(SocketFd.get(), SOL_SOCKET, SO_RCVBUF, &BufferSize, sizeof(BufferSize)) < 0)
{
LOG_ERROR("setsockopt(SO_RCVBUF, {}) failed {}", BufferSize, errno);
return {};
}
}
sockaddr_vm SocketAddress{};
SocketAddress.svm_family = AF_VSOCK;
SocketAddress.svm_cid = VMADDR_CID_HOST;
SocketAddress.svm_port = Port;
if (connect(SocketFd.get(), (const struct sockaddr*)&SocketAddress, sizeof(SocketAddress)) < 0)
{
LOG_ERROR("connect port {} failed {}", Port, errno);
return {};
}
return SocketFd;
}
int UtilCreateProcessAndWait(const char* const File, const char* const Argv[], int* Status, const std::map<std::string, std::string>& Env)
/*++
Routine Description:
This routine creates a helper process from init and waits for it to exit.
Arguments:
File - Supplies the file name to execute.
Argv - Supplies the arguments for the command.
Status - Supplies an optional pointer that receives the exit status of the
process.
Return Value:
0 on success, -1 on failure.
--*/
{
pid_t ChildPid;
int Result;
int LocalStatus;
pid_t WaitResult;
Result = -1;
//
// Init needs to not ignore SIGCHLD so it can wait for this child.
//
auto restore = signal(SIGCHLD, SIG_DFL);
ChildPid = fork();
if (ChildPid < 0)
{
LOG_ERROR("Forking child process for {} failed with {}", File, errno);
goto CreateProcessAndWaitEnd;
}
if (ChildPid == 0)
{
//
// Restore default signal dispositions for the child process.
//
if (UtilSetSignalHandlers(g_SavedSignalActions, false) < 0 || UtilRestoreBlockedSignals() < 0)
{
exit(-1);
}
//
// Set environment variables.
//
for (const auto& e : Env)
{
setenv(e.first.c_str(), e.second.c_str(), 1);
}
//
// Invoke the executable.
//
// This explicit cast is okay for now because:
// 1. execv function is guaranteed to not alter the arguments
// 2. In sometime we probably will replace most of these string constants
// with std::string anyway.
execv(File, const_cast<char* const*>(Argv));
LOG_ERROR("{} failed with {}", File, errno);
exit(-1);
}
if (Status == nullptr)
{
Status = &LocalStatus;
}
//
// TODO_LX: Do we need a timeout when waiting for the process?
//
WaitResult = waitpid(ChildPid, Status, 0);
if (WaitResult < 0)
{
LOG_ERROR("Waiting for {} failed with {}", File, errno);
goto CreateProcessAndWaitEnd;
}
if (*Status != 0)
{
LOG_ERROR("{} failed with status {:#x}", File, *Status);
goto CreateProcessAndWaitEnd;
}
Result = 0;
CreateProcessAndWaitEnd:
//
// Restore the disposition of SIGCHLD.
//
signal(SIGCHLD, restore);
return Result;
}
int UtilExecCommandLine(const char* CommandLine, std::string* Output, int ExpectedStatus, bool PrintError)
/*++
Routine Description:
This routine runs the command and optionally returns the output.
Arguments:
CommandLine - Supplies the command line of the process to launch.
Output - Supplies an optional pointer to an std::string to receive the output of the command.
If no buffer is provied the output will appear in stdout.
ExpectedStatus - Supplies the expected return status of the command.
PrintError - Supplies a boolean that specifies if an error should be printed if the process does not return the expected status.
Return Value:
0 on success, -1 on failure.
--*/
{
//
// Exec the command and read the output.
//
wil::unique_file Pipe{popen(CommandLine, "re")};
if (!Pipe)
{
LOG_ERROR("popen({}) failed {}", CommandLine, errno);
return -1;
}
std::vector<char> Buffer(1024);
int Result = -1;
while (fgets(Buffer.data(), Buffer.size(), Pipe.get()) != nullptr)
{
if (Output)
{
(*Output) += Buffer.data();
if (Result < 0)
{
goto ErrorExit;
}
}
else
{
fputs(Buffer.data(), stdout);
}
}
if (ferror(Pipe.get()))
{
Result = -1;
LOG_ERROR("fgets failed {}", errno);
goto ErrorExit;
}
Result = 0;
ErrorExit:
if (Pipe)
{
Result = pclose(Pipe.release());
if (Result == -1)
{
LOG_ERROR("pclose failed {}", errno);
}
else
{
Result = UtilProcessChildExitCode(Result, CommandLine, ExpectedStatus, PrintError);
}
}
return Result;
}
std::string UtilFindMount(const char* MountInfoFile, const char* Path, bool WinPath, size_t* PrefixLength)
/*++
Routine Description:
This routine parses the /proc/self/mountinfo file to find a mount that
matches the specified path.
N.B. The caller is responsible for freeing the returned replacement prefix
buffer.
Arguments:
MountInfoFile - Supplies the path to the mountinfo file.
Path - Supplies the path.
WinPath - Supplies a value that indicates whether the path is a Windows
path.
PrefixLength - Supplies a pointer which receives the length of the prefix
that should be stripped from the path.
Return Value:
The replacement prefix on success, or an empty string on failure.
--*/
try
{
char** MatchField;
char** ReplacementField;
mountutil::MountEnum MountEnum{MountInfoFile};
if (WinPath != false)
{
MatchField = &MountEnum.Current().Source;
ReplacementField = &MountEnum.Current().MountPoint;
}
else
{
MatchField = &MountEnum.Current().MountPoint;
ReplacementField = &MountEnum.Current().Source;
}
std::string FoundReplacement;
size_t FoundPrefixLength = 0;
while (MountEnum.Next())
{
//
// If a mount point was previously found, and this mount point is a
// prefix of the path (or the previously found mount point, for Windows
// to Linux translation), it means that the path is not actually on
// the previously found mount, so discard that result.
//
// For example:
// - When translating /mnt/c/foo/bar, first /mnt/c is found, but a
// later entry indicates /mnt/c/foo is also a mount point (e.g. using
// tmpfs). This means /mnt/c/foo/bar is not on the /mnt/c mount.
// - When translating C:\foo, first /mnt/c is found. A later entry
// indicates /mnt itself is a mount point, making the earlier /mnt/c
// mount unreachable.
//
// TODO_LX: This doesn't catch the case when translating C:\foo\bar and
// /mnt/c/foo is a mount point. Handling that is more complicated.
//
if (!FoundReplacement.empty())
{
const char* LinuxPath = WinPath ? FoundReplacement.c_str() : Path;
size_t LinuxPrefixLength = UtilIsPathPrefix(LinuxPath, MountEnum.Current().MountPoint, false);
if (LinuxPrefixLength > 0)
{
FoundReplacement.resize(0);
}
}
//
// For Plan 9, parse the actual mount source from the superblock options.
// For virtiofs, parse the mount source from source (for example drvfsC or drvfsaC).
// If the file system isn't Plan 9, virtiofs, or DrvFs, skip this mount.
//
std::string MountSource;
if (strcmp(MountEnum.Current().FileSystemType, PLAN9_FS_TYPE) == 0)
{
MountSource = UtilParsePlan9MountSource(MountEnum.Current().SuperOptions);
if (MountSource.empty())
{
continue;
}
MountEnum.Current().Source = MountSource.data();
}
else if (strcmp(MountEnum.Current().FileSystemType, VIRTIO_FS_TYPE) == 0)
{
MountSource = UtilParseVirtiofsMountSource(MountEnum.Current().Source);
if (MountSource.empty())
{
continue;
}
MountEnum.Current().Source = MountSource.data();
}
else if (strcmp(MountEnum.Current().FileSystemType, DRVFS_FS_TYPE) == 0)
{
//
// The mount source is a Windows path and may use forward slashes;
// flip them to backslashes.
//
UtilCanonicalisePathSeparator(MountEnum.Current().Source, PATH_SEP_NT);
}
else
{
continue;
}
//
// Strip the trailing backslash if present.
//
size_t Length = strlen(MountEnum.Current().Source);
if ((Length > 0) && (MountEnum.Current().Source[Length - 1] == PATH_SEP_NT))
{
MountEnum.Current().Source[Length - 1] = '\0';
}
//
// For bind mounts, use the concatenation of the mount source and root
// of the mount as the mount source string.
//
std::string CombinedMountSource;
if (strcmp(MountEnum.Current().Root, "/") != 0)
{
CombinedMountSource += MountEnum.Current().Source;
CombinedMountSource += MountEnum.Current().Root;
UtilCanonicalisePathSeparator(CombinedMountSource, PATH_SEP_NT);
MountEnum.Current().Source = CombinedMountSource.data();
}
//
// Check if the match field is a prefix of the path.
//
// N.B. For Windows paths, only matches longer than the existing match
// are considered. This is because Windows mounts aren't
// guaranteed to be in order and NTFS directory mounts should be
// preferred over plain drive letter mounts if they match.
//
Length = UtilIsPathPrefix(Path, *MatchField, WinPath);
if ((Length == 0) || ((WinPath != false) && (Length < FoundPrefixLength)))
{
continue;
}
//
// Store the length of the prefix so the caller can strip it from the
// string.
//
FoundPrefixLength = Length;
//
// Store the replacement.
//
FoundReplacement = *ReplacementField;
//
// Continue searching the file even if a mount has been found, since
// newer mounts could shadow this one or be a nested mount.
//
}
if (!FoundReplacement.empty() && PrefixLength != nullptr)
{
*PrefixLength = FoundPrefixLength;
}
return FoundReplacement;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
return {};
}
std::optional<std::string> UtilGetEnv(const char* Name, char* Environment)
/*++
Routine Description: