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(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? */
696 syslog(2, "client_read_ssl() failed\n");
705 retval = StrBufReadBLOBBuffered(Target,
714 syslog(2, "client_read() failed: %s\n",
725 * Begin buffering HTTP output so we can transmit it all in one write operation later.
727 void begin_burst(void)
729 if (WC->WBuf == NULL) {
730 WC->WBuf = NewStrBufPlain(NULL, 32768);
736 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
741 const char *ptr, *eptr;
747 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
749 if (CompressBuffer(WCC->WBuf) > 0)
750 hprintf("Content-encoding: gzip\r\n");
752 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
757 if (WCC->WFBuf != NULL) {
758 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
759 FreeStrBuf(&WCC->WFBuf);
762 if (WCC->Hdr->HR.prohibit_caching)
763 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
764 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
766 ptr = ChrPtr(WCC->HBuf);
767 count = StrLength(WCC->HBuf);
772 client_write_ssl(WCC->HBuf);
773 client_write_ssl(WCC->WBuf);
778 if (WCC->Hdr->http_sock == -1)
780 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
782 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
783 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
785 FD_SET(WCC->Hdr->http_sock, &wset);
786 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
787 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
792 if ((WCC->Hdr->http_sock == -1) ||
793 (res = write(WCC->Hdr->http_sock,
796 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
804 ptr = ChrPtr(WCC->WBuf);
805 count = StrLength(WCC->WBuf);
808 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
809 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
811 FD_SET(WCC->Hdr->http_sock, &wset);
812 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
813 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
818 if ((WCC->Hdr->http_sock == -1) ||
819 (res = write(WCC->Hdr->http_sock,
822 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
830 return StrLength(WCC->WBuf);
835 * lingering_close() a`la Apache. see
836 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
838 int lingering_close(int fd)
843 struct timeval tv, start;
845 gettimeofday(&start, NULL);
851 gettimeofday(&tv, NULL);
852 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
853 tv.tv_usec = start.tv_usec - tv.tv_usec;
854 if (tv.tv_usec < 0) {
856 tv.tv_usec += 1000000;
860 i = select(fd + 1, &set, NULL, NULL, &tv);
861 } while (i == -1 && errno == EINTR);
866 i = read(fd, buf, sizeof buf);
867 } while (i != 0 && (i != -1 || errno == EINTR));
873 HttpNewModule_TCPSOCKETS
874 (ParsedHttpHdrs *httpreq)
877 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
881 HttpDetachModule_TCPSOCKETS
882 (ParsedHttpHdrs *httpreq)
885 FlushStrBuf(httpreq->ReadBuf);
886 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
890 HttpDestroyModule_TCPSOCKETS
891 (ParsedHttpHdrs *httpreq)
894 FreeStrBuf(&httpreq->ReadBuf);
899 SessionNewModule_TCPSOCKETS
902 sess->CLineBuf = NewStrBuf();
903 sess->MigrateReadLineBuf = NewStrBuf();
907 SessionDestroyModule_TCPSOCKETS
910 FreeStrBuf(&sess->CLineBuf);
911 FreeStrBuf(&sess->ReadBuf);
913 sess->ReadPos = NULL;
914 FreeStrBuf(&sess->MigrateReadLineBuf);
915 if (sess->serv_sock > 0) {
916 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
917 close(sess->serv_sock);
919 sess->serv_sock = -1;