2 #include "simple-ipc.h"
5 #include "thread-utils.h"
7 #ifndef GIT_WINDOWS_NATIVE
8 #error This file can only be compiled on Windows
11 static int initialize_pipe_name(const char *path, wchar_t *wpath, size_t alloc)
14 struct strbuf realpath = STRBUF_INIT;
16 if (!strbuf_realpath(&realpath, path, 0))
19 off = swprintf(wpath, alloc, L"\\\\.\\pipe\\");
20 if (xutftowcs(wpath + off, realpath.buf, alloc - off) < 0)
23 /* Handle drive prefix */
24 if (wpath[off] && wpath[off + 1] == L':') {
25 wpath[off + 1] = L'_';
29 for (; wpath[off]; off++)
30 if (wpath[off] == L'/')
33 strbuf_release(&realpath);
37 static enum ipc_active_state get_active_state(wchar_t *pipe_path)
39 if (WaitNamedPipeW(pipe_path, NMPWAIT_USE_DEFAULT_WAIT))
40 return IPC_STATE__LISTENING;
42 if (GetLastError() == ERROR_SEM_TIMEOUT)
43 return IPC_STATE__NOT_LISTENING;
45 if (GetLastError() == ERROR_FILE_NOT_FOUND)
46 return IPC_STATE__PATH_NOT_FOUND;
48 return IPC_STATE__OTHER_ERROR;
51 enum ipc_active_state ipc_get_active_state(const char *path)
53 wchar_t pipe_path[MAX_PATH];
55 if (initialize_pipe_name(path, pipe_path, ARRAY_SIZE(pipe_path)) < 0)
56 return IPC_STATE__INVALID_PATH;
58 return get_active_state(pipe_path);
61 #define WAIT_STEP_MS (50)
63 static enum ipc_active_state connect_to_server(
66 const struct ipc_client_connect_options *options,
69 DWORD t_start_ms, t_waited_ms;
71 HANDLE hPipe = INVALID_HANDLE_VALUE;
72 DWORD mode = PIPE_READMODE_BYTE;
78 hPipe = CreateFileW(wpath, GENERIC_READ | GENERIC_WRITE,
79 0, NULL, OPEN_EXISTING, 0, NULL);
80 if (hPipe != INVALID_HANDLE_VALUE)
86 case ERROR_FILE_NOT_FOUND:
87 if (!options->wait_if_not_found)
88 return IPC_STATE__PATH_NOT_FOUND;
90 return IPC_STATE__PATH_NOT_FOUND;
92 step_ms = (timeout_ms < WAIT_STEP_MS) ?
93 timeout_ms : WAIT_STEP_MS;
94 sleep_millisec(step_ms);
96 timeout_ms -= step_ms;
97 break; /* try again */
100 if (!options->wait_if_busy)
101 return IPC_STATE__NOT_LISTENING;
103 return IPC_STATE__NOT_LISTENING;
105 t_start_ms = (DWORD)(getnanotime() / 1000000);
107 if (!WaitNamedPipeW(wpath, timeout_ms)) {
108 if (GetLastError() == ERROR_SEM_TIMEOUT)
109 return IPC_STATE__NOT_LISTENING;
111 return IPC_STATE__OTHER_ERROR;
115 * A pipe server instance became available.
116 * Race other client processes to connect to
119 * But first decrement our overall timeout so
120 * that we don't starve if we keep losing the
121 * race. But also guard against special
122 * NPMWAIT_ values (0 and -1).
124 t_waited_ms = (DWORD)(getnanotime() / 1000000) - t_start_ms;
125 if (t_waited_ms < timeout_ms)
126 timeout_ms -= t_waited_ms;
129 break; /* try again */
132 return IPC_STATE__OTHER_ERROR;
136 if (!SetNamedPipeHandleState(hPipe, &mode, NULL, NULL)) {
138 return IPC_STATE__OTHER_ERROR;
141 *pfd = _open_osfhandle((intptr_t)hPipe, O_RDWR|O_BINARY);
144 return IPC_STATE__OTHER_ERROR;
147 /* fd now owns hPipe */
149 return IPC_STATE__LISTENING;
153 * The default connection timeout for Windows clients.
155 * This is not currently part of the ipc_ API (nor the config settings)
156 * because of differences between Windows and other platforms.
158 * This value was chosen at random.
160 #define WINDOWS_CONNECTION_TIMEOUT_MS (30000)
162 enum ipc_active_state ipc_client_try_connect(
164 const struct ipc_client_connect_options *options,
165 struct ipc_client_connection **p_connection)
167 wchar_t wpath[MAX_PATH];
168 enum ipc_active_state state = IPC_STATE__OTHER_ERROR;
171 *p_connection = NULL;
173 trace2_region_enter("ipc-client", "try-connect", NULL);
174 trace2_data_string("ipc-client", NULL, "try-connect/path", path);
176 if (initialize_pipe_name(path, wpath, ARRAY_SIZE(wpath)) < 0)
177 state = IPC_STATE__INVALID_PATH;
179 state = connect_to_server(wpath, WINDOWS_CONNECTION_TIMEOUT_MS,
182 trace2_data_intmax("ipc-client", NULL, "try-connect/state",
184 trace2_region_leave("ipc-client", "try-connect", NULL);
186 if (state == IPC_STATE__LISTENING) {
187 (*p_connection) = xcalloc(1, sizeof(struct ipc_client_connection));
188 (*p_connection)->fd = fd;
194 void ipc_client_close_connection(struct ipc_client_connection *connection)
199 if (connection->fd != -1)
200 close(connection->fd);
205 int ipc_client_send_command_to_connection(
206 struct ipc_client_connection *connection,
207 const char *message, struct strbuf *answer)
211 strbuf_setlen(answer, 0);
213 trace2_region_enter("ipc-client", "send-command", NULL);
215 if (write_packetized_from_buf_no_flush(message, strlen(message),
216 connection->fd) < 0 ||
217 packet_flush_gently(connection->fd) < 0) {
218 ret = error(_("could not send IPC command"));
222 FlushFileBuffers((HANDLE)_get_osfhandle(connection->fd));
224 if (read_packetized_to_strbuf(
225 connection->fd, answer,
226 PACKET_READ_GENTLE_ON_EOF | PACKET_READ_GENTLE_ON_READ_ERROR) < 0) {
227 ret = error(_("could not read IPC response"));
232 trace2_region_leave("ipc-client", "send-command", NULL);
236 int ipc_client_send_command(const char *path,
237 const struct ipc_client_connect_options *options,
238 const char *message, struct strbuf *response)
241 enum ipc_active_state state;
242 struct ipc_client_connection *connection = NULL;
244 state = ipc_client_try_connect(path, options, &connection);
246 if (state != IPC_STATE__LISTENING)
249 ret = ipc_client_send_command_to_connection(connection, message, response);
251 ipc_client_close_connection(connection);
257 * Duplicate the given pipe handle and wrap it in a file descriptor so
258 * that we can use pkt-line on it.
260 static int dup_fd_from_pipe(const HANDLE pipe)
262 HANDLE process = GetCurrentProcess();
266 if (!DuplicateHandle(process, pipe, process, &handle, 0, FALSE,
267 DUPLICATE_SAME_ACCESS)) {
268 errno = err_win_to_posix(GetLastError());
272 fd = _open_osfhandle((intptr_t)handle, O_RDWR|O_BINARY);
274 errno = err_win_to_posix(GetLastError());
280 * `handle` is now owned by `fd` and will be automatically closed
281 * when the descriptor is closed.
288 * Magic numbers used to annotate callback instance data.
289 * These are used to help guard against accidentally passing the
290 * wrong instance data across multiple levels of callbacks (which
291 * is easy to do if there are `void*` arguments).
294 MAGIC_SERVER_REPLY_DATA,
295 MAGIC_SERVER_THREAD_DATA,
299 struct ipc_server_reply_data {
302 struct ipc_server_thread_data *server_thread_data;
305 struct ipc_server_thread_data {
307 struct ipc_server_thread_data *next_thread;
308 struct ipc_server_data *server_data;
309 pthread_t pthread_id;
314 * On Windows, the conceptual "ipc-server" is implemented as a pool of
315 * n idential/peer "server-thread" threads. That is, there is no
316 * hierarchy of threads; and therefore no controller thread managing
317 * the pool. Each thread has an independent handle to the named pipe,
318 * receives incoming connections, processes the client, and re-uses
319 * the pipe for the next client connection.
321 * Therefore, the "ipc-server" only needs to maintain a list of the
322 * spawned threads for eventual "join" purposes.
324 * A single "stop-event" is visible to all of the server threads to
325 * tell them to shutdown (when idle).
327 struct ipc_server_data {
329 ipc_server_application_cb *application_cb;
330 void *application_data;
331 struct strbuf buf_path;
332 wchar_t wpath[MAX_PATH];
334 HANDLE hEventStopRequested;
335 struct ipc_server_thread_data *thread_list;
339 enum connect_result {
347 static enum connect_result queue_overlapped_connect(
348 struct ipc_server_thread_data *server_thread_data,
351 if (ConnectNamedPipe(server_thread_data->hPipe, lpo))
354 switch (GetLastError()) {
355 case ERROR_IO_PENDING:
356 return CR_CONNECT_PENDING;
358 case ERROR_PIPE_CONNECTED:
359 SetEvent(lpo->hEvent);
367 error(_("ConnectNamedPipe failed for '%s' (%lu)"),
368 server_thread_data->server_data->buf_path.buf,
370 return CR_CONNECT_ERROR;
374 * Use Windows Overlapped IO to wait for a connection or for our event
377 static enum connect_result wait_for_connection(
378 struct ipc_server_thread_data *server_thread_data,
381 enum connect_result r;
382 HANDLE waitHandles[2];
385 r = queue_overlapped_connect(server_thread_data, lpo);
386 if (r != CR_CONNECT_PENDING)
389 waitHandles[0] = server_thread_data->server_data->hEventStopRequested;
390 waitHandles[1] = lpo->hEvent;
392 dwWaitResult = WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE);
393 switch (dwWaitResult) {
394 case WAIT_OBJECT_0 + 0:
397 case WAIT_OBJECT_0 + 1:
398 ResetEvent(lpo->hEvent);
402 return CR_WAIT_ERROR;
407 * Forward declare our reply callback function so that any compiler
408 * errors are reported when we actually define the function (in addition
409 * to any errors reported when we try to pass this callback function as
410 * a parameter in a function call). The former are easier to understand.
412 static ipc_server_reply_cb do_io_reply_callback;
415 * Relay application's response message to the client process.
416 * (We do not flush at this point because we allow the caller
417 * to chunk data to the client thru us.)
419 static int do_io_reply_callback(struct ipc_server_reply_data *reply_data,
420 const char *response, size_t response_len)
422 if (reply_data->magic != MAGIC_SERVER_REPLY_DATA)
423 BUG("reply_cb called with wrong instance data");
425 return write_packetized_from_buf_no_flush(response, response_len,
430 * Receive the request/command from the client and pass it to the
431 * registered request-callback. The request-callback will compose
432 * a response and call our reply-callback to send it to the client.
434 * Simple-IPC only contains one round trip, so we flush and close
435 * here after the response.
437 static int do_io(struct ipc_server_thread_data *server_thread_data)
439 struct strbuf buf = STRBUF_INIT;
440 struct ipc_server_reply_data reply_data;
443 reply_data.magic = MAGIC_SERVER_REPLY_DATA;
444 reply_data.server_thread_data = server_thread_data;
446 reply_data.fd = dup_fd_from_pipe(server_thread_data->hPipe);
447 if (reply_data.fd < 0)
448 return error(_("could not create fd from pipe for '%s'"),
449 server_thread_data->server_data->buf_path.buf);
451 ret = read_packetized_to_strbuf(
453 PACKET_READ_GENTLE_ON_EOF | PACKET_READ_GENTLE_ON_READ_ERROR);
455 ret = server_thread_data->server_data->application_cb(
456 server_thread_data->server_data->application_data,
457 buf.buf, do_io_reply_callback, &reply_data);
459 packet_flush_gently(reply_data.fd);
461 FlushFileBuffers((HANDLE)_get_osfhandle((reply_data.fd)));
465 * The client probably disconnected/shutdown before it
466 * could send a well-formed message. Ignore it.
470 strbuf_release(&buf);
471 close(reply_data.fd);
477 * Handle IPC request and response with this connected client. And reset
478 * the pipe to prepare for the next client.
480 static int use_connection(struct ipc_server_thread_data *server_thread_data)
484 ret = do_io(server_thread_data);
486 FlushFileBuffers(server_thread_data->hPipe);
487 DisconnectNamedPipe(server_thread_data->hPipe);
493 * Thread proc for an IPC server worker thread. It handles a series of
494 * connections from clients. It cleans and reuses the hPipe between each
497 static void *server_thread_proc(void *_server_thread_data)
499 struct ipc_server_thread_data *server_thread_data = _server_thread_data;
500 HANDLE hEventConnected = INVALID_HANDLE_VALUE;
502 enum connect_result cr;
505 assert(server_thread_data->hPipe != INVALID_HANDLE_VALUE);
507 trace2_thread_start("ipc-server");
508 trace2_data_string("ipc-server", NULL, "pipe",
509 server_thread_data->server_data->buf_path.buf);
511 hEventConnected = CreateEventW(NULL, TRUE, FALSE, NULL);
513 memset(&oConnect, 0, sizeof(oConnect));
514 oConnect.hEvent = hEventConnected;
517 cr = wait_for_connection(server_thread_data, &oConnect);
524 ret = use_connection(server_thread_data);
525 if (ret == SIMPLE_IPC_QUIT) {
526 ipc_server_stop_async(
527 server_thread_data->server_data);
532 * Ignore (transient) IO errors with this
533 * client and reset for the next client.
538 case CR_CONNECT_PENDING:
539 /* By construction, this should not happen. */
540 BUG("ipc-server[%s]: unexpeced CR_CONNECT_PENDING",
541 server_thread_data->server_data->buf_path.buf);
543 case CR_CONNECT_ERROR:
546 * Ignore these theoretical errors.
548 DisconnectNamedPipe(server_thread_data->hPipe);
552 BUG("unandled case after wait_for_connection");
557 CloseHandle(server_thread_data->hPipe);
558 CloseHandle(hEventConnected);
560 trace2_thread_exit();
564 static HANDLE create_new_pipe(wchar_t *wpath, int is_first)
567 DWORD dwOpenMode, dwPipeMode;
568 LPSECURITY_ATTRIBUTES lpsa = NULL;
570 dwOpenMode = PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND |
571 FILE_FLAG_OVERLAPPED;
573 dwPipeMode = PIPE_TYPE_MESSAGE | PIPE_READMODE_BYTE | PIPE_WAIT |
574 PIPE_REJECT_REMOTE_CLIENTS;
577 dwOpenMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
580 * On Windows, the first server pipe instance gets to
581 * set the ACL / Security Attributes on the named
582 * pipe; subsequent instances inherit and cannot
585 * TODO Should we allow the application layer to
586 * specify security attributes, such as `LocalService`
587 * or `LocalSystem`, when we create the named pipe?
588 * This question is probably not important when the
589 * daemon is started by a foreground user process and
590 * only needs to talk to the current user, but may be
591 * if the daemon is run via the Control Panel as a
596 hPipe = CreateNamedPipeW(wpath, dwOpenMode, dwPipeMode,
597 PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, lpsa);
602 int ipc_server_run_async(struct ipc_server_data **returned_server_data,
603 const char *path, const struct ipc_server_opts *opts,
604 ipc_server_application_cb *application_cb,
605 void *application_data)
607 struct ipc_server_data *server_data;
608 wchar_t wpath[MAX_PATH];
609 HANDLE hPipeFirst = INVALID_HANDLE_VALUE;
612 int nr_threads = opts->nr_threads;
614 *returned_server_data = NULL;
616 ret = initialize_pipe_name(path, wpath, ARRAY_SIZE(wpath));
622 hPipeFirst = create_new_pipe(wpath, 1);
623 if (hPipeFirst == INVALID_HANDLE_VALUE) {
628 server_data = xcalloc(1, sizeof(*server_data));
629 server_data->magic = MAGIC_SERVER_DATA;
630 server_data->application_cb = application_cb;
631 server_data->application_data = application_data;
632 server_data->hEventStopRequested = CreateEvent(NULL, TRUE, FALSE, NULL);
633 strbuf_init(&server_data->buf_path, 0);
634 strbuf_addstr(&server_data->buf_path, path);
635 wcscpy(server_data->wpath, wpath);
640 for (k = 0; k < nr_threads; k++) {
641 struct ipc_server_thread_data *std;
643 std = xcalloc(1, sizeof(*std));
644 std->magic = MAGIC_SERVER_THREAD_DATA;
645 std->server_data = server_data;
646 std->hPipe = INVALID_HANDLE_VALUE;
648 std->hPipe = (k == 0)
650 : create_new_pipe(server_data->wpath, 0);
652 if (std->hPipe == INVALID_HANDLE_VALUE) {
654 * If we've reached a pipe instance limit for
655 * this path, just use fewer threads.
661 if (pthread_create(&std->pthread_id, NULL,
662 server_thread_proc, std)) {
664 * Likewise, if we're out of threads, just use
665 * fewer threads than requested.
667 * However, we just give up if we can't even get
668 * one thread. This should not happen.
671 die(_("could not start thread[0] for '%s'"),
674 CloseHandle(std->hPipe);
679 std->next_thread = server_data->thread_list;
680 server_data->thread_list = std;
683 *returned_server_data = server_data;
687 int ipc_server_stop_async(struct ipc_server_data *server_data)
693 * Gently tell all of the ipc_server threads to shutdown.
694 * This will be seen the next time they are idle (and waiting
697 * We DO NOT attempt to force them to drop an active connection.
699 SetEvent(server_data->hEventStopRequested);
703 int ipc_server_await(struct ipc_server_data *server_data)
710 dwWaitResult = WaitForSingleObject(server_data->hEventStopRequested, INFINITE);
711 if (dwWaitResult != WAIT_OBJECT_0)
712 return error(_("wait for hEvent failed for '%s'"),
713 server_data->buf_path.buf);
715 while (server_data->thread_list) {
716 struct ipc_server_thread_data *std = server_data->thread_list;
718 pthread_join(std->pthread_id, NULL);
720 server_data->thread_list = std->next_thread;
724 server_data->is_stopped = 1;
729 void ipc_server_free(struct ipc_server_data *server_data)
734 if (!server_data->is_stopped)
735 BUG("cannot free ipc-server while running for '%s'",
736 server_data->buf_path.buf);
738 strbuf_release(&server_data->buf_path);
740 if (server_data->hEventStopRequested != INVALID_HANDLE_VALUE)
741 CloseHandle(server_data->hEventStopRequested);
743 while (server_data->thread_list) {
744 struct ipc_server_thread_data *std = server_data->thread_list;
746 server_data->thread_list = std->next_thread;