3 * Copyright (c) 1998-2009 by the citadel.org team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 #include <sys/types.h>
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
37 # include <sys/time.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
51 #include <libcitadel.h>
54 #include "citserver.h"
61 #include "internet_addressing.h"
64 #include "clientsocket.h"
65 #include "locate_host.h"
66 #include "citadel_dirs.h"
68 #include "event_client.h"
70 static void IO_abort_shutdown_callback(struct ev_loop *loop, ev_cleanup *watcher, int revents)
72 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
74 AsyncIO *IO = watcher->data;
75 assert(IO->ShutdownAbort);
76 IO->ShutdownAbort(IO);
80 /*--------------------------------------------------------------------------------
83 extern int evdb_count;
84 extern citthread_mutex_t DBEventQueueMutex;
85 extern HashList *DBInboundEventQueue;
86 extern struct ev_loop *event_db;
87 extern ev_async DBAddJob;
88 extern ev_async DBExitEventLoop;
90 int 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;
101 ev_cleanup_start(event_db, &IO->db_abort_by_shutdown);
103 citthread_mutex_lock(&DBEventQueueMutex);
104 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT Q\n");
106 Put(DBInboundEventQueue, IKEY(i), h, NULL);
107 citthread_mutex_unlock(&DBEventQueueMutex);
109 ev_async_send (event_db, &DBAddJob);
110 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT Q Done.\n");
114 void ShutDownDBCLient(AsyncIO *IO)
116 CitContext *Ctx =IO->CitContext;
119 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT\n");
120 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
122 assert(IO->Terminate);
125 Ctx->state = CON_IDLE;
130 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
132 AsyncIO *IO = watcher->data;
133 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
134 become_session(IO->CitContext);
136 ev_idle_stop(event_db, &IO->db_unwind_stack);
138 assert(IO->NextDBOperation);
139 switch (IO->NextDBOperation(IO))
151 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
153 case eTerminateConnection:
155 ShutDownDBCLient(IO);
159 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
161 IO->NextDBOperation = CB;
162 ev_idle_init(&IO->db_unwind_stack,
164 IO->db_unwind_stack.data = IO;
165 ev_idle_start(event_db, &IO->db_unwind_stack);
169 /*--------------------------------------------------------------------------------
172 extern int evbase_count;
173 extern citthread_mutex_t EventQueueMutex;
174 extern HashList *InboundEventQueue;
175 extern struct ev_loop *event_base;
176 extern ev_async AddJob;
177 extern ev_async ExitEventLoop;
180 int QueueEventContext(AsyncIO *IO, IO_CallBack CB)
185 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
188 ev_cleanup_init(&IO->abort_by_shutdown,
189 IO_abort_shutdown_callback);
190 IO->abort_by_shutdown.data = IO;
191 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
193 citthread_mutex_lock(&EventQueueMutex);
194 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
196 Put(InboundEventQueue, IKEY(i), h, NULL);
197 citthread_mutex_unlock(&EventQueueMutex);
199 ev_async_send (event_base, &AddJob);
200 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
204 int ShutDownEventQueue(void)
206 citthread_mutex_lock(&DBEventQueueMutex);
207 ev_async_send (event_db, &DBExitEventLoop);
208 citthread_mutex_unlock(&DBEventQueueMutex);
210 citthread_mutex_lock(&EventQueueMutex);
211 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
212 citthread_mutex_unlock(&EventQueueMutex);
216 void FreeAsyncIOContents(AsyncIO *IO)
218 FreeStrBuf(&IO->IOBuf);
219 FreeStrBuf(&IO->SendBuf.Buf);
220 FreeStrBuf(&IO->RecvBuf.Buf);
224 void StopClientWatchers(AsyncIO *IO)
226 ev_timer_stop(event_base, &IO->conn_fail);
227 ev_io_stop(event_base, &IO->conn_event);
228 ev_idle_stop(event_base, &IO->unwind_stack);
230 if (IO->SendBuf.fd != 0)
232 ev_io_stop(event_base, &IO->send_event);
233 ev_io_stop(event_base, &IO->recv_event);
234 ev_timer_stop (event_base, &IO->rw_timeout);
235 close(IO->SendBuf.fd);
241 void ShutDownCLient(AsyncIO *IO)
243 CitContext *Ctx =IO->CitContext;
246 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
248 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
249 StopClientWatchers(IO);
251 if (IO->DNSChannel != NULL) {
252 ares_destroy(IO->DNSChannel);
253 ev_io_stop(event_base, &IO->dns_recv_event);
254 ev_io_stop(event_base, &IO->dns_send_event);
255 IO->DNSChannel = NULL;
257 assert(IO->Terminate);
259 Ctx->state = CON_IDLE;
264 eReadState HandleInbound(AsyncIO *IO)
266 eReadState Finished = eBufferNotEmpty;
268 become_session(IO->CitContext);
270 while ((Finished == eBufferNotEmpty) &&
271 ((IO->NextState == eReadMessage)||
272 (IO->NextState == eReadMore)||
273 (IO->NextState == eReadPayload)))
275 if (IO->RecvBuf.nBlobBytesWanted != 0) {
278 else { /* Reading lines... */
279 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
281 Finished = IO->LineReader(IO);
283 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
286 case eMustReadMore: /// read new from socket...
289 case eBufferNotEmpty: /* shouldn't happen... */
290 case eReadSuccess: /// done for now...
292 case eReadFail: /// WHUT?
299 if (Finished != eMustReadMore) {
300 assert(IO->ReadDone);
301 ev_io_stop(event_base, &IO->recv_event);
302 IO->NextState = IO->ReadDone(IO);
303 Finished = StrBufCheckBuffer(&IO->RecvBuf);
307 switch (IO->NextState) {
310 assert(IO->SendDone);
311 IO->NextState = IO->SendDone(IO);
312 ev_io_start(event_base, &IO->send_event);
316 ev_io_start(event_base, &IO->recv_event);
318 case eTerminateConnection:
334 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
337 AsyncIO *IO = watcher->data;
339 become_session(IO->CitContext);
345 const char *pch = ChrPtr(IO->SendBuf.Buf);
346 const char *pchh = IO->SendBuf.ReadWritePointer;
352 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
353 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
354 ((CitContext*)(IO->CitContext))->ServiceName,
357 fd = fopen(fn, "a+");
358 fprintf(fd, "Read: BufSize: %ld BufContent: [",
360 rv = fwrite(pchh, nbytes, 1, fd);
361 if (!rv) printf("failed to write debug to %s!\n", fn);
368 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
377 const char *pch = ChrPtr(IO->SendBuf.Buf);
378 const char *pchh = IO->SendBuf.ReadWritePointer;
384 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
385 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
386 ((CitContext*)(IO->CitContext))->ServiceName,
389 fd = fopen(fn, "a+");
390 fprintf(fd, "Read: BufSize: %ld BufContent: [",
392 rv = fwrite(pchh, nbytes, 1, fd);
393 if (!rv) printf("failed to write debug to %s!\n", fn);
400 ev_io_stop(event_base, &IO->send_event);
401 switch (IO->NextState) {
403 assert(IO->SendDone);
404 IO->NextState = IO->SendDone(IO);
406 if ((IO->NextState == eTerminateConnection) ||
407 (IO->NextState == eAbort) )
410 ev_io_start(event_base, &IO->send_event);
414 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
416 IO->NextState = eReadMore;
420 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
424 ev_io_start(event_base, &IO->recv_event);
429 /* we now live in another queue, so we have to unregister. */
430 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
435 case eTerminateConnection:
444 /* else : must write more. */
447 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
450 switch(IO->NextState) {
453 ev_io_start(event_base, &IO->recv_event);
458 become_session(IO->CitContext);
459 IO_send_callback(loop, &IO->send_event, revents);
465 case eTerminateConnection:
473 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
475 AsyncIO *IO = watcher->data;
477 ev_timer_stop (event_base, &IO->rw_timeout);
478 become_session(IO->CitContext);
480 if (IO->SendBuf.fd != 0)
482 ev_io_stop(event_base, &IO->send_event);
483 ev_io_stop(event_base, &IO->recv_event);
484 ev_timer_stop (event_base, &IO->rw_timeout);
485 close(IO->SendBuf.fd);
486 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
490 switch (IO->Timeout(IO))
500 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
502 AsyncIO *IO = watcher->data;
504 ev_timer_stop (event_base, &IO->conn_fail);
506 if (IO->SendBuf.fd != 0)
508 ev_io_stop(loop, &IO->conn_event);
509 ev_io_stop(event_base, &IO->send_event);
510 ev_io_stop(event_base, &IO->recv_event);
511 ev_timer_stop (event_base, &IO->rw_timeout);
512 close(IO->SendBuf.fd);
513 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
515 become_session(IO->CitContext);
517 assert(IO->ConnFail);
518 switch (IO->ConnFail(IO))
529 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
531 AsyncIO *IO = watcher->data;
533 ev_idle_stop (event_base, &IO->conn_fail_immediate);
535 if (IO->SendBuf.fd != 0)
537 close(IO->SendBuf.fd);
538 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
540 become_session(IO->CitContext);
542 assert(IO->ConnFail);
543 switch (IO->ConnFail(IO))
554 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
556 AsyncIO *IO = watcher->data;
558 ev_io_stop(loop, &IO->conn_event);
559 ev_timer_stop (event_base, &IO->conn_fail);
560 set_start_callback(loop, IO, revents);
563 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
566 AsyncIO *IO = watcher->data;
568 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
574 const char *pch = ChrPtr(IO->RecvBuf.Buf);
575 const char *pchh = IO->RecvBuf.ReadWritePointer;
581 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
582 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
583 ((CitContext*)(IO->CitContext))->ServiceName,
586 fd = fopen(fn, "a+");
587 fprintf(fd, "Read: BufSize: %ld BufContent: [",
589 rv = fwrite(pchh, nbytes, 1, fd);
590 if (!rv) printf("failed to write debug to %s!\n", fn);
599 } else if (nbytes == 0) {
602 switch (IO->Timeout(IO))
610 } else if (nbytes == -1) {
611 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
612 CtdlLogPrintf(CTDL_DEBUG,
613 "EVENT: Socket Invalid! %s \n",
620 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
622 AsyncIO *IO = watcher->data;
623 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
624 become_session(IO->CitContext);
626 switch (IO->DNSQuery->PostDNS(IO))
635 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
640 IO->SendBuf.fd = IO->RecvBuf.fd =
642 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
646 if (IO->SendBuf.fd < 0) {
647 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
648 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
651 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
653 CtdlLogPrintf(CTDL_DEBUG,
654 "EVENT: unable to get socket flags! %s \n",
656 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
659 fdflags = fdflags | O_NONBLOCK;
660 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
661 CtdlLogPrintf(CTDL_DEBUG,
662 "EVENT: unable to set socket nonblocking flags! %s \n",
664 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
665 close(IO->SendBuf.fd);
666 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
669 /* TODO: maye we could use offsetof() to calc the position of data...
670 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
672 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
673 IO->recv_event.data = IO;
674 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
675 IO->send_event.data = IO;
677 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
678 IO->conn_fail.data = IO;
679 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
680 IO->rw_timeout.data = IO;
683 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
684 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
685 if (IO->ConnectMe->IPv6)
686 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
688 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
691 CtdlLogPrintf(CTDL_DEBUG, "connect() immediate success.\n");
692 set_start_callback(event_base, IO, 0);
693 ev_timer_start(event_base, &IO->rw_timeout);
694 return IO->NextState;
696 else if (errno == EINPROGRESS) {
697 CtdlLogPrintf(CTDL_DEBUG, "connect() have to wait now.\n");
699 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
700 IO->conn_event.data = IO;
702 ev_io_start(event_base, &IO->conn_event);
703 ev_timer_start(event_base, &IO->conn_fail);
704 return IO->NextState;
707 ev_idle_init(&IO->conn_fail_immediate,
708 IO_connfailimmediate_callback);
709 IO->conn_fail_immediate.data = IO;
710 ev_idle_start(event_base, &IO->conn_fail_immediate);
712 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
713 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
714 return IO->NextState;
716 return IO->NextState;
719 void SetNextTimeout(AsyncIO *IO, double timeout)
721 IO->rw_timeout.repeat = timeout;
722 ev_timer_again (event_base, &IO->rw_timeout);
725 eNextState InitEventIO(AsyncIO *IO,
728 double first_rw_timeout,
732 become_session(IO->CitContext);
735 IO->NextState = eReadMessage;
738 IO->NextState = eSendReply;
740 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
743 eNextState ReAttachIO(AsyncIO *IO,
748 become_session(IO->CitContext);
749 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
751 IO->NextState = eReadMessage;
754 IO->NextState = eSendReply;
756 set_start_callback(event_base, IO, 0);
758 return IO->NextState;