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