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)
453 pchs = ChrPtr(Hdr->ReadBuf);
454 pch = strchr(pchs, '\n');
458 if (len > 0 && (*(pch - 1) == '\r') )
460 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
461 StrBufCutLeft(Hdr->ReadBuf, len + 1);
466 while (retval == 0) {
468 pchs = ChrPtr(Hdr->ReadBuf);
470 pch = strchr(pchs, '\n');
472 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
473 pchs = ChrPtr(Hdr->ReadBuf);
474 pch = strchr(pchs, '\n');
485 if ((retval > 0) && (pch != NULL)) {
488 if (len > 0 && (*(pch - 1) == '\r') )
490 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
491 StrBufCutLeft(Hdr->ReadBuf, len + 1);
500 return StrBufTCP_read_buffered_line_fast(Target,
511 * This is a generic function to set up a master socket for listening on
512 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
514 * ip_addr IP address to bind
515 * port_number port number to bind
516 * queue_len number of incoming connections to allow in the queue
518 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
521 struct sockaddr_in6 sin6;
522 struct sockaddr_in sin4;
526 memset(&sin6, 0, sizeof(sin6));
527 memset(&sin4, 0, sizeof(sin4));
528 sin6.sin6_family = AF_INET6;
529 sin4.sin_family = AF_INET;
531 if ( (ip_addr == NULL) /* any IPv6 */
532 || (IsEmptyStr(ip_addr))
533 || (!strcmp(ip_addr, "*"))
536 sin6.sin6_addr = in6addr_any;
538 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
541 sin4.sin_addr.s_addr = INADDR_ANY;
543 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
546 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
547 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
548 return (-WC_EXIT_BIND);
551 else /* specific IPv6 */
554 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
555 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
556 return (-WC_EXIT_BIND);
560 if (port_number == 0) {
561 syslog(1, "Cannot start: no port number specified.\n");
562 return (-WC_EXIT_BIND);
564 sin6.sin6_port = htons((u_short) port_number);
565 sin4.sin_port = htons((u_short) port_number);
567 p = getprotobyname("tcp");
569 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
571 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
572 return (-WC_EXIT_BIND);
574 /* Set some socket options that make sense. */
576 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
578 if (ip_version == 6) {
579 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
582 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
586 syslog(1, "Can't bind: %s\n", strerror(errno));
588 return (-WC_EXIT_BIND);
591 if (listen(s, queue_len) < 0) {
592 syslog(1, "Can't listen: %s\n", strerror(errno));
594 return (-WC_EXIT_BIND);
601 * Create a Unix domain socket and listen on it
602 * sockpath - file name of the unix domain socket
603 * queue_len - Number of incoming connections to allow in the queue
605 int webcit_uds_server(char *sockpath, int queue_len)
607 struct sockaddr_un addr;
610 int actual_queue_len;
612 actual_queue_len = queue_len;
613 if (actual_queue_len < 5) actual_queue_len = 5;
615 i = unlink(sockpath);
616 if ((i != 0) && (errno != ENOENT)) {
617 syslog(1, "webcit: can't unlink %s: %s\n",
618 sockpath, strerror(errno));
619 return (-WC_EXIT_BIND);
622 memset(&addr, 0, sizeof(addr));
623 addr.sun_family = AF_UNIX;
624 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
626 s = socket(AF_UNIX, SOCK_STREAM, 0);
628 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
629 return (-WC_EXIT_BIND);
632 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
633 syslog(1, "webcit: Can't bind: %s\n", strerror(errno));
635 return (-WC_EXIT_BIND);
638 if (listen(s, actual_queue_len) < 0) {
639 syslog(1, "webcit: Can't listen: %s\n", strerror(errno));
641 return (-WC_EXIT_BIND);
644 chmod(sockpath, 0777);
652 * Read data from the client socket.
654 * sock socket fd to read from
655 * buf buffer to read into
656 * bytes number of bytes to read
657 * timeout Number of seconds to wait before timing out
659 * Possible return values:
660 * 1 Requested number of bytes has been read.
661 * 0 Request timed out.
662 * -1 Connection is broken, or other error.
664 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
674 baselen = StrLength(Target);
676 if (Hdr->Pos == NULL)
677 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
679 if (StrLength(Hdr->ReadBuf) > 0)
681 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
683 if (bytes < bufremain)
685 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
686 StrBufCutLeft(Hdr->ReadBuf, bufremain);
689 if (bytes > bufremain)
691 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
693 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
695 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
699 syslog(2, "client_read_ssl() failed\n");
708 retval = StrBufReadBLOBBuffered(Target,
717 syslog(2, "client_read() failed: %s\n",
728 * Begin buffering HTTP output so we can transmit it all in one write operation later.
730 void begin_burst(void)
732 if (WC->WBuf == NULL) {
733 WC->WBuf = NewStrBufPlain(NULL, 32768);
739 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
744 const char *ptr, *eptr;
750 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
752 if (CompressBuffer(WCC->WBuf) > 0)
753 hprintf("Content-encoding: gzip\r\n");
755 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
760 if (WCC->WFBuf != NULL) {
761 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
762 FreeStrBuf(&WCC->WFBuf);
765 if (WCC->Hdr->HR.prohibit_caching)
766 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
767 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
769 ptr = ChrPtr(WCC->HBuf);
770 count = StrLength(WCC->HBuf);
775 client_write_ssl(WCC->HBuf);
776 client_write_ssl(WCC->WBuf);
781 if (WCC->Hdr->http_sock == -1)
783 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
785 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
786 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
788 FD_SET(WCC->Hdr->http_sock, &wset);
789 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
790 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
795 if ((WCC->Hdr->http_sock == -1) ||
796 (res = write(WCC->Hdr->http_sock,
799 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
807 ptr = ChrPtr(WCC->WBuf);
808 count = StrLength(WCC->WBuf);
811 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
812 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
814 FD_SET(WCC->Hdr->http_sock, &wset);
815 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
816 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
821 if ((WCC->Hdr->http_sock == -1) ||
822 (res = write(WCC->Hdr->http_sock,
825 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
833 return StrLength(WCC->WBuf);
838 * lingering_close() a`la Apache. see
839 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
841 int lingering_close(int fd)
846 struct timeval tv, start;
848 gettimeofday(&start, NULL);
854 gettimeofday(&tv, NULL);
855 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
856 tv.tv_usec = start.tv_usec - tv.tv_usec;
857 if (tv.tv_usec < 0) {
859 tv.tv_usec += 1000000;
863 i = select(fd + 1, &set, NULL, NULL, &tv);
864 } while (i == -1 && errno == EINTR);
869 i = read(fd, buf, sizeof buf);
870 } while (i != 0 && (i != -1 || errno == EINTR));
876 HttpNewModule_TCPSOCKETS
877 (ParsedHttpHdrs *httpreq)
880 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
884 HttpDetachModule_TCPSOCKETS
885 (ParsedHttpHdrs *httpreq)
888 FlushStrBuf(httpreq->ReadBuf);
889 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
893 HttpDestroyModule_TCPSOCKETS
894 (ParsedHttpHdrs *httpreq)
897 FreeStrBuf(&httpreq->ReadBuf);
902 SessionNewModule_TCPSOCKETS
905 sess->CLineBuf = NewStrBuf();
906 sess->MigrateReadLineBuf = NewStrBuf();
910 SessionDestroyModule_TCPSOCKETS
913 FreeStrBuf(&sess->CLineBuf);
914 FreeStrBuf(&sess->ReadBuf);
916 sess->ReadPos = NULL;
917 FreeStrBuf(&sess->MigrateReadLineBuf);
918 if (sess->serv_sock > 0) {
919 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
920 close(sess->serv_sock);
922 sess->serv_sock = -1;