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);
128 /************************************************************************/
132 /* Internal routine to allocate a new connection structure and
133 /* initialize all its fields to logical null values.
135 /************************************************************************/
140 register CONNECTION con;
143 * Try to allocate a connection, fatal error if none available
145 con = gdb_allocate_connection();
147 GDB_GIVEUP("start_peer_connection: Tried to allocate too many connections") /* <==RECOVERABLE */
150 * Give the fields their initial values
159 /************************************************************************/
163 /* Sets a connection descriptor to have all null values in
164 /* its fields. This routine does NOT do any of the cleanup
165 /* which is necessary after the connection has really been used.
167 /************************************************************************/
174 * Initialize the connection control data structure.
176 con->id = GDB_CON_ID;
177 con->status = CON_STARTING;
178 con->oob_fcn = NULL; /* out of band signalling */
179 /* is not currently */
181 con->errno = 0; /* system errno gets */
182 /* copied here iff it */
183 /* causes this con to die */
185 * Initialize input half connection to null state before trying
188 con->in.status = OP_NOT_STARTED;
191 con->in.op_q_first = (struct oper_data *)&con->in;
192 con->in.op_q_last = (struct oper_data *)&con->in;
193 con->in.next_byte = NULL;
194 con->in.remaining = 0;
198 * Initialize output half connection to null state before trying
201 con->out.status = OP_NOT_STARTED;
203 con->out.oob_fd = -1;
204 con->out.op_q_first = (struct oper_data *)&con->out;
205 con->out.op_q_last = (struct oper_data *)&con->out;
206 con->out.next_byte = NULL;
207 con->out.remaining = 0;
215 /************************************************************************/
217 /* gdb_allocate_connection
219 /* Return an unused entry in the connection array. Unused entries
220 /* are recognized by being marked as CON_STOPPED.
222 /* Note that gdb_mcons is the number of descriptors which have
223 /* ever been used (i.e. a high water mark), so status fields
224 /* are invalid above that.
226 /************************************************************************/
229 gdb_allocate_connection()
231 register int i; /* index of next one */
235 * First look for one below the high water mark
237 for(i=0; i<gdb_mcons; i++) {
238 if (gdb_cons[i].status == CON_STOPPED)
243 * Allocate one which has never been used, if possible
246 if (i>=GDB_MAX_CONNECTIONS)
247 GDB_GIVEUP("gdb: tried to allocate too many simulataneous connections.\n, See GDB_MAX_CONNECTIONS in gdb.h.") /* <==RECOVERABLE */
249 gdb_mcons++; /* bump the high water mark */
250 gdb_cons[i].status = CON_STOPPED; /* initialize status of the */
252 return &gdb_cons[i]; /* return new highest con */
257 /************************************************************************/
261 /* Try to start a connection to the designated site, filling
262 /* in the appropriate information in the connection descriptor
263 /* if successful. Return TRUE if connection succeeded or if
264 /* error was fatal enough that we shouldn't try accepting. Returns
265 /* FALSE if we should try accepting.
267 /************************************************************************/
271 g_try_connecting(con,id)
275 int peer; /* socket for talking to
277 int on = 1; /* flag for ioctl */
278 struct sockaddr_in target; /* build the peer address */
280 struct hostent *peer_host; /* host where peer is */
282 /*----------------------------------------------------------*/
284 /* Make sure connection is marked stopped until we
287 /*----------------------------------------------------------*/
289 con->status = CON_STOPPED;
291 /*----------------------------------------------------------*/
293 /* Find out host where peer is, and validate it. Take
294 /* care of port at the same time.
296 /*----------------------------------------------------------*/
298 memset((char *)&target, 0, sizeof(target));
299 g_parse_target(id, &peer_host, &target.sin_port);
300 if (peer_host == NULL) {
301 fprintf(gdb_log,"gdb: g_try_connecting... '%s' is not a valid host:server\n",
303 return TRUE; /* so we won't try accepting */
306 /*----------------------------------------------------------*/
310 /*----------------------------------------------------------*/
312 peer = socket(AF_INET, SOCK_STREAM, 0);
314 g_stop_with_errno(con);
315 return TRUE; /* fatal error */
318 /*----------------------------------------------------------*/
320 /* Get information and bind socket using well known
321 /* port (BUG: this restricts us to one pair of peers
322 /* per host pair, as well as being bad practice on
323 /* the network. It will do for debugging.
325 /*----------------------------------------------------------*/
328 memcpy((char *)&target.sin_addr,peer_host->h_addr,peer_host->h_length);
329 target.sin_family = peer_host->h_addrtype;
331 /*----------------------------------------------------------*/
333 /* Make the connection
335 /*----------------------------------------------------------*/
337 if(connect(peer, (struct sockaddr *)&target, sizeof(target)) < 0) {
338 if (errno == ECONNREFUSED)
339 return FALSE; /* other side not yet */
340 /* up, but no other fatal */
343 gdb_perror("gdb: unexpected error connecting");
344 g_stop_with_errno(con);
349 if ((gdb_Options & GDB_OPT_KEEPALIVE) &&
350 setsockopt(peer, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0) {
351 gdb_perror("gdb: unable to start keepalives");
352 g_stop_with_errno(con);
356 /*----------------------------------------------------------*/
358 /* The connection has been made, fill in the connection
359 /* control data structure.
361 /*----------------------------------------------------------*/
365 con->status = CON_STARTING;
372 /************************************************************************/
376 /* For a given server or peer i.d., figure out the host and the
377 /* port. Arguments are:
379 /* string i.d. of the server, which is
380 /* in one of two forms:
382 /* host:servicename (where service name must not begin
385 /* host:#portnumber (where portnumber is the actual
386 /* number of the port to be used)
388 /* (actually, a 3rd form, with no port number supplied,
389 /* will use a default GDB_PORT, but this is unsafe
390 /* and it will be disabled in production versions
391 /* of the gdb system.)
393 /* **hostent: returned to indicate host to be used. Null
394 /* if host could not be found
396 /* *port pointer to an integer where the port number will
397 /* be put. We return the port number in network
400 /************************************************************************/
403 g_parse_target(id, host, port)
405 struct hostent **host;
408 char buffer[256]; /* longest host name */
409 register char *ip, *bp; /* for copying name */
410 struct servent *serv; /* returned from */
411 /* get service by name */
413 /*----------------------------------------------------------*/
415 /* copy the host name part only to local buffer
417 /*----------------------------------------------------------*/
422 while (*ip != '\0' && *ip != ':')
426 /*----------------------------------------------------------*/
428 /* Look up the host name, return if bad.
430 /*----------------------------------------------------------*/
432 *host = gethostbyname(buffer);
437 /*----------------------------------------------------------*/
439 /* Set up the port address
441 /*----------------------------------------------------------*/
455 * port number supplied explictly
458 if (*ip < '0' || *ip>'9') {
462 *port = htons((u_short)atoi(ip));
465 * service identified by name
467 serv = getservbyname(ip, "tcp");
472 *port = serv->s_port;
477 /************************************************************************/
481 /* Try to accept a connection to the designated site, filling
482 /* in the appropriate information in the connection descriptor
485 /************************************************************************/
488 g_try_accepting(con,id)
492 int slisten; /* socket on which
493 we listen for connections */
495 int peer; /* socket for talking to
498 struct sockaddr_in self, from;
499 int retries = GDB_BIND_RETRY_COUNT;
500 int onoff = 1; /* used as argument to */
503 struct hostent *peer_host; /* host where peer is */
505 /*----------------------------------------------------------*/
507 /* Make sure connection is marked stopped until we
510 /*----------------------------------------------------------*/
512 con->status = CON_STOPPED;
514 /*----------------------------------------------------------*/
516 /* Create a socket on which to listen. Tell it that
517 /* it's OK to re-use the port address, which may still
518 /* appear busy if connections are taking awhile to go
521 /*----------------------------------------------------------*/
523 slisten = socket(AF_INET, SOCK_STREAM, 0);
525 gdb_perror("g_try_accepting: error creating listen socket");
526 g_stop_with_errno(con);
529 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0, 0)<0)
530 /* that didn't work, try 4.3 */
531 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
532 (char *)&onoff, sizeof(int)) <0)
533 GDB_GIVEUP("g_try_accepting: could not set SO_REUSEADDR");
535 /*----------------------------------------------------------*/
537 /* Find out host where peer is, and validate it. Take
538 /* care of port at the same time. This is redundant
539 /* given that g_try_connecting is always called first.
541 /*----------------------------------------------------------*/
543 memset((char *)&self, 0, sizeof(self));
544 g_parse_target(id, &peer_host, &self.sin_port);
545 if (peer_host == NULL) {
546 GDB_GIVEUP("gdb_try_accepting: bad port not caught by try connecting")
549 /*----------------------------------------------------------*/
551 /* Bind the socket to ourselves, using the well known
552 /* port (See bug note in g_try_connecting.
554 /* This code should really go in initialization, I think.
556 /*----------------------------------------------------------*/
558 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
559 if (errno == EADDRINUSE && retries--) {
560 fprintf(gdb_log,"gdb: port address in use, will retry %d more time(s)\n",retries+1);
561 sleep(GDB_BIND_RETRY_INTERVAL);
564 gdb_perror("gdb: error binding listen socket");
565 g_stop_with_errno(con);
566 (void) close(slisten);
571 /*----------------------------------------------------------*/
573 /* Listen for connections.
575 /*----------------------------------------------------------*/
577 (void) listen (slisten, 5); /* does not block, just */
578 /* sets the maximum backlog */
579 /* of pending non-accepted */
581 fromlen = sizeof(from);
582 peer = accept(slisten, &from, &fromlen);
584 g_stop_with_errno(con);
585 gdb_perror("gdb_try_accepting: error accepting connection");
586 (void) close(slisten);
590 (void) close (slisten); /* we're not using the */
591 /* listening socket */
592 /* anymore, only the */
593 /* connection to the peer */
595 /*----------------------------------------------------------*/
597 /* The connection has been made, fill in the connection
598 /* control data structure.
600 /*----------------------------------------------------------*/
604 con->status = CON_STARTING;
608 /************************************************************************/
612 /* Called when an outbound connection is started to verify
613 /* the version of the protocol being observed.
615 /************************************************************************/
621 #ifdef VERIFY_PROTOCOL
622 char ver = GDB_PROTOCOL_VERSION;
626 int onoff = 0; /* for ioctl to turn off */
629 * Because the connection was accepted on a non-blocking
630 * listening socket, the connection itself may be non-blocking.
631 * We can't tolerate that here. It will be reset later.
633 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
634 g_stop_with_errno(con);
635 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
639 while (write(con->out.fd, &ver, 1) < 0) {
640 g_stop_with_errno(con);
645 len = read(con->in.fd, &theirs, 1);
647 g_stop_with_errno(con);
653 con->status = CON_UP;
655 con->status = CON_STOPPED;
656 #else !VERIFY_PROTOCOL
657 con->status = CON_UP;
658 #endif !VERIFY_PROTOCOL
662 /************************************************************************/
666 /* Called when an inbound connection is started to verify
667 /* the version of the protocol being observed.
669 /************************************************************************/
675 #ifdef VERIFY_PROTOCOL
676 char ver = GDB_PROTOCOL_VERSION;
680 int onoff = 0; /* for ioctl to turn off */
683 * Because the connection was accepted on a non-blocking
684 * listening socket, the connection itself may be non-blocking.
685 * We can't tolerate that here. It will be reset later.
687 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
688 g_stop_with_errno(con);
689 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
694 len = read(con->in.fd, &theirs, 1);
696 g_stop_with_errno(con);
702 con->status = CON_UP;
704 con->status = CON_STOPPED;
706 while (write(con->out.fd, &ver, 1) < 0) {
707 g_stop_with_errno(con);
710 #else !VERIFY_PROTOCOL
711 con->status = CON_UP;
716 /************************************************************************/
718 /* sever_connection (sever_connection)
720 /* Unconditionally, but cleanly, terminates a connection. All
721 /* pending operations on the connection are cancelled, and the
722 /* file descriptor for the connection is closed. This routine
723 /* should be called directly from applications wishing to shut
724 /* down a connection. No transmissions are attempted
725 /* by this routine. Returns NULL, in the hope that applications
726 /* will assign this to their old CONNECTION variable.
728 /************************************************************************/
731 sever_connection(con)
736 GDB_CHECK_CON(con, "sever_connection")
737 if (con->status == CON_UP || con->status == CON_STARTING)
738 g_stop_connection(con);
739 if (con->status != CON_STOPPED)
740 gdb_de_allocate_connection(con);
746 /************************************************************************/
750 /* This connection is stopping because of a problem on a syscall.
751 /* We record the errno in the connection descriptor for inspection
752 /* by the application, then stop the connection.
754 /************************************************************************/
757 g_stop_with_errno(con)
761 g_stop_connection(con);
766 /************************************************************************/
770 /* Unconditionally, but cleanly, terminates a connection. All
771 /* pending operations on the connection are cancelled, and the
772 /* file descriptor for the connection is closed. This routine is
773 /* for internal use. Applications call sever_connection, which
774 /* also de_allocates the descriptor. No transmissions are attempted
777 /************************************************************************/
780 g_stop_connection(con)
784 * Shutdown activity on the two half connections.
786 g_cleanup_half_connection(&(con->in));
787 g_cleanup_half_connection(&(con->out));
790 * Remove the file descriptor from the select bit maps
792 if (!(con->in.flags & HCON_UNUSED) && con->in.fd >= 0)
793 FD_CLR(con->in.fd, &gdb_crfds);
794 if (!(con->out.flags & HCON_UNUSED) && con->out.fd >= 0)
795 FD_CLR(con->out.fd, &gdb_cwfds);
797 * Close the file descriptor. Note, this presumes that in fact
798 * 1) in is never the unused half and
799 * 2) when the connection is bi-directional, in and out share an
800 * fd. We could do with a more elaborate scheme to control
801 * this in the future.
803 (void) close(con->in.fd);
806 * Mark the connection as stopping. We can't reclaim the
807 * descriptor until the application does a sever, or else there
808 * would be a risk of re-allocating it out from under the application.
811 con->status = CON_STOPPING;
817 /************************************************************************/
819 /* gdb_de_allocate_connection
821 /* Return a connection whose file descriptors have been closed
824 /************************************************************************/
827 gdb_de_allocate_connection(con)
832 con->status = CON_STOPPED;
834 i = gdb_mcons-1; /* start at last one used */
837 * Reset gdb_mcons to be the number of connections in use
839 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);
880 /************************************************************************/
882 /* create_listening_connection (create_listening_connection)
884 /* Starts a special type of connection which is used to listen
885 /* for incoming connection requests. The inbound half-connection
886 /* is the only one used for this special kind of connection.
888 /* It is the user's responsibility to insure that only appropriate
889 /* types of operation are queued on a connection of this sort. In
890 /* general, these connections are intended for internal use by
891 /* GDB, and they are not intended to be visible to servers or
894 /* The id supplied should be in one of two forms. If just a
895 /* string is supplied then it is presumed to be the name of
896 /* a registered tcp service. If the name begins with a #, then
897 /* the rest is interpreted as the integer port number to be used.
899 /* In future implementations, the id may have more structure, which
900 /* is why we define it as a string.
902 /************************************************************************/
905 create_listening_connection(id)
908 register CONNECTION con; /* the connection we're */
911 register int slisten; /* socket on which
912 we listen for connections */
914 struct sockaddr_in self;
915 int retries = GDB_BIND_RETRY_COUNT;
916 int onoff = 1; /* used as argument to */
918 struct servent *serv;
923 * Try to allocate a connection and fill it in with null values.
929 * Try to create a socket for listening
931 con->in.fd = socket(AF_INET, SOCK_STREAM, 0);
932 slisten = con->in.fd; /* easier and faster than */
933 /* using con->in.fd all the */
936 gdb_perror("create_listening_connection: error creating listen socket");
937 (void) g_stop_with_errno(con);
941 * Set options so the listening address can be re-used (this
942 * has its dangers, but otherwise we can't restart our servers
943 * for long periods after they crash because of connections which
944 * take a long to time clean up and hold ports in use.)
948 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0,0)<0)
949 /* that didn't work, try 4.3 */
950 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
951 (char *)&onoff, sizeof(int)) <0)
952 GDB_GIVEUP("create_listening_connection: could not set SO_REUSEADDR")
955 * Make the listening socket non-blocking so we won't have to do
956 * selects before polling it (change made by Bill Sommerfeld - wesommer)
958 if (ioctl(slisten, FIONBIO, (char *)&onoff) < 0) { /*<==FIX,,,add comment */
959 g_stop_with_errno(con);
960 gdb_perror("ioctl for listening socket");
963 /*----------------------------------------------------------*/
965 /* Bind the socket to ourselves, using port derived from
966 /* the supplied id string.
968 /*----------------------------------------------------------*/
970 memset((char *)&self, 0, sizeof(self));
972 * Determine our port number
975 self.sin_port = htons((u_short)atoi(id+1));
977 serv = getservbyname(id, "tcp");
979 fprintf(gdb_log,"gdb create_listening_connection: cannot become service named %s\n",id);
980 return NULL; /* BUG: causes connetion */
981 /* descriptor leakage. Should */
982 /* return an error code in */
983 /* the connection descriptor*/
985 self.sin_port = serv->s_port;
989 * Try and re-try the bind until it works or until retry count
992 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
993 if (errno == EADDRINUSE && retries--) {
994 fprintf(gdb_log,"gdb create_listening_connection: port address in use, will retry %d more time(s)\n",retries+1);
995 sleep(GDB_BIND_RETRY_INTERVAL);
998 gdb_perror("gdb create_listening_connection: error binding listen socket");
999 g_stop_with_errno(con);
1004 /*----------------------------------------------------------*/
1006 /* Listen for connections.
1008 /*----------------------------------------------------------*/
1010 (void) listen (slisten, 5); /* does not block, just */
1011 /* sets the maximum backlog */
1012 /* of pending non-accepted */
1015 con->in.flags |= HCON_LISTEN;
1016 con->out.flags |= HCON_UNUSED;
1017 con->status = CON_UP;
1018 if (con->in.fd +1 > gdb_mfd)
1019 gdb_mfd = con->in.fd + 1;
1024 /************************************************************************/
1026 /* g_allocate_connection_buffers
1028 /* Create a buffer which can be used to receive large
1029 /* chunks of data from the socket. This is currently done only
1030 /* on the inbound half connection. Also, the buffers are not freed
1031 /* once allocated, even if the connection descriptor is re-used.
1033 /************************************************************************/
1036 g_allocate_connection_buffers(con)
1039 HALF_CONNECTION inbound = &(con->in);
1042 * See if there is already one allocated, if not, allocate one.
1044 if (inbound->stream_buffer == (char *)NULL) {
1045 inbound->stream_buffer =
1046 db_alloc(inbound->stream_buffer_length);
1050 * In any case, make sure that it is effectively empty
1052 inbound -> stream_buffer_next = inbound -> stream_buffer;
1053 inbound -> stream_buffer_remaining = 0;