* just define vars if we need them
[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;
462 #ifdef HAVE_OPENSSL
463         const char *pch, *pchs;
464         int rlen, len, retval = 0;
465
466         if (is_https) {
467                 int ntries = 0;
468                 if (StrLength(Hdr->ReadBuf) > 0) {
469                         pchs = ChrPtr(Hdr->ReadBuf);
470                         pch = strchr(pchs, '\n');
471                         if (pch != NULL) {
472                                 rlen = 0;
473                                 len = pch - pchs;
474                                 if (len > 0 && (*(pch - 1) == '\r') )
475                                         rlen ++;
476                                 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
477                                 StrBufCutLeft(Hdr->ReadBuf, len + 1);
478                                 return len - rlen;
479                         }
480                 }
481
482                 while (retval == 0) { 
483                                 pch = NULL;
484                                 pchs = ChrPtr(Hdr->ReadBuf);
485                                 if (*pchs != '\0')
486                                         pch = strchr(pchs, '\n');
487                                 if (pch == NULL) {
488                                         retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
489                                         pchs = ChrPtr(Hdr->ReadBuf);
490                                         pch = strchr(pchs, '\n');
491                                 }
492                                 if (retval == 0) {
493                                         sleeeeeeeeeep(1);
494                                         ntries ++;
495                                 }
496                                 if (ntries > 10)
497                                         return 0;
498                 }
499                 if ((retval > 0) && (pch != NULL)) {
500                         rlen = 0;
501                         len = pch - pchs;
502                         if (len > 0 && (*(pch - 1) == '\r') )
503                                 rlen ++;
504                         StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
505                         StrBufCutLeft(Hdr->ReadBuf, len + 1);
506                         return len - rlen;
507
508                 }
509                 else 
510                         return -1;
511         }
512         else 
513 #endif
514                 return StrBufTCP_read_buffered_line_fast(Target, 
515                                                          Hdr->ReadBuf,
516                                                          &Hdr->Pos,
517                                                          &Hdr->http_sock,
518                                                          5,
519                                                          1,
520                                                          &Error);
521 }
522
523 /* 
524  * This is a generic function to set up a master socket for listening on
525  * a TCP port.  The server shuts down if the bind fails.
526  *
527  * ip_addr      IP address to bind
528  * port_number  port number to bind
529  * queue_len    number of incoming connections to allow in the queue
530  */
531 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
532 {
533         struct protoent *p;
534         struct sockaddr_in sin;
535         int s, i;
536
537         memset(&sin, 0, sizeof(sin));
538         sin.sin_family = AF_INET;
539         if (ip_addr == NULL) {
540                 sin.sin_addr.s_addr = INADDR_ANY;
541         } else {
542                 sin.sin_addr.s_addr = inet_addr(ip_addr);
543         }
544
545         if (sin.sin_addr.s_addr == INADDR_NONE) {
546                 sin.sin_addr.s_addr = INADDR_ANY;
547         }
548
549         if (port_number == 0) {
550                 lprintf(1, "Cannot start: no port number specified.\n");
551                 return (-WC_EXIT_BIND);
552         }
553         sin.sin_port = htons((u_short) port_number);
554
555         p = getprotobyname("tcp");
556
557         s = socket(PF_INET, SOCK_STREAM, (p->p_proto));
558         if (s < 0) {
559                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
560                 return (-WC_EXIT_BIND);
561         }
562         /* Set some socket options that make sense. */
563         i = 1;
564         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
565
566         #ifndef __APPLE__
567         fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
568                                           there should be a preceding F_GETFL
569                                           and a bitwise OR with the previous
570                                           fd flags */
571         #endif
572         
573         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
574                 lprintf(1, "Can't bind: %s\n", strerror(errno));
575                 return (-WC_EXIT_BIND);
576         }
577         if (listen(s, queue_len) < 0) {
578                 lprintf(1, "Can't listen: %s\n", strerror(errno));
579                 return (-WC_EXIT_BIND);
580         }
581         return (s);
582 }
583
584
585
586 /*
587  * Create a Unix domain socket and listen on it
588  * sockpath - file name of the unix domain socket
589  * queue_len - Number of incoming connections to allow in the queue
590  */
591 int ig_uds_server(char *sockpath, int queue_len)
592 {
593         struct sockaddr_un addr;
594         int s;
595         int i;
596         int actual_queue_len;
597
598         actual_queue_len = queue_len;
599         if (actual_queue_len < 5) actual_queue_len = 5;
600
601         i = unlink(sockpath);
602         if ((i != 0) && (errno != ENOENT)) {
603                 lprintf(1, "webcit: can't unlink %s: %s\n",
604                         sockpath, strerror(errno));
605                 return (-WC_EXIT_BIND);
606         }
607
608         memset(&addr, 0, sizeof(addr));
609         addr.sun_family = AF_UNIX;
610         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
611
612         s = socket(AF_UNIX, SOCK_STREAM, 0);
613         if (s < 0) {
614                 lprintf(1, "webcit: Can't create a socket: %s\n",
615                         strerror(errno));
616                 return (-WC_EXIT_BIND);
617         }
618
619         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
620                 lprintf(1, "webcit: Can't bind: %s\n",
621                         strerror(errno));
622                 return (-WC_EXIT_BIND);
623         }
624
625         if (listen(s, actual_queue_len) < 0) {
626                 lprintf(1, "webcit: Can't listen: %s\n",
627                         strerror(errno));
628                 return (-WC_EXIT_BIND);
629         }
630
631         chmod(sockpath, 0777);
632         return(s);
633 }
634
635
636
637
638 /*
639  * Read data from the client socket.
640  *
641  * sock         socket fd to read from
642  * buf          buffer to read into 
643  * bytes        number of bytes to read
644  * timeout      Number of seconds to wait before timing out
645  *
646  * Possible return values:
647  *      1       Requested number of bytes has been read.
648  *      0       Request timed out.
649  *      -1      Connection is broken, or other error.
650  */
651 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout)
652 {
653         const char *Error;
654         int retval = 0;
655
656 #ifdef HAVE_OPENSSL
657         if (is_https) {
658                 long bufremain;
659                 long baselen;
660
661                 baselen = StrLength(Target);
662
663                 if (Hdr->Pos == NULL)
664                         Hdr->Pos = ChrPtr(Hdr->ReadBuf);
665                 bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
666
667                 if (bytes < bufremain)
668                         bufremain = bytes;
669                 StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
670                 StrBufCutLeft(Hdr->ReadBuf, bufremain);
671
672                 if (bytes > bufremain) 
673                 {
674                         while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
675                                (retval >= 0))
676                                 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
677                         if (retval >= 0) {
678                                 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
679 #ifdef HTTP_TRACING
680                                 write(2, "\033[32m", 5);
681                                 write(2, buf, bytes);
682                                 write(2, "\033[30m", 5);
683 #endif
684                                 return 1;
685                         }
686                         else {
687                                 lprintf(2, "client_read_ssl() failed\n");
688                                 return -1;
689                         }
690                 }
691                 else 
692                         return 1;
693         }
694 #endif
695
696         retval = StrBufReadBLOBBuffered(Target, 
697                                         Hdr->ReadBuf, 
698                                         &Hdr->Pos, 
699                                         &Hdr->http_sock, 
700                                         1, 
701                                         bytes,
702                                         O_TERM,
703                                         &Error);
704         if (retval < 0) {
705                 lprintf(2, "client_read() failed: %s\n",
706                         Error);
707                 return retval;
708         }
709
710 #ifdef HTTP_TRACING
711         write(2, "\033[32m", 5);
712         write(2, buf, bytes);
713         write(2, "\033[30m", 5);
714 #endif
715         return 1;
716 }
717
718
719 /*
720  * Begin buffering HTTP output so we can transmit it all in one write operation later.
721  */
722 void begin_burst(void)
723 {
724         if (WC->WBuf == NULL) {
725                 WC->WBuf = NewStrBufPlain(NULL, 32768);
726         }
727 }
728
729
730 /*
731  * Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
732  */
733 long end_burst(void)
734 {
735         wcsession *WCC = WC;
736         const char *ptr, *eptr;
737         long count;
738         ssize_t res = 0;
739         fd_set wset;
740         int fdflags;
741
742         if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
743         {
744                 if (CompressBuffer(WCC->WBuf) > 0)
745                         hprintf("Content-encoding: gzip\r\n");
746                 else {
747                         lprintf(CTDL_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
748                         wc_backtrace();
749                 }
750         }
751
752         if (WCC->Hdr->HR.prohibit_caching)
753                 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
754         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
755
756         ptr = ChrPtr(WCC->HBuf);
757         count = StrLength(WCC->HBuf);
758         eptr = ptr + count;
759
760 #ifdef HAVE_OPENSSL
761         if (is_https) {
762                 client_write_ssl(WCC->HBuf);
763                 client_write_ssl(WCC->WBuf);
764                 return (count);
765         }
766 #endif
767
768         
769 #ifdef HTTP_TRACING
770         
771         write(2, "\033[34m", 5);
772         write(2, ptr, StrLength(WCC->WBuf));
773         write(2, "\033[30m", 5);
774 #endif
775         if (WCC->Hdr->http_sock == -1)
776                 return -1;
777         fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
778
779         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)){
780                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
781                         FD_ZERO(&wset);
782                         FD_SET(WCC->Hdr->http_sock, &wset);
783                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
784                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
785                                 return -1;
786                         }
787                 }
788
789                 if ((WCC->Hdr->http_sock == -1) || 
790                     (res = write(WCC->Hdr->http_sock, 
791                                  ptr,
792                                  count)) == -1) {
793                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
794                         wc_backtrace();
795                         return res;
796                 }
797                 count -= res;
798                 ptr += res;
799         }
800
801         ptr = ChrPtr(WCC->WBuf);
802         count = StrLength(WCC->WBuf);
803         eptr = ptr + count;
804
805 #ifdef HTTP_TRACING
806         
807         write(2, "\033[34m", 5);
808         write(2, ptr, StrLength(WCC->WBuf));
809         write(2, "\033[30m", 5);
810 #endif
811
812         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
813                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
814                         FD_ZERO(&wset);
815                         FD_SET(WCC->Hdr->http_sock, &wset);
816                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
817                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
818                                 return -1;
819                         }
820                 }
821
822                 if ((WCC->Hdr->http_sock == -1) || 
823                     (res = write(WCC->Hdr->http_sock, 
824                                  ptr,
825                                  count)) == -1) {
826                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
827                         wc_backtrace();
828                         return res;
829                 }
830                 count -= res;
831                 ptr += res;
832         }
833
834         return StrLength(WCC->WBuf);
835 }
836
837
838 /*
839  * lingering_close() a`la Apache. see
840  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
841  */
842 int lingering_close(int fd)
843 {
844         char buf[SIZ];
845         int i;
846         fd_set set;
847         struct timeval tv, start;
848
849         gettimeofday(&start, NULL);
850         if (fd == -1)
851                 return -1;
852         shutdown(fd, 1);
853         do {
854                 do {
855                         gettimeofday(&tv, NULL);
856                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
857                         tv.tv_usec = start.tv_usec - tv.tv_usec;
858                         if (tv.tv_usec < 0) {
859                                 tv.tv_sec--;
860                                 tv.tv_usec += 1000000;
861                         }
862                         FD_ZERO(&set);
863                         FD_SET(fd, &set);
864                         i = select(fd + 1, &set, NULL, NULL, &tv);
865                 } while (i == -1 && errno == EINTR);
866
867                 if (i <= 0)
868                         break;
869
870                 i = read(fd, buf, sizeof buf);
871         } while (i != 0 && (i != -1 || errno == EINTR));
872
873         return close(fd);
874 }
875
876 void
877 HttpNewModule_TCPSOCKETS
878 (ParsedHttpHdrs *httpreq)
879 {
880
881         httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
882 }
883
884 void
885 HttpDetachModule_TCPSOCKETS
886 (ParsedHttpHdrs *httpreq)
887 {
888
889         FlushStrBuf(httpreq->ReadBuf);
890         ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
891 }
892
893 void
894 HttpDestroyModule_TCPSOCKETS
895 (ParsedHttpHdrs *httpreq)
896 {
897
898         FreeStrBuf(&httpreq->ReadBuf);
899 }
900
901
902 void
903 SessionNewModule_TCPSOCKETS
904 (wcsession *sess)
905 {
906         sess->CLineBuf = NewStrBuf();
907         sess->MigrateReadLineBuf = NewStrBuf();
908 }
909
910 void 
911 SessionDestroyModule_TCPSOCKETS
912 (wcsession *sess)
913 {
914         FreeStrBuf(&sess->CLineBuf);
915         FreeStrBuf(&sess->ReadBuf);
916         sess->ReadPos = NULL;
917         FreeStrBuf(&sess->MigrateReadLineBuf);
918         if (sess->serv_sock > 0)
919                 close(sess->serv_sock);
920 }