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