687580e2de359c8b790e0c61cc0ca54a2ca65ed8
[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                 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                 syslog(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                 syslog(1, "StrBuf_ServGetBLOBBuffered(): 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                 syslog(9, "%3d<<<BLOB: %d 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                 syslog(1, "StrBuf_ServGetBLOB(): 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                 syslog(9, "%3d<<<BLOB: %d 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                         syslog(1, "ERROR: somebody didn't eat his soup! Remaing Chars: %d [%s]\n", 
279                                 pche - WCC->ReadPos, pche);
280                         syslog(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                         syslog(1, "serv_write(): 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         syslog(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         syslog(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         syslog(9, ">>>%s", buf);
380 #endif
381 }
382
383
384 /*
385  * Read binary data from server into memory using a series of server READ commands.
386  * returns the read content as StrBuf
387  */
388 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf) 
389 {
390         wcsession *WCC = WC;
391         size_t bytes_read = 0;
392         size_t this_block = 0;
393         int rc;
394
395         if (Ret == NULL) {
396                 return -1;
397         }
398
399         while (bytes_read < total_len) {
400
401                 if (WCC->serv_sock==-1) {
402                         FlushStrBuf(Ret); 
403                         return -1; 
404                 }
405
406                 serv_printf("READ %d|%d", bytes_read, total_len-bytes_read);
407                 if ( (rc = StrBuf_ServGetln(Buf) > 0) && (GetServerStatus(Buf, NULL) == 6) ) 
408                 {
409                         if (rc < 0)
410                                 return rc;
411                         StrBufCutLeft(Buf, 4);
412                         this_block = StrTol(Buf);
413                         rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
414                         if (rc < 0) {
415                                 syslog(1, "Server connection broken during download\n");
416                                 wc_backtrace();
417                                 WCC->serv_sock = (-1);
418                                 WCC->connected = 0;
419                                 WCC->logged_in = 0;
420                                 return rc;
421                         }
422                         bytes_read += rc;
423                 }
424         }
425
426         return StrLength(Ret);
427 }
428
429
430 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
431 {
432         const char *Error;
433 #ifdef HAVE_OPENSSL
434         const char *pch, *pchs;
435         int rlen, len, retval = 0;
436
437         if (is_https) {
438                 int ntries = 0;
439                 if (StrLength(Hdr->ReadBuf) > 0) {
440                         pchs = ChrPtr(Hdr->ReadBuf);
441                         pch = strchr(pchs, '\n');
442                         if (pch != NULL) {
443                                 rlen = 0;
444                                 len = pch - pchs;
445                                 if (len > 0 && (*(pch - 1) == '\r') )
446                                         rlen ++;
447                                 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
448                                 StrBufCutLeft(Hdr->ReadBuf, len + 1);
449                                 return len - rlen;
450                         }
451                 }
452
453                 while (retval == 0) { 
454                                 pch = NULL;
455                                 pchs = ChrPtr(Hdr->ReadBuf);
456                                 if (*pchs != '\0')
457                                         pch = strchr(pchs, '\n');
458                                 if (pch == NULL) {
459                                         retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
460                                         pchs = ChrPtr(Hdr->ReadBuf);
461                                         pch = strchr(pchs, '\n');
462                                 }
463                                 if (retval == 0) {
464                                         sleeeeeeeeeep(1);
465                                         ntries ++;
466                                 }
467                                 if (ntries > 10)
468                                         return 0;
469                 }
470                 if ((retval > 0) && (pch != NULL)) {
471                         rlen = 0;
472                         len = pch - pchs;
473                         if (len > 0 && (*(pch - 1) == '\r') )
474                                 rlen ++;
475                         StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
476                         StrBufCutLeft(Hdr->ReadBuf, len + 1);
477                         return len - rlen;
478
479                 }
480                 else 
481                         return -1;
482         }
483         else 
484 #endif
485                 return StrBufTCP_read_buffered_line_fast(Target, 
486                                                          Hdr->ReadBuf,
487                                                          &Hdr->Pos,
488                                                          &Hdr->http_sock,
489                                                          5,
490                                                          1,
491                                                          &Error);
492 }
493
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 webcit_tcp_server(char *ip_addr, int port_number, int queue_len)
504 {
505         struct protoent *p;
506         struct sockaddr_in6 sin6;
507         struct sockaddr_in sin4;
508         int s, i, b;
509         int ip_version = 6;
510
511         memset(&sin6, 0, sizeof(sin6));
512         memset(&sin4, 0, sizeof(sin4));
513         sin6.sin6_family = AF_INET6;
514         sin4.sin_family = AF_INET;
515
516         if (    (ip_addr == NULL)                                                       /* any IPv6 */
517                 || (IsEmptyStr(ip_addr))
518                 || (!strcmp(ip_addr, "*"))
519         ) {
520                 ip_version = 6;
521                 sin6.sin6_addr = in6addr_any;
522         }
523         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
524         {
525                 ip_version = 4;
526                 sin4.sin_addr.s_addr = INADDR_ANY;
527         }
528         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
529         {
530                 ip_version = 4;
531                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
532                         syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
533                         return (-WC_EXIT_BIND);
534                 }
535         }
536         else                                                                            /* specific IPv6 */
537         {
538                 ip_version = 6;
539                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
540                         syslog(1, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
541                         return (-WC_EXIT_BIND);
542                 }
543         }
544
545         if (port_number == 0) {
546                 syslog(1, "Cannot start: no port number specified.\n");
547                 return (-WC_EXIT_BIND);
548         }
549         sin6.sin6_port = htons((u_short) port_number);
550         sin4.sin_port = htons((u_short) port_number);
551
552         p = getprotobyname("tcp");
553
554         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
555         if (s < 0) {
556                 syslog(1, "Can't create a listening socket: %s\n", strerror(errno));
557                 return (-WC_EXIT_BIND);
558         }
559         /* Set some socket options that make sense. */
560         i = 1;
561         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
562
563         if (ip_version == 6) {
564                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
565         }
566         else {
567                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
568         }
569
570         if (b < 0) {
571                 syslog(1, "Can't bind: %s\n", strerror(errno));
572                 return (-WC_EXIT_BIND);
573         }
574
575         if (listen(s, queue_len) < 0) {
576                 syslog(1, "Can't listen: %s\n", strerror(errno));
577                 return (-WC_EXIT_BIND);
578         }
579         return (s);
580 }
581
582
583 /*
584  * Create a Unix domain socket and listen on it
585  * sockpath - file name of the unix domain socket
586  * queue_len - Number of incoming connections to allow in the queue
587  */
588 int webcit_uds_server(char *sockpath, int queue_len)
589 {
590         struct sockaddr_un addr;
591         int s;
592         int i;
593         int actual_queue_len;
594
595         actual_queue_len = queue_len;
596         if (actual_queue_len < 5) actual_queue_len = 5;
597
598         i = unlink(sockpath);
599         if ((i != 0) && (errno != ENOENT)) {
600                 syslog(1, "webcit: can't unlink %s: %s\n",
601                         sockpath, strerror(errno));
602                 return (-WC_EXIT_BIND);
603         }
604
605         memset(&addr, 0, sizeof(addr));
606         addr.sun_family = AF_UNIX;
607         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
608
609         s = socket(AF_UNIX, SOCK_STREAM, 0);
610         if (s < 0) {
611                 syslog(1, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
612                 return (-WC_EXIT_BIND);
613         }
614
615         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
616                 syslog(1, "webcit: Can't bind: %s\n",
617                         strerror(errno));
618                 return (-WC_EXIT_BIND);
619         }
620
621         if (listen(s, actual_queue_len) < 0) {
622                 syslog(1, "webcit: Can't listen: %s\n",
623                         strerror(errno));
624                 return (-WC_EXIT_BIND);
625         }
626
627         chmod(sockpath, 0777);
628         return(s);
629 }
630
631
632
633
634 /*
635  * Read data from the client socket.
636  *
637  * sock         socket fd to read from
638  * buf          buffer to read into 
639  * bytes        number of bytes to read
640  * timeout      Number of seconds to wait before timing out
641  *
642  * Possible return values:
643  *      1       Requested number of bytes has been read.
644  *      0       Request timed out.
645  *      -1      Connection is broken, or other error.
646  */
647 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
648 {
649         const char *Error;
650         int retval = 0;
651
652 #ifdef HAVE_OPENSSL
653         if (is_https) {
654                 long bufremain = 0;
655                 long baselen;
656
657                 baselen = StrLength(Target);
658
659                 if (Hdr->Pos == NULL)
660                         Hdr->Pos = ChrPtr(Hdr->ReadBuf);
661
662                 if (StrLength(Hdr->ReadBuf) > 0)
663                 {
664                         bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
665                         
666                         if (bytes < bufremain)
667                                 bufremain = bytes;
668                         StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
669                         StrBufCutLeft(Hdr->ReadBuf, bufremain);
670                 }
671
672                 if (bytes > bufremain) 
673                 {
674                         while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
675                                (retval >= 0))
676                                 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
677                         if (retval >= 0) {
678                                 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
679 #ifdef HTTP_TRACING
680                                 write(2, "\033[32m", 5);
681                                 write(2, buf, bytes);
682                                 write(2, "\033[30m", 5);
683 #endif
684                                 return 1;
685                         }
686                         else {
687                                 syslog(2, "client_read_ssl() failed\n");
688                                 return -1;
689                         }
690                 }
691                 else 
692                         return 1;
693         }
694 #endif
695
696         retval = StrBufReadBLOBBuffered(Target, 
697                                         Hdr->ReadBuf, 
698                                         &Hdr->Pos, 
699                                         &Hdr->http_sock, 
700                                         1, 
701                                         bytes,
702                                         O_TERM,
703                                         &Error);
704         if (retval < 0) {
705                 syslog(2, "client_read() failed: %s\n",
706                         Error);
707                 wc_backtrace();
708                 return retval;
709         }
710
711 #ifdef HTTP_TRACING
712         write(2, "\033[32m", 5);
713         write(2, buf, bytes);
714         write(2, "\033[30m", 5);
715 #endif
716         return 1;
717 }
718
719
720 /*
721  * Begin buffering HTTP output so we can transmit it all in one write operation later.
722  */
723 void begin_burst(void)
724 {
725         if (WC->WBuf == NULL) {
726                 WC->WBuf = NewStrBufPlain(NULL, 32768);
727         }
728 }
729
730
731 /*
732  * Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
733  */
734 long end_burst(void)
735 {
736         wcsession *WCC = WC;
737         const char *ptr, *eptr;
738         long count;
739         ssize_t res = 0;
740         fd_set wset;
741         int fdflags;
742
743         if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
744         {
745                 if (CompressBuffer(WCC->WBuf) > 0)
746                         hprintf("Content-encoding: gzip\r\n");
747                 else {
748                         syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
749                         wc_backtrace();
750                 }
751         }
752
753         if (WCC->WFBuf != NULL) {
754                 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
755                 FreeStrBuf(&WCC->WFBuf);
756         }
757
758         if (WCC->Hdr->HR.prohibit_caching)
759                 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
760         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
761
762         ptr = ChrPtr(WCC->HBuf);
763         count = StrLength(WCC->HBuf);
764         eptr = ptr + count;
765
766 #ifdef HAVE_OPENSSL
767         if (is_https) {
768                 client_write_ssl(WCC->HBuf);
769                 client_write_ssl(WCC->WBuf);
770                 return (count);
771         }
772 #endif
773
774         
775 #ifdef HTTP_TRACING
776         
777         write(2, "\033[34m", 5);
778         write(2, ptr, StrLength(WCC->WBuf));
779         write(2, "\033[30m", 5);
780 #endif
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 #ifdef HTTP_TRACING
812         
813         write(2, "\033[34m", 5);
814         write(2, ptr, StrLength(WCC->WBuf));
815         write(2, "\033[30m", 5);
816 #endif
817
818         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
819                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
820                         FD_ZERO(&wset);
821                         FD_SET(WCC->Hdr->http_sock, &wset);
822                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
823                                 syslog(2, "client_write: Socket select failed (%s)\n", strerror(errno));
824                                 return -1;
825                         }
826                 }
827
828                 if ((WCC->Hdr->http_sock == -1) || 
829                     (res = write(WCC->Hdr->http_sock, 
830                                  ptr,
831                                  count)) == -1) {
832                         syslog(2, "client_write: Socket write failed (%s)\n", strerror(errno));
833                         wc_backtrace();
834                         return res;
835                 }
836                 count -= res;
837                 ptr += res;
838         }
839
840         return StrLength(WCC->WBuf);
841 }
842
843
844 /*
845  * lingering_close() a`la Apache. see
846  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
847  */
848 int lingering_close(int fd)
849 {
850         char buf[SIZ];
851         int i;
852         fd_set set;
853         struct timeval tv, start;
854
855         gettimeofday(&start, NULL);
856         if (fd == -1)
857                 return -1;
858         shutdown(fd, 1);
859         do {
860                 do {
861                         gettimeofday(&tv, NULL);
862                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
863                         tv.tv_usec = start.tv_usec - tv.tv_usec;
864                         if (tv.tv_usec < 0) {
865                                 tv.tv_sec--;
866                                 tv.tv_usec += 1000000;
867                         }
868                         FD_ZERO(&set);
869                         FD_SET(fd, &set);
870                         i = select(fd + 1, &set, NULL, NULL, &tv);
871                 } while (i == -1 && errno == EINTR);
872
873                 if (i <= 0)
874                         break;
875
876                 i = read(fd, buf, sizeof buf);
877         } while (i != 0 && (i != -1 || errno == EINTR));
878
879         return close(fd);
880 }
881
882 void
883 HttpNewModule_TCPSOCKETS
884 (ParsedHttpHdrs *httpreq)
885 {
886
887         httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
888 }
889
890 void
891 HttpDetachModule_TCPSOCKETS
892 (ParsedHttpHdrs *httpreq)
893 {
894
895         FlushStrBuf(httpreq->ReadBuf);
896         ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
897 }
898
899 void
900 HttpDestroyModule_TCPSOCKETS
901 (ParsedHttpHdrs *httpreq)
902 {
903
904         FreeStrBuf(&httpreq->ReadBuf);
905 }
906
907
908 void
909 SessionNewModule_TCPSOCKETS
910 (wcsession *sess)
911 {
912         sess->CLineBuf = NewStrBuf();
913         sess->MigrateReadLineBuf = NewStrBuf();
914 }
915
916 void 
917 SessionDestroyModule_TCPSOCKETS
918 (wcsession *sess)
919 {
920         FreeStrBuf(&sess->CLineBuf);
921         FreeStrBuf(&sess->ReadBuf);
922         sess->ReadPos = NULL;
923         FreeStrBuf(&sess->MigrateReadLineBuf);
924         if (sess->serv_sock > 0) {
925                 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
926                 close(sess->serv_sock);
927         }
928 }