-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppIpc.cpp
More file actions
353 lines (316 loc) · 12.9 KB
/
Copy pathAppIpc.cpp
File metadata and controls
353 lines (316 loc) · 12.9 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
#include "AppIpc.h"
#include "AppLog.h"
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <chrono>
#include <cstdint>
#include <future>
#include <thread>
#include <vector>
namespace
{
constexpr wchar_t kPipeName[] = L"\\\\.\\pipe\\FICture2_IPC";
constexpr std::uint32_t kProtocolVersion = 2; // v2: Waiting ack precedes the final Decision
// Distinct from every Decision value; tells the client "request accepted,
// final decision follows - keep waiting".
constexpr std::uint32_t kWaitingAck = 0xFFFFFFFFu;
// Staged client hard timeouts + the server keep-alive cadence that feeds
// stage 3 (see AppIpc.h's protocol comment for the full ladder).
constexpr DWORD kRequestResponseTimeoutMs = 500; // request sent -> first server message
constexpr DWORD kPostAckTimeoutMs = 2000; // silence allowed after each Waiting ack
constexpr DWORD kKeepAliveIntervalMs = 1000; // server refreshes the ack this often
// Cap Waiting-ack parking: a healthy queue-or-decline server answers after
// the first ack; more than this many means it is alive but not deciding.
constexpr int kMaxWaitingAcks = 3;
bool WriteAll(HANDLE h, const void* data, DWORD bytes)
{
const std::uint8_t* p = static_cast<const std::uint8_t*>(data);
DWORD remaining = bytes;
while (remaining > 0)
{
DWORD written = 0;
if (!WriteFile(h, p, remaining, &written, nullptr))
{
return false;
}
p += written;
remaining -= written;
}
return true;
}
bool ReadAll(HANDLE h, void* data, DWORD bytes)
{
std::uint8_t* p = static_cast<std::uint8_t*>(data);
DWORD remaining = bytes;
while (remaining > 0)
{
DWORD read = 0;
if (!ReadFile(h, p, remaining, &read, nullptr))
{
return false;
}
if (read == 0)
{
return false;
}
p += read;
remaining -= read;
}
return true;
}
// Client-side deadline-bounded I/O: the client opens its pipe handle
// FILE_FLAG_OVERLAPPED so every read/write carries a hard timeout - a
// plain blocking ReadFile could hang forever on a frozen server, which
// is exactly what the staged client timeouts exist to prevent. Handles
// partial transfers (byte-mode pipe) by looping under one deadline.
bool OverlappedIo(HANDLE h, HANDLE event, bool isWrite, void* data, DWORD bytes, DWORD timeoutMs)
{
std::uint8_t* p = static_cast<std::uint8_t*>(data);
DWORD remaining = bytes;
const ULONGLONG deadline = GetTickCount64() + timeoutMs;
while (remaining > 0)
{
OVERLAPPED ov {};
ov.hEvent = event;
ResetEvent(event);
const BOOL started = isWrite
? WriteFile(h, p, remaining, nullptr, &ov)
: ReadFile(h, p, remaining, nullptr, &ov);
if (!started && GetLastError() != ERROR_IO_PENDING)
{
return false;
}
const ULONGLONG now = GetTickCount64();
const DWORD waitMs = now < deadline ? static_cast<DWORD>(deadline - now) : 0;
if (WaitForSingleObject(event, waitMs) != WAIT_OBJECT_0)
{
// Hard timeout. Cancel and wait for the cancellation to
// complete so `ov` may safely leave scope.
CancelIoEx(h, &ov);
DWORD ignored = 0;
GetOverlappedResult(h, &ov, &ignored, TRUE);
return false;
}
DWORD transferred = 0;
if (!GetOverlappedResult(h, &ov, &transferred, FALSE) || transferred == 0)
{
return false;
}
p += transferred;
remaining -= transferred;
}
return true;
}
bool HandleOneClient(HANDLE pipe, const std::function<AppIpc::Decision(const std::wstring&)>& onRequest)
{
std::uint32_t version = 0;
std::uint32_t payloadBytes = 0;
if (!ReadAll(pipe, &version, sizeof(version)) || !ReadAll(pipe, &payloadBytes, sizeof(payloadBytes)))
{
return false;
}
// Cap the payload to something sane for "one file path" so a
// malformed/hostile client cannot make the server allocate wildly.
constexpr std::uint32_t kMaxPayloadBytes = 64 * 1024;
if (version != kProtocolVersion || payloadBytes == 0 || payloadBytes > kMaxPayloadBytes ||
(payloadBytes % sizeof(wchar_t)) != 0)
{
return false;
}
std::vector<wchar_t> buf(payloadBytes / sizeof(wchar_t));
if (!ReadAll(pipe, buf.data(), payloadBytes))
{
return false;
}
// Ensure null-termination (client sends a null-terminated string).
if (buf.empty() || buf.back() != L'\0')
{
buf.push_back(L'\0');
}
const std::wstring path(buf.data());
// Ack receipt before consulting the app. onRequest is a fast
// queue-or-decline check, so the decision normally follows this first
// ack within milliseconds; the keep-alive loop only matters if the
// callback stalls, and even then the client's 3-ack bound caps parking.
const std::uint32_t ack = kWaitingAck;
if (!WriteAll(pipe, &ack, sizeof(ack)))
{
return false;
}
AppIpc::Decision decision = AppIpc::Decision::Ignore;
if (onRequest)
{
std::future<AppIpc::Decision> pending = std::async(std::launch::async,
[&onRequest, &path] { return onRequest(path); });
while (pending.wait_for(std::chrono::milliseconds(kKeepAliveIntervalMs)) !=
std::future_status::ready)
{
if (!WriteAll(pipe, &ack, sizeof(ack)))
{
// Client gave up or died. Let the app callback finish
// (bounded by its own response budget) and drop the
// result - there is nobody left to answer.
pending.wait();
return false;
}
}
decision = pending.get();
}
const std::uint32_t resp = static_cast<std::uint32_t>(decision);
return WriteAll(pipe, &resp, sizeof(resp));
}
}
namespace AppIpc
{
void StartServer(const std::function<Decision(const std::wstring&)>& onRequest)
{
FIC2_LOG_INFO("[IPC] StartServer: launching named-pipe server thread.");
std::thread([onRequest]()
{
for (;;)
{
HANDLE pipe = CreateNamedPipeW(
kPipeName,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
64 * 1024,
64 * 1024,
0,
nullptr);
if (pipe == INVALID_HANDLE_VALUE)
{
FIC2_LOG_ERROR("[IPC] Server: CreateNamedPipeW failed (err={}), retrying in 250ms.", GetLastError());
Sleep(250);
continue;
}
const BOOL ok = ConnectNamedPipe(pipe, nullptr) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (!ok)
{
FIC2_LOG_WARN("[IPC] Server: ConnectNamedPipe failed (err={}), discarding pipe.", GetLastError());
CloseHandle(pipe);
continue;
}
// Per-client worker: HandleOneClient can block for the app
// callback's whole response budget, and consecutive Explorer
// opens connect faster than that - serving them serially
// would let a later client's 500ms connect budget expire
// while an earlier request is still waiting on the UI.
std::thread([pipe, onRequest]()
{
(void)HandleOneClient(pipe, onRequest);
FlushFileBuffers(pipe);
DisconnectNamedPipe(pipe);
CloseHandle(pipe);
}).detach();
}
}).detach();
}
bool TrySendPath(const std::wstring& path, Decision& outDecision)
{
outDecision = Decision::Ignore;
if (path.empty())
{
return false;
}
// Connect to the server pipe with retry logic.
//
// Two distinct failure modes:
// ERROR_FILE_NOT_FOUND - pipe not yet created (server thread still
// starting); WaitNamedPipeW returns
// immediately for this, so poll instead.
// ERROR_PIPE_BUSY - pipe exists but occupied; WaitNamedPipeW
// blocks until an instance frees up.
constexpr DWORD kTotalBudgetMs = 500;
constexpr DWORD kPollIntervalMs = 5;
const auto deadline = std::chrono::steady_clock::now()
+ std::chrono::milliseconds(kTotalBudgetMs);
int retryCount = 0;
HANDLE h = INVALID_HANDLE_VALUE;
while (std::chrono::steady_clock::now() < deadline)
{
// FILE_FLAG_OVERLAPPED: all pipe I/O below runs through
// OverlappedIo so each stage carries its own hard timeout.
h = CreateFileW(kPipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
if (h != INVALID_HANDLE_VALUE)
{
break;
}
const DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND)
{
++retryCount;
Sleep(kPollIntervalMs);
continue;
}
if (err == ERROR_PIPE_BUSY)
{
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
if (remaining <= 0 || !WaitNamedPipeW(kPipeName, static_cast<DWORD>(remaining)))
{
FIC2_LOG_WARN("[IPC] Client: WaitNamedPipeW timed out (err={}).", GetLastError());
break;
}
continue;
}
FIC2_LOG_ERROR("[IPC] Client: pipe connect failed (err={}).", err);
break;
}
if (h == INVALID_HANDLE_VALUE)
{
if (retryCount > 0)
{
FIC2_LOG_WARN("[IPC] Client: server pipe not available after {}ms ({} retries).",
kTotalBudgetMs, retryCount);
}
return false;
}
HANDLE ioEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (ioEvent == nullptr)
{
CloseHandle(h);
return false;
}
std::wstring payload = path + L'\0';
std::uint32_t version = kProtocolVersion;
std::uint32_t payloadBytes = static_cast<std::uint32_t>(payload.size() * sizeof(wchar_t));
// Stage 2: the whole request plus the first server message must fit
// in kRequestResponseTimeoutMs each - a server that accepted the
// connection but never acks is not actually serving.
bool ok = true;
ok = ok && OverlappedIo(h, ioEvent, true, &version, sizeof(version), kRequestResponseTimeoutMs);
ok = ok && OverlappedIo(h, ioEvent, true, &payloadBytes, sizeof(payloadBytes), kRequestResponseTimeoutMs);
ok = ok && OverlappedIo(h, ioEvent, true, payload.data(), payloadBytes, kRequestResponseTimeoutMs);
std::uint32_t resp = 0;
ok = ok && OverlappedIo(h, ioEvent, false, &resp, sizeof(resp), kRequestResponseTimeoutMs);
// Stage 3: parked on Waiting acks, doubly bounded. Silence past
// kPostAckTimeoutMs after an ack means the server froze or died;
// more than kMaxWaitingAcks acks means it is alive but not deciding.
int acksSeen = 0;
while (ok && resp == kWaitingAck)
{
if (++acksSeen > kMaxWaitingAcks)
{
FIC2_LOG_WARN("[IPC] Client: server still undecided after {} Waiting acks - proceeding alone.",
kMaxWaitingAcks);
ok = false;
break;
}
ok = OverlappedIo(h, ioEvent, false, &resp, sizeof(resp), kPostAckTimeoutMs);
}
CloseHandle(ioEvent);
CloseHandle(h);
if (!ok)
{
FIC2_LOG_ERROR("[IPC] Client: pipe I/O failed or timed out during send/recv.");
return false;
}
outDecision = static_cast<Decision>(resp);
FIC2_LOG_INFO("[IPC] Client: server responded with decision={}.", static_cast<int>(outDecision));
return true;
}
}