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);
71 eNextState QueueAnEventContext(AsyncIO *IO);
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 QueueAnDBOperation(AsyncIO *IO)
95 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
98 assert(IO->ReAttachCB != NULL);
100 h->EvAttch = IO->ReAttachCB;
101 ev_cleanup_init(&IO->db_abort_by_shutdown,
102 IO_abort_shutdown_callback);
103 IO->db_abort_by_shutdown.data = IO;
105 pthread_mutex_lock(&DBEventQueueMutex);
106 if (DBInboundEventQueue == NULL)
108 /* shutting down... */
110 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
111 pthread_mutex_unlock(&DBEventQueueMutex);
114 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
116 Put(DBInboundEventQueue, IKEY(i), h, NULL);
117 pthread_mutex_unlock(&DBEventQueueMutex);
119 pthread_mutex_lock(&DBEventExitQueueMutex);
120 if (event_db == NULL)
122 pthread_mutex_unlock(&DBEventExitQueueMutex);
125 ev_async_send (event_db, &DBAddJob);
126 pthread_mutex_unlock(&DBEventExitQueueMutex);
128 EVQM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
132 void StopDBWatchers(AsyncIO *IO)
134 SetEVState(IO, eDBStop);
135 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
136 ev_idle_stop(event_db, &IO->db_unwind_stack);
139 void ShutDownDBCLient(AsyncIO *IO)
141 CitContext *Ctx =IO->CitContext;
144 SetEVState(IO, eDBTerm);
145 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
148 assert(IO->DBTerminate);
153 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
155 AsyncIO *IO = watcher->data;
157 SetEVState(IO, eDBNext);
158 IO->Now = ev_now(event_db);
159 EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
160 become_session(IO->CitContext);
162 ev_idle_stop(event_db, &IO->db_unwind_stack);
164 assert(IO->NextDBOperation);
165 switch (IO->NextDBOperation(IO))
168 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
169 QueueAnEventContext(IO);
182 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
184 case eTerminateConnection:
186 ev_idle_stop(event_db, &IO->db_unwind_stack);
187 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
188 ShutDownDBCLient(IO);
192 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
194 SetEVState(IO, eQDBNext);
195 IO->NextDBOperation = CB;
196 ev_idle_init(&IO->db_unwind_stack,
198 IO->db_unwind_stack.data = IO;
199 ev_idle_start(event_db, &IO->db_unwind_stack);
203 /*------------------------------------------------------------------------------
205 *----------------------------------------------------------------------------*/
206 extern int evbase_count;
207 extern pthread_mutex_t EventQueueMutex;
208 extern pthread_mutex_t EventExitQueueMutex;
209 extern HashList *InboundEventQueue;
210 extern struct ev_loop *event_base;
211 extern ev_async AddJob;
212 extern ev_async ExitEventLoop;
214 static void IO_abort_shutdown_callback(struct ev_loop *loop,
218 AsyncIO *IO = watcher->data;
220 SetEVState(IO, eIOAbort);
221 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
222 IO->Now = ev_now(event_base);
223 assert(IO->ShutdownAbort);
224 IO->ShutdownAbort(IO);
228 eNextState QueueAnEventContext(AsyncIO *IO)
233 SetEVState(IO, eIOQ);
234 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
237 assert(IO->ReAttachCB != NULL);
239 h->EvAttch = IO->ReAttachCB;
241 ev_cleanup_init(&IO->abort_by_shutdown,
242 IO_abort_shutdown_callback);
243 IO->abort_by_shutdown.data = IO;
245 pthread_mutex_lock(&EventQueueMutex);
246 if (InboundEventQueue == NULL)
249 /* shutting down... */
250 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
251 pthread_mutex_unlock(&EventQueueMutex);
254 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
256 Put(InboundEventQueue, IKEY(i), h, NULL);
257 pthread_mutex_unlock(&EventQueueMutex);
259 pthread_mutex_lock(&EventExitQueueMutex);
260 if (event_base == NULL) {
261 pthread_mutex_unlock(&EventExitQueueMutex);
264 ev_async_send (event_base, &AddJob);
265 pthread_mutex_unlock(&EventExitQueueMutex);
266 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
270 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB, int CloseFDs)
272 StopClientWatchers(IO, CloseFDs);
276 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
283 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
286 return QueueAnEventContext(IO);
289 extern eNextState evcurl_handle_start(AsyncIO *IO);
291 eNextState QueueCurlContext(AsyncIO *IO)
296 SetEVState(IO, eCurlQ);
297 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
299 h->EvAttch = evcurl_handle_start;
301 pthread_mutex_lock(&EventQueueMutex);
302 if (InboundEventQueue == NULL)
304 /* shutting down... */
306 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
307 pthread_mutex_unlock(&EventQueueMutex);
311 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
313 Put(InboundEventQueue, IKEY(i), h, NULL);
314 pthread_mutex_unlock(&EventQueueMutex);
316 pthread_mutex_lock(&EventExitQueueMutex);
317 if (event_base == NULL) {
318 pthread_mutex_unlock(&EventExitQueueMutex);
321 ev_async_send (event_base, &AddJob);
322 pthread_mutex_unlock(&EventExitQueueMutex);
324 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
328 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
330 StopCurlWatchers(IO);
336 void FreeAsyncIOContents(AsyncIO *IO)
338 CitContext *Ctx = IO->CitContext;
340 FreeStrBuf(&IO->IOBuf);
341 FreeStrBuf(&IO->SendBuf.Buf);
342 FreeStrBuf(&IO->RecvBuf.Buf);
344 FreeURL(&IO->ConnectMe);
345 FreeStrBuf(&IO->HttpReq.ReplyData);
348 Ctx->state = CON_IDLE;
350 IO->CitContext = NULL;
355 void DestructCAres(AsyncIO *IO);
356 void StopClientWatchers(AsyncIO *IO, int CloseFD)
358 EVM_syslog(LOG_DEBUG, "EVENT StopClientWatchers");
362 ev_timer_stop (event_base, &IO->rw_timeout);
363 ev_timer_stop(event_base, &IO->conn_fail);
364 ev_idle_stop(event_base, &IO->unwind_stack);
365 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
367 ev_io_stop(event_base, &IO->conn_event);
368 ev_io_stop(event_base, &IO->send_event);
369 ev_io_stop(event_base, &IO->recv_event);
371 if (CloseFD && (IO->SendBuf.fd > 0)) {
372 close(IO->SendBuf.fd);
378 void StopCurlWatchers(AsyncIO *IO)
380 EVM_syslog(LOG_DEBUG, "EVENT StopCurlWatchers \n");
382 ev_timer_stop (event_base, &IO->rw_timeout);
383 ev_timer_stop(event_base, &IO->conn_fail);
384 ev_idle_stop(event_base, &IO->unwind_stack);
385 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
387 ev_io_stop(event_base, &IO->conn_event);
388 ev_io_stop(event_base, &IO->send_event);
389 ev_io_stop(event_base, &IO->recv_event);
391 curl_easy_cleanup(IO->HttpReq.chnd);
392 IO->HttpReq.chnd = NULL;
394 if (IO->SendBuf.fd != 0) {
395 close(IO->SendBuf.fd);
401 eNextState ShutDownCLient(AsyncIO *IO)
403 CitContext *Ctx =IO->CitContext;
405 SetEVState(IO, eExit);
408 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
410 StopClientWatchers(IO, 1);
412 if (IO->DNS.Channel != NULL) {
413 ares_destroy(IO->DNS.Channel);
414 EV_DNS_LOG_STOP(DNS.recv_event);
415 EV_DNS_LOG_STOP(DNS.send_event);
416 ev_io_stop(event_base, &IO->DNS.recv_event);
417 ev_io_stop(event_base, &IO->DNS.send_event);
418 IO->DNS.Channel = NULL;
420 assert(IO->Terminate);
421 return IO->Terminate(IO);
424 void PostInbound(AsyncIO *IO)
427 switch (IO->NextState) {
429 ev_io_start(event_base, &IO->send_event);
433 assert(IO->SendDone);
434 IO->NextState = IO->SendDone(IO);
435 switch (IO->NextState)
444 ev_io_start(event_base, &IO->send_event);
447 StopClientWatchers(IO, 0);
448 QueueAnDBOperation(IO);
456 ev_io_start(event_base, &IO->recv_event);
458 case eTerminateConnection:
460 if (ShutDownCLient(IO) == eDBQuery) {
461 QueueAnDBOperation(IO);
470 QueueAnDBOperation(IO);
473 eReadState HandleInbound(AsyncIO *IO)
475 const char *Err = NULL;
476 eReadState Finished = eBufferNotEmpty;
478 become_session(IO->CitContext);
480 while ((Finished == eBufferNotEmpty) &&
481 ((IO->NextState == eReadMessage)||
482 (IO->NextState == eReadMore)||
483 (IO->NextState == eReadFile)||
484 (IO->NextState == eReadPayload)))
487 * lex line reply in callback,
488 * or do it ourselves.
489 * i.e. as nnn-blabla means continue reading in SMTP
491 if ((IO->NextState == eReadFile) &&
492 (Finished == eBufferNotEmpty))
494 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
495 if (Finished == eReadSuccess)
497 IO->NextState = eSendReply;
500 else if (IO->LineReader)
501 Finished = IO->LineReader(IO);
503 Finished = StrBufChunkSipLine(IO->IOBuf,
507 case eMustReadMore: /// read new from socket...
509 case eBufferNotEmpty: /* shouldn't happen... */
510 case eReadSuccess: /// done for now...
512 case eReadFail: /// WHUT?
517 if (Finished != eMustReadMore) {
518 ev_io_stop(event_base, &IO->recv_event);
519 IO->NextState = IO->ReadDone(IO);
520 if (IO->NextState == eDBQuery) {
521 if (QueueAnDBOperation(IO) == eAbort)
527 Finished = StrBufCheckBuffer(&IO->RecvBuf);
539 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
542 AsyncIO *IO = watcher->data;
543 const char *errmsg = NULL;
545 IO->Now = ev_now(event_base);
546 become_session(IO->CitContext);
552 const char *pch = ChrPtr(IO->SendBuf.Buf);
553 const char *pchh = IO->SendBuf.ReadWritePointer;
559 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
560 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
561 ((CitContext*)(IO->CitContext))->ServiceName,
564 fd = fopen(fn, "a+");
565 fprintf(fd, "Send: BufSize: %ld BufContent: [",
567 rv = fwrite(pchh, nbytes, 1, fd);
568 if (!rv) printf("failed to write debug to %s!\n", fn);
571 switch (IO->NextState) {
573 rc = FileSendChunked(&IO->IOB, &errmsg);
575 StrBufPlain(IO->ErrMsg, errmsg, -1);
578 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
584 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
590 ev_io_stop(event_base, &IO->send_event);
591 switch (IO->NextState) {
593 assert(IO->SendDone);
594 IO->NextState = IO->SendDone(IO);
596 if ((IO->NextState == eTerminateConnection) ||
597 (IO->NextState == eAbort) )
600 ev_io_start(event_base, &IO->send_event);
604 if (IO->IOB.ChunkSendRemain > 0) {
605 ev_io_start(event_base, &IO->recv_event);
606 SetNextTimeout(IO, 100.0);
609 assert(IO->ReadDone);
610 IO->NextState = IO->ReadDone(IO);
611 switch(IO->NextState) {
620 ev_io_start(event_base,
628 case eTerminateConnection:
635 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
637 IO->NextState = eReadMore;
642 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
647 ev_io_start(event_base, &IO->recv_event);
653 * we now live in another queue,
654 * so we have to unregister.
656 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
661 case eTerminateConnection:
667 if (errno != EAGAIN) {
668 StopClientWatchers(IO, 1);
670 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
671 errno, strerror(errno), IO->SendBuf.fd);
672 StrBufPrintf(IO->ErrMsg,
673 "Socket Invalid! [%s]",
675 SetNextTimeout(IO, 0.01);
678 /* else : must write more. */
681 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
683 ev_timer_stop(event_base, &IO->conn_fail);
684 ev_timer_start(event_base, &IO->rw_timeout);
686 switch(IO->NextState) {
690 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
691 ev_io_start(event_base, &IO->recv_event);
697 become_session(IO->CitContext);
698 IO_send_callback(loop, &IO->send_event, revents);
704 case eTerminateConnection:
712 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
714 AsyncIO *IO = watcher->data;
716 SetEVState(IO, eIOTimeout);
717 IO->Now = ev_now(event_base);
718 ev_timer_stop (event_base, &IO->rw_timeout);
719 become_session(IO->CitContext);
721 if (IO->SendBuf.fd != 0)
723 ev_io_stop(event_base, &IO->send_event);
724 ev_io_stop(event_base, &IO->recv_event);
725 ev_timer_stop (event_base, &IO->rw_timeout);
726 close(IO->SendBuf.fd);
727 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
731 switch (IO->Timeout(IO))
741 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
743 AsyncIO *IO = watcher->data;
745 SetEVState(IO, eIOConnfail);
746 IO->Now = ev_now(event_base);
747 ev_timer_stop (event_base, &IO->conn_fail);
749 if (IO->SendBuf.fd != 0)
751 ev_io_stop(loop, &IO->conn_event);
752 ev_io_stop(event_base, &IO->send_event);
753 ev_io_stop(event_base, &IO->recv_event);
754 ev_timer_stop (event_base, &IO->rw_timeout);
755 close(IO->SendBuf.fd);
756 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
758 become_session(IO->CitContext);
760 assert(IO->ConnFail);
761 switch (IO->ConnFail(IO))
772 IO_connfailimmediate_callback(struct ev_loop *loop,
776 AsyncIO *IO = watcher->data;
778 SetEVState(IO, eIOConnfailNow);
779 IO->Now = ev_now(event_base);
780 ev_idle_stop (event_base, &IO->conn_fail_immediate);
782 if (IO->SendBuf.fd != 0)
784 close(IO->SendBuf.fd);
785 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
787 become_session(IO->CitContext);
789 assert(IO->ConnFail);
790 switch (IO->ConnFail(IO))
801 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
803 AsyncIO *IO = watcher->data;
805 socklen_t lon = sizeof(so_err);
808 SetEVState(IO, eIOConnNow);
809 IO->Now = ev_now(event_base);
810 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
812 ev_io_stop(loop, &IO->conn_event);
813 ev_timer_stop(event_base, &IO->conn_fail);
815 err = getsockopt(IO->SendBuf.fd,
821 if ((err == 0) && (so_err != 0))
823 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
826 IO_connfail_callback(loop, &IO->conn_fail, revents);
831 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
832 set_start_callback(loop, IO, revents);
837 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
841 AsyncIO *IO = watcher->data;
843 IO->Now = ev_now(event_base);
844 switch (IO->NextState) {
846 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
848 StrBufPlain(IO->ErrMsg, errmsg, -1);
851 if (IO->IOB.ChunkSendRemain == 0)
853 IO->NextState = eSendReply;
854 assert(IO->ReadDone);
855 ev_io_stop(event_base, &IO->recv_event);
864 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
876 const char *pch = ChrPtr(IO->RecvBuf.Buf);
877 const char *pchh = IO->RecvBuf.ReadWritePointer;
882 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
883 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
884 ((CitContext*)(IO->CitContext))->ServiceName,
887 fd = fopen(fn, "a+");
888 fprintf(fd, "Read: BufSize: %ld BufContent: [",
890 rv = fwrite(pchh, nbytes, 1, fd);
891 if (!rv) printf("failed to write debug to %s!\n", fn);
898 } else if (nbytes == 0) {
899 StopClientWatchers(IO, 1);
900 SetNextTimeout(IO, 0.01);
902 } else if (nbytes == -1) {
903 if (errno != EAGAIN) {
904 // FD is gone. kick it.
905 StopClientWatchers(IO, 1);
907 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
908 errno, strerror(errno), IO->SendBuf.fd);
909 StrBufPrintf(IO->ErrMsg,
910 "Socket Invalid! [%s]",
912 SetNextTimeout(IO, 0.01);
919 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
921 AsyncIO *IO = watcher->data;
923 SetEVState(IO, eCaresFinished);
924 IO->Now = ev_now(event_base);
925 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
926 become_session(IO->CitContext);
927 assert(IO->DNS.Query->PostDNS);
928 switch (IO->DNS.Query->PostDNS(IO))
931 assert(IO->DNS.Fail);
932 switch (IO->DNS.Fail(IO)) {
934 //// StopClientWatchers(IO);
938 StopClientWatchers(IO, 0);
939 QueueAnDBOperation(IO);
945 StopClientWatchers(IO, 0);
946 QueueAnDBOperation(IO);
954 eNextState EvConnectSock(AsyncIO *IO,
956 double first_rw_timeout,
959 struct sockaddr_in egress_sin;
963 SetEVState(IO, eIOConnectSock);
964 become_session(IO->CitContext);
967 IO->NextState = eReadMessage;
970 IO->NextState = eSendReply;
973 IO->SendBuf.fd = IO->RecvBuf.fd =
975 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
979 if (IO->SendBuf.fd < 0) {
981 "EVENT: socket() failed: %s\n",
984 StrBufPrintf(IO->ErrMsg,
985 "Failed to create socket: %s",
987 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
990 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
993 "EVENT: unable to get socket %d flags! %s \n",
996 StrBufPrintf(IO->ErrMsg,
997 "Failed to get socket %d flags: %s",
1000 close(IO->SendBuf.fd);
1001 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1004 fdflags = fdflags | O_NONBLOCK;
1005 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
1008 "EVENT: unable to set socket %d nonblocking flags! %s \n",
1011 StrBufPrintf(IO->ErrMsg,
1012 "Failed to set socket flags: %s",
1014 close(IO->SendBuf.fd);
1015 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1018 /* TODO: maye we could use offsetof() to calc the position of data...
1019 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1021 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1022 IO->recv_event.data = IO;
1023 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1024 IO->send_event.data = IO;
1026 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1027 IO->conn_fail.data = IO;
1028 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1029 IO->rw_timeout.data = IO;
1034 /* for debugging you may bypass it like this:
1035 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1036 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1037 * inet_addr("127.0.0.1");
1039 if (IO->ConnectMe->IPv6) {
1040 rc = connect(IO->SendBuf.fd,
1041 &IO->ConnectMe->Addr,
1042 sizeof(struct sockaddr_in6));
1045 /* If citserver is bound to a specific IP address on the host, make
1046 * sure we use that address for outbound connections.
1049 memset(&egress_sin, 0, sizeof(egress_sin));
1050 egress_sin.sin_family = AF_INET;
1051 if (!IsEmptyStr(config.c_ip_addr)) {
1052 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1053 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1054 egress_sin.sin_addr.s_addr = INADDR_ANY;
1057 /* If this bind fails, no problem; we can still use INADDR_ANY */
1058 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1060 rc = connect(IO->SendBuf.fd,
1061 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1062 sizeof(struct sockaddr_in));
1066 SetEVState(IO, eIOConnNow);
1067 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1068 set_start_callback(event_base, IO, 0);
1069 return IO->NextState;
1071 else if (errno == EINPROGRESS) {
1072 SetEVState(IO, eIOConnWait);
1073 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1075 ev_io_init(&IO->conn_event,
1076 IO_connestd_callback,
1080 IO->conn_event.data = IO;
1082 ev_io_start(event_base, &IO->conn_event);
1083 ev_timer_start(event_base, &IO->conn_fail);
1084 return IO->NextState;
1087 SetEVState(IO, eIOConnfail);
1088 ev_idle_init(&IO->conn_fail_immediate,
1089 IO_connfailimmediate_callback);
1090 IO->conn_fail_immediate.data = IO;
1091 ev_idle_start(event_base, &IO->conn_fail_immediate);
1094 "connect() = %d failed: %s\n",
1098 StrBufPrintf(IO->ErrMsg,
1099 "Failed to connect: %s",
1101 return IO->NextState;
1103 return IO->NextState;
1106 void SetNextTimeout(AsyncIO *IO, double timeout)
1108 IO->rw_timeout.repeat = timeout;
1109 ev_timer_again (event_base, &IO->rw_timeout);
1113 eNextState ReAttachIO(AsyncIO *IO,
1117 SetEVState(IO, eIOAttach);
1119 become_session(IO->CitContext);
1120 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1122 IO->NextState = eReadMessage;
1125 IO->NextState = eSendReply;
1127 set_start_callback(event_base, IO, 0);
1129 return IO->NextState;
1132 void InitIOStruct(AsyncIO *IO,
1134 eNextState NextState,
1135 IO_LineReaderCallback LineReader,
1136 IO_CallBack DNS_Fail,
1137 IO_CallBack SendDone,
1138 IO_CallBack ReadDone,
1139 IO_CallBack Terminate,
1140 IO_CallBack DBTerminate,
1141 IO_CallBack ConnFail,
1142 IO_CallBack Timeout,
1143 IO_CallBack ShutdownAbort)
1147 IO->CitContext = CloneContext(CC);
1148 IO->CitContext->session_specific_data = Data;
1149 IO->CitContext->IO = IO;
1151 IO->NextState = NextState;
1153 IO->SendDone = SendDone;
1154 IO->ReadDone = ReadDone;
1155 IO->Terminate = Terminate;
1156 IO->DBTerminate = DBTerminate;
1157 IO->LineReader = LineReader;
1158 IO->ConnFail = ConnFail;
1159 IO->Timeout = Timeout;
1160 IO->ShutdownAbort = ShutdownAbort;
1162 IO->DNS.Fail = DNS_Fail;
1164 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1165 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1166 IO->IOBuf = NewStrBuf();
1167 EV_syslog(LOG_DEBUG,
1168 "EVENT: Session lives at %p IO at %p \n",
1173 extern int evcurl_init(AsyncIO *IO);
1175 int InitcURLIOStruct(AsyncIO *IO,
1178 IO_CallBack SendDone,
1179 IO_CallBack Terminate,
1180 IO_CallBack DBTerminate,
1181 IO_CallBack ShutdownAbort)
1185 IO->CitContext = CloneContext(CC);
1186 IO->CitContext->session_specific_data = Data;
1187 IO->CitContext->IO = IO;
1189 IO->SendDone = SendDone;
1190 IO->Terminate = Terminate;
1191 IO->DBTerminate = DBTerminate;
1192 IO->ShutdownAbort = ShutdownAbort;
1194 strcpy(IO->HttpReq.errdesc, Desc);
1197 return evcurl_init(IO);
1202 typedef struct KillOtherSessionContext {
1205 }KillOtherSessionContext;
1207 eNextState KillTerminate(AsyncIO *IO)
1210 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1211 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1213 FreeAsyncIOContents(IO);
1214 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1215 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1221 eNextState KillShutdown(AsyncIO *IO)
1223 return eTerminateConnection;
1226 eNextState KillOtherContextNow(AsyncIO *IO)
1228 KillOtherSessionContext *Ctx = IO->Data;
1230 SetEVState(IO, eKill);
1232 if (Ctx->OtherOne->ShutdownAbort != NULL) {
1233 Ctx->OtherOne->NextState = eAbort;
1234 if (Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne) == eDBQuery) {
1235 StopClientWatchers(Ctx->OtherOne, 0);
1236 QueueAnDBOperation(Ctx->OtherOne);
1239 return eTerminateConnection;
1242 void KillAsyncIOContext(AsyncIO *IO)
1244 KillOtherSessionContext *Ctx;
1246 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1247 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1249 InitIOStruct(&Ctx->IO,
1264 switch(IO->NextState) {
1277 Ctx->IO.ReAttachCB = KillOtherContextNow;
1278 QueueAnEventContext(&Ctx->IO);
1281 Ctx->IO.ReAttachCB = KillOtherContextNow;
1282 QueueAnDBOperation(&Ctx->IO);
1284 case eTerminateConnection:
1286 /*hm, its already dying, dunno which Queue its in... */
1292 extern int DebugEventLoopBacktrace;
1293 void EV_backtrace(AsyncIO *IO)
1295 #ifdef HAVE_BACKTRACE
1296 void *stack_frames[50];
1300 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1302 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1303 strings = backtrace_symbols(stack_frames, size);
1304 for (i = 0; i < size; i++) {
1305 if (strings != NULL) {
1306 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1309 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1317 ev_tstamp ctdl_ev_now (void)
1319 return ev_now(event_base);