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 CtdlLogPrintf(CTDL_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 citthread_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 int QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
95 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
98 ev_cleanup_init(&IO->abort_by_shutdown,
99 IO_abort_shutdown_callback);
100 IO->abort_by_shutdown.data = IO;
101 ev_cleanup_start(event_db, &IO->abort_by_shutdown);
103 citthread_mutex_lock(&DBEventQueueMutex);
104 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT Q\n");
106 Put(DBInboundEventQueue, IKEY(i), h, NULL);
107 citthread_mutex_unlock(&DBEventQueueMutex);
109 ev_async_send (event_db, &DBAddJob);
110 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT Q Done.\n");
114 void ShutDownDBCLient(AsyncIO *IO)
116 CitContext *Ctx =IO->CitContext;
119 CtdlLogPrintf(CTDL_DEBUG, "DBEVENT\n");
120 ev_cleanup_stop(event_db, &IO->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 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
134 become_session(IO->CitContext);
136 ev_idle_stop(event_db, &IO->unwind_stack);
138 assert(IO->ReadDone);
139 switch (IO->ReadDone(IO))
142 ShutDownDBCLient(IO);
148 void NextDBOperation(AsyncIO *IO, IO_CallBack CB)
151 ev_idle_init(&IO->unwind_stack,
153 IO->unwind_stack.data = IO;
154 ev_idle_start(event_db, &IO->unwind_stack);
157 /*--------------------------------------------------------------------------------
160 extern int evbase_count;
161 extern citthread_mutex_t EventQueueMutex;
162 extern HashList *InboundEventQueue;
163 extern struct ev_loop *event_base;
164 extern ev_async AddJob;
165 extern ev_async ExitEventLoop;
168 int QueueEventContext(AsyncIO *IO, IO_CallBack CB)
173 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
176 ev_cleanup_init(&IO->abort_by_shutdown,
177 IO_abort_shutdown_callback);
178 IO->abort_by_shutdown.data = IO;
179 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
181 citthread_mutex_lock(&EventQueueMutex);
182 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
184 Put(InboundEventQueue, IKEY(i), h, NULL);
185 citthread_mutex_unlock(&EventQueueMutex);
187 ev_async_send (event_base, &AddJob);
188 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
192 int ShutDownEventQueue(void)
194 citthread_mutex_lock(&DBEventQueueMutex);
195 ev_async_send (event_db, &DBExitEventLoop);
196 citthread_mutex_unlock(&DBEventQueueMutex);
198 citthread_mutex_lock(&EventQueueMutex);
199 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
200 citthread_mutex_unlock(&EventQueueMutex);
204 void FreeAsyncIOContents(AsyncIO *IO)
206 FreeStrBuf(&IO->IOBuf);
207 FreeStrBuf(&IO->SendBuf.Buf);
208 FreeStrBuf(&IO->RecvBuf.Buf);
212 void StopClientWatchers(AsyncIO *IO)
214 ev_timer_stop(event_base, &IO->conn_fail);
215 ev_io_stop(event_base, &IO->conn_event);
216 ev_idle_stop(event_base, &IO->unwind_stack);
218 if (IO->SendBuf.fd != 0)
220 ev_io_stop(event_base, &IO->send_event);
221 ev_io_stop(event_base, &IO->recv_event);
222 ev_timer_stop (event_base, &IO->rw_timeout);
223 close(IO->SendBuf.fd);
229 void ShutDownCLient(AsyncIO *IO)
231 CitContext *Ctx =IO->CitContext;
234 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
236 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
237 StopClientWatchers(IO);
239 if (IO->DNSChannel != NULL) {
240 ares_destroy(IO->DNSChannel);
241 ev_io_stop(event_base, &IO->dns_recv_event);
242 ev_io_stop(event_base, &IO->dns_send_event);
243 IO->DNSChannel = NULL;
245 assert(IO->Terminate);
247 Ctx->state = CON_IDLE;
252 eReadState HandleInbound(AsyncIO *IO)
254 eReadState Finished = eBufferNotEmpty;
256 become_session(IO->CitContext);
258 while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
259 if (IO->RecvBuf.nBlobBytesWanted != 0) {
262 else { /* Reading lines... */
263 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
265 Finished = IO->LineReader(IO);
267 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
270 case eMustReadMore: /// read new from socket...
273 case eBufferNotEmpty: /* shouldn't happen... */
274 case eReadSuccess: /// done for now...
276 case eReadFail: /// WHUT?
283 if (Finished != eMustReadMore) {
284 assert(IO->ReadDone);
285 ev_io_stop(event_base, &IO->recv_event);
286 IO->NextState = IO->ReadDone(IO);
287 Finished = StrBufCheckBuffer(&IO->RecvBuf);
292 if ((IO->NextState == eSendReply) ||
293 (IO->NextState == eSendMore))
295 assert(IO->SendDone);
296 IO->NextState = IO->SendDone(IO);
297 ev_io_start(event_base, &IO->send_event);
299 else if ((IO->NextState == eTerminateConnection) ||
300 (IO->NextState == eAbort) )
307 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
310 AsyncIO *IO = watcher->data;
312 become_session(IO->CitContext);
313 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
322 const char *pch = ChrPtr(IO->SendBuf.Buf);
323 const char *pchh = IO->SendBuf.ReadWritePointer;
329 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
330 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->SendBuf.fd);
332 fd = fopen(fn, "a+");
333 fprintf(fd, "Read: BufSize: %ld BufContent: [",
335 rv = fwrite(pchh, nbytes, 1, fd);
336 if (!rv) printf("failed to write debug!");
343 ev_io_stop(event_base, &IO->send_event);
344 switch (IO->NextState) {
348 assert(IO->SendDone);
349 IO->NextState = IO->SendDone(IO);
351 if ((IO->NextState == eTerminateConnection) ||
352 (IO->NextState == eAbort) )
355 ev_io_start(event_base, &IO->send_event);
359 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
363 ev_io_start(event_base, &IO->recv_event);
370 case eTerminateConnection:
379 /* else : must write more. */
382 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
385 switch(IO->NextState) {
387 ev_io_start(event_base, &IO->recv_event);
391 become_session(IO->CitContext);
392 IO_send_callback(loop, &IO->send_event, revents);
397 case eTerminateConnection:
405 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
407 AsyncIO *IO = watcher->data;
409 ev_timer_stop (event_base, &IO->rw_timeout);
410 become_session(IO->CitContext);
412 if (IO->SendBuf.fd != 0)
414 ev_io_stop(event_base, &IO->send_event);
415 ev_io_stop(event_base, &IO->recv_event);
416 ev_timer_stop (event_base, &IO->rw_timeout);
417 close(IO->SendBuf.fd);
418 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
422 switch (IO->Timeout(IO))
432 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
434 AsyncIO *IO = watcher->data;
436 ev_timer_stop (event_base, &IO->conn_fail);
438 if (IO->SendBuf.fd != 0)
440 ev_io_stop(loop, &IO->conn_event);
441 ev_io_stop(event_base, &IO->send_event);
442 ev_io_stop(event_base, &IO->recv_event);
443 ev_timer_stop (event_base, &IO->rw_timeout);
444 close(IO->SendBuf.fd);
445 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
447 become_session(IO->CitContext);
449 assert(IO->ConnFail);
450 switch (IO->ConnFail(IO))
461 IO_connfailimmediate_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
463 AsyncIO *IO = watcher->data;
465 ev_idle_stop (event_base, &IO->conn_fail_immediate);
467 if (IO->SendBuf.fd != 0)
469 close(IO->SendBuf.fd);
470 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
472 become_session(IO->CitContext);
474 assert(IO->ConnFail);
475 switch (IO->ConnFail(IO))
486 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
488 AsyncIO *IO = watcher->data;
490 ev_io_stop(loop, &IO->conn_event);
491 ev_timer_stop (event_base, &IO->conn_fail);
492 set_start_callback(loop, IO, revents);
495 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
498 AsyncIO *IO = watcher->data;
500 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
503 } else if (nbytes == 0) {
506 switch (IO->Timeout(IO))
514 } else if (nbytes == -1) {
515 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
521 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
523 AsyncIO *IO = watcher->data;
524 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
525 become_session(IO->CitContext);
527 switch (IO->DNSQuery->PostDNS(IO))
536 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
541 IO->SendBuf.fd = IO->RecvBuf.fd =
543 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
547 if (IO->SendBuf.fd < 0) {
548 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
549 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
552 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
554 CtdlLogPrintf(CTDL_DEBUG,
555 "EVENT: unable to get socket flags! %s \n",
557 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
560 fdflags = fdflags | O_NONBLOCK;
561 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
562 CtdlLogPrintf(CTDL_DEBUG,
563 "EVENT: unable to set socket nonblocking flags! %s \n",
565 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
566 close(IO->SendBuf.fd);
567 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
570 /* TODO: maye we could use offsetof() to calc the position of data...
571 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
573 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
574 IO->recv_event.data = IO;
575 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
576 IO->send_event.data = IO;
578 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
579 IO->conn_fail.data = IO;
580 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
581 IO->rw_timeout.data = IO;
583 if (IO->ConnectMe->IPv6)
584 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
586 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
589 CtdlLogPrintf(CTDL_DEBUG, "connect() immediate success.\n");
590 set_start_callback(event_base, IO, 0);
591 ev_timer_start(event_base, &IO->rw_timeout);
592 return IO->NextState;
594 else if (errno == EINPROGRESS) {
595 CtdlLogPrintf(CTDL_DEBUG, "connect() have to wait now.\n");
597 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
598 IO->conn_event.data = IO;
600 ev_io_start(event_base, &IO->conn_event);
601 ev_timer_start(event_base, &IO->conn_fail);
602 return IO->NextState;
605 ev_idle_init(&IO->conn_fail_immediate,
606 IO_connfailimmediate_callback);
607 IO->conn_fail_immediate.data = IO;
608 ev_idle_start(event_base, &IO->conn_fail_immediate);
610 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
611 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
612 return IO->NextState;
614 return IO->NextState;
617 void SetNextTimeout(AsyncIO *IO, double timeout)
619 IO->rw_timeout.repeat = timeout;
620 ev_timer_again (event_base, &IO->rw_timeout);
623 eNextState InitEventIO(AsyncIO *IO,
626 double first_rw_timeout,
630 become_session(IO->CitContext);
633 IO->NextState = eReadMessage;
636 IO->NextState = eSendReply;
638 return event_connect_socket(IO, conn_timeout, first_rw_timeout);