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);
248 const char *pch = ChrPtr(IO->SendBuf.Buf);
249 const char *pchh = IO->SendBuf.ReadWritePointer;
255 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
256 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
258 fd = fopen(fn, "a+");
259 fprintf(fd, "Read: BufSize: %ld BufContent: [",
261 rv = fwrite(pchh, nbytes, 1, fd);
268 ev_io_stop(event_base, &IO->send_event);
269 IO->active_event = 0;
270 switch (IO->NextState) {
274 IO->NextState = IO->SendDone(IO->Data);
276 if ((IO->NextState == eTerminateConnection) ||
277 (IO->NextState == eAbort) )
280 ev_io_start(event_base, &IO->send_event);
282 IO->active_event = SEND_EVENT;
286 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
290 ev_io_start(event_base, &IO->recv_event);
292 IO->active_event = RECV_EVENT;
296 case eTerminateConnection:
309 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
312 AsyncIO *IO = watcher->data;
314 // assert(fd == IO->sock);
316 // assert(fd == sb->fd);
318 CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d : [%s%s%s%s]\n",
320 (event&EV_TIMEOUT) ? " timeout" : "",
321 (event&EV_READ) ? " read" : "",
322 (event&EV_WRITE) ? " write" : "",
323 (event&EV_SIGNAL) ? " signal" : "");
325 nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
328 } else if (nbytes == 0) {
330 /// TODO: this is a timeout??? sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
332 } else if (nbytes == -1) {
333 /// TODO: FD is gone. kick it. sock_buff_invoke_free(sb, errno);
340 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
342 switch(IO->NextState) {
344 ev_io_start(event_base, &IO->recv_event);
345 IO->active_event = RECV_EVENT;
349 IO_send_callback(loop, &IO->send_event, revents);
351 case eTerminateConnection:
358 int event_connect_socket(AsyncIO *IO)
360 struct sockaddr_in saddr;
364 IO->SendBuf.fd = IO->RecvBuf.fd =
365 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
367 IO->curr_ai->ai_family,
368 IO->curr_ai->ai_socktype,
369 IO->curr_ai->ai_protocol);
372 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
373 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
374 // freeaddrinfo(res);
377 fdflags = fcntl(IO->sock, F_GETFL);
379 CtdlLogPrintf(CTDL_DEBUG,
380 "EVENT: unable to get socket flags! %s \n",
382 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
385 fdflags = fdflags | O_NONBLOCK;
386 if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
387 CtdlLogPrintf(CTDL_DEBUG,
388 "EVENT: unable to set socket nonblocking flags! %s \n",
390 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
394 /* TODO: maye we could use offsetof() to calc the position of data...
395 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
397 ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
398 IO->recv_event.data = IO;
399 ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
400 IO->send_event.data = IO;
402 memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
404 memcpy(&saddr.sin_addr,
405 IO->HEnt->h_addr_list[0],
406 sizeof(struct in_addr));
408 // saddr.sin_addr.s_addr = inet_addr("85.88.5.80");
409 saddr.sin_family = AF_INET;
410 saddr.sin_port = htons(IO->dport);
411 rc = connect(IO->sock,
412 (struct sockaddr *) &saddr,
413 /// TODO: ipv6?? (IO->HEnt->h_addrtype == AF_INET6)?
414 /* sizeof(in6_addr):*/
415 sizeof(struct sockaddr_in));
416 if ((rc >= 0) || (errno == EINPROGRESS)){
417 //// freeaddrinfo(res);
418 set_start_callback(event_base, IO, 0);
423 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
424 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
426 /* IO->curr_ai = IO->curr_ai->ai_next;
427 if (IO->curr_ai != NULL)
428 return event_connect_socket(IO);
434 void InitEventIO(AsyncIO *IO,
436 IO_CallBack ReadDone,
437 IO_CallBack SendDone,
438 IO_CallBack Terminate,
440 IO_CallBack ConnFail,
441 IO_LineReaderCallback LineReader,
445 IO->SendDone = SendDone;
446 IO->ReadDone = ReadDone;
447 IO->Terminate = Terminate;
448 IO->LineReader = LineReader;
451 IO->NextState = eReadMessage;
454 IO->NextState = eSendReply;
456 IO->IP6 = IO->HEnt->h_addrtype == AF_INET6;
457 // IO->res = HEnt->h_addr_list[0];
458 event_connect_socket(IO);