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 ev_io_stop(event_base, &IO->send_event);
231 ev_io_stop(event_base, &IO->recv_event);
232 ev_timer_stop (event_base, &IO->rw_timeout);
233 close(IO->SendBuf.fd);
238 void ShutDownCLient(AsyncIO *IO)
240 CitContext *Ctx =IO->CitContext;
243 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
245 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
246 StopClientWatchers(IO);
248 if (IO->DNSChannel != NULL) {
249 ares_destroy(IO->DNSChannel);
250 ev_io_stop(event_base, &IO->dns_recv_event);
251 ev_io_stop(event_base, &IO->dns_send_event);
252 IO->DNSChannel = NULL;
254 assert(IO->Terminate);
256 Ctx->state = CON_IDLE;
261 eReadState HandleInbound(AsyncIO *IO)
263 eReadState Finished = eBufferNotEmpty;
265 become_session(IO->CitContext);
267 while ((Finished == eBufferNotEmpty) &&
268 ((IO->NextState == eReadMessage)||
269 (IO->NextState == eReadMore)||
270 (IO->NextState == eReadPayload)))
272 if (IO->RecvBuf.nBlobBytesWanted != 0) {
275 else { /* Reading lines... */
276 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
278 Finished = IO->LineReader(IO);
280 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
283 case eMustReadMore: /// read new from socket...
286 case eBufferNotEmpty: /* shouldn't happen... */
287 case eReadSuccess: /// done for now...
289 case eReadFail: /// WHUT?
296 if (Finished != eMustReadMore) {
297 assert(IO->ReadDone);
298 ev_io_stop(event_base, &IO->recv_event);
299 IO->NextState = IO->ReadDone(IO);
300 Finished = StrBufCheckBuffer(&IO->RecvBuf);
304 switch (IO->NextState) {
307 assert(IO->SendDone);
308 IO->NextState = IO->SendDone(IO);
309 ev_io_start(event_base, &IO->send_event);
313 ev_io_start(event_base, &IO->recv_event);
315 case eTerminateConnection:
331 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
334 AsyncIO *IO = watcher->data;
336 become_session(IO->CitContext);
342 const char *pch = ChrPtr(IO->SendBuf.Buf);
343 const char *pchh = IO->SendBuf.ReadWritePointer;
349 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
350 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
351 ((CitContext*)(IO->CitContext))->ServiceName,
354 fd = fopen(fn, "a+");
355 fprintf(fd, "Send: BufSize: %ld BufContent: [",
357 rv = fwrite(pchh, nbytes, 1, fd);
358 if (!rv) printf("failed to write debug to %s!\n", fn);
361 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
364 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
370 ev_io_stop(event_base, &IO->send_event);
371 switch (IO->NextState) {
373 assert(IO->SendDone);
374 IO->NextState = IO->SendDone(IO);
376 if ((IO->NextState == eTerminateConnection) ||
377 (IO->NextState == eAbort) )
380 ev_io_start(event_base, &IO->send_event);
384 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
386 IO->NextState = eReadMore;
390 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
394 ev_io_start(event_base, &IO->recv_event);
399 /* we now live in another queue, so we have to unregister. */
400 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
405 case eTerminateConnection:
414 /* else : must write more. */
417 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
420 switch(IO->NextState) {
423 ev_io_start(event_base, &IO->recv_event);
428 become_session(IO->CitContext);
429 IO_send_callback(loop, &IO->send_event, revents);
435 case eTerminateConnection:
443 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
445 AsyncIO *IO = watcher->data;
447 ev_timer_stop (event_base, &IO->rw_timeout);
448 become_session(IO->CitContext);
450 if (IO->SendBuf.fd != 0)
452 ev_io_stop(event_base, &IO->send_event);
453 ev_io_stop(event_base, &IO->recv_event);
454 ev_timer_stop (event_base, &IO->rw_timeout);
455 close(IO->SendBuf.fd);
456 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
460 switch (IO->Timeout(IO))
470 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
472 AsyncIO *IO = watcher->data;
474 ev_timer_stop (event_base, &IO->conn_fail);
476 if (IO->SendBuf.fd != 0)
478 ev_io_stop(loop, &IO->conn_event);
479 ev_io_stop(event_base, &IO->send_event);
480 ev_io_stop(event_base, &IO->recv_event);
481 ev_timer_stop (event_base, &IO->rw_timeout);
482 close(IO->SendBuf.fd);
483 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
485 become_session(IO->CitContext);
487 assert(IO->ConnFail);
488 switch (IO->ConnFail(IO))
499 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
501 AsyncIO *IO = watcher->data;
503 ev_idle_stop (event_base, &IO->conn_fail_immediate);
505 if (IO->SendBuf.fd != 0)
507 close(IO->SendBuf.fd);
508 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
510 become_session(IO->CitContext);
512 assert(IO->ConnFail);
513 switch (IO->ConnFail(IO))
524 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
526 AsyncIO *IO = watcher->data;
528 ev_io_stop(loop, &IO->conn_event);
529 ev_timer_stop (event_base, &IO->conn_fail);
530 set_start_callback(loop, IO, revents);
533 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
536 AsyncIO *IO = watcher->data;
538 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
544 const char *pch = ChrPtr(IO->RecvBuf.Buf);
545 const char *pchh = IO->RecvBuf.ReadWritePointer;
551 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
552 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
553 ((CitContext*)(IO->CitContext))->ServiceName,
556 fd = fopen(fn, "a+");
557 fprintf(fd, "Read: BufSize: %ld BufContent: [",
559 rv = fwrite(pchh, nbytes, 1, fd);
560 if (!rv) printf("failed to write debug to %s!\n", fn);
569 } else if (nbytes == 0) {
572 switch (IO->Timeout(IO))
580 } else if (nbytes == -1) {
581 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
582 CtdlLogPrintf(CTDL_DEBUG,
583 "EVENT: Socket Invalid! %s \n",
590 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
592 AsyncIO *IO = watcher->data;
593 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
594 become_session(IO->CitContext);
596 switch (IO->DNSQuery->PostDNS(IO))
605 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
610 IO->SendBuf.fd = IO->RecvBuf.fd =
612 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
616 if (IO->SendBuf.fd < 0) {
617 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
618 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
621 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
623 CtdlLogPrintf(CTDL_DEBUG,
624 "EVENT: unable to get socket flags! %s \n",
626 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
629 fdflags = fdflags | O_NONBLOCK;
630 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
631 CtdlLogPrintf(CTDL_DEBUG,
632 "EVENT: unable to set socket nonblocking flags! %s \n",
634 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
635 close(IO->SendBuf.fd);
636 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
639 /* TODO: maye we could use offsetof() to calc the position of data...
640 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
642 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
643 IO->recv_event.data = IO;
644 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
645 IO->send_event.data = IO;
647 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
648 IO->conn_fail.data = IO;
649 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
650 IO->rw_timeout.data = IO;
653 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
654 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
655 if (IO->ConnectMe->IPv6)
656 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
658 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
661 CtdlLogPrintf(CTDL_DEBUG, "connect() immediate success.\n");
662 set_start_callback(event_base, IO, 0);
663 ev_timer_start(event_base, &IO->rw_timeout);
664 return IO->NextState;
666 else if (errno == EINPROGRESS) {
667 CtdlLogPrintf(CTDL_DEBUG, "connect() have to wait now.\n");
669 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
670 IO->conn_event.data = IO;
672 ev_io_start(event_base, &IO->conn_event);
673 ev_timer_start(event_base, &IO->conn_fail);
674 return IO->NextState;
677 ev_idle_init(&IO->conn_fail_immediate,
678 IO_connfailimmediate_callback);
679 IO->conn_fail_immediate.data = IO;
680 ev_idle_start(event_base, &IO->conn_fail_immediate);
682 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
683 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
684 return IO->NextState;
686 return IO->NextState;
689 void SetNextTimeout(AsyncIO *IO, double timeout)
691 IO->rw_timeout.repeat = timeout;
692 ev_timer_again (event_base, &IO->rw_timeout);
695 eNextState InitEventIO(AsyncIO *IO,
698 double first_rw_timeout,
702 become_session(IO->CitContext);
705 IO->NextState = eReadMessage;
708 IO->NextState = eSendReply;
710 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
713 eNextState ReAttachIO(AsyncIO *IO,
718 become_session(IO->CitContext);
719 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
721 IO->NextState = eReadMessage;
724 IO->NextState = eSendReply;
726 set_start_callback(event_base, IO, 0);
728 return IO->NextState;