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