3 * Copyright (c) 1998-2012 by the citadel.org team
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.
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.
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
29 #include <sys/types.h>
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
37 # include <sys/time.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
51 #include <libcitadel.h>
54 #include "citserver.h"
61 #include "internet_addressing.h"
64 #include "clientsocket.h"
65 #include "locate_host.h"
66 #include "citadel_dirs.h"
68 #include "event_client.h"
70 static void IO_abort_shutdown_callback(struct ev_loop *loop,
74 AsyncIO *IO = watcher->data;
75 EV_syslog(LOG_DEBUG, "EVENT Q: %s\n", __FUNCTION__);
77 assert(IO->ShutdownAbort);
78 IO->ShutdownAbort(IO);
82 /*------------------------------------------------------------------------------
84 *----------------------------------------------------------------------------*/
85 extern int evdb_count;
86 extern pthread_mutex_t DBEventQueueMutex;
87 extern HashList *DBInboundEventQueue;
88 extern struct ev_loop *event_db;
89 extern ev_async DBAddJob;
90 extern ev_async DBExitEventLoop;
92 eNextState QueueDBOperation(AsyncIO *IO, IO_CallBack CB)
97 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
100 ev_cleanup_init(&IO->db_abort_by_shutdown,
101 IO_abort_shutdown_callback);
102 IO->db_abort_by_shutdown.data = IO;
103 ev_cleanup_start(event_db, &IO->db_abort_by_shutdown);
105 pthread_mutex_lock(&DBEventQueueMutex);
106 EVM_syslog(LOG_DEBUG, "DBEVENT Q\n");
108 Put(DBInboundEventQueue, IKEY(i), h, NULL);
109 pthread_mutex_unlock(&DBEventQueueMutex);
111 ev_async_send (event_db, &DBAddJob);
112 EVM_syslog(LOG_DEBUG, "DBEVENT Q Done.\n");
116 void ShutDownDBCLient(AsyncIO *IO)
118 CitContext *Ctx =IO->CitContext;
121 EVM_syslog(LOG_DEBUG, "DBEVENT Terminating.\n");
122 ev_cleanup_stop(event_db, &IO->db_abort_by_shutdown);
124 assert(IO->Terminate);
129 DB_PerformNext(struct ev_loop *loop, ev_idle *watcher, int revents)
131 AsyncIO *IO = watcher->data;
132 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
133 become_session(IO->CitContext);
135 ev_idle_stop(event_db, &IO->db_unwind_stack);
137 assert(IO->NextDBOperation);
138 switch (IO->NextDBOperation(IO))
152 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
154 case eTerminateConnection:
156 ev_idle_stop(event_db, &IO->db_unwind_stack);
157 ev_cleanup_stop(loop, &IO->db_abort_by_shutdown);
158 ShutDownDBCLient(IO);
162 eNextState NextDBOperation(AsyncIO *IO, IO_CallBack CB)
164 IO->NextDBOperation = CB;
165 ev_idle_init(&IO->db_unwind_stack,
167 IO->db_unwind_stack.data = IO;
168 ev_idle_start(event_db, &IO->db_unwind_stack);
172 /*------------------------------------------------------------------------------
174 *----------------------------------------------------------------------------*/
175 extern int evbase_count;
176 extern pthread_mutex_t EventQueueMutex;
177 extern HashList *InboundEventQueue;
178 extern struct ev_loop *event_base;
179 extern ev_async AddJob;
180 extern ev_async ExitEventLoop;
183 eNextState QueueEventContext(AsyncIO *IO, IO_CallBack CB)
188 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
191 ev_cleanup_init(&IO->abort_by_shutdown,
192 IO_abort_shutdown_callback);
193 IO->abort_by_shutdown.data = IO;
194 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
196 pthread_mutex_lock(&EventQueueMutex);
197 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
199 Put(InboundEventQueue, IKEY(i), h, NULL);
200 pthread_mutex_unlock(&EventQueueMutex);
202 ev_async_send (event_base, &AddJob);
203 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
207 extern eNextState evcurl_handle_start(AsyncIO *IO);
209 eNextState QueueCurlContext(AsyncIO *IO)
214 h = (IOAddHandler*)malloc(sizeof(IOAddHandler));
216 h->EvAttch = evcurl_handle_start;
218 pthread_mutex_lock(&EventQueueMutex);
219 EVM_syslog(LOG_DEBUG, "EVENT Q\n");
221 Put(InboundEventQueue, IKEY(i), h, NULL);
222 pthread_mutex_unlock(&EventQueueMutex);
224 ev_async_send (event_base, &AddJob);
225 EVM_syslog(LOG_DEBUG, "EVENT Q Done.\n");
229 void DestructCAres(AsyncIO *IO);
230 void FreeAsyncIOContents(AsyncIO *IO)
232 CitContext *Ctx = IO->CitContext;
234 FreeStrBuf(&IO->IOBuf);
235 FreeStrBuf(&IO->SendBuf.Buf);
236 FreeStrBuf(&IO->RecvBuf.Buf);
240 FreeURL(&IO->ConnectMe);
241 FreeStrBuf(&IO->HttpReq.ReplyData);
244 Ctx->state = CON_IDLE;
250 void StopClientWatchers(AsyncIO *IO)
252 ev_timer_stop (event_base, &IO->rw_timeout);
253 ev_timer_stop(event_base, &IO->conn_fail);
254 ev_idle_stop(event_base, &IO->unwind_stack);
256 ev_io_stop(event_base, &IO->conn_event);
257 ev_io_stop(event_base, &IO->send_event);
258 ev_io_stop(event_base, &IO->recv_event);
259 close(IO->SendBuf.fd);
264 void ShutDownCLient(AsyncIO *IO)
266 CitContext *Ctx =IO->CitContext;
269 EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");
271 ev_cleanup_stop(event_base, &IO->abort_by_shutdown);
272 StopClientWatchers(IO);
274 if (IO->DNS.Channel != NULL) {
275 ares_destroy(IO->DNS.Channel);
276 ev_io_stop(event_base, &IO->DNS.recv_event);
277 ev_io_stop(event_base, &IO->DNS.send_event);
278 IO->DNS.Channel = NULL;
280 assert(IO->Terminate);
284 eReadState HandleInbound(AsyncIO *IO)
286 const char *Err = NULL;
287 eReadState Finished = eBufferNotEmpty;
289 become_session(IO->CitContext);
291 while ((Finished == eBufferNotEmpty) &&
292 ((IO->NextState == eReadMessage)||
293 (IO->NextState == eReadMore)||
294 (IO->NextState == eReadFile)||
295 (IO->NextState == eReadPayload)))
298 * lex line reply in callback,
299 * or do it ourselves.
300 * i.e. as nnn-blabla means continue reading in SMTP
302 if ((IO->NextState == eReadFile) &&
303 (Finished == eBufferNotEmpty))
305 Finished = WriteIOBAlreadyRead(&IO->IOB, &Err);
306 if (Finished == eReadSuccess)
308 IO->NextState = eSendReply;
311 else if (IO->LineReader)
312 Finished = IO->LineReader(IO);
314 Finished = StrBufChunkSipLine(IO->IOBuf,
318 case eMustReadMore: /// read new from socket...
320 case eBufferNotEmpty: /* shouldn't happen... */
321 case eReadSuccess: /// done for now...
323 case eReadFail: /// WHUT?
328 if (Finished != eMustReadMore) {
329 assert(IO->ReadDone);
330 ev_io_stop(event_base, &IO->recv_event);
331 IO->NextState = IO->ReadDone(IO);
332 Finished = StrBufCheckBuffer(&IO->RecvBuf);
336 switch (IO->NextState) {
338 ev_io_start(event_base, &IO->send_event);
342 assert(IO->SendDone);
343 IO->NextState = IO->SendDone(IO);
344 ev_io_start(event_base, &IO->send_event);
349 ev_io_start(event_base, &IO->recv_event);
351 case eTerminateConnection:
369 IO_send_callback(struct ev_loop *loop, ev_io *watcher, int revents)
372 AsyncIO *IO = watcher->data;
373 const char *errmsg = NULL;
375 become_session(IO->CitContext);
381 const char *pch = ChrPtr(IO->SendBuf.Buf);
382 const char *pchh = IO->SendBuf.ReadWritePointer;
388 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
389 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
390 ((CitContext*)(IO->CitContext))->ServiceName,
393 fd = fopen(fn, "a+");
394 fprintf(fd, "Send: BufSize: %ld BufContent: [",
396 rv = fwrite(pchh, nbytes, 1, fd);
397 if (!rv) printf("failed to write debug to %s!\n", fn);
400 switch (IO->NextState) {
402 rc = FileSendChunked(&IO->IOB, &errmsg);
404 StrBufPlain(IO->ErrMsg, errmsg, -1);
407 rc = StrBuf_write_one_chunk_callback(watcher->fd,
413 fprintf(fd, "Sent: BufSize: %d bytes.\n", rc);
419 ev_io_stop(event_base, &IO->send_event);
420 switch (IO->NextState) {
422 assert(IO->SendDone);
423 IO->NextState = IO->SendDone(IO);
425 if ((IO->NextState == eTerminateConnection) ||
426 (IO->NextState == eAbort) )
429 ev_io_start(event_base, &IO->send_event);
433 if (IO->IOB.ChunkSendRemain > 0) {
434 ev_io_start(event_base, &IO->recv_event);
436 assert(IO->ReadDone);
437 IO->NextState = IO->ReadDone(IO);
438 switch(IO->NextState) {
447 ev_io_start(event_base,
455 case eTerminateConnection:
462 if (StrBufCheckBuffer(&IO->SendBuf) != eReadSuccess)
464 IO->NextState = eReadMore;
469 if (StrBufCheckBuffer(&IO->RecvBuf) == eBufferNotEmpty)
474 ev_io_start(event_base, &IO->recv_event);
480 * we now live in another queue,
481 * so we have to unregister.
483 ev_cleanup_stop(loop, &IO->abort_by_shutdown);
488 case eTerminateConnection:
497 /* else : must write more. */
500 set_start_callback(struct ev_loop *loop, AsyncIO *IO, int revents)
502 switch(IO->NextState) {
506 ev_io_start(event_base, &IO->recv_event);
512 become_session(IO->CitContext);
513 IO_send_callback(loop, &IO->send_event, revents);
519 case eTerminateConnection:
527 IO_Timeout_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
529 AsyncIO *IO = watcher->data;
531 ev_timer_stop (event_base, &IO->rw_timeout);
532 become_session(IO->CitContext);
534 if (IO->SendBuf.fd != 0)
536 ev_io_stop(event_base, &IO->send_event);
537 ev_io_stop(event_base, &IO->recv_event);
538 ev_timer_stop (event_base, &IO->rw_timeout);
539 close(IO->SendBuf.fd);
540 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
544 switch (IO->Timeout(IO))
554 IO_connfail_callback(struct ev_loop *loop, ev_timer *watcher, int revents)
556 AsyncIO *IO = watcher->data;
558 ev_timer_stop (event_base, &IO->conn_fail);
560 if (IO->SendBuf.fd != 0)
562 ev_io_stop(loop, &IO->conn_event);
563 ev_io_stop(event_base, &IO->send_event);
564 ev_io_stop(event_base, &IO->recv_event);
565 ev_timer_stop (event_base, &IO->rw_timeout);
566 close(IO->SendBuf.fd);
567 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
569 become_session(IO->CitContext);
571 assert(IO->ConnFail);
572 switch (IO->ConnFail(IO))
583 IO_connfailimmediate_callback(struct ev_loop *loop,
587 AsyncIO *IO = watcher->data;
589 ev_idle_stop (event_base, &IO->conn_fail_immediate);
591 if (IO->SendBuf.fd != 0)
593 close(IO->SendBuf.fd);
594 IO->SendBuf.fd = IO->RecvBuf.fd = 0;
596 become_session(IO->CitContext);
598 assert(IO->ConnFail);
599 switch (IO->ConnFail(IO))
610 IO_connestd_callback(struct ev_loop *loop, ev_io *watcher, int revents)
612 AsyncIO *IO = watcher->data;
614 ev_io_stop(loop, &IO->conn_event);
615 ev_timer_stop (event_base, &IO->conn_fail);
616 set_start_callback(loop, IO, revents);
619 IO_recv_callback(struct ev_loop *loop, ev_io *watcher, int revents)
623 AsyncIO *IO = watcher->data;
625 switch (IO->NextState) {
627 nbytes = FileRecvChunked(&IO->IOB, &errmsg);
629 StrBufPlain(IO->ErrMsg, errmsg, -1);
632 if (IO->IOB.ChunkSendRemain == 0)
634 IO->NextState = eSendReply;
641 nbytes = StrBuf_read_one_chunk_callback(watcher->fd,
653 const char *pch = ChrPtr(IO->RecvBuf.Buf);
654 const char *pchh = IO->RecvBuf.ReadWritePointer;
659 nbytes = StrLength(IO->RecvBuf.Buf) - (pchh - pch);
660 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
661 ((CitContext*)(IO->CitContext))->ServiceName,
664 fd = fopen(fn, "a+");
665 fprintf(fd, "Read: BufSize: %ld BufContent: [",
667 rv = fwrite(pchh, nbytes, 1, fd);
668 if (!rv) printf("failed to write debug to %s!\n", fn);
675 } else if (nbytes == 0) {
678 switch (IO->Timeout(IO))
686 } else if (nbytes == -1) {
687 // FD is gone. kick it.
688 StopClientWatchers(IO);
690 "EVENT: Socket Invalid! %s \n",
698 IO_postdns_callback(struct ev_loop *loop, ev_idle *watcher, int revents)
700 AsyncIO *IO = watcher->data;
701 EV_syslog(LOG_DEBUG, "event: %s\n", __FUNCTION__);
702 become_session(IO->CitContext);
703 assert(IO->DNS.Fail);
704 assert(IO->DNS.Query->PostDNS);
705 switch (IO->DNS.Query->PostDNS(IO))
708 switch (IO->DNS.Fail(IO)) {
720 eNextState EvConnectSock(AsyncIO *IO,
722 double first_rw_timeout,
728 become_session(IO->CitContext);
731 IO->NextState = eReadMessage;
734 IO->NextState = eSendReply;
737 IO->SendBuf.fd = IO->RecvBuf.fd =
739 (IO->ConnectMe->IPv6)?PF_INET6:PF_INET,
743 if (IO->SendBuf.fd < 0) {
745 "EVENT: socket() failed: %s\n",
748 StrBufPrintf(IO->ErrMsg,
749 "Failed to create socket: %s",
753 fdflags = fcntl(IO->SendBuf.fd, F_GETFL);
756 "EVENT: unable to get socket flags! %s \n",
758 StrBufPrintf(IO->ErrMsg,
759 "Failed to get socket flags: %s",
763 fdflags = fdflags | O_NONBLOCK;
764 if (fcntl(IO->SendBuf.fd, F_SETFL, fdflags) < 0) {
767 "EVENT: unable to set socket nonblocking flags! %s \n",
769 StrBufPrintf(IO->ErrMsg,
770 "Failed to set socket flags: %s",
772 close(IO->SendBuf.fd);
773 IO->SendBuf.fd = IO->RecvBuf.fd = -1;
776 /* TODO: maye we could use offsetof() to calc the position of data...
777 * http://doc.dvgu.ru/devel/ev.html#associating_custom_data_with_a_watcher
779 ev_io_init(&IO->recv_event, IO_recv_callback, IO->RecvBuf.fd, EV_READ);
780 IO->recv_event.data = IO;
781 ev_io_init(&IO->send_event, IO_send_callback, IO->SendBuf.fd, EV_WRITE);
782 IO->send_event.data = IO;
784 ev_timer_init(&IO->conn_fail, IO_connfail_callback, conn_timeout, 0);
785 IO->conn_fail.data = IO;
786 ev_timer_init(&IO->rw_timeout, IO_Timeout_callback, first_rw_timeout,0);
787 IO->rw_timeout.data = IO;
790 /* for debugging you may bypass it like this:
791 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
792 * ((struct sockaddr_in)IO->ConnectMe->Addr).sin_addr.s_addr =
793 * inet_addr("127.0.0.1");
795 if (IO->ConnectMe->IPv6)
796 rc = connect(IO->SendBuf.fd,
797 &IO->ConnectMe->Addr,
798 sizeof(struct sockaddr_in6));
800 rc = connect(IO->SendBuf.fd,
801 (struct sockaddr_in *)&IO->ConnectMe->Addr,
802 sizeof(struct sockaddr_in));
805 EVM_syslog(LOG_DEBUG, "connect() immediate success.\n");
806 set_start_callback(event_base, IO, 0);
807 ev_timer_start(event_base, &IO->rw_timeout);
808 return IO->NextState;
810 else if (errno == EINPROGRESS) {
811 EVM_syslog(LOG_DEBUG, "connect() have to wait now.\n");
813 ev_io_init(&IO->conn_event,
814 IO_connestd_callback,
818 IO->conn_event.data = IO;
820 ev_io_start(event_base, &IO->conn_event);
821 ev_timer_start(event_base, &IO->conn_fail);
822 return IO->NextState;
825 ev_idle_init(&IO->conn_fail_immediate,
826 IO_connfailimmediate_callback);
827 IO->conn_fail_immediate.data = IO;
828 ev_idle_start(event_base, &IO->conn_fail_immediate);
830 EV_syslog(LOG_ERR, "connect() failed: %s\n", strerror(errno));
831 StrBufPrintf(IO->ErrMsg,
832 "Failed to connect: %s",
834 return IO->NextState;
836 return IO->NextState;
839 void SetNextTimeout(AsyncIO *IO, double timeout)
841 IO->rw_timeout.repeat = timeout;
842 ev_timer_again (event_base, &IO->rw_timeout);
846 eNextState ReAttachIO(AsyncIO *IO,
851 become_session(IO->CitContext);
852 ev_cleanup_start(event_base, &IO->abort_by_shutdown);
854 IO->NextState = eReadMessage;
857 IO->NextState = eSendReply;
859 set_start_callback(event_base, IO, 0);
861 return IO->NextState;
864 void InitIOStruct(AsyncIO *IO,
866 eNextState NextState,
867 IO_LineReaderCallback LineReader,
868 IO_CallBack DNS_Fail,
869 IO_CallBack SendDone,
870 IO_CallBack ReadDone,
871 IO_CallBack Terminate,
872 IO_CallBack ConnFail,
874 IO_CallBack ShutdownAbort)
878 IO->CitContext = CloneContext(CC);
879 ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
881 IO->NextState = NextState;
883 IO->SendDone = SendDone;
884 IO->ReadDone = ReadDone;
885 IO->Terminate = Terminate;
886 IO->LineReader = LineReader;
887 IO->ConnFail = ConnFail;
888 IO->Timeout = Timeout;
889 IO->ShutdownAbort = ShutdownAbort;
891 IO->DNS.Fail = DNS_Fail;
893 IO->SendBuf.Buf = NewStrBufPlain(NULL, 1024);
894 IO->RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
895 IO->IOBuf = NewStrBuf();
899 extern int evcurl_init(AsyncIO *IO);
901 int InitcURLIOStruct(AsyncIO *IO,
904 IO_CallBack SendDone,
905 IO_CallBack Terminate,
906 IO_CallBack ShutdownAbort)
910 IO->CitContext = CloneContext(CC);
911 ((CitContext *)IO->CitContext)->session_specific_data = (char*) Data;
913 IO->SendDone = SendDone;
914 IO->Terminate = Terminate;
915 IO->ShutdownAbort = ShutdownAbort;
917 strcpy(IO->HttpReq.errdesc, Desc);
920 return evcurl_init(IO);