2ffc1c6e5e1970759d84326eab57b3ce2558b759
[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
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                 
241 #ifdef BIGBAD_IODBG
242                 {
243                         int rv = 0;
244                         char fn [SIZ];
245                         FILE *fd;
246                         const char *pch = ChrPtr(IO->SendBuf.Buf);
247                         const char *pchh = IO->SendBuf.ReadWritePointer;
248                         long nbytes;
249
250                         if (pchh == NULL)
251                                 pchh = pch;
252                         
253                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
254                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
255                 
256                         fd = fopen(fn, "a+");
257                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
258                                 nbytes);
259                         rv = fwrite(pchh, nbytes, 1, fd);
260                         fprintf(fd, "]\n");
261                 
262                         
263                         fclose(fd);
264                 }
265 #endif
266                 ev_io_stop(event_base, &IO->send_event);
267                 IO->active_event = 0;
268                 switch (IO->NextState) {
269                 case eSendReply:
270                         break;
271                 case eSendMore:
272                         IO->NextState = IO->SendDone(IO->Data);
273
274                         if ((IO->NextState == eTerminateConnection) ||
275                             (IO->NextState == eAbort) )
276                                 ShutDownCLient(IO);
277                         else {
278                                 ev_io_start(event_base, &IO->send_event);
279
280                                 IO->active_event = SEND_EVENT;
281                         }
282                         break;
283                 case eReadMessage:
284                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
285                                 HandleInbound(IO);
286                         }
287                         else {
288                                 ev_io_start(event_base, &IO->recv_event);
289
290                                 IO->active_event = RECV_EVENT;
291                         }
292
293                         break;
294                 case eTerminateConnection:
295                 case eAbort:
296                         break;
297                 }
298         }
299         else if (rc > 0)
300                 ShutDownCLient(IO);
301 //      else 
302                 ///abort!
303 }
304
305
306 static void
307 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
308 {
309         ssize_t nbytes;
310         AsyncIO *IO = watcher->data;
311
312 //    assert(fd == IO->sock);
313         
314 //    assert(fd == sb->fd);
315 /*
316         CtdlLogPrintf(CTDL_DEBUG, "EVENT <- %d  : [%s%s%s%s]\n",
317             (int) fd,
318             (event&EV_TIMEOUT) ? " timeout" : "",
319             (event&EV_READ)    ? " read" : "",
320             (event&EV_WRITE)   ? " write" : "",
321             (event&EV_SIGNAL)  ? " signal" : "");
322 */
323         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
324         if (nbytes > 0) {
325                 HandleInbound(IO);
326         } else if (nbytes == 0) {
327                 ShutDownCLient(IO);
328 ///  TODO: this is a timeout???  sock_buff_invoke_free(sb, 0); seems as if socket is gone then?
329                 return;
330         } else if (nbytes == -1) {
331 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
332                 return;
333         }
334 }
335
336
337 static void
338 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
339 {
340         switch(IO->NextState) {
341         case eReadMessage:
342                 ev_io_start(event_base, &IO->recv_event);
343                 IO->active_event = RECV_EVENT;
344                 break;
345         case eSendReply:
346         case eSendMore:
347                 IO_send_callback(loop, &IO->send_event, revents);
348                 break;
349         case eTerminateConnection:
350         case eAbort:
351                 /// TODO: WHUT?
352                 break;
353         }
354 }
355
356 int event_connect_socket(AsyncIO *IO)
357 {
358         int fdflags; 
359         int rc = -1;
360
361         IO->SendBuf.fd = 
362                 IO->RecvBuf.fd = 
363                 IO->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
364 /*
365 IO->curr_ai->ai_family, 
366                           IO->curr_ai->ai_socktype, 
367                           IO->curr_ai->ai_protocol);
368 */
369         if (IO->sock < 0) {
370                 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
371                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
372 //              freeaddrinfo(res);
373                 return -1;
374         }
375         fdflags = fcntl(IO->sock, F_GETFL);
376         if (fdflags < 0) {
377                 CtdlLogPrintf(CTDL_DEBUG,
378                               "EVENT: unable to get socket flags! %s \n",
379                               strerror(errno));
380                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
381                 return -1;
382         }
383         fdflags = fdflags | O_NONBLOCK;
384         if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
385                 CtdlLogPrintf(CTDL_DEBUG,
386                               "EVENT: unable to set socket nonblocking flags! %s \n",
387                               strerror(errno));
388                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
389                 close(IO->sock);
390                 return -1;
391         }
392 /* TODO: maye we could use offsetof() to calc the position of data... 
393  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
394  */
395         ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
396         IO->recv_event.data = IO;
397         ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
398         IO->send_event.data = IO;
399         
400         unsigned short dport = atoi("25"); ///todo
401         struct sockaddr_in  saddr;
402         memset( (struct sockaddr_in *)&saddr, '\0', sizeof( saddr ) );
403
404         memcpy(&saddr.sin_addr, 
405                IO->HEnt->h_addr_list[0],
406                sizeof(struct in_addr));
407
408 //      saddr.sin_addr.s_addr = inet_addr("85.88.5.80");
409         saddr.sin_family = AF_INET;
410         saddr.sin_port = htons(dport);/// TODO
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);
419                 
420                 return 0;
421         }
422         else {
423                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
424                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
425                 close(IO->sock);
426 /*              IO->curr_ai = IO->curr_ai->ai_next;
427                 if (IO->curr_ai != NULL)
428                         return event_connect_socket(IO);
429                         else*/
430                         return -1;
431         }
432 }
433
434 void InitEventIO(AsyncIO *IO, 
435                  void *pData, 
436                  IO_CallBack ReadDone, 
437                  IO_CallBack SendDone, 
438                  IO_CallBack Terminate, 
439                  IO_CallBack Timeout, 
440                  IO_CallBack ConnFail, 
441                  IO_LineReaderCallback LineReader,
442                  int ReadFirst)
443 {
444         IO->Data = pData;
445         IO->SendDone = SendDone;
446         IO->ReadDone = ReadDone;
447         IO->Terminate = Terminate;
448         IO->LineReader = LineReader;
449         
450         if (ReadFirst) {
451                 IO->NextState = eReadMessage;
452         }
453         else {
454                 IO->NextState = eSendReply;
455         }
456 //      IO->IP6 = IO->HEnt->h_addrtype == AF_INET6;
457 //      IO->res = HEnt->h_addr_list[0];
458         event_connect_socket(IO);
459 }
460
461
462 #endif