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 syslog(LOG_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 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 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 syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
114 void ShutDownDBCLient(AsyncIO *IO)
116 CitContext *Ctx =IO->CitContext;
119 syslog(LOG_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 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 ShutDownDBCLient(IO);
161 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
163 IO->NextDBOperation = CB;
164 ev_idle_init(&IO->db_unwind_stack,
166 IO->db_unwind_stack.data = IO;
167 ev_idle_start(event_db, &IO->db_unwind_stack);
171 /*--------------------------------------------------------------------------------
174 extern int evbase_count;
175 extern pthread_mutex_t EventQueueMutex;
176 extern HashList *InboundEventQueue;
177 extern struct ev_loop *event_base;
178 extern ev_async AddJob;
179 extern ev_async ExitEventLoop;
182 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
187 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
190 ev_cleanup_init(&IO->abort_by_shutdown,
191 IO_abort_shutdown_callback);
192 IO->abort_by_shutdown.data = IO;
193 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
195 pthread_mutex_lock(&EventQueueMutex);
196 syslog(LOG_DEBUG, "EVENT Q\n");
198 Put(InboundEventQueue, IKEY(i), h, NULL);
199 pthread_mutex_unlock(&EventQueueMutex);
201 ev_async_send (event_base, &AddJob);
202 syslog(LOG_DEBUG, "EVENT Q Done.\n");
206 int ShutDownEventQueue(void)
208 pthread_mutex_lock(&DBEventQueueMutex);
209 ev_async_send (event_db, &DBExitEventLoop);
210 pthread_mutex_unlock(&DBEventQueueMutex);
212 pthread_mutex_lock(&EventQueueMutex);
213 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
214 pthread_mutex_unlock(&EventQueueMutex);
218 void FreeAsyncIOContents(AsyncIO *IO)
220 FreeStrBuf(&IO->IOBuf);
221 FreeStrBuf(&IO->SendBuf.Buf);
222 FreeStrBuf(&IO->RecvBuf.Buf);
226 void StopClientWatchers(AsyncIO *IO)
228 ev_timer_stop(event_base, &IO->conn_fail);
229 ev_io_stop(event_base, &IO->conn_event);
230 ev_idle_stop(event_base, &IO->unwind_stack);
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);
240 void ShutDownCLient(AsyncIO *IO)
242 CitContext *Ctx =IO->CitContext;
245 syslog(LOG_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
247 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
248 StopClientWatchers(IO);
250 if (IO->DNSChannel != NULL) {
251 ares_destroy(IO->DNSChannel);
252 ev_io_stop(event_base, &IO->dns_recv_event);
253 ev_io_stop(event_base, &IO->dns_send_event);
254 IO->DNSChannel = NULL;
256 assert(IO->Terminate);
258 Ctx->state = CON_IDLE;
263 eReadState HandleInbound(AsyncIO *IO)
265 const char *Err = NULL;
266 eReadState Finished = eBufferNotEmpty;
268 become_session(IO->CitContext);
270 while ((Finished == eBufferNotEmpty) &&
271 ((IO->NextState == eReadMessage)||
272 (IO->NextState == eReadMore)||
273 (IO->NextState == eReadFile)||
274 (IO->NextState == eReadPayload)))
276 if (IO->RecvBuf.nBlobBytesWanted != 0) {
279 else { /* Reading lines... */
280 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
281 if ((IO->NextState == eReadFile) &&
282 (Finished == eBufferNotEmpty))
284 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
285 if (Finished == eReadSuccess)
287 IO->NextState = eSendReply;
290 else if (IO->LineReader)
291 Finished = IO->LineReader(IO);
293 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
296 case eMustReadMore: /// read new from socket...
298 case eBufferNotEmpty: /* shouldn't happen... */
299 case eReadSuccess: /// done for now...
301 case eReadFail: /// WHUT?
308 if (Finished != eMustReadMore) {
309 assert(IO->ReadDone);
310 ev_io_stop(event_base, &IO->recv_event);
311 IO->NextState = IO->ReadDone(IO);
312 Finished = StrBufCheckBuffer(&IO->RecvBuf);
316 switch (IO->NextState) {
318 ev_io_start(event_base, &IO->send_event);
322 assert(IO->SendDone);
323 IO->NextState = IO->SendDone(IO);
324 ev_io_start(event_base, &IO->send_event);
329 ev_io_start(event_base, &IO->recv_event);
331 case eTerminateConnection:
349 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
352 AsyncIO *IO = watcher->data;
353 const char *errmsg = NULL;
355 become_session(IO->CitContext);
361 const char *pch = ChrPtr(IO->SendBuf.Buf);
362 const char *pchh = IO->SendBuf.ReadWritePointer;
368 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
369 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
370 ((CitContext*)(IO->CitContext))->ServiceName,
373 fd = fopen(fn, "a+");
374 fprintf(fd, "Send: BufSize: %ld BufContent: [",
376 rv = fwrite(pchh, nbytes, 1, fd);
377 if (!rv) printf("failed to write debug to %s!\n", fn);
380 switch (IO->NextState) {
382 rc = FileSendChunked(&IO->IOB, &errmsg);
384 StrBufPlain(IO->ErrMsg, errmsg, -1);
387 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
391 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
397 ev_io_stop(event_base, &IO->send_event);
398 switch (IO->NextState) {
400 assert(IO->SendDone);
401 IO->NextState = IO->SendDone(IO);
403 if ((IO->NextState == eTerminateConnection) ||
404 (IO->NextState == eAbort) )
407 ev_io_start(event_base, &IO->send_event);
411 if (IO->IOB.ChunkSendRemain > 0) {
412 ev_io_start(event_base, &IO->recv_event);
414 assert(IO->ReadDone);
415 IO->NextState = IO->ReadDone(IO);
416 switch(IO->NextState) {
425 ev_io_start(event_base, &IO->send_event);
432 case eTerminateConnection:
439 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
441 IO->NextState = eReadMore;
446 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
450 ev_io_start(event_base, &IO->recv_event);
455 /* we now live in another queue, so we have to unregister. */
456 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
461 case eTerminateConnection:
470 /* else : must write more. */
473 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
476 switch(IO->NextState) {
480 ev_io_start(event_base, &IO->recv_event);
486 become_session(IO->CitContext);
487 IO_send_callback(loop, &IO->send_event, revents);
493 case eTerminateConnection:
501 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
503 AsyncIO *IO = watcher->data;
505 ev_timer_stop (event_base, &IO->rw_timeout);
506 become_session(IO->CitContext);
508 if (IO->SendBuf.fd != 0)
510 ev_io_stop(event_base, &IO->send_event);
511 ev_io_stop(event_base, &IO->recv_event);
512 ev_timer_stop (event_base, &IO->rw_timeout);
513 close(IO->SendBuf.fd);
514 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
518 switch (IO->Timeout(IO))
528 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
530 AsyncIO *IO = watcher->data;
532 ev_timer_stop (event_base, &IO->conn_fail);
534 if (IO->SendBuf.fd != 0)
536 ev_io_stop(loop, &IO->conn_event);
537 ev_io_stop(event_base, &IO->send_event);
538 ev_io_stop(event_base, &IO->recv_event);
539 ev_timer_stop (event_base, &IO->rw_timeout);
540 close(IO->SendBuf.fd);
541 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
543 become_session(IO->CitContext);
545 assert(IO->ConnFail);
546 switch (IO->ConnFail(IO))
557 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
559 AsyncIO *IO = watcher->data;
561 ev_idle_stop (event_base, &IO->conn_fail_immediate);
563 if (IO->SendBuf.fd != 0)
565 close(IO->SendBuf.fd);
566 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
568 become_session(IO->CitContext);
570 assert(IO->ConnFail);
571 switch (IO->ConnFail(IO))
582 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
584 AsyncIO *IO = watcher->data;
586 ev_io_stop(loop, &IO->conn_event);
587 ev_timer_stop (event_base, &IO->conn_fail);
588 set_start_callback(loop, IO, revents);
591 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
595 AsyncIO *IO = watcher->data;
597 switch (IO->NextState) {
599 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
601 StrBufPlain(IO->ErrMsg, errmsg, -1);
604 if (IO->IOB.ChunkSendRemain == 0)
606 IO->NextState = eSendReply;
613 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
622 const char *pch = ChrPtr(IO->RecvBuf.Buf);
623 const char *pchh = IO->RecvBuf.ReadWritePointer;
629 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
630 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
631 ((CitContext*)(IO->CitContext))->ServiceName,
634 fd = fopen(fn, "a+");
635 fprintf(fd, "Read: BufSize: %ld BufContent: [",
637 rv = fwrite(pchh, nbytes, 1, fd);
638 if (!rv) printf("failed to write debug to %s!\n", fn);
647 } else if (nbytes == 0) {
650 switch (IO->Timeout(IO))
658 } else if (nbytes == -1) {
659 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
661 "EVENT: Socket Invalid! %s \n",
669 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
671 AsyncIO *IO = watcher->data;
672 syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
673 become_session(IO->CitContext);
675 assert(IO->DNSQuery->PostDNS);
676 switch (IO->DNSQuery->PostDNS(IO))
685 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
690 IO->SendBuf.fd = IO->RecvBuf.fd =
692 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
696 if (IO->SendBuf.fd < 0) {
697 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
698 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
701 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
704 "EVENT: unable to get socket flags! %s \n",
706 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
709 fdflags = fdflags | O_NONBLOCK;
710 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
712 "EVENT: unable to set socket nonblocking flags! %s \n",
714 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
715 close(IO->SendBuf.fd);
716 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
719 /* TODO: maye we could use offsetof() to calc the position of data...
720 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
722 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
723 IO->recv_event.data = IO;
724 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
725 IO->send_event.data = IO;
727 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
728 IO->conn_fail.data = IO;
729 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
730 IO->rw_timeout.data = IO;
733 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
734 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
735 if (IO->ConnectMe->IPv6)
736 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
738 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
741 syslog(LOG_DEBUG, "connect() immediate success.\n");
742 set_start_callback(event_base, IO, 0);
743 ev_timer_start(event_base, &IO->rw_timeout);
744 return IO->NextState;
746 else if (errno == EINPROGRESS) {
747 syslog(LOG_DEBUG, "connect() have to wait now.\n");
749 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
750 IO->conn_event.data = IO;
752 ev_io_start(event_base, &IO->conn_event);
753 ev_timer_start(event_base, &IO->conn_fail);
754 return IO->NextState;
757 ev_idle_init(&IO->conn_fail_immediate,
758 IO_connfailimmediate_callback);
759 IO->conn_fail_immediate.data = IO;
760 ev_idle_start(event_base, &IO->conn_fail_immediate);
762 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
763 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
764 return IO->NextState;
766 return IO->NextState;
769 void SetNextTimeout(AsyncIO *IO, double timeout)
771 IO->rw_timeout.repeat = timeout;
772 ev_timer_again (event_base, &IO->rw_timeout);
775 eNextState InitEventIO(AsyncIO *IO,
778 double first_rw_timeout,
782 become_session(IO->CitContext);
785 IO->NextState = eReadMessage;
788 IO->NextState = eSendReply;
790 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
793 eNextState ReAttachIO(AsyncIO *IO,
798 become_session(IO->CitContext);
799 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
801 IO->NextState = eReadMessage;
804 IO->NextState = eSendReply;
806 set_start_callback(event_base, IO, 0);
808 return IO->NextState;