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.
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
25 #include <libcitadel.h>
27 #include "ctdl_module.h"
28 #include "event_client.h"
30 ConstStr IOStates[] = {
37 {HKEY("DB Terminate")},
40 {HKEY("IO Connect Socket")},
43 {HKEY("IO ConnFail")},
44 {HKEY("IO ConnFail Now")},
45 {HKEY("IO Conn Now")},
46 {HKEY("IO Conn Wait")},
49 {HKEY("Curl Shotdown")},
50 {HKEY("Curl More IO")},
51 {HKEY("Curl Got IO")},
52 {HKEY("Curl Got Data")},
53 {HKEY("Curl Got Status")},
54 {HKEY("C-Ares Start")},
55 {HKEY("C-Ares IO Done")},
56 {HKEY("C-Ares Finished")},
57 {HKEY("C-Ares exit")},
62 void SetEVState(AsyncIO *IO, eIOState State)
65 CitContext* CCC = IO->CitContext;
67 memcpy(CCC->lastcmdname, IOStates[State].Key, IOStates[State].len + 1);
72 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
73 static void IO_abort_shutdown_callback(struct ev_loop *loop,
78 /*------------------------------------------------------------------------------
80 *----------------------------------------------------------------------------*/
81 extern int evdb_count;
82 extern pthread_mutex_t DBEventQueueMutex;
83 extern pthread_mutex_t DBEventExitQueueMutex;
84 extern HashList *DBInboundEventQueue;
85 extern struct ev_loop *event_db;
86 extern ev_async DBAddJob;
87 extern ev_async DBExitEventLoop;
89 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
95 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
98 ev_cleanup_init(&IO->db_abort_by_shutdown,
99 IO_abort_shutdown_callback);
100 IO->db_abort_by_shutdown.data = IO;
102 pthread_mutex_lock(&DBEventQueueMutex);
103 if (DBInboundEventQueue == NULL)
105 /* shutting down... */
107 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
108 pthread_mutex_unlock(&DBEventQueueMutex);
111 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
113 Put(DBInboundEventQueue, IKEY(i), h, NULL);
114 pthread_mutex_unlock(&DBEventQueueMutex);
116 pthread_mutex_lock(&DBEventExitQueueMutex);
117 if (event_db == NULL)
119 pthread_mutex_unlock(&DBEventExitQueueMutex);
122 ev_async_send (event_db, &DBAddJob);
123 pthread_mutex_unlock(&DBEventExitQueueMutex);
125 EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
129 void StopDBWatchers(AsyncIO *IO)
131 SetEVState(IO, eDBStop);
132 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
133 ev_idle_stop(event_db, &IO->db_unwind_stack);
136 void ShutDownDBCLient(AsyncIO *IO)
138 CitContext *Ctx =IO->CitContext;
141 SetEVState(IO, eDBTerm);
142 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
145 assert(IO->DBTerminate);
150 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
152 AsyncIO *IO = watcher->data;
154 SetEVState(IO, eDBNext);
155 IO->Now = ev_now(event_db);
156 EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
157 become_session(IO->CitContext);
159 ev_idle_stop(event_db, &IO->db_unwind_stack);
161 assert(IO->NextDBOperation);
162 switch (IO->NextDBOperation(IO))
176 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
178 case eTerminateConnection:
180 ev_idle_stop(event_db, &IO->db_unwind_stack);
181 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
182 ShutDownDBCLient(IO);
186 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
188 SetEVState(IO, eQDBNext);
189 IO->NextDBOperation = CB;
190 ev_idle_init(&IO->db_unwind_stack,
192 IO->db_unwind_stack.data = IO;
193 ev_idle_start(event_db, &IO->db_unwind_stack);
197 /*------------------------------------------------------------------------------
199 *----------------------------------------------------------------------------*/
200 extern int evbase_count;
201 extern pthread_mutex_t EventQueueMutex;
202 extern pthread_mutex_t EventExitQueueMutex;
203 extern HashList *InboundEventQueue;
204 extern struct ev_loop *event_base;
205 extern ev_async AddJob;
206 extern ev_async ExitEventLoop;
208 static void IO_abort_shutdown_callback(struct ev_loop *loop,
212 AsyncIO *IO = watcher->data;
214 SetEVState(IO, eIOAbort);
215 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
216 IO->Now = ev_now(event_base);
217 assert(IO->ShutdownAbort);
218 IO->ShutdownAbort(IO);
222 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
227 SetEVState(IO, eIOQ);
228 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
231 ev_cleanup_init(&IO->abort_by_shutdown,
232 IO_abort_shutdown_callback);
233 IO->abort_by_shutdown.data = IO;
235 pthread_mutex_lock(&EventQueueMutex);
236 if (InboundEventQueue == NULL)
239 /* shutting down... */
240 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
241 pthread_mutex_unlock(&EventQueueMutex);
244 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
246 Put(InboundEventQueue, IKEY(i), h, NULL);
247 pthread_mutex_unlock(&EventQueueMutex);
249 pthread_mutex_lock(&EventExitQueueMutex);
250 if (event_base == NULL) {
251 pthread_mutex_unlock(&EventExitQueueMutex);
254 ev_async_send (event_base, &AddJob);
255 pthread_mutex_unlock(&EventExitQueueMutex);
256 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
260 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
262 StopClientWatchers(IO, 0);
263 return QueueDBOperation(IO, CB);
265 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
268 return QueueEventContext(IO, CB);
271 extern eNextState evcurl_handle_start(AsyncIO *IO);
273 eNextState QueueCurlContext(AsyncIO *IO)
278 SetEVState(IO, eCurlQ);
279 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
281 h->EvAttch = evcurl_handle_start;
283 pthread_mutex_lock(&EventQueueMutex);
284 if (InboundEventQueue == NULL)
286 /* shutting down... */
288 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
289 pthread_mutex_unlock(&EventQueueMutex);
293 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
295 Put(InboundEventQueue, IKEY(i), h, NULL);
296 pthread_mutex_unlock(&EventQueueMutex);
298 pthread_mutex_lock(&EventExitQueueMutex);
299 if (event_base == NULL) {
300 pthread_mutex_unlock(&EventExitQueueMutex);
303 ev_async_send (event_base, &AddJob);
304 pthread_mutex_unlock(&EventExitQueueMutex);
306 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
310 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
312 StopCurlWatchers(IO);
313 return QueueDBOperation(IO, CB);
317 void DestructCAres(AsyncIO *IO);
318 void FreeAsyncIOContents(AsyncIO *IO)
320 CitContext *Ctx = IO->CitContext;
322 FreeStrBuf(&IO->IOBuf);
323 FreeStrBuf(&IO->SendBuf.Buf);
324 FreeStrBuf(&IO->RecvBuf.Buf);
328 FreeURL(&IO->ConnectMe);
329 FreeStrBuf(&IO->HttpReq.ReplyData);
332 Ctx->state = CON_IDLE;
334 IO->CitContext = NULL;
339 void StopClientWatchers(AsyncIO *IO, int CloseFD)
341 ev_timer_stop (event_base, &IO->rw_timeout);
342 ev_timer_stop(event_base, &IO->conn_fail);
343 ev_idle_stop(event_base, &IO->unwind_stack);
344 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
346 ev_io_stop(event_base, &IO->conn_event);
347 ev_io_stop(event_base, &IO->send_event);
348 ev_io_stop(event_base, &IO->recv_event);
350 if (CloseFD && (IO->SendBuf.fd > 0)) {
351 close(IO->SendBuf.fd);
357 void StopCurlWatchers(AsyncIO *IO)
359 EVM_syslog(LOG_DEBUG, "EVENT StopCurlWatchers \n");
361 ev_timer_stop (event_base, &IO->rw_timeout);
362 ev_timer_stop(event_base, &IO->conn_fail);
363 ev_idle_stop(event_base, &IO->unwind_stack);
364 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
366 ev_io_stop(event_base, &IO->conn_event);
367 ev_io_stop(event_base, &IO->send_event);
368 ev_io_stop(event_base, &IO->recv_event);
370 curl_easy_cleanup(IO->HttpReq.chnd);
371 IO->HttpReq.chnd = NULL;
373 if (IO->SendBuf.fd != 0) {
374 close(IO->SendBuf.fd);
380 void ShutDownCLient(AsyncIO *IO)
382 CitContext *Ctx =IO->CitContext;
384 SetEVState(IO, eExit);
387 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
389 StopClientWatchers(IO, 1);
391 if (IO->DNS.Channel != NULL) {
392 ares_destroy(IO->DNS.Channel);
393 EV_DNS_LOG_STOP(DNS.recv_event);
394 EV_DNS_LOG_STOP(DNS.send_event);
395 ev_io_stop(event_base, &IO->DNS.recv_event);
396 ev_io_stop(event_base, &IO->DNS.send_event);
397 IO->DNS.Channel = NULL;
399 assert(IO->Terminate);
403 void PostInbound(AsyncIO *IO)
405 switch (IO->NextState) {
407 ev_io_start(event_base, &IO->send_event);
411 assert(IO->SendDone);
412 IO->NextState = IO->SendDone(IO);
413 switch (IO->NextState)
422 ev_io_start(event_base, &IO->send_event);
425 StopClientWatchers(IO, 0);
433 ev_io_start(event_base, &IO->recv_event);
435 case eTerminateConnection:
449 eReadState HandleInbound(AsyncIO *IO)
451 const char *Err = NULL;
452 eReadState Finished = eBufferNotEmpty;
454 become_session(IO->CitContext);
456 while ((Finished == eBufferNotEmpty) &&
457 ((IO->NextState == eReadMessage)||
458 (IO->NextState == eReadMore)||
459 (IO->NextState == eReadFile)||
460 (IO->NextState == eReadPayload)))
463 * lex line reply in callback,
464 * or do it ourselves.
465 * i.e. as nnn-blabla means continue reading in SMTP
467 if ((IO->NextState == eReadFile) &&
468 (Finished == eBufferNotEmpty))
470 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
471 if (Finished == eReadSuccess)
473 IO->NextState = eSendReply;
476 else if (IO->LineReader)
477 Finished = IO->LineReader(IO);
479 Finished = StrBufChunkSipLine(IO->IOBuf,
483 case eMustReadMore: /// read new from socket...
485 case eBufferNotEmpty: /* shouldn't happen... */
486 case eReadSuccess: /// done for now...
488 case eReadFail: /// WHUT?
493 if (Finished != eMustReadMore) {
494 assert(IO->ReadDone);
495 ev_io_stop(event_base, &IO->recv_event);
496 IO->NextState = IO->ReadDone(IO);
497 Finished = StrBufCheckBuffer(&IO->RecvBuf);
508 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
511 AsyncIO *IO = watcher->data;
512 const char *errmsg = NULL;
514 IO->Now = ev_now(event_base);
515 become_session(IO->CitContext);
521 const char *pch = ChrPtr(IO->SendBuf.Buf);
522 const char *pchh = IO->SendBuf.ReadWritePointer;
528 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
529 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
530 ((CitContext*)(IO->CitContext))->ServiceName,
533 fd = fopen(fn, "a+");
534 fprintf(fd, "Send: BufSize: %ld BufContent: [",
536 rv = fwrite(pchh, nbytes, 1, fd);
537 if (!rv) printf("failed to write debug to %s!\n", fn);
540 switch (IO->NextState) {
542 rc = FileSendChunked(&IO->IOB, &errmsg);
544 StrBufPlain(IO->ErrMsg, errmsg, -1);
547 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
553 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
559 ev_io_stop(event_base, &IO->send_event);
560 switch (IO->NextState) {
562 assert(IO->SendDone);
563 IO->NextState = IO->SendDone(IO);
565 if ((IO->NextState == eTerminateConnection) ||
566 (IO->NextState == eAbort) )
569 ev_io_start(event_base, &IO->send_event);
573 if (IO->IOB.ChunkSendRemain > 0) {
574 ev_io_start(event_base, &IO->recv_event);
575 SetNextTimeout(IO, 100.0);
578 assert(IO->ReadDone);
579 IO->NextState = IO->ReadDone(IO);
580 switch(IO->NextState) {
589 ev_io_start(event_base,
597 case eTerminateConnection:
604 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
606 IO->NextState = eReadMore;
611 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
616 ev_io_start(event_base, &IO->recv_event);
622 * we now live in another queue,
623 * so we have to unregister.
625 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
630 case eTerminateConnection:
636 if (errno != EAGAIN) {
637 StopClientWatchers(IO, 1);
639 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
640 errno, strerror(errno), IO->SendBuf.fd);
641 StrBufPrintf(IO->ErrMsg,
642 "Socket Invalid! [%s]",
644 SetNextTimeout(IO, 0.01);
647 /* else : must write more. */
650 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
652 ev_timer_stop(event_base, &IO->conn_fail);
653 ev_timer_start(event_base, &IO->rw_timeout);
655 switch(IO->NextState) {
659 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
660 ev_io_start(event_base, &IO->recv_event);
666 become_session(IO->CitContext);
667 IO_send_callback(loop, &IO->send_event, revents);
673 case eTerminateConnection:
681 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
683 AsyncIO *IO = watcher->data;
685 SetEVState(IO, eIOTimeout);
686 IO->Now = ev_now(event_base);
687 ev_timer_stop (event_base, &IO->rw_timeout);
688 become_session(IO->CitContext);
690 if (IO->SendBuf.fd != 0)
692 ev_io_stop(event_base, &IO->send_event);
693 ev_io_stop(event_base, &IO->recv_event);
694 ev_timer_stop (event_base, &IO->rw_timeout);
695 close(IO->SendBuf.fd);
696 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
700 switch (IO->Timeout(IO))
710 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
712 AsyncIO *IO = watcher->data;
714 SetEVState(IO, eIOConnfail);
715 IO->Now = ev_now(event_base);
716 ev_timer_stop (event_base, &IO->conn_fail);
718 if (IO->SendBuf.fd != 0)
720 ev_io_stop(loop, &IO->conn_event);
721 ev_io_stop(event_base, &IO->send_event);
722 ev_io_stop(event_base, &IO->recv_event);
723 ev_timer_stop (event_base, &IO->rw_timeout);
724 close(IO->SendBuf.fd);
725 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
727 become_session(IO->CitContext);
729 assert(IO->ConnFail);
730 switch (IO->ConnFail(IO))
741 IO_connfailimmediate_callback(struct ev_loop *loop,
745 AsyncIO *IO = watcher->data;
747 SetEVState(IO, eIOConnfailNow);
748 IO->Now = ev_now(event_base);
749 ev_idle_stop (event_base, &IO->conn_fail_immediate);
751 if (IO->SendBuf.fd != 0)
753 close(IO->SendBuf.fd);
754 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
756 become_session(IO->CitContext);
758 assert(IO->ConnFail);
759 switch (IO->ConnFail(IO))
770 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
772 AsyncIO *IO = watcher->data;
774 socklen_t lon = sizeof(so_err);
777 SetEVState(IO, eIOConnNow);
778 IO->Now = ev_now(event_base);
779 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
781 ev_io_stop(loop, &IO->conn_event);
782 ev_timer_stop(event_base, &IO->conn_fail);
784 err = getsockopt(IO->SendBuf.fd,
790 if ((err == 0) && (so_err != 0))
792 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
795 IO_connfail_callback(loop, &IO->conn_fail, revents);
800 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
801 set_start_callback(loop, IO, revents);
806 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
810 AsyncIO *IO = watcher->data;
812 IO->Now = ev_now(event_base);
813 switch (IO->NextState) {
815 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
817 StrBufPlain(IO->ErrMsg, errmsg, -1);
820 if (IO->IOB.ChunkSendRemain == 0)
822 IO->NextState = eSendReply;
823 assert(IO->ReadDone);
824 ev_io_stop(event_base, &IO->recv_event);
833 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
845 const char *pch = ChrPtr(IO->RecvBuf.Buf);
846 const char *pchh = IO->RecvBuf.ReadWritePointer;
851 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
852 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
853 ((CitContext*)(IO->CitContext))->ServiceName,
856 fd = fopen(fn, "a+");
857 fprintf(fd, "Read: BufSize: %ld BufContent: [",
859 rv = fwrite(pchh, nbytes, 1, fd);
860 if (!rv) printf("failed to write debug to %s!\n", fn);
867 } else if (nbytes == 0) {
868 StopClientWatchers(IO, 1);
869 SetNextTimeout(IO, 0.01);
871 } else if (nbytes == -1) {
872 if (errno != EAGAIN) {
873 // FD is gone. kick it.
874 StopClientWatchers(IO, 1);
876 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
877 errno, strerror(errno), IO->SendBuf.fd);
878 StrBufPrintf(IO->ErrMsg,
879 "Socket Invalid! [%s]",
881 SetNextTimeout(IO, 0.01);
888 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
890 AsyncIO *IO = watcher->data;
892 SetEVState(IO, eCaresFinished);
893 IO->Now = ev_now(event_base);
894 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
895 become_session(IO->CitContext);
896 assert(IO->DNS.Query->PostDNS);
897 switch (IO->DNS.Query->PostDNS(IO))
900 assert(IO->DNS.Fail);
901 switch (IO->DNS.Fail(IO)) {
903 //// StopClientWatchers(IO);
914 eNextState EvConnectSock(AsyncIO *IO,
916 double first_rw_timeout,
919 struct sockaddr_in egress_sin;
923 SetEVState(IO, eIOConnectSock);
924 become_session(IO->CitContext);
927 IO->NextState = eReadMessage;
930 IO->NextState = eSendReply;
933 IO->SendBuf.fd = IO->RecvBuf.fd =
935 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
939 if (IO->SendBuf.fd < 0) {
941 "EVENT: socket() failed: %s\n",
944 StrBufPrintf(IO->ErrMsg,
945 "Failed to create socket: %s",
947 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
950 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
953 "EVENT: unable to get socket %d flags! %s \n",
956 StrBufPrintf(IO->ErrMsg,
957 "Failed to get socket %d flags: %s",
960 close(IO->SendBuf.fd);
961 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
964 fdflags = fdflags | O_NONBLOCK;
965 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
968 "EVENT: unable to set socket %d nonblocking flags! %s \n",
971 StrBufPrintf(IO->ErrMsg,
972 "Failed to set socket flags: %s",
974 close(IO->SendBuf.fd);
975 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
978 /* TODO: maye we could use offsetof() to calc the position of data...
979 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
981 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
982 IO->recv_event.data = IO;
983 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
984 IO->send_event.data = IO;
986 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
987 IO->conn_fail.data = IO;
988 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
989 IO->rw_timeout.data = IO;
994 /* for debugging you may bypass it like this:
995 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
996 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
997 * inet_addr("127.0.0.1");
999 if (IO->ConnectMe->IPv6) {
1000 rc = connect(IO->SendBuf.fd,
1001 &IO->ConnectMe->Addr,
1002 sizeof(struct sockaddr_in6));
1005 /* If citserver is bound to a specific IP address on the host, make
1006 * sure we use that address for outbound connections.
1009 memset(&egress_sin, 0, sizeof(egress_sin));
1010 egress_sin.sin_family = AF_INET;
1011 if (!IsEmptyStr(config.c_ip_addr)) {
1012 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1013 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1014 egress_sin.sin_addr.s_addr = INADDR_ANY;
1017 /* If this bind fails, no problem; we can still use INADDR_ANY */
1018 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1020 rc = connect(IO->SendBuf.fd,
1021 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1022 sizeof(struct sockaddr_in));
1026 SetEVState(IO, eIOConnNow);
1027 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1028 set_start_callback(event_base, IO, 0);
1029 return IO->NextState;
1031 else if (errno == EINPROGRESS) {
1032 SetEVState(IO, eIOConnWait);
1033 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1035 ev_io_init(&IO->conn_event,
1036 IO_connestd_callback,
1040 IO->conn_event.data = IO;
1042 ev_io_start(event_base, &IO->conn_event);
1043 ev_timer_start(event_base, &IO->conn_fail);
1044 return IO->NextState;
1047 SetEVState(IO, eIOConnfail);
1048 ev_idle_init(&IO->conn_fail_immediate,
1049 IO_connfailimmediate_callback);
1050 IO->conn_fail_immediate.data = IO;
1051 ev_idle_start(event_base, &IO->conn_fail_immediate);
1054 "connect() = %d failed: %s\n",
1058 StrBufPrintf(IO->ErrMsg,
1059 "Failed to connect: %s",
1061 return IO->NextState;
1063 return IO->NextState;
1066 void SetNextTimeout(AsyncIO *IO, double timeout)
1068 IO->rw_timeout.repeat = timeout;
1069 ev_timer_again (event_base, &IO->rw_timeout);
1073 eNextState ReAttachIO(AsyncIO *IO,
1077 SetEVState(IO, eIOAttach);
1079 become_session(IO->CitContext);
1080 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1082 IO->NextState = eReadMessage;
1085 IO->NextState = eSendReply;
1087 set_start_callback(event_base, IO, 0);
1089 return IO->NextState;
1092 void InitIOStruct(AsyncIO *IO,
1094 eNextState NextState,
1095 IO_LineReaderCallback LineReader,
1096 IO_CallBack DNS_Fail,
1097 IO_CallBack SendDone,
1098 IO_CallBack ReadDone,
1099 IO_CallBack Terminate,
1100 IO_CallBack DBTerminate,
1101 IO_CallBack ConnFail,
1102 IO_CallBack Timeout,
1103 IO_CallBack ShutdownAbort)
1107 IO->CitContext = CloneContext(CC);
1108 IO->CitContext->session_specific_data = Data;
1109 IO->CitContext->IO = IO;
1111 IO->NextState = NextState;
1113 IO->SendDone = SendDone;
1114 IO->ReadDone = ReadDone;
1115 IO->Terminate = Terminate;
1116 IO->DBTerminate = DBTerminate;
1117 IO->LineReader = LineReader;
1118 IO->ConnFail = ConnFail;
1119 IO->Timeout = Timeout;
1120 IO->ShutdownAbort = ShutdownAbort;
1122 IO->DNS.Fail = DNS_Fail;
1124 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1125 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1126 IO->IOBuf = NewStrBuf();
1127 EV_syslog(LOG_DEBUG,
1128 "EVENT: Session lives at %p IO at %p \n",
1133 extern int evcurl_init(AsyncIO *IO);
1135 int InitcURLIOStruct(AsyncIO *IO,
1138 IO_CallBack SendDone,
1139 IO_CallBack Terminate,
1140 IO_CallBack DBTerminate,
1141 IO_CallBack ShutdownAbort)
1145 IO->CitContext = CloneContext(CC);
1146 IO->CitContext->session_specific_data = Data;
1147 IO->CitContext->IO = IO;
1149 IO->SendDone = SendDone;
1150 IO->Terminate = Terminate;
1151 IO->DBTerminate = DBTerminate;
1152 IO->ShutdownAbort = ShutdownAbort;
1154 strcpy(IO->HttpReq.errdesc, Desc);
1157 return evcurl_init(IO);
1162 typedef struct KillOtherSessionContext {
1165 }KillOtherSessionContext;
1167 eNextState KillTerminate(AsyncIO *IO)
1170 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1171 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1173 FreeAsyncIOContents(IO);
1174 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1175 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1181 eNextState KillShutdown(AsyncIO *IO)
1183 return eTerminateConnection;
1186 eNextState KillOtherContextNow(AsyncIO *IO)
1188 KillOtherSessionContext *Ctx = IO->Data;
1190 SetEVState(IO, eKill);
1192 if (Ctx->OtherOne->ShutdownAbort != NULL)
1193 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1194 return eTerminateConnection;
1197 void KillAsyncIOContext(AsyncIO *IO)
1199 KillOtherSessionContext *Ctx;
1201 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1202 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1204 InitIOStruct(&Ctx->IO,
1219 switch(IO->NextState) {
1232 QueueEventContext(&Ctx->IO, KillOtherContextNow);
1235 QueueDBOperation(&Ctx->IO, KillOtherContextNow);
1237 case eTerminateConnection:
1239 /*hm, its already dying, dunno which Queue its in... */
1245 extern int DebugEventLoopBacktrace;
1246 void EV_backtrace(AsyncIO *IO)
1248 #ifdef HAVE_BACKTRACE
1249 void *stack_frames[50];
1253 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1255 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1256 strings = backtrace_symbols(stack_frames, size);
1257 for (i = 0; i < size; i++) {
1258 if (strings != NULL) {
1259 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1262 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1270 ev_tstamp ctdl_ev_now (void)
1272 return ev_now(event_base);