libev/c-ares migration; fix lookup chains
[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 <assert.h>
50
51 #include <libcitadel.h>
52 #include "citadel.h"
53 #include "server.h"
54 #include "citserver.h"
55 #include "support.h"
56 #include "config.h"
57 #include "control.h"
58 #include "user_ops.h"
59 #include "database.h"
60 #include "msgbase.h"
61 #include "internet_addressing.h"
62 #include "genstamp.h"
63 #include "domain.h"
64 #include "clientsocket.h"
65 #include "locate_host.h"
66 #include "citadel_dirs.h"
67
68 #include "event_client.h"
69
70 extern citthread_mutex_t EventQueueMutex;
71 extern HashList *InboundEventQueue;
72 extern struct ev_loop *event_base;
73 extern ev_async AddJob;   
74 extern ev_async ExitEventLoop;
75
76 static void
77 IO_abort_shutdown_callback(struct ev_loop *loop, ev_cleanup *watcher, int revents)
78 {
79         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
80
81         AsyncIO *IO = watcher->data;
82         IO->ShutdownAbort(IO);
83 }
84         
85 int QueueEventContext(AsyncIO *IO, IO_CallBack CB)
86 {
87         IOAddHandler *h;
88         int i;
89
90         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
91         h->IO = IO;
92         h->EvAttch = CB;
93         ev_cleanup_init(&IO->abort_by_shutdown, 
94                         IO_abort_shutdown_callback);
95         IO->abort_by_shutdown.data = IO;
96         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
97
98         citthread_mutex_lock(&EventQueueMutex);
99         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q\n");
100         i = GetCount(InboundEventQueue);
101         Put(InboundEventQueue, IKEY(i), h, NULL);
102         citthread_mutex_unlock(&EventQueueMutex);
103
104         ev_async_send (event_base, &AddJob);
105         CtdlLogPrintf(CTDL_DEBUG, "EVENT Q Done.\n");
106         return 0;
107 }
108
109
110 int ShutDownEventQueue(void)
111 {
112         citthread_mutex_lock(&EventQueueMutex);
113         ev_async_send (EV_DEFAULT_ &ExitEventLoop);
114         citthread_mutex_unlock(&EventQueueMutex);
115         return 0;
116 }
117
118 void FreeAsyncIOContents(AsyncIO *IO)
119 {
120         FreeStrBuf(&IO->IOBuf);
121         FreeStrBuf(&IO->SendBuf.Buf);
122         FreeStrBuf(&IO->RecvBuf.Buf);
123 }
124
125
126 void ShutDownCLient(AsyncIO *IO)
127 {
128         CtdlLogPrintf(CTDL_DEBUG, "EVENT x %d\n", IO->sock);
129
130         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
131
132         if (IO->sock != 0)
133         {
134                 ev_io_stop(event_base, &IO->send_event);
135                 ev_io_stop(event_base, &IO->recv_event);
136                 ev_timer_stop (event_base, &IO->rw_timeout);
137                 close(IO->sock);
138                 IO->sock = 0;
139                 IO->SendBuf.fd = 0;
140                 IO->RecvBuf.fd = 0;
141         }
142         if (IO->DNSChannel != NULL) {
143                 ares_destroy(IO->DNSChannel);
144                 ev_io_stop(event_base, &IO->dns_recv_event);
145                 ev_io_stop(event_base, &IO->dns_send_event);
146                 IO->DNSChannel = NULL;
147         }
148         assert(IO->Terminate);
149         IO->Terminate(IO);
150         
151 }
152
153
154 eReadState HandleInbound(AsyncIO *IO)
155 {
156         eReadState Finished = eBufferNotEmpty;
157         
158         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
159                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
160                                 
161                 }
162                 else { /* Reading lines... */
163 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
164                         if (IO->LineReader)
165                                 Finished = IO->LineReader(IO);
166                         else 
167                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
168                                 
169                         switch (Finished) {
170                         case eMustReadMore: /// read new from socket... 
171                                 return Finished;
172                                 break;
173                         case eBufferNotEmpty: /* shouldn't happen... */
174                         case eReadSuccess: /// done for now...
175                                 break;
176                         case eReadFail: /// WHUT?
177                                 ///todo: shut down! 
178                                 break;
179                         }
180                                         
181                 }
182                         
183                 if (Finished != eMustReadMore) {
184                         assert(IO->ReadDone);
185                         ev_io_stop(event_base, &IO->recv_event);
186                         IO->NextState = IO->ReadDone(IO);
187                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
188                 }
189         }
190
191
192         if ((IO->NextState == eSendReply) ||
193             (IO->NextState == eSendMore))
194         {
195                 assert(IO->SendDone);
196                 IO->NextState = IO->SendDone(IO);
197                 ev_io_start(event_base, &IO->send_event);
198         }
199         else if ((IO->NextState == eTerminateConnection) ||
200                  (IO->NextState == eAbort) )
201                 ShutDownCLient(IO);
202         return Finished;
203 }
204
205
206 static void
207 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
208 {
209         int rc;
210         AsyncIO *IO = watcher->data;
211
212         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
213
214         if (rc == 0)
215         {               
216 #ifdef BIGBAD_IODBG
217                 {
218                         int rv = 0;
219                         char fn [SIZ];
220                         FILE *fd;
221                         const char *pch = ChrPtr(IO->SendBuf.Buf);
222                         const char *pchh = IO->SendBuf.ReadWritePointer;
223                         long nbytes;
224
225                         if (pchh == NULL)
226                                 pchh = pch;
227                         
228                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
229                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
230                 
231                         fd = fopen(fn, "a+");
232                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
233                                 nbytes);
234                         rv = fwrite(pchh, nbytes, 1, fd);
235                         fprintf(fd, "]\n");
236                 
237                         
238                         fclose(fd);
239                 }
240 #endif
241                 ev_io_stop(event_base, &IO->send_event);
242                 switch (IO->NextState) {
243                 case eSendReply:
244                         break;
245                 case eSendMore:
246                         assert(IO->SendDone);
247                         IO->NextState = IO->SendDone(IO);
248
249                         if ((IO->NextState == eTerminateConnection) ||
250                             (IO->NextState == eAbort) )
251                                 ShutDownCLient(IO);
252                         else {
253                                 ev_io_start(event_base, &IO->send_event);
254                         }
255                         break;
256                 case eReadMessage:
257                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
258                                 HandleInbound(IO);
259                         }
260                         else {
261                                 ev_io_start(event_base, &IO->recv_event);
262                         }
263
264                         break;
265                 case eTerminateConnection:
266                 case eAbort:
267                         break;
268                 }
269         }
270         else if (rc < 0) {
271                 assert(IO->Timeout);
272                 IO->Timeout(IO);
273         }
274         /* else : must write more. */
275 }
276 static void
277 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
278 {
279         
280         switch(IO->NextState) {
281         case eReadMessage:
282                 ev_io_start(event_base, &IO->recv_event);
283                 break;
284         case eSendReply:
285         case eSendMore:
286                 IO_send_callback(loop, &IO->send_event, revents);
287                 break;
288         case eTerminateConnection:
289         case eAbort:
290                 /// TODO: WHUT?
291                 break;
292         }
293 }
294
295 static void
296 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
297 {
298         AsyncIO *IO = watcher->data;
299
300         ev_timer_stop (event_base, &IO->rw_timeout);
301         assert(IO->Timeout);
302         IO->Timeout(IO);
303 }
304 static void
305 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
306 {
307         AsyncIO *IO = watcher->data;
308
309         ev_timer_stop (event_base, &IO->conn_fail);
310         ev_io_stop(loop, &IO->conn_event);
311         assert(IO->ConnFail);
312         IO->ConnFail(IO);
313 }
314 static void
315 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
316 {
317         AsyncIO *IO = watcher->data;
318
319         ev_io_stop(loop, &IO->conn_event);
320         ev_timer_stop (event_base, &IO->conn_fail);
321         set_start_callback(loop, IO, revents);
322 }
323 static void
324 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
325 {
326         ssize_t nbytes;
327         AsyncIO *IO = watcher->data;
328
329         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
330         if (nbytes > 0) {
331                 HandleInbound(IO);
332         } else if (nbytes == 0) {
333                 assert(IO->Timeout);
334                 IO->Timeout(IO); /* this is a timeout... */
335                 return;
336         } else if (nbytes == -1) {
337 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
338                 return;
339         }
340 }
341
342 void
343 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
344 {
345         AsyncIO *IO = watcher->data;
346         CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
347
348         IO->DNSQuery->PostDNS(IO);
349 }
350
351 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
352 {
353         int fdflags; 
354         int rc = -1;
355
356         IO->SendBuf.fd = IO->RecvBuf.fd = 
357                 IO->sock = socket(
358                         (IO->IP6)?PF_INET6:PF_INET, 
359                         SOCK_STREAM, 
360                         IPPROTO_TCP);
361
362         if (IO->sock < 0) {
363                 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
364                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
365 //              freeaddrinfo(res);
366                 return eAbort;
367         }
368         fdflags = fcntl(IO->sock, F_GETFL);
369         if (fdflags < 0) {
370                 CtdlLogPrintf(CTDL_DEBUG,
371                               "EVENT: unable to get socket flags! %s \n",
372                               strerror(errno));
373                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
374                 return eAbort;
375         }
376         fdflags = fdflags | O_NONBLOCK;
377         if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
378                 CtdlLogPrintf(CTDL_DEBUG,
379                               "EVENT: unable to set socket nonblocking flags! %s \n",
380                               strerror(errno));
381                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
382                 close(IO->sock);
383                 return eAbort;
384         }
385 /* TODO: maye we could use offsetof() to calc the position of data... 
386  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
387  */
388         ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
389         IO->recv_event.data = IO;
390         ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
391         IO->send_event.data = IO;
392
393         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
394         IO->conn_fail.data = IO;
395         ev_timer_init(&IO->rw_timeout, IO_Timout_callback, first_rw_timeout, 0);
396         IO->rw_timeout.data = IO;
397
398         if (IO->IP6)
399                 rc = connect(IO->sock, &IO->Addr, sizeof(struct sockaddr_in6));
400         else
401                 rc = connect(IO->sock, (struct sockaddr_in *)&IO->Addr, sizeof(struct sockaddr_in));
402
403         if (rc >= 0){
404 ////            freeaddrinfo(res);
405                 set_start_callback(event_base, IO, 0);
406                 ev_timer_start(event_base, &IO->rw_timeout);
407                 return IO->NextState;
408         }
409         else if (errno == EINPROGRESS) {
410
411                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->sock, EV_READ|EV_WRITE);
412                 IO->conn_event.data = IO;
413
414                 ev_io_start(event_base, &IO->conn_event);
415                 ev_timer_start(event_base, &IO->conn_fail);
416                 return IO->NextState;
417         }
418         else {
419                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
420                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
421                 assert(IO->ConnFail);
422                 IO->ConnFail(IO);
423                 return eAbort;
424         }
425         return IO->NextState;
426 }
427
428 void SetNextTimeout(AsyncIO *IO, double timeout)
429 {
430         IO->rw_timeout.repeat = timeout;
431         ev_timer_again (event_base,  &IO->rw_timeout);
432 }
433
434 eNextState InitEventIO(AsyncIO *IO, 
435                        void *pData, 
436                        double conn_timeout, 
437                        double first_rw_timeout,
438                        int ReadFirst)
439 {
440         IO->Data = pData;
441         
442         if (ReadFirst) {
443                 IO->NextState = eReadMessage;
444         }
445         else {
446                 IO->NextState = eSendReply;
447         }
448         return event_connect_socket(IO, conn_timeout, first_rw_timeout);
449 }