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>
49 #include <libcitadel.h>
52 #include "citserver.h"
59 #include "internet_addressing.h"
62 #include "clientsocket.h"
63 #include "locate_host.h"
64 #include "citadel_dirs.h"
66 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
68 #include "event_client.h"
70 extern int event_add_pipe[2];
71 extern citthread_mutex_t EventQueueMutex;
72 extern HashList *InboundEventQueue;
73 extern struct ev_loop *event_base;
78 int QueueEventContext(void *Ctx, AsyncIO *IO, EventContextAttach CB)
83 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
87 citthread_mutex_lock(&EventQueueMutex);
88 if (event_add_pipe[1] == -1) {
89 citthread_mutex_unlock(&EventQueueMutex);
93 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
94 i = GetCount(InboundEventQueue);
95 Put(InboundEventQueue, IKEY(i), h, NULL);
96 citthread_mutex_unlock(&EventQueueMutex);
98 write(event_add_pipe[1], "+_", 1);
99 CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
104 int ShutDownEventQueue(void)
106 citthread_mutex_lock(&EventQueueMutex);
107 if (event_add_pipe[1] == -1) {
108 citthread_mutex_unlock(&EventQueueMutex);
112 write(event_add_pipe[1], "x_", 1);
113 close(event_add_pipe[1]);
114 event_add_pipe[1] = -1;
115 citthread_mutex_unlock(&EventQueueMutex);
119 void FreeAsyncIOContents(AsyncIO *IO)
121 FreeStrBuf(&IO->IOBuf);
122 FreeStrBuf(&IO->SendBuf.Buf);
123 FreeStrBuf(&IO->RecvBuf.Buf);
124 FreeStrBuf(&IO->ErrMsg);
125 ares_destroy(IO->DNSChannel);
131 setup_signal_handlers(struct instance *instance)
133 signal(SIGPIPE, SIG_IGN);
135 event_set(&instance->sigterm_event, SIGTERM, EV_SIGNAL|EV_PERSIST,
136 exit_event_callback, instance);
137 event_add(&instance->sigterm_event, NULL);
139 event_set(&instance->sigint_event, SIGINT, EV_SIGNAL|EV_PERSIST,
140 exit_event_callback, instance);
141 event_add(&instance->sigint_event, NULL);
143 event_set(&instance->sigquit_event, SIGQUIT, EV_SIGNAL|EV_PERSIST,
144 exit_event_callback, instance);
145 event_add(&instance->sigquit_event, NULL);
149 void ShutDownCLient(AsyncIO *IO)
151 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
152 switch (IO->active_event) {
154 ev_io_stop(event_base, &IO->send_event);
157 ev_io_stop(event_base, &IO->recv_event);
160 // no event active here; just bail out.
164 IO->active_event = 0;
165 IO->Terminate(IO->Data);
169 eReadState HandleInbound(AsyncIO *IO)
171 eReadState Finished = eBufferNotEmpty;
173 while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
174 if (IO->RecvBuf.nBlobBytesWanted != 0) {
177 else { /* Reading lines... */
178 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
180 Finished = IO->LineReader(IO);
182 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
185 case eMustReadMore: /// read new from socket...
188 case eBufferNotEmpty: /* shouldn't happen... */
189 case eReadSuccess: /// done for now...
191 case eReadFail: /// WHUT?
198 if (Finished != eMustReadMore) {
199 ev_io_stop(event_base, &IO->recv_event);
200 IO->active_event = 0;
201 IO->NextState = IO->ReadDone(IO->Data);
202 Finished = StrBufCheckBuffer(&IO->RecvBuf);
207 if ((IO->NextState == eSendReply) ||
208 (IO->NextState == eSendMore))
210 IO->NextState = IO->SendDone(IO->Data);
211 ev_io_start(event_base, &IO->send_event);
213 IO->active_event = SEND_EVENT;
216 else if ((IO->NextState == eTerminateConnection) ||
217 (IO->NextState == eAbort) )
224 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
227 AsyncIO *IO = watcher->data;
229 CtdlLogPrintf(CTDL_DEBUG, "EVENT -> %d : [%s%s%s%s]\n",
231 (event&EV_TIMEOUT) ? " timeout" : "",
232 (event&EV_READ) ? " read" : "",
233 (event&EV_WRITE) ? " write" : "",
234 (event&EV_SIGNAL) ? " signal" : "");
236 /// assert(fd == IO->sock);
238 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
247 const char *pch = ChrPtr(IO->SendBuf.Buf);
248 const char *pchh = IO->SendBuf.ReadWritePointer;
254 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
255 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
257 fd = fopen(fn, "a+");
258 fprintf(fd, "Read: BufSize: %ld BufContent: [",
260 rv = fwrite(pchh, nbytes, 1, fd);
267 ev_io_stop(event_base, &IO->send_event);
268 IO->active_event = 0;
269 switch (IO->NextState) {
273 IO->NextState = IO->SendDone(IO->Data);
275 if ((IO->NextState == eTerminateConnection) ||
276 (IO->NextState == eAbort) )
279 ev_io_start(event_base, &IO->send_event);
281 IO->active_event = SEND_EVENT;
285 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
289 ev_io_start(event_base, &IO->recv_event);
291 IO->active_event = RECV_EVENT;
295 case eTerminateConnection:
302 /* else : must write more. */
306 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
308 AsyncIO *IO = watcher->data;
313 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
315 AsyncIO *IO = watcher->data;
320 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
323 AsyncIO *IO = watcher->data;
325 // assert(fd == IO->sock);
327 // assert(fd == sb->fd);
329 CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d : [%s%s%s%s]\n",
331 (event&EV_TIMEOUT) ? " timeout" : "",
332 (event&EV_READ) ? " read" : "",
333 (event&EV_WRITE) ? " write" : "",
334 (event&EV_SIGNAL) ? " signal" : "");
336 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
339 } else if (nbytes == 0) {
341 /// TODO: this is a timeout??? sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
343 } else if (nbytes == -1) {
344 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
351 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents, int first_rw_timeout)
353 ev_timer_init(&IO->conn_timeout,
355 first_rw_timeout, 0);
356 IO->conn_timeout.data = IO;
358 switch(IO->NextState) {
360 ev_io_start(event_base, &IO->recv_event);
361 IO->active_event = RECV_EVENT;
365 IO_send_callback(loop, &IO->send_event, revents);
367 case eTerminateConnection:
374 int event_connect_socket(AsyncIO *IO, int conn_timeout, int first_rw_timeout)
376 struct sockaddr_in saddr;
380 IO->SendBuf.fd = IO->RecvBuf.fd =
381 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
383 IO->curr_ai->ai_family,
384 IO->curr_ai->ai_socktype,
385 IO->curr_ai->ai_protocol);
388 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
389 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
390 // freeaddrinfo(res);
393 fdflags = fcntl(IO->sock, F_GETFL);
395 CtdlLogPrintf(CTDL_DEBUG,
396 "EVENT: unable to get socket flags! %s \n",
398 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
401 fdflags = fdflags | O_NONBLOCK;
402 if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
403 CtdlLogPrintf(CTDL_DEBUG,
404 "EVENT: unable to set socket nonblocking flags! %s \n",
406 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
410 /* TODO: maye we could use offsetof() to calc the position of data...
411 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
413 ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
414 IO->recv_event.data = IO;
415 ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
416 IO->send_event.data = IO;
418 memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
420 memcpy(&saddr.sin_addr,
421 IO->HEnt->h_addr_list[0],
422 sizeof(struct in_addr));
424 // saddr.sin_addr.s_addr = inet_addr("85.88.5.80");
425 saddr.sin_family = AF_INET;
426 saddr.sin_port = htons(IO->dport);
427 rc = connect(IO->sock,
428 (struct sockaddr *) &saddr,
429 /// TODO: ipv6?? (IO->HEnt->h_addrtype == AF_INET6)?
430 /* sizeof(in6_addr):*/
431 sizeof(struct sockaddr_in));
433 //// freeaddrinfo(res);
434 set_start_callback(event_base, IO, 0, first_rw_timeout);
437 else if (errno == EINPROGRESS) {
438 set_start_callback(event_base, IO, 0, first_rw_timeout);
439 ev_timer_init(&IO->conn_fail,
440 IO_connfail_callback,
442 IO->conn_fail.data = IO;
447 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
448 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
450 /* IO->curr_ai = IO->curr_ai->ai_next;
451 if (IO->curr_ai != NULL)
452 return event_connect_socket(IO);
458 void InitEventIO(AsyncIO *IO,
460 IO_CallBack ReadDone,
461 IO_CallBack SendDone,
462 IO_CallBack Terminate,
464 IO_CallBack ConnFail,
465 IO_LineReaderCallback LineReader,
467 int first_rw_timeout,
471 IO->SendDone = SendDone;
472 IO->ReadDone = ReadDone;
473 IO->Terminate = Terminate;
474 IO->LineReader = LineReader;
477 IO->NextState = eReadMessage;
480 IO->NextState = eSendReply;
482 IO->IP6 = IO->HEnt->h_addrtype == AF_INET6;
483 // IO->res = HEnt->h_addr_list[0];
484 event_connect_socket(IO, conn_timeout, first_rw_timeout);