Implement IPv6 support for GDB/gdbserver
[external/binutils.git] / gdb / ser-tcp.c
1 /* Serial interface for raw TCP connections on Un*x like systems.
2
3    Copyright (C) 1992-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
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.
11
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.
16
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/>.  */
19
20 #include "defs.h"
21 #include "serial.h"
22 #include "ser-base.h"
23 #include "ser-tcp.h"
24 #include "gdbcmd.h"
25 #include "cli/cli-decode.h"
26 #include "cli/cli-setshow.h"
27 #include "filestuff.h"
28 #include "netstuff.h"
29
30 #include <sys/types.h>
31
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h>  /* For FIONBIO.  */
34 #endif
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>  /* For FIONBIO.  */
37 #endif
38
39 #include "gdb_sys_time.h"
40
41 #ifdef USE_WIN32API
42 #include <winsock2.h>
43 #include <wspiapi.h>
44 #ifndef ETIMEDOUT
45 #define ETIMEDOUT WSAETIMEDOUT
46 #endif
47 /* Gnulib defines close too, but gnulib's replacement
48    doesn't call closesocket unless we import the
49    socketlib module.  */
50 #undef close
51 #define close(fd) closesocket (fd)
52 #define ioctl ioctlsocket
53 #else
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/socket.h>
58 #include <netinet/tcp.h>
59 #endif
60
61 #include <signal.h>
62 #include "gdb_select.h"
63 #include <algorithm>
64
65 #ifndef HAVE_SOCKLEN_T
66 typedef int socklen_t;
67 #endif
68
69 /* For "set tcp" and "show tcp".  */
70
71 static struct cmd_list_element *tcp_set_cmdlist;
72 static struct cmd_list_element *tcp_show_cmdlist;
73
74 /* Whether to auto-retry refused connections.  */
75
76 static int tcp_auto_retry = 1;
77
78 /* Timeout period for connections, in seconds.  */
79
80 static unsigned int tcp_retry_limit = 15;
81
82 /* How many times per second to poll deprecated_ui_loop_hook.  */
83
84 #define POLL_INTERVAL 5
85
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.  */
90
91 static int
92 wait_for_connect (int sock, unsigned int *polls)
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
126   if (sock >= 0)
127     {
128       fd_set rset, wset, eset;
129
130       FD_ZERO (&rset);
131       FD_SET (sock, &rset);
132       wset = rset;
133       eset = rset;
134
135       /* POSIX systems return connection success or failure by signalling
136          wset.  Windows systems return success in wset and failure in
137          eset.
138
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.  */
143       n = select (sock + 1, &rset, &wset, &eset, &t);
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 }
158
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.  */
163
164 static int
165 try_connect (const struct addrinfo *ainfo, unsigned int *polls)
166 {
167   int sock = gdb_socket_cloexec (ainfo->ai_family, ainfo->ai_socktype,
168                                  ainfo->ai_protocol);
169
170   if (sock < 0)
171     return -1;
172
173   /* Set socket nonblocking.  */
174   int ioarg = 1;
175
176   ioctl (sock, FIONBIO, &ioarg);
177
178   /* Use Non-blocking connect.  connect() will return 0 if connected
179      already.  */
180   if (connect (sock, ainfo->ai_addr, ainfo->ai_addrlen) < 0)
181     {
182 #ifdef USE_WIN32API
183       int err = WSAGetLastError();
184 #else
185       int err = errno;
186 #endif
187
188       /* If we've got a "connection refused" error, just return
189          -1.  The caller will know what to do.  */
190       if (
191 #ifdef USE_WIN32API
192           err == WSAECONNREFUSED
193 #else
194           err == ECONNREFUSED
195 #endif
196           )
197         {
198           close (sock);
199           errno = err;
200           return -1;
201         }
202
203       if (
204           /* Any other error (except EINPROGRESS) will be "swallowed"
205              here.  We return without specifying a return value, and
206              set errno if the caller wants to inspect what
207              happened.  */
208 #ifdef USE_WIN32API
209           /* Under Windows, calling "connect" with a non-blocking socket
210              results in WSAEWOULDBLOCK, not WSAEINPROGRESS.  */
211           err != WSAEWOULDBLOCK
212 #else
213           err != EINPROGRESS
214 #endif
215           )
216         {
217           close (sock);
218           errno = err;
219           return -1;
220         }
221
222       /* Looks like we need to wait for the connect.  */
223       int n;
224
225       do
226         n = wait_for_connect (sock, polls);
227       while (n == 0);
228
229       if (n < 0)
230         {
231           int saved_errno = errno;
232
233           /* A negative value here means that we either timed out or
234              got interrupted by the user.  Just return.  */
235           close (sock);
236           errno = saved_errno;
237           return -1;
238         }
239     }
240
241   /* Got something.  Is it an error?  */
242   int err;
243   socklen_t len = sizeof (err);
244
245   /* On Windows, the fourth parameter to getsockopt is a "char *";
246      on UNIX systems it is generally "void *".  The cast to "char *"
247      is OK everywhere, since in C++ any data pointer type can be
248      implicitly converted to "void *".  */
249   int ret = getsockopt (sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
250
251   if (ret < 0)
252     {
253       int saved_errno = errno;
254
255       close (sock);
256       errno = saved_errno;
257       return -1;
258     }
259   else if (ret == 0 && err != 0)
260     {
261       close (sock);
262       errno = err;
263       return -1;
264     }
265
266   /* The connection succeeded.  Return the socket.  */
267   return sock;
268 }
269
270 /* Open a tcp socket.  */
271
272 int
273 net_open (struct serial *scb, const char *name)
274 {
275   struct addrinfo hint;
276   struct addrinfo *ainfo;
277
278   memset (&hint, 0, sizeof (hint));
279   /* Assume no prefix will be passed, therefore we should use
280      AF_UNSPEC.  */
281   hint.ai_family = AF_UNSPEC;
282   hint.ai_socktype = SOCK_STREAM;
283   hint.ai_protocol = IPPROTO_TCP;
284
285   parsed_connection_spec parsed = parse_connection_spec (name, &hint);
286
287   if (parsed.port_str.empty ())
288     error (_("Missing port on hostname '%s'"), name);
289
290   int r = getaddrinfo (parsed.host_str.c_str (),
291                        parsed.port_str.c_str (),
292                        &hint, &ainfo);
293
294   if (r != 0)
295     {
296       fprintf_unfiltered (gdb_stderr, _("%s: cannot resolve name: %s\n"),
297                           name, gai_strerror (r));
298       errno = ENOENT;
299       return -1;
300     }
301
302   scoped_free_addrinfo free_ainfo (ainfo);
303
304   /* Flag to indicate whether we've got a connection refused.  It will
305      be true if any of the connections tried was refused.  */
306   bool got_connrefused;
307   /* If a connection succeeeds, SUCCESS_AINFO will point to the
308      'struct addrinfo' that succeed.  */
309   struct addrinfo *success_ainfo = NULL;
310   unsigned int polls = 0;
311
312   /* Assume the worst.  */
313   scb->fd = -1;
314
315   do
316     {
317       got_connrefused = false;
318
319       for (struct addrinfo *iter = ainfo; iter != NULL; iter = iter->ai_next)
320         {
321           /* Iterate over the list of possible addresses to connect
322              to.  For each, we'll try to connect and see if it
323              succeeds.  */
324           int sock = try_connect (iter, &polls);
325
326           if (sock >= 0)
327             {
328               /* We've gotten a successful connection.  Save its
329                  'struct addrinfo', the socket, and break.  */
330               success_ainfo = iter;
331               scb->fd = sock;
332               break;
333             }
334           else if (
335 #ifdef USE_WIN32API
336           errno == WSAECONNREFUSED
337 #else
338           errno == ECONNREFUSED
339 #endif
340                    )
341             got_connrefused = true;
342         }
343     }
344   /* Just retry if:
345
346      - tcp_auto_retry is true, and
347      - We haven't gotten a connection yet, and
348      - Any of our connection attempts returned with ECONNREFUSED, and
349      - wait_for_connect signals that we can keep going.  */
350   while (tcp_auto_retry
351          && success_ainfo == NULL
352          && got_connrefused
353          && wait_for_connect (-1, &polls) >= 0);
354
355   if (success_ainfo == NULL)
356     {
357       net_close (scb);
358       return -1;
359     }
360
361   /* Turn off nonblocking.  */
362 #ifdef USE_WIN32API
363   u_long ioarg = 0;
364 #else
365   int ioarg = 0;
366 #endif
367
368   ioctl (scb->fd, FIONBIO, &ioarg);
369
370   if (success_ainfo->ai_socktype == IPPROTO_TCP)
371     {
372       /* Disable Nagle algorithm.  Needed in some cases.  */
373       int tmp = 1;
374
375       setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
376                   (char *) &tmp, sizeof (tmp));
377     }
378
379 #ifdef SIGPIPE
380   /* If we don't do this, then GDB simply exits
381      when the remote side dies.  */
382   signal (SIGPIPE, SIG_IGN);
383 #endif
384
385   return 0;
386 }
387
388 void
389 net_close (struct serial *scb)
390 {
391   if (scb->fd == -1)
392     return;
393
394   close (scb->fd);
395   scb->fd = -1;
396 }
397
398 int
399 net_read_prim (struct serial *scb, size_t count)
400 {
401   /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
402      'recv' takes 'char *' as second argument, while 'scb->buf' is
403      'unsigned char *'.  */
404   return recv (scb->fd, (char *) scb->buf, count, 0);
405 }
406
407 int
408 net_write_prim (struct serial *scb, const void *buf, size_t count)
409 {
410   /* On Windows, the second parameter to send is a "const char *"; on
411      UNIX systems it is generally "const void *".  The cast to "const
412      char *" is OK everywhere, since in C++ any data pointer type can
413      be implicitly converted to "const void *".  */
414   return send (scb->fd, (const char *) buf, count, 0);
415 }
416
417 int
418 ser_tcp_send_break (struct serial *scb)
419 {
420   /* Send telnet IAC and BREAK characters.  */
421   return (serial_write (scb, "\377\363", 2));
422 }
423
424 /* Support for "set tcp" and "show tcp" commands.  */
425
426 static void
427 set_tcp_cmd (const char *args, int from_tty)
428 {
429   help_list (tcp_set_cmdlist, "set tcp ", all_commands, gdb_stdout);
430 }
431
432 static void
433 show_tcp_cmd (const char *args, int from_tty)
434 {
435   help_list (tcp_show_cmdlist, "show tcp ", all_commands, gdb_stdout);
436 }
437
438 #ifndef USE_WIN32API
439
440 /* The TCP ops.  */
441
442 static const struct serial_ops tcp_ops =
443 {
444   "tcp",
445   net_open,
446   net_close,
447   NULL,
448   ser_base_readchar,
449   ser_base_write,
450   ser_base_flush_output,
451   ser_base_flush_input,
452   ser_tcp_send_break,
453   ser_base_raw,
454   ser_base_get_tty_state,
455   ser_base_copy_tty_state,
456   ser_base_set_tty_state,
457   ser_base_print_tty_state,
458   ser_base_setbaudrate,
459   ser_base_setstopbits,
460   ser_base_setparity,
461   ser_base_drain_output,
462   ser_base_async,
463   net_read_prim,
464   net_write_prim
465 };
466
467 #endif /* USE_WIN32API */
468
469 void
470 _initialize_ser_tcp (void)
471 {
472 #ifdef USE_WIN32API
473   /* Do nothing; the TCP serial operations will be initialized in
474      ser-mingw.c.  */
475 #else
476   serial_add_interface (&tcp_ops);
477 #endif /* USE_WIN32API */
478
479   add_prefix_cmd ("tcp", class_maintenance, set_tcp_cmd, _("\
480 TCP protocol specific variables\n\
481 Configure variables specific to remote TCP connections"),
482                   &tcp_set_cmdlist, "set tcp ",
483                   0 /* allow-unknown */, &setlist);
484   add_prefix_cmd ("tcp", class_maintenance, show_tcp_cmd, _("\
485 TCP protocol specific variables\n\
486 Configure variables specific to remote TCP connections"),
487                   &tcp_show_cmdlist, "show tcp ",
488                   0 /* allow-unknown */, &showlist);
489
490   add_setshow_boolean_cmd ("auto-retry", class_obscure,
491                            &tcp_auto_retry, _("\
492 Set auto-retry on socket connect"), _("\
493 Show auto-retry on socket connect"), 
494                            NULL, NULL, NULL,
495                            &tcp_set_cmdlist, &tcp_show_cmdlist);
496
497   add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
498                             &tcp_retry_limit, _("\
499 Set timeout limit in seconds for socket connection"), _("\
500 Show timeout limit in seconds for socket connection"), _("\
501 If set to \"unlimited\", GDB will keep attempting to establish a\n\
502 connection forever, unless interrupted with Ctrl-c.\n\
503 The default is 15 seconds."),
504                             NULL, NULL,
505                             &tcp_set_cmdlist, &tcp_show_cmdlist);
506 }