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 if (IO->SendBuf.fd != 0) {
407 close(IO->SendBuf.fd);
413 void ShutDownCLient(AsyncIO *IO)
415 CitContext *Ctx =IO->CitContext;
417 SetEVState(IO, eExit);
420 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
422 StopClientWatchers(IO, 1);
424 if (IO->DNS.Channel != NULL) {
425 ares_destroy(IO->DNS.Channel);
426 EV_DNS_LOG_STOP(DNS.recv_event);
427 EV_DNS_LOG_STOP(DNS.send_event);
428 ev_io_stop(event_base, &IO->DNS.recv_event);
429 ev_io_stop(event_base, &IO->DNS.send_event);
430 IO->DNS.Channel = NULL;
432 assert(IO->Terminate);
436 void PostInbound(AsyncIO *IO)
438 switch (IO->NextState) {
440 ev_io_start(event_base, &IO->send_event);
444 assert(IO->SendDone);
445 IO->NextState = IO->SendDone(IO);
446 switch (IO->NextState)
455 ev_io_start(event_base, &IO->send_event);
458 StopClientWatchers(IO, 0);
466 ev_io_start(event_base, &IO->recv_event);
468 case eTerminateConnection:
482 eReadState HandleInbound(AsyncIO *IO)
484 const char *Err = NULL;
485 eReadState Finished = eBufferNotEmpty;
487 become_session(IO->CitContext);
489 while ((Finished == eBufferNotEmpty) &&
490 ((IO->NextState == eReadMessage)||
491 (IO->NextState == eReadMore)||
492 (IO->NextState == eReadFile)||
493 (IO->NextState == eReadPayload)))
496 * lex line reply in callback,
497 * or do it ourselves.
498 * i.e. as nnn-blabla means continue reading in SMTP
500 if ((IO->NextState == eReadFile) &&
501 (Finished == eBufferNotEmpty))
503 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
504 if (Finished == eReadSuccess)
506 IO->NextState = eSendReply;
509 else if (IO->LineReader)
510 Finished = IO->LineReader(IO);
512 Finished = StrBufChunkSipLine(IO->IOBuf,
516 case eMustReadMore: /// read new from socket...
518 case eBufferNotEmpty: /* shouldn't happen... */
519 case eReadSuccess: /// done for now...
521 case eReadFail: /// WHUT?
526 if (Finished != eMustReadMore) {
527 assert(IO->ReadDone);
528 ev_io_stop(event_base, &IO->recv_event);
529 IO->NextState = IO->ReadDone(IO);
530 Finished = StrBufCheckBuffer(&IO->RecvBuf);
541 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
544 AsyncIO *IO = watcher->data;
545 const char *errmsg = NULL;
547 IO->Now = ev_now(event_base);
548 become_session(IO->CitContext);
554 const char *pch = ChrPtr(IO->SendBuf.Buf);
555 const char *pchh = IO->SendBuf.ReadWritePointer;
561 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
562 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
563 ((CitContext*)(IO->CitContext))->ServiceName,
566 fd = fopen(fn, "a+");
567 fprintf(fd, "Send: BufSize: %ld BufContent: [",
569 rv = fwrite(pchh, nbytes, 1, fd);
570 if (!rv) printf("failed to write debug to %s!\n", fn);
573 switch (IO->NextState) {
575 rc = FileSendChunked(&IO->IOB, &errmsg);
577 StrBufPlain(IO->ErrMsg, errmsg, -1);
580 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
586 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
592 ev_io_stop(event_base, &IO->send_event);
593 switch (IO->NextState) {
595 assert(IO->SendDone);
596 IO->NextState = IO->SendDone(IO);
598 if ((IO->NextState == eTerminateConnection) ||
599 (IO->NextState == eAbort) )
602 ev_io_start(event_base, &IO->send_event);
606 if (IO->IOB.ChunkSendRemain > 0) {
607 ev_io_start(event_base, &IO->recv_event);
608 SetNextTimeout(IO, 100.0);
611 assert(IO->ReadDone);
612 IO->NextState = IO->ReadDone(IO);
613 switch(IO->NextState) {
622 ev_io_start(event_base,
630 case eTerminateConnection:
637 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
639 IO->NextState = eReadMore;
644 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
649 ev_io_start(event_base, &IO->recv_event);
655 * we now live in another queue,
656 * so we have to unregister.
658 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
663 case eTerminateConnection:
669 if (errno != EAGAIN) {
670 StopClientWatchers(IO, 1);
672 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
673 errno, strerror(errno), IO->SendBuf.fd);
674 StrBufPrintf(IO->ErrMsg,
675 "Socket Invalid! [%s]",
677 SetNextTimeout(IO, 0.01);
680 /* else : must write more. */
683 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
685 ev_timer_stop(event_base, &IO->conn_fail);
686 ev_timer_start(event_base, &IO->rw_timeout);
688 switch(IO->NextState) {
692 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
693 ev_io_start(event_base, &IO->recv_event);
699 become_session(IO->CitContext);
700 IO_send_callback(loop, &IO->send_event, revents);
706 case eTerminateConnection:
714 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
716 AsyncIO *IO = watcher->data;
718 SetEVState(IO, eIOTimeout);
719 IO->Now = ev_now(event_base);
720 ev_timer_stop (event_base, &IO->rw_timeout);
721 become_session(IO->CitContext);
723 if (IO->SendBuf.fd != 0)
725 ev_io_stop(event_base, &IO->send_event);
726 ev_io_stop(event_base, &IO->recv_event);
727 ev_timer_stop (event_base, &IO->rw_timeout);
728 close(IO->SendBuf.fd);
729 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
733 switch (IO->Timeout(IO))
743 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
745 AsyncIO *IO = watcher->data;
747 SetEVState(IO, eIOConnfail);
748 IO->Now = ev_now(event_base);
749 ev_timer_stop (event_base, &IO->conn_fail);
751 if (IO->SendBuf.fd != 0)
753 ev_io_stop(loop, &IO->conn_event);
754 ev_io_stop(event_base, &IO->send_event);
755 ev_io_stop(event_base, &IO->recv_event);
756 ev_timer_stop (event_base, &IO->rw_timeout);
757 close(IO->SendBuf.fd);
758 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
760 become_session(IO->CitContext);
762 assert(IO->ConnFail);
763 switch (IO->ConnFail(IO))
774 IO_connfailimmediate_callback(struct ev_loop *loop,
778 AsyncIO *IO = watcher->data;
780 SetEVState(IO, eIOConnfailNow);
781 IO->Now = ev_now(event_base);
782 ev_idle_stop (event_base, &IO->conn_fail_immediate);
784 if (IO->SendBuf.fd != 0)
786 close(IO->SendBuf.fd);
787 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
789 become_session(IO->CitContext);
791 assert(IO->ConnFail);
792 switch (IO->ConnFail(IO))
803 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
805 AsyncIO *IO = watcher->data;
807 socklen_t lon = sizeof(so_err);
810 SetEVState(IO, eIOConnNow);
811 IO->Now = ev_now(event_base);
812 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
814 ev_io_stop(loop, &IO->conn_event);
815 ev_timer_stop(event_base, &IO->conn_fail);
817 err = getsockopt(IO->SendBuf.fd,
823 if ((err == 0) && (so_err != 0))
825 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
828 IO_connfail_callback(loop, &IO->conn_fail, revents);
833 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
834 set_start_callback(loop, IO, revents);
839 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
843 AsyncIO *IO = watcher->data;
845 IO->Now = ev_now(event_base);
846 switch (IO->NextState) {
848 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
850 StrBufPlain(IO->ErrMsg, errmsg, -1);
853 if (IO->IOB.ChunkSendRemain == 0)
855 IO->NextState = eSendReply;
856 assert(IO->ReadDone);
857 ev_io_stop(event_base, &IO->recv_event);
866 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
878 const char *pch = ChrPtr(IO->RecvBuf.Buf);
879 const char *pchh = IO->RecvBuf.ReadWritePointer;
884 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
885 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
886 ((CitContext*)(IO->CitContext))->ServiceName,
889 fd = fopen(fn, "a+");
890 fprintf(fd, "Read: BufSize: %ld BufContent: [",
892 rv = fwrite(pchh, nbytes, 1, fd);
893 if (!rv) printf("failed to write debug to %s!\n", fn);
900 } else if (nbytes == 0) {
901 StopClientWatchers(IO, 1);
902 SetNextTimeout(IO, 0.01);
904 } else if (nbytes == -1) {
905 if (errno != EAGAIN) {
906 // FD is gone. kick it.
907 StopClientWatchers(IO, 1);
909 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
910 errno, strerror(errno), IO->SendBuf.fd);
911 StrBufPrintf(IO->ErrMsg,
912 "Socket Invalid! [%s]",
914 SetNextTimeout(IO, 0.01);
921 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
923 AsyncIO *IO = watcher->data;
925 SetEVState(IO, eCaresFinished);
926 IO->Now = ev_now(event_base);
927 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
928 become_session(IO->CitContext);
929 assert(IO->DNS.Query->PostDNS);
930 switch (IO->DNS.Query->PostDNS(IO))
933 assert(IO->DNS.Fail);
934 switch (IO->DNS.Fail(IO)) {
936 //// StopClientWatchers(IO);
947 eNextState EvConnectSock(AsyncIO *IO,
949 double first_rw_timeout,
952 struct sockaddr_in egress_sin;
956 SetEVState(IO, eIOConnectSock);
957 become_session(IO->CitContext);
960 IO->NextState = eReadMessage;
963 IO->NextState = eSendReply;
966 IO->SendBuf.fd = IO->RecvBuf.fd =
968 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
972 if (IO->SendBuf.fd < 0) {
974 "EVENT: socket() failed: %s\n",
977 StrBufPrintf(IO->ErrMsg,
978 "Failed to create socket: %s",
980 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
983 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
986 "EVENT: unable to get socket %d flags! %s \n",
989 StrBufPrintf(IO->ErrMsg,
990 "Failed to get socket %d flags: %s",
993 close(IO->SendBuf.fd);
994 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
997 fdflags = fdflags | O_NONBLOCK;
998 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
1001 "EVENT: unable to set socket %d nonblocking flags! %s \n",
1004 StrBufPrintf(IO->ErrMsg,
1005 "Failed to set socket flags: %s",
1007 close(IO->SendBuf.fd);
1008 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1011 /* TODO: maye we could use offsetof() to calc the position of data...
1012 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1014 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1015 IO->recv_event.data = IO;
1016 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1017 IO->send_event.data = IO;
1019 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1020 IO->conn_fail.data = IO;
1021 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1022 IO->rw_timeout.data = IO;
1027 /* for debugging you may bypass it like this:
1028 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1029 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1030 * inet_addr("127.0.0.1");
1032 if (IO->ConnectMe->IPv6) {
1033 rc = connect(IO->SendBuf.fd,
1034 &IO->ConnectMe->Addr,
1035 sizeof(struct sockaddr_in6));
1038 /* If citserver is bound to a specific IP address on the host, make
1039 * sure we use that address for outbound connections.
1042 memset(&egress_sin, 0, sizeof(egress_sin));
1043 egress_sin.sin_family = AF_INET;
1044 if (!IsEmptyStr(config.c_ip_addr)) {
1045 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1046 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1047 egress_sin.sin_addr.s_addr = INADDR_ANY;
1050 /* If this bind fails, no problem; we can still use INADDR_ANY */
1051 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1053 rc = connect(IO->SendBuf.fd,
1054 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1055 sizeof(struct sockaddr_in));
1059 SetEVState(IO, eIOConnNow);
1060 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1061 set_start_callback(event_base, IO, 0);
1062 return IO->NextState;
1064 else if (errno == EINPROGRESS) {
1065 SetEVState(IO, eIOConnWait);
1066 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1068 ev_io_init(&IO->conn_event,
1069 IO_connestd_callback,
1073 IO->conn_event.data = IO;
1075 ev_io_start(event_base, &IO->conn_event);
1076 ev_timer_start(event_base, &IO->conn_fail);
1077 return IO->NextState;
1080 SetEVState(IO, eIOConnfail);
1081 ev_idle_init(&IO->conn_fail_immediate,
1082 IO_connfailimmediate_callback);
1083 IO->conn_fail_immediate.data = IO;
1084 ev_idle_start(event_base, &IO->conn_fail_immediate);
1087 "connect() = %d failed: %s\n",
1091 StrBufPrintf(IO->ErrMsg,
1092 "Failed to connect: %s",
1094 return IO->NextState;
1096 return IO->NextState;
1099 void SetNextTimeout(AsyncIO *IO, double timeout)
1101 IO->rw_timeout.repeat = timeout;
1102 ev_timer_again (event_base, &IO->rw_timeout);
1106 eNextState ReAttachIO(AsyncIO *IO,
1110 SetEVState(IO, eIOAttach);
1112 become_session(IO->CitContext);
1113 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1115 IO->NextState = eReadMessage;
1118 IO->NextState = eSendReply;
1120 set_start_callback(event_base, IO, 0);
1122 return IO->NextState;
1125 void InitIOStruct(AsyncIO *IO,
1127 eNextState NextState,
1128 IO_LineReaderCallback LineReader,
1129 IO_CallBack DNS_Fail,
1130 IO_CallBack SendDone,
1131 IO_CallBack ReadDone,
1132 IO_CallBack Terminate,
1133 IO_CallBack DBTerminate,
1134 IO_CallBack ConnFail,
1135 IO_CallBack Timeout,
1136 IO_CallBack ShutdownAbort)
1140 IO->CitContext = CloneContext(CC);
1141 IO->CitContext->session_specific_data = Data;
1142 IO->CitContext->IO = IO;
1144 IO->NextState = NextState;
1146 IO->SendDone = SendDone;
1147 IO->ReadDone = ReadDone;
1148 IO->Terminate = Terminate;
1149 IO->DBTerminate = DBTerminate;
1150 IO->LineReader = LineReader;
1151 IO->ConnFail = ConnFail;
1152 IO->Timeout = Timeout;
1153 IO->ShutdownAbort = ShutdownAbort;
1155 IO->DNS.Fail = DNS_Fail;
1157 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1158 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1159 IO->IOBuf = NewStrBuf();
1160 EV_syslog(LOG_DEBUG,
1161 "EVENT: Session lives at %p IO at %p \n",
1166 extern int evcurl_init(AsyncIO *IO);
1168 int InitcURLIOStruct(AsyncIO *IO,
1171 IO_CallBack SendDone,
1172 IO_CallBack Terminate,
1173 IO_CallBack DBTerminate,
1174 IO_CallBack ShutdownAbort)
1178 IO->CitContext = CloneContext(CC);
1179 IO->CitContext->session_specific_data = Data;
1180 IO->CitContext->IO = IO;
1182 IO->SendDone = SendDone;
1183 IO->Terminate = Terminate;
1184 IO->DBTerminate = DBTerminate;
1185 IO->ShutdownAbort = ShutdownAbort;
1187 strcpy(IO->HttpReq.errdesc, Desc);
1190 return evcurl_init(IO);
1195 typedef struct KillOtherSessionContext {
1198 }KillOtherSessionContext;
1200 eNextState KillTerminate(AsyncIO *IO)
1203 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1204 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1206 FreeAsyncIOContents(IO);
1207 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1208 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1214 eNextState KillShutdown(AsyncIO *IO)
1216 return eTerminateConnection;
1219 eNextState KillOtherContextNow(AsyncIO *IO)
1221 KillOtherSessionContext *Ctx = IO->Data;
1223 SetEVState(IO, eKill);
1225 if (Ctx->OtherOne->ShutdownAbort != NULL)
1226 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1227 return eTerminateConnection;
1230 void KillAsyncIOContext(AsyncIO *IO)
1232 KillOtherSessionContext *Ctx;
1234 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1235 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1237 InitIOStruct(&Ctx->IO,
1252 switch(IO->NextState) {
1265 QueueEventContext(&Ctx->IO, KillOtherContextNow);
1268 QueueDBOperation(&Ctx->IO, KillOtherContextNow);
1270 case eTerminateConnection:
1272 /*hm, its already dying, dunno which Queue its in... */
1278 extern int DebugEventLoopBacktrace;
1279 void EV_backtrace(AsyncIO *IO)
1281 #ifdef HAVE_BACKTRACE
1282 void *stack_frames[50];
1286 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1288 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1289 strings = backtrace_symbols(stack_frames, size);
1290 for (i = 0; i < size; i++) {
1291 if (strings != NULL) {
1292 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1295 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1303 ev_tstamp ctdl_ev_now (void)
1305 return ev_now(event_base);