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 #define CONN_EVENT 3
78         
79 int QueueEventContext(void *Ctx, AsyncIO *IO, EventContextAttach CB)
80 {
81         IOAddHandler *h;
82         int i;
83
84         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
85         h->Ctx = Ctx;
86         h->EvAttch = CB;
87
88         citthread_mutex_lock(&EventQueueMutex);
89         if (event_add_pipe[1] == -1) {
90                 citthread_mutex_unlock(&EventQueueMutex);
91                 free (h);
92                 return -1;
93         }
94         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
95         i = GetCount(InboundEventQueue);
96         Put(InboundEventQueue, IKEY(i), h, NULL);
97         citthread_mutex_unlock(&EventQueueMutex);
98
99         write(event_add_pipe[1], "+_", 1);
100         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
101         return 0;
102 }
103
104
105 int ShutDownEventQueue(void)
106 {
107         citthread_mutex_lock(&EventQueueMutex);
108         if (event_add_pipe[1] == -1) {
109                 citthread_mutex_unlock(&EventQueueMutex);
110
111                 return -1;
112         }
113         write(event_add_pipe[1], "x_", 1);
114         close(event_add_pipe[1]);
115         event_add_pipe[1] = -1;
116         citthread_mutex_unlock(&EventQueueMutex);
117         return 0;
118 }
119
120 void FreeAsyncIOContents(AsyncIO *IO)
121 {
122         FreeStrBuf(&IO->IOBuf);
123         FreeStrBuf(&IO->SendBuf.Buf);
124         FreeStrBuf(&IO->RecvBuf.Buf);
125
126 }
127
128 /*
129   static void
130   setup_signal_handlers(struct instance *instance)
131   {
132   signal(SIGPIPE, SIG_IGN);
133
134   event_set(&instance->sigterm_event, SIGTERM, EV_SIGNAL|EV_PERSIST,
135   exit_event_callback, instance);
136   event_add(&instance->sigterm_event, NULL);
137
138   event_set(&instance->sigint_event, SIGINT, EV_SIGNAL|EV_PERSIST,
139   exit_event_callback, instance);
140   event_add(&instance->sigint_event, NULL);
141
142   event_set(&instance->sigquit_event, SIGQUIT, EV_SIGNAL|EV_PERSIST,
143   exit_event_callback, instance);
144   event_add(&instance->sigquit_event, NULL);
145   }
146 */
147
148 void ShutDownCLient(AsyncIO *IO)
149 {
150         CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
151         switch (IO->active_event) {
152         case SEND_EVENT:
153                 ev_io_stop(event_base, &IO->send_event);
154                 break;
155         case RECV_EVENT:
156                 ev_io_stop(event_base, &IO->recv_event);
157                 break;
158         case CONN_EVENT:
159                 ev_io_stop(event_base, &IO->conn_event);
160                 break;
161         case 0:
162                 // no event active here; just bail out.
163                 break;
164         }
165
166         IO->active_event = 0;
167         IO->Terminate(IO->Data);
168         
169 }
170
171 eReadState HandleInbound(AsyncIO *IO)
172 {
173         eReadState Finished = eBufferNotEmpty;
174                 
175         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
176                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
177                                 
178                 }
179                 else { /* Reading lines... */
180 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
181                         if (IO->LineReader)
182                                 Finished = IO->LineReader(IO);
183                         else 
184                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
185                                 
186                         switch (Finished) {
187                         case eMustReadMore: /// read new from socket... 
188                                 return Finished;
189                                 break;
190                         case eBufferNotEmpty: /* shouldn't happen... */
191                         case eReadSuccess: /// done for now...
192                                 break;
193                         case eReadFail: /// WHUT?
194                                 ///todo: shut down! 
195                                 break;
196                         }
197                                         
198                 }
199                         
200                 if (Finished != eMustReadMore) {
201                         ev_io_stop(event_base, &IO->recv_event);
202                         IO->active_event = 0;
203                         IO->NextState = IO->ReadDone(IO->Data);
204                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
205                 }
206         }
207
208
209         if ((IO->NextState == eSendReply) ||
210             (IO->NextState == eSendMore))
211         {
212                 IO->NextState = IO->SendDone(IO->Data);
213                 ev_io_start(event_base, &IO->send_event);
214
215                 IO->active_event = SEND_EVENT;
216                         
217         }
218         else if ((IO->NextState == eTerminateConnection) ||
219                  (IO->NextState == eAbort) )
220                 ShutDownCLient(IO);
221         return Finished;
222 }
223
224
225 static void
226 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
227 {
228         int rc;
229         AsyncIO *IO = watcher->data;
230 /*
231         CtdlLogPrintf(CTDL_DEBUG, "EVENT -> %d  : [%s%s%s%s]\n",
232                       watcher->fd,
233                       (event&EV_TIMEOUT) ? " timeout" : "",
234                       (event&EV_READ)    ? " read" : "",
235                       (event&EV_WRITE)   ? " write" : "",
236                       (event&EV_SIGNAL)  ? " signal" : "");
237 */
238 ///    assert(fd == IO->sock);
239         
240         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
241
242         if (rc == 0)
243         {
244                 
245 #ifdef BIGBAD_IODBG
246                 {
247                         int rv = 0;
248                         char fn [SIZ];
249                         FILE *fd;
250                         const char *pch = ChrPtr(IO->SendBuf.Buf);
251                         const char *pchh = IO->SendBuf.ReadWritePointer;
252                         long nbytes;
253
254                         if (pchh == NULL)
255                                 pchh = pch;
256                         
257                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
258                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
259                 
260                         fd = fopen(fn, "a+");
261                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
262                                 nbytes);
263                         rv = fwrite(pchh, nbytes, 1, fd);
264                         fprintf(fd, "]\n");
265                 
266                         
267                         fclose(fd);
268                 }
269 #endif
270                 ev_io_stop(event_base, &IO->send_event);
271                 IO->active_event = 0;
272                 switch (IO->NextState) {
273                 case eSendReply:
274                         break;
275                 case eSendMore:
276                         IO->NextState = IO->SendDone(IO->Data);
277
278                         if ((IO->NextState == eTerminateConnection) ||
279                             (IO->NextState == eAbort) )
280                                 ShutDownCLient(IO);
281                         else {
282                                 ev_io_start(event_base, &IO->send_event);
283
284                                 IO->active_event = SEND_EVENT;
285                         }
286                         break;
287                 case eReadMessage:
288                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
289                                 HandleInbound(IO);
290                         }
291                         else {
292                                 ev_io_start(event_base, &IO->recv_event);
293
294                                 IO->active_event = RECV_EVENT;
295                         }
296
297                         break;
298                 case eTerminateConnection:
299                 case eAbort:
300                         break;
301                 }
302         }
303         else if (rc > 0)
304                 ShutDownCLient(IO);
305 //      else 
306                 ///abort!
307 }
308
309
310 static void
311 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
312 {
313         ssize_t nbytes;
314         AsyncIO *IO = watcher->data;
315
316 //    assert(fd == IO->sock);
317         
318 //    assert(fd == sb->fd);
319 /*
320         CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d  : [%s%s%s%s]\n",
321             (int) fd,
322             (event&EV_TIMEOUT) ? " timeout" : "",
323             (event&EV_READ)    ? " read" : "",
324             (event&EV_WRITE)   ? " write" : "",
325             (event&EV_SIGNAL)  ? " signal" : "");
326 */
327         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
328         if (nbytes > 0) {
329                 HandleInbound(IO);
330         } else if (nbytes == 0) {
331                 ShutDownCLient(IO);
332 ///  TODO: this is a timeout???  sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
333                 return;
334         } else if (nbytes == -1) {
335 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
336                 return;
337         }
338 }
339
340
341 static void
342 set_start_callback(struct ev_loop *loop, ev_io *watcher, int revents)
343 {
344         AsyncIO *IO = watcher->data;
345
346         switch(IO->NextState) {
347         case eReadMessage:
348                 ev_io_start(event_base, &IO->recv_event);
349                 IO->active_event = RECV_EVENT;
350                 break;
351         case eSendReply:
352         case eSendMore:
353                 IO_send_callback(loop, watcher, revents);
354                 break;
355         case eTerminateConnection:
356         case eAbort:
357                 /// TODO: WHUT?
358                 break;
359         }
360 }
361
362 static void
363 IO_connect_callback(struct ev_loop *loop, ev_io *watcher, int revents)
364 {
365         AsyncIO *IO = watcher->data;
366
367         ev_io_stop(event_base, &IO->conn_event);
368         IO->active_event = 0;
369         set_start_callback(loop, watcher, revents);
370 }
371
372 int event_connect_socket(AsyncIO *IO)
373 {
374         int fdflags; 
375         int rc = -1;
376
377         IO->SendBuf.fd = 
378         IO->RecvBuf.fd = 
379         IO->sock = socket(IO->curr_ai->ai_family, 
380                           IO->curr_ai->ai_socktype, 
381                           IO->curr_ai->ai_protocol);
382
383         if (IO->sock < 0) {
384                 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
385                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
386 //              freeaddrinfo(res);
387                 return -1;
388         }
389         fdflags = fcntl(IO->sock, F_GETFL);
390         if (fdflags < 0) {
391                 CtdlLogPrintf(CTDL_DEBUG,
392                               "EVENT: unable to get socket flags! %s \n",
393                               strerror(errno));
394                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
395                 return -1;
396         }
397         fdflags = fdflags | O_NONBLOCK;
398         if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
399                 CtdlLogPrintf(CTDL_DEBUG,
400                               "EVENT: unable to set socket nonblocking flags! %s \n",
401                               strerror(errno));
402                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
403                 close(IO->sock);
404                 return -1;
405         }
406 /* TODO: maye we could use offsetof() to calc the position of data... 
407  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
408  */
409         ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
410         IO->recv_event.data = IO;
411         ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
412         IO->send_event.data = IO;
413         
414         rc = connect(IO->sock, IO->curr_ai->ai_addr, IO->curr_ai->ai_addrlen);
415         if (rc >= 0) {
416 ////            freeaddrinfo(res);
417                 ev_io_init(&IO->conn_event, IO_send_callback, IO->sock, EV_WRITE);
418                 IO->conn_event.data = IO;
419                 set_start_callback(event_base, &IO->conn_event, 0);
420                 
421                 return 0;
422         }
423         else if (errno == EINPROGRESS) {
424                 ev_io_init(&IO->conn_event, IO_connect_callback, IO->sock, EV_READ|EV_WRITE);
425                 IO->conn_event.data = IO;
426 /* TODO
427
428                 event_set(&IO->conn_event, 
429                           IO->sock,
430                           EV_READ|EV_WRITE|EV_PERSIST,
431                           IO_connect_callback, 
432                           IO);
433 */
434                 ev_io_start(event_base, &IO->conn_event);
435
436                 IO->active_event = CONN_EVENT;
437                 return 1;
438         }
439         else {
440                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
441                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
442                 close(IO->sock);
443                 IO->curr_ai = IO->curr_ai->ai_next;
444                 if (IO->curr_ai != NULL)
445                         return event_connect_socket(IO);
446                 else
447                         return -1;
448         }
449 }
450
451 void InitEventIO(AsyncIO *IO, 
452                  void *pData, 
453                  IO_CallBack ReadDone, 
454                  IO_CallBack SendDone, 
455                  IO_CallBack Terminate, 
456                  IO_CallBack Timeout, 
457                  IO_CallBack ConnFail, 
458                  IO_CallBack CustomDNS,
459                  IO_LineReaderCallback LineReader,
460                  int ReadFirst)
461 {
462         IO->Data = pData;
463         IO->SendDone = SendDone;
464         IO->ReadDone = ReadDone;
465         IO->Terminate = Terminate;
466         IO->LineReader = LineReader;
467
468         if (ReadFirst) {
469                 IO->NextState = eReadMessage;
470         }
471         else {
472                 IO->NextState = eSendReply;
473         }
474
475         event_connect_socket(IO);
476 }
477
478
479 #endif