Libev / libc-ares Migration
[citadel.git] / citadel / event_client.c
1 /*
2  *
3  * Copyright (c) 1998-2009 by the citadel.org team
4  *
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.
9  *
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.
14  *
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
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <termios.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <pwd.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <syslog.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42 #include <sys/wait.h>
43 #include <ctype.h>
44 #include <string.h>
45 #include <limits.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <libcitadel.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "control.h"
56 #include "user_ops.h"
57 #include "database.h"
58 #include "msgbase.h"
59 #include "internet_addressing.h"
60 #include "genstamp.h"
61 #include "domain.h"
62 #include "clientsocket.h"
63 #include "locate_host.h"
64 #include "citadel_dirs.h"
65
66 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
67
68 #include "event_client.h"
69
70 extern int event_add_pipe[2];
71 extern citthread_mutex_t EventQueueMutex;
72 extern HashList *InboundEventQueue;
73 extern struct ev_loop *event_base;
74
75 #define SEND_EVENT 1
76 #define RECV_EVENT 2
77         
78 int QueueEventContext(void *Ctx, AsyncIO *IO, EventContextAttach CB)
79 {
80         IOAddHandler *h;
81         int i;
82
83         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
84         h->Ctx = Ctx;
85         h->EvAttch = CB;
86
87         citthread_mutex_lock(&EventQueueMutex);
88         if (event_add_pipe[1] == -1) {
89                 citthread_mutex_unlock(&EventQueueMutex);
90                 free (h);
91                 return -1;
92         }
93         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
94         i = GetCount(InboundEventQueue);
95         Put(InboundEventQueue, IKEY(i), h, NULL);
96         citthread_mutex_unlock(&EventQueueMutex);
97
98         write(event_add_pipe[1], "+_", 1);
99         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
100         return 0;
101 }
102
103
104 int ShutDownEventQueue(void)
105 {
106         citthread_mutex_lock(&EventQueueMutex);
107         if (event_add_pipe[1] == -1) {
108                 citthread_mutex_unlock(&EventQueueMutex);
109
110                 return -1;
111         }
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);
116         return 0;
117 }
118
119 void FreeAsyncIOContents(AsyncIO *IO)
120 {
121         FreeStrBuf(&IO->IOBuf);
122         FreeStrBuf(&IO->SendBuf.Buf);
123         FreeStrBuf(&IO->RecvBuf.Buf);
124         FreeStrBuf(&IO->ErrMsg);
125         ares_destroy(IO->DNSChannel);
126
127 }
128
129 /*
130   static void
131   setup_signal_handlers(struct instance *instance)
132   {
133   signal(SIGPIPE, SIG_IGN);
134
135   event_set(&instance->sigterm_event, SIGTERM, EV_SIGNAL|EV_PERSIST,
136   exit_event_callback, instance);
137   event_add(&instance->sigterm_event, NULL);
138
139   event_set(&instance->sigint_event, SIGINT, EV_SIGNAL|EV_PERSIST,
140   exit_event_callback, instance);
141   event_add(&instance->sigint_event, NULL);
142
143   event_set(&instance->sigquit_event, SIGQUIT, EV_SIGNAL|EV_PERSIST,
144   exit_event_callback, instance);
145   event_add(&instance->sigquit_event, NULL);
146   }
147 */
148
149 void ShutDownCLient(AsyncIO *IO)
150 {
151         CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
152         switch (IO->active_event) {
153         case SEND_EVENT:
154                 ev_io_stop(event_base, &IO->send_event);
155                 break;
156         case RECV_EVENT:
157                 ev_io_stop(event_base, &IO->recv_event);
158                 break;
159         case 0:
160                 // no event active here; just bail out.
161                 break;
162         }
163
164         IO->active_event = 0;
165         IO->Terminate(IO->Data);
166         
167 }
168
169 eReadState HandleInbound(AsyncIO *IO)
170 {
171         eReadState Finished = eBufferNotEmpty;
172                 
173         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
174                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
175                                 
176                 }
177                 else { /* Reading lines... */
178 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
179                         if (IO->LineReader)
180                                 Finished = IO->LineReader(IO);
181                         else 
182                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
183                                 
184                         switch (Finished) {
185                         case eMustReadMore: /// read new from socket... 
186                                 return Finished;
187                                 break;
188                         case eBufferNotEmpty: /* shouldn't happen... */
189                         case eReadSuccess: /// done for now...
190                                 break;
191                         case eReadFail: /// WHUT?
192                                 ///todo: shut down! 
193                                 break;
194                         }
195                                         
196                 }
197                         
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);
203                 }
204         }
205
206
207         if ((IO->NextState == eSendReply) ||
208             (IO->NextState == eSendMore))
209         {
210                 IO->NextState = IO->SendDone(IO->Data);
211                 ev_io_start(event_base, &IO->send_event);
212
213                 IO->active_event = SEND_EVENT;
214                         
215         }
216         else if ((IO->NextState == eTerminateConnection) ||
217                  (IO->NextState == eAbort) )
218                 ShutDownCLient(IO);
219         return Finished;
220 }
221
222
223 static void
224 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
225 {
226         int rc;
227         AsyncIO *IO = watcher->data;
228 /*
229         CtdlLogPrintf(CTDL_DEBUG, "EVENT -> %d  : [%s%s%s%s]\n",
230                       watcher->fd,
231                       (event&EV_TIMEOUT) ? " timeout" : "",
232                       (event&EV_READ)    ? " read" : "",
233                       (event&EV_WRITE)   ? " write" : "",
234                       (event&EV_SIGNAL)  ? " signal" : "");
235 */
236 ///    assert(fd == IO->sock);
237         
238         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
239
240         if (rc == 0)
241         {               
242 #ifdef BIGBAD_IODBG
243                 {
244                         int rv = 0;
245                         char fn [SIZ];
246                         FILE *fd;
247                         const char *pch = ChrPtr(IO->SendBuf.Buf);
248                         const char *pchh = IO->SendBuf.ReadWritePointer;
249                         long nbytes;
250
251                         if (pchh == NULL)
252                                 pchh = pch;
253                         
254                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
255                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
256                 
257                         fd = fopen(fn, "a+");
258                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
259                                 nbytes);
260                         rv = fwrite(pchh, nbytes, 1, fd);
261                         fprintf(fd, "]\n");
262                 
263                         
264                         fclose(fd);
265                 }
266 #endif
267                 ev_io_stop(event_base, &IO->send_event);
268                 IO->active_event = 0;
269                 switch (IO->NextState) {
270                 case eSendReply:
271                         break;
272                 case eSendMore:
273                         IO->NextState = IO->SendDone(IO->Data);
274
275                         if ((IO->NextState == eTerminateConnection) ||
276                             (IO->NextState == eAbort) )
277                                 ShutDownCLient(IO);
278                         else {
279                                 ev_io_start(event_base, &IO->send_event);
280
281                                 IO->active_event = SEND_EVENT;
282                         }
283                         break;
284                 case eReadMessage:
285                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
286                                 HandleInbound(IO);
287                         }
288                         else {
289                                 ev_io_start(event_base, &IO->recv_event);
290
291                                 IO->active_event = RECV_EVENT;
292                         }
293
294                         break;
295                 case eTerminateConnection:
296                 case eAbort:
297                         break;
298                 }
299         }
300         else if (rc < 0)
301                 IO->Timeout(IO);
302         /* else : must write more. */
303 }
304
305 static void
306 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
307 {
308         AsyncIO *IO = watcher->data;
309
310         IO->Timeout(IO);
311 }
312 static void
313 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
314 {
315         AsyncIO *IO = watcher->data;
316
317         IO->ConnFail(IO);
318 }
319 static void
320 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
321 {
322         ssize_t nbytes;
323         AsyncIO *IO = watcher->data;
324
325 //    assert(fd == IO->sock);
326         
327 //    assert(fd == sb->fd);
328 /*
329         CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d  : [%s%s%s%s]\n",
330             (int) fd,
331             (event&EV_TIMEOUT) ? " timeout" : "",
332             (event&EV_READ)    ? " read" : "",
333             (event&EV_WRITE)   ? " write" : "",
334             (event&EV_SIGNAL)  ? " signal" : "");
335 */
336         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
337         if (nbytes > 0) {
338                 HandleInbound(IO);
339         } else if (nbytes == 0) {
340                 IO->Timeout(IO);
341 ///  TODO: this is a timeout???  sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
342                 return;
343         } else if (nbytes == -1) {
344 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
345                 return;
346         }
347 }
348
349
350 static void
351 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents, int first_rw_timeout)
352 {
353         ev_timer_init(&IO->conn_timeout, 
354                       IO_Timout_callback, 
355                       first_rw_timeout, 0);
356         IO->conn_timeout.data = IO;
357         
358         switch(IO->NextState) {
359         case eReadMessage:
360                 ev_io_start(event_base, &IO->recv_event);
361                 IO->active_event = RECV_EVENT;
362                 break;
363         case eSendReply:
364         case eSendMore:
365                 IO_send_callback(loop, &IO->send_event, revents);
366                 break;
367         case eTerminateConnection:
368         case eAbort:
369                 /// TODO: WHUT?
370                 break;
371         }
372 }
373
374 int event_connect_socket(AsyncIO *IO, int conn_timeout, int first_rw_timeout)
375 {
376         struct sockaddr_in  saddr;
377         int fdflags; 
378         int rc = -1;
379
380         IO->SendBuf.fd = IO->RecvBuf.fd = 
381                 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
382 /*
383 IO->curr_ai->ai_family, 
384                           IO->curr_ai->ai_socktype, 
385                           IO->curr_ai->ai_protocol);
386 */
387         if (IO->sock < 0) {
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);
391                 return -1;
392         }
393         fdflags = fcntl(IO->sock, F_GETFL);
394         if (fdflags < 0) {
395                 CtdlLogPrintf(CTDL_DEBUG,
396                               "EVENT: unable to get socket flags! %s \n",
397                               strerror(errno));
398                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
399                 return -1;
400         }
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",
405                               strerror(errno));
406                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
407                 close(IO->sock);
408                 return -1;
409         }
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
412  */
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;
417         
418         memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
419
420         memcpy(&saddr.sin_addr, 
421                IO->HEnt->h_addr_list[0],
422                sizeof(struct in_addr));
423
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));
432         if (rc >= 0){
433 ////            freeaddrinfo(res);
434                 set_start_callback(event_base, IO, 0, first_rw_timeout);
435                 return 0;
436         }
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, 
441                               conn_timeout, 0);
442                 IO->conn_fail.data = IO;
443                 
444                 return 0;
445         }
446         else {
447                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
448                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
449                 close(IO->sock);
450 /*              IO->curr_ai = IO->curr_ai->ai_next;
451                 if (IO->curr_ai != NULL)
452                         return event_connect_socket(IO);
453                         else*/
454                         return -1;
455         }
456 }
457
458 void InitEventIO(AsyncIO *IO, 
459                  void *pData, 
460                  IO_CallBack ReadDone, 
461                  IO_CallBack SendDone, 
462                  IO_CallBack Terminate, 
463                  IO_CallBack Timeout, 
464                  IO_CallBack ConnFail, 
465                  IO_LineReaderCallback LineReader,
466                  int conn_timeout, 
467                  int first_rw_timeout,
468                  int ReadFirst)
469 {
470         IO->Data = pData;
471         IO->SendDone = SendDone;
472         IO->ReadDone = ReadDone;
473         IO->Terminate = Terminate;
474         IO->LineReader = LineReader;
475         
476         if (ReadFirst) {
477                 IO->NextState = eReadMessage;
478         }
479         else {
480                 IO->NextState = eSendReply;
481         }
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);
485 }
486
487
488 #endif