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