- replaced WMBag with WMArray in connection.c and host.c
[wmaker-crm.git] / WINGs / connection.c
blob49632433ba45f2e8e3733e468aa976a686977aeb
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.
30 #include "../src/config.h"
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdarg.h>
38 #include <errno.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <netdb.h>
43 #include <signal.h>
44 #ifdef __FreeBSD__
45 #include <sys/signal.h>
46 #endif
48 #include "WINGs.h"
51 /* Some older systems does not define this (linux libc5, maybe others too) */
52 #ifndef SHUT_RDWR
53 # define SHUT_RDWR 2
54 #endif
56 /* For SunOS */
57 #ifndef SA_RESTART
58 # define SA_RESTART 0
59 #endif
61 /* For Solaris */
62 #ifndef INADDR_NONE
63 # define INADDR_NONE -1
64 #endif
66 /* Stuff for setting the sockets into non-blocking mode. */
67 /*#ifdef __POSIX_SOURCE
68 # define NONBLOCK_OPT O_NONBLOCK
69 #else
70 # define NONBLOCK_OPT FNDELAY
71 #endif*/
73 #define NONBLOCK_OPT O_NONBLOCK
75 #define NETBUF_SIZE 4096
77 #define DEF_TIMEOUT 600 /* 600 seconds == 10 minutes */
81 int WCErrorCode = 0;
83 static Bool SigInitialized = False;
85 static unsigned int DefaultTimeout = DEF_TIMEOUT;
86 static unsigned int OpenTimeout = DEF_TIMEOUT;
90 typedef struct TimeoutData {
91 unsigned timeout;
92 WMHandlerID *handler;
93 } TimeoutData;
96 typedef struct W_Connection {
97 int sock; /* the socket we speak through */
99 struct {
100 WMHandlerID *read; /* the input read handler */
101 WMHandlerID *write; /* the input write handler */
102 WMHandlerID *exception; /* the input exception handler */
103 } handler;
105 ConnectionDelegate *delegate; /* client delegates */
106 void *clientData; /* client data */
107 unsigned int uflags; /* flags for the client */
109 WMArray *outputQueue;
110 unsigned bufPos;
112 TimeoutData sendTimeout;
113 TimeoutData openTimeout;
115 WMConnectionState state;
116 WMConnectionTimeoutState timeoutState;
118 char *address;
119 char *service;
120 char *protocol;
122 Bool closeOnRelease;
123 Bool wasNonBlocking;
124 Bool isNonBlocking;
126 } W_Connection;
130 static void
131 clearOutputQueue(WMConnection *cPtr) /*FOLD00*/
133 cPtr->bufPos = 0;
134 WMEmptyArray(cPtr->outputQueue);
138 static void
139 openTimeout(void *cdata) /*FOLD00*/
141 WMConnection *cPtr = (WMConnection*) cdata;
143 cPtr->openTimeout.handler = NULL;
144 if (cPtr->handler.write) {
145 WMDeleteInputHandler(cPtr->handler.write);
146 cPtr->handler.write = NULL;
148 if (cPtr->state != WCConnected) {
149 cPtr->state = WCTimedOut;
150 cPtr->timeoutState = WCTWhileOpening;
151 if (cPtr->delegate && cPtr->delegate->didTimeout) {
152 (*cPtr->delegate->didTimeout)(cPtr->delegate, cPtr);
153 } else {
154 WMCloseConnection(cPtr);
155 cPtr->state = WCTimedOut; /* the above set state to WCClosed */
161 static void
162 sendTimeout(void *cdata) /*FOLD00*/
164 WMConnection *cPtr = (WMConnection*) cdata;
166 cPtr->sendTimeout.handler = NULL;
167 if (cPtr->handler.write) {
168 WMDeleteInputHandler(cPtr->handler.write);
169 cPtr->handler.write = NULL;
171 if (WMGetArrayItemCount(cPtr->outputQueue)>0) {
172 clearOutputQueue(cPtr);
173 cPtr->state = WCTimedOut;
174 cPtr->timeoutState = WCTWhileSending;
175 if (cPtr->delegate && cPtr->delegate->didTimeout) {
176 (*cPtr->delegate->didTimeout)(cPtr->delegate, cPtr);
177 } else {
178 WMCloseConnection(cPtr);
179 cPtr->state = WCTimedOut; /* the above set state to WCClosed */
185 static void
186 inputHandler(int fd, int mask, void *clientData) /*FOLD00*/
188 WMConnection *cPtr = (WMConnection*)clientData;
190 if (cPtr->state==WCClosed || cPtr->state==WCDied)
191 return;
193 if ((mask & WIWriteMask)) {
194 if (cPtr->state == WCInProgress) {
195 Bool failed;
196 int result;
197 int len = sizeof(result);
199 if (getsockopt(cPtr->sock, SOL_SOCKET, SO_ERROR,
200 (void*)&result, &len) == 0 && result != 0) {
201 cPtr->state = WCFailed;
202 WCErrorCode = result;
203 failed = True;
204 /* should call wsyserrorwithcode(result, ...) here? */
205 } else {
206 cPtr->state = WCConnected;
207 failed = False;
210 if (cPtr->handler.write) {
211 WMDeleteInputHandler(cPtr->handler.write);
212 cPtr->handler.write = NULL;
215 if (cPtr->openTimeout.handler) {
216 WMDeleteTimerHandler(cPtr->openTimeout.handler);
217 cPtr->openTimeout.handler = NULL;
220 if (cPtr->delegate && cPtr->delegate->didInitialize)
221 (*cPtr->delegate->didInitialize)(cPtr->delegate, cPtr);
223 /* we use failed and not cPtr->state here, because cPtr may be
224 * destroyed by the delegate called above if the connection failed
226 if (failed)
227 return;
228 } else if (cPtr->state == WCConnected) {
229 WMFlushConnection(cPtr);
233 if (!cPtr->delegate)
234 return;
236 /* if the connection died, may get destroyed in the delegate, so retain */
237 wretain(cPtr);
239 if ((mask & WIReadMask) && cPtr->delegate->didReceiveInput)
240 (*cPtr->delegate->didReceiveInput)(cPtr->delegate, cPtr);
242 if ((mask & WIExceptMask) && cPtr->delegate->didCatchException)
243 (*cPtr->delegate->didCatchException)(cPtr->delegate, cPtr);
245 wrelease(cPtr);
249 static Bool
250 setSocketNonBlocking(int sock, Bool flag) /*FOLD00*/
252 int state;
253 Bool isNonBlock;
255 state = fcntl(sock, F_GETFL, 0);
257 if (state < 0) {
258 wsyserror("Failed to get socket flags with fcntl.");
259 return False;
262 isNonBlock = (state & NONBLOCK_OPT) != 0;
264 if (flag) {
265 if (isNonBlock)
266 return True;
267 state |= NONBLOCK_OPT;
268 } else {
269 if (!isNonBlock)
270 return True;
271 state &= ~NONBLOCK_OPT;
274 if (fcntl(sock, F_SETFL, state) < 0) {
275 wsyserror("Failed to set socket flags with fcntl.");
276 return False;
279 return True;
283 static void
284 setConnectionAddress(WMConnection *cPtr, struct sockaddr_in *socketaddr) /*FOLD00*/
286 wassertr(cPtr->address==NULL);
288 cPtr->address = wstrdup(inet_ntoa(socketaddr->sin_addr));
289 cPtr->service = wmalloc(16);
290 sprintf(cPtr->service, "%hu", ntohs(socketaddr->sin_port));
291 cPtr->protocol = wstrdup("tcp");
295 static struct sockaddr_in*
296 getSocketAddress(char* name, char* service, char* protocol) /*FOLD00*/
298 static struct sockaddr_in socketaddr;
299 struct servent *sp;
301 if (!protocol || protocol[0]=='\0')
302 protocol = "tcp";
304 memset(&socketaddr, 0, sizeof(struct sockaddr_in));
305 socketaddr.sin_family = AF_INET;
308 * If we were given a hostname, we use any address for that host.
309 * Otherwise we expect the given name to be an address unless it is
310 * NULL (any address).
312 if (name && name[0]!='\0') {
313 WMHost *host = WMGetHostWithName(name);
315 if (!host)
316 return NULL; /* name is not a hostname nor a number and dot adr */
318 name = WMGetHostAddress(host);
319 #ifndef HAVE_INET_ATON
320 if ((socketaddr.sin_addr.s_addr = inet_addr(name)) == INADDR_NONE) {
321 #else
322 if (inet_aton(name, &socketaddr.sin_addr) == 0) {
323 #endif
324 WMReleaseHost(host);
325 return NULL;
327 WMReleaseHost(host);
328 } else {
329 socketaddr.sin_addr.s_addr = htonl(INADDR_ANY);
332 if (!service || service[0]=='\0') {
333 socketaddr.sin_port = 0;
334 } else if ((sp = getservbyname(service, protocol))==0) {
335 char *endptr;
336 unsigned portNumber;
338 portNumber = strtoul(service, &endptr, 10);
340 if (service[0]!='\0' && *endptr=='\0' && portNumber<65536) {
341 socketaddr.sin_port = htons(portNumber);
342 } else {
343 return NULL;
345 } else {
346 socketaddr.sin_port = sp->s_port;
349 return &socketaddr;
353 static WMConnection*
354 createConnectionWithSocket(int sock, Bool closeOnRelease) /*FOLD00*/
356 WMConnection *cPtr;
357 struct sigaction sig_action;
359 cPtr = wmalloc(sizeof(WMConnection));
360 wretain(cPtr);
361 memset(cPtr, 0, sizeof(WMConnection));
363 cPtr->sock = sock;
364 cPtr->openTimeout.timeout = OpenTimeout;
365 cPtr->openTimeout.handler = NULL;
366 cPtr->sendTimeout.timeout = DefaultTimeout;
367 cPtr->sendTimeout.handler = NULL;
368 cPtr->closeOnRelease = closeOnRelease;
369 cPtr->outputQueue =
370 WMCreateArrayWithDestructor(16, (WMFreeDataProc*)WMReleaseData);
371 cPtr->state = WCNotConnected;
372 cPtr->timeoutState = WCTNone;
374 /* ignore dead pipe */
375 if (!SigInitialized) {
376 sig_action.sa_handler = SIG_IGN;
377 sig_action.sa_flags = SA_RESTART;
378 sigaction(SIGPIPE, &sig_action, NULL);
379 SigInitialized = True;
382 return cPtr;
384 /*FOLD00*/
386 #if 0
387 WMConnection*
388 WMCreateConnectionWithSocket(int sock, Bool closeOnRelease) /*FOLD00*/
390 WMConnection *cPtr;
391 struct sockaddr_in clientname;
392 int size, n;
394 cPtr = createConnectionWithSocket(sock, closeOnRelease);
395 cPtr->wasNonBlocking = WMIsConnectionNonBlocking(cPtr);
396 cPtr->isNonBlocking = cPtr->wasNonBlocking;
398 /* some way to find out if it is connected, and binded. can't find
399 if it listens though!!!
402 size = sizeof(clientname);
403 n = getpeername(sock, (struct sockaddr*) &clientname, &size);
404 if (n==0) {
405 /* Since we have a peer, it means we are connected */
406 cPtr->state = WCConnected;
407 } else {
408 size = sizeof(clientname);
409 n = getsockname(sock, (struct sockaddr*) &clientname, &size);
410 if (n==0) {
411 /* We don't have a peer, but we are binded to an address.
412 * Assume we are listening on it (we don't know that for sure!)
414 cPtr->state = WCListening;
415 } else {
416 cPtr->state = WCNotConnected;
420 return cPtr;
422 #endif
423 /*FOLD00*/
426 * host is the name on which we want to listen for incoming connections,
427 * and it must be a name of this host, or NULL if we want to listen
428 * on any incoming address.
429 * service is either a service name as present in /etc/services, or the port
430 * number we want to listen on. If NULL, a random port between
431 * 1024 and 65535 will be assigned to us.
432 * protocol is one of "tcp" or "udp". If NULL, "tcp" will be used by default.
433 * currently only "tcp" is supported.
435 WMConnection*
436 WMCreateConnectionAsServerAtAddress(char *host, char *service, char *protocol) /*FOLD00*/
438 WMConnection *cPtr;
439 struct sockaddr_in *socketaddr;
440 int sock, size, on;
442 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
443 WCErrorCode = 0;
444 wwarning("Bad address-service-protocol combination");
445 return NULL;
448 /* Create the actual socket */
449 sock = socket(PF_INET, SOCK_STREAM, 0);
450 if (sock<0) {
451 WCErrorCode = errno;
452 wsyserror("Unable to create socket");
453 return NULL;
457 * Set socket options. We try to make the port reusable and have it
458 * close as fast as possible without waiting in unnecessary wait states
459 * on close.
461 on = 1;
462 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
464 if (bind(sock, (struct sockaddr *)socketaddr, sizeof(*socketaddr)) < 0) {
465 WCErrorCode = errno;
466 wsyserror("Unable to bind to address '%s:%hu'",
467 inet_ntoa(socketaddr->sin_addr),
468 ntohs(socketaddr->sin_port));
469 close(sock);
470 return NULL;
473 if (listen(sock, 10) < 0) {
474 WCErrorCode = errno;
475 wsyserror("Unable to listen on port '%hu'",
476 ntohs(socketaddr->sin_port));
477 close(sock);
478 return NULL;
481 /* Find out what is the address/service/protocol we get */
482 /* In case some of address/service/protocol were NULL */
483 size = sizeof(*socketaddr);
484 if (getsockname(sock, (struct sockaddr*)socketaddr, &size) < 0) {
485 WCErrorCode = errno;
486 wsyserror("Unable to get socket address");
487 close(sock);
488 return NULL;
491 cPtr = createConnectionWithSocket(sock, True);
492 cPtr->state = WCListening;
493 WMSetConnectionNonBlocking(cPtr, True);
495 setConnectionAddress(cPtr, socketaddr);
497 return cPtr;
501 WMConnection*
502 WMCreateConnectionToAddress(char *host, char *service, char *protocol) /*FOLD00*/
504 WMConnection *cPtr;
505 struct sockaddr_in *socketaddr;
506 int sock;
508 if (service==NULL || service[0]=='\0') {
509 WCErrorCode = 0;
510 wwarning("Bad argument - service is not specified");
511 return NULL;
514 if (host==NULL || host[0]=='\0')
515 host = "localhost";
517 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
518 WCErrorCode = 0;
519 wwarning("Bad address-service-protocol combination");
520 return NULL;
523 /* Create the actual socket */
524 sock = socket(PF_INET, SOCK_STREAM, 0);
525 if (sock<0) {
526 WCErrorCode = errno;
527 wsyserror("Unable to create socket");
528 return NULL;
530 /* make socket blocking while we connect. */
531 setSocketNonBlocking(sock, False);
532 if (connect(sock, (struct sockaddr*)socketaddr, sizeof(*socketaddr)) < 0) {
533 WCErrorCode = errno;
534 wsyserror("Unable to make connection to address '%s:%hu'",
535 inet_ntoa(socketaddr->sin_addr),
536 ntohs(socketaddr->sin_port));
537 close(sock);
538 return NULL;
541 cPtr = createConnectionWithSocket(sock, True);
542 cPtr->state = WCConnected;
543 WMSetConnectionNonBlocking(cPtr, True);
544 setConnectionAddress(cPtr, socketaddr);
546 return cPtr;
550 WMConnection*
551 WMCreateConnectionToAddressAndNotify(char *host, char *service, char *protocol) /*FOLD00*/
553 WMConnection *cPtr;
554 struct sockaddr_in *socketaddr;
555 int sock;
556 Bool isNonBlocking;
558 if (service==NULL || service[0]=='\0') {
559 WCErrorCode = 0;
560 wwarning("Bad argument - service is not specified");
561 return NULL;
564 if (host==NULL || host[0]=='\0')
565 host = "localhost";
567 if ((socketaddr = getSocketAddress(host, service, protocol)) == NULL) {
568 WCErrorCode = 0;
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 wsyserror("Unable to create socket");
578 return NULL;
580 isNonBlocking = setSocketNonBlocking(sock, True);
581 if (connect(sock, (struct sockaddr*)socketaddr, sizeof(*socketaddr)) < 0) {
582 if (errno!=EINPROGRESS) {
583 WCErrorCode = errno;
584 wsyserror("Unable to make connection to address '%s:%hu'",
585 inet_ntoa(socketaddr->sin_addr),
586 ntohs(socketaddr->sin_port));
587 close(sock);
588 return NULL;
592 cPtr = createConnectionWithSocket(sock, True);
593 cPtr->state = WCInProgress;
594 cPtr->isNonBlocking = isNonBlocking;
596 cPtr->handler.write = WMAddInputHandler(cPtr->sock, WIWriteMask,
597 inputHandler, cPtr);
599 cPtr->openTimeout.handler =
600 WMAddTimerHandler(cPtr->openTimeout.timeout*1000, openTimeout, cPtr);
602 setConnectionAddress(cPtr, socketaddr);
604 return cPtr;
608 static void
609 removeAllHandlers(WMConnection *cPtr) /*FOLD00*/
611 if (cPtr->handler.read)
612 WMDeleteInputHandler(cPtr->handler.read);
613 if (cPtr->handler.write)
614 WMDeleteInputHandler(cPtr->handler.write);
615 if (cPtr->handler.exception)
616 WMDeleteInputHandler(cPtr->handler.exception);
617 if (cPtr->openTimeout.handler)
618 WMDeleteTimerHandler(cPtr->openTimeout.handler);
619 if (cPtr->sendTimeout.handler)
620 WMDeleteTimerHandler(cPtr->sendTimeout.handler);
622 cPtr->handler.read = NULL;
623 cPtr->handler.write = NULL;
624 cPtr->handler.exception = NULL;
625 cPtr->openTimeout.handler = NULL;
626 cPtr->sendTimeout.handler = NULL;
630 void
631 WMDestroyConnection(WMConnection *cPtr) /*FOLD00*/
633 if (cPtr->closeOnRelease && cPtr->sock>=0) {
634 shutdown(cPtr->sock, SHUT_RDWR);
635 close(cPtr->sock);
638 removeAllHandlers(cPtr);
639 WMFreeArray(cPtr->outputQueue); /* will also free the items with the destructor */
641 if (cPtr->address) {
642 wfree(cPtr->address);
643 wfree(cPtr->service);
644 wfree(cPtr->protocol);
647 wrelease(cPtr);
651 void
652 WMCloseConnection(WMConnection *cPtr) /*FOLD00*/
654 if (cPtr->sock>=0) {
655 shutdown(cPtr->sock, SHUT_RDWR);
656 close(cPtr->sock);
657 cPtr->sock = -1;
660 removeAllHandlers(cPtr);
661 clearOutputQueue(cPtr);
663 cPtr->state = WCClosed;
667 WMConnection*
668 WMAcceptConnection(WMConnection *listener) /*FOLD00*/
670 struct sockaddr_in clientname;
671 int size;
672 int newSock;
673 WMConnection *newConnection;
675 if (listener->state!=WCListening) {
676 wwarning("Called 'WMAcceptConnection()' on a non-listening connection");
677 WCErrorCode = 0;
678 return NULL;
681 size = sizeof(clientname);
682 newSock = accept(listener->sock, (struct sockaddr*) &clientname, &size);
683 if (newSock<0) {
684 if (errno!=EAGAIN && errno!=EWOULDBLOCK) {
685 WCErrorCode = errno;
686 wsyserror("Could not accept connection");
687 } else {
688 WCErrorCode = 0;
690 return NULL;
693 newConnection = createConnectionWithSocket(newSock, True);
694 WMSetConnectionNonBlocking(newConnection, True);
695 newConnection->state = WCConnected;
696 setConnectionAddress(newConnection, &clientname);
698 return newConnection;
702 char*
703 WMGetConnectionAddress(WMConnection *cPtr) /*FOLD00*/
705 return cPtr->address;
709 char*
710 WMGetConnectionService(WMConnection *cPtr) /*FOLD00*/
712 return cPtr->service;
716 char*
717 WMGetConnectionProtocol(WMConnection *cPtr) /*FOLD00*/
719 return cPtr->protocol;
724 WMGetConnectionSocket(WMConnection *cPtr) /*FOLD00*/
726 return cPtr->sock;
730 WMConnectionState
731 WMGetConnectionState(WMConnection *cPtr) /*FOLD00*/
733 return cPtr->state;
737 WMConnectionTimeoutState
738 WMGetConnectionTimeoutState(WMConnection *cPtr) /*FOLD00*/
740 return cPtr->timeoutState;
744 Bool
745 WMEnqueueConnectionData(WMConnection *cPtr, WMData *data) /*FOLD00*/
747 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, False);
748 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, False);
750 if (cPtr->state!=WCConnected)
751 return False;
753 WMAddToArray(cPtr->outputQueue, WMRetainData(data));
754 return True;
759 WMSendConnectionData(WMConnection *cPtr, WMData *data) /*FOLD00*/
761 int bytes, pos, len, totalTransfer;
762 TimeoutData *tPtr = &cPtr->sendTimeout;
763 const unsigned char *dataBytes;
765 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, -1);
766 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, -1);
768 if (cPtr->state!=WCConnected)
769 return -1;
771 /* If we have no data just flush the queue, else try to send data */
772 if (data && WMGetDataLength(data)>0) {
773 WMAddToArray(cPtr->outputQueue, WMRetainData(data));
774 /* If there already was something in queue, and also a write input
775 * handler is established, it means we were unable to send, so
776 * return and let the write handler notify us when we can send.
778 if (WMGetArrayItemCount(cPtr->outputQueue)>1 && cPtr->handler.write)
779 return 0;
782 totalTransfer = 0;
784 while (WMGetArrayItemCount(cPtr->outputQueue) > 0) {
785 data = WMGetFromArray(cPtr->outputQueue, 0);
786 dataBytes = (const unsigned char *)WMDataBytes(data);
787 len = WMGetDataLength(data);
788 pos = cPtr->bufPos; /* where we're left last time */
789 while(pos < len) {
790 again:
791 bytes = write(cPtr->sock, dataBytes+pos, len - pos);
792 if(bytes<0) {
793 switch (errno) {
794 case EINTR:
795 goto again;
796 case EWOULDBLOCK:
797 /* save the position where we're left and add a timeout */
798 cPtr->bufPos = pos;
799 if (!tPtr->handler) {
800 tPtr->handler = WMAddTimerHandler(tPtr->timeout*1000,
801 sendTimeout, cPtr);
803 if (!cPtr->handler.write) {
804 cPtr->handler.write =
805 WMAddInputHandler(cPtr->sock, WIWriteMask,
806 inputHandler, cPtr);
808 return totalTransfer;
809 default:
810 WCErrorCode = errno;
811 cPtr->state = WCDied;
812 removeAllHandlers(cPtr);
813 if (cPtr->delegate && cPtr->delegate->didDie)
814 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
815 return -1;
818 pos += bytes;
819 totalTransfer += bytes;
821 WMDeleteFromArray(cPtr->outputQueue, 0);
822 cPtr->bufPos = 0;
823 if (tPtr->handler) {
824 WMDeleteTimerHandler(tPtr->handler);
825 tPtr->handler = NULL;
827 if (cPtr->handler.write) {
828 WMDeleteInputHandler(cPtr->handler.write);
829 cPtr->handler.write = NULL;
833 return totalTransfer;
838 * WMGetConnectionAvailableData(connection):
840 * will return a WMData structure containing the available data on the
841 * specified connection. If connection is non-blocking (default) and no data
842 * is available when this function is called, an empty WMData is returned.
844 * If an error occurs while reading or the other side closed connection,
845 * it will return NULL.
846 * Also trying to read from an already died or closed connection is
847 * considered to be an error condition, and will return NULL.
849 WMData*
850 WMGetConnectionAvailableData(WMConnection *cPtr) /*FOLD00*/
852 char buffer[NETBUF_SIZE];
853 int nbytes;
854 WMData *aData;
856 wassertrv(cPtr->state!=WCNotConnected && cPtr->state!=WCListening, NULL);
857 wassertrv(cPtr->state!=WCInProgress && cPtr->state!=WCFailed, NULL);
859 if (cPtr->state!=WCConnected)
860 return NULL;
862 aData = NULL;
864 again:
865 nbytes = read(cPtr->sock, buffer, NETBUF_SIZE);
866 if (nbytes<0) {
867 switch (errno) {
868 case EINTR:
869 goto again;
870 case EWOULDBLOCK:
871 aData = WMCreateDataWithCapacity(0);
872 break;
873 default:
874 WCErrorCode = errno;
875 cPtr->state = WCDied;
876 removeAllHandlers(cPtr);
877 if (cPtr->delegate && cPtr->delegate->didDie)
878 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
879 break;
881 } else if (nbytes==0) { /* the other side has closed connection */
882 cPtr->state = WCClosed;
883 removeAllHandlers(cPtr);
884 if (cPtr->delegate && cPtr->delegate->didDie)
885 (*cPtr->delegate->didDie)(cPtr->delegate, cPtr);
886 } else {
887 aData = WMCreateDataWithBytes(buffer, nbytes);
890 return aData;
894 void
895 WMSetConnectionDelegate(WMConnection *cPtr, ConnectionDelegate *delegate) /*FOLD00*/
897 wassertr(cPtr->sock >= 0);
898 /* Don't try to set the delegate multiple times */
899 wassertr(cPtr->delegate == NULL);
901 cPtr->delegate = delegate;
902 if (delegate && delegate->didReceiveInput && !cPtr->handler.read)
903 cPtr->handler.read = WMAddInputHandler(cPtr->sock, WIReadMask,
904 inputHandler, cPtr);
905 if (delegate && delegate->didCatchException && !cPtr->handler.exception)
906 cPtr->handler.exception = WMAddInputHandler(cPtr->sock, WIExceptMask,
907 inputHandler, cPtr);
911 #if 0
912 Bool
913 WMIsConnectionNonBlocking(WMConnection *cPtr) /*FOLD00*/
915 #if 1
916 int state;
918 state = fcntl(cPtr->sock, F_GETFL, 0);
920 if (state < 0) {
921 wsyserror("Failed to get socket flags with fcntl.");
922 /* If we can't use fcntl on socket, this probably also means we could
923 * not use fcntl to set non-blocking mode, and since a socket defaults
924 * to blocking when created, return False as the best assumption */
925 return False;
928 return ((state & NONBLOCK_OPT)!=0);
929 #else
930 return cPtr->isNonBlocking;
931 #endif
933 #endif
936 void
937 WMSetConnectionNonBlocking(WMConnection *cPtr, Bool flag) /*FOLD00*/
939 if (cPtr->sock < 0)
940 return;
942 if (cPtr->isNonBlocking == flag)
943 return;
945 if (setSocketNonBlocking(cPtr->sock, flag)==True)
946 cPtr->isNonBlocking = flag;
950 void*
951 WMGetConnectionClientData(WMConnection *cPtr) /*FOLD00*/
953 return cPtr->clientData;
957 void
958 WMSetConnectionClientData(WMConnection *cPtr, void *data) /*FOLD00*/
960 cPtr->clientData = data;
964 unsigned int
965 WMGetConnectionFlags(WMConnection *cPtr) /*FOLD00*/
967 return cPtr->uflags;
971 void
972 WMSetConnectionFlags(WMConnection *cPtr, unsigned int flags) /*FOLD00*/
974 cPtr->uflags = flags;
978 WMArray*
979 WMGetConnectionUnsentData(WMConnection *cPtr)
981 return cPtr->outputQueue;
985 void
986 WMSetConnectionDefaultTimeout(unsigned int timeout) /*FOLD00*/
988 if (timeout == 0) {
989 DefaultTimeout = DEF_TIMEOUT;
990 } else {
991 DefaultTimeout = timeout;
996 void
997 WMSetConnectionOpenTimeout(unsigned int timeout) /*FOLD00*/
999 if (timeout == 0) {
1000 OpenTimeout = DefaultTimeout;
1001 } else {
1002 OpenTimeout = timeout;
1007 void
1008 WMSetConnectionSendTimeout(WMConnection *cPtr, unsigned int timeout) /*FOLD00*/
1010 if (timeout == 0) {
1011 cPtr->sendTimeout.timeout = DefaultTimeout;
1012 } else {
1013 cPtr->sendTimeout.timeout = timeout;