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