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