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.
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.
20 * Uncomment this to log all communications with the Citadel server
26 #include "webserver.h"
28 long MaxRead = -1; /* should we do READ scattered or all at once? */
31 * register the timeout
33 RETSIGTYPE timeout(int signum)
35 syslog(1, "Connection timed out; unable to reach citserver\n");
36 /* no exit here, since we need to server the connection unreachable thing. exit(3); */
41 * Client side - connect to a unix domain socket
43 int uds_connectsock(char *sockpath)
45 struct sockaddr_un addr;
48 memset(&addr, 0, sizeof(addr));
49 addr.sun_family = AF_UNIX;
50 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
52 s = socket(AF_UNIX, SOCK_STREAM, 0);
54 syslog(1, "Can't create socket [%s]: %s\n", sockpath, strerror(errno));
58 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
59 syslog(1, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
69 * TCP client - connect to a host/port
71 int tcp_connectsock(char *host, char *service)
73 struct in6_addr serveraddr;
74 struct addrinfo hints;
75 struct addrinfo *res = NULL;
76 struct addrinfo *ai = NULL;
80 if ((host == NULL) || IsEmptyStr(host))
82 if ((service == NULL) || IsEmptyStr(service))
85 syslog(9, "tcp_connectsock(%s,%s)\n", host, service);
87 memset(&hints, 0x00, sizeof(hints));
88 hints.ai_flags = AI_NUMERICSERV;
89 hints.ai_family = AF_UNSPEC;
90 hints.ai_socktype = SOCK_STREAM;
93 * Handle numeric IPv4 and IPv6 addresses
95 rc = inet_pton(AF_INET, host, &serveraddr);
96 if (rc == 1) { /* dotted quad */
97 hints.ai_family = AF_INET;
98 hints.ai_flags |= AI_NUMERICHOST;
100 rc = inet_pton(AF_INET6, host, &serveraddr);
101 if (rc == 1) { /* IPv6 address */
102 hints.ai_family = AF_INET6;
103 hints.ai_flags |= AI_NUMERICHOST;
107 /* Begin the connection process */
109 rc = getaddrinfo(host, service, &hints, &res);
111 syslog(1, "%s: %s\n", host, gai_strerror(rc));
117 * Try all available addresses until we connect to one or until we run out.
119 for (ai = res; ai != NULL; ai = ai->ai_next) {
121 if (ai->ai_family == AF_INET) syslog(9, "Trying IPv4\n");
122 else if (ai->ai_family == AF_INET6) syslog(9, "Trying IPv6\n");
123 else syslog(9, "This is going to fail.\n");
125 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
127 syslog(1, "socket() failed: %s\n", strerror(errno));
131 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
137 syslog(1, "connect() failed: %s\n", strerror(errno));
147 * input string from pipe
149 int serv_getln(char *strbuf, int bufsize)
155 StrBuf_ServGetln(WCC->MigrateReadLineBuf);
156 len = StrLength(WCC->MigrateReadLineBuf);
159 memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
160 FlushStrBuf(WCC->MigrateReadLineBuf);
163 syslog(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
169 int StrBuf_ServGetln(StrBuf *buf)
172 const char *ErrStr = NULL;
179 rc = StrBufTCP_read_buffered_line_fast(buf,
187 syslog(1, "StrBuf_ServGetln(): Server connection broken: %s\n",
190 if (WCC->serv_sock > 0) close(WCC->serv_sock);
191 WCC->serv_sock = (-1);
199 if (WCC->ReadPos != NULL)
200 pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
201 syslog(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
207 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
213 rc = StrBufReadBLOBBuffered(buf,
223 syslog(1, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
226 if (WCC->serv_sock > 0) close(WCC->serv_sock);
227 WCC->serv_sock = (-1);
233 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
239 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
246 rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
249 syslog(1, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
252 if (WCC->serv_sock > 0) close(WCC->serv_sock);
253 WCC->serv_sock = (-1);
259 syslog(9, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
266 void FlushReadBuf (void)
273 len = StrLength(WCC->ReadBuf);
275 (WCC->ReadPos != NULL) &&
276 (WCC->ReadPos != StrBufNOTNULL))
279 pch = ChrPtr(WCC->ReadBuf);
281 if (WCC->ReadPos != pche)
284 "ERROR: somebody didn't eat his soup! Remaing Chars: %ld [%s]\n",
285 (long)(pche - WCC->ReadPos),
289 "--------------------------------------------------------------------------------\n"
291 "--------------------------------------------------------------------------------\n",
293 AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
297 FlushStrBuf(WCC->ReadBuf);
305 * send binary to server
306 * buf the buffer to write to citadel server
307 * nbytes how many bytes to send to citadel server
309 int serv_write(const char *buf, int nbytes)
312 int bytes_written = 0;
316 while (bytes_written < nbytes) {
317 retval = write(WCC->serv_sock, &buf[bytes_written],
318 nbytes - bytes_written);
320 const char *ErrStr = strerror(errno);
321 syslog(1, "serv_write(): Server connection broken: %s\n",
323 if (WCC->serv_sock > 0) close(WCC->serv_sock);
324 WCC->serv_sock = (-1);
329 bytes_written = bytes_written + retval;
336 * send line to server
337 * string the line to send to the citadel server
339 int serv_puts(const char *string)
342 syslog(9, "%3d>>>%s\n", WC->serv_sock, string);
346 if (!serv_write(string, strlen(string)))
348 return serv_write("\n", 1);
352 * send line to server
353 * string the line to send to the citadel server
355 int serv_putbuf(const StrBuf *string)
358 syslog(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
362 if (!serv_write(ChrPtr(string), StrLength(string)))
364 return serv_write("\n", 1);
369 * convenience function to send stuff to the server
370 * format the formatstring
371 * ... the entities to insert into format
373 int serv_printf(const char *format,...)
382 va_start(arg_ptr, format);
383 vsnprintf(buf, sizeof buf, format, arg_ptr);
389 rc = serv_write(buf, len);
391 syslog(9, ">>>%s", buf);
398 * Read binary data from server into memory using a series of server READ commands.
399 * returns the read content as StrBuf
401 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf)
404 size_t bytes_read = 0;
405 size_t this_block = 0;
412 while (bytes_read < total_len) {
414 if (WCC->serv_sock==-1) {
419 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
420 if ( (rc = StrBuf_ServGetln(Buf) > 0) && (GetServerStatus(Buf, NULL) == 6) )
424 StrBufCutLeft(Buf, 4);
425 this_block = StrTol(Buf);
426 rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
428 syslog(1, "Server connection broken during download\n");
430 if (WCC->serv_sock > 0) close(WCC->serv_sock);
431 WCC->serv_sock = (-1);
440 return StrLength(Ret);
444 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
448 const char *pch, *pchs;
449 int rlen, len, retval = 0;
453 if (StrLength(Hdr->ReadBuf) > 0)
455 pchs = ChrPtr(Hdr->ReadBuf);
456 pch = strchr(pchs, '\n');
460 if (len > 0 && (*(pch - 1) == '\r') )
462 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
463 StrBufCutLeft(Hdr->ReadBuf, len + 1);
468 while (retval == 0) {
470 pchs = ChrPtr(Hdr->ReadBuf);
472 pch = strchr(pchs, '\n');
474 retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
475 pchs = ChrPtr(Hdr->ReadBuf);
476 pch = strchr(pchs, '\n');
487 if ((retval > 0) && (pch != NULL)) {
490 if (len > 0 && (*(pch - 1) == '\r') )
492 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
493 StrBufCutLeft(Hdr->ReadBuf, len + 1);
502 return StrBufTCP_read_buffered_line_fast(Target,
513 * This is a generic function to set up a master socket for listening on
514 * a TCP port. The server shuts down if the bind fails. (IPv4/IPv6 version)
516 * ip_addr IP address to bind
517 * port_number port number to bind
518 * queue_len number of incoming connections to allow in the queue
520 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
523 struct sockaddr_in6 sin6;
524 struct sockaddr_in sin4;
528 memset(&sin6, 0, sizeof(sin6));
529 memset(&sin4, 0, sizeof(sin4));
530 sin6.sin6_family = AF_INET6;
531 sin4.sin_family = AF_INET;
533 if ( (ip_addr == NULL) /* any IPv6 */
534 || (IsEmptyStr(ip_addr))
535 || (!strcmp(ip_addr, "*"))
538 sin6.sin6_addr = in6addr_any;
540 else if (!strcmp(ip_addr, "0.0.0.0")) /* any IPv4 */
543 sin4.sin_addr.s_addr = INADDR_ANY;
545 else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) /* specific IPv4 */
548 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
549 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
550 return (-WC_EXIT_BIND);
553 else /* specific IPv6 */
556 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
557 syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
558 return (-WC_EXIT_BIND);
562 if (port_number == 0) {
563 syslog(1, "Cannot start: no port number specified.\n");
564 return (-WC_EXIT_BIND);
566 sin6.sin6_port = htons((u_short) port_number);
567 sin4.sin_port = htons((u_short) port_number);
569 p = getprotobyname("tcp");
571 s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
573 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
574 return (-WC_EXIT_BIND);
576 /* Set some socket options that make sense. */
578 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
580 if (ip_version == 6) {
581 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
584 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
588 syslog(1, "Can't bind: %s\n", strerror(errno));
590 return (-WC_EXIT_BIND);
593 if (listen(s, queue_len) < 0) {
594 syslog(1, "Can't listen: %s\n", strerror(errno));
596 return (-WC_EXIT_BIND);
603 * Create a Unix domain socket and listen on it
604 * sockpath - file name of the unix domain socket
605 * queue_len - Number of incoming connections to allow in the queue
607 int webcit_uds_server(char *sockpath, int queue_len)
609 struct sockaddr_un addr;
612 int actual_queue_len;
614 actual_queue_len = queue_len;
615 if (actual_queue_len < 5) actual_queue_len = 5;
617 i = unlink(sockpath);
618 if ((i != 0) && (errno != ENOENT)) {
619 syslog(1, "webcit: can't unlink %s: %s\n",
620 sockpath, strerror(errno));
621 return (-WC_EXIT_BIND);
624 memset(&addr, 0, sizeof(addr));
625 addr.sun_family = AF_UNIX;
626 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
628 s = socket(AF_UNIX, SOCK_STREAM, 0);
630 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
631 return (-WC_EXIT_BIND);
634 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
635 syslog(1, "webcit: Can't bind: %s\n", strerror(errno));
637 return (-WC_EXIT_BIND);
640 if (listen(s, actual_queue_len) < 0) {
641 syslog(1, "webcit: Can't listen: %s\n", strerror(errno));
643 return (-WC_EXIT_BIND);
646 chmod(sockpath, 0777);
654 * Read data from the client socket.
656 * sock socket fd to read from
657 * buf buffer to read into
658 * bytes number of bytes to read
659 * timeout Number of seconds to wait before timing out
661 * Possible return values:
662 * 1 Requested number of bytes has been read.
663 * 0 Request timed out.
664 * -1 Connection is broken, or other error.
666 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
676 baselen = StrLength(Target);
678 if (Hdr->Pos == NULL)
679 Hdr->Pos = ChrPtr(Hdr->ReadBuf);
681 if (StrLength(Hdr->ReadBuf) > 0)
683 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
685 if (bytes < bufremain)
687 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
688 StrBufCutLeft(Hdr->ReadBuf, bufremain);
691 if (bytes > bufremain)
693 while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
695 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
697 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
701 syslog(2, "client_read_ssl() failed\n");
710 retval = StrBufReadBLOBBuffered(Target,
719 syslog(2, "client_read() failed: %s\n",
730 * Begin buffering HTTP output so we can transmit it all in one write operation later.
732 void begin_burst(void)
734 if (WC->WBuf == NULL) {
735 WC->WBuf = NewStrBufPlain(NULL, 32768);
741 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
746 const char *ptr, *eptr;
752 if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
754 if (CompressBuffer(WCC->WBuf) > 0)
755 hprintf("Content-encoding: gzip\r\n");
757 syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
762 if (WCC->WFBuf != NULL) {
763 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
764 FreeStrBuf(&WCC->WFBuf);
767 if (WCC->Hdr->HR.prohibit_caching)
768 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
769 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
771 ptr = ChrPtr(WCC->HBuf);
772 count = StrLength(WCC->HBuf);
777 client_write_ssl(WCC->HBuf);
778 client_write_ssl(WCC->WBuf);
783 if (WCC->Hdr->http_sock == -1)
785 fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
787 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
788 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
790 FD_SET(WCC->Hdr->http_sock, &wset);
791 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
792 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
797 if ((WCC->Hdr->http_sock == -1) ||
798 (res = write(WCC->Hdr->http_sock,
801 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
809 ptr = ChrPtr(WCC->WBuf);
810 count = StrLength(WCC->WBuf);
813 while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
814 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
816 FD_SET(WCC->Hdr->http_sock, &wset);
817 if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
818 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
823 if ((WCC->Hdr->http_sock == -1) ||
824 (res = write(WCC->Hdr->http_sock,
827 syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
835 return StrLength(WCC->WBuf);
840 * lingering_close() a`la Apache. see
841 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
843 int lingering_close(int fd)
848 struct timeval tv, start;
850 gettimeofday(&start, NULL);
856 gettimeofday(&tv, NULL);
857 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
858 tv.tv_usec = start.tv_usec - tv.tv_usec;
859 if (tv.tv_usec < 0) {
861 tv.tv_usec += 1000000;
865 i = select(fd + 1, &set, NULL, NULL, &tv);
866 } while (i == -1 && errno == EINTR);
871 i = read(fd, buf, sizeof buf);
872 } while (i != 0 && (i != -1 || errno == EINTR));
878 HttpNewModule_TCPSOCKETS
879 (ParsedHttpHdrs *httpreq)
882 httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
886 HttpDetachModule_TCPSOCKETS
887 (ParsedHttpHdrs *httpreq)
890 FlushStrBuf(httpreq->ReadBuf);
891 ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
895 HttpDestroyModule_TCPSOCKETS
896 (ParsedHttpHdrs *httpreq)
899 FreeStrBuf(&httpreq->ReadBuf);
904 SessionNewModule_TCPSOCKETS
907 sess->CLineBuf = NewStrBuf();
908 sess->MigrateReadLineBuf = NewStrBuf();
912 SessionDestroyModule_TCPSOCKETS
915 FreeStrBuf(&sess->CLineBuf);
916 FreeStrBuf(&sess->ReadBuf);
918 sess->ReadPos = NULL;
919 FreeStrBuf(&sess->MigrateReadLineBuf);
920 if (sess->serv_sock > 0) {
921 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
922 close(sess->serv_sock);
924 sess->serv_sock = -1;