xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/ser-tcp.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /* Serial interface for raw TCP connections on Un*x like systems.
2 
3    Copyright (C) 1992-2016 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 
29 #include <sys/types.h>
30 
31 #ifdef HAVE_SYS_FILIO_H
32 #include <sys/filio.h>  /* For FIONBIO.  */
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>  /* For FIONBIO.  */
36 #endif
37 
38 #include "gdb_sys_time.h"
39 
40 #ifdef USE_WIN32API
41 #include <winsock2.h>
42 #ifndef ETIMEDOUT
43 #define ETIMEDOUT WSAETIMEDOUT
44 #endif
45 #define close(fd) closesocket (fd)
46 #define ioctl ioctlsocket
47 #else
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <netdb.h>
51 #include <sys/socket.h>
52 #include <netinet/tcp.h>
53 #endif
54 
55 #include <signal.h>
56 #include "gdb_select.h"
57 
58 #ifndef HAVE_SOCKLEN_T
59 typedef int socklen_t;
60 #endif
61 
62 void _initialize_ser_tcp (void);
63 
64 /* For "set tcp" and "show tcp".  */
65 
66 static struct cmd_list_element *tcp_set_cmdlist;
67 static struct cmd_list_element *tcp_show_cmdlist;
68 
69 /* Whether to auto-retry refused connections.  */
70 
71 static int tcp_auto_retry = 1;
72 
73 /* Timeout period for connections, in seconds.  */
74 
75 static unsigned int tcp_retry_limit = 15;
76 
77 /* How many times per second to poll deprecated_ui_loop_hook.  */
78 
79 #define POLL_INTERVAL 5
80 
81 /* Helper function to wait a while.  If SCB is non-null, wait on its
82    file descriptor.  Otherwise just wait on a timeout, updating *POLLS.
83    Returns -1 on timeout or interrupt, otherwise the value of select.  */
84 
85 static int
86 wait_for_connect (struct serial *scb, unsigned int *polls)
87 {
88   struct timeval t;
89   int n;
90 
91   /* While we wait for the connect to complete,
92      poll the UI so it can update or the user can
93      interrupt.  */
94   if (deprecated_ui_loop_hook && deprecated_ui_loop_hook (0))
95     {
96       errno = EINTR;
97       return -1;
98     }
99 
100   /* Check for timeout.  */
101   if (*polls > tcp_retry_limit * POLL_INTERVAL)
102     {
103       errno = ETIMEDOUT;
104       return -1;
105     }
106 
107   /* Back off to polling once per second after the first POLL_INTERVAL
108      polls.  */
109   if (*polls < POLL_INTERVAL)
110     {
111       t.tv_sec = 0;
112       t.tv_usec = 1000000 / POLL_INTERVAL;
113     }
114   else
115     {
116       t.tv_sec = 1;
117       t.tv_usec = 0;
118     }
119 
120   if (scb)
121     {
122       fd_set rset, wset, eset;
123 
124       FD_ZERO (&rset);
125       FD_SET (scb->fd, &rset);
126       wset = rset;
127       eset = rset;
128 
129       /* POSIX systems return connection success or failure by signalling
130 	 wset.  Windows systems return success in wset and failure in
131 	 eset.
132 
133 	 We must call select here, rather than gdb_select, because
134 	 the serial structure has not yet been initialized - the
135 	 MinGW select wrapper will not know that this FD refers
136 	 to a socket.  */
137       n = select (scb->fd + 1, &rset, &wset, &eset, &t);
138     }
139   else
140     /* Use gdb_select here, since we have no file descriptors, and on
141        Windows, plain select doesn't work in that case.  */
142     n = gdb_select (0, NULL, NULL, NULL, &t);
143 
144   /* If we didn't time out, only count it as one poll.  */
145   if (n > 0 || *polls < POLL_INTERVAL)
146     (*polls)++;
147   else
148     (*polls) += POLL_INTERVAL;
149 
150   return n;
151 }
152 
153 /* Open a tcp socket.  */
154 
155 int
156 net_open (struct serial *scb, const char *name)
157 {
158   char hostname[100];
159   const char *port_str;
160   int n, port, tmp;
161   int use_udp;
162   struct hostent *hostent;
163   struct sockaddr_in sockaddr;
164 #ifdef USE_WIN32API
165   u_long ioarg;
166 #else
167   int ioarg;
168 #endif
169   unsigned int polls = 0;
170 
171   use_udp = 0;
172   if (startswith (name, "udp:"))
173     {
174       use_udp = 1;
175       name = name + 4;
176     }
177   else if (startswith (name, "tcp:"))
178     name = name + 4;
179 
180   port_str = strchr (name, ':');
181 
182   if (!port_str)
183     error (_("net_open: No colon in host name!"));  /* Shouldn't ever
184 						       happen.  */
185 
186   tmp = min (port_str - name, (int) sizeof hostname - 1);
187   strncpy (hostname, name, tmp);	/* Don't want colon.  */
188   hostname[tmp] = '\000';	/* Tie off host name.  */
189   port = atoi (port_str + 1);
190 
191   /* Default hostname is localhost.  */
192   if (!hostname[0])
193     strcpy (hostname, "localhost");
194 
195   hostent = gethostbyname (hostname);
196   if (!hostent)
197     {
198       fprintf_unfiltered (gdb_stderr, "%s: unknown host\n", hostname);
199       errno = ENOENT;
200       return -1;
201     }
202 
203   sockaddr.sin_family = PF_INET;
204   sockaddr.sin_port = htons (port);
205   memcpy (&sockaddr.sin_addr.s_addr, hostent->h_addr,
206 	  sizeof (struct in_addr));
207 
208  retry:
209 
210   if (use_udp)
211     scb->fd = gdb_socket_cloexec (PF_INET, SOCK_DGRAM, 0);
212   else
213     scb->fd = gdb_socket_cloexec (PF_INET, SOCK_STREAM, 0);
214 
215   if (scb->fd == -1)
216     return -1;
217 
218   /* Set socket nonblocking.  */
219   ioarg = 1;
220   ioctl (scb->fd, FIONBIO, &ioarg);
221 
222   /* Use Non-blocking connect.  connect() will return 0 if connected
223      already.  */
224   n = connect (scb->fd, (struct sockaddr *) &sockaddr, sizeof (sockaddr));
225 
226   if (n < 0)
227     {
228 #ifdef USE_WIN32API
229       int err = WSAGetLastError();
230 #else
231       int err = errno;
232 #endif
233 
234       /* Maybe we're waiting for the remote target to become ready to
235 	 accept connections.  */
236       if (tcp_auto_retry
237 #ifdef USE_WIN32API
238 	  && err == WSAECONNREFUSED
239 #else
240 	  && err == ECONNREFUSED
241 #endif
242 	  && wait_for_connect (NULL, &polls) >= 0)
243 	{
244 	  close (scb->fd);
245 	  goto retry;
246 	}
247 
248       if (
249 #ifdef USE_WIN32API
250 	  /* Under Windows, calling "connect" with a non-blocking socket
251 	     results in WSAEWOULDBLOCK, not WSAEINPROGRESS.  */
252 	  err != WSAEWOULDBLOCK
253 #else
254 	  err != EINPROGRESS
255 #endif
256 	  )
257 	{
258 	  errno = err;
259 	  net_close (scb);
260 	  return -1;
261 	}
262 
263       /* Looks like we need to wait for the connect.  */
264       do
265 	{
266 	  n = wait_for_connect (scb, &polls);
267 	}
268       while (n == 0);
269       if (n < 0)
270 	{
271 	  net_close (scb);
272 	  return -1;
273 	}
274     }
275 
276   /* Got something.  Is it an error?  */
277   {
278     int res, err;
279     socklen_t len;
280 
281     len = sizeof (err);
282     /* On Windows, the fourth parameter to getsockopt is a "char *";
283        on UNIX systems it is generally "void *".  The cast to "char *"
284        is OK everywhere, since in C++ any data pointer type can be
285        implicitly converted to "void *".  */
286     res = getsockopt (scb->fd, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
287     if (res < 0 || err)
288       {
289 	/* Maybe the target still isn't ready to accept the connection.  */
290 	if (tcp_auto_retry
291 #ifdef USE_WIN32API
292 	    && err == WSAECONNREFUSED
293 #else
294 	    && err == ECONNREFUSED
295 #endif
296 	    && wait_for_connect (NULL, &polls) >= 0)
297 	  {
298 	    close (scb->fd);
299 	    goto retry;
300 	  }
301 	if (err)
302 	  errno = err;
303 	net_close (scb);
304 	return -1;
305       }
306   }
307 
308   /* Turn off nonblocking.  */
309   ioarg = 0;
310   ioctl (scb->fd, FIONBIO, &ioarg);
311 
312   if (use_udp == 0)
313     {
314       /* Disable Nagle algorithm.  Needed in some cases.  */
315       tmp = 1;
316       setsockopt (scb->fd, IPPROTO_TCP, TCP_NODELAY,
317 		  (char *)&tmp, sizeof (tmp));
318     }
319 
320 #ifdef SIGPIPE
321   /* If we don't do this, then GDB simply exits
322      when the remote side dies.  */
323   signal (SIGPIPE, SIG_IGN);
324 #endif
325 
326   return 0;
327 }
328 
329 void
330 net_close (struct serial *scb)
331 {
332   if (scb->fd == -1)
333     return;
334 
335   close (scb->fd);
336   scb->fd = -1;
337 }
338 
339 int
340 net_read_prim (struct serial *scb, size_t count)
341 {
342   /* Need to cast to silence -Wpointer-sign on MinGW, as Winsock's
343      'recv' takes 'char *' as second argument, while 'scb->buf' is
344      'unsigned char *'.  */
345   return recv (scb->fd, (char *) scb->buf, count, 0);
346 }
347 
348 int
349 net_write_prim (struct serial *scb, const void *buf, size_t count)
350 {
351   /* On Windows, the second parameter to send is a "const char *"; on
352      UNIX systems it is generally "const void *".  The cast to "const
353      char *" is OK everywhere, since in C++ any data pointer type can
354      be implicitly converted to "const void *".  */
355   return send (scb->fd, (const char *) buf, count, 0);
356 }
357 
358 int
359 ser_tcp_send_break (struct serial *scb)
360 {
361   /* Send telnet IAC and BREAK characters.  */
362   return (serial_write (scb, "\377\363", 2));
363 }
364 
365 /* Support for "set tcp" and "show tcp" commands.  */
366 
367 static void
368 set_tcp_cmd (char *args, int from_tty)
369 {
370   help_list (tcp_set_cmdlist, "set tcp ", all_commands, gdb_stdout);
371 }
372 
373 static void
374 show_tcp_cmd (char *args, int from_tty)
375 {
376   help_list (tcp_show_cmdlist, "show tcp ", all_commands, gdb_stdout);
377 }
378 
379 #ifndef USE_WIN32API
380 
381 /* The TCP ops.  */
382 
383 static const struct serial_ops tcp_ops =
384 {
385   "tcp",
386   net_open,
387   net_close,
388   NULL,
389   ser_base_readchar,
390   ser_base_write,
391   ser_base_flush_output,
392   ser_base_flush_input,
393   ser_tcp_send_break,
394   ser_base_raw,
395   ser_base_get_tty_state,
396   ser_base_copy_tty_state,
397   ser_base_set_tty_state,
398   ser_base_print_tty_state,
399   ser_base_noflush_set_tty_state,
400   ser_base_setbaudrate,
401   ser_base_setstopbits,
402   ser_base_setparity,
403   ser_base_drain_output,
404   ser_base_async,
405   net_read_prim,
406   net_write_prim
407 };
408 
409 #endif /* USE_WIN32API */
410 
411 void
412 _initialize_ser_tcp (void)
413 {
414 #ifdef USE_WIN32API
415   /* Do nothing; the TCP serial operations will be initialized in
416      ser-mingw.c.  */
417 #else
418   serial_add_interface (&tcp_ops);
419 #endif /* USE_WIN32API */
420 
421   add_prefix_cmd ("tcp", class_maintenance, set_tcp_cmd, _("\
422 TCP protocol specific variables\n\
423 Configure variables specific to remote TCP connections"),
424 		  &tcp_set_cmdlist, "set tcp ",
425 		  0 /* allow-unknown */, &setlist);
426   add_prefix_cmd ("tcp", class_maintenance, show_tcp_cmd, _("\
427 TCP protocol specific variables\n\
428 Configure variables specific to remote TCP connections"),
429 		  &tcp_show_cmdlist, "show tcp ",
430 		  0 /* allow-unknown */, &showlist);
431 
432   add_setshow_boolean_cmd ("auto-retry", class_obscure,
433 			   &tcp_auto_retry, _("\
434 Set auto-retry on socket connect"), _("\
435 Show auto-retry on socket connect"),
436 			   NULL, NULL, NULL,
437 			   &tcp_set_cmdlist, &tcp_show_cmdlist);
438 
439   add_setshow_uinteger_cmd ("connect-timeout", class_obscure,
440 			    &tcp_retry_limit, _("\
441 Set timeout limit in seconds for socket connection"), _("\
442 Show timeout limit in seconds for socket connection"), _("\
443 If set to \"unlimited\", GDB will keep attempting to establish a\n\
444 connection forever, unless interrupted with Ctrl-c.\n\
445 The default is 15 seconds."),
446 			    NULL, NULL,
447 			    &tcp_set_cmdlist, &tcp_show_cmdlist);
448 }
449