2 * WINGs WMConnection function library
4 * Copyright (c) 1999-2000 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 /* For some Solaris systems */
62 #if !defined(HAVE_INET_ATON) && !defined(INADDR_NONE)
63 # define INADDR_NONE (-1)
66 /* Stuff for setting the sockets into non-blocking mode. */
67 /*#ifdef __POSIX_SOURCE
68 # define NONBLOCK_OPT O_NONBLOCK
70 # define NONBLOCK_OPT FNDELAY
73 #define NONBLOCK_OPT O_NONBLOCK
75 #define NETBUF_SIZE 4096
77 #define DEF_TIMEOUT 600 /* 600 seconds == 10 minutes */
84 static Bool SigInitialized
= False
;
88 typedef struct TimeoutData
{
95 typedef struct W_Connection
{
96 int sock
; /* the socket we speak through */
99 WMHandlerID
*read
; /* the input read handler */
100 WMHandlerID
*write
; /* the input write handler */
101 WMHandlerID
*exception
; /* the input exception handler */
104 ConnectionDelegate
*delegate
; /* client delegates */
105 void *clientData
; /* client data */
106 unsigned int uflags
; /* flags for the client */
111 TimeoutData sendTimeout
;
113 WMConnectionState state
;
129 clearOutputQueue(WMConnection
*cPtr
) /*FOLD00*/
135 for (i
=0; i
<WMGetBagItemCount(cPtr
->outputQueue
); i
++)
136 WMReleaseData(WMGetFromBag(cPtr
->outputQueue
, i
));
138 WMEmptyBag(cPtr
->outputQueue
);
143 sendTimeout(void *cdata
) /*FOLD00*/
145 WMConnection
*cPtr
= (WMConnection
*) cdata
;
146 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
148 tPtr
->handler
= NULL
;
149 if (cPtr
->handler
.write
) {
150 WMDeleteInputHandler(cPtr
->handler
.write
);
151 cPtr
->handler
.write
= NULL
;
153 if (WMGetBagItemCount(cPtr
->outputQueue
)>0) {
154 clearOutputQueue(cPtr
);
155 if (cPtr
->delegate
&& cPtr
->delegate
->didTimeout
)
156 (*cPtr
->delegate
->didTimeout
)(cPtr
->delegate
, cPtr
);
162 inputHandler(int fd
, int mask
, void *clientData
) /*FOLD00*/
164 WMConnection
*cPtr
= (WMConnection
*)clientData
;
166 if (cPtr
->state
==WCClosed
|| cPtr
->state
==WCDied
)
169 if ((mask
& WIWriteMask
)) {
170 if (cPtr
->state
== WCInProgress
) {
172 int len
= sizeof(result
);
174 if (getsockopt(cPtr
->sock
, SOL_SOCKET
, SO_ERROR
,
175 (void*)&result
, &len
) == 0 && result
!= 0) {
176 cPtr
->state
= WCFailed
;
177 WCErrorCode
= result
;
178 /* should call wsyserrorwithcode(result, ...) here? */
180 cPtr
->state
= WCConnected
;
183 if (cPtr
->handler
.write
) {
184 WMDeleteInputHandler(cPtr
->handler
.write
);
185 cPtr
->handler
.write
= NULL
;
188 if (cPtr
->delegate
&& cPtr
->delegate
->didInitialize
)
189 (*cPtr
->delegate
->didInitialize
)(cPtr
->delegate
, cPtr
);
191 if (cPtr
->state
== WCFailed
)
193 } else if (cPtr
->state
== WCConnected
) {
194 WMFlushConnection(cPtr
);
201 /* if the connection died, may get destroyed in the delegate, so retain */
204 if ((mask
& WIReadMask
) && cPtr
->delegate
->didReceiveInput
)
205 (*cPtr
->delegate
->didReceiveInput
)(cPtr
->delegate
, cPtr
);
207 if ((mask
& WIExceptMask
) && cPtr
->delegate
->didCatchException
)
208 (*cPtr
->delegate
->didCatchException
)(cPtr
->delegate
, cPtr
);
215 setSocketNonBlocking(int sock
, Bool flag
) /*FOLD00*/
220 state
= fcntl(sock
, F_GETFL
, 0);
223 wsyserror("Failed to get socket flags with fcntl.");
227 isNonBlock
= (state
& NONBLOCK_OPT
) != 0;
232 state
|= NONBLOCK_OPT
;
236 state
&= ~NONBLOCK_OPT
;
239 if (fcntl(sock
, F_SETFL
, state
) < 0) {
240 wsyserror("Failed to set socket flags with fcntl.");
249 setConnectionAddress(WMConnection
*cPtr
, struct sockaddr_in
*socketaddr
) /*FOLD00*/
251 wassertr(cPtr
->address
==NULL
);
253 cPtr
->address
= wstrdup(inet_ntoa(socketaddr
->sin_addr
));
254 cPtr
->service
= wmalloc(16);
255 sprintf(cPtr
->service
, "%hu", ntohs(socketaddr
->sin_port
));
256 cPtr
->protocol
= wstrdup("tcp");
260 static struct sockaddr_in
*
261 getSocketAddress(char* name
, char* service
, char* protocol
) /*FOLD00*/
263 static struct sockaddr_in socketaddr
;
266 if (!protocol
|| protocol
[0]=='\0')
269 memset(&socketaddr
, 0, sizeof(struct sockaddr_in
));
270 socketaddr
.sin_family
= AF_INET
;
273 * If we were given a hostname, we use any address for that host.
274 * Otherwise we expect the given name to be an address unless it is
275 * NULL (any address).
277 if (name
&& name
[0]!='\0') {
278 WMHost
*host
= WMGetHostWithName(name
);
281 return NULL
; /* name is not a hostname nor a number and dot adr */
283 name
= WMGetHostAddress(host
);
284 #ifndef HAVE_INET_ATON
285 if ((socketaddr
.sin_addr
.s_addr
= inet_addr(name
)) == INADDR_NONE
) {
287 if (inet_aton(name
, &socketaddr
.sin_addr
) == 0) {
294 socketaddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
297 if (!service
|| service
[0]=='\0') {
298 socketaddr
.sin_port
= 0;
299 } else if ((sp
= getservbyname(service
, protocol
))==0) {
303 portNumber
= strtoul(service
, &endptr
, 10);
305 if (service
[0]!='\0' && *endptr
=='\0' && portNumber
<65536) {
306 socketaddr
.sin_port
= htons(portNumber
);
311 socketaddr
.sin_port
= sp
->s_port
;
319 createConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
322 struct sigaction sig_action
;
324 cPtr
= wmalloc(sizeof(WMConnection
));
326 memset(cPtr
, 0, sizeof(WMConnection
));
329 cPtr
->sendTimeout
.timeout
= DEF_TIMEOUT
;
330 cPtr
->sendTimeout
.handler
= NULL
;
331 cPtr
->closeOnRelease
= closeOnRelease
;
332 cPtr
->outputQueue
= WMCreateBag(16);
333 cPtr
->state
= WCNotConnected
;
335 /* ignore dead pipe */
336 if (!SigInitialized
) {
337 sig_action
.sa_handler
= SIG_IGN
;
338 sig_action
.sa_flags
= SA_RESTART
;
339 sigaction(SIGPIPE
, &sig_action
, NULL
);
340 SigInitialized
= True
;
349 WMCreateConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
352 struct sockaddr_in clientname
;
355 cPtr
= createConnectionWithSocket(sock
, closeOnRelease
);
356 cPtr
->wasNonBlocking
= WMIsConnectionNonBlocking(cPtr
);
357 cPtr
->isNonBlocking
= cPtr
->wasNonBlocking
;
359 /* some way to find out if it is connected, and binded. can't find
360 if it listens though!!!
363 size
= sizeof(clientname
);
364 n
= getpeername(sock
, (struct sockaddr
*) &clientname
, &size
);
366 /* Since we have a peer, it means we are connected */
367 cPtr
->state
= WCConnected
;
369 size
= sizeof(clientname
);
370 n
= getsockname(sock
, (struct sockaddr
*) &clientname
, &size
);
372 /* We don't have a peer, but we are binded to an address.
373 * Assume we are listening on it (we don't know that for sure!)
375 cPtr
->state
= WCListening
;
377 cPtr
->state
= WCNotConnected
;
387 * host is the name on which we want to listen for incoming connections,
388 * and it must be a name of this host, or NULL if we want to listen
389 * on any incoming address.
390 * service is either a service name as present in /etc/services, or the port
391 * number we want to listen on. If NULL, a random port between
392 * 1024 and 65535 will be assigned to us.
393 * protocol is one of "tcp" or "udp". If NULL, "tcp" will be used by default.
394 * currently only "tcp" is supported.
397 WMCreateConnectionAsServerAtAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
400 struct sockaddr_in
*socketaddr
;
403 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
405 wwarning("Bad address-service-protocol combination");
409 /* Create the actual socket */
410 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
413 wsyserror("Unable to create socket");
418 * Set socket options. We try to make the port reusable and have it
419 * close as fast as possible without waiting in unnecessary wait states
423 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
425 if (bind(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
427 wsyserror("Unable to bind to address '%s:%hu'",
428 inet_ntoa(socketaddr
->sin_addr
),
429 ntohs(socketaddr
->sin_port
));
434 if (listen(sock
, 10) < 0) {
436 wsyserror("Unable to listen on port '%hu'",
437 ntohs(socketaddr
->sin_port
));
442 /* Find out what is the address/service/protocol we get */
443 /* In case some of address/service/protocol were NULL */
444 size
= sizeof(*socketaddr
);
445 if (getsockname(sock
, (struct sockaddr
*)socketaddr
, &size
) < 0) {
447 wsyserror("Unable to get socket address");
452 cPtr
= createConnectionWithSocket(sock
, True
);
453 cPtr
->state
= WCListening
;
454 WMSetConnectionNonBlocking(cPtr
, True
);
456 setConnectionAddress(cPtr
, socketaddr
);
463 WMCreateConnectionToAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
466 struct sockaddr_in
*socketaddr
;
469 if (service
==NULL
|| service
[0]=='\0') {
471 wwarning("Bad argument - service is not specified");
475 if (host
==NULL
|| host
[0]=='\0')
478 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
480 wwarning("Bad address-service-protocol combination");
484 /* Create the actual socket */
485 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
488 wsyserror("Unable to create socket");
491 /* make socket blocking while we connect. */
492 setSocketNonBlocking(sock
, False
);
493 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
495 wsyserror("Unable to make connection to address '%s:%hu'",
496 inet_ntoa(socketaddr
->sin_addr
),
497 ntohs(socketaddr
->sin_port
));
502 cPtr
= createConnectionWithSocket(sock
, True
);
503 cPtr
->state
= WCConnected
;
504 WMSetConnectionNonBlocking(cPtr
, True
);
505 setConnectionAddress(cPtr
, socketaddr
);
512 WMCreateConnectionToAddressAndNotify(char *host
, char *service
, char *protocol
) /*FOLD00*/
515 /*TimeoutData *tPtr;*/
516 struct sockaddr_in
*socketaddr
;
520 if (service
==NULL
|| service
[0]=='\0') {
522 wwarning("Bad argument - service is not specified");
526 if (host
==NULL
|| host
[0]=='\0')
529 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
531 wwarning("Bad address-service-protocol combination");
535 /* Create the actual socket */
536 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
539 wsyserror("Unable to create socket");
542 isNonBlocking
= setSocketNonBlocking(sock
, True
);
543 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
544 if (errno
!=EINPROGRESS
) {
546 wsyserror("Unable to make connection to address '%s:%hu'",
547 inet_ntoa(socketaddr
->sin_addr
),
548 ntohs(socketaddr
->sin_port
));
554 cPtr
= createConnectionWithSocket(sock
, True
);
555 cPtr
->state
= WCInProgress
;
556 cPtr
->isNonBlocking
= isNonBlocking
;
558 /*tPtr = &cPtr->sendTimeout;
559 tPtr->handler = WMAddTimerHandler(tPtr->timeout*1000, connectTimeout, cPtr);
561 cPtr
->handler
.write
= WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
564 setConnectionAddress(cPtr
, socketaddr
);
571 removeAllHandlers(WMConnection
*cPtr
) /*FOLD00*/
573 if (cPtr
->handler
.read
)
574 WMDeleteInputHandler(cPtr
->handler
.read
);
575 if (cPtr
->handler
.write
)
576 WMDeleteInputHandler(cPtr
->handler
.write
);
577 if (cPtr
->handler
.exception
)
578 WMDeleteInputHandler(cPtr
->handler
.exception
);
579 if (cPtr
->sendTimeout
.handler
)
580 WMDeleteTimerHandler(cPtr
->sendTimeout
.handler
);
582 cPtr
->handler
.read
= NULL
;
583 cPtr
->handler
.write
= NULL
;
584 cPtr
->handler
.exception
= NULL
;
585 cPtr
->sendTimeout
.handler
= NULL
;
590 WMDestroyConnection(WMConnection
*cPtr
) /*FOLD00*/
592 if (cPtr
->closeOnRelease
&& cPtr
->sock
>=0) {
593 shutdown(cPtr
->sock
, SHUT_RDWR
);
597 removeAllHandlers(cPtr
);
598 clearOutputQueue(cPtr
);
599 WMFreeBag(cPtr
->outputQueue
);
602 wfree(cPtr
->address
);
603 wfree(cPtr
->service
);
604 wfree(cPtr
->protocol
);
612 WMCloseConnection(WMConnection
*cPtr
) /*FOLD00*/
615 shutdown(cPtr
->sock
, SHUT_RDWR
);
620 removeAllHandlers(cPtr
);
621 clearOutputQueue(cPtr
);
623 cPtr
->state
= WCClosed
;
628 WMAcceptConnection(WMConnection
*listener
) /*FOLD00*/
630 struct sockaddr_in clientname
;
633 WMConnection
*newConnection
;
635 if (listener
->state
!=WCListening
) {
636 wwarning("Called 'WMAcceptConnection()' on a non-listening connection");
641 size
= sizeof(clientname
);
642 newSock
= accept(listener
->sock
, (struct sockaddr
*) &clientname
, &size
);
644 if (errno
!=EAGAIN
&& errno
!=EWOULDBLOCK
) {
646 wsyserror("Could not accept connection");
653 newConnection
= createConnectionWithSocket(newSock
, True
);
654 WMSetConnectionNonBlocking(newConnection
, True
);
655 newConnection
->state
= WCConnected
;
656 setConnectionAddress(newConnection
, &clientname
);
658 return newConnection
;
663 WMGetConnectionAddress(WMConnection
*cPtr
) /*FOLD00*/
665 return cPtr
->address
;
670 WMGetConnectionService(WMConnection
*cPtr
) /*FOLD00*/
672 return cPtr
->service
;
677 WMGetConnectionProtocol(WMConnection
*cPtr
)
679 return cPtr
->protocol
;
684 WMGetConnectionSocket(WMConnection
*cPtr
) /*FOLD00*/
691 WMGetConnectionState(WMConnection
*cPtr
) /*FOLD00*/
698 WMEnqueueConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
700 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, False
);
701 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, False
);
703 if (cPtr
->state
!=WCConnected
)
706 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
712 WMSendConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
714 int bytes
, pos
, len
, totalTransfer
;
715 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
716 const unsigned char *dataBytes
;
718 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, -1);
719 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, -1);
721 if (cPtr
->state
!=WCConnected
)
724 /* If we have no data just flush the queue, else try to send data */
725 if (data
&& WMGetDataLength(data
)>0) {
726 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
727 /* If there already was something in queue, and also a write input
728 * handler is established, it means we were unable to send, so
729 * return and let the write handler notify us when we can send.
731 if (WMGetBagItemCount(cPtr
->outputQueue
)>1 && cPtr
->handler
.write
)
737 while (WMGetBagItemCount(cPtr
->outputQueue
) > 0) {
738 data
= WMGetFromBag(cPtr
->outputQueue
, 0);
739 dataBytes
= (const unsigned char *)WMDataBytes(data
);
740 len
= WMGetDataLength(data
);
741 pos
= cPtr
->bufPos
; /* where we're left last time */
744 bytes
= write(cPtr
->sock
, dataBytes
+pos
, len
- pos
);
750 /* save the position where we're left and add a timeout */
752 if (!tPtr
->handler
) {
753 tPtr
->handler
= WMAddTimerHandler(tPtr
->timeout
*1000,
756 if (!cPtr
->handler
.write
) {
757 cPtr
->handler
.write
=
758 WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
761 return totalTransfer
;
764 cPtr
->state
= WCDied
;
765 /*clearOutputQueue(cPtr);*/
766 removeAllHandlers(cPtr
);
767 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
768 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
773 totalTransfer
+= bytes
;
776 WMDeleteFromBag(cPtr
->outputQueue
, 0);
779 WMDeleteTimerHandler(tPtr
->handler
);
780 tPtr
->handler
= NULL
;
782 if (cPtr
->handler
.write
) {
783 WMDeleteInputHandler(cPtr
->handler
.write
);
784 cPtr
->handler
.write
= NULL
;
788 return totalTransfer
;
793 * WMGetConnectionAvailableData(connection):
795 * will return a WMData structure containing the available data on the
796 * specified connection. If connection is non-blocking (default) and no data
797 * is available when this function is called, an empty WMData is returned.
799 * If an error occurs while reading or the other side closed connection,
800 * it will return NULL.
801 * Also trying to read from an already died or closed connection is
802 * considered to be an error condition, and will return NULL.
805 WMGetConnectionAvailableData(WMConnection
*cPtr
) /*FOLD00*/
807 char buffer
[NETBUF_SIZE
];
811 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, NULL
);
812 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, NULL
);
814 if (cPtr
->state
!=WCConnected
)
820 nbytes
= read(cPtr
->sock
, buffer
, NETBUF_SIZE
);
826 aData
= WMCreateDataWithCapacity(0);
830 cPtr
->state
= WCDied
;
831 removeAllHandlers(cPtr
);
832 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
833 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
836 } else if (nbytes
==0) { /* the other side has closed connection */
837 cPtr
->state
= WCClosed
;
838 removeAllHandlers(cPtr
);
839 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
840 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
842 aData
= WMCreateDataWithBytes(buffer
, nbytes
);
850 WMSetConnectionDelegate(WMConnection
*cPtr
, ConnectionDelegate
*delegate
) /*FOLD00*/
852 wassertr(cPtr
->sock
>= 0);
853 /* Don't try to set the delegate multiple times */
854 wassertr(cPtr
->delegate
== NULL
);
856 cPtr
->delegate
= delegate
;
857 if (delegate
&& delegate
->didReceiveInput
&& !cPtr
->handler
.read
)
858 cPtr
->handler
.read
= WMAddInputHandler(cPtr
->sock
, WIReadMask
,
860 if (delegate
&& delegate
->didCatchException
&& !cPtr
->handler
.exception
)
861 cPtr
->handler
.exception
= WMAddInputHandler(cPtr
->sock
, WIExceptMask
,
868 WMIsConnectionNonBlocking(WMConnection
*cPtr
) /*FOLD00*/
873 state
= fcntl(cPtr
->sock
, F_GETFL
, 0);
876 wsyserror("Failed to get socket flags with fcntl.");
877 /* If we can't use fcntl on socket, this probably also means we could
878 * not use fcntl to set non-blocking mode, and since a socket defaults
879 * to blocking when created, return False as the best assumption */
883 return ((state
& NONBLOCK_OPT
)!=0);
885 return cPtr
->isNonBlocking
;
892 WMSetConnectionNonBlocking(WMConnection
*cPtr
, Bool flag
) /*FOLD00*/
897 if (cPtr
->isNonBlocking
== flag
)
900 if (setSocketNonBlocking(cPtr
->sock
, flag
)==True
)
901 cPtr
->isNonBlocking
= flag
;
906 WMGetConnectionClientData(WMConnection
*cPtr
) /*FOLD00*/
908 return cPtr
->clientData
;
913 WMSetConnectionClientData(WMConnection
*cPtr
, void *data
) /*FOLD00*/
915 cPtr
->clientData
= data
;
920 WMGetConnectionFlags(WMConnection
*cPtr
) /*FOLD00*/
927 WMSetConnectionFlags(WMConnection
*cPtr
, unsigned int flags
) /*FOLD00*/
929 cPtr
->uflags
= flags
;
934 WMSetConnectionSendTimeout(WMConnection
*cPtr
, unsigned int timeout
) /*FOLD00*/
937 timeout
= DEF_TIMEOUT
;
939 cPtr
->sendTimeout
.timeout
= timeout
;