/** * Translates an error returned from GetLastError returned from a WinInet API call. * * @param GetLastErrorResult - error code to translate * @return string for the error code */ FString InternetTranslateError(::DWORD GetLastErrorResult) { FString ErrorStr = FString::Printf(TEXT("ErrorCode: %08X. "), (uint32)GetLastErrorResult); HANDLE ProcessHeap = GetProcessHeap(); if (ProcessHeap == NULL) { ErrorStr += TEXT("Call to GetProcessHeap() failed, cannot translate error... "); return ErrorStr; } TCHAR FormatBuffer[1024]; uint32 BaseLength = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE, GetModuleHandle(TEXT("wininet.dll")), GetLastErrorResult, 0, FormatBuffer, ARRAYSIZE(FormatBuffer), NULL); if (!BaseLength) { ErrorStr += FString::Printf(TEXT("Call to FormatMessage() failed: %08X. "), (uint32)GetLastError()); return ErrorStr; } ErrorStr += FString::Printf(TEXT("Desc: %s. "), FormatBuffer); if (GetLastErrorResult == ERROR_INTERNET_EXTENDED_ERROR) { ::DWORD InetError; ::DWORD ExtLength = 0; InternetGetLastResponseInfo(&InetError, NULL, &ExtLength); ExtLength = ExtLength+1; TArray<TCHAR> ExtErrMsg; ExtErrMsg.AddUninitialized(ExtLength); if (!InternetGetLastResponseInfo(&InetError, ExtErrMsg.GetTypedData(), &ExtLength)) { ErrorStr += FString::Printf(TEXT("Call to InternetGetLastResponseInfo() failed: %08X. "), (uint32) GetLastError()); return ErrorStr; } } return ErrorStr; }
void CNetRequestImpl::ErrorMessage(LPCTSTR pszFunction) { // Retrieve the system error message for the last-error code LPTSTR pszMessage = NULL; DWORD dwLastError = GetLastError(); DWORD dwLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | //FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE| FORMAT_MESSAGE_IGNORE_INSERTS, GetModuleHandle( _T("wininet.dll") ), dwLastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&pszMessage, 0, NULL ); CAtlStringW strExtError; if ( dwLastError == ERROR_INTERNET_EXTENDED_ERROR ) { DWORD dwInetError =0, dwExtLength = 0; InternetGetLastResponseInfo( &dwInetError, NULL, &dwExtLength ); if ( dwExtLength > 0 ) { InternetGetLastResponseInfo( &dwInetError, strExtError.GetBuffer(dwExtLength+1), &dwExtLength ); strExtError.ReleaseBuffer(); } } rho::LogMessage oLogMsg(__FILE__, __LINE__, L_ERROR, LOGCONF(), getLogCategory() ); oLogMsg + "Call " + pszFunction + " failed. With code : " + dwLastError; if ( pszMessage ) oLogMsg + ".Message: " + pszMessage; if ( strExtError.GetLength() ) oLogMsg + ".Extended info: " + strExtError.GetString(); if ( pszMessage ) LocalFree(pszMessage); }
void fsSpeaking::DialogFtpResponse() { if (m_pfnDlgFunc && m_bMute == FALSE) { char sz [10000]; DWORD dwErr, dwLen = sizeof (sz); if (InternetGetLastResponseInfo (&dwErr, sz, &dwLen)) m_pfnDlgFunc (IFDD_FROMSERVER, sz, m_lpDlgParam1, m_lpDlgParam2); } }
BOOL ErrorOut(DWORD dError, TCHAR * szCallFunc) { fprintf(stderr, "%s error %d\n", szCallFunc, dError); if (dError == ERROR_INTERNET_EXTENDED_ERROR) { DWORD dwIntError , dwLength = 0; TCHAR *szBuffer=NULL; InternetGetLastResponseInfo (&dwIntError, NULL, &dwLength); if (dwLength) { if ( !(szBuffer = (TCHAR *) LocalAlloc ( LPTR, dwLength) ) ) { fprintf(stderr, "Unable to allocate memory to display Internet error code. Error code: %d\n", GetLastError()); return FALSE; } if (!InternetGetLastResponseInfo (&dwIntError, (LPTSTR) szBuffer, &dwLength)) { fprintf(stderr, "Unable to get Intrnet error. Error code: %d\n", GetLastError()); return FALSE; } fprintf(stderr, "%s\n", szBuffer); LocalFree (szBuffer); } } return TRUE; }
char *CzHttp::GetFtpResponse( void ) { // FTPレスポンスへのポインタを返す // DWORD dwSize = INETBUF_MAX; DWORD dwError; if ( InternetGetLastResponseInfo( &dwError, buf, &dwSize ) ) { mode = CZHTTP_MODE_FTPREADY; } else { InternetCloseHandle( hService ); mode = CZHTTP_MODE_ERROR; } return buf; }
BOOL CFtpFile::GetFile(TCHAR *RemotePath,TCHAR *LocalPath) { if(!(m_isConnect && m_hConnect)) { g_Datalog.Trace(LOGL_TOP,LOGT_WARNING, __TFILE__,__LINE__, _T("下载文件:%s失败,ftp未连接"),RemotePath); return FALSE; } BOOL bRet = FtpGetFile(m_hConnect, RemotePath,LocalPath , FALSE, 0, 1, 0); TCHAR buff[300]={0}; if(bRet == FALSE) { DWORD dwErr = GetLastError(); switch(dwErr) { case ERROR_INTERNET_CONNECTION_ABORTED: //网络中断 case ERROR_INTERNET_CONNECTION_RESET: //连接已经重置 case ERROR_FILE_NOT_FOUND: //文件未找到也要重新连接 { _stprintf(buff,_T("FTP下载,连接已经重置 err=%d %s ,%s"),dwErr,RemotePath, LocalPath); g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, buff); ReConnect(); //失败就重新连接一次网络 } break; default: { DWORD dwLastError = 0; DWORD dwLen = 512; TCHAR szErrMsg[512] = {0}; InternetGetLastResponseInfo(&dwLastError, szErrMsg, &dwLen); _stprintf(buff,_T("FTP下载错误 err=%d, lasterr=%d :%s %s, %s"),dwErr, dwLastError, szErrMsg, RemotePath,LocalPath); g_Datalog.Trace(LOGL_TOP,LOGT_ERROR, __TFILE__,__LINE__, buff); ReConnect(); } break; } } else { _stprintf(buff,_T("下载文件成功 %ls, %s"),RemotePath,LocalPath); g_Datalog.Trace(LOGL_TOP,LOGT_PROMPT, __TFILE__,__LINE__, buff); } return bRet; }
HINTERNET CPatch::ConnectInet(HINTERNET hInet, char *sIP, WORD lPort, char *pID, char *pPass) { DWORD LenStr; DWORD dwErrorCode; char szErrorBuffer[512]; HINTERNET thInet; thInet = InternetConnect( hInet,sIP,lPort,pID, pPass, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE,0); if ( thInet == NULL ) { LenStr =0; dwErrorCode =0; dwErrorCode = GetLastError(); InternetGetLastResponseInfo(&dwErrorCode,szErrorBuffer,&LenStr); } return thInet; }
/* Writes the last error to log. */ void ShowError(void* rm, WCHAR* description) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_INTERNET_EXTENDED_ERROR) { WCHAR szBuffer[1024]; DWORD dwError, dwLen = 1024; const WCHAR* error = L"Unknown error"; if (InternetGetLastResponseInfo(&dwError, szBuffer, &dwLen)) { error = szBuffer; dwErr = dwError; } RmLogF(rm, LOG_ERROR, L"WebParser: (%s) %s (ErrorCode=%i)", description, error, dwErr); } else { LPVOID lpMsgBuf = nullptr; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, GetModuleHandle(L"wininet"), dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, nullptr ); const WCHAR* error = lpMsgBuf ? (WCHAR*)lpMsgBuf : L"Unknown error"; RmLogF(rm, LOG_ERROR, L"WebParser: (%s) %s (ErrorCode=%i)", description, error, dwErr); if (lpMsgBuf) LocalFree(lpMsgBuf); } }
netio_ie5_t * netio_ie5_connect (char const *url) { int resend = 0; DWORD type, type_s; netio_ie5_t * netio_ie5_conn; DWORD dw_ret; DWORD flags = /* INTERNET_FLAG_DONT_CACHE |*/ INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE; if (internet == 0) { HINSTANCE h = LoadLibrary ("wininet.dll"); if (!h) { /* XXX - how to return an error code? */ g_warning("Failed to load wininet.dll"); return NULL; } /* pop-up dialup dialog box */ /* XXX - do we need the dialup box or simply don't attempt an update in this case? */ dw_ret = InternetAttemptConnect (0); if (dw_ret != ERROR_SUCCESS) { g_warning("InternetAttemptConnect failed: %u", dw_ret); return NULL; } internet = InternetOpen ("Wireshark Update", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(internet == NULL) { g_warning("InternetOpen failed %u", GetLastError()); return NULL; } } netio_ie5_conn = g_malloc(sizeof(netio_ie5_t)); netio_ie5_conn->connection = InternetOpenUrl (internet, url, NULL, 0, flags, 0); try_again: #if 0 /* XXX - implement this option */ if (net_user && net_passwd) { InternetSetOption (connection, INTERNET_OPTION_USERNAME, net_user, strlen (net_user)); InternetSetOption (connection, INTERNET_OPTION_PASSWORD, net_passwd, strlen (net_passwd)); } #endif #if 0 /* XXX - implement this option */ if (net_proxy_user && net_proxy_passwd) { InternetSetOption (connection, INTERNET_OPTION_PROXY_USERNAME, net_proxy_user, strlen (net_proxy_user)); InternetSetOption (connection, INTERNET_OPTION_PROXY_PASSWORD, net_proxy_passwd, strlen (net_proxy_passwd)); } #endif if (resend) if (!HttpSendRequest (netio_ie5_conn->connection, 0, 0, 0, 0)) netio_ie5_conn->connection = 0; if (!netio_ie5_conn->connection) { switch(GetLastError ()) { case ERROR_INTERNET_EXTENDED_ERROR: { char buf[2000]; DWORD e, l = sizeof (buf); InternetGetLastResponseInfo (&e, buf, &l); MessageBox (0, buf, "Internet Error", 0); } break; case ERROR_INTERNET_NAME_NOT_RESOLVED: g_warning("Internet error: The servername could not be resolved"); break; case ERROR_INTERNET_CANNOT_CONNECT: g_warning("Internet error: Could not connect to the server"); break; default: g_warning("Internet error: %u", GetLastError ()); } return NULL; } type_s = sizeof (type); InternetQueryOption (netio_ie5_conn->connection, INTERNET_OPTION_HANDLE_TYPE, &type, &type_s); switch (type) { case INTERNET_HANDLE_TYPE_HTTP_REQUEST: case INTERNET_HANDLE_TYPE_CONNECT_HTTP: type_s = sizeof (DWORD); if (HttpQueryInfo (netio_ie5_conn->connection, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &type, &type_s, NULL)) { if (type == 401) /* authorization required */ { netio_ie5_flush_io (netio_ie5_conn); /* XXX - query net_user && net_passwd from user get_auth (NULL);*/ resend = 1; goto try_again; } else if (type == 407) /* proxy authorization required */ { netio_ie5_flush_io (netio_ie5_conn); /* XXX - query net_proxy_user && net_proxy_passwd from user get_proxy_auth (NULL);*/ resend = 1; goto try_again; } else if (type >= 300) { g_warning("Failed with HTTP response %u", type); g_free(netio_ie5_conn); return NULL; } } } return netio_ie5_conn; }
void Download::downloadFile(const string &url, const string &file, const vector< pair<string, string> > &headers) { if (hURL || !hInternet) throw std::exception("Not inititialized"); success = false; string hdr; for (size_t k = 0; k<headers.size(); k++) hdr += headers[k].first + ": " + headers[k].second + "\r\n"; string url2 = url; hURL = InternetOpenUrl(hInternet, url2.c_str(), hdr.empty() ? 0 : hdr.c_str(), hdr.length(), INTERNET_FLAG_DONT_CACHE, 0); if (!hURL) { int err = GetLastError(); string msg2 = getErrorMessage(err); DWORD em = 0, blen = 256; char bf2[256]; InternetGetLastResponseInfo(&em, bf2, &blen); string msg = "Failed to connect to: " + url; msg += " " + msg2; if (bf2[0] != 0) msg += " (" + string(bf2) + ")"; throw std::exception(msg.c_str()); } DWORD dwContentLen = 0; DWORD dwBufLen = sizeof(dwContentLen); BOOL success = HttpQueryInfo(hURL, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwContentLen, &dwBufLen, 0); if (success) setBytesToDownload(dwContentLen); else setBytesToDownload(0); DWORD dwStatus = 0; dwBufLen = sizeof(dwStatus); success = HttpQueryInfo(hURL, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwStatus, &dwBufLen, 0); if (success) { if (dwStatus >= 400) { char bf[256]; switch (dwStatus) { case HTTP_STATUS_BAD_REQUEST: sprintf_s(bf, "HTTP Error 400: The request could not be processed by the server due to invalid syntax."); break; case HTTP_STATUS_DENIED: sprintf_s(bf, "HTTP Error 401: The requested resource requires user authentication."); break; case HTTP_STATUS_FORBIDDEN: sprintf_s(bf, "HTTP Error 403: Åtkomst nekad (access is denied)."); break; case HTTP_STATUS_NOT_FOUND: sprintf_s(bf, "HTTP Error 404: Resursen kunde ej hittas (not found)."); break; case HTTP_STATUS_NOT_SUPPORTED: sprintf_s(bf, "HTTP Error 501: Förfrågan stöds ej (not supported)."); break; case HTTP_STATUS_SERVER_ERROR: sprintf_s(bf, "HTTP Error 500: Internt serverfel (server error)."); break; default: sprintf_s(bf, "HTTP Status Error %d", dwStatus); } throw dwException(bf, dwStatus); } } fileno=_open(file.c_str(), O_BINARY|O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE); if (fileno==-1) { fileno=0; endDownload(); char bf[256]; sprintf_s(bf, "Error opening '%s' for writing", file.c_str()); throw std::exception(bf); } bytesLoaded = 0; return; }
void CFtpDownLoaderDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 std::auto_ptr<CInternetSession> m_pInetSession(new CInternetSession); std::auto_ptr<CFtpConnection> m_pFtpConnection(m_pInetSession->GetFtpConnection(TEXT("localhost"),TEXT("anonymous"),TEXT("[email protected]"),21,FALSE)); if(m_pFtpConnection->GetFile(TEXT("/1/1.t"),TEXT("f:\\1.t"),FALSE,FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1)) { AfxMessageBox(TEXT("下载成功!")); } if(m_pFtpConnection->GetFile(TEXT("/1/1.t"),TEXT("f:\\2.t"),FALSE,FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1)) { AfxMessageBox(TEXT("下载成功!")); } //用command方式获取文件大小 TCHAR databuf[256]; DWORD size=256; BOOL bRes; DWORD dwError; m_pFtpConnection->Command(_T("SIZE /1/1.t \r\n"),CFtpConnection::CmdRespNone); bRes =InternetGetLastResponseInfo(&dwError,databuf,&size); //CInternetFile * a = m_pFtpConnection->OpenFile(TEXT("/1.t")); //ULONGLONG fileSize = a->GetLength(); //a->Close(); CString str;
_bstr_t CXMLHttpRequest::GetErrorMsg(DWORD rc) { _bstr_t msg(_T("")); TCHAR *lpBuffer = NULL; if (ERROR_INTERNET_EXTENDED_ERROR == rc) { DWORD dwError = 0; DWORD dwLength = 0; InternetGetLastResponseInfo (&dwError, NULL, &dwLength); if (dwLength > 0) { lpBuffer = (TCHAR *) LocalAlloc(LPTR,dwLength); if (!lpBuffer) { msg = _T("Unable to allocate memory to display Internet extended error: "); rc = GetLastError(); } else { if (!InternetGetLastResponseInfo(&dwError,lpBuffer,&dwLength)) { msg = _T("Unable to get Internet extended error: "); rc = GetLastError(); LocalFree(lpBuffer); } else { int len = lstrlen(lpBuffer); for (int i=0; i < len; ++i) { if (_istcntrl(lpBuffer[i])) lpBuffer[i] = _T(' '); } msg = lpBuffer; LocalFree(lpBuffer); return msg; } } } } lpBuffer = NULL; HMODULE hModule = NULL; // default to system source if (rc >= INTERNET_ERROR_BASE) hModule = LoadLibraryEx(_T("wininet.dll"),NULL,LOAD_LIBRARY_AS_DATAFILE); ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | ((hModule != NULL) ? FORMAT_MESSAGE_FROM_HMODULE : 0), hModule, rc, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), (LPTSTR)&lpBuffer, 0, NULL); if (lpBuffer) { int len = lstrlen(lpBuffer); for (int i=0; i < len; ++i) { if (_istcntrl(lpBuffer[i])) lpBuffer[i] = _T(' '); } } msg += lpBuffer; LocalFree(lpBuffer); if (hModule != NULL) FreeLibrary(hModule); return msg; }
void ResourceHandle::onRequestComplete(LPARAM lParam) { if (d->m_writing) { DWORD bytesWritten; InternetWriteFile(d->m_secondaryHandle, d->m_formDataString + (d->m_formDataLength - d->m_bytesRemainingToWrite), d->m_bytesRemainingToWrite, &bytesWritten); d->m_bytesRemainingToWrite -= bytesWritten; if (!d->m_bytesRemainingToWrite) { // End the request. d->m_writing = false; HttpEndRequest(d->m_secondaryHandle, 0, 0, (DWORD_PTR)d->m_jobId); free(d->m_formDataString); d->m_formDataString = 0; } return; } HINTERNET handle = (method() == "POST") ? d->m_secondaryHandle : d->m_resourceHandle; BOOL ok = FALSE; static const int bufferSize = 32768; char buffer[bufferSize]; INTERNET_BUFFERSA buffers; buffers.dwStructSize = sizeof(INTERNET_BUFFERSA); buffers.lpvBuffer = buffer; buffers.dwBufferLength = bufferSize; bool receivedAnyData = false; while ((ok = InternetReadFileExA(handle, &buffers, IRF_NO_WAIT, (DWORD_PTR)this)) && buffers.dwBufferLength) { if (!hasReceivedResponse()) { setHasReceivedResponse(); ResourceResponse response; client()->didReceiveResponse(this, response); } client()->didReceiveData(this, buffer, buffers.dwBufferLength, 0); buffers.dwBufferLength = bufferSize; } PlatformDataStruct platformData; platformData.errorString = 0; platformData.error = 0; platformData.loaded = ok; if (!ok) { int error = GetLastError(); if (error == ERROR_IO_PENDING) return; DWORD errorStringChars = 0; if (!InternetGetLastResponseInfo(&platformData.error, 0, &errorStringChars)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { platformData.errorString = new TCHAR[errorStringChars]; InternetGetLastResponseInfo(&platformData.error, platformData.errorString, &errorStringChars); } } _RPTF1(_CRT_WARN, "Load error: %i\n", error); } if (d->m_secondaryHandle) InternetCloseHandle(d->m_secondaryHandle); InternetCloseHandle(d->m_resourceHandle); client()->didFinishLoading(this); delete this; }
/* Writes the last error to log. */ void ShowError(int lineNumber, WCHAR* errorMsg) { DWORD dwErr = GetLastError(); WCHAR buffer[16]; wsprintf(buffer, L"%i", lineNumber); std::wstring err = L"WebParser.dll: ("; err += buffer; err += L") "; if (errorMsg == nullptr) { if (dwErr == ERROR_INTERNET_EXTENDED_ERROR) { WCHAR szBuffer[1024]; DWORD dwError, dwLen = 1024; if (InternetGetLastResponseInfo(&dwError, szBuffer, &dwLen)) { err += szBuffer; wsprintf(buffer, L"%i", dwError); } else { err += L"Unknown error"; wsprintf(buffer, L"%i", dwErr); } err += L" (ErrorCode="; err += buffer; err += L')'; } else { LPVOID lpMsgBuf = nullptr; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, GetModuleHandle(L"wininet"), dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, nullptr ); if (lpMsgBuf == nullptr) { err += L"Unknown error"; } else { err += (LPTSTR)lpMsgBuf; LocalFree(lpMsgBuf); } wsprintf(buffer, L"%i", dwErr); err += L" (ErrorCode="; err += buffer; err += L')'; } } else { err += errorMsg; } RmLog(LOG_ERROR, err.c_str()); }