2 * Copyright (c) 1998-2012 by the citadel.org team
4 * This program is open source software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License, version 3.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
22 #include <sys/types.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
47 #include <libcitadel.h>
50 #include "citserver.h"
57 #include "internet_addressing.h"
60 #include "clientsocket.h"
61 #include "locate_host.h"
62 #include "citadel_dirs.h"
64 #include "event_client.h"
65 #include "ctdl_module.h"
68 ConstStr IOStates[] = {
75 {HKEY("DB Terminate")},
78 {HKEY("IO Connect Socket")},
81 {HKEY("IO ConnFail")},
82 {HKEY("IO ConnFail Now")},
83 {HKEY("IO Conn Now")},
84 {HKEY("IO Conn Wait")},
87 {HKEY("Curl Shotdown")},
88 {HKEY("Curl More IO")},
89 {HKEY("Curl Got IO")},
90 {HKEY("Curl Got Data")},
91 {HKEY("Curl Got Status")},
92 {HKEY("C-Ares Start")},
93 {HKEY("C-Ares IO Done")},
94 {HKEY("C-Ares Finished")},
95 {HKEY("C-Ares exit")},
100 void SetEVState(AsyncIO *IO, eIOState State)
103 CitContext* CCC = IO->CitContext;
105 memcpy(CCC->lastcmdname, IOStates[State].Key, IOStates[State].len + 1);
110 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
111 static void IO_abort_shutdown_callback(struct ev_loop *loop,
116 /*------------------------------------------------------------------------------
118 *----------------------------------------------------------------------------*/
119 extern int evdb_count;
120 extern pthread_mutex_t DBEventQueueMutex;
121 extern pthread_mutex_t DBEventExitQueueMutex;
122 extern HashList *DBInboundEventQueue;
123 extern struct ev_loop *event_db;
124 extern ev_async DBAddJob;
125 extern ev_async DBExitEventLoop;
127 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
132 SetEVState(IO, eDBQ);
133 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
136 ev_cleanup_init(&IO->db_abort_by_shutdown,
137 IO_abort_shutdown_callback);
138 IO->db_abort_by_shutdown.data = IO;
140 pthread_mutex_lock(&DBEventQueueMutex);
141 if (DBInboundEventQueue == NULL)
143 /* shutting down... */
145 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
146 pthread_mutex_unlock(&DBEventQueueMutex);
149 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
151 Put(DBInboundEventQueue, IKEY(i), h, NULL);
152 pthread_mutex_unlock(&DBEventQueueMutex);
154 pthread_mutex_lock(&DBEventExitQueueMutex);
155 if (event_db == NULL)
157 pthread_mutex_unlock(&DBEventExitQueueMutex);
160 ev_async_send (event_db, &DBAddJob);
161 pthread_mutex_unlock(&DBEventExitQueueMutex);
163 EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
167 void StopDBWatchers(AsyncIO *IO)
169 SetEVState(IO, eDBStop);
170 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
171 ev_idle_stop(event_db, &IO->db_unwind_stack);
174 void ShutDownDBCLient(AsyncIO *IO)
176 CitContext *Ctx =IO->CitContext;
179 SetEVState(IO, eDBTerm);
180 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
183 assert(IO->DBTerminate);
188 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
190 AsyncIO *IO = watcher->data;
192 SetEVState(IO, eDBNext);
193 IO->Now = ev_now(event_db);
194 EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
195 become_session(IO->CitContext);
197 ev_idle_stop(event_db, &IO->db_unwind_stack);
199 assert(IO->NextDBOperation);
200 switch (IO->NextDBOperation(IO))
214 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
216 case eTerminateConnection:
218 ev_idle_stop(event_db, &IO->db_unwind_stack);
219 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
220 ShutDownDBCLient(IO);
224 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
226 SetEVState(IO, eQDBNext);
227 IO->NextDBOperation = CB;
228 ev_idle_init(&IO->db_unwind_stack,
230 IO->db_unwind_stack.data = IO;
231 ev_idle_start(event_db, &IO->db_unwind_stack);
235 /*------------------------------------------------------------------------------
237 *----------------------------------------------------------------------------*/
238 extern int evbase_count;
239 extern pthread_mutex_t EventQueueMutex;
240 extern pthread_mutex_t EventExitQueueMutex;
241 extern HashList *InboundEventQueue;
242 extern struct ev_loop *event_base;
243 extern ev_async AddJob;
244 extern ev_async ExitEventLoop;
246 static void IO_abort_shutdown_callback(struct ev_loop *loop,
250 AsyncIO *IO = watcher->data;
252 SetEVState(IO, eIOAbort);
253 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
254 IO->Now = ev_now(event_base);
255 assert(IO->ShutdownAbort);
256 IO->ShutdownAbort(IO);
260 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
265 SetEVState(IO, eIOQ);
266 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
269 ev_cleanup_init(&IO->abort_by_shutdown,
270 IO_abort_shutdown_callback);
271 IO->abort_by_shutdown.data = IO;
273 pthread_mutex_lock(&EventQueueMutex);
274 if (InboundEventQueue == NULL)
277 /* shutting down... */
278 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
279 pthread_mutex_unlock(&EventQueueMutex);
282 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
284 Put(InboundEventQueue, IKEY(i), h, NULL);
285 pthread_mutex_unlock(&EventQueueMutex);
287 pthread_mutex_lock(&EventExitQueueMutex);
288 if (event_base == NULL) {
289 pthread_mutex_unlock(&EventExitQueueMutex);
292 ev_async_send (event_base, &AddJob);
293 pthread_mutex_unlock(&EventExitQueueMutex);
294 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
298 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
300 StopClientWatchers(IO, 0);
301 return QueueDBOperation(IO, CB);
303 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
306 return QueueEventContext(IO, CB);
309 extern eNextState evcurl_handle_start(AsyncIO *IO);
311 eNextState QueueCurlContext(AsyncIO *IO)
316 SetEVState(IO, eCurlQ);
317 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
319 h->EvAttch = evcurl_handle_start;
321 pthread_mutex_lock(&EventQueueMutex);
322 if (InboundEventQueue == NULL)
324 /* shutting down... */
326 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
327 pthread_mutex_unlock(&EventQueueMutex);
331 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
333 Put(InboundEventQueue, IKEY(i), h, NULL);
334 pthread_mutex_unlock(&EventQueueMutex);
336 pthread_mutex_lock(&EventExitQueueMutex);
337 if (event_base == NULL) {
338 pthread_mutex_unlock(&EventExitQueueMutex);
341 ev_async_send (event_base, &AddJob);
342 pthread_mutex_unlock(&EventExitQueueMutex);
344 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
348 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
350 StopCurlWatchers(IO);
351 return QueueDBOperation(IO, CB);
355 void DestructCAres(AsyncIO *IO);
356 void FreeAsyncIOContents(AsyncIO *IO)
358 CitContext *Ctx = IO->CitContext;
360 FreeStrBuf(&IO->IOBuf);
361 FreeStrBuf(&IO->SendBuf.Buf);
362 FreeStrBuf(&IO->RecvBuf.Buf);
366 FreeURL(&IO->ConnectMe);
367 FreeStrBuf(&IO->HttpReq.ReplyData);
370 Ctx->state = CON_IDLE;
372 IO->CitContext = NULL;
377 void StopClientWatchers(AsyncIO *IO, int CloseFD)
379 ev_timer_stop (event_base, &IO->rw_timeout);
380 ev_timer_stop(event_base, &IO->conn_fail);
381 ev_idle_stop(event_base, &IO->unwind_stack);
382 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
384 ev_io_stop(event_base, &IO->conn_event);
385 ev_io_stop(event_base, &IO->send_event);
386 ev_io_stop(event_base, &IO->recv_event);
388 if (CloseFD && (IO->SendBuf.fd > 0)) {
389 close(IO->SendBuf.fd);
395 void StopCurlWatchers(AsyncIO *IO)
397 ev_timer_stop (event_base, &IO->rw_timeout);
398 ev_timer_stop(event_base, &IO->conn_fail);
399 ev_idle_stop(event_base, &IO->unwind_stack);
400 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
402 ev_io_stop(event_base, &IO->conn_event);
403 ev_io_stop(event_base, &IO->send_event);
404 ev_io_stop(event_base, &IO->recv_event);
406 curl_easy_cleanup(IO->HttpReq.chnd);
407 IO->HttpReq.chnd = NULL;
409 if (IO->SendBuf.fd != 0) {
410 close(IO->SendBuf.fd);
416 void ShutDownCLient(AsyncIO *IO)
418 CitContext *Ctx =IO->CitContext;
420 SetEVState(IO, eExit);
423 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
425 StopClientWatchers(IO, 1);
427 if (IO->DNS.Channel != NULL) {
428 ares_destroy(IO->DNS.Channel);
429 EV_DNS_LOG_STOP(DNS.recv_event);
430 EV_DNS_LOG_STOP(DNS.send_event);
431 ev_io_stop(event_base, &IO->DNS.recv_event);
432 ev_io_stop(event_base, &IO->DNS.send_event);
433 IO->DNS.Channel = NULL;
435 assert(IO->Terminate);
439 void PostInbound(AsyncIO *IO)
441 switch (IO->NextState) {
443 ev_io_start(event_base, &IO->send_event);
447 assert(IO->SendDone);
448 IO->NextState = IO->SendDone(IO);
449 switch (IO->NextState)
458 ev_io_start(event_base, &IO->send_event);
461 StopClientWatchers(IO, 0);
469 ev_io_start(event_base, &IO->recv_event);
471 case eTerminateConnection:
485 eReadState HandleInbound(AsyncIO *IO)
487 const char *Err = NULL;
488 eReadState Finished = eBufferNotEmpty;
490 become_session(IO->CitContext);
492 while ((Finished == eBufferNotEmpty) &&
493 ((IO->NextState == eReadMessage)||
494 (IO->NextState == eReadMore)||
495 (IO->NextState == eReadFile)||
496 (IO->NextState == eReadPayload)))
499 * lex line reply in callback,
500 * or do it ourselves.
501 * i.e. as nnn-blabla means continue reading in SMTP
503 if ((IO->NextState == eReadFile) &&
504 (Finished == eBufferNotEmpty))
506 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
507 if (Finished == eReadSuccess)
509 IO->NextState = eSendReply;
512 else if (IO->LineReader)
513 Finished = IO->LineReader(IO);
515 Finished = StrBufChunkSipLine(IO->IOBuf,
519 case eMustReadMore: /// read new from socket...
521 case eBufferNotEmpty: /* shouldn't happen... */
522 case eReadSuccess: /// done for now...
524 case eReadFail: /// WHUT?
529 if (Finished != eMustReadMore) {
530 assert(IO->ReadDone);
531 ev_io_stop(event_base, &IO->recv_event);
532 IO->NextState = IO->ReadDone(IO);
533 Finished = StrBufCheckBuffer(&IO->RecvBuf);
544 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
547 AsyncIO *IO = watcher->data;
548 const char *errmsg = NULL;
550 IO->Now = ev_now(event_base);
551 become_session(IO->CitContext);
557 const char *pch = ChrPtr(IO->SendBuf.Buf);
558 const char *pchh = IO->SendBuf.ReadWritePointer;
564 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
565 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
566 ((CitContext*)(IO->CitContext))->ServiceName,
569 fd = fopen(fn, "a+");
570 fprintf(fd, "Send: BufSize: %ld BufContent: [",
572 rv = fwrite(pchh, nbytes, 1, fd);
573 if (!rv) printf("failed to write debug to %s!\n", fn);
576 switch (IO->NextState) {
578 rc = FileSendChunked(&IO->IOB, &errmsg);
580 StrBufPlain(IO->ErrMsg, errmsg, -1);
583 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
589 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
595 ev_io_stop(event_base, &IO->send_event);
596 switch (IO->NextState) {
598 assert(IO->SendDone);
599 IO->NextState = IO->SendDone(IO);
601 if ((IO->NextState == eTerminateConnection) ||
602 (IO->NextState == eAbort) )
605 ev_io_start(event_base, &IO->send_event);
609 if (IO->IOB.ChunkSendRemain > 0) {
610 ev_io_start(event_base, &IO->recv_event);
611 SetNextTimeout(IO, 100.0);
614 assert(IO->ReadDone);
615 IO->NextState = IO->ReadDone(IO);
616 switch(IO->NextState) {
625 ev_io_start(event_base,
633 case eTerminateConnection:
640 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
642 IO->NextState = eReadMore;
647 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
652 ev_io_start(event_base, &IO->recv_event);
658 * we now live in another queue,
659 * so we have to unregister.
661 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
666 case eTerminateConnection:
672 if (errno != EAGAIN) {
673 StopClientWatchers(IO, 1);
675 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
676 errno, strerror(errno), IO->SendBuf.fd);
677 StrBufPrintf(IO->ErrMsg,
678 "Socket Invalid! [%s]",
680 SetNextTimeout(IO, 0.01);
683 /* else : must write more. */
686 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
688 ev_timer_stop(event_base, &IO->conn_fail);
689 ev_timer_start(event_base, &IO->rw_timeout);
691 switch(IO->NextState) {
695 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
696 ev_io_start(event_base, &IO->recv_event);
702 become_session(IO->CitContext);
703 IO_send_callback(loop, &IO->send_event, revents);
709 case eTerminateConnection:
717 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
719 AsyncIO *IO = watcher->data;
721 SetEVState(IO, eIOTimeout);
722 IO->Now = ev_now(event_base);
723 ev_timer_stop (event_base, &IO->rw_timeout);
724 become_session(IO->CitContext);
726 if (IO->SendBuf.fd != 0)
728 ev_io_stop(event_base, &IO->send_event);
729 ev_io_stop(event_base, &IO->recv_event);
730 ev_timer_stop (event_base, &IO->rw_timeout);
731 close(IO->SendBuf.fd);
732 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
736 switch (IO->Timeout(IO))
746 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
748 AsyncIO *IO = watcher->data;
750 SetEVState(IO, eIOConnfail);
751 IO->Now = ev_now(event_base);
752 ev_timer_stop (event_base, &IO->conn_fail);
754 if (IO->SendBuf.fd != 0)
756 ev_io_stop(loop, &IO->conn_event);
757 ev_io_stop(event_base, &IO->send_event);
758 ev_io_stop(event_base, &IO->recv_event);
759 ev_timer_stop (event_base, &IO->rw_timeout);
760 close(IO->SendBuf.fd);
761 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
763 become_session(IO->CitContext);
765 assert(IO->ConnFail);
766 switch (IO->ConnFail(IO))
777 IO_connfailimmediate_callback(struct ev_loop *loop,
781 AsyncIO *IO = watcher->data;
783 SetEVState(IO, eIOConnfailNow);
784 IO->Now = ev_now(event_base);
785 ev_idle_stop (event_base, &IO->conn_fail_immediate);
787 if (IO->SendBuf.fd != 0)
789 close(IO->SendBuf.fd);
790 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
792 become_session(IO->CitContext);
794 assert(IO->ConnFail);
795 switch (IO->ConnFail(IO))
806 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
808 AsyncIO *IO = watcher->data;
810 socklen_t lon = sizeof(so_err);
813 SetEVState(IO, eIOConnNow);
814 IO->Now = ev_now(event_base);
815 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
817 ev_io_stop(loop, &IO->conn_event);
818 ev_timer_stop(event_base, &IO->conn_fail);
820 err = getsockopt(IO->SendBuf.fd,
826 if ((err == 0) && (so_err != 0))
828 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
831 IO_connfail_callback(loop, &IO->conn_fail, revents);
836 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
837 set_start_callback(loop, IO, revents);
842 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
846 AsyncIO *IO = watcher->data;
848 IO->Now = ev_now(event_base);
849 switch (IO->NextState) {
851 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
853 StrBufPlain(IO->ErrMsg, errmsg, -1);
856 if (IO->IOB.ChunkSendRemain == 0)
858 IO->NextState = eSendReply;
859 assert(IO->ReadDone);
860 ev_io_stop(event_base, &IO->recv_event);
869 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
881 const char *pch = ChrPtr(IO->RecvBuf.Buf);
882 const char *pchh = IO->RecvBuf.ReadWritePointer;
887 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
888 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
889 ((CitContext*)(IO->CitContext))->ServiceName,
892 fd = fopen(fn, "a+");
893 fprintf(fd, "Read: BufSize: %ld BufContent: [",
895 rv = fwrite(pchh, nbytes, 1, fd);
896 if (!rv) printf("failed to write debug to %s!\n", fn);
903 } else if (nbytes == 0) {
904 StopClientWatchers(IO, 1);
905 SetNextTimeout(IO, 0.01);
907 } else if (nbytes == -1) {
908 if (errno != EAGAIN) {
909 // FD is gone. kick it.
910 StopClientWatchers(IO, 1);
912 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
913 errno, strerror(errno), IO->SendBuf.fd);
914 StrBufPrintf(IO->ErrMsg,
915 "Socket Invalid! [%s]",
917 SetNextTimeout(IO, 0.01);
924 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
926 AsyncIO *IO = watcher->data;
928 SetEVState(IO, eCaresFinished);
929 IO->Now = ev_now(event_base);
930 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
931 become_session(IO->CitContext);
932 assert(IO->DNS.Query->PostDNS);
933 switch (IO->DNS.Query->PostDNS(IO))
936 assert(IO->DNS.Fail);
937 switch (IO->DNS.Fail(IO)) {
939 //// StopClientWatchers(IO);
950 eNextState EvConnectSock(AsyncIO *IO,
952 double first_rw_timeout,
955 struct sockaddr_in egress_sin;
959 SetEVState(IO, eIOConnectSock);
960 become_session(IO->CitContext);
963 IO->NextState = eReadMessage;
966 IO->NextState = eSendReply;
969 IO->SendBuf.fd = IO->RecvBuf.fd =
971 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
975 if (IO->SendBuf.fd < 0) {
977 "EVENT: socket() failed: %s\n",
980 StrBufPrintf(IO->ErrMsg,
981 "Failed to create socket: %s",
983 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
986 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
989 "EVENT: unable to get socket %d flags! %s \n",
992 StrBufPrintf(IO->ErrMsg,
993 "Failed to get socket %d flags: %s",
996 close(IO->SendBuf.fd);
997 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1000 fdflags = fdflags | O_NONBLOCK;
1001 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
1004 "EVENT: unable to set socket %d nonblocking flags! %s \n",
1007 StrBufPrintf(IO->ErrMsg,
1008 "Failed to set socket flags: %s",
1010 close(IO->SendBuf.fd);
1011 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1014 /* TODO: maye we could use offsetof() to calc the position of data...
1015 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1017 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1018 IO->recv_event.data = IO;
1019 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1020 IO->send_event.data = IO;
1022 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1023 IO->conn_fail.data = IO;
1024 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1025 IO->rw_timeout.data = IO;
1030 /* for debugging you may bypass it like this:
1031 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1032 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1033 * inet_addr("127.0.0.1");
1035 if (IO->ConnectMe->IPv6) {
1036 rc = connect(IO->SendBuf.fd,
1037 &IO->ConnectMe->Addr,
1038 sizeof(struct sockaddr_in6));
1041 /* If citserver is bound to a specific IP address on the host, make
1042 * sure we use that address for outbound connections.
1045 memset(&egress_sin, 0, sizeof(egress_sin));
1046 egress_sin.sin_family = AF_INET;
1047 if (!IsEmptyStr(config.c_ip_addr)) {
1048 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1049 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1050 egress_sin.sin_addr.s_addr = INADDR_ANY;
1053 /* If this bind fails, no problem; we can still use INADDR_ANY */
1054 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1056 rc = connect(IO->SendBuf.fd,
1057 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1058 sizeof(struct sockaddr_in));
1062 SetEVState(IO, eIOConnNow);
1063 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1064 set_start_callback(event_base, IO, 0);
1065 return IO->NextState;
1067 else if (errno == EINPROGRESS) {
1068 SetEVState(IO, eIOConnWait);
1069 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1071 ev_io_init(&IO->conn_event,
1072 IO_connestd_callback,
1076 IO->conn_event.data = IO;
1078 ev_io_start(event_base, &IO->conn_event);
1079 ev_timer_start(event_base, &IO->conn_fail);
1080 return IO->NextState;
1083 SetEVState(IO, eIOConnfail);
1084 ev_idle_init(&IO->conn_fail_immediate,
1085 IO_connfailimmediate_callback);
1086 IO->conn_fail_immediate.data = IO;
1087 ev_idle_start(event_base, &IO->conn_fail_immediate);
1090 "connect() = %d failed: %s\n",
1094 StrBufPrintf(IO->ErrMsg,
1095 "Failed to connect: %s",
1097 return IO->NextState;
1099 return IO->NextState;
1102 void SetNextTimeout(AsyncIO *IO, double timeout)
1104 IO->rw_timeout.repeat = timeout;
1105 ev_timer_again (event_base, &IO->rw_timeout);
1109 eNextState ReAttachIO(AsyncIO *IO,
1113 SetEVState(IO, eIOAttach);
1115 become_session(IO->CitContext);
1116 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1118 IO->NextState = eReadMessage;
1121 IO->NextState = eSendReply;
1123 set_start_callback(event_base, IO, 0);
1125 return IO->NextState;
1128 void InitIOStruct(AsyncIO *IO,
1130 eNextState NextState,
1131 IO_LineReaderCallback LineReader,
1132 IO_CallBack DNS_Fail,
1133 IO_CallBack SendDone,
1134 IO_CallBack ReadDone,
1135 IO_CallBack Terminate,
1136 IO_CallBack DBTerminate,
1137 IO_CallBack ConnFail,
1138 IO_CallBack Timeout,
1139 IO_CallBack ShutdownAbort)
1143 IO->CitContext = CloneContext(CC);
1144 IO->CitContext->session_specific_data = Data;
1145 IO->CitContext->IO = IO;
1147 IO->NextState = NextState;
1149 IO->SendDone = SendDone;
1150 IO->ReadDone = ReadDone;
1151 IO->Terminate = Terminate;
1152 IO->DBTerminate = DBTerminate;
1153 IO->LineReader = LineReader;
1154 IO->ConnFail = ConnFail;
1155 IO->Timeout = Timeout;
1156 IO->ShutdownAbort = ShutdownAbort;
1158 IO->DNS.Fail = DNS_Fail;
1160 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1161 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1162 IO->IOBuf = NewStrBuf();
1163 EV_syslog(LOG_DEBUG,
1164 "EVENT: Session lives at %p IO at %p \n",
1169 extern int evcurl_init(AsyncIO *IO);
1171 int InitcURLIOStruct(AsyncIO *IO,
1174 IO_CallBack SendDone,
1175 IO_CallBack Terminate,
1176 IO_CallBack DBTerminate,
1177 IO_CallBack ShutdownAbort)
1181 IO->CitContext = CloneContext(CC);
1182 IO->CitContext->session_specific_data = Data;
1183 IO->CitContext->IO = IO;
1185 IO->SendDone = SendDone;
1186 IO->Terminate = Terminate;
1187 IO->DBTerminate = DBTerminate;
1188 IO->ShutdownAbort = ShutdownAbort;
1190 strcpy(IO->HttpReq.errdesc, Desc);
1193 return evcurl_init(IO);
1198 typedef struct KillOtherSessionContext {
1201 }KillOtherSessionContext;
1203 eNextState KillTerminate(AsyncIO *IO)
1206 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1207 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1209 FreeAsyncIOContents(IO);
1210 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1211 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1217 eNextState KillShutdown(AsyncIO *IO)
1219 return eTerminateConnection;
1222 eNextState KillOtherContextNow(AsyncIO *IO)
1224 KillOtherSessionContext *Ctx = IO->Data;
1226 SetEVState(IO, eKill);
1228 if (Ctx->OtherOne->ShutdownAbort != NULL)
1229 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1230 return eTerminateConnection;
1233 void KillAsyncIOContext(AsyncIO *IO)
1235 KillOtherSessionContext *Ctx;
1237 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1238 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1240 InitIOStruct(&Ctx->IO,
1255 switch(IO->NextState) {
1268 QueueEventContext(&Ctx->IO, KillOtherContextNow);
1271 QueueDBOperation(&Ctx->IO, KillOtherContextNow);
1273 case eTerminateConnection:
1275 /*hm, its already dying, dunno which Queue its in... */
1281 extern int DebugEventLoopBacktrace;
1282 void EV_backtrace(AsyncIO *IO)
1284 #ifdef HAVE_BACKTRACE
1285 void *stack_frames[50];
1289 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1291 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1292 strings = backtrace_symbols(stack_frames, size);
1293 for (i = 0; i < size; i++) {
1294 if (strings != NULL) {
1295 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1298 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1306 ev_tstamp ctdl_ev_now (void)
1308 return ev_now(event_base);