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