ad4903afc782e55bd43b47d302c789f40bac46f5
[citadel] / webcit / tcp_sockets.c
1 /*
2  * Copyright (c) 1987-2017 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  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  */
12
13 /*
14  * Uncomment this to log all communications with the Citadel server
15 #define SERV_TRACE 1
16  */
17
18 #include "webcit.h"
19 #include "webserver.h"
20
21 long MaxRead = -1; /* should we do READ scattered or all at once? */
22
23 /*
24  * register the timeout
25  */
26 RETSIGTYPE timeout(int signum)
27 {
28         syslog(LOG_WARNING, "Connection timed out; unable to reach citserver\n");
29         /* no exit here, since we need to server the connection unreachable thing. exit(3); */
30 }
31
32
33 /*
34  * Client side - connect to a unix domain socket
35  */
36 int uds_connectsock(char *sockpath)
37 {
38         struct sockaddr_un addr;
39         int s;
40
41         memset(&addr, 0, sizeof(addr));
42         addr.sun_family = AF_UNIX;
43         strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
44
45         s = socket(AF_UNIX, SOCK_STREAM, 0);
46         if (s < 0) {
47                 syslog(LOG_WARNING, "Can't create socket [%s]: %s\n", sockpath, strerror(errno));
48                 return(-1);
49         }
50
51         if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
52                 syslog(LOG_WARNING, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
53                 close(s);
54                 return(-1);
55         }
56         return s;
57 }
58
59
60 /*
61  * TCP client - connect to a host/port 
62  */
63 int tcp_connectsock(char *host, char *service)
64 {
65         struct in6_addr serveraddr;
66         struct addrinfo hints;
67         struct addrinfo *res = NULL;
68         struct addrinfo *ai = NULL;
69         int rc = (-1);
70         int s = (-1);
71
72         if ((host == NULL) || IsEmptyStr(host))
73                 return (-1);
74         if ((service == NULL) || IsEmptyStr(service))
75                 return (-1);
76
77         syslog(LOG_DEBUG, "tcp_connectsock(%s,%s)\n", host, service);
78
79         memset(&hints, 0x00, sizeof(hints));
80         hints.ai_flags = AI_NUMERICSERV;
81         hints.ai_family = AF_UNSPEC;
82         hints.ai_socktype = SOCK_STREAM;
83
84         /*
85          * Handle numeric IPv4 and IPv6 addresses
86          */
87         rc = inet_pton(AF_INET, host, &serveraddr);
88         if (rc == 1) {                                          /* dotted quad */
89                 hints.ai_family = AF_INET;
90                 hints.ai_flags |= AI_NUMERICHOST;
91         } else {
92                 rc = inet_pton(AF_INET6, host, &serveraddr);
93                 if (rc == 1) {                                  /* IPv6 address */
94                         hints.ai_family = AF_INET6;
95                         hints.ai_flags |= AI_NUMERICHOST;
96                 }
97         }
98
99         /* Begin the connection process */
100
101         rc = getaddrinfo(host, service, &hints, &res);
102         if (rc != 0) {
103                 syslog(LOG_DEBUG, "%s: %s\n", host, gai_strerror(rc));
104                 freeaddrinfo(res);
105                 return(-1);
106         }
107
108         /*
109          * Try all available addresses until we connect to one or until we run out.
110          */
111         for (ai = res; ai != NULL; ai = ai->ai_next) {
112
113                 if (ai->ai_family == AF_INET) syslog(LOG_DEBUG, "Trying IPv4\n");
114                 else if (ai->ai_family == AF_INET6) syslog(LOG_DEBUG, "Trying IPv6\n");
115                 else syslog(LOG_WARNING, "This is going to fail.\n");
116
117                 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
118                 if (s < 0) {
119                         syslog(LOG_WARNING, "socket() failed: %s\n", strerror(errno));
120                         freeaddrinfo(res);
121                         return(-1);
122                 }
123                 rc = connect(s, ai->ai_addr, ai->ai_addrlen);
124                 if (rc >= 0) {
125                         int fdflags;
126                         freeaddrinfo(res);
127
128                         fdflags = fcntl(rc, F_GETFL);
129                         if (fdflags < 0) {
130                                 syslog(LOG_ERR,
131                                        "unable to get socket %d flags! %s \n",
132                                        rc,
133                                        strerror(errno));
134                                 close(rc);
135                                 return -1;
136                         }
137                         fdflags = fdflags | O_NONBLOCK;
138                         if (fcntl(rc, F_SETFL, fdflags) < 0) {
139                                 syslog(LOG_ERR,
140                                        "unable to set socket %d nonblocking flags! %s \n",
141                                        rc,
142                                        strerror(errno));
143                                 close(s);
144                                 return -1;
145                         }
146
147                         return(s);
148                 }
149                 else {
150                         syslog(LOG_WARNING, "connect() failed: %s\n", strerror(errno));
151                         close(s);
152                 }
153         }
154         freeaddrinfo(res);
155         return(-1);
156 }
157
158
159 /*
160  *  input string from pipe
161  */
162 int serv_getln(char *strbuf, int bufsize)
163 {
164         wcsession *WCC = WC;
165         int len;
166
167         *strbuf = '\0';
168         StrBuf_ServGetln(WCC->MigrateReadLineBuf);
169         len = StrLength(WCC->MigrateReadLineBuf);
170         if (len > bufsize)
171                 len = bufsize - 1;
172         memcpy(strbuf, ChrPtr(WCC->MigrateReadLineBuf), len);
173         FlushStrBuf(WCC->MigrateReadLineBuf);
174         strbuf[len] = '\0';
175 #ifdef SERV_TRACE
176         syslog(LOG_DEBUG, "%3d<<<%s\n", WCC->serv_sock, strbuf);
177 #endif
178         return len;
179 }
180
181
182 int StrBuf_ServGetln(StrBuf *buf)
183 {
184         wcsession *WCC = WC;
185         const char *ErrStr = NULL;
186         int rc;
187         
188         if (!WCC->connected)
189                 return -1;
190
191         FlushStrBuf(buf);
192         rc = StrBufTCP_read_buffered_line_fast(buf, 
193                                                WCC->ReadBuf, 
194                                                &WCC->ReadPos, 
195                                                &WCC->serv_sock, 
196                                                5, 1, 
197                                                &ErrStr);
198         if (rc < 0)
199         {
200                 syslog(LOG_INFO, "StrBuf_ServGetln(): Server connection broken: %s\n",
201                         (ErrStr)?ErrStr:"");
202                 wc_backtrace(LOG_INFO);
203                 if (WCC->serv_sock > 0) close(WCC->serv_sock);
204                 WCC->serv_sock = (-1);
205                 WCC->connected = 0;
206                 WCC->logged_in = 0;
207         }
208 #ifdef SERV_TRACE
209         else 
210         {
211                 long pos = 0;
212                 if (WCC->ReadPos != NULL)
213                         pos = WCC->ReadPos - ChrPtr(WCC->ReadBuf);
214                 syslog(LOG_DEBUG, "%3d<<<[%ld]%s\n", WC->serv_sock, pos, ChrPtr(buf));
215         }
216 #endif
217         return rc;
218 }
219
220 int StrBuf_ServGetBLOBBuffered(StrBuf *buf, long BlobSize)
221 {
222         wcsession *WCC = WC;
223         const char *ErrStr;
224         int rc;
225         
226         rc = StrBufReadBLOBBuffered(buf, 
227                                     WCC->ReadBuf, 
228                                     &WCC->ReadPos,
229                                     &WCC->serv_sock, 
230                                     1, 
231                                     BlobSize, 
232                                     NNN_TERM,
233                                     &ErrStr);
234         if (rc < 0)
235         {
236                 syslog(LOG_INFO, "StrBuf_ServGetBLOBBuffered(): Server connection broken: %s\n",
237                         (ErrStr)?ErrStr:"");
238                 wc_backtrace(LOG_INFO);
239                 if (WCC->serv_sock > 0) close(WCC->serv_sock);
240                 WCC->serv_sock = (-1);
241                 WCC->connected = 0;
242                 WCC->logged_in = 0;
243         }
244 #ifdef SERV_TRACE
245         else
246                 syslog(LOG_DEBUG, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
247 #endif
248
249         return rc;
250 }
251
252 int StrBuf_ServGetBLOB(StrBuf *buf, long BlobSize)
253 {
254         wcsession *WCC = WC;
255         const char *ErrStr;
256         int rc;
257         
258         WCC->ReadPos = NULL;
259         rc = StrBufReadBLOB(buf, &WCC->serv_sock, 1, BlobSize, &ErrStr);
260         if (rc < 0)
261         {
262                 syslog(LOG_INFO, "StrBuf_ServGetBLOB(): Server connection broken: %s\n",
263                         (ErrStr)?ErrStr:"");
264                 wc_backtrace(LOG_INFO);
265                 if (WCC->serv_sock > 0) close(WCC->serv_sock);
266                 WCC->serv_sock = (-1);
267                 WCC->connected = 0;
268                 WCC->logged_in = 0;
269         }
270 #ifdef SERV_TRACE
271         else
272                 syslog(LOG_DEBUG, "%3d<<<BLOB: %d bytes\n", WC->serv_sock, StrLength(buf));
273 #endif
274
275         return rc;
276 }
277
278
279 void FlushReadBuf (void)
280 {
281         long len;
282         const char *pch;
283         const char *pche;
284         wcsession *WCC = WC;
285
286         len = StrLength(WCC->ReadBuf);
287         if ((len > 0) &&
288             (WCC->ReadPos != NULL) && 
289             (WCC->ReadPos != StrBufNOTNULL))
290                 
291         {
292                 pch = ChrPtr(WCC->ReadBuf);
293                 pche = pch + len;
294                 if (WCC->ReadPos != pche)
295                 {
296                         syslog(LOG_ERR,
297                                 "ERROR: somebody didn't eat his soup! Remaing Chars: %ld [%s]\n", 
298                                 (long)(pche - WCC->ReadPos),
299                                 pche
300                         );
301                         syslog(LOG_ERR, 
302                                 "--------------------------------------------------------------------------------\n"
303                                 "Whole buf: [%s]\n"
304                                 "--------------------------------------------------------------------------------\n", 
305                                 pch);
306                         AppendImportantMessage(HKEY("Suppenkasper alert! watch your webcit logfile and get connected to your favourite opensource Crew."));
307                 }
308         }
309
310         FlushStrBuf(WCC->ReadBuf);
311         WCC->ReadPos = NULL;
312
313
314 }
315
316
317 /*
318  *  send binary to server
319  *  buf the buffer to write to citadel server
320  *  nbytes how many bytes to send to citadel server
321  */
322 int serv_write(const char *buf, int nbytes)
323 {
324         wcsession *WCC = WC;
325         int bytes_written = 0;
326         int retval;
327
328         FlushReadBuf();
329         while (bytes_written < nbytes) {
330                 retval = write(WCC->serv_sock, &buf[bytes_written],
331                                nbytes - bytes_written);
332                 if (retval < 1) {
333                         const char *ErrStr = strerror(errno);
334                         syslog(LOG_INFO, "serv_write(): Server connection broken: %s\n",
335                                 (ErrStr)?ErrStr:"");
336                         if (WCC->serv_sock > 0) close(WCC->serv_sock);
337                         WCC->serv_sock = (-1);
338                         WCC->connected = 0;
339                         WCC->logged_in = 0;
340                         return 0;
341                 }
342                 bytes_written = bytes_written + retval;
343         }
344         return 1;
345 }
346
347
348 /*
349  *  send line to server
350  *  string the line to send to the citadel server
351  */
352 int serv_puts(const char *string)
353 {
354 #ifdef SERV_TRACE
355         syslog(LOG_DEBUG, "%3d>>>%s\n", WC->serv_sock, string);
356 #endif
357         FlushReadBuf();
358
359         if (!serv_write(string, strlen(string)))
360                 return 0;
361         return serv_write("\n", 1);
362 }
363
364 /*
365  *  send line to server
366  *  string the line to send to the citadel server
367  */
368 int serv_putbuf(const StrBuf *string)
369 {
370 #ifdef SERV_TRACE
371         syslog(LOG_DEBUG, "%3d>>>%s\n", WC->serv_sock, ChrPtr(string));
372 #endif
373         FlushReadBuf();
374
375         if (!serv_write(ChrPtr(string), StrLength(string)))
376                 return 0;
377         return serv_write("\n", 1);
378 }
379
380
381 /*
382  *  convenience function to send stuff to the server
383  *  format the formatstring
384  *  ... the entities to insert into format 
385  */
386 int serv_printf(const char *format,...)
387 {
388         va_list arg_ptr;
389         char buf[SIZ];
390         size_t len;
391         int rc;
392
393         FlushReadBuf();
394
395         va_start(arg_ptr, format);
396         vsnprintf(buf, sizeof buf, format, arg_ptr);
397         va_end(arg_ptr);
398
399         len = strlen(buf);
400         buf[len++] = '\n';
401         buf[len] = '\0';
402         rc = serv_write(buf, len);
403 #ifdef SERV_TRACE
404         syslog(LOG_DEBUG, ">>>%s", buf);
405 #endif
406         return rc;
407 }
408
409
410 /*
411  * Read binary data from server into memory using a series of server READ commands.
412  * returns the read content as StrBuf
413  */
414 int serv_read_binary(StrBuf *Ret, size_t total_len, StrBuf *Buf) 
415 {
416         wcsession *WCC = WC;
417         size_t bytes_read = 0;
418         size_t this_block = 0;
419         int rc = 6;
420         int ServerRc = 6;
421
422         if (Ret == NULL) {
423                 return -1;
424         }
425
426         while ((bytes_read < total_len) && (ServerRc == 6)) {
427
428                 if (WCC->serv_sock==-1) {
429                         FlushStrBuf(Ret); 
430                         return -1; 
431                 }
432
433                 serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, bytes_read, total_len-bytes_read);
434                 if ( (rc = StrBuf_ServGetln(Buf) > 0) &&
435                      (ServerRc = GetServerStatus(Buf, NULL), ServerRc == 6) ) 
436                 {
437                         if (rc < 0)
438                                 return rc;
439                         StrBufCutLeft(Buf, 4);
440                         this_block = StrTol(Buf);
441                         rc = StrBuf_ServGetBLOBBuffered(Ret, this_block);
442                         if (rc < 0) {
443                                 syslog(LOG_INFO, "Server connection broken during download\n");
444                                 wc_backtrace(LOG_INFO);
445                                 if (WCC->serv_sock > 0) close(WCC->serv_sock);
446                                 WCC->serv_sock = (-1);
447                                 WCC->connected = 0;
448                                 WCC->logged_in = 0;
449                                 return rc;
450                         }
451                         bytes_read += rc;
452                 }
453         }
454
455         return StrLength(Ret);
456 }
457
458
459 int client_write(StrBuf *ThisBuf)
460 {
461         wcsession *WCC = WC;
462         const char *ptr, *eptr;
463         long count;
464         ssize_t res = 0;
465         fd_set wset;
466         int fdflags;
467
468         ptr = ChrPtr(ThisBuf);
469         count = StrLength(ThisBuf);
470         eptr = ptr + count;
471
472         fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
473
474         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
475                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
476                         FD_ZERO(&wset);
477                         FD_SET(WCC->Hdr->http_sock, &wset);
478                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
479                                 syslog(LOG_INFO, "client_write: Socket select failed (%s)\n", strerror(errno));
480                                 return -1;
481                         }
482                 }
483
484                 if ((WCC->Hdr->http_sock == -1) || 
485                     ((res = write(WCC->Hdr->http_sock, ptr, count)),
486                      (res == -1)))
487                 {
488                         syslog(LOG_INFO, "client_write: Socket write failed (%s)\n", strerror(errno));
489                         wc_backtrace(LOG_INFO);
490                         return -1;
491                 }
492                 count -= res;
493                 ptr += res;
494         }
495         return 0;
496 }
497
498
499 int
500 read_serv_chunk(
501
502         StrBuf *Buf,
503         size_t total_len,
504         size_t *bytes_read
505         )
506 {
507         int rc;
508         int ServerRc;
509         wcsession *WCC = WC;
510
511         serv_printf("READ "SIZE_T_FMT"|"SIZE_T_FMT, *bytes_read, total_len-(*bytes_read));
512         if ( (rc = StrBuf_ServGetln(Buf) > 0) &&
513              (ServerRc = GetServerStatus(Buf, NULL), ServerRc == 6) ) 
514         {
515                 size_t this_block = 0;
516
517                 if (rc < 0)
518                         return rc;
519
520                 StrBufCutLeft(Buf, 4);
521                 this_block = StrTol(Buf);
522                 rc = StrBuf_ServGetBLOBBuffered(WCC->WBuf, this_block);
523                 if (rc < 0) {
524                         syslog(LOG_INFO, "Server connection broken during download\n");
525                         wc_backtrace(LOG_INFO);
526                         if (WCC->serv_sock > 0) close(WCC->serv_sock);
527                         WCC->serv_sock = (-1);
528                         WCC->connected = 0;
529                         WCC->logged_in = 0;
530                         return rc;
531                 }
532                 *bytes_read += rc;
533         }
534         return 6;
535 }
536
537 static inline int send_http(StrBuf *Buf)
538 {
539 #ifdef HAVE_OPENSSL
540         if (is_https)
541                 return client_write_ssl(Buf);
542         else
543 #endif
544                 return client_write(Buf);
545 }
546 /*
547  * Read binary data from server into memory using a series of server READ commands.
548  * returns the read content as StrBuf
549  */
550 void serv_read_binary_to_http(StrBuf *MimeType, size_t total_len, int is_static, int detect_mime)
551 {
552         int ServerRc = 6;
553         wcsession *WCC = WC;
554         size_t bytes_read = 0;
555         int first = 1;
556         int client_con_state = 0;
557         int chunked = 0;
558         int is_gzip = 0;
559         const char *Err = NULL;
560         StrBuf *BufHeader = NULL;
561         StrBuf *Buf;
562         StrBuf *pBuf = NULL;
563         vStreamT *SC = NULL;
564         IOBuffer ReadBuffer;
565         IOBuffer WriteBuffer;
566         
567
568         Buf = NewStrBuf();
569
570         if (WCC->Hdr->HaveRange)
571         {
572                 WCC->Hdr->HaveRange++;
573                 WCC->Hdr->TotalBytes = total_len;
574                 /* open range? or beyound file border? correct the numbers. */
575                 if ((WCC->Hdr->RangeTil == -1) || (WCC->Hdr->RangeTil>= total_len))
576                         WCC->Hdr->RangeTil = total_len - 1;
577                 bytes_read = WCC->Hdr->RangeStart;
578                 total_len = WCC->Hdr->RangeTil;
579         }
580         else
581                 chunked = total_len > SIZ * 10; /* TODO: disallow for HTTP / 1.0 */
582
583         if (chunked)
584         {
585                 BufHeader = NewStrBuf();
586         }
587
588         if ((detect_mime != 0) && (bytes_read != 0))
589         {
590                 /* need to read first chunk to detect mime, though the client doesn't care */
591                 size_t bytes_read = 0;
592                 const char *CT;
593
594                 ServerRc = read_serv_chunk(
595                         Buf,
596                         total_len,
597                         &bytes_read);
598
599                 if (ServerRc != 6)
600                 {
601                         FreeStrBuf(&BufHeader);
602                         FreeStrBuf(&Buf);
603                         return;
604                 }
605                 CT = GuessMimeType(SKEY(WCC->WBuf));
606                 FlushStrBuf(WCC->WBuf);
607                 StrBufPlain(MimeType, CT, -1);
608                 CheckGZipCompressionAllowed(SKEY(MimeType));
609                 detect_mime = 0;
610                 FreeStrBuf(&Buf);
611         }
612
613         memset(&WriteBuffer, 0, sizeof(IOBuffer));
614         if (chunked && !DisableGzip && WCC->Hdr->HR.gzip_ok)
615         {
616                 is_gzip = 1;
617                 SC = StrBufNewStreamContext (eZLibEncode, &Err);
618                 if (SC == NULL) {
619                         syslog(LOG_ERR, "Error while initializing stream context: %s", Err);
620                         FreeStrBuf(&Buf);
621                         return;
622                 }
623
624                 memset(&ReadBuffer, 0, sizeof(IOBuffer));
625                 ReadBuffer.Buf = WCC->WBuf;
626
627                 WriteBuffer.Buf = NewStrBufPlain(NULL, SIZ*2);;
628                 pBuf = WriteBuffer.Buf;
629         }
630         else
631         {
632                 pBuf = WCC->WBuf;
633         }
634
635         if (!detect_mime)
636         {
637                 http_transmit_headers(ChrPtr(MimeType), is_static, chunked, is_gzip);
638                 
639                 if (send_http(WCC->HBuf) < 0)
640                 {
641                         FreeStrBuf(&Buf);
642                         FreeStrBuf(&WriteBuffer.Buf);
643                         FreeStrBuf(&BufHeader);
644                         if (StrBufDestroyStreamContext(eZLibEncode, &SC, &Err) && Err) {
645                                 syslog(LOG_ERR, "Error while destroying stream context: %s", Err);
646                         }
647                         return;
648                 }
649         }
650
651         while ((bytes_read < total_len) &&
652                (ServerRc == 6) &&
653                (client_con_state == 0))
654         {
655
656                 if (WCC->serv_sock==-1) {
657                         FlushStrBuf(WCC->WBuf); 
658                         FreeStrBuf(&Buf);
659                         FreeStrBuf(&WriteBuffer.Buf);
660                         FreeStrBuf(&BufHeader);
661                         StrBufDestroyStreamContext(eZLibEncode, &SC, &Err);
662                         if (StrBufDestroyStreamContext(eZLibEncode, &SC, &Err) && Err) {
663                                 syslog(LOG_ERR, "Error while destroying stream context: %s", Err);
664                         }
665                         return;
666                 }
667
668                 ServerRc = read_serv_chunk(
669                         Buf,
670                         total_len,
671                         &bytes_read);
672                 if (ServerRc != 6)
673                         break;
674
675                 if (detect_mime)
676                 {
677                         const char *CT;
678                         detect_mime = 0;
679                         
680                         CT = GuessMimeType(SKEY(WCC->WBuf));
681                         StrBufPlain(MimeType, CT, -1);
682                         if (is_gzip) {
683                                 CheckGZipCompressionAllowed(SKEY(MimeType));
684                                 is_gzip = WCC->Hdr->HR.gzip_ok;
685                         }
686                         http_transmit_headers(ChrPtr(MimeType), is_static, chunked, is_gzip);
687                         
688                         client_con_state = send_http(WCC->HBuf);
689                 }
690
691                 if (is_gzip)
692                 {
693                         int done = (bytes_read == total_len);
694                         while ((IOBufferStrLength(&ReadBuffer) > 0) && (client_con_state == 0)) {
695                                 int rc;
696
697                                 do {
698                                         rc = StrBufStreamTranscode(eZLibEncode, &WriteBuffer, &ReadBuffer, NULL, -1, SC, done, &Err);
699
700                                         if (StrLength (pBuf) > 0) {
701                                                 StrBufPrintf(BufHeader, "%s%x\r\n", 
702                                                      (first)?"":"\r\n",
703                                                              StrLength (pBuf));
704                                                 first = 0;
705                                                 client_con_state = send_http(BufHeader);
706                                                 if (client_con_state == 0) {
707                                                         client_con_state = send_http(pBuf);
708                                                 }
709                                                 FlushStrBuf(pBuf);
710                                         }
711                                 } while ((rc == 1) && (StrLength(pBuf) > 0));
712                         }
713                         FlushStrBuf(WCC->WBuf);
714                 }
715                 else {
716                         if ((chunked) && (client_con_state == 0))
717                         {
718                                 StrBufPrintf(BufHeader, "%s%x\r\n", 
719                                              (first)?"":"\r\n",
720                                              StrLength (pBuf));
721                                 first = 0;
722                                 client_con_state = send_http(BufHeader);
723                         }
724
725                         if (client_con_state == 0)
726                                 client_con_state = send_http(pBuf);
727
728                         FlushStrBuf(pBuf);
729                 }
730         }
731
732         if (SC && StrBufDestroyStreamContext(eZLibEncode, &SC, &Err) && Err) {
733                 syslog(LOG_ERR, "Error while destroying stream context: %s", Err);
734         }
735         FreeStrBuf(&WriteBuffer.Buf);
736         if ((chunked) && (client_con_state == 0))
737         {
738                 StrBufPlain(BufHeader, HKEY("\r\n0\r\n\r\n"));
739                 if (send_http(BufHeader) < 0)
740                 {
741                         FreeStrBuf(&Buf);
742                         FreeStrBuf(&BufHeader);
743                         return;
744                 }
745         }
746         FreeStrBuf(&BufHeader);
747         FreeStrBuf(&Buf);
748 }
749
750 int ClientGetLine(ParsedHttpHdrs *Hdr, StrBuf *Target)
751 {
752         const char *Error;
753 #ifdef HAVE_OPENSSL
754         const char *pch, *pchs;
755         int rlen, len, retval = 0;
756
757         if (is_https) {
758                 int ntries = 0;
759                 if (StrLength(Hdr->ReadBuf) > 0)
760                 {
761                         pchs = ChrPtr(Hdr->ReadBuf);
762                         pch = strchr(pchs, '\n');
763                         if (pch != NULL) {
764                                 rlen = 0;
765                                 len = pch - pchs;
766                                 if (len > 0 && (*(pch - 1) == '\r') )
767                                         rlen ++;
768                                 StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
769                                 StrBufCutLeft(Hdr->ReadBuf, len + 1);
770                                 return len - rlen;
771                         }
772                 }
773
774                 while (retval == 0) { 
775                                 pch = NULL;
776                                 pchs = ChrPtr(Hdr->ReadBuf);
777                                 if (*pchs != '\0')
778                                         pch = strchr(pchs, '\n');
779                                 if (pch == NULL) {
780                                         retval = client_read_sslbuffer(Hdr->ReadBuf, SLEEPING);
781                                         pchs = ChrPtr(Hdr->ReadBuf);
782                                         pch = strchr(pchs, '\n');
783                                         if (pch == NULL)
784                                                 retval = 0;
785                                 }
786                                 if (retval == 0) {
787                                         sleeeeeeeeeep(1);
788                                         ntries ++;
789                                 }
790                                 if (ntries > 10)
791                                         return 0;
792                 }
793                 if ((retval > 0) && (pch != NULL)) {
794                         rlen = 0;
795                         len = pch - pchs;
796                         if (len > 0 && (*(pch - 1) == '\r') )
797                                 rlen ++;
798                         StrBufSub(Target, Hdr->ReadBuf, 0, len - rlen);
799                         StrBufCutLeft(Hdr->ReadBuf, len + 1);
800                         return len - rlen;
801
802                 }
803                 else 
804                         return -1;
805         }
806         else 
807 #endif
808                 return StrBufTCP_read_buffered_line_fast(Target, 
809                                                          Hdr->ReadBuf,
810                                                          &Hdr->Pos,
811                                                          &Hdr->http_sock,
812                                                          5,
813                                                          1,
814                                                          &Error);
815 }
816
817
818 /* 
819  * This is a generic function to set up a master socket for listening on
820  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
821  *
822  * ip_addr      IP address to bind
823  * port_number  port number to bind
824  * queue_len    number of incoming connections to allow in the queue
825  */
826 int webcit_tcp_server(const char *ip_addr, int port_number, int queue_len)
827 {
828         const char *ipv4broadcast = "0.0.0.0";
829         int IsDefault = 0;
830         struct protoent *p;
831         struct sockaddr_in6 sin6;
832         struct sockaddr_in sin4;
833         int s, i, b;
834         int ip_version = 6;
835
836 retry:
837         memset(&sin6, 0, sizeof(sin6));
838         memset(&sin4, 0, sizeof(sin4));
839         sin6.sin6_family = AF_INET6;
840         sin4.sin_family = AF_INET;
841
842         if (    (ip_addr == NULL)                                                       /* any IPv6 */
843                 || (IsEmptyStr(ip_addr))
844                 || (!strcmp(ip_addr, "*"))
845         ) {
846                 IsDefault = 1;
847                 ip_version = 6;
848                 sin6.sin6_addr = in6addr_any;
849         }
850         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
851         {
852                 ip_version = 4;
853                 sin4.sin_addr.s_addr = INADDR_ANY;
854         }
855         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
856         {
857                 ip_version = 4;
858                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
859                         syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
860                         return (-WC_EXIT_BIND);
861                 }
862         }
863         else                                                                            /* specific IPv6 */
864         {
865                 ip_version = 6;
866                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
867                         syslog(LOG_WARNING, "Error binding to [%s] : %s\n", ip_addr, strerror(errno));
868                         return (-WC_EXIT_BIND);
869                 }
870         }
871
872         if (port_number == 0) {
873                 syslog(LOG_WARNING, "Cannot start: no port number specified.\n");
874                 return (-WC_EXIT_BIND);
875         }
876         sin6.sin6_port = htons((u_short) port_number);
877         sin4.sin_port = htons((u_short) port_number);
878
879         p = getprotobyname("tcp");
880
881         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
882         if (s < 0) {
883                 if (IsDefault && (errno == EAFNOSUPPORT))
884                 {
885                         s = 0;
886                         ip_addr = ipv4broadcast;
887                         goto retry;
888                 }
889                 syslog(LOG_WARNING, "Can't create a listening socket: %s\n", strerror(errno));
890                 return (-WC_EXIT_BIND);
891         }
892         /* Set some socket options that make sense. */
893         i = 1;
894         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
895
896         if (ip_version == 6) {
897                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
898         }
899         else {
900                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
901         }
902
903         if (b < 0) {
904                 syslog(LOG_ERR, "Can't bind: %s\n", strerror(errno));
905                 close(s);
906                 return (-WC_EXIT_BIND);
907         }
908
909         if (listen(s, queue_len) < 0) {
910                 syslog(LOG_ERR, "Can't listen: %s\n", strerror(errno));
911                 close(s);
912                 return (-WC_EXIT_BIND);
913         }
914         return (s);
915 }
916
917
918 /*
919  * Create a Unix domain socket and listen on it
920  * sockpath - file name of the unix domain socket
921  * queue_len - Number of incoming connections to allow in the queue
922  */
923 int webcit_uds_server(char *sockpath, int queue_len) {
924         struct sockaddr_un addr;
925         int s;
926         int i;
927         int actual_queue_len;
928
929         actual_queue_len = queue_len;
930         if (actual_queue_len < 5) actual_queue_len = 5;
931
932         i = unlink(sockpath);
933         if ((i != 0) && (errno != ENOENT)) {
934                 syslog(LOG_WARNING, "webcit: can't unlink %s: %s\n",
935                         sockpath, strerror(errno));
936                 return (-WC_EXIT_BIND);
937         }
938
939         memset(&addr, 0, sizeof(addr));
940         addr.sun_family = AF_UNIX;
941         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
942
943         s = socket(AF_UNIX, SOCK_STREAM, 0);
944         if (s < 0) {
945                 syslog(LOG_WARNING, "webcit: Can't create a unix domain socket: %s\n", strerror(errno));
946                 return (-WC_EXIT_BIND);
947         }
948
949         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
950                 syslog(LOG_WARNING, "webcit: Can't bind: %s\n", strerror(errno));
951                 close(s);
952                 return (-WC_EXIT_BIND);
953         }
954
955         if (listen(s, actual_queue_len) < 0) {
956                 syslog(LOG_WARNING, "webcit: Can't listen: %s\n", strerror(errno));
957                 close(s);
958                 return (-WC_EXIT_BIND);
959         }
960
961         chmod(sockpath, 0777);
962         return(s);
963 }
964
965
966 /*
967  * Read data from the client socket.
968  *
969  * sock         socket fd to read from
970  * buf          buffer to read into 
971  * bytes        number of bytes to read
972  * timeout      Number of seconds to wait before timing out
973  *
974  * Possible return values:
975  *      1       Requested number of bytes has been read.
976  *      0       Request timed out.
977  *      -1      Connection is broken, or other error.
978  */
979 int client_read_to(ParsedHttpHdrs *Hdr, StrBuf *Target, int bytes, int timeout) {
980         const char *Error;
981         int retval = 0;
982
983 #ifdef HAVE_OPENSSL
984         if (is_https) {
985                 long bufremain = 0;
986                 long baselen;
987
988                 baselen = StrLength(Target);
989
990                 if (Hdr->Pos == NULL) {
991                         Hdr->Pos = ChrPtr(Hdr->ReadBuf);
992                 }
993
994                 if (StrLength(Hdr->ReadBuf) > 0) {
995                         bufremain = StrLength(Hdr->ReadBuf) - (Hdr->Pos - ChrPtr(Hdr->ReadBuf));
996                         
997                         if (bytes < bufremain)
998                                 bufremain = bytes;
999                         StrBufAppendBufPlain(Target, Hdr->Pos, bufremain, 0);
1000                         StrBufCutLeft(Hdr->ReadBuf, bufremain);
1001                 }
1002
1003                 if (bytes > bufremain) {
1004                         while ((StrLength(Hdr->ReadBuf) + StrLength(Target) < bytes + baselen) &&
1005                                (retval >= 0))
1006                                 retval = client_read_sslbuffer(Hdr->ReadBuf, timeout);
1007                         if (retval >= 0) {
1008                                 StrBufAppendBuf(Target, Hdr->ReadBuf, 0); /* todo: Buf > bytes? */
1009                                 return 1;
1010                         }
1011                         else {
1012                                 syslog(LOG_INFO, "client_read_ssl() failed\n");
1013                                 return -1;
1014                         }
1015                 }
1016                 else 
1017                         return 1;
1018         }
1019 #endif
1020         retval = StrBufReadBLOBBuffered(Target, 
1021                                         Hdr->ReadBuf, 
1022                                         &Hdr->Pos, 
1023                                         &Hdr->http_sock, 
1024                                         1, 
1025                                         bytes,
1026                                         O_TERM,
1027                                         &Error);
1028         if (retval < 0) {
1029                 syslog(LOG_INFO, "client_read() failed: %s\n", Error);
1030                 wc_backtrace(LOG_DEBUG);
1031                 return retval;
1032         }
1033
1034         return 1;
1035 }
1036
1037
1038 /*
1039  * Begin buffering HTTP output so we can transmit it all in one write operation later.
1040  */
1041 void begin_burst(void)
1042 {
1043         if (WC->WBuf == NULL) {
1044                 WC->WBuf = NewStrBufPlain(NULL, 32768);
1045         }
1046 }
1047
1048
1049 /*
1050  * Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
1051  */
1052 long end_burst(void)
1053 {
1054         wcsession *WCC = WC;
1055         const char *ptr, *eptr;
1056         long count;
1057         ssize_t res = 0;
1058         fd_set wset;
1059         int fdflags;
1060
1061         if (!DisableGzip && (WCC->Hdr->HR.gzip_ok))
1062         {
1063                 if (CompressBuffer(WCC->WBuf) > 0)
1064                         hprintf("Content-encoding: gzip\r\n");
1065                 else {
1066                         syslog(LOG_ALERT, "Compression failed: %d [%s] sending uncompressed\n", errno, strerror(errno));
1067                         wc_backtrace(LOG_INFO);
1068                 }
1069         }
1070
1071         if (WCC->WFBuf != NULL) {
1072                 WildFireSerializePayload(WCC->WFBuf, WCC->HBuf, &WCC->Hdr->nWildfireHeaders, NULL);
1073                 FreeStrBuf(&WCC->WFBuf);
1074         }
1075
1076         if (WCC->Hdr->HR.prohibit_caching)
1077                 hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1078         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
1079
1080         ptr = ChrPtr(WCC->HBuf);
1081         count = StrLength(WCC->HBuf);
1082         eptr = ptr + count;
1083
1084 #ifdef HAVE_OPENSSL
1085         if (is_https) {
1086                 client_write_ssl(WCC->HBuf);
1087                 client_write_ssl(WCC->WBuf);
1088                 return (count);
1089         }
1090 #endif
1091
1092         if (WCC->Hdr->http_sock == -1) {
1093                 return -1;
1094         }
1095         fdflags = fcntl(WC->Hdr->http_sock, F_GETFL);
1096
1097         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
1098                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1099                         FD_ZERO(&wset);
1100                         FD_SET(WCC->Hdr->http_sock, &wset);
1101                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
1102                                 syslog(LOG_DEBUG, "client_write: Socket select failed (%s)\n", strerror(errno));
1103                                 return -1;
1104                         }
1105                 }
1106
1107                 if ((WCC->Hdr->http_sock == -1) || 
1108                     (res = write(WCC->Hdr->http_sock, 
1109                                  ptr,
1110                                  count)) == -1) {
1111                         syslog(LOG_DEBUG, "client_write: Socket write failed (%s)\n", strerror(errno));
1112                         wc_backtrace(LOG_INFO);
1113                         return res;
1114                 }
1115                 count -= res;
1116                 ptr += res;
1117         }
1118
1119         ptr = ChrPtr(WCC->WBuf);
1120         count = StrLength(WCC->WBuf);
1121         eptr = ptr + count;
1122
1123         while ((ptr < eptr) && (WCC->Hdr->http_sock != -1)) {
1124                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1125                         FD_ZERO(&wset);
1126                         FD_SET(WCC->Hdr->http_sock, &wset);
1127                         if (select(WCC->Hdr->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
1128                                 syslog(LOG_INFO, "client_write: Socket select failed (%s)\n", strerror(errno));
1129                                 return -1;
1130                         }
1131                 }
1132
1133                 if ((WCC->Hdr->http_sock == -1) || 
1134                     (res = write(WCC->Hdr->http_sock, 
1135                                  ptr,
1136                                  count)) == -1) {
1137                         syslog(LOG_INFO, "client_write: Socket write failed (%s)\n", strerror(errno));
1138                         wc_backtrace(LOG_INFO);
1139                         return res;
1140                 }
1141                 count -= res;
1142                 ptr += res;
1143         }
1144
1145         return StrLength(WCC->WBuf);
1146 }
1147
1148
1149 /*
1150  * lingering_close() a`la Apache. see
1151  * http://httpd.apache.org/docs/2.0/misc/fin_wait_2.html for rationale
1152  */
1153 int lingering_close(int fd)
1154 {
1155         char buf[SIZ];
1156         int i;
1157         fd_set set;
1158         struct timeval tv, start;
1159
1160         gettimeofday(&start, NULL);
1161         if (fd == -1)
1162                 return -1;
1163         shutdown(fd, 1);
1164         do {
1165                 do {
1166                         gettimeofday(&tv, NULL);
1167                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
1168                         tv.tv_usec = start.tv_usec - tv.tv_usec;
1169                         if (tv.tv_usec < 0) {
1170                                 tv.tv_sec--;
1171                                 tv.tv_usec += 1000000;
1172                         }
1173                         FD_ZERO(&set);
1174                         FD_SET(fd, &set);
1175                         i = select(fd + 1, &set, NULL, NULL, &tv);
1176                 } while (i == -1 && errno == EINTR);
1177
1178                 if (i <= 0)
1179                         break;
1180
1181                 i = read(fd, buf, sizeof buf);
1182         } while (i != 0 && (i != -1 || errno == EINTR));
1183
1184         return close(fd);
1185 }
1186
1187 void
1188 HttpNewModule_TCPSOCKETS
1189 (ParsedHttpHdrs *httpreq)
1190 {
1191
1192         httpreq->ReadBuf = NewStrBufPlain(NULL, SIZ * 4);
1193 }
1194
1195 void
1196 HttpDetachModule_TCPSOCKETS
1197 (ParsedHttpHdrs *httpreq)
1198 {
1199
1200         FlushStrBuf(httpreq->ReadBuf);
1201         ReAdjustEmptyBuf(httpreq->ReadBuf, 4 * SIZ, SIZ);
1202 }
1203
1204 void
1205 HttpDestroyModule_TCPSOCKETS
1206 (ParsedHttpHdrs *httpreq)
1207 {
1208
1209         FreeStrBuf(&httpreq->ReadBuf);
1210 }
1211
1212
1213 void
1214 SessionNewModule_TCPSOCKETS
1215 (wcsession *sess)
1216 {
1217         sess->CLineBuf = NewStrBuf();
1218         sess->MigrateReadLineBuf = NewStrBuf();
1219 }
1220
1221 void 
1222 SessionDestroyModule_TCPSOCKETS
1223 (wcsession *sess)
1224 {
1225         FreeStrBuf(&sess->CLineBuf);
1226         FreeStrBuf(&sess->ReadBuf);
1227         sess->connected = 0;
1228         sess->ReadPos = NULL;
1229         FreeStrBuf(&sess->MigrateReadLineBuf);
1230         if (sess->serv_sock > 0) {
1231                 syslog(LOG_DEBUG, "Closing socket %d", sess->serv_sock);
1232                 close(sess->serv_sock);
1233         }
1234         sess->serv_sock = -1;
1235 }