+static inline int send_http(StrBuf *Buf)
+{
+#ifdef HAVE_OPENSSL
+ if (is_https)
+ return client_write_ssl(Buf);
+ else
+#endif
+ return client_write(Buf);
+}
+/*
+ * Read binary data from server into memory using a series of server READ commands.
+ * returns the read content as StrBuf
+ */
+void serv_read_binary_to_http(StrBuf *MimeType, size_t total_len, int is_static, int detect_mime)
+{
+ int ServerRc = 6;
+ wcsession *WCC = WC;
+ size_t bytes_read = 0;
+ int first = 1;
+ int client_con_state = 0;
+ int chunked = 0;
+ StrBuf *BufHeader = NULL;
+ StrBuf *Buf;
+
+ Buf = NewStrBuf();
+
+ if (WCC->Hdr->HaveRange)
+ {
+ WCC->Hdr->HaveRange++;
+ WCC->Hdr->TotalBytes = total_len;
+ /* open range? or beyound file border? correct the numbers. */
+ if ((WCC->Hdr->RangeTil == -1) || (WCC->Hdr->RangeTil>= total_len))
+ WCC->Hdr->RangeTil = total_len - 1;
+ bytes_read = WCC->Hdr->RangeStart;
+ total_len = WCC->Hdr->RangeTil;
+ }
+ else
+ chunked = total_len > SIZ * 10; /* TODO: disallow for HTTP / 1.0 */
+
+ if (chunked)
+ {
+ BufHeader=NewStrBuf();
+ }
+
+ if ((detect_mime != 0) && (bytes_read != 0))
+ {
+ /* need to read first chunk to detect mime, though the client doesn't care */
+ size_t bytes_read = 0;
+ const char *CT;
+
+ ServerRc = read_serv_chunk(
+ Buf,
+ total_len,
+ &bytes_read);
+
+ if (ServerRc != 6)
+ {
+ FreeStrBuf(&Buf);
+ return;
+ }
+ CT = GuessMimeType(SKEY(WCC->WBuf));
+ FlushStrBuf(WCC->WBuf);
+ StrBufPlain(MimeType, CT, -1);
+ detect_mime = 0;
+ FreeStrBuf(&Buf);
+ }
+
+ if (!detect_mime)
+ {
+ http_transmit_headers(ChrPtr(MimeType), is_static, chunked);
+
+ if (send_http(WCC->HBuf) < 0)
+ {
+ FreeStrBuf(&Buf);
+ return;
+ }
+ }
+
+ while ((bytes_read < total_len) &&
+ (ServerRc == 6) &&
+ (client_con_state == 0))
+ {
+
+ if (WCC->serv_sock==-1) {
+ FlushStrBuf(WCC->WBuf);
+ FreeStrBuf(&Buf);
+ return;
+ }
+
+ ServerRc = read_serv_chunk(
+ Buf,
+ total_len,
+ &bytes_read);
+ if (ServerRc != 6)
+ break;
+
+ if (detect_mime)
+ {
+ const char *CT;
+ detect_mime = 0;
+
+ CT = GuessMimeType(SKEY(WCC->WBuf));
+ StrBufPlain(MimeType, CT, -1);
+ http_transmit_headers(ChrPtr(MimeType), is_static, chunked);
+
+ client_con_state = send_http(WCC->HBuf);
+ }
+
+ if ((chunked) && (client_con_state == 0))
+ {
+ StrBufPrintf(BufHeader, "%s%x\r\n",
+ (first)?"":"\r\n",
+ StrLength (WCC->WBuf));
+ first = 0;
+ client_con_state = send_http(BufHeader);
+ }
+
+ if (client_con_state == 0)
+ client_con_state = send_http(WCC->WBuf);
+
+ FlushStrBuf(WCC->WBuf);
+ }
+
+ if ((chunked) && (client_con_state == 0))
+ {
+ StrBufPlain(BufHeader, HKEY("\r\n0\r\n\r\n"));
+ if (send_http(BufHeader) < 0)
+ {
+ FreeStrBuf(&Buf);
+ return;
+ }
+ }
+ FreeStrBuf(&Buf);
+}