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(1, "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;
41 memset(&addr, 0, sizeof(addr));
42 addr.sun_family = AF_UNIX;
43 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
45 s = socket(AF_UNIX, SOCK_STREAM, 0);
47 syslog(1, "Can't create socket [%s]: %s\n", sockpath, strerror(errno));
51 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
52 syslog(1, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
62 * TCP client - connect to a host/port
64 int tcp_connectsock(char *host, char *service)
66 struct in6_addr serveraddr;
67 struct addrinfo hints;
68 struct addrinfo *res = NULL;
69 struct addrinfo *ai = NULL;
73 if ((host == NULL) || IsEmptyStr(host))
75 if ((service == NULL) || IsEmptyStr(service))
78 syslog(9, "tcp_connectsock(%s,%s)\n", host, service);
80 memset(&hints, 0x00, sizeof(hints));
81 hints.ai_flags = AI_NUMERICSERV;
82 hints.ai_family = AF_UNSPEC;
83 hints.ai_socktype = SOCK_STREAM;
86 * Handle numeric IPv4 and IPv6 addresses
88 rc = inet_pton(AF_INET, host, &serveraddr);
89 if (rc == 1) { /* dotted quad */
90 hints.ai_family = AF_INET;
91 hints.ai_flags |= AI_NUMERICHOST;
93 rc = inet_pton(AF_INET6, host, &serveraddr);
94 if (rc == 1) { /* IPv6 address */
95 hints.ai_family = AF_INET6;
96 hints.ai_flags |= AI_NUMERICHOST;
100 /* Begin the connection process */
102 rc = getaddrinfo(host, service, &hints, &res);
104 syslog(1, "%s: %s\n", host, gai_strerror(rc));
110 * Try all available addresses until we connect to one or until we run out.
112 for (ai = res; ai != NULL; ai = ai->ai_next) {
114 if (ai->ai_family == AF_INET) syslog(9, "Trying IPv4\n");
115 else if (ai->ai_family == AF_INET6) syslog(9, "Trying IPv6\n");
116 else syslog(9, "This is going to fail.\n");
118 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
120 syslog(1, "socket() failed: %s\n", strerror(errno));
124 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
130 syslog(1, "connect() failed: %s\n", strerror(errno));
140 * input string from pipe
142 int serv_getln(char *strbuf, int bufsize)
148 StrBuf_ServGetln(WCC->MigrateReadLineBuf);
149 len = StrLength(WCC->MigrateReadLineBuf);
152 memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
153 FlushStrBuf(WCC->MigrateReadLineBuf);
156 syslog(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
162 int StrBuf_ServGetln(StrBuf *buf)
165 const char *ErrStr = NULL;
172 rc = StrBufTCP_read_buffered_line_fast(buf,
180 syslog(1, "StrBuf_ServGetln(): Server connection broken: %s\n",
183 if (WCC->serv_sock > 0) close(WCC->serv_sock);
184 WCC->serv_sock = (-1);
192 if (WCC->ReadPos != NULL)
193 pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
194 syslog(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
200 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
206 rc = StrBufReadBLOBBuffered(buf,
216 syslog(1, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
219 if (WCC->serv_sock > 0) close(WCC->serv_sock);
220 WCC->serv_sock = (-1);
226 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
232 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
239 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
242 syslog(1, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
245 if (WCC->serv_sock > 0) close(WCC->serv_sock);
246 WCC->serv_sock = (-1);
252 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
259 void FlushReadBuf (void)
266 len = StrLength(WCC->ReadBuf);
268 (WCC->ReadPos != NULL) &&
269 (WCC->ReadPos != StrBufNOTNULL))
272 pch = ChrPtr(WCC->ReadBuf);
274 if (WCC->ReadPos != pche)
277 "ERROR: somebody didn't eat his soup! Remaing Chars: %ld [%s]\n",
278 (long)(pche - WCC->ReadPos),
282 "--------------------------------------------------------------------------------\n"
284 "--------------------------------------------------------------------------------\n",
286 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
290 FlushStrBuf(WCC->ReadBuf);
298 * send binary to server
299 * buf the buffer to write to citadel server
300 * nbytes how many bytes to send to citadel server
302 int serv_write(const char *buf, int nbytes)
305 int bytes_written = 0;
309 while (bytes_written < nbytes) {
310 retval = write(WCC->serv_sock, &buf[bytes_written],
311 nbytes - bytes_written);
313 const char *ErrStr = strerror(errno);
314 syslog(1, "serv_write(): Server connection broken: %s\n",
316 if (WCC->serv_sock > 0) close(WCC->serv_sock);
317 WCC->serv_sock = (-1);
322 bytes_written = bytes_written + retval;
329 * send line to server
330 * string the line to send to the citadel server
332 int serv_puts(const char *string)
335 syslog(9, "%3d>>>%s\n", WC->serv_sock, string);
339 if (!serv_write(string, strlen(string)))
341 return serv_write("\n", 1);
345 * send line to server
346 * string the line to send to the citadel server
348 int serv_putbuf(const StrBuf *string)
351 syslog(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
355 if (!serv_write(ChrPtr(string), StrLength(string)))
357 return serv_write("\n", 1);
362 * convenience function to send stuff to the server
363 * format the formatstring
364 * ... the entities to insert into format
366 int serv_printf(const char *format,...)
375 va_start(arg_ptr, format);
376 vsnprintf(buf, sizeof buf, format, arg_ptr);
382 rc = serv_write(buf, len);
384 syslog(9, ">>>%s", buf);
391 * Read binary data from server into memory using a series of server READ commands.
392 * returns the read content as StrBuf
394 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
397 size_t bytes_read = 0;
398 size_t this_block = 0;
406 while ((bytes_read < total_len) && (ServerRc == 6)) {
408 if (WCC->serv_sock==-1) {
413 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
414 if ( (rc = StrBuf_ServGetln(Buf) > 0) &&
415 (ServerRc = GetServerStatus(Buf, NULL), ServerRc == 6) )
419 StrBufCutLeft(Buf, 4);
420 this_block = StrTol(Buf);
421 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
423 syslog(1, "Server connection broken during download\n");
425 if (WCC->serv_sock > 0) close(WCC->serv_sock);
426 WCC->serv_sock = (-1);
435 return StrLength(Ret);
439 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
443 const char *pch, *pchs;
444 int rlen, len, retval = 0;
448 if (StrLength(Hdr->ReadBuf) > 0)
450 pchs = ChrPtr(Hdr->ReadBuf);
451 pch = strchr(pchs, '\n');
455 if (len > 0 && (*(pch - 1) == '\r') )
457 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
458 StrBufCutLeft(Hdr->ReadBuf, len + 1);
463 while (retval == 0) {
465 pchs = ChrPtr(Hdr->ReadBuf);
467 pch = strchr(pchs, '\n');
469 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
470 pchs = ChrPtr(Hdr->ReadBuf);
471 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(const char *ip_addr, int port_number, int queue_len)
517 const char *ipv4broadcast = "0.0.0.0";
520 struct sockaddr_in6 sin6;
521 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, "*"))
537 sin6.sin6_addr = in6addr_any;
539 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
542 sin4.sin_addr.s_addr = INADDR_ANY;
544 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
547 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
548 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
549 return (-WC_EXIT_BIND);
552 else /* specific IPv6 */
555 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
556 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
557 return (-WC_EXIT_BIND);
561 if (port_number == 0) {
562 syslog(1, "Cannot start: no port number specified.\n");
563 return (-WC_EXIT_BIND);
565 sin6.sin6_port = htons((u_short) port_number);
566 sin4.sin_port = htons((u_short) port_number);
568 p = getprotobyname("tcp");
570 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
572 if (IsDefault && (errno == EAFNOSUPPORT))
575 ip_addr = ipv4broadcast;
578 syslog(LOG_WARNING, "Can't create a listening socket: %s\n", strerror(errno));
579 return (-WC_EXIT_BIND);
581 /* Set some socket options that make sense. */
583 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
585 if (ip_version == 6) {
586 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
589 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
593 syslog(1, "Can't bind: %s\n", strerror(errno));
595 return (-WC_EXIT_BIND);
598 if (listen(s, queue_len) < 0) {
599 syslog(1, "Can't listen: %s\n", strerror(errno));
601 return (-WC_EXIT_BIND);
608 * Create a Unix domain socket and listen on it
609 * sockpath - file name of the unix domain socket
610 * queue_len - Number of incoming connections to allow in the queue
612 int webcit_uds_server(char *sockpath, int queue_len)
614 struct sockaddr_un addr;
617 int actual_queue_len;
619 actual_queue_len = queue_len;
620 if (actual_queue_len < 5) actual_queue_len = 5;
622 i = unlink(sockpath);
623 if ((i != 0) && (errno != ENOENT)) {
624 syslog(1, "webcit: can't unlink %s: %s\n",
625 sockpath, strerror(errno));
626 return (-WC_EXIT_BIND);
629 memset(&addr, 0, sizeof(addr));
630 addr.sun_family = AF_UNIX;
631 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
633 s = socket(AF_UNIX, SOCK_STREAM, 0);
635 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
636 return (-WC_EXIT_BIND);
639 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
640 syslog(1, "webcit: Can't bind: %s\n", strerror(errno));
642 return (-WC_EXIT_BIND);
645 if (listen(s, actual_queue_len) < 0) {
646 syslog(1, "webcit: Can't listen: %s\n", strerror(errno));
648 return (-WC_EXIT_BIND);
651 chmod(sockpath, 0777);
659 * Read data from the client socket.
661 * sock socket fd to read from
662 * buf buffer to read into
663 * bytes number of bytes to read
664 * timeout Number of seconds to wait before timing out
666 * Possible return values:
667 * 1 Requested number of bytes has been read.
668 * 0 Request timed out.
669 * -1 Connection is broken, or other error.
671 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
681 baselen = StrLength(Target);
683 if (Hdr->Pos == NULL)
684 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
686 if (StrLength(Hdr->ReadBuf) > 0)
688 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
690 if (bytes < bufremain)
692 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
693 StrBufCutLeft(Hdr->ReadBuf, bufremain);
696 if (bytes > bufremain)
698 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
700 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
702 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
706 syslog(2, "client_read_ssl() failed\n");
715 retval = StrBufReadBLOBBuffered(Target,
724 syslog(2, "client_read() failed: %s\n",
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);
788 if (WCC->Hdr->http_sock == -1)
790 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
792 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
793 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
795 FD_SET(WCC->Hdr->http_sock, &wset);
796 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
797 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
802 if ((WCC->Hdr->http_sock == -1) ||
803 (res = write(WCC->Hdr->http_sock,
806 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
814 ptr = ChrPtr(WCC->WBuf);
815 count = StrLength(WCC->WBuf);
818 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
819 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
821 FD_SET(WCC->Hdr->http_sock, &wset);
822 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
823 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
828 if ((WCC->Hdr->http_sock == -1) ||
829 (res = write(WCC->Hdr->http_sock,
832 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
840 return StrLength(WCC->WBuf);
845 * lingering_close() a`la Apache. see
846 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
848 int lingering_close(int fd)
853 struct timeval tv, start;
855 gettimeofday(&start, NULL);
861 gettimeofday(&tv, NULL);
862 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
863 tv.tv_usec = start.tv_usec - tv.tv_usec;
864 if (tv.tv_usec < 0) {
866 tv.tv_usec += 1000000;
870 i = select(fd + 1, &set, NULL, NULL, &tv);
871 } while (i == -1 && errno == EINTR);
876 i = read(fd, buf, sizeof buf);
877 } while (i != 0 && (i != -1 || errno == EINTR));
883 HttpNewModule_TCPSOCKETS
884 (ParsedHttpHdrs *httpreq)
887 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
891 HttpDetachModule_TCPSOCKETS
892 (ParsedHttpHdrs *httpreq)
895 FlushStrBuf(httpreq->ReadBuf);
896 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
900 HttpDestroyModule_TCPSOCKETS
901 (ParsedHttpHdrs *httpreq)
904 FreeStrBuf(&httpreq->ReadBuf);
909 SessionNewModule_TCPSOCKETS
912 sess->CLineBuf = NewStrBuf();
913 sess->MigrateReadLineBuf = NewStrBuf();
917 SessionDestroyModule_TCPSOCKETS
920 FreeStrBuf(&sess->CLineBuf);
921 FreeStrBuf(&sess->ReadBuf);
923 sess->ReadPos = NULL;
924 FreeStrBuf(&sess->MigrateReadLineBuf);
925 if (sess->serv_sock > 0) {
926 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
927 close(sess->serv_sock);
929 sess->serv_sock = -1;