2 * Copyright (c) 1987-2012 by the citadel.org team
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.
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.
14 * Uncomment this to log all communications with the Citadel server
19 #include "webserver.h"
21 long MaxRead = -1; /* should we do READ scattered or all at once? */
24 * register the timeout
26 RETSIGTYPE timeout(int signum)
28 syslog(LOG_WARNING, "Connection timed out; unable to reach citserver\n");
29 /* no exit here, since we need to server the connection unreachable thing. exit(3); */
34 * Client side - connect to a unix domain socket
36 int uds_connectsock(char *sockpath)
38 struct sockaddr_un addr;
42 memset(&addr, 0, sizeof(addr));
43 addr.sun_family = AF_UNIX;
44 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
46 s = socket(AF_UNIX, SOCK_STREAM, 0);
48 syslog(LOG_WARNING, "Can't create socket [%s]: %s\n", sockpath, strerror(errno));
52 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
53 syslog(LOG_WARNING, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
58 fdflags = fcntl(s, F_GETFL);
61 "unable to get socket %d flags! %s \n",
67 fdflags = fdflags | O_NONBLOCK;
68 if (fcntl(s, F_SETFL, fdflags) < 0) {
70 "unable to set socket %d nonblocking flags! %s \n",
82 * TCP client - connect to a host/port
84 int tcp_connectsock(char *host, char *service)
86 struct in6_addr serveraddr;
87 struct addrinfo hints;
88 struct addrinfo *res = NULL;
89 struct addrinfo *ai = NULL;
93 if ((host == NULL) || IsEmptyStr(host))
95 if ((service == NULL) || IsEmptyStr(service))
98 syslog(LOG_DEBUG, "tcp_connectsock(%s,%s)\n", host, service);
100 memset(&hints, 0x00, sizeof(hints));
101 hints.ai_flags = AI_NUMERICSERV;
102 hints.ai_family = AF_UNSPEC;
103 hints.ai_socktype = SOCK_STREAM;
106 * Handle numeric IPv4 and IPv6 addresses
108 rc = inet_pton(AF_INET, host, &serveraddr);
109 if (rc == 1) { /* dotted quad */
110 hints.ai_family = AF_INET;
111 hints.ai_flags |= AI_NUMERICHOST;
113 rc = inet_pton(AF_INET6, host, &serveraddr);
114 if (rc == 1) { /* IPv6 address */
115 hints.ai_family = AF_INET6;
116 hints.ai_flags |= AI_NUMERICHOST;
120 /* Begin the connection process */
122 rc = getaddrinfo(host, service, &hints, &res);
124 syslog(LOG_DEBUG, "%s: %s\n", host, gai_strerror(rc));
130 * Try all available addresses until we connect to one or until we run out.
132 for (ai = res; ai != NULL; ai = ai->ai_next) {
134 if (ai->ai_family == AF_INET) syslog(LOG_DEBUG, "Trying IPv4\n");
135 else if (ai->ai_family == AF_INET6) syslog(LOG_DEBUG, "Trying IPv6\n");
136 else syslog(LOG_WARNING, "This is going to fail.\n");
138 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
140 syslog(LOG_WARNING, "socket() failed: %s\n", strerror(errno));
144 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
149 fdflags = fcntl(rc, F_GETFL);
152 "unable to get socket %d flags! %s \n",
158 fdflags = fdflags | O_NONBLOCK;
159 if (fcntl(rc, F_SETFL, fdflags) < 0) {
161 "unable to set socket %d nonblocking flags! %s \n",
171 syslog(LOG_WARNING, "connect() failed: %s\n", strerror(errno));
181 * input string from pipe
183 int serv_getln(char *strbuf, int bufsize)
189 StrBuf_ServGetln(WCC->MigrateReadLineBuf);
190 len = StrLength(WCC->MigrateReadLineBuf);
193 memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
194 FlushStrBuf(WCC->MigrateReadLineBuf);
197 syslog(LOG_DEBUG, "%3d<<<%s\n", WCC->serv_sock, strbuf);
203 int StrBuf_ServGetln(StrBuf *buf)
206 const char *ErrStr = NULL;
213 rc = StrBufTCP_read_buffered_line_fast(buf,
221 syslog(LOG_INFO, "StrBuf_ServGetln(): Server connection broken: %s\n",
223 wc_backtrace(LOG_INFO);
224 if (WCC->serv_sock > 0) close(WCC->serv_sock);
225 WCC->serv_sock = (-1);
233 if (WCC->ReadPos != NULL)
234 pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
235 syslog(LOG_DEBUG, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
241 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
247 rc = StrBufReadBLOBBuffered(buf,
257 syslog(LOG_INFO, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
259 wc_backtrace(LOG_INFO);
260 if (WCC->serv_sock > 0) close(WCC->serv_sock);
261 WCC->serv_sock = (-1);
267 syslog(LOG_DEBUG, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
273 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
280 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
283 syslog(LOG_INFO, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
285 wc_backtrace(LOG_INFO);
286 if (WCC->serv_sock > 0) close(WCC->serv_sock);
287 WCC->serv_sock = (-1);
293 syslog(LOG_DEBUG, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
300 void FlushReadBuf (void)
307 len = StrLength(WCC->ReadBuf);
309 (WCC->ReadPos != NULL) &&
310 (WCC->ReadPos != StrBufNOTNULL))
313 pch = ChrPtr(WCC->ReadBuf);
315 if (WCC->ReadPos != pche)
318 "ERROR: somebody didn't eat his soup! Remaing Chars: %ld [%s]\n",
319 (long)(pche - WCC->ReadPos),
323 "--------------------------------------------------------------------------------\n"
325 "--------------------------------------------------------------------------------\n",
327 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
331 FlushStrBuf(WCC->ReadBuf);
339 * send binary to server
340 * buf the buffer to write to citadel server
341 * nbytes how many bytes to send to citadel server
343 int serv_write(const char *buf, int nbytes)
346 int bytes_written = 0;
350 while (bytes_written < nbytes) {
351 retval = write(WCC->serv_sock, &buf[bytes_written],
352 nbytes - bytes_written);
354 const char *ErrStr = strerror(errno);
355 syslog(LOG_INFO, "serv_write(): Server connection broken: %s\n",
357 if (WCC->serv_sock > 0) close(WCC->serv_sock);
358 WCC->serv_sock = (-1);
363 bytes_written = bytes_written + retval;
370 * send line to server
371 * string the line to send to the citadel server
373 int serv_puts(const char *string)
376 syslog(LOG_DEBUG, "%3d>>>%s\n", WC->serv_sock, string);
380 if (!serv_write(string, strlen(string)))
382 return serv_write("\n", 1);
386 * send line to server
387 * string the line to send to the citadel server
389 int serv_putbuf(const StrBuf *string)
392 syslog(LOG_DEBUG, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
396 if (!serv_write(ChrPtr(string), StrLength(string)))
398 return serv_write("\n", 1);
403 * convenience function to send stuff to the server
404 * format the formatstring
405 * ... the entities to insert into format
407 int serv_printf(const char *format,...)
416 va_start(arg_ptr, format);
417 vsnprintf(buf, sizeof buf, format, arg_ptr);
423 rc = serv_write(buf, len);
425 syslog(LOG_DEBUG, ">>>%s", buf);
432 * Read binary data from server into memory using a series of server READ commands.
433 * returns the read content as StrBuf
435 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
438 size_t bytes_read = 0;
439 size_t this_block = 0;
447 while ((bytes_read < total_len) && (ServerRc == 6)) {
449 if (WCC->serv_sock==-1) {
454 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
455 if ( (rc = StrBuf_ServGetln(Buf) > 0) &&
456 (ServerRc = GetServerStatus(Buf, NULL), ServerRc == 6) )
460 StrBufCutLeft(Buf, 4);
461 this_block = StrTol(Buf);
462 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
464 syslog(LOG_INFO, "Server connection broken during download\n");
465 wc_backtrace(LOG_INFO);
466 if (WCC->serv_sock > 0) close(WCC->serv_sock);
467 WCC->serv_sock = (-1);
476 return StrLength(Ret);
480 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
484 const char *pch, *pchs;
485 int rlen, len, retval = 0;
489 if (StrLength(Hdr->ReadBuf) > 0)
491 pchs = ChrPtr(Hdr->ReadBuf);
492 pch = strchr(pchs, '\n');
496 if (len > 0 && (*(pch - 1) == '\r') )
498 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
499 StrBufCutLeft(Hdr->ReadBuf, len + 1);
504 while (retval == 0) {
506 pchs = ChrPtr(Hdr->ReadBuf);
508 pch = strchr(pchs, '\n');
510 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
511 pchs = ChrPtr(Hdr->ReadBuf);
512 pch = strchr(pchs, '\n');
523 if ((retval > 0) && (pch != NULL)) {
526 if (len > 0 && (*(pch - 1) == '\r') )
528 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
529 StrBufCutLeft(Hdr->ReadBuf, len + 1);
538 return StrBufTCP_read_buffered_line_fast(Target,
549 * This is a generic function to set up a master socket for listening on
550 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
552 * ip_addr IP address to bind
553 * port_number port number to bind
554 * queue_len number of incoming connections to allow in the queue
556 int webcit_tcp_server(const char *ip_addr, int port_number, int queue_len)
558 const char *ipv4broadcast = "0.0.0.0";
561 struct sockaddr_in6 sin6;
562 struct sockaddr_in sin4;
567 memset(&sin6, 0, sizeof(sin6));
568 memset(&sin4, 0, sizeof(sin4));
569 sin6.sin6_family = AF_INET6;
570 sin4.sin_family = AF_INET;
572 if ( (ip_addr == NULL) /* any IPv6 */
573 || (IsEmptyStr(ip_addr))
574 || (!strcmp(ip_addr, "*"))
578 sin6.sin6_addr = in6addr_any;
580 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
583 sin4.sin_addr.s_addr = INADDR_ANY;
585 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
588 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
589 syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
590 return (-WC_EXIT_BIND);
593 else /* specific IPv6 */
596 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
597 syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
598 return (-WC_EXIT_BIND);
602 if (port_number == 0) {
603 syslog(LOG_WARNING, "Cannot start: no port number specified.\n");
604 return (-WC_EXIT_BIND);
606 sin6.sin6_port = htons((u_short) port_number);
607 sin4.sin_port = htons((u_short) port_number);
609 p = getprotobyname("tcp");
611 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
613 if (IsDefault && (errno == EAFNOSUPPORT))
616 ip_addr = ipv4broadcast;
619 syslog(LOG_WARNING, "Can't create a listening socket: %s\n", strerror(errno));
620 return (-WC_EXIT_BIND);
622 /* Set some socket options that make sense. */
624 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
626 if (ip_version == 6) {
627 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
630 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
634 syslog(LOG_EMERG, "Can't bind: %s\n", strerror(errno));
636 return (-WC_EXIT_BIND);
639 if (listen(s, queue_len) < 0) {
640 syslog(LOG_EMERG, "Can't listen: %s\n", strerror(errno));
642 return (-WC_EXIT_BIND);
649 * Create a Unix domain socket and listen on it
650 * sockpath - file name of the unix domain socket
651 * queue_len - Number of incoming connections to allow in the queue
653 int webcit_uds_server(char *sockpath, int queue_len)
655 struct sockaddr_un addr;
658 int actual_queue_len;
660 actual_queue_len = queue_len;
661 if (actual_queue_len < 5) actual_queue_len = 5;
663 i = unlink(sockpath);
664 if ((i != 0) && (errno != ENOENT)) {
665 syslog(LOG_WARNING, "webcit: can't unlink %s: %s\n",
666 sockpath, strerror(errno));
667 return (-WC_EXIT_BIND);
670 memset(&addr, 0, sizeof(addr));
671 addr.sun_family = AF_UNIX;
672 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
674 s = socket(AF_UNIX, SOCK_STREAM, 0);
676 syslog(LOG_WARNING, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
677 return (-WC_EXIT_BIND);
680 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
681 syslog(LOG_WARNING, "webcit: Can't bind: %s\n", strerror(errno));
683 return (-WC_EXIT_BIND);
686 if (listen(s, actual_queue_len) < 0) {
687 syslog(LOG_WARNING, "webcit: Can't listen: %s\n", strerror(errno));
689 return (-WC_EXIT_BIND);
692 chmod(sockpath, 0777);
700 * Read data from the client socket.
702 * sock socket fd to read from
703 * buf buffer to read into
704 * bytes number of bytes to read
705 * timeout Number of seconds to wait before timing out
707 * Possible return values:
708 * 1 Requested number of bytes has been read.
709 * 0 Request timed out.
710 * -1 Connection is broken, or other error.
712 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
722 baselen = StrLength(Target);
724 if (Hdr->Pos == NULL)
725 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
727 if (StrLength(Hdr->ReadBuf) > 0)
729 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
731 if (bytes < bufremain)
733 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
734 StrBufCutLeft(Hdr->ReadBuf, bufremain);
737 if (bytes > bufremain)
739 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
741 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
743 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
747 syslog(LOG_INFO, "client_read_ssl() failed\n");
756 retval = StrBufReadBLOBBuffered(Target,
765 syslog(LOG_INFO, "client_read() failed: %s\n",
767 wc_backtrace(LOG_DEBUG);
776 * Begin buffering HTTP output so we can transmit it all in one write operation later.
778 void begin_burst(void)
780 if (WC->WBuf == NULL) {
781 WC->WBuf = NewStrBufPlain(NULL, 32768);
787 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
792 const char *ptr, *eptr;
798 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
800 if (CompressBuffer(WCC->WBuf) > 0)
801 hprintf("Content-encoding: gzip\r\n");
803 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
804 wc_backtrace(LOG_INFO);
808 if (WCC->WFBuf != NULL) {
809 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
810 FreeStrBuf(&WCC->WFBuf);
813 if (WCC->Hdr->HR.prohibit_caching)
814 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
815 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
817 ptr = ChrPtr(WCC->HBuf);
818 count = StrLength(WCC->HBuf);
823 client_write_ssl(WCC->HBuf);
824 client_write_ssl(WCC->WBuf);
829 if (WCC->Hdr->http_sock == -1)
831 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
833 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
834 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
836 FD_SET(WCC->Hdr->http_sock, &wset);
837 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
838 syslog(LOG_DEBUG, "client_write: Socket select failed (%s)\n", strerror(errno));
843 if ((WCC->Hdr->http_sock == -1) ||
844 (res = write(WCC->Hdr->http_sock,
847 syslog(LOG_DEBUG, "client_write: Socket write failed (%s)\n", strerror(errno));
848 wc_backtrace(LOG_INFO);
855 ptr = ChrPtr(WCC->WBuf);
856 count = StrLength(WCC->WBuf);
859 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
860 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
862 FD_SET(WCC->Hdr->http_sock, &wset);
863 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
864 syslog(LOG_INFO, "client_write: Socket select failed (%s)\n", strerror(errno));
869 if ((WCC->Hdr->http_sock == -1) ||
870 (res = write(WCC->Hdr->http_sock,
873 syslog(LOG_INFO, "client_write: Socket write failed (%s)\n", strerror(errno));
874 wc_backtrace(LOG_INFO);
881 return StrLength(WCC->WBuf);
886 * lingering_close() a`la Apache. see
887 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
889 int lingering_close(int fd)
894 struct timeval tv, start;
896 gettimeofday(&start, NULL);
902 gettimeofday(&tv, NULL);
903 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
904 tv.tv_usec = start.tv_usec - tv.tv_usec;
905 if (tv.tv_usec < 0) {
907 tv.tv_usec += 1000000;
911 i = select(fd + 1, &set, NULL, NULL, &tv);
912 } while (i == -1 && errno == EINTR);
917 i = read(fd, buf, sizeof buf);
918 } while (i != 0 && (i != -1 || errno == EINTR));
924 HttpNewModule_TCPSOCKETS
925 (ParsedHttpHdrs *httpreq)
928 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
932 HttpDetachModule_TCPSOCKETS
933 (ParsedHttpHdrs *httpreq)
936 FlushStrBuf(httpreq->ReadBuf);
937 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
941 HttpDestroyModule_TCPSOCKETS
942 (ParsedHttpHdrs *httpreq)
945 FreeStrBuf(&httpreq->ReadBuf);
950 SessionNewModule_TCPSOCKETS
953 sess->CLineBuf = NewStrBuf();
954 sess->MigrateReadLineBuf = NewStrBuf();
958 SessionDestroyModule_TCPSOCKETS
961 FreeStrBuf(&sess->CLineBuf);
962 FreeStrBuf(&sess->ReadBuf);
964 sess->ReadPos = NULL;
965 FreeStrBuf(&sess->MigrateReadLineBuf);
966 if (sess->serv_sock > 0) {
967 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
968 close(sess->serv_sock);
970 sess->serv_sock = -1;