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