WebdavServer::~WebdavServer() { if (hSession) WinHttpCloseHandle(hSession); }
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; }
VOID CALLBACK ProxyResolver::GetProxyCallBack( _In_ HINTERNET hResolver, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_ PVOID pvStatusInformation, _In_ DWORD dwStatusInformationLength ) /*++ Routine Description: Fetch proxy query results asynchronizely. This application shows how to cope with new APIs. In multithreaded environment, developers must keep in mind resource contention. Arguments: hSession - The WinHttp session to use for the proxy resolution. dwContext - The context value supplied by this application to associate with the callback handle hSession. dwInternetStatus - The INTERNET_STATUS_ value which specifies the status code that indicates why the callback function is called. pvStatusInformation - A pointer to a buffer that specifies information pertinent to this call to the callback function. dwStatusInformationLength - A value of type unsigned long integer that specifies the size of the lpvStatusInformation buffer. Return Value: None. --*/ { ProxyResolver* pProxyResolver = NULL; WINHTTP_ASYNC_RESULT *pAsyncResult = NULL; UNREFERENCED_PARAMETER(dwStatusInformationLength); pProxyResolver = (ProxyResolver *)dwContext; if ((dwInternetStatus != WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE && dwInternetStatus != WINHTTP_CALLBACK_STATUS_REQUEST_ERROR) || pProxyResolver == NULL) { goto quit; } if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR) { pAsyncResult = (WINHTTP_ASYNC_RESULT *)pvStatusInformation; if (pAsyncResult->dwResult != API_GET_PROXY_FOR_URL) { goto quit; } pProxyResolver->m_dwError = pAsyncResult->dwError; } else if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE) { pProxyResolver->m_dwError = s_pfnWinhttpGetProxyResult(hResolver, &pProxyResolver->m_wprProxyResult); } if (hResolver != NULL) { WinHttpCloseHandle(hResolver); hResolver = NULL; } SetEvent(pProxyResolver->m_hEvent); quit: return; }
/* * @brief Wrapper around WinHTTP-specific request handle closing functionality. * @param hReq HTTP request handle. * @return An indication of the result of sending the request. */ static BOOL close_request_winhttp(HANDLE hReq) { return WinHttpCloseHandle(hReq); }
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; }
BOOL COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper() { //Validate our parameters AFXASSUME(m_pOSMCtrl); //What will be the return value from this function (assume the best) BOOL bSuccess = TRUE; //Next get the server to connect to COSMCtrlMapnikTileProvider MapnikTileProvider; CString sServer(MapnikTileProvider.GetDownloadServer()); //Accumulate how many tiles we have request to rerender and which ones indicated a failure to rerender int nTilesRerendered = 0; int nTilesNotRerendered = 0; //Next create the Wininet session object ASSERT(m_hSession == NULL); HRESULT hr = m_pOSMCtrl->CreateSession(m_hSession); if (SUCCEEDED(hr)) { //Now create the connection object from the session object HINTERNET hConnection = NULL; hr = m_pOSMCtrl->CreateConnection(m_hSession, sServer, 80, hConnection); if (SUCCEEDED(hr)) { //Iterate across the array of tiles to rerender for (INT_PTR i=0; i<m_Tiles.GetSize() && bSuccess; i++) { //Pull out the next tile to download const COSMCtrlMapOperationsDlgTile& tile = m_Tiles.ElementAt(i); //Form the name of the tile we will be rerendering CString sObject(MapnikTileProvider.GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY) + _T("/dirty")); //Now issue the request to rerender COSMCtrlMapOperationsDlgEvent dlgEvent; dlgEvent.m_bSuccess = false; CStringA sResponse; hr = m_pOSMCtrl->DownloadPage(hConnection, sObject, TRUE, sResponse); if (FAILED(hr)) { //report the error TRACE(_T("COSMCtrlMapOperationsDlg::ForceMapnikRerenderHelper, Failed to download page \"%s\", Error:%08X\n"), sObject.operator LPCTSTR(), hr); //Update the stats ++nTilesNotRerendered; } else { //Screen scrape the response to see if it worked if (sResponse.Find("Tile submitted for rendering") != -1) { //Update the stats ++nTilesRerendered; dlgEvent.m_bSuccess = true; } else { //Update the stats ++nTilesNotRerendered; } } //Update the UI dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus; dlgEvent.m_sString = sObject; dlgEvent.m_nItemData = i + 1; AddEvent(dlgEvent); //Check if we have been cancelled before we loop around bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT); } //Close the wininet connection #ifdef COSMCTRL_NOWINHTTP InternetCloseHandle(hConnection); #else WinHttpCloseHandle(hConnection); #endif } //Clean up the wininet session before we exit #ifdef COSMCTRL_NOWINHTTP InternetCloseHandle(m_hSession); #else WinHttpCloseHandle(m_hSession); #endif m_hSession = NULL; } //Finally add a event about how many items have been downloaded COSMCtrlMapOperationsDlgEvent dlgEvent; dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus; CString sTilesRerendered; sTilesRerendered.Format(_T("%d"), nTilesRerendered); CString sTilesNotRerendered; sTilesNotRerendered.Format(_T("%d"), nTilesNotRerendered); AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_RERENDER_TILES_STATS, sTilesRerendered, sTilesNotRerendered); AddEvent(dlgEvent); return TRUE; }
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; }
//リクエストを送る //内部メモリバッファにDLする場合はファイル容量に要注意 //戻り値:エラーコード DWORD CWinHTTPUtil::SendRequest( LPCWSTR url, //[IN] アクセスするURL NW_VERB_MODE verbMode, //[IN] VERBの種類 LPCWSTR addHttpHeader, //[IN] Httpヘッダに追加するものあるなら指定 LPCWSTR saveFilePath, //[IN] DLファイル名、NULL時は内部メモリバッファにDL UPLOAD_DATA_LIST* upList //[IN] サーバーに送信するデータ(PUT or POST) ) { if( url == NULL ){ return ERR_INVALID_ARG; } if( this->session == NULL ){ return ERR_NW_NO_SESSION; } //リクエストクローズ if( this->request != NULL ){ WinHttpSetStatusCallback( this->request, NULL, NULL, NULL ); WinHttpCloseHandle(this->request); this->request = NULL; } ClearUpList(); for( size_t i=0; i<this->dlBuffList.size(); i++ ){ SAFE_DELETE(this->dlBuffList[i]); } this->dlBuffList.clear(); //URLの分解 URL_COMPONENTS stURL; ZeroMemory(&stURL, sizeof(URL_COMPONENTS)); stURL.dwStructSize = sizeof(URL_COMPONENTS); stURL.dwSchemeLength = -1; stURL.dwHostNameLength = -1; stURL.dwUrlPathLength = -1; stURL.dwExtraInfoLength = -1; if( WinHttpCrackUrl( url, (DWORD)wcslen(url), 0, &stURL) == NULL ){ return ERR_FALSE; } if( stURL.dwHostNameLength <= 0 ){ return ERR_FALSE; } wstring host = L""; host.insert(0,stURL.lpszHostName, stURL.dwHostNameLength ); host += L"\0"; if( CompareNoCase(host, stURL.lpszHostName) != 0 || this->lastPort != stURL.nPort){ //前回と違うコネクションなのでやりなおし if( this->connect != NULL ){ WinHttpCloseHandle(this->connect); this->connect = NULL; } } //コネクションオープン if( this->connect == NULL ){ this->connect = WinHttpConnect( this->session, host.c_str(), stURL.nPort, 0 ); if( this->connect == NULL ){ return ERR_NW_OPEN_CONNECT; } } //Verbの設定 wstring verb = L"GET"; if( verbMode == NW_VERB_GET ){ verb = L"GET"; }else if( verbMode == NW_VERB_POST ){ verb = L"POST"; }else if( verbMode == NW_VERB_PUT ){ verb = L"PUT"; } wstring sendUrl = L""; sendUrl.insert(0, stURL.lpszUrlPath, stURL.dwUrlPathLength+stURL.dwExtraInfoLength); sendUrl += L"\0"; //リクエストオープン if( stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ){ this->request = WinHttpOpenRequest( this->connect, verb.c_str(), sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); }else{ this->request = WinHttpOpenRequest( this->connect, verb.c_str(), sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0 ); } if( this->request == NULL ){ return ERR_NW_OPEN_REQUEST; } if( this->useProxy == TRUE ){ //ProxyのIDとパスワードがあったらセット if( this->proxyID.size() > 0 || this->proxyPWD.size() > 0 ){ if( WinHttpSetCredentials( this->request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, this->proxyID.c_str(), this->proxyPWD.c_str(), NULL ) == FALSE ){ return ERR_NW_PROXY_LOGIN; } } } //HTTPヘッダを設定 if( addHttpHeader != NULL ){ WinHttpAddRequestHeaders( this->request, addHttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD ); } //コールバック設定 WinHttpSetStatusCallback(this->request, StatusCallback, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS, NULL ); //アップロードデータのコピー this->totalUpSize = 0; if( upList != NULL ){ for( DWORD i=0; i<upList->listCount; i++ ){ UPLOAD_DATA* item = new UPLOAD_DATA; item->filePathFlag = upList->list[i].filePathFlag; item->buffSize = upList->list[i].buffSize; if( item->buffSize > 0 ){ item->buff = new BYTE[item->buffSize]; memcpy(item->buff, upList->list[i].buff, item->buffSize); } upDataList.push_back(item); if( item->filePathFlag == TRUE ){ HANDLE file = CreateFileW( (WCHAR*)item->buff, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if( file == INVALID_HANDLE_VALUE ){ //ファイルにアクセスできないのでエラー return ERR_NW_OPEN_FILE; } DWORD HSize=0; DWORD LSize=0; LSize = GetFileSize(file, &HSize); CloseHandle(file); if( HSize > 0 ){ //DWORD以上は未サポート return ERR_SIZE; } this->totalUpSize += LSize; }else{ this->totalUpSize += item->buffSize; } } } this->lastHost = host; this->lastPort = stURL.nPort; if( saveFilePath != NULL ){ this->saveFilePath = saveFilePath; }else{ this->saveFilePath = L""; } ResetEvent(this->upStopEvent); ResetEvent(this->responseCompEvent); this->errEndCode = NO_ERR; if( WinHttpSendRequest( this->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, totalUpSize, (DWORD_PTR)this) == FALSE ){ return ERR_NW_SEND_REQUEST; } if( this->asyncMode == FALSE ){ //同期なので完了するまで待つ WaitForSingleObject(this->responseCompEvent, INFINITE); return this->errEndCode; } return NO_ERR; }
~WinHTTPSession() { if (handle) WinHttpCloseHandle(handle); }
WinHttpIO::~WinHttpIO() { WinHttpCloseHandle(hSession); }
WinHttpIO::~WinHttpIO() { WinHttpCloseHandle(hSession); LeaveCriticalSection(&csHTTP); }
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; }
// Read URL server LPSTR SoffidEssoManager::readURL (HINTERNET hSession, const wchar_t* host, int port, LPCWSTR path, BOOL allowUnknownCA, size_t *pSize) { BOOL bResults = FALSE; HINTERNET hConnect = NULL, hRequest = NULL; DWORD dwDownloaded = -1; BYTE *buffer = NULL; if (debug) { log("Connecting to %s:%d...\n", host, port); } hConnect = WinHttpConnect(hSession, host, port, 0); if (hConnect) { if (debug) { log("Performing request %s...\n", path); } hRequest = WinHttpOpenRequest(hConnect, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); } // Send a request. if (hRequest) { if (debug) log("Sending request ...\n"); WinHttpSetOption(hRequest, WINHTTP_OPTION_CLIENT_CERT_CONTEXT, NULL, 0); if (allowUnknownCA) { DWORD flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA; WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, (LPVOID) &flags, sizeof flags); } bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); } if (bResults && allowUnknownCA) { // Agreagar la CA ROOT PCERT_CONTEXT context; DWORD dwSize = sizeof context; BOOL result = WinHttpQueryOption(hRequest, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &context, &dwSize); if (!result) { log("Cannot get context\n"); // notifyError(); } PCCERT_CONTEXT issuerContext = CertFindCertificateInStore(context->hCertStore, X509_ASN_ENCODING, 0, CERT_FIND_ISSUER_OF, context, NULL); HCERTSTORE systemStore = CertOpenStore((LPCSTR) 13, // CERT_STORE_PROV_SYSTEM_REGISTRY_W 0, (HCRYPTPROV) NULL, (2 << 16) | // CERT_SYSTEM_STORE_LOCAL_MACHINE 0x1000, // CERT_STORE_MAXIMUM_ALLOWED L"ROOT"); CertAddCertificateContextToStore(systemStore, issuerContext, 1 /*CERT_STORE_ADD_NEW*/, NULL); CertFreeCertificateContext(issuerContext); CertFreeCertificateContext(context); } // End the request. if (bResults) { if (debug) log("Waiting for response....\n"); bResults = WinHttpReceiveResponse(hRequest, NULL); } // Keep checking for data until there is nothing left. DWORD used = 0; if (bResults) { const DWORD chunk = 4096; DWORD allocated = 0; do { if (used + chunk > allocated) { allocated += chunk; buffer = (LPBYTE) realloc(buffer, allocated); } dwDownloaded = 0; if (!WinHttpReadData(hRequest, &buffer[used], chunk, &dwDownloaded)) dwDownloaded = -1; else used += dwDownloaded; } while (dwDownloaded > 0); buffer[used] = '\0'; } DWORD dw = GetLastError(); if (!bResults && debug) { if (dw == ERROR_WINHTTP_CANNOT_CONNECT) log("Error: Cannot connect\n"); else if (dw == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) log("Error: Client CERT required\n"); else if (dw == ERROR_WINHTTP_CONNECTION_ERROR) log("Error: Connection error\n"); else if (dw == ERROR_WINHTTP_INCORRECT_HANDLE_STATE) log("Error: ERROR_WINHTTP_INCORRECT_HANDLE_STATE\n"); else if (dw == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE) log("Error: ERROR_WINHTTP_INCORRECT_HANDLE_TYPE\n"); else if (dw == ERROR_WINHTTP_INTERNAL_ERROR) log("Error: ERROR_WINHTTP_INTERNAL_ERROR\n"); else if (dw == ERROR_WINHTTP_INVALID_URL) log("Error: ERROR_WINHTTP_INVALID_URL\n"); else if (dw == ERROR_WINHTTP_LOGIN_FAILURE) log("Error: ERROR_WINHTTP_LOGIN_FAILURE\n"); else if (dw == ERROR_WINHTTP_NAME_NOT_RESOLVED) log("Error: ERROR_WINHTTP_NAME_NOT_RESOLVED\n"); else if (dw == ERROR_WINHTTP_OPERATION_CANCELLED) log("Error: ERROR_WINHTTP_OPERATION_CANCELLED\n"); else if (dw == ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW) log("Error: ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW\n"); else if (dw == ERROR_WINHTTP_SECURE_FAILURE) log("Error: ERROR_WINHTTP_SECURE_FAILURE\n"); else if (dw == ERROR_WINHTTP_SHUTDOWN) log("Error: ERROR_WINHTTP_SHUTDOWN\n"); else if (dw == ERROR_WINHTTP_TIMEOUT) log("Error: ERROR_WINHTTP_TIMEOUT\n"); else if (dw == ERROR_WINHTTP_UNRECOGNIZED_SCHEME) log("Error: ERROR_WINHTTP_UNRECOGNIZED_SCHEME\n"); else if (dw == ERROR_NOT_ENOUGH_MEMORY) log("Error: ERROR_NOT_ENOUGH_MEMORY\n"); else if (dw == ERROR_INVALID_PARAMETER) log("Error: ERROR_INVALID_PARAMETER\n"); else if (dw == ERROR_WINHTTP_RESEND_REQUEST) log("Error: ERROR_WINHTTP_RESEND_REQUEST\n"); else if (dw != ERROR_SUCCESS) { log("Unkonwn error %d\n", dw); } // notifyError(); } // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); SetLastError(dw); if (pSize != NULL) *pSize = used; return (LPSTR) buffer; }
int Songs::LoadHistory(const char *userId) { //ここでサーバに接続して前回と前々回の点数を受信 HINTERNET hSession, hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; //URL WCHAR szUrl[256] = L"http://globalstudios.jp/mai-archive/api_history.php?user="******"Sample Application/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) return -1; 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 -1; } //接続 hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return -1; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return -1; } 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 0; } WinHttpReceiveResponse(hRequest, NULL); //ボディ取得 lpData = ReadData(hRequest, &dwSize); for (int i = 0; i < NUMSONGS; i++) { char* temp = NULL; char* ctx;//内部的に使用するので深く考えない if (i == 0) { temp = strtok_s((char*)lpData, "\n", &ctx); } else { temp = strtok_s(0, "\n", &ctx); } if (temp == NULL)break; int history[2] = {}; int hoge; sscanf_s(temp, "%d||%d||%d", &hoge, &history[0], &history[1]); //以下の式を実行することによってデータを保存 //song[Search(<曲ID>)]->songHistory->Set(<前回と前々回の点数(配列ポインタ)>); song[Search(hoge)]->songHistory->Set(history); } HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; }
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 ); }
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 COSMCtrlMapOperationsDlg::DownloadTiles(BOOL bSkipIfTileAlreadyExists) { //Validate our parameters AFXASSUME(m_pOSMCtrl); //What will be the return value from this function (assume the best) BOOL bSuccess = TRUE; CSingleLock sl(&m_pOSMCtrl->m_csData, TRUE); IOSMCtrlTileProvider* pTileProvider = m_pOSMCtrl->GetTileProvider(); CString sCacheDirectory(m_pOSMCtrl->m_sCacheDirectory); ASSERT(sCacheDirectory.GetLength()); BOOL bUseIfModifiedSinceHeader(m_pOSMCtrl->m_bUseIfModifiedSinceHeader); sl.Unlock(); //Next get the server to connect to CString sServer(pTileProvider->GetDownloadServer()); //Accumulate how many tiles we have deleted and not deleted int nTilesDownloaded = 0; int nTilesNotDownloaded = 0; //Next create the Wininet session object ASSERT(m_hSession == NULL); HRESULT hr = m_pOSMCtrl->CreateSession(m_hSession); if (SUCCEEDED(hr)) { //Now create the connection object from the session object HINTERNET hConnection = NULL; hr = m_pOSMCtrl->CreateConnection(m_hSession, sServer, 80, hConnection); if (SUCCEEDED(hr)) { //Iterate across the array of tiles to download for (INT_PTR i=0; i<m_Tiles.GetSize() && bSuccess; i++) { //Pull out the next tile to download const COSMCtrlMapOperationsDlgTile& tile = m_Tiles.ElementAt(i); //Create the sub directories if we can CString sSubDirectory; sSubDirectory.Format(_T("%s\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom); CreateDirectory(sSubDirectory, NULL); sSubDirectory.Format(_T("%s\\%d\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom, tile.m_nTileX); CreateDirectory(sSubDirectory, NULL); //Form the name of the tile we will be downloading CString sObject(pTileProvider->GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY)); //Form the path to the tile we will be downloading to and determine if we should do the download CString sFile(COSMCtrl::GetTileCachePath(sCacheDirectory, tile.m_nZoom, tile.m_nTileX, tile.m_nTileY, FALSE)); BOOL bDownload = TRUE; if (bSkipIfTileAlreadyExists) bDownload = (GetFileAttributes(sFile) == INVALID_FILE_ATTRIBUTES); //Now download the specific tile to the cache if required COSMCtrlMapOperationsDlgEvent dlgEvent; dlgEvent.m_bSuccess = false; if (bDownload) { hr = m_pOSMCtrl->DownloadTile(hConnection, sObject, bUseIfModifiedSinceHeader, !bSkipIfTileAlreadyExists, tile.m_nZoom, tile.m_nTileX, tile.m_nTileY, sFile); if (FAILED(hr)) { //report the error TRACE(_T("COSMCtrlMapOperationsDlg::DownloadTiles, Failed to download tile \"%s\", Error:%08X\n"), sFile.operator LPCTSTR(), hr); //Ensure any remants of a bad download file are nuked DeleteFile(sFile); //Update the stats ++nTilesNotDownloaded; } else { //Update the stats ++nTilesDownloaded; dlgEvent.m_bSuccess = true; } } else { //Update the stats ++nTilesNotDownloaded; } //Update the UI dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus; dlgEvent.m_sString = sFile; dlgEvent.m_nItemData = i + 1; AddEvent(dlgEvent); //Check if we have been cancelled before we loop around bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT); } //Close the wininet connection #ifdef COSMCTRL_NOWINHTTP InternetCloseHandle(hConnection); #else WinHttpCloseHandle(hConnection); #endif } //Clean up the wininet session before we exit #ifdef COSMCTRL_NOWINHTTP InternetCloseHandle(m_hSession); #else WinHttpCloseHandle(m_hSession); #endif m_hSession = NULL; } //Finally add a event about how many items have been downloaded COSMCtrlMapOperationsDlgEvent dlgEvent; dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus; CString sTilesDownloaded; sTilesDownloaded.Format(_T("%d"), nTilesDownloaded); CString sTilesNotDownloaded; sTilesNotDownloaded.Format(_T("%d"), nTilesNotDownloaded); AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_DOWNLOAD_TILES_STATS, sTilesDownloaded, sTilesNotDownloaded); AddEvent(dlgEvent); return TRUE; }
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]; int request_failed = 0, cert_valid = 1; 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 */ WinHttpCloseHandle(s->request); s->request = NULL; s->sent_request = 0; 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_connect(t, location8); } 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); WinHttpCloseHandle(s->request); s->request = NULL; s->sent_request = 0; /* 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; }
HTTPMsg::~HTTPMsg(){ if( _hRequest ){ WinHttpCloseHandle( _hRequest ); } }
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; }
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"); }
//------------------------------------------------------------------------------------------------------------------------ CHttpClient::~CHttpClient() { if (hSession) WinHttpCloseHandle(hSession); }
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; }
// Detect any proxy configuration settings automatically. // static void windows_detect_autoproxy_settings() { if (log_flags.proxy_debug) { post_sysmon_msg("[proxy] automatic proxy check in progress"); } HINTERNET hWinHttp = NULL; WINHTTP_AUTOPROXY_OPTIONS autoproxy_options; WINHTTP_PROXY_INFO proxy_info; PARSED_URL purl; std::wstring network_test_url; size_t pos; memset(&autoproxy_options, 0, sizeof(autoproxy_options)); memset(&proxy_info, 0, sizeof(proxy_info)); autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoproxy_options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoproxy_options.fAutoLogonIfChallenged = TRUE; network_test_url = boinc_ascii_to_wide(nvc_config.network_test_url).c_str(); hWinHttp = WinHttpOpen( L"BOINC client", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL ); char msg[1024], buf[1024]; safe_strcpy(msg, "[proxy] "); if (WinHttpGetProxyForUrl(hWinHttp, network_test_url.c_str(), &autoproxy_options, &proxy_info)) { // Apparently there are some conditions where WinHttpGetProxyForUrl can return // success but where proxy_info.lpszProxy is null. Maybe related to UPNP? // // For the time being check to see if proxy_info.lpszProxy is non-null. // if (proxy_info.lpszProxy) { std::string proxy(boinc_wide_to_ascii(std::wstring(proxy_info.lpszProxy))); std::string new_proxy; if (log_flags.proxy_debug) { safe_strcat(msg, "proxy list: "); safe_strcat(msg, proxy.c_str()); } if (!proxy.empty()) { // Trim string if more than one proxy is defined // proxy list is defined as: // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) // Find and erase first delimeter type. pos = proxy.find(';'); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Find and erase second delimeter type. pos = proxy.find(' '); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Parse the remaining url parse_url(proxy.c_str(), purl); // Store the results for future use. if (0 != strcmp(working_proxy_info.autodetect_server_name, purl.host)) { // Reset clients connection error detection path net_status.need_physical_connection = false; working_proxy_info.autodetect_protocol = purl.protocol; safe_strcpy(working_proxy_info.autodetect_server_name, purl.host); working_proxy_info.autodetect_port = purl.port; } if (log_flags.proxy_debug) { snprintf(buf, sizeof(buf), "proxy detected %s:%d", purl.host, purl.port); safe_strcat(msg, buf); } } } // Clean up if (proxy_info.lpszProxy) GlobalFree(proxy_info.lpszProxy); if (proxy_info.lpszProxyBypass) GlobalFree(proxy_info.lpszProxyBypass); } else { // We can get here if the user is switching from a network that // requires a proxy to one that does not require a proxy. working_proxy_info.autodetect_protocol = 0; safe_strcpy(working_proxy_info.autodetect_server_name, ""); working_proxy_info.autodetect_port = 0; if (log_flags.proxy_debug) { safe_strcat(msg, "no automatic proxy detected"); } } if (hWinHttp) WinHttpCloseHandle(hWinHttp); if (log_flags.proxy_debug) { post_sysmon_msg(msg); } }
HttpRequest::~HttpRequest(void) { if (_handle != NULL) WinHttpCloseHandle(_handle); }
//-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const CSCore::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs) { CS_ASSERT(CSCore::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread"); CS_ASSERT(in_delegate != nullptr, "Cannot make an http request with a null delegate"); CS_ASSERT(in_url.empty() == false, "Cannot make an http request to a blank url"); URL_COMPONENTS urlComps; //Initialize the URL_COMPONENTS structure. ZeroMemory(&urlComps, sizeof(URL_COMPONENTS)); urlComps.dwStructSize = sizeof(URL_COMPONENTS); //Set required component lengths to non-zero so that they are cracked. urlComps.dwSchemeLength = (DWORD)-1; urlComps.dwHostNameLength = (DWORD)-1; urlComps.dwUrlPathLength = (DWORD)-1; urlComps.dwExtraInfoLength = (DWORD)-1; //Change the URL to wide string std::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url)); //Crack the URL. if (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps)) { CS_LOG_FATAL("Cannot crack URL: " + in_url); return nullptr; } //Weirdly the cracked URL struct only gives you the ability to crack your own URL std::wstring hostName = urlComps.lpszHostName; hostName = hostName.substr(0, urlComps.dwHostNameLength); HINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0); if (!connectionHandle) { CS_LOG_ERROR("Failed to connect to server: " + in_url); return nullptr; } //Set up the request based on whether it is POST or GET and whether it is SSL LPCWSTR type = (in_type == CSNetworking::HttpRequest::Type::k_get ? L"GET" : L"POST"); HINTERNET requestHandle = 0; std::wstring urlPath = urlComps.lpszUrlPath; urlPath = urlPath.substr(0, urlComps.dwUrlPathLength); if (urlComps.nScheme == INTERNET_SCHEME_HTTPS) { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); if (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } else { requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (requestHandle == nullptr) { CS_LOG_ERROR("Failed to open request: " + in_url); WinHttpCloseHandle(connectionHandle); return nullptr; } } if (in_headers.empty() == false) { std::wstring headerBlob = ConvertHeaders(in_headers); if (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false) { CS_LOG_ERROR("Failed to add http headers: " + in_url); WinHttpCloseHandle(requestHandle); WinHttpCloseHandle(connectionHandle); return nullptr; } } HttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate); m_requests.push_back(httpRequest); return httpRequest; }
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; }
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 */ }
DWORD ProxyResolver::GetProxyForUrlEx( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS *pAutoProxyOptions ) /*++ Routine Description: Retrieves the proxy data with the specified option using WinhttpGetProxyForUrlEx. Arguments: hSession - The WinHttp session to use for the proxy resolution. pwszUrl - The URL to get the proxy for. pAutoProxyOptions - Specifies the auto-proxy options to use. Return Value: WIN32 Error codes. --*/ { DWORD dwError = ERROR_SUCCESS; HINTERNET hResolver = NULL; WINHTTP_STATUS_CALLBACK wscCallback = NULL; // // Create proxy resolver handle. It's best to close the handle during call back. // dwError = s_pfnWinhttpCreateProxyResolver(hSession, &hResolver); if (dwError != ERROR_SUCCESS) { goto quit; } // // Sets up a callback function that WinHTTP can call as proxy results are resolved. // wscCallback = WinHttpSetStatusCallback(hResolver, GetProxyCallBack, WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE, 0); if(wscCallback == WINHTTP_INVALID_STATUS_CALLBACK) { dwError = GetLastError(); goto quit; } // // The extended API works in asynchronous mode, therefore wait until the // results are set in the call back function. // dwError = s_pfnWinhttpGetProxyForUrlEx(hResolver, pwszUrl, pAutoProxyOptions, (DWORD_PTR)this); if (dwError != ERROR_IO_PENDING) { goto quit; } // // The resolver handle will get closed in the callback and cannot be used any longer. // hResolver = NULL; dwError = WaitForSingleObjectEx(m_hEvent, INFINITE, FALSE); if (dwError != WAIT_OBJECT_0) { dwError = GetLastError(); goto quit; } dwError = m_dwError; quit: if (hResolver != NULL) { WinHttpCloseHandle(hResolver); hResolver = NULL; } return dwError; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_ERROR* error = NULL; WS_SERVICE_PROXY* serviceProxy = NULL; WS_HEAP* heap = NULL; WS_ENDPOINT_ADDRESS address = {}; static const WS_STRING serviceUrl = WS_STRING_VALUE(L"http://terraservice.net/TerraService2.asmx"); WS_CHANNEL_PROPERTY channelPropertyArray[4]; WS_ADDRESSING_VERSION addressingVersion = WS_ADDRESSING_VERSION_TRANSPORT; WS_ENVELOPE_VERSION envelopeVersion = WS_ENVELOPE_VERSION_SOAP_1_1; WCHAR* place = NULL; WS_HTTP_PROXY_SETTING_MODE proxySettingMode = WS_HTTP_PROXY_SETTING_MODE_CUSTOM; WS_CUSTOM_HTTP_PROXY customProxy = {}; address.url = serviceUrl; WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions = {}; WINHTTP_PROXY_INFO proxyInfo = {}; HINTERNET session = NULL; channelPropertyArray[0].id = WS_CHANNEL_PROPERTY_ADDRESSING_VERSION; channelPropertyArray[0].value = &addressingVersion; channelPropertyArray[0].valueSize = sizeof(addressingVersion); channelPropertyArray[1].id = WS_CHANNEL_PROPERTY_ENVELOPE_VERSION; channelPropertyArray[1].value = &envelopeVersion; channelPropertyArray[1].valueSize = sizeof(envelopeVersion); channelPropertyArray[2].id = WS_CHANNEL_PROPERTY_HTTP_PROXY_SETTING_MODE; channelPropertyArray[2].value = &proxySettingMode; channelPropertyArray[2].valueSize = sizeof(proxySettingMode); channelPropertyArray[3].id = WS_CHANNEL_PROPERTY_CUSTOM_HTTP_PROXY; channelPropertyArray[3].value = &customProxy; channelPropertyArray[3].valueSize = sizeof(customProxy); // This part illustrates how to setup a HTTP header authentication security binding // against the HTTP proxy server in case it requires authentication. // declare and initialize a default windows credential WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL windowsCredential = {}; // zero out the struct windowsCredential.credential.credentialType = WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL_TYPE; // set the credential type // for illustration only; usernames and passwords should never be included in source files windowsCredential.username.chars = L"domain\\user"; windowsCredential.username.length = (ULONG)wcslen(windowsCredential.username.chars); windowsCredential.password.chars = L"password"; windowsCredential.password.length = (ULONG)wcslen(windowsCredential.password.chars); // declare and initialize properties to set the authentication scheme to Basic ULONG scheme = WS_HTTP_HEADER_AUTH_SCHEME_NEGOTIATE; ULONG target = WS_HTTP_HEADER_AUTH_TARGET_PROXY; WS_SECURITY_BINDING_PROPERTY httpProxyAuthBindingProperties[2] = { { WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_SCHEME, &scheme, sizeof(scheme) }, { WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_TARGET, &target, sizeof(target) } }; // declare and initialize an HTTP header authentication security binding for the HTTP proxy server WS_HTTP_HEADER_AUTH_SECURITY_BINDING httpProxyAuthBinding = {}; // zero out the struct httpProxyAuthBinding.binding.bindingType = WS_HTTP_HEADER_AUTH_SECURITY_BINDING_TYPE; // set the binding type httpProxyAuthBinding.binding.properties = httpProxyAuthBindingProperties; httpProxyAuthBinding.binding.propertyCount = WsCountOf(httpProxyAuthBindingProperties); httpProxyAuthBinding.clientCredential = &windowsCredential.credential; // declare and initialize the array of all security bindings WS_SECURITY_BINDING* securityBindings[1] = { &httpProxyAuthBinding.binding }; // declare and initialize the security description WS_SECURITY_DESCRIPTION securityDescription = {}; // zero out the struct securityDescription.securityBindings = securityBindings; securityDescription.securityBindingCount = WsCountOf(securityBindings); // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Create a heap to store deserialized data hr = WsCreateHeap( /*maxSize*/ 2048, /*trimSize*/ 512, NULL, 0, &heap, error); if (FAILED(hr)) { goto Exit; } session = WinHttpOpen(L"NWS Example", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (!session) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_RUN_INPROCESS | WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoProxyOptions.fAutoLogonIfChallenged = FALSE; WinHttpGetProxyForUrl( session, serviceUrl.chars, &autoProxyOptions, &proxyInfo); if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) { if (proxyInfo.lpszProxy) { customProxy.servers.chars = proxyInfo.lpszProxy; customProxy.servers.length = (ULONG)wcslen(proxyInfo.lpszProxy); } if (proxyInfo.lpszProxyBypass) { customProxy.bypass.chars = proxyInfo.lpszProxyBypass; customProxy.bypass.length = (ULONG)wcslen(proxyInfo.lpszProxyBypass); } } hr = WsCreateServiceProxy( WS_CHANNEL_TYPE_REQUEST, WS_HTTP_CHANNEL_BINDING, &securityDescription, NULL, 0, channelPropertyArray, WsCountOf(channelPropertyArray), &serviceProxy, error); if (FAILED(hr)) { goto Exit; } // Open channel to address hr = WsOpenServiceProxy( serviceProxy, &address, NULL, error); if (FAILED(hr)) { goto Exit; } for (int i = 0; i < 100; i++) { LonLatPt point = {10.0, 10.0}; hr = TerraServiceSoap_ConvertLonLatPtToNearestPlace( serviceProxy, &point, &place, heap, NULL, 0, NULL, error); if (FAILED(hr)) { goto Exit; } if (place != NULL) { wprintf(L"Place @ Lattitude=%f, Longitutde=%f is %s\n", point.Lon, point.Lat, place); } else { wprintf(L"Could not find any place for Lattitude=%f, Longitutde=%f\n", point.Lon, point.Lat); } fflush(stdout); hr = WsResetHeap( heap, error); if (FAILED(hr)) { goto Exit; } } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (proxyInfo.lpszProxy) { ::GlobalFree(proxyInfo.lpszProxy); } if (proxyInfo.lpszProxyBypass) { ::GlobalFree(proxyInfo.lpszProxyBypass); } if (serviceProxy != NULL) { WsCloseServiceProxy(serviceProxy, NULL, NULL); WsFreeServiceProxy(serviceProxy); } if (!session) { WinHttpCloseHandle(session); } if (heap != NULL) { WsFreeHeap(heap); } if (error != NULL) { WsFreeError(error); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }