libev migration - add shutdown handlers
[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         if (IO->sock != 0)
131         {
132                 ev_io_stop(event_base, &IO->send_event);
133                 ev_io_stop(event_base, &IO->recv_event);
134                 ev_timer_stop (event_base, &IO->rw_timeout);
135                 close(IO->sock);
136                 IO->sock = 0;
137                 IO->SendBuf.fd = 0;
138                 IO->RecvBuf.fd = 0;
139         }
140         if (IO->DNSChannel != NULL) {
141                 ares_destroy(IO->DNSChannel);
142                 ev_io_stop(event_base, &IO->dns_recv_event);
143                 ev_io_stop(event_base, &IO->dns_send_event);
144                 IO->DNSChannel = NULL;
145         }
146         assert(IO->Terminate);
147         IO->Terminate(IO);
148         
149 }
150
151
152 eReadState HandleInbound(AsyncIO *IO)
153 {
154         eReadState Finished = eBufferNotEmpty;
155         
156         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
157                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
158                                 
159                 }
160                 else { /* Reading lines... */
161 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
162                         if (IO->LineReader)
163                                 Finished = IO->LineReader(IO);
164                         else 
165                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
166                                 
167                         switch (Finished) {
168                         case eMustReadMore: /// read new from socket... 
169                                 return Finished;
170                                 break;
171                         case eBufferNotEmpty: /* shouldn't happen... */
172                         case eReadSuccess: /// done for now...
173                                 break;
174                         case eReadFail: /// WHUT?
175                                 ///todo: shut down! 
176                                 break;
177                         }
178                                         
179                 }
180                         
181                 if (Finished != eMustReadMore) {
182                         assert(IO->ReadDone);
183                         ev_io_stop(event_base, &IO->recv_event);
184                         IO->NextState = IO->ReadDone(IO);
185                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
186                 }
187         }
188
189
190         if ((IO->NextState == eSendReply) ||
191             (IO->NextState == eSendMore))
192         {
193                 assert(IO->SendDone);
194                 IO->NextState = IO->SendDone(IO);
195                 ev_io_start(event_base, &IO->send_event);
196         }
197         else if ((IO->NextState == eTerminateConnection) ||
198                  (IO->NextState == eAbort) )
199                 ShutDownCLient(IO);
200         return Finished;
201 }
202
203
204 static void
205 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
206 {
207         int rc;
208         AsyncIO *IO = watcher->data;
209
210         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
211
212         if (rc == 0)
213         {               
214 #ifdef BIGBAD_IODBG
215                 {
216                         int rv = 0;
217                         char fn [SIZ];
218                         FILE *fd;
219                         const char *pch = ChrPtr(IO->SendBuf.Buf);
220                         const char *pchh = IO->SendBuf.ReadWritePointer;
221                         long nbytes;
222
223                         if (pchh == NULL)
224                                 pchh = pch;
225                         
226                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
227                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->sock);
228                 
229                         fd = fopen(fn, "a+");
230                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
231                                 nbytes);
232                         rv = fwrite(pchh, nbytes, 1, fd);
233                         fprintf(fd, "]\n");
234                 
235                         
236                         fclose(fd);
237                 }
238 #endif
239                 ev_io_stop(event_base, &IO->send_event);
240                 switch (IO->NextState) {
241                 case eSendReply:
242                         break;
243                 case eSendMore:
244                         assert(IO->SendDone);
245                         IO->NextState = IO->SendDone(IO);
246
247                         if ((IO->NextState == eTerminateConnection) ||
248                             (IO->NextState == eAbort) )
249                                 ShutDownCLient(IO);
250                         else {
251                                 ev_io_start(event_base, &IO->send_event);
252                         }
253                         break;
254                 case eReadMessage:
255                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
256                                 HandleInbound(IO);
257                         }
258                         else {
259                                 ev_io_start(event_base, &IO->recv_event);
260                         }
261
262                         break;
263                 case eTerminateConnection:
264                 case eAbort:
265                         break;
266                 }
267         }
268         else if (rc < 0) {
269                 assert(IO->Timeout);
270                 IO->Timeout(IO);
271         }
272         /* else : must write more. */
273 }
274 static void
275 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
276 {
277         
278         switch(IO->NextState) {
279         case eReadMessage:
280                 ev_io_start(event_base, &IO->recv_event);
281                 break;
282         case eSendReply:
283         case eSendMore:
284                 IO_send_callback(loop, &IO->send_event, revents);
285                 break;
286         case eTerminateConnection:
287         case eAbort:
288                 /// TODO: WHUT?
289                 break;
290         }
291 }
292
293 static void
294 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
295 {
296         AsyncIO *IO = watcher->data;
297
298         ev_timer_stop (event_base, &IO->rw_timeout);
299         assert(IO->Timeout);
300         IO->Timeout(IO);
301 }
302 static void
303 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
304 {
305         AsyncIO *IO = watcher->data;
306
307         ev_timer_stop (event_base, &IO->conn_fail);
308         ev_io_stop(loop, &IO->conn_event);
309         assert(IO->ConnFail);
310         IO->ConnFail(IO);
311 }
312 static void
313 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
314 {
315         AsyncIO *IO = watcher->data;
316
317         ev_io_stop(loop, &IO->conn_event);
318         ev_timer_stop (event_base, &IO->conn_fail);
319         set_start_callback(loop, IO, revents);
320 }
321 static void
322 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
323 {
324         ssize_t nbytes;
325         AsyncIO *IO = watcher->data;
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                 assert(IO->Timeout);
332                 IO->Timeout(IO); /* this is a timeout... */
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 void
341 IO_postdns_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
342 {
343         AsyncIO *IO = watcher->data;
344         CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
345
346         IO->PostDNS(IO);
347 }
348
349 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
350 {
351         int fdflags; 
352         int rc = -1;
353
354         IO->SendBuf.fd = IO->RecvBuf.fd = 
355                 IO->sock = socket(
356                         (IO->IP6)?PF_INET6:PF_INET, 
357                         SOCK_STREAM, 
358                         IPPROTO_TCP);
359
360         if (IO->sock < 0) {
361                 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
362                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
363 //              freeaddrinfo(res);
364                 return eAbort;
365         }
366         fdflags = fcntl(IO->sock, F_GETFL);
367         if (fdflags < 0) {
368                 CtdlLogPrintf(CTDL_DEBUG,
369                               "EVENT: unable to get socket flags! %s \n",
370                               strerror(errno));
371                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
372                 return eAbort;
373         }
374         fdflags = fdflags | O_NONBLOCK;
375         if (fcntl(IO->sock, F_SETFL, fdflags) < 0) {
376                 CtdlLogPrintf(CTDL_DEBUG,
377                               "EVENT: unable to set socket nonblocking flags! %s \n",
378                               strerror(errno));
379                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
380                 close(IO->sock);
381                 return eAbort;
382         }
383 /* TODO: maye we could use offsetof() to calc the position of data... 
384  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
385  */
386         ev_io_init(&IO->recv_event, IO_recv_callback, IO->sock, EV_READ);
387         IO->recv_event.data = IO;
388         ev_io_init(&IO->send_event, IO_send_callback, IO->sock, EV_WRITE);
389         IO->send_event.data = IO;
390
391         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
392         IO->conn_fail.data = IO;
393         ev_timer_init(&IO->rw_timeout, IO_Timout_callback, first_rw_timeout, 0);
394         IO->rw_timeout.data = IO;
395
396         if (IO->IP6)
397                 rc = connect(IO->sock, &IO->Addr, sizeof(struct sockaddr_in6));
398         else
399                 rc = connect(IO->sock, (struct sockaddr_in *)&IO->Addr, sizeof(struct sockaddr_in));
400
401         if (rc >= 0){
402 ////            freeaddrinfo(res);
403                 set_start_callback(event_base, IO, 0);
404                 ev_timer_start(event_base, &IO->rw_timeout);
405                 return IO->NextState;
406         }
407         else if (errno == EINPROGRESS) {
408
409                 ev_io_init(&IO->conn_event, IO_connestd_callback, IO->sock, EV_READ|EV_WRITE);
410                 IO->conn_event.data = IO;
411
412                 ev_io_start(event_base, &IO->conn_event);
413                 ev_timer_start(event_base, &IO->conn_fail);
414                 return IO->NextState;
415         }
416         else {
417                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
418                 StrBufPrintf(IO->ErrMsg, "Failed to connect: %s", strerror(errno));
419                 assert(IO->ConnFail);
420                 IO->ConnFail(IO);
421                 return eAbort;
422         }
423         return IO->NextState;
424 }
425
426 void SetNextTimeout(AsyncIO *IO, double timeout)
427 {
428         IO->rw_timeout.repeat = timeout;
429         ev_timer_again (event_base,  &IO->rw_timeout);
430 }
431
432 eNextState InitEventIO(AsyncIO *IO, 
433                        void *pData, 
434                        double conn_timeout, 
435                        double first_rw_timeout,
436                        int ReadFirst)
437 {
438         IO->Data = pData;
439         
440         if (ReadFirst) {
441                 IO->NextState = eReadMessage;
442         }
443         else {
444                 IO->NextState = eSendReply;
445         }
446         return event_connect_socket(IO, conn_timeout, first_rw_timeout);
447 }