]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/ser-tcp.c
Add a testcase for PR binutils/23460
[thirdparty/binutils-gdb.git] / gdb / ser-tcp.c
CommitLineData
f9f87d2c
MK
1/* Serial interface for raw TCP connections on Un*x like systems.
2
e2882c85 3 Copyright (C) 1992-2018 Free Software Foundation, Inc.
c906108c 4
c5aa993b 5 This file is part of GDB.
c906108c 6
c5aa993b
JM
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
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b 10 (at your option) any later version.
c906108c 11
c5aa993b
JM
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.
c906108c 16
c5aa993b 17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c906108c
SS
19
20#include "defs.h"
21#include "serial.h"
3eb25fda 22#include "ser-base.h"
0ea3f30e 23#include "ser-tcp.h"
84603566
SL
24#include "gdbcmd.h"
25#include "cli/cli-decode.h"
26#include "cli/cli-setshow.h"
614c279d 27#include "filestuff.h"
c7ab0aef 28#include "netstuff.h"
c2c6d25f 29
c906108c 30#include <sys/types.h>
0cf3e697
MH
31
32#ifdef HAVE_SYS_FILIO_H
c378eb4e 33#include <sys/filio.h> /* For FIONBIO. */
0cf3e697
MH
34#endif
35#ifdef HAVE_SYS_IOCTL_H
c378eb4e 36#include <sys/ioctl.h> /* For FIONBIO. */
0cf3e697
MH
37#endif
38
438e1e42 39#include "gdb_sys_time.h"
b4505029
MM
40
41#ifdef USE_WIN32API
42#include <winsock2.h>
c7ab0aef 43#include <wspiapi.h>
8e7ebaf5 44#ifndef ETIMEDOUT
b4505029 45#define ETIMEDOUT WSAETIMEDOUT
8e7ebaf5 46#endif
6ec2e0f5
SDJ
47/* Gnulib defines close too, but gnulib's replacement
48 doesn't call closesocket unless we import the
49 socketlib module. */
50#undef close
056d7646 51#define close(fd) closesocket (fd)
b4505029
MM
52#define ioctl ioctlsocket
53#else
9eb1356e 54#include <netinet/in.h>
c906108c
SS
55#include <arpa/inet.h>
56#include <netdb.h>
9eb1356e 57#include <sys/socket.h>
c906108c 58#include <netinet/tcp.h>
b4505029 59#endif
c906108c 60
042be3a9 61#include <signal.h>
84603566 62#include "gdb_select.h"
325fac50 63#include <algorithm>
c906108c 64
f9f87d2c
MK
65#ifndef HAVE_SOCKLEN_T
66typedef int socklen_t;
67#endif
68
84603566
SL
69/* For "set tcp" and "show tcp". */
70
71static struct cmd_list_element *tcp_set_cmdlist;
72static struct cmd_list_element *tcp_show_cmdlist;
73
74/* Whether to auto-retry refused connections. */
75
76static int tcp_auto_retry = 1;
77
78/* Timeout period for connections, in seconds. */
79
964b8317 80static unsigned int tcp_retry_limit = 15;
84603566 81
c378eb4e 82/* How many times per second to poll deprecated_ui_loop_hook. */
84603566
SL
83
84#define POLL_INTERVAL 5
85
c7ab0aef
SDJ
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
89 select. */
84603566
SL
90
91static int
c7ab0aef 92wait_for_connect (int sock, unsigned int *polls)
84603566
SL
93{
94 struct timeval t;
95 int n;
96
97 /* While we wait for the connect to complete,
98 poll the UI so it can update or the user can
99 interrupt. */
100 if (deprecated_ui_loop_hook && deprecated_ui_loop_hook (0))
101 {
102 errno = EINTR;
103 return -1;
104 }
105
106 /* Check for timeout. */
107 if (*polls > tcp_retry_limit * POLL_INTERVAL)
108 {
109 errno = ETIMEDOUT;
110 return -1;
111 }
112
113 /* Back off to polling once per second after the first POLL_INTERVAL
114 polls. */
115 if (*polls < POLL_INTERVAL)
116 {
117 t.tv_sec = 0;
118 t.tv_usec = 1000000 / POLL_INTERVAL;
119 }
120 else
121 {
122 t.tv_sec = 1;
123 t.tv_usec = 0;
124 }
125
c7ab0aef 126 if (sock >= 0)
84603566
SL
127 {
128 fd_set rset, wset, eset;
433759f7 129
84603566 130 FD_ZERO (&rset);
c7ab0aef 131 FD_SET (sock, &rset);
84603566
SL
132 wset = rset;
133 eset = rset;
c7ab0aef 134
84603566
SL
135 /* POSIX systems return connection success or failure by signalling
136 wset. Windows systems return success in wset and failure in
137 eset.
c7ab0aef 138
84603566
SL
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
142 to a socket. */
c7ab0aef 143 n = select (sock + 1, &rset, &wset, &eset, &t);
84603566
SL
144 }
145 else
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);
149
150 /* If we didn't time out, only count it as one poll. */
151 if (n > 0 || *polls < POLL_INTERVAL)
152 (*polls)++;
153 else
154 (*polls) += POLL_INTERVAL;
155
156 return n;
157}
7c7a201a 158
c7ab0aef
SDJ
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. */
c906108c 163
c7ab0aef
SDJ
164static int
165try_connect (const struct addrinfo *ainfo, unsigned int *polls)
c906108c 166{
c7ab0aef
SDJ
167 int sock = gdb_socket_cloexec (ainfo->ai_family, ainfo->ai_socktype,
168 ainfo->ai_protocol);
84603566 169
c7ab0aef 170 if (sock < 0)
7c7a201a 171 return -1;
c7ab0aef 172
c378eb4e 173 /* Set socket nonblocking. */
64b58472
SDJ
174#ifdef USE_WIN32API
175 u_long ioarg = 1;
176#else
c7ab0aef 177 int ioarg = 1;
64b58472 178#endif
c7ab0aef
SDJ
179
180 ioctl (sock, FIONBIO, &ioarg);
c906108c 181
3e43a32a 182 /* Use Non-blocking connect. connect() will return 0 if connected
c378eb4e 183 already. */
c7ab0aef 184 if (connect (sock, ainfo->ai_addr, ainfo->ai_addrlen) < 0)
84603566 185 {
b4505029 186#ifdef USE_WIN32API
84603566 187 int err = WSAGetLastError();
b4505029 188#else
84603566 189 int err = errno;
b4505029 190#endif
84603566 191
c7ab0aef
SDJ
192 /* If we've got a "connection refused" error, just return
193 -1. The caller will know what to do. */
194 if (
b4505029 195#ifdef USE_WIN32API
c7ab0aef 196 err == WSAECONNREFUSED
84603566 197#else
c7ab0aef 198 err == ECONNREFUSED
b4505029 199#endif
c7ab0aef 200 )
84603566 201 {
c7ab0aef
SDJ
202 close (sock);
203 errno = err;
204 return -1;
84603566 205 }
c906108c 206
84603566 207 if (
c7ab0aef
SDJ
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
211 happened. */
84603566
SL
212#ifdef USE_WIN32API
213 /* Under Windows, calling "connect" with a non-blocking socket
214 results in WSAEWOULDBLOCK, not WSAEINPROGRESS. */
215 err != WSAEWOULDBLOCK
216#else
217 err != EINPROGRESS
218#endif
219 )
220 {
c7ab0aef 221 close (sock);
84603566 222 errno = err;
84603566
SL
223 return -1;
224 }
7c7a201a 225
c378eb4e 226 /* Looks like we need to wait for the connect. */
c7ab0aef
SDJ
227 int n;
228
229 do
230 n = wait_for_connect (sock, polls);
84603566 231 while (n == 0);
c7ab0aef 232
84603566 233 if (n < 0)
7c7a201a 234 {
c7ab0aef
SDJ
235 int saved_errno = errno;
236
237 /* A negative value here means that we either timed out or
238 got interrupted by the user. Just return. */
239 close (sock);
240 errno = saved_errno;
7c7a201a
MH
241 return -1;
242 }
243 }
c906108c 244
c378eb4e 245 /* Got something. Is it an error? */
c7ab0aef
SDJ
246 int err;
247 socklen_t len = sizeof (err);
248
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);
254
255 if (ret < 0)
256 {
257 int saved_errno = errno;
258
259 close (sock);
260 errno = saved_errno;
261 return -1;
262 }
263 else if (ret == 0 && err != 0)
264 {
265 close (sock);
266 errno = err;
267 return -1;
268 }
269
270 /* The connection succeeded. Return the socket. */
271 return sock;
272}
273
274/* Open a tcp socket. */
275
276int
277net_open (struct serial *scb, const char *name)
278{
279 struct addrinfo hint;
280 struct addrinfo *ainfo;
281
282 memset (&hint, 0, sizeof (hint));
283 /* Assume no prefix will be passed, therefore we should use
284 AF_UNSPEC. */
285 hint.ai_family = AF_UNSPEC;
286 hint.ai_socktype = SOCK_STREAM;
287 hint.ai_protocol = IPPROTO_TCP;
288
289 parsed_connection_spec parsed = parse_connection_spec (name, &hint);
290
291 if (parsed.port_str.empty ())
292 error (_("Missing port on hostname '%s'"), name);
293
294 int r = getaddrinfo (parsed.host_str.c_str (),
295 parsed.port_str.c_str (),
296 &hint, &ainfo);
297
298 if (r != 0)
299 {
300 fprintf_unfiltered (gdb_stderr, _("%s: cannot resolve name: %s\n"),
301 name, gai_strerror (r));
302 errno = ENOENT;
303 return -1;
304 }
305
306 scoped_free_addrinfo free_ainfo (ainfo);
307
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;
315
316 /* Assume the worst. */
317 scb->fd = -1;
318
319 do
320 {
321 got_connrefused = false;
322
323 for (struct addrinfo *iter = ainfo; iter != NULL; iter = iter->ai_next)
324 {
325 /* Iterate over the list of possible addresses to connect
326 to. For each, we'll try to connect and see if it
327 succeeds. */
328 int sock = try_connect (iter, &polls);
329
330 if (sock >= 0)
331 {
332 /* We've gotten a successful connection. Save its
333 'struct addrinfo', the socket, and break. */
334 success_ainfo = iter;
335 scb->fd = sock;
336 break;
337 }
338 else if (
84603566 339#ifdef USE_WIN32API
c7ab0aef 340 errno == WSAECONNREFUSED
84603566 341#else
c7ab0aef 342 errno == ECONNREFUSED
84603566 343#endif
c7ab0aef
SDJ
344 )
345 got_connrefused = true;
346 }
347 }
348 /* Just retry if:
349
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
356 && got_connrefused
357 && wait_for_connect (-1, &polls) >= 0);
358
359 if (success_ainfo == NULL)
360 {
361 net_close (scb);
362 return -1;
363 }
9db8d71f 364
c378eb4e 365 /* Turn off nonblocking. */
c7ab0aef
SDJ
366#ifdef USE_WIN32API
367 u_long ioarg = 0;
368#else
369 int ioarg = 0;
370#endif
371
b4505029 372 ioctl (scb->fd, FIONBIO, &ioarg);
7c7a201a 373
c7ab0aef 374 if (success_ainfo->ai_socktype == IPPROTO_TCP)
9db8d71f 375 {
c378eb4e 376 /* Disable Nagle algorithm. Needed in some cases. */
c7ab0aef
SDJ
377 int tmp = 1;
378
9db8d71f 379 setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
c7ab0aef 380 (char *) &tmp, sizeof (tmp));
9db8d71f
DJ
381 }
382
6d318c73 383#ifdef SIGPIPE
7c7a201a
MH
384 /* If we don't do this, then GDB simply exits
385 when the remote side dies. */
386 signal (SIGPIPE, SIG_IGN);
6d318c73 387#endif
c906108c
SS
388
389 return 0;
390}
391
0ea3f30e 392void
9db8d71f 393net_close (struct serial *scb)
c906108c 394{
363a6e9f 395 if (scb->fd == -1)
c906108c
SS
396 return;
397
c5aa993b 398 close (scb->fd);
c906108c
SS
399 scb->fd = -1;
400}
401
0ea3f30e 402int
b4505029
MM
403net_read_prim (struct serial *scb, size_t count)
404{
c49e7f76
PA
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 *'. */
69e976f8 408 return recv (scb->fd, (char *) scb->buf, count, 0);
b4505029
MM
409}
410
0ea3f30e 411int
b4505029
MM
412net_write_prim (struct serial *scb, const void *buf, size_t count)
413{
69e976f8
PA
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);
b4505029
MM
419}
420
8775bb90
MS
421int
422ser_tcp_send_break (struct serial *scb)
423{
c378eb4e 424 /* Send telnet IAC and BREAK characters. */
8775bb90
MS
425 return (serial_write (scb, "\377\363", 2));
426}
427
84603566
SL
428/* Support for "set tcp" and "show tcp" commands. */
429
430static void
981a3fb3 431set_tcp_cmd (const char *args, int from_tty)
84603566 432{
635c7e8a 433 help_list (tcp_set_cmdlist, "set tcp ", all_commands, gdb_stdout);
84603566
SL
434}
435
436static void
981a3fb3 437show_tcp_cmd (const char *args, int from_tty)
84603566 438{
635c7e8a 439 help_list (tcp_show_cmdlist, "show tcp ", all_commands, gdb_stdout);
84603566
SL
440}
441
12e8c7d7
TT
442#ifndef USE_WIN32API
443
444/* The TCP ops. */
445
446static const struct serial_ops tcp_ops =
447{
448 "tcp",
449 net_open,
450 net_close,
451 NULL,
452 ser_base_readchar,
453 ser_base_write,
454 ser_base_flush_output,
455 ser_base_flush_input,
456 ser_tcp_send_break,
457 ser_base_raw,
458 ser_base_get_tty_state,
459 ser_base_copy_tty_state,
460 ser_base_set_tty_state,
461 ser_base_print_tty_state,
12e8c7d7
TT
462 ser_base_setbaudrate,
463 ser_base_setstopbits,
236af5e3 464 ser_base_setparity,
12e8c7d7
TT
465 ser_base_drain_output,
466 ser_base_async,
467 net_read_prim,
468 net_write_prim
469};
470
471#endif /* USE_WIN32API */
84603566 472
c906108c 473void
c2c6d25f 474_initialize_ser_tcp (void)
c906108c 475{
b4505029 476#ifdef USE_WIN32API
0ea3f30e
DJ
477 /* Do nothing; the TCP serial operations will be initialized in
478 ser-mingw.c. */
0ea3f30e 479#else
12e8c7d7 480 serial_add_interface (&tcp_ops);
0ea3f30e 481#endif /* USE_WIN32API */
84603566
SL
482
483 add_prefix_cmd ("tcp", class_maintenance, set_tcp_cmd, _("\
484TCP protocol specific variables\n\
485Configure 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, _("\
489TCP protocol specific variables\n\
490Configure variables specific to remote TCP connections"),
491 &tcp_show_cmdlist, "show tcp ",
492 0 /* allow-unknown */, &showlist);
493
494 add_setshow_boolean_cmd ("auto-retry", class_obscure,
495 &tcp_auto_retry, _("\
496Set auto-retry on socket connect"), _("\
497Show auto-retry on socket connect"),
498 NULL, NULL, NULL,
499 &tcp_set_cmdlist, &tcp_show_cmdlist);
500
501 add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
502 &tcp_retry_limit, _("\
f81d1120
PA
503Set timeout limit in seconds for socket connection"), _("\
504Show timeout limit in seconds for socket connection"), _("\
505If set to \"unlimited\", GDB will keep attempting to establish a\n\
506connection forever, unless interrupted with Ctrl-c.\n\
507The default is 15 seconds."),
508 NULL, NULL,
509 &tcp_set_cmdlist, &tcp_show_cmdlist);
c906108c 510}