Event-client: in sort of uncasual timeout use our regular timeout handler instead...
[citadel.git] / citadel / event_client.c
1 /*
2  *
3  * Copyright (c) 1998-2012 by the citadel.org team
4  *
5  *  This program is open source software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 3 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <termios.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <pwd.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <syslog.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42 #include <sys/wait.h>
43 #include <ctype.h>
44 #include <string.h>
45 #include <limits.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <assert.h>
50 #if HAVE_BACKTRACE
51 #include <execinfo.h>
52 #endif
53
54 #include <libcitadel.h>
55 #include "citadel.h"
56 #include "server.h"
57 #include "citserver.h"
58 #include "support.h"
59 #include "config.h"
60 #include "control.h"
61 #include "user_ops.h"
62 #include "database.h"
63 #include "msgbase.h"
64 #include "internet_addressing.h"
65 #include "genstamp.h"
66 #include "domain.h"
67 #include "clientsocket.h"
68 #include "locate_host.h"
69 #include "citadel_dirs.h"
70
71 #include "event_client.h"
72 #include "ctdl_module.h"
73
74 static void IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents);
75
76 static void IO_abort_shutdown_callback(struct ev_loop *loop,
77                                        ev_cleanup *watcher,
78                                        int revents)
79 {
80         AsyncIO *IO = watcher->data;
81         EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
82
83         assert(IO->ShutdownAbort);
84         IO->ShutdownAbort(IO);
85 }
86
87
88 /*------------------------------------------------------------------------------
89  *                              Server DB IO
90  *----------------------------------------------------------------------------*/
91 extern int evdb_count;
92 extern pthread_mutex_t DBEventQueueMutex;
93 extern HashList *DBInboundEventQueue;
94 extern struct ev_loop *event_db;
95 extern ev_async DBAddJob;
96 extern ev_async DBExitEventLoop;
97
98 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
99 {
100         IOAddHandler *h;
101         int i;
102
103         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
104         h->IO = IO;
105         h->EvAttch = CB;
106         ev_cleanup_init(&IO->db_abort_by_shutdown,
107                         IO_abort_shutdown_callback);
108         IO->db_abort_by_shutdown.data = IO;
109         ev_cleanup_start(event_db, &IO->db_abort_by_shutdown);
110
111         pthread_mutex_lock(&DBEventQueueMutex);
112         EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
113         i = ++evdb_count ;
114         Put(DBInboundEventQueue, IKEY(i), h, NULL);
115         pthread_mutex_unlock(&DBEventQueueMutex);
116
117         ev_async_send (event_db, &DBAddJob);
118         EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
119         return eDBQuery;
120 }
121
122 void ShutDownDBCLient(AsyncIO *IO)
123 {
124         CitContext *Ctx =IO->CitContext;
125         become_session(Ctx);
126
127         EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
128         ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
129
130         assert(IO->Terminate);
131         IO->Terminate(IO);
132 }
133
134 void
135 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
136 {
137         AsyncIO *IO = watcher->data;
138         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
139         become_session(IO->CitContext);
140
141         ev_idle_stop(event_db, &IO->db_unwind_stack);
142
143         assert(IO->NextDBOperation);
144         switch (IO->NextDBOperation(IO))
145         {
146         case eDBQuery:
147                 break;
148         case eSendDNSQuery:
149         case eReadDNSReply:
150         case eConnect:
151         case eSendReply:
152         case eSendMore:
153         case eSendFile:
154         case eReadMessage:
155         case eReadMore:
156         case eReadPayload:
157         case eReadFile:
158                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
159                 break;
160         case eTerminateConnection:
161         case eAbort:
162                 ev_idle_stop(event_db, &IO->db_unwind_stack);
163                 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
164                 ShutDownDBCLient(IO);
165         }
166 }
167
168 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
169 {
170         IO->NextDBOperation = CB;
171         ev_idle_init(&IO->db_unwind_stack,
172                      DB_PerformNext);
173         IO->db_unwind_stack.data = IO;
174         ev_idle_start(event_db, &IO->db_unwind_stack);
175         return eDBQuery;
176 }
177
178 /*------------------------------------------------------------------------------
179  *                      Client IO
180  *----------------------------------------------------------------------------*/
181 extern int evbase_count;
182 extern pthread_mutex_t EventQueueMutex;
183 extern HashList *InboundEventQueue;
184 extern struct ev_loop *event_base;
185 extern ev_async AddJob;
186 extern ev_async ExitEventLoop;
187
188
189 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
190 {
191         IOAddHandler *h;
192         int i;
193
194         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
195         h->IO = IO;
196         h->EvAttch = CB;
197         ev_cleanup_init(&IO->abort_by_shutdown,
198                         IO_abort_shutdown_callback);
199         IO->abort_by_shutdown.data = IO;
200         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
201
202         pthread_mutex_lock(&EventQueueMutex);
203         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
204         i = ++evbase_count;
205         Put(InboundEventQueue, IKEY(i), h, NULL);
206         pthread_mutex_unlock(&EventQueueMutex);
207
208         ev_async_send (event_base, &AddJob);
209         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
210         return eSendReply;
211 }
212
213 extern eNextState evcurl_handle_start(AsyncIO *IO);
214
215 eNextState QueueCurlContext(AsyncIO *IO)
216 {
217         IOAddHandler *h;
218         int i;
219
220         h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
221         h->IO = IO;
222         h->EvAttch = evcurl_handle_start;
223
224         pthread_mutex_lock(&EventQueueMutex);
225         EVM_syslog(LOG_DEBUG, "EVENT Q\n");
226         i = ++evbase_count;
227         Put(InboundEventQueue, IKEY(i), h, NULL);
228         pthread_mutex_unlock(&EventQueueMutex);
229
230         ev_async_send (event_base, &AddJob);
231         EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
232         return eSendReply;
233 }
234
235 void DestructCAres(AsyncIO *IO);
236 void FreeAsyncIOContents(AsyncIO *IO)
237 {
238         CitContext *Ctx = IO->CitContext;
239
240         FreeStrBuf(&IO->IOBuf);
241         FreeStrBuf(&IO->SendBuf.Buf);
242         FreeStrBuf(&IO->RecvBuf.Buf);
243
244         DestructCAres(IO);
245
246         FreeURL(&IO->ConnectMe);
247         FreeStrBuf(&IO->HttpReq.ReplyData);
248
249         if (Ctx) {
250                 Ctx->state = CON_IDLE;
251                 Ctx->kill_me = 1;
252         }
253 }
254
255
256 void StopClientWatchers(AsyncIO *IO)
257 {
258         ev_timer_stop (event_base, &IO->rw_timeout);
259         ev_timer_stop(event_base, &IO->conn_fail);
260         ev_idle_stop(event_base, &IO->unwind_stack);
261
262         ev_io_stop(event_base, &IO->conn_event);
263         ev_io_stop(event_base, &IO->send_event);
264         ev_io_stop(event_base, &IO->recv_event);
265
266         if (IO->SendBuf.fd != 0) {
267                 close(IO->SendBuf.fd);
268         }
269         IO->SendBuf.fd = 0;
270         IO->RecvBuf.fd = 0;
271 }
272
273 void ShutDownCLient(AsyncIO *IO)
274 {
275         CitContext *Ctx =IO->CitContext;
276         become_session(Ctx);
277
278         EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
279
280         ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
281         StopClientWatchers(IO);
282
283         if (IO->DNS.Channel != NULL) {
284                 ares_destroy(IO->DNS.Channel);
285                 EV_DNS_LOG_STOP(DNS.recv_event);
286                 EV_DNS_LOG_STOP(DNS.send_event);
287                 ev_io_stop(event_base, &IO->DNS.recv_event);
288                 ev_io_stop(event_base, &IO->DNS.send_event);
289                 IO->DNS.Channel = NULL;
290         }
291         assert(IO->Terminate);
292         IO->Terminate(IO);
293 }
294
295 eReadState HandleInbound(AsyncIO *IO)
296 {
297         const char *Err = NULL;
298         eReadState Finished = eBufferNotEmpty;
299
300         become_session(IO->CitContext);
301
302         while ((Finished == eBufferNotEmpty) &&
303                ((IO->NextState == eReadMessage)||
304                 (IO->NextState == eReadMore)||
305                 (IO->NextState == eReadFile)||
306                 (IO->NextState == eReadPayload)))
307         {
308                 /* Reading lines...
309                  * lex line reply in callback,
310                  * or do it ourselves.
311                  * i.e. as nnn-blabla means continue reading in SMTP
312                  */
313                 if ((IO->NextState == eReadFile) &&
314                     (Finished == eBufferNotEmpty))
315                 {
316                         Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
317                         if (Finished == eReadSuccess)
318                         {
319                                 IO->NextState = eSendReply;
320                         }
321                 }
322                 else if (IO->LineReader)
323                         Finished = IO->LineReader(IO);
324                 else
325                         Finished = StrBufChunkSipLine(IO->IOBuf,
326                                                       &IO->RecvBuf);
327
328                 switch (Finished) {
329                 case eMustReadMore: /// read new from socket...
330                         break;
331                 case eBufferNotEmpty: /* shouldn't happen... */
332                 case eReadSuccess: /// done for now...
333                         break;
334                 case eReadFail: /// WHUT?
335                                 ///todo: shut down!
336                         break;
337                 }
338
339                 if (Finished != eMustReadMore) {
340                         assert(IO->ReadDone);
341                         ev_io_stop(event_base, &IO->recv_event);
342                         IO->NextState = IO->ReadDone(IO);
343                         Finished = StrBufCheckBuffer(&IO->RecvBuf);
344                 }
345         }
346
347         switch (IO->NextState) {
348         case eSendFile:
349                 ev_io_start(event_base, &IO->send_event);
350                 break;
351         case eSendReply:
352         case eSendMore:
353                 assert(IO->SendDone);
354                 IO->NextState = IO->SendDone(IO);
355                 ev_io_start(event_base, &IO->send_event);
356                 break;
357         case eReadPayload:
358         case eReadMore:
359         case eReadFile:
360                 ev_io_start(event_base, &IO->recv_event);
361                 break;
362         case eTerminateConnection:
363                 ShutDownCLient(IO);
364                 break;
365         case eAbort:
366                 ShutDownCLient(IO);
367                 break;
368         case eSendDNSQuery:
369         case eReadDNSReply:
370         case eDBQuery:
371         case eConnect:
372         case eReadMessage:
373                 break;
374         }
375         return Finished;
376 }
377
378
379 static void
380 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
381 {
382         int rc;
383         AsyncIO *IO = watcher->data;
384         const char *errmsg = NULL;
385
386         become_session(IO->CitContext);
387 #ifdef BIGBAD_IODBG
388         {
389                 int rv = 0;
390                 char fn [SIZ];
391                 FILE *fd;
392                 const char *pch = ChrPtr(IO->SendBuf.Buf);
393                 const char *pchh = IO->SendBuf.ReadWritePointer;
394                 long nbytes;
395
396                 if (pchh == NULL)
397                         pchh = pch;
398
399                 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
400                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
401                          ((CitContext*)(IO->CitContext))->ServiceName,
402                          IO->SendBuf.fd);
403
404                 fd = fopen(fn, "a+");
405                 fprintf(fd, "Send: BufSize: %ld BufContent: [",
406                         nbytes);
407                 rv = fwrite(pchh, nbytes, 1, fd);
408                 if (!rv) printf("failed to write debug to %s!\n", fn);
409                 fprintf(fd, "]\n");
410 #endif
411                 switch (IO->NextState) {
412                 case eSendFile:
413                         rc = FileSendChunked(&IO->IOB, &errmsg);
414                         if (rc < 0)
415                                 StrBufPlain(IO->ErrMsg, errmsg, -1);
416                         break;
417                 default:
418                         rc = StrBuf_write_one_chunk_callback(watcher->fd,
419                                                              0/*TODO*/,
420                                                              &IO->SendBuf);
421                 }
422
423 #ifdef BIGBAD_IODBG
424                 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
425                 fclose(fd);
426         }
427 #endif
428         if (rc == 0)
429         {
430                 ev_io_stop(event_base, &IO->send_event);
431                 switch (IO->NextState) {
432                 case eSendMore:
433                         assert(IO->SendDone);
434                         IO->NextState = IO->SendDone(IO);
435
436                         if ((IO->NextState == eTerminateConnection) ||
437                             (IO->NextState == eAbort) )
438                                 ShutDownCLient(IO);
439                         else {
440                                 ev_io_start(event_base, &IO->send_event);
441                         }
442                         break;
443                 case eSendFile:
444                         if (IO->IOB.ChunkSendRemain > 0) {
445                                 ev_io_start(event_base, &IO->recv_event);
446                                 SetNextTimeout(IO, 100.0);
447
448                         } else {
449                                 assert(IO->ReadDone);
450                                 IO->NextState = IO->ReadDone(IO);
451                                 switch(IO->NextState) {
452                                 case eSendDNSQuery:
453                                 case eReadDNSReply:
454                                 case eDBQuery:
455                                 case eConnect:
456                                         break;
457                                 case eSendReply:
458                                 case eSendMore:
459                                 case eSendFile:
460                                         ev_io_start(event_base,
461                                                     &IO->send_event);
462                                         break;
463                                 case eReadMessage:
464                                 case eReadMore:
465                                 case eReadPayload:
466                                 case eReadFile:
467                                         break;
468                                 case eTerminateConnection:
469                                 case eAbort:
470                                         break;
471                                 }
472                         }
473                         break;
474                 case eSendReply:
475                     if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
476                         break;
477                     IO->NextState = eReadMore;
478                 case eReadMore:
479                 case eReadMessage:
480                 case eReadPayload:
481                 case eReadFile:
482                         if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
483                         {
484                                 HandleInbound(IO);
485                         }
486                         else {
487                                 ev_io_start(event_base, &IO->recv_event);
488                         }
489
490                         break;
491                 case eDBQuery:
492                         /*
493                          * we now live in another queue,
494                          * so we have to unregister.
495                          */
496                         ev_cleanup_stop(loop, &IO->abort_by_shutdown);
497                         break;
498                 case eSendDNSQuery:
499                 case eReadDNSReply:
500                 case eConnect:
501                 case eTerminateConnection:
502                 case eAbort:
503                         break;
504                 }
505         }
506         else if (rc < 0) {
507                 IO_Timeout_callback(loop, &IO->rw_timeout, revents);
508         }
509         /* else : must write more. */
510 }
511 static void
512 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
513 {
514         switch(IO->NextState) {
515         case eReadMore:
516         case eReadMessage:
517         case eReadFile:
518                 ev_io_start(event_base, &IO->recv_event);
519                 break;
520         case eSendReply:
521         case eSendMore:
522         case eReadPayload:
523         case eSendFile:
524                 become_session(IO->CitContext);
525                 IO_send_callback(loop, &IO->send_event, revents);
526                 break;
527         case eDBQuery:
528         case eSendDNSQuery:
529         case eReadDNSReply:
530         case eConnect:
531         case eTerminateConnection:
532         case eAbort:
533                 /// TODO: WHUT?
534                 break;
535         }
536 }
537
538 static void
539 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
540 {
541         AsyncIO *IO = watcher->data;
542
543         ev_timer_stop (event_base, &IO->rw_timeout);
544         become_session(IO->CitContext);
545
546         if (IO->SendBuf.fd != 0)
547         {
548                 ev_io_stop(event_base, &IO->send_event);
549                 ev_io_stop(event_base, &IO->recv_event);
550                 ev_timer_stop (event_base, &IO->rw_timeout);
551                 close(IO->SendBuf.fd);
552                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
553         }
554
555         assert(IO->Timeout);
556         switch (IO->Timeout(IO))
557         {
558         case eAbort:
559                 ShutDownCLient(IO);
560         default:
561                 break;
562         }
563 }
564
565 static void
566 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
567 {
568         AsyncIO *IO = watcher->data;
569
570         ev_timer_stop (event_base, &IO->conn_fail);
571
572         if (IO->SendBuf.fd != 0)
573         {
574                 ev_io_stop(loop, &IO->conn_event);
575                 ev_io_stop(event_base, &IO->send_event);
576                 ev_io_stop(event_base, &IO->recv_event);
577                 ev_timer_stop (event_base, &IO->rw_timeout);
578                 close(IO->SendBuf.fd);
579                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
580         }
581         become_session(IO->CitContext);
582
583         assert(IO->ConnFail);
584         switch (IO->ConnFail(IO))
585         {
586         case eAbort:
587                 ShutDownCLient(IO);
588         default:
589                 break;
590
591         }
592 }
593
594 static void
595 IO_connfailimmediate_callback(struct ev_loop *loop,
596                               ev_idle *watcher,
597                               int revents)
598 {
599         AsyncIO *IO = watcher->data;
600
601         ev_idle_stop (event_base, &IO->conn_fail_immediate);
602
603         if (IO->SendBuf.fd != 0)
604         {
605                 close(IO->SendBuf.fd);
606                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
607         }
608         become_session(IO->CitContext);
609
610         assert(IO->ConnFail);
611         switch (IO->ConnFail(IO))
612         {
613         case eAbort:
614                 ShutDownCLient(IO);
615         default:
616                 break;
617
618         }
619 }
620
621 static void
622 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
623 {
624         AsyncIO *IO = watcher->data;
625
626         ev_io_stop(loop, &IO->conn_event);
627         ev_timer_stop (event_base, &IO->conn_fail);
628         set_start_callback(loop, IO, revents);
629 }
630 static void
631 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
632 {
633         const char *errmsg;
634         ssize_t nbytes;
635         AsyncIO *IO = watcher->data;
636
637         switch (IO->NextState) {
638         case eReadFile:
639                 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
640                 if (nbytes < 0)
641                         StrBufPlain(IO->ErrMsg, errmsg, -1);
642                 else
643                 {
644                         if (IO->IOB.ChunkSendRemain == 0)
645                         {
646                                 IO->NextState = eSendReply;
647                         }
648                         else
649                                 return;
650                 }
651                 break;
652         default:
653                 nbytes = StrBuf_read_one_chunk_callback(watcher->fd,
654                                                         0 /*TODO */,
655                                                         &IO->RecvBuf);
656                 break;
657         }
658
659 #ifdef BIGBAD_IODBG
660         {
661                 long nbytes;
662                 int rv = 0;
663                 char fn [SIZ];
664                 FILE *fd;
665                 const char *pch = ChrPtr(IO->RecvBuf.Buf);
666                 const char *pchh = IO->RecvBuf.ReadWritePointer;
667
668                 if (pchh == NULL)
669                         pchh = pch;
670
671                 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
672                 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
673                          ((CitContext*)(IO->CitContext))->ServiceName,
674                          IO->SendBuf.fd);
675
676                 fd = fopen(fn, "a+");
677                 fprintf(fd, "Read: BufSize: %ld BufContent: [",
678                         nbytes);
679                 rv = fwrite(pchh, nbytes, 1, fd);
680                 if (!rv) printf("failed to write debug to %s!\n", fn);
681                 fprintf(fd, "]\n");
682                 fclose(fd);
683         }
684 #endif
685         if (nbytes > 0) {
686                 HandleInbound(IO);
687         } else if (nbytes == 0) {
688                 assert(IO->Timeout);
689
690                 switch (IO->Timeout(IO))
691                 {
692                 case eAbort:
693                         ShutDownCLient(IO);
694                 default:
695                         break;
696                 }
697                 return;
698         } else if (nbytes == -1) {
699                 // FD is gone. kick it. 
700                 StopClientWatchers(IO);
701                 EV_syslog(LOG_DEBUG,
702                           "EVENT: Socket Invalid! %s \n",
703                           strerror(errno));
704                 ShutDownCLient(IO);
705                 return;
706         }
707 }
708
709 void
710 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
711 {
712         AsyncIO *IO = watcher->data;
713         EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
714         become_session(IO->CitContext);
715         assert(IO->DNS.Query->PostDNS);
716         switch (IO->DNS.Query->PostDNS(IO))
717         {
718         case eAbort:
719                 assert(IO->DNS.Fail);
720                 switch (IO->DNS.Fail(IO)) {
721                 case eAbort:
722 ////                    StopClientWatchers(IO);
723                         ShutDownCLient(IO);
724                 default:
725                         break;
726                 }
727         default:
728                 break;
729         }
730 }
731
732
733 eNextState EvConnectSock(AsyncIO *IO,
734                          double conn_timeout,
735                          double first_rw_timeout,
736                          int ReadFirst)
737 {
738         struct sockaddr_in egress_sin;
739         int fdflags;
740         int rc = -1;
741
742         become_session(IO->CitContext);
743
744         if (ReadFirst) {
745                 IO->NextState = eReadMessage;
746         }
747         else {
748                 IO->NextState = eSendReply;
749         }
750
751         IO->SendBuf.fd = IO->RecvBuf.fd =
752                 socket(
753                         (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
754                         SOCK_STREAM,
755                         IPPROTO_TCP);
756
757         if (IO->SendBuf.fd < 0) {
758                 EV_syslog(LOG_ERR,
759                           "EVENT: socket() failed: %s\n",
760                           strerror(errno));
761
762                 StrBufPrintf(IO->ErrMsg,
763                              "Failed to create socket: %s",
764                              strerror(errno));
765                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
766                 return eAbort;
767         }
768         fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
769         if (fdflags < 0) {
770                 EV_syslog(LOG_DEBUG,
771                           "EVENT: unable to get socket flags! %s \n",
772                           strerror(errno));
773                 StrBufPrintf(IO->ErrMsg,
774                              "Failed to get socket flags: %s",
775                              strerror(errno));
776                 close(IO->SendBuf.fd);
777                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
778                 return eAbort;
779         }
780         fdflags = fdflags | O_NONBLOCK;
781         if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
782                 EV_syslog(
783                         LOG_DEBUG,
784                         "EVENT: unable to set socket nonblocking flags! %s \n",
785                         strerror(errno));
786                 StrBufPrintf(IO->ErrMsg,
787                              "Failed to set socket flags: %s",
788                              strerror(errno));
789                 close(IO->SendBuf.fd);
790                 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
791                 return eAbort;
792         }
793 /* TODO: maye we could use offsetof() to calc the position of data...
794  * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
795  */
796         ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
797         IO->recv_event.data = IO;
798         ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
799         IO->send_event.data = IO;
800
801         ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
802         IO->conn_fail.data = IO;
803         ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
804         IO->rw_timeout.data = IO;
805
806
807
808
809         /* for debugging you may bypass it like this:
810          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
811          * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
812          *   inet_addr("127.0.0.1");
813          */
814         if (IO->ConnectMe->IPv6) {
815                 rc = connect(IO->SendBuf.fd,
816                              &IO->ConnectMe->Addr,
817                              sizeof(struct sockaddr_in6));
818         }
819         else {
820                 /* If citserver is bound to a specific IP address on the host, make
821                  * sure we use that address for outbound connections.
822                  */
823         
824                 memset(&egress_sin, 0, sizeof(egress_sin));
825                 egress_sin.sin_family = AF_INET;
826                 if (!IsEmptyStr(config.c_ip_addr)) {
827                         egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
828                         if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
829                                 egress_sin.sin_addr.s_addr = INADDR_ANY;
830                         }
831
832                         /* If this bind fails, no problem; we can still use INADDR_ANY */
833                         bind(IO->SendBuf.fd, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
834                 }
835                 rc = connect(IO->SendBuf.fd,
836                              (struct sockaddr_in *)&IO->ConnectMe->Addr,
837                              sizeof(struct sockaddr_in));
838         }
839
840         if (rc >= 0){
841                 EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
842                 set_start_callback(event_base, IO, 0);
843                 ev_timer_start(event_base, &IO->rw_timeout);
844                 return IO->NextState;
845         }
846         else if (errno == EINPROGRESS) {
847                 EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
848
849                 ev_io_init(&IO->conn_event,
850                            IO_connestd_callback,
851                            IO->SendBuf.fd,
852                            EV_READ|EV_WRITE);
853
854                 IO->conn_event.data = IO;
855
856                 ev_io_start(event_base, &IO->conn_event);
857                 ev_timer_start(event_base, &IO->conn_fail);
858                 return IO->NextState;
859         }
860         else {
861                 ev_idle_init(&IO->conn_fail_immediate,
862                              IO_connfailimmediate_callback);
863                 IO->conn_fail_immediate.data = IO;
864                 ev_idle_start(event_base, &IO->conn_fail_immediate);
865
866                 EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
867                 StrBufPrintf(IO->ErrMsg,
868                              "Failed to connect: %s",
869                              strerror(errno));
870                 return IO->NextState;
871         }
872         return IO->NextState;
873 }
874
875 void SetNextTimeout(AsyncIO *IO, double timeout)
876 {
877         IO->rw_timeout.repeat = timeout;
878         ev_timer_again (event_base,  &IO->rw_timeout);
879 }
880
881
882 eNextState ReAttachIO(AsyncIO *IO,
883                       void *pData,
884                       int ReadFirst)
885 {
886         IO->Data = pData;
887         become_session(IO->CitContext);
888         ev_cleanup_start(event_base, &IO->abort_by_shutdown);
889         if (ReadFirst) {
890                 IO->NextState = eReadMessage;
891         }
892         else {
893                 IO->NextState = eSendReply;
894         }
895         set_start_callback(event_base, IO, 0);
896
897         return IO->NextState;
898 }
899
900 void InitIOStruct(AsyncIO *IO,
901                   void *Data,
902                   eNextState NextState,
903                   IO_LineReaderCallback LineReader,
904                   IO_CallBack DNS_Fail,
905                   IO_CallBack SendDone,
906                   IO_CallBack ReadDone,
907                   IO_CallBack Terminate,
908                   IO_CallBack ConnFail,
909                   IO_CallBack Timeout,
910                   IO_CallBack ShutdownAbort)
911 {
912         IO->Data          = Data;
913
914         IO->CitContext    = CloneContext(CC);
915         ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
916
917         IO->NextState     = NextState;
918
919         IO->SendDone      = SendDone;
920         IO->ReadDone      = ReadDone;
921         IO->Terminate     = Terminate;
922         IO->LineReader    = LineReader;
923         IO->ConnFail      = ConnFail;
924         IO->Timeout       = Timeout;
925         IO->ShutdownAbort = ShutdownAbort;
926
927         IO->DNS.Fail      = DNS_Fail;
928
929         IO->SendBuf.Buf   = NewStrBufPlain(NULL, 1024);
930         IO->RecvBuf.Buf   = NewStrBufPlain(NULL, 1024);
931         IO->IOBuf         = NewStrBuf();
932         EV_syslog(LOG_DEBUG,
933                   "EVENT: Session lives at %p IO at %p \n",
934                   Data, IO);
935
936 }
937
938 extern int evcurl_init(AsyncIO *IO);
939
940 int InitcURLIOStruct(AsyncIO *IO,
941                      void *Data,
942                      const char* Desc,
943                      IO_CallBack SendDone,
944                      IO_CallBack Terminate,
945                      IO_CallBack ShutdownAbort)
946 {
947         IO->Data          = Data;
948
949         IO->CitContext    = CloneContext(CC);
950         ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
951
952         IO->SendDone = SendDone;
953         IO->Terminate = Terminate;
954         IO->ShutdownAbort = ShutdownAbort;
955
956         strcpy(IO->HttpReq.errdesc, Desc);
957
958
959         return  evcurl_init(IO);
960
961 }
962
963 void EV_backtrace(AsyncIO *IO)
964 {
965 #ifdef HAVE_BACKTRACE
966         void *stack_frames[50];
967         size_t size, i;
968         char **strings;
969
970
971         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
972         strings = backtrace_symbols(stack_frames, size);
973         for (i = 0; i < size; i++) {
974                 if (strings != NULL)
975                         EV_syslog(LOG_ALERT, " BT %s\n", strings[i]);
976                 else
977                         EV_syslog(LOG_ALERT, " BT %p\n", stack_frames[i]);
978         }
979         free(strings);
980 #endif
981 }
982
983
984 ev_tstamp ctdl_ev_now (void)
985 {
986         return ev_now(event_base);
987 }