- Fixed a bug that crashed wmaker when closing a window if multiple screens
[wmaker-crm.git] / WINGs / connection.c
blob19860915e6d116a4300bf1061398b2ae6d5b15f4
1 /*
2 * WINGs WMConnection function library
3 *
4 * Copyright (c) 1999-2000 Dan Pascu
5 *
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.
23 * TODO:
24 * - decide if we want to support connections with external sockets, else
25 * clean up the structure of the unneeded members.
26 * - decide what to do with all wwarning() calls that are still there.
31 #include "wconfig.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdarg.h>
39 #include <errno.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <netdb.h>
44 #include <signal.h>
45 #ifdef __FreeBSD__
46 #include <sys/signal.h>
47 #endif
49 #include "WINGs.h"
52 /* Some older systems does not define this (linux libc5, maybe others too) */
53 #ifndef SHUT_RDWR
54 # define SHUT_RDWR 2
55 #endif
57 /* For SunOS */
58 #ifndef SA_RESTART
59 # define SA_RESTART 0
60 #endif
62 /* For Solaris */
63 #ifndef INADDR_NONE
64 # define INADDR_NONE -1
65 #endif
67 /* Stuff for setting the sockets into non-blocking mode. */
68 /*#ifdef __POSIX_SOURCE
69 # define NONBLOCK_OPT O_NONBLOCK
70 #else
71 # define NONBLOCK_OPT FNDELAY
72 #endif*/
74 #define NONBLOCK_OPT O_NONBLOCK
76 #define NETBUF_SIZE 4096
78 #define DEF_TIMEOUT 600 /* 600 seconds == 10 minutes */
82 int WCErrorCode = 0;
84 static Bool SigInitialized = False;
86 static unsigned int DefaultTimeout = DEF_TIMEOUT;
87 static unsigned int OpenTimeout = DEF_TIMEOUT;
91 typedef struct TimeoutData {
92 unsigned timeout;
93 WMHandlerID *handler;
94 } TimeoutData;
97 typedef struct W_Connection {
98 int sock; /* the socket we speak through */
100 struct {
101 WMHandlerID *read; /* the input read handler */
102 WMHandlerID *write; /* the input write handler */
103 WMHandlerID *exception; /* the input exception handler */
104 } handler;
106 ConnectionDelegate *delegate; /* client delegates */
107 void *clientData; /* client data */
108 unsigned int uflags; /* flags for the client */
110 WMArray *outputQueue;
111 unsigned bufPos;
113 TimeoutData sendTimeout;
114 TimeoutData openTimeout;
116 WMConnectionState state;
117 WMConnectionTimeoutState timeoutState;
119 char *address;
120 char *service;
121 char *protocol;
123 Bool closeOnRelease;
124 Bool wasNonBlocking;
125 Bool isNonBlocking;
127 } W_Connection;
131 static void
132 clearOutputQueue(WMConnection *cPtr)
134 cPtr->bufPos = 0;
135 WMEmptyArray(cPtr->outputQueue);
139 static void
140 openTimeout(void *cdata)
142 WMConnection *cPtr = (WMConnection*) cdata;
144 cPtr->openTimeout.handler = NULL;
145 if (cPtr->handler.write) {
146 WMDeleteInputHandler(cPtr->handler.write);
147 cPtr->handler.write = NULL;
149 if (cPtr->state != WCConnected) {
150 cPtr->state = WCTimedOut;
151 cPtr->timeoutState = WCTWhileOpening;
152 if (cPtr->delegate && cPtr->delegate->didTimeout) {
153 (*cPtr->delegate->didTimeout)(cPtr->delegate, cPtr);
154 } else {
155 WMCloseConnection(cPtr);
156 cPtr->state = WCTimedOut; /* the above set state to WCClosed */
162 static void
163 sendTimeout(void *cdata)
165 WMConnection *cPtr = (WMConnection*) cdata;
167 cPtr->sendTimeout.handler = NULL;
168 if (cPtr->handler.write) {
169 WMDeleteInputHandler(cPtr->handler.write);
170 cPtr->handler.write = NULL;
172 if (WMGetArrayItemCount(cPtr->outputQueue)>0) {
173 clearOutputQueue(cPtr);
174 cPtr->state = WCTimedOut;
175 cPtr->timeoutState = WCTWhileSending;
176 if (cPtr->delegate && cPtr->delegate->didTimeout) {
177 (*cPtr->delegate->didTimeout)(cPtr->delegate, cPtr);
178 } else {
179 WMCloseConnection(cPtr);
180 cPtr->state = WCTimedOut; /* the above set state to WCClosed */
186 static void
187 inputHandler(int fd, int mask, void *clientData)
189 WMConnection *cPtr = (WMConnection*)clientData;
191 if (cPtr->state==WCClosed || cPtr->state==WCDied)
192 return;
194 if ((mask & WIWriteMask)) {
195 if (cPtr->state == WCInProgress) {
196 Bool failed;
197 int result;
198 int len = sizeof(result);
200 WCErrorCode = 0;
201 if (getsockopt(cPtr->sock, SOL_SOCKET, SO_ERROR,
202 (void*)&result, &len) == 0 && result != 0) {
203 cPtr->state = WCFailed;
204 WCErrorCode = result;
205 failed = True;
206 /* should call wsyserrorwithcode(result, ...) here? */
207 } else {
208 cPtr->state = WCConnected;
209 failed = False;
212 if (cPtr->handler.write) {
213 WMDeleteInputHandler(cPtr->handler.write);
214 cPtr->handler.write = NULL;
217 if (cPtr->openTimeout.handler) {
218 WMDeleteTimerHandler(cPtr->openTimeout.handler);
219 cPtr->openTimeout.handler = NULL;
222 if (cPtr->delegate && cPtr->delegate->didInitialize)
223 (*cPtr->delegate->didInitialize)(cPtr->delegate, cPtr);
225 /* we use failed and not cPtr->state here, because cPtr may be
226 * destroyed by the delegate called above if the connection failed
228 if (failed)
229 return;
230 } else if (cPtr->state == WCConnected) {
231 WMFlushConnection(cPtr);
235 if (!cPtr->delegate)
236 return;
238 /* if the connection died, may get destroyed in the delegate, so retain */
239 wretain(cPtr);
241 if ((mask & WIReadMask) && cPtr->delegate->didReceiveInput)
242 (*cPtr->delegate->didReceiveInput)(cPtr->delegate, cPtr);
244 if ((mask & WIExceptMask) && cPtr->delegate->didCatchException)
245 (*cPtr->delegate->didCatchException)(cPtr->delegate, cPtr);
247 wrelease(cPtr);
251 static Bool
252 setSocketNonBlocking(int sock, Bool flag)
254 int state;
255 Bool isNonBlock;
257 state = fcntl(sock, F_GETFL, 0);
259 if (state < 0) {
260 /* set WCErrorCode here? -Dan*/
261 return False;
264 isNonBlock = (state & NONBLOCK_OPT) != 0;
266 if (flag) {
267 if (isNonBlock)
268 return True;
269 state |= NONBLOCK_OPT;
270 } else {
271 if (!isNonBlock)
272 return True;
273 state &= ~NONBLOCK_OPT;
276 if (fcntl(sock, F_SETFL, state) < 0) {
277 /* set WCErrorCode here? -Dan*/
278 return False;
281 return True;
285 static void
286 setConnectionAddress(WMConnection *cPtr, struct sockaddr_in *socketaddr)
288 wassertr(cPtr->address==NULL);
290 cPtr->address = wstrdup(inet_ntoa(socketaddr->sin_addr));
291 cPtr->service = wmalloc(16);
292 sprintf(cPtr->service, "%hu", ntohs(socketaddr->sin_port));
293 cPtr->protocol = wstrdup("tcp");
297 static struct sockaddr_in*
298 getSocketAddress(char* name, char* service, char* protocol)
300 static struct sockaddr_in socketaddr;
301 struct servent *sp;
303 if (!protocol || protocol[0]==0)
304 protocol = "tcp";
306 memset(&socketaddr, 0, sizeof(struct sockaddr_in));
307 socketaddr.sin_family = AF_INET;
310 * If we were given a hostname, we use any address for that host.
311 * Otherwise we expect the given name to be an address unless it is
312 * NULL (any address).
314 if (name && name[0]!=0) {
315 WMHost *host = WMGetHostWithName(name);
317 if (!host)
318 return NULL; /* name is not a hostname nor a number and dot adr */
320 name = WMGetHostAddress(host);
321 #ifndef HAVE_INET_ATON
322 if ((socketaddr.sin_addr.s_addr = inet_addr(name)) == INADDR_NONE) {
323 #else
324 if (inet_aton(name, &socketaddr.sin_addr) == 0) {
325 #endif
326 WMReleaseHost(host);
327 return NULL;
329 WMReleaseHost(host);
330 } else {
331 socketaddr.sin_addr.s_addr = htonl(INADDR_ANY);
334 if (!service || service[0]==0) {
335 socketaddr.sin_port = 0;
336 } else if ((sp = getservbyname(service, protocol))==0) {
337 char *endptr;
338 unsigned portNumber;
340 portNumber = strtoul(service, &endptr, 10);
342 if (service[0]!=0 && *endptr==0 && portNumber<65536) {
343 socketaddr.sin_port = htons(portNumber);
344 } else {
345 return NULL;
347 } else {
348 socketaddr.sin_port = sp->s_port;
351 return &socketaddr;
355 static void
356 dummyHandler(int signum)
361 static WMConnection*
362 createConnectionWithSocket(int sock, Bool closeOnRelease)
364 WMConnection *cPtr;
365 struct sigaction sig_action;
367 cPtr = wmalloc(sizeof(WMConnection));
368 wretain(cPtr);
369 memset(cPtr, 0, sizeof(WMConnection));
371 fcntl(sock, F_SETFD, FD_CLOEXEC); /* by default close on exec */
373 cPtr->sock = sock;
374 cPtr->openTimeout.timeout = OpenTimeout;
375 cPtr->openTimeout.handler = NULL;
376 cPtr->sendTimeout.timeout = DefaultTimeout;
377 cPtr->sendTimeout.handler = NULL;
378 cPtr->closeOnRelease = closeOnRelease;
379 cPtr->outputQueue =
380 WMCreateArrayWithDestructor(16, (WMFreeDataProc*)WMReleaseData);
381 cPtr->state = WCNotConnected;
382 cPtr->timeoutState = WCTNone;
384 /* ignore dead pipe */
385 if (!SigInitialized) {
386 /* Because POSIX mandates that only signal with handlers are reset
387 * accross an exec*(), we do not want to propagate ignoring SIGPIPEs
388 * to children. Hence the dummy handler. Philippe Troin <phil@fifi.org>
390 sig_action.sa_handler = &dummyHandler;
391 sig_action.sa_flags = SA_RESTART;
392 sigaction(SIGPIPE, &sig_action, NULL);
393 SigInitialized = True;
396 return cPtr;
400 #if 0
401 WMConnection*
402 WMCreateConnectionWithSocket(int sock, Bool closeOnRelease)
404 WMConnection *cPtr;
405 struct sockaddr_in clientname;
406 int size;
407 int n;
409 cPtr = createConnectionWithSocket(sock, closeOnRelease);
410 cPtr->wasNonBlocking = WMIsConnectionNonBlocking(cPtr);
411 cPtr->isNonBlocking = cPtr->wasNonBlocking;
413 /* some way to find out if it is connected, and binded. can't find
414 if it listens though!!!
417 size = sizeof(clientname);
418 n = getpeername(sock, (struct sockaddr*) &clientname, &size);
419 if (n==0) {
420 /* Since we have a peer, it means we are connected */
421 cPtr->state = WCConnected;
422 } else {
423 size = sizeof(clientname);
424 n = getsockname(sock, (struct sockaddr*) &clientname, &size);
425 if (n==0) {
426 /* We don't have a peer, but we are binded to an address.
427 * Assume we are listening on it (we don't know that for sure!)
429 cPtr->state = WCListening;
430 } else {
431 cPtr->state = WCNotConnected;
435 return cPtr;
437 #endif
441 * host is the name on which we want to listen for incoming connections,
442 * and it must be a name of this host, or NULL if we want to listen
443 * on any incoming address.
444 * service is either a service name as present in /etc/services, or the port
445 * number we want to listen on. If NULL, a random port between
446 * 1024 and 65535 will be assigned to us.
447 * protocol is one of "tcp" or "udp". If NULL, "tcp" will be used by default.
448 * currently only "tcp" is supported.
450 WMConnection*
451 WMCreateConnectionAsServerAtAddress(char *host, char *service, char *protocol)
453 WMConnection *cPtr;
454 struct sockaddr_in *socketaddr;
455 int sock, on;
456 int size;
458 WCErrorCode = 0;
460 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
461 wwarning(_("Bad address-service-protocol combination"));
462 return NULL;
465 /* Create the actual socket */
466 sock = socket(PF_INET, SOCK_STREAM, 0);
467 if (sock<0) {
468 WCErrorCode = errno;
469 return NULL;
473 * Set socket options. We try to make the port reusable and have it
474 * close as fast as possible without waiting in unnecessary wait states
475 * on close.
477 on = 1;
478 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
480 if (bind(sock, (struct sockaddr *)socketaddr, sizeof(*socketaddr)) < 0) {
481 WCErrorCode = errno;
482 close(sock);
483 return NULL;
486 if (listen(sock, 10) < 0) {
487 WCErrorCode = errno;
488 close(sock);
489 return NULL;
492 /* Find out what is the address/service/protocol we get */
493 /* In case some of address/service/protocol were NULL */
494 size = sizeof(*socketaddr);
495 if (getsockname(sock, (struct sockaddr*)socketaddr, &size) < 0) {
496 WCErrorCode = errno;
497 close(sock);
498 return NULL;
501 cPtr = createConnectionWithSocket(sock, True);
502 cPtr->state = WCListening;
503 WMSetConnectionNonBlocking(cPtr, True);
505 setConnectionAddress(cPtr, socketaddr);
507 return cPtr;
511 WMConnection*
512 WMCreateConnectionToAddress(char *host, char *service, char *protocol)
514 WMConnection *cPtr;
515 struct sockaddr_in *socketaddr;
516 int sock;
518 WCErrorCode = 0;
520 wassertrv(service!=NULL && service[0]!=0, NULL);
522 if (host==NULL || host[0]==0)
523 host = "localhost";
525 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
526 wwarning(_("Bad address-service-protocol combination"));
527 return NULL;
530 /* Create the actual socket */
531 sock = socket(PF_INET, SOCK_STREAM, 0);
532 if (sock<0) {
533 WCErrorCode = errno;
534 return NULL;
536 /* make socket blocking while we connect. */
537 setSocketNonBlocking(sock, False);
538 if (connect(sock, (struct sockaddr*)socketaddr, sizeof(*socketaddr)) < 0) {
539 WCErrorCode = errno;
540 close(sock);
541 return NULL;
544 cPtr = createConnectionWithSocket(sock, True);
545 cPtr->state = WCConnected;
546 WMSetConnectionNonBlocking(cPtr, True);
547 setConnectionAddress(cPtr, socketaddr);
549 return cPtr;
553 WMConnection*
554 WMCreateConnectionToAddressAndNotify(char *host, char *service, char *protocol)
556 WMConnection *cPtr;
557 struct sockaddr_in *socketaddr;
558 int sock;
559 Bool isNonBlocking;
561 WCErrorCode = 0;
563 wassertrv(service!=NULL && service[0]!=0, NULL);
565 if (host==NULL || host[0]==0)
566 host = "localhost";
568 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
569 wwarning(_("Bad address-service-protocol combination"));
570 return NULL;
573 /* Create the actual socket */
574 sock = socket(PF_INET, SOCK_STREAM, 0);
575 if (sock<0) {
576 WCErrorCode = errno;
577 return NULL;
579 isNonBlocking = setSocketNonBlocking(sock, True);
580 if (connect(sock, (struct sockaddr*)socketaddr, sizeof(*socketaddr)) < 0) {
581 if (errno!=EINPROGRESS) {
582 WCErrorCode = errno;
583 close(sock);
584 return NULL;
588 cPtr = createConnectionWithSocket(sock, True);
589 cPtr->state = WCInProgress;
590 cPtr->isNonBlocking = isNonBlocking;
592 cPtr->handler.write = WMAddInputHandler(cPtr->sock, WIWriteMask,
593 inputHandler, cPtr);
595 cPtr->openTimeout.handler =
596 WMAddTimerHandler(cPtr->openTimeout.timeout*1000, openTimeout, cPtr);
598 setConnectionAddress(cPtr, socketaddr);
600 return cPtr;
604 static void
605 removeAllHandlers(WMConnection *cPtr)
607 if (cPtr->handler.read)
608 WMDeleteInputHandler(cPtr->handler.read);
609 if (cPtr->handler.write)
610 WMDeleteInputHandler(cPtr->handler.write);
611 if (cPtr->handler.exception)
612 WMDeleteInputHandler(cPtr->handler.exception);
613 if (cPtr->openTimeout.handler)
614 WMDeleteTimerHandler(cPtr->openTimeout.handler);
615 if (cPtr->sendTimeout.handler)
616 WMDeleteTimerHandler(cPtr->sendTimeout.handler);
618 cPtr->handler.read = NULL;
619 cPtr->handler.write = NULL;
620 cPtr->handler.exception = NULL;
621 cPtr->openTimeout.handler = NULL;
622 cPtr->sendTimeout.handler = NULL;
626 void
627 WMDestroyConnection(WMConnection *cPtr)
629 if (cPtr->closeOnRelease && cPtr->sock>=0) {
630 shutdown(cPtr->sock, SHUT_RDWR);
631 close(cPtr->sock);
634 removeAllHandlers(cPtr);
635 WMFreeArray(cPtr->outputQueue); /* will also free the items with the destructor */
637 if (cPtr->address) {
638 wfree(cPtr->address);
639 wfree(cPtr->service);
640 wfree(cPtr->protocol);
643 wrelease(cPtr);
647 void
648 WMCloseConnection(WMConnection *cPtr)
650 if (cPtr->sock>=0) {
651 shutdown(cPtr->sock, SHUT_RDWR);
652 close(cPtr->sock);
653 cPtr->sock = -1;
656 removeAllHandlers(cPtr);
657 clearOutputQueue(cPtr);
659 cPtr->state = WCClosed;
663 WMConnection*
664 WMAcceptConnection(WMConnection *listener)
666 struct sockaddr_in clientname;
667 int size;
668 int newSock;
669 WMConnection *newConnection;
671 WCErrorCode = 0;
672 wassertrv(listener && listener->state==WCListening, NULL);
674 size = sizeof(clientname);
675 newSock = accept(listener->sock, (struct sockaddr*) &clientname, &size);
676 if (newSock<0) {
677 WCErrorCode = ((errno!=EAGAIN && errno!=EWOULDBLOCK) ? errno : 0);
678 return NULL;
681 newConnection = createConnectionWithSocket(newSock, True);
682 WMSetConnectionNonBlocking(newConnection, True);
683 newConnection->state = WCConnected;
684 setConnectionAddress(newConnection, &clientname);
686 return newConnection;
690 char*
691 WMGetConnectionAddress(WMConnection *cPtr)
693 return cPtr->address;
697 char*
698 WMGetConnectionService(WMConnection *cPtr)
700 return cPtr->service;
704 char*
705 WMGetConnectionProtocol(WMConnection *cPtr)
707 return cPtr->protocol;
712 WMGetConnectionSocket(WMConnection *cPtr)
714 return cPtr->sock;
718 WMConnectionState
719 WMGetConnectionState(WMConnection *cPtr)
721 return cPtr->state;
725 WMConnectionTimeoutState
726 WMGetConnectionTimeoutState(WMConnection *cPtr)
728 return cPtr->timeoutState;
732 Bool
733 WMEnqueueConnectionData(WMConnection *cPtr, WMData *data)
735 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, False);
736 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, False);
738 if (cPtr->state!=WCConnected)
739 return False;
741 WMAddToArray(cPtr->outputQueue, WMRetainData(data));
742 return True;
747 WMSendConnectionData(WMConnection *cPtr, WMData *data)
749 int bytes, pos, len, totalTransfer;
750 TimeoutData *tPtr = &cPtr->sendTimeout;
751 const unsigned char *dataBytes;
753 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, -1);
754 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, -1);
756 if (cPtr->state!=WCConnected)
757 return -1;
759 /* If we have no data just flush the queue, else try to send data */
760 if (data && WMGetDataLength(data)>0) {
761 WMAddToArray(cPtr->outputQueue, WMRetainData(data));
762 /* If there already was something in queue, and also a write input
763 * handler is established, it means we were unable to send, so
764 * return and let the write handler notify us when we can send.
766 if (WMGetArrayItemCount(cPtr->outputQueue)>1 && cPtr->handler.write)
767 return 0;
770 totalTransfer = 0;
772 while (WMGetArrayItemCount(cPtr->outputQueue) > 0) {
773 data = WMGetFromArray(cPtr->outputQueue, 0);
774 dataBytes = (const unsigned char *)WMDataBytes(data);
775 len = WMGetDataLength(data);
776 pos = cPtr->bufPos; /* where we're left last time */
777 while(pos < len) {
778 again:
779 bytes = write(cPtr->sock, dataBytes+pos, len - pos);
780 if(bytes<0) {
781 switch (errno) {
782 case EINTR:
783 goto again;
784 case EWOULDBLOCK:
785 /* save the position where we're left and add a timeout */
786 cPtr->bufPos = pos;
787 if (!tPtr->handler) {
788 tPtr->handler = WMAddTimerHandler(tPtr->timeout*1000,
789 sendTimeout, cPtr);
791 if (!cPtr->handler.write) {
792 cPtr->handler.write =
793 WMAddInputHandler(cPtr->sock, WIWriteMask,
794 inputHandler, cPtr);
796 return totalTransfer;
797 default:
798 WCErrorCode = errno;
799 cPtr->state = WCDied;
800 removeAllHandlers(cPtr);
801 if (cPtr->delegate && cPtr->delegate->didDie)
802 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
803 return -1;
806 pos += bytes;
807 totalTransfer += bytes;
809 WMDeleteFromArray(cPtr->outputQueue, 0);
810 cPtr->bufPos = 0;
811 if (tPtr->handler) {
812 WMDeleteTimerHandler(tPtr->handler);
813 tPtr->handler = NULL;
815 if (cPtr->handler.write) {
816 WMDeleteInputHandler(cPtr->handler.write);
817 cPtr->handler.write = NULL;
821 return totalTransfer;
826 * WMGetConnectionAvailableData(connection):
828 * will return a WMData structure containing the available data on the
829 * specified connection. If connection is non-blocking (default) and no data
830 * is available when this function is called, an empty WMData is returned.
832 * If an error occurs while reading or the other side closed connection,
833 * it will return NULL.
834 * Also trying to read from an already died or closed connection is
835 * considered to be an error condition, and will return NULL.
837 WMData*
838 WMGetConnectionAvailableData(WMConnection *cPtr)
840 char buffer[NETBUF_SIZE];
841 int nbytes;
842 WMData *aData;
844 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, NULL);
845 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, NULL);
847 if (cPtr->state!=WCConnected)
848 return NULL;
850 aData = NULL;
852 again:
853 nbytes = read(cPtr->sock, buffer, NETBUF_SIZE);
854 if (nbytes<0) {
855 switch (errno) {
856 case EINTR:
857 goto again;
858 case EWOULDBLOCK:
859 aData = WMCreateDataWithCapacity(0);
860 break;
861 default:
862 WCErrorCode = errno;
863 cPtr->state = WCDied;
864 removeAllHandlers(cPtr);
865 if (cPtr->delegate && cPtr->delegate->didDie)
866 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
867 break;
869 } else if (nbytes==0) { /* the other side has closed connection */
870 cPtr->state = WCClosed;
871 removeAllHandlers(cPtr);
872 if (cPtr->delegate && cPtr->delegate->didDie)
873 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
874 } else {
875 aData = WMCreateDataWithBytes(buffer, nbytes);
878 return aData;
882 void
883 WMSetConnectionDelegate(WMConnection *cPtr, ConnectionDelegate *delegate)
885 wassertr(cPtr->sock >= 0);
886 /* Don't try to set the delegate multiple times */
887 wassertr(cPtr->delegate == NULL);
889 cPtr->delegate = delegate;
890 if (delegate && delegate->didReceiveInput && !cPtr->handler.read)
891 cPtr->handler.read = WMAddInputHandler(cPtr->sock, WIReadMask,
892 inputHandler, cPtr);
893 if (delegate && delegate->didCatchException && !cPtr->handler.exception)
894 cPtr->handler.exception = WMAddInputHandler(cPtr->sock, WIExceptMask,
895 inputHandler, cPtr);
899 #if 0
900 Bool
901 WMIsConnectionNonBlocking(WMConnection *cPtr)
903 #if 1
904 int state;
906 state = fcntl(cPtr->sock, F_GETFL, 0);
908 if (state < 0) {
909 /* If we can't use fcntl on socket, this probably also means we could
910 * not use fcntl to set non-blocking mode, and since a socket defaults
911 * to blocking when created, return False as the best assumption */
912 return False;
915 return ((state & NONBLOCK_OPT)!=0);
916 #else
917 return cPtr->isNonBlocking;
918 #endif
920 #endif
923 Bool
924 WMSetConnectionNonBlocking(WMConnection *cPtr, Bool flag)
926 wassertrv(cPtr!=NULL && cPtr->sock>=0, False);
928 if (cPtr->isNonBlocking == flag)
929 return True;
931 if (setSocketNonBlocking(cPtr->sock, flag)==True) {
932 cPtr->isNonBlocking = flag;
933 return True;
936 return False;
940 Bool
941 WMSetConnectionCloseOnExec(WMConnection *cPtr, Bool flag)
943 wassertrv(cPtr!=NULL && cPtr->sock>=0, False);
945 if (fcntl(cPtr->sock, F_SETFD, (flag ? FD_CLOEXEC : 0)) < 0) {
946 return False;
949 return True;
953 void*
954 WMGetConnectionClientData(WMConnection *cPtr)
956 return cPtr->clientData;
960 void
961 WMSetConnectionClientData(WMConnection *cPtr, void *data)
963 cPtr->clientData = data;
967 unsigned int
968 WMGetConnectionFlags(WMConnection *cPtr)
970 return cPtr->uflags;
974 void
975 WMSetConnectionFlags(WMConnection *cPtr, unsigned int flags)
977 cPtr->uflags = flags;
981 WMArray*
982 WMGetConnectionUnsentData(WMConnection *cPtr)
984 return cPtr->outputQueue;
988 void
989 WMSetConnectionDefaultTimeout(unsigned int timeout)
991 if (timeout == 0) {
992 DefaultTimeout = DEF_TIMEOUT;
993 } else {
994 DefaultTimeout = timeout;
999 void
1000 WMSetConnectionOpenTimeout(unsigned int timeout)
1002 if (timeout == 0) {
1003 OpenTimeout = DefaultTimeout;
1004 } else {
1005 OpenTimeout = timeout;
1010 void
1011 WMSetConnectionSendTimeout(WMConnection *cPtr, unsigned int timeout)
1013 if (timeout == 0) {
1014 cPtr->sendTimeout.timeout = DefaultTimeout;
1015 } else {
1016 cPtr->sendTimeout.timeout = timeout;