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 void 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);
424 void PostInbound(AsyncIO *IO)
426 switch (IO->NextState) {
428 ev_io_start(event_base, &IO->send_event);
432 assert(IO->SendDone);
433 IO->NextState = IO->SendDone(IO);
434 switch (IO->NextState)
443 ev_io_start(event_base, &IO->send_event);
446 StopClientWatchers(IO, 0);
454 ev_io_start(event_base, &IO->recv_event);
456 case eTerminateConnection:
470 eReadState HandleInbound(AsyncIO *IO)
472 const char *Err = NULL;
473 eReadState Finished = eBufferNotEmpty;
475 become_session(IO->CitContext);
477 while ((Finished == eBufferNotEmpty) &&
478 ((IO->NextState == eReadMessage)||
479 (IO->NextState == eReadMore)||
480 (IO->NextState == eReadFile)||
481 (IO->NextState == eReadPayload)))
484 * lex line reply in callback,
485 * or do it ourselves.
486 * i.e. as nnn-blabla means continue reading in SMTP
488 if ((IO->NextState == eReadFile) &&
489 (Finished == eBufferNotEmpty))
491 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
492 if (Finished == eReadSuccess)
494 IO->NextState = eSendReply;
497 else if (IO->LineReader)
498 Finished = IO->LineReader(IO);
500 Finished = StrBufChunkSipLine(IO->IOBuf,
504 case eMustReadMore: /// read new from socket...
506 case eBufferNotEmpty: /* shouldn't happen... */
507 case eReadSuccess: /// done for now...
509 case eReadFail: /// WHUT?
514 if (Finished != eMustReadMore) {
516 assert(IO->ReadDone);
517 ev_io_stop(event_base, &IO->recv_event);
518 rc = IO->ReadDone(IO);
519 if (rc == eDBQuery) {
520 return QueueAnDBOperation(IO);
524 Finished = StrBufCheckBuffer(&IO->RecvBuf);
536 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
539 AsyncIO *IO = watcher->data;
540 const char *errmsg = NULL;
542 IO->Now = ev_now(event_base);
543 become_session(IO->CitContext);
549 const char *pch = ChrPtr(IO->SendBuf.Buf);
550 const char *pchh = IO->SendBuf.ReadWritePointer;
556 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
557 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
558 ((CitContext*)(IO->CitContext))->ServiceName,
561 fd = fopen(fn, "a+");
562 fprintf(fd, "Send: BufSize: %ld BufContent: [",
564 rv = fwrite(pchh, nbytes, 1, fd);
565 if (!rv) printf("failed to write debug to %s!\n", fn);
568 switch (IO->NextState) {
570 rc = FileSendChunked(&IO->IOB, &errmsg);
572 StrBufPlain(IO->ErrMsg, errmsg, -1);
575 rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
581 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
587 ev_io_stop(event_base, &IO->send_event);
588 switch (IO->NextState) {
590 assert(IO->SendDone);
591 IO->NextState = IO->SendDone(IO);
593 if ((IO->NextState == eTerminateConnection) ||
594 (IO->NextState == eAbort) )
597 ev_io_start(event_base, &IO->send_event);
601 if (IO->IOB.ChunkSendRemain > 0) {
602 ev_io_start(event_base, &IO->recv_event);
603 SetNextTimeout(IO, 100.0);
606 assert(IO->ReadDone);
607 IO->NextState = IO->ReadDone(IO);
608 switch(IO->NextState) {
617 ev_io_start(event_base,
625 case eTerminateConnection:
632 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
634 IO->NextState = eReadMore;
639 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
644 ev_io_start(event_base, &IO->recv_event);
650 * we now live in another queue,
651 * so we have to unregister.
653 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
658 case eTerminateConnection:
664 if (errno != EAGAIN) {
665 StopClientWatchers(IO, 1);
667 "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
668 errno, strerror(errno), IO->SendBuf.fd);
669 StrBufPrintf(IO->ErrMsg,
670 "Socket Invalid! [%s]",
672 SetNextTimeout(IO, 0.01);
675 /* else : must write more. */
678 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
680 ev_timer_stop(event_base, &IO->conn_fail);
681 ev_timer_start(event_base, &IO->rw_timeout);
683 switch(IO->NextState) {
687 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
688 ev_io_start(event_base, &IO->recv_event);
694 become_session(IO->CitContext);
695 IO_send_callback(loop, &IO->send_event, revents);
701 case eTerminateConnection:
709 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
711 AsyncIO *IO = watcher->data;
713 SetEVState(IO, eIOTimeout);
714 IO->Now = ev_now(event_base);
715 ev_timer_stop (event_base, &IO->rw_timeout);
716 become_session(IO->CitContext);
718 if (IO->SendBuf.fd != 0)
720 ev_io_stop(event_base, &IO->send_event);
721 ev_io_stop(event_base, &IO->recv_event);
722 ev_timer_stop (event_base, &IO->rw_timeout);
723 close(IO->SendBuf.fd);
724 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
728 switch (IO->Timeout(IO))
738 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
740 AsyncIO *IO = watcher->data;
742 SetEVState(IO, eIOConnfail);
743 IO->Now = ev_now(event_base);
744 ev_timer_stop (event_base, &IO->conn_fail);
746 if (IO->SendBuf.fd != 0)
748 ev_io_stop(loop, &IO->conn_event);
749 ev_io_stop(event_base, &IO->send_event);
750 ev_io_stop(event_base, &IO->recv_event);
751 ev_timer_stop (event_base, &IO->rw_timeout);
752 close(IO->SendBuf.fd);
753 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
755 become_session(IO->CitContext);
757 assert(IO->ConnFail);
758 switch (IO->ConnFail(IO))
769 IO_connfailimmediate_callback(struct ev_loop *loop,
773 AsyncIO *IO = watcher->data;
775 SetEVState(IO, eIOConnfailNow);
776 IO->Now = ev_now(event_base);
777 ev_idle_stop (event_base, &IO->conn_fail_immediate);
779 if (IO->SendBuf.fd != 0)
781 close(IO->SendBuf.fd);
782 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
784 become_session(IO->CitContext);
786 assert(IO->ConnFail);
787 switch (IO->ConnFail(IO))
798 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
800 AsyncIO *IO = watcher->data;
802 socklen_t lon = sizeof(so_err);
805 SetEVState(IO, eIOConnNow);
806 IO->Now = ev_now(event_base);
807 EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
809 ev_io_stop(loop, &IO->conn_event);
810 ev_timer_stop(event_base, &IO->conn_fail);
812 err = getsockopt(IO->SendBuf.fd,
818 if ((err == 0) && (so_err != 0))
820 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
823 IO_connfail_callback(loop, &IO->conn_fail, revents);
828 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
829 set_start_callback(loop, IO, revents);
834 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
838 AsyncIO *IO = watcher->data;
840 IO->Now = ev_now(event_base);
841 switch (IO->NextState) {
843 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
845 StrBufPlain(IO->ErrMsg, errmsg, -1);
848 if (IO->IOB.ChunkSendRemain == 0)
850 IO->NextState = eSendReply;
851 assert(IO->ReadDone);
852 ev_io_stop(event_base, &IO->recv_event);
861 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
873 const char *pch = ChrPtr(IO->RecvBuf.Buf);
874 const char *pchh = IO->RecvBuf.ReadWritePointer;
879 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
880 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
881 ((CitContext*)(IO->CitContext))->ServiceName,
884 fd = fopen(fn, "a+");
885 fprintf(fd, "Read: BufSize: %ld BufContent: [",
887 rv = fwrite(pchh, nbytes, 1, fd);
888 if (!rv) printf("failed to write debug to %s!\n", fn);
895 } else if (nbytes == 0) {
896 StopClientWatchers(IO, 1);
897 SetNextTimeout(IO, 0.01);
899 } else if (nbytes == -1) {
900 if (errno != EAGAIN) {
901 // FD is gone. kick it.
902 StopClientWatchers(IO, 1);
904 "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
905 errno, strerror(errno), IO->SendBuf.fd);
906 StrBufPrintf(IO->ErrMsg,
907 "Socket Invalid! [%s]",
909 SetNextTimeout(IO, 0.01);
916 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
918 AsyncIO *IO = watcher->data;
920 SetEVState(IO, eCaresFinished);
921 IO->Now = ev_now(event_base);
922 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
923 become_session(IO->CitContext);
924 assert(IO->DNS.Query->PostDNS);
925 switch (IO->DNS.Query->PostDNS(IO))
928 assert(IO->DNS.Fail);
929 switch (IO->DNS.Fail(IO)) {
931 //// StopClientWatchers(IO);
942 eNextState EvConnectSock(AsyncIO *IO,
944 double first_rw_timeout,
947 struct sockaddr_in egress_sin;
951 SetEVState(IO, eIOConnectSock);
952 become_session(IO->CitContext);
955 IO->NextState = eReadMessage;
958 IO->NextState = eSendReply;
961 IO->SendBuf.fd = IO->RecvBuf.fd =
963 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
967 if (IO->SendBuf.fd < 0) {
969 "EVENT: socket() failed: %s\n",
972 StrBufPrintf(IO->ErrMsg,
973 "Failed to create socket: %s",
975 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
978 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
981 "EVENT: unable to get socket %d flags! %s \n",
984 StrBufPrintf(IO->ErrMsg,
985 "Failed to get socket %d flags: %s",
988 close(IO->SendBuf.fd);
989 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
992 fdflags = fdflags | O_NONBLOCK;
993 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
996 "EVENT: unable to set socket %d nonblocking flags! %s \n",
999 StrBufPrintf(IO->ErrMsg,
1000 "Failed to set socket flags: %s",
1002 close(IO->SendBuf.fd);
1003 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1006 /* TODO: maye we could use offsetof() to calc the position of data...
1007 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1009 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1010 IO->recv_event.data = IO;
1011 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1012 IO->send_event.data = IO;
1014 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1015 IO->conn_fail.data = IO;
1016 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1017 IO->rw_timeout.data = IO;
1022 /* for debugging you may bypass it like this:
1023 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1024 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1025 * inet_addr("127.0.0.1");
1027 if (IO->ConnectMe->IPv6) {
1028 rc = connect(IO->SendBuf.fd,
1029 &IO->ConnectMe->Addr,
1030 sizeof(struct sockaddr_in6));
1033 /* If citserver is bound to a specific IP address on the host, make
1034 * sure we use that address for outbound connections.
1037 memset(&egress_sin, 0, sizeof(egress_sin));
1038 egress_sin.sin_family = AF_INET;
1039 if (!IsEmptyStr(config.c_ip_addr)) {
1040 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1041 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1042 egress_sin.sin_addr.s_addr = INADDR_ANY;
1045 /* If this bind fails, no problem; we can still use INADDR_ANY */
1046 bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1048 rc = connect(IO->SendBuf.fd,
1049 (struct sockaddr_in *)&IO->ConnectMe->Addr,
1050 sizeof(struct sockaddr_in));
1054 SetEVState(IO, eIOConnNow);
1055 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1056 set_start_callback(event_base, IO, 0);
1057 return IO->NextState;
1059 else if (errno == EINPROGRESS) {
1060 SetEVState(IO, eIOConnWait);
1061 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1063 ev_io_init(&IO->conn_event,
1064 IO_connestd_callback,
1068 IO->conn_event.data = IO;
1070 ev_io_start(event_base, &IO->conn_event);
1071 ev_timer_start(event_base, &IO->conn_fail);
1072 return IO->NextState;
1075 SetEVState(IO, eIOConnfail);
1076 ev_idle_init(&IO->conn_fail_immediate,
1077 IO_connfailimmediate_callback);
1078 IO->conn_fail_immediate.data = IO;
1079 ev_idle_start(event_base, &IO->conn_fail_immediate);
1082 "connect() = %d failed: %s\n",
1086 StrBufPrintf(IO->ErrMsg,
1087 "Failed to connect: %s",
1089 return IO->NextState;
1091 return IO->NextState;
1094 void SetNextTimeout(AsyncIO *IO, double timeout)
1096 IO->rw_timeout.repeat = timeout;
1097 ev_timer_again (event_base, &IO->rw_timeout);
1101 eNextState ReAttachIO(AsyncIO *IO,
1105 SetEVState(IO, eIOAttach);
1107 become_session(IO->CitContext);
1108 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1110 IO->NextState = eReadMessage;
1113 IO->NextState = eSendReply;
1115 set_start_callback(event_base, IO, 0);
1117 return IO->NextState;
1120 void InitIOStruct(AsyncIO *IO,
1122 eNextState NextState,
1123 IO_LineReaderCallback LineReader,
1124 IO_CallBack DNS_Fail,
1125 IO_CallBack SendDone,
1126 IO_CallBack ReadDone,
1127 IO_CallBack Terminate,
1128 IO_CallBack DBTerminate,
1129 IO_CallBack ConnFail,
1130 IO_CallBack Timeout,
1131 IO_CallBack ShutdownAbort)
1135 IO->CitContext = CloneContext(CC);
1136 IO->CitContext->session_specific_data = Data;
1137 IO->CitContext->IO = IO;
1139 IO->NextState = NextState;
1141 IO->SendDone = SendDone;
1142 IO->ReadDone = ReadDone;
1143 IO->Terminate = Terminate;
1144 IO->DBTerminate = DBTerminate;
1145 IO->LineReader = LineReader;
1146 IO->ConnFail = ConnFail;
1147 IO->Timeout = Timeout;
1148 IO->ShutdownAbort = ShutdownAbort;
1150 IO->DNS.Fail = DNS_Fail;
1152 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
1153 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
1154 IO->IOBuf = NewStrBuf();
1155 EV_syslog(LOG_DEBUG,
1156 "EVENT: Session lives at %p IO at %p \n",
1161 extern int evcurl_init(AsyncIO *IO);
1163 int InitcURLIOStruct(AsyncIO *IO,
1166 IO_CallBack SendDone,
1167 IO_CallBack Terminate,
1168 IO_CallBack DBTerminate,
1169 IO_CallBack ShutdownAbort)
1173 IO->CitContext = CloneContext(CC);
1174 IO->CitContext->session_specific_data = Data;
1175 IO->CitContext->IO = IO;
1177 IO->SendDone = SendDone;
1178 IO->Terminate = Terminate;
1179 IO->DBTerminate = DBTerminate;
1180 IO->ShutdownAbort = ShutdownAbort;
1182 strcpy(IO->HttpReq.errdesc, Desc);
1185 return evcurl_init(IO);
1190 typedef struct KillOtherSessionContext {
1193 }KillOtherSessionContext;
1195 eNextState KillTerminate(AsyncIO *IO)
1198 KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1199 EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1201 FreeAsyncIOContents(IO);
1202 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1203 IO->ID = id; /* just for the case we want to analyze it in a coredump */
1209 eNextState KillShutdown(AsyncIO *IO)
1211 return eTerminateConnection;
1214 eNextState KillOtherContextNow(AsyncIO *IO)
1216 KillOtherSessionContext *Ctx = IO->Data;
1218 SetEVState(IO, eKill);
1220 if (Ctx->OtherOne->ShutdownAbort != NULL)
1221 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1222 return eTerminateConnection;
1225 void KillAsyncIOContext(AsyncIO *IO)
1227 KillOtherSessionContext *Ctx;
1229 Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1230 memset(Ctx, 0, sizeof(KillOtherSessionContext));
1232 InitIOStruct(&Ctx->IO,
1247 switch(IO->NextState) {
1260 IO->ReAttachCB = KillOtherContextNow;
1261 QueueAnEventContext(&Ctx->IO);
1264 IO->ReAttachCB = KillOtherContextNow;
1265 QueueAnDBOperation(&Ctx->IO);
1267 case eTerminateConnection:
1269 /*hm, its already dying, dunno which Queue its in... */
1275 extern int DebugEventLoopBacktrace;
1276 void EV_backtrace(AsyncIO *IO)
1278 #ifdef HAVE_BACKTRACE
1279 void *stack_frames[50];
1283 if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1285 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1286 strings = backtrace_symbols(stack_frames, size);
1287 for (i = 0; i < size; i++) {
1288 if (strings != NULL) {
1289 EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1292 EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1300 ev_tstamp ctdl_ev_now (void)
1302 return ev_now(event_base);