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"
29 #include "citserver.h"
31 ConstStr IOStates[] = {
38 {HKEY("DB Terminate")},
41 {HKEY("IO Connect Socket")},
44 {HKEY("IO ConnFail")},
45 {HKEY("IO ConnFail Now")},
46 {HKEY("IO Conn Now")},
47 {HKEY("IO Conn Wait")},
50 {HKEY("Curl Shotdown")},
51 {HKEY("Curl More IO")},
52 {HKEY("Curl Got IO")},
53 {HKEY("Curl Got Data")},
54 {HKEY("Curl Got Status")},
55 {HKEY("C-Ares Start")},
56 {HKEY("C-Ares IO Done")},
57 {HKEY("C-Ares Finished")},
58 {HKEY("C-Ares exit")},
63 void SetEVState(AsyncIO *IO, eIOState State)
66 CitContext* CCC = IO->CitContext;
68 memcpy(CCC->lastcmdname, IOStates[State].Key, IOStates[State].len + 1);
72 eNextState QueueAnEventContext(AsyncIO *IO);
73 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
74 static void IO_abort_shutdown_callback(struct ev_loop *loop,
79 /*------------------------------------------------------------------------------
81 *----------------------------------------------------------------------------*/
82 extern int evdb_count;
83 extern pthread_mutex_t DBEventQueueMutex;
84 extern pthread_mutex_t DBEventExitQueueMutex;
85 extern HashList *DBInboundEventQueue;
86 extern struct ev_loop *event_db;
87 extern ev_async DBAddJob;
88 extern ev_async DBExitEventLoop;
90 eNextState QueueAnDBOperation(AsyncIO *IO)
96 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
99 assert(IO->ReAttachCB != NULL);
101 h->EvAttch = IO->ReAttachCB;
102 ev_cleanup_init(&IO->db_abort_by_shutdown,
103 IO_abort_shutdown_callback);
104 IO->db_abort_by_shutdown.data = IO;
106 pthread_mutex_lock(&DBEventQueueMutex);
107 if (DBInboundEventQueue == NULL)
109 /* shutting down... */
111 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
112 pthread_mutex_unlock(&DBEventQueueMutex);
115 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
117 Put(DBInboundEventQueue, IKEY(i), h, NULL);
118 pthread_mutex_unlock(&DBEventQueueMutex);
120 pthread_mutex_lock(&DBEventExitQueueMutex);
121 if (event_db == NULL)
123 pthread_mutex_unlock(&DBEventExitQueueMutex);
126 ev_async_send (event_db, &DBAddJob);
127 pthread_mutex_unlock(&DBEventExitQueueMutex);
129 EVQM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
133 void StopDBWatchers(AsyncIO *IO)
135 SetEVState(IO, eDBStop);
136 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
137 ev_idle_stop(event_db, &IO->db_unwind_stack);
140 void ShutDownDBCLient(AsyncIO *IO)
142 CitContext *Ctx =IO->CitContext;
145 SetEVState(IO, eDBTerm);
146 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
149 assert(IO->DBTerminate);
154 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
156 AsyncIO *IO = watcher->data;
158 SetEVState(IO, eDBNext);
159 IO->Now = ev_now(event_db);
160 EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
161 become_session(IO->CitContext);
163 ev_idle_stop(event_db, &IO->db_unwind_stack);
165 assert(IO->NextDBOperation);
166 switch (IO->NextDBOperation(IO))
169 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
170 QueueAnEventContext(IO);
183 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
185 case eTerminateConnection:
187 ev_idle_stop(event_db, &IO->db_unwind_stack);
188 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
189 ShutDownDBCLient(IO);
193 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
195 SetEVState(IO, eQDBNext);
196 IO->NextDBOperation = CB;
197 ev_idle_init(&IO->db_unwind_stack,
199 IO->db_unwind_stack.data = IO;
200 ev_idle_start(event_db, &IO->db_unwind_stack);
204 /*------------------------------------------------------------------------------
206 *----------------------------------------------------------------------------*/
207 extern int evbase_count;
208 extern pthread_mutex_t EventQueueMutex;
209 extern pthread_mutex_t EventExitQueueMutex;
210 extern HashList *InboundEventQueue;
211 extern struct ev_loop *event_base;
212 extern ev_async AddJob;
213 extern ev_async ExitEventLoop;
215 static void IO_abort_shutdown_callback(struct ev_loop *loop,
219 AsyncIO *IO = watcher->data;
221 SetEVState(IO, eIOAbort);
222 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
223 IO->Now = ev_now(event_base);
224 assert(IO->ShutdownAbort);
225 IO->ShutdownAbort(IO);
229 eNextState QueueAnEventContext(AsyncIO *IO)
234 SetEVState(IO, eIOQ);
235 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
238 assert(IO->ReAttachCB != NULL);
240 h->EvAttch = IO->ReAttachCB;
242 ev_cleanup_init(&IO->abort_by_shutdown,
243 IO_abort_shutdown_callback);
244 IO->abort_by_shutdown.data = IO;
246 pthread_mutex_lock(&EventQueueMutex);
247 if (InboundEventQueue == NULL)
250 /* shutting down... */
251 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
252 pthread_mutex_unlock(&EventQueueMutex);
255 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
257 Put(InboundEventQueue, IKEY(i), h, NULL);
258 pthread_mutex_unlock(&EventQueueMutex);
260 pthread_mutex_lock(&EventExitQueueMutex);
261 if (event_base == NULL) {
262 pthread_mutex_unlock(&EventExitQueueMutex);
265 ev_async_send (event_base, &AddJob);
266 pthread_mutex_unlock(&EventExitQueueMutex);
267 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
271 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB, int CloseFDs)
273 StopClientWatchers(IO, CloseFDs);
277 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
284 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
287 return QueueAnEventContext(IO);
290 extern eNextState evcurl_handle_start(AsyncIO *IO);
292 eNextState QueueCurlContext(AsyncIO *IO)
297 SetEVState(IO, eCurlQ);
298 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
300 h->EvAttch = evcurl_handle_start;
302 pthread_mutex_lock(&EventQueueMutex);
303 if (InboundEventQueue == NULL)
305 /* shutting down... */
307 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
308 pthread_mutex_unlock(&EventQueueMutex);
312 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
314 Put(InboundEventQueue, IKEY(i), h, NULL);
315 pthread_mutex_unlock(&EventQueueMutex);
317 pthread_mutex_lock(&EventExitQueueMutex);
318 if (event_base == NULL) {
319 pthread_mutex_unlock(&EventExitQueueMutex);
322 ev_async_send (event_base, &AddJob);
323 pthread_mutex_unlock(&EventExitQueueMutex);
325 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
329 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
331 StopCurlWatchers(IO);
337 void FreeAsyncIOContents(AsyncIO *IO)
339 CitContext *Ctx = IO->CitContext;
341 FreeStrBuf(&IO->IOBuf);
342 FreeStrBuf(&IO->SendBuf.Buf);
343 FreeStrBuf(&IO->RecvBuf.Buf);
345 FreeURL(&IO->ConnectMe);
346 FreeStrBuf(&IO->HttpReq.ReplyData);
349 Ctx->state = CON_IDLE;
351 IO->CitContext = NULL;
356 void DestructCAres(AsyncIO *IO);
357 void StopClientWatchers(AsyncIO *IO, int CloseFD)
359 EVM_syslog(LOG_DEBUG, "EVENT StopClientWatchers");
363 ev_timer_stop (event_base, &IO->rw_timeout);
364 ev_timer_stop(event_base, &IO->conn_fail);
365 ev_idle_stop(event_base, &IO->unwind_stack);
366 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
368 ev_io_stop(event_base, &IO->conn_event);
369 ev_io_stop(event_base, &IO->send_event);
370 ev_io_stop(event_base, &IO->recv_event);
372 if (CloseFD && (IO->SendBuf.fd > 0)) {
373 close(IO->SendBuf.fd);
379 void StopCurlWatchers(AsyncIO *IO)
381 EVM_syslog(LOG_DEBUG, "EVENT StopCurlWatchers \n");
383 ev_timer_stop (event_base, &IO->rw_timeout);
384 ev_timer_stop(event_base, &IO->conn_fail);
385 ev_idle_stop(event_base, &IO->unwind_stack);
386 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
388 ev_io_stop(event_base, &IO->conn_event);
389 ev_io_stop(event_base, &IO->send_event);
390 ev_io_stop(event_base, &IO->recv_event);
392 curl_easy_cleanup(IO->HttpReq.chnd);
393 IO->HttpReq.chnd = NULL;
395 if (IO->SendBuf.fd != 0) {
396 close(IO->SendBuf.fd);
402 eNextState ShutDownCLient(AsyncIO *IO)
404 CitContext *Ctx =IO->CitContext;
406 SetEVState(IO, eExit);
409 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
411 StopClientWatchers(IO, 1);
413 if (IO->DNS.Channel != NULL) {
414 ares_destroy(IO->DNS.Channel);
415 EV_DNS_LOG_STOP(DNS.recv_event);
416 EV_DNS_LOG_STOP(DNS.send_event);
417 ev_io_stop(event_base, &IO->DNS.recv_event);
418 ev_io_stop(event_base, &IO->DNS.send_event);
419 IO->DNS.Channel = NULL;
421 assert(IO->Terminate);
422 return IO->Terminate(IO);
425 void PostInbound(AsyncIO *IO)
428 switch (IO->NextState) {
430 ev_io_start(event_base, &IO->send_event);
434 assert(IO->SendDone);
435 IO->NextState = IO->SendDone(IO);
436 switch (IO->NextState)
445 ev_io_start(event_base, &IO->send_event);
448 StopClientWatchers(IO, 0);
449 QueueAnDBOperation(IO);
457 ev_io_start(event_base, &IO->recv_event);
459 case eTerminateConnection:
461 if (ShutDownCLient(IO) == eDBQuery) {
462 QueueAnDBOperation(IO);
471 QueueAnDBOperation(IO);
474 eReadState HandleInbound(AsyncIO *IO)
476 const char *Err = NULL;
477 eReadState Finished = eBufferNotEmpty;
479 become_session(IO->CitContext);
481 while ((Finished == eBufferNotEmpty) &&
482 ((IO->NextState == eReadMessage)||
483 (IO->NextState == eReadMore)||
484 (IO->NextState == eReadFile)||
485 (IO->NextState == eReadPayload)))
488 * lex line reply in callback,
489 * or do it ourselves.
490 * i.e. as nnn-blabla means continue reading in SMTP
492 if ((IO->NextState == eReadFile) &&
493 (Finished == eBufferNotEmpty))
495 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
496 if (Finished == eReadSuccess)
498 IO->NextState = eSendReply;
501 else if (IO->LineReader)
502 Finished = IO->LineReader(IO);
504 Finished = StrBufChunkSipLine(IO->IOBuf,
508 case eMustReadMore: /// read new from socket...
510 case eBufferNotEmpty: /* shouldn't happen... */
511 case eReadSuccess: /// done for now...
513 case eReadFail: /// WHUT?
518 if (Finished != eMustReadMore) {
519 ev_io_stop(event_base, &IO->recv_event);
520 IO->NextState = IO->ReadDone(IO);
521 if (IO->NextState == eDBQuery) {
522 if (QueueAnDBOperation(IO) == eAbort)
528 Finished = StrBufCheckBuffer(&IO->RecvBuf);
540 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
543 AsyncIO *IO = watcher->data;
544 const char *errmsg = NULL;
546 IO->Now = ev_now(event_base);
547 become_session(IO->CitContext);
553 const char *pch = ChrPtr(IO->SendBuf.Buf);
554 const char *pchh = IO->SendBuf.ReadWritePointer;
560 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
561 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
562 ((CitContext*)(IO->CitContext))->ServiceName,
565 fd = fopen(fn, "a+");
567 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
571 fprintf(fd, "Send: BufSize: %ld BufContent: [",
573 rv = fwrite(pchh, nbytes, 1, fd);
574 if (!rv) printf("failed to write debug to %s!\n", fn);
577 switch (IO->NextState) {
579 rc = FileSendChunked(&IO->IOB, &errmsg);
581 StrBufPlain(IO->ErrMsg, errmsg, -1);
584 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
590 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
596 ev_io_stop(event_base, &IO->send_event);
597 switch (IO->NextState) {
599 assert(IO->SendDone);
600 IO->NextState = IO->SendDone(IO);
602 if ((IO->NextState == eTerminateConnection) ||
603 (IO->NextState == eAbort) )
606 ev_io_start(event_base, &IO->send_event);
610 if (IO->IOB.ChunkSendRemain > 0) {
611 ev_io_start(event_base, &IO->recv_event);
612 SetNextTimeout(IO, 100.0);
615 assert(IO->ReadDone);
616 IO->NextState = IO->ReadDone(IO);
617 switch(IO->NextState) {
626 ev_io_start(event_base,
634 case eTerminateConnection:
641 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
643 IO->NextState = eReadMore;
648 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
653 ev_io_start(event_base, &IO->recv_event);
659 * we now live in another queue,
660 * so we have to unregister.
662 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
667 case eTerminateConnection:
673 if (errno != EAGAIN) {
674 StopClientWatchers(IO, 1);
676 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
677 errno, strerror(errno), IO->SendBuf.fd);
678 StrBufPrintf(IO->ErrMsg,
679 "Socket Invalid! [%s]",
681 SetNextTimeout(IO, 0.01);
684 /* else : must write more. */
687 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
689 ev_timer_stop(event_base, &IO->conn_fail);
690 ev_timer_start(event_base, &IO->rw_timeout);
692 switch(IO->NextState) {
696 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
697 ev_io_start(event_base, &IO->recv_event);
703 become_session(IO->CitContext);
704 IO_send_callback(loop, &IO->send_event, revents);
710 case eTerminateConnection:
718 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
720 AsyncIO *IO = watcher->data;
722 SetEVState(IO, eIOTimeout);
723 IO->Now = ev_now(event_base);
724 ev_timer_stop (event_base, &IO->rw_timeout);
725 become_session(IO->CitContext);
727 if (IO->SendBuf.fd != 0)
729 ev_io_stop(event_base, &IO->send_event);
730 ev_io_stop(event_base, &IO->recv_event);
731 ev_timer_stop (event_base, &IO->rw_timeout);
732 close(IO->SendBuf.fd);
733 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
737 switch (IO->Timeout(IO))
747 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
749 AsyncIO *IO = watcher->data;
751 SetEVState(IO, eIOConnfail);
752 IO->Now = ev_now(event_base);
753 ev_timer_stop (event_base, &IO->conn_fail);
755 if (IO->SendBuf.fd != 0)
757 ev_io_stop(loop, &IO->conn_event);
758 ev_io_stop(event_base, &IO->send_event);
759 ev_io_stop(event_base, &IO->recv_event);
760 ev_timer_stop (event_base, &IO->rw_timeout);
761 close(IO->SendBuf.fd);
762 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
764 become_session(IO->CitContext);
766 assert(IO->ConnFail);
767 switch (IO->ConnFail(IO))
778 IO_connfailimmediate_callback(struct ev_loop *loop,
782 AsyncIO *IO = watcher->data;
784 SetEVState(IO, eIOConnfailNow);
785 IO->Now = ev_now(event_base);
786 ev_idle_stop (event_base, &IO->conn_fail_immediate);
788 if (IO->SendBuf.fd != 0)
790 close(IO->SendBuf.fd);
791 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
793 become_session(IO->CitContext);
795 assert(IO->ConnFail);
796 switch (IO->ConnFail(IO))
807 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
809 AsyncIO *IO = watcher->data;
811 socklen_t lon = sizeof(so_err);
814 SetEVState(IO, eIOConnNow);
815 IO->Now = ev_now(event_base);
816 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
818 ev_io_stop(loop, &IO->conn_event);
819 ev_timer_stop(event_base, &IO->conn_fail);
821 err = getsockopt(IO->SendBuf.fd,
827 if ((err == 0) && (so_err != 0))
829 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
832 IO_connfail_callback(loop, &IO->conn_fail, revents);
837 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
838 set_start_callback(loop, IO, revents);
843 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
847 AsyncIO *IO = watcher->data;
849 IO->Now = ev_now(event_base);
850 switch (IO->NextState) {
852 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
854 StrBufPlain(IO->ErrMsg, errmsg, -1);
857 if (IO->IOB.ChunkSendRemain == 0)
859 IO->NextState = eSendReply;
860 assert(IO->ReadDone);
861 ev_io_stop(event_base, &IO->recv_event);
870 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
882 const char *pch = ChrPtr(IO->RecvBuf.Buf);
883 const char *pchh = IO->RecvBuf.ReadWritePointer;
888 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
889 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
890 ((CitContext*)(IO->CitContext))->ServiceName,
893 fd = fopen(fn, "a+");
895 syslog(LOG_EMERG, "failed to open file %s: %s", fn, strerror(errno));
899 fprintf(fd, "Read: BufSize: %ld BufContent: [",
901 rv = fwrite(pchh, nbytes, 1, fd);
902 if (!rv) printf("failed to write debug to %s!\n", fn);
909 } else if (nbytes == 0) {
910 StopClientWatchers(IO, 1);
911 SetNextTimeout(IO, 0.01);
913 } else if (nbytes == -1) {
914 if (errno != EAGAIN) {
915 // FD is gone. kick it.
916 StopClientWatchers(IO, 1);
918 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
919 errno, strerror(errno), IO->SendBuf.fd);
920 StrBufPrintf(IO->ErrMsg,
921 "Socket Invalid! [%s]",
923 SetNextTimeout(IO, 0.01);
930 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
932 AsyncIO *IO = watcher->data;
934 SetEVState(IO, eCaresFinished);
935 IO->Now = ev_now(event_base);
936 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
937 become_session(IO->CitContext);
938 assert(IO->DNS.Query->PostDNS);
939 switch (IO->DNS.Query->PostDNS(IO))
942 assert(IO->DNS.Fail);
943 switch (IO->DNS.Fail(IO)) {
945 //// StopClientWatchers(IO);
949 StopClientWatchers(IO, 0);
950 QueueAnDBOperation(IO);
956 StopClientWatchers(IO, 0);
957 QueueAnDBOperation(IO);
965 eNextState EvConnectSock(AsyncIO *IO,
967 double first_rw_timeout,
970 struct sockaddr_in egress_sin;
974 SetEVState(IO, eIOConnectSock);
975 become_session(IO->CitContext);
978 IO->NextState = eReadMessage;
981 IO->NextState = eSendReply;
984 IO->SendBuf.fd = IO->RecvBuf.fd =
986 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
990 if (IO->SendBuf.fd < 0) {
992 "EVENT: socket() failed: %s\n",
995 StrBufPrintf(IO->ErrMsg,
996 "Failed to create socket: %s",
998 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1001 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
1004 "EVENT: unable to get socket %d flags! %s \n",
1007 StrBufPrintf(IO->ErrMsg,
1008 "Failed to get socket %d flags: %s",
1011 close(IO->SendBuf.fd);
1012 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1015 fdflags = fdflags | O_NONBLOCK;
1016 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
1019 "EVENT: unable to set socket %d nonblocking flags! %s \n",
1022 StrBufPrintf(IO->ErrMsg,
1023 "Failed to set socket flags: %s",
1025 close(IO->SendBuf.fd);
1026 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1029 /* TODO: maye we could use offsetof() to calc the position of data...
1030 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1032 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1033 IO->recv_event.data = IO;
1034 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1035 IO->send_event.data = IO;
1037 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1038 IO->conn_fail.data = IO;
1039 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1040 IO->rw_timeout.data = IO;
1045 /* for debugging you may bypass it like this:
1046 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1047 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1048 * inet_addr("127.0.0.1");
1050 if (IO->ConnectMe->IPv6) {
1051 rc = connect(IO->SendBuf.fd,
1052 &IO->ConnectMe->Addr,
1053 sizeof(struct sockaddr_in6));
1056 /* If citserver is bound to a specific IP address on the host, make
1057 * sure we use that address for outbound connections.
1060 memset(&egress_sin, 0, sizeof(egress_sin));
1061 egress_sin.sin_family = AF_INET;
1062 if (!IsEmptyStr(config.c_ip_addr)) {
1063 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1064 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1065 egress_sin.sin_addr.s_addr = INADDR_ANY;
1068 /* If this bind fails, no problem; we can still use INADDR_ANY */
1069 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1071 rc = connect(IO->SendBuf.fd,
1072 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1073 sizeof(struct sockaddr_in));
1077 SetEVState(IO, eIOConnNow);
1078 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1079 set_start_callback(event_base, IO, 0);
1080 return IO->NextState;
1082 else if (errno == EINPROGRESS) {
1083 SetEVState(IO, eIOConnWait);
1084 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1086 ev_io_init(&IO->conn_event,
1087 IO_connestd_callback,
1091 IO->conn_event.data = IO;
1093 ev_io_start(event_base, &IO->conn_event);
1094 ev_timer_start(event_base, &IO->conn_fail);
1095 return IO->NextState;
1098 SetEVState(IO, eIOConnfail);
1099 ev_idle_init(&IO->conn_fail_immediate,
1100 IO_connfailimmediate_callback);
1101 IO->conn_fail_immediate.data = IO;
1102 ev_idle_start(event_base, &IO->conn_fail_immediate);
1105 "connect() = %d failed: %s\n",
1109 StrBufPrintf(IO->ErrMsg,
1110 "Failed to connect: %s",
1112 return IO->NextState;
1114 return IO->NextState;
1117 void SetNextTimeout(AsyncIO *IO, double timeout)
1119 IO->rw_timeout.repeat = timeout;
1120 ev_timer_again (event_base, &IO->rw_timeout);
1124 eNextState ReAttachIO(AsyncIO *IO,
1128 SetEVState(IO, eIOAttach);
1130 become_session(IO->CitContext);
1131 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1133 IO->NextState = eReadMessage;
1136 IO->NextState = eSendReply;
1138 set_start_callback(event_base, IO, 0);
1140 return IO->NextState;
1143 void InitIOStruct(AsyncIO *IO,
1145 eNextState NextState,
1146 IO_LineReaderCallback LineReader,
1147 IO_CallBack DNS_Fail,
1148 IO_CallBack SendDone,
1149 IO_CallBack ReadDone,
1150 IO_CallBack Terminate,
1151 IO_CallBack DBTerminate,
1152 IO_CallBack ConnFail,
1153 IO_CallBack Timeout,
1154 IO_CallBack ShutdownAbort)
1158 IO->CitContext = CloneContext(CC);
1159 IO->CitContext->session_specific_data = Data;
1160 IO->CitContext->IO = IO;
1162 IO->NextState = NextState;
1164 IO->SendDone = SendDone;
1165 IO->ReadDone = ReadDone;
1166 IO->Terminate = Terminate;
1167 IO->DBTerminate = DBTerminate;
1168 IO->LineReader = LineReader;
1169 IO->ConnFail = ConnFail;
1170 IO->Timeout = Timeout;
1171 IO->ShutdownAbort = ShutdownAbort;
1173 IO->DNS.Fail = DNS_Fail;
1175 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1176 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1177 IO->IOBuf = NewStrBuf();
1178 EV_syslog(LOG_DEBUG,
1179 "EVENT: Session lives at %p IO at %p \n",
1184 extern int evcurl_init(AsyncIO *IO);
1186 int InitcURLIOStruct(AsyncIO *IO,
1189 IO_CallBack SendDone,
1190 IO_CallBack Terminate,
1191 IO_CallBack DBTerminate,
1192 IO_CallBack ShutdownAbort)
1196 IO->CitContext = CloneContext(CC);
1197 IO->CitContext->session_specific_data = Data;
1198 IO->CitContext->IO = IO;
1200 IO->SendDone = SendDone;
1201 IO->Terminate = Terminate;
1202 IO->DBTerminate = DBTerminate;
1203 IO->ShutdownAbort = ShutdownAbort;
1205 strcpy(IO->HttpReq.errdesc, Desc);
1208 return evcurl_init(IO);
1213 typedef struct KillOtherSessionContext {
1216 }KillOtherSessionContext;
1218 eNextState KillTerminate(AsyncIO *IO)
1221 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1222 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1224 FreeAsyncIOContents(IO);
1225 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1226 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1232 eNextState KillShutdown(AsyncIO *IO)
1234 return eTerminateConnection;
1237 eNextState KillOtherContextNow(AsyncIO *IO)
1239 KillOtherSessionContext *Ctx = IO->Data;
1241 SetEVState(IO, eKill);
1243 if (Ctx->OtherOne->ShutdownAbort != NULL) {
1244 Ctx->OtherOne->NextState = eAbort;
1245 if (Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne) == eDBQuery) {
1246 StopClientWatchers(Ctx->OtherOne, 0);
1247 QueueAnDBOperation(Ctx->OtherOne);
1250 return eTerminateConnection;
1253 void KillAsyncIOContext(AsyncIO *IO)
1255 KillOtherSessionContext *Ctx;
1257 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1258 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1260 InitIOStruct(&Ctx->IO,
1275 switch(IO->NextState) {
1288 Ctx->IO.ReAttachCB = KillOtherContextNow;
1289 QueueAnEventContext(&Ctx->IO);
1292 Ctx->IO.ReAttachCB = KillOtherContextNow;
1293 QueueAnDBOperation(&Ctx->IO);
1295 case eTerminateConnection:
1297 /*hm, its already dying, dunno which Queue its in... */
1303 extern int DebugEventLoopBacktrace;
1304 void EV_backtrace(AsyncIO *IO)
1306 #ifdef HAVE_BACKTRACE
1307 void *stack_frames[50];
1311 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1313 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1314 strings = backtrace_symbols(stack_frames, size);
1315 for (i = 0; i < size; i++) {
1316 if (strings != NULL) {
1317 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1320 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1328 ev_tstamp ctdl_ev_now (void)
1330 return ev_now(event_base);