Libev 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         ares_destroy(IO->DNSChannel);
125 }
126
127 /*
128   static void
129   setup_signal_handlers(struct instance *instance)
130   {
131   signal(SIGPIPE, SIG_IGN);
132
133   event_set(&instance->sigterm_event, SIGTERM, EV_SIGNAL|EV_PERSIST,
134   exit_event_callback, instance);
135   event_add(&instance->sigterm_event, NULL);
136
137   event_set(&instance->sigint_event, SIGINT, EV_SIGNAL|EV_PERSIST,
138   exit_event_callback, instance);
139   event_add(&instance->sigint_event, NULL);
140
141   event_set(&instance->sigquit_event, SIGQUIT, EV_SIGNAL|EV_PERSIST,
142   exit_event_callback, instance);
143   event_add(&instance->sigquit_event, NULL);
144   }
145 */
146
147 void ShutDownCLient(AsyncIO *IO)
148 {
149         CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
150         switch (IO->active_event) {
151         case SEND_EVENT:
152                 ev_io_stop(event_base, &IO->send_event);
153                 break;
154         case RECV_EVENT:
155                 ev_io_stop(event_base, &IO->recv_event);
156                 break;
157         case 0:
158                 // no event active here; just bail out.
159                 break;
160         }
161
162         IO->active_event = 0;
163         IO->Terminate(IO->Data);
164         
165 }
166
167 eReadState HandleInbound(AsyncIO *IO)
168 {
169         eReadState Finished = eBufferNotEmpty;
170                 
171         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
172                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
173                                 
174                 }
175                 else { /* Reading lines... */
176 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
177                         if (IO->LineReader)
178                                 Finished = IO->LineReader(IO);
179                         else 
180                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
181                                 
182                         switch (Finished) {
183                         case eMustReadMore: /// read new from socket... 
184                                 return Finished;
185                                 break;
186                         case eBufferNotEmpty: /* shouldn't happen... */
187                         case eReadSuccess: /// done for now...
188                                 break;
189                         case eReadFail: /// WHUT?
190                                 ///todo: shut down! 
191                                 break;
192                         }
193                                         
194                 }
195                         
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);
201                 }
202         }
203
204
205         if ((IO->NextState == eSendReply) ||
206             (IO->NextState == eSendMore))
207         {
208                 IO->NextState = IO->SendDone(IO->Data);
209                 ev_io_start(event_base, &IO->send_event);
210
211                 IO->active_event = SEND_EVENT;
212                         
213         }
214         else if ((IO->NextState == eTerminateConnection) ||
215                  (IO->NextState == eAbort) )
216                 ShutDownCLient(IO);
217         return Finished;
218 }
219
220
221 static void
222 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
223 {
224         int rc;
225         AsyncIO *IO = watcher->data;
226 /*
227         CtdlLogPrintf(CTDL_DEBUG, "EVENT -> %d  : [%s%s%s%s]\n",
228                       watcher->fd,
229                       (event&EV_TIMEOUT) ? " timeout" : "",
230                       (event&EV_READ)    ? " read" : "",
231                       (event&EV_WRITE)   ? " write" : "",
232                       (event&EV_SIGNAL)  ? " signal" : "");
233 */
234 ///    assert(fd == IO->sock);
235         
236         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
237
238         if (rc == 0)
239         {               
240 #ifdef BIGBAD_IODBG
241                 {
242                         int rv = 0;
243                         char fn [SIZ];
244                         FILE *fd;
245                         const char *pch = ChrPtr(IO->SendBuf.Buf);
246                         const char *pchh = IO->SendBuf.ReadWritePointer;
247                         long nbytes;
248
249                         if (pchh == NULL)
250                                 pchh = pch;
251                         
252                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
253                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
254                 
255                         fd = fopen(fn, "a+");
256                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
257                                 nbytes);
258                         rv = fwrite(pchh, nbytes, 1, fd);
259                         fprintf(fd, "]\n");
260                 
261                         
262                         fclose(fd);
263                 }
264 #endif
265                 ev_io_stop(event_base, &IO->send_event);
266                 IO->active_event = 0;
267                 switch (IO->NextState) {
268                 case eSendReply:
269                         break;
270                 case eSendMore:
271                         IO->NextState = IO->SendDone(IO->Data);
272
273                         if ((IO->NextState == eTerminateConnection) ||
274                             (IO->NextState == eAbort) )
275                                 ShutDownCLient(IO);
276                         else {
277                                 ev_io_start(event_base, &IO->send_event);
278
279                                 IO->active_event = SEND_EVENT;
280                         }
281                         break;
282                 case eReadMessage:
283                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
284                                 HandleInbound(IO);
285                         }
286                         else {
287                                 ev_io_start(event_base, &IO->recv_event);
288
289                                 IO->active_event = RECV_EVENT;
290                         }
291
292                         break;
293                 case eTerminateConnection:
294                 case eAbort:
295                         break;
296                 }
297         }
298         else if (rc < 0)
299                 IO->Timeout(IO);
300         /* else : must write more. */
301 }
302
303 static void
304 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
305 {
306         AsyncIO *IO = watcher->data;
307
308         IO->Timeout(IO);
309 }
310 static void
311 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
312 {
313         AsyncIO *IO = watcher->data;
314
315         IO->ConnFail(IO);
316 }
317 static void
318 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
319 {
320         ssize_t nbytes;
321         AsyncIO *IO = watcher->data;
322
323 //    assert(fd == IO->sock);
324         
325 //    assert(fd == sb->fd);
326 /*
327         CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d  : [%s%s%s%s]\n",
328             (int) fd,
329             (event&EV_TIMEOUT) ? " timeout" : "",
330             (event&EV_READ)    ? " read" : "",
331             (event&EV_WRITE)   ? " write" : "",
332             (event&EV_SIGNAL)  ? " signal" : "");
333 */
334         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
335         if (nbytes > 0) {
336                 HandleInbound(IO);
337         } else if (nbytes == 0) {
338                 IO->Timeout(IO);
339 ///  TODO: this is a timeout???  sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
340                 return;
341         } else if (nbytes == -1) {
342 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
343                 return;
344         }
345 }
346
347
348 static void
349 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents, int first_rw_timeout)
350 {
351         ev_timer_init(&IO->conn_timeout, 
352                       IO_Timout_callback, 
353                       first_rw_timeout, 0);
354         IO->conn_timeout.data = IO;
355         
356         switch(IO->NextState) {
357         case eReadMessage:
358                 ev_io_start(event_base, &IO->recv_event);
359                 IO->active_event = RECV_EVENT;
360                 break;
361         case eSendReply:
362         case eSendMore:
363                 IO_send_callback(loop, &IO->send_event, revents);
364                 break;
365         case eTerminateConnection:
366         case eAbort:
367                 /// TODO: WHUT?
368                 break;
369         }
370 }
371
372 int event_connect_socket(AsyncIO *IO, int conn_timeout, int first_rw_timeout)
373 {
374         struct sockaddr_in  saddr;
375         int fdflags; 
376         int rc = -1;
377
378         IO->SendBuf.fd = IO->RecvBuf.fd = 
379                 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
380 /*
381 IO->curr_ai->ai_family, 
382                           IO->curr_ai->ai_socktype, 
383                           IO->curr_ai->ai_protocol);
384 */
385         if (IO->sock < 0) {
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);
389                 return -1;
390         }
391         fdflags = fcntl(IO->sock, F_GETFL);
392         if (fdflags < 0) {
393                 CtdlLogPrintf(CTDL_DEBUG,
394                               "EVENT: unable to get socket flags! %s \n",
395                               strerror(errno));
396                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
397                 return -1;
398         }
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",
403                               strerror(errno));
404                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
405                 close(IO->sock);
406                 return -1;
407         }
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
410  */
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;
415         
416         memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
417
418         memcpy(&saddr.sin_addr, 
419                IO->HEnt->h_addr_list[0],
420                sizeof(struct in_addr));
421
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));
430         if (rc >= 0){
431 ////            freeaddrinfo(res);
432                 set_start_callback(event_base, IO, 0, first_rw_timeout);
433                 return 0;
434         }
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, 
439                               conn_timeout, 0);
440                 IO->conn_fail.data = IO;
441                 
442                 return 0;
443         }
444         else {
445                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
446                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
447                 close(IO->sock);
448 /*              IO->curr_ai = IO->curr_ai->ai_next;
449                 if (IO->curr_ai != NULL)
450                         return event_connect_socket(IO);
451                         else*/
452                         return -1;
453         }
454 }
455
456 void InitEventIO(AsyncIO *IO, 
457                  void *pData, 
458                  IO_CallBack ReadDone, 
459                  IO_CallBack SendDone, 
460                  IO_CallBack Terminate, 
461                  IO_CallBack Timeout, 
462                  IO_CallBack ConnFail, 
463                  IO_LineReaderCallback LineReader,
464                  int conn_timeout, 
465                  int first_rw_timeout,
466                  int ReadFirst)
467 {
468         IO->Data = pData;
469         IO->SendDone = SendDone;
470         IO->ReadDone = ReadDone;
471         IO->Terminate = Terminate;
472         IO->LineReader = LineReader;
473         
474         if (ReadFirst) {
475                 IO->NextState = eReadMessage;
476         }
477         else {
478                 IO->NextState = eSendReply;
479         }
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);
483 }
484
485
486 #endif