6f32d66ef108ad36f24c4a843fff77a0f96280df
[citadel.git] / webcit / tcp_sockets.c
1 /*
2  * $Id$
3  *
4  * Copyright (c) 1987-2010 by the citadel.org team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /*
22  * Uncomment this to log all communications with the Citadel server
23 #define SERV_TRACE 1
24  */
25
26
27 #include "webcit.h"
28 #include "webserver.h"
29
30 extern int DisableGzip;
31 long MaxRead = -1; /* should we do READ scattered or all at once? */
32
33 /*
34  * register the timeout
35  */
36 RETSIGTYPE timeout(int signum)
37 {
38         lprintf(1, "Connection timed out; unable to reach citserver\n");
39         /* no exit here, since we need to server the connection unreachable thing. exit(3); */
40 }
41
42
43 /*
44  * Client side - connect to a unix domain socket
45  */
46 int uds_connectsock(char *sockpath)
47 {
48         struct sockaddr_un addr;
49         int s;
50
51         memset(&addr, 0, sizeof(addr));
52         addr.sun_family = AF_UNIX;
53         strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
54
55         s = socket(AF_UNIX, SOCK_STREAM, 0);
56         if (s < 0) {
57                 lprintf(1, "Can't create socket[%s]: %s\n", sockpath, strerror(errno));
58                 return(-1);
59         }
60
61         if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
62                 lprintf(1, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
63                 close(s);
64                 return(-1);
65         }
66
67         return s;
68 }
69
70
71 /*
72  * TCP client - connect to a host/port 
73  */
74 int tcp_connectsock(char *host, char *service)
75 {
76         struct in6_addr serveraddr;
77         struct addrinfo hints;
78         struct addrinfo *res = NULL;
79         struct addrinfo *ai = NULL;
80         int rc = (-1);
81         int s = (-1);
82
83         if ((host == NULL) || IsEmptyStr(host))
84                 return (-1);
85         if ((service == NULL) || IsEmptyStr(service))
86                 return (-1);
87
88         lprintf(9, "tcp_connectsock(%s,%s)\n", host, service);
89
90         memset(&hints, 0x00, sizeof(hints));
91         hints.ai_flags = AI_NUMERICSERV;
92         hints.ai_family = AF_UNSPEC;
93         hints.ai_socktype = SOCK_STREAM;
94
95         /*
96          * Handle numeric IPv4 and IPv6 addresses
97          */
98         rc = inet_pton(AF_INET, host, &serveraddr);
99         if (rc == 1) {                                          /* dotted quad */
100                 hints.ai_family = AF_INET;
101                 hints.ai_flags |= AI_NUMERICHOST;
102         } else {
103                 rc = inet_pton(AF_INET6, host, &serveraddr);
104                 if (rc == 1) {                                  /* IPv6 address */
105                         hints.ai_family = AF_INET6;
106                         hints.ai_flags |= AI_NUMERICHOST;
107                 }
108         }
109
110         /* Begin the connection process */
111
112         rc = getaddrinfo(host, service, &hints, &res);
113         if (rc != 0) {
114                 lprintf(1, "%s: %s\n", host, gai_strerror(rc));
115                 return(-1);
116         }
117
118         /*
119          * Try all available addresses until we connect to one or until we run out.
120          */
121         for (ai = res; ai != NULL; ai = ai->ai_next) {
122
123                 if (ai->ai_family == AF_INET) lprintf(9, "Trying IPv4\n");
124                 else if (ai->ai_family == AF_INET6) lprintf(9, "Trying IPv6\n");
125                 else lprintf(9, "This is going to fail.\n");
126
127                 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
128                 if (s < 0) {
129                         lprintf(1, "socket() failed: %s\n", strerror(errno));
130                         return(-1);
131                 }
132                 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
133                 if (rc >= 0) {
134                         return(s);
135                 }
136                 else {
137                         lprintf(1, "connect() failed: %s\n", strerror(errno));
138                         close(s);
139                 }
140         }
141
142         return(-1);
143 }
144
145
146 /*
147  *  input string from pipe
148  */
149 int serv_getln(char *strbuf, int bufsize)
150 {
151         wcsession *WCC = WC;
152         int len;
153
154         *strbuf = '\0';
155         StrBuf_ServGetln(WCC->MigrateReadLineBuf);
156         len = StrLength(WCC->MigrateReadLineBuf);
157         if (len > bufsize)
158                 len = bufsize - 1;
159         memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
160         FlushStrBuf(WCC->MigrateReadLineBuf);
161         strbuf[len] = '\0';
162 #ifdef SERV_TRACE
163         lprintf(9, "%3d<<<%s\n", WC->serv_sock, strbuf);
164 #endif
165         return len;
166 }
167
168
169 int StrBuf_ServGetln(StrBuf *buf)
170 {
171         wcsession *WCC = WC;
172         const char *ErrStr = NULL;
173         int rc;
174         
175         FlushStrBuf(buf);
176         rc = StrBufTCP_read_buffered_line_fast(buf, 
177                                                WCC->ReadBuf, 
178                                                &WCC->ReadPos, 
179                                                &WCC->serv_sock, 
180                                                5, 1, 
181                                                &ErrStr);
182         if (rc < 0)
183         {
184                 lprintf(1, "Server connection broken: %s\n",
185                         (ErrStr)?ErrStr:"");
186                 wc_backtrace();
187                 WCC->serv_sock = (-1);
188                 WCC->connected = 0;
189                 WCC->logged_in = 0;
190         }
191 #ifdef SERV_TRACE
192         else 
193         {
194                 long pos = 0;
195                 if (WCC->ReadPos != NULL)
196                         pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
197                 lprintf(9, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
198         }
199 #endif
200         return rc;
201 }
202
203 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
204 {
205         wcsession *WCC = WC;
206         const char *ErrStr;
207         int rc;
208         
209         rc = StrBufReadBLOBBuffered(buf, 
210                                     WCC->ReadBuf, 
211                                     &WCC->ReadPos,
212                                     &WCC->serv_sock, 
213                                     1, 
214                                     BlobSize, 
215                                     NNN_TERM,
216                                     &ErrStr);
217         if (rc < 0)
218         {
219                 lprintf(1, "Server connection broken: %s\n",
220                         (ErrStr)?ErrStr:"");
221                 wc_backtrace();
222                 WCC->serv_sock = (-1);
223                 WCC->connected = 0;
224                 WCC->logged_in = 0;
225         }
226 #ifdef SERV_TRACE
227         else
228                 lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
229 #endif
230
231         return rc;
232 }
233
234 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
235 {
236         wcsession *WCC = WC;
237         const char *ErrStr;
238         int rc;
239         
240         WCC->ReadPos = NULL;
241         rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
242         if (rc < 0)
243         {
244                 lprintf(1, "Server connection broken: %s\n",
245                         (ErrStr)?ErrStr:"");
246                 wc_backtrace();
247                 WCC->serv_sock = (-1);
248                 WCC->connected = 0;
249                 WCC->logged_in = 0;
250         }
251 #ifdef SERV_TRACE
252         else
253                 lprintf(9, "%3d<<<BLOB: %ld bytes\n", WC->serv_sock, StrLength(buf));
254 #endif
255
256         return rc;
257 }
258
259
260 void FlushReadBuf (void)
261 {
262         long len;
263         const char *pch;
264         const char *pche;
265         wcsession *WCC = WC;
266
267         len = StrLength(WCC->ReadBuf);
268         if ((len > 0) &&
269             (WCC->ReadPos != NULL) && 
270             (WCC->ReadPos != StrBufNOTNULL))
271                 
272         {
273                 pch = ChrPtr(WCC->ReadBuf);
274                 pche = pch + len;
275                 if (WCC->ReadPos != pche)
276                 {
277                         lprintf(1, "ERROR: somebody didn't eat his soup! Remaing Chars: %d [%s]\n", 
278                                 pche - WCC->ReadPos, pche);
279                         lprintf(1, 
280                                 "--------------------------------------------------------------------------------\n"
281                                 "Whole buf: [%s]\n"
282                                 "--------------------------------------------------------------------------------\n", 
283                                 pch);
284                         AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
285                 }
286         }
287
288         FlushStrBuf(WCC->ReadBuf);
289         WCC->ReadPos = NULL;
290
291
292 }
293
294
295 /*
296  *  send binary to server
297  *  buf the buffer to write to citadel server
298  *  nbytes how many bytes to send to citadel server
299  */
300 void serv_write(const char *buf, int nbytes)
301 {
302         wcsession *WCC = WC;
303         int bytes_written = 0;
304         int retval;
305
306         FlushReadBuf();
307         while (bytes_written < nbytes) {
308                 retval = write(WCC->serv_sock, &buf[bytes_written],
309                                nbytes - bytes_written);
310                 if (retval < 1) {
311                         const char *ErrStr = strerror(errno);
312                         lprintf(1, "Server connection broken: %s\n",
313                                 (ErrStr)?ErrStr:"");
314                         close(WCC->serv_sock);
315                         WCC->serv_sock = (-1);
316                         WCC->connected = 0;
317                         WCC->logged_in = 0;
318                         return;
319                 }
320                 bytes_written = bytes_written + retval;
321         }
322 }
323
324
325 /*
326  *  send line to server
327  *  string the line to send to the citadel server
328  */
329 void serv_puts(const char *string)
330 {
331 #ifdef SERV_TRACE
332         lprintf(9, "%3d>>>%s\n", WC->serv_sock, string);
333 #endif
334         FlushReadBuf();
335
336         serv_write(string, strlen(string));
337         serv_write("\n", 1);
338 }
339
340 /*
341  *  send line to server
342  *  string the line to send to the citadel server
343  */
344 void serv_putbuf(const StrBuf *string)
345 {
346 #ifdef SERV_TRACE
347         lprintf(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
348 #endif
349         FlushReadBuf();
350
351         serv_write(ChrPtr(string), StrLength(string));
352         serv_write("\n", 1);
353 }
354
355
356 /*
357  *  convenience function to send stuff to the server
358  *  format the formatstring
359  *  ... the entities to insert into format 
360  */
361 void serv_printf(const char *format,...)
362 {
363         va_list arg_ptr;
364         char buf[SIZ];
365         size_t len;
366
367         FlushReadBuf();
368
369         va_start(arg_ptr, format);
370         vsnprintf(buf, sizeof buf, format, arg_ptr);
371         va_end(arg_ptr);
372
373         len = strlen(buf);
374         buf[len++] = '\n';
375         buf[len] = '\0';
376         serv_write(buf, len);
377 #ifdef SERV_TRACE
378         lprintf(9, ">>>%s", buf);
379 #endif
380 }
381
382
383
384 /**
385  * Read binary data from server into memory using a series of
386  * server READ commands.
387  * \return the read content as StrBuf
388  */
389 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf) 
390 {
391         wcsession *WCC = WC;
392         size_t bytes = 0;
393         size_t thisblock = 0;
394         
395         if (Ret == NULL)
396             return -1;
397
398         if (MaxRead == -1)
399         {
400                 serv_printf("READ %d|"SIZE_T_FMT, 0, total_len);
401                 if (StrBuf_ServGetln(Buf) > 0)
402                 {
403                         long YetRead;
404                         const char *ErrStr;
405                         const char *pch;
406                         int rc;
407
408                         if (GetServerStatus(Buf, NULL) == 6)
409                         {
410                             StrBufCutLeft(Buf, 4);
411                             thisblock = StrTol(Buf);
412                             if (WCC->serv_sock==-1) {
413                                     FlushStrBuf(Ret); 
414                                     return -1; 
415                             }
416
417                             if (WCC->ReadPos != NULL) {
418                                     pch = ChrPtr(WCC->ReadBuf);
419
420                                     YetRead = WCC->ReadPos - pch;
421                                     if (YetRead > 0)
422                                     {
423                                             long StillThere;
424                                             
425                                             StillThere = StrLength(WCC->ReadBuf) - 
426                                                     YetRead;
427                                             
428                                             StrBufPlain(Ret, 
429                                                         WCC->ReadPos,
430                                                         StillThere);
431                                             total_len -= StillThere;
432                                     }
433                                     FlushStrBuf(WCC->ReadBuf);
434                                     WCC->ReadPos = NULL;
435                             } 
436                             if (total_len > 0)
437                             {
438                                     rc = StrBufReadBLOB(Ret, 
439                                                         &WCC->serv_sock, 
440                                                         1, 
441                                                         total_len,
442                                                         &ErrStr);
443                                     if (rc < 0)
444                                     {
445                                             lprintf(1, "Server connection broken: %s\n",
446                                                     (ErrStr)?ErrStr:"");
447                                             wc_backtrace();
448                                             WCC->serv_sock = (-1);
449                                             WCC->connected = 0;
450                                             WCC->logged_in = 0;
451                                             return rc;
452                                     }
453                                     else
454                                             return StrLength(Ret);
455                             }
456                             else 
457                                     return StrLength(Ret);
458                         }
459                 }
460                 else
461                         return -1;
462         }
463         else while ((WCC->serv_sock!=-1) &&
464                (bytes < total_len)) {
465                 thisblock = MaxRead;
466                 if ((total_len - bytes) < thisblock) {
467                         thisblock = total_len - bytes;
468                         if (thisblock == 0) {
469                                 FlushStrBuf(Ret); 
470                                 return -1; 
471                         }
472                 }
473                 serv_printf("READ %d|%d", (int)bytes, (int)thisblock);
474                 if (StrBuf_ServGetln(Buf) > 0)
475                 {
476                         if (GetServerStatus(Buf, NULL) == 6)
477                         {
478                             StrBufCutLeft(Buf, 4);
479                             thisblock = StrTol(Buf);
480                             if (WCC->serv_sock==-1) {
481                                     FlushStrBuf(Ret); 
482                                     return -1; 
483                             }
484                             StrBuf_ServGetBLOBBuffered(Ret, thisblock);
485                             bytes += thisblock;
486                     }
487                     else {
488                             lprintf(3, "Error: %s\n", ChrPtr(Buf) + 4);
489                             return -1;
490                     }
491                 }
492         }
493         return StrLength(Ret);
494 }
495
496
497 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
498 {
499         const char *Error;
500 #ifdef HAVE_OPENSSL
501         const char *pch, *pchs;
502         int rlen, len, retval = 0;
503
504         if (is_https) {
505                 int ntries = 0;
506                 if (StrLength(Hdr->ReadBuf) > 0) {
507                         pchs = ChrPtr(Hdr->ReadBuf);
508                         pch = strchr(pchs, '\n');
509                         if (pch != NULL) {
510                                 rlen = 0;
511                                 len = pch - pchs;
512                                 if (len > 0 && (*(pch - 1) == '\r') )
513                                         rlen ++;
514                                 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
515                                 StrBufCutLeft(Hdr->ReadBuf, len + 1);
516                                 return len - rlen;
517                         }
518                 }
519
520                 while (retval == 0) { 
521                                 pch = NULL;
522                                 pchs = ChrPtr(Hdr->ReadBuf);
523                                 if (*pchs != '\0')
524                                         pch = strchr(pchs, '\n');
525                                 if (pch == NULL) {
526                                         retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
527                                         pchs = ChrPtr(Hdr->ReadBuf);
528                                         pch = strchr(pchs, '\n');
529                                 }
530                                 if (retval == 0) {
531                                         sleeeeeeeeeep(1);
532                                         ntries ++;
533                                 }
534                                 if (ntries > 10)
535                                         return 0;
536                 }
537                 if ((retval > 0) && (pch != NULL)) {
538                         rlen = 0;
539                         len = pch - pchs;
540                         if (len > 0 && (*(pch - 1) == '\r') )
541                                 rlen ++;
542                         StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
543                         StrBufCutLeft(Hdr->ReadBuf, len + 1);
544                         return len - rlen;
545
546                 }
547                 else 
548                         return -1;
549         }
550         else 
551 #endif
552                 return StrBufTCP_read_buffered_line_fast(Target, 
553                                                          Hdr->ReadBuf,
554                                                          &Hdr->Pos,
555                                                          &Hdr->http_sock,
556                                                          5,
557                                                          1,
558                                                          &Error);
559 }
560
561
562 /* 
563  * This is a generic function to set up a master socket for listening on
564  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
565  *
566  * ip_addr      IP address to bind
567  * port_number  port number to bind
568  * queue_len    number of incoming connections to allow in the queue
569  */
570 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
571 {
572         struct protoent *p;
573         struct sockaddr_in6 sin6;
574         struct sockaddr_in sin4;
575         int s, i, b;
576         int ip_version = 6;
577
578         memset(&sin6, 0, sizeof(sin6));
579         memset(&sin4, 0, sizeof(sin4));
580         sin6.sin6_family = AF_INET6;
581         sin4.sin_family = AF_INET;
582
583         if (    (ip_addr == NULL)                                                       /* any IPv6 */
584                 || (IsEmptyStr(ip_addr))
585                 || (!strcmp(ip_addr, "*"))
586         ) {
587                 ip_version = 6;
588                 sin6.sin6_addr = in6addr_any;
589         }
590         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
591         {
592                 ip_version = 4;
593                 sin4.sin_addr.s_addr = INADDR_ANY;
594         }
595         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
596         {
597                 ip_version = 4;
598                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
599                         lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
600                         return (-WC_EXIT_BIND);
601                 }
602         }
603         else                                                                            /* specific IPv6 */
604         {
605                 ip_version = 6;
606                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
607                         lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
608                         return (-WC_EXIT_BIND);
609                 }
610         }
611
612         if (port_number == 0) {
613                 lprintf(1, "Cannot start: no port number specified.\n");
614                 return (-WC_EXIT_BIND);
615         }
616         sin6.sin6_port = htons((u_short) port_number);
617         sin4.sin_port = htons((u_short) port_number);
618
619         p = getprotobyname("tcp");
620
621         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
622         if (s < 0) {
623                 lprintf(1, "Can't create a listening socket: %s\n", strerror(errno));
624                 return (-WC_EXIT_BIND);
625         }
626         /* Set some socket options that make sense. */
627         i = 1;
628         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
629
630         if (ip_version == 6) {
631                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
632         }
633         else {
634                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
635         }
636
637         if (b < 0) {
638                 lprintf(1, "Can't bind: %s\n", strerror(errno));
639                 return (-WC_EXIT_BIND);
640         }
641
642         if (listen(s, queue_len) < 0) {
643                 lprintf(1, "Can't listen: %s\n", strerror(errno));
644                 return (-WC_EXIT_BIND);
645         }
646         return (s);
647 }
648
649
650 /*
651  * Create a Unix domain socket and listen on it
652  * sockpath - file name of the unix domain socket
653  * queue_len - Number of incoming connections to allow in the queue
654  */
655 int webcit_uds_server(char *sockpath, int queue_len)
656 {
657         struct sockaddr_un addr;
658         int s;
659         int i;
660         int actual_queue_len;
661
662         actual_queue_len = queue_len;
663         if (actual_queue_len < 5) actual_queue_len = 5;
664
665         i = unlink(sockpath);
666         if ((i != 0) && (errno != ENOENT)) {
667                 lprintf(1, "webcit: can't unlink %s: %s\n",
668                         sockpath, strerror(errno));
669                 return (-WC_EXIT_BIND);
670         }
671
672         memset(&addr, 0, sizeof(addr));
673         addr.sun_family = AF_UNIX;
674         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
675
676         s = socket(AF_UNIX, SOCK_STREAM, 0);
677         if (s < 0) {
678                 lprintf(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
679                 return (-WC_EXIT_BIND);
680         }
681
682         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
683                 lprintf(1, "webcit: Can't bind: %s\n",
684                         strerror(errno));
685                 return (-WC_EXIT_BIND);
686         }
687
688         if (listen(s, actual_queue_len) < 0) {
689                 lprintf(1, "webcit: Can't listen: %s\n",
690                         strerror(errno));
691                 return (-WC_EXIT_BIND);
692         }
693
694         chmod(sockpath, 0777);
695         return(s);
696 }
697
698
699
700
701 /*
702  * Read data from the client socket.
703  *
704  * sock         socket fd to read from
705  * buf          buffer to read into 
706  * bytes        number of bytes to read
707  * timeout      Number of seconds to wait before timing out
708  *
709  * Possible return values:
710  *      1       Requested number of bytes has been read.
711  *      0       Request timed out.
712  *      -1      Connection is broken, or other error.
713  */
714 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
715 {
716         const char *Error;
717         int retval = 0;
718
719 #ifdef HAVE_OPENSSL
720         if (is_https) {
721                 long bufremain;
722                 long baselen;
723
724                 baselen = StrLength(Target);
725
726                 if (Hdr->Pos == NULL)
727                         Hdr->Pos = ChrPtr(Hdr->ReadBuf);
728                 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
729
730                 if (bytes < bufremain)
731                         bufremain = bytes;
732                 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
733                 StrBufCutLeft(Hdr->ReadBuf, bufremain);
734
735                 if (bytes > bufremain) 
736                 {
737                         while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
738                                (retval >= 0))
739                                 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
740                         if (retval >= 0) {
741                                 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
742 #ifdef HTTP_TRACING
743                                 write(2, "\033[32m", 5);
744                                 write(2, buf, bytes);
745                                 write(2, "\033[30m", 5);
746 #endif
747                                 return 1;
748                         }
749                         else {
750                                 lprintf(2, "client_read_ssl() failed\n");
751                                 return -1;
752                         }
753                 }
754                 else 
755                         return 1;
756         }
757 #endif
758
759         retval = StrBufReadBLOBBuffered(Target, 
760                                         Hdr->ReadBuf, 
761                                         &Hdr->Pos, 
762                                         &Hdr->http_sock, 
763                                         1, 
764                                         bytes,
765                                         O_TERM,
766                                         &Error);
767         if (retval < 0) {
768                 lprintf(2, "client_read() failed: %s\n",
769                         Error);
770                 wc_backtrace();
771                 return retval;
772         }
773
774 #ifdef HTTP_TRACING
775         write(2, "\033[32m", 5);
776         write(2, buf, bytes);
777         write(2, "\033[30m", 5);
778 #endif
779         return 1;
780 }
781
782
783 /*
784  * Begin buffering HTTP output so we can transmit it all in one write operation later.
785  */
786 void begin_burst(void)
787 {
788         if (WC->WBuf == NULL) {
789                 WC->WBuf = NewStrBufPlain(NULL, 32768);
790         }
791 }
792
793
794 /*
795  * Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
796  */
797 long end_burst(void)
798 {
799         wcsession *WCC = WC;
800         const char *ptr, *eptr;
801         long count;
802         ssize_t res = 0;
803         fd_set wset;
804         int fdflags;
805
806         if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
807         {
808                 if (CompressBuffer(WCC->WBuf) > 0)
809                         hprintf("Content-encoding: gzip\r\n");
810                 else {
811                         lprintf(CTDL_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
812                         wc_backtrace();
813                 }
814         }
815
816         if (WCC->WFBuf != NULL) {
817                 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
818                 FreeStrBuf(&WCC->WFBuf);
819         }
820
821         if (WCC->Hdr->HR.prohibit_caching)
822                 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
823         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
824
825         ptr = ChrPtr(WCC->HBuf);
826         count = StrLength(WCC->HBuf);
827         eptr = ptr + count;
828
829 #ifdef HAVE_OPENSSL
830         if (is_https) {
831                 client_write_ssl(WCC->HBuf);
832                 client_write_ssl(WCC->WBuf);
833                 return (count);
834         }
835 #endif
836
837         
838 #ifdef HTTP_TRACING
839         
840         write(2, "\033[34m", 5);
841         write(2, ptr, StrLength(WCC->WBuf));
842         write(2, "\033[30m", 5);
843 #endif
844         if (WCC->Hdr->http_sock == -1)
845                 return -1;
846         fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
847
848         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
849                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
850                         FD_ZERO(&wset);
851                         FD_SET(WCC->Hdr->http_sock, &wset);
852                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
853                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
854                                 return -1;
855                         }
856                 }
857
858                 if ((WCC->Hdr->http_sock == -1) || 
859                     (res = write(WCC->Hdr->http_sock, 
860                                  ptr,
861                                  count)) == -1) {
862                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
863                         wc_backtrace();
864                         return res;
865                 }
866                 count -= res;
867                 ptr += res;
868         }
869
870         ptr = ChrPtr(WCC->WBuf);
871         count = StrLength(WCC->WBuf);
872         eptr = ptr + count;
873
874 #ifdef HTTP_TRACING
875         
876         write(2, "\033[34m", 5);
877         write(2, ptr, StrLength(WCC->WBuf));
878         write(2, "\033[30m", 5);
879 #endif
880
881         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
882                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
883                         FD_ZERO(&wset);
884                         FD_SET(WCC->Hdr->http_sock, &wset);
885                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
886                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
887                                 return -1;
888                         }
889                 }
890
891                 if ((WCC->Hdr->http_sock == -1) || 
892                     (res = write(WCC->Hdr->http_sock, 
893                                  ptr,
894                                  count)) == -1) {
895                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
896                         wc_backtrace();
897                         return res;
898                 }
899                 count -= res;
900                 ptr += res;
901         }
902
903         return StrLength(WCC->WBuf);
904 }
905
906
907 /*
908  * lingering_close() a`la Apache. see
909  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
910  */
911 int lingering_close(int fd)
912 {
913         char buf[SIZ];
914         int i;
915         fd_set set;
916         struct timeval tv, start;
917
918         gettimeofday(&start, NULL);
919         if (fd == -1)
920                 return -1;
921         shutdown(fd, 1);
922         do {
923                 do {
924                         gettimeofday(&tv, NULL);
925                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
926                         tv.tv_usec = start.tv_usec - tv.tv_usec;
927                         if (tv.tv_usec < 0) {
928                                 tv.tv_sec--;
929                                 tv.tv_usec += 1000000;
930                         }
931                         FD_ZERO(&set);
932                         FD_SET(fd, &set);
933                         i = select(fd + 1, &set, NULL, NULL, &tv);
934                 } while (i == -1 && errno == EINTR);
935
936                 if (i <= 0)
937                         break;
938
939                 i = read(fd, buf, sizeof buf);
940         } while (i != 0 && (i != -1 || errno == EINTR));
941
942         return close(fd);
943 }
944
945 void
946 HttpNewModule_TCPSOCKETS
947 (ParsedHttpHdrs *httpreq)
948 {
949
950         httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
951 }
952
953 void
954 HttpDetachModule_TCPSOCKETS
955 (ParsedHttpHdrs *httpreq)
956 {
957
958         FlushStrBuf(httpreq->ReadBuf);
959         ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
960 }
961
962 void
963 HttpDestroyModule_TCPSOCKETS
964 (ParsedHttpHdrs *httpreq)
965 {
966
967         FreeStrBuf(&httpreq->ReadBuf);
968 }
969
970
971 void
972 SessionNewModule_TCPSOCKETS
973 (wcsession *sess)
974 {
975         sess->CLineBuf = NewStrBuf();
976         sess->MigrateReadLineBuf = NewStrBuf();
977 }
978
979 void 
980 SessionDestroyModule_TCPSOCKETS
981 (wcsession *sess)
982 {
983         FreeStrBuf(&sess->CLineBuf);
984         FreeStrBuf(&sess->ReadBuf);
985         sess->ReadPos = NULL;
986         FreeStrBuf(&sess->MigrateReadLineBuf);
987         if (sess->serv_sock > 0)
988                 close(sess->serv_sock);
989 }