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