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);
600 syslog(LOG_DEBUG, "****************nbytes: %ld ChunkRemain: %ldx.\n",
601 nbytes, IO->IOB.ChunkSendRemain);
603 StrBufPlain(IO->ErrMsg, errmsg, -1);
606 if (IO->IOB.ChunkSendRemain == 0)
608 IO->NextState = eSendReply;
609 syslog(LOG_DEBUG, "***********************************xxxx.\n");
616 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
625 const char *pch = ChrPtr(IO->RecvBuf.Buf);
626 const char *pchh = IO->RecvBuf.ReadWritePointer;
632 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
633 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
634 ((CitContext*)(IO->CitContext))->ServiceName,
637 fd = fopen(fn, "a+");
638 fprintf(fd, "Read: BufSize: %ld BufContent: [",
640 rv = fwrite(pchh, nbytes, 1, fd);
641 if (!rv) printf("failed to write debug to %s!\n", fn);
650 } else if (nbytes == 0) {
653 switch (IO->Timeout(IO))
661 } else if (nbytes == -1) {
662 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
664 "EVENT: Socket Invalid! %s \n",
672 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
674 AsyncIO *IO = watcher->data;
675 syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
676 become_session(IO->CitContext);
678 assert(IO->DNSQuery->PostDNS);
679 switch (IO->DNSQuery->PostDNS(IO))
688 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
693 IO->SendBuf.fd = IO->RecvBuf.fd =
695 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
699 if (IO->SendBuf.fd < 0) {
700 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
701 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
704 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
707 "EVENT: unable to get socket flags! %s \n",
709 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
712 fdflags = fdflags | O_NONBLOCK;
713 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
715 "EVENT: unable to set socket nonblocking flags! %s \n",
717 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
718 close(IO->SendBuf.fd);
719 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
722 /* TODO: maye we could use offsetof() to calc the position of data...
723 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
725 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
726 IO->recv_event.data = IO;
727 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
728 IO->send_event.data = IO;
730 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
731 IO->conn_fail.data = IO;
732 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
733 IO->rw_timeout.data = IO;
736 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
737 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
738 if (IO->ConnectMe->IPv6)
739 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
741 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
744 syslog(LOG_DEBUG, "connect() immediate success.\n");
745 set_start_callback(event_base, IO, 0);
746 ev_timer_start(event_base, &IO->rw_timeout);
747 return IO->NextState;
749 else if (errno == EINPROGRESS) {
750 syslog(LOG_DEBUG, "connect() have to wait now.\n");
752 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
753 IO->conn_event.data = IO;
755 ev_io_start(event_base, &IO->conn_event);
756 ev_timer_start(event_base, &IO->conn_fail);
757 return IO->NextState;
760 ev_idle_init(&IO->conn_fail_immediate,
761 IO_connfailimmediate_callback);
762 IO->conn_fail_immediate.data = IO;
763 ev_idle_start(event_base, &IO->conn_fail_immediate);
765 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
766 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
767 return IO->NextState;
769 return IO->NextState;
772 void SetNextTimeout(AsyncIO *IO, double timeout)
774 IO->rw_timeout.repeat = timeout;
775 ev_timer_again (event_base, &IO->rw_timeout);
778 eNextState InitEventIO(AsyncIO *IO,
781 double first_rw_timeout,
785 become_session(IO->CitContext);
788 IO->NextState = eReadMessage;
791 IO->NextState = eSendReply;
793 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
796 eNextState ReAttachIO(AsyncIO *IO,
801 become_session(IO->CitContext);
802 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
804 IO->NextState = eReadMessage;
807 IO->NextState = eSendReply;
809 set_start_callback(event_base, IO, 0);
811 return IO->NextState;