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