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