7 static char *rcsid_gdb_conn_c = "$Header$";
33 /************************************************************************/
37 /* GDB - Connection Management Services
39 /* Author: Noah Mendelsohn
40 /* Copyright: 1986 MIT Project Athena
41 /* For copying and distribution information, please see
42 /* the file <mit-copyright.h>.
44 /* Routines used in the creation and maintenance of CONNECTIONS.
45 /* Note: these are closely related to the services provided
46 /* by gdb_trans.c and gdb_trans2.c.
49 /************************************************************************/
51 #include <mit-copyright.h>
55 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <sys/ioctl.h>
59 #include <netinet/in.h>
65 extern u_short htons(); /* ?? All versions? */
68 CONNECTION gdb_allocate_connection();
70 /************************************************************************/
72 /* start_peer_connection (start_peer_connection)
74 /* Starts a connection to another process which itself will be
75 /* issuing a start_peer_connection to us. Current implementation
76 /* builds at most one stream, with the risk of a hang if
77 /* the attempts to connect cross in the night. This is a bug,
78 /* but this level of support is acceptable for casual debugging
79 /* of applications, and perhaps for some production use in
80 /* controlled settings. I think the only other way to do it
81 /* is to risk building two streams in parallel, possibly tearing
82 /* one down when the duplication is discovered. Seems complicated
85 /************************************************************************/
88 start_peer_connection(id)
89 char *id; /* null terminated string */
91 register CONNECTION con; /* the connection we're */
97 * Try to allocate a connection and fill it in with null values.
103 * In this implementation, we use a single fd for both inbound and
104 * outbound traffic. Try to connect to other side. If that
105 * doesn't work, wait to accept a connection from the other side.
106 * Current implementation of this is synchronous--may be a problem?
107 * Also note timing window bug in the following. If the two peers
108 * are started at just about the same time, the race may not be handled
109 * propoerly. If the connections come up, then verify the level of
110 * protocol being observed on the connections. If incompatible,
111 * then turn off the connection.
114 if(!g_try_connecting(con,id)) {
115 g_try_accepting(con,id);
116 if(con->status == CON_STARTING)
117 g_ver_iprotocol(con);
119 if(con->status == CON_STARTING)
120 g_ver_oprotocol(con);
123 if (con->status == CON_UP) {
125 * We've successfully started the connection, now mark
126 * it for non-blocking I/O. Also, update the high water
127 * mark of fd's controlled by our system.
130 if(ioctl(con->in.fd, FIONBIO, (char *)&nb)== (-1)) {
131 g_stop_with_errno(con);
134 if (con->in.fd +1 > gdb_mfd)
135 gdb_mfd = con->in.fd + 1;
137 * Allocate a buffer, if necessary, and reset buffer pointers
138 * so first request will result in a long read into the buffer
140 g_allocate_connection_buffers(con);
147 /************************************************************************/
151 /* Internal routine to allocate a new connection structure and
152 /* initialize all its fields to logical null values.
154 /************************************************************************/
159 register CONNECTION con;
162 * Try to allocate a connection, fatal error if none available
164 con = gdb_allocate_connection();
166 GDB_GIVEUP("start_peer_connection: Tried to allocate too many connections") /* <==RECOVERABLE */
169 * Give the fields their initial values
177 \f/************************************************************************/
181 /* Sets a connection descriptor to have all null values in
182 /* its fields. This routine does NOT do any of the cleanup
183 /* which is necessary after the connection has really been used.
185 /************************************************************************/
192 * Initialize the connection control data structure.
194 con->id = GDB_CON_ID;
195 con->status = CON_STARTING;
196 con->oob_fcn = NULL; /* out of band signalling */
197 /* is not currently */
199 con->errno = 0; /* system errno gets */
200 /* copied here iff it */
201 /* causes this con to die */
203 * Initialize input half connection to null state before trying
206 con->in.status = OP_NOT_STARTED;
209 con->in.op_q_first = (struct oper_data *)&con->in;
210 con->in.op_q_last = (struct oper_data *)&con->in;
211 con->in.next_byte = NULL;
212 con->in.remaining = 0;
216 * Initialize output half connection to null state before trying
219 con->out.status = OP_NOT_STARTED;
221 con->out.oob_fd = -1;
222 con->out.op_q_first = (struct oper_data *)&con->out;
223 con->out.op_q_last = (struct oper_data *)&con->out;
224 con->out.next_byte = NULL;
225 con->out.remaining = 0;
233 /************************************************************************/
235 /* gdb_allocate_connection
237 /* Return an unused entry in the connection array. Unused entries
238 /* are recognized by being marked as CON_STOPPED.
240 /* Note that gdb_mcons is the number of descriptors which have
241 /* ever been used (i.e. a high water mark), so status fields
242 /* are invalid above that.
244 /************************************************************************/
247 gdb_allocate_connection()
249 register int i; /* index of next one */
253 * First look for one below the high water mark
255 for(i=0; i<gdb_mcons; i++) {
256 if (gdb_cons[i].status == CON_STOPPED)
261 * Allocate one which has never been used, if possible
264 if (i>=GDB_MAX_CONNECTIONS)
265 GDB_GIVEUP("gdb: tried to allocate too many simulataneous connections.\n, See GDB_MAX_CONNECTIONS in gdb.h.") /* <==RECOVERABLE */
267 gdb_mcons++; /* bump the high water mark */
268 gdb_cons[i].status = CON_STOPPED; /* initialize status of the */
270 return &gdb_cons[i]; /* return new highest con */
274 /************************************************************************/
278 /* Try to start a connection to the designated site, filling
279 /* in the appropriate information in the connection descriptor
280 /* if successful. Return TRUE if connection succeeded or if
281 /* error was fatal enough that we shouldn't try accepting. Returns
282 /* FALSE if we should try accepting.
284 /************************************************************************/
288 g_try_connecting(con,id)
292 int peer; /* socket for talking to
294 int on = 1; /* flag for ioctl */
295 struct sockaddr_in target; /* build the peer address */
297 struct hostent *peer_host; /* host where peer is */
299 /*----------------------------------------------------------*/
301 /* Make sure connection is marked stopped until we
304 /*----------------------------------------------------------*/
306 con->status = CON_STOPPED;
308 /*----------------------------------------------------------*/
310 /* Find out host where peer is, and validate it. Take
311 /* care of port at the same time.
313 /*----------------------------------------------------------*/
315 bzero((char *)&target, sizeof(target));
316 g_parse_target(id, &peer_host, &target.sin_port);
317 if (peer_host == NULL) {
318 fprintf(gdb_log,"gdb: g_try_connecting... '%s' is not a valid host:server\n",
320 return TRUE; /* so we won't try accepting */
323 /*----------------------------------------------------------*/
327 /*----------------------------------------------------------*/
329 peer = socket(AF_INET, SOCK_STREAM, 0);
331 g_stop_with_errno(con);
332 return TRUE; /* fatal error */
335 /*----------------------------------------------------------*/
337 /* Get information and bind socket using well known
338 /* port (BUG: this restricts us to one pair of peers
339 /* per host pair, as well as being bad practice on
340 /* the network. It will do for debugging.
342 /*----------------------------------------------------------*/
345 bcopy(peer_host->h_addr, (char *)&target.sin_addr, peer_host->h_length);
346 target.sin_family = peer_host->h_addrtype;
348 /*----------------------------------------------------------*/
350 /* Make the connection
352 /*----------------------------------------------------------*/
354 if(connect(peer, (struct sockaddr *)&target, sizeof(target)) < 0) {
355 if (errno == ECONNREFUSED)
356 return FALSE; /* other side not yet */
357 /* up, but no other fatal */
360 gdb_perror("gdb: unexpected error connecting");
361 g_stop_with_errno(con);
366 if ((gdb_Options & GDB_OPT_KEEPALIVE) &&
367 setsockopt(peer, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0) {
368 gdb_perror("gdb: unable to start keepalives");
369 g_stop_with_errno(con);
373 /*----------------------------------------------------------*/
375 /* The connection has been made, fill in the connection
376 /* control data structure.
378 /*----------------------------------------------------------*/
382 con->status = CON_STARTING;
388 /************************************************************************/
392 /* For a given server or peer i.d., figure out the host and the
393 /* port. Arguments are:
395 /* string i.d. of the server, which is
396 /* in one of two forms:
398 /* host:servicename (where service name must not begin
401 /* host:#portnumber (where portnumber is the actual
402 /* number of the port to be used)
404 /* (actually, a 3rd form, with no port number supplied,
405 /* will use a default GDB_PORT, but this is unsafe
406 /* and it will be disabled in production versions
407 /* of the gdb system.)
409 /* **hostent: returned to indicate host to be used. Null
410 /* if host could not be found
412 /* *port pointer to an integer where the port number will
413 /* be put. We return the port number in network
416 /************************************************************************/
419 g_parse_target(id, host, port)
421 struct hostent **host;
424 char buffer[256]; /* longest host name */
425 register char *ip, *bp; /* for copying name */
426 struct servent *serv; /* returned from */
427 /* get service by name */
429 /*----------------------------------------------------------*/
431 /* copy the host name part only to local buffer
433 /*----------------------------------------------------------*/
438 while (*ip != '\0' && *ip != ':')
442 /*----------------------------------------------------------*/
444 /* Look up the host name, return if bad.
446 /*----------------------------------------------------------*/
448 *host = gethostbyname(buffer);
453 /*----------------------------------------------------------*/
455 /* Set up the port address
457 /*----------------------------------------------------------*/
471 * port number supplied explictly
474 if (*ip < '0' || *ip>'9') {
478 *port = htons((u_short)atoi(ip));
481 * service identified by name
483 serv = getservbyname(ip, "tcp");
488 *port = serv->s_port;
492 /************************************************************************/
496 /* Try to accept a connection to the designated site, filling
497 /* in the appropriate information in the connection descriptor
500 /************************************************************************/
503 g_try_accepting(con,id)
507 int slisten; /* socket on which
508 we listen for connections */
510 int peer; /* socket for talking to
513 struct sockaddr_in self, from;
514 int retries = GDB_BIND_RETRY_COUNT;
515 int onoff = 1; /* used as argument to */
518 struct hostent *peer_host; /* host where peer is */
520 /*----------------------------------------------------------*/
522 /* Make sure connection is marked stopped until we
525 /*----------------------------------------------------------*/
527 con->status = CON_STOPPED;
529 /*----------------------------------------------------------*/
531 /* Create a socket on which to listen. Tell it that
532 /* it's OK to re-use the port address, which may still
533 /* appear busy if connections are taking awhile to go
536 /*----------------------------------------------------------*/
538 slisten = socket(AF_INET, SOCK_STREAM, 0);
540 gdb_perror("g_try_accepting: error creating listen socket");
541 g_stop_with_errno(con);
544 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0, 0)<0)
545 /* that didn't work, try 4.3 */
546 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
547 (char *)&onoff, sizeof(int)) <0)
548 GDB_GIVEUP("g_try_accepting: could not set SO_REUSEADDR");
550 /*----------------------------------------------------------*/
552 /* Find out host where peer is, and validate it. Take
553 /* care of port at the same time. This is redundant
554 /* given that g_try_connecting is always called first.
556 /*----------------------------------------------------------*/
558 bzero((char *)&self, sizeof(self));
559 g_parse_target(id, &peer_host, &self.sin_port);
560 if (peer_host == NULL) {
561 GDB_GIVEUP("gdb_try_accepting: bad port not caught by try connecting")
564 /*----------------------------------------------------------*/
566 /* Bind the socket to ourselves, using the well known
567 /* port (See bug note in g_try_connecting.
569 /* This code should really go in initialization, I think.
571 /*----------------------------------------------------------*/
573 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
574 if (errno == EADDRINUSE && retries--) {
575 fprintf(gdb_log,"gdb: port address in use, will retry %d more time(s)\n",retries+1);
576 sleep(GDB_BIND_RETRY_INTERVAL);
579 gdb_perror("gdb: error binding listen socket");
580 g_stop_with_errno(con);
581 (void) close(slisten);
586 /*----------------------------------------------------------*/
588 /* Listen for connections.
590 /*----------------------------------------------------------*/
592 (void) listen (slisten, 5); /* does not block, just */
593 /* sets the maximum backlog */
594 /* of pending non-accepted */
596 fromlen = sizeof(from);
597 peer = accept(slisten, &from, &fromlen);
599 g_stop_with_errno(con);
600 gdb_perror("gdb_try_accepting: error accepting connection");
601 (void) close(slisten);
605 (void) close (slisten); /* we're not using the */
606 /* listening socket */
607 /* anymore, only the */
608 /* connection to the peer */
610 /*----------------------------------------------------------*/
612 /* The connection has been made, fill in the connection
613 /* control data structure.
615 /*----------------------------------------------------------*/
619 con->status = CON_STARTING;
622 /************************************************************************/
626 /* Called when an outbound connection is started to verify
627 /* the version of the protocol being observed.
629 /************************************************************************/
635 #ifdef VERIFY_PROTOCOL
636 char ver = GDB_PROTOCOL_VERSION;
640 int onoff = 0; /* for ioctl to turn off */
643 * Because the connection was accepted on a non-blocking
644 * listening socket, the connection itself may be non-blocking.
645 * We can't tolerate that here. It will be reset later.
647 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
648 g_stop_with_errno(con);
649 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
653 while (write(con->out.fd, &ver, 1) < 0) {
654 g_stop_with_errno(con);
659 len = read(con->in.fd, &theirs, 1);
661 g_stop_with_errno(con);
667 con->status = CON_UP;
669 con->status = CON_STOPPED;
670 #else !VERIFY_PROTOCOL
671 con->status = CON_UP;
672 #endif !VERIFY_PROTOCOL
675 /************************************************************************/
679 /* Called when an inbound connection is started to verify
680 /* the version of the protocol being observed.
682 /************************************************************************/
688 #ifdef VERIFY_PROTOCOL
689 char ver = GDB_PROTOCOL_VERSION;
693 int onoff = 0; /* for ioctl to turn off */
696 * Because the connection was accepted on a non-blocking
697 * listening socket, the connection itself may be non-blocking.
698 * We can't tolerate that here. It will be reset later.
700 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
701 g_stop_with_errno(con);
702 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
707 len = read(con->in.fd, &theirs, 1);
709 g_stop_with_errno(con);
715 con->status = CON_UP;
717 con->status = CON_STOPPED;
719 while (write(con->out.fd, &ver, 1) < 0) {
720 g_stop_with_errno(con);
723 #else !VERIFY_PROTOCOL
724 con->status = CON_UP;
729 /************************************************************************/
731 /* sever_connection (sever_connection)
733 /* Unconditionally, but cleanly, terminates a connection. All
734 /* pending operations on the connection are cancelled, and the
735 /* file descriptor for the connection is closed. This routine
736 /* should be called directly from applications wishing to shut
737 /* down a connection. No transmissions are attempted
738 /* by this routine. Returns NULL, in the hope that applications
739 /* will assign this to their old CONNECTION variable.
741 /************************************************************************/
744 sever_connection(con)
749 GDB_CHECK_CON(con, "sever_connection")
750 if (con->status == CON_UP || con->status == CON_STARTING)
751 g_stop_connection(con);
752 if (con->status != CON_STOPPED)
753 gdb_de_allocate_connection(con);
758 /************************************************************************/
762 /* This connection is stopping because of a problem on a syscall.
763 /* We record the errno in the connection descriptor for inspection
764 /* by the application, then stop the connection.
766 /************************************************************************/
770 g_stop_with_errno(con)
774 g_stop_connection(con);
778 /************************************************************************/
782 /* Unconditionally, but cleanly, terminates a connection. All
783 /* pending operations on the connection are cancelled, and the
784 /* file descriptor for the connection is closed. This routine is
785 /* for internal use. Applications call sever_connection, which
786 /* also de_allocates the descriptor. No transmissions are attempted
789 /************************************************************************/
792 g_stop_connection(con)
796 * Shutdown activity on the two half connections.
798 g_cleanup_half_connection(&(con->in));
799 g_cleanup_half_connection(&(con->out));
802 * Remove the file descriptor from the select bit maps
804 if (!(con->in.flags & HCON_UNUSED) && con->in.fd >= 0)
805 FD_CLR(con->in.fd, &gdb_crfds);
806 if (!(con->out.flags & HCON_UNUSED) && con->out.fd >= 0)
807 FD_CLR(con->out.fd, &gdb_cwfds);
809 * Close the file descriptor. Note, this presumes that in fact
810 * 1) in is never the unused half and
811 * 2) when the connection is bi-directional, in and out share an
812 * fd. We could do with a more elaborate scheme to control
813 * this in the future.
815 (void) close(con->in.fd);
818 * Mark the connection as stopping. We can't reclaim the
819 * descriptor until the application does a sever, or else there
820 * would be a risk of re-allocating it out from under the application.
823 con->status = CON_STOPPING;
829 /************************************************************************/
831 /* gdb_de_allocate_connection
833 /* Return a connection whose file descriptors have been closed
836 /************************************************************************/
839 gdb_de_allocate_connection(con)
844 con->status = CON_STOPPED;
846 i = gdb_mcons-1; /* start at last one used */
849 * Reset gdb_mcons to be the number of connections in use
851 while (i>=0 && gdb_cons[i].status == CON_STOPPED)
857 /************************************************************************/
859 /* g_cleanup_half_conection
861 /* Terminate all pending operations on the supplied half
862 /* connection. Note that the algorithm used here presumes
863 /* that cancel_operation will de-queue the operation descriptor,
864 /* therefore we have to be careful here about when we look at
867 /************************************************************************/
870 g_cleanup_half_connection(hcon)
871 HALF_CONNECTION hcon;
873 OPERATION current, next;
875 current = hcon->op_q_first;
878 * Loop through all operations in the queue canceling them.
879 * Make sure to pick up pointer to 'next' before the current
880 * one is canceled, as cancelling may invalidate the pointer.
883 while (current != (OPERATION)hcon) {
884 next = current->next;
885 (void) cancel_operation(current);
890 /************************************************************************/
892 /* create_listening_connection (create_listening_connection)
894 /* Starts a special type of connection which is used to listen
895 /* for incoming connection requests. The inbound half-connection
896 /* is the only one used for this special kind of connection.
898 /* It is the user's responsibility to insure that only appropriate
899 /* types of operation are queued on a connection of this sort. In
900 /* general, these connections are intended for internal use by
901 /* GDB, and they are not intended to be visible to servers or
904 /* The id supplied should be in one of two forms. If just a
905 /* string is supplied then it is presumed to be the name of
906 /* a registered tcp service. If the name begins with a #, then
907 /* the rest is interpreted as the integer port number to be used.
909 /* In future implementations, the id may have more structure, which
910 /* is why we define it as a string.
912 /************************************************************************/
915 create_listening_connection(id)
918 register CONNECTION con; /* the connection we're */
921 register int slisten; /* socket on which
922 we listen for connections */
924 struct sockaddr_in self;
925 int retries = GDB_BIND_RETRY_COUNT;
926 int onoff = 1; /* used as argument to */
928 struct servent *serv;
933 * Try to allocate a connection and fill it in with null values.
939 * Try to create a socket for listening
941 con->in.fd = socket(AF_INET, SOCK_STREAM, 0);
942 slisten = con->in.fd; /* easier and faster than */
943 /* using con->in.fd all the */
946 gdb_perror("create_listening_connection: error creating listen socket");
947 (void) g_stop_with_errno(con);
951 * Set options so the listening address can be re-used (this
952 * has its dangers, but otherwise we can't restart our servers
953 * for long periods after they crash because of connections which
954 * take a long to time clean up and hold ports in use.)
958 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0,0)<0)
959 /* that didn't work, try 4.3 */
960 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
961 (char *)&onoff, sizeof(int)) <0)
962 GDB_GIVEUP("create_listening_connection: could not set SO_REUSEADDR")
965 * Make the listening socket non-blocking so we won't have to do
966 * selects before polling it (change made by Bill Sommerfeld - wesommer)
968 if (ioctl(slisten, FIONBIO, (char *)&onoff) < 0) { /*<==FIX,,,add comment */
969 g_stop_with_errno(con);
970 gdb_perror("ioctl for listening socket");
973 /*----------------------------------------------------------*/
975 /* Bind the socket to ourselves, using port derived from
976 /* the supplied id string.
978 /*----------------------------------------------------------*/
980 bzero((char *)&self, sizeof(self));
982 * Determine our port number
985 self.sin_port = htons((u_short)atoi(id+1));
987 serv = getservbyname(id, "tcp");
989 fprintf(gdb_log,"gdb create_listening_connection: cannot become service named %s\n",id);
990 return NULL; /* BUG: causes connetion */
991 /* descriptor leakage. Should */
992 /* return an error code in */
993 /* the connection descriptor*/
995 self.sin_port = serv->s_port;
999 * Try and re-try the bind until it works or until retry count
1002 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
1003 if (errno == EADDRINUSE && retries--) {
1004 fprintf(gdb_log,"gdb create_listening_connection: port address in use, will retry %d more time(s)\n",retries+1);
1005 sleep(GDB_BIND_RETRY_INTERVAL);
1008 gdb_perror("gdb create_listening_connection: error binding listen socket");
1009 g_stop_with_errno(con);
1014 /*----------------------------------------------------------*/
1016 /* Listen for connections.
1018 /*----------------------------------------------------------*/
1020 (void) listen (slisten, 5); /* does not block, just */
1021 /* sets the maximum backlog */
1022 /* of pending non-accepted */
1025 con->in.flags |= HCON_LISTEN;
1026 con->out.flags |= HCON_UNUSED;
1027 con->status = CON_UP;
1028 if (con->in.fd +1 > gdb_mfd)
1029 gdb_mfd = con->in.fd + 1;
1033 /************************************************************************/
1035 /* g_allocate_connection_buffers
1037 /* Create a buffer which can be used to receive large
1038 /* chunks of data from the socket. This is currently done only
1039 /* on the inbound half connection. Also, the buffers are not freed
1040 /* once allocated, even if the connection descriptor is re-used.
1042 /************************************************************************/
1045 g_allocate_connection_buffers(con)
1048 HALF_CONNECTION inbound = &(con->in);
1051 * See if there is already one allocated, if not, allocate one.
1053 if (inbound->stream_buffer == (char *)NULL) {
1054 inbound->stream_buffer =
1055 db_alloc(inbound->stream_buffer_length);
1059 * In any case, make sure that it is effectively empty
1061 inbound -> stream_buffer_next = inbound -> stream_buffer;
1062 inbound -> stream_buffer_remaining = 0;