2 * Copyright (c) 1987-2011 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 as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * Uncomment this to log all communications with the Citadel server
26 #include "webserver.h"
28 extern int DisableGzip;
29 long MaxRead = -1; /* should we do READ scattered or all at once? */
32 * register the timeout
34 RETSIGTYPE timeout(int signum)
36 syslog(1, "Connection timed out; unable to reach citserver\n");
37 /* no exit here, since we need to server the connection unreachable thing. exit(3); */
42 * Client side - connect to a unix domain socket
44 int uds_connectsock(char *sockpath)
46 struct sockaddr_un addr;
49 memset(&addr, 0, sizeof(addr));
50 addr.sun_family = AF_UNIX;
51 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
53 s = socket(AF_UNIX, SOCK_STREAM, 0);
55 syslog(1, "Can't create socket [%s]: %s\n", sockpath, strerror(errno));
59 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
60 syslog(1, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
70 * TCP client - connect to a host/port
72 int tcp_connectsock(char *host, char *service)
74 struct in6_addr serveraddr;
75 struct addrinfo hints;
76 struct addrinfo *res = NULL;
77 struct addrinfo *ai = NULL;
81 if ((host == NULL) || IsEmptyStr(host))
83 if ((service == NULL) || IsEmptyStr(service))
86 syslog(9, "tcp_connectsock(%s,%s)\n", host, service);
88 memset(&hints, 0x00, sizeof(hints));
89 hints.ai_flags = AI_NUMERICSERV;
90 hints.ai_family = AF_UNSPEC;
91 hints.ai_socktype = SOCK_STREAM;
94 * Handle numeric IPv4 and IPv6 addresses
96 rc = inet_pton(AF_INET, host, &serveraddr);
97 if (rc == 1) { /* dotted quad */
98 hints.ai_family = AF_INET;
99 hints.ai_flags |= AI_NUMERICHOST;
101 rc = inet_pton(AF_INET6, host, &serveraddr);
102 if (rc == 1) { /* IPv6 address */
103 hints.ai_family = AF_INET6;
104 hints.ai_flags |= AI_NUMERICHOST;
108 /* Begin the connection process */
110 rc = getaddrinfo(host, service, &hints, &res);
112 syslog(1, "%s: %s\n", host, gai_strerror(rc));
118 * Try all available addresses until we connect to one or until we run out.
120 for (ai = res; ai != NULL; ai = ai->ai_next) {
122 if (ai->ai_family == AF_INET) syslog(9, "Trying IPv4\n");
123 else if (ai->ai_family == AF_INET6) syslog(9, "Trying IPv6\n");
124 else syslog(9, "This is going to fail.\n");
126 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
128 syslog(1, "socket() failed: %s\n", strerror(errno));
132 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
138 syslog(1, "connect() failed: %s\n", strerror(errno));
148 * input string from pipe
150 int serv_getln(char *strbuf, int bufsize)
156 StrBuf_ServGetln(WCC->MigrateReadLineBuf);
157 len = StrLength(WCC->MigrateReadLineBuf);
160 memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
161 FlushStrBuf(WCC->MigrateReadLineBuf);
164 syslog(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
170 int StrBuf_ServGetln(StrBuf *buf)
173 const char *ErrStr = NULL;
177 rc = StrBufTCP_read_buffered_line_fast(buf,
185 syslog(1, "StrBuf_ServGetln(): Server connection broken: %s\n",
188 if (WCC->serv_sock > 0) close(WCC->serv_sock);
189 WCC->serv_sock = (-1);
197 if (WCC->ReadPos != NULL)
198 pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
199 syslog(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
205 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
211 rc = StrBufReadBLOBBuffered(buf,
221 syslog(1, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
224 if (WCC->serv_sock > 0) close(WCC->serv_sock);
225 WCC->serv_sock = (-1);
231 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
237 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
244 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
247 syslog(1, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
250 if (WCC->serv_sock > 0) close(WCC->serv_sock);
251 WCC->serv_sock = (-1);
257 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
264 void FlushReadBuf (void)
271 len = StrLength(WCC->ReadBuf);
273 (WCC->ReadPos != NULL) &&
274 (WCC->ReadPos != StrBufNOTNULL))
277 pch = ChrPtr(WCC->ReadBuf);
279 if (WCC->ReadPos != pche)
282 "ERROR: somebody didn't eat his soup! Remaing Chars: %ld [%s]\n",
283 (long)(pche - WCC->ReadPos),
287 "--------------------------------------------------------------------------------\n"
289 "--------------------------------------------------------------------------------\n",
291 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
295 FlushStrBuf(WCC->ReadBuf);
303 * send binary to server
304 * buf the buffer to write to citadel server
305 * nbytes how many bytes to send to citadel server
307 int serv_write(const char *buf, int nbytes)
310 int bytes_written = 0;
314 while (bytes_written < nbytes) {
315 retval = write(WCC->serv_sock, &buf[bytes_written],
316 nbytes - bytes_written);
318 const char *ErrStr = strerror(errno);
319 syslog(1, "serv_write(): Server connection broken: %s\n",
321 if (WCC->serv_sock > 0) close(WCC->serv_sock);
322 WCC->serv_sock = (-1);
327 bytes_written = bytes_written + retval;
334 * send line to server
335 * string the line to send to the citadel server
337 int serv_puts(const char *string)
340 syslog(9, "%3d>>>%s\n", WC->serv_sock, string);
344 if (!serv_write(string, strlen(string)))
346 return serv_write("\n", 1);
350 * send line to server
351 * string the line to send to the citadel server
353 int serv_putbuf(const StrBuf *string)
356 syslog(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
360 if (!serv_write(ChrPtr(string), StrLength(string)))
362 return serv_write("\n", 1);
367 * convenience function to send stuff to the server
368 * format the formatstring
369 * ... the entities to insert into format
371 int serv_printf(const char *format,...)
380 va_start(arg_ptr, format);
381 vsnprintf(buf, sizeof buf, format, arg_ptr);
387 rc = serv_write(buf, len);
389 syslog(9, ">>>%s", buf);
396 * Read binary data from server into memory using a series of server READ commands.
397 * returns the read content as StrBuf
399 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
402 size_t bytes_read = 0;
403 size_t this_block = 0;
410 while (bytes_read < total_len) {
412 if (WCC->serv_sock==-1) {
417 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
418 if ( (rc = StrBuf_ServGetln(Buf) > 0) && (GetServerStatus(Buf, NULL) == 6) )
422 StrBufCutLeft(Buf, 4);
423 this_block = StrTol(Buf);
424 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
426 syslog(1, "Server connection broken during download\n");
428 if (WCC->serv_sock > 0) close(WCC->serv_sock);
429 WCC->serv_sock = (-1);
438 return StrLength(Ret);
442 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
446 const char *pch, *pchs;
447 int rlen, len, retval = 0;
451 if (StrLength(Hdr->ReadBuf) > 0) {
452 pchs = ChrPtr(Hdr->ReadBuf);
453 pch = strchr(pchs, '\n');
457 if (len > 0 && (*(pch - 1) == '\r') )
459 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
460 StrBufCutLeft(Hdr->ReadBuf, len + 1);
465 while (retval == 0) {
467 pchs = ChrPtr(Hdr->ReadBuf);
469 pch = strchr(pchs, '\n');
471 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
472 pchs = ChrPtr(Hdr->ReadBuf);
473 pch = strchr(pchs, '\n');
482 if ((retval > 0) && (pch != NULL)) {
485 if (len > 0 && (*(pch - 1) == '\r') )
487 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
488 StrBufCutLeft(Hdr->ReadBuf, len + 1);
497 return StrBufTCP_read_buffered_line_fast(Target,
508 * This is a generic function to set up a master socket for listening on
509 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
511 * ip_addr IP address to bind
512 * port_number port number to bind
513 * queue_len number of incoming connections to allow in the queue
515 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
518 struct sockaddr_in6 sin6;
519 struct sockaddr_in sin4;
523 memset(&sin6, 0, sizeof(sin6));
524 memset(&sin4, 0, sizeof(sin4));
525 sin6.sin6_family = AF_INET6;
526 sin4.sin_family = AF_INET;
528 if ( (ip_addr == NULL) /* any IPv6 */
529 || (IsEmptyStr(ip_addr))
530 || (!strcmp(ip_addr, "*"))
533 sin6.sin6_addr = in6addr_any;
535 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
538 sin4.sin_addr.s_addr = INADDR_ANY;
540 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
543 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
544 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
545 return (-WC_EXIT_BIND);
548 else /* specific IPv6 */
551 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
552 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
553 return (-WC_EXIT_BIND);
557 if (port_number == 0) {
558 syslog(1, "Cannot start: no port number specified.\n");
559 return (-WC_EXIT_BIND);
561 sin6.sin6_port = htons((u_short) port_number);
562 sin4.sin_port = htons((u_short) port_number);
564 p = getprotobyname("tcp");
566 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
568 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
569 return (-WC_EXIT_BIND);
571 /* Set some socket options that make sense. */
573 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
575 if (ip_version == 6) {
576 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
579 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
583 syslog(1, "Can't bind: %s\n", strerror(errno));
585 return (-WC_EXIT_BIND);
588 if (listen(s, queue_len) < 0) {
589 syslog(1, "Can't listen: %s\n", strerror(errno));
591 return (-WC_EXIT_BIND);
598 * Create a Unix domain socket and listen on it
599 * sockpath - file name of the unix domain socket
600 * queue_len - Number of incoming connections to allow in the queue
602 int webcit_uds_server(char *sockpath, int queue_len)
604 struct sockaddr_un addr;
607 int actual_queue_len;
609 actual_queue_len = queue_len;
610 if (actual_queue_len < 5) actual_queue_len = 5;
612 i = unlink(sockpath);
613 if ((i != 0) && (errno != ENOENT)) {
614 syslog(1, "webcit: can't unlink %s: %s\n",
615 sockpath, strerror(errno));
616 return (-WC_EXIT_BIND);
619 memset(&addr, 0, sizeof(addr));
620 addr.sun_family = AF_UNIX;
621 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
623 s = socket(AF_UNIX, SOCK_STREAM, 0);
625 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
626 return (-WC_EXIT_BIND);
629 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
630 syslog(1, "webcit: Can't bind: %s\n", strerror(errno));
632 return (-WC_EXIT_BIND);
635 if (listen(s, actual_queue_len) < 0) {
636 syslog(1, "webcit: Can't listen: %s\n", strerror(errno));
638 return (-WC_EXIT_BIND);
641 chmod(sockpath, 0777);
649 * Read data from the client socket.
651 * sock socket fd to read from
652 * buf buffer to read into
653 * bytes number of bytes to read
654 * timeout Number of seconds to wait before timing out
656 * Possible return values:
657 * 1 Requested number of bytes has been read.
658 * 0 Request timed out.
659 * -1 Connection is broken, or other error.
661 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
671 baselen = StrLength(Target);
673 if (Hdr->Pos == NULL)
674 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
676 if (StrLength(Hdr->ReadBuf) > 0)
678 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
680 if (bytes < bufremain)
682 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
683 StrBufCutLeft(Hdr->ReadBuf, bufremain);
686 if (bytes > bufremain)
688 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
690 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
692 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
694 write(2, "\033[32m", 5);
695 write(2, buf, bytes);
696 write(2, "\033[30m", 5);
701 syslog(2, "client_read_ssl() failed\n");
710 retval = StrBufReadBLOBBuffered(Target,
719 syslog(2, "client_read() failed: %s\n",
726 write(2, "\033[32m", 5);
727 write(2, buf, bytes);
728 write(2, "\033[30m", 5);
735 * Begin buffering HTTP output so we can transmit it all in one write operation later.
737 void begin_burst(void)
739 if (WC->WBuf == NULL) {
740 WC->WBuf = NewStrBufPlain(NULL, 32768);
746 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
751 const char *ptr, *eptr;
757 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
759 if (CompressBuffer(WCC->WBuf) > 0)
760 hprintf("Content-encoding: gzip\r\n");
762 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
767 if (WCC->WFBuf != NULL) {
768 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
769 FreeStrBuf(&WCC->WFBuf);
772 if (WCC->Hdr->HR.prohibit_caching)
773 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
774 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
776 ptr = ChrPtr(WCC->HBuf);
777 count = StrLength(WCC->HBuf);
782 client_write_ssl(WCC->HBuf);
783 client_write_ssl(WCC->WBuf);
791 write(2, "\033[34m", 5);
792 write(2, ptr, StrLength(WCC->WBuf));
793 write(2, "\033[30m", 5);
795 if (WCC->Hdr->http_sock == -1)
797 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
799 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
800 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
802 FD_SET(WCC->Hdr->http_sock, &wset);
803 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
804 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
809 if ((WCC->Hdr->http_sock == -1) ||
810 (res = write(WCC->Hdr->http_sock,
813 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
821 ptr = ChrPtr(WCC->WBuf);
822 count = StrLength(WCC->WBuf);
827 write(2, "\033[34m", 5);
828 write(2, ptr, StrLength(WCC->WBuf));
829 write(2, "\033[30m", 5);
832 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
833 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
835 FD_SET(WCC->Hdr->http_sock, &wset);
836 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
837 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
842 if ((WCC->Hdr->http_sock == -1) ||
843 (res = write(WCC->Hdr->http_sock,
846 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
854 return StrLength(WCC->WBuf);
859 * lingering_close() a`la Apache. see
860 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
862 int lingering_close(int fd)
867 struct timeval tv, start;
869 gettimeofday(&start, NULL);
875 gettimeofday(&tv, NULL);
876 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
877 tv.tv_usec = start.tv_usec - tv.tv_usec;
878 if (tv.tv_usec < 0) {
880 tv.tv_usec += 1000000;
884 i = select(fd + 1, &set, NULL, NULL, &tv);
885 } while (i == -1 && errno == EINTR);
890 i = read(fd, buf, sizeof buf);
891 } while (i != 0 && (i != -1 || errno == EINTR));
897 HttpNewModule_TCPSOCKETS
898 (ParsedHttpHdrs *httpreq)
901 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
905 HttpDetachModule_TCPSOCKETS
906 (ParsedHttpHdrs *httpreq)
909 FlushStrBuf(httpreq->ReadBuf);
910 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
914 HttpDestroyModule_TCPSOCKETS
915 (ParsedHttpHdrs *httpreq)
918 FreeStrBuf(&httpreq->ReadBuf);
923 SessionNewModule_TCPSOCKETS
926 sess->CLineBuf = NewStrBuf();
927 sess->MigrateReadLineBuf = NewStrBuf();
931 SessionDestroyModule_TCPSOCKETS
934 FreeStrBuf(&sess->CLineBuf);
935 FreeStrBuf(&sess->ReadBuf);
936 sess->ReadPos = NULL;
937 FreeStrBuf(&sess->MigrateReadLineBuf);
938 if (sess->serv_sock > 0) {
939 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
940 close(sess->serv_sock);