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))
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 pthread_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 eNextState 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 pthread_mutex_lock(&EventQueueMutex);
194 syslog(LOG_DEBUG, "EVENT Q\n");
196 Put(InboundEventQueue, IKEY(i), h, NULL);
197 pthread_mutex_unlock(&EventQueueMutex);
199 ev_async_send (event_base, &AddJob);
200 syslog(LOG_DEBUG, "EVENT Q Done.\n");
204 int ShutDownEventQueue(void)
206 pthread_mutex_lock(&DBEventQueueMutex);
207 ev_async_send (event_db, &DBExitEventLoop);
208 pthread_mutex_unlock(&DBEventQueueMutex);
210 pthread_mutex_lock(&EventQueueMutex);
211 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
212 pthread_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 syslog(LOG_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...
285 case eBufferNotEmpty: /* shouldn't happen... */
286 case eReadSuccess: /// done for now...
288 case eReadFail: /// WHUT?
295 if (Finished != eMustReadMore) {
296 assert(IO->ReadDone);
297 ev_io_stop(event_base, &IO->recv_event);
298 IO->NextState = IO->ReadDone(IO);
299 Finished = StrBufCheckBuffer(&IO->RecvBuf);
303 switch (IO->NextState) {
306 assert(IO->SendDone);
307 IO->NextState = IO->SendDone(IO);
308 ev_io_start(event_base, &IO->send_event);
312 ev_io_start(event_base, &IO->recv_event);
314 case eTerminateConnection:
330 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
333 AsyncIO *IO = watcher->data;
335 become_session(IO->CitContext);
341 const char *pch = ChrPtr(IO->SendBuf.Buf);
342 const char *pchh = IO->SendBuf.ReadWritePointer;
348 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
349 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
350 ((CitContext*)(IO->CitContext))->ServiceName,
353 fd = fopen(fn, "a+");
354 fprintf(fd, "Send: BufSize: %ld BufContent: [",
356 rv = fwrite(pchh, nbytes, 1, fd);
357 if (!rv) printf("failed to write debug to %s!\n", fn);
360 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
363 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
369 ev_io_stop(event_base, &IO->send_event);
370 switch (IO->NextState) {
372 assert(IO->SendDone);
373 IO->NextState = IO->SendDone(IO);
375 if ((IO->NextState == eTerminateConnection) ||
376 (IO->NextState == eAbort) )
379 ev_io_start(event_base, &IO->send_event);
383 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
385 IO->NextState = eReadMore;
389 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
393 ev_io_start(event_base, &IO->recv_event);
398 /* we now live in another queue, so we have to unregister. */
399 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
404 case eTerminateConnection:
413 /* else : must write more. */
416 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
419 switch(IO->NextState) {
422 ev_io_start(event_base, &IO->recv_event);
427 become_session(IO->CitContext);
428 IO_send_callback(loop, &IO->send_event, revents);
434 case eTerminateConnection:
442 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
444 AsyncIO *IO = watcher->data;
446 ev_timer_stop (event_base, &IO->rw_timeout);
447 become_session(IO->CitContext);
449 if (IO->SendBuf.fd != 0)
451 ev_io_stop(event_base, &IO->send_event);
452 ev_io_stop(event_base, &IO->recv_event);
453 ev_timer_stop (event_base, &IO->rw_timeout);
454 close(IO->SendBuf.fd);
455 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
459 switch (IO->Timeout(IO))
469 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
471 AsyncIO *IO = watcher->data;
473 ev_timer_stop (event_base, &IO->conn_fail);
475 if (IO->SendBuf.fd != 0)
477 ev_io_stop(loop, &IO->conn_event);
478 ev_io_stop(event_base, &IO->send_event);
479 ev_io_stop(event_base, &IO->recv_event);
480 ev_timer_stop (event_base, &IO->rw_timeout);
481 close(IO->SendBuf.fd);
482 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
484 become_session(IO->CitContext);
486 assert(IO->ConnFail);
487 switch (IO->ConnFail(IO))
498 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
500 AsyncIO *IO = watcher->data;
502 ev_idle_stop (event_base, &IO->conn_fail_immediate);
504 if (IO->SendBuf.fd != 0)
506 close(IO->SendBuf.fd);
507 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
509 become_session(IO->CitContext);
511 assert(IO->ConnFail);
512 switch (IO->ConnFail(IO))
523 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
525 AsyncIO *IO = watcher->data;
527 ev_io_stop(loop, &IO->conn_event);
528 ev_timer_stop (event_base, &IO->conn_fail);
529 set_start_callback(loop, IO, revents);
532 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
535 AsyncIO *IO = watcher->data;
537 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
543 const char *pch = ChrPtr(IO->RecvBuf.Buf);
544 const char *pchh = IO->RecvBuf.ReadWritePointer;
550 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
551 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
552 ((CitContext*)(IO->CitContext))->ServiceName,
555 fd = fopen(fn, "a+");
556 fprintf(fd, "Read: BufSize: %ld BufContent: [",
558 rv = fwrite(pchh, nbytes, 1, fd);
559 if (!rv) printf("failed to write debug to %s!\n", fn);
568 } else if (nbytes == 0) {
571 switch (IO->Timeout(IO))
579 } else if (nbytes == -1) {
580 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
582 "EVENT: Socket Invalid! %s \n",
589 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
591 AsyncIO *IO = watcher->data;
592 syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
593 become_session(IO->CitContext);
595 switch (IO->DNSQuery->PostDNS(IO))
604 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
609 IO->SendBuf.fd = IO->RecvBuf.fd =
611 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
615 if (IO->SendBuf.fd < 0) {
616 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
617 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
620 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
623 "EVENT: unable to get socket flags! %s \n",
625 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
628 fdflags = fdflags | O_NONBLOCK;
629 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
631 "EVENT: unable to set socket nonblocking flags! %s \n",
633 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
634 close(IO->SendBuf.fd);
635 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
638 /* TODO: maye we could use offsetof() to calc the position of data...
639 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
641 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
642 IO->recv_event.data = IO;
643 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
644 IO->send_event.data = IO;
646 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
647 IO->conn_fail.data = IO;
648 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
649 IO->rw_timeout.data = IO;
652 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
653 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
654 if (IO->ConnectMe->IPv6)
655 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
657 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
660 syslog(LOG_DEBUG, "connect() immediate success.\n");
661 set_start_callback(event_base, IO, 0);
662 ev_timer_start(event_base, &IO->rw_timeout);
663 return IO->NextState;
665 else if (errno == EINPROGRESS) {
666 syslog(LOG_DEBUG, "connect() have to wait now.\n");
668 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
669 IO->conn_event.data = IO;
671 ev_io_start(event_base, &IO->conn_event);
672 ev_timer_start(event_base, &IO->conn_fail);
673 return IO->NextState;
676 ev_idle_init(&IO->conn_fail_immediate,
677 IO_connfailimmediate_callback);
678 IO->conn_fail_immediate.data = IO;
679 ev_idle_start(event_base, &IO->conn_fail_immediate);
681 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
682 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
683 return IO->NextState;
685 return IO->NextState;
688 void SetNextTimeout(AsyncIO *IO, double timeout)
690 IO->rw_timeout.repeat = timeout;
691 ev_timer_again (event_base, &IO->rw_timeout);
694 eNextState InitEventIO(AsyncIO *IO,
697 double first_rw_timeout,
701 become_session(IO->CitContext);
704 IO->NextState = eReadMessage;
707 IO->NextState = eSendReply;
709 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
712 eNextState ReAttachIO(AsyncIO *IO,
717 become_session(IO->CitContext);
718 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
720 IO->NextState = eReadMessage;
723 IO->NextState = eSendReply;
725 set_start_callback(event_base, IO, 0);
727 return IO->NextState;