robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
4a08596314
master
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{ 32if (address == NULL ) { 33return NULL ; 34 } 35 36// Windows drive letter path: "X:/..." is a local path, not TCP. 37if (ASCII_ISALPHA ((uint8_t )address [0 ])&& address [1 ]== ':' && address [2 ]== '/' ) { 38return NULL ; 39 } 40 41char * colon = strrchr ((char * )address ,':' ); 42return colon != NULL && colon != address ?colon :NULL ; 43} 44 45int socket_watcher_init (Loop * loop ,SocketWatcher * watcher ,const char * endpoint ) 46FUNC_ATTR_NONNULL_ALL 47{ 48xstrlcpy (watcher -> addr ,endpoint ,sizeof (watcher -> addr )); 49char * addr = watcher -> addr ; 50char * host_end = socket_address_tcp_host_end (addr ); 51 52if (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 ; 56char * port = host_end + 1 ; 57intmax_t iport ; 58 59int ok = try_getdigits (& (char * ){port },& iport ); 60if (!ok || iport < 0 || iport > UINT16_MAX ) { 61ELOG ("Invalid port: %s" ,port ); 62return UV_EINVAL ; 63 } 64 65if (* 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) 68port = NULL ; 69 } 70 71uv_getaddrinfo_t request ; 72 73int retval = uv_getaddrinfo (& loop -> uv ,& request ,NULL ,addr ,port , 74& (struct addrinfo ){ .ai_family = AF_UNSPEC , 75 .ai_socktype = SOCK_STREAM , }); 76if (retval != 0 ) { 77ELOG ("Host lookup failed: %s" ,endpoint ); 78return retval ; 79 } 80watcher -> uv .tcp .addrinfo = request .addrinfo ; 81 82uv_tcp_init (& loop -> uv ,& watcher -> uv .tcp .handle ); 83uv_tcp_nodelay (& watcher -> uv .tcp .handle , true); 84watcher -> stream = (uv_stream_t * )(& watcher -> uv .tcp .handle ); 85 }else { 86uv_pipe_init (& loop -> uv ,& watcher -> uv .pipe .handle ,0 ); 87watcher -> stream = (uv_stream_t * )(& watcher -> uv .pipe .handle ); 88 } 89 90watcher -> stream -> data = watcher ; 91watcher -> cb = NULL ; 92watcher -> close_cb = NULL ; 93watcher -> events = NULL ; 94watcher -> data = NULL ; 95 96return 0 ; 97} 98 99/// Callback after closing a Stream initialized by socket_connect(). 100static void connect_close_cb (Stream * stream ,void * data ) 101{ 102bool * 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{ 112RStream stream = {0 }; 113const char * error = NULL ; 114 115// Try to connect with a 500ms timeout (fast failure for dead sockets) 116bool connected = socket_connect (loop ,& stream , false,addr ,500 ,& error ); 117if (!connected ) { 118return false; 119 } 120 121// Connection succeeded - socket is alive. Close the probe connection properly. 122bool closed = false; 123stream .s .internal_close_cb = connect_close_cb ; 124stream .s .internal_data = & closed ; 125stream_may_close (& stream .s ); 126LOOP_PROCESS_EVENTS_UNTIL (& main_loop ,NULL ,-1 ,closed ); 127 128return true; 129} 130 131static void early_server_close_cb (uv_handle_t * handle ) 132{ 133bool * closed = handle -> data ; 134* closed = true; 135} 136 137int socket_watcher_start (SocketWatcher * watcher ,int backlog ,socket_cb cb ) 138FUNC_ATTR_NONNULL_ALL 139{ 140watcher -> cb = cb ; 141int result = UV_EINVAL ; 142 143if (watcher -> stream -> type == UV_TCP ) { 144struct addrinfo * ai = watcher -> uv .tcp .addrinfo ; 145 146for (;ai ;ai = ai -> ai_next ) { 147result = uv_tcp_bind (& watcher -> uv .tcp .handle ,ai -> ai_addr ,0 ); 148if (result != 0 ) { 149continue ; 150 } 151result = uv_listen (watcher -> stream ,backlog ,connection_cb ); 152if (result == 0 ) { 153struct 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. 158uv_tcp_getsockname (& watcher -> uv .tcp .handle , (struct sockaddr * )& sas , 159& (int ){sizeof (sas ) }); 160uint16_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 163size_t len = strlen (watcher -> addr ); 164snprintf (watcher -> addr + len ,sizeof (watcher -> addr )- len ,":%" PRIu16 , 165ntohs (port )); 166break ; 167 } 168 } 169uv_freeaddrinfo (watcher -> uv .tcp .addrinfo ); 170 }else { 171result = uv_pipe_bind2 (& watcher -> uv .pipe .handle ,watcher -> addr ,strlen (watcher -> addr ), 172UV_PIPE_NO_TRUNCATE ); 173 174// If bind failed with EACCES/EADDRINUSE, check if socket is stale 175if (result == UV_EACCES || result == UV_EADDRINUSE ) { 176Loop * loop = watcher -> stream -> loop -> data ; 177 178if (!socket_alive (loop ,watcher -> addr )) { 179// Socket exists but is dead - remove it 180ILOG ("Removing stale socket: %s" ,watcher -> addr ); 181int rm_result = os_remove (watcher -> addr ); 182 183if (rm_result != 0 ) { 184WLOG ("Failed to remove stale socket %s: %s" , 185watcher -> addr ,uv_strerror (rm_result )); 186 }else { 187// Close and reinit the pipe handle before retrying bind 188uv_loop_t * uv_loop = watcher -> uv .pipe .handle .loop ; 189bool closed = false; 190watcher -> uv .pipe .handle .data = & closed ; 191uv_close ((uv_handle_t * )& watcher -> uv .pipe .handle ,early_server_close_cb ); 192LOOP_PROCESS_EVENTS_UNTIL (& main_loop ,NULL ,-1 ,closed ); 193 194uv_pipe_init (uv_loop ,& watcher -> uv .pipe .handle ,0 ); 195watcher -> stream = (uv_stream_t * )(& watcher -> uv .pipe .handle ); 196watcher -> stream -> data = watcher ; 197 198// Retry bind with fresh handle 199result = uv_pipe_bind2 (& watcher -> uv .pipe .handle ,watcher -> addr ,strlen (watcher -> addr ), 200UV_PIPE_NO_TRUNCATE ); 201 } 202 }else { 203// Socket is alive - this is a real error 204ELOG ("Socket already in use by another Nvim instance: %s" ,watcher -> addr ); 205 } 206 } 207 208if (result == 0 ) { 209result = uv_listen (watcher -> stream ,backlog ,connection_cb ); 210 } 211 } 212 213assert (result <=0 );// libuv should return negative error code or zero. 214if (result < 0 ) { 215if (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 ; 219if (!os_path_exists (watcher -> addr )) { 220result = UV_ENOENT ; 221 } 222 } 223return result ; 224 } 225 226return 0 ; 227} 228 229int socket_watcher_accept (SocketWatcher * watcher ,RStream * stream ) 230FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_NONNULL_ARG (2 ) 231{ 232uv_stream_t * client ; 233 234if (watcher -> stream -> type == UV_TCP ) { 235client = (uv_stream_t * )(& stream -> s .uv .tcp ); 236uv_tcp_init (watcher -> uv .tcp .handle .loop , (uv_tcp_t * )client ); 237uv_tcp_nodelay ((uv_tcp_t * )client , true); 238 }else { 239client = (uv_stream_t * )& stream -> s .uv .pipe ; 240uv_pipe_init (watcher -> uv .pipe .handle .loop , (uv_pipe_t * )client ,0 ); 241 } 242 243int result = uv_accept (watcher -> stream ,client ); 244 245if (result ) { 246uv_close ((uv_handle_t * )client ,NULL ); 247return result ; 248 } 249 250stream_init (NULL ,& stream -> s ,-1 ,client ); 251return 0 ; 252} 253 254void socket_watcher_close (SocketWatcher * watcher ,socket_close_cb cb ) 255FUNC_ATTR_NONNULL_ARG (1 ) 256{ 257watcher -> close_cb = cb ; 258uv_close ((uv_handle_t * )watcher -> stream ,close_cb ); 259} 260 261static void connection_event (void ** argv ) 262{ 263SocketWatcher * watcher = argv [0 ]; 264int status = (int )(uintptr_t )(argv [1 ]); 265watcher -> cb (watcher ,status ,watcher -> data ); 266} 267 268static void connection_cb (uv_stream_t * handle ,int status ) 269{ 270SocketWatcher * watcher = handle -> data ; 271CREATE_EVENT (watcher -> events ,connection_event ,watcher , (void * )(uintptr_t )status ); 272} 273 274static void close_cb (uv_handle_t * handle ) 275{ 276SocketWatcher * watcher = handle -> data ; 277if (watcher -> close_cb ) { 278watcher -> close_cb (watcher ,watcher -> data ); 279 } 280} 281 282static void connect_cb (uv_connect_t * req ,int status ) 283{ 284int * ret_status = req -> data ; 285* ret_status = status ; 286uv_handle_t * handle = (uv_handle_t * )req -> handle ; 287if (status != 0 ) { 288stream_may_close (handle -> data ); 289 } 290} 291 292bool socket_connect (Loop * loop ,RStream * stream ,bool is_tcp ,const char * address ,int timeout , 293const char ** error ) 294{ 295bool success = false; 296bool closed ; 297int status ; 298uv_connect_t req ; 299req .data = & status ; 300uv_stream_t * uv_stream ; 301 302uv_tcp_t * tcp = & stream -> s .uv .tcp ; 303uv_getaddrinfo_t addr_req ; 304addr_req .addrinfo = NULL ; 305const struct addrinfo * addrinfo = NULL ; 306char * addr = NULL ; 307if (is_tcp ) { 308addr = xstrdup (address ); 309char * host_end = strrchr (addr ,':' ); 310if (!host_end ) { 311* error = _ ("tcp address must be host:port" ); 312 gotocleanup ; 313 } 314* host_end = NUL ; 315 316const struct addrinfo hints = { .ai_family = AF_UNSPEC , 317 .ai_socktype = SOCK_STREAM , 318 .ai_flags = AI_NUMERICSERV }; 319int retval = uv_getaddrinfo (& loop -> uv ,& addr_req ,NULL , 320addr ,host_end + 1 ,& hints ); 321if (retval != 0 ) { 322* error = _ ("failed to lookup host or port" ); 323 gotocleanup ; 324 } 325addrinfo = addr_req .addrinfo ; 326 327tcp_retry : 328uv_tcp_init (& loop -> uv ,tcp ); 329uv_tcp_nodelay (tcp , true); 330uv_tcp_connect (& req ,tcp ,addrinfo -> ai_addr ,connect_cb ); 331uv_stream = (uv_stream_t * )tcp ; 332 }else { 333uv_pipe_t * pipe = & stream -> s .uv .pipe ; 334uv_pipe_init (& loop -> uv ,pipe ,0 ); 335uv_pipe_connect (& req ,pipe ,address ,connect_cb ); 336uv_stream = (uv_stream_t * )pipe ; 337 } 338stream_init (NULL ,& stream -> s ,-1 ,uv_stream ); 339stream -> s .internal_close_cb = connect_close_cb ; 340stream -> s .internal_data = & closed ; 341closed = false; 342status = 1 ; 343LOOP_PROCESS_EVENTS_UNTIL (& main_loop ,NULL ,timeout ,status != 1 ); 344if (status == 0 ) { 345success = true; 346 }else { 347stream_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. 350LOOP_PROCESS_EVENTS_UNTIL (& main_loop ,NULL ,-1 ,closed ); 351 352if (is_tcp && addrinfo -> ai_next ) { 353addrinfo = addrinfo -> ai_next ; 354 gototcp_retry ; 355 }else { 356* error = _ ("connection refused" ); 357 } 358 } 359 360cleanup : 361stream -> s .internal_close_cb = NULL ; 362stream -> s .internal_data = NULL ; 363xfree (addr ); 364uv_freeaddrinfo (addr_req .addrinfo ); 365return success ; 366}