2 * WINGs WMConnection function library
4 * Copyright (c) 1999 Dan Pascu
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 * - decide if we want to support connections with external sockets, else
25 * clean up the structure of the unneeded members.
30 #include "../src/config.h"
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
45 #include <sys/signal.h>
51 /* Some older systems does not define this (linux libc5, maybe others too) */
61 /* Stuff for setting the sockets into non-blocking mode. */
62 /*#ifdef __POSIX_SOURCE
63 # define NONBLOCK_OPT O_NONBLOCK
65 # define NONBLOCK_OPT FNDELAY
68 #define NONBLOCK_OPT O_NONBLOCK
71 #define NETBUF_SIZE 4096
74 #define DEF_TIMEOUT 600 /* 600 seconds == 10 minutes */
81 static Bool SigInitialized
= False
;
85 typedef struct TimeoutData
{
92 typedef struct W_Connection
{
93 int sock
; /* the socket we speak through */
96 WMHandlerID
*read
; /* the input read handler */
97 WMHandlerID
*write
; /* the input write handler */
98 WMHandlerID
*exception
; /* the input exception handler */
101 ConnectionDelegate
*delegate
; /* client delegates */
102 void *clientData
; /* client data */
103 unsigned int uflags
; /* flags for the client */
108 TimeoutData sendTimeout
;
110 WMConnectionState state
;
126 clearOutputQueue(WMConnection
*cPtr
) /*FOLD00*/
132 for (i
=0; i
<WMGetBagItemCount(cPtr
->outputQueue
); i
++)
133 WMReleaseData(WMGetFromBag(cPtr
->outputQueue
, i
));
135 WMEmptyBag(cPtr
->outputQueue
);
140 sendTimeout(void *cdata
) /*FOLD00*/
142 WMConnection
*cPtr
= (WMConnection
*) cdata
;
143 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
145 tPtr
->handler
= NULL
;
146 if (cPtr
->handler
.write
) {
147 WMDeleteInputHandler(cPtr
->handler
.write
);
148 cPtr
->handler
.write
= NULL
;
150 if (WMGetBagItemCount(cPtr
->outputQueue
)>0) {
151 clearOutputQueue(cPtr
);
152 if (cPtr
->delegate
&& cPtr
->delegate
->didTimeout
)
153 (*cPtr
->delegate
->didTimeout
)(cPtr
->delegate
, cPtr
);
159 inputHandler(int fd
, int mask
, void *clientData
) /*FOLD00*/
161 WMConnection
*cPtr
= (WMConnection
*)clientData
;
163 if (cPtr
->state
==WCClosed
|| cPtr
->state
==WCDied
)
166 if ((mask
& WIWriteMask
)) {
167 if (cPtr
->state
== WCInProgress
) {
169 int len
= sizeof(result
);
171 if (getsockopt(cPtr
->sock
, SOL_SOCKET
, SO_ERROR
,
172 (void*)&result
, &len
) == 0 && result
!= 0) {
173 cPtr
->state
= WCFailed
;
174 WCErrorCode
= result
;
175 /* should call wsyserrorwithcode(result, ...) here? */
177 cPtr
->state
= WCConnected
;
180 if (cPtr
->handler
.write
) {
181 WMDeleteInputHandler(cPtr
->handler
.write
);
182 cPtr
->handler
.write
= NULL
;
185 if (cPtr
->delegate
&& cPtr
->delegate
->didInitialize
)
186 (*cPtr
->delegate
->didInitialize
)(cPtr
->delegate
, cPtr
);
188 if (cPtr
->state
== WCFailed
)
190 } else if (cPtr
->state
== WCConnected
) {
191 WMFlushConnection(cPtr
);
198 /* if the connection died, may get destroyed in the delegate, so retain */
201 if ((mask
& WIReadMask
) && cPtr
->delegate
->didReceiveInput
)
202 (*cPtr
->delegate
->didReceiveInput
)(cPtr
->delegate
, cPtr
);
204 if ((mask
& WIExceptMask
) && cPtr
->delegate
->didCatchException
)
205 (*cPtr
->delegate
->didCatchException
)(cPtr
->delegate
, cPtr
);
212 setSocketNonBlocking(int sock
, Bool flag
) /*FOLD00*/
217 state
= fcntl(sock
, F_GETFL
, 0);
220 wsyserror("Failed to get socket flags with fcntl.");
224 isNonBlock
= (state
& NONBLOCK_OPT
) != 0;
229 state
|= NONBLOCK_OPT
;
233 state
&= ~NONBLOCK_OPT
;
236 if (fcntl(sock
, F_SETFL
, state
) < 0) {
237 wsyserror("Failed to set socket flags with fcntl.");
246 setConnectionAddress(WMConnection
*cPtr
, struct sockaddr_in
*socketaddr
) /*FOLD00*/
248 wassertr(cPtr
->address
==NULL
);
250 cPtr
->address
= wstrdup(inet_ntoa(socketaddr
->sin_addr
));
251 cPtr
->service
= wmalloc(16);
252 sprintf(cPtr
->service
, "%hu", ntohs(socketaddr
->sin_port
));
253 cPtr
->protocol
= wstrdup("tcp");
257 static struct sockaddr_in
*
258 getSocketAddress(char* name
, char* service
, char* protocol
) /*FOLD00*/
260 static struct sockaddr_in socketaddr
;
263 if (!protocol
|| protocol
[0]=='\0')
266 memset(&socketaddr
, 0, sizeof(struct sockaddr_in
));
267 socketaddr
.sin_family
= AF_INET
;
270 * If we were given a hostname, we use any address for that host.
271 * Otherwise we expect the given name to be an address unless it is
272 * NULL (any address).
274 if (name
&& name
[0]!='\0') {
275 WMHost
*host
= WMGetHostWithName(name
);
278 return NULL
; /* name is not a hostname nor a number and dot adr */
280 name
= WMGetHostAddress(host
);
281 #ifndef HAVE_INET_ATON
282 if ((socketaddr
.sin_addr
.s_addr
= inet_addr(name
)) == INADDR_NONE
) {
284 if (inet_aton(name
, &socketaddr
.sin_addr
) == 0) {
291 socketaddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
294 if (!service
|| service
[0]=='\0') {
295 socketaddr
.sin_port
= 0;
296 } else if ((sp
= getservbyname(service
, protocol
))==0) {
300 portNumber
= strtoul(service
, &endptr
, 10);
302 if (service
[0]!='\0' && *endptr
=='\0' && portNumber
<65536) {
303 socketaddr
.sin_port
= htons(portNumber
);
308 socketaddr
.sin_port
= sp
->s_port
;
316 createConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
319 struct sigaction sig_action
;
321 cPtr
= wmalloc(sizeof(WMConnection
));
323 memset(cPtr
, 0, sizeof(WMConnection
));
326 cPtr
->sendTimeout
.timeout
= DEF_TIMEOUT
;
327 cPtr
->sendTimeout
.handler
= NULL
;
328 cPtr
->closeOnRelease
= closeOnRelease
;
329 cPtr
->outputQueue
= WMCreateBag(16);
330 cPtr
->state
= WCNotConnected
;
332 /* ignore dead pipe */
333 if (!SigInitialized
) {
334 sig_action
.sa_handler
= SIG_IGN
;
335 sig_action
.sa_flags
= SA_RESTART
;
336 sigaction(SIGPIPE
, &sig_action
, NULL
);
337 SigInitialized
= True
;
346 WMCreateConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
349 struct sockaddr_in clientname
;
352 cPtr
= createConnectionWithSocket(sock
, closeOnRelease
);
353 cPtr
->wasNonBlocking
= WMIsConnectionNonBlocking(cPtr
);
354 cPtr
->isNonBlocking
= cPtr
->wasNonBlocking
;
356 // some way to find out if it is connected, and binded. can't find
357 // if it listens though!!!
359 size
= sizeof(clientname
);
360 n
= getpeername(sock
, (struct sockaddr
*) &clientname
, &size
);
362 /* Since we have a peer, it means we are connected */
363 cPtr
->state
= WCConnected
;
365 size
= sizeof(clientname
);
366 n
= getsockname(sock
, (struct sockaddr
*) &clientname
, &size
);
368 /* We don't have a peer, but we are binded to an address.
369 * Assume we are listening on it (we don't know that for sure!)
371 cPtr
->state
= WCListening
;
373 cPtr
->state
= WCNotConnected
;
383 * host is the name on which we want to listen for incoming connections,
384 * and it must be a name of this host, or NULL if we want to listen
385 * on any incoming address.
386 * service is either a service name as present in /etc/services, or the port
387 * number we want to listen on. If NULL, a random port between
388 * 1024 and 65535 will be assigned to us.
389 * protocol is one of "tcp" or "udp". If NULL, "tcp" will be used by default.
390 * currently only "tcp" is supported.
393 WMCreateConnectionAsServerAtAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
396 struct sockaddr_in
*socketaddr
;
399 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
401 wwarning("Bad address-service-protocol combination");
405 /* Create the actual socket */
406 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
409 wsyserror("Unable to create socket");
414 * Set socket options. We try to make the port reusable and have it
415 * close as fast as possible without waiting in unnecessary wait states
419 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
421 if (bind(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
423 wsyserror("Unable to bind to address '%s:%hu'",
424 inet_ntoa(socketaddr
->sin_addr
),
425 ntohs(socketaddr
->sin_port
));
430 if (listen(sock
, 10) < 0) {
432 wsyserror("Unable to listen on port '%hu'",
433 ntohs(socketaddr
->sin_port
));
438 /* Find out what is the address/service/protocol we get */
439 /* In case some of address/service/protocol were NULL */
440 size
= sizeof(*socketaddr
);
441 if (getsockname(sock
, (struct sockaddr
*)socketaddr
, &size
) < 0) {
443 wsyserror("Unable to get socket address");
448 cPtr
= createConnectionWithSocket(sock
, True
);
449 cPtr
->state
= WCListening
;
450 WMSetConnectionNonBlocking(cPtr
, True
);
452 setConnectionAddress(cPtr
, socketaddr
);
459 WMCreateConnectionToAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
462 struct sockaddr_in
*socketaddr
;
465 if (service
==NULL
|| service
[0]=='\0') {
467 wwarning("Bad argument - service is not specified");
471 if (host
==NULL
|| host
[0]=='\0')
474 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
476 wwarning("Bad address-service-protocol combination");
480 /* Create the actual socket */
481 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
484 wsyserror("Unable to create socket");
487 /* make socket blocking while we connect. */
488 setSocketNonBlocking(sock
, False
);
489 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
491 wsyserror("Unable to make connection to address '%s:%hu'",
492 inet_ntoa(socketaddr
->sin_addr
),
493 ntohs(socketaddr
->sin_port
));
498 cPtr
= createConnectionWithSocket(sock
, True
);
499 cPtr
->state
= WCConnected
;
500 WMSetConnectionNonBlocking(cPtr
, True
);
501 setConnectionAddress(cPtr
, socketaddr
);
508 WMCreateConnectionToAddressAndNotify(char *host
, char *service
, char *protocol
) /*FOLD00*/
511 /*TimeoutData *tPtr;*/
512 struct sockaddr_in
*socketaddr
;
516 if (service
==NULL
|| service
[0]=='\0') {
518 wwarning("Bad argument - service is not specified");
522 if (host
==NULL
|| host
[0]=='\0')
525 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
527 wwarning("Bad address-service-protocol combination");
531 /* Create the actual socket */
532 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
535 wsyserror("Unable to create socket");
538 isNonBlocking
= setSocketNonBlocking(sock
, True
);
539 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
540 if (errno
!=EINPROGRESS
) {
542 wsyserror("Unable to make connection to address '%s:%hu'",
543 inet_ntoa(socketaddr
->sin_addr
),
544 ntohs(socketaddr
->sin_port
));
550 cPtr
= createConnectionWithSocket(sock
, True
);
551 cPtr
->state
= WCInProgress
;
552 cPtr
->isNonBlocking
= isNonBlocking
;
554 /*tPtr = &cPtr->sendTimeout;
555 tPtr->handler = WMAddTimerHandler(tPtr->timeout*1000, connectTimeout, cPtr);
557 cPtr
->handler
.write
= WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
560 setConnectionAddress(cPtr
, socketaddr
);
567 removeAllHandlers(WMConnection
*cPtr
) /*FOLD00*/
569 if (cPtr
->handler
.read
)
570 WMDeleteInputHandler(cPtr
->handler
.read
);
571 if (cPtr
->handler
.write
)
572 WMDeleteInputHandler(cPtr
->handler
.write
);
573 if (cPtr
->handler
.exception
)
574 WMDeleteInputHandler(cPtr
->handler
.exception
);
575 if (cPtr
->sendTimeout
.handler
)
576 WMDeleteTimerHandler(cPtr
->sendTimeout
.handler
);
578 cPtr
->handler
.read
= NULL
;
579 cPtr
->handler
.write
= NULL
;
580 cPtr
->handler
.exception
= NULL
;
581 cPtr
->sendTimeout
.handler
= NULL
;
586 WMDestroyConnection(WMConnection
*cPtr
) /*FOLD00*/
588 if (cPtr
->closeOnRelease
&& cPtr
->sock
>=0) {
589 shutdown(cPtr
->sock
, SHUT_RDWR
);
593 removeAllHandlers(cPtr
);
594 clearOutputQueue(cPtr
);
595 WMFreeBag(cPtr
->outputQueue
);
598 wfree(cPtr
->address
);
599 wfree(cPtr
->service
);
600 wfree(cPtr
->protocol
);
608 WMCloseConnection(WMConnection
*cPtr
) /*FOLD00*/
611 shutdown(cPtr
->sock
, SHUT_RDWR
);
616 removeAllHandlers(cPtr
);
617 clearOutputQueue(cPtr
);
619 cPtr
->state
= WCClosed
;
624 WMAcceptConnection(WMConnection
*listener
) /*FOLD00*/
626 struct sockaddr_in clientname
;
629 WMConnection
*newConnection
;
631 if (listener
->state
!=WCListening
) {
632 wwarning("Called 'WMAcceptConnection()' on a non-listening connection");
637 size
= sizeof(clientname
);
638 newSock
= accept(listener
->sock
, (struct sockaddr
*) &clientname
, &size
);
640 if (errno
!=EAGAIN
&& errno
!=EWOULDBLOCK
) {
642 wsyserror("Could not accept connection");
649 newConnection
= createConnectionWithSocket(newSock
, True
);
650 WMSetConnectionNonBlocking(newConnection
, True
);
651 newConnection
->state
= WCConnected
;
652 setConnectionAddress(newConnection
, &clientname
);
654 return newConnection
;
659 WMGetConnectionAddress(WMConnection
*cPtr
) /*FOLD00*/
661 return cPtr
->address
;
666 WMGetConnectionService(WMConnection
*cPtr
) /*FOLD00*/
668 return cPtr
->service
;
673 WMGetConnectionProtocol(WMConnection
*cPtr
)
675 return cPtr
->protocol
;
680 WMGetConnectionSocket(WMConnection
*cPtr
) /*FOLD00*/
687 WMGetConnectionState(WMConnection
*cPtr
) /*FOLD00*/
694 WMEnqueueConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
696 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, False
);
697 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, False
);
699 if (cPtr
->state
!=WCConnected
)
702 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
708 WMSendConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
710 int bytes
, pos
, len
, totalTransfer
;
711 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
712 const void *dataBytes
;
714 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, -1);
715 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, -1);
717 if (cPtr
->state
!=WCConnected
)
720 /* If we have no data just flush the queue, else try to send data */
721 if (data
&& WMGetDataLength(data
)>0) {
722 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
723 /* If there already was something in queue, and also a write input
724 * handler is established, it means we were unable to send, so
725 * return and let the write handler notify us when we can send.
727 if (WMGetBagItemCount(cPtr
->outputQueue
)>1 && cPtr
->handler
.write
)
733 while (WMGetBagItemCount(cPtr
->outputQueue
) > 0) {
734 data
= WMGetFromBag(cPtr
->outputQueue
, 0);
735 dataBytes
= WMDataBytes(data
);
736 len
= WMGetDataLength(data
);
737 pos
= cPtr
->bufPos
; /* where we're left last time */
740 bytes
= write(cPtr
->sock
, dataBytes
+pos
, len
- pos
);
746 /* save the position where we're left and add a timeout */
748 if (!tPtr
->handler
) {
749 tPtr
->handler
= WMAddTimerHandler(tPtr
->timeout
*1000,
752 if (!cPtr
->handler
.write
) {
753 cPtr
->handler
.write
=
754 WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
757 return totalTransfer
;
760 cPtr
->state
= WCDied
;
761 /*clearOutputQueue(cPtr);*/
762 removeAllHandlers(cPtr
);
763 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
764 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
769 totalTransfer
+= bytes
;
772 WMDeleteFromBag(cPtr
->outputQueue
, 0);
775 WMDeleteTimerHandler(tPtr
->handler
);
776 tPtr
->handler
= NULL
;
778 if (cPtr
->handler
.write
) {
779 WMDeleteInputHandler(cPtr
->handler
.write
);
780 cPtr
->handler
.write
= NULL
;
784 return totalTransfer
;
789 * WMGetConnectionAvailableData(connection):
791 * will return a WMData structure containing the available data on the
792 * specified connection. If connection is non-blocking (default) and no data
793 * is available when this function is called, an empty WMData is returned.
795 * If an error occurs while reading or the other side closed connection,
796 * it will return NULL.
797 * Also trying to read from an already died or closed connection is
798 * considered to be an error condition, and will return NULL.
801 WMGetConnectionAvailableData(WMConnection
*cPtr
) /*FOLD00*/
803 char buffer
[NETBUF_SIZE
];
807 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, NULL
);
808 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, NULL
);
810 if (cPtr
->state
!=WCConnected
)
816 nbytes
= read(cPtr
->sock
, buffer
, NETBUF_SIZE
);
822 aData
= WMCreateDataWithCapacity(0);
826 cPtr
->state
= WCDied
;
827 removeAllHandlers(cPtr
);
828 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
829 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
832 } else if (nbytes
==0) { /* the other side has closed connection */
833 cPtr
->state
= WCClosed
;
834 removeAllHandlers(cPtr
);
835 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
836 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
838 aData
= WMCreateDataWithBytes(buffer
, nbytes
);
846 WMSetConnectionDelegate(WMConnection
*cPtr
, ConnectionDelegate
*delegate
) /*FOLD00*/
848 wassertr(cPtr
->sock
>= 0);
849 /* Don't try to set the delegate multiple times */
850 wassertr(cPtr
->delegate
== NULL
);
852 cPtr
->delegate
= delegate
;
853 if (delegate
&& delegate
->didReceiveInput
&& !cPtr
->handler
.read
)
854 cPtr
->handler
.read
= WMAddInputHandler(cPtr
->sock
, WIReadMask
,
856 if (delegate
&& delegate
->didCatchException
&& !cPtr
->handler
.exception
)
857 cPtr
->handler
.exception
= WMAddInputHandler(cPtr
->sock
, WIExceptMask
,
864 WMIsConnectionNonBlocking(WMConnection
*cPtr
) /*FOLD00*/
869 state
= fcntl(cPtr
->sock
, F_GETFL
, 0);
872 wsyserror("Failed to get socket flags with fcntl.");
873 /* If we can't use fcntl on socket, this probably also means we could
874 * not use fcntl to set non-blocking mode, and since a socket defaults
875 * to blocking when created, return False as the best assumption */
879 return ((state
& NONBLOCK_OPT
)!=0);
881 return cPtr
->isNonBlocking
;
888 WMSetConnectionNonBlocking(WMConnection
*cPtr
, Bool flag
) /*FOLD00*/
893 if (cPtr
->isNonBlocking
== flag
)
896 if (setSocketNonBlocking(cPtr
->sock
, flag
)==True
)
897 cPtr
->isNonBlocking
= flag
;
902 WMGetConnectionClientData(WMConnection
*cPtr
) /*FOLD00*/
904 return cPtr
->clientData
;
909 WMSetConnectionClientData(WMConnection
*cPtr
, void *data
) /*FOLD00*/
911 cPtr
->clientData
= data
;
916 WMGetConnectionFlags(WMConnection
*cPtr
) /*FOLD00*/
923 WMSetConnectionFlags(WMConnection
*cPtr
, unsigned int flags
) /*FOLD00*/
925 cPtr
->uflags
= flags
;
930 WMSetConnectionSendTimeout(WMConnection
*cPtr
, unsigned int timeout
) /*FOLD00*/
933 timeout
= DEF_TIMEOUT
;
935 cPtr
->sendTimeout
.timeout
= timeout
;