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;
405 while (bytes_read < total_len) {
407 if (WCC->serv_sock==-1) {
412 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
413 if ( (rc = StrBuf_ServGetln(Buf) > 0) && (GetServerStatus(Buf, NULL) == 6) )
417 StrBufCutLeft(Buf, 4);
418 this_block = StrTol(Buf);
419 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
421 syslog(1, "Server connection broken during download\n");
423 if (WCC->serv_sock > 0) close(WCC->serv_sock);
424 WCC->serv_sock = (-1);
433 return StrLength(Ret);
437 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
441 const char *pch, *pchs;
442 int rlen, len, retval = 0;
446 if (StrLength(Hdr->ReadBuf) > 0)
448 pchs = ChrPtr(Hdr->ReadBuf);
449 pch = strchr(pchs, '\n');
453 if (len > 0 && (*(pch - 1) == '\r') )
455 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
456 StrBufCutLeft(Hdr->ReadBuf, len + 1);
461 while (retval == 0) {
463 pchs = ChrPtr(Hdr->ReadBuf);
465 pch = strchr(pchs, '\n');
467 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
468 pchs = ChrPtr(Hdr->ReadBuf);
469 pch = strchr(pchs, '\n');
480 if ((retval > 0) && (pch != NULL)) {
483 if (len > 0 && (*(pch - 1) == '\r') )
485 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
486 StrBufCutLeft(Hdr->ReadBuf, len + 1);
495 return StrBufTCP_read_buffered_line_fast(Target,
506 * This is a generic function to set up a master socket for listening on
507 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
509 * ip_addr IP address to bind
510 * port_number port number to bind
511 * queue_len number of incoming connections to allow in the queue
513 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
516 struct sockaddr_in6 sin6;
517 struct sockaddr_in sin4;
521 memset(&sin6, 0, sizeof(sin6));
522 memset(&sin4, 0, sizeof(sin4));
523 sin6.sin6_family = AF_INET6;
524 sin4.sin_family = AF_INET;
526 if ( (ip_addr == NULL) /* any IPv6 */
527 || (IsEmptyStr(ip_addr))
528 || (!strcmp(ip_addr, "*"))
531 sin6.sin6_addr = in6addr_any;
533 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
536 sin4.sin_addr.s_addr = INADDR_ANY;
538 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
541 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
542 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
543 return (-WC_EXIT_BIND);
546 else /* specific IPv6 */
549 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
550 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
551 return (-WC_EXIT_BIND);
555 if (port_number == 0) {
556 syslog(1, "Cannot start: no port number specified.\n");
557 return (-WC_EXIT_BIND);
559 sin6.sin6_port = htons((u_short) port_number);
560 sin4.sin_port = htons((u_short) port_number);
562 p = getprotobyname("tcp");
564 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
566 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
567 return (-WC_EXIT_BIND);
569 /* Set some socket options that make sense. */
571 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
573 if (ip_version == 6) {
574 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
577 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
581 syslog(1, "Can't bind: %s\n", strerror(errno));
583 return (-WC_EXIT_BIND);
586 if (listen(s, queue_len) < 0) {
587 syslog(1, "Can't listen: %s\n", strerror(errno));
589 return (-WC_EXIT_BIND);
596 * Create a Unix domain socket and listen on it
597 * sockpath - file name of the unix domain socket
598 * queue_len - Number of incoming connections to allow in the queue
600 int webcit_uds_server(char *sockpath, int queue_len)
602 struct sockaddr_un addr;
605 int actual_queue_len;
607 actual_queue_len = queue_len;
608 if (actual_queue_len < 5) actual_queue_len = 5;
610 i = unlink(sockpath);
611 if ((i != 0) && (errno != ENOENT)) {
612 syslog(1, "webcit: can't unlink %s: %s\n",
613 sockpath, strerror(errno));
614 return (-WC_EXIT_BIND);
617 memset(&addr, 0, sizeof(addr));
618 addr.sun_family = AF_UNIX;
619 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
621 s = socket(AF_UNIX, SOCK_STREAM, 0);
623 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
624 return (-WC_EXIT_BIND);
627 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
628 syslog(1, "webcit: Can't bind: %s\n", strerror(errno));
630 return (-WC_EXIT_BIND);
633 if (listen(s, actual_queue_len) < 0) {
634 syslog(1, "webcit: Can't listen: %s\n", strerror(errno));
636 return (-WC_EXIT_BIND);
639 chmod(sockpath, 0777);
647 * Read data from the client socket.
649 * sock socket fd to read from
650 * buf buffer to read into
651 * bytes number of bytes to read
652 * timeout Number of seconds to wait before timing out
654 * Possible return values:
655 * 1 Requested number of bytes has been read.
656 * 0 Request timed out.
657 * -1 Connection is broken, or other error.
659 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
669 baselen = StrLength(Target);
671 if (Hdr->Pos == NULL)
672 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
674 if (StrLength(Hdr->ReadBuf) > 0)
676 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
678 if (bytes < bufremain)
680 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
681 StrBufCutLeft(Hdr->ReadBuf, bufremain);
684 if (bytes > bufremain)
686 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
688 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
690 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
694 syslog(2, "client_read_ssl() failed\n");
703 retval = StrBufReadBLOBBuffered(Target,
712 syslog(2, "client_read() failed: %s\n",
723 * Begin buffering HTTP output so we can transmit it all in one write operation later.
725 void begin_burst(void)
727 if (WC->WBuf == NULL) {
728 WC->WBuf = NewStrBufPlain(NULL, 32768);
734 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
739 const char *ptr, *eptr;
745 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
747 if (CompressBuffer(WCC->WBuf) > 0)
748 hprintf("Content-encoding: gzip\r\n");
750 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
755 if (WCC->WFBuf != NULL) {
756 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
757 FreeStrBuf(&WCC->WFBuf);
760 if (WCC->Hdr->HR.prohibit_caching)
761 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
762 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
764 ptr = ChrPtr(WCC->HBuf);
765 count = StrLength(WCC->HBuf);
770 client_write_ssl(WCC->HBuf);
771 client_write_ssl(WCC->WBuf);
776 if (WCC->Hdr->http_sock == -1)
778 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
780 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
781 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
783 FD_SET(WCC->Hdr->http_sock, &wset);
784 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
785 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
790 if ((WCC->Hdr->http_sock == -1) ||
791 (res = write(WCC->Hdr->http_sock,
794 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
802 ptr = ChrPtr(WCC->WBuf);
803 count = StrLength(WCC->WBuf);
806 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
807 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
809 FD_SET(WCC->Hdr->http_sock, &wset);
810 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
811 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
816 if ((WCC->Hdr->http_sock == -1) ||
817 (res = write(WCC->Hdr->http_sock,
820 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
828 return StrLength(WCC->WBuf);
833 * lingering_close() a`la Apache. see
834 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
836 int lingering_close(int fd)
841 struct timeval tv, start;
843 gettimeofday(&start, NULL);
849 gettimeofday(&tv, NULL);
850 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
851 tv.tv_usec = start.tv_usec - tv.tv_usec;
852 if (tv.tv_usec < 0) {
854 tv.tv_usec += 1000000;
858 i = select(fd + 1, &set, NULL, NULL, &tv);
859 } while (i == -1 && errno == EINTR);
864 i = read(fd, buf, sizeof buf);
865 } while (i != 0 && (i != -1 || errno == EINTR));
871 HttpNewModule_TCPSOCKETS
872 (ParsedHttpHdrs *httpreq)
875 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
879 HttpDetachModule_TCPSOCKETS
880 (ParsedHttpHdrs *httpreq)
883 FlushStrBuf(httpreq->ReadBuf);
884 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
888 HttpDestroyModule_TCPSOCKETS
889 (ParsedHttpHdrs *httpreq)
892 FreeStrBuf(&httpreq->ReadBuf);
897 SessionNewModule_TCPSOCKETS
900 sess->CLineBuf = NewStrBuf();
901 sess->MigrateReadLineBuf = NewStrBuf();
905 SessionDestroyModule_TCPSOCKETS
908 FreeStrBuf(&sess->CLineBuf);
909 FreeStrBuf(&sess->ReadBuf);
911 sess->ReadPos = NULL;
912 FreeStrBuf(&sess->MigrateReadLineBuf);
913 if (sess->serv_sock > 0) {
914 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
915 close(sess->serv_sock);
917 sess->serv_sock = -1;