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 == eReadPayload)))
275 if (IO->RecvBuf.nBlobBytesWanted != 0) {
278 else { /* Reading lines... */
279 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
281 Finished = IO->LineReader(IO);
283 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
286 case eMustReadMore: /// read new from socket...
288 case eBufferNotEmpty: /* shouldn't happen... */
289 case eReadSuccess: /// done for now...
291 case eReadFail: /// WHUT?
298 if (Finished != eMustReadMore) {
299 assert(IO->ReadDone);
300 ev_io_stop(event_base, &IO->recv_event);
301 IO->NextState = IO->ReadDone(IO);
302 Finished = StrBufCheckBuffer(&IO->RecvBuf);
303 if ((IO->NextState == eReadFile) &&
304 (Finished == eBufferNotEmpty))
306 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
307 if (Finished == eReadSuccess)
309 IO->NextState = eSendReply;
315 switch (IO->NextState) {
317 ev_io_start(event_base, &IO->send_event);
321 assert(IO->SendDone);
322 IO->NextState = IO->SendDone(IO);
323 ev_io_start(event_base, &IO->send_event);
328 ev_io_start(event_base, &IO->recv_event);
330 case eTerminateConnection:
348 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
351 AsyncIO *IO = watcher->data;
352 const char *errmsg = NULL;
354 become_session(IO->CitContext);
360 const char *pch = ChrPtr(IO->SendBuf.Buf);
361 const char *pchh = IO->SendBuf.ReadWritePointer;
367 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
368 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
369 ((CitContext*)(IO->CitContext))->ServiceName,
372 fd = fopen(fn, "a+");
373 fprintf(fd, "Send: BufSize: %ld BufContent: [",
375 rv = fwrite(pchh, nbytes, 1, fd);
376 if (!rv) printf("failed to write debug to %s!\n", fn);
379 switch (IO->NextState) {
381 rc = FileSendChunked(&IO->IOB, &errmsg);
383 StrBufPlain(IO->ErrMsg, errmsg, -1);
386 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
390 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
396 ev_io_stop(event_base, &IO->send_event);
397 switch (IO->NextState) {
399 assert(IO->SendDone);
400 IO->NextState = IO->SendDone(IO);
402 if ((IO->NextState == eTerminateConnection) ||
403 (IO->NextState == eAbort) )
406 ev_io_start(event_base, &IO->send_event);
410 if (IO->IOB.ChunkSendRemain > 0) {
411 ev_io_start(event_base, &IO->recv_event);
413 assert(IO->ReadDone);
414 IO->NextState = IO->ReadDone(IO);
415 switch(IO->NextState) {
424 ev_io_start(event_base, &IO->send_event);
431 case eTerminateConnection:
438 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
440 IO->NextState = eReadMore;
445 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
449 ev_io_start(event_base, &IO->recv_event);
454 /* we now live in another queue, so we have to unregister. */
455 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
460 case eTerminateConnection:
469 /* else : must write more. */
472 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
475 switch(IO->NextState) {
479 ev_io_start(event_base, &IO->recv_event);
485 become_session(IO->CitContext);
486 IO_send_callback(loop, &IO->send_event, revents);
492 case eTerminateConnection:
500 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
502 AsyncIO *IO = watcher->data;
504 ev_timer_stop (event_base, &IO->rw_timeout);
505 become_session(IO->CitContext);
507 if (IO->SendBuf.fd != 0)
509 ev_io_stop(event_base, &IO->send_event);
510 ev_io_stop(event_base, &IO->recv_event);
511 ev_timer_stop (event_base, &IO->rw_timeout);
512 close(IO->SendBuf.fd);
513 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
517 switch (IO->Timeout(IO))
527 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
529 AsyncIO *IO = watcher->data;
531 ev_timer_stop (event_base, &IO->conn_fail);
533 if (IO->SendBuf.fd != 0)
535 ev_io_stop(loop, &IO->conn_event);
536 ev_io_stop(event_base, &IO->send_event);
537 ev_io_stop(event_base, &IO->recv_event);
538 ev_timer_stop (event_base, &IO->rw_timeout);
539 close(IO->SendBuf.fd);
540 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
542 become_session(IO->CitContext);
544 assert(IO->ConnFail);
545 switch (IO->ConnFail(IO))
556 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
558 AsyncIO *IO = watcher->data;
560 ev_idle_stop (event_base, &IO->conn_fail_immediate);
562 if (IO->SendBuf.fd != 0)
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_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
583 AsyncIO *IO = watcher->data;
585 ev_io_stop(loop, &IO->conn_event);
586 ev_timer_stop (event_base, &IO->conn_fail);
587 set_start_callback(loop, IO, revents);
590 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
595 AsyncIO *IO = watcher->data;
597 switch (IO->NextState) {
599 rc = FileRecvChunked(&IO->IOB, &errmsg);
601 StrBufPlain(IO->ErrMsg, errmsg, -1);
604 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
612 const char *pch = ChrPtr(IO->RecvBuf.Buf);
613 const char *pchh = IO->RecvBuf.ReadWritePointer;
619 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
620 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
621 ((CitContext*)(IO->CitContext))->ServiceName,
624 fd = fopen(fn, "a+");
625 fprintf(fd, "Read: BufSize: %ld BufContent: [",
627 rv = fwrite(pchh, nbytes, 1, fd);
628 if (!rv) printf("failed to write debug to %s!\n", fn);
637 } else if (nbytes == 0) {
640 switch (IO->Timeout(IO))
648 } else if (nbytes == -1) {
649 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
651 "EVENT: Socket Invalid! %s \n",
658 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
660 AsyncIO *IO = watcher->data;
661 syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
662 become_session(IO->CitContext);
664 switch (IO->DNSQuery->PostDNS(IO))
673 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
678 IO->SendBuf.fd = IO->RecvBuf.fd =
680 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
684 if (IO->SendBuf.fd < 0) {
685 syslog(LOG_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
686 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
689 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
692 "EVENT: unable to get socket flags! %s \n",
694 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
697 fdflags = fdflags | O_NONBLOCK;
698 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
700 "EVENT: unable to set socket nonblocking flags! %s \n",
702 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
703 close(IO->SendBuf.fd);
704 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
707 /* TODO: maye we could use offsetof() to calc the position of data...
708 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
710 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
711 IO->recv_event.data = IO;
712 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
713 IO->send_event.data = IO;
715 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
716 IO->conn_fail.data = IO;
717 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
718 IO->rw_timeout.data = IO;
721 /* Bypass it like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
722 /// ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr = inet_addr("127.0.0.1");
723 if (IO->ConnectMe->IPv6)
724 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
726 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
729 syslog(LOG_DEBUG, "connect() immediate success.\n");
730 set_start_callback(event_base, IO, 0);
731 ev_timer_start(event_base, &IO->rw_timeout);
732 return IO->NextState;
734 else if (errno == EINPROGRESS) {
735 syslog(LOG_DEBUG, "connect() have to wait now.\n");
737 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
738 IO->conn_event.data = IO;
740 ev_io_start(event_base, &IO->conn_event);
741 ev_timer_start(event_base, &IO->conn_fail);
742 return IO->NextState;
745 ev_idle_init(&IO->conn_fail_immediate,
746 IO_connfailimmediate_callback);
747 IO->conn_fail_immediate.data = IO;
748 ev_idle_start(event_base, &IO->conn_fail_immediate);
750 syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
751 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
752 return IO->NextState;
754 return IO->NextState;
757 void SetNextTimeout(AsyncIO *IO, double timeout)
759 IO->rw_timeout.repeat = timeout;
760 ev_timer_again (event_base, &IO->rw_timeout);
763 eNextState InitEventIO(AsyncIO *IO,
766 double first_rw_timeout,
770 become_session(IO->CitContext);
773 IO->NextState = eReadMessage;
776 IO->NextState = eSendReply;
778 return event_connect_socket(IO, conn_timeout, first_rw_timeout);
781 eNextState ReAttachIO(AsyncIO *IO,
786 become_session(IO->CitContext);
787 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
789 IO->NextState = eReadMessage;
792 IO->NextState = eSendReply;
794 set_start_callback(event_base, IO, 0);
796 return IO->NextState;