robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

taofix(path): normalize separators (slashes) #391554a08596314

master
11.1 KiB366 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <stdbool.h>
4#include <stdio.h>
5#include <string.h>
6#include <uv.h>
7
8#include "nvim/ascii_defs.h"
9#include "nvim/charset.h"
10#include "nvim/event/defs.h"
11#include "nvim/event/loop.h"
12#include "nvim/event/multiqueue.h"
13#include "nvim/event/socket.h"
14#include "nvim/event/stream.h"
15#include "nvim/gettext_defs.h"
16#include "nvim/log.h"
17#include "nvim/main.h"
18#include "nvim/memory.h"
19#include "nvim/os/fs.h"
20#include "nvim/os/os_defs.h"
21#include "nvim/path.h"
22#include "nvim/types_defs.h"
23
24#include "event/socket.c.generated.h"
25
26/// Checks if an address string looks like a TCP endpoint, and returns the end of the host part.
27///
28/// @param address Address string
29/// @return pointer to the end of the host part of the address, or NULL if it is not a TCP address
30char *socket_address_tcp_host_end(const char *address)
31{
32  if (address == NULL) {
33    return NULL;
34  }
35
36  // Windows drive letter path: "X:/..." is a local path, not TCP.
37  if (ASCII_ISALPHA((uint8_t)address[0]) && address[1] == ':' && address[2] == '/') {
38    return NULL;
39  }
40
41  char *colon = strrchr((char *)address, ':');
42  return colon != NULL && colon != address ? colon : NULL;
43}
44
45int socket_watcher_init(Loop *loop, SocketWatcher *watcher, const char *endpoint)
46  FUNC_ATTR_NONNULL_ALL
47{
48  xstrlcpy(watcher->addr, endpoint, sizeof(watcher->addr));
49  char *addr = watcher->addr;
50  char *host_end = socket_address_tcp_host_end(addr);
51
52  if (host_end) {
53    // Split user specified address into two strings, addr (hostname) and port.
54    // The port part in watcher->addr will be updated later.
55    *host_end = NUL;
56    char *port = host_end + 1;
57    intmax_t iport;
58
59    int ok = try_getdigits(&(char *){ port }, &iport);
60    if (!ok || iport < 0 || iport > UINT16_MAX) {
61      ELOG("Invalid port: %s", port);
62      return UV_EINVAL;
63    }
64
65    if (*port == NUL) {
66      // When no port is given, (uv_)getaddrinfo expects NULL otherwise the
67      // implementation may attempt to lookup the service by name (and fail)
68      port = NULL;
69    }
70
71    uv_getaddrinfo_t request;
72
73    int retval = uv_getaddrinfo(&loop->uv, &request, NULL, addr, port,
74                                &(struct addrinfo){ .ai_family = AF_UNSPEC,
75                                                    .ai_socktype = SOCK_STREAM, });
76    if (retval != 0) {
77      ELOG("Host lookup failed: %s", endpoint);
78      return retval;
79    }
80    watcher->uv.tcp.addrinfo = request.addrinfo;
81
82    uv_tcp_init(&loop->uv, &watcher->uv.tcp.handle);
83    uv_tcp_nodelay(&watcher->uv.tcp.handle, true);
84    watcher->stream = (uv_stream_t *)(&watcher->uv.tcp.handle);
85  } else {
86    uv_pipe_init(&loop->uv, &watcher->uv.pipe.handle, 0);
87    watcher->stream = (uv_stream_t *)(&watcher->uv.pipe.handle);
88  }
89
90  watcher->stream->data = watcher;
91  watcher->cb = NULL;
92  watcher->close_cb = NULL;
93  watcher->events = NULL;
94  watcher->data = NULL;
95
96  return 0;
97}
98
99/// Callback after closing a Stream initialized by socket_connect().
100static void connect_close_cb(Stream *stream, void *data)
101{
102  bool *closed = data;
103  *closed = true;
104}
105
106/// Check if a socket is alive by attempting to connect to it.
107/// @param loop Event loop
108/// @param addr Socket address to probe
109/// @return true if socket is alive (connection succeeded), false otherwise
110static bool socket_alive(Loop *loop, const char *addr)
111{
112  RStream stream = { 0 };
113  const char *error = NULL;
114
115  // Try to connect with a 500ms timeout (fast failure for dead sockets)
116  bool connected = socket_connect(loop, &stream, false, addr, 500, &error);
117  if (!connected) {
118    return false;
119  }
120
121  // Connection succeeded - socket is alive. Close the probe connection properly.
122  bool closed = false;
123  stream.s.internal_close_cb = connect_close_cb;
124  stream.s.internal_data = &closed;
125  stream_may_close(&stream.s);
126  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, -1, closed);
127
128  return true;
129}
130
131static void early_server_close_cb(uv_handle_t *handle)
132{
133  bool *closed = handle->data;
134  *closed = true;
135}
136
137int socket_watcher_start(SocketWatcher *watcher, int backlog, socket_cb cb)
138  FUNC_ATTR_NONNULL_ALL
139{
140  watcher->cb = cb;
141  int result = UV_EINVAL;
142
143  if (watcher->stream->type == UV_TCP) {
144    struct addrinfo *ai = watcher->uv.tcp.addrinfo;
145
146    for (; ai; ai = ai->ai_next) {
147      result = uv_tcp_bind(&watcher->uv.tcp.handle, ai->ai_addr, 0);
148      if (result != 0) {
149        continue;
150      }
151      result = uv_listen(watcher->stream, backlog, connection_cb);
152      if (result == 0) {
153        struct sockaddr_storage sas;
154
155        // When the endpoint in socket_watcher_init() didn't specify a port
156        // number, a free random port number will be assigned. sin_port will
157        // contain 0 in this case, unless uv_tcp_getsockname() is used first.
158        uv_tcp_getsockname(&watcher->uv.tcp.handle, (struct sockaddr *)&sas,
159                           &(int){ sizeof(sas) });
160        uint16_t port = (sas.ss_family == AF_INET) ? ((struct sockaddr_in *)(&sas))->sin_port
161                                                   : ((struct sockaddr_in6 *)(&sas))->sin6_port;
162        // v:servername uses the string from watcher->addr
163        size_t len = strlen(watcher->addr);
164        snprintf(watcher->addr + len, sizeof(watcher->addr) - len, ":%" PRIu16,
165                 ntohs(port));
166        break;
167      }
168    }
169    uv_freeaddrinfo(watcher->uv.tcp.addrinfo);
170  } else {
171    result = uv_pipe_bind2(&watcher->uv.pipe.handle, watcher->addr, strlen(watcher->addr),
172                           UV_PIPE_NO_TRUNCATE);
173
174    // If bind failed with EACCES/EADDRINUSE, check if socket is stale
175    if (result == UV_EACCES || result == UV_EADDRINUSE) {
176      Loop *loop = watcher->stream->loop->data;
177
178      if (!socket_alive(loop, watcher->addr)) {
179        // Socket exists but is dead - remove it
180        ILOG("Removing stale socket: %s", watcher->addr);
181        int rm_result = os_remove(watcher->addr);
182
183        if (rm_result != 0) {
184          WLOG("Failed to remove stale socket %s: %s",
185               watcher->addr, uv_strerror(rm_result));
186        } else {
187          // Close and reinit the pipe handle before retrying bind
188          uv_loop_t *uv_loop = watcher->uv.pipe.handle.loop;
189          bool closed = false;
190          watcher->uv.pipe.handle.data = &closed;
191          uv_close((uv_handle_t *)&watcher->uv.pipe.handle, early_server_close_cb);
192          LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, -1, closed);
193
194          uv_pipe_init(uv_loop, &watcher->uv.pipe.handle, 0);
195          watcher->stream = (uv_stream_t *)(&watcher->uv.pipe.handle);
196          watcher->stream->data = watcher;
197
198          // Retry bind with fresh handle
199          result = uv_pipe_bind2(&watcher->uv.pipe.handle, watcher->addr, strlen(watcher->addr),
200                                 UV_PIPE_NO_TRUNCATE);
201        }
202      } else {
203        // Socket is alive - this is a real error
204        ELOG("Socket already in use by another Nvim instance: %s", watcher->addr);
205      }
206    }
207
208    if (result == 0) {
209      result = uv_listen(watcher->stream, backlog, connection_cb);
210    }
211  }
212
213  assert(result <= 0);  // libuv should return negative error code or zero.
214  if (result < 0) {
215    if (result == UV_EACCES) {
216      // Libuv converts ENOENT to EACCES for Windows compatibility, but if
217      // the parent directory does not exist, ENOENT would be more accurate.
218      *path_tail(watcher->addr) = NUL;
219      if (!os_path_exists(watcher->addr)) {
220        result = UV_ENOENT;
221      }
222    }
223    return result;
224  }
225
226  return 0;
227}
228
229int socket_watcher_accept(SocketWatcher *watcher, RStream *stream)
230  FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_NONNULL_ARG(2)
231{
232  uv_stream_t *client;
233
234  if (watcher->stream->type == UV_TCP) {
235    client = (uv_stream_t *)(&stream->s.uv.tcp);
236    uv_tcp_init(watcher->uv.tcp.handle.loop, (uv_tcp_t *)client);
237    uv_tcp_nodelay((uv_tcp_t *)client, true);
238  } else {
239    client = (uv_stream_t *)&stream->s.uv.pipe;
240    uv_pipe_init(watcher->uv.pipe.handle.loop, (uv_pipe_t *)client, 0);
241  }
242
243  int result = uv_accept(watcher->stream, client);
244
245  if (result) {
246    uv_close((uv_handle_t *)client, NULL);
247    return result;
248  }
249
250  stream_init(NULL, &stream->s, -1, client);
251  return 0;
252}
253
254void socket_watcher_close(SocketWatcher *watcher, socket_close_cb cb)
255  FUNC_ATTR_NONNULL_ARG(1)
256{
257  watcher->close_cb = cb;
258  uv_close((uv_handle_t *)watcher->stream, close_cb);
259}
260
261static void connection_event(void **argv)
262{
263  SocketWatcher *watcher = argv[0];
264  int status = (int)(uintptr_t)(argv[1]);
265  watcher->cb(watcher, status, watcher->data);
266}
267
268static void connection_cb(uv_stream_t *handle, int status)
269{
270  SocketWatcher *watcher = handle->data;
271  CREATE_EVENT(watcher->events, connection_event, watcher, (void *)(uintptr_t)status);
272}
273
274static void close_cb(uv_handle_t *handle)
275{
276  SocketWatcher *watcher = handle->data;
277  if (watcher->close_cb) {
278    watcher->close_cb(watcher, watcher->data);
279  }
280}
281
282static void connect_cb(uv_connect_t *req, int status)
283{
284  int *ret_status = req->data;
285  *ret_status = status;
286  uv_handle_t *handle = (uv_handle_t *)req->handle;
287  if (status != 0) {
288    stream_may_close(handle->data);
289  }
290}
291
292bool socket_connect(Loop *loop, RStream *stream, bool is_tcp, const char *address, int timeout,
293                    const char **error)
294{
295  bool success = false;
296  bool closed;
297  int status;
298  uv_connect_t req;
299  req.data = &status;
300  uv_stream_t *uv_stream;
301
302  uv_tcp_t *tcp = &stream->s.uv.tcp;
303  uv_getaddrinfo_t addr_req;
304  addr_req.addrinfo = NULL;
305  const struct addrinfo *addrinfo = NULL;
306  char *addr = NULL;
307  if (is_tcp) {
308    addr = xstrdup(address);
309    char *host_end = strrchr(addr, ':');
310    if (!host_end) {
311      *error = _("tcp address must be host:port");
312      goto cleanup;
313    }
314    *host_end = NUL;
315
316    const struct addrinfo hints = { .ai_family = AF_UNSPEC,
317                                    .ai_socktype = SOCK_STREAM,
318                                    .ai_flags = AI_NUMERICSERV };
319    int retval = uv_getaddrinfo(&loop->uv, &addr_req, NULL,
320                                addr, host_end + 1, &hints);
321    if (retval != 0) {
322      *error = _("failed to lookup host or port");
323      goto cleanup;
324    }
325    addrinfo = addr_req.addrinfo;
326
327tcp_retry:
328    uv_tcp_init(&loop->uv, tcp);
329    uv_tcp_nodelay(tcp, true);
330    uv_tcp_connect(&req,  tcp, addrinfo->ai_addr, connect_cb);
331    uv_stream = (uv_stream_t *)tcp;
332  } else {
333    uv_pipe_t *pipe = &stream->s.uv.pipe;
334    uv_pipe_init(&loop->uv, pipe, 0);
335    uv_pipe_connect(&req,  pipe, address, connect_cb);
336    uv_stream = (uv_stream_t *)pipe;
337  }
338  stream_init(NULL, &stream->s, -1, uv_stream);
339  stream->s.internal_close_cb = connect_close_cb;
340  stream->s.internal_data = &closed;
341  closed = false;
342  status = 1;
343  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, timeout, status != 1);
344  if (status == 0) {
345    success = true;
346  } else {
347    stream_may_close(&stream->s);
348    // Wait for the close callback to arrive before retrying or returning, otherwise
349    // it may lead to a hang or stack-use-after-return.
350    LOOP_PROCESS_EVENTS_UNTIL(&main_loop, NULL, -1, closed);
351
352    if (is_tcp && addrinfo->ai_next) {
353      addrinfo = addrinfo->ai_next;
354      goto tcp_retry;
355    } else {
356      *error = _("connection refused");
357    }
358  }
359
360cleanup:
361  stream->s.internal_close_cb = NULL;
362  stream->s.internal_data = NULL;
363  xfree(addr);
364  uv_freeaddrinfo(addr_req.addrinfo);
365  return success;
366}