78876b50271296bb19196de5033537dd70113412
[citadel.git] / citadel / event_client.c
1 /*
2  * Copyright (c) 1998-2012 by the citadel.org team
3  *
4  * This program is open source software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License, version 3.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  */
12
13 #include "sysdep.h"
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <termios.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #include <pwd.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <syslog.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35 #include <sys/wait.h>
36 #include <ctype.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <assert.h>
43 #if HAVE_BACKTRACE
44 #include <execinfo.h>
45 #endif
46
47 #include <libcitadel.h>
48 #include "citadel.h"
49 #include "server.h"
50 #include "citserver.h"
51 #include "support.h"
52 #include "config.h"
53 #include "control.h"
54 #include "user_ops.h"
55 #include "database.h"
56 #include "msgbase.h"
57 #include "internet_addressing.h"
58 #include "genstamp.h"
59 #include "domain.h"
60 #include "clientsocket.h"
61 #include "locate_host.h"
62 #include "citadel_dirs.h"
63
64 #include "event_client.h"
65 #include "ctdl_module.h"
66
67
68 ConstStr IOStates[] = {
69         {HKEY("DB Queue")},
70         {HKEY("DB Q Next")},
71         {HKEY("DB Attach")},
72         {HKEY("DB Next")},
73         {HKEY("DB Stop")},
74         {HKEY("DB Exit")},
75         {HKEY("DB Terminate")},
76         {HKEY("IO Queue")},
77         {HKEY("IO Attach")},
78         {HKEY("IO Connect Socket")},
79         {HKEY("IO Abort")},
80         {HKEY("IO Timeout")},
81         {HKEY("IO ConnFail")},
82         {HKEY("IO ConnFail Now")},
83         {HKEY("IO Conn Now")},
84         {HKEY("IO Conn Wait")},
85         {HKEY("Curl Q")},
86         {HKEY("Curl Start")},
87         {HKEY("Curl Shotdown")},
88         {HKEY("Curl More IO")},
89         {HKEY("Curl Got IO")},
90         {HKEY("Curl Got Data")},
91         {HKEY("Curl Got Status")},
92         {HKEY("C-Ares Start")},
93         {HKEY("C-Ares IO Done")},
94         {HKEY("C-Ares Finished")},
95         {HKEY("C-Ares exit")},
96         {HKEY("Killing")},
97         {HKEY("Exit")}
98 };
99
100 void SetEVState(AsyncIO *IO, eIOState State)
101 {
102
103         CitContext* CCC = IO->CitContext;
104         if (CCC != NULL)
105                 memcpy(CCC->lastcmdname, IOStates[State].Key, IOStates[State].len + 1);
106
107 }
108
109
110 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
111 static void IO_abort_shutdown_callback(struct ev_loop *loop,
112                                        ev_cleanup *watcher,
113                                        int revents);
114
115
116 /*------------------------------------------------------------------------------
117  *                              Server DB IO
118  *----------------------------------------------------------------------------*/
119 extern int evdb_count;
120 extern pthread_mutex_t DBEventQueueMutex;
121 extern pthread_mutex_t DBEventExitQueueMutex;
122 extern HashList *DBInboundEventQueue;
123 extern struct ev_loop *event_db;
124 extern ev_async DBAddJob;
125 extern ev_async DBExitEventLoop;
126
127 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
128 {
129         IOAddHandler *h;
130         int i;
131
132         SetEVState(IO, eDBQ);
133         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
134         h->IO = IO;
135         h->EvAttch = CB;
136         ev_cleanup_init(&IO->db_abort_by_shutdown,
137                         IO_abort_shutdown_callback);
138         IO->db_abort_by_shutdown.data = IO;
139
140         pthread_mutex_lock(&DBEventQueueMutex);
141         if (DBInboundEventQueue == NULL)
142         {
143                 /* shutting down... */
144                 free(h);
145                 EVM_syslog(LOG_DEBUG, "DBEVENT Q exiting.\n");
146                 pthread_mutex_unlock(&DBEventQueueMutex);
147                 return eAbort;
148         }
149         EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
150         i = ++evdb_count ;
151         Put(DBInboundEventQueue, IKEY(i), h, NULL);
152         pthread_mutex_unlock(&DBEventQueueMutex);
153
154         pthread_mutex_lock(&DBEventExitQueueMutex);
155         if (event_db == NULL)
156         {
157                 pthread_mutex_unlock(&DBEventExitQueueMutex);
158                 return eAbort;
159         }
160         ev_async_send (event_db, &DBAddJob);
161         pthread_mutex_unlock(&DBEventExitQueueMutex);
162
163         EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
164         return eDBQuery;
165 }
166
167 void StopDBWatchers(AsyncIO *IO)
168 {
169         SetEVState(IO, eDBStop);
170         ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
171         ev_idle_stop(event_db, &IO->db_unwind_stack);
172 }
173
174 void ShutDownDBCLient(AsyncIO *IO)
175 {
176         CitContext *Ctx =IO->CitContext;
177         become_session(Ctx);
178
179         SetEVState(IO, eDBTerm);
180         EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
181         StopDBWatchers(IO);
182
183         assert(IO->DBTerminate);
184         IO->DBTerminate(IO);
185 }
186
187 void
188 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
189 {
190         AsyncIO *IO = watcher->data;
191
192         SetEVState(IO, eDBNext);
193         IO->Now = ev_now(event_db);
194         EV_syslog(LOG_DEBUG, "%s()", __FUNCTION__);
195         become_session(IO->CitContext);
196
197         ev_idle_stop(event_db, &IO->db_unwind_stack);
198
199         assert(IO->NextDBOperation);
200         switch (IO->NextDBOperation(IO))
201         {
202         case eDBQuery:
203                 break;
204         case eSendDNSQuery:
205         case eReadDNSReply:
206         case eConnect:
207         case eSendReply:
208         case eSendMore:
209         case eSendFile:
210         case eReadMessage:
211         case eReadMore:
212         case eReadPayload:
213         case eReadFile:
214                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
215                 break;
216         case eTerminateConnection:
217         case eAbort:
218                 ev_idle_stop(event_db, &IO->db_unwind_stack);
219                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
220                 ShutDownDBCLient(IO);
221         }
222 }
223
224 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
225 {
226         SetEVState(IO, eQDBNext);
227         IO->NextDBOperation = CB;
228         ev_idle_init(&IO->db_unwind_stack,
229                      DB_PerformNext);
230         IO->db_unwind_stack.data = IO;
231         ev_idle_start(event_db, &IO->db_unwind_stack);
232         return eDBQuery;
233 }
234
235 /*------------------------------------------------------------------------------
236  *                      Client IO
237  *----------------------------------------------------------------------------*/
238 extern int evbase_count;
239 extern pthread_mutex_t EventQueueMutex;
240 extern pthread_mutex_t EventExitQueueMutex; 
241 extern HashList *InboundEventQueue;
242 extern struct ev_loop *event_base;
243 extern ev_async AddJob;
244 extern ev_async ExitEventLoop;
245
246 static void IO_abort_shutdown_callback(struct ev_loop *loop,
247                                        ev_cleanup *watcher,
248                                        int revents)
249 {
250         AsyncIO *IO = watcher->data;
251
252         SetEVState(IO, eIOAbort);
253         EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
254         IO->Now = ev_now(event_base);
255         assert(IO->ShutdownAbort);
256         IO->ShutdownAbort(IO);
257 }
258
259
260 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
261 {
262         IOAddHandler *h;
263         int i;
264
265         SetEVState(IO, eIOQ);
266         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
267         h->IO = IO;
268         h->EvAttch = CB;
269         ev_cleanup_init(&IO->abort_by_shutdown,
270                         IO_abort_shutdown_callback);
271         IO->abort_by_shutdown.data = IO;
272
273         pthread_mutex_lock(&EventQueueMutex);
274         if (InboundEventQueue == NULL)
275         {
276                 free(h);
277                 /* shutting down... */
278                 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
279                 pthread_mutex_unlock(&EventQueueMutex);
280                 return eAbort;
281         }
282         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
283         i = ++evbase_count;
284         Put(InboundEventQueue, IKEY(i), h, NULL);
285         pthread_mutex_unlock(&EventQueueMutex);
286
287         pthread_mutex_lock(&EventExitQueueMutex);
288         if (event_base == NULL) {
289                 pthread_mutex_unlock(&EventExitQueueMutex);
290                 return eAbort;
291         }
292         ev_async_send (event_base, &AddJob);
293         pthread_mutex_unlock(&EventExitQueueMutex);
294         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
295         return eSendReply;
296 }
297
298 eNextState EventQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
299 {
300         StopClientWatchers(IO, 0);
301         return QueueDBOperation(IO, CB);
302 }
303 eNextState DBQueueEventContext(AsyncIO *IO, IO_CallBack CB)
304 {
305         StopDBWatchers(IO);
306         return QueueEventContext(IO, CB);
307 }
308
309 extern eNextState evcurl_handle_start(AsyncIO *IO);
310
311 eNextState QueueCurlContext(AsyncIO *IO)
312 {
313         IOAddHandler *h;
314         int i;
315
316         SetEVState(IO, eCurlQ);
317         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
318         h->IO = IO;
319         h->EvAttch = evcurl_handle_start;
320
321         pthread_mutex_lock(&EventQueueMutex);
322         if (InboundEventQueue == NULL)
323         {
324                 /* shutting down... */
325                 free(h);
326                 EVM_syslog(LOG_DEBUG, "EVENT Q exiting.\n");
327                 pthread_mutex_unlock(&EventQueueMutex);
328                 return eAbort;
329         }
330
331         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
332         i = ++evbase_count;
333         Put(InboundEventQueue, IKEY(i), h, NULL);
334         pthread_mutex_unlock(&EventQueueMutex);
335
336         pthread_mutex_lock(&EventExitQueueMutex);
337         if (event_base == NULL) {
338                 pthread_mutex_unlock(&EventExitQueueMutex);
339                 return eAbort;
340         }
341         ev_async_send (event_base, &AddJob);
342         pthread_mutex_unlock(&EventExitQueueMutex);
343
344         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
345         return eSendReply;
346 }
347
348 eNextState CurlQueueDBOperation(AsyncIO *IO, IO_CallBack CB)
349 {
350         StopCurlWatchers(IO);
351         return QueueDBOperation(IO, CB);
352 }
353
354
355 void DestructCAres(AsyncIO *IO);
356 void FreeAsyncIOContents(AsyncIO *IO)
357 {
358         CitContext *Ctx = IO->CitContext;
359
360         FreeStrBuf(&IO->IOBuf);
361         FreeStrBuf(&IO->SendBuf.Buf);
362         FreeStrBuf(&IO->RecvBuf.Buf);
363
364         DestructCAres(IO);
365
366         FreeURL(&IO->ConnectMe);
367         FreeStrBuf(&IO->HttpReq.ReplyData);
368
369         if (Ctx) {
370                 Ctx->state = CON_IDLE;
371                 Ctx->kill_me = 1;
372                 IO->CitContext = NULL;
373         }
374 }
375
376
377 void StopClientWatchers(AsyncIO *IO, int CloseFD)
378 {
379         ev_timer_stop (event_base, &IO->rw_timeout);
380         ev_timer_stop(event_base, &IO->conn_fail);
381         ev_idle_stop(event_base, &IO->unwind_stack);
382         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
383
384         ev_io_stop(event_base, &IO->conn_event);
385         ev_io_stop(event_base, &IO->send_event);
386         ev_io_stop(event_base, &IO->recv_event);
387
388         if (CloseFD && (IO->SendBuf.fd > 0)) {
389                 close(IO->SendBuf.fd);
390                 IO->SendBuf.fd = 0;
391                 IO->RecvBuf.fd = 0;
392         }
393 }
394
395 void StopCurlWatchers(AsyncIO *IO)
396 {
397         ev_timer_stop (event_base, &IO->rw_timeout);
398         ev_timer_stop(event_base, &IO->conn_fail);
399         ev_idle_stop(event_base, &IO->unwind_stack);
400         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
401
402         ev_io_stop(event_base, &IO->conn_event);
403         ev_io_stop(event_base, &IO->send_event);
404         ev_io_stop(event_base, &IO->recv_event);
405
406         curl_easy_cleanup(IO->HttpReq.chnd);
407         IO->HttpReq.chnd = NULL;
408
409         if (IO->SendBuf.fd != 0) {
410                 close(IO->SendBuf.fd);
411         }
412         IO->SendBuf.fd = 0;
413         IO->RecvBuf.fd = 0;
414 }
415
416 void ShutDownCLient(AsyncIO *IO)
417 {
418         CitContext *Ctx =IO->CitContext;
419
420         SetEVState(IO, eExit);
421         become_session(Ctx);
422
423         EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
424
425         StopClientWatchers(IO, 1);
426
427         if (IO->DNS.Channel != NULL) {
428                 ares_destroy(IO->DNS.Channel);
429                 EV_DNS_LOG_STOP(DNS.recv_event);
430                 EV_DNS_LOG_STOP(DNS.send_event);
431                 ev_io_stop(event_base, &IO->DNS.recv_event);
432                 ev_io_stop(event_base, &IO->DNS.send_event);
433                 IO->DNS.Channel = NULL;
434         }
435         assert(IO->Terminate);
436         IO->Terminate(IO);
437 }
438
439 void PostInbound(AsyncIO *IO)
440 {
441         switch (IO->NextState) {
442         case eSendFile:
443                 ev_io_start(event_base, &IO->send_event);
444                 break;
445         case eSendReply:
446         case eSendMore:
447                 assert(IO->SendDone);
448                 IO->NextState = IO->SendDone(IO);
449                 switch (IO->NextState)
450                 {
451                 case eSendFile:
452                 case eSendReply:
453                 case eSendMore:
454                 case eReadMessage:
455                 case eReadPayload:
456                 case eReadMore:
457                 case eReadFile:
458                         ev_io_start(event_base, &IO->send_event);
459                         break;
460                 case eDBQuery:
461                         StopClientWatchers(IO, 0);
462                 default:
463                         break;
464                 }
465                 break;
466         case eReadPayload:
467         case eReadMore:
468         case eReadFile:
469                 ev_io_start(event_base, &IO->recv_event);
470                 break;
471         case eTerminateConnection:
472                 ShutDownCLient(IO);
473                 break;
474         case eAbort:
475                 ShutDownCLient(IO);
476                 break;
477         case eSendDNSQuery:
478         case eReadDNSReply:
479         case eDBQuery:
480         case eConnect:
481         case eReadMessage:
482                 break;
483         }
484 }
485 eReadState HandleInbound(AsyncIO *IO)
486 {
487         const char *Err = NULL;
488         eReadState Finished = eBufferNotEmpty;
489
490         become_session(IO->CitContext);
491
492         while ((Finished == eBufferNotEmpty) &&
493                ((IO->NextState == eReadMessage)||
494                 (IO->NextState == eReadMore)||
495                 (IO->NextState == eReadFile)||
496                 (IO->NextState == eReadPayload)))
497         {
498                 /* Reading lines...
499                  * lex line reply in callback,
500                  * or do it ourselves.
501                  * i.e. as nnn-blabla means continue reading in SMTP
502                  */
503                 if ((IO->NextState == eReadFile) &&
504                     (Finished == eBufferNotEmpty))
505                 {
506                         Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
507                         if (Finished == eReadSuccess)
508                         {
509                                 IO->NextState = eSendReply;
510                         }
511                 }
512                 else if (IO->LineReader)
513                         Finished = IO->LineReader(IO);
514                 else
515                         Finished = StrBufChunkSipLine(IO->IOBuf,
516                                                       &IO->RecvBuf);
517
518                 switch (Finished) {
519                 case eMustReadMore: /// read new from socket...
520                         break;
521                 case eBufferNotEmpty: /* shouldn't happen... */
522                 case eReadSuccess: /// done for now...
523                         break;
524                 case eReadFail: /// WHUT?
525                                 ///todo: shut down!
526                         break;
527                 }
528
529                 if (Finished != eMustReadMore) {
530                         assert(IO->ReadDone);
531                         ev_io_stop(event_base, &IO->recv_event);
532                         IO->NextState = IO->ReadDone(IO);
533                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
534                 }
535         }
536
537         PostInbound(IO);
538
539         return Finished;
540 }
541
542
543 static void
544 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
545 {
546         int rc;
547         AsyncIO *IO = watcher->data;
548         const char *errmsg = NULL;
549
550         IO->Now = ev_now(event_base);
551         become_session(IO->CitContext);
552 #ifdef BIGBAD_IODBG
553         {
554                 int rv = 0;
555                 char fn [SIZ];
556                 FILE *fd;
557                 const char *pch = ChrPtr(IO->SendBuf.Buf);
558                 const char *pchh = IO->SendBuf.ReadWritePointer;
559                 long nbytes;
560
561                 if (pchh == NULL)
562                         pchh = pch;
563
564                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
565                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
566                          ((CitContext*)(IO->CitContext))->ServiceName,
567                          IO->SendBuf.fd);
568
569                 fd = fopen(fn, "a+");
570                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
571                         nbytes);
572                 rv = fwrite(pchh, nbytes, 1, fd);
573                 if (!rv) printf("failed to write debug to %s!\n", fn);
574                 fprintf(fd, "]\n");
575 #endif
576                 switch (IO->NextState) {
577                 case eSendFile:
578                         rc = FileSendChunked(&IO->IOB, &errmsg);
579                         if (rc < 0)
580                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
581                         break;
582                 default:
583                         rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
584                                                              0,
585                                                              &IO->SendBuf);
586                 }
587
588 #ifdef BIGBAD_IODBG
589                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
590                 fclose(fd);
591         }
592 #endif
593         if (rc == 0)
594         {
595                 ev_io_stop(event_base, &IO->send_event);
596                 switch (IO->NextState) {
597                 case eSendMore:
598                         assert(IO->SendDone);
599                         IO->NextState = IO->SendDone(IO);
600
601                         if ((IO->NextState == eTerminateConnection) ||
602                             (IO->NextState == eAbort) )
603                                 ShutDownCLient(IO);
604                         else {
605                                 ev_io_start(event_base, &IO->send_event);
606                         }
607                         break;
608                 case eSendFile:
609                         if (IO->IOB.ChunkSendRemain > 0) {
610                                 ev_io_start(event_base, &IO->recv_event);
611                                 SetNextTimeout(IO, 100.0);
612
613                         } else {
614                                 assert(IO->ReadDone);
615                                 IO->NextState = IO->ReadDone(IO);
616                                 switch(IO->NextState) {
617                                 case eSendDNSQuery:
618                                 case eReadDNSReply:
619                                 case eDBQuery:
620                                 case eConnect:
621                                         break;
622                                 case eSendReply:
623                                 case eSendMore:
624                                 case eSendFile:
625                                         ev_io_start(event_base,
626                                                     &IO->send_event);
627                                         break;
628                                 case eReadMessage:
629                                 case eReadMore:
630                                 case eReadPayload:
631                                 case eReadFile:
632                                         break;
633                                 case eTerminateConnection:
634                                 case eAbort:
635                                         break;
636                                 }
637                         }
638                         break;
639                 case eSendReply:
640                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
641                         break;
642                     IO->NextState = eReadMore;
643                 case eReadMore:
644                 case eReadMessage:
645                 case eReadPayload:
646                 case eReadFile:
647                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
648                         {
649                                 HandleInbound(IO);
650                         }
651                         else {
652                                 ev_io_start(event_base, &IO->recv_event);
653                         }
654
655                         break;
656                 case eDBQuery:
657                         /*
658                          * we now live in another queue,
659                          * so we have to unregister.
660                          */
661                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
662                         break;
663                 case eSendDNSQuery:
664                 case eReadDNSReply:
665                 case eConnect:
666                 case eTerminateConnection:
667                 case eAbort:
668                         break;
669                 }
670         }
671         else if (rc < 0) {
672                 if (errno != EAGAIN) {
673                         StopClientWatchers(IO, 1);
674                         EV_syslog(LOG_DEBUG,
675                                   "IO_send_callback(): Socket Invalid! [%d] [%s] [%d]\n",
676                                   errno, strerror(errno), IO->SendBuf.fd);
677                         StrBufPrintf(IO->ErrMsg,
678                                      "Socket Invalid! [%s]",
679                                      strerror(errno));
680                         SetNextTimeout(IO, 0.01);
681                 }
682         }
683         /* else : must write more. */
684 }
685 static void
686 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
687 {
688         ev_timer_stop(event_base, &IO->conn_fail);
689         ev_timer_start(event_base, &IO->rw_timeout);
690
691         switch(IO->NextState) {
692         case eReadMore:
693         case eReadMessage:
694         case eReadFile:
695                 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
696                 ev_io_start(event_base, &IO->recv_event);
697                 break;
698         case eSendReply:
699         case eSendMore:
700         case eReadPayload:
701         case eSendFile:
702                 become_session(IO->CitContext);
703                 IO_send_callback(loop, &IO->send_event, revents);
704                 break;
705         case eDBQuery:
706         case eSendDNSQuery:
707         case eReadDNSReply:
708         case eConnect:
709         case eTerminateConnection:
710         case eAbort:
711                 /// TODO: WHUT?
712                 break;
713         }
714 }
715
716 static void
717 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
718 {
719         AsyncIO *IO = watcher->data;
720
721         SetEVState(IO, eIOTimeout);
722         IO->Now = ev_now(event_base);
723         ev_timer_stop (event_base, &IO->rw_timeout);
724         become_session(IO->CitContext);
725
726         if (IO->SendBuf.fd != 0)
727         {
728                 ev_io_stop(event_base, &IO->send_event);
729                 ev_io_stop(event_base, &IO->recv_event);
730                 ev_timer_stop (event_base, &IO->rw_timeout);
731                 close(IO->SendBuf.fd);
732                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
733         }
734
735         assert(IO->Timeout);
736         switch (IO->Timeout(IO))
737         {
738         case eAbort:
739                 ShutDownCLient(IO);
740         default:
741                 break;
742         }
743 }
744
745 static void
746 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
747 {
748         AsyncIO *IO = watcher->data;
749
750         SetEVState(IO, eIOConnfail);
751         IO->Now = ev_now(event_base);
752         ev_timer_stop (event_base, &IO->conn_fail);
753
754         if (IO->SendBuf.fd != 0)
755         {
756                 ev_io_stop(loop, &IO->conn_event);
757                 ev_io_stop(event_base, &IO->send_event);
758                 ev_io_stop(event_base, &IO->recv_event);
759                 ev_timer_stop (event_base, &IO->rw_timeout);
760                 close(IO->SendBuf.fd);
761                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
762         }
763         become_session(IO->CitContext);
764
765         assert(IO->ConnFail);
766         switch (IO->ConnFail(IO))
767         {
768         case eAbort:
769                 ShutDownCLient(IO);
770         default:
771                 break;
772
773         }
774 }
775
776 static void
777 IO_connfailimmediate_callback(struct ev_loop *loop,
778                               ev_idle *watcher,
779                               int revents)
780 {
781         AsyncIO *IO = watcher->data;
782
783         SetEVState(IO, eIOConnfailNow);
784         IO->Now = ev_now(event_base);
785         ev_idle_stop (event_base, &IO->conn_fail_immediate);
786
787         if (IO->SendBuf.fd != 0)
788         {
789                 close(IO->SendBuf.fd);
790                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
791         }
792         become_session(IO->CitContext);
793
794         assert(IO->ConnFail);
795         switch (IO->ConnFail(IO))
796         {
797         case eAbort:
798                 ShutDownCLient(IO);
799         default:
800                 break;
801
802         }
803 }
804
805 static void
806 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
807 {
808         AsyncIO *IO = watcher->data;
809         int             so_err = 0;
810         socklen_t       lon = sizeof(so_err);
811         int             err;
812
813         SetEVState(IO, eIOConnNow);
814         IO->Now = ev_now(event_base);
815         EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
816
817         ev_io_stop(loop, &IO->conn_event);
818         ev_timer_stop(event_base, &IO->conn_fail);
819
820         err = getsockopt(IO->SendBuf.fd,
821                          SOL_SOCKET,
822                          SO_ERROR,
823                          (void*)&so_err,
824                          &lon);
825
826         if ((err == 0) && (so_err != 0))
827         {
828                 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
829                           so_err,
830                           strerror(so_err));
831                 IO_connfail_callback(loop, &IO->conn_fail, revents);
832
833         }
834         else
835         {
836                 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
837                 set_start_callback(loop, IO, revents);
838         }
839 }
840
841 static void
842 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
843 {
844         const char *errmsg;
845         ssize_t nbytes;
846         AsyncIO *IO = watcher->data;
847
848         IO->Now = ev_now(event_base);
849         switch (IO->NextState) {
850         case eReadFile:
851                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
852                 if (nbytes < 0)
853                         StrBufPlain(IO->ErrMsg, errmsg, -1);
854                 else
855                 {
856                         if (IO->IOB.ChunkSendRemain == 0)
857                         {
858                                 IO->NextState = eSendReply;
859                                 assert(IO->ReadDone);
860                                 ev_io_stop(event_base, &IO->recv_event);
861                                 PostInbound(IO);
862                                 return;
863                         }
864                         else
865                                 return;
866                 }
867                 break;
868         default:
869                 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
870                                                         0,
871                                                         &IO->RecvBuf);
872                 break;
873         }
874
875 #ifdef BIGBAD_IODBG
876         {
877                 long nbytes;
878                 int rv = 0;
879                 char fn [SIZ];
880                 FILE *fd;
881                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
882                 const char *pchh = IO->RecvBuf.ReadWritePointer;
883
884                 if (pchh == NULL)
885                         pchh = pch;
886
887                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
888                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
889                          ((CitContext*)(IO->CitContext))->ServiceName,
890                          IO->SendBuf.fd);
891
892                 fd = fopen(fn, "a+");
893                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
894                         nbytes);
895                 rv = fwrite(pchh, nbytes, 1, fd);
896                 if (!rv) printf("failed to write debug to %s!\n", fn);
897                 fprintf(fd, "]\n");
898                 fclose(fd);
899         }
900 #endif
901         if (nbytes > 0) {
902                 HandleInbound(IO);
903         } else if (nbytes == 0) {
904                 StopClientWatchers(IO, 1);
905                 SetNextTimeout(IO, 0.01);
906                 return;
907         } else if (nbytes == -1) {
908                 if (errno != EAGAIN) {
909                         // FD is gone. kick it. 
910                         StopClientWatchers(IO, 1);
911                         EV_syslog(LOG_DEBUG,
912                                   "IO_recv_callback(): Socket Invalid! [%d] [%s] [%d]\n",
913                                   errno, strerror(errno), IO->SendBuf.fd);
914                         StrBufPrintf(IO->ErrMsg,
915                                      "Socket Invalid! [%s]",
916                                      strerror(errno));
917                         SetNextTimeout(IO, 0.01);
918                 }
919                 return;
920         }
921 }
922
923 void
924 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
925 {
926         AsyncIO *IO = watcher->data;
927
928         SetEVState(IO, eCaresFinished);
929         IO->Now = ev_now(event_base);
930         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
931         become_session(IO->CitContext);
932         assert(IO->DNS.Query->PostDNS);
933         switch (IO->DNS.Query->PostDNS(IO))
934         {
935         case eAbort:
936                 assert(IO->DNS.Fail);
937                 switch (IO->DNS.Fail(IO)) {
938                 case eAbort:
939 ////                    StopClientWatchers(IO);
940                         ShutDownCLient(IO);
941                 default:
942                         break;
943                 }
944         default:
945                 break;
946         }
947 }
948
949
950 eNextState EvConnectSock(AsyncIO *IO,
951                          double conn_timeout,
952                          double first_rw_timeout,
953                          int ReadFirst)
954 {
955         struct sockaddr_in egress_sin;
956         int fdflags;
957         int rc = -1;
958
959         SetEVState(IO, eIOConnectSock);
960         become_session(IO->CitContext);
961
962         if (ReadFirst) {
963                 IO->NextState = eReadMessage;
964         }
965         else {
966                 IO->NextState = eSendReply;
967         }
968
969         IO->SendBuf.fd = IO->RecvBuf.fd =
970                 socket(
971                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
972                         SOCK_STREAM,
973                         IPPROTO_TCP);
974
975         if (IO->SendBuf.fd < 0) {
976                 EV_syslog(LOG_ERR,
977                           "EVENT: socket() failed: %s\n",
978                           strerror(errno));
979
980                 StrBufPrintf(IO->ErrMsg,
981                              "Failed to create socket: %s",
982                              strerror(errno));
983                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
984                 return eAbort;
985         }
986         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
987         if (fdflags < 0) {
988                 EV_syslog(LOG_ERR,
989                           "EVENT: unable to get socket %d flags! %s \n",
990                           IO->SendBuf.fd,
991                           strerror(errno));
992                 StrBufPrintf(IO->ErrMsg,
993                              "Failed to get socket %d flags: %s",
994                              IO->SendBuf.fd,
995                              strerror(errno));
996                 close(IO->SendBuf.fd);
997                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
998                 return eAbort;
999         }
1000         fdflags = fdflags | O_NONBLOCK;
1001         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
1002                 EV_syslog(
1003                         LOG_ERR,
1004                         "EVENT: unable to set socket %d nonblocking flags! %s \n",
1005                         IO->SendBuf.fd,
1006                         strerror(errno));
1007                 StrBufPrintf(IO->ErrMsg,
1008                              "Failed to set socket flags: %s",
1009                              strerror(errno));
1010                 close(IO->SendBuf.fd);
1011                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
1012                 return eAbort;
1013         }
1014 /* TODO: maye we could use offsetof() to calc the position of data...
1015  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
1016  */
1017         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
1018         IO->recv_event.data = IO;
1019         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
1020         IO->send_event.data = IO;
1021
1022         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
1023         IO->conn_fail.data = IO;
1024         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
1025         IO->rw_timeout.data = IO;
1026
1027
1028
1029
1030         /* for debugging you may bypass it like this:
1031          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1032          * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
1033          *   inet_addr("127.0.0.1");
1034          */
1035         if (IO->ConnectMe->IPv6) {
1036                 rc = connect(IO->SendBuf.fd,
1037                              &IO->ConnectMe->Addr,
1038                              sizeof(struct sockaddr_in6));
1039         }
1040         else {
1041                 /* If citserver is bound to a specific IP address on the host, make
1042                  * sure we use that address for outbound connections.
1043                  */
1044         
1045                 memset(&egress_sin, 0, sizeof(egress_sin));
1046                 egress_sin.sin_family = AF_INET;
1047                 if (!IsEmptyStr(config.c_ip_addr)) {
1048                         egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
1049                         if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
1050                                 egress_sin.sin_addr.s_addr = INADDR_ANY;
1051                         }
1052
1053                         /* If this bind fails, no problem; we can still use INADDR_ANY */
1054                         bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
1055                 }
1056                 rc = connect(IO->SendBuf.fd,
1057                              (struct sockaddr_in *)&IO->ConnectMe->Addr,
1058                              sizeof(struct sockaddr_in));
1059         }
1060
1061         if (rc >= 0){
1062                 SetEVState(IO, eIOConnNow);
1063                 EV_syslog(LOG_DEBUG, "connect() = %d immediate success.\n", IO->SendBuf.fd);
1064                 set_start_callback(event_base, IO, 0);
1065                 return IO->NextState;
1066         }
1067         else if (errno == EINPROGRESS) {
1068                 SetEVState(IO, eIOConnWait);
1069                 EV_syslog(LOG_DEBUG, "connect() = %d have to wait now.\n", IO->SendBuf.fd);
1070
1071                 ev_io_init(&IO->conn_event,
1072                            IO_connestd_callback,
1073                            IO->SendBuf.fd,
1074                            EV_READ|EV_WRITE);
1075
1076                 IO->conn_event.data = IO;
1077
1078                 ev_io_start(event_base, &IO->conn_event);
1079                 ev_timer_start(event_base, &IO->conn_fail);
1080                 return IO->NextState;
1081         }
1082         else {
1083                 SetEVState(IO, eIOConnfail);
1084                 ev_idle_init(&IO->conn_fail_immediate,
1085                              IO_connfailimmediate_callback);
1086                 IO->conn_fail_immediate.data = IO;
1087                 ev_idle_start(event_base, &IO->conn_fail_immediate);
1088
1089                 EV_syslog(LOG_ERR,
1090                           "connect() = %d failed: %s\n",
1091                           IO->SendBuf.fd,
1092                           strerror(errno));
1093
1094                 StrBufPrintf(IO->ErrMsg,
1095                              "Failed to connect: %s",
1096                              strerror(errno));
1097                 return IO->NextState;
1098         }
1099         return IO->NextState;
1100 }
1101
1102 void SetNextTimeout(AsyncIO *IO, double timeout)
1103 {
1104         IO->rw_timeout.repeat = timeout;
1105         ev_timer_again (event_base,  &IO->rw_timeout);
1106 }
1107
1108
1109 eNextState ReAttachIO(AsyncIO *IO,
1110                       void *pData,
1111                       int ReadFirst)
1112 {
1113         SetEVState(IO, eIOAttach);
1114         IO->Data = pData;
1115         become_session(IO->CitContext);
1116         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1117         if (ReadFirst) {
1118                 IO->NextState = eReadMessage;
1119         }
1120         else {
1121                 IO->NextState = eSendReply;
1122         }
1123         set_start_callback(event_base, IO, 0);
1124
1125         return IO->NextState;
1126 }
1127
1128 void InitIOStruct(AsyncIO *IO,
1129                   void *Data,
1130                   eNextState NextState,
1131                   IO_LineReaderCallback LineReader,
1132                   IO_CallBack DNS_Fail,
1133                   IO_CallBack SendDone,
1134                   IO_CallBack ReadDone,
1135                   IO_CallBack Terminate,
1136                   IO_CallBack DBTerminate,
1137                   IO_CallBack ConnFail,
1138                   IO_CallBack Timeout,
1139                   IO_CallBack ShutdownAbort)
1140 {
1141         IO->Data          = Data;
1142
1143         IO->CitContext    = CloneContext(CC);
1144         IO->CitContext->session_specific_data = Data;
1145         IO->CitContext->IO = IO;
1146
1147         IO->NextState     = NextState;
1148
1149         IO->SendDone      = SendDone;
1150         IO->ReadDone      = ReadDone;
1151         IO->Terminate     = Terminate;
1152         IO->DBTerminate   = DBTerminate;
1153         IO->LineReader    = LineReader;
1154         IO->ConnFail      = ConnFail;
1155         IO->Timeout       = Timeout;
1156         IO->ShutdownAbort = ShutdownAbort;
1157
1158         IO->DNS.Fail      = DNS_Fail;
1159
1160         IO->SendBuf.Buf   = NewStrBufPlain(NULL, 1024);
1161         IO->RecvBuf.Buf   = NewStrBufPlain(NULL, 1024);
1162         IO->IOBuf         = NewStrBuf();
1163         EV_syslog(LOG_DEBUG,
1164                   "EVENT: Session lives at %p IO at %p \n",
1165                   Data, IO);
1166
1167 }
1168
1169 extern int evcurl_init(AsyncIO *IO);
1170
1171 int InitcURLIOStruct(AsyncIO *IO,
1172                      void *Data,
1173                      const char* Desc,
1174                      IO_CallBack SendDone,
1175                      IO_CallBack Terminate,
1176                      IO_CallBack DBTerminate,
1177                      IO_CallBack ShutdownAbort)
1178 {
1179         IO->Data          = Data;
1180
1181         IO->CitContext    = CloneContext(CC);
1182         IO->CitContext->session_specific_data = Data;
1183         IO->CitContext->IO = IO;
1184
1185         IO->SendDone      = SendDone;
1186         IO->Terminate     = Terminate;
1187         IO->DBTerminate   = DBTerminate;
1188         IO->ShutdownAbort = ShutdownAbort;
1189
1190         strcpy(IO->HttpReq.errdesc, Desc);
1191
1192
1193         return  evcurl_init(IO);
1194
1195 }
1196
1197
1198 typedef struct KillOtherSessionContext {
1199         AsyncIO IO;
1200         AsyncIO *OtherOne;
1201 }KillOtherSessionContext;
1202
1203 eNextState KillTerminate(AsyncIO *IO)
1204 {
1205         long id;
1206         KillOtherSessionContext *Ctx = (KillOtherSessionContext*)IO->Data;
1207         EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
1208         id = IO->ID;
1209         FreeAsyncIOContents(IO);
1210         memset(Ctx, 0, sizeof(KillOtherSessionContext));
1211         IO->ID = id; /* just for the case we want to analyze it in a coredump */
1212         free(Ctx);
1213         return eAbort;
1214
1215 }
1216
1217 eNextState KillShutdown(AsyncIO *IO)
1218 {
1219         return eTerminateConnection;
1220 }
1221
1222 eNextState KillOtherContextNow(AsyncIO *IO)
1223 {
1224         KillOtherSessionContext *Ctx = IO->Data;
1225
1226         SetEVState(IO, eKill);
1227
1228         if (Ctx->OtherOne->ShutdownAbort != NULL)
1229                 Ctx->OtherOne->ShutdownAbort(Ctx->OtherOne);
1230         return eTerminateConnection;
1231 }
1232
1233 void KillAsyncIOContext(AsyncIO *IO)
1234 {
1235         KillOtherSessionContext *Ctx;
1236
1237         Ctx = (KillOtherSessionContext*) malloc(sizeof(KillOtherSessionContext));
1238         memset(Ctx, 0, sizeof(KillOtherSessionContext));
1239         
1240         InitIOStruct(&Ctx->IO,
1241                      Ctx,
1242                      eReadMessage,
1243                      NULL,
1244                      NULL,
1245                      NULL,
1246                      NULL,
1247                      KillTerminate,
1248                      NULL,
1249                      NULL,
1250                      NULL,
1251                      KillShutdown);
1252
1253         Ctx->OtherOne = IO;
1254
1255         switch(IO->NextState) {
1256         case eSendDNSQuery:
1257         case eReadDNSReply:
1258
1259         case eConnect:
1260         case eSendReply:
1261         case eSendMore:
1262         case eSendFile:
1263
1264         case eReadMessage:
1265         case eReadMore:
1266         case eReadPayload:
1267         case eReadFile:
1268                 QueueEventContext(&Ctx->IO, KillOtherContextNow);
1269                 break;
1270         case eDBQuery:
1271                 QueueDBOperation(&Ctx->IO, KillOtherContextNow);
1272                 break;
1273         case eTerminateConnection:
1274         case eAbort:
1275                 /*hm, its already dying, dunno which Queue its in... */
1276                 free(Ctx);
1277         }
1278         
1279 }
1280
1281 extern int DebugEventLoopBacktrace;
1282 void EV_backtrace(AsyncIO *IO)
1283 {
1284 #ifdef HAVE_BACKTRACE
1285         void *stack_frames[50];
1286         size_t size, i;
1287         char **strings;
1288
1289         if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1290                 return;
1291         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1292         strings = backtrace_symbols(stack_frames, size);
1293         for (i = 0; i < size; i++) {
1294                 if (strings != NULL) {
1295                         EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1296                 }
1297                 else {
1298                         EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1299                 }
1300         }
1301         free(strings);
1302 #endif
1303 }
1304
1305
1306 ev_tstamp ctdl_ev_now (void)
1307 {
1308         return ev_now(event_base);
1309 }