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