7 static char *rcsid_gdb_conn_c = "$Header$";
33 /************************************************************************/
37 /* GDB - Connection Management Services
39 /* Author: Noah Mendelsohn
40 /* Copyright: 1986 MIT Project Athena
42 /* Routines used in the creation and maintenance of CONNECTIONS.
43 /* Note: these are closely related to the services provided
44 /* by gdb_trans.c and gdb_trans2.c.
47 /************************************************************************/
52 #include <sys/types.h>
54 #include <sys/socket.h>
55 #include <sys/ioctl.h>
56 #include <netinet/in.h>
62 extern u_short htons(); /* ?? All versions? */
65 CONNECTION gdb_allocate_connection();
67 /************************************************************************/
69 /* start_peer_connection (start_peer_connection)
71 /* Starts a connection to another process which itself will be
72 /* issuing a start_peer_connection to us. Current implementation
73 /* builds at most one stream, with the risk of a hang if
74 /* the attempts to connect cross in the night. This is a bug,
75 /* but this level of support is acceptable for casual debugging
76 /* of applications, and perhaps for some production use in
77 /* controlled settings. I think the only other way to do it
78 /* is to risk building two streams in parallel, possibly tearing
79 /* one down when the duplication is discovered. Seems complicated
82 /************************************************************************/
85 start_peer_connection(id)
86 char *id; /* null terminated string */
88 register CONNECTION con; /* the connection we're */
94 * Try to allocate a connection and fill it in with null values.
100 * In this implementation, we use a single fd for both inbound and
101 * outbound traffic. Try to connect to other side. If that
102 * doesn't work, wait to accept a connection from the other side.
103 * Current implementation of this is synchronous--may be a problem?
104 * Also note timing window bug in the following. If the two peers
105 * are started at just about the same time, the race may not be handled
106 * propoerly. If the connections come up, then verify the level of
107 * protocol being observed on the connections. If incompatible,
108 * then turn off the connection.
111 if(!g_try_connecting(con,id)) {
112 g_try_accepting(con,id);
113 if(con->status == CON_STARTING)
114 g_ver_iprotocol(con);
116 if(con->status == CON_STARTING)
117 g_ver_oprotocol(con);
120 if (con->status == CON_UP) {
122 * We've successfully started the connection, now mark
123 * it for non-blocking I/O. Also, update the high water
124 * mark of fd's controlled by our system.
127 if(ioctl(con->in.fd, FIONBIO, (char *)&nb)== (-1)) {
128 g_stop_with_errno(con);
131 if (con->in.fd +1 > gdb_mfd)
132 gdb_mfd = con->in.fd + 1;
134 * Allocate a buffer, if necessary, and reset buffer pointers
135 * so first request will result in a long read into the buffer
137 g_allocate_connection_buffers(con);
144 /************************************************************************/
148 /* Internal routine to allocate a new connection structure and
149 /* initialize all its fields to logical null values.
151 /************************************************************************/
156 register CONNECTION con;
159 * Try to allocate a connection, fatal error if none available
161 con = gdb_allocate_connection();
163 GDB_GIVEUP("start_peer_connection: Tried to allocate too many connections") /* <==RECOVERABLE */
166 * Give the fields their initial values
174 \f/************************************************************************/
178 /* Sets a connection descriptor to have all null values in
179 /* its fields. This routine does NOT do any of the cleanup
180 /* which is necessary after the connection has really been used.
182 /************************************************************************/
189 * Initialize the connection control data structure.
191 con->id = GDB_CON_ID;
192 con->status = CON_STARTING;
193 con->oob_fcn = NULL; /* out of band signalling */
194 /* is not currently */
196 con->errno = 0; /* system errno gets */
197 /* copied here iff it */
198 /* causes this con to die */
200 * Initialize input half connection to null state before trying
203 con->in.status = OP_NOT_STARTED;
206 con->in.op_q_first = (struct oper_data *)&con->in;
207 con->in.op_q_last = (struct oper_data *)&con->in;
208 con->in.next_byte = NULL;
209 con->in.remaining = 0;
213 * Initialize output half connection to null state before trying
216 con->out.status = OP_NOT_STARTED;
218 con->out.oob_fd = -1;
219 con->out.op_q_first = (struct oper_data *)&con->out;
220 con->out.op_q_last = (struct oper_data *)&con->out;
221 con->out.next_byte = NULL;
222 con->out.remaining = 0;
230 /************************************************************************/
232 /* gdb_allocate_connection
234 /* Return an unused entry in the connection array. Unused entries
235 /* are recognized by being marked as CON_STOPPED.
237 /* Note that gdb_mcons is the number of descriptors which have
238 /* ever been used (i.e. a high water mark), so status fields
239 /* are invalid above that.
241 /************************************************************************/
244 gdb_allocate_connection()
246 register int i; /* index of next one */
250 * First look for one below the high water mark
252 for(i=0; i<gdb_mcons; i++) {
253 if (gdb_cons[i].status == CON_STOPPED)
258 * Allocate one which has never been used, if possible
261 if (i>=GDB_MAX_CONNECTIONS)
262 GDB_GIVEUP("gdb: tried to allocate too many simulataneous connections.\n, See GDB_MAX_CONNECTIONS in gdb.h.") /* <==RECOVERABLE */
264 gdb_mcons++; /* bump the high water mark */
265 gdb_cons[i].status = CON_STOPPED; /* initialize status of the */
267 return &gdb_cons[i]; /* return new highest con */
271 /************************************************************************/
275 /* Try to start a connection to the designated site, filling
276 /* in the appropriate information in the connection descriptor
277 /* if successful. Return TRUE if connection succeeded or if
278 /* error was fatal enough that we shouldn't try accepting. Returns
279 /* FALSE if we should try accepting.
281 /************************************************************************/
285 g_try_connecting(con,id)
289 int peer; /* socket for talking to
291 struct sockaddr_in target; /* build the peer address */
293 struct hostent *peer_host; /* host where peer is */
295 /*----------------------------------------------------------*/
297 /* Make sure connection is marked stopped until we
300 /*----------------------------------------------------------*/
302 con->status = CON_STOPPED;
304 /*----------------------------------------------------------*/
306 /* Find out host where peer is, and validate it. Take
307 /* care of port at the same time.
309 /*----------------------------------------------------------*/
311 bzero((char *)&target, sizeof(target));
312 g_parse_target(id, &peer_host, &target.sin_port);
313 if (peer_host == NULL) {
314 fprintf(gdb_log,"gdb: g_try_connecting... '%s' is not a valid host:server\n",
316 return TRUE; /* so we won't try accepting */
319 /*----------------------------------------------------------*/
323 /*----------------------------------------------------------*/
325 peer = socket(AF_INET, SOCK_STREAM, 0);
327 g_stop_with_errno(con);
328 return TRUE; /* fatal error */
331 /*----------------------------------------------------------*/
333 /* Get information and bind socket using well known
334 /* port (BUG: this restricts us to one pair of peers
335 /* per host pair, as well as being bad practice on
336 /* the network. It will do for debugging.
338 /*----------------------------------------------------------*/
341 bcopy(peer_host->h_addr, (char *)&target.sin_addr, peer_host->h_length);
342 target.sin_family = peer_host->h_addrtype;
344 /*----------------------------------------------------------*/
346 /* Make the connection
348 /*----------------------------------------------------------*/
350 if(connect(peer, (struct sockaddr *)&target, sizeof(target)) < 0) {
351 if (errno == ECONNREFUSED)
352 return FALSE; /* other side not yet */
353 /* up, but no other fatal */
356 gdb_perror("gdb: unexpected error connecting");
357 g_stop_with_errno(con);
362 /*----------------------------------------------------------*/
364 /* The connection has been made, fill in the connection
365 /* control data structure.
367 /*----------------------------------------------------------*/
371 con->status = CON_STARTING;
377 /************************************************************************/
381 /* For a given server or peer i.d., figure out the host and the
382 /* port. Arguments are:
384 /* string i.d. of the server, which is
385 /* in one of two forms:
387 /* host:servicename (where service name must not begin
390 /* host:#portnumber (where portnumber is the actual
391 /* number of the port to be used)
393 /* (actually, a 3rd form, with no port number supplied,
394 /* will use a default GDB_PORT, but this is unsafe
395 /* and it will be disabled in production versions
396 /* of the gdb system.)
398 /* **hostent: returned to indicate host to be used. Null
399 /* if host could not be found
401 /* *port pointer to an integer where the port number will
402 /* be put. We return the port number in network
405 /************************************************************************/
408 g_parse_target(id, host, port)
410 struct hostent **host;
413 char buffer[256]; /* longest host name */
414 register char *ip, *bp; /* for copying name */
415 struct servent *serv; /* returned from */
416 /* get service by name */
418 /*----------------------------------------------------------*/
420 /* copy the host name part only to local buffer
422 /*----------------------------------------------------------*/
427 while (*ip != '\0' && *ip != ':')
431 /*----------------------------------------------------------*/
433 /* Look up the host name, return if bad.
435 /*----------------------------------------------------------*/
437 *host = gethostbyname(buffer);
442 /*----------------------------------------------------------*/
444 /* Set up the port address
446 /*----------------------------------------------------------*/
460 * port number supplied explictly
463 if (*ip < '0' || *ip>'9') {
467 *port = htons((u_short)atoi(ip));
470 * service identified by name
472 serv = getservbyname(ip, "tcp");
477 *port = serv->s_port;
481 /************************************************************************/
485 /* Try to accept a connection to the designated site, filling
486 /* in the appropriate information in the connection descriptor
489 /************************************************************************/
492 g_try_accepting(con,id)
496 int slisten; /* socket on which
497 we listen for connections */
499 int peer; /* socket for talking to
502 struct sockaddr_in self, from;
503 int retries = GDB_BIND_RETRY_COUNT;
504 int onoff = 1; /* used as argument to */
507 struct hostent *peer_host; /* host where peer is */
509 /*----------------------------------------------------------*/
511 /* Make sure connection is marked stopped until we
514 /*----------------------------------------------------------*/
516 con->status = CON_STOPPED;
518 /*----------------------------------------------------------*/
520 /* Create a socket on which to listen. Tell it that
521 /* it's OK to re-use the port address, which may still
522 /* appear busy if connections are taking awhile to go
525 /*----------------------------------------------------------*/
527 slisten = socket(AF_INET, SOCK_STREAM, 0);
529 gdb_perror("g_try_accepting: error creating listen socket");
530 g_stop_with_errno(con);
533 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0, 0)<0)
534 /* that didn't work, try 4.3 */
535 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
536 (char *)&onoff, sizeof(int)) <0)
537 GDB_GIVEUP("g_try_accepting: could not set SO_REUSEADDR");
539 /*----------------------------------------------------------*/
541 /* Find out host where peer is, and validate it. Take
542 /* care of port at the same time. This is redundant
543 /* given that g_try_connecting is always called first.
545 /*----------------------------------------------------------*/
547 bzero((char *)&self, sizeof(self));
548 g_parse_target(id, &peer_host, &self.sin_port);
549 if (peer_host == NULL) {
550 GDB_GIVEUP("gdb_try_accepting: bad port not caught by try connecting")
553 /*----------------------------------------------------------*/
555 /* Bind the socket to ourselves, using the well known
556 /* port (See bug note in g_try_connecting.
558 /* This code should really go in initialization, I think.
560 /*----------------------------------------------------------*/
562 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
563 if (errno == EADDRINUSE && retries--) {
564 fprintf(gdb_log,"gdb: port address in use, will retry %d more time(s)\n",retries+1);
565 sleep(GDB_BIND_RETRY_INTERVAL);
568 gdb_perror("gdb: error binding listen socket");
569 g_stop_with_errno(con);
570 (void) close(slisten);
575 /*----------------------------------------------------------*/
577 /* Listen for connections.
579 /*----------------------------------------------------------*/
581 (void) listen (slisten, 5); /* does not block, just */
582 /* sets the maximum backlog */
583 /* of pending non-accepted */
585 fromlen = sizeof(from);
586 peer = accept(slisten, &from, &fromlen);
588 g_stop_with_errno(con);
589 gdb_perror("gdb_try_accepting: error accepting connection");
590 (void) close(slisten);
594 (void) close (slisten); /* we're not using the */
595 /* listening socket */
596 /* anymore, only the */
597 /* connection to the peer */
599 /*----------------------------------------------------------*/
601 /* The connection has been made, fill in the connection
602 /* control data structure.
604 /*----------------------------------------------------------*/
608 con->status = CON_STARTING;
611 /************************************************************************/
615 /* Called when an outbound connection is started to verify
616 /* the version of the protocol being observed.
618 /************************************************************************/
624 #ifdef VERIFY_PROTOCOL
625 char ver = GDB_PROTOCOL_VERSION;
629 int onoff = 0; /* for ioctl to turn off */
632 * Because the connection was accepted on a non-blocking
633 * listening socket, the connection itself may be non-blocking.
634 * We can't tolerate that here. It will be reset later.
636 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
637 g_stop_with_errno(con);
638 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
642 while (write(con->out.fd, &ver, 1) < 0) {
643 g_stop_with_errno(con);
648 len = read(con->in.fd, &theirs, 1);
650 g_stop_with_errno(con);
656 con->status = CON_UP;
658 con->status = CON_STOPPED;
659 #else !VERIFY_PROTOCOL
660 con->status = CON_UP;
661 #endif !VERIFY_PROTOCOL
664 /************************************************************************/
668 /* Called when an inbound connection is started to verify
669 /* the version of the protocol being observed.
671 /************************************************************************/
677 #ifdef VERIFY_PROTOCOL
678 char ver = GDB_PROTOCOL_VERSION;
682 int onoff = 0; /* for ioctl to turn off */
685 * Because the connection was accepted on a non-blocking
686 * listening socket, the connection itself may be non-blocking.
687 * We can't tolerate that here. It will be reset later.
689 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
690 g_stop_with_errno(con);
691 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
696 len = read(con->in.fd, &theirs, 1);
698 g_stop_with_errno(con);
704 con->status = CON_UP;
706 con->status = CON_STOPPED;
708 while (write(con->out.fd, &ver, 1) < 0) {
709 g_stop_with_errno(con);
712 #else !VERIFY_PROTOCOL
713 con->status = CON_UP;
718 /************************************************************************/
720 /* sever_connection (sever_connection)
722 /* Unconditionally, but cleanly, terminates a connection. All
723 /* pending operations on the connection are cancelled, and the
724 /* file descriptor for the connection is closed. This routine
725 /* should be called directly from applications wishing to shut
726 /* down a connection. No transmissions are attempted
727 /* by this routine. Returns NULL, in the hope that applications
728 /* will assign this to their old CONNECTION variable.
730 /************************************************************************/
733 sever_connection(con)
738 GDB_CHECK_CON(con, "sever_connection")
739 if (con->status == CON_UP || con->status == CON_STARTING)
740 g_stop_connection(con);
741 if (con->status != CON_STOPPED)
742 gdb_de_allocate_connection(con);
747 /************************************************************************/
751 /* This connection is stopping because of a problem on a syscall.
752 /* We record the errno in the connection descriptor for inspection
753 /* by the application, then stop the connection.
755 /************************************************************************/
759 g_stop_with_errno(con)
763 g_stop_connection(con);
767 /************************************************************************/
771 /* Unconditionally, but cleanly, terminates a connection. All
772 /* pending operations on the connection are cancelled, and the
773 /* file descriptor for the connection is closed. This routine is
774 /* for internal use. Applications call sever_connection, which
775 /* also de_allocates the descriptor. No transmissions are attempted
778 /************************************************************************/
781 g_stop_connection(con)
785 * Shutdown activity on the two half connections.
787 g_cleanup_half_connection(&(con->in));
788 g_cleanup_half_connection(&(con->out));
791 * Remove the file descriptor from the select bit maps
793 if (!(con->in.flags & HCON_UNUSED))
794 FD_CLR(con->in.fd, &gdb_crfds);
795 if (!(con->out.flags & HCON_UNUSED))
796 FD_CLR(con->out.fd, &gdb_cwfds);
798 * Close the file descriptor. Note, this presumes that in fact
799 * 1) in is never the unused half and
800 * 2) when the connection is bi-directional, in and out share an
801 * fd. We could do with a more elaborate scheme to control
802 * this in the future.
804 (void) close(con->in.fd);
807 * Mark the connection as stopping. We can't reclaim the
808 * descriptor until the application does a sever, or else there
809 * would be a risk of re-allocating it out from under the application.
812 con->status = CON_STOPPING;
818 /************************************************************************/
820 /* gdb_de_allocate_connection
822 /* Return a connection whose file descriptors have been closed
825 /************************************************************************/
828 gdb_de_allocate_connection(con)
833 con->status = CON_STOPPED;
835 i = gdb_mcons-1; /* start at last one used */
838 * Reset gdb_mcons to be the number of connections in use
840 while (i>=0 && gdb_cons[i].status == CON_STOPPED)
846 /************************************************************************/
848 /* g_cleanup_half_conection
850 /* Terminate all pending operations on the supplied half
851 /* connection. Note that the algorithm used here presumes
852 /* that cancel_operation will de-queue the operation descriptor,
853 /* therefore we have to be careful here about when we look at
856 /************************************************************************/
859 g_cleanup_half_connection(hcon)
860 HALF_CONNECTION hcon;
862 OPERATION current, next;
864 current = hcon->op_q_first;
867 * Loop through all operations in the queue canceling them.
868 * Make sure to pick up pointer to 'next' before the current
869 * one is canceled, as cancelling may invalidate the pointer.
872 while (current != (OPERATION)hcon) {
873 next = current->next;
874 (void) cancel_operation(current);
879 /************************************************************************/
881 /* create_listening_connection (create_listening_connection)
883 /* Starts a special type of connection which is used to listen
884 /* for incoming connection requests. The inbound half-connection
885 /* is the only one used for this special kind of connection.
887 /* It is the user's responsibility to insure that only appropriate
888 /* types of operation are queued on a connection of this sort. In
889 /* general, these connections are intended for internal use by
890 /* GDB, and they are not intended to be visible to servers or
893 /* The id supplied should be in one of two forms. If just a
894 /* string is supplied then it is presumed to be the name of
895 /* a registered tcp service. If the name begins with a #, then
896 /* the rest is interpreted as the integer port number to be used.
898 /* In future implementations, the id may have more structure, which
899 /* is why we define it as a string.
901 /************************************************************************/
904 create_listening_connection(id)
907 register CONNECTION con; /* the connection we're */
910 register int slisten; /* socket on which
911 we listen for connections */
913 struct sockaddr_in self;
914 int retries = GDB_BIND_RETRY_COUNT;
915 int onoff = 1; /* used as argument to */
917 struct servent *serv;
922 * Try to allocate a connection and fill it in with null values.
928 * Try to create a socket for listening
930 con->in.fd = socket(AF_INET, SOCK_STREAM, 0);
931 slisten = con->in.fd; /* easier and faster than */
932 /* using con->in.fd all the */
935 gdb_perror("create_listening_connection: error creating listen socket");
936 (void) g_stop_with_errno(con);
940 * Set options so the listening address can be re-used (this
941 * has its dangers, but otherwise we can't restart our servers
942 * for long periods after they crash because of connections which
943 * take a long to time clean up and hold ports in use.)
947 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0,0)<0)
948 /* that didn't work, try 4.3 */
949 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
950 (char *)&onoff, sizeof(int)) <0)
951 GDB_GIVEUP("create_listening_connection: could not set SO_REUSEADDR")
954 * Make the listening socket non-blocking so we won't have to do
955 * selects before polling it (change made by Bill Sommerfeld - wesommer)
957 if (ioctl(slisten, FIONBIO, (char *)&onoff) < 0) { /*<==FIX,,,add comment */
958 g_stop_with_errno(con);
959 gdb_perror("ioctl for listening socket");
962 /*----------------------------------------------------------*/
964 /* Bind the socket to ourselves, using port derived from
965 /* the supplied id string.
967 /*----------------------------------------------------------*/
969 bzero((char *)&self, sizeof(self));
971 * Determine our port number
974 self.sin_port = htons((u_short)atoi(id+1));
976 serv = getservbyname(id, "tcp");
978 fprintf(gdb_log,"gdb create_listening_connection: cannot become service named %s\n",id);
979 return NULL; /* BUG: causes connetion */
980 /* descriptor leakage. Should */
981 /* return an error code in */
982 /* the connection descriptor*/
984 self.sin_port = serv->s_port;
988 * Try and re-try the bind until it works or until retry count
991 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
992 if (errno == EADDRINUSE && retries--) {
993 fprintf(gdb_log,"gdb create_listening_connection: port address in use, will retry %d more time(s)\n",retries+1);
994 sleep(GDB_BIND_RETRY_INTERVAL);
997 gdb_perror("gdb create_listening_connection: error binding listen socket");
998 g_stop_with_errno(con);
1003 /*----------------------------------------------------------*/
1005 /* Listen for connections.
1007 /*----------------------------------------------------------*/
1009 (void) listen (slisten, 5); /* does not block, just */
1010 /* sets the maximum backlog */
1011 /* of pending non-accepted */
1014 con->in.flags |= HCON_LISTEN;
1015 con->out.flags |= HCON_UNUSED;
1016 con->status = CON_UP;
1017 if (con->in.fd +1 > gdb_mfd)
1018 gdb_mfd = con->in.fd + 1;
1022 /************************************************************************/
1024 /* g_allocate_connection_buffers
1026 /* Create a buffer which can be used to receive large
1027 /* chunks of data from the socket. This is currently done only
1028 /* on the inbound half connection. Also, the buffers are not freed
1029 /* once allocated, even if the connection descriptor is re-used.
1031 /************************************************************************/
1034 g_allocate_connection_buffers(con)
1037 HALF_CONNECTION inbound = &(con->in);
1040 * See if there is already one allocated, if not, allocate one.
1042 if (inbound->stream_buffer == (char *)NULL) {
1043 inbound->stream_buffer =
1044 db_alloc(inbound->stream_buffer_length);
1048 * In any case, make sure that it is effectively empty
1050 inbound -> stream_buffer_next = inbound -> stream_buffer;
1051 inbound -> stream_buffer_remaining = 0;