7 static char *rcsid_gdb_conn_c = "$Header$";
10 /************************************************************************
14 * GDB - Connection Management Services
16 * Author: Noah Mendelsohn
17 * Copyright: 1986 MIT Project Athena
18 * For copying and distribution information, please see
19 * the file <mit-copyright.h>.
21 * Routines used in the creation and maintenance of CONNECTIONS.
22 * Note: these are closely related to the services provided
23 * by gdb_trans.c and gdb_trans2.c.
26 ************************************************************************/
28 #include <mit-copyright.h>
32 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <sys/ioctl.h>
36 #include <netinet/in.h>
40 #include <sys/filio.h>
45 extern u_short htons(); /* ?? All versions? */
48 CONNECTION gdb_allocate_connection();
50 /************************************************************************/
52 /* start_peer_connection (start_peer_connection)
54 /* Starts a connection to another process which itself will be
55 /* issuing a start_peer_connection to us. Current implementation
56 /* builds at most one stream, with the risk of a hang if
57 /* the attempts to connect cross in the night. This is a bug,
58 /* but this level of support is acceptable for casual debugging
59 /* of applications, and perhaps for some production use in
60 /* controlled settings. I think the only other way to do it
61 /* is to risk building two streams in parallel, possibly tearing
62 /* one down when the duplication is discovered. Seems complicated
65 /************************************************************************/
68 start_peer_connection(id)
69 char *id; /* null terminated string */
71 register CONNECTION con; /* the connection we're */
77 * Try to allocate a connection and fill it in with null values.
83 * In this implementation, we use a single fd for both inbound and
84 * outbound traffic. Try to connect to other side. If that
85 * doesn't work, wait to accept a connection from the other side.
86 * Current implementation of this is synchronous--may be a problem?
87 * Also note timing window bug in the following. If the two peers
88 * are started at just about the same time, the race may not be handled
89 * propoerly. If the connections come up, then verify the level of
90 * protocol being observed on the connections. If incompatible,
91 * then turn off the connection.
94 if(!g_try_connecting(con,id)) {
95 g_try_accepting(con,id);
96 if(con->status == CON_STARTING)
99 if(con->status == CON_STARTING)
100 g_ver_oprotocol(con);
103 if (con->status == CON_UP) {
105 * We've successfully started the connection, now mark
106 * it for non-blocking I/O. Also, update the high water
107 * mark of fd's controlled by our system.
110 if(ioctl(con->in.fd, FIONBIO, (char *)&nb)== (-1)) {
111 g_stop_with_errno(con);
114 if (con->in.fd +1 > gdb_mfd)
115 gdb_mfd = con->in.fd + 1;
117 * Allocate a buffer, if necessary, and reset buffer pointers
118 * so first request will result in a long read into the buffer
120 g_allocate_connection_buffers(con);
127 /************************************************************************/
131 /* Internal routine to allocate a new connection structure and
132 /* initialize all its fields to logical null values.
134 /************************************************************************/
139 register CONNECTION con;
142 * Try to allocate a connection, fatal error if none available
144 con = gdb_allocate_connection();
146 GDB_GIVEUP("start_peer_connection: Tried to allocate too many connections") /* <==RECOVERABLE */
149 * Give the fields their initial values
157 \f/************************************************************************/
161 /* Sets a connection descriptor to have all null values in
162 /* its fields. This routine does NOT do any of the cleanup
163 /* which is necessary after the connection has really been used.
165 /************************************************************************/
172 * Initialize the connection control data structure.
174 con->id = GDB_CON_ID;
175 con->status = CON_STARTING;
176 con->oob_fcn = NULL; /* out of band signalling */
177 /* is not currently */
179 con->errno = 0; /* system errno gets */
180 /* copied here iff it */
181 /* causes this con to die */
183 * Initialize input half connection to null state before trying
186 con->in.status = OP_NOT_STARTED;
189 con->in.op_q_first = (struct oper_data *)&con->in;
190 con->in.op_q_last = (struct oper_data *)&con->in;
191 con->in.next_byte = NULL;
192 con->in.remaining = 0;
196 * Initialize output half connection to null state before trying
199 con->out.status = OP_NOT_STARTED;
201 con->out.oob_fd = -1;
202 con->out.op_q_first = (struct oper_data *)&con->out;
203 con->out.op_q_last = (struct oper_data *)&con->out;
204 con->out.next_byte = NULL;
205 con->out.remaining = 0;
213 /************************************************************************/
215 /* gdb_allocate_connection
217 /* Return an unused entry in the connection array. Unused entries
218 /* are recognized by being marked as CON_STOPPED.
220 /* Note that gdb_mcons is the number of descriptors which have
221 /* ever been used (i.e. a high water mark), so status fields
222 /* are invalid above that.
224 /************************************************************************/
227 gdb_allocate_connection()
229 register int i; /* index of next one */
233 * First look for one below the high water mark
235 for(i=0; i<gdb_mcons; i++) {
236 if (gdb_cons[i].status == CON_STOPPED)
241 * Allocate one which has never been used, if possible
244 if (i>=GDB_MAX_CONNECTIONS)
245 GDB_GIVEUP("gdb: tried to allocate too many simulataneous connections.\n, See GDB_MAX_CONNECTIONS in gdb.h.") /* <==RECOVERABLE */
247 gdb_mcons++; /* bump the high water mark */
248 gdb_cons[i].status = CON_STOPPED; /* initialize status of the */
250 return &gdb_cons[i]; /* return new highest con */
254 /************************************************************************/
258 /* Try to start a connection to the designated site, filling
259 /* in the appropriate information in the connection descriptor
260 /* if successful. Return TRUE if connection succeeded or if
261 /* error was fatal enough that we shouldn't try accepting. Returns
262 /* FALSE if we should try accepting.
264 /************************************************************************/
268 g_try_connecting(con,id)
272 int peer; /* socket for talking to
274 int on = 1; /* flag for ioctl */
275 struct sockaddr_in target; /* build the peer address */
277 struct hostent *peer_host; /* host where peer is */
279 /*----------------------------------------------------------*/
281 /* Make sure connection is marked stopped until we
284 /*----------------------------------------------------------*/
286 con->status = CON_STOPPED;
288 /*----------------------------------------------------------*/
290 /* Find out host where peer is, and validate it. Take
291 /* care of port at the same time.
293 /*----------------------------------------------------------*/
295 bzero((char *)&target, sizeof(target));
296 g_parse_target(id, &peer_host, &target.sin_port);
297 if (peer_host == NULL) {
298 fprintf(gdb_log,"gdb: g_try_connecting... '%s' is not a valid host:server\n",
300 return TRUE; /* so we won't try accepting */
303 /*----------------------------------------------------------*/
307 /*----------------------------------------------------------*/
309 peer = socket(AF_INET, SOCK_STREAM, 0);
311 g_stop_with_errno(con);
312 return TRUE; /* fatal error */
315 /*----------------------------------------------------------*/
317 /* Get information and bind socket using well known
318 /* port (BUG: this restricts us to one pair of peers
319 /* per host pair, as well as being bad practice on
320 /* the network. It will do for debugging.
322 /*----------------------------------------------------------*/
325 bcopy(peer_host->h_addr, (char *)&target.sin_addr, peer_host->h_length);
326 target.sin_family = peer_host->h_addrtype;
328 /*----------------------------------------------------------*/
330 /* Make the connection
332 /*----------------------------------------------------------*/
334 if(connect(peer, (struct sockaddr *)&target, sizeof(target)) < 0) {
335 if (errno == ECONNREFUSED)
336 return FALSE; /* other side not yet */
337 /* up, but no other fatal */
340 gdb_perror("gdb: unexpected error connecting");
341 g_stop_with_errno(con);
346 if ((gdb_Options & GDB_OPT_KEEPALIVE) &&
347 setsockopt(peer, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0) {
348 gdb_perror("gdb: unable to start keepalives");
349 g_stop_with_errno(con);
353 /*----------------------------------------------------------*/
355 /* The connection has been made, fill in the connection
356 /* control data structure.
358 /*----------------------------------------------------------*/
362 con->status = CON_STARTING;
368 /************************************************************************/
372 /* For a given server or peer i.d., figure out the host and the
373 /* port. Arguments are:
375 /* string i.d. of the server, which is
376 /* in one of two forms:
378 /* host:servicename (where service name must not begin
381 /* host:#portnumber (where portnumber is the actual
382 /* number of the port to be used)
384 /* (actually, a 3rd form, with no port number supplied,
385 /* will use a default GDB_PORT, but this is unsafe
386 /* and it will be disabled in production versions
387 /* of the gdb system.)
389 /* **hostent: returned to indicate host to be used. Null
390 /* if host could not be found
392 /* *port pointer to an integer where the port number will
393 /* be put. We return the port number in network
396 /************************************************************************/
399 g_parse_target(id, host, port)
401 struct hostent **host;
404 char buffer[256]; /* longest host name */
405 register char *ip, *bp; /* for copying name */
406 struct servent *serv; /* returned from */
407 /* get service by name */
409 /*----------------------------------------------------------*/
411 /* copy the host name part only to local buffer
413 /*----------------------------------------------------------*/
418 while (*ip != '\0' && *ip != ':')
422 /*----------------------------------------------------------*/
424 /* Look up the host name, return if bad.
426 /*----------------------------------------------------------*/
428 *host = gethostbyname(buffer);
433 /*----------------------------------------------------------*/
435 /* Set up the port address
437 /*----------------------------------------------------------*/
451 * port number supplied explictly
454 if (*ip < '0' || *ip>'9') {
458 *port = htons((u_short)atoi(ip));
461 * service identified by name
463 serv = getservbyname(ip, "tcp");
468 *port = serv->s_port;
472 /************************************************************************/
476 /* Try to accept a connection to the designated site, filling
477 /* in the appropriate information in the connection descriptor
480 /************************************************************************/
483 g_try_accepting(con,id)
487 int slisten; /* socket on which
488 we listen for connections */
490 int peer; /* socket for talking to
493 struct sockaddr_in self, from;
494 int retries = GDB_BIND_RETRY_COUNT;
495 int onoff = 1; /* used as argument to */
498 struct hostent *peer_host; /* host where peer is */
500 /*----------------------------------------------------------*/
502 /* Make sure connection is marked stopped until we
505 /*----------------------------------------------------------*/
507 con->status = CON_STOPPED;
509 /*----------------------------------------------------------*/
511 /* Create a socket on which to listen. Tell it that
512 /* it's OK to re-use the port address, which may still
513 /* appear busy if connections are taking awhile to go
516 /*----------------------------------------------------------*/
518 slisten = socket(AF_INET, SOCK_STREAM, 0);
520 gdb_perror("g_try_accepting: error creating listen socket");
521 g_stop_with_errno(con);
524 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0, 0)<0)
525 /* that didn't work, try 4.3 */
526 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
527 (char *)&onoff, sizeof(int)) <0)
528 GDB_GIVEUP("g_try_accepting: could not set SO_REUSEADDR");
530 /*----------------------------------------------------------*/
532 /* Find out host where peer is, and validate it. Take
533 /* care of port at the same time. This is redundant
534 /* given that g_try_connecting is always called first.
536 /*----------------------------------------------------------*/
538 bzero((char *)&self, sizeof(self));
539 g_parse_target(id, &peer_host, &self.sin_port);
540 if (peer_host == NULL) {
541 GDB_GIVEUP("gdb_try_accepting: bad port not caught by try connecting")
544 /*----------------------------------------------------------*/
546 /* Bind the socket to ourselves, using the well known
547 /* port (See bug note in g_try_connecting.
549 /* This code should really go in initialization, I think.
551 /*----------------------------------------------------------*/
553 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
554 if (errno == EADDRINUSE && retries--) {
555 fprintf(gdb_log,"gdb: port address in use, will retry %d more time(s)\n",retries+1);
556 sleep(GDB_BIND_RETRY_INTERVAL);
559 gdb_perror("gdb: error binding listen socket");
560 g_stop_with_errno(con);
561 (void) close(slisten);
566 /*----------------------------------------------------------*/
568 /* Listen for connections.
570 /*----------------------------------------------------------*/
572 (void) listen (slisten, 5); /* does not block, just */
573 /* sets the maximum backlog */
574 /* of pending non-accepted */
576 fromlen = sizeof(from);
577 peer = accept(slisten, &from, &fromlen);
579 g_stop_with_errno(con);
580 gdb_perror("gdb_try_accepting: error accepting connection");
581 (void) close(slisten);
585 (void) close (slisten); /* we're not using the */
586 /* listening socket */
587 /* anymore, only the */
588 /* connection to the peer */
590 /*----------------------------------------------------------*/
592 /* The connection has been made, fill in the connection
593 /* control data structure.
595 /*----------------------------------------------------------*/
599 con->status = CON_STARTING;
602 /************************************************************************/
606 /* Called when an outbound connection is started to verify
607 /* the version of the protocol being observed.
609 /************************************************************************/
615 #ifdef VERIFY_PROTOCOL
616 char ver = GDB_PROTOCOL_VERSION;
620 int onoff = 0; /* for ioctl to turn off */
623 * Because the connection was accepted on a non-blocking
624 * listening socket, the connection itself may be non-blocking.
625 * We can't tolerate that here. It will be reset later.
627 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
628 g_stop_with_errno(con);
629 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
633 while (write(con->out.fd, &ver, 1) < 0) {
634 g_stop_with_errno(con);
639 len = read(con->in.fd, &theirs, 1);
641 g_stop_with_errno(con);
647 con->status = CON_UP;
649 con->status = CON_STOPPED;
650 #else !VERIFY_PROTOCOL
651 con->status = CON_UP;
652 #endif !VERIFY_PROTOCOL
655 /************************************************************************/
659 /* Called when an inbound connection is started to verify
660 /* the version of the protocol being observed.
662 /************************************************************************/
668 #ifdef VERIFY_PROTOCOL
669 char ver = GDB_PROTOCOL_VERSION;
673 int onoff = 0; /* for ioctl to turn off */
676 * Because the connection was accepted on a non-blocking
677 * listening socket, the connection itself may be non-blocking.
678 * We can't tolerate that here. It will be reset later.
680 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
681 g_stop_with_errno(con);
682 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
687 len = read(con->in.fd, &theirs, 1);
689 g_stop_with_errno(con);
695 con->status = CON_UP;
697 con->status = CON_STOPPED;
699 while (write(con->out.fd, &ver, 1) < 0) {
700 g_stop_with_errno(con);
703 #else !VERIFY_PROTOCOL
704 con->status = CON_UP;
709 /************************************************************************/
711 /* sever_connection (sever_connection)
713 /* Unconditionally, but cleanly, terminates a connection. All
714 /* pending operations on the connection are cancelled, and the
715 /* file descriptor for the connection is closed. This routine
716 /* should be called directly from applications wishing to shut
717 /* down a connection. No transmissions are attempted
718 /* by this routine. Returns NULL, in the hope that applications
719 /* will assign this to their old CONNECTION variable.
721 /************************************************************************/
724 sever_connection(con)
729 GDB_CHECK_CON(con, "sever_connection")
730 if (con->status == CON_UP || con->status == CON_STARTING)
731 g_stop_connection(con);
732 if (con->status != CON_STOPPED)
733 gdb_de_allocate_connection(con);
738 /************************************************************************/
742 /* This connection is stopping because of a problem on a syscall.
743 /* We record the errno in the connection descriptor for inspection
744 /* by the application, then stop the connection.
746 /************************************************************************/
750 g_stop_with_errno(con)
754 g_stop_connection(con);
758 /************************************************************************/
762 /* Unconditionally, but cleanly, terminates a connection. All
763 /* pending operations on the connection are cancelled, and the
764 /* file descriptor for the connection is closed. This routine is
765 /* for internal use. Applications call sever_connection, which
766 /* also de_allocates the descriptor. No transmissions are attempted
769 /************************************************************************/
772 g_stop_connection(con)
776 * Shutdown activity on the two half connections.
778 g_cleanup_half_connection(&(con->in));
779 g_cleanup_half_connection(&(con->out));
782 * Remove the file descriptor from the select bit maps
784 if (!(con->in.flags & HCON_UNUSED) && con->in.fd >= 0)
785 FD_CLR(con->in.fd, &gdb_crfds);
786 if (!(con->out.flags & HCON_UNUSED) && con->out.fd >= 0)
787 FD_CLR(con->out.fd, &gdb_cwfds);
789 * Close the file descriptor. Note, this presumes that in fact
790 * 1) in is never the unused half and
791 * 2) when the connection is bi-directional, in and out share an
792 * fd. We could do with a more elaborate scheme to control
793 * this in the future.
795 (void) close(con->in.fd);
798 * Mark the connection as stopping. We can't reclaim the
799 * descriptor until the application does a sever, or else there
800 * would be a risk of re-allocating it out from under the application.
803 con->status = CON_STOPPING;
809 /************************************************************************/
811 /* gdb_de_allocate_connection
813 /* Return a connection whose file descriptors have been closed
816 /************************************************************************/
819 gdb_de_allocate_connection(con)
824 con->status = CON_STOPPED;
826 i = gdb_mcons-1; /* start at last one used */
829 * Reset gdb_mcons to be the number of connections in use
831 while (i>=0 && gdb_cons[i].status == CON_STOPPED)
837 /************************************************************************/
839 /* g_cleanup_half_conection
841 /* Terminate all pending operations on the supplied half
842 /* connection. Note that the algorithm used here presumes
843 /* that cancel_operation will de-queue the operation descriptor,
844 /* therefore we have to be careful here about when we look at
847 /************************************************************************/
850 g_cleanup_half_connection(hcon)
851 HALF_CONNECTION hcon;
853 OPERATION current, next;
855 current = hcon->op_q_first;
858 * Loop through all operations in the queue canceling them.
859 * Make sure to pick up pointer to 'next' before the current
860 * one is canceled, as cancelling may invalidate the pointer.
863 while (current != (OPERATION)hcon) {
864 next = current->next;
865 (void) cancel_operation(current);
870 /************************************************************************/
872 /* create_listening_connection (create_listening_connection)
874 /* Starts a special type of connection which is used to listen
875 /* for incoming connection requests. The inbound half-connection
876 /* is the only one used for this special kind of connection.
878 /* It is the user's responsibility to insure that only appropriate
879 /* types of operation are queued on a connection of this sort. In
880 /* general, these connections are intended for internal use by
881 /* GDB, and they are not intended to be visible to servers or
884 /* The id supplied should be in one of two forms. If just a
885 /* string is supplied then it is presumed to be the name of
886 /* a registered tcp service. If the name begins with a #, then
887 /* the rest is interpreted as the integer port number to be used.
889 /* In future implementations, the id may have more structure, which
890 /* is why we define it as a string.
892 /************************************************************************/
895 create_listening_connection(id)
898 register CONNECTION con; /* the connection we're */
901 register int slisten; /* socket on which
902 we listen for connections */
904 struct sockaddr_in self;
905 int retries = GDB_BIND_RETRY_COUNT;
906 int onoff = 1; /* used as argument to */
908 struct servent *serv;
913 * Try to allocate a connection and fill it in with null values.
919 * Try to create a socket for listening
921 con->in.fd = socket(AF_INET, SOCK_STREAM, 0);
922 slisten = con->in.fd; /* easier and faster than */
923 /* using con->in.fd all the */
926 gdb_perror("create_listening_connection: error creating listen socket");
927 (void) g_stop_with_errno(con);
931 * Set options so the listening address can be re-used (this
932 * has its dangers, but otherwise we can't restart our servers
933 * for long periods after they crash because of connections which
934 * take a long to time clean up and hold ports in use.)
938 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0,0)<0)
939 /* that didn't work, try 4.3 */
940 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
941 (char *)&onoff, sizeof(int)) <0)
942 GDB_GIVEUP("create_listening_connection: could not set SO_REUSEADDR")
945 * Make the listening socket non-blocking so we won't have to do
946 * selects before polling it (change made by Bill Sommerfeld - wesommer)
948 if (ioctl(slisten, FIONBIO, (char *)&onoff) < 0) { /*<==FIX,,,add comment */
949 g_stop_with_errno(con);
950 gdb_perror("ioctl for listening socket");
953 /*----------------------------------------------------------*/
955 /* Bind the socket to ourselves, using port derived from
956 /* the supplied id string.
958 /*----------------------------------------------------------*/
960 bzero((char *)&self, sizeof(self));
962 * Determine our port number
965 self.sin_port = htons((u_short)atoi(id+1));
967 serv = getservbyname(id, "tcp");
969 fprintf(gdb_log,"gdb create_listening_connection: cannot become service named %s\n",id);
970 return NULL; /* BUG: causes connetion */
971 /* descriptor leakage. Should */
972 /* return an error code in */
973 /* the connection descriptor*/
975 self.sin_port = serv->s_port;
979 * Try and re-try the bind until it works or until retry count
982 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
983 if (errno == EADDRINUSE && retries--) {
984 fprintf(gdb_log,"gdb create_listening_connection: port address in use, will retry %d more time(s)\n",retries+1);
985 sleep(GDB_BIND_RETRY_INTERVAL);
988 gdb_perror("gdb create_listening_connection: error binding listen socket");
989 g_stop_with_errno(con);
994 /*----------------------------------------------------------*/
996 /* Listen for connections.
998 /*----------------------------------------------------------*/
1000 (void) listen (slisten, 5); /* does not block, just */
1001 /* sets the maximum backlog */
1002 /* of pending non-accepted */
1005 con->in.flags |= HCON_LISTEN;
1006 con->out.flags |= HCON_UNUSED;
1007 con->status = CON_UP;
1008 if (con->in.fd +1 > gdb_mfd)
1009 gdb_mfd = con->in.fd + 1;
1013 /************************************************************************/
1015 /* g_allocate_connection_buffers
1017 /* Create a buffer which can be used to receive large
1018 /* chunks of data from the socket. This is currently done only
1019 /* on the inbound half connection. Also, the buffers are not freed
1020 /* once allocated, even if the connection descriptor is re-used.
1022 /************************************************************************/
1025 g_allocate_connection_buffers(con)
1028 HALF_CONNECTION inbound = &(con->in);
1031 * See if there is already one allocated, if not, allocate one.
1033 if (inbound->stream_buffer == (char *)NULL) {
1034 inbound->stream_buffer =
1035 db_alloc(inbound->stream_buffer_length);
1039 * In any case, make sure that it is effectively empty
1041 inbound -> stream_buffer_next = inbound -> stream_buffer;
1042 inbound -> stream_buffer_remaining = 0;