forked from TunSafe/TunSafe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_pipe_win32.cpp
374 lines (329 loc) · 10.8 KB
/
service_pipe_win32.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// SPDX-License-Identifier: AGPL-1.0-only
// Copyright (C) 2018 Ludvig Strigeus <info@tunsafe.com>. All Rights Reserved.
#include "stdafx.h"
#include "service_pipe_win32.h"
#include "util.h"
#include "service_win32_constants.h"
///////////////////////////////////////////////////////////////////////////////////////
// PipeManager
///////////////////////////////////////////////////////////////////////////////////////
PipeManager::PipeManager(const char *pipe_name, bool is_server_pipe, Delegate *delegate) {
pipe_name_ = _strdup(pipe_name);
is_server_pipe_ = is_server_pipe;
for (size_t i = 0; i < kMaxConnections * 2 + 1; i++)
events_[i] = CreateEvent(NULL, i != 0, FALSE, NULL); // For Exit
delegate_ = delegate;
thread_ = NULL;
exit_thread_ = false;
thread_id_ = 0;
for (size_t i = 0; i != kMaxConnections; i++)
connections_[i].Configure(this, (int)i);
connections_[0].state_ = PipeConnection::kStateStarting;
}
PipeManager::~PipeManager() {
StopThread();
for (size_t i = 0; i < kMaxConnections * 2 + 1; i++)
CloseHandle(events_[i]);
free(pipe_name_);
}
bool PipeManager::StartThread() {
assert(thread_ == NULL);
thread_ = CreateThread(NULL, 0, &StaticThreadMain, this, 0, &thread_id_);
return thread_ != NULL;
}
void PipeManager::StopThread() {
if (thread_ != NULL) {
exit_thread_ = true;
SetEvent(events_[0]);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = NULL;
}
}
bool PipeManager::VerifyThread() {
return thread_id_ == GetCurrentThreadId();
}
void PipeManager::TryStartNewListener() {
assert(VerifyThread());
assert(is_server_pipe_);
// Check if any thread is in the listener state, if not, start
PipeConnection *found_conn = NULL;
for (size_t i = 0; i < kMaxConnections; i++) {
PipeConnection *conn = &connections_[i];
if (conn->connection_established_)
continue;
if (conn->state_ == PipeConnection::kStateWaitConnect)
return;
if (conn->state_ == PipeConnection::kStateNone && found_conn == NULL)
found_conn = conn;
}
if (found_conn) {
found_conn->state_ = PipeConnection::kStateStarting;
found_conn->AdvanceStateMachine();
}
}
DWORD WINAPI PipeManager::StaticThreadMain(void *x) {
return ((PipeManager*)x)->ThreadMain();
}
DWORD PipeManager::ThreadMain() {
assert(VerifyThread());
for (size_t i = 0; i < kMaxConnections; i++)
connections_[i].AdvanceStateMachine();
for (;;) {
DWORD rv = WaitForMultipleObjects(1 + kMaxConnections * 2, events_, FALSE, INFINITE);
// notify?
if (rv == WAIT_OBJECT_0) {
if (exit_thread_)
break;
delegate_->HandleNotify();
// The notification event is set when there might be new messages to send,
// so try to send them.
for (size_t i = 0; i != kMaxConnections; i++)
connections_[i].TrySendNextQueuedWrite();
} else if (rv >= WAIT_OBJECT_0 + 1 && rv < WAIT_OBJECT_0 + 1 + kMaxConnections * 2) {
PipeConnection *conn = &connections_[(rv - 1) >> 1];
if (rv & 1) {
// read finished
conn->AdvanceStateMachine();
} else {
// is the write event
conn->HandleWriteComplete();
}
} else {
assert(0);
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////
// PipeConnection
///////////////////////////////////////////////////////////////////////////////////////
static void ClearPipeOverlapped(OVERLAPPED *ov) {
ov->Internal = 0;
ov->InternalHigh = 0;
ov->Offset = 0;
ov->OffsetHigh = 0;
}
PipeConnection::PipeConnection() {
pipe_ = INVALID_HANDLE_VALUE;
packets_ = NULL;
packets_end_ = &packets_;
write_overlapped_active_ = false;
connection_established_ = false;
state_ = kStateNone;
tmp_packet_buf_ = NULL;
tmp_packet_size_ = 0;
manager_ = NULL;
delegate_ = NULL;
}
PipeConnection::~PipeConnection() {
}
void PipeConnection::Configure(PipeManager *manager, int slot) {
manager_ = manager;
read_overlapped_.hEvent = manager->events_[1 + slot * 2];
write_overlapped_.hEvent = manager->events_[1 + slot * 2 + 1];
}
int PipeConnection::InitializeServerPipeAndConnect() {
int BUFSIZE = 8192;
SECURITY_ATTRIBUTES saPipeSecurity = {0};
uint8 buf[SECURITY_DESCRIPTOR_MIN_LENGTH];
PSECURITY_DESCRIPTOR pPipeSD = (PSECURITY_DESCRIPTOR)buf;
if (!InitializeSecurityDescriptor(pPipeSD, SECURITY_DESCRIPTOR_REVISION))
return -1;
// set NULL DACL on the SD
if (!SetSecurityDescriptorDacl(pPipeSD, TRUE, (PACL)NULL, FALSE))
return -1;
// now set up the security attributes
saPipeSecurity.nLength = sizeof(SECURITY_ATTRIBUTES);
saPipeSecurity.bInheritHandle = TRUE;
saPipeSecurity.lpSecurityDescriptor = pPipeSD;
pipe_ = CreateNamedPipe(manager_->pipe_name_,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE, BUFSIZE, 0, &saPipeSecurity);
if (pipe_ == INVALID_HANDLE_VALUE)
return -1;
ClearPipeOverlapped(&read_overlapped_);
// It seems like ConnectNamedPipe never sets the event object if it completes
// right away.
if (!ConnectNamedPipe(pipe_, &read_overlapped_)) {
DWORD rv = GetLastError();
return (rv == ERROR_IO_PENDING) ? 0 : (rv == ERROR_PIPE_CONNECTED) ? 1 : -1;
} else {
return 1;
}
}
bool PipeConnection::InitializeClientPipe() {
assert(pipe_ == INVALID_HANDLE_VALUE);
pipe_ = CreateFile(manager_->pipe_name_, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
return (pipe_ != INVALID_HANDLE_VALUE);
}
void PipeConnection::ClosePipe() {
if (pipe_ != INVALID_HANDLE_VALUE) {
CancelIo(pipe_);
CloseHandle(pipe_);
pipe_ = INVALID_HANDLE_VALUE;
}
connection_established_ = false;
write_overlapped_active_ = false;
state_ = kStateNone;
free(tmp_packet_buf_);
tmp_packet_buf_ = NULL;
tmp_packet_size_ = 0;
ResetEvent(read_overlapped_.hEvent);
ResetEvent(write_overlapped_.hEvent);
packets_mutex_.Acquire();
OutgoingPacket *packets = packets_;
packets_ = NULL;
packets_end_ = &packets_;
packets_mutex_.Release();
while (packets) {
OutgoingPacket *p = packets;
packets = p->next;
free(p);
}
}
void PipeConnection::HandleWriteComplete() {
assert(write_overlapped_active_);
write_overlapped_active_ = false;
// Remove the packet from the front of the queue, now that it was sent.
packets_mutex_.Acquire();
OutgoingPacket *p = packets_;
if ((packets_ = p->next) == NULL)
packets_end_ = &packets_;
packets_mutex_.Release();
free(p);
if (packets_ == NULL && state_ == kStateWaitTimeout)
AdvanceStateMachine();
else
TrySendNextQueuedWrite();
}
bool PipeConnection::WritePacket(int type, const uint8 *data, size_t data_size) {
OutgoingPacket *packet = (OutgoingPacket *)malloc(offsetof(OutgoingPacket, data[data_size + 1]));
if (packet) {
packet->size = (uint32)(data_size + 1);
packet->data[0] = type;
memcpy(packet->data + 1, data, data_size);
packet->next = NULL;
packets_mutex_.Acquire();
OutgoingPacket *was_empty = packets_;
// login messages are always queued up front
if (type == TS_SERVICE_REQ_LOGIN) {
packet->next = packets_;
if (packet->next == NULL)
packets_end_ = &packet->next;
packets_ = packet;
} else {
*packets_end_ = packet;
packets_end_ = &packet->next;
}
packets_mutex_.Release();
if (was_empty == NULL) {
// Only allow the pipe thread to invoke the send
if (GetCurrentThreadId() == manager_->thread_id_) {
TrySendNextQueuedWrite();
} else {
SetEvent(manager_->notify_handle());
}
}
}
return true;
}
bool PipeConnection::VerifyThread() {
return manager_->VerifyThread();
}
void PipeConnection::TrySendNextQueuedWrite() {
assert(manager_->VerifyThread());
if (!write_overlapped_active_) {
OutgoingPacket *p = packets_;
if (p && connection_established_) {
ClearPipeOverlapped(&write_overlapped_);
if (WriteFile(pipe_, &p->size, p->size + 4, NULL, &write_overlapped_) || GetLastError() == ERROR_IO_PENDING)
write_overlapped_active_ = true;
} else {
ResetEvent(write_overlapped_.hEvent);
}
}
}
#define TS_WAIT_BEGIN(t) switch(state_) { case t:
#define TS_WAIT_POINT(t) state_ = (t); return; case t:
#define TS_WAIT_END() }
void PipeConnection::AdvanceStateMachine() {
DWORD rv;
int srv;
TS_WAIT_BEGIN(kStateStarting)
// Create a named pipe and wait for connections from the UI process
if (manager_->is_server_pipe_) {
srv = InitializeServerPipeAndConnect();
if (srv < 0) {
if (!manager_->exit_thread_)
ExitProcess(1);
ClosePipe();
return;
}
if (srv == 0) {
TS_WAIT_POINT(kStateWaitConnect);
}
} else {
if (!InitializeClientPipe()) {
RINFO("Unable to connect to the TunSafe Service. Please make sure it's running.");
ClosePipe();
return;
}
}
connection_established_ = true;
delegate_ = manager_->delegate_->HandleNewConnection(this);
TrySendNextQueuedWrite();
for (;;) {
// Read the packet length
read_pos_ = 0;
do {
ClearPipeOverlapped(&read_overlapped_);
if (!ReadFile(pipe_, (uint8*)&packet_size_ + read_pos_, 4 - read_pos_, NULL, &read_overlapped_)) {
if ((rv = GetLastError()) != ERROR_IO_PENDING)
goto fail;
TS_WAIT_POINT(kStateWaitReadLength);
}
if ((uint32)read_overlapped_.InternalHigh == 0)
goto fail;
read_pos_ += (uint32)read_overlapped_.InternalHigh;
} while (read_pos_ != 4);
assert(packet_size_ != 0 && packet_size_ < 0x1000000);
if (packet_size_ == 0 || packet_size_ >= 0x1000000)
break;
free(tmp_packet_buf_);
tmp_packet_buf_ = (uint8*)malloc(packet_size_);
if (!tmp_packet_buf_)
break;
// Read the packet payload
read_pos_ = 0;
do {
ClearPipeOverlapped(&read_overlapped_);
if (!ReadFile(pipe_, tmp_packet_buf_ + read_pos_, packet_size_ - read_pos_, NULL, &read_overlapped_)) {
if ((rv = GetLastError()) != ERROR_IO_PENDING)
goto fail;
TS_WAIT_POINT(kStateWaitReadPayload);
}
if ((uint32)read_overlapped_.InternalHigh == 0)
goto fail;
read_pos_ += (uint32)read_overlapped_.InternalHigh;
} while (read_pos_ != packet_size_);
if (!delegate_->HandleMessage(tmp_packet_buf_[0], tmp_packet_buf_ + 1, packet_size_ - 1)) {
ResetEvent(read_overlapped_.hEvent);
if (packets_ != NULL) {
TS_WAIT_POINT(kStateWaitTimeout);
}
break;
}
}
fail:
ClosePipe();
if (!manager_->exit_thread_) {
delegate_->HandleDisconnect();
if (manager_->is_server_pipe_)
manager_->TryStartNewListener();
}
TS_WAIT_END()
}