diff --git a/uppsrc/Core/Http.cpp b/uppsrc/Core/Http.cpp index 3e3c4a86e..7ee928c8a 100644 --- a/uppsrc/Core/Http.cpp +++ b/uppsrc/Core/Http.cpp @@ -1,704 +1,707 @@ -#include "Core.h" - -NAMESPACE_UPP - -bool HttpRequest_Trace__; - -#define LLOG(x) do { if(HttpRequest_Trace__) RLOG(x); } while(0) - -#ifdef _DEBUG -_DBG_ -// #define ENDZIP -#endif - -void HttpRequest::Trace(bool b) -{ - HttpRequest_Trace__ = b; -} - -void HttpRequest::Init() -{ - port = 0; - proxy_port = 0; - ssl_proxy_port = 0; - max_header_size = 1000000; - max_content_size = 10000000; - max_redirects = 5; - max_retries = 3; - force_digest = false; - std_headers = true; - hasurlvar = false; - method = METHOD_GET; - phase = BEGIN; - redirect_count = 0; - retry_count = 0; - gzip = false; - WhenContent = callback(this, &HttpRequest::ContentOut); - chunk = 4096; - timeout = 120000; - ssl = false; -} - -HttpRequest::HttpRequest() -{ - Init(); -} - -HttpRequest::HttpRequest(const char *url) -{ - Init(); - Url(url); -} - -HttpRequest& HttpRequest::Url(const char *u) -{ - ssl = memcmp(u, "https", 5) == 0; - const char *t = u; - while(*t && *t != '?') - if(*t++ == '/' && *t == '/') { - u = ++t; - break; - } - t = u; - while(*u && *u != ':' && *u != '/' && *u != '?') - u++; - if(*u == '?' && u[1]) - hasurlvar = true; - host = String(t, u); - port = 0; - if(*u == ':') - port = ScanInt(u + 1, &u); - path = u; - int q = path.Find('#'); - if(q >= 0) - path.Trim(q); - return *this; -} - -static -void sParseProxyUrl(const char *p, String& proxy_host, int proxy_port) -{ - const char *t = p; - while(*p && *p != ':') - p++; - proxy_host = String(t, p); - if(*p++ == ':' && IsDigit(*p)) - proxy_port = ScanInt(p); -} - -HttpRequest& HttpRequest::Proxy(const char *url) -{ - proxy_port = 80; - sParseProxyUrl(url, proxy_host, proxy_port); - return *this; -} - -HttpRequest& HttpRequest::SSLProxy(const char *url) -{ - ssl_proxy_port = 8080; - sParseProxyUrl(url, ssl_proxy_host, ssl_proxy_port); - return *this; -} - -HttpRequest& HttpRequest::Post(const char *id, const String& data) -{ - POST(); - if(postdata.GetCount()) - postdata << '&'; - postdata << id << '=' << UrlEncode(data); - return *this; -} - -HttpRequest& HttpRequest::UrlVar(const char *id, const String& data) -{ - int c = *path.Last(); - if(hasurlvar && c != '&') - path << '&'; - if(!hasurlvar && c != '?') - path << '?'; - path << id << '=' << UrlEncode(data); - hasurlvar = true; - return *this; -} - -String HttpRequest::CalculateDigest(const String& authenticate) const -{ - const char *p = authenticate; - String realm, qop, nonce, opaque; - while(*p) { - if(!IsAlNum(*p)) { - p++; - continue; - } - else { - const char *b = p; - while(IsAlNum(*p)) - p++; - String var = ToLower(String(b, p)); - String value; - while(*p && (byte)*p <= ' ') - p++; - if(*p == '=') { - p++; - while(*p && (byte)*p <= ' ') - p++; - if(*p == '\"') { - p++; - while(*p && *p != '\"') - if(*p != '\\' || *++p) - value.Cat(*p++); - if(*p == '\"') - p++; - } - else { - b = p; - while(*p && *p != ',' && (byte)*p > ' ') - p++; - value = String(b, p); - } - } - if(var == "realm") - realm = value; - else if(var == "qop") - qop = value; - else if(var == "nonce") - nonce = value; - else if(var == "opaque") - opaque = value; - } - } - String hv1, hv2; - hv1 << username << ':' << realm << ':' << password; - String ha1 = MD5String(hv1); - hv2 << (method == METHOD_GET ? "GET" : method == METHOD_PUT ? "PUT" : method == METHOD_POST ? "POST" : "READ") - << ':' << path; - String ha2 = MD5String(hv2); - int nc = 1; - String cnonce = FormatIntHex(Random(), 8); - String hv; - hv << ha1 - << ':' << nonce - << ':' << FormatIntHex(nc, 8) - << ':' << cnonce - << ':' << qop << ':' << ha2; - String ha = MD5String(hv); - String auth; - auth << "username=" << AsCString(username) - << ", realm=" << AsCString(realm) - << ", nonce=" << AsCString(nonce) - << ", uri=" << AsCString(path) - << ", qop=" << AsCString(qop) - << ", nc=" << AsCString(FormatIntHex(nc, 8)) - << ", cnonce=" << cnonce - << ", response=" << AsCString(ha); - if(!IsNull(opaque)) - auth << ", opaque=" << AsCString(opaque); - return auth; -} - -HttpRequest& HttpRequest::Header(const char *id, const String& data) -{ - request_headers << id << ": " << data << "\r\n"; - return *this; -} - -void HttpRequest::HttpError(const char *s) -{ - if(IsError()) - return; - error = NFormat(t_("%s:%d: ") + String(s), host, port); - LLOG("HTTP ERROR: " << error); - Close(); -} - -void HttpRequest::StartPhase(int s) -{ - phase = s; - LLOG("Starting status " << s << " '" << GetPhaseName() << "', url: " << host); - data.Clear(); -} - -void HttpRequest::New() -{ - ClearError(); - ClearAbort(); - phase = BEGIN; -} - -bool HttpRequest::Do() -{ - int c1, c2; - switch(phase) { - case BEGIN: - retry_count = 0; - redirect_count = 0; - start_time = msecs(); - case START: - Start(); - break; - case DNS: - Dns(); - break; - case SSLPROXYREQUEST: - if(SendingData()) - break; - StartPhase(SSLPROXYRESPONSE); - break; - case SSLPROXYRESPONSE: - if(ReadingHeader()) - break; - ProcessSSLProxyResponse(); - break; - case SSLHANDSHAKE: - if(SSLHandshake()) - break; - StartRequest(); - break; - case REQUEST: - if(SendingData()) - break; - StartPhase(HEADER); - break; - case HEADER: - if(ReadingHeader()) - break; - StartBody(); - break; - case BODY: - if(ReadingBody()) - break; - Finish(); - break; - case CHUNK_HEADER: - ReadingChunkHeader(); - break; - case CHUNK_BODY: - if(ReadingBody()) - break; - c1 = TcpSocket::Get(); - c2 = TcpSocket::Get(); - if(c1 != '\r' || c2 != '\n') - HttpError("missing ending CRLF in chunked transfer"); - StartPhase(CHUNK_HEADER); - break; - case TRAILER: - if(ReadingHeader()) - break; - header.Parse(data); - Finish(); - break; - case FINISHED: - case FAILED: - WhenDo(); - return false; - default: - NEVER(); - } - - if(phase != FAILED) - if(IsSocketError() || IsError()) - phase = FAILED; - else - if(msecs(start_time) >= timeout) { - HttpError("connection timed out"); - phase = FAILED; - } - else - if(IsAbort()) { - HttpError("connection was aborted"); - phase = FAILED; - } - - if(phase == FAILED) { - if(retry_count++ < max_retries) { - LLOG("HTTP retry on error " << GetErrorDesc()); - start_time = msecs(); - StartPhase(START); - } - } - WhenDo(); - return phase != FINISHED && phase != FAILED; -} - -void HttpRequest::Start() -{ - Close(); - ClearError(); - gzip = false; - z.Clear(); - header.Clear(); - status_code = 0; - reason_phrase.Clear(); - WhenStart(); - - bool use_proxy = !IsNull(ssl ? ssl_proxy_host : proxy_host); - - int p = use_proxy ? (ssl ? ssl_proxy_port : proxy_port) : port; - if(!p) - p = ssl ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT; - String h = use_proxy ? ssl ? ssl_proxy_host : proxy_host : host; - - StartPhase(DNS); - if(IsNull(GetTimeout())) { - if(WhenWait) { - addrinfo.Start(h, p); - while(addrinfo.InProgress()) { - Sleep(GetWaitStep()); - WhenWait(); - } - } - else - addrinfo.Execute(h, p); - StartConnect(); - } - else - addrinfo.Start(h, p); -} - -void HttpRequest::Dns() -{ - for(int i = 0; i <= Nvl(GetTimeout(), INT_MAX); i++) { - if(!addrinfo.InProgress()) { - StartConnect(); - return; - } - Sleep(1); - } -} - -void HttpRequest::StartConnect() -{ - if(!Connect(addrinfo)) - return; - if(ssl && ssl_proxy_host.GetCount()) { - StartPhase(SSLPROXYREQUEST); - String host_port = host; - if(port) - host_port << ':' << port; - else - host_port << ":443"; - data << "CONNECT " << host_port << " HTTP/1.1\r\n" - << "Host: " << host_port << "\r\n"; - if(!IsNull(ssl_proxy_username)) - data << "Proxy-Authorization: Basic " - << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n"; - data << "\r\n"; - count = 0; - LLOG("HTTPS proxy request:\n" << data); - } - else - AfterConnect(); -} - -void HttpRequest::ProcessSSLProxyResponse() -{ - LLOG("HTTPS proxy response:\n" << data); - int q = min(data.Find('\r'), data.Find('\n')); - if(q >= 0) - data.Trim(q); - if(!data.StartsWith("HTTP") || data.Find(" 2") < 0) { - HttpError("Invalid proxy reply: " + data); - return; - } - AfterConnect(); -} - -void HttpRequest::AfterConnect() -{ - if(ssl && !StartSSL()) - return; - if(ssl) - StartPhase(SSLHANDSHAKE); - else - StartRequest(); -} - -void HttpRequest::StartRequest() -{ - StartPhase(REQUEST); - count = 0; - String ctype = contenttype; - if((method == METHOD_POST || method == METHOD_PUT) && IsNull(ctype)) - ctype = "application/x-www-form-urlencoded"; - switch(method) { - case METHOD_GET: data << "GET "; break; - case METHOD_POST: data << "POST "; break; - case METHOD_PUT: data << "PUT "; break; - case METHOD_HEAD: data << "HEAD "; break; - default: NEVER(); // invalid method - } - String host_port = host; - if(port) - host_port << ':' << port; - String url; - url << "http://" << host_port << Nvl(path, "/"); - if(!IsNull(proxy_host) && !ssl) - data << url; - else - data << Nvl(path, "/"); - data << " HTTP/1.1\r\n"; - if(std_headers) { - data << "URL: " << url << "\r\n" - << "Host: " << host_port << "\r\n" - << "Connection: close\r\n" - << "Accept: " << Nvl(accept, "*/*") << "\r\n" - << "Accept-Encoding: gzip\r\n" - << "User-Agent: " << Nvl(agent, "U++ HTTP request") << "\r\n"; - if(postdata.GetCount()) - data << "Content-Length: " << postdata.GetCount() << "\r\n"; - if(ctype.GetCount()) - data << "Content-Type: " << ctype << "\r\n"; - } - if(!IsNull(proxy_host) && !IsNull(proxy_username)) - data << "Proxy-Authorization: Basic " << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n"; - if(!IsNull(digest)) - data << "Authorization: Digest " << digest << "\r\n"; - else - if(!force_digest && (!IsNull(username) || !IsNull(password))) - data << "Authorization: Basic " << Base64Encode(username + ":" + password) << "\r\n"; - data << request_headers << "\r\n" << postdata; // !!! POST PHASE !!! - LLOG("HTTP REQUEST " << host << ":" << port); - LLOG("HTTP request:\n" << data); -} - -bool HttpRequest::SendingData() -{ - for(;;) { - int n = min(2048, data.GetLength() - count); - n = TcpSocket::Put(~data + count, n); - if(n == 0) - break; - count += n; - } - return count < data.GetLength(); -} - -bool HttpRequest::ReadingHeader() -{ - for(;;) { - int c = TcpSocket::Get(); - if(c < 0) - return !IsEof(); - else - data.Cat(c); - if(data.GetCount() > 3) { - const char *h = data.Last(); - if(h[0] == '\n' && (h[-1] == '\r' && h[-2] == '\n' || h[-1] == '\n')) - return false; - } - if(data.GetCount() > max_header_size) { - HttpError("HTTP header exceeded " + AsString(max_header_size)); - return true; - } - } -} - -void HttpRequest::ReadingChunkHeader() -{ - for(;;) { - int c = TcpSocket::Get(); - if(c < 0) - break; - else - if(c == '\n') { - int n = ScanInt(~data, NULL, 16); - LLOG("HTTP Chunk header: 0x" << data << " = " << n); - if(IsNull(n)) { - HttpError("invalid chunk header"); - break; - } - if(n == 0) { - StartPhase(TRAILER); - break; - } - count += n; - StartPhase(CHUNK_BODY); - break; - } - if(c != '\r') - data.Cat(c); - } -} - -String HttpRequest::GetRedirectUrl() -{ - String redirect_url = TrimLeft(header["location"]); - if(redirect_url.StartsWith("http://") || redirect_url.StartsWith("https://")) - return redirect_url; - String h = (ssl ? "https://" : "http://") + host; - if(*redirect_url != '/') - h << '/'; - h << redirect_url; - return h; -} - -int HttpRequest::GetContentLength() -{ - return Nvl(ScanInt(header["content-length"]), -1); -} - -void HttpRequest::StartBody() -{ - LLOG("HTTP Header received: "); - LLOG(data); - header.Clear(); - if(!header.Parse(data)) { - HttpError("invalid HTTP header"); - return; - } - - if(!header.Response(protocol, status_code, reason_phrase)) { - HttpError("invalid HTTP response"); - return; - } - - LLOG("HTTP status code: " << status_code); - - count = GetContentLength(); - - if(count > 0) - body.Reserve(count); - - if(method == METHOD_HEAD) - phase = FINISHED; - else - if(header["transfer-encoding"] == "chunked") { - count = 0; - StartPhase(CHUNK_HEADER); - } - else - StartPhase(BODY); - body.Clear(); - bodylen = 0; - gzip = GetHeader("content-encoding") == "gzip"; - if(gzip) { - gzip = true; - z.WhenOut = callback(this, &HttpRequest::Out); - z.ChunkSize(chunk).GZip().Decompress(); - } -} - -void HttpRequest::ContentOut(const void *ptr, int size) -{ - body.Cat((const char *)ptr, size); -} - -void HttpRequest::Out(const void *ptr, int size) -{ - LLOG("HTTP Out " << size); - if(z.IsError()) - HttpError("gzip format error"); - int64 l = bodylen + size; - if(l > max_content_size) { - HttpError("content length exceeded " + AsString(max_content_size)); - phase = FAILED; - return; - } - WhenContent(ptr, size); - bodylen += size; -} - -bool HttpRequest::ReadingBody() -{ - LLOG("HTTP reading data " << count); - int n = chunk; - if(count >= 0) - n = min(n, count); - String s = TcpSocket::Get(n); - if(s.GetCount() == 0) - return !IsEof() && count; -#ifndef ENDZIP - if(gzip) - z.Put(~s, s.GetCount()); - else -#endif - Out(~s, s.GetCount()); - if(count >= 0) { - count -= s.GetCount(); - return !IsEof() && count > 0; - } - return !IsEof(); -} - -void HttpRequest::CopyCookies() -{ - int q = header.fields.Find("set-cookie"); - while(q >= 0) { - Cookie(header.fields[q]); - q = header.fields.FindNext(q); - } -} - -void HttpRequest::Finish() -{ - if(gzip) { - #ifdef ENDZIP - body = GZDecompress(body); - if(body.IsVoid()) { - HttpError("gzip decompress at finish error"); - phase = FAILED; - return; - } - #else - z.End(); - if(z.IsError()) { - HttpError("gzip format error (finish)"); - phase = FAILED; - return; - } - #endif - } - Close(); - if(status_code == 401 && !IsNull(username)) { - String authenticate = header["www-authenticate"]; - if(authenticate.GetCount() && redirect_count++ < max_redirects) { - LLOG("HTTP auth digest"); - CopyCookies(); - Digest(CalculateDigest(authenticate)); - Start(); - return; - } - } - if(status_code >= 300 && status_code < 400) { - String url = GetRedirectUrl(); - if(url.GetCount() && redirect_count++ < max_redirects) { - LLOG("HTTP redirect " << url); - Url(url); - CopyCookies(); - Start(); - retry_count = 0; - return; - } - } - phase = FINISHED; -} - -String HttpRequest::Execute() -{ - while(Do()) - LLOG("HTTP Execute: " << GetPhaseName()); - return IsSuccess() ? GetContent() : String::GetVoid(); -} - -String HttpRequest::GetPhaseName() const -{ - static const char *m[] = { - "Initial state", - "Start", - "Resolving host name", - "SSL proxy request", - "SSL proxy response", - "SSL handshake", - "Sending request", - "Receiving header", - "Receiving content", - "Receiving chunk header", - "Receiving content chunk", - "Receiving trailer", - "Finished", - "Failed", - }; - return phase >= 0 && phase <= FAILED ? m[phase] : ""; -} - -END_UPP_NAMESPACE +#include "Core.h" + +NAMESPACE_UPP + +bool HttpRequest_Trace__; + +#define LLOG(x) do { if(HttpRequest_Trace__) RLOG(x); } while(0) + +#ifdef _DEBUG +_DBG_ +// #define ENDZIP +#endif + +void HttpRequest::Trace(bool b) +{ + HttpRequest_Trace__ = b; +} + +void HttpRequest::Init() +{ + port = 0; + proxy_port = 0; + ssl_proxy_port = 0; + max_header_size = 1000000; + max_content_size = 10000000; + max_redirects = 5; + max_retries = 3; + force_digest = false; + std_headers = true; + hasurlvar = false; + method = METHOD_GET; + phase = BEGIN; + redirect_count = 0; + retry_count = 0; + gzip = false; + WhenContent = callback(this, &HttpRequest::ContentOut); + chunk = 4096; + timeout = 120000; + ssl = false; +} + +HttpRequest::HttpRequest() +{ + Init(); +} + +HttpRequest::HttpRequest(const char *url) +{ + Init(); + Url(url); +} + +HttpRequest& HttpRequest::Url(const char *u) +{ + ssl = memcmp(u, "https", 5) == 0; + const char *t = u; + while(*t && *t != '?') + if(*t++ == '/' && *t == '/') { + u = ++t; + break; + } + t = u; + while(*u && *u != ':' && *u != '/' && *u != '?') + u++; + if(*u == '?' && u[1]) + hasurlvar = true; + host = String(t, u); + port = 0; + if(*u == ':') + port = ScanInt(u + 1, &u); + path = u; + int q = path.Find('#'); + if(q >= 0) + path.Trim(q); + return *this; +} + +static +void sParseProxyUrl(const char *p, String& proxy_host, int proxy_port) +{ + const char *t = p; + while(*p && *p != ':') + p++; + proxy_host = String(t, p); + if(*p++ == ':' && IsDigit(*p)) + proxy_port = ScanInt(p); +} + +HttpRequest& HttpRequest::Proxy(const char *url) +{ + proxy_port = 80; + sParseProxyUrl(url, proxy_host, proxy_port); + return *this; +} + +HttpRequest& HttpRequest::SSLProxy(const char *url) +{ + ssl_proxy_port = 8080; + sParseProxyUrl(url, ssl_proxy_host, ssl_proxy_port); + return *this; +} + +HttpRequest& HttpRequest::Post(const char *id, const String& data) +{ + POST(); + if(postdata.GetCount()) + postdata << '&'; + postdata << id << '=' << UrlEncode(data); + return *this; +} + +HttpRequest& HttpRequest::UrlVar(const char *id, const String& data) +{ + int c = *path.Last(); + if(hasurlvar && c != '&') + path << '&'; + if(!hasurlvar && c != '?') + path << '?'; + path << id << '=' << UrlEncode(data); + hasurlvar = true; + return *this; +} + +String HttpRequest::CalculateDigest(const String& authenticate) const +{ + const char *p = authenticate; + String realm, qop, nonce, opaque; + while(*p) { + if(!IsAlNum(*p)) { + p++; + continue; + } + else { + const char *b = p; + while(IsAlNum(*p)) + p++; + String var = ToLower(String(b, p)); + String value; + while(*p && (byte)*p <= ' ') + p++; + if(*p == '=') { + p++; + while(*p && (byte)*p <= ' ') + p++; + if(*p == '\"') { + p++; + while(*p && *p != '\"') + if(*p != '\\' || *++p) + value.Cat(*p++); + if(*p == '\"') + p++; + } + else { + b = p; + while(*p && *p != ',' && (byte)*p > ' ') + p++; + value = String(b, p); + } + } + if(var == "realm") + realm = value; + else if(var == "qop") + qop = value; + else if(var == "nonce") + nonce = value; + else if(var == "opaque") + opaque = value; + } + } + String hv1, hv2; + hv1 << username << ':' << realm << ':' << password; + String ha1 = MD5String(hv1); + hv2 << (method == METHOD_GET ? "GET" : method == METHOD_PUT ? "PUT" : method == METHOD_POST ? "POST" : "READ") + << ':' << path; + String ha2 = MD5String(hv2); + int nc = 1; + String cnonce = FormatIntHex(Random(), 8); + String hv; + hv << ha1 + << ':' << nonce + << ':' << FormatIntHex(nc, 8) + << ':' << cnonce + << ':' << qop << ':' << ha2; + String ha = MD5String(hv); + String auth; + auth << "username=" << AsCString(username) + << ", realm=" << AsCString(realm) + << ", nonce=" << AsCString(nonce) + << ", uri=" << AsCString(path) + << ", qop=" << AsCString(qop) + << ", nc=" << AsCString(FormatIntHex(nc, 8)) + << ", cnonce=" << cnonce + << ", response=" << AsCString(ha); + if(!IsNull(opaque)) + auth << ", opaque=" << AsCString(opaque); + return auth; +} + +HttpRequest& HttpRequest::Header(const char *id, const String& data) +{ + request_headers << id << ": " << data << "\r\n"; + return *this; +} + +void HttpRequest::HttpError(const char *s) +{ + if(IsError()) + return; + error = NFormat(t_("%s:%d: ") + String(s), host, port); + LLOG("HTTP ERROR: " << error); + Close(); +} + +void HttpRequest::StartPhase(int s) +{ + phase = s; + LLOG("Starting status " << s << " '" << GetPhaseName() << "', url: " << host); + data.Clear(); +} + +void HttpRequest::New() +{ + ClearError(); + ClearAbort(); + phase = BEGIN; +} + +bool HttpRequest::Do() +{ + int c1, c2; + switch(phase) { + case BEGIN: + retry_count = 0; + redirect_count = 0; + start_time = msecs(); + GlobalTimeout(timeout); + case START: + Start(); + break; + case DNS: + Dns(); + break; + case SSLPROXYREQUEST: + if(SendingData()) + break; + StartPhase(SSLPROXYRESPONSE); + break; + case SSLPROXYRESPONSE: + if(ReadingHeader()) + break; + ProcessSSLProxyResponse(); + break; + case SSLHANDSHAKE: + if(SSLHandshake()) + break; + StartRequest(); + break; + case REQUEST: + if(SendingData()) + break; + StartPhase(HEADER); + break; + case HEADER: + if(ReadingHeader()) + break; + StartBody(); + break; + case BODY: + if(ReadingBody()) + break; + Finish(); + break; + case CHUNK_HEADER: + ReadingChunkHeader(); + break; + case CHUNK_BODY: + if(ReadingBody()) + break; + c1 = TcpSocket::Get(); + c2 = TcpSocket::Get(); + if(c1 != '\r' || c2 != '\n') + HttpError("missing ending CRLF in chunked transfer"); + StartPhase(CHUNK_HEADER); + break; + case TRAILER: + if(ReadingHeader()) + break; + header.Parse(data); + Finish(); + break; + case FINISHED: + case FAILED: + WhenDo(); + return false; + default: + NEVER(); + } + + if(phase != FAILED) + if(IsSocketError() || IsError()) + phase = FAILED; + else + if(msecs(start_time) >= timeout) { + HttpError("connection timed out"); + phase = FAILED; + } + else + if(IsAbort()) { + HttpError("connection was aborted"); + phase = FAILED; + } + + if(phase == FAILED) { + if(retry_count++ < max_retries) { + LLOG("HTTP retry on error " << GetErrorDesc()); + start_time = msecs(); + StartPhase(START); + } + } + WhenDo(); + return phase != FINISHED && phase != FAILED; +} + +void HttpRequest::Start() +{ + Close(); + ClearError(); + gzip = false; + z.Clear(); + header.Clear(); + status_code = 0; + reason_phrase.Clear(); + WhenStart(); + + bool use_proxy = !IsNull(ssl ? ssl_proxy_host : proxy_host); + + int p = use_proxy ? (ssl ? ssl_proxy_port : proxy_port) : port; + if(!p) + p = ssl ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT; + String h = use_proxy ? ssl ? ssl_proxy_host : proxy_host : host; + + StartPhase(DNS); + if(IsNull(GetTimeout())) { + if(WhenWait) { + addrinfo.Start(h, p); + while(addrinfo.InProgress()) { + Sleep(GetWaitStep()); + WhenWait(); + if(msecs(start_time) >= timeout) + break; + } + } + else + addrinfo.Execute(h, p); + StartConnect(); + } + else + addrinfo.Start(h, p); +} + +void HttpRequest::Dns() +{ + for(int i = 0; i <= Nvl(GetTimeout(), INT_MAX); i++) { + if(!addrinfo.InProgress()) { + StartConnect(); + return; + } + Sleep(1); + } +} + +void HttpRequest::StartConnect() +{ + if(!Connect(addrinfo)) + return; + if(ssl && ssl_proxy_host.GetCount()) { + StartPhase(SSLPROXYREQUEST); + String host_port = host; + if(port) + host_port << ':' << port; + else + host_port << ":443"; + data << "CONNECT " << host_port << " HTTP/1.1\r\n" + << "Host: " << host_port << "\r\n"; + if(!IsNull(ssl_proxy_username)) + data << "Proxy-Authorization: Basic " + << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n"; + data << "\r\n"; + count = 0; + LLOG("HTTPS proxy request:\n" << data); + } + else + AfterConnect(); +} + +void HttpRequest::ProcessSSLProxyResponse() +{ + LLOG("HTTPS proxy response:\n" << data); + int q = min(data.Find('\r'), data.Find('\n')); + if(q >= 0) + data.Trim(q); + if(!data.StartsWith("HTTP") || data.Find(" 2") < 0) { + HttpError("Invalid proxy reply: " + data); + return; + } + AfterConnect(); +} + +void HttpRequest::AfterConnect() +{ + if(ssl && !StartSSL()) + return; + if(ssl) + StartPhase(SSLHANDSHAKE); + else + StartRequest(); +} + +void HttpRequest::StartRequest() +{ + StartPhase(REQUEST); + count = 0; + String ctype = contenttype; + if((method == METHOD_POST || method == METHOD_PUT) && IsNull(ctype)) + ctype = "application/x-www-form-urlencoded"; + switch(method) { + case METHOD_GET: data << "GET "; break; + case METHOD_POST: data << "POST "; break; + case METHOD_PUT: data << "PUT "; break; + case METHOD_HEAD: data << "HEAD "; break; + default: NEVER(); // invalid method + } + String host_port = host; + if(port) + host_port << ':' << port; + String url; + url << "http://" << host_port << Nvl(path, "/"); + if(!IsNull(proxy_host) && !ssl) + data << url; + else + data << Nvl(path, "/"); + data << " HTTP/1.1\r\n"; + if(std_headers) { + data << "URL: " << url << "\r\n" + << "Host: " << host_port << "\r\n" + << "Connection: close\r\n" + << "Accept: " << Nvl(accept, "*/*") << "\r\n" + << "Accept-Encoding: gzip\r\n" + << "User-Agent: " << Nvl(agent, "U++ HTTP request") << "\r\n"; + if(postdata.GetCount()) + data << "Content-Length: " << postdata.GetCount() << "\r\n"; + if(ctype.GetCount()) + data << "Content-Type: " << ctype << "\r\n"; + } + if(!IsNull(proxy_host) && !IsNull(proxy_username)) + data << "Proxy-Authorization: Basic " << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n"; + if(!IsNull(digest)) + data << "Authorization: Digest " << digest << "\r\n"; + else + if(!force_digest && (!IsNull(username) || !IsNull(password))) + data << "Authorization: Basic " << Base64Encode(username + ":" + password) << "\r\n"; + data << request_headers << "\r\n" << postdata; // !!! POST PHASE !!! + LLOG("HTTP REQUEST " << host << ":" << port); + LLOG("HTTP request:\n" << data); +} + +bool HttpRequest::SendingData() +{ + for(;;) { + int n = min(2048, data.GetLength() - count); + n = TcpSocket::Put(~data + count, n); + if(n == 0) + break; + count += n; + } + return count < data.GetLength(); +} + +bool HttpRequest::ReadingHeader() +{ + for(;;) { + int c = TcpSocket::Get(); + if(c < 0) + return !IsEof(); + else + data.Cat(c); + if(data.GetCount() > 3) { + const char *h = data.Last(); + if(h[0] == '\n' && (h[-1] == '\r' && h[-2] == '\n' || h[-1] == '\n')) + return false; + } + if(data.GetCount() > max_header_size) { + HttpError("HTTP header exceeded " + AsString(max_header_size)); + return true; + } + } +} + +void HttpRequest::ReadingChunkHeader() +{ + for(;;) { + int c = TcpSocket::Get(); + if(c < 0) + break; + else + if(c == '\n') { + int n = ScanInt(~data, NULL, 16); + LLOG("HTTP Chunk header: 0x" << data << " = " << n); + if(IsNull(n)) { + HttpError("invalid chunk header"); + break; + } + if(n == 0) { + StartPhase(TRAILER); + break; + } + count += n; + StartPhase(CHUNK_BODY); + break; + } + if(c != '\r') + data.Cat(c); + } +} + +String HttpRequest::GetRedirectUrl() +{ + String redirect_url = TrimLeft(header["location"]); + if(redirect_url.StartsWith("http://") || redirect_url.StartsWith("https://")) + return redirect_url; + String h = (ssl ? "https://" : "http://") + host; + if(*redirect_url != '/') + h << '/'; + h << redirect_url; + return h; +} + +int HttpRequest::GetContentLength() +{ + return Nvl(ScanInt(header["content-length"]), -1); +} + +void HttpRequest::StartBody() +{ + LLOG("HTTP Header received: "); + LLOG(data); + header.Clear(); + if(!header.Parse(data)) { + HttpError("invalid HTTP header"); + return; + } + + if(!header.Response(protocol, status_code, reason_phrase)) { + HttpError("invalid HTTP response"); + return; + } + + LLOG("HTTP status code: " << status_code); + + count = GetContentLength(); + + if(count > 0) + body.Reserve(count); + + if(method == METHOD_HEAD) + phase = FINISHED; + else + if(header["transfer-encoding"] == "chunked") { + count = 0; + StartPhase(CHUNK_HEADER); + } + else + StartPhase(BODY); + body.Clear(); + bodylen = 0; + gzip = GetHeader("content-encoding") == "gzip"; + if(gzip) { + gzip = true; + z.WhenOut = callback(this, &HttpRequest::Out); + z.ChunkSize(chunk).GZip().Decompress(); + } +} + +void HttpRequest::ContentOut(const void *ptr, int size) +{ + body.Cat((const char *)ptr, size); +} + +void HttpRequest::Out(const void *ptr, int size) +{ + LLOG("HTTP Out " << size); + if(z.IsError()) + HttpError("gzip format error"); + int64 l = bodylen + size; + if(l > max_content_size) { + HttpError("content length exceeded " + AsString(max_content_size)); + phase = FAILED; + return; + } + WhenContent(ptr, size); + bodylen += size; +} + +bool HttpRequest::ReadingBody() +{ + LLOG("HTTP reading data " << count); + int n = chunk; + if(count >= 0) + n = min(n, count); + String s = TcpSocket::Get(n); + if(s.GetCount() == 0) + return !IsEof() && count; +#ifndef ENDZIP + if(gzip) + z.Put(~s, s.GetCount()); + else +#endif + Out(~s, s.GetCount()); + if(count >= 0) { + count -= s.GetCount(); + return !IsEof() && count > 0; + } + return !IsEof(); +} + +void HttpRequest::CopyCookies() +{ + int q = header.fields.Find("set-cookie"); + while(q >= 0) { + Cookie(header.fields[q]); + q = header.fields.FindNext(q); + } +} + +void HttpRequest::Finish() +{ + if(gzip) { + #ifdef ENDZIP + body = GZDecompress(body); + if(body.IsVoid()) { + HttpError("gzip decompress at finish error"); + phase = FAILED; + return; + } + #else + z.End(); + if(z.IsError()) { + HttpError("gzip format error (finish)"); + phase = FAILED; + return; + } + #endif + } + Close(); + if(status_code == 401 && !IsNull(username)) { + String authenticate = header["www-authenticate"]; + if(authenticate.GetCount() && redirect_count++ < max_redirects) { + LLOG("HTTP auth digest"); + CopyCookies(); + Digest(CalculateDigest(authenticate)); + Start(); + return; + } + } + if(status_code >= 300 && status_code < 400) { + String url = GetRedirectUrl(); + if(url.GetCount() && redirect_count++ < max_redirects) { + LLOG("HTTP redirect " << url); + Url(url); + CopyCookies(); + Start(); + retry_count = 0; + return; + } + } + phase = FINISHED; +} + +String HttpRequest::Execute() +{ + while(Do()) + LLOG("HTTP Execute: " << GetPhaseName()); + return IsSuccess() ? GetContent() : String::GetVoid(); +} + +String HttpRequest::GetPhaseName() const +{ + static const char *m[] = { + "Initial state", + "Start", + "Resolving host name", + "SSL proxy request", + "SSL proxy response", + "SSL handshake", + "Sending request", + "Receiving header", + "Receiving content", + "Receiving chunk header", + "Receiving content chunk", + "Receiving trailer", + "Finished", + "Failed", + }; + return phase >= 0 && phase <= FAILED ? m[phase] : ""; +} + +END_UPP_NAMESPACE diff --git a/uppsrc/Core/Inet.h b/uppsrc/Core/Inet.h index 52cc09fce..0fa1f8a30 100644 --- a/uppsrc/Core/Inet.h +++ b/uppsrc/Core/Inet.h @@ -1,439 +1,448 @@ -String WwwFormat(Time tm); - -String MIMECharsetName(byte charset); - -String UrlEncode(const char *s, const char *end); -String UrlEncode(const char *s, int len); -String UrlEncode(const String& s); -String UrlDecode(const char *s, const char *end); -String UrlDecode(const char *s, int len); -String UrlDecode(const String& s); - -String Base64Encode(const char *s, const char *end); -String Base64Encode(const char *s, int len); -String Base64Encode(const String& data); -String Base64Decode(const char *s, const char *end); -String Base64Decode(const char *s, int len); -String Base64Decode(const String& data); - -class IpAddrInfo { - enum { COUNT = 32 }; - struct Entry { - const char *host; - const char *port; - int status; - addrinfo *addr; - }; - static Entry pool[COUNT]; - - enum { - EMPTY = 0, WORKING, CANCELED, RESOLVED, FAILED - }; - - String host, port; - Entry *entry; - Entry exe[1]; - - static void EnterPool(); - static void LeavePool(); - static auxthread_t auxthread__ Thread(void *ptr); - - void Start(); - -public: - void Start(const String& host, int port); - bool InProgress(); - bool Execute(const String& host, int port); - addrinfo *GetResult(); - void Clear(); - - IpAddrInfo(); - ~IpAddrInfo() { Clear(); } -}; - -enum { WAIT_READ = 1, WAIT_WRITE = 2, WAIT_EXCEPTION = 4, WAIT_ALL = 7 }; - -struct SSLInfo { - String cipher; - bool cert_avail; - bool cert_verified; // Peer verification not yet working - this is always false - String cert_subject; - String cert_issuer; - Date cert_notbefore; - Date cert_notafter; - int cert_version; - String cert_serial; -}; - -class TcpSocket { - enum { BUFFERSIZE = 512 }; - enum { NONE, CONNECT, ACCEPT, SSL_CONNECTED }; - SOCKET socket; - int mode; - char buffer[BUFFERSIZE]; - char *ptr; - char *end; - bool is_eof; - bool is_error; - bool is_abort; - bool ipv6; - - int timeout; - int waitstep; - int done; - - int errorcode; - String errordesc; - - struct SSL { - virtual bool Start() = 0; - virtual bool Wait(dword flags, int end_time) = 0; - virtual int Send(const void *buffer, int maxlen) = 0; - virtual int Recv(void *buffer, int maxlen) = 0; - virtual void Close() = 0; - virtual dword Handshake() = 0; - - virtual ~SSL() {} - }; - - One ssl; - One sslinfo; - String cert, pkey; - bool asn1; - - struct SSLImp; - friend struct SSLImp; - - static SSL *(*CreateSSL)(TcpSocket& socket); - static SSL *CreateSSLImp(TcpSocket& socket); - - friend void InitCreateSSL(); - friend class IpAddrInfo; - - int GetEndTime() const; - bool RawWait(dword flags, int end_time); - bool Wait(dword events, int end_time); - SOCKET AcceptRaw(dword *ipaddr, int timeout_msec); - bool Open(int family, int type, int protocol); - int RawRecv(void *buffer, int maxlen); - int Recv(void *buffer, int maxlen); - int RawSend(const void *buffer, int maxlen); - int Send(const void *buffer, int maxlen); - bool RawConnect(addrinfo *info); - void RawClose(); - - void ReadBuffer(int end_time); - int Get_(); - int Peek_(); - int Peek_(int end_time); - int Peek(int end_time) { return ptr < end ? *ptr : Peek_(end_time); } - - void Reset(); - - void SetSockError(const char *context, int code, const char *errdesc); - void SetSockError(const char *context, const char *errdesc); - void SetSockError(const char *context); - - static int GetErrorCode(); - static bool WouldBlock(); - static void Init(); - - -public: - Callback WhenWait; - - static String GetHostName(); - - int GetDone() const { return done; } - - bool IsOpen() const { return socket != INVALID_SOCKET; } - bool IsEof() const { return is_eof && ptr == end; } - - bool IsError() const { return is_error; } - void ClearError() { is_error = false; errorcode = 0; errordesc.Clear(); } - int GetError() const { return errorcode; } - String GetErrorDesc() const { return errordesc; } - - void Abort() { is_abort = true; } - bool IsAbort() const { return is_abort; } - void ClearAbort() { is_abort = false; } - - SOCKET GetSOCKET() const { return socket; } - String GetPeerAddr() const; - - void Attach(SOCKET socket); - bool Connect(const char *host, int port); - bool Connect(IpAddrInfo& info); - bool Listen(int port, int listen_count, bool ipv6 = false, bool reuse = true); - bool Accept(TcpSocket& listen_socket); - void Close(); - void Shutdown(); - - void NoDelay(); - void Linger(int msecs); - void NoLinger() { Linger(Null); } - - bool Wait(dword events); - bool WaitRead() { return Wait(WAIT_READ); } - bool WaitWrite() { return Wait(WAIT_WRITE); } - - int Peek() { return ptr < end ? *ptr : Peek_(); } - int Term() { return Peek(); } - int Get() { return ptr < end ? *ptr++ : Get_(); } - int Get(void *buffer, int len); - String Get(int len); - - int Put(const char *s, int len); - int Put(const String& s) { return Put(s.Begin(), s.GetLength()); } - - bool GetAll(void *buffer, int len); - String GetAll(int len); - String GetLine(int maxlen = 65536); - - bool PutAll(const char *s, int len); - bool PutAll(const String& s); - - bool StartSSL(); - bool IsSSL() const { return ssl; } - bool SSLHandshake(); - void SSLCertificate(const String& cert, const String& pkey, bool asn1); - const SSLInfo *GetSSLInfo() const { return ~sslinfo; } - - TcpSocket& Timeout(int ms) { timeout = ms; return *this; } - int GetTimeout() const { return timeout; } - TcpSocket& Blocking() { return Timeout(Null); } - TcpSocket& WaitStep(int ms) { waitstep = ms; return *this; } - int GetWaitStep() const { return waitstep; } - - TcpSocket(); - ~TcpSocket() { Close(); } -}; - -class SocketWaitEvent { - Vector< Tuple2 > socket; - fd_set read[1], write[1], exception[1]; - -public: - void Clear() { socket.Clear(); } - void Add(SOCKET s, dword events = WAIT_ALL) { socket.Add(MakeTuple((int)s, events)); } - void Add(TcpSocket& s, dword events = WAIT_ALL) { Add(s.GetSOCKET(), events); } - int Wait(int timeout); - dword Get(int i) const; - dword operator[](int i) const { return Get(i); } - - SocketWaitEvent(); -}; - -struct HttpHeader { - String first_line; - String f1, f2, f3; - VectorMap fields; - - String operator[](const char *id) const { return fields.Get(id, Null); } - - bool Response(String& protocol, int& code, String& reason); - bool Request(String& method, String& uri, String& version); - - String GetProtocol() const { return f1; } - int GetCode() const; - String GetReason() const { return f3; } - - String GetMethod() const { return f1; } - String GetURI() const { return f2; } - String GetVersion() const { return f3; } - - void Clear(); - bool Parse(const String& hdrs); - - bool Read(TcpSocket& socket); -}; - -class HttpRequest : public TcpSocket { - int phase; - String data; - int count; - - HttpHeader header; - - String error; - String body; - - enum { - DEFAULT_HTTP_PORT = 80, - DEFAULT_HTTPS_PORT = 443 - }; - - enum { - METHOD_GET, - METHOD_POST, - METHOD_HEAD, - METHOD_PUT, - }; - - int max_header_size; - int max_content_size; - int max_redirects; - int max_retries; - int timeout; - - String host; - int port; - String proxy_host; - int proxy_port; - String proxy_username; - String proxy_password; - String ssl_proxy_host; - int ssl_proxy_port; - String ssl_proxy_username; - String ssl_proxy_password; - String path; - bool ssl; - - int method; - String accept; - String agent; - bool force_digest; - bool is_post; - bool std_headers; - bool hasurlvar; - String contenttype; - String username; - String password; - String digest; - String request_headers; - String postdata; - - String protocol; - int status_code; - String reason_phrase; - - int start_time; - int retry_count; - int redirect_count; - - int chunk; - - IpAddrInfo addrinfo; - int bodylen; - bool gzip; - Zlib z; - - void Init(); - - void StartPhase(int s); - void Start(); - void Dns(); - void StartConnect(); - void ProcessSSLProxyResponse(); - void AfterConnect(); - void StartRequest(); - bool SendingData(); - bool ReadingHeader(); - void StartBody(); - bool ReadingBody(); - void ReadingChunkHeader(); - void Finish(); - - void CopyCookies(); - - void HttpError(const char *s); - void ContentOut(const void *ptr, int size); - void Out(const void *ptr, int size); - - String CalculateDigest(const String& authenticate) const; - -public: - Callback2 WhenContent; - Callback WhenStart; - Callback WhenDo; - - HttpRequest& MaxHeaderSize(int m) { max_header_size = m; return *this; } - HttpRequest& MaxContentSize(int m) { max_content_size = m; return *this; } - HttpRequest& MaxRedirect(int n) { max_redirects = n; return *this; } - HttpRequest& MaxRetries(int n) { max_retries = n; return *this; } - HttpRequest& RequestTimeout(int ms) { timeout = ms; return *this; } - HttpRequest& ChunkSize(int n) { chunk = n; return *this; } - - HttpRequest& Method(int m) { method = m; return *this; } - HttpRequest& GET() { return Method(METHOD_GET); } - HttpRequest& POST() { return Method(METHOD_POST); } - HttpRequest& HEAD() { return Method(METHOD_HEAD); } - HttpRequest& PUT() { return Method(METHOD_PUT); } - - HttpRequest& Host(const String& h) { host = h; return *this; } - HttpRequest& Port(int p) { port = p; return *this; } - HttpRequest& SSL(bool b = true) { ssl = b; return *this; } - HttpRequest& Path(const String& p) { path = p; return *this; } - HttpRequest& User(const String& u, const String& p) { username = u; password = p; return *this; } - HttpRequest& Digest() { force_digest = true; return *this; } - HttpRequest& Digest(const String& d) { digest = d; return *this; } - HttpRequest& Url(const char *url); - HttpRequest& UrlVar(const char *id, const String& data); - HttpRequest& operator()(const char *id, const String& data) { return UrlVar(id, data); } - HttpRequest& PostData(const String& pd) { postdata = pd; return *this; } - HttpRequest& PostUData(const String& pd) { return PostData(UrlEncode(pd)); } - HttpRequest& Post(const String& data) { POST(); return PostData(data); } - HttpRequest& Post(const char *id, const String& data); - - HttpRequest& Headers(const String& h) { request_headers = h; return *this; } - HttpRequest& ClearHeaders() { return Headers(Null); } - HttpRequest& AddHeaders(const String& h) { request_headers.Cat(h); return *this; } - HttpRequest& Header(const char *id, const String& data); - HttpRequest& Cookie(const String& cookie) { return Header("Cookie", cookie); } - - HttpRequest& StdHeaders(bool sh) { std_headers = sh; return *this; } - HttpRequest& NoStdHeaders() { return StdHeaders(false); } - HttpRequest& Accept(const String& a) { accept = a; return *this; } - HttpRequest& UserAgent(const String& a) { agent = a; return *this; } - HttpRequest& ContentType(const String& a) { contenttype = a; return *this; } - - HttpRequest& Proxy(const String& host, int port) { proxy_host = host; proxy_port = port; return *this; } - HttpRequest& Proxy(const char *p); - HttpRequest& ProxyAuth(const String& u, const String& p) { proxy_username = u; proxy_password = p; return *this; } - - HttpRequest& SSLProxy(const String& host, int port) { ssl_proxy_host = host; ssl_proxy_port = port; return *this; } - HttpRequest& SSLProxy(const char *p); - HttpRequest& SSLProxyAuth(const String& u, const String& p) { ssl_proxy_username = u; ssl_proxy_password = p; return *this; } - - bool IsSocketError() const { return TcpSocket::IsError(); } - bool IsHttpError() const { return !IsNull(error) ; } - bool IsError() const { return IsSocketError() || IsHttpError(); } - String GetErrorDesc() const { return IsSocketError() ? TcpSocket::GetErrorDesc() : error; } - void ClearError() { TcpSocket::ClearError(); error.Clear(); } - - String GetHeader(const char *id) { return header[id]; } - String operator[](const char *id) { return GetHeader(id); } - String GetRedirectUrl(); - int GetContentLength(); - int GetStatusCode() const { return status_code; } - String GetReasonPhrase() const { return reason_phrase; } - - String GetContent() const { return body; } - String operator~() const { return GetContent(); } - operator String() const { return GetContent(); } - void ClearContent() { body.Clear(); } - - enum Phase { - BEGIN, START, DNS, - SSLPROXYREQUEST, SSLPROXYRESPONSE, SSLHANDSHAKE, - REQUEST, HEADER, BODY, - CHUNK_HEADER, CHUNK_BODY, TRAILER, - FINISHED, FAILED - }; - - bool Do(); - int GetPhase() const { return phase; } - String GetPhaseName() const; - bool InProgress() const { return phase != FAILED && phase != FINISHED; } - bool IsFailure() const { return phase == FAILED; } - bool IsSuccess() const { return phase == FINISHED && status_code >= 200 && status_code < 300; } - - String Execute(); - - void New(); - - HttpRequest(); - HttpRequest(const char *url); - - static void Trace(bool b = true); -}; +String WwwFormat(Time tm); + +String MIMECharsetName(byte charset); + +String UrlEncode(const char *s, const char *end); +String UrlEncode(const char *s, int len); +String UrlEncode(const String& s); +String UrlDecode(const char *s, const char *end); +String UrlDecode(const char *s, int len); +String UrlDecode(const String& s); + +String Base64Encode(const char *s, const char *end); +String Base64Encode(const char *s, int len); +String Base64Encode(const String& data); +String Base64Decode(const char *s, const char *end); +String Base64Decode(const char *s, int len); +String Base64Decode(const String& data); + +class IpAddrInfo { + enum { COUNT = 32 }; + struct Entry { + const char *host; + const char *port; + int status; + addrinfo *addr; + }; + static Entry pool[COUNT]; + + enum { + EMPTY = 0, WORKING, CANCELED, RESOLVED, FAILED + }; + + String host, port; + Entry *entry; + Entry exe[1]; + + static void EnterPool(); + static void LeavePool(); + static auxthread_t auxthread__ Thread(void *ptr); + + void Start(); + +public: + void Start(const String& host, int port); + bool InProgress(); + bool Execute(const String& host, int port); + addrinfo *GetResult(); + void Clear(); + + IpAddrInfo(); + ~IpAddrInfo() { Clear(); } +}; + +enum { WAIT_READ = 1, WAIT_WRITE = 2, WAIT_EXCEPTION = 4, WAIT_ALL = 7 }; + +struct SSLInfo { + String cipher; + bool cert_avail; + bool cert_verified; // Peer verification not yet working - this is always false + String cert_subject; + String cert_issuer; + Date cert_notbefore; + Date cert_notafter; + int cert_version; + String cert_serial; +}; + +class TcpSocket { + enum { BUFFERSIZE = 512 }; + enum { NONE, CONNECT, ACCEPT, SSL_CONNECTED }; + SOCKET socket; + int mode; + char buffer[BUFFERSIZE]; + char *ptr; + char *end; + bool is_eof; + bool is_error; + bool is_abort; + bool ipv6; + + int timeout; + int waitstep; + int done; + + int global_timeout; + int start_time; + + int errorcode; + String errordesc; + + struct SSL { + virtual bool Start() = 0; + virtual bool Wait(dword flags, int end_time) = 0; + virtual int Send(const void *buffer, int maxlen) = 0; + virtual int Recv(void *buffer, int maxlen) = 0; + virtual void Close() = 0; + virtual dword Handshake() = 0; + + virtual ~SSL() {} + }; + + One ssl; + One sslinfo; + String cert, pkey; + bool asn1; + + struct SSLImp; + friend struct SSLImp; + + static SSL *(*CreateSSL)(TcpSocket& socket); + static SSL *CreateSSLImp(TcpSocket& socket); + + friend void InitCreateSSL(); + friend class IpAddrInfo; + + int GetEndTime() const; + bool RawWait(dword flags, int end_time); + bool Wait(dword events, int end_time); + SOCKET AcceptRaw(dword *ipaddr, int timeout_msec); + bool Open(int family, int type, int protocol); + int RawRecv(void *buffer, int maxlen); + int Recv(void *buffer, int maxlen); + int RawSend(const void *buffer, int maxlen); + int Send(const void *buffer, int maxlen); + bool RawConnect(addrinfo *info); + void RawClose(); + + void ReadBuffer(int end_time); + int Get_(); + int Peek_(); + int Peek_(int end_time); + int Peek(int end_time) { return ptr < end ? *ptr : Peek_(end_time); } + bool IsGlobalTimeout(); + + void Reset(); + + void SetSockError(const char *context, int code, const char *errdesc); + void SetSockError(const char *context, const char *errdesc); + void SetSockError(const char *context); + + static int GetErrorCode(); + static bool WouldBlock(); + static void Init(); + + +public: + Callback WhenWait; + + enum { ERROR_GLOBAL_TIMEOUT = -1000000 }; + + static String GetHostName(); + + int GetDone() const { return done; } + + bool IsOpen() const { return socket != INVALID_SOCKET; } + bool IsEof() const { return is_eof && ptr == end; } + + bool IsError() const { return is_error; } + void ClearError() { is_error = false; errorcode = 0; errordesc.Clear(); } + int GetError() const { return errorcode; } + String GetErrorDesc() const { return errordesc; } + + void Abort() { is_abort = true; } + bool IsAbort() const { return is_abort; } + void ClearAbort() { is_abort = false; } + + SOCKET GetSOCKET() const { return socket; } + String GetPeerAddr() const; + + void Attach(SOCKET socket); + bool Connect(const char *host, int port); + bool Connect(IpAddrInfo& info); + bool Listen(int port, int listen_count, bool ipv6 = false, bool reuse = true); + bool Accept(TcpSocket& listen_socket); + void Close(); + void Shutdown(); + + void NoDelay(); + void Linger(int msecs); + void NoLinger() { Linger(Null); } + + bool Wait(dword events); + bool WaitRead() { return Wait(WAIT_READ); } + bool WaitWrite() { return Wait(WAIT_WRITE); } + + int Peek() { return ptr < end ? *ptr : Peek_(); } + int Term() { return Peek(); } + int Get() { return ptr < end ? *ptr++ : Get_(); } + int Get(void *buffer, int len); + String Get(int len); + + int Put(const char *s, int len); + int Put(const String& s) { return Put(s.Begin(), s.GetLength()); } + + bool GetAll(void *buffer, int len); + String GetAll(int len); + String GetLine(int maxlen = 65536); + + bool PutAll(const char *s, int len); + bool PutAll(const String& s); + + bool StartSSL(); + bool IsSSL() const { return ssl; } + bool SSLHandshake(); + void SSLCertificate(const String& cert, const String& pkey, bool asn1); + const SSLInfo *GetSSLInfo() const { return ~sslinfo; } + + TcpSocket& Timeout(int ms) { timeout = ms; return *this; } + int GetTimeout() const { return timeout; } + TcpSocket& GlobalTimeout(int ms); + TcpSocket& NoGlobalTimeout() { return GlobalTimeout(Null); } + TcpSocket& Blocking() { return Timeout(Null); } + TcpSocket& WaitStep(int ms) { waitstep = ms; return *this; } + int GetWaitStep() const { return waitstep; } + + TcpSocket(); + ~TcpSocket() { Close(); } +}; + +class SocketWaitEvent { + Vector< Tuple2 > socket; + fd_set read[1], write[1], exception[1]; + +public: + void Clear() { socket.Clear(); } + void Add(SOCKET s, dword events = WAIT_ALL) { socket.Add(MakeTuple((int)s, events)); } + void Add(TcpSocket& s, dword events = WAIT_ALL) { Add(s.GetSOCKET(), events); } + int Wait(int timeout); + dword Get(int i) const; + dword operator[](int i) const { return Get(i); } + + SocketWaitEvent(); +}; + +struct HttpHeader { + String first_line; + String f1, f2, f3; + VectorMap fields; + + String operator[](const char *id) const { return fields.Get(id, Null); } + + bool Response(String& protocol, int& code, String& reason); + bool Request(String& method, String& uri, String& version); + + String GetProtocol() const { return f1; } + int GetCode() const; + String GetReason() const { return f3; } + + String GetMethod() const { return f1; } + String GetURI() const { return f2; } + String GetVersion() const { return f3; } + + void Clear(); + bool Parse(const String& hdrs); + + bool Read(TcpSocket& socket); +}; + +class HttpRequest : public TcpSocket { + int phase; + String data; + int count; + + HttpHeader header; + + String error; + String body; + + enum { + DEFAULT_HTTP_PORT = 80, + DEFAULT_HTTPS_PORT = 443 + }; + + enum { + METHOD_GET, + METHOD_POST, + METHOD_HEAD, + METHOD_PUT, + }; + + int max_header_size; + int max_content_size; + int max_redirects; + int max_retries; + int timeout; + + String host; + int port; + String proxy_host; + int proxy_port; + String proxy_username; + String proxy_password; + String ssl_proxy_host; + int ssl_proxy_port; + String ssl_proxy_username; + String ssl_proxy_password; + String path; + bool ssl; + + int method; + String accept; + String agent; + bool force_digest; + bool is_post; + bool std_headers; + bool hasurlvar; + String contenttype; + String username; + String password; + String digest; + String request_headers; + String postdata; + + String protocol; + int status_code; + String reason_phrase; + + int start_time; + int retry_count; + int redirect_count; + + int chunk; + + IpAddrInfo addrinfo; + int bodylen; + bool gzip; + Zlib z; + + void Init(); + + void StartPhase(int s); + void Start(); + void Dns(); + void StartConnect(); + void ProcessSSLProxyResponse(); + void AfterConnect(); + void StartRequest(); + bool SendingData(); + bool ReadingHeader(); + void StartBody(); + bool ReadingBody(); + void ReadingChunkHeader(); + void Finish(); + bool IsRequestTimeout(); + + void CopyCookies(); + + void HttpError(const char *s); + void ContentOut(const void *ptr, int size); + void Out(const void *ptr, int size); + + String CalculateDigest(const String& authenticate) const; + +public: + Callback2 WhenContent; + Callback WhenStart; + Callback WhenDo; + + HttpRequest& MaxHeaderSize(int m) { max_header_size = m; return *this; } + HttpRequest& MaxContentSize(int m) { max_content_size = m; return *this; } + HttpRequest& MaxRedirect(int n) { max_redirects = n; return *this; } + HttpRequest& MaxRetries(int n) { max_retries = n; return *this; } + HttpRequest& RequestTimeout(int ms) { timeout = ms; return *this; } + HttpRequest& ChunkSize(int n) { chunk = n; return *this; } + + HttpRequest& Method(int m) { method = m; return *this; } + HttpRequest& GET() { return Method(METHOD_GET); } + HttpRequest& POST() { return Method(METHOD_POST); } + HttpRequest& HEAD() { return Method(METHOD_HEAD); } + HttpRequest& PUT() { return Method(METHOD_PUT); } + + HttpRequest& Host(const String& h) { host = h; return *this; } + HttpRequest& Port(int p) { port = p; return *this; } + HttpRequest& SSL(bool b = true) { ssl = b; return *this; } + HttpRequest& Path(const String& p) { path = p; return *this; } + HttpRequest& User(const String& u, const String& p) { username = u; password = p; return *this; } + HttpRequest& Digest() { force_digest = true; return *this; } + HttpRequest& Digest(const String& d) { digest = d; return *this; } + HttpRequest& Url(const char *url); + HttpRequest& UrlVar(const char *id, const String& data); + HttpRequest& operator()(const char *id, const String& data) { return UrlVar(id, data); } + HttpRequest& PostData(const String& pd) { postdata = pd; return *this; } + HttpRequest& PostUData(const String& pd) { return PostData(UrlEncode(pd)); } + HttpRequest& Post(const String& data) { POST(); return PostData(data); } + HttpRequest& Post(const char *id, const String& data); + + HttpRequest& Headers(const String& h) { request_headers = h; return *this; } + HttpRequest& ClearHeaders() { return Headers(Null); } + HttpRequest& AddHeaders(const String& h) { request_headers.Cat(h); return *this; } + HttpRequest& Header(const char *id, const String& data); + HttpRequest& Cookie(const String& cookie) { return Header("Cookie", cookie); } + + HttpRequest& StdHeaders(bool sh) { std_headers = sh; return *this; } + HttpRequest& NoStdHeaders() { return StdHeaders(false); } + HttpRequest& Accept(const String& a) { accept = a; return *this; } + HttpRequest& UserAgent(const String& a) { agent = a; return *this; } + HttpRequest& ContentType(const String& a) { contenttype = a; return *this; } + + HttpRequest& Proxy(const String& host, int port) { proxy_host = host; proxy_port = port; return *this; } + HttpRequest& Proxy(const char *p); + HttpRequest& ProxyAuth(const String& u, const String& p) { proxy_username = u; proxy_password = p; return *this; } + + HttpRequest& SSLProxy(const String& host, int port) { ssl_proxy_host = host; ssl_proxy_port = port; return *this; } + HttpRequest& SSLProxy(const char *p); + HttpRequest& SSLProxyAuth(const String& u, const String& p) { ssl_proxy_username = u; ssl_proxy_password = p; return *this; } + + bool IsSocketError() const { return TcpSocket::IsError(); } + bool IsHttpError() const { return !IsNull(error) ; } + bool IsError() const { return IsSocketError() || IsHttpError(); } + String GetErrorDesc() const { return IsSocketError() ? TcpSocket::GetErrorDesc() : error; } + void ClearError() { TcpSocket::ClearError(); error.Clear(); } + + String GetHeader(const char *id) { return header[id]; } + String operator[](const char *id) { return GetHeader(id); } + String GetRedirectUrl(); + int GetContentLength(); + int GetStatusCode() const { return status_code; } + String GetReasonPhrase() const { return reason_phrase; } + + String GetContent() const { return body; } + String operator~() const { return GetContent(); } + operator String() const { return GetContent(); } + void ClearContent() { body.Clear(); } + + enum Phase { + BEGIN, START, DNS, + SSLPROXYREQUEST, SSLPROXYRESPONSE, SSLHANDSHAKE, + REQUEST, HEADER, BODY, + CHUNK_HEADER, CHUNK_BODY, TRAILER, + FINISHED, FAILED + }; + + bool Do(); + int GetPhase() const { return phase; } + String GetPhaseName() const; + bool InProgress() const { return phase != FAILED && phase != FINISHED; } + bool IsFailure() const { return phase == FAILED; } + bool IsSuccess() const { return phase == FINISHED && status_code >= 200 && status_code < 300; } + + String Execute(); + + void New(); + + HttpRequest(); + HttpRequest(const char *url); + + static void Trace(bool b = true); +}; diff --git a/uppsrc/Core/Socket.cpp b/uppsrc/Core/Socket.cpp index 568d36982..5568879ff 100644 --- a/uppsrc/Core/Socket.cpp +++ b/uppsrc/Core/Socket.cpp @@ -263,6 +263,8 @@ void TcpSocket::Reset() mode = NONE; ssl.Clear(); sslinfo.Clear(); + global_timeout = Null; + start_time = Null; } TcpSocket::TcpSocket() @@ -524,6 +526,15 @@ String TcpSocket::GetHostName() return buffer; } +bool TcpSocket::IsGlobalTimeout() +{ + if(!IsNull(global_timeout) && msecs() - start_time > global_timeout) { + SetSockError("wait", ERROR_GLOBAL_TIMEOUT, "Timeout"); + return true; + } + return false; +} + bool TcpSocket::RawWait(dword flags, int end_time) { LLOG("Wait(" << msecs() << " - " << end_time << ", " << flags << ")"); @@ -559,6 +570,8 @@ bool TcpSocket::RawWait(dword flags, int end_time) } if(avail > 0) return true; + if(IsGlobalTimeout()) + return false; if(to <= 0 && timeout) return false; WhenWait(); @@ -567,6 +580,13 @@ bool TcpSocket::RawWait(dword flags, int end_time) } } +TcpSocket& TcpSocket::GlobalTimeout(int ms) +{ + start_time = msecs(); + global_timeout = ms; + return *this; +} + bool TcpSocket::Wait(dword flags, int end_time) { return ssl ? ssl->Wait(flags, end_time) : RawWait(flags, end_time); @@ -574,7 +594,8 @@ bool TcpSocket::Wait(dword flags, int end_time) int TcpSocket::GetEndTime() const { - return IsNull(timeout) ? INT_MAX : msecs() + timeout; + return min(IsNull(global_timeout) ? INT_MAX : start_time + global_timeout, + IsNull(timeout) ? INT_MAX : msecs() + timeout); } bool TcpSocket::Wait(dword flags) diff --git a/uppsrc/Core/src.tpp/TcpSocket$en-us.tpp b/uppsrc/Core/src.tpp/TcpSocket$en-us.tpp index df9702501..1a11dbfef 100644 --- a/uppsrc/Core/src.tpp/TcpSocket$en-us.tpp +++ b/uppsrc/Core/src.tpp/TcpSocket$en-us.tpp @@ -271,6 +271,20 @@ to adjust timeout before any single TcpSocket operation. Returns [s5;:TcpSocket`:`:GetTimeout`(`)const: [@(0.0.255) int]_[* GetTimeout]()_[@(0.0.255) const]&] [s2;%% Returns current timeout.&] [s3;%% &] +[s4; &] +[s5;:TcpSocket`:`:GlobalTimeout`(int`): [_^TcpSocket^ TcpSocket][@(0.0.255) `&]_[* GlobalTi +meout]([@(0.0.255) int]_[*@3 ms])&] +[s2;%% Sets the `"global timeout`". This timeout is in effect over +a whole range of operations, until it is canceled by calling +this method with Null parameter. If global timeout is exceeded, +operation during which it happened fails and socket error code +is set to ERROR`_GLOBAL`_TIMEOUT.&] +[s3;%% &] +[s4; &] +[s5;:TcpSocket`:`:NoGlobalTimeout`(`): [_^TcpSocket^ TcpSocket][@(0.0.255) `&]_[* NoGlobalT +imeout]()&] +[s2;%% Same as GlobalTimeout(Null).&] +[s3; &] [s4;%% &] [s5;:TcpSocket`:`:Blocking`(`): [_^TcpSocket^ TcpSocket][@(0.0.255) `&]_[* Blocking]()&] [s2;%% Same as Timeout(Null). Returns `*this.&]