Cleanup the event client struct, remove unused vars
[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->SendBuf.fd);
129
130         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
131
132         if (IO->SendBuf.fd != 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->SendBuf.fd);
138                 IO->SendBuf.fd = 0;
139                 IO->RecvBuf.fd = 0;
140         }
141         if (IO->DNSChannel != NULL) {
142                 ares_destroy(IO->DNSChannel);
143                 ev_io_stop(event_base, &IO->dns_recv_event);
144                 ev_io_stop(event_base, &IO->dns_send_event);
145                 IO->DNSChannel = NULL;
146         }
147         assert(IO->Terminate);
148         IO->Terminate(IO);
149         
150 }
151
152
153 eReadState HandleInbound(AsyncIO *IO)
154 {
155         eReadState Finished = eBufferNotEmpty;
156         
157         while ((Finished == eBufferNotEmpty) && (IO->NextState == eReadMessage)){
158                 if (IO->RecvBuf.nBlobBytesWanted != 0) { 
159                                 
160                 }
161                 else { /* Reading lines... */
162 //// lex line reply in callback, or do it ourselves. as nnn-blabla means continue reading in SMTP
163                         if (IO->LineReader)
164                                 Finished = IO->LineReader(IO);
165                         else 
166                                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
167                                 
168                         switch (Finished) {
169                         case eMustReadMore: /// read new from socket... 
170                                 return Finished;
171                                 break;
172                         case eBufferNotEmpty: /* shouldn't happen... */
173                         case eReadSuccess: /// done for now...
174                                 break;
175                         case eReadFail: /// WHUT?
176                                 ///todo: shut down! 
177                                 break;
178                         }
179                                         
180                 }
181                         
182                 if (Finished != eMustReadMore) {
183                         assert(IO->ReadDone);
184                         ev_io_stop(event_base, &IO->recv_event);
185                         IO->NextState = IO->ReadDone(IO);
186                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
187                 }
188         }
189
190
191         if ((IO->NextState == eSendReply) ||
192             (IO->NextState == eSendMore))
193         {
194                 assert(IO->SendDone);
195                 IO->NextState = IO->SendDone(IO);
196                 ev_io_start(event_base, &IO->send_event);
197         }
198         else if ((IO->NextState == eTerminateConnection) ||
199                  (IO->NextState == eAbort) )
200                 ShutDownCLient(IO);
201         return Finished;
202 }
203
204
205 static void
206 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
207 {
208         int rc;
209         AsyncIO *IO = watcher->data;
210
211         rc = StrBuf_write_one_chunk_callback(watcher->fd, 0/*TODO*/, &IO->SendBuf);
212
213         if (rc == 0)
214         {               
215 #ifdef BIGBAD_IODBG
216                 {
217                         int rv = 0;
218                         char fn [SIZ];
219                         FILE *fd;
220                         const char *pch = ChrPtr(IO->SendBuf.Buf);
221                         const char *pchh = IO->SendBuf.ReadWritePointer;
222                         long nbytes;
223
224                         if (pchh == NULL)
225                                 pchh = pch;
226                         
227                         nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
228                         snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d", "smtpev", IO->SendBuf.fd);
229                 
230                         fd = fopen(fn, "a+");
231                         fprintf(fd, "Read: BufSize: %ld BufContent: [",
232                                 nbytes);
233                         rv = fwrite(pchh, nbytes, 1, fd);
234                         fprintf(fd, "]\n");
235                 
236                         
237                         fclose(fd);
238                 }
239 #endif
240                 ev_io_stop(event_base, &IO->send_event);
241                 switch (IO->NextState) {
242                 case eSendReply:
243                         break;
244                 case eSendMore:
245                         assert(IO->SendDone);
246                         IO->NextState = IO->SendDone(IO);
247
248                         if ((IO->NextState == eTerminateConnection) ||
249                             (IO->NextState == eAbort) )
250                                 ShutDownCLient(IO);
251                         else {
252                                 ev_io_start(event_base, &IO->send_event);
253                         }
254                         break;
255                 case eReadMessage:
256                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty) {
257                                 HandleInbound(IO);
258                         }
259                         else {
260                                 ev_io_start(event_base, &IO->recv_event);
261                         }
262
263                         break;
264                 case eTerminateConnection:
265                 case eAbort:
266                         break;
267                 }
268         }
269         else if (rc < 0) {
270                 assert(IO->Timeout);
271                 IO->Timeout(IO);
272         }
273         /* else : must write more. */
274 }
275 static void
276 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
277 {
278         
279         switch(IO->NextState) {
280         case eReadMessage:
281                 ev_io_start(event_base, &IO->recv_event);
282                 break;
283         case eSendReply:
284         case eSendMore:
285                 IO_send_callback(loop, &IO->send_event, revents);
286                 break;
287         case eTerminateConnection:
288         case eAbort:
289                 /// TODO: WHUT?
290                 break;
291         }
292 }
293
294 static void
295 IO_Timout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
296 {
297         AsyncIO *IO = watcher->data;
298
299         ev_timer_stop (event_base, &IO->rw_timeout);
300         assert(IO->Timeout);
301         IO->Timeout(IO);
302 }
303 static void
304 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
305 {
306         AsyncIO *IO = watcher->data;
307
308         ev_timer_stop (event_base, &IO->conn_fail);
309         ev_io_stop(loop, &IO->conn_event);
310         assert(IO->ConnFail);
311         IO->ConnFail(IO);
312 }
313 static void
314 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
315 {
316         AsyncIO *IO = watcher->data;
317
318         ev_io_stop(loop, &IO->conn_event);
319         ev_timer_stop (event_base, &IO->conn_fail);
320         set_start_callback(loop, IO, revents);
321 }
322 static void
323 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
324 {
325         ssize_t nbytes;
326         AsyncIO *IO = watcher->data;
327
328         nbytes = StrBuf_read_one_chunk_callback(watcher->fd, 0 /*TODO */, &IO->RecvBuf);
329         if (nbytes > 0) {
330                 HandleInbound(IO);
331         } else if (nbytes == 0) {
332                 assert(IO->Timeout);
333                 IO->Timeout(IO); /* this is a timeout... */
334                 return;
335         } else if (nbytes == -1) {
336 /// TODO: FD is gone. kick it.        sock_buff_invoke_free(sb, errno);
337                 return;
338         }
339 }
340
341 void
342 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
343 {
344         AsyncIO *IO = watcher->data;
345         CtdlLogPrintf(CTDL_DEBUG, "event: %s\n", __FUNCTION__);
346
347         IO->DNSQuery->PostDNS(IO);
348 }
349
350 eNextState event_connect_socket(AsyncIO *IO, double conn_timeout, double first_rw_timeout)
351 {
352         int fdflags; 
353         int rc = -1;
354
355         IO->SendBuf.fd = IO->RecvBuf.fd = 
356                 socket(
357                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET, 
358                         SOCK_STREAM, 
359                         IPPROTO_TCP);
360
361         if (IO->SendBuf.fd < 0) {
362                 CtdlLogPrintf(CTDL_ERR, "EVENT: socket() failed: %s\n", strerror(errno));
363                 StrBufPrintf(IO->ErrMsg, "Failed to create socket: %s", strerror(errno));
364 //              freeaddrinfo(res);
365                 return eAbort;
366         }
367         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
368         if (fdflags < 0) {
369                 CtdlLogPrintf(CTDL_DEBUG,
370                               "EVENT: unable to get socket flags! %s \n",
371                               strerror(errno));
372                 StrBufPrintf(IO->ErrMsg, "Failed to get socket flags: %s", strerror(errno));
373                 return eAbort;
374         }
375         fdflags = fdflags | O_NONBLOCK;
376         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
377                 CtdlLogPrintf(CTDL_DEBUG,
378                               "EVENT: unable to set socket nonblocking flags! %s \n",
379                               strerror(errno));
380                 StrBufPrintf(IO->ErrMsg, "Failed to set socket flags: %s", strerror(errno));
381                 close(IO->SendBuf.fd);
382                 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
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->RecvBuf.fd, EV_READ);
389         IO->recv_event.data = IO;
390         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, 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->ConnectMe->IPv6)
399                 rc = connect(IO->SendBuf.fd, &IO->ConnectMe->Addr, sizeof(struct sockaddr_in6));
400         else
401                 rc = connect(IO->SendBuf.fd, (struct sockaddr_in *)&IO->ConnectMe->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->SendBuf.fd, 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 }