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 extern citthread_mutex_t EventQueueMutex;
71 extern HashList *InboundEventQueue;
72 extern struct ev_loop *event_base;
73 extern ev_async AddJob;
74 extern ev_async ExitEventLoop;
77 IO_abort_shutdown_callback(struct ev_loop *loop, ev_cleanup *watcher, int revents)
79 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
81 AsyncIO *IO = watcher->data;
82 IO->ShutdownAbort(IO);
85 int QueueEventContext(AsyncIO *IO, IO_CallBack CB)
90 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
93 ev_cleanup_init(&IO->abort_by_shutdown,
94 IO_abort_shutdown_callback);
95 IO->abort_by_shutdown.data = IO;
96 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
98 citthread_mutex_lock(&EventQueueMutex);
99 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
100 i = GetCount(InboundEventQueue);
101 Put(InboundEventQueue, IKEY(i), h, NULL);
102 citthread_mutex_unlock(&EventQueueMutex);
104 ev_async_send (event_base, &AddJob);
105 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
110 int ShutDownEventQueue(void)
112 citthread_mutex_lock(&EventQueueMutex);
113 ev_async_send (EV_DEFAULT_ &ExitEventLoop);
114 citthread_mutex_unlock(&EventQueueMutex);
118 void FreeAsyncIOContents(AsyncIO *IO)
120 FreeStrBuf(&IO->IOBuf);
121 FreeStrBuf(&IO->SendBuf.Buf);
122 FreeStrBuf(&IO->RecvBuf.Buf);
126 void StopClientWatchers(AsyncIO *IO)
128 ev_timer_stop(event_base, &IO->conn_fail);
129 ev_io_stop(event_base, &IO->conn_event);
130 ev_idle_stop(event_base, &IO->unwind_stack);
132 if (IO->SendBuf.fd != 0)
134 ev_io_stop(event_base, &IO->send_event);
135 ev_io_stop(event_base, &IO->recv_event);
136 ev_timer_stop (event_base, &IO->rw_timeout);
137 close(IO->SendBuf.fd);
143 void ShutDownCLient(AsyncIO *IO)
145 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->SendBuf.fd);
146 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
148 StopClientWatchers(IO);
150 if (IO->DNSChannel != NULL) {
151 ares_destroy(IO->DNSChannel);
152 ev_io_stop(event_base, &IO->dns_recv_event);
153 ev_io_stop(event_base, &IO->dns_send_event);
154 IO->DNSChannel = NULL;
156 assert(IO->Terminate);
157 become_session(IO->CitContext);
163 eReadState HandleInbound(AsyncIO *IO)
165 eReadState Finished = eBufferNotEmpty;
167 become_session(IO->CitContext);
169 while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
170 if (IO->RecvBuf.nBlobBytesWanted != 0) {
173 else { /* Reading lines... */
174 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
176 Finished = IO->LineReader(IO);
178 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
181 case eMustReadMore: /// read new from socket...
184 case eBufferNotEmpty: /* shouldn't happen... */
185 case eReadSuccess: /// done for now...
187 case eReadFail: /// WHUT?
194 if (Finished != eMustReadMore) {
195 assert(IO->ReadDone);
196 ev_io_stop(event_base, &IO->recv_event);
197 IO->NextState = IO->ReadDone(IO);
198 Finished = StrBufCheckBuffer(&IO->RecvBuf);
203 if ((IO->NextState == eSendReply) ||
204 (IO->NextState == eSendMore))
206 assert(IO->SendDone);
207 IO->NextState = IO->SendDone(IO);
208 ev_io_start(event_base, &IO->send_event);
210 else if ((IO->NextState == eTerminateConnection) ||
211 (IO->NextState == eAbort) )
218 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
221 AsyncIO *IO = watcher->data;
223 become_session(IO->CitContext);
224 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
233 const char *pch = ChrPtr(IO->SendBuf.Buf);
234 const char *pchh = IO->SendBuf.ReadWritePointer;
240 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
241 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->SendBuf.fd);
243 fd = fopen(fn, "a+");
244 fprintf(fd, "Read: BufSize: %ld BufContent: [",
246 rv = fwrite(pchh, nbytes, 1, fd);
253 ev_io_stop(event_base, &IO->send_event);
254 switch (IO->NextState) {
258 assert(IO->SendDone);
259 IO->NextState = IO->SendDone(IO);
261 if ((IO->NextState == eTerminateConnection) ||
262 (IO->NextState == eAbort) )
265 ev_io_start(event_base, &IO->send_event);
269 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
273 ev_io_start(event_base, &IO->recv_event);
280 case eTerminateConnection:
289 /* else : must write more. */
292 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
295 switch(IO->NextState) {
297 ev_io_start(event_base, &IO->recv_event);
301 become_session(IO->CitContext);
302 IO_send_callback(loop, &IO->send_event, revents);
307 case eTerminateConnection:
315 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
317 AsyncIO *IO = watcher->data;
319 ev_timer_stop (event_base, &IO->rw_timeout);
320 become_session(IO->CitContext);
322 if (IO->SendBuf.fd != 0)
324 ev_io_stop(event_base, &IO->send_event);
325 ev_io_stop(event_base, &IO->recv_event);
326 ev_timer_stop (event_base, &IO->rw_timeout);
327 close(IO->SendBuf.fd);
328 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
332 switch (IO->Timeout(IO))
341 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
343 AsyncIO *IO = watcher->data;
345 ev_timer_stop (event_base, &IO->conn_fail);
347 if (IO->SendBuf.fd != 0)
349 ev_io_stop(loop, &IO->conn_event);
350 ev_io_stop(event_base, &IO->send_event);
351 ev_io_stop(event_base, &IO->recv_event);
352 ev_timer_stop (event_base, &IO->rw_timeout);
353 close(IO->SendBuf.fd);
354 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
356 become_session(IO->CitContext);
358 assert(IO->ConnFail);
359 switch (IO->ConnFail(IO))
369 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
371 AsyncIO *IO = watcher->data;
373 ev_io_stop(loop, &IO->conn_event);
374 ev_timer_stop (event_base, &IO->conn_fail);
375 set_start_callback(loop, IO, revents);
378 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
381 AsyncIO *IO = watcher->data;
383 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
386 } else if (nbytes == 0) {
389 switch (IO->Timeout(IO))
397 } else if (nbytes == -1) {
398 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
404 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
406 AsyncIO *IO = watcher->data;
407 CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
408 become_session(IO->CitContext);
410 switch (IO->DNSQuery->PostDNS(IO))
419 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
424 IO->SendBuf.fd = IO->RecvBuf.fd =
426 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
430 if (IO->SendBuf.fd < 0) {
431 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
432 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
433 // freeaddrinfo(res);
436 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
438 CtdlLogPrintf(CTDL_DEBUG,
439 "EVENT: unable to get socket flags! %s \n",
441 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
444 fdflags = fdflags | O_NONBLOCK;
445 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
446 CtdlLogPrintf(CTDL_DEBUG,
447 "EVENT: unable to set socket nonblocking flags! %s \n",
449 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
450 close(IO->SendBuf.fd);
451 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
454 /* TODO: maye we could use offsetof() to calc the position of data...
455 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
457 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
458 IO->recv_event.data = IO;
459 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
460 IO->send_event.data = IO;
462 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
463 IO->conn_fail.data = IO;
464 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout, 0);
465 IO->rw_timeout.data = IO;
467 if (IO->ConnectMe->IPv6)
468 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
470 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->Addr, sizeof(struct sockaddr_in));
473 CtdlLogPrintf(CTDL_DEBUG, "connect() immediate success.\n");
474 //// freeaddrinfo(res);
475 set_start_callback(event_base, IO, 0);
476 ev_timer_start(event_base, &IO->rw_timeout);
477 return IO->NextState;
479 else if (errno == EINPROGRESS) {
480 CtdlLogPrintf(CTDL_DEBUG, "connect() have to wait now.\n");
482 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->SendBuf.fd, EV_READ|EV_WRITE);
483 IO->conn_event.data = IO;
485 ev_io_start(event_base, &IO->conn_event);
486 ev_timer_start(event_base, &IO->conn_fail);
487 return IO->NextState;
490 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
491 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
492 assert(IO->ConnFail);
496 return IO->NextState;
499 void SetNextTimeout(AsyncIO *IO, double timeout)
501 IO->rw_timeout.repeat = timeout;
502 ev_timer_again (event_base, &IO->rw_timeout);
505 eNextState InitEventIO(AsyncIO *IO,
508 double first_rw_timeout,
512 become_session(IO->CitContext);
515 IO->NextState = eReadMessage;
518 IO->NextState = eSendReply;
520 return event_connect_socket(IO, conn_timeout, first_rw_timeout);