BOOL HttpRequest(HTTPREQ* req, const wchar_t* url, const wchar_t* header, DWORD header_length, const char* body, DWORD body_length) { BOOL ret = FALSE; req->internet = WinHttpOpen(NULL, NULL, NULL, NULL, NULL); if (req->internet != NULL) { URL_COMPONENTS urlinfo = {0}; urlinfo.dwStructSize = sizeof(URL_COMPONENTS); urlinfo.dwSchemeLength = (DWORD)-1; urlinfo.dwUserNameLength = (DWORD)-1; urlinfo.dwHostNameLength = (DWORD)-1; urlinfo.dwUrlPathLength = (DWORD)-1; urlinfo.dwExtraInfoLength = (DWORD)-1; urlinfo.dwPasswordLength = (DWORD)-1; if (WinHttpCrackUrl(url, wcslen(url), 0, &urlinfo)) { if (WinHttpSetTimeouts(req->internet, req->resolveTimeout, req->connectTimeout, req->sendTimeout, req->receiveTimeout)) { TCHAR* host = new TCHAR[urlinfo.dwHostNameLength + 1]; wmemset(host, 0, urlinfo.dwHostNameLength + 1); StrCpyN(host, urlinfo.lpszHostName, urlinfo.dwHostNameLength + 1); req->connect = WinHttpConnect(req->internet, host, urlinfo.nPort, 0); if (req->connect != NULL) { if (body == NULL || body_length == 0) req->request = WinHttpOpenRequest(req->connect, L"GET", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); else req->request = WinHttpOpenRequest(req->connect, L"POST", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (req->request != NULL) { if (WinHttpSendRequest(req->request, header, header_length, (void*)body, body_length, body_length, 0) && WinHttpReceiveResponse(req->request, 0)) { TCHAR status[16] = {0}; DWORD size = sizeof(status); if (WinHttpQueryHeaders(req->request, WINHTTP_QUERY_STATUS_CODE, NULL, status, &size, 0)) { if (StrCmp(status, L"200") == 0) { char buffer[4096] = {0}; DWORD length = 0; while (TRUE) { if (WinHttpReadData(req->request, buffer, sizeof(buffer), &length) && length > 0) { AppendBuffer(&req->buffer, req->dataLength, req->bufferLength, buffer, length); length = 0; } else break; } ret = TRUE; } } } } } SAFE_DELETE_ARRAY(host); } } } return ret; }
//------------------------------------------------------------------------------------------------------------------------ const char *CHttpClient::SendRequest(const wchar_t * verb, const wchar_t * target_url, const wchar_t * headers, const wchar_t * body) { CParsedURL<wchar_t> url; url.Parse(target_url); HINTERNET hConnect = NULL, hRequest = NULL; if (hSession) // Specify an HTTP server. hConnect = WinHttpConnect(hSession, url.Base(), url.is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (hConnect) // Create an HTTP request handle. hRequest = WinHttpOpenRequest(hConnect, verb, url.Route(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); BOOL bResults = FALSE; if (hRequest) // Send a request. { if (body==nullptr) // indicates a GET request bResults = WinHttpSendRequest(hRequest, headers, wcslen(headers), WINHTTP_NO_REQUEST_DATA, 0, 0, NULL); else bResults = WinHttpSendRequest(hRequest, headers, wcslen(headers), (LPVOID)body, (DWORD)wcslen(body) * 2, (DWORD)wcslen(body) * 2, NULL); } if (bResults)// End the request. bResults = WinHttpReceiveResponse(hRequest, NULL); response.clear(); // Keep checking for data until there is nothing left. if (bResults) for (DWORD dwSize = 1; dwSize > 0;) { if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) // Check for available data. StoreErrorCode(); LPSTR pszOutBuffer = new char[dwSize + 1]; // Allocate space for the buffer. if (!pszOutBuffer) { //ReportError("Out of memory\n", -1); dwSize = 0; } else { ZeroMemory(pszOutBuffer, dwSize + 1); DWORD dwDownloaded = 0; if (WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) // Read the data. response.append(pszOutBuffer); else StoreErrorCode(); delete[] pszOutBuffer;// Free the memory allocated to the buffer. } } else // !bResults StoreErrorCode(); // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); return last_err_code? nullptr : response.c_str(); }
bool uploadToImgur(Image* image, String& response) { MemWriteFile memRaw; image->writePNG(&memRaw); bool success = false; response = "Failed to connect"; HINTERNET hSession = WinHttpOpen(L"MuleView", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0); if (hSession) { HINTERNET hConnect = WinHttpConnect(hSession, L"api.imgur.com", INTERNET_DEFAULT_HTTPS_PORT, 0); if (hConnect) { HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/3/image", L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); if (hRequest) { wchar_t* headers = L"Authorization: Client-ID b7668fe01959177\r\n" L"Content-Type: image/png\r\n"; BOOL result = WinHttpSendRequest(hRequest, headers, -1, memRaw.buffer(), memRaw.size(), memRaw.size(), NULL); if (result) result = WinHttpReceiveResponse(hRequest, NULL); DWORD avail; if (result) result = WinHttpQueryDataAvailable(hRequest, &avail); if (result) { char* ptr = new char[avail + 1]; WinHttpReadData(hRequest, ptr, avail, &avail); ptr[avail] = 0; LocalPtr<json::Value> value = json::Value::parse(File::memfile(ptr, avail, false)); json::Value* sub = (value && value->type() == json::Value::tObject ? value->get("data") : NULL); json::Value* sub2 = (sub && sub->type() == json::Value::tObject ? sub->get("id") : NULL); if (sub2 && sub2->type() == json::Value::tString) { success = true; response = sub2->getString(); } else { sub2 = (sub && sub->type() == json::Value::tObject ? sub->get("error") : NULL); if (sub2 && sub2->type() == json::Value::tString) response = sub2->getString(); } delete[] ptr; } WinHttpCloseHandle(hRequest); } WinHttpCloseHandle(hConnect); } WinHttpCloseHandle(hSession); } return success; }
HRESULT PROPFINDRequest::perform() { wstring depthProperty; wostringstream ss; BOOL bResults = FALSE; int bodyLength = 0; if (! this->hRequest) return E_INVALIDARG; ss<<L"Depth: "<<depth; depthProperty = ss.str(); //set Depth bodyLength = lstrlen(DEFAULT_PROPFIND)*sizeof(WCHAR); WinHttpAddRequestHeaders(this->hRequest, depthProperty.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_REPLACE|WINHTTP_ADDREQ_FLAG_ADD); bResults = WinHttpSendRequest(this->hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, DEFAULT_PROPFIND, bodyLength, bodyLength, 0); if (! bResults) return E_FAIL; bResults = WinHttpReceiveResponse(this->hRequest, NULL); this->updateStatus(); return S_OK; }
xlw::XlfOper HttpProtocol::Execute(const char* name, bool sendCaller, xlw::XlfOper* args, int argc) { REQUEST_CONTEXT context; context.hEvent = CreateEvent(0, 1, 0, 0); context.hConnect = WinHttpConnect(hSession, host, urlc.nPort, 0); int flags = WINHTTP_FLAG_BYPASS_PROXY_CACHE; if(urlc.nScheme == INTERNET_SCHEME_HTTPS) flags |= WINHTTP_FLAG_SECURE; context.hRequest = WinHttpOpenRequest(context.hConnect, L"POST", path, 0, 0, 0, flags); context.conf.beautify = 0; context.conf.indentString = ""; context.g = yajl_gen_alloc(&context.conf, 0); context.px = xlw::XlfOper(); //context.px->xltype = xltypeNil | xlbitDLLFree; GenerateRequest(context.g, name, sendCaller, args, argc); const unsigned char * buf; unsigned int len = 0; yajl_gen_get_buf(context.g, &buf, &len); BOOL res = FALSE; res = WinHttpSendRequest(context.hRequest, 0, 0, (LPVOID) buf, len, len, (DWORD_PTR) &context); if(!res) { const char* err = "#Could not connect to server"; Log::Error(err); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } // TODO timeout/background res = WinHttpReceiveResponse(context.hRequest, 0); if(!res) { const char* err = "#Error retrieving server response"; Log::Error(err); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } // Check http response code DWORD status; DWORD statusLength = 4; res = WinHttpQueryHeaders(context.hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &statusLength, 0); if(!res || status != 200) { Log::Error("Status code: %d", status); const char* err = "#Server returned an error"; WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } ReadData(&context); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); yajl_gen_clear(context.g); yajl_gen_free(context.g); //context.px->xltype |= xlbitDLLFree; return context.px; }
static HRESULT send_message( struct channel *channel, BYTE *data, ULONG len ) { if (!WinHttpSendRequest( channel->http_request, NULL, 0, data, len, len, 0 )) return HRESULT_FROM_WIN32( GetLastError() ); if (!WinHttpReceiveResponse( channel->http_request, NULL )) return HRESULT_FROM_WIN32( GetLastError() ); return S_OK; }
bool Http::Send(WCHAR szUrl[]) { if (this->hSession == NULL) return false; HINTERNET hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; LPBYTE lpHeader, lpData; DWORD dwSize; ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS)); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.lpszHostName = szHostName; urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR); urlComponents.lpszUrlPath = szUrlPath; urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR); if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) { WinHttpCloseHandle(hSession); return false; } hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return false; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return false; } if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return false; } WinHttpReceiveResponse(hRequest, NULL); dwSize = 0; lpData = ReadData(hRequest, &dwSize); HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return true; }
void CWinHTTPUtil::StatusSendRequestComplete() { if( this->totalUpSize > 0 ){ //アップ処理 this->upThread = (HANDLE)_beginthreadex( NULL, 0, UploadThread, this, CREATE_SUSPENDED, NULL ); if( this->upThread == NULL ){ return ; } ResumeThread(this->upThread); }else{ WinHttpReceiveResponse(this->request, NULL); } }
bool CWinHttp::SendRequest(PVOID pBuffer,int LenOfData) { bool bRet=false, bResults=false; //int n=GetLastError(); if(!hRequest) goto exit0; // Send a request. if(lstrcmpW(m_strVerb,L"GET")==0) { bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); } else { if(LenOfData>=1024) goto exit0; bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, LenOfData, 0); PostDataToServer(pBuffer,LenOfData); } if(!bResults) goto exit0; // End the request. bResults = WinHttpReceiveResponse(hRequest, NULL); if(!bResults) goto exit0; bRet=true; exit0: assert(bRet!=false); return bRet; }
static void test_redirect( void ) { static const WCHAR codeweavers[] = {'c','o','d','e','w','e','a','v','e','r','s','.','c','o','m',0}; HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; info.test = redirect_test; info.count = sizeof(redirect_test) / sizeof(redirect_test[0]); info.index = 0; info.wait = NULL; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, codeweavers, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); }
BOOL GetHttpResponse(PBYTE pBufOut,DWORD& dwBuf,HINTERNET hRequest) { dwBuf = 0; DWORD dwSize = 0; BOOL bResults = WinHttpReceiveResponse( hRequest, NULL); if(bResults) { do { // Check for available data. dwSize = 0; bResults = WinHttpQueryDataAvailable( hRequest, &dwSize); // Read the Data. ZeroMemory(pBufOut+dwBuf, dwSize+1); DWORD dwDownloaded=0; WinHttpReadData( hRequest, (LPVOID)(pBufOut+dwBuf), dwSize, &dwDownloaded); dwBuf+=dwDownloaded; } while (dwSize > 0); } return bResults; }
HRESULT GETRequest::perform() { wstring rangeProperty; wostringstream ss; BOOL bResults = FALSE; if (! this->hRequest) return E_INVALIDARG; if (this->offset > 0 && this->length > 0) { ss<<L"Range: bytes="<<(int)this->offset<<L"-"<<(int)(this->offset+this->length); rangeProperty = ss.str(); WinHttpAddRequestHeaders(this->hRequest, rangeProperty.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_REPLACE|WINHTTP_ADDREQ_FLAG_ADD); } bResults = WinHttpSendRequest(this->hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if (! bResults) return E_FAIL; bResults = WinHttpReceiveResponse(this->hRequest, NULL); this->updateStatus(); return S_OK; }
BOOL HTTPGetFile (CTSTR url, CTSTR outputPath, CTSTR extraHeaders, int *responseCode) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; BOOL ret = FALSE; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(url, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(OBS_VERSION_STRING, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { BYTE buffer[16384]; DWORD dwSize, dwOutSize; XFile updateFile; if (!updateFile.Open(outputPath, XFILE_WRITE, CREATE_ALWAYS)) goto failure; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; if (!updateFile.Write(buffer, dwOutSize)) goto failure; } } while (dwSize > 0); updateFile.Close(); } ret = TRUE; failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return ret; }
/*! * @brief Wrapper around WinHTTP-specific receiving functionality. * @param hReq HTTP request handle. * @return An indication of the result of receiving the request. */ static BOOL receive_response_winhttp(HANDLE hReq) { return WinHttpReceiveResponse(hReq, NULL); }
String HTTPGetString (CTSTR url, CTSTR extraHeaders, int *responseCode, String verb) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; String result = ""; String body = TEXT(""); String nurl = url; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; if (verb == TEXT("POST")){ CTSTR s = srchr(url, TEXT('?')); body = String(s + 1); nurl = nurl.Left(s - url); } hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(nurl, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(TEXT("gecko test"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, verb, path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, body.Array(), body.Length(), body.Length(), 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { CHAR buffer[16384]; DWORD dwSize, dwOutSize; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; // Ensure the string is terminated. buffer[dwOutSize] = 0; String b = String((LPCSTR)buffer); result.AppendString(b); } } while (dwSize > 0); } failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return result; }
BOOL CSyoboiCalUtil::SendReserve(const vector<RESERVE_DATA>* reserveList, const vector<TUNER_RESERVE_INFO>* tunerList) { if( reserveList == NULL || tunerList == NULL ){ return FALSE; } if( reserveList->size() == 0 ){ return FALSE; } wstring iniAppPath = L""; GetModuleIniPath(iniAppPath); if( GetPrivateProfileInt(L"SYOBOI", L"use", 0, iniAppPath.c_str()) == 0 ){ return FALSE; } _OutputDebugString(L"★SyoboiCalUtil:SendReserve"); wstring textPath; GetModuleFolderPath(textPath); textPath += L"\\SyoboiCh.txt"; CParseServiceChgText srvChg; srvChg.ParseText(textPath.c_str()); wstring proxyServerName; wstring proxyUserName; wstring proxyPassword; if( GetPrivateProfileInt(L"SYOBOI", L"useProxy", 0, iniAppPath.c_str()) != 0 ){ proxyServerName = GetPrivateProfileToString(L"SYOBOI", L"ProxyServer", L"", iniAppPath.c_str()); proxyUserName = GetPrivateProfileToString(L"SYOBOI", L"ProxyID", L"", iniAppPath.c_str()); proxyPassword = GetPrivateProfileToString(L"SYOBOI", L"ProxyPWD", L"", iniAppPath.c_str()); } wstring id=GetPrivateProfileToString(L"SYOBOI", L"userID", L"", iniAppPath.c_str()); wstring pass=GetPrivateProfileToString(L"SYOBOI", L"PWD", L"", iniAppPath.c_str()); int slot = GetPrivateProfileInt(L"SYOBOI", L"slot", 0, iniAppPath.c_str()); wstring devcolors=GetPrivateProfileToString(L"SYOBOI", L"devcolors", L"", iniAppPath.c_str()); wstring epgurl=GetPrivateProfileToString(L"SYOBOI", L"epgurl", L"", iniAppPath.c_str()); if( id.size() == 0 ){ _OutputDebugString(L"★SyoboiCalUtil:NoUserID"); return FALSE; } //Authorization wstring auth = L""; auth = id; auth += L":"; auth += pass; string authA; WtoA(auth, authA); DWORD destSize = 0; Base64Enc(authA.c_str(), (DWORD)authA.size(), NULL, &destSize); vector<WCHAR> base64(destSize + 1, L'\0'); Base64Enc(authA.c_str(), (DWORD)authA.size(), &base64.front(), &destSize); //無駄なCRLFが混じることがあるため std::replace(base64.begin(), base64.end(), L'\r', L'\0'); std::replace(base64.begin(), base64.end(), L'\n', L'\0'); wstring authHead = L""; Format(authHead, L"Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", &base64.front()); //data wstring dataParam; wstring param; map<DWORD, wstring> tunerMap; for( size_t i=0; i<tunerList->size(); i++ ){ for( size_t j=0; j<(*tunerList)[i].reserveList.size(); j++ ){ tunerMap.insert(pair<DWORD, wstring>((*tunerList)[i].reserveList[j], (*tunerList)[i].tunerName)); } } map<DWORD, wstring>::iterator itrTuner; DWORD dataCount = 0; for(size_t i=0; i<reserveList->size(); i++ ){ if( dataCount>=200 ){ break; } const RESERVE_DATA* info = &(*reserveList)[i]; if( info->recSetting.recMode == RECMODE_NO || info->recSetting.recMode == RECMODE_VIEW ){ continue; } wstring device=L""; itrTuner = tunerMap.find(info->reserveID); if( itrTuner != tunerMap.end() ){ device = itrTuner->second; } wstring stationName = info->stationName; srvChg.ChgText(stationName); __int64 startTime = GetTimeStamp(info->startTime); Format(param, L"%I64d\t%I64d\t%s\t%s\t%s\t\t0\t%d\n", startTime, startTime+info->durationSecond, device.c_str(), info->title.c_str(), stationName.c_str(), info->reserveID ); dataParam+=param; } if(dataParam.size() == 0 ){ _OutputDebugString(L"★SyoboiCalUtil:NoReserve"); return FALSE; } string utf8; UrlEncodeUTF8(dataParam.c_str(), (DWORD)dataParam.size(), utf8); string data; Format(data, "slot=%d&data=%s",slot, utf8.c_str()); if( devcolors.size() > 0){ utf8 = ""; UrlEncodeUTF8(devcolors.c_str(), (DWORD)devcolors.size(), utf8); data += "&devcolors="; data += utf8; } if( epgurl.size() > 0){ utf8 = ""; UrlEncodeUTF8(epgurl.c_str(), (DWORD)epgurl.size(), utf8); data += "&epgurl="; data += utf8; } vector<char> dataBuff(data.begin(), data.end()); //URLの分解 URL_COMPONENTS stURL = {}; stURL.dwStructSize = sizeof(stURL); stURL.dwSchemeLength = (DWORD)-1; stURL.dwHostNameLength = (DWORD)-1; stURL.dwUrlPathLength = (DWORD)-1; stURL.dwExtraInfoLength = (DWORD)-1; if( WinHttpCrackUrl(SYOBOI_UP_URL, 0, 0, &stURL) == FALSE || stURL.dwHostNameLength == 0 ){ return FALSE; } wstring host(stURL.lpszHostName, stURL.dwHostNameLength); wstring sendUrl(stURL.lpszUrlPath, stURL.dwUrlPathLength + stURL.dwExtraInfoLength); HINTERNET session; if( proxyServerName.empty() ){ session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); }else{ session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NAMED_PROXY, proxyServerName.c_str(), WINHTTP_NO_PROXY_BYPASS, 0); } if( session == NULL ){ return FALSE; } LPCWSTR result = L"1"; HINTERNET connect = NULL; HINTERNET request = NULL; if( WinHttpSetTimeouts(session, 15000, 15000, 15000, 15000) == FALSE ){ result = L"0 SetTimeouts"; goto EXIT; } //コネクションオープン connect = WinHttpConnect(session, host.c_str(), stURL.nPort, 0); if( connect == NULL ){ result = L"0 Connect"; goto EXIT; } //リクエストオープン request = WinHttpOpenRequest(connect, L"POST", sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ? WINHTTP_FLAG_SECURE : 0); if( request == NULL ){ result = L"0 OpenRequest"; goto EXIT; } if( proxyServerName.empty() == false ){ //ProxyのIDかパスワードがあったらセット if( proxyUserName.empty() == false || proxyPassword.empty() == false ){ if( WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, proxyUserName.c_str(), proxyPassword.c_str(), NULL) == FALSE ){ result = L"0 SetCredentials"; goto EXIT; } } } if( WinHttpSendRequest(request, authHead.c_str(), (DWORD)-1, &dataBuff.front(), (DWORD)dataBuff.size(), (DWORD)dataBuff.size(), 0) == FALSE ){ result = L"0 SendRequest"; goto EXIT; } if( WinHttpReceiveResponse(request, NULL) == FALSE ){ result = L"0 ReceiveResponse"; goto EXIT; } //HTTPのステータスコード確認 DWORD statusCode; DWORD statusCodeSize = sizeof(statusCode); if( WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX) == FALSE ){ statusCode = 0; } if( statusCode != 200 && statusCode != 201 ){ result = L"0 StatusNotOK"; goto EXIT; } EXIT: if( request != NULL ){ WinHttpCloseHandle(request); } if( connect != NULL ){ WinHttpCloseHandle(connect); } if( session != NULL ){ WinHttpCloseHandle(session); } _OutputDebugString(L"★SyoboiCalUtil:SendRequest res:%s", result); if( result[0] != L'1' ){ return FALSE; } return TRUE; }
void main() { DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer = NULL; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; BOOL bResults = FALSE; hSession=WinHttpOpen(L"User-Agent",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0); if(hSession) { hConnect=WinHttpConnect(hSession,L"kinggigi.sinaapp.com",INTERNET_DEFAULT_HTTP_PORT,0); } if(hConnect) { hRequest=WinHttpOpenRequest(hConnect, L"POST",L"hello.php",L"HTTP/1.1", WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0); } LPCWSTR header=L"Content-type: application/x-www-form-urlencoded"; SIZE_T len = lstrlenW(header); WinHttpAddRequestHeaders(hRequest,header,DWORD(len), WINHTTP_ADDREQ_FLAG_ADD); if(hRequest) { std::string data="val1=10&val2=9"; const void *ss=(const char *)data.c_str(); bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, const_cast<void *>(ss), data.length(), data.length(), 0); ////bResults=WinHttpSendRequest(hRequest,WINHTTP_NO_ADDITIONAL_HEADERS, 0,WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); } if(bResults) { bResults=WinHttpReceiveResponse(hRequest,NULL); } if(bResults) { do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) { printf( "Error %u in WinHttpQueryDataAvailable.\n",GetLastError()); break; } if (!dwSize) break; pszOutBuffer = new char[dwSize+1]; if (!pszOutBuffer) { printf("Out of memory\n"); break; } ZeroMemory(pszOutBuffer, dwSize+1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) { printf( "Error %u in WinHttpReadData.\n", GetLastError()); } else { printf("%s", pszOutBuffer); } delete [] pszOutBuffer; if (!dwDownloaded) break; } while (dwSize > 0); } if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); system("pause"); }
string fetchUrl(string server, string path) { BOOL bResults = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; string result; wstring wserver(server.begin(), server.end()); wstring wpath(path.begin(), path.end()); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"Penis Browser/1.1", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, wserver.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", wpath.c_str(), NULL, WINHTTP_NO_REFERER, NULL, NULL); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { DWORD dwSize = 0; do { DWORD dwDownloaded = 0; LPSTR pszOutBuffer; // Check for available data. WinHttpQueryDataAvailable(hRequest, &dwSize); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; // Read the Data. ZeroMemory(pszOutBuffer, dwSize + 1); if (WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) result.append(string(pszOutBuffer, dwDownloaded)); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } while (dwSize > 0); } // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return result; }
khm_int32 HttpRequest::FetchResource(const wchar_t * domain, const wchar_t * resource, const wchar_t ** mimetypes) { HANDLE hFile = INVALID_HANDLE_VALUE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; DWORD nTotalBytes = 0; BOOL bContinue = TRUE; khm_int32 rv = KHM_ERROR_GENERAL; hSession = WinHttpOpen(USER_AGENT, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) { ReportStatus(KHERR_ERROR, L"Can't create HTTP session", L"%s", GetLastErrorString().c_str()); goto done; } hConnect = WinHttpConnect(hSession, domain, INTERNET_DEFAULT_HTTP_PORT, 0); if (hConnect == NULL) { ReportStatus(KHERR_ERROR, L"Can't open HTTP connection", L"%s", GetLastErrorString().c_str()); goto done; } hRequest = WinHttpOpenRequest(hConnect, L"GET", resource, NULL, WINHTTP_NO_REFERER, mimetypes, WINHTTP_FLAG_ESCAPE_PERCENT); if (hRequest == NULL) { ReportStatus(KHERR_ERROR, L"Can't open request", L"%s", GetLastErrorString().c_str()); goto done; } { DWORD opt; opt = WINHTTP_DISABLE_AUTHENTICATION; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; opt = WINHTTP_DISABLE_COOKIES; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; opt = WINHTTP_DISABLE_KEEP_ALIVE; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; } rv = KHM_ERROR_NOT_FOUND; if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) { ReportStatus(KHERR_ERROR, L"Can't send request to server", L"Unable to send HTTP request to server at %s.\n" L"%s", domain, GetLastErrorString().c_str()); goto done; } if (!WinHttpReceiveResponse(hRequest, NULL)) { ReportStatus(KHERR_ERROR, L"Error while receiving response", L"%s", GetLastErrorString().c_str()); goto done; } rv = KHM_ERROR_GENERAL; { DWORD status = 0; DWORD nb = sizeof(status); if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &nb, WINHTTP_NO_HEADER_INDEX)) { ReportStatus(KHERR_ERROR, L"Error while querying response status", L"%s", GetLastErrorString().c_str()); goto done; } if (status == HTTP_STATUS_NOT_FOUND) { switch (m_method) { case ByFavIcon: // Status reports are ignored for Favicon searches // anyway. break; case ByGravatar: ReportStatus(KHERR_ERROR, L"Could not find Gravatar", L"An icon could not be found for %s on %s.\n", m_target.c_str(), domain); break; default: ReportStatus(KHERR_ERROR, L"The requested resource was not found", L"The requested resource was not found on %s.", domain); break; } rv = KHM_ERROR_NOT_FOUND; goto done; } if (status != HTTP_STATUS_OK) { ReportStatus(KHERR_ERROR, L"The request failed", L"The server at %s returned an unexpected status (%d)", domain, status); rv = KHM_ERROR_GENERAL; goto done; } } { wchar_t contenttype[128]; DWORD nb = sizeof(contenttype); int i; if (WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, contenttype, &nb, WINHTTP_NO_HEADER_INDEX)) { std::wstring::size_type epos; epos = m_path.rfind(L'.'); if (epos != std::wstring::npos) m_path.erase(epos); for (i=0; i < ARRAYLENGTH(content_type_map); i++) { if (!_wcsicmp(contenttype, content_type_map[i].content_type)) break; } if (i < ARRAYLENGTH(content_type_map)) { m_path.append(content_type_map[i].extension); } else { ReportStatus(KHERR_WARNING, L"Unknown content type", L"The content type %s was not expected for this request.", contenttype); } } else { ReportStatus(KHERR_WARNING, L"Could not query response content type", L"%s", GetLastErrorString().c_str()); } } /* The request went through. Create the file now */ hFile = CreateFile(m_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile == INVALID_HANDLE_VALUE) { ReportStatus(KHERR_ERROR, L"Can't create file", L"%s", GetLastErrorString().c_str()); goto done; } while (nTotalBytes < MAX_ICON_SIZE && bContinue) { DWORD nBytes = 0; BYTE * buffer = NULL; DWORD nRead = 0; DWORD nWritten = 0; bContinue = FALSE; if (!WinHttpQueryDataAvailable(hRequest, &nBytes)) break; if (nBytes == 0) { bContinue = TRUE; break; } if (nBytes + nTotalBytes > MAX_ICON_SIZE) break; buffer = PNEW BYTE[nBytes]; if (buffer == NULL) break; if (!WinHttpReadData(hRequest, buffer, nBytes, &nRead) || nRead == 0) { /* Fail */ } else { /* Data found */ if (WriteFile(hFile, buffer, nRead, &nWritten, NULL)) bContinue = TRUE; } delete [] buffer; nTotalBytes += nBytes; } if (bContinue) { /* Done with file */ rv = KHM_ERROR_SUCCESS; } else { /* File is incomplete */ ReportStatus(KHERR_ERROR, L"Download incomplete", L"The download was terminated unexpectedly."); DeleteFile(m_path.c_str()); } done: if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); ReportComplete(KHM_SUCCEEDED(rv)); return rv; }
bool GameJoltAPI::SendRequest( CStdString &output, CStdString url ) { // The private key must be set to send a request. if ( m_GamePrivateKey == _T("") ) { m_ErrorMessage += _T("(You must put in your game's private key before you can use any of the API functions.)"); return false; } //////////////////////////////////// // Let's form the URL first. url = GJAPI_ROOT + GJAPI_VERSION + url; CStdString signature( md5( CStdStringA( _T("http://") + GJAPI_SERVER + url + m_GamePrivateKey ) ) ); url += _T("&signature=") + signature; // Now let's build the request. BOOL ret = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; hSession = WinHttpOpen ( L"Game Jolt API Construct/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if ( hSession ) hConnect = WinHttpConnect ( hSession, CStdStringW( GJAPI_SERVER ), INTERNET_DEFAULT_PORT, 0 ); else m_ErrorMessage += _T("(Could not open HTTP session.)"); if ( hConnect ) hRequest = WinHttpOpenRequest ( hConnect, L"GET", CStdStringW( url ), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH ); else m_ErrorMessage += _T("(Could not connect to the HTTP session.)"); if ( hRequest ) ret = WinHttpSendRequest ( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); else m_ErrorMessage += _T("(Could not set up the HTTP request.)"); if ( ret ) ret = WinHttpReceiveResponse( hRequest, NULL ); else m_ErrorMessage += _T("(Could not send the HTTP request.)"); DWORD bufferSize = 0; DWORD outputDownloaded = 0; LPSTR outputBuffer = 0; // Keep checking for data until there is nothing left. if ( ret ) { do { // Check for available data. bufferSize = 0; WinHttpQueryDataAvailable( hRequest, &bufferSize ); // Allocate space for the buffer. outputBuffer = new char[bufferSize + 1]; if ( outputBuffer ) { // Read the data. ZeroMemory( outputBuffer, bufferSize + 1 ); if ( WinHttpReadData( hRequest, (LPVOID)outputBuffer, bufferSize, &outputDownloaded ) ) output += outputBuffer; // Free the memory allocated to the buffer. delete [] outputBuffer; } } while( bufferSize > 0 ); } else m_ErrorMessage += _T("(Did not get a response from the server.)"); if ( hRequest ) WinHttpCloseHandle( hRequest ); if ( hConnect ) WinHttpCloseHandle( hConnect ); if ( hSession ) WinHttpCloseHandle( hSession ); return true; }
BOOL DoBlockingHttpGet( const char* sRequestedPage, char* pBufferOut, const unsigned int /*nBufferOutSize*/, DWORD* pBytesRead ) { BOOL bResults = FALSE, bSuccess = FALSE; HINTERNET hSession = nullptr, hConnect = nullptr, hRequest = nullptr; WCHAR wBuffer[1024]; size_t nTemp; char* sDataDestOffset = &pBufferOut[0]; DWORD nBytesToRead = 0; DWORD nBytesFetched = 0; char sClientName[1024]; sprintf_s( sClientName, 1024, "Retro Achievements Client" ); WCHAR wClientNameBuffer[1024]; mbstowcs_s( &nTemp, wClientNameBuffer, 1024, sClientName, strlen(sClientName)+1 ); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen( wClientNameBuffer, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if( hSession != nullptr ) { hConnect = WinHttpConnect( hSession, L"www.retroachievements.org", INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP Request handle. if( hConnect != nullptr ) { mbstowcs_s( &nTemp, wBuffer, 1024, sRequestedPage, strlen(sRequestedPage)+1 ); hRequest = WinHttpOpenRequest( hConnect, L"GET", wBuffer, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); // Send a Request. if( hRequest != nullptr ) { bResults = WinHttpSendRequest( hRequest, L"Content-Type: application/x-www-form-urlencoded", 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if( WinHttpReceiveResponse( hRequest, NULL ) ) { nBytesToRead = 0; (*pBytesRead) = 0; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); while( nBytesToRead > 0 ) { char sHttpReadData[8192]; ZeroMemory( sHttpReadData, 8192*sizeof(char) ); assert( nBytesToRead <= 8192 ); if( nBytesToRead <= 8192 ) { nBytesFetched = 0; if( WinHttpReadData( hRequest, &sHttpReadData, nBytesToRead, &nBytesFetched ) ) { assert( nBytesToRead == nBytesFetched ); //Read: parse buffer memcpy( sDataDestOffset, sHttpReadData, nBytesFetched ); sDataDestOffset += nBytesFetched; (*pBytesRead) += nBytesFetched; } } bSuccess = TRUE; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); } } } } } // Close open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return bSuccess; }
DWORD WINAPI SendProc(LPVOID data) { DWORD dataSize = 0; DWORD bytesDownloaded = 0; LPSTR outBuffer; BOOL result = FALSE; HINTERNET session = NULL,connection = NULL,request = NULL; std::wstring *wurl = (std::wstring*)data; if( wurl == NULL ) { return result; } session = WinHttpOpen(GA_HOST.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if( session ) connection = WinHttpConnect( session, GA_HOST.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0 ); if( connection ) request = WinHttpOpenRequest( connection, L"GET", wurl->c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0 ); if( request ) result = WinHttpSendRequest( request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); //DWORD n = GetLastError(); if( result ) result = WinHttpReceiveResponse( request, NULL ); if( result ) { do { dataSize = 0; if( !WinHttpQueryDataAvailable( request, &dataSize ) ) return FALSE; outBuffer = new char[dataSize+1]; if( !outBuffer ) { return false; } else { ZeroMemory( outBuffer, dataSize+1 ); if( !WinHttpReadData( request, (LPVOID)outBuffer, dataSize, &bytesDownloaded ) ) { delete []outBuffer; return false; } // TODO: if you care about the response, please handle it here... // delete[] outBuffer; } } while( dataSize > 0 ); } // clean up if( request ) WinHttpCloseHandle( request ); if( connection ) WinHttpCloseHandle( connection ); if( session ) WinHttpCloseHandle( session ); delete wurl; return result; }
static void test_async( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; char buffer[1024]; info.test = async_test; info.count = sizeof(async_test) / sizeof(async_test[0]); info.index = 0; info.wait = CreateEventW( NULL, FALSE, FALSE, NULL ); ses = WinHttpOpen( user_agent, 0, NULL, NULL, WINHTTP_FLAG_ASYNC ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_query_data, __LINE__ ); ret = WinHttpQueryDataAvailable( req, NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_read_data, __LINE__ ); ret = WinHttpReadData( req, buffer, sizeof(buffer), NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); WaitForSingleObject( info.wait, INFINITE ); CloseHandle( info.wait ); }
static void test_connection_cache( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; info.test = cache_test; info.count = sizeof(cache_test) / sizeof(cache_test[0]); info.index = 0; info.wait = NULL; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ info.index = 0; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ }
static int winhttp_stream_read( git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { winhttp_stream *s = (winhttp_stream *)stream; winhttp_subtransport *t = OWNING_SUBTRANSPORT(s); DWORD dw_bytes_read; char replay_count = 0; int error; replay: /* Enforce a reasonable cap on the number of replays */ if (++replay_count >= 7) { giterr_set(GITERR_NET, "Too many redirects or authentication replays"); return -1; } /* Connect if necessary */ if (!s->request && winhttp_stream_connect(s) < 0) return -1; if (!s->received_response) { DWORD status_code, status_code_length, content_type_length, bytes_written; char expected_content_type_8[MAX_CONTENT_TYPE_LEN]; wchar_t expected_content_type[MAX_CONTENT_TYPE_LEN], content_type[MAX_CONTENT_TYPE_LEN]; if (!s->sent_request) { if ((error = send_request(s, s->post_body_len, 0)) < 0) return error; s->sent_request = 1; } if (s->chunked) { assert(s->verb == post_verb); /* Flush, if necessary */ if (s->chunk_buffer_len > 0 && write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0) return -1; s->chunk_buffer_len = 0; /* Write the final chunk. */ if (!WinHttpWriteData(s->request, "0\r\n\r\n", 5, &bytes_written)) { giterr_set(GITERR_OS, "Failed to write final chunk"); return -1; } } else if (s->post_body) { char *buffer; DWORD len = s->post_body_len, bytes_read; if (INVALID_SET_FILE_POINTER == SetFilePointer(s->post_body, 0, 0, FILE_BEGIN) && NO_ERROR != GetLastError()) { giterr_set(GITERR_OS, "Failed to reset file pointer"); return -1; } buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE); while (len > 0) { DWORD bytes_written; if (!ReadFile(s->post_body, buffer, min(CACHED_POST_BODY_BUF_SIZE, len), &bytes_read, NULL) || !bytes_read) { git__free(buffer); giterr_set(GITERR_OS, "Failed to read from temp file"); return -1; } if (!WinHttpWriteData(s->request, buffer, bytes_read, &bytes_written)) { git__free(buffer); giterr_set(GITERR_OS, "Failed to write data"); return -1; } len -= bytes_read; assert(bytes_read == bytes_written); } git__free(buffer); /* Eagerly close the temp file */ CloseHandle(s->post_body); s->post_body = NULL; } if (!WinHttpReceiveResponse(s->request, 0)) { giterr_set(GITERR_OS, "Failed to receive response"); return -1; } /* Verify that we got a 200 back */ status_code_length = sizeof(status_code); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status_code, &status_code_length, WINHTTP_NO_HEADER_INDEX)) { giterr_set(GITERR_OS, "Failed to retrieve status code"); return -1; } /* The implementation of WinHTTP prior to Windows 7 will not * redirect to an identical URI. Some Git hosters use self-redirects * as part of their DoS mitigation strategy. Check first to see if we * have a redirect status code, and that we haven't already streamed * a post body. (We can't replay a streamed POST.) */ if (!s->chunked && (HTTP_STATUS_MOVED == status_code || HTTP_STATUS_REDIRECT == status_code || (HTTP_STATUS_REDIRECT_METHOD == status_code && get_verb == s->verb) || HTTP_STATUS_REDIRECT_KEEP_VERB == status_code)) { /* Check for Windows 7. This workaround is only necessary on * Windows Vista and earlier. Windows 7 is version 6.1. */ wchar_t *location; DWORD location_length; char *location8; /* OK, fetch the Location header from the redirect. */ if (WinHttpQueryHeaders(s->request, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, WINHTTP_NO_OUTPUT_BUFFER, &location_length, WINHTTP_NO_HEADER_INDEX) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) { giterr_set(GITERR_OS, "Failed to read Location header"); return -1; } location = git__malloc(location_length); GITERR_CHECK_ALLOC(location); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, location, &location_length, WINHTTP_NO_HEADER_INDEX)) { giterr_set(GITERR_OS, "Failed to read Location header"); git__free(location); return -1; } /* Convert the Location header to UTF-8 */ if (git__utf16_to_8_alloc(&location8, location) < 0) { giterr_set(GITERR_OS, "Failed to convert Location header to UTF-8"); git__free(location); return -1; } git__free(location); /* Replay the request */ winhttp_stream_close(s); if (!git__prefixcmp_icase(location8, prefix_https)) { /* Upgrade to secure connection; disconnect and start over */ if (gitno_connection_data_from_url(&t->connection_data, location8, s->service_url) < 0) { git__free(location8); return -1; } winhttp_close_connection(t); if (winhttp_connect(t) < 0) return -1; } git__free(location8); goto replay; } /* Handle authentication failures */ if (HTTP_STATUS_DENIED == status_code && get_verb == s->verb) { int allowed_types; if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanism) < 0) return -1; if (allowed_types && (!t->cred || 0 == (t->cred->credtype & allowed_types))) { int cred_error = 1; /* Start with the user-supplied credential callback, if present */ if (t->owner->cred_acquire_cb) { cred_error = t->owner->cred_acquire_cb(&t->cred, t->owner->url, t->connection_data.user, allowed_types, t->owner->cred_acquire_payload); if (cred_error < 0) return cred_error; } /* Invoke the fallback credentials acquisition callback if necessary */ if (cred_error > 0) { cred_error = fallback_cred_acquire_cb(&t->cred, t->owner->url, t->connection_data.user, allowed_types, NULL); if (cred_error < 0) return cred_error; } if (!cred_error) { assert(t->cred); winhttp_stream_close(s); /* Successfully acquired a credential */ goto replay; } } } if (HTTP_STATUS_OK != status_code) { giterr_set(GITERR_NET, "Request failed with status code: %d", status_code); return -1; } /* Verify that we got the correct content-type back */ if (post_verb == s->verb) p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-result", s->service); else p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-advertisement", s->service); if (git__utf8_to_16(expected_content_type, MAX_CONTENT_TYPE_LEN, expected_content_type_8) < 0) { giterr_set(GITERR_OS, "Failed to convert expected content-type to wide characters"); return -1; } content_type_length = sizeof(content_type); if (!WinHttpQueryHeaders(s->request, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, &content_type, &content_type_length, WINHTTP_NO_HEADER_INDEX)) { giterr_set(GITERR_OS, "Failed to retrieve response content-type"); return -1; } if (wcscmp(expected_content_type, content_type)) { giterr_set(GITERR_NET, "Received unexpected content-type"); return -1; } s->received_response = 1; } if (!WinHttpReadData(s->request, (LPVOID)buffer, (DWORD)buf_size, &dw_bytes_read)) { giterr_set(GITERR_OS, "Failed to read data"); return -1; } *bytes_read = dw_bytes_read; return 0; }
void HTTPMsg::onSendComplete(){ _buff.reset(); WinHttpReceiveResponse(_hRequest, NULL); }
int _tmain(int argc, _TCHAR* argv[]) { // WinHTTP Sessions Overview | https://msdn.microsoft.com/en-us/library/windows/desktop/aa384270(v=vs.85).aspx DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, L"www.microsoft.com", INTERNET_DEFAULT_HTTPS_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", NULL, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError()); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; if (!pszOutBuffer) { printf("Out of memory\n"); dwSize = 0; } else { // Read the data. ZeroMemory(pszOutBuffer, dwSize + 1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) printf("Error %u in WinHttpReadData.\n", GetLastError()); else printf("%s", pszOutBuffer); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } } while (dwSize > 0); } // Report any errors. if (!bResults) printf("Error %d has occurred.\n", GetLastError()); // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return 0; }
UINT CWinHTTPUtil::UploadThread(LPVOID pParam) { if( pParam == NULL ){ return 0; } CWinHTTPUtil* sys = (CWinHTTPUtil*)pParam; HANDLE eventArray[2]; eventArray[0] = sys->upStopEvent; eventArray[1] = sys->writeCompEvent; SetEvent(sys->writeCompEvent); for( size_t i=0; i<sys->upDataList.size(); i++ ){ UPLOAD_DATA* data = sys->upDataList[i]; if( data->filePathFlag == FALSE ){ DWORD res = WaitForMultipleObjects(2, eventArray, FALSE, INFINITE); if( res == WAIT_OBJECT_0 ){ //STOP break; }else if( res == WAIT_OBJECT_0+1 ){ WinHttpWriteData( sys->request, data->buff, data->buffSize, NULL ); } }else{ HANDLE file; file = CreateFile( (WCHAR*)data->buff, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if( file == INVALID_HANDLE_VALUE ){ sys->errEndCode = ERR_NW_FILE_OPEN; WinHttpSetStatusCallback( sys->request, NULL, NULL, NULL ); SetEvent(sys->responseCompEvent); return 0; } DWORD readSize = 0; DWORD readBuffSize = 0; BYTE buff[SEND_BUFF_SIZE]; DWORD fileSize = GetFileSize(file, NULL); while( readSize < fileSize ){ DWORD res = WaitForMultipleObjects(2, eventArray, FALSE, INFINITE); if( res == WAIT_OBJECT_0 ){ //STOP break; }else if( res == WAIT_OBJECT_0+1 ){ DWORD buffSize = 0; if( SEND_BUFF_SIZE+readSize < fileSize ){ buffSize = SEND_BUFF_SIZE; }else{ buffSize = fileSize - readSize; } if( ReadFile(file, buff, SEND_BUFF_SIZE, &readBuffSize, NULL ) == FALSE ){ sys->errEndCode = ERR_NW_FILE_OPEN; WinHttpSetStatusCallback( sys->request, NULL, NULL, NULL ); SetEvent(sys->responseCompEvent); return 0; }else{ DWORD retryCount = 0; while( WinHttpWriteData( sys->request, buff, readBuffSize, NULL ) == FALSE ){ Sleep(200); if( retryCount > 100 ){ sys->errEndCode = ERR_NW_FALSE; WinHttpSetStatusCallback( sys->request, NULL, NULL, NULL ); SetEvent(sys->responseCompEvent); return 0; } retryCount++; } } readSize+=buffSize; } } CloseHandle(file); } } WinHttpReceiveResponse(sys->request, NULL); sys->ClearUpList(); return 0; }
// handle WinHTTP callbacks (which can be in a worker thread context) VOID CALLBACK WinHttpIO::asynccallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { WinHttpContext* httpctx = (WinHttpContext*)dwContext; WinHttpIO* httpio = (WinHttpIO*)httpctx->httpio; if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) { LOG_verbose << "Closing request"; assert(!httpctx->req); if (httpctx->gzip) { inflateEnd(&httpctx->z); } delete httpctx; return; } httpio->lock(); HttpReq* req = httpctx->req; // request cancellations that occured after asynccallback() was entered are caught here if (!req) { LOG_verbose << "Request cancelled"; httpio->unlock(); return; } switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: { DWORD size = *(DWORD*)lpvStatusInformation; if (!size) { if (req->binary) { LOG_debug << "[received " << (req->buf ? req->buflen : req->in.size()) << " bytes of raw data]"; } else { if(req->in.size() < 2048) { LOG_debug << "Received: " << req->in.c_str(); } else { LOG_debug << "Received: " << req->in.substr(0,2048).c_str(); } } LOG_debug << "Request finished with HTTP status: " << req->httpstatus; req->status = (req->httpstatus == 200 && (req->contentlength < 0 || req->contentlength == (req->buf ? req->bufpos : (int)req->in.size()))) ? REQ_SUCCESS : REQ_FAILURE; if (req->status == REQ_SUCCESS) { httpio->lastdata = Waiter::ds; } httpio->success = true; } else { LOG_verbose << "Data available. Remaining: " << size << " bytes"; char* ptr; if (httpctx->gzip) { m_off_t zprevsize = httpctx->zin.size(); httpctx->zin.resize(zprevsize + size); ptr = (char*)httpctx->zin.data() + zprevsize; } else { ptr = (char*)req->reserveput((unsigned*)&size); req->bufpos += size; } if (!WinHttpReadData(hInternet, ptr, size, NULL)) { LOG_err << "Unable to get more data. Code: " << GetLastError(); httpio->cancel(req); } } httpio->httpevent(); break; } case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: LOG_verbose << "Read complete"; if (dwStatusInformationLength) { LOG_verbose << dwStatusInformationLength << " bytes received"; if (req->httpio) { req->httpio->lastdata = Waiter::ds; } if (httpctx->gzip) { httpctx->z.next_in = (Bytef*)lpvStatusInformation; httpctx->z.avail_in = dwStatusInformationLength; req->bufpos += httpctx->z.avail_out; int t = inflate(&httpctx->z, Z_SYNC_FLUSH); req->bufpos -= httpctx->z.avail_out; if ((char*)lpvStatusInformation + dwStatusInformationLength == httpctx->zin.data() + httpctx->zin.size()) { httpctx->zin.clear(); } if (t != Z_OK && (t != Z_STREAM_END || httpctx->z.avail_out)) { LOG_err << "GZIP error"; httpio->cancel(req); } } if (!WinHttpQueryDataAvailable(httpctx->hRequest, NULL)) { LOG_err << "Error on WinHttpQueryDataAvailable. Code: " << GetLastError(); httpio->cancel(req); httpio->httpevent(); } } break; case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: { DWORD statusCode; DWORD statusCodeSize = sizeof(statusCode); if (!WinHttpQueryHeaders(httpctx->hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX)) { LOG_err << "Error getting headers. Code: " << GetLastError(); httpio->cancel(req); httpio->httpevent(); } else { LOG_verbose << "Headers available"; req->httpstatus = statusCode; if (req->httpio) { req->httpio->lastdata = Waiter::ds; } if (!req->buf) { // obtain original content length - always present if gzip is in use DWORD contentLength; DWORD contentLengthSize = sizeof(contentLength); if (WinHttpQueryHeaders(httpctx->hRequest, WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_NUMBER, L"Original-Content-Length", &contentLength, &contentLengthSize, WINHTTP_NO_HEADER_INDEX)) { LOG_verbose << "Content-Length: " << contentLength; req->setcontentlength(contentLength); // check for gzip content encoding WCHAR contentEncoding[16]; DWORD contentEncodingSize = sizeof(contentEncoding); httpctx->gzip = WinHttpQueryHeaders(httpctx->hRequest, WINHTTP_QUERY_CONTENT_ENCODING, WINHTTP_HEADER_NAME_BY_INDEX, &contentEncoding, &contentEncodingSize, WINHTTP_NO_HEADER_INDEX) && !wcscmp(contentEncoding, L"gzip"); if (httpctx->gzip) { LOG_verbose << "Using GZIP"; httpctx->z.zalloc = Z_NULL; httpctx->z.zfree = Z_NULL; httpctx->z.opaque = Z_NULL; httpctx->z.avail_in = 0; httpctx->z.next_in = Z_NULL; inflateInit2(&httpctx->z, MAX_WBITS+16); req->in.resize(contentLength); httpctx->z.avail_out = contentLength; httpctx->z.next_out = (unsigned char*)req->in.data(); } else { LOG_verbose << "Not using GZIP"; } } else { LOG_verbose << "Content-Length not available"; } } if (!WinHttpQueryDataAvailable(httpctx->hRequest, NULL)) { LOG_err << "Unable to query data. Code: " << GetLastError(); httpio->cancel(req); httpio->httpevent(); } else if (httpio->waiter && httpio->noinetds) { httpio->inetstatus(true); } } break; } case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: { DWORD e = GetLastError(); LOG_err << "Request error. Code: " << e; if (httpio->waiter && e != ERROR_WINHTTP_TIMEOUT) { httpio->inetstatus(false); } } // fall through case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_SECURE_FAILURE) { LOG_err << "Security check failed. Code: " << (*(DWORD*)lpvStatusInformation); } httpio->cancel(req); httpio->httpevent(); break; case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: { if(MegaClient::disablepkp) { break; } PCCERT_CONTEXT cert; DWORD len = sizeof cert; if (WinHttpQueryOption(httpctx->hRequest, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert, &len)) { CRYPT_BIT_BLOB* pkey = &cert->pCertInfo->SubjectPublicKeyInfo.PublicKey; // this is an SSL connection: verify public key to prevent MITM attacks if (pkey->cbData != 270 || (memcmp(pkey->pbData, "\x30\x82\x01\x0a\x02\x82\x01\x01\x00" APISSLMODULUS1 "\x02" APISSLEXPONENTSIZE APISSLEXPONENT, 270) && memcmp(pkey->pbData, "\x30\x82\x01\x0a\x02\x82\x01\x01\x00" APISSLMODULUS2 "\x02" APISSLEXPONENTSIZE APISSLEXPONENT, 270))) { LOG_err << "Certificate error. Possible MITM attack!!"; CertFreeCertificateContext(cert); httpio->cancel(req); httpio->httpevent(); break; } CertFreeCertificateContext(cert); } break; } case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: if (httpctx->postpos < httpctx->postlen) { LOG_verbose << "Chunk written"; unsigned pos = httpctx->postpos; unsigned t = httpctx->postlen - pos; if (t > HTTP_POST_CHUNK_SIZE) { t = HTTP_POST_CHUNK_SIZE; } httpctx->postpos += t; if (!WinHttpWriteData(httpctx->hRequest, (LPVOID)(httpctx->postdata + pos), t, NULL)) { LOG_err << "Error writting data. Code: " << GetLastError(); req->httpio->cancel(req); } httpio->httpevent(); } else { LOG_verbose << "Request written"; if (!WinHttpReceiveResponse(httpctx->hRequest, NULL)) { LOG_err << "Error receiving response. Code: " << GetLastError(); httpio->cancel(req); httpio->httpevent(); } httpctx->postdata = NULL; } } httpio->unlock(); }
void shoes_winhttp(LPCWSTR host, INTERNET_PORT port, LPCWSTR path, TCHAR **mem, ULONG memlen, HANDLE file, LPDWORD size, shoes_download_handler handler, void *data) { DWORD len = 0, rlen = 0, status = 0, complete = 0, flen = 0, total = 0, written = 0; LPTSTR buf = SHOE_ALLOC_N(TCHAR, SHOES_BUFSIZE); LPTSTR fbuf = SHOE_ALLOC_N(TCHAR, SHOES_CHUNKSIZE); LPWSTR uagent = SHOE_ALLOC_N(WCHAR, SHOES_BUFSIZE); HINTERNET sess = NULL, conn = NULL, req = NULL; SHOES_TIME last = 0; if (buf == NULL || fbuf == NULL || uagent == NULL) goto done; _snwprintf(uagent, SHOES_BUFSIZE, L"Shoes/0.r%d (%S) %S/%d", SHOES_REVISION, SHOES_PLATFORM, SHOES_RELEASE_NAME, SHOES_BUILD_DATE); sess = WinHttpOpen(uagent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (sess == NULL) goto done; conn = WinHttpConnect(sess, host, port, 0); if (conn == NULL) goto done; req = WinHttpOpenRequest(conn, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (req == NULL) goto done; if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0)) goto done; if (!WinHttpReceiveResponse(req, NULL)) goto done; len = sizeof(DWORD); if (!WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &len, NULL)) goto done; else { shoes_download_event event; event.stage = SHOES_HTTP_STATUS; event.status = status; if (handler != NULL) handler(&event, data); } shoes_winhttp_headers(req, handler, data); *size = 0; len = sizeof(buf); if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_LENGTH, NULL, buf, &len, NULL)) { *size = _wtoi((wchar_t *)buf); if (*mem != NULL && *size > memlen) { SHOE_REALLOC_N(*mem, char, (memlen = *size)); if (*mem == NULL) goto done; }