BOOL CUrlCrack::Crack(LPCTSTR pszUrl) { DWORD urlLen = _tcslen(pszUrl) * 2; TCHAR *pszCanUrl = new TCHAR[urlLen]; if (!InternetCanonicalizeUrl(pszUrl, pszCanUrl, &urlLen, ICU_BROWSER_MODE)) { delete[] pszCanUrl; if (GetLastError () == ERROR_INSUFFICIENT_BUFFER) { pszCanUrl = new TCHAR[urlLen + 1]; if (!InternetCanonicalizeUrl(pszUrl, pszCanUrl, &urlLen, ICU_BROWSER_MODE)) { delete[] pszCanUrl; return FALSE; } } else return FALSE; } URL_COMPONENTS url_comp; ZeroMemory(&url_comp, sizeof(url_comp)); url_comp.dwStructSize = sizeof(url_comp); url_comp.lpszHostName = m_szHost; url_comp.lpszPassword = m_szPassword; url_comp.lpszScheme = m_szScheme; url_comp.lpszUrlPath = m_szPath; url_comp.lpszUserName = m_szUser; url_comp.dwHostNameLength = UP_HOSTNAME_SIZE; url_comp.dwPasswordLength = UP_PASSWORD_SIZE; url_comp.dwSchemeLength = UP_SCHEME_SIZE; url_comp.dwUrlPathLength = UP_PATH_SIZE; url_comp.dwUserNameLength = UP_USERNAME_SIZE; if (!InternetCrackUrl(pszCanUrl, urlLen, 0, &url_comp)) { delete[] pszCanUrl; return FALSE; } delete[] pszCanUrl; // if (url_comp.nScheme != INTERNET_SCHEME_HTTP) // return FALSE; m_wPort = url_comp.nPort; return TRUE; }
HRESULT STDMETHODCALLTYPE CSuneidoAPP::Start( /* [in] */ LPCWSTR szUrl, /* [in] */ IInternetProtocolSink __RPC_FAR* pOIProtSink, /* [in] */ IInternetBindInfo __RPC_FAR* pOIBindInfo, /* [in] */ DWORD grfPI, /* [in] */ DWORD dwReserved) { USES_CONVERSION; const char* url = W2CA(szUrl); ULONG buflen = strlen(url) + 10; // shouldn't get any bigger? char* buf = new char[buflen]; InternetCanonicalizeUrl(url, buf, &buflen, ICU_DECODE | ICU_NO_ENCODE); LOG("Start: " << buf); int n; str = trycall("SuneidoAPP", buf, &n); if (str == 0) return INET_E_DATA_NOT_AVAILABLE; str = localmemdup(str, n); len = n; pos = 0; LOG("ReportData"); pOIProtSink->ReportData(BSCF_DATAFULLYAVAILABLE | BSCF_LASTDATANOTIFICATION, len, len); // MUST call this LOG("end Start"); return S_OK; }
CNetRequestImpl::CNetRequestImpl(const char* method, const String& strUrl) { pszErrFunction = NULL; hInet = NULL, hConnection = NULL, hRequest = NULL; memset(&uri, 0, sizeof(uri) ); m_pInstance = this; CAtlStringW strUrlW(strUrl.c_str()); do { if ( !isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) ) { pszErrFunction = L"SetupInternetConnection"; break; } hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL ); if ( !hInet ) { pszErrFunction = L"InternetOpen"; break; } DWORD dwUrlLength = 1024; CAtlStringW strCanonicalUrlW; if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) ) { pszErrFunction = _T("InternetCanonicalizeUrl"); break; } strCanonicalUrlW.ReleaseBuffer(); alloc_url_components( &uri, strCanonicalUrlW ); if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) { pszErrFunction = L"InternetCrackUrl"; break; } hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { pszErrFunction = L"InternetConnect"; break; } strReqUrlW = uri.lpszUrlPath; strReqUrlW += uri.lpszExtraInfo; hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL ); if ( !hRequest ) { pszErrFunction = L"HttpOpenRequest"; break; } }while(0); }
// Get a session pointer to the remote file // HINTERNET CAutoUpdater::GetSession(CString &URL) { // Canonicalization of the URL converts unsafe characters into escape character equivalents TCHAR canonicalURL[1024]; DWORD nSize = 1024; InternetCanonicalizeUrl(URL, canonicalURL, &nSize, ICU_BROWSER_MODE); DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD; HINTERNET hSession = InternetOpenUrl(hInternet, canonicalURL, NULL, NULL, options, 0); URL = canonicalURL; return hSession; }
void CDlgInfoURL::OnOK() { //char szPath[_MAX_PATH]; //ULONG lBufLength = _MAX_PATH; // TODO: Add extra validation here /* if (FALSE==InternetCanonicalizeUrl(m_strInfoURL, szPath, &lBufLength, ICU_NO_ENCODE )) { AfxMessageBox("This must be a valid URL."); } else { */ UpdateData(); char buf[80]; DWORD length = 80; if(m_strInfoURL.GetLength()>0) { BOOL bret; URL_COMPONENTS UrlComponents; memset(&UrlComponents, 0,sizeof(URL_COMPONENTS)); UrlComponents.dwStructSize = sizeof(URL_COMPONENTS); bret = InternetCrackUrl(m_strInfoURL, m_strInfoURL.GetLength(), 0, &UrlComponents); if(bret==TRUE && (UrlComponents.nScheme!=INTERNET_SCHEME_UNKNOWN)) { bret = InternetCanonicalizeUrl(m_strInfoURL, buf, &length, ICU_DECODE); if(bret==TRUE) { m_strInfoURL = CString(buf); UpdateData(FALSE); CDialog::OnOK(); } else { AfxMessageBox("The string has invalid characters."); } } else AfxMessageBox("The string is not a valid URL."); } else CDialog::OnOK(); }
extern "C" int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInst , __in LPSTR lpszCmdLine, int nCmdShow) { //----------------------------------------------------------------------------------------------------------------- // VARIABLES // //----------------------------------------------------------------------------------------------------------------- UINT uiRet = ERROR_SUCCESS; HRESULT hr = S_OK; char *szMsiFile = 0; char *szBaseURL = 0; char *szInstallPath = 0; char *szMsiCacheFile = 0; char *szOperation = 0; char *szProductName = 0; char *szMinimumMsi = 0; char *szProperties = 0; char *szInstProperties = 0; char *szTempPath = 0; char *szFilePart = 0; char *szBase = 0; char *szUpdate = 0; char *szRegisteredMsiFolder = 0; char *szMsiDllLocation = 0; char szAppTitle[MAX_STR_CAPTION] = {0}; char szError[MAX_STR_LENGTH] = {0}; char szText[MAX_STR_CAPTION] = {0}; char szBanner[MAX_STR_LENGTH] = {0}; char szAction[MAX_STR_LENGTH] = {0}; char szUserPrompt[MAX_STR_LENGTH] = {0}; char szProductCode[MAX_LENGTH_GUID] = {0}; char szModuleFile[MAX_PATH] = {0}; DWORD dwModuleFileSize = MAX_PATH; DWORD dwMsiFileSize = 0; DWORD dwBaseURLSize = 0; DWORD cchInstallPath = 0; DWORD dwMsiCacheFileSize = 0; DWORD dwOperationSize = 0; DWORD dwProductNameSize = 0; DWORD dwMinimumMsiSize = 0; DWORD dwPropertiesSize = 0; DWORD cchInstProperties = 0; DWORD cchTempPath = 0; DWORD dwLastError = 0; DWORD cchReturn = 0; DWORD dwBaseUpdateSize = 0; DWORD dwUpdateSize = 0; DWORD dwResult = 0; DWORD dwType = 0; DWORD dwProductCodeSize = MAX_LENGTH_GUID; DWORD dwRegisteredMsiFolderSize = 0; DWORD dwMsiDllLocationSize = 0; ULONG ulMsiMinVer = 0; char *szStopScan = NULL; bool fDelayRebootReq = false; bool fPatch = false; bool fQFE = false; bool fOSSupported = false; emEnum emExecMode = emPreset; HKEY hInstallerKey = 0; HMODULE hMsi = 0; PFnMsiSetInternalUI pfnMsiSetInternalUI = 0; PFnMsiInstallProduct pfnMsiInstallProduct = 0; PFnMsiApplyPatch pfnMsiApplyPatch = 0; PFnMsiReinstallProduct pfnMsiReinstallProduct = 0; PFnMsiQueryProductState pfnMsiQueryProductState = 0; PFnMsiOpenDatabase pfnMsiOpenDatabase = 0; PFnMsiDatabaseOpenView pfnMsiDatabaseOpenView = 0; PFnMsiViewExecute pfnMsiViewExecute = 0; PFnMsiViewFetch pfnMsiViewFetch = 0; PFnMsiRecordGetString pfnMsiRecordGetString = 0; PFnMsiCloseHandle pfnMsiCloseHandle = 0; MSIHANDLE hDatabase = 0; MSIHANDLE hView = 0; MSIHANDLE hRec = 0; INSTALLSTATE isProduct = INSTALLSTATE_UNKNOWN; const char * szAdminImagePath = 0; //----------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------- // create our UI object CDownloadUI DownloadUI; // Load our AppTitle (caption) WIN::LoadString(hInst, IDS_APP_TITLE, szAppTitle, sizeof(szAppTitle)/sizeof(char)); // Obtain path we are running from if (0 == WIN::GetModuleFileName(hInst, szModuleFile, dwModuleFileSize)) { // No UI displayed. Silent failure. uiRet = GetLastError(); goto CleanUp; } DebugMsg("[Info] we are running from --> %s\n", szModuleFile); // Figure out what we want to do emExecMode = GetExecutionMode (lpszCmdLine); if (emVerify == emExecMode) { // // We don't want any UI to be displayed in this case. The return value // from the exe is the result of the verification. Therefore, this // should be done before initializing the UI. // uiRet = VerifyFileSignature (szModuleFile, lpszCmdLine); if (ERROR_BAD_ARGUMENTS != uiRet) goto CleanUp; } if (ERROR_BAD_ARGUMENTS == uiRet || emHelp == emExecMode) { DisplayUsage(hInst, NULL, szAppTitle); goto CleanUp; } // // NOTE: // Delay handling admin. installs until we have determined if we are // patching an existing install or if we are doing a default install. // // initialize our UI object with desktop as parent DownloadUI.Initialize(hInst, /* hwndParent = */ 0, szAppTitle); // Check if we are installing on an OS that supports Windows Installer 3.0 fOSSupported = IsOSSupported(); if(!fOSSupported) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_OS_NOT_SUPPORTED); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } HANDLE hMutex = 0; // only run one instance at a time if (AlreadyInProgress(hMutex)) { // silently return - correct return code ? uiRet = ERROR_INSTALL_ALREADY_RUNNING; goto CleanUp; } // determine operation, default (if not present) is INSTALL if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_OPERATION, &szOperation, dwOperationSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } if (ERROR_SUCCESS != uiRet) { // set operation to default which is install if (szOperation) delete [] szOperation; szOperation = new char[lstrlen(szDefaultOperation) + 1]; if (!szOperation) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } if (FAILED(StringCchCopy(szOperation, lstrlen(szDefaultOperation) + 1, szDefaultOperation))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } // obtain name of product if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PRODUCTNAME, &szProductName, dwProductNameSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } if (ERROR_SUCCESS != uiRet) { // use default if (szProductName) delete [] szProductName; szProductName = new char[MAX_STR_CAPTION]; if (!szProductName) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } WIN::LoadString(hInst, IDS_DEFAULT_PRODUCT, szProductName, MAX_STR_CAPTION); } // set banner text WIN::LoadString(hInst, IDS_BANNER_TEXT, szText, MAX_STR_CAPTION); StringCchPrintf(szBanner, sizeof(szBanner), szText, szProductName); if (irmCancel == DownloadUI.SetBannerText(szBanner)) { ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } // Determine if this is a patch or a normal install. if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_DATABASE, &szMsiFile, dwMsiFileSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS != uiRet) { // look for patch if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PATCH, &szMsiFile, dwMsiFileSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS != uiRet) { PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_DATABASE); goto CleanUp; } fPatch = true; } // // If we are here, this is either an admin. install or a default install. // File signature verification, help and other invalid parameters have // already been taken care of above. // if (emAdminInstall == emExecMode) { uiRet = GetAdminInstallInfo (fPatch, lpszCmdLine, &szAdminImagePath); if (ERROR_BAD_ARGUMENTS == uiRet) { DisplayUsage(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } } // // At this point, the validation of the commandline arguments is complete // and we have all the information we need. // // obtain minimum required MSI version if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_MINIMUM_MSI, &szMinimumMsi, dwMinimumMsiSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS != uiRet) { PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_MINIMUM_MSI); goto CleanUp; } // make sure required Msi version is a valid value -- must be >= 150 ulMsiMinVer = strtoul(szMinimumMsi, &szStopScan, 10); if (!szStopScan || (szStopScan == szMinimumMsi) || (*szStopScan != 0) || ulMsiMinVer < MINIMUM_SUPPORTED_MSI_VERSION) { // invalid minimum version string PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_VER_STR, szMinimumMsi, MINIMUM_SUPPORTED_MSI_VERSION); uiRet = ERROR_INVALID_PARAMETER; goto CleanUp; } DebugMsg("[Resource] Minimum Msi Value = %d\n", ulMsiMinVer); // compare minimum required MSI version to that which is on the machine if (IsMsiUpgradeNecessary(ulMsiMinVer)) { DebugMsg("[Info] Upgrade of Windows Installer is requested\n"); // make sure this is admin -- must have admin priviledges to upgrade Windows Installer if (!IsAdmin()) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_REQUIRES_ADMIN_PRIV); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } // Ask the user if they want to upgrade the installer WIN::LoadString(hInst, IDS_ALLOW_MSI_UPDATE, szUserPrompt, MAX_STR_LENGTH); if (IDYES != WIN::MessageBox(DownloadUI.GetCurrentWindow(), szUserPrompt, szAppTitle, MB_YESNO|MB_ICONQUESTION)) { // user decided to cancel ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATE, &szUpdate, dwUpdateSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS != uiRet) { PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_UPDATE); goto CleanUp; } // determine if we need to download the Windows Installer update package from the web -- based on presence of UPDATELOCATION property if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATELOCATION, &szBase, dwBaseUpdateSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS == uiRet) { // presence of UPDATELOCATION property indicates assumption of URL source if (ERROR_SUCCESS != (uiRet = DownloadAndUpgradeMsi(hInst, &DownloadUI, szAppTitle, szBase, szUpdate, szModuleFile, ulMsiMinVer))) { if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet) { // successful, but must reboot at end fDelayRebootReq = true; } else goto CleanUp; } } else { // lack of UPDATELOCATION property indicates assumption of Media source if (ERROR_SUCCESS != (uiRet = UpgradeMsi(hInst, &DownloadUI, szAppTitle, szModuleFile, szUpdate, ulMsiMinVer))) { if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet) { // successful, but must reboot at end fDelayRebootReq = true; } else goto CleanUp; } } } DebugMsg("[Info] Windows Installer has been upgraded, or was already correct version\n"); // perform some extra authoring validation if (fPatch && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1) && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMajPatchOperation, -1) && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1)) { // wrong operation DebugMsg("[Error] Operation %s is not valid for a patch\n", szOperation); PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation); uiRet = ERROR_INVALID_PARAMETER; goto CleanUp; } else if (!fPatch && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallOperation, -1) && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1) && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1)) { // wrong operation DebugMsg("[Error] Operation %s is not valid for a package\n", szOperation); PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation); uiRet = ERROR_INVALID_PARAMETER; goto CleanUp; } // by now we either have a MSI or a MSP if (CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1) || CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1) || (fPatch && CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))) fQFE = true; // obtain base URL if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_BASEURL, &szBaseURL, dwBaseURLSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); goto CleanUp; } else if (ERROR_SUCCESS == uiRet) { // presence of BASEURL property indicates assumption of URL source . . . // generate the path to the installation package == baseURL + msiFile // note: msiFile is a relative path cchTempPath = lstrlen(szBaseURL) + lstrlen(szMsiFile) + 2; // 1 for slash, 1 for null szTempPath = new char[cchTempPath ]; if (!szTempPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } if (FAILED(StringCchCopy(szTempPath, cchTempPath, szBaseURL))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } // check for trailing slash on szBaseURL char *pch = szBaseURL + lstrlen(szBaseURL) + 1; // put at null terminator pch = CharPrev(szBaseURL, pch); if (*pch != '/') { if (FAILED(StringCchCat(szTempPath, cchTempPath, szUrlPathSep))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } // canocialize the URL path cchInstallPath = cchTempPath*2; szInstallPath = new char[cchInstallPath]; if (!szInstallPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } dwLastError = 0; // success if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0)) { dwLastError = GetLastError(); if (ERROR_INSUFFICIENT_BUFFER == dwLastError) { // try again delete [] szInstallPath; szInstallPath = new char[cchInstallPath]; if (!szInstallPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } dwLastError = 0; // reset to success for 2nd attempt if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0)) dwLastError = GetLastError(); } } if (0 != dwLastError) { // error -- invalid path/Url PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); uiRet = dwLastError; goto CleanUp; } // set action text for download WIN::LoadString(hInst, IDS_DOWNLOADING_PACKAGE, szText, MAX_STR_CAPTION); StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile); if (irmCancel == DownloadUI.SetActionText(szAction)) { ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } // download the msi file so we can attempt a trust check -- must be local for WinVerifyTrust DebugMsg("[Info] Downloading msi file %s for WinVerifyTrust check\n", szInstallPath); szMsiCacheFile = new char[MAX_PATH]; dwMsiCacheFileSize = MAX_PATH; if (!szMsiCacheFile) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } hr = WIN::URLDownloadToCacheFile(NULL, szInstallPath, szMsiCacheFile, dwMsiCacheFileSize, 0, /* IBindStatusCallback = */ &CDownloadBindStatusCallback(&DownloadUI)); if (DownloadUI.HasUserCanceled()) { ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } if (FAILED(hr)) { // error during download -- probably because file not found (or lost connection) PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath); uiRet = ERROR_FILE_NOT_FOUND; goto CleanUp; } DebugMsg("[Info] Msi file was cached to %s\n", szMsiCacheFile); // set action text for trust verification WIN::LoadString(hInst, IDS_VALIDATING_SIGNATURE, szText, MAX_STR_CAPTION); StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile); if (irmCancel == DownloadUI.SetActionText(szAction)) { ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } // perform trust check itvEnum itv = IsPackageTrusted(szModuleFile, szMsiCacheFile, DownloadUI.GetCurrentWindow()); if (itvWintrustNotOnMachine == itv) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NO_WINTRUST); uiRet = ERROR_CALL_NOT_IMPLEMENTED; goto CleanUp; } else if (itvUnTrusted == itv) { PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_UNTRUSTED, szInstallPath); uiRet = HRESULT_CODE(TRUST_E_SUBJECT_NOT_TRUSTED); goto CleanUp; } } else { // lack of BASEURL property indicates assumption of Media source // generate the path to the Msi file = szModuleFile + msiFile // note: msiFile is a relative path cchTempPath = lstrlen(szModuleFile) + lstrlen(szMsiFile) + 2; // 1 for null terminator, 1 for back slash szTempPath = new char[cchTempPath]; if (!szTempPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } // find 'setup.exe' in the path so we can remove it if (0 == GetFullPathName(szModuleFile, cchTempPath, szTempPath, &szFilePart)) { uiRet = GetLastError(); PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); goto CleanUp; } if (szFilePart) *szFilePart = '\0'; if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } cchInstallPath = 2*cchTempPath; szInstallPath = new char[cchInstallPath]; if (!szInstallPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } // normalize the path cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart); if (cchReturn > cchInstallPath) { // try again, with larger buffer delete [] szInstallPath; cchInstallPath = cchReturn; szInstallPath = new char[cchInstallPath]; if (!szInstallPath) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart); } if (0 == cchReturn) { // error -- invalid path PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); uiRet = dwLastError; goto CleanUp; } // no download is necessary -- but we can check for the file's existence DWORD dwFileAttrib = GetFileAttributes(szInstallPath); if (0xFFFFFFFF == dwFileAttrib) { // package is missing PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath); uiRet = ERROR_FILE_NOT_FOUND; goto CleanUp; } } // // good to go -- terminate our UI and let the Windows Installer take over // // retrieve the optional command line PROPERTY = VALUE strings if available if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PROPERTIES, &szProperties, dwPropertiesSize))) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } else if (ERROR_SUCCESS != uiRet) { // PROPERTY=VALUE pairs not specified if (szProperties) delete [] szProperties; szProperties = NULL; } DownloadUI.Terminate(); // // perform install // hMsi = LoadLibrary(MSI_DLL); if (hMsi) { pfnMsiSetInternalUI = (PFnMsiSetInternalUI)GetProcAddress(hMsi, MSIAPI_MsiSetInternalUI); pfnMsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, MSIAPI_MsiInstallProduct); pfnMsiApplyPatch = (PFnMsiApplyPatch)GetProcAddress(hMsi, MSIAPI_MsiApplyPatch); pfnMsiReinstallProduct = (PFnMsiReinstallProduct)GetProcAddress(hMsi, MSIAPI_MsiReinstallProduct); pfnMsiQueryProductState = (PFnMsiQueryProductState)GetProcAddress(hMsi, MSIAPI_MsiQueryProductState); pfnMsiOpenDatabase = (PFnMsiOpenDatabase)GetProcAddress(hMsi, MSIAPI_MsiOpenDatabase); pfnMsiDatabaseOpenView = (PFnMsiDatabaseOpenView)GetProcAddress(hMsi, MSIAPI_MsiDatabaseOpenView); pfnMsiViewExecute = (PFnMsiViewExecute)GetProcAddress(hMsi, MSIAPI_MsiViewExecute); pfnMsiViewFetch = (PFnMsiViewFetch)GetProcAddress(hMsi, MSIAPI_MsiViewFetch); pfnMsiRecordGetString = (PFnMsiRecordGetString)GetProcAddress(hMsi, MSIAPI_MsiRecordGetString); pfnMsiCloseHandle = (PFnMsiCloseHandle)GetProcAddress(hMsi, MSIAPI_MsiCloseHandle); } if (!hMsi || !pfnMsiSetInternalUI || !pfnMsiInstallProduct || !pfnMsiApplyPatch || !pfnMsiReinstallProduct || !pfnMsiQueryProductState || !pfnMsiDatabaseOpenView || !pfnMsiViewExecute || !pfnMsiViewFetch || !pfnMsiRecordGetString || !pfnMsiCloseHandle) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_FAILED_TO_UPGRADE_MSI); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } DebugMsg("[Info] Setting Internal UI level to FULL...\n"); pfnMsiSetInternalUI(INSTALLUILEVEL_FULL, 0); if (!fPatch) { // performing install or reinstall/recache DebugMsg("[Info] Calling MsiInstallProduct with szInstallPath = %s", szInstallPath); DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}"); // default operation for a package is INSTALL if (fQFE) { // check to see if this product is already installed if (ERROR_SUCCESS == pfnMsiOpenDatabase(szMsiCacheFile ? szMsiCacheFile : szInstallPath, MSIDBOPEN_READONLY, &hDatabase) && ERROR_SUCCESS == pfnMsiDatabaseOpenView(hDatabase, sqlProductCode, &hView) && ERROR_SUCCESS == pfnMsiViewExecute(hView, 0) && ERROR_SUCCESS == pfnMsiViewFetch(hView, &hRec) && ERROR_SUCCESS == pfnMsiRecordGetString(hRec, 1, szProductCode, &dwProductCodeSize)) { isProduct = pfnMsiQueryProductState(szProductCode); DebugMsg("[Info] MsiQueryProductState returned %d\n", isProduct); if (INSTALLSTATE_ADVERTISED != isProduct && INSTALLSTATE_DEFAULT != isProduct) { // product is unknown, so this will be a first time install DebugMsg("[Info] The product code '%s' is unknown. Will use first time install logic...\n", szProductCode); fQFE = false; } else { // product is known, use QFE syntax DebugMsg("[Info] The product code '%s' is known. Will use QFE recache and reinstall upgrade logic...\n", szProductCode); } } else { // some failure occurred when processing the product code, so treat as non-QFE DebugMsg("[Info] Unable to process product code. Will treat as first time install...\n"); fQFE = false; } if (hDatabase) pfnMsiCloseHandle(hDatabase); if (hView) pfnMsiCloseHandle(hView); if (hRec) pfnMsiCloseHandle(hRec); } // // Set up the properties to be passed into MSIInstallProduct // if (fQFE && !szProperties) cchInstProperties = lstrlen (szDefaultInstallUpdCommandLine); else if (szProperties) cchInstProperties = lstrlen (szProperties); if (emAdminInstall == emExecMode) cchInstProperties += lstrlen (szAdminInstallProperty); szInstProperties = new char[cchInstProperties + 1]; if (! szInstProperties) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } if (fQFE && !szProperties) { if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szDefaultInstallUpdCommandLine))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } else if (szProperties) { if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szProperties))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } else szInstProperties[0] = '\0'; if (emAdminInstall == emExecMode) { if (FAILED(StringCchCat(szInstProperties, cchInstProperties + 1, szAdminInstallProperty))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } uiRet = pfnMsiInstallProduct(szInstallPath, szInstProperties); if (ERROR_SUCCESS != uiRet) { // attempt to display an error message stored in msi.dll PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet); } DebugMsg("[Info] MsiInstallProduct returned %d\n", uiRet); } else { // default Operation for a patch is MINPATCH // if szProperties is NULL, use our default value for QFE patches if (!szProperties && fQFE) { DebugMsg("[Info] Patch is a MINPATCH (small or minor update patch) so using default command line '%s'\n", szDefaultMinPatchCommandLine); szProperties = new char[lstrlen(szDefaultMinPatchCommandLine) + 1]; if (!szProperties) { ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } if (FAILED(StringCchCopy(szProperties, lstrlen(szDefaultMinPatchCommandLine) + 1, szDefaultMinPatchCommandLine))) { PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR); uiRet = ERROR_INSTALL_FAILURE; goto CleanUp; } } if (emAdminInstall == emExecMode) { // performing a patch DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szMsiCacheFile); DebugMsg(" and szInstallPackage = %s and eInstallType = INSTALLTYPE_NETWORK_IMAGE", szAdminImagePath); DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}"); uiRet = pfnMsiApplyPatch(szMsiCacheFile, szAdminImagePath, INSTALLTYPE_NETWORK_IMAGE, szProperties); } else { // performing a patch DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szInstallPath); DebugMsg(" and szInstallPackage = {null} and eInstallType = INSTALLTYPE_DEFAULT"); DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}"); uiRet = pfnMsiApplyPatch(szInstallPath, NULL, INSTALLTYPE_DEFAULT, szProperties); } if (ERROR_SUCCESS != uiRet) { // attempt to display an error message stored in msi.dll PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet); } DebugMsg("[Info] MsiApplyPatch returned %d\n", uiRet); } CleanUp: if (szMsiFile) delete [] szMsiFile; if (szBaseURL) delete [] szBaseURL; if (szInstallPath) delete [] szInstallPath; if (szMsiCacheFile) { WIN::DeleteUrlCacheEntry(szMsiCacheFile); delete [] szMsiCacheFile; } if (szProductName) delete [] szProductName; if (szMinimumMsi) delete [] szMinimumMsi; if (szProperties) delete [] szProperties; if (szTempPath) delete [] szTempPath; if (szBase) delete [] szBase; if (szUpdate) delete [] szUpdate; if (szRegisteredMsiFolder) delete [] szRegisteredMsiFolder; if (szMsiDllLocation) delete [] szMsiDllLocation; if (szOperation) delete [] szOperation; if(hMutex) CloseHandle(hMutex); if (hMsi) FreeLibrary(hMsi); DebugMsg("[Info] Setup exit code is %d\n", uiRet); if (fDelayRebootReq) { // need to reboot machine for updating Windows Installer WIN::LoadString(hInst, IDS_REBOOT_REQUIRED, szAction, MAX_STR_LENGTH); if (IDYES == MessageBox(NULL, szAction, szAppTitle, MB_YESNO|MB_ICONQUESTION)) { // must first aquire system shutdown privileges on NT/Win2K AcquireShutdownPrivilege(); // initiate system shutdown for reboot WIN::ExitWindowsEx(EWX_REBOOT, PCLEANUI | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION); } } return uiRet; }
bool CUrlClient::SetUrl(LPCTSTR pszUrl, uint32 nIP) { USES_CONVERSION; TCHAR szCanonUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwCanonUrlSize = ARRSIZE(szCanonUrl); if (!InternetCanonicalizeUrl(pszUrl, szCanonUrl, &dwCanonUrlSize, ICU_NO_ENCODE)) return false; TCHAR szUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwUrlSize = ARRSIZE(szUrl); if (!InternetCanonicalizeUrl(szCanonUrl, szUrl, &dwUrlSize, ICU_DECODE | ICU_NO_ENCODE | ICU_BROWSER_MODE)) return false; TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH]; TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH]; TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH]; TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH]; TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH]; TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH]; URL_COMPONENTS Url = {0}; Url.dwStructSize = sizeof(Url); Url.lpszScheme = szScheme; Url.dwSchemeLength = ARRSIZE(szScheme); Url.lpszHostName = szHostName; Url.dwHostNameLength = ARRSIZE(szHostName); Url.lpszUserName = szUserName; Url.dwUserNameLength = ARRSIZE(szUserName); Url.lpszPassword = szPassword; Url.dwPasswordLength = ARRSIZE(szPassword); Url.lpszUrlPath = szUrlPath; Url.dwUrlPathLength = ARRSIZE(szUrlPath); Url.lpszExtraInfo = szExtraInfo; Url.dwExtraInfoLength = ARRSIZE(szExtraInfo); if (!InternetCrackUrl(szUrl, 0, 0, &Url)) return false; if (Url.dwSchemeLength == 0 || Url.nScheme != INTERNET_SCHEME_HTTP) // we only support "http://" return false; if (Url.dwHostNameLength == 0) // we must know the hostname return false; if (Url.dwUserNameLength != 0) // no support for user/password return false; if (Url.dwPasswordLength != 0) // no support for user/password return false; if (Url.dwUrlPathLength == 0) // we must know the URL path on that host return false; m_strHost = szHostName; TCHAR szEncodedUrl[INTERNET_MAX_URL_LENGTH]; DWORD dwEncodedUrl = ARRSIZE(szEncodedUrl); if (!InternetCanonicalizeUrl(szUrl, szEncodedUrl, &dwEncodedUrl, ICU_ENCODE_PERCENT)) return false; m_strUrlPath = szEncodedUrl; m_nUrlStartPos = (UINT)-1; SetUserName(szUrl); //NOTE: be very careful with what is stored in the following IP/ID/Port members! if (nIP) m_nConnectIP = nIP; else m_nConnectIP = inet_addr(T2A(szHostName)); // if (m_nConnectIP == INADDR_NONE) // m_nConnectIP = 0; m_nUserIDHybrid = htonl(m_nConnectIP); ASSERT( m_nUserIDHybrid != 0 ); m_nUserPort = Url.nPort; return true; }
HRESULT ceInternetCanonicalizeUrl( IN WCHAR const *pwszIn, OUT WCHAR **ppwszOut) { HRESULT hr; WCHAR *pwsz = NULL; assert(NULL != pwszIn); // Calculate required buffer size by passing a very small buffer // The call will fail, and tell us how big the buffer should be. WCHAR wszPlaceHolder[1]; DWORD cwc = ARRAYSIZE(wszPlaceHolder); BOOL bResult; bResult = InternetCanonicalizeUrl( pwszIn, // lpszUrl wszPlaceHolder, // lpszBuffer &cwc, // lpdwBufferLength 0); // dwFlags assert(!bResult); // This will always fail hr = ceHLastError(); if (HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) != hr) { // unexpected error _JumpError(hr, error, "InternetCanonicalizeUrl"); } // NOTE: InternetCanonicalizeUrl counts characters, not bytes as doc'd // cwc includes trailing L'0' pwsz = (WCHAR *) LocalAlloc(LMEM_FIXED, cwc * sizeof(WCHAR)); if (NULL == pwsz) { hr = E_OUTOFMEMORY; _JumpError(hr, error, "LocalAlloc"); } // canonicalize if (!InternetCanonicalizeUrl( pwszIn, // lpszUrl pwsz, // lpszBuffer &cwc, // lpdwBufferLength 0)) // dwFlags { hr = ceHLastError(); _JumpError(hr, error, "InternetCanonicalizeUrl"); } *ppwszOut = pwsz; pwsz = NULL; hr = S_OK; error: if (NULL != pwsz) { LocalFree(pwsz); } return(hr); }
STDMETHODIMP HttpRequest::put_Url(BSTR newVal) { ATLASSERT(newVal); if(IsValidURL(NULL,newVal,0)!=S_OK){ ErrorMsgBox(0,_T("请求地址不合法!")); return S_OK; } DWORD dwSize=STRLEN_4K; if (!InternetCanonicalizeUrl(newVal,m_szUrl,&dwSize,ICU_BROWSER_MODE)){ ErrorMsgBox(GetLastError(),_T("请求地址不合法或者长度太大:%s")); ZeroMemory(m_szUrl,sizeof(m_szUrl)); return S_OK; } ZeroMemory(m_szUrl,sizeof(m_szUrl)); _tcsncpy_s(m_szUrl,newVal,_tcslen(newVal)); ZeroMemory(m_szUrlProtocol,sizeof(m_szUrlProtocol)); ZeroMemory(m_szUrlHost,sizeof(m_szUrlHost)); ZeroMemory(m_szUrlFile,sizeof(m_szUrlFile)); m_usUrlPort=DEFAULT_HTTP_PORT; m_blUrlIsSSL=VARIANT_FALSE; if (!m_szUrl || _tcslen(m_szUrl)==0) return S_OK; //»ñÈ¡urlÐÒ鲿·Ö for(size_t i=0;i<sizeof(m_szUrl);i++){ if (m_szUrl[i]==_T(':') || i>=sizeof(m_szUrlProtocol)) break; m_szUrlProtocol[i]=m_szUrl[i]; } //ÊÇ·ñsslºÍsslĬÈÏ¶Ë¿Ú if (_tcsicmp(m_szUrlProtocol,_T("https"))==0) { m_blUrlIsSSL=VARIANT_TRUE; if (m_usUrlPort==DEFAULT_HTTP_PORT) m_usUrlPort=DEFAULT_HTTPS_PORT; } //»ñÈ¡url¶Ë¿Ú²¿·Ö TCHAR* szPos1=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+1,_T(':')); TCHAR* szPos2=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+3,_T('/')); if (szPos1 && szPos2){ TCHAR szPort[STRLEN_SMALL]={0}; _tcsncpy_s(szPort,szPos1+1,szPos2-szPos1-1); TCHAR *stop; m_usUrlPort=(USHORT)_tcstoul(szPort,&stop,0); } //»ñÈ¡urlÖ÷»ú²¿·Ö int idx=0; for(size_t i=_tcslen(m_szUrlProtocol)+3;i<sizeof(m_szUrl);i++){ if (m_szUrl[i]==_T(':') || m_szUrl[i]==_T('/')) break; m_szUrlHost[idx++]=m_szUrl[i]; } //»ñÈ¡urlÎļþ²¿·Ö TCHAR* szPos3=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+3,_T('/')); if(szPos3) _tcscpy_s(this->m_szUrlFile,szPos3); else this->m_szUrlFile[0]=_T('/'); return S_OK; }
BOOL CNetFile::Upload(LPCTSTR pUrl, LPCTSTR pLocal, BOOL bPassive) {_STT(); // Stop whatever else we were doing if ( pLocal != NULL ) Destroy(); // Uploading file m_bUpload = TRUE; m_dwDataWritten = 0; m_bPassive = bPassive; // Save parent window m_hWndParent = NULL; // Sanity check if ( pUrl == NULL || *pUrl == NULL ) return FALSE; // Are we downloading to file or ram? m_bMem = ( pLocal == NULL ); { // Copy the url char buf[ sizeof( m_szUrl ) ]; DWORD size = sizeof( m_szUrl ) - 1; // Is it a local file? if ( GetFileAttributes( pUrl ) == MAXDWORD ) { // Fix the url if ( InternetCanonicalizeUrl( pUrl, buf, &size, 0 ) ) { strcpy_sz( m_szUrl, buf ); } // Copy the url name else strcpy_sz( m_szUrl, pUrl ); } // end if // Copy the local file name else strcpy_sz( m_szUrl, pUrl ); } // end copy url if ( !m_bMem ) { // Where to download the file if ( pLocal != DOWNLOADTEMP ) { strcpy_sz( m_szLocal, pLocal ); } else CWinFile::CreateTemp( m_szLocal ); // Create a file to load data if ( !m_local.OpenExisting( m_szLocal, GENERIC_READ | GENERIC_WRITE ) ) return FALSE; } // end else // Set status m_dwTransferStatus = NETFILE_DS_INITIALIZING; // Create a thread to download the file if ( !StartThread() ) { Destroy(); m_dwTransferStatus = NETFILE_DS_INITIALIZING; return FALSE; } // end if return TRUE; }
bool CHttp::BreakUrl () { wyWChar temp[1]; wyWChar *canonicalurl; DWORD requiredlen = 1; URL_COMPONENTS urlcmp; urlcmp.dwStructSize = sizeof(urlcmp); // when initialized with NULL, the members of the structure will contain the // pointer to a the first char within the string. NO DYNAMIC ALLOCATION IS DONE urlcmp.lpszScheme = NULL; urlcmp.lpszHostName = NULL; urlcmp.lpszUserName = NULL; urlcmp.lpszPassword = NULL; urlcmp.lpszUrlPath = NULL; urlcmp.lpszExtraInfo = NULL; // The following lines set which components will be displayed. urlcmp.dwSchemeLength = 1; urlcmp.dwHostNameLength = 1; urlcmp.dwUserNameLength = 1; urlcmp.dwPasswordLength = 1; urlcmp.dwUrlPathLength = 1; urlcmp.dwExtraInfoLength= 1; // Canonicalize URLs - remove unsafe chars // find out the space required InternetCanonicalizeUrl (m_url, temp, &requiredlen, 0); canonicalurl = new wyWChar[requiredlen + 1]; InternetCanonicalizeUrl (m_url, canonicalurl, &requiredlen, 0); canonicalurl[requiredlen] = 0; // delete the prev url buffer and copy the new contents delete[] m_url; m_url = new wyWChar[requiredlen + 1]; wcscpy (m_url, canonicalurl ); delete[] canonicalurl; if (!InternetCrackUrl (m_url, wcslen(m_url), 0, &urlcmp )) { return false; } else { if (urlcmp.lpszScheme != 0) { m_Protocol = new wyWChar[urlcmp.dwSchemeLength + 1]; wcsncpy(m_Protocol, urlcmp.lpszScheme, urlcmp.dwSchemeLength); m_Protocol[urlcmp.dwSchemeLength] = 0; } else m_Protocol = NULL; if (urlcmp.lpszHostName != 0) { m_HostName = new wyWChar[urlcmp.dwHostNameLength + 1]; wcsncpy(m_HostName, urlcmp.lpszHostName, urlcmp.dwHostNameLength); m_HostName[urlcmp.dwHostNameLength] = '\0'; } else m_HostName = NULL; m_Port = urlcmp.nPort; if (urlcmp.lpszUserName != 0) { m_UserName = new wyWChar[urlcmp.dwUserNameLength + 1]; wcsncpy(m_UserName, urlcmp.lpszUserName, urlcmp.dwUserNameLength); m_UserName[urlcmp.dwUserNameLength] = '\0'; } else m_UserName = NULL; if (urlcmp.lpszPassword != 0) { m_Password = new wyWChar[urlcmp.dwPasswordLength + 1]; wcsncpy(m_Password, urlcmp.lpszPassword, urlcmp.dwPasswordLength); m_Password[urlcmp.dwPasswordLength] = '\0'; } else m_Password = NULL; if (urlcmp.lpszUrlPath != 0) { m_FileName = new wyWChar[urlcmp.dwUrlPathLength + 1]; wcsncpy(m_FileName, urlcmp.lpszUrlPath, urlcmp.dwUrlPathLength); m_FileName[urlcmp.dwUrlPathLength] = NULL; } else m_FileName = NULL; // append querystring to urlpath if (m_FileName && urlcmp.lpszExtraInfo ) { wyWChar *temp = m_FileName; m_FileName = new wyWChar[urlcmp.dwUrlPathLength + urlcmp.dwExtraInfoLength + 1]; wmemcpy (m_FileName, urlcmp.lpszUrlPath, urlcmp.dwUrlPathLength ); wmemcpy (m_FileName + urlcmp.dwUrlPathLength, urlcmp.lpszExtraInfo, urlcmp.dwExtraInfoLength ); m_FileName[urlcmp.dwUrlPathLength + urlcmp.dwExtraInfoLength] = NULL; delete[] temp; } } return true; }
/** * Download and install from a remote location using HTTP. * @param url the url indicating the location of the widget. * @param widget receives the constructed widget on success. */ STDMETHODIMP CBondiWidgetLibrary::RemoteInstall(BSTR url, IBondiWidget** widget) { HRESULT hRes = S_OK; try { TCHAR appDataPath[MAX_PATH]; WidgetUtils::GetAppFolder(NULL,appDataPath); TCHAR canonicalURL[1024]; DWORD nSize = 1024; InternetCanonicalizeUrl(url, canonicalURL, &nSize, ICU_BROWSER_MODE); // Check for an internet connection. if (InternetAttemptConnect(0) != ERROR_SUCCESS) BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("no internet connection found")); // Open a connection. HINTERNET hINet = InternetOpen(agentName,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE); if (hINet != 0) { HANDLE hConnection = ConnectToNetwork(25); if (hConnection != NULL) { // Attempt to access the resource at the url. DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD; HINTERNET hFile = InternetOpenUrl( hINet, canonicalURL, NULL, 0, options, 0 ); if (hFile != 0) { // Determine the file name to store the downloaded widget resource. TCHAR fName[MAX_PATH]; _tsplitpath_s(url, NULL, 0, NULL, 0, fName, _MAX_FNAME, NULL, 0); // Create the target local file. _bstr_t downloadPath = appDataPath + _bstr_t("\\") + _bstr_t(fName) + _bstr_t(".wgt"); HANDLE target = ::CreateFile(downloadPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); // Read chunks. BYTE buffer[1024]; DWORD dwRead; while (::InternetReadFile( hFile, buffer, 1024, &dwRead ) ) { if ( dwRead == 0 ) break; ::WriteFile(target,buffer,dwRead,&dwRead,NULL); } ::CloseHandle(target); InternetCloseHandle(hFile); CComObject<CBondiWidget>* newWidget; BONDI_CHECK_ERROR(CComObject<CBondiWidget>::CreateInstance(&newWidget),(IBondiWidgetLibrary*)this); newWidget->AddRef(); // Do the installation. _bstr_t locale("en"); hRes = newWidget->Install(downloadPath,locale,VARIANT_FALSE,VARIANT_FALSE); BONDI_CHECK_ERROR(hRes,(IBondiWidget*)newWidget); if (hRes == S_OK) { // Set the install URL. CComPtr<IBondiWidgetAppConfig> appConfig; BONDI_CHECK_ERROR(newWidget->get_AppSettings(&appConfig),(IBondiWidget*)newWidget); if (appConfig != NULL) BONDI_CHECK_ERROR(appConfig->PutBondiSetting(_T("bondi.installUri"),canonicalURL,VARIANT_TRUE),appConfig); newWidget->InitialiseAppSettings(); // We've finished with the temporary downloaded resource. ::DeleteFile(downloadPath); *widget = (IBondiWidget*)newWidget; } else { // Didn't install (probably because of an existing widget). *widget = NULL; } } else { DWORD err = GetLastError(); BONDI_RAISE_ERROR(E_BONDI_WIDGET_URL_OPEN_FAILED,_T("couldn't open url: ") + CString(canonicalURL)); } #ifdef UNDER_CE ConnMgrReleaseConnection(hConnection,1); CloseHandle(hConnection); #endif } InternetCloseHandle(hINet); } else { BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("error opening internet connection")); } } catch (_com_error& err) { hRes = BONDI_SET_ERROR(err,"CBondiWidgetLibrary::RemoteInstall - COM exception"); } catch (...) { hRes = BONDI_SET_ERROR(E_FAIL,"CBondiWidgetLibrary::RemoteInstall - C++ exception"); } return hRes; }
char * HTParse (const char *aName, const char *relatedName, int wanted) { int ret; char *result, *abs, *rel; DWORD len; BOOL bAgain = FALSE; #if 0 if (aName && *aName) { abs = xmalloc(strlen(aName) + 2); strcpy(abs, aName); strcat(abs, "/"); } else { /* FIXME: what does mean a null base url ? */ abs = xstrdup(""); } #else abs = xstrdup(aName ? aName : ""); #endif rel = (relatedName ? relatedName : ""); len = strlen(abs) + strlen(rel) + 45; result = xmalloc(len*sizeof(char)); #if 0 fprintf(stderr, "HTParse called with aName = %s and relatedName = %s\n", aName, relatedName); #endif do { if (*rel) { ret = InternetCombineUrl(abs, rel, result, &len, ICU_BROWSER_MODE); } else { ret = InternetCanonicalizeUrl(abs, result, &len, ICU_BROWSER_MODE); } bAgain = FALSE; if (!ret) { switch (GetLastError()) { case ERROR_INSUFFICIENT_BUFFER: #if 0 fprintf(stderr, "InternetCombineUrl: buffer was not long enough (needed %d)\n", len+1); #endif result = xrealloc(result, len+1); bAgain = TRUE; break; case ERROR_BAD_PATHNAME: fprintf(stderr, "InternetCombineUrl failed, one of the path names is bad:\n\t%s\n\t%s\n", aName, relatedName); break; case ERROR_INTERNET_INVALID_URL: fprintf(stderr, "InternetCombineUrl failed, url %s is malformed.\n", aName); break; case ERROR_INVALID_PARAMETER: fprintf(stderr, "InternetCombineUrl failed with `invalid parameter'.\n"); break; default: break; } } } while (bAgain); /* abs has always been malloc'ed */ if (abs) free(abs); if (!ret) { /* FIXME: Try this poor thing ! */ sprintf(result, "%s/%s", aName, relatedName); } #if 0 fprintf(stderr, "HTParse: result is %s\n", result); #endif return result; }
BOOL CNetFile::Download(LPCTSTR pUrl, LPCTSTR pLocal, BOOL bCloseFileAfterDownload, HWND hWndParent) {_STT(); // Lose previous file Destroy(); // Downloading m_bUpload = FALSE; // Save parent window m_hWndParent = hWndParent; // Save close file status m_bCloseFileAfterDownload = bCloseFileAfterDownload; // Sanity check if ( pUrl == NULL || *pUrl == NULL ) return FALSE; // Are we downloading to file or ram? m_bMem = ( pLocal == NULL ); { // Copy the url char buf[ sizeof( m_szUrl ) ]; DWORD size = sizeof( m_szUrl ) - 1; // Is it a local file? if ( GetFileAttributes( pUrl ) == MAXDWORD ) { // Fix the url if ( InternetCanonicalizeUrl( pUrl, buf, &size, 0 ) ) { strcpy_sz( m_szUrl, buf ); } // Copy the url name else strcpy_sz( m_szUrl, pUrl ); } // end if // Copy the local file name else strcpy_sz( m_szUrl, pUrl ); } // end copy url // Is it a local file? if ( GetFileAttributes( m_szUrl ) != MAXDWORD ) { CWinFile file; if ( file.OpenExisting( m_szUrl, GENERIC_READ ) ) { DWORD size = file.Size(); if ( m_bMem ) { // Allocate memory m_pMem = new BYTE[ size + 1 ]; if ( m_pMem == NULL ) { m_dwTransferStatus = NETFILE_DS_ERROR; return FALSE; } // end if // Read in the file if ( !file.Read( m_pMem, size, &m_dwDataRead ) ) { m_dwTransferStatus = NETFILE_DS_ERROR; return FALSE; } // end if // NULL terminate for good measure m_pMem[ size ] = 0; } // end if else { // Where to download the file if ( pLocal != DOWNLOADTEMP ) { strcpy_sz( m_szLocal, pLocal ); } else CWinFile::CreateTemp( m_szLocal ); // Copy the file CopyFile( m_szUrl, m_szLocal, FALSE ); // Open the file if ( !m_local.OpenExisting( m_szLocal, GENERIC_READ | GENERIC_WRITE ) ) { m_dwTransferStatus = NETFILE_DS_ERROR; return FALSE; } // end if // Get the file size m_dwDataRead = m_local.Size(); } // end else // Memory read complete m_dwTransferStatus = NETFILE_DS_DONE; return TRUE; } // end if } // end if if ( !m_bMem ) { // Where to download the file if ( pLocal != DOWNLOADTEMP ) { strcpy_sz( m_szLocal, pLocal ); } else CWinFile::CreateTemp( m_szLocal ); // Create a file to load data if ( !m_local.OpenNew( m_szLocal, GENERIC_READ | GENERIC_WRITE ) ) return FALSE; } // end else // Set status m_dwTransferStatus = NETFILE_DS_INITIALIZING; // Create a thread to download the file if ( !StartThread() ) { Destroy(); m_dwTransferStatus = NETFILE_DS_ERROR; return FALSE; } // end if return TRUE; }
static BOOL AFXAPI _ParseURLWorker(LPCTSTR pstrURL, LPURL_COMPONENTS lpComponents, DWORD& dwServiceType, INTERNET_PORT& nPort, DWORD dwFlags) { // this function will return bogus stuff if lpComponents // isn't set up to copy the components ASSERT(lpComponents != NULL && pstrURL != NULL); if (lpComponents == NULL || pstrURL == NULL) return FALSE; ASSERT(lpComponents->dwHostNameLength == 0 || lpComponents->lpszHostName != NULL); ASSERT(lpComponents->dwUrlPathLength == 0 || lpComponents->lpszUrlPath != NULL); ASSERT(lpComponents->dwUserNameLength == 0 || lpComponents->lpszUserName != NULL); ASSERT(lpComponents->dwPasswordLength == 0 || lpComponents->lpszPassword != NULL); ASSERT(AfxIsValidAddress(lpComponents, sizeof(URL_COMPONENTS), TRUE)); LPTSTR pstrCanonicalizedURL; TCHAR szCanonicalizedURL[INTERNET_MAX_URL_LENGTH]; DWORD dwNeededLength = INTERNET_MAX_URL_LENGTH; BOOL bRetVal; BOOL bMustFree = FALSE; DWORD dwCanonicalizeFlags = dwFlags & (ICU_NO_ENCODE | ICU_DECODE | ICU_NO_META | ICU_ENCODE_SPACES_ONLY | ICU_BROWSER_MODE); DWORD dwCrackFlags = dwFlags & (ICU_ESCAPE | ICU_USERNAME); bRetVal = InternetCanonicalizeUrl(pstrURL, szCanonicalizedURL, &dwNeededLength, dwCanonicalizeFlags); if (!bRetVal) { if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE; pstrCanonicalizedURL = new TCHAR[dwNeededLength]; bMustFree = TRUE; bRetVal = InternetCanonicalizeUrl(pstrURL, pstrCanonicalizedURL, &dwNeededLength, dwCanonicalizeFlags); if (!bRetVal) { delete [] pstrCanonicalizedURL; return FALSE; } } else pstrCanonicalizedURL = szCanonicalizedURL; // now that it's safely canonicalized, crack it bRetVal = InternetCrackUrl(pstrCanonicalizedURL, 0, dwCrackFlags, lpComponents); if (bMustFree) delete [] pstrCanonicalizedURL; // convert to MFC-style service ID if (!bRetVal) dwServiceType = INET_SERVICE_UNK; else { nPort = lpComponents->nPort; switch (lpComponents->nScheme) { case INTERNET_SCHEME_FTP: dwServiceType = INET_SERVICE_FTP; break; case INTERNET_SCHEME_GOPHER: dwServiceType = INET_SERVICE_GOPHER; break; case INTERNET_SCHEME_HTTP: dwServiceType = INET_SERVICE_HTTP; break; case INTERNET_SCHEME_HTTPS: dwServiceType = INET_SERVICE_HTTPS; break; case INTERNET_SCHEME_FILE: dwServiceType = INET_SERVICE_FILE; break; case INTERNET_SCHEME_NEWS: dwServiceType = INET_SERVICE_NNTP; break; case INTERNET_SCHEME_MAILTO: dwServiceType = INET_SERVICE_MAILTO; break; default: dwServiceType = INET_SERVICE_UNK; } } return bRetVal; }
virtual HRESULT STDMETHODCALLTYPE OnProgress( ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { HWND Item; LONG r; Item = GetDlgItem(m_hDialog, IDC_DOWNLOAD_PROGRESS); if (Item && ulProgressMax) { WCHAR szProgress[100]; WCHAR szProgressMax[100]; UINT uiPercentage = ((ULONGLONG)ulProgress * 100) / ulProgressMax; /* send the current progress to the progress bar */ SendMessageW(Item, PBM_SETPOS, uiPercentage, 0); /* format the bits and bytes into pretty and accesible units... */ StrFormatByteSizeW(ulProgress, szProgress, _countof(szProgress)); StrFormatByteSizeW(ulProgressMax, szProgressMax, _countof(szProgressMax)); /* ...and post all of it to our subclassed progress bar text subroutine */ StringCbPrintfW(m_ProgressText, sizeof(m_ProgressText), L"%u%% \x2014 %ls / %ls", uiPercentage, szProgress, szProgressMax); SendMessageW(Item, WM_SETTEXT, 0, (LPARAM)m_ProgressText); } Item = GetDlgItem(m_hDialog, IDC_DOWNLOAD_STATUS); if (Item && szStatusText && wcslen(szStatusText) > 0 && m_UrlHasBeenCopied == FALSE) { DWORD len = wcslen(szStatusText) + 1; PWSTR buf = (PWSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(WCHAR)); if (buf) { /* beautify our url for display purposes */ InternetCanonicalizeUrl(szStatusText, buf, &len, ICU_DECODE | ICU_NO_ENCODE); } else { /* just use the original */ buf = (PWSTR)szStatusText; } /* paste it into our dialog and don't do it again in this instance */ SendMessageW(Item, WM_SETTEXT, 0, (LPARAM)buf); m_UrlHasBeenCopied = TRUE; if (buf != szStatusText) { HeapFree(GetProcessHeap(), 0, buf); } } SetLastError(0); r = GetWindowLongPtrW(m_hDialog, GWLP_USERDATA); if (0 != r || 0 != GetLastError()) { *m_pbCancelled = TRUE; return E_ABORT; } return S_OK; }
BOOL CNetFile::HttpRequest(LPCTSTR pUrl, CRKey *pHeaders, CRKey *pData, LPCTSTR pMethod, LPCTSTR pLocal, BOOL bCloseFileAfterDownload, HWND hWndParent, DWORD dwUrlEncoding) {_STT(); // Lose previous file Destroy(); // Downloading m_bUpload = FALSE; // Save parent window m_hWndParent = hWndParent; // Save close file status m_bCloseFileAfterDownload = bCloseFileAfterDownload; // Sanity check if ( pUrl == NULL || *pUrl == NULL ) return FALSE; // Are we downloading to file or ram? m_bMem = ( pLocal == NULL ); { // Copy the url char buf[ sizeof( m_szUrl ) ] = { 0 }; DWORD size = sizeof( m_szUrl ) - 1; // Is it a local file? if ( GetFileAttributes( pUrl ) == MAXDWORD ) { // Fix the url if ( InternetCanonicalizeUrl( pUrl, buf, &size, 0 ) ) { strcpy_sz( m_szUrl, buf ); } // Copy the url name else strcpy_sz( m_szUrl, pUrl ); } // end if // Copy the local file name else strcpy_sz( m_szUrl, pUrl ); } // end copy url if ( !m_bMem ) { // Where to download the file if ( pLocal != DOWNLOADTEMP ) { strcpy_sz( m_szLocal, pLocal ); } else CWinFile::CreateTemp( m_szLocal ); // Create a file to load data if ( !m_local.OpenNew( m_szLocal, GENERIC_READ | GENERIC_WRITE ) ) return FALSE; } // end else // Set status m_dwTransferStatus = NETFILE_DS_INITIALIZING; // Save request method if ( pMethod == NULL || *pMethod == 0 ) m_sMethod = "POST"; else m_sMethod = pMethod; // Set data DWORD dwContentLength = 0; if ( pData != NULL ) { CPipe pipe; pData->EncodeUrl( &pipe, dwUrlEncoding ); m_sData.copy( (LPCTSTR)pipe.GetBuffer(), pipe.GetBufferSize() ); dwContentLength = pipe.GetBufferSize(); } // end if // Set headers if ( strcmpi( m_sMethod, "GET" ) ) { CRKey rkHeaders; if ( pHeaders != NULL ) rkHeaders.Copy( pHeaders ); rkHeaders.Set( "Content-Type", "application/x-www-form-urlencoded" ); rkHeaders.Set( "Content-Length", dwContentLength ); CPipe pipe; rkHeaders.EncodeHttpHeaders( &pipe ); m_sHeaders.copy( (LPCTSTR)pipe.GetBuffer(), pipe.GetBufferSize() ); } // end if // Create a thread to download the file if ( !StartThread() ) { Destroy(); m_dwTransferStatus = NETFILE_DS_ERROR; return FALSE; } // end if return TRUE; }
UINT DownloadAndUpgradeMsi(HINSTANCE hInst, CDownloadUI *piDownloadUI, LPCSTR szAppTitle, LPCSTR szUpdateLocation, LPCSTR szUpdate, LPCSTR szModuleFile, ULONG ulMinVer) { char *szTempPath = 0; char *szUpdatePath = 0; char *szUpdateCacheFile = 0; const char *pch = 0; DWORD cchTempPath = 0; DWORD cchUpdatePath = 0; DWORD cchUpdateCacheFile = 0; DWORD dwLastError = 0; UINT uiRet = 0; HRESULT hr = 0; DWORD Status = ERROR_SUCCESS; char szDebugOutput[MAX_STR_LENGTH] = {0}; char szText[MAX_STR_CAPTION] = {0}; // generate the path to the update == UPDATELOCATION + szUpdate // note: szUpdate is a relative path cchTempPath = lstrlen(szUpdateLocation) + lstrlen(szUpdate) + 2; // 1 for slash, 1 for null szTempPath = new char[cchTempPath]; if (!szTempPath) { ReportErrorOutOfMemory(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } memset((void*)szTempPath, 0x0, cchTempPath*sizeof(char)); hr = StringCchCopy(szTempPath, cchTempPath, szUpdateLocation); if (FAILED(hr)) { uiRet = HRESULT_CODE(hr); PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); goto CleanUp; } // check for trailing slash on szUpdateLocation pch = szUpdateLocation + lstrlen(szUpdateLocation) + 1; // put at null terminator pch = CharPrev(szUpdateLocation, pch); if (*pch != '/') { hr = StringCchCat(szTempPath, cchTempPath, szUrlPathSep); if (FAILED(hr)) { uiRet = HRESULT_CODE(hr); PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); goto CleanUp; } } hr = StringCchCat(szTempPath, cchTempPath, szUpdate); if (FAILED(hr)) { uiRet = HRESULT_CODE(hr); PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); goto CleanUp; } // canonicalize the URL path cchUpdatePath = cchTempPath*2; szUpdatePath = new char[cchUpdatePath]; if (!szUpdatePath) { ReportErrorOutOfMemory(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } if (!InternetCanonicalizeUrl(szTempPath, szUpdatePath, &cchUpdatePath, 0)) { dwLastError = GetLastError(); if (ERROR_INSUFFICIENT_BUFFER == dwLastError) { // try again delete [] szUpdatePath; szUpdatePath = new char[cchUpdatePath]; if (!szUpdatePath) { ReportErrorOutOfMemory(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } dwLastError = 0; // reset to success for 2nd attempt if (!InternetCanonicalizeUrl(szTempPath, szUpdatePath, &cchUpdatePath, 0)) dwLastError = GetLastError(); } } if (0 != dwLastError) { // error -- invalid path/Url PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath); uiRet = dwLastError; goto CleanUp; } DebugMsg("[Info] Downloading update package from --> %s\n", szUpdatePath); // set action text for download WIN::LoadString(hInst, IDS_DOWNLOADING_UPDATE, szText, MAX_STR_CAPTION); if (irmCancel == piDownloadUI->SetActionText(szText)) { ReportUserCancelled(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } // download the Update file so we can run it -- must be local to execute szUpdateCacheFile = new char[MAX_PATH]; cchUpdateCacheFile = MAX_PATH; if (!szUpdateCacheFile) { ReportErrorOutOfMemory(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_OUTOFMEMORY; goto CleanUp; } hr = WIN::URLDownloadToCacheFile(NULL, szUpdatePath, szUpdateCacheFile, cchUpdateCacheFile, 0, /* IBindStatusCallback = */ &CDownloadBindStatusCallback(piDownloadUI)); if (piDownloadUI->HasUserCanceled()) { ReportUserCancelled(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle); uiRet = ERROR_INSTALL_USEREXIT; goto CleanUp; } if (FAILED(hr)) { // error during download -- probably because file not found (or lost connection) PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_NOUPDATE, szUpdatePath); uiRet = ERROR_FILE_NOT_FOUND; goto CleanUp; } // // Perform trust check on MSI. Note, this must be done in a separate process. // This is because MSI 2.0 and higher register sip callbacks for verifying // digital signatures on msi files. At this point, it is quite likely that // the SIP callbacks have not been registered. So we don't want to load // wintrust.dll into this process's image yet, otherwise it will remain unaware // of the sip callbacks registered by WindowsInstaller-KB884016-x86.exe and will // fail later when it tries to verify the signature on the msi file downloaded // from the web. // Status = ExecuteVerifyUpdate(szModuleFile, szUpdateCacheFile); if (TRUST_E_PROVIDER_UNKNOWN == Status) { PostError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_NO_WINTRUST); uiRet = ERROR_CALL_NOT_IMPLEMENTED; goto CleanUp; } else if (ERROR_SUCCESS != Status) { PostFormattedError(hInst, piDownloadUI->GetCurrentWindow(), szAppTitle, IDS_UNTRUSTED, szUpdateCacheFile); uiRet = HRESULT_CODE(TRUST_E_SUBJECT_NOT_TRUSTED); goto CleanUp; } // continue other validations uiRet = ValidateUpdate(hInst, piDownloadUI, szAppTitle, szUpdateCacheFile, szModuleFile, ulMinVer); CleanUp: if (szTempPath) delete [] szTempPath; if (szUpdatePath) delete [] szUpdatePath; if (szUpdateCacheFile) { WIN::DeleteUrlCacheEntry(szUpdateCacheFile); delete [] szUpdateCacheFile; } return uiRet; }
CNetRequestImpl::CNetRequestImpl(CNetRequest* pParent, const char* method, const String& strUrl, IRhoSession* oSession, Hashtable<String,String>* pHeaders) { m_pParent = pParent; m_pParent->m_pCurNetRequestImpl = this; m_pHeaders = pHeaders; m_bCancel = false; m_pSession = oSession; pszErrFunction = NULL; hInet = NULL, hConnection = NULL, hRequest = NULL; memset(&uri, 0, sizeof(uri) ); m_strUrl = strUrl; CAtlStringW strUrlW(strUrl.c_str()); LOG(INFO) + "Method: " + method + ";Url: " + strUrl; do { if ( !URI::isLocalHost(strUrl.c_str()) && !SetupInternetConnection(strUrlW) ) { pszErrFunction = L"SetupInternetConnection"; break; } hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL ); if ( !hInet ) { pszErrFunction = L"InternetOpen"; break; } DWORD dwUrlLength = 1024; CAtlStringW strCanonicalUrlW; if ( !InternetCanonicalizeUrl( strUrlW, strCanonicalUrlW.GetBuffer(dwUrlLength), &dwUrlLength, 0) ) { pszErrFunction = _T("InternetCanonicalizeUrl"); break; } strCanonicalUrlW.ReleaseBuffer(); alloc_url_components( &uri, strCanonicalUrlW ); if( !InternetCrackUrl( strCanonicalUrlW, strCanonicalUrlW.GetLength(), 0, &uri ) ) { pszErrFunction = L"InternetCrackUrl"; break; } hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { pszErrFunction = L"InternetConnect"; break; } strReqUrlW = uri.lpszUrlPath; strReqUrlW += uri.lpszExtraInfo; DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_COOKIES; if ( uri.lpszScheme && wcsicmp(uri.lpszScheme,L"https")==0) dwFlags |= INTERNET_FLAG_SECURE; hRequest = HttpOpenRequest( hConnection, CAtlStringW(method), strReqUrlW, NULL, NULL, NULL, dwFlags, NULL ); if ( !hRequest ) { pszErrFunction = L"HttpOpenRequest"; break; } if (oSession!=null) { String strSession = oSession->getSession(); LOG(INFO) + "Cookie : " + strSession; if ( strSession.length() > 0 ) { String strHeader = "Cookie: " + strSession + "\r\n"; if ( !HttpAddRequestHeaders( hRequest, common::convertToStringW(strHeader).c_str(), -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE ) ) pszErrFunction = L"HttpAddRequestHeaders"; } } }while(0); }
char* remote_data(LPWSTR verb, char* url, char* body, size_t body_size, bool bGetHeaders, bool bGetRawData = false, bool bCheckSession = false, DWORD* pdwDataSize = NULL) { char *cstr = NULL; char *session = NULL; std::string data = ""; //CAtlStringA data; char sBuf[1024]; DWORD dwBytesRead = 0; LPWSTR urlw; HINTERNET hInet, hConnection, hRequest; LPTSTR pszFunction = NULL; if ( url==NULL || strlen(url)==0 ) return NULL; urlw = wce_mbtowc(url); hInet = hConnection = hRequest = NULL; do { // Don't make a connection attempt if there is no session session = get_db_session(load_source_url()); if ( bCheckSession && !session && !strstr(url, "clientcreate") ) { break; } if (session) free(session); if( !SetupInternetConnection(urlw) ) { break; } hInet = InternetOpen(_T("rhodes-wm"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL ); if ( !hInet ) { pszFunction = L"InternetOpen"; break; } DWORD lpdwBufferLength = sizeof(sBuf)/sizeof(wchar_t); if ( !InternetCanonicalizeUrl(urlw, (LPWSTR)sBuf, &lpdwBufferLength, 0) ) { pszFunction = L"InternetCanonicalizeUrl"; break; } ATLTRACE(L"Connecting to url: %s\n",(LPWSTR)sBuf); URL_COMPONENTS uri; alloc_url_components(&uri,url); if( !InternetCrackUrl((LPWSTR)sBuf,lpdwBufferLength,0,&uri) ) { pszFunction = L"InternetCrackUrl"; free_url_components(&uri); break; } hConnection = InternetConnect( hInet, uri.lpszHostName, uri.nPort, _T("anonymous"), NULL, INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { pszFunction = L"InternetConnect"; free_url_components(&uri); break; } wsprintf((LPWSTR)sBuf,L"%s%s",uri.lpszUrlPath,uri.lpszExtraInfo); hRequest = HttpOpenRequest( hConnection, verb, (LPWSTR)sBuf, NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_NO_CACHE_WRITE, NULL ); if ( !hRequest ) { pszFunction = L"HttpOpenRequest"; free_url_components(&uri); break; } free_url_components(&uri); //Send data if ( HttpSendRequest( hRequest, NULL, 0, body, body_size) ) { wchar_t res[10]; DWORD dwLen = 10; DWORD nIndex = 0; bool bOk = false; if( HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE,res,&dwLen,&nIndex) ){ if ( wcscmp(res,L"200") == 0 ) bOk = true; else { bOk = false; // If we're unauthorized, delete any cookies that might have been // stored so we don't reuse them later if ( wcscmp(res,L"401") == 0 ) delete_winmo_session(load_source_url()); } } if ( bOk ){ if ( bGetHeaders ){ DWORD dwSize = 0; HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS, NULL, &dwSize, NULL); if( dwSize != 0 ) { cstr = new char [dwSize+1]; // Call HttpQueryInfo again to get the headers. bOk = (bool) HttpQueryInfoA(hRequest, HTTP_QUERY_RAW_HEADERS, (LPVOID) cstr, &dwSize, NULL); } }else{ BOOL bRead = InternetReadFile(hRequest, &sBuf, sizeof(sBuf), &dwBytesRead); while (bRead && (dwBytesRead > 0)) { data.append(sBuf, dwBytesRead); //data.Append(sBuf, dwBytesRead); bRead = InternetReadFile(hRequest, &sBuf, sizeof(sBuf), &dwBytesRead); } if ( bGetRawData && pdwDataSize ){ cstr = new char [*pdwDataSize]; memcpy (cstr, data.c_str(), *pdwDataSize); } else { //make a copy of recieved data cstr = new char [data.size()+1]; strcpy (cstr, data.c_str()); //cstr = new char [data.GetLength()+1]; //strcpy (cstr, data.GetString()); } } } } else { pszFunction = L"HttpOpenRequest"; } } while(0); if (pszFunction) { ErrorMessage(pszFunction); } if(hRequest) InternetCloseHandle(hRequest); if(hConnection) InternetCloseHandle(hConnection); if(hInet) InternetCloseHandle(hInet); free(urlw); return cstr; }
fsInternetResult CCreateTPDownloadDlg::Crack(LPCSTR pszUrl) { CHAR m_szScheme [URL_SCHEME_SIZE]; CHAR m_szHost [URL_HOSTNAME_SIZE]; CHAR m_szUser [URL_USERNAME_SIZE]; CHAR m_szPassword [URL_PASSWORD_SIZE]; CHAR m_szPath [URL_PATH_SIZE]; DWORD urlLen = strlen (pszUrl) * 2; CHAR *pszCanUrl = NULL; fsString strUrl; if (*pszUrl == '"' || *pszUrl == '\'') { strUrl = pszUrl + 1; if (strUrl [0] == 0) return IR_BADURL; strUrl [strUrl.Length () - 1] = 0; m_strUrl = pszUrl = strUrl; } fsnew (pszCanUrl, CHAR, urlLen); if (!InternetCanonicalizeUrl (pszUrl, pszCanUrl, &urlLen, ICU_BROWSER_MODE)) { delete pszCanUrl; if (GetLastError () == ERROR_INSUFFICIENT_BUFFER) { fsnew (pszCanUrl, CHAR, urlLen+1); if (!InternetCanonicalizeUrl (pszUrl, pszCanUrl, &urlLen, ICU_BROWSER_MODE)) { delete pszCanUrl; return fsWinInetErrorToIR (); } } else return fsWinInetErrorToIR (); } URL_COMPONENTS m_url; ZeroMemory (&m_url, sizeof (m_url)); m_url.dwStructSize = sizeof (m_url); m_url.lpszHostName = m_szHost; m_url.lpszPassword = m_szPassword; m_url.lpszScheme = m_szScheme; m_url.lpszUrlPath = m_szPath; m_url.lpszUserName = m_szUser; m_url.dwHostNameLength = URL_HOSTNAME_SIZE; m_url.dwPasswordLength = URL_PASSWORD_SIZE; m_url.dwSchemeLength = URL_SCHEME_SIZE; m_url.dwUrlPathLength = URL_PATH_SIZE; m_url.dwUserNameLength = URL_USERNAME_SIZE; if (!InternetCrackUrl (pszCanUrl, urlLen, 0, &m_url)) { delete pszCanUrl; return fsWinInetErrorToIR (); } delete pszCanUrl; if (strstr (m_url.lpszScheme, "mmsh") == NULL && strstr (m_url.lpszScheme, "mmst") == NULL && strstr (m_url.lpszScheme, "mms") == NULL && strstr (m_url.lpszScheme, "rtsp") == NULL || m_url.dwHostNameLength == 0) return IR_BADURL; return IR_SUCCESS; }