Updated the copyright declaration in several modules, removing any language which...
[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         }
302 }
303
304
305 void StopClientWatchers(AsyncIO *IO, int CloseFD)
306 {
307         ev_timer_stop (event_base, &IO->rw_timeout);
308         ev_timer_stop(event_base, &IO->conn_fail);
309         ev_idle_stop(event_base, &IO->unwind_stack);
310         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
311
312         ev_io_stop(event_base, &IO->conn_event);
313         ev_io_stop(event_base, &IO->send_event);
314         ev_io_stop(event_base, &IO->recv_event);
315
316         if (CloseFD && (IO->SendBuf.fd > 0)) {
317                 close(IO->SendBuf.fd);
318                 IO->SendBuf.fd = -1;
319                 IO->RecvBuf.fd = -1;
320         }
321 }
322
323 void StopCurlWatchers(AsyncIO *IO)
324 {
325         ev_timer_stop (event_base, &IO->rw_timeout);
326         ev_timer_stop(event_base, &IO->conn_fail);
327         ev_idle_stop(event_base, &IO->unwind_stack);
328         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
329
330         ev_io_stop(event_base, &IO->conn_event);
331         ev_io_stop(event_base, &IO->send_event);
332         ev_io_stop(event_base, &IO->recv_event);
333
334         if (IO->SendBuf.fd != 0) {
335                 close(IO->SendBuf.fd);
336         }
337         IO->SendBuf.fd = 0;
338         IO->RecvBuf.fd = 0;
339 }
340
341 void ShutDownCLient(AsyncIO *IO)
342 {
343         CitContext *Ctx =IO->CitContext;
344         become_session(Ctx);
345
346         EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
347
348         StopClientWatchers(IO, 1);
349
350         if (IO->DNS.Channel != NULL) {
351                 ares_destroy(IO->DNS.Channel);
352                 EV_DNS_LOG_STOP(DNS.recv_event);
353                 EV_DNS_LOG_STOP(DNS.send_event);
354                 ev_io_stop(event_base, &IO->DNS.recv_event);
355                 ev_io_stop(event_base, &IO->DNS.send_event);
356                 IO->DNS.Channel = NULL;
357         }
358         assert(IO->Terminate);
359         IO->Terminate(IO);
360 }
361
362 void PostInbound(AsyncIO *IO)
363 {
364         switch (IO->NextState) {
365         case eSendFile:
366                 ev_io_start(event_base, &IO->send_event);
367                 break;
368         case eSendReply:
369         case eSendMore:
370                 assert(IO->SendDone);
371                 IO->NextState = IO->SendDone(IO);
372                 ev_io_start(event_base, &IO->send_event);
373                 break;
374         case eReadPayload:
375         case eReadMore:
376         case eReadFile:
377                 ev_io_start(event_base, &IO->recv_event);
378                 break;
379         case eTerminateConnection:
380                 ShutDownCLient(IO);
381                 break;
382         case eAbort:
383                 ShutDownCLient(IO);
384                 break;
385         case eSendDNSQuery:
386         case eReadDNSReply:
387         case eDBQuery:
388         case eConnect:
389         case eReadMessage:
390                 break;
391         }
392 }
393 eReadState HandleInbound(AsyncIO *IO)
394 {
395         const char *Err = NULL;
396         eReadState Finished = eBufferNotEmpty;
397
398         become_session(IO->CitContext);
399
400         while ((Finished == eBufferNotEmpty) &&
401                ((IO->NextState == eReadMessage)||
402                 (IO->NextState == eReadMore)||
403                 (IO->NextState == eReadFile)||
404                 (IO->NextState == eReadPayload)))
405         {
406                 /* Reading lines...
407                  * lex line reply in callback,
408                  * or do it ourselves.
409                  * i.e. as nnn-blabla means continue reading in SMTP
410                  */
411                 if ((IO->NextState == eReadFile) &&
412                     (Finished == eBufferNotEmpty))
413                 {
414                         Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
415                         if (Finished == eReadSuccess)
416                         {
417                                 IO->NextState = eSendReply;
418                         }
419                 }
420                 else if (IO->LineReader)
421                         Finished = IO->LineReader(IO);
422                 else
423                         Finished = StrBufChunkSipLine(IO->IOBuf,
424                                                       &IO->RecvBuf);
425
426                 switch (Finished) {
427                 case eMustReadMore: /// read new from socket...
428                         break;
429                 case eBufferNotEmpty: /* shouldn't happen... */
430                 case eReadSuccess: /// done for now...
431                         break;
432                 case eReadFail: /// WHUT?
433                                 ///todo: shut down!
434                         break;
435                 }
436
437                 if (Finished != eMustReadMore) {
438                         assert(IO->ReadDone);
439                         ev_io_stop(event_base, &IO->recv_event);
440                         IO->NextState = IO->ReadDone(IO);
441                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
442                 }
443         }
444
445         PostInbound(IO);
446
447         return Finished;
448 }
449
450
451 static void
452 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
453 {
454         int rc;
455         AsyncIO *IO = watcher->data;
456         const char *errmsg = NULL;
457
458         IO->Now = ev_now(event_base);
459         become_session(IO->CitContext);
460 #ifdef BIGBAD_IODBG
461         {
462                 int rv = 0;
463                 char fn [SIZ];
464                 FILE *fd;
465                 const char *pch = ChrPtr(IO->SendBuf.Buf);
466                 const char *pchh = IO->SendBuf.ReadWritePointer;
467                 long nbytes;
468
469                 if (pchh == NULL)
470                         pchh = pch;
471
472                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
473                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
474                          ((CitContext*)(IO->CitContext))->ServiceName,
475                          IO->SendBuf.fd);
476
477                 fd = fopen(fn, "a+");
478                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
479                         nbytes);
480                 rv = fwrite(pchh, nbytes, 1, fd);
481                 if (!rv) printf("failed to write debug to %s!\n", fn);
482                 fprintf(fd, "]\n");
483 #endif
484                 switch (IO->NextState) {
485                 case eSendFile:
486                         rc = FileSendChunked(&IO->IOB, &errmsg);
487                         if (rc < 0)
488                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
489                         break;
490                 default:
491                         rc = StrBuf_write_one_chunk_callback(IO->SendBuf.fd,
492                                                              0,
493                                                              &IO->SendBuf);
494                 }
495
496 #ifdef BIGBAD_IODBG
497                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
498                 fclose(fd);
499         }
500 #endif
501         if (rc == 0)
502         {
503                 ev_io_stop(event_base, &IO->send_event);
504                 switch (IO->NextState) {
505                 case eSendMore:
506                         assert(IO->SendDone);
507                         IO->NextState = IO->SendDone(IO);
508
509                         if ((IO->NextState == eTerminateConnection) ||
510                             (IO->NextState == eAbort) )
511                                 ShutDownCLient(IO);
512                         else {
513                                 ev_io_start(event_base, &IO->send_event);
514                         }
515                         break;
516                 case eSendFile:
517                         if (IO->IOB.ChunkSendRemain > 0) {
518                                 ev_io_start(event_base, &IO->recv_event);
519                                 SetNextTimeout(IO, 100.0);
520
521                         } else {
522                                 assert(IO->ReadDone);
523                                 IO->NextState = IO->ReadDone(IO);
524                                 switch(IO->NextState) {
525                                 case eSendDNSQuery:
526                                 case eReadDNSReply:
527                                 case eDBQuery:
528                                 case eConnect:
529                                         break;
530                                 case eSendReply:
531                                 case eSendMore:
532                                 case eSendFile:
533                                         ev_io_start(event_base,
534                                                     &IO->send_event);
535                                         break;
536                                 case eReadMessage:
537                                 case eReadMore:
538                                 case eReadPayload:
539                                 case eReadFile:
540                                         break;
541                                 case eTerminateConnection:
542                                 case eAbort:
543                                         break;
544                                 }
545                         }
546                         break;
547                 case eSendReply:
548                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
549                         break;
550                     IO->NextState = eReadMore;
551                 case eReadMore:
552                 case eReadMessage:
553                 case eReadPayload:
554                 case eReadFile:
555                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
556                         {
557                                 HandleInbound(IO);
558                         }
559                         else {
560                                 ev_io_start(event_base, &IO->recv_event);
561                         }
562
563                         break;
564                 case eDBQuery:
565                         /*
566                          * we now live in another queue,
567                          * so we have to unregister.
568                          */
569                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
570                         break;
571                 case eSendDNSQuery:
572                 case eReadDNSReply:
573                 case eConnect:
574                 case eTerminateConnection:
575                 case eAbort:
576                         break;
577                 }
578         }
579         else if (rc < 0) {
580                 if (errno != EAGAIN) {
581                         StopClientWatchers(IO, 1);
582                         EV_syslog(LOG_DEBUG,
583                                   "EVENT: Socket Invalid! [%d] [%s] [%d]\n",
584                                   errno, strerror(errno), IO->SendBuf.fd);
585                         StrBufPrintf(IO->ErrMsg,
586                                      "Socket Invalid! [%s]",
587                                      strerror(errno));
588                         SetNextTimeout(IO, 0.0);
589                 }
590         }
591         /* else : must write more. */
592 }
593 static void
594 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
595 {
596         ev_timer_stop(event_base, &IO->conn_fail);
597         ev_timer_start(event_base, &IO->rw_timeout);
598
599         switch(IO->NextState) {
600         case eReadMore:
601         case eReadMessage:
602         case eReadFile:
603                 StrBufAppendBufPlain(IO->ErrMsg, HKEY("[while waiting for greeting]"), 0);
604                 ev_io_start(event_base, &IO->recv_event);
605                 break;
606         case eSendReply:
607         case eSendMore:
608         case eReadPayload:
609         case eSendFile:
610                 become_session(IO->CitContext);
611                 IO_send_callback(loop, &IO->send_event, revents);
612                 break;
613         case eDBQuery:
614         case eSendDNSQuery:
615         case eReadDNSReply:
616         case eConnect:
617         case eTerminateConnection:
618         case eAbort:
619                 /// TODO: WHUT?
620                 break;
621         }
622 }
623
624 static void
625 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
626 {
627         AsyncIO *IO = watcher->data;
628
629         IO->Now = ev_now(event_base);
630         ev_timer_stop (event_base, &IO->rw_timeout);
631         become_session(IO->CitContext);
632
633         if (IO->SendBuf.fd != 0)
634         {
635                 ev_io_stop(event_base, &IO->send_event);
636                 ev_io_stop(event_base, &IO->recv_event);
637                 ev_timer_stop (event_base, &IO->rw_timeout);
638                 close(IO->SendBuf.fd);
639                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
640         }
641
642         assert(IO->Timeout);
643         switch (IO->Timeout(IO))
644         {
645         case eAbort:
646                 ShutDownCLient(IO);
647         default:
648                 break;
649         }
650 }
651
652 static void
653 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
654 {
655         AsyncIO *IO = watcher->data;
656
657         IO->Now = ev_now(event_base);
658         ev_timer_stop (event_base, &IO->conn_fail);
659
660         if (IO->SendBuf.fd != 0)
661         {
662                 ev_io_stop(loop, &IO->conn_event);
663                 ev_io_stop(event_base, &IO->send_event);
664                 ev_io_stop(event_base, &IO->recv_event);
665                 ev_timer_stop (event_base, &IO->rw_timeout);
666                 close(IO->SendBuf.fd);
667                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
668         }
669         become_session(IO->CitContext);
670
671         assert(IO->ConnFail);
672         switch (IO->ConnFail(IO))
673         {
674         case eAbort:
675                 ShutDownCLient(IO);
676         default:
677                 break;
678
679         }
680 }
681
682 static void
683 IO_connfailimmediate_callback(struct ev_loop *loop,
684                               ev_idle *watcher,
685                               int revents)
686 {
687         AsyncIO *IO = watcher->data;
688
689         IO->Now = ev_now(event_base);
690         ev_idle_stop (event_base, &IO->conn_fail_immediate);
691
692         if (IO->SendBuf.fd != 0)
693         {
694                 close(IO->SendBuf.fd);
695                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
696         }
697         become_session(IO->CitContext);
698
699         assert(IO->ConnFail);
700         switch (IO->ConnFail(IO))
701         {
702         case eAbort:
703                 ShutDownCLient(IO);
704         default:
705                 break;
706
707         }
708 }
709
710 static void
711 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
712 {
713         AsyncIO *IO = watcher->data;
714         int             so_err = 0;
715         socklen_t       lon = sizeof(so_err);
716         int             err;
717
718         IO->Now = ev_now(event_base);
719         EVM_syslog(LOG_DEBUG, "connect() succeeded.\n");
720
721         ev_io_stop(loop, &IO->conn_event);
722         ev_timer_stop(event_base, &IO->conn_fail);
723
724         err = getsockopt(IO->SendBuf.fd,
725                          SOL_SOCKET,
726                          SO_ERROR,
727                          (void*)&so_err,
728                          &lon);
729
730         if ((err == 0) && (so_err != 0))
731         {
732                 EV_syslog(LOG_DEBUG, "connect() failed [%d][%s]\n",
733                           so_err,
734                           strerror(so_err));
735                 IO_connfail_callback(loop, &IO->conn_fail, revents);
736
737         }
738         else
739         {
740                 EVM_syslog(LOG_DEBUG, "connect() succeeded\n");
741                 set_start_callback(loop, IO, revents);
742         }
743 }
744
745 static void
746 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
747 {
748         const char *errmsg;
749         ssize_t nbytes;
750         AsyncIO *IO = watcher->data;
751
752         IO->Now = ev_now(event_base);
753         switch (IO->NextState) {
754         case eReadFile:
755                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
756                 if (nbytes < 0)
757                         StrBufPlain(IO->ErrMsg, errmsg, -1);
758                 else
759                 {
760                         if (IO->IOB.ChunkSendRemain == 0)
761                         {
762                                 IO->NextState = eSendReply;
763                                 assert(IO->ReadDone);
764                                 ev_io_stop(event_base, &IO->recv_event);
765                                 PostInbound(IO);
766                                 return;
767                         }
768                         else
769                                 return;
770                 }
771                 break;
772         default:
773                 nbytes = StrBuf_read_one_chunk_callback(IO->RecvBuf.fd,
774                                                         0,
775                                                         &IO->RecvBuf);
776                 break;
777         }
778
779 #ifdef BIGBAD_IODBG
780         {
781                 long nbytes;
782                 int rv = 0;
783                 char fn [SIZ];
784                 FILE *fd;
785                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
786                 const char *pchh = IO->RecvBuf.ReadWritePointer;
787
788                 if (pchh == NULL)
789                         pchh = pch;
790
791                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
792                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
793                          ((CitContext*)(IO->CitContext))->ServiceName,
794                          IO->SendBuf.fd);
795
796                 fd = fopen(fn, "a+");
797                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
798                         nbytes);
799                 rv = fwrite(pchh, nbytes, 1, fd);
800                 if (!rv) printf("failed to write debug to %s!\n", fn);
801                 fprintf(fd, "]\n");
802                 fclose(fd);
803         }
804 #endif
805         if (nbytes > 0) {
806                 HandleInbound(IO);
807         } else if (nbytes == 0) {
808                 SetNextTimeout(IO, 0.0);
809                 return;
810         } else if (nbytes == -1) {
811                 if (errno != EAGAIN) {
812                         // FD is gone. kick it. 
813                         StopClientWatchers(IO, 1);
814                         EV_syslog(LOG_DEBUG,
815                                   "EVENT: Socket Invalid! [%d] [%s] [%d]\n",
816                                   errno, strerror(errno), IO->SendBuf.fd);
817                         StrBufPrintf(IO->ErrMsg,
818                                      "Socket Invalid! [%s]",
819                                      strerror(errno));
820                         SetNextTimeout(IO, 0.0);
821                 }
822                 return;
823         }
824 }
825
826 void
827 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
828 {
829         AsyncIO *IO = watcher->data;
830         IO->Now = ev_now(event_base);
831         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
832         become_session(IO->CitContext);
833         assert(IO->DNS.Query->PostDNS);
834         switch (IO->DNS.Query->PostDNS(IO))
835         {
836         case eAbort:
837                 assert(IO->DNS.Fail);
838                 switch (IO->DNS.Fail(IO)) {
839                 case eAbort:
840 ////                    StopClientWatchers(IO);
841                         ShutDownCLient(IO);
842                 default:
843                         break;
844                 }
845         default:
846                 break;
847         }
848 }
849
850
851 eNextState EvConnectSock(AsyncIO *IO,
852                          double conn_timeout,
853                          double first_rw_timeout,
854                          int ReadFirst)
855 {
856         struct sockaddr_in egress_sin;
857         int fdflags;
858         int rc = -1;
859
860         become_session(IO->CitContext);
861
862         if (ReadFirst) {
863                 IO->NextState = eReadMessage;
864         }
865         else {
866                 IO->NextState = eSendReply;
867         }
868
869         IO->SendBuf.fd = IO->RecvBuf.fd =
870                 socket(
871                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
872                         SOCK_STREAM,
873                         IPPROTO_TCP);
874
875         if (IO->SendBuf.fd < 0) {
876                 EV_syslog(LOG_ERR,
877                           "EVENT: socket() failed: %s\n",
878                           strerror(errno));
879
880                 StrBufPrintf(IO->ErrMsg,
881                              "Failed to create socket: %s",
882                              strerror(errno));
883                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
884                 return eAbort;
885         }
886         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
887         if (fdflags < 0) {
888                 EV_syslog(LOG_ERR,
889                           "EVENT: unable to get socket flags! %s \n",
890                           strerror(errno));
891                 StrBufPrintf(IO->ErrMsg,
892                              "Failed to get socket flags: %s",
893                              strerror(errno));
894                 close(IO->SendBuf.fd);
895                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
896                 return eAbort;
897         }
898         fdflags = fdflags | O_NONBLOCK;
899         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
900                 EV_syslog(
901                         LOG_ERR,
902                         "EVENT: unable to set socket nonblocking flags! %s \n",
903                         strerror(errno));
904                 StrBufPrintf(IO->ErrMsg,
905                              "Failed to set socket flags: %s",
906                              strerror(errno));
907                 close(IO->SendBuf.fd);
908                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
909                 return eAbort;
910         }
911 /* TODO: maye we could use offsetof() to calc the position of data...
912  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
913  */
914         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
915         IO->recv_event.data = IO;
916         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
917         IO->send_event.data = IO;
918
919         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
920         IO->conn_fail.data = IO;
921         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
922         IO->rw_timeout.data = IO;
923
924
925
926
927         /* for debugging you may bypass it like this:
928          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
929          * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
930          *   inet_addr("127.0.0.1");
931          */
932         if (IO->ConnectMe->IPv6) {
933                 rc = connect(IO->SendBuf.fd,
934                              &IO->ConnectMe->Addr,
935                              sizeof(struct sockaddr_in6));
936         }
937         else {
938                 /* If citserver is bound to a specific IP address on the host, make
939                  * sure we use that address for outbound connections.
940                  */
941         
942                 memset(&egress_sin, 0, sizeof(egress_sin));
943                 egress_sin.sin_family = AF_INET;
944                 if (!IsEmptyStr(config.c_ip_addr)) {
945                         egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
946                         if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
947                                 egress_sin.sin_addr.s_addr = INADDR_ANY;
948                         }
949
950                         /* If this bind fails, no problem; we can still use INADDR_ANY */
951                         bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
952                 }
953                 rc = connect(IO->SendBuf.fd,
954                              (struct sockaddr_in *)&IO->ConnectMe->Addr,
955                              sizeof(struct sockaddr_in));
956         }
957
958         if (rc >= 0){
959                 EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
960                 set_start_callback(event_base, IO, 0);
961                 return IO->NextState;
962         }
963         else if (errno == EINPROGRESS) {
964                 EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
965
966                 ev_io_init(&IO->conn_event,
967                            IO_connestd_callback,
968                            IO->SendBuf.fd,
969                            EV_READ|EV_WRITE);
970
971                 IO->conn_event.data = IO;
972
973                 ev_io_start(event_base, &IO->conn_event);
974                 ev_timer_start(event_base, &IO->conn_fail);
975                 return IO->NextState;
976         }
977         else {
978                 ev_idle_init(&IO->conn_fail_immediate,
979                              IO_connfailimmediate_callback);
980                 IO->conn_fail_immediate.data = IO;
981                 ev_idle_start(event_base, &IO->conn_fail_immediate);
982
983                 EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
984                 StrBufPrintf(IO->ErrMsg,
985                              "Failed to connect: %s",
986                              strerror(errno));
987                 return IO->NextState;
988         }
989         return IO->NextState;
990 }
991
992 void SetNextTimeout(AsyncIO *IO, double timeout)
993 {
994         IO->rw_timeout.repeat = timeout;
995         ev_timer_again (event_base,  &IO->rw_timeout);
996 }
997
998
999 eNextState ReAttachIO(AsyncIO *IO,
1000                       void *pData,
1001                       int ReadFirst)
1002 {
1003         IO->Data = pData;
1004         become_session(IO->CitContext);
1005         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
1006         if (ReadFirst) {
1007                 IO->NextState = eReadMessage;
1008         }
1009         else {
1010                 IO->NextState = eSendReply;
1011         }
1012         set_start_callback(event_base, IO, 0);
1013
1014         return IO->NextState;
1015 }
1016
1017 void InitIOStruct(AsyncIO *IO,
1018                   void *Data,
1019                   eNextState NextState,
1020                   IO_LineReaderCallback LineReader,
1021                   IO_CallBack DNS_Fail,
1022                   IO_CallBack SendDone,
1023                   IO_CallBack ReadDone,
1024                   IO_CallBack Terminate,
1025                   IO_CallBack DBTerminate,
1026                   IO_CallBack ConnFail,
1027                   IO_CallBack Timeout,
1028                   IO_CallBack ShutdownAbort)
1029 {
1030         IO->Data          = Data;
1031
1032         IO->CitContext    = CloneContext(CC);
1033         ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
1034
1035         IO->NextState     = NextState;
1036
1037         IO->SendDone      = SendDone;
1038         IO->ReadDone      = ReadDone;
1039         IO->Terminate     = Terminate;
1040         IO->DBTerminate   = DBTerminate;
1041         IO->LineReader    = LineReader;
1042         IO->ConnFail      = ConnFail;
1043         IO->Timeout       = Timeout;
1044         IO->ShutdownAbort = ShutdownAbort;
1045
1046         IO->DNS.Fail      = DNS_Fail;
1047
1048         IO->SendBuf.Buf   = NewStrBufPlain(NULL, 1024);
1049         IO->RecvBuf.Buf   = NewStrBufPlain(NULL, 1024);
1050         IO->IOBuf         = NewStrBuf();
1051         EV_syslog(LOG_DEBUG,
1052                   "EVENT: Session lives at %p IO at %p \n",
1053                   Data, IO);
1054
1055 }
1056
1057 extern int evcurl_init(AsyncIO *IO);
1058
1059 int InitcURLIOStruct(AsyncIO *IO,
1060                      void *Data,
1061                      const char* Desc,
1062                      IO_CallBack SendDone,
1063                      IO_CallBack Terminate,
1064                      IO_CallBack DBTerminate,
1065                      IO_CallBack ShutdownAbort)
1066 {
1067         IO->Data          = Data;
1068
1069         IO->CitContext    = CloneContext(CC);
1070         ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
1071
1072         IO->SendDone      = SendDone;
1073         IO->Terminate     = Terminate;
1074         IO->DBTerminate   = DBTerminate;
1075         IO->ShutdownAbort = ShutdownAbort;
1076
1077         strcpy(IO->HttpReq.errdesc, Desc);
1078
1079
1080         return  evcurl_init(IO);
1081
1082 }
1083
1084 extern int DebugEventLoopBacktrace;
1085 void EV_backtrace(AsyncIO *IO)
1086 {
1087 #ifdef HAVE_BACKTRACE
1088         void *stack_frames[50];
1089         size_t size, i;
1090         char **strings;
1091
1092         if ((IO == NULL) || (DebugEventLoopBacktrace == 0))
1093                 return;
1094         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1095         strings = backtrace_symbols(stack_frames, size);
1096         for (i = 0; i < size; i++) {
1097                 if (strings != NULL) {
1098                         EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
1099                 }
1100                 else {
1101                         EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
1102                 }
1103         }
1104         free(strings);
1105 #endif
1106 }
1107
1108
1109 ev_tstamp ctdl_ev_now (void)
1110 {
1111         return ev_now(event_base);
1112 }