1 /* Serial interface for raw TCP connections on Un*x like systems.
3 Copyright (C) 1992-2019 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/>. */
25 #include "cli/cli-decode.h"
26 #include "cli/cli-setshow.h"
27 #include "common/filestuff.h"
28 #include "common/netstuff.h"
30 #include <sys/types.h>
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h> /* For FIONBIO. */
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h> /* For FIONBIO. */
39 #include "common/gdb_sys_time.h"
45 #define ETIMEDOUT WSAETIMEDOUT
47 /* Gnulib defines close too, but gnulib's replacement
48 doesn't call closesocket unless we import the
51 #define close(fd) closesocket (fd)
52 #define ioctl ioctlsocket
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
57 #include <sys/socket.h>
58 #include <netinet/tcp.h>
62 #include "gdb_select.h"
65 #ifndef HAVE_SOCKLEN_T
66 typedef int socklen_t;
69 /* For "set tcp" and "show tcp". */
71 static struct cmd_list_element *tcp_set_cmdlist;
72 static struct cmd_list_element *tcp_show_cmdlist;
74 /* Whether to auto-retry refused connections. */
76 static int tcp_auto_retry = 1;
78 /* Timeout period for connections, in seconds. */
80 static unsigned int tcp_retry_limit = 15;
82 /* How many times per second to poll deprecated_ui_loop_hook. */
84 #define POLL_INTERVAL 5
86 /* Helper function to wait a while. If SOCK is not -1, wait on its
87 file descriptor. Otherwise just wait on a timeout, updating
88 *POLLS. Returns -1 on timeout or interrupt, otherwise the value of
92 wait_for_connect (int sock, unsigned int *polls)
97 /* While we wait for the connect to complete,
98 poll the UI so it can update or the user can
100 if (deprecated_ui_loop_hook && deprecated_ui_loop_hook (0))
106 /* Check for timeout. */
107 if (*polls > tcp_retry_limit * POLL_INTERVAL)
113 /* Back off to polling once per second after the first POLL_INTERVAL
115 if (*polls < POLL_INTERVAL)
118 t.tv_usec = 1000000 / POLL_INTERVAL;
128 fd_set rset, wset, eset;
131 FD_SET (sock, &rset);
135 /* POSIX systems return connection success or failure by signalling
136 wset. Windows systems return success in wset and failure in
139 We must call select here, rather than gdb_select, because
140 the serial structure has not yet been initialized - the
141 MinGW select wrapper will not know that this FD refers
143 n = select (sock + 1, &rset, &wset, &eset, &t);
146 /* Use gdb_select here, since we have no file descriptors, and on
147 Windows, plain select doesn't work in that case. */
148 n = gdb_select (0, NULL, NULL, NULL, &t);
150 /* If we didn't time out, only count it as one poll. */
151 if (n > 0 || *polls < POLL_INTERVAL)
154 (*polls) += POLL_INTERVAL;
159 /* Try to connect to the host represented by AINFO. If the connection
160 succeeds, return its socket. Otherwise, return -1 and set ERRNO
161 accordingly. POLLS is used when 'connect' returns EINPROGRESS, and
162 we need to invoke 'wait_for_connect' to obtain the status. */
165 try_connect (const struct addrinfo *ainfo, unsigned int *polls)
167 int sock = gdb_socket_cloexec (ainfo->ai_family, ainfo->ai_socktype,
173 /* Set socket nonblocking. */
180 ioctl (sock, FIONBIO, &ioarg);
182 /* Use Non-blocking connect. connect() will return 0 if connected
184 if (connect (sock, ainfo->ai_addr, ainfo->ai_addrlen) < 0)
187 int err = WSAGetLastError();
192 /* If we've got a "connection refused" error, just return
193 -1. The caller will know what to do. */
196 err == WSAECONNREFUSED
208 /* Any other error (except EINPROGRESS) will be "swallowed"
209 here. We return without specifying a return value, and
210 set errno if the caller wants to inspect what
213 /* Under Windows, calling "connect" with a non-blocking socket
214 results in WSAEWOULDBLOCK, not WSAEINPROGRESS. */
215 err != WSAEWOULDBLOCK
226 /* Looks like we need to wait for the connect. */
230 n = wait_for_connect (sock, polls);
235 int saved_errno = errno;
237 /* A negative value here means that we either timed out or
238 got interrupted by the user. Just return. */
245 /* Got something. Is it an error? */
247 socklen_t len = sizeof (err);
249 /* On Windows, the fourth parameter to getsockopt is a "char *";
250 on UNIX systems it is generally "void *". The cast to "char *"
251 is OK everywhere, since in C++ any data pointer type can be
252 implicitly converted to "void *". */
253 int ret = getsockopt (sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
257 int saved_errno = errno;
263 else if (ret == 0 && err != 0)
270 /* The connection succeeded. Return the socket. */
274 /* Open a tcp socket. */
277 net_open (struct serial *scb, const char *name)
279 struct addrinfo hint;
280 struct addrinfo *ainfo;
282 memset (&hint, 0, sizeof (hint));
283 /* Assume no prefix will be passed, therefore we should use
285 hint.ai_family = AF_UNSPEC;
286 hint.ai_socktype = SOCK_STREAM;
287 hint.ai_protocol = IPPROTO_TCP;
289 parsed_connection_spec parsed = parse_connection_spec (name, &hint);
291 if (parsed.port_str.empty ())
292 error (_("Missing port on hostname '%s'"), name);
294 int r = getaddrinfo (parsed.host_str.c_str (),
295 parsed.port_str.c_str (),
300 fprintf_unfiltered (gdb_stderr, _("%s: cannot resolve name: %s\n"),
301 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 succeeeds, SUCCESS_AINFO will point to the
312 'struct addrinfo' that succeed. */
313 struct addrinfo *success_ainfo = NULL;
314 unsigned int polls = 0;
316 /* Assume the worst. */
321 got_connrefused = false;
323 for (struct addrinfo *iter = ainfo; iter != NULL; iter = iter->ai_next)
325 /* Iterate over the list of possible addresses to connect
326 to. For each, we'll try to connect and see if it
328 int sock = try_connect (iter, &polls);
332 /* We've gotten a successful connection. Save its
333 'struct addrinfo', the socket, and break. */
334 success_ainfo = iter;
340 errno == WSAECONNREFUSED
342 errno == ECONNREFUSED
345 got_connrefused = true;
350 - tcp_auto_retry is true, and
351 - We haven't gotten a connection yet, and
352 - Any of our connection attempts returned with ECONNREFUSED, and
353 - wait_for_connect signals that we can keep going. */
354 while (tcp_auto_retry
355 && success_ainfo == NULL
357 && wait_for_connect (-1, &polls) >= 0);
359 if (success_ainfo == NULL)
365 /* Turn off nonblocking. */
372 ioctl (scb->fd, FIONBIO, &ioarg);
374 if (success_ainfo->ai_protocol == IPPROTO_TCP)
376 /* Disable Nagle algorithm. Needed in some cases. */
379 setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
380 (char *) &tmp, sizeof (tmp));
384 /* If we don't do this, then GDB simply exits
385 when the remote side dies. */
386 signal (SIGPIPE, SIG_IGN);
393 net_close (struct serial *scb)
403 net_read_prim (struct serial *scb, size_t count)
405 /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
406 'recv' takes 'char *' as second argument, while 'scb->buf' is
407 'unsigned char *'. */
408 return recv (scb->fd, (char *) scb->buf, count, 0);
412 net_write_prim (struct serial *scb, const void *buf, size_t count)
414 /* On Windows, the second parameter to send is a "const char *"; on
415 UNIX systems it is generally "const void *". The cast to "const
416 char *" is OK everywhere, since in C++ any data pointer type can
417 be implicitly converted to "const void *". */
418 return send (scb->fd, (const char *) buf, count, 0);
422 ser_tcp_send_break (struct serial *scb)
424 /* Send telnet IAC and BREAK characters. */
425 return (serial_write (scb, "\377\363", 2));
428 /* Support for "set tcp" and "show tcp" commands. */
431 set_tcp_cmd (const char *args, int from_tty)
433 help_list (tcp_set_cmdlist, "set tcp ", all_commands, gdb_stdout);
437 show_tcp_cmd (const char *args, int from_tty)
439 help_list (tcp_show_cmdlist, "show tcp ", all_commands, gdb_stdout);
446 static const struct serial_ops tcp_ops =
454 ser_base_flush_output,
455 ser_base_flush_input,
458 ser_base_get_tty_state,
459 ser_base_copy_tty_state,
460 ser_base_set_tty_state,
461 ser_base_print_tty_state,
462 ser_base_setbaudrate,
463 ser_base_setstopbits,
465 ser_base_drain_output,
471 #endif /* USE_WIN32API */
474 _initialize_ser_tcp (void)
477 /* Do nothing; the TCP serial operations will be initialized in
480 serial_add_interface (&tcp_ops);
481 #endif /* USE_WIN32API */
483 add_prefix_cmd ("tcp", class_maintenance, set_tcp_cmd, _("\
484 TCP protocol specific variables\n\
485 Configure variables specific to remote TCP connections"),
486 &tcp_set_cmdlist, "set tcp ",
487 0 /* allow-unknown */, &setlist);
488 add_prefix_cmd ("tcp", class_maintenance, show_tcp_cmd, _("\
489 TCP protocol specific variables\n\
490 Configure variables specific to remote TCP connections"),
491 &tcp_show_cmdlist, "show tcp ",
492 0 /* allow-unknown */, &showlist);
494 add_setshow_boolean_cmd ("auto-retry", class_obscure,
495 &tcp_auto_retry, _("\
496 Set auto-retry on socket connect"), _("\
497 Show auto-retry on socket connect"),
499 &tcp_set_cmdlist, &tcp_show_cmdlist);
501 add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
502 &tcp_retry_limit, _("\
503 Set timeout limit in seconds for socket connection"), _("\
504 Show timeout limit in seconds for socket connection"), _("\
505 If set to \"unlimited\", GDB will keep attempting to establish a\n\
506 connection forever, unless interrupted with Ctrl-c.\n\
507 The default is 15 seconds."),
509 &tcp_set_cmdlist, &tcp_show_cmdlist);