-
Notifications
You must be signed in to change notification settings - Fork 19
/
wslbridge.cc
1298 lines (1192 loc) · 42 KB
/
wslbridge.cc
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
#include <windows.h>
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <getopt.h>
#include <locale.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/cygwin.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <wchar.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "../common/SocketIo.h"
#define BACKEND_PROGRAM "wslbridge-backend"
// SystemFunction036 is also known as RtlGenRandom. It might be possible to
// replace this with getentropy, if not now, then later.
extern "C" BOOLEAN WINAPI SystemFunction036(PVOID, ULONG);
namespace {
const int32_t kOutputWindowSize = 8192;
static WakeupFd *g_wakeupFd = nullptr;
static TermSize terminalSize() {
winsize ws = {};
if (isatty(STDIN_FILENO) && ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0) {
return TermSize { ws.ws_col, ws.ws_row };
} else {
return TermSize { 80, 24 };
}
}
class Socket {
public:
Socket();
~Socket() { close(); }
int port() { return port_; }
int accept();
void close();
private:
int s_;
int port_;
};
Socket::Socket() {
s_ = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
assert(s_ >= 0);
setSocketNoDelay(s_);
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(0);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
const int bindRet = bind(s_, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr));
assert(bindRet == 0);
const int listenRet = listen(s_, 1);
assert(listenRet == 0);
socklen_t addrLen = sizeof(addr);
const int getRet = getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrLen);
assert(getRet == 0);
port_ = ntohs(addr.sin_port);
}
int Socket::accept() {
const int cs = ::accept(s_, nullptr, nullptr);
assert(cs >= 0);
setSocketNoDelay(cs);
return cs;
}
void Socket::close() {
if (s_ != -1) {
::close(s_);
s_ = -1;
}
}
static std::string randomString() {
char buf[32] = {};
if (!SystemFunction036(&buf, sizeof(buf))) {
assert(false && "RtlGenRandom failed");
}
std::string out;
for (char ch : buf) {
out.push_back("0123456789ABCDEF"[(ch >> 4) & 0xF]);
out.push_back("0123456789ABCDEF"[(ch >> 0) & 0xF]);
}
return out;
}
static std::wstring mbsToWcs(const std::string &s) {
const size_t len = mbstowcs(nullptr, s.c_str(), 0);
if (len == static_cast<size_t>(-1)) {
fatal("error: mbsToWcs: invalid string\n");
}
std::wstring ret;
ret.resize(len);
const size_t len2 = mbstowcs(&ret[0], s.c_str(), len);
assert(len == len2);
return ret;
}
static std::string wcsToMbs(const std::wstring &s, bool emptyOnError=false) {
const size_t len = wcstombs(nullptr, s.c_str(), 0);
if (len == static_cast<size_t>(-1)) {
if (emptyOnError) {
return {};
}
fatal("error: wcsToMbs: invalid string\n");
}
std::string ret;
ret.resize(len);
const size_t len2 = wcstombs(&ret[0], s.c_str(), len);
assert(len == len2);
return ret;
}
// As long as clients only get one chance to provide a key, this function
// should be unnecessary.
static bool secureStrEqual(const std::string &x, const std::string &y) {
if (x.size() != y.size()) {
return false;
}
volatile char ch = 0;
volatile const char *xp = &x[0];
volatile const char *yp = &y[0];
for (size_t i = 0; i < x.size(); ++i) {
ch |= (xp[i] ^ yp[i]);
}
return ch == 0;
}
static int acceptClientAndAuthenticate(Socket &socket, const std::string &key) {
const int cs = socket.accept();
std::string checkBuf;
checkBuf.resize(key.size());
size_t i = 0;
while (i < checkBuf.size()) {
const size_t remaining = checkBuf.size() - i;
const ssize_t actual = read(cs, &checkBuf[i], remaining);
assert(actual > 0 && static_cast<size_t>(actual) <= remaining);
i += actual;
}
if (!secureStrEqual(checkBuf, key)) {
fatal("error: key check failed\n");
}
return cs;
}
class TerminalState {
private:
std::mutex mutex_;
bool inRawMode_ = false;
bool modeValid_[2] = {false, false};
termios mode_[2] = {};
public:
void enterRawMode();
private:
void leaveRawMode(const std::lock_guard<std::mutex> &lock);
public:
void fatal(const char *fmt, ...)
__attribute__((noreturn))
__attribute__((format(printf, 2, 3)));
void fatalv(const char *fmt, va_list ap) __attribute__((noreturn));
void exitCleanly(int exitStatus);
};
// Put the input terminal into non-canonical mode.
void TerminalState::enterRawMode() {
std::lock_guard<std::mutex> lock(mutex_);
assert(!inRawMode_);
inRawMode_ = true;
for (int i = 0; i < 2; ++i) {
if (!isatty(i)) {
modeValid_[i] = false;
} else {
if (tcgetattr(i, &mode_[i]) < 0) {
fatalPerror("tcgetattr failed");
}
modeValid_[i] = true;
}
}
if (modeValid_[0]) {
termios buf;
if (tcgetattr(0, &buf) < 0) {
fatalPerror("tcgetattr failed");
}
buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
buf.c_cflag &= ~(CSIZE | PARENB);
buf.c_cflag |= CS8;
buf.c_cc[VMIN] = 1; // blocking read
buf.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSAFLUSH, &buf) < 0) {
fatalPerror("tcsetattr failed");
}
}
if (modeValid_[1]) {
termios buf;
if (tcgetattr(1, &buf) < 0) {
fatalPerror("tcgetattr failed");
}
buf.c_cflag &= ~(CSIZE | PARENB);
buf.c_cflag |= CS8;
buf.c_oflag &= ~OPOST;
if (tcsetattr(1, TCSAFLUSH, &buf) < 0) {
fatalPerror("tcsetattr failed");
}
}
}
void TerminalState::leaveRawMode(const std::lock_guard<std::mutex> &lock) {
if (!inRawMode_) {
return;
}
for (int i = 0; i < 2; ++i) {
if (modeValid_[i]) {
if (tcsetattr(i, TCSAFLUSH, &mode_[i]) < 0) {
fatalPerror("error restoring terminal mode");
}
}
}
}
// This function cannot be used from a signal handler.
void TerminalState::fatal(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
this->fatalv(fmt, ap);
va_end(ap);
}
void TerminalState::fatalv(const char *fmt, va_list ap) {
std::lock_guard<std::mutex> lock(mutex_);
leaveRawMode(lock);
::fatalv(fmt, ap);
}
void TerminalState::exitCleanly(int exitStatus) {
std::lock_guard<std::mutex> lock(mutex_);
leaveRawMode(lock);
fflush(stdout);
fflush(stderr);
// Avoid calling exit, which would call global destructors and destruct the
// WakeupFd object.
_exit(exitStatus);
}
static TerminalState g_terminalState;
struct IoLoop {
std::string spawnCwd;
bool usePty = false;
std::mutex mutex;
bool ioFinished = false;
int controlSocketFd = -1;
bool childReaped = false;
int childExitStatus = -1;
};
static void fatalConnectionBroken() {
g_terminalState.fatal("\nwslbridge error: connection broken\n");
}
static void writePacket(IoLoop &ioloop, const Packet &p) {
assert(p.size >= sizeof(p));
std::lock_guard<std::mutex> lock(ioloop.mutex);
if (!writeAllRestarting(ioloop.controlSocketFd,
reinterpret_cast<const char*>(&p), p.size)) {
fatalConnectionBroken();
}
}
static void parentToSocketThread(int socketFd) {
std::array<char, 8192> buf;
while (true) {
const ssize_t amt1 = readRestarting(STDIN_FILENO, buf.data(), buf.size());
if (amt1 <= 0) {
// If we reach EOF reading from stdin, propagate EOF to the child.
close(socketFd);
break;
}
if (!writeAllRestarting(socketFd, buf.data(), amt1)) {
// We don't propagate EOF backwards, but we do let data build up.
break;
}
}
}
static void socketToParentThread(IoLoop *ioloop, bool isErrorPipe, int socketFd, int outFd) {
uint32_t bytesWritten = 0;
std::array<char, 32 * 1024> buf;
while (true) {
const ssize_t amt1 = readRestarting(socketFd, buf.data(), buf.size());
if (amt1 == 0) {
std::lock_guard<std::mutex> lock(ioloop->mutex);
ioloop->ioFinished = true;
g_wakeupFd->set();
break;
}
if (amt1 < 0) {
break;
}
if (!writeAllRestarting(outFd, buf.data(), amt1)) {
if (!ioloop->usePty && !isErrorPipe) {
// ssh seems to propagate an stdout EOF backwards to the remote
// program, so do the same thing. It doesn't do this for
// stderr, though, where the remote process is allowed to block
// forever.
Packet p = { sizeof(Packet), Packet::Type::CloseStdoutPipe };
writePacket(*ioloop, p);
}
shutdown(socketFd, SHUT_RDWR);
break;
}
bytesWritten += amt1;
if (bytesWritten >= kOutputWindowSize / 2) {
Packet p = { sizeof(Packet), Packet::Type::IncreaseWindow };
p.u.window.amount = bytesWritten;
p.u.window.isErrorPipe = isErrorPipe;
writePacket(*ioloop, p);
bytesWritten = 0;
}
}
}
static void handlePacket(IoLoop *ioloop, const Packet &p) {
switch (p.type) {
case Packet::Type::ChildExitStatus: {
std::lock_guard<std::mutex> lock(ioloop->mutex);
ioloop->childReaped = true;
ioloop->childExitStatus = p.u.exitStatus;
g_wakeupFd->set();
break;
}
case Packet::Type::SpawnFailed: {
const PacketSpawnFailed &psf = reinterpret_cast<const PacketSpawnFailed&>(p);
std::string msg;
switch (p.u.spawnError.type) {
case SpawnError::Type::ForkPtyFailed:
msg = "error: forkpty failed: ";
break;
case SpawnError::Type::ChdirFailed:
msg = "error: could not chdir to '" + ioloop->spawnCwd + "': ";
break;
case SpawnError::Type::ExecFailed:
msg = "error: could not exec '" + std::string(psf.exe) + "': ";
break;
default:
assert(false && "Unhandled SpawnError type");
}
msg += errorString(p.u.spawnError.error);
g_terminalState.fatal("%s\n", msg.c_str());
break;
}
default: {
g_terminalState.fatal("internal error: unexpected packet %d\n",
static_cast<int>(p.type));
}
}
}
static void mainLoop(const std::string &spawnCwd,
bool usePty, int controlSocketFd,
int inputSocketFd, int outputSocketFd, int errorSocketFd,
TermSize termSize) {
IoLoop ioloop;
ioloop.spawnCwd = spawnCwd;
ioloop.usePty = usePty;
ioloop.controlSocketFd = controlSocketFd;
std::thread p2s(parentToSocketThread, inputSocketFd);
std::thread s2p(socketToParentThread, &ioloop, false, outputSocketFd, STDOUT_FILENO);
std::unique_ptr<std::thread> es2p;
if (errorSocketFd != -1) {
es2p = std::unique_ptr<std::thread>(
new std::thread(socketToParentThread, &ioloop, true, errorSocketFd, STDERR_FILENO));
}
std::thread rcs(readControlSocketThread<IoLoop, handlePacket, fatalConnectionBroken>,
controlSocketFd, &ioloop);
int32_t exitStatus = -1;
while (true) {
g_wakeupFd->wait();
const auto newSize = terminalSize();
if (newSize != termSize) {
Packet p = { sizeof(Packet), Packet::Type::SetSize };
p.u.termSize = termSize = newSize;
writePacket(ioloop, p);
}
std::lock_guard<std::mutex> lock(ioloop.mutex);
if (ioloop.childReaped && ioloop.ioFinished) {
exitStatus = ioloop.childExitStatus;
break;
}
}
// Socket-to-pty I/O is finished already.
s2p.join();
// We can't return, because the threads could still be running. Rather
// than shut them down gracefully, which seems hard(?), just let the OS
// clean everything up.
g_terminalState.exitCleanly(exitStatus);
}
static bool pathExists(const std::wstring &path) {
return GetFileAttributesW(path.c_str()) != 0xFFFFFFFF;
}
static std::wstring dirname(const std::wstring &path) {
std::wstring::size_type pos = path.find_last_of(L"\\/");
if (pos == std::wstring::npos) {
return L"";
} else {
return path.substr(0, pos);
}
}
static HMODULE getCurrentModule() {
HMODULE module;
if (!GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(getCurrentModule),
&module)) {
fatal("error: GetModuleHandleEx failed\n");
}
return module;
}
static std::wstring getModuleFileName(HMODULE module) {
const int bufsize = 4096;
wchar_t path[bufsize];
int size = GetModuleFileNameW(module, path, bufsize);
assert(size != 0 && size != bufsize);
return std::wstring(path);
}
static std::wstring findBackendProgram(const std::string &customBackendPath) {
std::wstring ret;
if (!customBackendPath.empty()) {
char *winPath = static_cast<char*>(
cygwin_create_path(CCP_POSIX_TO_WIN_A, customBackendPath.c_str()));
if (winPath == nullptr) {
fatalPerror(("error: bad path: '" + customBackendPath + "'").c_str());
}
ret = mbsToWcs(winPath);
free(winPath);
} else {
const auto progDir = dirname(getModuleFileName(getCurrentModule()));
ret = progDir + (L"\\" BACKEND_PROGRAM);
}
if (!pathExists(ret)) {
fatal("error: '%s' backend program is missing\n",
wcsToMbs(ret).c_str());
}
return ret;
}
static wchar_t lowerDrive(wchar_t ch) {
if (ch >= L'a' && ch <= L'z') {
return ch;
} else if (ch >= L'A' && ch <= 'Z') {
return ch - L'A' + L'a';
} else {
return L'\0';
}
}
static std::pair<std::wstring, std::wstring>
normalizePath(const std::wstring &path) {
const auto getFinalPathName = [&](HANDLE h) -> std::wstring {
std::wstring ret;
ret.resize(MAX_PATH + 1);
while (true) {
const auto sz = GetFinalPathNameByHandleW(h, &ret[0], ret.size(), 0);
if (sz == 0) {
fatal("error: GetFinalPathNameByHandle failed on '%s'\n",
wcsToMbs(path).c_str());
} else if (sz < ret.size()) {
ret.resize(sz);
return ret;
} else {
assert(sz > ret.size());
ret.resize(sz);
}
}
};
const auto h = CreateFileW(
path.c_str(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING, 0, nullptr);
if (h == INVALID_HANDLE_VALUE) {
fatal("error: could not open '%s'\n", wcsToMbs(path).c_str());
}
auto npath = getFinalPathName(h);
std::array<wchar_t, MAX_PATH + 1> fsname;
fsname.back() = L'\0';
if (!GetVolumeInformationByHandleW(
h, nullptr, 0, nullptr, nullptr, nullptr,
&fsname[0], fsname.size())) {
fsname[0] = L'\0';
}
CloseHandle(h);
// Example of GetFinalPathNameByHandle result:
// \\?\C:\cygwin64\bin\wslbridge-backend
// 0123456
// \\?\UNC\server\share\file
// 01234567
if (npath.size() >= 7 &&
npath.substr(0, 4) == L"\\\\?\\" &&
lowerDrive(npath[4]) &&
npath.substr(5, 2) == L":\\") {
// Strip off the atypical \\?\ prefix.
npath = npath.substr(4);
} else if (npath.substr(0, 8) == L"\\\\?\\UNC\\") {
// Strip off the \\\\?\\UNC\\ prefix and replace it with \\.
npath = L"\\\\" + npath.substr(8);
}
return std::make_pair(std::move(npath), fsname.data());
}
static std::wstring convertPathToWsl(const std::wstring &path) {
const auto isSlash = [](wchar_t ch) -> bool {
return ch == L'/' || ch == L'\\';
};
if (path.size() >= 3) {
const auto drive = lowerDrive(path[0]);
if (drive && path[1] == L':' && isSlash(path[2])) {
// Acceptable path.
std::wstring ret = L"/mnt/";
ret.push_back(drive);
ret.append(path.substr(2));
for (wchar_t &ch : ret) {
if (ch == L'\\') {
ch = L'/';
}
}
return ret;
}
}
fatal(
"error: the backend program '%s' must be located on a "
"letter drive so WSL can access it with a /mnt/<LTR> path\n",
wcsToMbs(path).c_str());
}
static std::wstring findSystemProgram(const wchar_t *name) {
std::array<wchar_t, MAX_PATH> windir;
windir[0] = L'\0';
if (GetWindowsDirectoryW(windir.data(), windir.size()) == 0) {
fatal("error: GetWindowsDirectory call failed\n");
}
const wchar_t *const kPart32 = L"\\System32\\";
const auto path = [&](const wchar_t *part) -> std::wstring {
return std::wstring(windir.data()) + part + name;
};
#if defined(__x86_64__)
const auto ret = path(kPart32);
if (pathExists(ret)) {
return ret;
} else {
fatal("error: '%s' does not exist\n"
"note: Ubuntu-on-Windows must be installed\n",
wcsToMbs(ret).c_str());
}
#elif defined(__i386__)
const wchar_t *const kPartNat = L"\\Sysnative\\";
const auto pathNat = path(kPartNat);
if (pathExists(pathNat)) {
return std::move(pathNat);
}
const auto path32 = path(kPart32);
if (pathExists(path32)) {
return std::move(path32);
}
fatal("error: neither '%s' nor '%s' exist\n"
"note: Ubuntu-on-Windows must be installed\n",
wcsToMbs(pathNat).c_str(), wcsToMbs(path32).c_str());
#else
#error "Could not determine architecture"
#endif
}
static void usage(const char *prog) {
printf("Usage: %s [options] [--] [command]...\n", prog);
printf("Runs a program within a Windows Subsystem for Linux (WSL) pty\n");
printf("\n");
printf("Options:\n");
printf(" -C WSLDIR Changes the working directory to WSLDIR first.\n");
printf(" An initial '~' indicates the WSL home directory.\n");
printf(" -e VAR Copies VAR into the WSL environment.\n");
printf(" -e VAR=VAL Sets VAR to VAL in the WSL environment.\n");
printf(" -l Start a login shell.\n");
printf(" --no-login Do not start a login shell.\n");
printf(" -T Do not use a pty.\n");
printf(" -t Use a pty (as long as stdin is a tty).\n");
printf(" -t -t Force a pty (even if stdin is not a tty).\n");
printf(" --distro-guid GUID\n");
printf(" Uses the WSL distribution identified by GUID.\n");
printf(" See HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss\n");
printf(" for a list of distribution GUIDs.\n");
printf(" --backend BACKEND\n");
printf(" Overrides the default path to wslbridge-backend. BACKEND is a\n");
printf(" Cygwin-style path (not a WSL path).\n");
exit(0);
}
class Environment {
public:
void set(const std::string &var) {
const char *value = getenv(var.c_str());
if (value != nullptr) {
set(var, value);
}
}
void set(const std::string &var, const std::string &value) {
pairs_.push_back(std::make_pair(mbsToWcs(var), mbsToWcs(value)));
}
bool hasVar(const std::wstring &var) {
for (const auto &pair : pairs_) {
if (pair.first == var) {
return true;
}
}
return false;
}
const std::vector<std::pair<std::wstring, std::wstring>> &pairs() { return pairs_; }
private:
std::vector<std::pair<std::wstring, std::wstring>> pairs_;
};
static void appendBashArg(std::wstring &out, const std::wstring &arg) {
if (!out.empty()) {
out.push_back(L' ');
}
const auto isCharSafe = [](wchar_t ch) -> bool {
switch (ch) {
case L'%':
case L'+':
case L',':
case L'-':
case L'.':
case L'/':
case L':':
case L'=':
case L'@':
case L'_':
case L'{':
case L'}':
return true;
default:
return (ch >= L'0' && ch <= L'9') ||
(ch >= L'a' && ch <= L'z') ||
(ch >= L'A' && ch <= L'Z');
}
};
if (arg.empty()) {
out.append(L"''");
return;
}
if (std::all_of(arg.begin(), arg.end(), isCharSafe)) {
out.append(arg);
return;
}
bool inQuote = false;
const auto enterQuote = [&](bool newInQuote) {
if (inQuote != newInQuote) {
out.push_back(L'\'');
inQuote = newInQuote;
}
};
enterQuote(true);
for (auto ch : arg) {
if (ch == L'\'') {
enterQuote(false);
out.append(L"\\'");
enterQuote(true);
} else if (isCharSafe(ch)) {
out.push_back(ch);
} else {
out.push_back(ch);
}
}
enterQuote(false);
}
static std::string errorMessageToString(DWORD err) {
// Use FormatMessageW rather than FormatMessageA, because we want to use
// wcstombs to convert to the Cygwin locale, which might not match the
// codepage FormatMessageA would use. We need to convert using wcstombs,
// rather than print using %ls, because %ls doesn't work in the original
// MSYS.
wchar_t *wideMsgPtr = NULL;
const DWORD formatRet = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<wchar_t*>(&wideMsgPtr),
0,
NULL);
if (formatRet == 0 || wideMsgPtr == NULL) {
return std::string();
}
std::string msg = wcsToMbs(wideMsgPtr);
LocalFree(wideMsgPtr);
const size_t pos = msg.find_last_not_of(" \r\n\t");
if (pos == std::string::npos) {
msg.clear();
} else {
msg.erase(pos + 1);
}
return msg;
}
static std::string formatErrorMessage(DWORD err) {
char buf[64];
sprintf(buf, "error %#x", static_cast<unsigned int>(err));
std::string ret = errorMessageToString(err);
if (ret.empty()) {
ret += buf;
} else {
ret += " (";
ret += buf;
ret += ")";
}
return ret;
}
struct PipeHandles {
HANDLE rh;
HANDLE wh;
};
static PipeHandles createPipe() {
SECURITY_ATTRIBUTES sa {};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
PipeHandles ret {};
const BOOL success = CreatePipe(&ret.rh, &ret.wh, &sa, 0);
assert(success && "CreatePipe failed");
return ret;
}
class StartupInfoAttributeList {
public:
StartupInfoAttributeList(PPROC_THREAD_ATTRIBUTE_LIST &attrList, int count) {
SIZE_T size {};
InitializeProcThreadAttributeList(nullptr, count, 0, &size);
assert(size > 0 && "InitializeProcThreadAttributeList failed");
buffer_ = std::unique_ptr<char[]>(new char[size]);
const BOOL success = InitializeProcThreadAttributeList(get(), count, 0, &size);
assert(success && "InitializeProcThreadAttributeList failed");
attrList = get();
}
StartupInfoAttributeList(const StartupInfoAttributeList &) = delete;
StartupInfoAttributeList &operator=(const StartupInfoAttributeList &) = delete;
~StartupInfoAttributeList() {
DeleteProcThreadAttributeList(get());
}
private:
PPROC_THREAD_ATTRIBUTE_LIST get() {
return reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(buffer_.get());
}
std::unique_ptr<char[]> buffer_;
};
class StartupInfoInheritList {
public:
StartupInfoInheritList(PPROC_THREAD_ATTRIBUTE_LIST attrList,
std::vector<HANDLE> &&inheritList) :
inheritList_(std::move(inheritList)) {
const BOOL success = UpdateProcThreadAttribute(
attrList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inheritList_.data(), inheritList_.size() * sizeof(HANDLE),
nullptr, nullptr);
assert(success && "UpdateProcThreadAttribute failed");
}
StartupInfoInheritList(const StartupInfoInheritList &) = delete;
StartupInfoInheritList &operator=(const StartupInfoInheritList &) = delete;
~StartupInfoInheritList() {}
private:
std::vector<HANDLE> inheritList_;
};
// WSL bash will print an error if the user tries to run elevated and
// non-elevated instances simultaneously, and maybe other situations. We'd
// like to detect this situation and report the error back to the user.
//
// Two complications:
// - WSL bash will print the error to stdout/stderr, but if the file is a
// pipe, then WSL bash doesn't print it until it exits (presumably due to
// block buffering).
// - WSL bash puts up a prompt, "Press any key to continue", and it reads
// that key from the attached console, not from stdin.
//
// This function spawns the frontend again and instructs it to attach to the
// new WSL bash console and send it a return keypress.
//
// The HANDLE must be inheritable.
static void spawnPressReturnProcess(HANDLE bashProcess) {
const auto exePath = getModuleFileName(getCurrentModule());
std::wstring cmdline;
cmdline.append(L"\"");
cmdline.append(exePath);
cmdline.append(L"\" --press-return ");
cmdline.append(std::to_wstring(reinterpret_cast<uintptr_t>(bashProcess)));
STARTUPINFOEXW sui {};
sui.StartupInfo.cb = sizeof(sui);
StartupInfoAttributeList attrList { sui.lpAttributeList, 1 };
StartupInfoInheritList inheritList { sui.lpAttributeList, { bashProcess } };
PROCESS_INFORMATION pi {};
const BOOL success = CreateProcessW(exePath.c_str(), &cmdline[0], nullptr, nullptr,
true, 0, nullptr, nullptr, &sui.StartupInfo, &pi);
if (!success) {
fprintf(stderr, "wslbridge warning: could not spawn: %s\n", wcsToMbs(cmdline).c_str());
}
if (WaitForSingleObject(pi.hProcess, 10000) != WAIT_OBJECT_0) {
fprintf(stderr, "wslbridge warning: process didn't exit after 10 seconds: %ls\n",
cmdline.c_str());
} else {
DWORD code {};
BOOL success = GetExitCodeProcess(pi.hProcess, &code);
if (!success) {
fprintf(stderr, "wslbridge warning: GetExitCodeProcess failed\n");
} else if (code != 0) {
fprintf(stderr, "wslbridge warning: process failed: %ls\n", cmdline.c_str());
}
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
static int handlePressReturn(const char *pidStr) {
// AttachConsole replaces STD_INPUT_HANDLE with a new console input
// handle. See https://github.com/rprichard/win32-console-docs. The
// bash.exe process has already started, but console creation and
// process creation don't happen atomically, so poll for the console's
// existence.
auto str2handle = [](const char *str) {
std::stringstream ss(str);
uintptr_t n {};
ss >> n;
return reinterpret_cast<HANDLE>(n);
};
const HANDLE bashProcess = str2handle(pidStr);
const DWORD bashPid = GetProcessId(bashProcess);
FreeConsole();
for (int i = 0; i < 400; ++i) {
if (WaitForSingleObject(bashProcess, 0) == WAIT_OBJECT_0) {
// bash.exe has exited, give up immediately.
return 0;
} else if (AttachConsole(bashPid)) {
std::array<INPUT_RECORD, 2> ir {};
ir[0].EventType = KEY_EVENT;
ir[0].Event.KeyEvent.bKeyDown = TRUE;
ir[0].Event.KeyEvent.wRepeatCount = 1;
ir[0].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
ir[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC);
ir[0].Event.KeyEvent.uChar.UnicodeChar = '\r';
ir[1] = ir[0];
ir[1].Event.KeyEvent.bKeyDown = FALSE;
DWORD actual {};
WriteConsoleInputW(
GetStdHandle(STD_INPUT_HANDLE),
ir.data(), ir.size(), &actual);
return 0;
}
Sleep(25);
}
return 1;
}
static std::vector<char> readAllFromHandle(HANDLE h) {
std::vector<char> ret;
char buf[1024];
DWORD actual {};
while (ReadFile(h, buf, sizeof(buf), &actual, nullptr) && actual > 0) {
ret.insert(ret.end(), buf, buf + actual);
}
return ret;
}
static std::tuple<DWORD, DWORD, DWORD> windowsVersion() {
OSVERSIONINFO info {};
info.dwOSVersionInfoSize = sizeof(info);
const BOOL success = GetVersionEx(&info);
assert(success && "GetVersionEx failed");
if (info.dwMajorVersion == 6 && info.dwMinorVersion == 2) {
// We want to distinguish between Windows 10.0.14393 and 10.0.15063,
// but if the EXE doesn't have an appropriate manifest, then
// GetVersionEx will report the lesser of 6.2 and the true version.
fprintf(stderr, "wslbridge warning: GetVersionEx reports version 6.2 -- "
"is wslbridge.exe properly manifested?\n");
}
return std::make_tuple(info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber);
}
static std::string replaceAll(std::string str, const std::string &from, const std::string &to) {
size_t pos {};
while ((pos = str.find(from, pos)) != std::string::npos) {
str = str.replace(pos, from.size(), to);
pos += to.size();
}
return str;
}
static std::string stripTrailing(std::string str) {
while (!str.empty() && isspace(str.back())) {
str.pop_back();
}
return str;
}
// Ensure that the GUID is lower-case and surrounded with braces.
// If the string isn't a valid GUID, then return an empty string.
static std::string canonicalGuid(std::string guid) {
if (guid.size() == 38 && guid[0] == '{' && guid[37] == '}') {
// OK
} else if (guid.size() == 36) {
guid = '{' + guid + '}';
} else {
return {};
}
assert(guid.size() == 38);
for (size_t i = 1; i <= 36; ++i) {
if (i == 9 || i == 14 || i == 19 || i == 24) {
if (guid[i] != '-') {
return {};
}
} else {
guid[i] = tolower(guid[i]);
if (!isxdigit(guid[i])) {
return {};
}
}
}
return guid;
}
} // namespace
int main(int argc, char *argv[]) {
setlocale(LC_ALL, "");
cygwin_internal(CW_SYNC_WINENV);
g_wakeupFd = new WakeupFd();
if (argc == 3 && !strcmp(argv[1], "--press-return")) {
return handlePressReturn(argv[2]);
}
Environment env;
std::string spawnCwd;
std::string distroGuid;