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 AsyncIO *IO = watcher->data;
73 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
75 assert(IO->ShutdownAbort);
76 IO->ShutdownAbort(IO);
80 /*--------------------------------------------------------------------------------
83 extern int evdb_count;
84 extern pthread_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 eNextState 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 pthread_mutex_lock(&DBEventQueueMutex);
104 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
106 Put(DBInboundEventQueue, IKEY(i), h, NULL);
107 pthread_mutex_unlock(&DBEventQueueMutex);
109 ev_async_send (event_db, &DBAddJob);
110 EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
114 void ShutDownDBCLient(AsyncIO *IO)
116 CitContext *Ctx =IO->CitContext;
119 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\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 EV_syslog(LOG_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))
153 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
155 case eTerminateConnection:
157 ev_idle_stop(event_db, &IO->db_unwind_stack);
158 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
159 ShutDownDBCLient(IO);
163 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
165 IO->NextDBOperation = CB;
166 ev_idle_init(&IO->db_unwind_stack,
168 IO->db_unwind_stack.data = IO;
169 ev_idle_start(event_db, &IO->db_unwind_stack);
173 /*--------------------------------------------------------------------------------
176 extern int evbase_count;
177 extern pthread_mutex_t EventQueueMutex;
178 extern HashList *InboundEventQueue;
179 extern struct ev_loop *event_base;
180 extern ev_async AddJob;
181 extern ev_async ExitEventLoop;
184 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
189 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
192 ev_cleanup_init(&IO->abort_by_shutdown,
193 IO_abort_shutdown_callback);
194 IO->abort_by_shutdown.data = IO;
195 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
197 pthread_mutex_lock(&EventQueueMutex);
198 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
200 Put(InboundEventQueue, IKEY(i), h, NULL);
201 pthread_mutex_unlock(&EventQueueMutex);
203 ev_async_send (event_base, &AddJob);
204 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
208 extern eNextState evcurl_handle_start(AsyncIO *IO);
210 eNextState QueueCurlContext(AsyncIO *IO)
215 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
217 h->EvAttch = evcurl_handle_start;
219 pthread_mutex_lock(&EventQueueMutex);
220 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
222 Put(InboundEventQueue, IKEY(i), h, NULL);
223 pthread_mutex_unlock(&EventQueueMutex);
225 ev_async_send (event_base, &AddJob);
226 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
230 int ShutDownEventQueue(void)
232 pthread_mutex_lock(&DBEventQueueMutex);
233 ev_async_send (event_db, &DBExitEventLoop);
234 pthread_mutex_unlock(&DBEventQueueMutex);
236 pthread_mutex_lock(&EventQueueMutex);
237 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
238 pthread_mutex_unlock(&EventQueueMutex);
242 void FreeAsyncIOContents(AsyncIO *IO)
244 FreeStrBuf(&IO->IOBuf);
245 FreeStrBuf(&IO->SendBuf.Buf);
246 FreeStrBuf(&IO->RecvBuf.Buf);
250 void StopClientWatchers(AsyncIO *IO)
252 ev_timer_stop(event_base, &IO->conn_fail);
253 ev_io_stop(event_base, &IO->conn_event);
254 ev_idle_stop(event_base, &IO->unwind_stack);
256 ev_io_stop(event_base, &IO->send_event);
257 ev_io_stop(event_base, &IO->recv_event);
258 ev_timer_stop (event_base, &IO->rw_timeout);
259 close(IO->SendBuf.fd);
264 void ShutDownCLient(AsyncIO *IO)
266 CitContext *Ctx =IO->CitContext;
269 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
271 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
272 StopClientWatchers(IO);
274 if (IO->DNSChannel != NULL) {
275 ares_destroy(IO->DNSChannel);
276 ev_io_stop(event_base, &IO->dns_recv_event);
277 ev_io_stop(event_base, &IO->dns_send_event);
278 IO->DNSChannel = NULL;
280 assert(IO->Terminate);
282 Ctx->state = CON_IDLE;
287 eReadState HandleInbound(AsyncIO *IO)
289 const char *Err = NULL;
290 eReadState Finished = eBufferNotEmpty;
292 become_session(IO->CitContext);
294 while ((Finished == eBufferNotEmpty) &&
295 ((IO->NextState == eReadMessage)||
296 (IO->NextState == eReadMore)||
297 (IO->NextState == eReadFile)||
298 (IO->NextState == eReadPayload)))
300 if (IO->RecvBuf.nBlobBytesWanted != 0) {
303 else { /* Reading lines... */
304 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
305 if ((IO->NextState == eReadFile) &&
306 (Finished == eBufferNotEmpty))
308 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
309 if (Finished == eReadSuccess)
311 IO->NextState = eSendReply;
314 else if (IO->LineReader)
315 Finished = IO->LineReader(IO);
317 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
320 case eMustReadMore: /// read new from socket...
322 case eBufferNotEmpty: /* shouldn't happen... */
323 case eReadSuccess: /// done for now...
325 case eReadFail: /// WHUT?
332 if (Finished != eMustReadMore) {
333 assert(IO->ReadDone);
334 ev_io_stop(event_base, &IO->recv_event);
335 IO->NextState = IO->ReadDone(IO);
336 Finished = StrBufCheckBuffer(&IO->RecvBuf);
340 switch (IO->NextState) {
342 ev_io_start(event_base, &IO->send_event);
346 assert(IO->SendDone);
347 IO->NextState = IO->SendDone(IO);
348 ev_io_start(event_base, &IO->send_event);
353 ev_io_start(event_base, &IO->recv_event);
355 case eTerminateConnection:
373 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
376 AsyncIO *IO = watcher->data;
377 const char *errmsg = NULL;
379 become_session(IO->CitContext);
385 const char *pch = ChrPtr(IO->SendBuf.Buf);
386 const char *pchh = IO->SendBuf.ReadWritePointer;
392 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
393 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
394 ((CitContext*)(IO->CitContext))->ServiceName,
397 fd = fopen(fn, "a+");
398 fprintf(fd, "Send: BufSize: %ld BufContent: [",
400 rv = fwrite(pchh, nbytes, 1, fd);
401 if (!rv) printf("failed to write debug to %s!\n", fn);
404 switch (IO->NextState) {
406 rc = FileSendChunked(&IO->IOB, &errmsg);
408 StrBufPlain(IO->ErrMsg, errmsg, -1);
411 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
415 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
421 ev_io_stop(event_base, &IO->send_event);
422 switch (IO->NextState) {
424 assert(IO->SendDone);
425 IO->NextState = IO->SendDone(IO);
427 if ((IO->NextState == eTerminateConnection) ||
428 (IO->NextState == eAbort) )
431 ev_io_start(event_base, &IO->send_event);
435 if (IO->IOB.ChunkSendRemain > 0) {
436 ev_io_start(event_base, &IO->recv_event);
438 assert(IO->ReadDone);
439 IO->NextState = IO->ReadDone(IO);
440 switch(IO->NextState) {
449 ev_io_start(event_base, &IO->send_event);
456 case eTerminateConnection:
463 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
465 IO->NextState = eReadMore;
470 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
474 ev_io_start(event_base, &IO->recv_event);
479 /* we now live in another queue, so we have to unregister. */
480 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
485 case eTerminateConnection:
494 /* else : must write more. */
497 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
500 switch(IO->NextState) {
504 ev_io_start(event_base, &IO->recv_event);
510 become_session(IO->CitContext);
511 IO_send_callback(loop, &IO->send_event, revents);
517 case eTerminateConnection:
525 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
527 AsyncIO *IO = watcher->data;
529 ev_timer_stop (event_base, &IO->rw_timeout);
530 become_session(IO->CitContext);
532 if (IO->SendBuf.fd != 0)
534 ev_io_stop(event_base, &IO->send_event);
535 ev_io_stop(event_base, &IO->recv_event);
536 ev_timer_stop (event_base, &IO->rw_timeout);
537 close(IO->SendBuf.fd);
538 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
542 switch (IO->Timeout(IO))
552 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
554 AsyncIO *IO = watcher->data;
556 ev_timer_stop (event_base, &IO->conn_fail);
558 if (IO->SendBuf.fd != 0)
560 ev_io_stop(loop, &IO->conn_event);
561 ev_io_stop(event_base, &IO->send_event);
562 ev_io_stop(event_base, &IO->recv_event);
563 ev_timer_stop (event_base, &IO->rw_timeout);
564 close(IO->SendBuf.fd);
565 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
567 become_session(IO->CitContext);
569 assert(IO->ConnFail);
570 switch (IO->ConnFail(IO))
581 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
583 AsyncIO *IO = watcher->data;
585 ev_idle_stop (event_base, &IO->conn_fail_immediate);
587 if (IO->SendBuf.fd != 0)
589 close(IO->SendBuf.fd);
590 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
592 become_session(IO->CitContext);
594 assert(IO->ConnFail);
595 switch (IO->ConnFail(IO))
606 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
608 AsyncIO *IO = watcher->data;
610 ev_io_stop(loop, &IO->conn_event);
611 ev_timer_stop (event_base, &IO->conn_fail);
612 set_start_callback(loop, IO, revents);
615 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
619 AsyncIO *IO = watcher->data;
621 switch (IO->NextState) {
623 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
625 StrBufPlain(IO->ErrMsg, errmsg, -1);
628 if (IO->IOB.ChunkSendRemain == 0)
630 IO->NextState = eSendReply;
637 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
646 const char *pch = ChrPtr(IO->RecvBuf.Buf);
647 const char *pchh = IO->RecvBuf.ReadWritePointer;
653 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
654 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
655 ((CitContext*)(IO->CitContext))->ServiceName,
658 fd = fopen(fn, "a+");
659 fprintf(fd, "Read: BufSize: %ld BufContent: [",
661 rv = fwrite(pchh, nbytes, 1, fd);
662 if (!rv) printf("failed to write debug to %s!\n", fn);
671 } else if (nbytes == 0) {
674 switch (IO->Timeout(IO))
682 } else if (nbytes == -1) {
683 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
685 "EVENT: Socket Invalid! %s \n",
693 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
695 AsyncIO *IO = watcher->data;
696 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
697 become_session(IO->CitContext);
699 assert(IO->DNSQuery->PostDNS);
700 switch (IO->DNSQuery->PostDNS(IO))
709 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
714 IO->SendBuf.fd = IO->RecvBuf.fd =
716 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
720 if (IO->SendBuf.fd < 0) {
721 EV_syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
722 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
725 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
728 "EVENT: unable to get socket flags! %s \n",
730 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
733 fdflags = fdflags | O_NONBLOCK;
734 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
736 "EVENT: unable to set socket nonblocking flags! %s \n",
738 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
739 close(IO->SendBuf.fd);
740 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
743 /* TODO: maye we could use offsetof() to calc the position of data...
744 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
746 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
747 IO->recv_event.data = IO;
748 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
749 IO->send_event.data = IO;
751 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
752 IO->conn_fail.data = IO;
753 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
754 IO->rw_timeout.data = IO;
757 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
758 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
759 if (IO->ConnectMe->IPv6)
760 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
762 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
765 EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
766 set_start_callback(event_base, IO, 0);
767 ev_timer_start(event_base, &IO->rw_timeout);
768 return IO->NextState;
770 else if (errno == EINPROGRESS) {
771 EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
773 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
774 IO->conn_event.data = IO;
776 ev_io_start(event_base, &IO->conn_event);
777 ev_timer_start(event_base, &IO->conn_fail);
778 return IO->NextState;
781 ev_idle_init(&IO->conn_fail_immediate,
782 IO_connfailimmediate_callback);
783 IO->conn_fail_immediate.data = IO;
784 ev_idle_start(event_base, &IO->conn_fail_immediate);
786 EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
787 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
788 return IO->NextState;
790 return IO->NextState;
793 void SetNextTimeout(AsyncIO *IO, double timeout)
795 IO->rw_timeout.repeat = timeout;
796 ev_timer_again (event_base, &IO->rw_timeout);
799 eNextState InitEventIO(AsyncIO *IO,
802 double first_rw_timeout,
806 become_session(IO->CitContext);
809 IO->NextState = eReadMessage;
812 IO->NextState = eSendReply;
814 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
817 eNextState ReAttachIO(AsyncIO *IO,
822 become_session(IO->CitContext);
823 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
825 IO->NextState = eReadMessage;
828 IO->NextState = eSendReply;
830 set_start_callback(event_base, IO, 0);
832 return IO->NextState;