* Fixed bug in webcit-to-citadel IPv6/IPv4 connectivity
[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(buf);
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  *  send binary to server
261  *  buf the buffer to write to citadel server
262  *  nbytes how many bytes to send to citadel server
263  */
264 void serv_write(const char *buf, int nbytes)
265 {
266         wcsession *WCC = WC;
267         int bytes_written = 0;
268         int retval;
269
270         FlushStrBuf(WCC->ReadBuf);
271         WCC->ReadPos = NULL;
272         while (bytes_written < nbytes) {
273                 retval = write(WCC->serv_sock, &buf[bytes_written],
274                                nbytes - bytes_written);
275                 if (retval < 1) {
276                         const char *ErrStr = strerror(errno);
277                         lprintf(1, "Server connection broken: %s\n",
278                                 (ErrStr)?ErrStr:"");
279                         close(WCC->serv_sock);
280                         WCC->serv_sock = (-1);
281                         WCC->connected = 0;
282                         WCC->logged_in = 0;
283                         return;
284                 }
285                 bytes_written = bytes_written + retval;
286         }
287 }
288
289
290 /*
291  *  send line to server
292  *  string the line to send to the citadel server
293  */
294 void serv_puts(const char *string)
295 {
296         wcsession *WCC = WC;
297 #ifdef SERV_TRACE
298         lprintf(9, "%3d>>>%s\n", WC->serv_sock, string);
299 #endif
300         FlushStrBuf(WCC->ReadBuf);
301         WCC->ReadPos = NULL;
302
303         serv_write(string, strlen(string));
304         serv_write("\n", 1);
305 }
306
307 /*
308  *  send line to server
309  *  string the line to send to the citadel server
310  */
311 void serv_putbuf(const StrBuf *string)
312 {
313         wcsession *WCC = WC;
314 #ifdef SERV_TRACE
315         lprintf(9, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
316 #endif
317         FlushStrBuf(WCC->ReadBuf);
318         WCC->ReadPos = NULL;
319
320         serv_write(ChrPtr(string), StrLength(string));
321         serv_write("\n", 1);
322 }
323
324
325 /*
326  *  convenience function to send stuff to the server
327  *  format the formatstring
328  *  ... the entities to insert into format 
329  */
330 void serv_printf(const char *format,...)
331 {
332         wcsession *WCC = WC;
333         va_list arg_ptr;
334         char buf[SIZ];
335         size_t len;
336
337         FlushStrBuf(WCC->ReadBuf);
338         WCC->ReadPos = NULL;
339
340         va_start(arg_ptr, format);
341         vsnprintf(buf, sizeof buf, format, arg_ptr);
342         va_end(arg_ptr);
343
344         len = strlen(buf);
345         buf[len++] = '\n';
346         buf[len] = '\0';
347         serv_write(buf, len);
348 #ifdef SERV_TRACE
349         lprintf(9, ">>>%s", buf);
350 #endif
351 }
352
353
354
355 /**
356  * Read binary data from server into memory using a series of
357  * server READ commands.
358  * \return the read content as StrBuf
359  */
360 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf) 
361 {
362         wcsession *WCC = WC;
363         size_t bytes = 0;
364         size_t thisblock = 0;
365         
366         if (Ret == NULL)
367             return -1;
368
369         if (MaxRead == -1)
370         {
371                 serv_printf("READ %d|"SIZE_T_FMT, 0, total_len);
372                 if (StrBuf_ServGetln(Buf) > 0)
373                 {
374                         long YetRead;
375                         const char *ErrStr;
376                         const char *pch;
377                         int rc;
378
379                         if (GetServerStatus(Buf, NULL) == 6)
380                         {
381                             StrBufCutLeft(Buf, 4);
382                             thisblock = StrTol(Buf);
383                             if (WCC->serv_sock==-1) {
384                                     FlushStrBuf(Ret); 
385                                     return -1; 
386                             }
387
388                             if (WCC->ReadPos != NULL) {
389                                     pch = ChrPtr(WCC->ReadBuf);
390
391                                     YetRead = WCC->ReadPos - pch;
392                                     if (YetRead > 0)
393                                     {
394                                             long StillThere;
395                                             
396                                             StillThere = StrLength(WCC->ReadBuf) - 
397                                                     YetRead;
398                                             
399                                             StrBufPlain(Ret, 
400                                                         WCC->ReadPos,
401                                                         StillThere);
402                                             total_len -= StillThere;
403                                     }
404                                     FlushStrBuf(WCC->ReadBuf);
405                                     WCC->ReadPos = NULL;
406                             } 
407                             if (total_len > 0)
408                             {
409                                     rc = StrBufReadBLOB(Ret, 
410                                                         &WCC->serv_sock, 
411                                                         1, 
412                                                         total_len,
413                                                         &ErrStr);
414                                     if (rc < 0)
415                                     {
416                                             lprintf(1, "Server connection broken: %s\n",
417                                                     (ErrStr)?ErrStr:"");
418                                             wc_backtrace();
419                                             WCC->serv_sock = (-1);
420                                             WCC->connected = 0;
421                                             WCC->logged_in = 0;
422                                             return rc;
423                                     }
424                                     else
425                                             return StrLength(Ret);
426                             }
427                             else 
428                                     return StrLength(Ret);
429                         }
430                 }
431                 else
432                         return -1;
433         }
434         else while ((WCC->serv_sock!=-1) &&
435                (bytes < total_len)) {
436                 thisblock = MaxRead;
437                 if ((total_len - bytes) < thisblock) {
438                         thisblock = total_len - bytes;
439                         if (thisblock == 0) {
440                                 FlushStrBuf(Ret); 
441                                 return -1; 
442                         }
443                 }
444                 serv_printf("READ %d|%d", (int)bytes, (int)thisblock);
445                 if (StrBuf_ServGetln(Buf) > 0)
446                 {
447                         if (GetServerStatus(Buf, NULL) == 6)
448                         {
449                             StrBufCutLeft(Buf, 4);
450                             thisblock = StrTol(Buf);
451                             if (WCC->serv_sock==-1) {
452                                     FlushStrBuf(Ret); 
453                                     return -1; 
454                             }
455                             StrBuf_ServGetBLOBBuffered(Ret, thisblock);
456                             bytes += thisblock;
457                     }
458                     else {
459                             lprintf(3, "Error: %s\n", ChrPtr(Buf) + 4);
460                             return -1;
461                     }
462                 }
463         }
464         return StrLength(Ret);
465 }
466
467
468 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
469 {
470         const char *Error;
471 #ifdef HAVE_OPENSSL
472         const char *pch, *pchs;
473         int rlen, len, retval = 0;
474
475         if (is_https) {
476                 int ntries = 0;
477                 if (StrLength(Hdr->ReadBuf) > 0) {
478                         pchs = ChrPtr(Hdr->ReadBuf);
479                         pch = strchr(pchs, '\n');
480                         if (pch != NULL) {
481                                 rlen = 0;
482                                 len = pch - pchs;
483                                 if (len > 0 && (*(pch - 1) == '\r') )
484                                         rlen ++;
485                                 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
486                                 StrBufCutLeft(Hdr->ReadBuf, len + 1);
487                                 return len - rlen;
488                         }
489                 }
490
491                 while (retval == 0) { 
492                                 pch = NULL;
493                                 pchs = ChrPtr(Hdr->ReadBuf);
494                                 if (*pchs != '\0')
495                                         pch = strchr(pchs, '\n');
496                                 if (pch == NULL) {
497                                         retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
498                                         pchs = ChrPtr(Hdr->ReadBuf);
499                                         pch = strchr(pchs, '\n');
500                                 }
501                                 if (retval == 0) {
502                                         sleeeeeeeeeep(1);
503                                         ntries ++;
504                                 }
505                                 if (ntries > 10)
506                                         return 0;
507                 }
508                 if ((retval > 0) && (pch != NULL)) {
509                         rlen = 0;
510                         len = pch - pchs;
511                         if (len > 0 && (*(pch - 1) == '\r') )
512                                 rlen ++;
513                         StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
514                         StrBufCutLeft(Hdr->ReadBuf, len + 1);
515                         return len - rlen;
516
517                 }
518                 else 
519                         return -1;
520         }
521         else 
522 #endif
523                 return StrBufTCP_read_buffered_line_fast(Target, 
524                                                          Hdr->ReadBuf,
525                                                          &Hdr->Pos,
526                                                          &Hdr->http_sock,
527                                                          5,
528                                                          1,
529                                                          &Error);
530 }
531
532
533 /* 
534  * This is a generic function to set up a master socket for listening on
535  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
536  *
537  * ip_addr      IP address to bind
538  * port_number  port number to bind
539  * queue_len    number of incoming connections to allow in the queue
540  */
541 int webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
542 {
543         struct protoent *p;
544         struct sockaddr_in6 sin6;
545         struct sockaddr_in sin4;
546         int s, i, b;
547         int ip_version = 6;
548
549         memset(&sin6, 0, sizeof(sin6));
550         memset(&sin4, 0, sizeof(sin4));
551         sin6.sin6_family = AF_INET6;
552         sin4.sin_family = AF_INET;
553
554         if (    (ip_addr == NULL)                                                       /* any IPv6 */
555                 || (IsEmptyStr(ip_addr))
556                 || (!strcmp(ip_addr, "*"))
557         ) {
558                 ip_version = 6;
559                 sin6.sin6_addr = in6addr_any;
560         }
561         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
562         {
563                 ip_version = 4;
564                 sin4.sin_addr.s_addr = INADDR_ANY;
565         }
566         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
567         {
568                 ip_version = 4;
569                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
570                         lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
571                         return (-WC_EXIT_BIND);
572                 }
573         }
574         else                                                                            /* specific IPv6 */
575         {
576                 ip_version = 6;
577                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
578                         lprintf(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
579                         return (-WC_EXIT_BIND);
580                 }
581         }
582
583         if (port_number == 0) {
584                 lprintf(1, "Cannot start: no port number specified.\n");
585                 return (-WC_EXIT_BIND);
586         }
587         sin6.sin6_port = htons((u_short) port_number);
588         sin4.sin_port = htons((u_short) port_number);
589
590         p = getprotobyname("tcp");
591
592         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
593         if (s < 0) {
594                 lprintf(1, "Can't create a listening socket: %s\n", strerror(errno));
595                 return (-WC_EXIT_BIND);
596         }
597         /* Set some socket options that make sense. */
598         i = 1;
599         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
600
601         if (ip_version == 6) {
602                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
603         }
604         else {
605                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
606         }
607
608         if (b < 0) {
609                 lprintf(1, "Can't bind: %s\n", strerror(errno));
610                 return (-WC_EXIT_BIND);
611         }
612
613         if (listen(s, queue_len) < 0) {
614                 lprintf(1, "Can't listen: %s\n", strerror(errno));
615                 return (-WC_EXIT_BIND);
616         }
617         return (s);
618 }
619
620
621 /*
622  * Create a Unix domain socket and listen on it
623  * sockpath - file name of the unix domain socket
624  * queue_len - Number of incoming connections to allow in the queue
625  */
626 int webcit_uds_server(char *sockpath, int queue_len)
627 {
628         struct sockaddr_un addr;
629         int s;
630         int i;
631         int actual_queue_len;
632
633         actual_queue_len = queue_len;
634         if (actual_queue_len < 5) actual_queue_len = 5;
635
636         i = unlink(sockpath);
637         if ((i != 0) && (errno != ENOENT)) {
638                 lprintf(1, "webcit: can't unlink %s: %s\n",
639                         sockpath, strerror(errno));
640                 return (-WC_EXIT_BIND);
641         }
642
643         memset(&addr, 0, sizeof(addr));
644         addr.sun_family = AF_UNIX;
645         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
646
647         s = socket(AF_UNIX, SOCK_STREAM, 0);
648         if (s < 0) {
649                 lprintf(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
650                 return (-WC_EXIT_BIND);
651         }
652
653         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
654                 lprintf(1, "webcit: Can't bind: %s\n",
655                         strerror(errno));
656                 return (-WC_EXIT_BIND);
657         }
658
659         if (listen(s, actual_queue_len) < 0) {
660                 lprintf(1, "webcit: Can't listen: %s\n",
661                         strerror(errno));
662                 return (-WC_EXIT_BIND);
663         }
664
665         chmod(sockpath, 0777);
666         return(s);
667 }
668
669
670
671
672 /*
673  * Read data from the client socket.
674  *
675  * sock         socket fd to read from
676  * buf          buffer to read into 
677  * bytes        number of bytes to read
678  * timeout      Number of seconds to wait before timing out
679  *
680  * Possible return values:
681  *      1       Requested number of bytes has been read.
682  *      0       Request timed out.
683  *      -1      Connection is broken, or other error.
684  */
685 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
686 {
687         const char *Error;
688         int retval = 0;
689
690 #ifdef HAVE_OPENSSL
691         if (is_https) {
692                 long bufremain;
693                 long baselen;
694
695                 baselen = StrLength(Target);
696
697                 if (Hdr->Pos == NULL)
698                         Hdr->Pos = ChrPtr(Hdr->ReadBuf);
699                 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
700
701                 if (bytes < bufremain)
702                         bufremain = bytes;
703                 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
704                 StrBufCutLeft(Hdr->ReadBuf, bufremain);
705
706                 if (bytes > bufremain) 
707                 {
708                         while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
709                                (retval >= 0))
710                                 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
711                         if (retval >= 0) {
712                                 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
713 #ifdef HTTP_TRACING
714                                 write(2, "\033[32m", 5);
715                                 write(2, buf, bytes);
716                                 write(2, "\033[30m", 5);
717 #endif
718                                 return 1;
719                         }
720                         else {
721                                 lprintf(2, "client_read_ssl() failed\n");
722                                 return -1;
723                         }
724                 }
725                 else 
726                         return 1;
727         }
728 #endif
729
730         retval = StrBufReadBLOBBuffered(Target, 
731                                         Hdr->ReadBuf, 
732                                         &Hdr->Pos, 
733                                         &Hdr->http_sock, 
734                                         1, 
735                                         bytes,
736                                         O_TERM,
737                                         &Error);
738         if (retval < 0) {
739                 lprintf(2, "client_read() failed: %s\n",
740                         Error);
741                 wc_backtrace();
742                 return retval;
743         }
744
745 #ifdef HTTP_TRACING
746         write(2, "\033[32m", 5);
747         write(2, buf, bytes);
748         write(2, "\033[30m", 5);
749 #endif
750         return 1;
751 }
752
753
754 /*
755  * Begin buffering HTTP output so we can transmit it all in one write operation later.
756  */
757 void begin_burst(void)
758 {
759         if (WC->WBuf == NULL) {
760                 WC->WBuf = NewStrBufPlain(NULL, 32768);
761         }
762 }
763
764
765 /*
766  * Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
767  */
768 long end_burst(void)
769 {
770         wcsession *WCC = WC;
771         const char *ptr, *eptr;
772         long count;
773         ssize_t res = 0;
774         fd_set wset;
775         int fdflags;
776
777         if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
778         {
779                 if (CompressBuffer(WCC->WBuf) > 0)
780                         hprintf("Content-encoding: gzip\r\n");
781                 else {
782                         lprintf(CTDL_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
783                         wc_backtrace();
784                 }
785         }
786
787         if (WCC->WFBuf != NULL) {
788                 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
789                 FreeStrBuf(&WCC->WFBuf);
790         }
791
792         if (WCC->Hdr->HR.prohibit_caching)
793                 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
794         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
795
796         ptr = ChrPtr(WCC->HBuf);
797         count = StrLength(WCC->HBuf);
798         eptr = ptr + count;
799
800 #ifdef HAVE_OPENSSL
801         if (is_https) {
802                 client_write_ssl(WCC->HBuf);
803                 client_write_ssl(WCC->WBuf);
804                 return (count);
805         }
806 #endif
807
808         
809 #ifdef HTTP_TRACING
810         
811         write(2, "\033[34m", 5);
812         write(2, ptr, StrLength(WCC->WBuf));
813         write(2, "\033[30m", 5);
814 #endif
815         if (WCC->Hdr->http_sock == -1)
816                 return -1;
817         fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
818
819         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
820                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
821                         FD_ZERO(&wset);
822                         FD_SET(WCC->Hdr->http_sock, &wset);
823                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
824                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
825                                 return -1;
826                         }
827                 }
828
829                 if ((WCC->Hdr->http_sock == -1) || 
830                     (res = write(WCC->Hdr->http_sock, 
831                                  ptr,
832                                  count)) == -1) {
833                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
834                         wc_backtrace();
835                         return res;
836                 }
837                 count -= res;
838                 ptr += res;
839         }
840
841         ptr = ChrPtr(WCC->WBuf);
842         count = StrLength(WCC->WBuf);
843         eptr = ptr + count;
844
845 #ifdef HTTP_TRACING
846         
847         write(2, "\033[34m", 5);
848         write(2, ptr, StrLength(WCC->WBuf));
849         write(2, "\033[30m", 5);
850 #endif
851
852         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
853                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
854                         FD_ZERO(&wset);
855                         FD_SET(WCC->Hdr->http_sock, &wset);
856                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
857                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
858                                 return -1;
859                         }
860                 }
861
862                 if ((WCC->Hdr->http_sock == -1) || 
863                     (res = write(WCC->Hdr->http_sock, 
864                                  ptr,
865                                  count)) == -1) {
866                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
867                         wc_backtrace();
868                         return res;
869                 }
870                 count -= res;
871                 ptr += res;
872         }
873
874         return StrLength(WCC->WBuf);
875 }
876
877
878 /*
879  * lingering_close() a`la Apache. see
880  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
881  */
882 int lingering_close(int fd)
883 {
884         char buf[SIZ];
885         int i;
886         fd_set set;
887         struct timeval tv, start;
888
889         gettimeofday(&start, NULL);
890         if (fd == -1)
891                 return -1;
892         shutdown(fd, 1);
893         do {
894                 do {
895                         gettimeofday(&tv, NULL);
896                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
897                         tv.tv_usec = start.tv_usec - tv.tv_usec;
898                         if (tv.tv_usec < 0) {
899                                 tv.tv_sec--;
900                                 tv.tv_usec += 1000000;
901                         }
902                         FD_ZERO(&set);
903                         FD_SET(fd, &set);
904                         i = select(fd + 1, &set, NULL, NULL, &tv);
905                 } while (i == -1 && errno == EINTR);
906
907                 if (i <= 0)
908                         break;
909
910                 i = read(fd, buf, sizeof buf);
911         } while (i != 0 && (i != -1 || errno == EINTR));
912
913         return close(fd);
914 }
915
916 void
917 HttpNewModule_TCPSOCKETS
918 (ParsedHttpHdrs *httpreq)
919 {
920
921         httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
922 }
923
924 void
925 HttpDetachModule_TCPSOCKETS
926 (ParsedHttpHdrs *httpreq)
927 {
928
929         FlushStrBuf(httpreq->ReadBuf);
930         ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
931 }
932
933 void
934 HttpDestroyModule_TCPSOCKETS
935 (ParsedHttpHdrs *httpreq)
936 {
937
938         FreeStrBuf(&httpreq->ReadBuf);
939 }
940
941
942 void
943 SessionNewModule_TCPSOCKETS
944 (wcsession *sess)
945 {
946         sess->CLineBuf = NewStrBuf();
947         sess->MigrateReadLineBuf = NewStrBuf();
948 }
949
950 void 
951 SessionDestroyModule_TCPSOCKETS
952 (wcsession *sess)
953 {
954         FreeStrBuf(&sess->CLineBuf);
955         FreeStrBuf(&sess->ReadBuf);
956         sess->ReadPos = NULL;
957         FreeStrBuf(&sess->MigrateReadLineBuf);
958         if (sess->serv_sock > 0)
959                 close(sess->serv_sock);
960 }