gdb/ser-tcp.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Serial interface for raw TCP connections on Un*x like systems.

  2.    Copyright (C) 1992-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "serial.h"
  16. #include "ser-base.h"
  17. #include "ser-tcp.h"
  18. #include "gdbcmd.h"
  19. #include "cli/cli-decode.h"
  20. #include "cli/cli-setshow.h"
  21. #include "filestuff.h"

  22. #include <sys/types.h>

  23. #ifdef HAVE_SYS_FILIO_H
  24. #include <sys/filio.h>  /* For FIONBIO.  */
  25. #endif
  26. #ifdef HAVE_SYS_IOCTL_H
  27. #include <sys/ioctl.h>  /* For FIONBIO.  */
  28. #endif

  29. #include <sys/time.h>

  30. #ifdef USE_WIN32API
  31. #include <winsock2.h>
  32. #ifndef ETIMEDOUT
  33. #define ETIMEDOUT WSAETIMEDOUT
  34. #endif
  35. #define close(fd) closesocket (fd)
  36. #define ioctl ioctlsocket
  37. #else
  38. #include <netinet/in.h>
  39. #include <arpa/inet.h>
  40. #include <netdb.h>
  41. #include <sys/socket.h>
  42. #include <netinet/tcp.h>
  43. #endif

  44. #include <signal.h>
  45. #include "gdb_select.h"

  46. #ifndef HAVE_SOCKLEN_T
  47. typedef int socklen_t;
  48. #endif

  49. void _initialize_ser_tcp (void);

  50. /* For "set tcp" and "show tcp".  */

  51. static struct cmd_list_element *tcp_set_cmdlist;
  52. static struct cmd_list_element *tcp_show_cmdlist;

  53. /* Whether to auto-retry refused connections.  */

  54. static int tcp_auto_retry = 1;

  55. /* Timeout period for connections, in seconds.  */

  56. static unsigned int tcp_retry_limit = 15;

  57. /* How many times per second to poll deprecated_ui_loop_hook.  */

  58. #define POLL_INTERVAL 5

  59. /* Helper function to wait a while.  If SCB is non-null, wait on its
  60.    file descriptor.  Otherwise just wait on a timeout, updating *POLLS.
  61.    Returns -1 on timeout or interrupt, otherwise the value of select.  */

  62. static int
  63. wait_for_connect (struct serial *scb, unsigned int *polls)
  64. {
  65.   struct timeval t;
  66.   int n;

  67.   /* While we wait for the connect to complete,
  68.      poll the UI so it can update or the user can
  69.      interrupt.  */
  70.   if (deprecated_ui_loop_hook && deprecated_ui_loop_hook (0))
  71.     {
  72.       errno = EINTR;
  73.       return -1;
  74.     }

  75.   /* Check for timeout.  */
  76.   if (*polls > tcp_retry_limit * POLL_INTERVAL)
  77.     {
  78.       errno = ETIMEDOUT;
  79.       return -1;
  80.     }

  81.   /* Back off to polling once per second after the first POLL_INTERVAL
  82.      polls.  */
  83.   if (*polls < POLL_INTERVAL)
  84.     {
  85.       t.tv_sec = 0;
  86.       t.tv_usec = 1000000 / POLL_INTERVAL;
  87.     }
  88.   else
  89.     {
  90.       t.tv_sec = 1;
  91.       t.tv_usec = 0;
  92.     }

  93.   if (scb)
  94.     {
  95.       fd_set rset, wset, eset;

  96.       FD_ZERO (&rset);
  97.       FD_SET (scb->fd, &rset);
  98.       wset = rset;
  99.       eset = rset;

  100.       /* POSIX systems return connection success or failure by signalling
  101.          wset.  Windows systems return success in wset and failure in
  102.          eset.

  103.          We must call select here, rather than gdb_select, because
  104.          the serial structure has not yet been initialized - the
  105.          MinGW select wrapper will not know that this FD refers
  106.          to a socket.  */
  107.       n = select (scb->fd + 1, &rset, &wset, &eset, &t);
  108.     }
  109.   else
  110.     /* Use gdb_select here, since we have no file descriptors, and on
  111.        Windows, plain select doesn't work in that case.  */
  112.     n = gdb_select (0, NULL, NULL, NULL, &t);

  113.   /* If we didn't time out, only count it as one poll.  */
  114.   if (n > 0 || *polls < POLL_INTERVAL)
  115.     (*polls)++;
  116.   else
  117.     (*polls) += POLL_INTERVAL;

  118.   return n;
  119. }

  120. /* Open a tcp socket.  */

  121. int
  122. net_open (struct serial *scb, const char *name)
  123. {
  124.   char *port_str, hostname[100];
  125.   int n, port, tmp;
  126.   int use_udp;
  127.   struct hostent *hostent;
  128.   struct sockaddr_in sockaddr;
  129. #ifdef USE_WIN32API
  130.   u_long ioarg;
  131. #else
  132.   int ioarg;
  133. #endif
  134.   unsigned int polls = 0;

  135.   use_udp = 0;
  136.   if (strncmp (name, "udp:", 4) == 0)
  137.     {
  138.       use_udp = 1;
  139.       name = name + 4;
  140.     }
  141.   else if (strncmp (name, "tcp:", 4) == 0)
  142.     name = name + 4;

  143.   port_str = strchr (name, ':');

  144.   if (!port_str)
  145.     error (_("net_open: No colon in host name!"));  /* Shouldn't ever
  146.                                                        happen.  */

  147.   tmp = min (port_str - name, (int) sizeof hostname - 1);
  148.   strncpy (hostname, name, tmp);        /* Don't want colon.  */
  149.   hostname[tmp] = '\000';        /* Tie off host name.  */
  150.   port = atoi (port_str + 1);

  151.   /* Default hostname is localhost.  */
  152.   if (!hostname[0])
  153.     strcpy (hostname, "localhost");

  154.   hostent = gethostbyname (hostname);
  155.   if (!hostent)
  156.     {
  157.       fprintf_unfiltered (gdb_stderr, "%s: unknown host\n", hostname);
  158.       errno = ENOENT;
  159.       return -1;
  160.     }

  161.   sockaddr.sin_family = PF_INET;
  162.   sockaddr.sin_port = htons (port);
  163.   memcpy (&sockaddr.sin_addr.s_addr, hostent->h_addr,
  164.           sizeof (struct in_addr));

  165. retry:

  166.   if (use_udp)
  167.     scb->fd = gdb_socket_cloexec (PF_INET, SOCK_DGRAM, 0);
  168.   else
  169.     scb->fd = gdb_socket_cloexec (PF_INET, SOCK_STREAM, 0);

  170.   if (scb->fd == -1)
  171.     return -1;

  172.   /* Set socket nonblocking.  */
  173.   ioarg = 1;
  174.   ioctl (scb->fd, FIONBIO, &ioarg);

  175.   /* Use Non-blocking connect.  connect() will return 0 if connected
  176.      already.  */
  177.   n = connect (scb->fd, (struct sockaddr *) &sockaddr, sizeof (sockaddr));

  178.   if (n < 0)
  179.     {
  180. #ifdef USE_WIN32API
  181.       int err = WSAGetLastError();
  182. #else
  183.       int err = errno;
  184. #endif

  185.       /* Maybe we're waiting for the remote target to become ready to
  186.          accept connections.  */
  187.       if (tcp_auto_retry
  188. #ifdef USE_WIN32API
  189.           && err == WSAECONNREFUSED
  190. #else
  191.           && err == ECONNREFUSED
  192. #endif
  193.           && wait_for_connect (NULL, &polls) >= 0)
  194.         {
  195.           close (scb->fd);
  196.           goto retry;
  197.         }

  198.       if (
  199. #ifdef USE_WIN32API
  200.           /* Under Windows, calling "connect" with a non-blocking socket
  201.              results in WSAEWOULDBLOCK, not WSAEINPROGRESS.  */
  202.           err != WSAEWOULDBLOCK
  203. #else
  204.           err != EINPROGRESS
  205. #endif
  206.           )
  207.         {
  208.           errno = err;
  209.           net_close (scb);
  210.           return -1;
  211.         }

  212.       /* Looks like we need to wait for the connect.  */
  213.       do
  214.         {
  215.           n = wait_for_connect (scb, &polls);
  216.         }
  217.       while (n == 0);
  218.       if (n < 0)
  219.         {
  220.           net_close (scb);
  221.           return -1;
  222.         }
  223.     }

  224.   /* Got something.  Is it an error?  */
  225.   {
  226.     int res, err;
  227.     socklen_t len;

  228.     len = sizeof (err);
  229.     /* On Windows, the fourth parameter to getsockopt is a "char *";
  230.        on UNIX systems it is generally "void *".  The cast to "void *"
  231.        is OK everywhere, since in C "void *" can be implicitly
  232.        converted to any pointer type.  */
  233.     res = getsockopt (scb->fd, SOL_SOCKET, SO_ERROR, (void *) &err, &len);
  234.     if (res < 0 || err)
  235.       {
  236.         /* Maybe the target still isn't ready to accept the connection.  */
  237.         if (tcp_auto_retry
  238. #ifdef USE_WIN32API
  239.             && err == WSAECONNREFUSED
  240. #else
  241.             && err == ECONNREFUSED
  242. #endif
  243.             && wait_for_connect (NULL, &polls) >= 0)
  244.           {
  245.             close (scb->fd);
  246.             goto retry;
  247.           }
  248.         if (err)
  249.           errno = err;
  250.         net_close (scb);
  251.         return -1;
  252.       }
  253.   }

  254.   /* Turn off nonblocking.  */
  255.   ioarg = 0;
  256.   ioctl (scb->fd, FIONBIO, &ioarg);

  257.   if (use_udp == 0)
  258.     {
  259.       /* Disable Nagle algorithm.  Needed in some cases.  */
  260.       tmp = 1;
  261.       setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
  262.                   (char *)&tmp, sizeof (tmp));
  263.     }

  264. #ifdef SIGPIPE
  265.   /* If we don't do this, then GDB simply exits
  266.      when the remote side dies.  */
  267.   signal (SIGPIPE, SIG_IGN);
  268. #endif

  269.   return 0;
  270. }

  271. void
  272. net_close (struct serial *scb)
  273. {
  274.   if (scb->fd == -1)
  275.     return;

  276.   close (scb->fd);
  277.   scb->fd = -1;
  278. }

  279. int
  280. net_read_prim (struct serial *scb, size_t count)
  281. {
  282.   /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
  283.      'recv' takes 'char *' as second argument, while 'scb->buf' is
  284.      'unsigned char *'.  */
  285.   return recv (scb->fd, (void *) scb->buf, count, 0);
  286. }

  287. int
  288. net_write_prim (struct serial *scb, const void *buf, size_t count)
  289. {
  290.   return send (scb->fd, buf, count, 0);
  291. }

  292. int
  293. ser_tcp_send_break (struct serial *scb)
  294. {
  295.   /* Send telnet IAC and BREAK characters.  */
  296.   return (serial_write (scb, "\377\363", 2));
  297. }

  298. /* Support for "set tcp" and "show tcp" commands.  */

  299. static void
  300. set_tcp_cmd (char *args, int from_tty)
  301. {
  302.   help_list (tcp_set_cmdlist, "set tcp ", all_commands, gdb_stdout);
  303. }

  304. static void
  305. show_tcp_cmd (char *args, int from_tty)
  306. {
  307.   help_list (tcp_show_cmdlist, "show tcp ", all_commands, gdb_stdout);
  308. }

  309. #ifndef USE_WIN32API

  310. /* The TCP ops.  */

  311. static const struct serial_ops tcp_ops =
  312. {
  313.   "tcp",
  314.   net_open,
  315.   net_close,
  316.   NULL,
  317.   ser_base_readchar,
  318.   ser_base_write,
  319.   ser_base_flush_output,
  320.   ser_base_flush_input,
  321.   ser_tcp_send_break,
  322.   ser_base_raw,
  323.   ser_base_get_tty_state,
  324.   ser_base_copy_tty_state,
  325.   ser_base_set_tty_state,
  326.   ser_base_print_tty_state,
  327.   ser_base_noflush_set_tty_state,
  328.   ser_base_setbaudrate,
  329.   ser_base_setstopbits,
  330.   ser_base_drain_output,
  331.   ser_base_async,
  332.   net_read_prim,
  333.   net_write_prim
  334. };

  335. #endif /* USE_WIN32API */

  336. void
  337. _initialize_ser_tcp (void)
  338. {
  339. #ifdef USE_WIN32API
  340.   /* Do nothing; the TCP serial operations will be initialized in
  341.      ser-mingw.c.  */
  342. #else
  343.   serial_add_interface (&tcp_ops);
  344. #endif /* USE_WIN32API */

  345.   add_prefix_cmd ("tcp", class_maintenance, set_tcp_cmd, _("\
  346. TCP protocol specific variables\n\
  347. Configure variables specific to remote TCP connections"),
  348.                   &tcp_set_cmdlist, "set tcp ",
  349.                   0 /* allow-unknown */, &setlist);
  350.   add_prefix_cmd ("tcp", class_maintenance, show_tcp_cmd, _("\
  351. TCP protocol specific variables\n\
  352. Configure variables specific to remote TCP connections"),
  353.                   &tcp_show_cmdlist, "show tcp ",
  354.                   0 /* allow-unknown */, &showlist);

  355.   add_setshow_boolean_cmd ("auto-retry", class_obscure,
  356.                            &tcp_auto_retry, _("\
  357. Set auto-retry on socket connect"), _("\
  358. Show auto-retry on socket connect"),
  359.                            NULL, NULL, NULL,
  360.                            &tcp_set_cmdlist, &tcp_show_cmdlist);

  361.   add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
  362.                             &tcp_retry_limit, _("\
  363. Set timeout limit in seconds for socket connection"), _("\
  364. Show timeout limit in seconds for socket connection"), _("\
  365. If set to \"unlimited\", GDB will keep attempting to establish a\n\
  366. connection forever, unless interrupted with Ctrl-c.\n\
  367. The default is 15 seconds."),
  368.                             NULL, NULL,
  369.                             &tcp_set_cmdlist, &tcp_show_cmdlist);
  370. }