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