4 * Copyright (c) 1987-2010 by the citadel.org team
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * Uncomment this to log all communications with the Citadel server
28 #include "webserver.h"
30 extern int DisableGzip;
31 long MaxRead = -1; /* should we do READ scattered or all at once? */
34 * register the timeout
36 RETSIGTYPE timeout(int signum)
38 lprintf(1, "Connection timed out; unable to reach citserver\n");
39 /* no exit here, since we need to server the connection unreachable thing. exit(3); */
44 * Client side - connect to a unix domain socket
46 int uds_connectsock(char *sockpath)
48 struct sockaddr_un addr;
51 memset(&addr, 0, sizeof(addr));
52 addr.sun_family = AF_UNIX;
53 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
55 s = socket(AF_UNIX, SOCK_STREAM, 0);
57 lprintf(1, "Can't create socket[%s]: %s\n", sockpath, strerror(errno));
61 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
62 lprintf(1, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
72 * TCP client - connect to a host/port
74 int tcp_connectsock(char *host, char *service)
76 struct in6_addr serveraddr;
77 struct addrinfo hints;
78 struct addrinfo *res = NULL;
79 struct addrinfo *ai = NULL;
83 if ((host == NULL) || IsEmptyStr(host))
85 if ((service == NULL) || IsEmptyStr(service))
88 lprintf(9, "tcp_connectsock(%s,%s)\n", host, service);
90 memset(&hints, 0x00, sizeof(hints));
91 hints.ai_flags = AI_NUMERICSERV;
92 hints.ai_family = AF_UNSPEC;
93 hints.ai_socktype = SOCK_STREAM;
96 * Handle numeric IPv4 and IPv6 addresses
98 rc = inet_pton(AF_INET, host, &serveraddr);
99 if (rc == 1) { /* dotted quad */
100 hints.ai_family = AF_INET;
101 hints.ai_flags |= AI_NUMERICHOST;
103 rc = inet_pton(AF_INET6, host, &serveraddr);
104 if (rc == 1) { /* IPv6 address */
105 hints.ai_family = AF_INET6;
106 hints.ai_flags |= AI_NUMERICHOST;
110 /* Begin the connection process */
112 rc = getaddrinfo(host, service, &hints, &res);
114 lprintf(1, "%s: %s\n", host, gai_strerror(rc));
119 * Try all available addresses until we connect to one or until we run out.
121 for (ai = res; ai != NULL; ai = ai->ai_next) {
123 if (ai->ai_family == AF_INET) lprintf(9, "Trying IPv4\n");
124 else if (ai->ai_family == AF_INET6) lprintf(9, "Trying IPv6\n");
125 else lprintf(9, "This is going to fail.\n");
127 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
129 lprintf(1, "socket() failed: %s\n", strerror(errno));
132 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
137 lprintf(1, "connect() failed: %s\n", strerror(errno));
147 * input string from pipe
149 int serv_getln(char *strbuf, int bufsize)
155 StrBuf_ServGetln(WCC->MigrateReadLineBuf);
156 len = StrLength(WCC->MigrateReadLineBuf);
159 memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
160 FlushStrBuf(WCC->MigrateReadLineBuf);
163 lprintf(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
169 int StrBuf_ServGetln(StrBuf *buf)
172 const char *ErrStr = NULL;
176 rc = StrBufTCP_read_buffered_line_fast(buf,
184 lprintf(1, "Server connection broken: %s\n",
187 WCC->serv_sock = (-1);
195 if (WCC->ReadPos != NULL)
196 pos = WCC->ReadPos - ChrPtr(buf);
197 lprintf(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
203 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
209 rc = StrBufReadBLOBBuffered(buf,
219 lprintf(1, "Server connection broken: %s\n",
222 WCC->serv_sock = (-1);
228 lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
234 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
241 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
244 lprintf(1, "Server connection broken: %s\n",
247 WCC->serv_sock = (-1);
253 lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
260 void FlushReadBuf (void)
267 len = StrLength(WCC->ReadBuf);
269 (WCC->ReadPos != NULL) &&
270 (WCC->ReadPos != StrBufNOTNULL))
273 pch = ChrPtr(WCC->ReadBuf);
275 if (WCC->ReadPos != pche)
277 lprintf(1, "ERROR: somebody didn't eat his soup! Remaing Chars: %d [%s]\n",
278 pche - WCC->ReadPos, pche);
280 "--------------------------------------------------------------------------------\n"
282 "--------------------------------------------------------------------------------\n",
284 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
288 FlushStrBuf(WCC->ReadBuf);
296 * send binary to server
297 * buf the buffer to write to citadel server
298 * nbytes how many bytes to send to citadel server
300 void serv_write(const char *buf, int nbytes)
303 int bytes_written = 0;
307 while (bytes_written < nbytes) {
308 retval = write(WCC->serv_sock, &buf[bytes_written],
309 nbytes - bytes_written);
311 const char *ErrStr = strerror(errno);
312 lprintf(1, "Server connection broken: %s\n",
314 close(WCC->serv_sock);
315 WCC->serv_sock = (-1);
320 bytes_written = bytes_written + retval;
326 * send line to server
327 * string the line to send to the citadel server
329 void serv_puts(const char *string)
332 lprintf(9, "%3d>>>%s\n", WC->serv_sock, string);
336 serv_write(string, strlen(string));
341 * send line to server
342 * string the line to send to the citadel server
344 void serv_putbuf(const StrBuf *string)
347 lprintf(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
351 serv_write(ChrPtr(string), StrLength(string));
357 * convenience function to send stuff to the server
358 * format the formatstring
359 * ... the entities to insert into format
361 void serv_printf(const char *format,...)
369 va_start(arg_ptr, format);
370 vsnprintf(buf, sizeof buf, format, arg_ptr);
376 serv_write(buf, len);
378 lprintf(9, ">>>%s", buf);
385 * Read binary data from server into memory using a series of
386 * server READ commands.
387 * \return the read content as StrBuf
389 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
393 size_t thisblock = 0;
400 serv_printf("READ %d|"SIZE_T_FMT, 0, total_len);
401 if (StrBuf_ServGetln(Buf) > 0)
408 if (GetServerStatus(Buf, NULL) == 6)
410 StrBufCutLeft(Buf, 4);
411 thisblock = StrTol(Buf);
412 if (WCC->serv_sock==-1) {
417 if (WCC->ReadPos != NULL) {
418 pch = ChrPtr(WCC->ReadBuf);
420 YetRead = WCC->ReadPos - pch;
425 StillThere = StrLength(WCC->ReadBuf) -
431 total_len -= StillThere;
433 FlushStrBuf(WCC->ReadBuf);
438 rc = StrBufReadBLOB(Ret,
445 lprintf(1, "Server connection broken: %s\n",
448 WCC->serv_sock = (-1);
454 return StrLength(Ret);
457 return StrLength(Ret);
463 else while ((WCC->serv_sock!=-1) &&
464 (bytes < total_len)) {
466 if ((total_len - bytes) < thisblock) {
467 thisblock = total_len - bytes;
468 if (thisblock == 0) {
473 serv_printf("READ %d|%d", (int)bytes, (int)thisblock);
474 if (StrBuf_ServGetln(Buf) > 0)
476 if (GetServerStatus(Buf, NULL) == 6)
478 StrBufCutLeft(Buf, 4);
479 thisblock = StrTol(Buf);
480 if (WCC->serv_sock==-1) {
484 StrBuf_ServGetBLOBBuffered(Ret, thisblock);
488 lprintf(3, "Error: %s\n", ChrPtr(Buf) + 4);
493 return StrLength(Ret);
497 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
501 const char *pch, *pchs;
502 int rlen, len, retval = 0;
506 if (StrLength(Hdr->ReadBuf) > 0) {
507 pchs = ChrPtr(Hdr->ReadBuf);
508 pch = strchr(pchs, '\n');
512 if (len > 0 && (*(pch - 1) == '\r') )
514 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
515 StrBufCutLeft(Hdr->ReadBuf, len + 1);
520 while (retval == 0) {
522 pchs = ChrPtr(Hdr->ReadBuf);
524 pch = strchr(pchs, '\n');
526 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
527 pchs = ChrPtr(Hdr->ReadBuf);
528 pch = strchr(pchs, '\n');
537 if ((retval > 0) && (pch != NULL)) {
540 if (len > 0 && (*(pch - 1) == '\r') )
542 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
543 StrBufCutLeft(Hdr->ReadBuf, len + 1);
552 return StrBufTCP_read_buffered_line_fast(Target,
563 * This is a generic function to set up a master socket for listening on
564 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
566 * ip_addr IP address to bind
567 * port_number port number to bind
568 * queue_len number of incoming connections to allow in the queue
570 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
573 struct sockaddr_in6 sin6;
574 struct sockaddr_in sin4;
578 memset(&sin6, 0, sizeof(sin6));
579 memset(&sin4, 0, sizeof(sin4));
580 sin6.sin6_family = AF_INET6;
581 sin4.sin_family = AF_INET;
583 if ( (ip_addr == NULL) /* any IPv6 */
584 || (IsEmptyStr(ip_addr))
585 || (!strcmp(ip_addr, "*"))
588 sin6.sin6_addr = in6addr_any;
590 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
593 sin4.sin_addr.s_addr = INADDR_ANY;
595 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
598 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
599 lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
600 return (-WC_EXIT_BIND);
603 else /* specific IPv6 */
606 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
607 lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
608 return (-WC_EXIT_BIND);
612 if (port_number == 0) {
613 lprintf(1, "Cannot start: no port number specified.\n");
614 return (-WC_EXIT_BIND);
616 sin6.sin6_port = htons((u_short) port_number);
617 sin4.sin_port = htons((u_short) port_number);
619 p = getprotobyname("tcp");
621 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
623 lprintf(1, "Can't create a listening socket: %s\n", strerror(errno));
624 return (-WC_EXIT_BIND);
626 /* Set some socket options that make sense. */
628 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
630 if (ip_version == 6) {
631 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
634 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
638 lprintf(1, "Can't bind: %s\n", strerror(errno));
639 return (-WC_EXIT_BIND);
642 if (listen(s, queue_len) < 0) {
643 lprintf(1, "Can't listen: %s\n", strerror(errno));
644 return (-WC_EXIT_BIND);
651 * Create a Unix domain socket and listen on it
652 * sockpath - file name of the unix domain socket
653 * queue_len - Number of incoming connections to allow in the queue
655 int webcit_uds_server(char *sockpath, int queue_len)
657 struct sockaddr_un addr;
660 int actual_queue_len;
662 actual_queue_len = queue_len;
663 if (actual_queue_len < 5) actual_queue_len = 5;
665 i = unlink(sockpath);
666 if ((i != 0) && (errno != ENOENT)) {
667 lprintf(1, "webcit: can't unlink %s: %s\n",
668 sockpath, strerror(errno));
669 return (-WC_EXIT_BIND);
672 memset(&addr, 0, sizeof(addr));
673 addr.sun_family = AF_UNIX;
674 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
676 s = socket(AF_UNIX, SOCK_STREAM, 0);
678 lprintf(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
679 return (-WC_EXIT_BIND);
682 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
683 lprintf(1, "webcit: Can't bind: %s\n",
685 return (-WC_EXIT_BIND);
688 if (listen(s, actual_queue_len) < 0) {
689 lprintf(1, "webcit: Can't listen: %s\n",
691 return (-WC_EXIT_BIND);
694 chmod(sockpath, 0777);
702 * Read data from the client socket.
704 * sock socket fd to read from
705 * buf buffer to read into
706 * bytes number of bytes to read
707 * timeout Number of seconds to wait before timing out
709 * Possible return values:
710 * 1 Requested number of bytes has been read.
711 * 0 Request timed out.
712 * -1 Connection is broken, or other error.
714 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
724 baselen = StrLength(Target);
726 if (Hdr->Pos == NULL)
727 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
728 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
730 if (bytes < bufremain)
732 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
733 StrBufCutLeft(Hdr->ReadBuf, bufremain);
735 if (bytes > bufremain)
737 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
739 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
741 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
743 write(2, "\033[32m", 5);
744 write(2, buf, bytes);
745 write(2, "\033[30m", 5);
750 lprintf(2, "client_read_ssl() failed\n");
759 retval = StrBufReadBLOBBuffered(Target,
768 lprintf(2, "client_read() failed: %s\n",
775 write(2, "\033[32m", 5);
776 write(2, buf, bytes);
777 write(2, "\033[30m", 5);
784 * Begin buffering HTTP output so we can transmit it all in one write operation later.
786 void begin_burst(void)
788 if (WC->WBuf == NULL) {
789 WC->WBuf = NewStrBufPlain(NULL, 32768);
795 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
800 const char *ptr, *eptr;
806 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
808 if (CompressBuffer(WCC->WBuf) > 0)
809 hprintf("Content-encoding: gzip\r\n");
811 lprintf(CTDL_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
816 if (WCC->WFBuf != NULL) {
817 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
818 FreeStrBuf(&WCC->WFBuf);
821 if (WCC->Hdr->HR.prohibit_caching)
822 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
823 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
825 ptr = ChrPtr(WCC->HBuf);
826 count = StrLength(WCC->HBuf);
831 client_write_ssl(WCC->HBuf);
832 client_write_ssl(WCC->WBuf);
840 write(2, "\033[34m", 5);
841 write(2, ptr, StrLength(WCC->WBuf));
842 write(2, "\033[30m", 5);
844 if (WCC->Hdr->http_sock == -1)
846 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
848 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
849 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
851 FD_SET(WCC->Hdr->http_sock, &wset);
852 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
853 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
858 if ((WCC->Hdr->http_sock == -1) ||
859 (res = write(WCC->Hdr->http_sock,
862 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
870 ptr = ChrPtr(WCC->WBuf);
871 count = StrLength(WCC->WBuf);
876 write(2, "\033[34m", 5);
877 write(2, ptr, StrLength(WCC->WBuf));
878 write(2, "\033[30m", 5);
881 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
882 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
884 FD_SET(WCC->Hdr->http_sock, &wset);
885 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
886 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
891 if ((WCC->Hdr->http_sock == -1) ||
892 (res = write(WCC->Hdr->http_sock,
895 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
903 return StrLength(WCC->WBuf);
908 * lingering_close() a`la Apache. see
909 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
911 int lingering_close(int fd)
916 struct timeval tv, start;
918 gettimeofday(&start, NULL);
924 gettimeofday(&tv, NULL);
925 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
926 tv.tv_usec = start.tv_usec - tv.tv_usec;
927 if (tv.tv_usec < 0) {
929 tv.tv_usec += 1000000;
933 i = select(fd + 1, &set, NULL, NULL, &tv);
934 } while (i == -1 && errno == EINTR);
939 i = read(fd, buf, sizeof buf);
940 } while (i != 0 && (i != -1 || errno == EINTR));
946 HttpNewModule_TCPSOCKETS
947 (ParsedHttpHdrs *httpreq)
950 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
954 HttpDetachModule_TCPSOCKETS
955 (ParsedHttpHdrs *httpreq)
958 FlushStrBuf(httpreq->ReadBuf);
959 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
963 HttpDestroyModule_TCPSOCKETS
964 (ParsedHttpHdrs *httpreq)
967 FreeStrBuf(&httpreq->ReadBuf);
972 SessionNewModule_TCPSOCKETS
975 sess->CLineBuf = NewStrBuf();
976 sess->MigrateReadLineBuf = NewStrBuf();
980 SessionDestroyModule_TCPSOCKETS
983 FreeStrBuf(&sess->CLineBuf);
984 FreeStrBuf(&sess->ReadBuf);
985 sess->ReadPos = NULL;
986 FreeStrBuf(&sess->MigrateReadLineBuf);
987 if (sess->serv_sock > 0)
988 close(sess->serv_sock);