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>
33 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/ioctl.h>
37 #include <netinet/in.h>
41 #include <sys/filio.h>
49 CONNECTION gdb_allocate_connection();
51 /************************************************************************
53 * start_peer_connection (start_peer_connection)
55 * Starts a connection to another process which itself will be
56 * issuing a start_peer_connection to us. Current implementation
57 * builds at most one stream, with the risk of a hang if
58 * the attempts to connect cross in the night. This is a bug,
59 * but this level of support is acceptable for casual debugging
60 * of applications, and perhaps for some production use in
61 * controlled settings. I think the only other way to do it
62 * is to risk building two streams in parallel, possibly tearing
63 * one down when the duplication is discovered. Seems complicated
66 ************************************************************************/
69 start_peer_connection(id)
70 char *id; /* null terminated string */
72 register CONNECTION con; /* the connection we're */
78 * Try to allocate a connection and fill it in with null values.
84 * In this implementation, we use a single fd for both inbound and
85 * outbound traffic. Try to connect to other side. If that
86 * doesn't work, wait to accept a connection from the other side.
87 * Current implementation of this is synchronous--may be a problem?
88 * Also note timing window bug in the following. If the two peers
89 * are started at just about the same time, the race may not be handled
90 * propoerly. If the connections come up, then verify the level of
91 * protocol being observed on the connections. If incompatible,
92 * then turn off the connection.
95 if(!g_try_connecting(con,id)) {
96 g_try_accepting(con,id);
97 if(con->status == CON_STARTING)
100 if(con->status == CON_STARTING)
101 g_ver_oprotocol(con);
104 if (con->status == CON_UP) {
106 * We've successfully started the connection, now mark
107 * it for non-blocking I/O. Also, update the high water
108 * mark of fd's controlled by our system.
111 if(ioctl(con->in.fd, FIONBIO, (char *)&nb)== (-1)) {
112 g_stop_with_errno(con);
115 if (con->in.fd +1 > gdb_mfd)
116 gdb_mfd = con->in.fd + 1;
118 * Allocate a buffer, if necessary, and reset buffer pointers
119 * so first request will result in a long read into the buffer
121 g_allocate_connection_buffers(con);
129 /************************************************************************/
133 /* Internal routine to allocate a new connection structure and
134 /* initialize all its fields to logical null values.
136 /************************************************************************/
141 register CONNECTION con;
144 * Try to allocate a connection, fatal error if none available
146 con = gdb_allocate_connection();
148 GDB_GIVEUP("start_peer_connection: Tried to allocate too many connections") /* <==RECOVERABLE */
151 * Give the fields their initial values
160 /************************************************************************/
164 /* Sets a connection descriptor to have all null values in
165 /* its fields. This routine does NOT do any of the cleanup
166 /* which is necessary after the connection has really been used.
168 /************************************************************************/
175 * Initialize the connection control data structure.
177 con->id = GDB_CON_ID;
178 con->status = CON_STARTING;
179 con->oob_fcn = NULL; /* out of band signalling */
180 /* is not currently */
182 con->errno = 0; /* system errno gets */
183 /* copied here iff it */
184 /* causes this con to die */
186 * Initialize input half connection to null state before trying
189 con->in.status = OP_NOT_STARTED;
192 con->in.op_q_first = (struct oper_data *)&con->in;
193 con->in.op_q_last = (struct oper_data *)&con->in;
194 con->in.next_byte = NULL;
195 con->in.remaining = 0;
199 * Initialize output half connection to null state before trying
202 con->out.status = OP_NOT_STARTED;
204 con->out.oob_fd = -1;
205 con->out.op_q_first = (struct oper_data *)&con->out;
206 con->out.op_q_last = (struct oper_data *)&con->out;
207 con->out.next_byte = NULL;
208 con->out.remaining = 0;
216 /************************************************************************/
218 /* gdb_allocate_connection
220 /* Return an unused entry in the connection array. Unused entries
221 /* are recognized by being marked as CON_STOPPED.
223 /* Note that gdb_mcons is the number of descriptors which have
224 /* ever been used (i.e. a high water mark), so status fields
225 /* are invalid above that.
227 /************************************************************************/
230 gdb_allocate_connection()
232 register int i; /* index of next one */
236 * First look for one below the high water mark
238 for(i=0; i<gdb_mcons; i++) {
239 if (gdb_cons[i].status == CON_STOPPED)
244 * Allocate one which has never been used, if possible
247 if (i>=GDB_MAX_CONNECTIONS)
248 GDB_GIVEUP("gdb: tried to allocate too many simulataneous connections.\n, See GDB_MAX_CONNECTIONS in gdb.h.") /* <==RECOVERABLE */
250 gdb_mcons++; /* bump the high water mark */
251 gdb_cons[i].status = CON_STOPPED; /* initialize status of the */
253 return &gdb_cons[i]; /* return new highest con */
258 /************************************************************************/
262 /* Try to start a connection to the designated site, filling
263 /* in the appropriate information in the connection descriptor
264 /* if successful. Return TRUE if connection succeeded or if
265 /* error was fatal enough that we shouldn't try accepting. Returns
266 /* FALSE if we should try accepting.
268 /************************************************************************/
272 g_try_connecting(con,id)
276 int peer; /* socket for talking to
278 int on = 1; /* flag for ioctl */
279 struct sockaddr_in target; /* build the peer address */
281 struct hostent *peer_host; /* host where peer is */
283 /*----------------------------------------------------------*/
285 /* Make sure connection is marked stopped until we
288 /*----------------------------------------------------------*/
290 con->status = CON_STOPPED;
292 /*----------------------------------------------------------*/
294 /* Find out host where peer is, and validate it. Take
295 /* care of port at the same time.
297 /*----------------------------------------------------------*/
299 memset((char *)&target, 0, sizeof(target));
300 g_parse_target(id, &peer_host, &target.sin_port);
301 if (peer_host == NULL) {
302 fprintf(gdb_log,"gdb: g_try_connecting... '%s' is not a valid host:server\n",
304 return TRUE; /* so we won't try accepting */
307 /*----------------------------------------------------------*/
311 /*----------------------------------------------------------*/
313 peer = socket(AF_INET, SOCK_STREAM, 0);
315 g_stop_with_errno(con);
316 return TRUE; /* fatal error */
319 /*----------------------------------------------------------*/
321 /* Get information and bind socket using well known
322 /* port (BUG: this restricts us to one pair of peers
323 /* per host pair, as well as being bad practice on
324 /* the network. It will do for debugging.
326 /*----------------------------------------------------------*/
329 memcpy((char *)&target.sin_addr,peer_host->h_addr,peer_host->h_length);
330 target.sin_family = peer_host->h_addrtype;
332 /*----------------------------------------------------------*/
334 /* Make the connection
336 /*----------------------------------------------------------*/
338 if(connect(peer, (struct sockaddr *)&target, sizeof(target)) < 0) {
339 if (errno == ECONNREFUSED)
340 return FALSE; /* other side not yet */
341 /* up, but no other fatal */
344 gdb_perror("gdb: unexpected error connecting");
345 g_stop_with_errno(con);
350 if ((gdb_Options & GDB_OPT_KEEPALIVE) &&
351 setsockopt(peer, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0) {
352 gdb_perror("gdb: unable to start keepalives");
353 g_stop_with_errno(con);
357 /*----------------------------------------------------------*/
359 /* The connection has been made, fill in the connection
360 /* control data structure.
362 /*----------------------------------------------------------*/
366 con->status = CON_STARTING;
373 /************************************************************************/
377 /* For a given server or peer i.d., figure out the host and the
378 /* port. Arguments are:
380 /* string i.d. of the server, which is
381 /* in one of two forms:
383 /* host:servicename (where service name must not begin
386 /* host:#portnumber (where portnumber is the actual
387 /* number of the port to be used)
389 /* (actually, a 3rd form, with no port number supplied,
390 /* will use a default GDB_PORT, but this is unsafe
391 /* and it will be disabled in production versions
392 /* of the gdb system.)
394 /* **hostent: returned to indicate host to be used. Null
395 /* if host could not be found
397 /* *port pointer to an integer where the port number will
398 /* be put. We return the port number in network
401 /************************************************************************/
404 g_parse_target(id, host, port)
406 struct hostent **host;
409 char buffer[256]; /* longest host name */
410 register char *ip, *bp; /* for copying name */
411 struct servent *serv; /* returned from */
412 /* get service by name */
414 /*----------------------------------------------------------*/
416 /* copy the host name part only to local buffer
418 /*----------------------------------------------------------*/
423 while (*ip != '\0' && *ip != ':')
427 /*----------------------------------------------------------*/
429 /* Look up the host name, return if bad.
431 /*----------------------------------------------------------*/
433 *host = gethostbyname(buffer);
438 /*----------------------------------------------------------*/
440 /* Set up the port address
442 /*----------------------------------------------------------*/
456 * port number supplied explictly
459 if (*ip < '0' || *ip>'9') {
463 *port = htons((u_short)atoi(ip));
466 * service identified by name
468 serv = getservbyname(ip, "tcp");
473 *port = serv->s_port;
478 /************************************************************************/
482 /* Try to accept a connection to the designated site, filling
483 /* in the appropriate information in the connection descriptor
486 /************************************************************************/
489 g_try_accepting(con,id)
493 int slisten; /* socket on which
494 we listen for connections */
496 int peer; /* socket for talking to
499 struct sockaddr_in self, from;
500 int retries = GDB_BIND_RETRY_COUNT;
501 int onoff = 1; /* used as argument to */
504 struct hostent *peer_host; /* host where peer is */
506 /*----------------------------------------------------------*/
508 /* Make sure connection is marked stopped until we
511 /*----------------------------------------------------------*/
513 con->status = CON_STOPPED;
515 /*----------------------------------------------------------*/
517 /* Create a socket on which to listen. Tell it that
518 /* it's OK to re-use the port address, which may still
519 /* appear busy if connections are taking awhile to go
522 /*----------------------------------------------------------*/
524 slisten = socket(AF_INET, SOCK_STREAM, 0);
526 gdb_perror("g_try_accepting: error creating listen socket");
527 g_stop_with_errno(con);
530 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0, 0)<0)
531 /* that didn't work, try 4.3 */
532 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
533 (char *)&onoff, sizeof(int)) <0)
534 GDB_GIVEUP("g_try_accepting: could not set SO_REUSEADDR");
536 /*----------------------------------------------------------*/
538 /* Find out host where peer is, and validate it. Take
539 /* care of port at the same time. This is redundant
540 /* given that g_try_connecting is always called first.
542 /*----------------------------------------------------------*/
544 memset((char *)&self, 0, sizeof(self));
545 g_parse_target(id, &peer_host, &self.sin_port);
546 if (peer_host == NULL) {
547 GDB_GIVEUP("gdb_try_accepting: bad port not caught by try connecting")
550 /*----------------------------------------------------------*/
552 /* Bind the socket to ourselves, using the well known
553 /* port (See bug note in g_try_connecting.
555 /* This code should really go in initialization, I think.
557 /*----------------------------------------------------------*/
559 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
560 if (errno == EADDRINUSE && retries--) {
561 fprintf(gdb_log,"gdb: port address in use, will retry %d more time(s)\n",retries+1);
562 sleep(GDB_BIND_RETRY_INTERVAL);
565 gdb_perror("gdb: error binding listen socket");
566 g_stop_with_errno(con);
567 (void) close(slisten);
572 /*----------------------------------------------------------*/
574 /* Listen for connections.
576 /*----------------------------------------------------------*/
578 (void) listen (slisten, 5); /* does not block, just */
579 /* sets the maximum backlog */
580 /* of pending non-accepted */
582 fromlen = sizeof(from);
583 peer = accept(slisten, (struct sockaddr *)&from, &fromlen);
585 g_stop_with_errno(con);
586 gdb_perror("gdb_try_accepting: error accepting connection");
587 (void) close(slisten);
591 (void) close (slisten); /* we're not using the */
592 /* listening socket */
593 /* anymore, only the */
594 /* connection to the peer */
596 /*----------------------------------------------------------*/
598 /* The connection has been made, fill in the connection
599 /* control data structure.
601 /*----------------------------------------------------------*/
605 con->status = CON_STARTING;
609 /************************************************************************/
613 /* Called when an outbound connection is started to verify
614 /* the version of the protocol being observed.
616 /************************************************************************/
622 #ifdef VERIFY_PROTOCOL
623 char ver = GDB_PROTOCOL_VERSION;
627 int onoff = 0; /* for ioctl to turn off */
630 * Because the connection was accepted on a non-blocking
631 * listening socket, the connection itself may be non-blocking.
632 * We can't tolerate that here. It will be reset later.
634 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
635 g_stop_with_errno(con);
636 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
640 while (write(con->out.fd, &ver, 1) < 0) {
641 g_stop_with_errno(con);
646 len = read(con->in.fd, &theirs, 1);
648 g_stop_with_errno(con);
654 con->status = CON_UP;
656 con->status = CON_STOPPED;
658 con->status = CON_UP;
663 /************************************************************************/
667 /* Called when an inbound connection is started to verify
668 /* the version of the protocol being observed.
670 /************************************************************************/
676 #ifdef VERIFY_PROTOCOL
677 char ver = GDB_PROTOCOL_VERSION;
681 int onoff = 0; /* for ioctl to turn off */
684 * Because the connection was accepted on a non-blocking
685 * listening socket, the connection itself may be non-blocking.
686 * We can't tolerate that here. It will be reset later.
688 if (ioctl(con->in.fd, FIONBIO, (char *)&onoff) < 0) {
689 g_stop_with_errno(con);
690 gdb_perror("Can't turn off FIONBIO in g_ver_iprotocol");
695 len = read(con->in.fd, &theirs, 1);
697 g_stop_with_errno(con);
703 con->status = CON_UP;
705 con->status = CON_STOPPED;
707 while (write(con->out.fd, &ver, 1) < 0) {
708 g_stop_with_errno(con);
712 con->status = CON_UP;
717 /************************************************************************/
719 /* sever_connection (sever_connection)
721 /* Unconditionally, but cleanly, terminates a connection. All
722 /* pending operations on the connection are cancelled, and the
723 /* file descriptor for the connection is closed. This routine
724 /* should be called directly from applications wishing to shut
725 /* down a connection. No transmissions are attempted
726 /* by this routine. Returns NULL, in the hope that applications
727 /* will assign this to their old CONNECTION variable.
729 /************************************************************************/
732 sever_connection(con)
737 GDB_CHECK_CON(con, "sever_connection")
738 if (con->status == CON_UP || con->status == CON_STARTING)
739 g_stop_connection(con);
740 if (con->status != CON_STOPPED)
741 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 /************************************************************************/
758 g_stop_with_errno(con)
762 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) && con->in.fd >= 0)
794 FD_CLR(con->in.fd, &gdb_crfds);
795 if (!(con->out.flags & HCON_UNUSED) && con->out.fd >= 0)
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)
847 /************************************************************************/
849 /* g_cleanup_half_conection
851 /* Terminate all pending operations on the supplied half
852 /* connection. Note that the algorithm used here presumes
853 /* that cancel_operation will de-queue the operation descriptor,
854 /* therefore we have to be careful here about when we look at
857 /************************************************************************/
860 g_cleanup_half_connection(hcon)
861 HALF_CONNECTION hcon;
863 OPERATION current, next;
865 current = hcon->op_q_first;
868 * Loop through all operations in the queue canceling them.
869 * Make sure to pick up pointer to 'next' before the current
870 * one is canceled, as cancelling may invalidate the pointer.
873 while (current != (OPERATION)hcon) {
874 next = current->next;
875 (void) cancel_operation(current);
881 /************************************************************************/
883 /* create_listening_connection (create_listening_connection)
885 /* Starts a special type of connection which is used to listen
886 /* for incoming connection requests. The inbound half-connection
887 /* is the only one used for this special kind of connection.
889 /* It is the user's responsibility to insure that only appropriate
890 /* types of operation are queued on a connection of this sort. In
891 /* general, these connections are intended for internal use by
892 /* GDB, and they are not intended to be visible to servers or
895 /* The id supplied should be in one of two forms. If just a
896 /* string is supplied then it is presumed to be the name of
897 /* a registered tcp service. If the name begins with a #, then
898 /* the rest is interpreted as the integer port number to be used.
900 /* In future implementations, the id may have more structure, which
901 /* is why we define it as a string.
903 /************************************************************************/
906 create_listening_connection(id)
909 register CONNECTION con; /* the connection we're */
912 register int slisten; /* socket on which
913 we listen for connections */
915 struct sockaddr_in self;
916 int retries = GDB_BIND_RETRY_COUNT;
917 int onoff = 1; /* used as argument to */
919 struct servent *serv;
924 * Try to allocate a connection and fill it in with null values.
930 * Try to create a socket for listening
932 con->in.fd = socket(AF_INET, SOCK_STREAM, 0);
933 slisten = con->in.fd; /* easier and faster than */
934 /* using con->in.fd all the */
937 gdb_perror("create_listening_connection: error creating listen socket");
938 (void) g_stop_with_errno(con);
942 * Set options so the listening address can be re-used (this
943 * has its dangers, but otherwise we can't restart our servers
944 * for long periods after they crash because of connections which
945 * take a long to time clean up and hold ports in use.)
949 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, (char *)0,0)<0)
950 /* that didn't work, try 4.3 */
951 if(setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR,
952 (char *)&onoff, sizeof(int)) <0)
953 GDB_GIVEUP("create_listening_connection: could not set SO_REUSEADDR")
956 * Make the listening socket non-blocking so we won't have to do
957 * selects before polling it (change made by Bill Sommerfeld - wesommer)
959 if (ioctl(slisten, FIONBIO, (char *)&onoff) < 0) { /*<==FIX,,,add comment */
960 g_stop_with_errno(con);
961 gdb_perror("ioctl for listening socket");
964 /*----------------------------------------------------------*/
966 /* Bind the socket to ourselves, using port derived from
967 /* the supplied id string.
969 /*----------------------------------------------------------*/
971 memset((char *)&self, 0, sizeof(self));
973 * Determine our port number
976 self.sin_port = htons((u_short)atoi(id+1));
978 serv = getservbyname(id, "tcp");
980 fprintf(gdb_log,"gdb create_listening_connection: cannot become service named %s\n",id);
981 return NULL; /* BUG: causes connetion */
982 /* descriptor leakage. Should */
983 /* return an error code in */
984 /* the connection descriptor*/
986 self.sin_port = serv->s_port;
990 * Try and re-try the bind until it works or until retry count
993 while (bind(slisten,(struct sockaddr *)&self,sizeof(self)) < 0) {
994 if (errno == EADDRINUSE && retries--) {
995 fprintf(gdb_log,"gdb create_listening_connection: port address in use, will retry %d more time(s)\n",retries+1);
996 sleep(GDB_BIND_RETRY_INTERVAL);
999 gdb_perror("gdb create_listening_connection: error binding listen socket");
1000 g_stop_with_errno(con);
1005 /*----------------------------------------------------------*/
1007 /* Listen for connections.
1009 /*----------------------------------------------------------*/
1011 (void) listen (slisten, 5); /* does not block, just */
1012 /* sets the maximum backlog */
1013 /* of pending non-accepted */
1016 con->in.flags |= HCON_LISTEN;
1017 con->out.flags |= HCON_UNUSED;
1018 con->status = CON_UP;
1019 if (con->in.fd +1 > gdb_mfd)
1020 gdb_mfd = con->in.fd + 1;
1025 /************************************************************************/
1027 /* g_allocate_connection_buffers
1029 /* Create a buffer which can be used to receive large
1030 /* chunks of data from the socket. This is currently done only
1031 /* on the inbound half connection. Also, the buffers are not freed
1032 /* once allocated, even if the connection descriptor is re-used.
1034 /************************************************************************/
1037 g_allocate_connection_buffers(con)
1040 HALF_CONNECTION inbound = &(con->in);
1043 * See if there is already one allocated, if not, allocate one.
1045 if (inbound->stream_buffer == (char *)NULL) {
1046 inbound->stream_buffer =
1047 db_alloc(inbound->stream_buffer_length);
1051 * In any case, make sure that it is effectively empty
1053 inbound -> stream_buffer_next = inbound -> stream_buffer;
1054 inbound -> stream_buffer_remaining = 0;