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 WCC->serv_sock = (-1);
196 if (WCC->ReadPos != NULL)
197 pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
198 syslog(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
204 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
210 rc = StrBufReadBLOBBuffered(buf,
220 syslog(1, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
223 WCC->serv_sock = (-1);
229 syslog(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
235 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
242 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
245 syslog(1, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
248 WCC->serv_sock = (-1);
254 syslog(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
261 void FlushReadBuf (void)
268 len = StrLength(WCC->ReadBuf);
270 (WCC->ReadPos != NULL) &&
271 (WCC->ReadPos != StrBufNOTNULL))
274 pch = ChrPtr(WCC->ReadBuf);
276 if (WCC->ReadPos != pche)
278 syslog(1, "ERROR: somebody didn't eat his soup! Remaing Chars: %d [%s]\n",
279 pche - WCC->ReadPos, pche);
281 "--------------------------------------------------------------------------------\n"
283 "--------------------------------------------------------------------------------\n",
285 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
289 FlushStrBuf(WCC->ReadBuf);
297 * send binary to server
298 * buf the buffer to write to citadel server
299 * nbytes how many bytes to send to citadel server
301 void serv_write(const char *buf, int nbytes)
304 int bytes_written = 0;
308 while (bytes_written < nbytes) {
309 retval = write(WCC->serv_sock, &buf[bytes_written],
310 nbytes - bytes_written);
312 const char *ErrStr = strerror(errno);
313 syslog(1, "serv_write(): Server connection broken: %s\n",
315 close(WCC->serv_sock);
316 WCC->serv_sock = (-1);
321 bytes_written = bytes_written + retval;
327 * send line to server
328 * string the line to send to the citadel server
330 void serv_puts(const char *string)
333 syslog(9, "%3d>>>%s\n", WC->serv_sock, string);
337 serv_write(string, strlen(string));
342 * send line to server
343 * string the line to send to the citadel server
345 void serv_putbuf(const StrBuf *string)
348 syslog(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
352 serv_write(ChrPtr(string), StrLength(string));
358 * convenience function to send stuff to the server
359 * format the formatstring
360 * ... the entities to insert into format
362 void serv_printf(const char *format,...)
370 va_start(arg_ptr, format);
371 vsnprintf(buf, sizeof buf, format, arg_ptr);
377 serv_write(buf, len);
379 syslog(9, ">>>%s", buf);
385 * Read binary data from server into memory using a series of server READ commands.
386 * returns the read content as StrBuf
388 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
391 size_t bytes_read = 0;
392 size_t this_block = 0;
399 while (bytes_read < total_len) {
401 if (WCC->serv_sock==-1) {
406 serv_printf("READ %d|%d", bytes_read, total_len-bytes_read);
407 if ( (StrBuf_ServGetln(Buf) > 0) && (GetServerStatus(Buf, NULL) == 6) ) {
408 StrBufCutLeft(Buf, 4);
409 this_block = StrTol(Buf);
410 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
412 syslog(1, "Server connection broken during download\n");
414 WCC->serv_sock = (-1);
423 return StrLength(Ret);
427 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
431 const char *pch, *pchs;
432 int rlen, len, retval = 0;
436 if (StrLength(Hdr->ReadBuf) > 0) {
437 pchs = ChrPtr(Hdr->ReadBuf);
438 pch = strchr(pchs, '\n');
442 if (len > 0 && (*(pch - 1) == '\r') )
444 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
445 StrBufCutLeft(Hdr->ReadBuf, len + 1);
450 while (retval == 0) {
452 pchs = ChrPtr(Hdr->ReadBuf);
454 pch = strchr(pchs, '\n');
456 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
457 pchs = ChrPtr(Hdr->ReadBuf);
458 pch = strchr(pchs, '\n');
467 if ((retval > 0) && (pch != NULL)) {
470 if (len > 0 && (*(pch - 1) == '\r') )
472 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
473 StrBufCutLeft(Hdr->ReadBuf, len + 1);
482 return StrBufTCP_read_buffered_line_fast(Target,
493 * This is a generic function to set up a master socket for listening on
494 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
496 * ip_addr IP address to bind
497 * port_number port number to bind
498 * queue_len number of incoming connections to allow in the queue
500 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
503 struct sockaddr_in6 sin6;
504 struct sockaddr_in sin4;
508 memset(&sin6, 0, sizeof(sin6));
509 memset(&sin4, 0, sizeof(sin4));
510 sin6.sin6_family = AF_INET6;
511 sin4.sin_family = AF_INET;
513 if ( (ip_addr == NULL) /* any IPv6 */
514 || (IsEmptyStr(ip_addr))
515 || (!strcmp(ip_addr, "*"))
518 sin6.sin6_addr = in6addr_any;
520 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
523 sin4.sin_addr.s_addr = INADDR_ANY;
525 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
528 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
529 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
530 return (-WC_EXIT_BIND);
533 else /* specific IPv6 */
536 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
537 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
538 return (-WC_EXIT_BIND);
542 if (port_number == 0) {
543 syslog(1, "Cannot start: no port number specified.\n");
544 return (-WC_EXIT_BIND);
546 sin6.sin6_port = htons((u_short) port_number);
547 sin4.sin_port = htons((u_short) port_number);
549 p = getprotobyname("tcp");
551 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
553 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
554 return (-WC_EXIT_BIND);
556 /* Set some socket options that make sense. */
558 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
560 if (ip_version == 6) {
561 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
564 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
568 syslog(1, "Can't bind: %s\n", strerror(errno));
569 return (-WC_EXIT_BIND);
572 if (listen(s, queue_len) < 0) {
573 syslog(1, "Can't listen: %s\n", strerror(errno));
574 return (-WC_EXIT_BIND);
581 * Create a Unix domain socket and listen on it
582 * sockpath - file name of the unix domain socket
583 * queue_len - Number of incoming connections to allow in the queue
585 int webcit_uds_server(char *sockpath, int queue_len)
587 struct sockaddr_un addr;
590 int actual_queue_len;
592 actual_queue_len = queue_len;
593 if (actual_queue_len < 5) actual_queue_len = 5;
595 i = unlink(sockpath);
596 if ((i != 0) && (errno != ENOENT)) {
597 syslog(1, "webcit: can't unlink %s: %s\n",
598 sockpath, strerror(errno));
599 return (-WC_EXIT_BIND);
602 memset(&addr, 0, sizeof(addr));
603 addr.sun_family = AF_UNIX;
604 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
606 s = socket(AF_UNIX, SOCK_STREAM, 0);
608 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
609 return (-WC_EXIT_BIND);
612 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
613 syslog(1, "webcit: Can't bind: %s\n",
615 return (-WC_EXIT_BIND);
618 if (listen(s, actual_queue_len) < 0) {
619 syslog(1, "webcit: Can't listen: %s\n",
621 return (-WC_EXIT_BIND);
624 chmod(sockpath, 0777);
632 * Read data from the client socket.
634 * sock socket fd to read from
635 * buf buffer to read into
636 * bytes number of bytes to read
637 * timeout Number of seconds to wait before timing out
639 * Possible return values:
640 * 1 Requested number of bytes has been read.
641 * 0 Request timed out.
642 * -1 Connection is broken, or other error.
644 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
654 baselen = StrLength(Target);
656 if (Hdr->Pos == NULL)
657 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
658 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
660 if (bytes < bufremain)
662 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
663 StrBufCutLeft(Hdr->ReadBuf, bufremain);
665 if (bytes > bufremain)
667 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
669 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
671 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
673 write(2, "\033[32m", 5);
674 write(2, buf, bytes);
675 write(2, "\033[30m", 5);
680 syslog(2, "client_read_ssl() failed\n");
689 retval = StrBufReadBLOBBuffered(Target,
698 syslog(2, "client_read() failed: %s\n",
705 write(2, "\033[32m", 5);
706 write(2, buf, bytes);
707 write(2, "\033[30m", 5);
714 * Begin buffering HTTP output so we can transmit it all in one write operation later.
716 void begin_burst(void)
718 if (WC->WBuf == NULL) {
719 WC->WBuf = NewStrBufPlain(NULL, 32768);
725 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
730 const char *ptr, *eptr;
736 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
738 if (CompressBuffer(WCC->WBuf) > 0)
739 hprintf("Content-encoding: gzip\r\n");
741 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
746 if (WCC->WFBuf != NULL) {
747 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
748 FreeStrBuf(&WCC->WFBuf);
751 if (WCC->Hdr->HR.prohibit_caching)
752 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
753 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
755 ptr = ChrPtr(WCC->HBuf);
756 count = StrLength(WCC->HBuf);
761 client_write_ssl(WCC->HBuf);
762 client_write_ssl(WCC->WBuf);
770 write(2, "\033[34m", 5);
771 write(2, ptr, StrLength(WCC->WBuf));
772 write(2, "\033[30m", 5);
774 if (WCC->Hdr->http_sock == -1)
776 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
778 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
779 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
781 FD_SET(WCC->Hdr->http_sock, &wset);
782 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
783 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
788 if ((WCC->Hdr->http_sock == -1) ||
789 (res = write(WCC->Hdr->http_sock,
792 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
800 ptr = ChrPtr(WCC->WBuf);
801 count = StrLength(WCC->WBuf);
806 write(2, "\033[34m", 5);
807 write(2, ptr, StrLength(WCC->WBuf));
808 write(2, "\033[30m", 5);
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);
915 sess->ReadPos = NULL;
916 FreeStrBuf(&sess->MigrateReadLineBuf);
917 if (sess->serv_sock > 0)
918 close(sess->serv_sock);