* Change to main server loop. All threads block on accept() instead of using a mutex...
[citadel.git] / webcit / tcp_sockets.c
index b4fc2a84a5d8b6b99bbca15234b9c261758d3110..b4197e5d925d7dfc5e9d70ea563e6e3e97224936 100644 (file)
@@ -1,5 +1,21 @@
 /*
  * $Id$
+ *
+ * Copyright (c) 1987-2010 by the citadel.org team
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
 /*
@@ -12,6 +28,7 @@
 #include "webserver.h"
 
 extern int DisableGzip;
+long MaxRead = -1; /* should we do READ scattered or all at once? */
 
 /*
  * register the timeout
@@ -120,15 +137,16 @@ int tcp_connectsock(char *host, char *service)
        }
        alarm(0);
        signal(SIGALRM, SIG_IGN);
-
-       fdflags = fcntl(s, F_GETFL);
-       if (fdflags < 0)
-               lprintf(1, "unable to get socket flags!  %s.%s: %s \n",
-                       host, service, strerror(errno));
-       fdflags = fdflags | O_NONBLOCK;
-       if (fcntl(s, F_SETFD, fdflags) < 0)
-               lprintf(1, "unable to set socket nonblocking flags!  %s.%s: %s \n",
-                       host, service, strerror(errno));
+       if (!is_https) {
+               fdflags = fcntl(s, F_GETFL);
+               if (fdflags < 0)
+                       lprintf(1, "unable to get socket flags!  %s.%s: %s \n",
+                               host, service, strerror(errno));
+               fdflags = fdflags | O_NONBLOCK;
+               if (fcntl(s, F_SETFD, fdflags) < 0)
+                       lprintf(1, "unable to set socket nonblocking flags!  %s.%s: %s \n",
+                               host, service, strerror(errno));
+       }
        return (s);
 }
 
@@ -151,7 +169,7 @@ int serv_getln(char *strbuf, int bufsize)
        FlushStrBuf(WCC->MigrateReadLineBuf);
        strbuf[len] = '\0';
 #ifdef SERV_TRACE
-       lprintf(9, "%3d>%s\n", WC->serv_sock, strbuf);
+       lprintf(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
 #endif
        return len;
 }
@@ -162,7 +180,8 @@ int StrBuf_ServGetln(StrBuf *buf)
        wcsession *WCC = WC;
        const char *ErrStr = NULL;
        int rc;
-
+       
+       FlushStrBuf(buf);
        rc = StrBufTCP_read_buffered_line_fast(buf, 
                                               WCC->ReadBuf, 
                                               &WCC->ReadPos, 
@@ -172,19 +191,28 @@ int StrBuf_ServGetln(StrBuf *buf)
        if (rc < 0)
        {
                lprintf(1, "Server connection broken: %s\n",
-                       ErrStr);
+                       (ErrStr)?ErrStr:"");
                wc_backtrace();
                WCC->serv_sock = (-1);
                WCC->connected = 0;
                WCC->logged_in = 0;
        }
+#ifdef SERV_TRACE
+       else 
+       {
+               long pos=0;
+               if (WCC->ReadPos != NULL)
+                       pos = WCC->ReadPos - ChrPtr(buf);
+               lprintf(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
+       }
+#endif
        return rc;
 }
 
 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
 {
        wcsession *WCC = WC;
-       const char *Err;
+       const char *ErrStr;
        int rc;
        
        rc = StrBufReadBLOBBuffered(buf, 
@@ -194,36 +222,46 @@ int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
                                    1, 
                                    BlobSize, 
                                    NNN_TERM,
-                                   &Err);
+                                   &ErrStr);
        if (rc < 0)
        {
                lprintf(1, "Server connection broken: %s\n",
-                       Err);
+                       (ErrStr)?ErrStr:"");
                wc_backtrace();
                WCC->serv_sock = (-1);
                WCC->connected = 0;
                WCC->logged_in = 0;
        }
+#ifdef SERV_TRACE
+        else
+                lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
+#endif
+
        return rc;
 }
 
 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
 {
        wcsession *WCC = WC;
-       const char *Err;
+       const char *ErrStr;
        int rc;
        
        WCC->ReadPos = NULL;
-       rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &Err);
+       rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
        if (rc < 0)
        {
                lprintf(1, "Server connection broken: %s\n",
-                       Err);
+                       (ErrStr)?ErrStr:"");
                wc_backtrace();
                WCC->serv_sock = (-1);
                WCC->connected = 0;
                WCC->logged_in = 0;
        }
+#ifdef SERV_TRACE
+        else
+                lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
+#endif
+
        return rc;
 }
 
@@ -244,8 +282,9 @@ void serv_write(const char *buf, int nbytes)
                retval = write(WCC->serv_sock, &buf[bytes_written],
                               nbytes - bytes_written);
                if (retval < 1) {
+                       const char *ErrStr = strerror(errno);
                        lprintf(1, "Server connection broken: %s\n",
-                               strerror(errno));
+                               (ErrStr)?ErrStr:"");
                        close(WCC->serv_sock);
                        WCC->serv_sock = (-1);
                        WCC->connected = 0;
@@ -265,7 +304,7 @@ void serv_puts(const char *string)
 {
        wcsession *WCC = WC;
 #ifdef SERV_TRACE
-       lprintf(9, "%3d<%s\n", WC->serv_sock, string);
+       lprintf(9, "%3d>>>%s\n", WC->serv_sock, string);
 #endif
        FlushStrBuf(WCC->ReadBuf);
        WCC->ReadPos = NULL;
@@ -282,7 +321,7 @@ void serv_putbuf(const StrBuf *string)
 {
        wcsession *WCC = WC;
 #ifdef SERV_TRACE
-       lprintf(9, "%3d<%s\n", WC->serv_sock, ChrPtr(string));
+       lprintf(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
 #endif
        FlushStrBuf(WCC->ReadBuf);
        WCC->ReadPos = NULL;
@@ -316,19 +355,132 @@ void serv_printf(const char *format,...)
        buf[len] = '\0';
        serv_write(buf, len);
 #ifdef SERV_TRACE
-       lprintf(9, "<%s", buf);
+       lprintf(9, ">>>%s", buf);
 #endif
 }
 
 
 
+/**
+ * Read binary data from server into memory using a series of
+ * server READ commands.
+ * \return the read content as StrBuf
+ */
+int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf) 
+{
+       wcsession *WCC = WC;
+       size_t bytes = 0;
+       size_t thisblock = 0;
+       
+       if (Ret == NULL)
+           return -1;
+
+       if (MaxRead == -1)
+       {
+               serv_printf("READ %d|%d", 0, total_len);
+               if (StrBuf_ServGetln(Buf) > 0)
+               {
+                       long YetRead;
+                       const char *ErrStr;
+                       const char *pch;
+                       int rc;
+
+                       if (GetServerStatus(Buf, NULL) == 6)
+                       {
+                           StrBufCutLeft(Buf, 4);
+                           thisblock = StrTol(Buf);
+                           if (WCC->serv_sock==-1) {
+                                   FlushStrBuf(Ret); 
+                                   return -1; 
+                           }
+
+                           if (WCC->ReadPos != NULL) {
+                                   pch = ChrPtr(WCC->ReadBuf);
+
+                                   YetRead = WCC->ReadPos - pch;
+                                   if (YetRead > 0)
+                                   {
+                                           long StillThere;
+                                           
+                                           StillThere = StrLength(WCC->ReadBuf) - 
+                                                   YetRead;
+                                           
+                                           StrBufPlain(Ret, 
+                                                       WCC->ReadPos,
+                                                       StillThere);
+                                           total_len -= StillThere;
+                                   }
+                                   FlushStrBuf(WCC->ReadBuf);
+                                   WCC->ReadPos = NULL;
+                           } 
+                           if (total_len > 0)
+                           {
+                                   rc = StrBufReadBLOB(Ret, 
+                                                       &WCC->serv_sock, 
+                                                       1, 
+                                                       total_len,
+                                                       &ErrStr);
+                                   if (rc < 0)
+                                   {
+                                           lprintf(1, "Server connection broken: %s\n",
+                                                   (ErrStr)?ErrStr:"");
+                                           wc_backtrace();
+                                           WCC->serv_sock = (-1);
+                                           WCC->connected = 0;
+                                           WCC->logged_in = 0;
+                                           return rc;
+                                   }
+                                   else
+                                           return StrLength(Ret);
+                           }
+                           else 
+                                   return StrLength(Ret);
+                       }
+               }
+               else
+                       return -1;
+       }
+       else while ((WCC->serv_sock!=-1) &&
+              (bytes < total_len)) {
+               thisblock = MaxRead;
+               if ((total_len - bytes) < thisblock) {
+                       thisblock = total_len - bytes;
+                       if (thisblock == 0) {
+                               FlushStrBuf(Ret); 
+                               return -1; 
+                       }
+               }
+               serv_printf("READ %d|%d", (int)bytes, (int)thisblock);
+               if (StrBuf_ServGetln(Buf) > 0)
+               {
+                       if (GetServerStatus(Buf, NULL) == 6)
+                       {
+                           StrBufCutLeft(Buf, 4);
+                           thisblock = StrTol(Buf);
+                           if (WCC->serv_sock==-1) {
+                                   FlushStrBuf(Ret); 
+                                   return -1; 
+                           }
+                           StrBuf_ServGetBLOBBuffered(Ret, thisblock);
+                           bytes += thisblock;
+                   }
+                   else {
+                           lprintf(3, "Error: %s\n", ChrPtr(Buf) + 4);
+                           return -1;
+                   }
+               }
+       }
+       return StrLength(Ret);
+}
+
 
 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
 {
-       const char *Error, *pch, *pchs;
+       const char *Error;
+#ifdef HAVE_OPENSSL
+       const char *pch, *pchs;
        int rlen, len, retval = 0;
 
-#ifdef HAVE_OPENSSL
        if (is_https) {
                int ntries = 0;
                if (StrLength(Hdr->ReadBuf) > 0) {
@@ -386,6 +538,78 @@ int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
                                                         &Error);
 }
 
+#ifdef CTDL_IPV6
+
+/* 
+ * This is a generic function to set up a master socket for listening on
+ * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
+ *
+ * ip_addr     IP address to bind
+ * port_number port number to bind
+ * queue_len   number of incoming connections to allow in the queue
+ */
+int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
+{
+       struct protoent *p;
+       struct sockaddr_in6 sin;
+       int s, i;
+
+       memset(&sin, 0, sizeof(sin));
+       sin.sin6_family = AF_INET6;
+
+       if ((ip_addr == NULL) || (IsEmptyStr(ip_addr)) || (!strcmp(ip_addr, "0.0.0.0"))) {
+               sin.sin6_addr = in6addr_any;
+       } else {
+               char bind_to[256];
+               if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':'))) {
+                       snprintf(bind_to, sizeof bind_to, "::ffff:%s", ip_addr);
+               }
+               else {
+                       safestrncpy(bind_to, ip_addr, sizeof bind_to);
+               }
+               if (inet_pton(AF_INET6, bind_to, &sin.sin6_addr) <= 0) {
+                       lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
+                       return (-WC_EXIT_BIND);
+               }
+       }
+
+       if (port_number == 0) {
+               lprintf(1, "Cannot start: no port number specified.\n");
+               return (-WC_EXIT_BIND);
+       }
+       sin.sin6_port = htons((u_short) port_number);
+
+       p = getprotobyname("tcp");
+
+       s = socket(PF_INET6, SOCK_STREAM, (p->p_proto));
+       if (s < 0) {
+               lprintf(1, "Can't create an IPv6 socket: %s\n", strerror(errno));
+               return (-WC_EXIT_BIND);
+       }
+       /* Set some socket options that make sense. */
+       i = 1;
+       setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
+
+       #ifndef __APPLE__
+       fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
+                                         there should be a preceding F_GETFL
+                                         and a bitwise OR with the previous
+                                         fd flags */
+       #endif
+       
+       if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
+               lprintf(1, "Can't bind: %s\n", strerror(errno));
+               return (-WC_EXIT_BIND);
+       }
+       if (listen(s, queue_len) < 0) {
+               lprintf(1, "Can't listen: %s\n", strerror(errno));
+               return (-WC_EXIT_BIND);
+       }
+       return (s);
+}
+
+#else /* CTDL_IPV6 */
+
 /* 
  * This is a generic function to set up a master socket for listening on
  * a TCP port.  The server shuts down if the bind fails.
@@ -414,7 +638,7 @@ int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
 
        if (port_number == 0) {
                lprintf(1, "Cannot start: no port number specified.\n");
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
        sin.sin_port = htons((u_short) port_number);
 
@@ -422,31 +646,25 @@ int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
 
        s = socket(PF_INET, SOCK_STREAM, (p->p_proto));
        if (s < 0) {
-               lprintf(1, "Can't create a socket: %s\n", strerror(errno));
-               exit(WC_EXIT_BIND);
+               lprintf(1, "Can't create an IPv4 socket: %s\n", strerror(errno));
+               return (-WC_EXIT_BIND);
        }
        /* Set some socket options that make sense. */
        i = 1;
        setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
 
-       #ifndef __APPLE__
-       fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
-                                         there should be a preceding F_GETFL
-                                         and a bitwise OR with the previous
-                                         fd flags */
-       #endif
-       
        if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
                lprintf(1, "Can't bind: %s\n", strerror(errno));
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
        if (listen(s, queue_len) < 0) {
                lprintf(1, "Can't listen: %s\n", strerror(errno));
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
        return (s);
 }
 
+#endif /* CTDL_IPV6 */
 
 
 /*
@@ -468,7 +686,7 @@ int ig_uds_server(char *sockpath, int queue_len)
        if ((i != 0) && (errno != ENOENT)) {
                lprintf(1, "webcit: can't unlink %s: %s\n",
                        sockpath, strerror(errno));
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
 
        memset(&addr, 0, sizeof(addr));
@@ -477,21 +695,20 @@ int ig_uds_server(char *sockpath, int queue_len)
 
        s = socket(AF_UNIX, SOCK_STREAM, 0);
        if (s < 0) {
-               lprintf(1, "webcit: Can't create a socket: %s\n",
-                       strerror(errno));
-               exit(WC_EXIT_BIND);
+               lprintf(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
+               return (-WC_EXIT_BIND);
        }
 
        if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
                lprintf(1, "webcit: Can't bind: %s\n",
                        strerror(errno));
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
 
        if (listen(s, actual_queue_len) < 0) {
                lprintf(1, "webcit: Can't listen: %s\n",
                        strerror(errno));
-               exit(WC_EXIT_BIND);
+               return (-WC_EXIT_BIND);
        }
 
        chmod(sockpath, 0777);
@@ -522,6 +739,9 @@ int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
 #ifdef HAVE_OPENSSL
        if (is_https) {
                long bufremain;
+               long baselen;
+
+               baselen = StrLength(Target);
 
                if (Hdr->Pos == NULL)
                        Hdr->Pos = ChrPtr(Hdr->ReadBuf);
@@ -534,7 +754,7 @@ int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
 
                if (bytes > bufremain) 
                {
-                       while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes) &&
+                       while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
                               (retval >= 0))
                                retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
                        if (retval >= 0) {
@@ -567,6 +787,7 @@ int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
        if (retval < 0) {
                lprintf(2, "client_read() failed: %s\n",
                        Error);
+               wc_backtrace();
                return retval;
        }
 
@@ -598,13 +819,23 @@ long end_burst(void)
        wcsession *WCC = WC;
         const char *ptr, *eptr;
         long count;
-       ssize_t res;
+       ssize_t res = 0;
         fd_set wset;
         int fdflags;
 
-       if (!DisableGzip && (WCC->Hdr->HR.gzip_ok) && CompressBuffer(WCC->WBuf))
+       if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
        {
-               hprintf("Content-encoding: gzip\r\n");
+               if (CompressBuffer(WCC->WBuf) > 0)
+                       hprintf("Content-encoding: gzip\r\n");
+               else {
+                       lprintf(CTDL_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
+                       wc_backtrace();
+               }
+       }
+
+       if (WCC->WFBuf != NULL) {
+               WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
+               FreeStrBuf(&WCC->WFBuf);
        }
 
        if (WCC->Hdr->HR.prohibit_caching)
@@ -630,9 +861,11 @@ long end_burst(void)
        write(2, ptr, StrLength(WCC->WBuf));
        write(2, "\033[30m", 5);
 #endif
+       if (WCC->Hdr->http_sock == -1)
+               return -1;
        fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
 
-       while (ptr < eptr) {
+       while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
                         FD_ZERO(&wset);
                         FD_SET(WCC->Hdr->http_sock, &wset);
@@ -642,7 +875,8 @@ long end_burst(void)
                         }
                 }
 
-                if ((res = write(WCC->Hdr->http_sock, 
+                if ((WCC->Hdr->http_sock == -1) || 
+                   (res = write(WCC->Hdr->http_sock, 
                                 ptr,
                                 count)) == -1) {
                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
@@ -664,7 +898,7 @@ long end_burst(void)
        write(2, "\033[30m", 5);
 #endif
 
-        while (ptr < eptr) {
+        while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
                         FD_ZERO(&wset);
                         FD_SET(WCC->Hdr->http_sock, &wset);
@@ -674,7 +908,8 @@ long end_burst(void)
                         }
                 }
 
-                if ((res = write(WCC->Hdr->http_sock, 
+                if ((WCC->Hdr->http_sock == -1) || 
+                   (res = write(WCC->Hdr->http_sock, 
                                 ptr,
                                 count)) == -1) {
                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
@@ -701,6 +936,8 @@ int lingering_close(int fd)
        struct timeval tv, start;
 
        gettimeofday(&start, NULL);
+       if (fd == -1)
+               return -1;
        shutdown(fd, 1);
        do {
                do {
@@ -765,6 +1002,7 @@ SessionDestroyModule_TCPSOCKETS
 {
        FreeStrBuf(&sess->CLineBuf);
        FreeStrBuf(&sess->ReadBuf);
+       sess->ReadPos = NULL;
        FreeStrBuf(&sess->MigrateReadLineBuf);
        if (sess->serv_sock > 0)
                close(sess->serv_sock);