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 ares_destroy(IO->DNSChannel);
129 setup_signal_handlers(struct instance *instance)
131 signal(SIGPIPE, SIG_IGN);
133 event_set(&instance->sigterm_event, SIGTERM, EV_SIGNAL|EV_PERSIST,
134 exit_event_callback, instance);
135 event_add(&instance->sigterm_event, NULL);
137 event_set(&instance->sigint_event, SIGINT, EV_SIGNAL|EV_PERSIST,
138 exit_event_callback, instance);
139 event_add(&instance->sigint_event, NULL);
141 event_set(&instance->sigquit_event, SIGQUIT, EV_SIGNAL|EV_PERSIST,
142 exit_event_callback, instance);
143 event_add(&instance->sigquit_event, NULL);
147 void ShutDownCLient(AsyncIO *IO)
149 CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
150 switch (IO->active_event) {
152 ev_io_stop(event_base, &IO->send_event);
155 ev_io_stop(event_base, &IO->recv_event);
158 // no event active here; just bail out.
162 IO->active_event = 0;
163 IO->Terminate(IO->Data);
167 eReadState HandleInbound(AsyncIO *IO)
169 eReadState Finished = eBufferNotEmpty;
171 while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
172 if (IO->RecvBuf.nBlobBytesWanted != 0) {
175 else { /* Reading lines... */
176 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
178 Finished = IO->LineReader(IO);
180 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
183 case eMustReadMore: /// read new from socket...
186 case eBufferNotEmpty: /* shouldn't happen... */
187 case eReadSuccess: /// done for now...
189 case eReadFail: /// WHUT?
196 if (Finished != eMustReadMore) {
197 ev_io_stop(event_base, &IO->recv_event);
198 IO->active_event = 0;
199 IO->NextState = IO->ReadDone(IO->Data);
200 Finished = StrBufCheckBuffer(&IO->RecvBuf);
205 if ((IO->NextState == eSendReply) ||
206 (IO->NextState == eSendMore))
208 IO->NextState = IO->SendDone(IO->Data);
209 ev_io_start(event_base, &IO->send_event);
211 IO->active_event = SEND_EVENT;
214 else if ((IO->NextState == eTerminateConnection) ||
215 (IO->NextState == eAbort) )
222 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
225 AsyncIO *IO = watcher->data;
227 CtdlLogPrintf(CTDL_DEBUG, "EVENT -> %d : [%s%s%s%s]\n",
229 (event&EV_TIMEOUT) ? " timeout" : "",
230 (event&EV_READ) ? " read" : "",
231 (event&EV_WRITE) ? " write" : "",
232 (event&EV_SIGNAL) ? " signal" : "");
234 /// assert(fd == IO->sock);
236 rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
245 const char *pch = ChrPtr(IO->SendBuf.Buf);
246 const char *pchh = IO->SendBuf.ReadWritePointer;
252 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
253 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
255 fd = fopen(fn, "a+");
256 fprintf(fd, "Read: BufSize: %ld BufContent: [",
258 rv = fwrite(pchh, nbytes, 1, fd);
265 ev_io_stop(event_base, &IO->send_event);
266 IO->active_event = 0;
267 switch (IO->NextState) {
271 IO->NextState = IO->SendDone(IO->Data);
273 if ((IO->NextState == eTerminateConnection) ||
274 (IO->NextState == eAbort) )
277 ev_io_start(event_base, &IO->send_event);
279 IO->active_event = SEND_EVENT;
283 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
287 ev_io_start(event_base, &IO->recv_event);
289 IO->active_event = RECV_EVENT;
293 case eTerminateConnection:
300 /* else : must write more. */
304 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
306 AsyncIO *IO = watcher->data;
311 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
313 AsyncIO *IO = watcher->data;
318 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
321 AsyncIO *IO = watcher->data;
323 // assert(fd == IO->sock);
325 // assert(fd == sb->fd);
327 CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d : [%s%s%s%s]\n",
329 (event&EV_TIMEOUT) ? " timeout" : "",
330 (event&EV_READ) ? " read" : "",
331 (event&EV_WRITE) ? " write" : "",
332 (event&EV_SIGNAL) ? " signal" : "");
334 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
337 } else if (nbytes == 0) {
339 /// TODO: this is a timeout??? sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
341 } else if (nbytes == -1) {
342 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
349 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents, int first_rw_timeout)
351 ev_timer_init(&IO->conn_timeout,
353 first_rw_timeout, 0);
354 IO->conn_timeout.data = IO;
356 switch(IO->NextState) {
358 ev_io_start(event_base, &IO->recv_event);
359 IO->active_event = RECV_EVENT;
363 IO_send_callback(loop, &IO->send_event, revents);
365 case eTerminateConnection:
372 int event_connect_socket(AsyncIO *IO, int conn_timeout, int first_rw_timeout)
374 struct sockaddr_in saddr;
378 IO->SendBuf.fd = IO->RecvBuf.fd =
379 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
381 IO->curr_ai->ai_family,
382 IO->curr_ai->ai_socktype,
383 IO->curr_ai->ai_protocol);
386 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
387 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
388 // freeaddrinfo(res);
391 fdflags = fcntl(IO->sock, F_GETFL);
393 CtdlLogPrintf(CTDL_DEBUG,
394 "EVENT: unable to get socket flags! %s \n",
396 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
399 fdflags = fdflags | O_NONBLOCK;
400 if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
401 CtdlLogPrintf(CTDL_DEBUG,
402 "EVENT: unable to set socket nonblocking flags! %s \n",
404 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
408 /* TODO: maye we could use offsetof() to calc the position of data...
409 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
411 ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
412 IO->recv_event.data = IO;
413 ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
414 IO->send_event.data = IO;
416 memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
418 memcpy(&saddr.sin_addr,
419 IO->HEnt->h_addr_list[0],
420 sizeof(struct in_addr));
422 // saddr.sin_addr.s_addr = inet_addr("85.88.5.80");
423 saddr.sin_family = AF_INET;
424 saddr.sin_port = htons(IO->dport);
425 rc = connect(IO->sock,
426 (struct sockaddr *) &saddr,
427 /// TODO: ipv6?? (IO->HEnt->h_addrtype == AF_INET6)?
428 /* sizeof(in6_addr):*/
429 sizeof(struct sockaddr_in));
431 //// freeaddrinfo(res);
432 set_start_callback(event_base, IO, 0, first_rw_timeout);
435 else if (errno == EINPROGRESS) {
436 set_start_callback(event_base, IO, 0, first_rw_timeout);
437 ev_timer_init(&IO->conn_fail,
438 IO_connfail_callback,
440 IO->conn_fail.data = IO;
445 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
446 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
448 /* IO->curr_ai = IO->curr_ai->ai_next;
449 if (IO->curr_ai != NULL)
450 return event_connect_socket(IO);
456 void InitEventIO(AsyncIO *IO,
458 IO_CallBack ReadDone,
459 IO_CallBack SendDone,
460 IO_CallBack Terminate,
462 IO_CallBack ConnFail,
463 IO_LineReaderCallback LineReader,
465 int first_rw_timeout,
469 IO->SendDone = SendDone;
470 IO->ReadDone = ReadDone;
471 IO->Terminate = Terminate;
472 IO->LineReader = LineReader;
475 IO->NextState = eReadMessage;
478 IO->NextState = eSendReply;
480 IO->IP6 = IO->HEnt->h_addrtype == AF_INET6;
481 // IO->res = HEnt->h_addr_list[0];
482 event_connect_socket(IO, conn_timeout, first_rw_timeout);