1 /* Serial interface for raw TCP connections on Un*x like systems.
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
24 #include "cli/cli-decode.h"
25 #include "cli/cli-setshow.h"
26 #include "gdbsupport/filestuff.h"
27 #include "gdbsupport/netstuff.h"
29 #include <sys/types.h>
31 #ifdef HAVE_SYS_FILIO_H
32 #include <sys/filio.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
38 #include "gdbsupport/gdb_sys_time.h"
43 #define ETIMEDOUT WSAETIMEDOUT
45 /* Gnulib defines close too, but gnulib's replacement
46 doesn't call closesocket unless we import the
49 #define close(fd) closesocket (fd)
50 #define ioctl ioctlsocket
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
55 #include <sys/socket.h>
56 #include <netinet/tcp.h>
60 #include "gdbsupport/gdb_select.h"
63 #ifndef HAVE_SOCKLEN_T
64 typedef int socklen_t
;
67 /* For "set tcp" and "show tcp". */
69 static struct cmd_list_element
*tcp_set_cmdlist
;
70 static struct cmd_list_element
*tcp_show_cmdlist
;
72 /* Whether to auto-retry refused connections. */
74 static bool tcp_auto_retry
= true;
76 /* Timeout period for connections, in seconds. */
78 static unsigned int tcp_retry_limit
= 15;
80 /* How many times per second to poll deprecated_ui_loop_hook. */
82 #define POLL_INTERVAL 5
84 /* Helper function to wait a while. If SOCK is not -1, wait on its
85 file descriptor. Otherwise just wait on a timeout, updating
86 *POLLS. Returns -1 on timeout or interrupt and set OUT_ERROR,
87 otherwise the value of select. */
90 wait_for_connect (int sock
, unsigned int *polls
, ULONGEST
*out_error
)
95 /* While we wait for the connect to complete,
96 poll the UI so it can update or the user can
98 if (deprecated_ui_loop_hook
&& deprecated_ui_loop_hook (0))
104 /* Check for timeout. */
105 if (*polls
> tcp_retry_limit
* POLL_INTERVAL
)
107 *out_error
= ETIMEDOUT
;
111 /* Back off to polling once per second after the first POLL_INTERVAL
113 if (*polls
< POLL_INTERVAL
)
116 t
.tv_usec
= 1000000 / POLL_INTERVAL
;
126 fd_set rset
, wset
, eset
;
129 FD_SET (sock
, &rset
);
133 /* POSIX systems return connection success or failure by signalling
134 wset. Windows systems return success in wset and failure in
137 We must call select here, rather than gdb_select, because
138 the serial structure has not yet been initialized - the
139 MinGW select wrapper will not know that this FD refers
141 n
= select (sock
+ 1, &rset
, &wset
, &eset
, &t
);
144 /* Use gdb_select here, since we have no file descriptors, and on
145 Windows, plain select doesn't work in that case. */
146 n
= interruptible_select (0, NULL
, NULL
, NULL
, &t
);
148 /* If we didn't time out, only count it as one poll. */
149 if (n
> 0 || *polls
< POLL_INTERVAL
)
152 (*polls
) += POLL_INTERVAL
;
157 /* A helper to get the error number for either Windows or POSIX. */
162 return WSAGetLastError ();
168 /* Try to connect to the host represented by AINFO. If the connection
169 succeeds, return its socket. Otherwise, return -1 and set OUT_ERROR
170 accordingly. POLLS is used when 'connect' returns EINPROGRESS, and
171 we need to invoke 'wait_for_connect' to obtain the status. */
174 try_connect (const struct addrinfo
*ainfo
, unsigned int *polls
,
177 int sock
= gdb_socket_cloexec (ainfo
->ai_family
, ainfo
->ai_socktype
,
182 *out_error
= get_error ();
186 /* Set socket nonblocking. */
193 ioctl (sock
, FIONBIO
, &ioarg
);
195 /* Use Non-blocking connect. connect() will return 0 if connected
197 if (connect (sock
, ainfo
->ai_addr
, ainfo
->ai_addrlen
) < 0)
199 ULONGEST err
= get_error ();
201 /* If we've got a "connection refused" error, just return
202 -1. The caller will know what to do. */
205 err
== WSAECONNREFUSED
217 /* Any other error (except EINPROGRESS) will be "swallowed"
218 here. We return without specifying a return value, and
219 set errno if the caller wants to inspect what
222 /* Under Windows, calling "connect" with a non-blocking socket
223 results in WSAEWOULDBLOCK, not WSAEINPROGRESS. */
224 err
!= WSAEWOULDBLOCK
235 /* Looks like we need to wait for the connect. */
239 n
= wait_for_connect (sock
, polls
, out_error
);
244 /* A negative value here means that we either timed out or
245 got interrupted by the user. Just return. */
247 /* OUT_ERROR was set by wait_for_connect, above. */
252 /* Got something. Is it an error? */
254 socklen_t len
= sizeof (err
);
256 /* On Windows, the fourth parameter to getsockopt is a "char *";
257 on UNIX systems it is generally "void *". The cast to "char *"
258 is OK everywhere, since in C++ any data pointer type can be
259 implicitly converted to "void *". */
260 int ret
= getsockopt (sock
, SOL_SOCKET
, SO_ERROR
, (char *) &err
, &len
);
264 *out_error
= get_error ();
268 else if (ret
== 0 && err
!= 0)
275 /* The connection succeeded. Return the socket. */
279 /* Open a tcp socket. */
282 net_open (struct serial
*scb
, const char *name
)
284 struct addrinfo hint
;
285 struct addrinfo
*ainfo
;
287 memset (&hint
, 0, sizeof (hint
));
288 /* Assume no prefix will be passed, therefore we should use
290 hint
.ai_family
= AF_UNSPEC
;
291 hint
.ai_socktype
= SOCK_STREAM
;
292 hint
.ai_protocol
= IPPROTO_TCP
;
294 parsed_connection_spec parsed
= parse_connection_spec (name
, &hint
);
296 if (parsed
.port_str
.empty ())
297 error (_("Missing port on hostname '%s'"), name
);
299 int r
= getaddrinfo (parsed
.host_str
.c_str (),
300 parsed
.port_str
.c_str (),
304 error (_("%s: cannot resolve name: %s\n"), name
, gai_strerror (r
));
306 scoped_free_addrinfo
free_ainfo (ainfo
);
308 /* Flag to indicate whether we've got a connection refused. It will
309 be true if any of the connections tried was refused. */
310 bool got_connrefused
;
311 /* If a connection succeeds, SUCCESS_AINFO will point to the
312 'struct addrinfo' that succeed. */
313 struct addrinfo
*success_ainfo
= NULL
;
314 unsigned int polls
= 0;
315 ULONGEST last_error
= 0;
317 /* Assume the worst. */
322 got_connrefused
= false;
324 for (addrinfo
*iter
= ainfo
; iter
!= NULL
; iter
= iter
->ai_next
)
326 /* Iterate over the list of possible addresses to connect
327 to. For each, we'll try to connect and see if it
329 int sock
= try_connect (iter
, &polls
, &last_error
);
333 /* We've gotten a successful connection. Save its
334 'struct addrinfo', the socket, and break. */
335 success_ainfo
= iter
;
341 last_error
== WSAECONNREFUSED
343 last_error
== ECONNREFUSED
346 got_connrefused
= true;
351 - tcp_auto_retry is true, and
352 - We haven't gotten a connection yet, and
353 - Any of our connection attempts returned with ECONNREFUSED, and
354 - wait_for_connect signals that we can keep going. */
355 while (tcp_auto_retry
356 && success_ainfo
== NULL
358 && wait_for_connect (-1, &polls
, &last_error
) >= 0);
360 if (success_ainfo
== NULL
)
364 throw_winerror_with_name (_("could not connect"), last_error
);
366 perror_with_name (_("could not connect"), last_error
);
370 /* Turn off nonblocking. */
377 ioctl (scb
->fd
, FIONBIO
, &ioarg
);
379 if (success_ainfo
->ai_protocol
== IPPROTO_TCP
)
381 /* Disable Nagle algorithm. Needed in some cases. */
384 setsockopt (scb
->fd
, IPPROTO_TCP
, TCP_NODELAY
,
385 (char *) &tmp
, sizeof (tmp
));
389 /* If we don't do this, then GDB simply exits
390 when the remote side dies. */
391 signal (SIGPIPE
, SIG_IGN
);
396 net_close (struct serial
*scb
)
406 net_read_prim (struct serial
*scb
, size_t count
)
408 /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
409 'recv' takes 'char *' as second argument, while 'scb->buf' is
410 'unsigned char *'. */
411 int result
= recv (scb
->fd
, (char *) scb
->buf
, count
, 0);
412 if (result
== -1 && errno
!= EINTR
)
413 perror_with_name ("error while reading");
418 net_write_prim (struct serial
*scb
, const void *buf
, size_t count
)
420 /* On Windows, the second parameter to send is a "const char *"; on
421 UNIX systems it is generally "const void *". The cast to "const
422 char *" is OK everywhere, since in C++ any data pointer type can
423 be implicitly converted to "const void *". */
424 int result
= send (scb
->fd
, (const char *) buf
, count
, 0);
425 if (result
== -1 && errno
!= EINTR
)
426 perror_with_name ("error while writing");
431 ser_tcp_send_break (struct serial
*scb
)
433 /* Send telnet IAC and BREAK characters. */
434 serial_write (scb
, "\377\363", 2);
441 static const struct serial_ops tcp_ops
=
449 ser_base_flush_output
,
450 ser_base_flush_input
,
453 ser_base_get_tty_state
,
454 ser_base_copy_tty_state
,
455 ser_base_set_tty_state
,
456 ser_base_print_tty_state
,
457 ser_base_setbaudrate
,
458 ser_base_setstopbits
,
460 ser_base_drain_output
,
466 #endif /* USE_WIN32API */
468 void _initialize_ser_tcp ();
470 _initialize_ser_tcp ()
473 /* Do nothing; the TCP serial operations will be initialized in
476 serial_add_interface (&tcp_ops
);
477 #endif /* USE_WIN32API */
479 add_setshow_prefix_cmd ("tcp", class_maintenance
,
481 TCP protocol specific variables.\n\
482 Configure variables specific to remote TCP connections."),
484 TCP protocol specific variables.\n\
485 Configure variables specific to remote TCP connections."),
486 &tcp_set_cmdlist
, &tcp_show_cmdlist
,
487 &setlist
, &showlist
);
489 add_setshow_boolean_cmd ("auto-retry", class_obscure
,
490 &tcp_auto_retry
, _("\
491 Set auto-retry on socket connect."), _("\
492 Show auto-retry on socket connect."),
494 &tcp_set_cmdlist
, &tcp_show_cmdlist
);
496 add_setshow_uinteger_cmd ("connect-timeout", class_obscure
,
497 &tcp_retry_limit
, _("\
498 Set timeout limit in seconds for socket connection."), _("\
499 Show timeout limit in seconds for socket connection."), _("\
500 If set to \"unlimited\", GDB will keep attempting to establish a\n\
501 connection forever, unless interrupted with Ctrl-c.\n\
502 The default is 15 seconds."),
504 &tcp_set_cmdlist
, &tcp_show_cmdlist
);