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.
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
42 #include <sys/signal.h>
48 /* Some older systems does not define this (linux libc5, maybe others too) */
58 /* Stuff for setting the sockets into non-blocking mode. */
60 # define NONBLOCK_OPT O_NONBLOCK
62 # define NONBLOCK_OPT FNDELAY
66 #define NETBUF_SIZE 4096
69 #define DEF_TIMEOUT 600 /* 600 seconds == 10 minutes */
76 static Bool SigInitialized
= False
;
80 typedef struct TimeoutData
{
87 typedef struct W_Connection
{
88 int sock
; /* the socket we speak through */
91 WMHandlerID
*read
; /* the input read handler */
92 WMHandlerID
*write
; /* the input write handler */
93 WMHandlerID
*exception
; /* the input exception handler */
96 ConnectionDelegate
*delegate
; /* client delegates */
97 void *clientData
; /* client data */
98 unsigned int uflags
; /* flags for the client */
103 TimeoutData sendTimeout
;
105 WMConnectionState state
;
121 clearOutputQueue(WMConnection
*cPtr
) /*FOLD00*/
127 for (i
=0; i
<WMGetBagItemCount(cPtr
->outputQueue
); i
++)
128 WMReleaseData(WMGetFromBag(cPtr
->outputQueue
, i
));
130 WMEmptyBag(cPtr
->outputQueue
);
135 sendTimeout(void *cdata
) /*FOLD00*/
137 WMConnection
*cPtr
= (WMConnection
*) cdata
;
138 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
140 tPtr
->handler
= NULL
;
141 if (cPtr
->handler
.write
) {
142 WMDeleteInputHandler(cPtr
->handler
.write
);
143 cPtr
->handler
.write
= NULL
;
145 if (WMGetBagItemCount(cPtr
->outputQueue
)>0) {
146 clearOutputQueue(cPtr
);
147 if (cPtr
->delegate
&& cPtr
->delegate
->didTimeout
)
148 (*cPtr
->delegate
->didTimeout
)(cPtr
->delegate
, cPtr
);
154 inputHandler(int fd
, int mask
, void *clientData
) /*FOLD00*/
156 WMConnection
*cPtr
= (WMConnection
*)clientData
;
158 if (cPtr
->state
==WCClosed
|| cPtr
->state
==WCDied
)
161 if ((mask
& WIWriteMask
)) {
162 if (cPtr
->state
== WCInProgress
) {
164 int len
= sizeof(result
);
166 if (getsockopt(cPtr
->sock
, SOL_SOCKET
, SO_ERROR
,
167 (void*)&result
, &len
) == 0 && result
!= 0) {
168 cPtr
->state
= WCFailed
;
169 WCErrorCode
= result
;
171 cPtr
->state
= WCConnected
;
174 if (cPtr
->handler
.write
) {
175 WMDeleteInputHandler(cPtr
->handler
.write
);
176 cPtr
->handler
.write
= NULL
;
179 if (cPtr
->delegate
&& cPtr
->delegate
->didInitialize
)
180 (*cPtr
->delegate
->didInitialize
)(cPtr
->delegate
, cPtr
);
182 if (cPtr
->state
== WCFailed
)
184 } else if (cPtr
->state
== WCConnected
) {
185 WMFlushConnection(cPtr
);
192 /* if the connection died, may get destroyed in the delegate, so retain */
195 if ((mask
& WIReadMask
) && cPtr
->delegate
->didReceiveInput
)
196 (*cPtr
->delegate
->didReceiveInput
)(cPtr
->delegate
, cPtr
);
198 if ((mask
& WIExceptMask
) && cPtr
->delegate
->didCatchException
)
199 (*cPtr
->delegate
->didCatchException
)(cPtr
->delegate
, cPtr
);
206 setSocketNonBlocking(int sock
, Bool flag
) /*FOLD00*/
211 state
= fcntl(sock
, F_GETFL
, 0);
214 wsyserror("Failed to get socket flags with fcntl.");
218 isNonBlock
= (state
& NONBLOCK_OPT
) != 0;
223 state
|= NONBLOCK_OPT
;
227 state
&= ~NONBLOCK_OPT
;
230 if (fcntl(sock
, F_SETFL
, state
) < 0) {
231 wsyserror("Failed to set socket flags with fcntl.");
240 setConnectionAddress(WMConnection
*cPtr
, struct sockaddr_in
*socketaddr
) /*FOLD00*/
242 wassertr(cPtr
->address
==NULL
);
244 cPtr
->address
= wstrdup(inet_ntoa(socketaddr
->sin_addr
));
245 cPtr
->service
= wmalloc(16);
246 sprintf(cPtr
->service
, "%hu", ntohs(socketaddr
->sin_port
));
247 cPtr
->protocol
= wstrdup("tcp");
251 static struct sockaddr_in
*
252 getSocketAddress(char* name
, char* service
, char* protocol
) /*FOLD00*/
254 static struct sockaddr_in socketaddr
;
257 if (!protocol
|| protocol
[0]=='\0')
260 memset(&socketaddr
, 0, sizeof(struct sockaddr_in
));
261 socketaddr
.sin_family
= AF_INET
;
264 * If we were given a hostname, we use any address for that host.
265 * Otherwise we expect the given name to be an address unless it is
266 * NULL (any address).
268 if (name
&& name
[0]!='\0') {
269 WMHost
*host
= WMGetHostWithName(name
);
272 return NULL
; /* name is not a hostname nor a number and dot adr */
274 name
= WMGetHostAddress(host
);
275 if (inet_aton(name
, &socketaddr
.sin_addr
) == 0) {
281 socketaddr
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
284 if (!service
|| service
[0]=='\0') {
285 socketaddr
.sin_port
= 0;
286 } else if ((sp
= getservbyname(service
, protocol
))==0) {
290 portNumber
= strtoul(service
, &endptr
, 10);
292 if (service
[0]!='\0' && *endptr
=='\0' && portNumber
<65536) {
293 socketaddr
.sin_port
= htons(portNumber
);
298 socketaddr
.sin_port
= sp
->s_port
;
306 createConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
309 struct sigaction sig_action
;
311 cPtr
= wmalloc(sizeof(WMConnection
));
313 memset(cPtr
, 0, sizeof(WMConnection
));
316 cPtr
->sendTimeout
.timeout
= DEF_TIMEOUT
;
317 cPtr
->sendTimeout
.handler
= NULL
;
318 cPtr
->closeOnRelease
= closeOnRelease
;
319 cPtr
->outputQueue
= WMCreateBag(16);
320 cPtr
->state
= WCNotConnected
;
322 /* ignore dead pipe */
323 if (!SigInitialized
) {
324 sig_action
.sa_handler
= SIG_IGN
;
325 sig_action
.sa_flags
= SA_RESTART
;
326 sigaction(SIGPIPE
, &sig_action
, NULL
);
327 SigInitialized
= True
;
336 WMCreateConnectionWithSocket(int sock
, Bool closeOnRelease
) /*FOLD00*/
339 struct sockaddr_in clientname
;
342 cPtr
= createConnectionWithSocket(sock
, closeOnRelease
);
343 cPtr
->wasNonBlocking
= WMIsConnectionNonBlocking(cPtr
);
344 cPtr
->isNonBlocking
= cPtr
->wasNonBlocking
;
346 // some way to find out if it is connected, and binded. can't find
347 // if it listens though!!!
349 size
= sizeof(clientname
);
350 n
= getpeername(sock
, (struct sockaddr
*) &clientname
, &size
);
352 /* Since we have a peer, it means we are connected */
353 cPtr
->state
= WCConnected
;
355 size
= sizeof(clientname
);
356 n
= getsockname(sock
, (struct sockaddr
*) &clientname
, &size
);
358 /* We don't have a peer, but we are binded to an address.
359 * Assume we are listening on it (we don't know that for sure!)
361 cPtr
->state
= WCListening
;
363 cPtr
->state
= WCNotConnected
;
373 * host is the name on which we want to listen for incoming connections,
374 * and it must be a name of this host, or NULL if we want to listen
375 * on any incoming address.
376 * service is either a service name as present in /etc/services, or the port
377 * number we want to listen on. If NULL, a random port between
378 * 1024 and 65535 will be assigned to us.
379 * protocol is one of "tcp" or "udp". If NULL, "tcp" will be used by default.
380 * currently only "tcp" is supported.
383 WMCreateConnectionAsServerAtAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
386 struct sockaddr_in
*socketaddr
;
389 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
391 wwarning("Bad address-service-protocol combination");
395 /* Create the actual socket */
396 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
399 wsyserror("Unable to create socket");
404 * Set socket options. We try to make the port reusable and have it
405 * close as fast as possible without waiting in unnecessary wait states
409 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&on
, sizeof(on
));
411 if (bind(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
413 wsyserror("Unable to bind to address '%s:%hu'",
414 inet_ntoa(socketaddr
->sin_addr
),
415 ntohs(socketaddr
->sin_port
));
420 if (listen(sock
, 10) < 0) {
422 wsyserror("Unable to listen on port '%hu'",
423 ntohs(socketaddr
->sin_port
));
428 /* Find out what is the address/service/protocol we get */
429 /* In case some of address/service/protocol were NULL */
430 size
= sizeof(*socketaddr
);
431 if (getsockname(sock
, (struct sockaddr
*)socketaddr
, &size
) < 0) {
433 wsyserror("Unable to get socket address");
438 cPtr
= createConnectionWithSocket(sock
, True
);
439 cPtr
->state
= WCListening
;
440 WMSetConnectionNonBlocking(cPtr
, True
);
442 setConnectionAddress(cPtr
, socketaddr
);
449 WMCreateConnectionToAddress(char *host
, char *service
, char *protocol
) /*FOLD00*/
452 struct sockaddr_in
*socketaddr
;
455 if (service
==NULL
|| service
[0]=='\0') {
457 wwarning("Bad argument - service is not specified");
461 if (host
==NULL
|| host
[0]=='\0')
464 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
466 wwarning("Bad address-service-protocol combination");
470 /* Create the actual socket */
471 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
474 wsyserror("Unable to create socket");
477 /* make socket blocking while we connect. */
478 setSocketNonBlocking(sock
, False
);
479 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
481 wsyserror("Unable to make connection to address '%s:%hu'",
482 inet_ntoa(socketaddr
->sin_addr
),
483 ntohs(socketaddr
->sin_port
));
488 cPtr
= createConnectionWithSocket(sock
, True
);
489 cPtr
->state
= WCConnected
;
490 WMSetConnectionNonBlocking(cPtr
, True
);
491 setConnectionAddress(cPtr
, socketaddr
);
498 WMCreateConnectionToAddressAndNotify(char *host
, char *service
, char *protocol
) /*FOLD00*/
501 /*TimeoutData *tPtr;*/
502 struct sockaddr_in
*socketaddr
;
506 if (service
==NULL
|| service
[0]=='\0') {
508 wwarning("Bad argument - service is not specified");
512 if (host
==NULL
|| host
[0]=='\0')
515 if ((socketaddr
= getSocketAddress(host
, service
, protocol
)) == NULL
) {
517 wwarning("Bad address-service-protocol combination");
521 /* Create the actual socket */
522 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
525 wsyserror("Unable to create socket");
528 isNonBlocking
= setSocketNonBlocking(sock
, True
);
529 if (connect(sock
, (struct sockaddr
*)socketaddr
, sizeof(*socketaddr
)) < 0) {
530 if (errno
!=EINPROGRESS
) {
532 wsyserror("Unable to make connection to address '%s:%hu'",
533 inet_ntoa(socketaddr
->sin_addr
),
534 ntohs(socketaddr
->sin_port
));
540 cPtr
= createConnectionWithSocket(sock
, True
);
541 cPtr
->state
= WCInProgress
;
542 cPtr
->isNonBlocking
= isNonBlocking
;
544 /*tPtr = &cPtr->sendTimeout;
545 tPtr->handler = WMAddTimerHandler(tPtr->timeout*1000, connectTimeout, cPtr);
547 cPtr
->handler
.write
= WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
550 setConnectionAddress(cPtr
, socketaddr
);
557 removeAllHandlers(WMConnection
*cPtr
) /*FOLD00*/
559 if (cPtr
->handler
.read
)
560 WMDeleteInputHandler(cPtr
->handler
.read
);
561 if (cPtr
->handler
.write
)
562 WMDeleteInputHandler(cPtr
->handler
.write
);
563 if (cPtr
->handler
.exception
)
564 WMDeleteInputHandler(cPtr
->handler
.exception
);
565 if (cPtr
->sendTimeout
.handler
)
566 WMDeleteTimerHandler(cPtr
->sendTimeout
.handler
);
568 cPtr
->handler
.read
= NULL
;
569 cPtr
->handler
.write
= NULL
;
570 cPtr
->handler
.exception
= NULL
;
571 cPtr
->sendTimeout
.handler
= NULL
;
576 WMDestroyConnection(WMConnection
*cPtr
) /*FOLD00*/
578 if (cPtr
->closeOnRelease
&& cPtr
->sock
>=0) {
579 shutdown(cPtr
->sock
, SHUT_RDWR
);
583 removeAllHandlers(cPtr
);
584 clearOutputQueue(cPtr
);
585 WMFreeBag(cPtr
->outputQueue
);
588 wfree(cPtr
->address
);
589 wfree(cPtr
->service
);
590 wfree(cPtr
->protocol
);
598 WMCloseConnection(WMConnection
*cPtr
) /*FOLD00*/
601 shutdown(cPtr
->sock
, SHUT_RDWR
);
606 removeAllHandlers(cPtr
);
607 clearOutputQueue(cPtr
);
609 cPtr
->state
= WCClosed
;
614 WMAcceptConnection(WMConnection
*listener
) /*FOLD00*/
616 struct sockaddr_in clientname
;
619 WMConnection
*newConnection
;
621 if (listener
->state
!=WCListening
) {
622 wwarning("Called 'WMAcceptConnection()' on a non-listening connection");
627 size
= sizeof(clientname
);
628 newSock
= accept(listener
->sock
, (struct sockaddr
*) &clientname
, &size
);
630 if (errno
!=EAGAIN
&& errno
!=EWOULDBLOCK
) {
632 wsyserror("Could not accept connection");
639 newConnection
= createConnectionWithSocket(newSock
, True
);
640 WMSetConnectionNonBlocking(newConnection
, True
);
641 newConnection
->state
= WCConnected
;
642 setConnectionAddress(newConnection
, &clientname
);
644 return newConnection
;
649 WMGetConnectionAddress(WMConnection
*cPtr
) /*FOLD00*/
651 return cPtr
->address
;
656 WMGetConnectionService(WMConnection
*cPtr
) /*FOLD00*/
658 return cPtr
->service
;
663 WMGetConnectionProtocol(WMConnection
*cPtr
)
665 return cPtr
->protocol
;
670 WMGetConnectionSocket(WMConnection
*cPtr
) /*FOLD00*/
677 WMGetConnectionState(WMConnection
*cPtr
) /*FOLD00*/
684 WMEnqueueConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
686 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, False
);
687 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, False
);
689 if (cPtr
->state
!=WCConnected
)
692 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
698 WMSendConnectionData(WMConnection
*cPtr
, WMData
*data
) /*FOLD00*/
700 int bytes
, pos
, len
, totalTransfer
;
701 TimeoutData
*tPtr
= &cPtr
->sendTimeout
;
702 const void *dataBytes
;
704 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, -1);
705 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, -1);
707 if (cPtr
->state
!=WCConnected
)
710 /* If we have no data just flush the queue, else try to send data */
711 if (data
&& WMGetDataLength(data
)>0) {
712 WMPutInBag(cPtr
->outputQueue
, WMRetainData(data
));
713 /* If there already was something in queue, and also a write input
714 * handler is established, it means we were unable to send, so
715 * return and let the write handler notify us when we can send.
717 if (WMGetBagItemCount(cPtr
->outputQueue
)>1 && cPtr
->handler
.write
)
723 while (WMGetBagItemCount(cPtr
->outputQueue
) > 0) {
724 data
= WMGetFromBag(cPtr
->outputQueue
, 0);
725 dataBytes
= WMDataBytes(data
);
726 len
= WMGetDataLength(data
);
727 pos
= cPtr
->bufPos
; /* where we're left last time */
730 bytes
= write(cPtr
->sock
, dataBytes
+pos
, len
- pos
);
736 /* save the position where we're left and add a timeout */
738 if (!tPtr
->handler
) {
739 tPtr
->handler
= WMAddTimerHandler(tPtr
->timeout
*1000,
742 if (!cPtr
->handler
.write
) {
743 cPtr
->handler
.write
=
744 WMAddInputHandler(cPtr
->sock
, WIWriteMask
,
747 return totalTransfer
;
750 cPtr
->state
= WCDied
;
751 /*clearOutputQueue(cPtr);*/
752 removeAllHandlers(cPtr
);
753 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
754 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
759 totalTransfer
+= bytes
;
762 WMDeleteFromBag(cPtr
->outputQueue
, 0);
765 WMDeleteTimerHandler(tPtr
->handler
);
766 tPtr
->handler
= NULL
;
768 if (cPtr
->handler
.write
) {
769 WMDeleteInputHandler(cPtr
->handler
.write
);
770 cPtr
->handler
.write
= NULL
;
774 return totalTransfer
;
779 * WMGetConnectionAvailableData(connection):
781 * will return a WMData structure containing the available data on the
782 * specified connection. If connection is non-blocking (default) and no data
783 * is available when this function is called, an empty WMData is returned.
785 * If an error occurs while reading or the other side closed connection,
786 * it will return NULL.
787 * Also trying to read from an already died or closed connection is
788 * considered to be an error condition, and will return NULL.
791 WMGetConnectionAvailableData(WMConnection
*cPtr
) /*FOLD00*/
793 char buffer
[NETBUF_SIZE
];
797 wassertrv(cPtr
->state
!=WCNotConnected
&& cPtr
->state
!=WCListening
, NULL
);
798 wassertrv(cPtr
->state
!=WCInProgress
&& cPtr
->state
!=WCFailed
, NULL
);
800 if (cPtr
->state
!=WCConnected
)
806 nbytes
= read(cPtr
->sock
, buffer
, NETBUF_SIZE
);
812 aData
= WMCreateDataWithCapacity(0);
816 cPtr
->state
= WCDied
;
817 removeAllHandlers(cPtr
);
818 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
819 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
822 } else if (nbytes
==0) { /* the other side has closed connection */
823 cPtr
->state
= WCClosed
;
824 removeAllHandlers(cPtr
);
825 if (cPtr
->delegate
&& cPtr
->delegate
->didDie
)
826 (*cPtr
->delegate
->didDie
)(cPtr
->delegate
, cPtr
);
828 aData
= WMCreateDataWithBytes(buffer
, nbytes
);
836 WMSetConnectionDelegate(WMConnection
*cPtr
, ConnectionDelegate
*delegate
) /*FOLD00*/
838 wassertr(cPtr
->sock
>= 0);
839 /* Don't try to set the delegate multiple times */
840 wassertr(cPtr
->delegate
== NULL
);
842 cPtr
->delegate
= delegate
;
843 if (delegate
&& delegate
->didReceiveInput
&& !cPtr
->handler
.read
)
844 cPtr
->handler
.read
= WMAddInputHandler(cPtr
->sock
, WIReadMask
,
846 if (delegate
&& delegate
->didCatchException
&& !cPtr
->handler
.exception
)
847 cPtr
->handler
.exception
= WMAddInputHandler(cPtr
->sock
, WIExceptMask
,
854 WMIsConnectionNonBlocking(WMConnection
*cPtr
) /*FOLD00*/
859 state
= fcntl(cPtr
->sock
, F_GETFL
, 0);
862 wsyserror("Failed to get socket flags with fcntl.");
863 /* If we can't use fcntl on socket, this probably also means we could
864 * not use fcntl to set non-blocking mode, and since a socket defaults
865 * to blocking when created, return False as the best assumption */
869 return ((state
& NONBLOCK_OPT
)!=0);
871 return cPtr
->isNonBlocking
;
878 WMSetConnectionNonBlocking(WMConnection
*cPtr
, Bool flag
) /*FOLD00*/
883 if (cPtr
->isNonBlocking
== flag
)
886 if (setSocketNonBlocking(cPtr
->sock
, flag
)==True
)
887 cPtr
->isNonBlocking
= flag
;
892 WMGetConnectionClientData(WMConnection
*cPtr
) /*FOLD00*/
894 return cPtr
->clientData
;
899 WMSetConnectionClientData(WMConnection
*cPtr
, void *data
) /*FOLD00*/
901 cPtr
->clientData
= data
;
906 WMGetConnectionFlags(WMConnection
*cPtr
) /*FOLD00*/
913 WMSetConnectionFlags(WMConnection
*cPtr
, unsigned int flags
) /*FOLD00*/
915 cPtr
->uflags
= flags
;
920 WMSetConnectionSendTimeout(WMConnection
*cPtr
, unsigned int timeout
) /*FOLD00*/
923 timeout
= DEF_TIMEOUT
;
925 cPtr
->sendTimeout
.timeout
= timeout
;