diff --git a/doc/ClientLog.md b/doc/ClientLog.md index dee260cec..3389631bb 100644 --- a/doc/ClientLog.md +++ b/doc/ClientLog.md @@ -27,7 +27,6 @@ Non-opt builds (dbg-win and coverage-win) allow provide much more logging and ha [LoggingLevel] LC_CORE=5 LC_NET=4 -LC_PLUGIN=3 LC_SERVICE=3 LC_SETUP=3 LC_SHELL=3 diff --git a/doc/CustomizingOmaha.md b/doc/CustomizingOmaha.md index 82dd951f9..aa77bd2b2 100644 --- a/doc/CustomizingOmaha.md +++ b/doc/CustomizingOmaha.md @@ -32,7 +32,6 @@ The following items **MUST** be changed before releasing a fork of Omaha. Prefe > Generate new GUIDs for every interface and coclass. Changing the descriptive names for them isn't a bad idea either. (Do not, however, change code-level names such as `IAppBundle` or `GoogleUpdate3UserClass`.) - * **`omaha\plugins\update\activex\update_control_idl.idl`** > Generate new GUIDs for every interface and coclass. diff --git a/doc/DeveloperSetupGuide.md b/doc/DeveloperSetupGuide.md index 2a4f69d77..7fe8bd54f 100644 --- a/doc/DeveloperSetupGuide.md +++ b/doc/DeveloperSetupGuide.md @@ -4,7 +4,7 @@ These instructions are intended to assist the would-be Omaha developer with sett We are striving to make the code build with the latest Windows toolchain from Microsoft. Since there is no continuous integration for this project, the code may not build using previous versions of the toolchain. -#### Currently, the supported toolchain is Visual Studio 2019 Update 16.3.6 and Windows SDK 10.0.18362.0. #### +#### Currently, the supported toolchain is Visual Studio 2019 Update 16.4.3 and Windows SDK 10.0.18362.0. #### Visual Studio 2017 Update 15.9.16 should work too. @@ -16,8 +16,6 @@ The following packages are required to build Omaha: * A copy of the Omaha source code. This can be done by cloning this repository. * Microsoft Visual Studio 2017 or 2019. The free Visual Studio Community edition is sufficient to build. * Download [here](https://visualstudio.microsoft.com/downloads) - * ATL Server headers - * Download [here](http://atlserver.codeplex.com). Omaha needs this library for regular expression support. * Windows 10 SDK. * Download Windows 10 SDK [here](https://dev.windows.com/en-us/downloads/windows-10-sdk). * Microsoft .NET Framework 2.0 diff --git a/doc/Omaha3SourceOrganization.md b/doc/Omaha3SourceOrganization.md index 8e9004e9b..d18e6d4fd 100644 --- a/doc/Omaha3SourceOrganization.md +++ b/doc/Omaha3SourceOrganization.md @@ -31,7 +31,6 @@ omaha\ mi_exe_stub\ Produces a stub EXE, mi_exe_stub.exe, that will be combined with a TAR to produce the untagged meta-installer. (The script to actually do the merge lives in installers\, mentioned below.) -plugins\ Produces the browser plugin, npGoogleUpdate3.dll. recovery\ Produces tools for “Code Red” - a mechanism that the apps being managed by Omaha can use to check Omaha’s integrity, and restore it if it appears broken. diff --git a/doc/Omaha3Walkthrough.md b/doc/Omaha3Walkthrough.md index 484ab5894..a3ecb0604 100644 --- a/doc/Omaha3Walkthrough.md +++ b/doc/Omaha3Walkthrough.md @@ -35,7 +35,7 @@ The Omaha Client always operates at user privilege levels and owns the UI of Oma * Setup - Create or update a permanent Omaha install, of either user or machine variety. * Install - Invoke the COM server to create a state machine object, fill it out with apps to be managed, and call a suitable function on it such as `checkForUpdate()`, `download()`, or `install()`. From that point onwards, poll the state object as the COM server does the work for you, and update the UI as the states advance. -In general, when referring to “the client”, we’re referring to the official Google Update client, which happens to live in the same executable as the COM Server; the role that the executable plays is decided simply by which command line is passed to it. However, there are other clients that may access the COM server; some of them we own (the web browser plugins), and some we do not own (partner applications which access our COM APIs directly). The server must stay as secure as possible, and sanitize all input. +In general, when referring to “the client”, we’re referring to the official Google Update client, which happens to live in the same executable as the COM Server; the role that the executable plays is decided simply by which command line is passed to it. However, there are other clients that may access the COM server; The server must stay as secure as possible, and sanitize all input. ## Example Code Flow ## @@ -50,7 +50,6 @@ appname=Google%20Chrome&needsadmin=False&lang=en" * We check the machine to see if there’s already a user Omaha installed with a version newer than or equal to ours. (If it’s equal to ours, we will do some supplementary checking to make sure that the installed copy is sane and working properly, and if not, we over-install.) Let’s assume that there is no user Omaha installed. We will create the direct directory in `AppData`, copy over the files, and then make entries in the Registry to do the following: * Register our COM servers * Create scheduled tasks to check for an update every five hours - * Expose our web browser plugins to IE/Firefox/Chrome/Safari/Opera * Store initial configuration/state for Omaha itself in the Registry * Register Omaha itself as an Omaha-managed application, so it can check for updates for itself * The client then starts a new copy of itself in its permanent installed location, modifying the command line from `/install` to `/handoff`. Once again, the constant shell loads Goopdate and passes the command line along - this time, however, we’re using the constant shell in the newly-created permanent install of Omaha, rather than the one in the temp directory. @@ -74,7 +73,6 @@ So, what files are actually in a permanent install of Omaha once it’s complete | `GoogleUpdateBroker.exe`
GoogleUpdateOnDemand.exe -
COM Forwarders. Both of these are small EXEs whose sole purpose is to take their own command line, append a command line switch to the end, and pass it to the Constant Shell.
goopdate.dll The central Omaha3 binary.
goopdateres_*.dll Resource-only DLLs, one per language, containing localized strings. As part of its startup, Goopdate will read the “lang” extra-args parameter if one exists (or the Registry) and select a language to load.
npGoogleUpdate3.dll Our web browser plugin. (It actually contains two plugins: ActiveX plugins for IE, and an NPAPI plugin for Firefox, Chrome, and other browsers that use that.) Allows Javascript on selected subdomains of google.com to access and use the COM Server.
psmachine.dll
psuser.dll
Custom marshaling stubs used by the COM Server. Used in order to work around some Windows bugs that are triggered by having both Machine and User Omaha installed simultaneously.
The directory tree typically looks like this:
diff --git a/doc/ServerProtocolV2.md b/doc/ServerProtocolV2.md index 09db2b743..ddc594070 100644 --- a/doc/ServerProtocolV2.md +++ b/doc/ServerProtocolV2.md @@ -180,7 +180,7 @@ _Request Attributes_ * client (optional): Similar to brand code. * iid (optional): A random GUID used to uniquely count install attempts. For example, if a user fails to install then re-runs the installer and succeeds, we might want to count that as one "attempt". * installage (optional): The number of days since the app was first installed. - * installsource (optional): Specifies the source of the request. Examples include "oneclick", "clickonce", "ondemandupdate", "ondemandcheckforupdate", "offline", "scheduler", "core". This value is specified to the Omaha client on the command line. + * installsource (optional): Specifies the source of the request. Examples include "clickonce", "ondemandupdate", "ondemandcheckforupdate", "offline", "scheduler", "core". This value is specified to the Omaha client on the command line. * fp (optional): Specifies a version-agnostic identifier for the last downloaded binary for this app. Usually "1.X" where X is the sha-256 hash of the downloaded binary. _Response Attributes_ diff --git a/omaha/VERSION b/omaha/VERSION index 19177a13a..a38f45a37 100644 --- a/omaha/VERSION +++ b/omaha/VERSION @@ -5,7 +5,4 @@ version_major = 1 # 1-65535 version_minor = 3 # 0-65535 version_build = 35 # 1-65535 -version_patch = 421 # 0-65535 - -oneclick_plugin_version = 9 -update_plugin_version = 3 +version_patch = 441 # 0-65535 diff --git a/omaha/base/apply_tag.cc b/omaha/base/apply_tag.cc index cc50e3ae0..c8809103d 100644 --- a/omaha/base/apply_tag.cc +++ b/omaha/base/apply_tag.cc @@ -18,8 +18,8 @@ #include "omaha/base/apply_tag.h" #include -#include #include +#include #include #include "omaha/base/utils.h" @@ -40,15 +40,7 @@ ApplyTag::ApplyTag() bool ApplyTag::IsValidTagString(const char* tag_string) { ASSERT1(tag_string); - - CAtlRegExp regex; - REParseError error = regex.Parse(kValidTagStringRegEx); - if (error != REPARSE_ERROR_OK) { - return false; - } - - CAtlREMatchContext context; - return !!regex.Match(tag_string, &context); + return std::regex_match(tag_string, std::regex(kValidTagStringRegEx)); } HRESULT ApplyTag::Init(const TCHAR* signed_exe_file, diff --git a/omaha/base/atl_regexp.cc b/omaha/base/atl_regexp.cc deleted file mode 100644 index ac0babba5..000000000 --- a/omaha/base/atl_regexp.cc +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/atl_regexp.h" - -#include -#include - -namespace omaha { - -constexpr int kMaxArgs = 16; - -AtlRE::AtlRE(const TCHAR* pattern, bool case_sensitive) { - ASSERT(pattern, (L"")); - REParseError status = re_.Parse(pattern, case_sensitive); - ASSERT(status == REPARSE_ERROR_OK, (L"")); -} - -AtlRE::~AtlRE() { -} - -bool AtlRE::DoMatchImpl(const TCHAR* text, - CString* args[], - int n, - const TCHAR** match_end) const { - // text may be NULL. - ASSERT(args, (L"")); - - if (!text) { - return false; - } - - AtlMatchContext matches; - BOOL b = re_.Match(text, &matches, match_end); - if (!b || matches.m_uNumGroups < static_cast(n)) { - return false; - } - - // Oddly enough, the Match call will make match_end - // point off the end of the string if the result is at the - // end of the string. We check this and handle it. - if (match_end) { - if ((*match_end - text) >= lstrlen(text)) { - *match_end = NULL; - } - } - - const TCHAR* start = 0; - const TCHAR* end = 0; - for (int i = 0; i < n; ++i) { - matches.GetMatch(i, &start, &end); - const ptrdiff_t size = end - start; - if (size > INT_MAX) { - return false; - } - const int len = static_cast(size); - ASSERT(args[i], (L"")); - // len+1 for the NULL character that's placed by lstrlen - VERIFY1(lstrcpyn(args[i]->GetBufferSetLength(len), start, len + 1) != NULL); - } - return true; -} - -} // namespace omaha diff --git a/omaha/base/atl_regexp.h b/omaha/base/atl_regexp.h deleted file mode 100644 index 1353a16d3..000000000 --- a/omaha/base/atl_regexp.h +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// ATL Regular expression class that implements the RE interface. -// See MSDN help for example patterns (lookup help on CAtlRegExp) -// NOTE: This class adds about 8k to release builds. -// TODO(omaha): add a unit test, showing examples, testing functionality -// and perf. - -#ifndef OMAHA_COMMON_ATL_REGEXP_H__ -#define OMAHA_COMMON_ATL_REGEXP_H__ - -#include -#pragma warning(push) -// enumerator 'identifier' in switch of enum 'enumeration' is not explicitly -// handled by a case label -#pragma warning(disable:4061) -#include -#pragma warning(pop) -#include -#include "base/basictypes.h" -#include "omaha/base/regexp.h" -#include "omaha/base/string.h" - -namespace omaha { - -// This class is essentially a copy of CAtlRECharTraitsWide from , but -// I've replaced CRT functions that are not in our minicrt. -// -// TODO(omaha): do we need this? -class CAtlRECharTraitsWideNoCrt -{ -public: - typedef WCHAR RECHARTYPE; - - // ATL80 addition. - static size_t GetBitFieldForRangeArrayIndex(const RECHARTYPE *sz) throw() - { -#ifndef ATL_NO_CHECK_BIT_FIELD - ATLASSERT(UseBitFieldForRange()); -#endif - return static_cast(*sz); - } - - static RECHARTYPE *Next(const RECHARTYPE *sz) throw() - { - return (RECHARTYPE *) (sz+1); - } - - static int Strncmp(const RECHARTYPE *szLeft, - const RECHARTYPE *szRight, size_t nCount) throw() - { - return String_StrNCmp(szLeft, szRight, nCount, false); - } - - static int Strnicmp(const RECHARTYPE *szLeft, - const RECHARTYPE *szRight, size_t nCount) throw() - { - return String_StrNCmp(szLeft, szRight, nCount,true); - } - - static RECHARTYPE *Strlwr(RECHARTYPE *sz) throw() - { - return String_FastToLower(sz); - } - - // In ATL 80 Strlwr must be passed a buffer size for security reasons. - // TODO(omaha): Implement the function to consider the nSize param. - static RECHARTYPE *Strlwr(RECHARTYPE *sz, int) throw() - { - return Strlwr(sz); - } - - static long Strtol(const RECHARTYPE *sz, - RECHARTYPE **szEnd, int nBase) throw() - { - return wcstol(sz, szEnd, nBase); - } - - static int Isdigit(RECHARTYPE ch) throw() - { - return String_IsDigit(ch) ? 1 : 0; - } - - static const RECHARTYPE** GetAbbrevs() - { - static const RECHARTYPE *s_szAbbrevs[] = - { - L"a([a-zA-Z0-9])", // alpha numeric - L"b([ \\t])", // white space (blank) - L"c([a-zA-Z])", // alpha - L"d([0-9])", // digit - L"h([0-9a-fA-F])", // hex digit - L"n(\r|(\r?\n))", // newline - L"q(\"[^\"]*\")|(\'[^\']*\')", // quoted string - L"w([a-zA-Z]+)", // simple word - L"z([0-9]+)", // integer - NULL - }; - - return s_szAbbrevs; - } - - static BOOL UseBitFieldForRange() throw() - { - return FALSE; - } - - static int ByteLen(const RECHARTYPE *sz) throw() - { - return int(lstrlen(sz)*sizeof(WCHAR)); - } -}; - -typedef CAtlRegExp AtlRegExp; -typedef CAtlREMatchContext AtlMatchContext; - -// implements the RE class using the ATL Regular Expressions class -class AtlRE : public RE { - public: - - AtlRE(const TCHAR* pattern, bool case_sensitive = true); - virtual ~AtlRE(); - - protected: - // See regexp.h for an explanation. - virtual bool DoMatchImpl(const TCHAR* text, - CString* args[], - int n, - const TCHAR** match_end) const; - - private: - mutable AtlRegExp re_; - DISALLOW_COPY_AND_ASSIGN(AtlRE); -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_ATL_REGEXP_H__ diff --git a/omaha/base/atl_regexp_unittest.cc b/omaha/base/atl_regexp_unittest.cc deleted file mode 100644 index a1c426133..000000000 --- a/omaha/base/atl_regexp_unittest.cc +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/atl_regexp.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -TEST(AtlRETest, AtlRE) { - AtlRE newline_test_re(_T("ab{\\n}cd")); - const TCHAR* newline_strings[] = { _T("\n"), _T("\r"), _T("\r\n") }; - for (size_t i = 0; i < arraysize(newline_strings); ++i) { - CString content(_T("ab")); - content.Append(newline_strings[i]); - content.Append(_T("cd")); - const TCHAR* content_ptr = content.GetString(); - CString newline; - EXPECT_TRUE(RE::FindAndConsume(&content_ptr, newline_test_re, &newline)); - EXPECT_STREQ(newline, newline_strings[i]); - } - - // Check that AtlRE works with Unicode characters. - AtlRE one_two_three_four(_T("\x1234")); - EXPECT_TRUE(RE::PartialMatch(_T("\x4321\x1234\x4321"), one_two_three_four)); -} - -} // namespace omaha diff --git a/omaha/base/build.scons b/omaha/base/build.scons index 7c5ea2f40..ddf551ed6 100644 --- a/omaha/base/build.scons +++ b/omaha/base/build.scons @@ -28,7 +28,6 @@ local_env = env.Clone() inputs = [ 'apply_tag.cc', 'app_util.cc', - 'atl_regexp.cc', 'browser_utils.cc', 'cgi.cc', 'clipboard.cc', @@ -61,7 +60,6 @@ inputs = [ 'queue_timer.cc', 'reactor.cc', 'reg_key.cc', - 'regexp.cc', 'registry_monitor_manager.cc', 'safe_format.cc', 'service_utils.cc', diff --git a/omaha/base/const_config.h b/omaha/base/const_config.h index 13bb02f4f..8b214c58e 100644 --- a/omaha/base/const_config.h +++ b/omaha/base/const_config.h @@ -25,24 +25,6 @@ namespace omaha { #define kCiRegKeyShared GOOPDATE_MAIN_KEY kRegKeyShared #define kRegValueReportIds _T("report_ids") -// TODO(omaha): Move these plugin values someplace else. Since we're building -// constants, that should probably be the customization header. Move the Omaha 3 -// plugin equivalents from config.cc there as well. - -// NOTE: ONECLICK_PLUGIN_VERSION_ANSI is defined in main.scons -// For example: kOneClickProgId == "Google.OneClickCtrl.1" -const TCHAR* const kOneClickProgId = COMPANY_NAME_IDENTIFIER - _T(".OneClickCtrl.") - _T(ONECLICK_PLUGIN_VERSION_ANSI); -// The plug-in MIME type. -// For example: -// kOneClickPluginMimeTypeAnsi == "application/x-vnd.google.oneclickctrl.1" -// TODO(omaha): Deal with the "Google.OneClickCtrl.%d") in -// tools\goopdump\data_dumper_oneclick.cc after integrating goopdump. -#define kOneClickPluginMimeTypeAnsi \ - "application/x-vnd." COMPANY_DOMAIN_BASE_ANSI ".oneclickctrl." \ - ONECLICK_PLUGIN_VERSION_ANSI - } // namespace omaha #endif // OMAHA_BASE_CONST_CONFIG_H_ diff --git a/omaha/base/constants.h b/omaha/base/constants.h index 577469e9f..048145778 100644 --- a/omaha/base/constants.h +++ b/omaha/base/constants.h @@ -113,8 +113,6 @@ const TCHAR* const kOmahaBrokerFileName = MAIN_EXE_BASE_NAME _T("Broker.exe"); const TCHAR* const kOmahaOnDemandFileName = MAIN_EXE_BASE_NAME _T("OnDemand.exe"); -const TCHAR* const kOmahaWebPluginFileName = - MAIN_EXE_BASE_NAME _T("WebPlugin.exe"); const TCHAR* const kCrashHandlerFileName = CRASH_HANDLER_NAME _T(".exe"); const TCHAR* const kCrashHandler64FileName = CRASH_HANDLER_NAME _T("64.exe"); const TCHAR* const kOmahaMetainstallerFileName = @@ -248,15 +246,6 @@ const TCHAR* const kChromeAppId = CHROME_APP_ID; // Expands to HKEY_LOCAL_MACHINE\SOFTWARE\Google\UpdateDev #define MACHINE_REG_UPDATE_DEV MACHINE_KEY REG_UPDATE_DEV -// Regular expressions for the servers allowed to use the Omaha plugins. -const TCHAR* const kSiteLockPatternStrings[] = { - _T("^(gears)|(mail)|(tools)|(www)|(desktop)|(pack)|(chrome)|(drive)\\.google\\.com$"), // NOLINT - _T("^www\\.google\\.(ad)|(bg)|(ca)|(cn)|(cz)|(de)|(es)|(fi)|(fr)|(gr)|(hr)|(hu)|(it)|(ki)|(kr)|(lt)|(lv)|(nl)|(no)|(pl)|(pt)|(ro)|(ru)|(sk)|(sg)|(sl)|(sr)|(vn)$"), // NOLINT - _T("^www\\.google\\.co\\.(hu)|(id)|(il)|(it)|(jp)|(kr)|(th)|(uk)$"), - _T("^www\\.google\\.com\\.(ar)|(au)|(br)|(cn)|(et)|(gr)|(hr)|(ki)|(lv)|(om)|(pl)|(pt)|(ru)|(sg)|(sv)|(tr)|(vn)$"), // NOLINT - _T("^(www\\.)?chrome\\.com$"), -}; - // // Minimum compatible shell version. // Shell versions equal to or newer than the following version are compatible @@ -323,13 +312,6 @@ const TCHAR* const kRegValueLastCheckPeriodSec = _T("LastCheckPeriodSec"); // Uses the production or the test cup keys. const TCHAR* const kRegValueCupKeys = _T("TestKeys"); -// Allow a custom host pattern to be specified. For example, -// "^https?://some_test_server\.google\.com/". For other examples, see -// kSiteLockPatternStrings. The detailed regular expression syntax is documented -// in the MSDN documentation for the CAtlRegExp class: -// http://msdn.microsoft.com/en-us/library/k3zs4axe.aspx. -const TCHAR* const kRegValueOneClickHostPattern = _T("OneClickHostPattern"); - // Disables executable verification for application commands. const TCHAR* const kRegValueSkipCommandVerification = _T("NoAppCommandVerification"); @@ -415,13 +397,6 @@ const TCHAR* const kDefaultCountryCode = _T("us"); // the max length of the extra info we can store inside the install stubs. const int kExtraMaxLength = 64 * 1024; // 64 KB -#if defined(HAS_DEVICE_MANAGEMENT) - -// The maximum length of an enrollment token. -const int kEnrollmentTokenMaxLength = 1024; - -#endif // defined(HAS_DEVICE_MANAGEMENT) - // Default brand code value when one is not specified. // This has been specifically assigned to Omaha. const TCHAR* const kDefaultGoogleUpdateBrandCode = _T("GGLS"); diff --git a/omaha/base/error.h b/omaha/base/error.h index 71c7b783c..148bad296 100644 --- a/omaha/base/error.h +++ b/omaha/base/error.h @@ -449,11 +449,12 @@ const ULONG kFacilityOmaha = 67; #define GOOGLEUPDATE_COMMANDLINE_E_NO_SCENARIO_HANDLER_MATCHED \ MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xC01) -// OneClick custom error codes -#define GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED \ - MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xD01) -#define GOOPDATE_E_ONECLICK_LANGUAGE_NOT_SUPPORTED \ - MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xD02) +// OneClick custom error codes. +// Obsolete. +// #define GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED \ +// MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xD01) +// #define GOOPDATE_E_ONECLICK_LANGUAGE_NOT_SUPPORTED \ +// MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xD02) // Usage stats / metrics error codes #define GOOPDATE_E_METRICS_LOCK_INIT_FAILED \ diff --git a/omaha/base/logging.cc b/omaha/base/logging.cc index a0d34208c..1b0ef0a76 100644 --- a/omaha/base/logging.cc +++ b/omaha/base/logging.cc @@ -101,7 +101,6 @@ struct { LC_ENTRY(LC_SHELL), LC_ENTRY(LC_CORE), LC_ENTRY(LC_JS), - LC_ENTRY(LC_PLUGIN), LC_ENTRY(LC_SERVICE), LC_ENTRY(LC_OPT), LC_ENTRY(LC_NET), diff --git a/omaha/base/logging.h b/omaha/base/logging.h index 2a6d714af..ef7dbf937 100644 --- a/omaha/base/logging.h +++ b/omaha/base/logging.h @@ -129,7 +129,6 @@ namespace omaha { // Shortcuts for different logging categories - no need to specify the category. #define CORE_LOG(x, y) LC_LOG_DEBUG(omaha::LC_CORE, x, y) #define NET_LOG(x, y) LC_LOG_DEBUG(omaha::LC_NET, x, y) -#define PLUGIN_LOG(x, y) LC_LOG_DEBUG(omaha::LC_PLUGIN, x, y) #define SERVICE_LOG(x, y) LC_LOG_DEBUG(omaha::LC_SERVICE, x, y) #define SETUP_LOG(x, y) LC_LOG_DEBUG(omaha::LC_SETUP, x, y) #define SHELL_LOG(x, y) LC_LOG_DEBUG(omaha::LC_SHELL, x, y) @@ -154,7 +153,6 @@ enum LogCategory { LC_SHELL, LC_CORE, LC_JS, - LC_PLUGIN, LC_SERVICE, LC_OPT, LC_NET, diff --git a/omaha/base/process.cc b/omaha/base/process.cc index 05a6b343b..7001bd7d4 100644 --- a/omaha/base/process.cc +++ b/omaha/base/process.cc @@ -159,7 +159,7 @@ bool Process::Running() const { HANDLE Process::AssignToJob() { // Make sure that the process handle is valid if (!get(process_)) { - return false; + return nullptr; } // Create a job @@ -168,7 +168,7 @@ HANDLE Process::AssignToJob() { UTIL_LOG(LEVEL_ERROR, (_T("[Process::AssignToJob - CreateJobObject failed][0x%x]"), HRESULTFromLastError())); - return false; + return nullptr; } // Assign the process to the job @@ -176,7 +176,7 @@ HANDLE Process::AssignToJob() { UTIL_LOG(LEVEL_ERROR, (_T("[Process::AssignToJob-AssignProcessToJobObject fail][0x%x]"), HRESULTFromLastError())); - return false; + return nullptr; } return release(job); diff --git a/omaha/base/regexp.cc b/omaha/base/regexp.cc deleted file mode 100644 index ba071ca06..000000000 --- a/omaha/base/regexp.cc +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/regexp.h" -#include "omaha/base/debug.h" - -namespace omaha { - -#define kMaxArgs 16 - -bool RE::PartialMatch(const TCHAR* text, const RE& re, // 3..16 args - CString * a0, - CString * a1, - CString * a2, - CString * a3, - CString * a4, - CString * a5, - CString * a6, - CString * a7, - CString * a8, - CString * a9, - CString * a10, - CString * a11, - CString * a12, - CString * a13, - CString * a14, - CString * a15) -{ - ASSERT(text, (L"")); - // a0 may be NULL - // a1 may be NULL - // a2 may be NULL - // a3 may be NULL - // a4 may be NULL - // a5 may be NULL - // a6 may be NULL - // a7 may be NULL - // a8 may be NULL - // a9 may be NULL - // a10 may be NULL - // a11 may be NULL - // a12 may be NULL - // a13 may be NULL - // a14 may be NULL - // a15 may be NULL - - CString * args[kMaxArgs]; - int n = 0; - if (a0 == NULL) goto done; args[n++] = a0; - if (a1 == NULL) goto done; args[n++] = a1; - if (a2 == NULL) goto done; args[n++] = a2; - if (a3 == NULL) goto done; args[n++] = a3; - if (a4 == NULL) goto done; args[n++] = a4; - if (a5 == NULL) goto done; args[n++] = a5; - if (a6 == NULL) goto done; args[n++] = a6; - if (a7 == NULL) goto done; args[n++] = a7; - if (a8 == NULL) goto done; args[n++] = a8; - if (a9 == NULL) goto done; args[n++] = a9; - if (a10 == NULL) goto done; args[n++] = a10; - if (a11 == NULL) goto done; args[n++] = a11; - if (a12 == NULL) goto done; args[n++] = a12; - if (a13 == NULL) goto done; args[n++] = a13; - if (a14 == NULL) goto done; args[n++] = a14; - if (a15 == NULL) goto done; args[n++] = a15; - -done: - return re.DoMatchImpl(text,args,n,NULL); -} - -// Like PartialMatch(), except the "input" is advanced past the matched -// text. Note: "input" is modified iff this routine returns true. -// For example, "FindAndConsume(s, "(\\w+)", &word)" finds the next -// word in "s" and stores it in "word". -bool RE::FindAndConsume(const TCHAR **input, const RE& re, - CString * a0, - CString * a1, - CString * a2, - CString * a3, - CString * a4, - CString * a5, - CString * a6, - CString * a7, - CString * a8, - CString * a9, - CString * a10, - CString * a11, - CString * a12, - CString * a13, - CString * a14, - CString * a15) -{ - ASSERT(input, (L"")); - // a0 may be NULL - // a1 may be NULL - // a2 may be NULL - // a3 may be NULL - // a4 may be NULL - // a5 may be NULL - // a6 may be NULL - // a7 may be NULL - // a8 may be NULL - // a9 may be NULL - // a10 may be NULL - // a11 may be NULL - // a12 may be NULL - // a13 may be NULL - // a14 may be NULL - // a15 may be NULL - - CString * args[kMaxArgs]; - int n = 0; - if (a0 == NULL) goto done; args[n++] = a0; - if (a1 == NULL) goto done; args[n++] = a1; - if (a2 == NULL) goto done; args[n++] = a2; - if (a3 == NULL) goto done; args[n++] = a3; - if (a4 == NULL) goto done; args[n++] = a4; - if (a5 == NULL) goto done; args[n++] = a5; - if (a6 == NULL) goto done; args[n++] = a6; - if (a7 == NULL) goto done; args[n++] = a7; - if (a8 == NULL) goto done; args[n++] = a8; - if (a9 == NULL) goto done; args[n++] = a9; - if (a10 == NULL) goto done; args[n++] = a10; - if (a11 == NULL) goto done; args[n++] = a11; - if (a12 == NULL) goto done; args[n++] = a12; - if (a13 == NULL) goto done; args[n++] = a13; - if (a14 == NULL) goto done; args[n++] = a14; - if (a15 == NULL) goto done; args[n++] = a15; - -done: - return re.DoMatchImpl(*input,args,n,input); -} - -} // namespace omaha - diff --git a/omaha/base/regexp.h b/omaha/base/regexp.h deleted file mode 100644 index 25781c1f0..000000000 --- a/omaha/base/regexp.h +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Implementors: There is only one function to implement -- DoMatchImpl -// See below - -#ifndef OMAHA_COMMON_REGEXP_H__ -#define OMAHA_COMMON_REGEXP_H__ - -#include - -namespace omaha { - -// Interface for regular expression matching. Also corresponds to a -// pre-compiled regular expression. An "RE" object is safe for -// concurrent use by multiple threads. -class RE { - public: - - // Matches "text" against "pattern". If pointer arguments are - // supplied, copies matched sub-patterns into them. Use braces - // "{", "}" within the regexp to indicate a pattern to be copied. - // - // Returns true iff all of the following conditions are satisfied: - // a. some substring of "text" matches "pattern" - // b. The number of matched sub-patterns is >= number of supplied pointers - static bool PartialMatch(const TCHAR* text, const RE& re, // 3..16 args - CString * a0 = NULL, - CString * a1 = NULL, - CString * a2 = NULL, - CString * a3 = NULL, - CString * a4 = NULL, - CString * a5 = NULL, - CString * a6 = NULL, - CString * a7 = NULL, - CString * a8 = NULL, - CString * a9 = NULL, - CString * a10 = NULL, - CString * a11 = NULL, - CString * a12 = NULL, - CString * a13 = NULL, - CString * a14 = NULL, - CString * a15 = NULL); - - // Like PartialMatch(), except the "input" is advanced past the matched - // text. Note: "input" is modified iff this routine returns true. - // For example, "FindAndConsume(s, "{\\w+}", &word)" finds the next - // word in "s" and stores it in "word". - static bool FindAndConsume(const TCHAR** input, const RE& re, - CString * a0 = NULL, - CString * a1 = NULL, - CString * a2 = NULL, - CString * a3 = NULL, - CString * a4 = NULL, - CString * a5 = NULL, - CString * a6 = NULL, - CString * a7 = NULL, - CString * a8 = NULL, - CString * a9 = NULL, - CString * a10 = NULL, - CString * a11 = NULL, - CString * a12 = NULL, - CString * a13 = NULL, - CString * a14 = NULL, - CString * a15 = NULL); - - protected: - - // The behavior of this function is subject to how it's used - // in PartialMatch() and FindAndConsume() above. See the header - // description of those functions to understand how an implementation - // should behave. - // text is the text we're looking in - // args is where matches should be outputted - // n is the number of CStrings in args - // match_end is a pointer to the position in text that - // we ended matching on - // returns true if data was found, false otherwise - // Example:Suppose text = "google 1\nYahoo! 2\n ..." and the regexp - // is something like "{\w+} \d". If args has two CStrings (n=2), - // then args[0] = "google", arg[1] = "1" and match_end will point to the \n - // before "Yahoo!" - virtual bool DoMatchImpl(const TCHAR *text, - CString * args[], - int n, - const TCHAR ** match_end) const = 0; -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_REGEXP_H__ diff --git a/omaha/base/security/build.scons b/omaha/base/security/build.scons index 8eaeaeb37..50df69290 100644 --- a/omaha/base/security/build.scons +++ b/omaha/base/security/build.scons @@ -36,7 +36,6 @@ security_inputs = [ 'p256_ec.c', 'p256_ecdsa.c', 'p256_prng.c', - 'sha.c', 'sha256.c', 'util.c', ] diff --git a/omaha/base/security/hmac.c b/omaha/base/security/hmac.c index 667076d6b..0eeb17a73 100644 --- a/omaha/base/security/hmac.c +++ b/omaha/base/security/hmac.c @@ -19,7 +19,6 @@ #include "util.h" #include -#include "sha.h" #include "sha256.h" static void HMAC_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { @@ -46,11 +45,6 @@ static void HMAC_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { } } -void HMAC_SHA_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { - SHA_init(&ctx->hash); - HMAC_init(ctx, key, len); -} - void HMAC_SHA256_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { SHA256_init(&ctx->hash); HMAC_init(ctx, key, len); diff --git a/omaha/base/security/hmac.h b/omaha/base/security/hmac.h index baf545ff1..1ec70f971 100644 --- a/omaha/base/security/hmac.h +++ b/omaha/base/security/hmac.h @@ -28,7 +28,6 @@ typedef struct LITE_HMAC_CTX { uint8_t opad[64]; } LITE_HMAC_CTX; -void HMAC_SHA_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len); void HMAC_SHA256_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len); const uint8_t* HMAC_final(LITE_HMAC_CTX* ctx); diff --git a/omaha/base/security/hmac_unittest.cc b/omaha/base/security/hmac_unittest.cc index 339926a7e..a7adff700 100644 --- a/omaha/base/security/hmac_unittest.cc +++ b/omaha/base/security/hmac_unittest.cc @@ -32,32 +32,26 @@ static const struct KAT { int md5_keylength; // md5 test keys are sometimes shorter. const char* data; const char* md5; - const char* sha1; const char* sha256; } KATS[] = { {"x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", 16, "Hi There", "9294727a3638bb1c13f48ef8158bfc9d", - "b617318655057264e28bc0b6fb378c8ef146be00", "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"}, {"Jefe", 4, "what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738", - "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"}, {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 16, "xdddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddddddddddddddddd", "56be34521d144c88dbb8c733f0e8b3f6", - "125d7342b9ac11cd91a39af48aa17b4f63f175d3", "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"}, {"x0102030405060708090a0b0c0d0e0f10111213141516171819", 25, "xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "697eaf0aca3a3aea3a75164746ffaa79", - "4c9007f4026250c6bc8414f9bf50c86c2d7235da", "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"}, {"x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", 16, "Test With Truncation", "56461ef2342edc00f9bab995690efd4c", - "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04", "a3b6167473100ee06e0c796c2955552bfa6f7c0a6a8aef8b93f860aab0cd20c5"}, {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -65,7 +59,7 @@ static const struct KAT { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 80, "Test Using Larger Than Block-Size Key - Hash Key First", "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd", - "aa4ae5e15272d00e95705637ce8a3b55ed402112", nullptr}, + nullptr}, {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -76,7 +70,7 @@ static const struct KAT { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", 8 * 16 + 3, "Test Using Larger Than Block-Size Key - Hash Key First", - nullptr, nullptr, + nullptr, "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"}, {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -86,7 +80,7 @@ static const struct KAT { "Test Using Larger Than Block-Size Key and Larger Than One Block-Size " "Data", "6f630fad67cda0ee1fb1f562db3aa53e", - "e8e99d0f45237d786d6bbaa7965c7808bbff1a91", nullptr}, + nullptr}, {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -100,7 +94,7 @@ static const struct KAT { "This is a test using a larger than block-size key and a larger t" "han block-size data. The key needs to be hashed before being use" "d by the HMAC algorithm.", - nullptr, nullptr, + nullptr, "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"}, {nullptr}}; @@ -114,16 +108,6 @@ TEST_F(HmacTest, RFC2202andRFC4131) { string data = katp->data[0] == 'x' ? omaha::a2b_hex(katp->data + 1) : katp->data; - if (katp->sha1) { - HMAC_SHA_init(&hmac, key.data(), key.size()); - HMAC_update(&hmac, data.data(), data.size()); - - EXPECT_EQ(omaha::b2a_hex( - reinterpret_cast(HMAC_final(&hmac)), - HMAC_size(&hmac)), - katp->sha1); - } - if (katp->sha256) { HMAC_SHA256_init(&hmac, key.data(), key.size()); HMAC_update(&hmac, data.data(), data.size()); diff --git a/omaha/base/security/sha.c b/omaha/base/security/sha.c deleted file mode 100644 index 3b0a79585..000000000 --- a/omaha/base/security/sha.c +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Optimized for minimal code size. - -#include "sha.h" - -#include -#include - -#define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -static void SHA1_Transform(SHA_CTX* ctx) { - uint32_t W[80]; - uint32_t A, B, C, D, E; - uint8_t* p = ctx->buf; - int t; - - for(t = 0; t < 16; ++t) { - uint32_t tmp = (uint32_t)(*p++) << 24; - tmp |= (uint32_t)(*p++) << 16; - tmp |= (uint32_t)(*p++) << 8; - tmp |= (uint32_t)(*p++); - W[t] = tmp; - } - - for(; t < 80; t++) { - W[t] = rol(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); - } - - A = ctx->state[0]; - B = ctx->state[1]; - C = ctx->state[2]; - D = ctx->state[3]; - E = ctx->state[4]; - - for(t = 0; t < 80; t++) { - uint32_t tmp = rol(5,A) + E + W[t]; - - if (t < 20) - tmp += (D^(B&(C^D))) + 0x5A827999; - else if ( t < 40) - tmp += (B^C^D) + 0x6ED9EBA1; - else if ( t < 60) - tmp += ((B&C)|(D&(B|C))) + 0x8F1BBCDC; - else - tmp += (B^C^D) + 0xCA62C1D6; - - E = D; - D = C; - C = rol(30,B); - B = A; - A = tmp; - } - - ctx->state[0] += A; - ctx->state[1] += B; - ctx->state[2] += C; - ctx->state[3] += D; - ctx->state[4] += E; -} - -static const HASH_VTAB SHA_VTAB = { - SHA_init, - SHA_update, - SHA_final, - SHA_hash, - SHA_DIGEST_SIZE -}; - -void SHA_init(SHA_CTX* ctx) { - ctx->f = &SHA_VTAB; - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xEFCDAB89; - ctx->state[2] = 0x98BADCFE; - ctx->state[3] = 0x10325476; - ctx->state[4] = 0xC3D2E1F0; - ctx->count = 0; -} - - -void SHA_update(SHA_CTX* ctx, const void* data, size_t len) { - unsigned int i = (unsigned int)(ctx->count & 63); - const uint8_t* p = (const uint8_t*)data; - - ctx->count += len; - - while (len--) { - ctx->buf[i++] = *p++; - if (i == 64) { - SHA1_Transform(ctx); - i = 0; - } - } -} - - -const uint8_t* SHA_final(SHA_CTX* ctx) { - uint8_t *p = ctx->buf; - uint64_t cnt = LITE_LShiftU64(ctx->count, 3); - int i; - - SHA_update(ctx, (uint8_t*)"\x80", 1); - while ((ctx->count & 63) != 56) { - SHA_update(ctx, (uint8_t*)"\0", 1); - } - for (i = 0; i < 8; ++i) { - uint8_t tmp = (uint8_t) LITE_RShiftU64(cnt, 56); - cnt = LITE_LShiftU64(cnt, 8); - SHA_update(ctx, &tmp, 1); - } - - for (i = 0; i < 5; i++) { - uint32_t tmp = ctx->state[i]; - *p++ = (uint8_t)(tmp >> 24); - *p++ = (uint8_t)(tmp >> 16); - *p++ = (uint8_t)(tmp >> 8); - *p++ = (uint8_t)(tmp >> 0); - } - - return ctx->buf; -} - -/* Convenience function */ -const uint8_t* SHA_hash(const void* data, size_t len, uint8_t* digest) { - SHA_CTX ctx; - SHA_init(&ctx); - SHA_update(&ctx, data, len); - memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE); - return digest; -} diff --git a/omaha/base/security/sha.h b/omaha/base/security/sha.h deleted file mode 100644 index 43867e2be..000000000 --- a/omaha/base/security/sha.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_BASE_SECURITY_SHA_H_ -#define OMAHA_BASE_SECURITY_SHA_H_ - -#include -#include "hash-internal.h" - -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -typedef HASH_CTX SHA_CTX; - -void SHA_init(SHA_CTX* ctx); -void SHA_update(SHA_CTX* ctx, const void* data, size_t len); -const uint8_t* SHA_final(SHA_CTX* ctx); - -// Convenience method. Returns digest address. -// NOTE: *digest needs to hold SHA_DIGEST_SIZE bytes. -const uint8_t* SHA_hash(const void* data, size_t len, uint8_t* digest); - -#define SHA_DIGEST_SIZE 20 - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // OMAHA_BASE_SECURITY_SHA_H_ diff --git a/omaha/base/signatures.cc b/omaha/base/signatures.cc index 7485f1606..549474cfd 100644 --- a/omaha/base/signatures.cc +++ b/omaha/base/signatures.cc @@ -19,12 +19,7 @@ // signatures of buffers. #include "omaha/base/signatures.h" -#include #include -#pragma warning(disable : 4245) -// C4245 : conversion from 'type1' to 'type2', signed/unsigned mismatch -#include -#pragma warning(default : 4245) #include #include @@ -32,18 +27,11 @@ #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/security/sha256.h" -#include "omaha/base/security/sha.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" namespace omaha { -constexpr ALG_ID kHashAlgorithm = CALG_SHA1; -constexpr DWORD kEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING; -constexpr DWORD kCertificateNameType = CERT_NAME_SIMPLE_DISPLAY_TYPE; -constexpr DWORD kKeyPairType = AT_SIGNATURE; - // Maximum file size allowed for performing authentication. constexpr size_t kMaxFileSizeForAuthentication = 512 * 1024 * 1024; // 512MB @@ -52,41 +40,6 @@ constexpr size_t kFileReadBufferSize = 128 * 1024; namespace CryptDetails { -void crypt_release_context(HCRYPTPROV provider) { - UTIL_LOG(L3, (L"Releasing HCRYPTPROV 0x%08lx", provider)); - BOOL b = ::CryptReleaseContext(provider, 0 /*flags*/); - ASSERT(b, (L"")); -} - -void crypt_close_store(HCERTSTORE store) { - UTIL_LOG(L3, (L"Releasing HCERTSTORE 0x%08lx", store)); - BOOL b = ::CertCloseStore(store, 0 /*flags*/); - ASSERT(b, (L"")); - ASSERT(::GetLastError() != CRYPT_E_PENDING_CLOSE, (L"")); -} - -void crypt_free_certificate(PCCERT_CONTEXT certificate) { - UTIL_LOG(L3, (L"Releasing PCCERT_CONTEXT 0x%08lx", certificate)); - BOOL b = ::CertFreeCertificateContext(certificate); - ASSERT(b, (L"")); -} - -void crypt_destroy_key(HCRYPTKEY key) { - UTIL_LOG(L3, (L"Releasing HCRYPTKEY 0x%08lx", key)); - BOOL b = ::CryptDestroyKey(key); - ASSERT(b, (L"")); -} - -void crypt_destroy_hash(HCRYPTHASH hash) { - UTIL_LOG(L3, (L"Releasing HCRYPTHASH 0x%08lx", hash)); - BOOL b = ::CryptDestroyHash(hash); - ASSERT(b, (L"")); -} - -typedef close_fun smart_destroy_hash; -typedef scoped_any scoped_crypt_hash; - class SHA256Hash : public HashInterface { public: SHA256Hash() { @@ -112,184 +65,12 @@ class SHA256Hash : public HashInterface { DISALLOW_COPY_AND_ASSIGN(SHA256Hash); }; -class SHA1Hash : public HashInterface { - public: - SHA1Hash() { - SHA_init(&ctx_); - } - virtual ~SHA1Hash() {} - - virtual void update(const void* data, unsigned int len) { - SHA_update(&ctx_, data, len); - } - - virtual const uint8_t* final() { - return SHA_final(&ctx_); - } - - virtual size_t hash_size() const { - return SHA_DIGEST_SIZE; - } - - private: - SHA_CTX ctx_; - - DISALLOW_COPY_AND_ASSIGN(SHA1Hash); -}; - -CryptDetails::HashInterface* CreateHasher(bool use_sha256) { - if (use_sha256) { - return new CryptDetails::SHA256Hash; - } else { - return new CryptDetails::SHA1Hash; - } +CryptDetails::HashInterface* CreateHasher() { + return new CryptDetails::SHA256Hash; } } // namespace CryptDetails -// Base64 encode/decode functions are part of ATL Server -HRESULT Base64::Encode(const std::vector& buffer_in, - std::vector* encoded, - bool break_into_lines) { - ASSERT(encoded, (L"")); - - if (buffer_in.empty()) { - encoded->clear(); - return S_OK; - } - - if (buffer_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - int encoded_len = - Base64EncodeGetRequiredLength( - static_cast(buffer_in.size()), - break_into_lines ? ATL_BASE64_FLAG_NONE : ATL_BASE64_FLAG_NOCRLF); - ASSERT(encoded_len > 0, (L"")); - - encoded->resize(encoded_len); - int str_out_len = encoded_len; - - BOOL result = Base64Encode( - &buffer_in.front(), - static_cast(buffer_in.size()), - reinterpret_cast(&encoded->front()), - &str_out_len, - break_into_lines ? ATL_BASE64_FLAG_NONE : ATL_BASE64_FLAG_NOCRLF); - if (!result) - return E_FAIL; - ASSERT(str_out_len <= encoded_len, (L"")); - if (str_out_len < encoded_len) - encoded->resize(str_out_len); - - return S_OK; -} - -HRESULT Base64::Encode(const std::vector& buffer_in, - CStringA* encoded, - bool break_into_lines) { - ASSERT(encoded, (L"")); - - if (buffer_in.empty()) { - return S_OK; - } - - std::vector buffer_out; - RET_IF_FAILED(Encode(buffer_in, &buffer_out, break_into_lines)); - - if (buffer_out.size() > INT_MAX) { - return E_FAIL; - } - encoded->Append(reinterpret_cast(&buffer_out.front()), - static_cast(buffer_out.size())); - - return S_OK; -} - -HRESULT Base64::Encode(const std::vector& buffer_in, - CString* encoded, - bool break_into_lines) { - ASSERT(encoded, (L"")); - - CStringA string_out; - RET_IF_FAILED(Encode(buffer_in, &string_out, break_into_lines)); - *encoded = string_out; - - return S_OK; -} - -HRESULT Base64::Decode(const std::vector& encoded, - std::vector* buffer_out) { - ASSERT(buffer_out, (L"")); - - const size_t encoded_len = encoded.size(); - if (encoded_len > INT_MAX) { - return E_INVALIDARG; - } - - const int required_len = Base64DecodeGetRequiredLength( - static_cast(encoded_len)); - - buffer_out->resize(required_len); - - if (required_len == 0) { - return S_OK; - } - - int bytes_written = required_len; - BOOL result = Base64Decode(reinterpret_cast(&encoded.front()), - static_cast(encoded_len), - &buffer_out->front(), - &bytes_written); - if (!result) - return E_FAIL; - ASSERT(bytes_written <= required_len, (L"")); - if (bytes_written < required_len) { - buffer_out->resize(bytes_written); - } - - return S_OK; -} - -HRESULT Base64::Decode(const CStringA& encoded, std::vector* buffer_out) { - ASSERT(buffer_out, (L"")); - - size_t encoded_len = encoded.GetLength(); - std::vector buffer_in(encoded_len); - if (encoded_len != 0) { - memcpy(&buffer_in.front(), encoded.GetString(), encoded_len); - } - - return Decode(buffer_in, buffer_out); -} - -// Base64 in a CString -> binary -HRESULT Base64::Decode(const CString& encoded, std::vector* buffer_out) { - ASSERT(buffer_out, (L"")); - - CW2A encoded_a(encoded.GetString()); - - size_t encoded_len = ::strlen(encoded_a); - std::vector buffer_in(encoded_len); - if (encoded_len != 0) { - memcpy(&buffer_in.front(), encoded_a, encoded_len); - } - - return Decode(buffer_in, buffer_out); -} - -const size_t CryptoHash::kSha1HashSize = 20; -const size_t CryptoHash::kSha256HashSize = 32; - -CryptoHash::CryptoHash(HashAlgorithm hash_algorithm) - : use_sha256_(hash_algorithm == kSha256) { - ASSERT1(hash_algorithm == kSha1 || hash_algorithm == kSha256); -} - -CryptoHash::~CryptoHash() { -} - HRESULT CryptoHash::Compute(const TCHAR* filepath, uint64 max_len, std::vector* hash_out) { @@ -357,7 +138,7 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& filepaths, static_assert(kFileReadBufferSize <= INT_MAX); std::unique_ptr hasher( - CryptDetails::CreateHasher(use_sha256_)); + CryptDetails::CreateHasher()); for (size_t i = 0; i < filepaths.size(); ++i) { scoped_hfile file_handle(::CreateFile(filepaths[i], @@ -401,7 +182,7 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& filepaths, } DWORD digest_size = static_cast(hash_size()); - std::vector digest_data(digest_size); + std::vector digest_data(digest_size); memcpy(&digest_data.front(), hasher->final(), digest_size); @@ -411,13 +192,9 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& filepaths, return S_OK; } - std::vector calculated_hash(digest_size); - memcpy(&calculated_hash.front(), &digest_data.front(), digest_size); CStringA base64_encoded_hash; - Base64::Encode(calculated_hash, &base64_encoded_hash, false); - CString hash = AnsiToWideString(base64_encoded_hash, - base64_encoded_hash.GetLength()); - REPORT_LOG(L1, (_T("[actual hash=%s]"), hash)); + Base64Escape(digest_data.data(), digest_size, &base64_encoded_hash, true); + REPORT_LOG(L1, (_T("[actual hash=%S]"), base64_encoded_hash)); return SIGS_E_INVALID_SIGNATURE; } else { hash_out->resize(digest_size); @@ -437,7 +214,7 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& buffer_in, } std::unique_ptr hasher( - CryptDetails::CreateHasher(use_sha256_)); + CryptDetails::CreateHasher()); const size_t datalen = buffer_in.size(); const uint8* data = datalen ? &buffer_in.front() : NULL; @@ -459,683 +236,6 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& buffer_in, } } -// To sign data you need a CSP with the proper private key installed. -// To get a signing certificate you start with a PFX file. This file -// encodes a "certificate store" which can hold more than one -// certificate. (In general it can hold a certificate chain, but we -// only use the signing certificate.) There are special APIs to verify -// the format of a PFX file and read it into a new certificate store. A -// password must be specified to read the PFX file as it is encrypted. -// The password was set when the PFX file was exported or otherwise -// created. Then you search for the proper certificate in the store -// (using the subject_name which tells who the certificate was issued -// to). Finally, to get a CSP with the certificate's private key -// available there is a special API, CryptAcquireCertificatePrivateKey, -// that takes a CSP and a certificate and makes the private key of the -// certificate the private key of the CSP. - -CryptoSigningCertificate::CryptoSigningCertificate() : key_spec_(0) { -} - -CryptoSigningCertificate::~CryptoSigningCertificate() { -} - -HRESULT CryptoSigningCertificate::ImportCertificate( - const TCHAR * filepath, - const TCHAR * password, - const TCHAR * subject_name) { - ASSERT(filepath, (L"")); - ASSERT(password, (L"")); - - std::vector buffer; - HRESULT hr = ReadEntireFile(filepath, kMaxCertificateSize, &buffer); - if (FAILED(hr)) { - UTIL_LOG(LE, (L"[CryptoSigningCertificate::ImportCertificate]" - L"['%s' not read, hr 0x%08lx]", filepath, hr)); - return hr; - } - return ImportCertificate(buffer, password, subject_name); -} - -HRESULT CryptoSigningCertificate::ImportCertificate( - const std::vector& certificate_in, - const TCHAR * password, - const TCHAR * subject_name) { - ASSERT(password, (L"")); - ASSERT1(!certificate_in.empty()); - - UTIL_LOG(L2, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[%d bytes, subject_name '%s']", - certificate_in.size(), subject_name ? subject_name : L"")); - - if (certificate_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - // CryptoAPI treats the certificate as a "blob" - CRYPT_DATA_BLOB blob; - blob.cbData = static_cast(certificate_in.size()); - blob.pbData = const_cast(&certificate_in.front()); - - // Ensure that it is PFX formatted - BOOL b = ::PFXIsPFXBlob(&blob); - if (!b) { - ASSERT(0, (L"Invalid PFX certificate, err 0x%08lx", ::GetLastError())); - return SIGS_E_INVALID_PFX_CERTIFICATE; - } - - // Make sure the password checks out - b = ::PFXVerifyPassword(&blob, password, 0 /* flags */); - if (!b) { - UTIL_LOG(LE, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[invalid password, err 0x%08lx]", ::GetLastError())); - return SIGS_E_INVALID_PASSWORD; - } - - // Do the import from the certificate to a new certificate store - // TODO(omaha): Check that this is in fact a new certificate store, not an - // existing one. If it is an existing one we'll need to delete the - // certificate later. - // The last parameter to ::PFXImportCertStore() is 0, indicating that we want - // the CSP to be "silent"; i.e., not prompt. - reset(store_, ::PFXImportCertStore(&blob, password, 0)); - if (!store_) { - DWORD err = ::GetLastError(); - ASSERT(0, (L"Failed to import PFX certificate into a certificate store, " - L"err 0x%08lx", err)); - return HRESULT_FROM_WIN32(err); - } - UTIL_LOG(L3, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[new store 0x%08lx]", get(store_))); - - // Now that we have a store, look for the correct certificate. (There may - // have been more than one in the PFX file, e.g., a certificate chain.) - PCCERT_CONTEXT certificate_context = NULL; - while ((certificate_context = - ::CertEnumCertificatesInStore(get(store_), - certificate_context)) != NULL) { - // Have a certificate, does it look like the right one? Check the name - DWORD name_len = ::CertGetNameString(certificate_context, - kCertificateNameType, - 0 /*flags*/, - NULL, - NULL, - 0); - if (name_len <= 1) { - // Name attribute not found - should never happen - ASSERT(0, (L"CryptoSigningCertificate::ImportCertificate failed to get " - L"certificate name length, err 0x%08lx", ::GetLastError())); - continue; - } - // name_len includes the terminating null - - std::vector name; - name.resize(name_len); - ASSERT1(!name.empty()); - DWORD name_len2 = ::CertGetNameString(certificate_context, - kCertificateNameType, - 0, - NULL, - &name.front(), - name_len); - ASSERT(name_len2 == name_len, (L"")); - - UTIL_LOG(L3, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[found '%s' in store]", &name.front())); - - // Check the name if the user so desires. (If subject_name == NULL then - // the first certificate found is used.) - if (subject_name && (0 != String_StrNCmp(&name.front(), - subject_name, - ::lstrlen(subject_name), - false))) { - // name mismatch - UTIL_LOG(L3, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[not the right certificate, we're looking for '%s']", - subject_name)); - continue; - } - - // This is the right certificate - subject_name_ = &name.front(); - reset(certificate_, certificate_context); - UTIL_LOG(L3, (L"[CryptoSigningCertificate::ImportCertificate]" - L"[new certificate 0x%08lx]", get(certificate_))); - break; - } - - return S_OK; -} - -HRESULT CryptoSigningCertificate::GetCSPContext(HCRYPTPROV* csp_context) { - ASSERT(csp_context, (L"")); - ASSERT(get(certificate_), (L"")); - - // CSP may have already been used - reset it - reset(csp_); - - // Create a CSP context using the private key of the certificate we imported - // earlier. - HCRYPTPROV csp = NULL; - BOOL must_free_csp = FALSE; - BOOL b = ::CryptAcquireCertificatePrivateKey(get(certificate_), - 0 /*flags*/, - 0 /*reserved*/, - &csp, - &key_spec_, - &must_free_csp); - if (!b) { - DWORD err = ::GetLastError(); - ASSERT(0, (L"CryptoSigningCertificate::GetCSPContext " - L"CryptAcquireCertificatePrivateKey failed, err 0x%08lx", err)); - return HRESULT_FROM_WIN32(err); - } - - // (Funky API returns a boolean which tells you whether it is your - // responsibility to delete the CSP context or not.) - if (must_free_csp) { - reset(csp_, csp); - } - if (get(csp_)) { - UTIL_LOG(L3, (L"[CryptoSigningCertificate::GetCSPContext new CSP 0x%08lx]", - get(csp_))); - } - - ASSERT(key_spec_ == AT_SIGNATURE || key_spec_ == AT_KEYEXCHANGE, (L"")); - if (key_spec_ != kKeyPairType) { - UTIL_LOG(LE, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[requires a AT_SIGNATURE type key]")); - return SIGS_E_INVALID_KEY_TYPE; - } - -#ifdef _DEBUG - // Which CSP did we get? - char csp_name[256] = {0}; - DWORD csp_name_len = arraysize(csp_name); - b = ::CryptGetProvParam(csp, - PP_NAME, - reinterpret_cast(&csp_name[0]), - &csp_name_len, - 0 /*flags*/); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[error getting CSP name, err 0x%08lx]", err)); - } - DWORD csp_prov_type; - DWORD csp_prov_type_len = sizeof(csp_prov_type); - b = ::CryptGetProvParam(csp, - PP_PROVTYPE, - reinterpret_cast(&csp_prov_type), - &csp_prov_type_len, - 0 /*flags*/); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[error getting CSP provtype, err 0x%08lx]", err)); - } - char csp_container[256] = {0}; - DWORD csp_container_len = arraysize(csp_container); - b = ::CryptGetProvParam(csp, - PP_CONTAINER, - reinterpret_cast(&csp_container[0]), - &csp_container_len, - 0 /*flags*/); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[error getting CSP current container name, err 0x%08lx]", - err)); - } - UTIL_LOG(L2, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[have CSP '%S' (provtype %d) key container '%S']", - csp_name, csp_prov_type, csp_container)); - // End of which CSP did we get -#endif - - *csp_context = csp; - - UTIL_LOG(L2, (L"[CryptoSigningCertificate::GetCSPContext]" - L"[getting CSP with private key from certificate]" - L"[HCRYPTPROV 0x%08lx]", csp)); - - return S_OK; -} - -// To sign some data using CryptoAPI you first hash it into a hash -// object, then sign it using the CSP. The CSP needs to have the -// private key, of type AT_SIGNATURE, in it already, as it isn't a -// parameter of the CryptSignHash API. The CryptoSigningCertificate -// can provide such a CSP. - -CryptoComputeSignature::CryptoComputeSignature( - CryptoSigningCertificate* certificate) - : certificate_(certificate) { -} - -CryptoComputeSignature::~CryptoComputeSignature() { -} - -HRESULT CryptoComputeSignature::Sign(TCHAR const * const filepath, - uint32 max_len, - std::vector* signature_out) { - ASSERT(filepath, (L"")); - std::vector buffer; - HRESULT hr = ReadEntireFile(filepath, max_len, &buffer); - if (FAILED(hr)) { - UTIL_LOG(LE, (L"[CryptoComputeSignature::Sign]" - L"['%s not read, hr 0x%08lx]", filepath, hr)); - return hr; - } - return Sign(buffer, signature_out); -} - -HRESULT CryptoComputeSignature::Sign(const std::vector& buffer_in, - std::vector* signature_out) { - ASSERT(signature_out, (L"")); - ASSERT1(!buffer_in.empty()); - - UTIL_LOG(L2, (L"[CryptoComputeSignature::Sign]" - L"[buffer of %d bytes]", buffer_in.size())); - - if (buffer_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - // Get the proper CSP with the private key (certificate retains ownership) - HCRYPTPROV csp = NULL; - HRESULT hr = certificate_->GetCSPContext(&csp); - ASSERT(SUCCEEDED(hr) && csp, (L"")); - - // Hash the data - CryptDetails::scoped_crypt_hash hash; - BOOL b = ::CryptCreateHash(csp, kHashAlgorithm, 0, 0, address(hash)); - if (!b) { - // hash is now invalid, but might not be NULL, so stomp on it - DWORD err = ::GetLastError(); - ASSERT(!hash, (L"")); - UTIL_LOG(LE, (L"[CryptoComputeSignature::Sign]" - L"[could not create hash, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - UTIL_LOG(L3, (L"CryptoComputeSignature::Sign new hash 0x%08lx", get(hash))); - - b = ::CryptHashData(get(hash), - &buffer_in.front(), - static_cast(buffer_in.size()), - 0); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoComputeSignature::Sign]" - L"[could not hash data, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - - // Sign the hash (first get length, then allocate buffer and do real signing) - DWORD signature_len = 0; - b = ::CryptSignHash(get(hash), - kKeyPairType, - NULL, - 0 /*flags*/, - NULL, - &signature_len); - if (!b && ::GetLastError() != ERROR_MORE_DATA) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoComputeSignature::Sign]" - L"[could not compute size of signature, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - signature_out->resize(signature_len); - b = ::CryptSignHash(get(hash), - kKeyPairType, - NULL, - 0, - &signature_out->front(), - &signature_len); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoComputeSignature::Sign]" - L"[could not compute signature, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - ASSERT(signature_len == signature_out->size(), (L"")); - - UTIL_LOG(L3, (L"[CryptoComputeSignature::Sign]" - L"[have %d byte signature]", signature_out->size())); - - return S_OK; -} - -// To verify signed data you need a CSP, and you also need the public -// key extracted from a certificate. The CSP can be any RSA CSP on the -// machine, the default one is fine. To get the public key you start -// by importing a certificate in standard "DER encoded" format. That -// returns a giant data structure, one field of which is the public key -// in a format that CryptoAPI understands. You import this public key -// into the CSP with the CryptImportPublicKey() API, and then create a -// key object from it suitable for use with the verification API. - -CryptoSignatureVerificationCertificate::CryptoSignatureVerificationCertificate() { // NOLINT -} - -CryptoSignatureVerificationCertificate::~CryptoSignatureVerificationCertificate() { // NOLINT -} - -HRESULT CryptoSignatureVerificationCertificate::ImportCertificate( - const TCHAR * filepath, - const TCHAR * subject_name) { - ASSERT(filepath, (L"")); - std::vector buffer; - HRESULT hr = ReadEntireFile(filepath, kMaxCertificateSize, &buffer); - if (FAILED(hr)) { - UTIL_LOG(LE, (L"[CryptoSignatureVerificationCertificate::ImportCertificate]" - L"['%s' not read, hr 0x%08lx]", filepath, hr)); - return hr; - } - return ImportCertificate(buffer, subject_name); -} - -HRESULT CryptoSignatureVerificationCertificate::ImportCertificate( - const std::vector& certificate_in, - const TCHAR * subject_name) { - // Import the certificate - ASSERT1(!certificate_in.empty()); - - if (certificate_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - reset(certificate_, - ::CertCreateCertificateContext( - kEncodingType, - &certificate_in.front(), - static_cast(certificate_in.size()))); - if (!certificate_) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoSignatureVerificationCertificate::ImportCertificate]" - L"[could not import certificate, err 0x%08lx]", err)); - return SIGS_E_INVALID_DER_CERTIFICATE; - } - UTIL_LOG(L3, (L"[CryptoSignatureVerificationCertificate::ImportCertificate]" - L"[new certificate 0x%08lx]", get(certificate_))); - - // Get certificate's subject name - DWORD name_len = ::CertGetNameString(get(certificate_), - kCertificateNameType, - 0 /*flags*/, - NULL, - NULL, - 0); - if (name_len <= 1) { - // Name attribute not found - should never happen - ASSERT(0, (L"CryptoSignatureVerificationCertificate failed to get " - L"certificate name length, err 0x%08lx", ::GetLastError())); - return E_FAIL; - } - // name_len includes the terminating NULL - - std::vector name; - name.resize(name_len); - ASSERT1(!name.empty()); - DWORD name_len2 = ::CertGetNameString(get(certificate_), - kCertificateNameType, - 0, - NULL, - &name.front(), - name_len); - ASSERT(name_len2 == name_len, (L"")); - - UTIL_LOG(L3, (L"[CryptoSignatureVerificationCertificate::ImportCertificate]" - L"['%s' is subject of certificate]", &name.front())); - - subject_name_ = &name.front(); - - // Check the name if the user so desires. - if (subject_name && (0 != String_StrNCmp(&name.front(), - subject_name, - ::lstrlen(subject_name), false))) { - // name mismatch - UTIL_LOG(L3, (L"[CryptoSignatureVerificationCertificate::ImportCertificate]" - L"[not the right certificate, we're looking for '%s']", - subject_name)); - return E_FAIL; - } - - return S_OK; -} - -HRESULT CryptoSignatureVerificationCertificate::GetCSPContextAndKey( - HCRYPTPROV* csp_context, - HCRYPTKEY* public_key) { - ASSERT(csp_context, (L"")); - ASSERT(public_key, (L"")); - ASSERT(get(certificate_), (L"")); - - // Get the public key out of the certificate - PCERT_INFO cert_info = get(certificate_)->pCertInfo; - ASSERT(cert_info, (L"")); - PCERT_PUBLIC_KEY_INFO public_key_info = &cert_info->SubjectPublicKeyInfo; - ASSERT(public_key_info, (L"")); - - // Reset the CSP and key in case it has been used already - reset(key_); - reset(csp_); - - // Get the default CSP. With CRYPT_VERIFYCONTEXT don't need to worry - // about creating/destroying a key container. - // TODO(omaha): Why wasn't PROV_RSA_SIG available? Maybe looking for the - // default isn't a good idea? - const DWORD provider_type = PROV_RSA_FULL; - BOOL b = ::CryptAcquireContext(address(csp_), - NULL, - NULL, - provider_type, - CRYPT_VERIFYCONTEXT|CRYPT_SILENT); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[GetCSPContextAndKey]" - L"[failed to acquire CSP, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - UTIL_LOG(L3, (L"[CryptoSignatureVerificationCertificate::GetCSPContextAndKey]" - L"[new CSP 0x%08lx]", get(csp_))); - - // Convert the public key in encoded form into a CryptoAPI HCRYPTKEY - b = ::CryptImportPublicKeyInfo(get(csp_), - kEncodingType, - public_key_info, - address(key_)); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[GetCSPContextAndKey]" - L"[failed to import public key, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - UTIL_LOG(L3, (L"[CryptoSignatureVerificationCertificate::GetCSPContextAndKey]" - L"[new key 0x%08lx]", get(key_))); - - *csp_context = get(csp_); - *public_key = get(key_); - - return S_OK; -} - -// To verify the signature of some data using CryptoAPI you first hash -// it into a hash object, then verify it using the CSP and a public key. -// In this case the CryptVerifySignature takes the key (of type -// AT_SIGNATURE) as a separate parameter. The -// CryptoSignatureVerificationCertificate can provide the proper CSP and -// the public key from the certificate. - -CryptoVerifySignature::CryptoVerifySignature( - CryptoSignatureVerificationCertificate& certificate) // NOLINT - : certificate_(&certificate) { -} - -CryptoVerifySignature::~CryptoVerifySignature() { -} - -HRESULT CryptoVerifySignature::Validate(const TCHAR* filepath, - uint32 max_len, - const std::vector& signature_in) { - ASSERT(filepath, (L"")); - std::vector buffer; - HRESULT hr = ReadEntireFile(filepath, max_len, &buffer); - if (FAILED(hr)) { - UTIL_LOG(LE, (L"[CryptoVerifySignature::Validate]" - L"['%s' not read, hr 0x%08lx]", filepath, hr)); - return hr; - } - return Validate(buffer, signature_in); -} - -HRESULT CryptoVerifySignature::Validate(const std::vector& buffer_in, - const std::vector& signature_in) { - ASSERT(certificate_, (L"")); - ASSERT1(!buffer_in.empty()); - ASSERT1(!signature_in.empty()); - - UTIL_LOG(L2, (L"[CryptoVerifySignature::Validate]" - L"[buffer of %d bytes, signature of %d bytes]", - buffer_in.size(), signature_in.size())); - - if (buffer_in.size() > INT_MAX || signature_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - // Get the CSP context and the public key from the certificate - HCRYPTPROV csp = NULL; - HCRYPTKEY key = NULL; - HRESULT hr = certificate_->GetCSPContextAndKey(&csp, &key); - ASSERT(SUCCEEDED(hr) && csp && key, (L"")); - - // Hash the data - CryptDetails::scoped_crypt_hash hash; - BOOL b = ::CryptCreateHash(csp, kHashAlgorithm, 0, 0, address(hash)); - if (!b) { - // hash is now invalid, but might not be NULL, so stomp on it - DWORD err = ::GetLastError(); - ASSERT(!hash, (L"")); - UTIL_LOG(LE, (L"[CrypoVerifySignature::Validate]" - L"[could not create hash], err 0x%08lx", err)); - return HRESULT_FROM_WIN32(err); - } - - b = ::CryptHashData(get(hash), - &buffer_in.front(), - static_cast(buffer_in.size()), - 0 /*flags*/); - if (!b) { - DWORD err = ::GetLastError(); - UTIL_LOG(LE, (L"[CryptoVerifySignature::Validate]" - L"[could not hash data, err 0x%08lx]", err)); - return HRESULT_FROM_WIN32(err); - } - - // Verify the hash - b = ::CryptVerifySignature(get(hash), - &signature_in.front(), - static_cast(signature_in.size()), - key, - NULL, - 0 /*flags*/); - if (!b) { - DWORD err = ::GetLastError(); -#ifdef LOGGING - CString encoded_signature; - Base64::Encode(signature_in, &encoded_signature, false); - - UTIL_LOG(LE, (_T("CryptoVerifySignature::Validate could not ") - _T("verify signature, err 0x%08lx with sig \"%s\""), - err, encoded_signature)); -#endif - if (err == NTE_BAD_SIGNATURE) - return SIGS_E_INVALID_SIGNATURE; - else - return HRESULT_FROM_WIN32(err); - } - - return S_OK; -} - -HRESULT SignData(const TCHAR* certificate_path, - const TCHAR* certificate_password, - const TCHAR* certificate_subject_name, - const std::vector& data, - CString* signature_base64) { - ASSERT(certificate_path, (L"")); - ASSERT(certificate_password, (L"")); - // certificate_subject_name can be NULL - ASSERT(signature_base64, (L"")); - - CryptoSigningCertificate certificate; - RET_IF_FAILED(certificate.ImportCertificate(certificate_path, - certificate_password, - certificate_subject_name)); - - CryptoComputeSignature signer(&certificate); - std::vector signature; - RET_IF_FAILED(signer.Sign(data, &signature)); - RET_IF_FAILED(Base64::Encode(signature, signature_base64, false)); - - return S_OK; -} - -HRESULT VerifyData(const TCHAR* certificate_path, - const TCHAR* certificate_subject_name, - const std::vector& data, - const TCHAR* signature_base64) { - ASSERT(certificate_path, (L"")); - // certificate_subject_name can be NULL - ASSERT(signature_base64, (L"")); - - std::vector signature; - RET_IF_FAILED(Base64::Decode(CString(signature_base64), &signature)); - - CryptoSignatureVerificationCertificate certificate; - RET_IF_FAILED(certificate.ImportCertificate(certificate_path, - certificate_subject_name)); - - CryptoVerifySignature verifier(certificate); - RET_IF_FAILED(verifier.Validate(data, signature)); - - return S_OK; -} - -HRESULT VerifyData(const std::vector& certificate_buffer, - const TCHAR* certificate_subject_name, - const std::vector& data, - const TCHAR* signature_base64) { - // certificate_subject_name can be NULL - ASSERT(signature_base64, (L"")); - - std::vector signature; - RET_IF_FAILED(Base64::Decode(CString(signature_base64), &signature)); - - CryptoSignatureVerificationCertificate certificate; - RET_IF_FAILED(certificate.ImportCertificate(certificate_buffer, - certificate_subject_name)); - - CryptoVerifySignature verifier(certificate); - RET_IF_FAILED(verifier.Validate(data, signature)); - - return S_OK; -} - -HRESULT VerifyFileHash(const std::vector& files, - const CString& expected_hash) { - ASSERT1(!files.empty()); - - std::vector hash_vector; - RET_IF_FAILED(Base64::Decode(expected_hash, &hash_vector)); - - CryptoHash crypto(CryptoHash::kSha1); - if (!crypto.IsValidSize(hash_vector.size())) { - return E_INVALIDARG; - } - return crypto.Validate(files, kMaxFileSizeForAuthentication, hash_vector); -} - HRESULT VerifyFileHashSha256(const std::vector& files, const CString& expected_hash) { ASSERT1(!files.empty()); @@ -1145,7 +245,7 @@ HRESULT VerifyFileHashSha256(const std::vector& files, return E_INVALIDARG; } - CryptoHash crypto(CryptoHash::kSha256); + CryptoHash crypto; if (!crypto.IsValidSize(hash_vector.size())) { return E_INVALIDARG; } diff --git a/omaha/base/signatures.h b/omaha/base/signatures.h index 8a5b3f42a..f1c7dc3c1 100644 --- a/omaha/base/signatures.h +++ b/omaha/base/signatures.h @@ -27,34 +27,15 @@ #include #include #include "base/basictypes.h" +#include "omaha/base/security/sha256.h" #include "omaha/third_party/smartany/scoped_any.h" namespace omaha { class CryptoHash; -class CryptoComputeSignature; -class CryptoVerifySignature; -class CryptoSigningCertificate; -class CryptoSignatureVerificationCertificate; -// Useful scoped pointers for working with CryptoAPI objects namespace CryptDetails { -void crypt_close_store(HCERTSTORE); -void crypt_release_context(HCRYPTPROV); -void crypt_free_certificate(PCCERT_CONTEXT); -void crypt_destroy_key(HCRYPTKEY); - -typedef close_fun smart_close_store; // NOLINT -typedef close_fun smart_release_context; // NOLINT -typedef close_fun smart_free_certificate; // NOLINT -typedef close_fun smart_destroy_key; // NOLINT - -typedef scoped_any scoped_crypt_store; // NOLINT -typedef scoped_any scoped_crypt_context; // NOLINT -typedef scoped_any scoped_crypt_cert; // NOLINT -typedef scoped_any scoped_crypt_key; // NOLINT - class HashInterface { public: virtual ~HashInterface() {} @@ -64,52 +45,15 @@ class HashInterface { virtual size_t hash_size() const = 0; }; -HashInterface* CreateHasher(bool use_sha256); +HashInterface* CreateHasher(); } // namespace CryptDetails - -// A namespace for encoding binary into base64 (portable ASCII) representation -// and for decoding it again. -namespace Base64 { - -// Binary -> base64 in a buffer -HRESULT Encode(const std::vector& buffer_in, - std::vector* encoded, - bool break_into_lines = true); - -// Binary -> base64 in a string -HRESULT Encode(const std::vector& buffer_in, - CStringA* encoded, - bool break_into_lines = true); - -// Binary -> base64 in a wide string -HRESULT Encode(const std::vector& buffer_in, - CString* encoded, - bool break_into_lines = true); - -// Base64 in a buffer -> binary -HRESULT Decode(const std::vector& encoded, - std::vector* buffer_out); - -// Base64 in a CStringA -> binary -HRESULT Decode(const CStringA& encoded, std::vector* buffer_out); - -// Base64 in a CString -> binary -HRESULT Decode(const CString& encoded, std::vector* buffer_out); - -} // namespace Base64 - -// Compute and validate SHA-1 or SHA256 hashes of data. +// Compute and validate SHA256 hashes of data. class CryptoHash { public: - enum HashAlgorithm { - kSha1 = 0, - kSha256 - }; - - explicit CryptoHash(HashAlgorithm hash_algorithm); - ~CryptoHash(); + CryptoHash() = default; + ~CryptoHash() = default; // Hash a file HRESULT Compute(const TCHAR * filepath, @@ -144,7 +88,7 @@ class CryptoHash { } size_t hash_size() const { - return use_sha256_ ? kSha256HashSize : kSha1HashSize; + return SHA256_DIGEST_SIZE; } private: @@ -159,167 +103,9 @@ class CryptoHash { const std::vector* hash_in, std::vector* hash_out); - static const size_t kSha1HashSize; - static const size_t kSha256HashSize; - - const bool use_sha256_; - DISALLOW_COPY_AND_ASSIGN(CryptoHash); }; - -// Import and use a certificate for signing data (has a private key) -class CryptoSigningCertificate { - public: - CryptoSigningCertificate(); - ~CryptoSigningCertificate(); - - // Import certificate - with both public key and private key. - // Must be in PFX format. Password must unlock the PFX file. - // subject_name is the certificate's subject name (who it was - // issued to) - if not NULL then it is checked for an exact - // match against the certificate. - - // User can get the certificate in PFX format by following the procedure at - // http://support.globalsign.net/en/objectsign/transform.cfm - - HRESULT ImportCertificate(const TCHAR * filepath, - const TCHAR * password, - const TCHAR * subject_name); - - HRESULT ImportCertificate(const std::vector& certificate_in, - const TCHAR * password, - const TCHAR * subject_name); - - CString subject_name() { return subject_name_; } - - private: - static const int kMaxCertificateSize = 100000; - - CryptDetails::scoped_crypt_store store_; - CryptDetails::scoped_crypt_cert certificate_; - CryptDetails::scoped_crypt_context csp_; - CString subject_name_; - DWORD key_spec_; - - friend class CryptoComputeSignature; - // Get the CSP with the private key - // (CryptoSigningCertificate retains ownership of csp_context.) - HRESULT GetCSPContext(HCRYPTPROV* csp_context); - - DISALLOW_COPY_AND_ASSIGN(CryptoSigningCertificate); -}; - - -// Compute digital signatures -class CryptoComputeSignature { - public: - explicit CryptoComputeSignature(CryptoSigningCertificate* certificate); - ~CryptoComputeSignature(); - - // Sign a file, returning a separate signature - HRESULT Sign(const TCHAR * filepath, - uint32 max_len, - std::vector* signature_out); - - // Sign a chunk of memory, returning a separate signature - HRESULT Sign(const std::vector& buffer_in, - std::vector* signature_out); - - private: - // Does not take ownership of the certificate - CryptoSigningCertificate* const certificate_; - - DISALLOW_COPY_AND_ASSIGN(CryptoComputeSignature); -}; - - -// Import and use a certificate for verifying signatures (has public key only) -class CryptoSignatureVerificationCertificate { - public: - CryptoSignatureVerificationCertificate(); - ~CryptoSignatureVerificationCertificate(); - - // Import certificate - with only public key. Must be in DER (.cer) format. - // subject_name is the certificate's subject name (who it was - // issued to) - if not NULL then it is checked for an exact - // match against the certificate. - - // User can get certificate in DER format (.cer) by exporting from - // certmgr.exe, using openssl, etc.) - - HRESULT ImportCertificate(const TCHAR * filepath, - const TCHAR * subject_name); - HRESULT ImportCertificate(const std::vector& certificate_in, - const TCHAR * subject_name); - - CString subject_name() { return subject_name_; } - - private: - static const int kMaxCertificateSize = 100000; - - CryptDetails::scoped_crypt_cert certificate_; - CryptDetails::scoped_crypt_context csp_; - CryptDetails::scoped_crypt_key key_; - CString subject_name_; - - friend class CryptoVerifySignature; - // Get the CSP and the public key - // (CryptoSignatureVerificationCertificate retains ownership of csp_context - // and public_key.) - HRESULT GetCSPContextAndKey(HCRYPTPROV* csp_context, HCRYPTKEY* public_key); - - DISALLOW_COPY_AND_ASSIGN(CryptoSignatureVerificationCertificate); -}; - - -// Verify digital signatures -class CryptoVerifySignature { - public: - explicit CryptoVerifySignature( - CryptoSignatureVerificationCertificate& certificate); // NOLINT - ~CryptoVerifySignature(); - - // Validate signature of a file, signature given separately - HRESULT Validate(const TCHAR * filepath, - uint32 max_len, - const std::vector& signature_in); - - // Validate signature of a buffer of data, signature given separately - HRESULT Validate(const std::vector& buffer_in, - const std::vector& signature_in); - - private: - // Does not take ownership of the certificate - CryptoSignatureVerificationCertificate* const certificate_; - - DISALLOW_COPY_AND_ASSIGN(CryptoVerifySignature); -}; - -// All-in-one routine to sign a chunk of data and return the signature -// (encoded in base64) -HRESULT SignData(const TCHAR* certificate_path, - const TCHAR* certificate_password, - const TCHAR* certificate_subject_name, - const std::vector& data, - CString* signature_base64); - -// All-in-one routine to verify the signature of a chunk of data -HRESULT VerifyData(const TCHAR* certificate_path, - const TCHAR* certificate_subject_name, - const std::vector& data, - const TCHAR* signature_base64); - -HRESULT VerifyData(const std::vector& certificate_buffer, - const TCHAR* certificate_subject_name, - const std::vector& data, - const TCHAR* signature_base64); - -// Verifies that the files' SHA1 hash is the expected_hash. The hash is -// base64 encoded. -HRESULT VerifyFileHash(const std::vector& files, - const CString& expected_hash); - // Verifies that the files' SHA256 hash is the expected_hash. The hash is // hex-digit encoded. HRESULT VerifyFileHashSha256(const std::vector& files, diff --git a/omaha/base/signatures_unittest.cc b/omaha/base/signatures_unittest.cc index 6031046ea..562ab5402 100644 --- a/omaha/base/signatures_unittest.cc +++ b/omaha/base/signatures_unittest.cc @@ -35,30 +35,6 @@ namespace omaha { namespace { -struct { - const char* binary; - const char* base64; -} test_data[] = { - "", "", - "what", "d2hhdA==", - "what will print out", "d2hhdCB3aWxsIHByaW50IG91dA==", - "foobar", "Zm9vYmFy", - "a man, a plan, a canal: panama!", "YSBtYW4sIGEgcGxhbiwgYSBjYW5hbDogcGFuYW1hIQ==", // NOLINT -}; - -// This test data from http://en.wikipedia.org/wiki/SHA-1: -const struct { - const char* binary; - byte hash[20]; -} test_hash[] = { - "The quick brown fox jumps over the lazy dog", - 0x2f, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc, 0xed, 0x84, - 0x9e, 0xe1, 0xbb, 0x76, 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12, - "The quick brown fox jumps over the lazy cog", - 0xde, 0x9f, 0x2c, 0x7f, 0xd2, 0x5e, 0x1b, 0x3a, 0xfa, 0xd3, - 0xe8, 0x5a, 0x0b, 0xd1, 0x7d, 0x9b, 0x10, 0x0d, 0xb4, 0xb3, -}; - // This test data from http://en.wikipedia.org/wiki/SHA-2: struct { const char* binary; @@ -84,46 +60,8 @@ struct { } // namespace -TEST(SignaturesTest, Base64) { - for (size_t i = 0; i != arraysize(test_data); i++) { - std::vector buffer(strlen(test_data[i].binary)); - if (strlen(test_data[i].binary) != 0) { - memcpy(&buffer.front(), test_data[i].binary, strlen(test_data[i].binary)); - } - CStringA test_e; - ASSERT_SUCCEEDED(Base64::Encode(buffer, &test_e)); - ASSERT_STREQ(test_e, test_data[i].base64); - std::vector test_d; - uint32 test_d_written = 0; - ASSERT_SUCCEEDED(Base64::Decode(test_e, &test_d)); - ASSERT_EQ(test_d.size(), strlen(test_data[i].binary)); - if (strlen(test_data[i].binary) != 0) { - ASSERT_EQ(0, memcmp(&test_d.front(), - test_data[i].binary, - strlen(test_data[i].binary))); - } - } -} - -TEST(SignaturesTest, CryptoHash) { - CryptoHash chash(CryptoHash::kSha1); - for (size_t i = 0; i != arraysize(test_hash); i++) { - std::vector buffer(strlen(test_hash[i].binary)); - if (!buffer.empty()) { - memcpy(&buffer.front(), test_hash[i].binary, strlen(test_hash[i].binary)); - } - std::vector hash; - ASSERT_SUCCEEDED(chash.Compute(buffer, &hash)); - ASSERT_EQ(hash.size(), chash.hash_size()); - ASSERT_EQ(0, memcmp(&hash.front(), - test_hash[i].hash, - hash.size())); - ASSERT_SUCCEEDED(chash.Validate(buffer, hash)); - } -} - TEST(SignaturesTest, CryptoHashSha256) { - CryptoHash chash(CryptoHash::kSha256); + CryptoHash chash; for (size_t i = 0; i != arraysize(test_hash256); i++) { std::vector buffer(strlen(test_hash256[i].binary)); @@ -142,118 +80,6 @@ TEST(SignaturesTest, CryptoHashSha256) { } } -TEST(SignaturesTest, CreationVerification) { - CString module_directory = app_util::GetModuleDirectory(NULL); - ASSERT_FALSE(module_directory.IsEmpty()); - CString directory; - directory.Format(_T("%s\\unittest_support"), module_directory); - - CString encoded_cert_with_private_key_path; - encoded_cert_with_private_key_path.AppendFormat( - _T("%s\\certificate-with-private-key.pfx"), directory); - CString encoded_cert_without_private_key_path; - encoded_cert_without_private_key_path.AppendFormat( - _T("%s\\certificate-without-private-key.cer"), directory); - CString raw_test_data_path; - raw_test_data_path.AppendFormat(_T("%s\\declaration.txt"), directory); - - // Get cert with private key and cert without private key. - std::vector encoded_cert_with_private_key; - std::vector encoded_cert_without_private_key; - ASSERT_SUCCEEDED(ReadEntireFile(encoded_cert_with_private_key_path, - 0, - &encoded_cert_with_private_key)); - ASSERT_SUCCEEDED(ReadEntireFile(encoded_cert_without_private_key_path, - 0, - &encoded_cert_without_private_key)); - CString cert_password = _T("f00bar"); - CString cert_subject_name = _T("Unofficial Google Test"); - - // Get testdata. - std::vector raw_testdata; - ASSERT_SUCCEEDED(ReadEntireFile(raw_test_data_path, 0, &raw_testdata)); - - // Create a signing certificate. - CryptoSigningCertificate signing_certificate; - ASSERT_SUCCEEDED(signing_certificate.ImportCertificate( - encoded_cert_with_private_key, cert_password, cert_subject_name)); - - // Create a signature object and sign the test data. - std::vector signature; - CryptoComputeSignature signer(&signing_certificate); - ASSERT_SUCCEEDED(signer.Sign(raw_testdata, &signature)); - - // Create a validating certificate. - CryptoSignatureVerificationCertificate verification_certificate; - ASSERT_SUCCEEDED(verification_certificate.ImportCertificate( - encoded_cert_without_private_key, cert_subject_name)); - - // Create a signature object and verify the test data's signature. - CryptoVerifySignature verifier(verification_certificate); - ASSERT_SUCCEEDED(verifier.Validate(raw_testdata, signature)); - - // Mess up the signature and show it doesn't verify. - size_t mid = signature.size() / 2; - byte mid_byte = signature[mid]; - signature[mid] = ~mid_byte; - ASSERT_FAILED(verifier.Validate(raw_testdata, signature)); - - // Restore the signature, mess up the test data, and show it doesn't verify. - signature[mid] = mid_byte; - mid = raw_testdata.size() / 2; - mid_byte = raw_testdata[mid]; - raw_testdata[mid] = ~mid_byte; - ASSERT_FAILED(verifier.Validate(raw_testdata, signature)); -} - -TEST(SignaturesTest, VerifyFileHash) { - const CString executable_path(app_util::GetCurrentModuleDirectory()); - - const CString source_file1 = ConcatenatePath( - executable_path, - _T("unittest_support\\download_cache_test\\") - _T("{89640431-FE64-4da8-9860-1A1085A60E13}\\gears-win32-opt.msi")); - - const CString hash_file1 = _T("ImV9skETZqGFMjs32vbZTvzAYJU="); - - const CString source_file2 = ConcatenatePath( - executable_path, - _T("unittest_support\\download_cache_test\\") - _T("{7101D597-3481-4971-AD23-455542964072}\\livelysetup.exe")); - - const CString hash_file2 = _T("Igq6bYaeXFJCjH770knXyJ6V53s="); - - const CString hash_files = _T("e2uzy96jlusKbADl87zie6F5iwE="); - - const CString bad_hash = _T("sFzmoHgCbowEnioqVb8WanTYbhIabcde="); - - std::vector files; - - // Authenticate one file. - files.push_back(source_file1); - EXPECT_HRESULT_SUCCEEDED(VerifyFileHash(files, hash_file1)); - - // Incorrect hash. - EXPECT_EQ(SIGS_E_INVALID_SIGNATURE, VerifyFileHash(files, hash_file2)); - - // Bad hash. - EXPECT_EQ(E_INVALIDARG, VerifyFileHash(files, bad_hash)); - EXPECT_EQ(E_INVALIDARG, VerifyFileHash(files, _T(""))); - - // Authenticate two files. - files.push_back(source_file2); - EXPECT_HRESULT_SUCCEEDED(VerifyFileHash(files, hash_files)); - - // Round trip through CryptoHash::Compute to verify the hash of two files. - CryptoHash crypto(CryptoHash::kSha1); - std::vector hash_out; - EXPECT_HRESULT_SUCCEEDED(crypto.Compute(files, 0, &hash_out)); - - CStringA actual_hash_files; - EXPECT_HRESULT_SUCCEEDED(Base64::Encode(hash_out, &actual_hash_files)); - EXPECT_STREQ(hash_files, CString(actual_hash_files)); -} - TEST(SignaturesTest, VerifyFileHashSha256) { const CString executable_path(app_util::GetCurrentModuleDirectory()); @@ -293,7 +119,7 @@ TEST(SignaturesTest, VerifyFileHashSha256) { EXPECT_HRESULT_SUCCEEDED(VerifyFileHashSha256(files, hash_files)); // Round trip through CryptoHash::Compute to verify the hash of two files. - CryptoHash crypto(CryptoHash::kSha256); + CryptoHash crypto; std::vector hash_out; EXPECT_HRESULT_SUCCEEDED(crypto.Compute(files, 0, &hash_out)); diff --git a/omaha/base/string.cc b/omaha/base/string.cc index f8cd8f040..95a0c92db 100644 --- a/omaha/base/string.cc +++ b/omaha/base/string.cc @@ -708,12 +708,6 @@ case 2: #define kWebSafeBase64Chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" -int Base64Escape(const char *src, int szsrc, char *dest, int szdest) { - ASSERT(dest, (L"")); - ASSERT(src, (L"")); - - return Base64EscapeInternal(src, szsrc, dest, szdest, kBase64Chars, true); -} int WebSafeBase64Escape(const char *src, int szsrc, char *dest, int szdest, bool do_padding) { ASSERT(dest, (L"")); @@ -995,6 +989,15 @@ int Base64Unescape(const char *src, int len_src, char *dest, int len_dest) { return Base64UnescapeInternal(src, len_src, dest, len_dest, UnBase64); } +int Base64Unescape(const CStringA& src, CStringA* dest) { + ASSERT1(dest); + + int len = src.GetLength(); + int unescape_len = Base64Unescape(src, len, dest->GetBuffer(len + 1), len); + dest->ReleaseBufferSetLength(unescape_len >= 0 ? unescape_len : 0); + return unescape_len; +} + int WebSafeBase64Unescape(const char *src, int szsrc, char *dest, int szdest) { ASSERT(dest, (L"")); ASSERT(src, (L"")); @@ -2236,4 +2239,3 @@ bool SafeHexStringToVector(const CStringW& str, std::vector* vec_out) { } } // namespace omaha - diff --git a/omaha/base/string.h b/omaha/base/string.h index ad9f1b636..682075640 100644 --- a/omaha/base/string.h +++ b/omaha/base/string.h @@ -121,7 +121,6 @@ int CalculateBase64EscapedLen(int input_len); // to escape them. It also has an extra parameter "do_padding", // which when set to false will prevent padding with "=". // ---------------------------------------------------------------------- -int Base64Escape(const char *src, int slen, char *dest, int szdest); int WebSafeBase64Escape(const char *src, int slen, char *dest, int szdest, bool do_padding); void WebSafeBase64Escape(const CStringA& src, CStringA* dest); @@ -143,6 +142,7 @@ void WebSafeBase64Escape(const char *src, int szsrc, // destination buffer or -1 in case of a decoding error. // ---------------------------------------------------------------------- int Base64Unescape(const char *src, int slen, char *dest, int len_dest); +int Base64Unescape(const CStringA& src, CStringA* dest); int WebSafeBase64Unescape(const char *src, int slen, char *dest, int szdest); #ifdef UNICODE diff --git a/omaha/base/string_unittest.cc b/omaha/base/string_unittest.cc index 27d7fae0e..0b9686e06 100644 --- a/omaha/base/string_unittest.cc +++ b/omaha/base/string_unittest.cc @@ -720,6 +720,38 @@ TEST(StringTest, WideToAnsiDirect) { } } +TEST(StringTest, Base64) { + struct { + const char* binary; + const char* base64; + } test_data[] = { + "", "", + "what", "d2hhdA==", + "what will print out", "d2hhdCB3aWxsIHByaW50IG91dA==", + "foobar", "Zm9vYmFy", + "a man, a plan, a canal: panama!", "YSBtYW4sIGEgcGxhbiwgYSBjYW5hbDogcGFuYW1hIQ==", // NOLINT + }; + + for (size_t i = 0; i != arraysize(test_data); i++) { + CStringA test_e; + Base64Escape(test_data[i].binary, + strlen(test_data[i].binary), + &test_e, + true); + EXPECT_STREQ(test_e, test_data[i].base64); + + CStringA test_d; + ASSERT_GE(Base64Unescape(test_e, &test_d), 0); + EXPECT_STREQ(test_d, test_data[i].binary); + } +} + +TEST(StringTest, Base64Unescape) { + CStringA input("AAAAAAAA"); + CStringA output; + ASSERT_EQ(Base64Unescape(input, &output), input.GetLength() * 3 / 4); +} + TEST(StringTest, TextToLinesAndBack) { const TCHAR sample_input[] = L"Now is the time\r\nfor all good men\r\nto come to the aid of their country"; const TCHAR* sample_lines[] = { L"Now is the time", L"for all good men", L"to come to the aid of their country" }; diff --git a/omaha/base/utils.h b/omaha/base/utils.h index 2296009cb..506ae25c7 100644 --- a/omaha/base/utils.h +++ b/omaha/base/utils.h @@ -859,6 +859,23 @@ inline bool IsLocalSystemSid(const TCHAR* sid) { return _tcsicmp(sid, kLocalSystemSid) == 0; } +// Returns true if the argument is a uuid. In Microsoft parlance, a UUID is a +// GUID without the curly braces, as defined by ::UuidFromString(). +inline bool IsUuid(const CString& s) { + if (s.IsEmpty()) { + return false; + } + + // We can use ::UuidFromString() instead of the following code. However, + // ::UuidFromString() requires taking a dependency on Rpcrt4.lib, and also + // uses NT types such as RPC_STATUS for the return code and RPC_WSTR for the + // input string. So this code reuses IsGuid() instead. + CString guid(s); + guid.Insert(0, _T('{')); + guid.AppendChar(_T('}')); + return IsGuid(guid); +} + // Deletes an object. The functor is useful in for_each algorithms. struct DeleteFun { template void operator()(T ptr) { delete ptr; } diff --git a/omaha/base/utils_unittest.cc b/omaha/base/utils_unittest.cc index 00d0e32c1..84662fe4c 100644 --- a/omaha/base/utils_unittest.cc +++ b/omaha/base/utils_unittest.cc @@ -16,11 +16,12 @@ #include #include #include + #include #include + #include "base/rand_util.h" #include "omaha/base/app_util.h" -#include "omaha/base/atl_regexp.h" #include "omaha/base/constants.h" #include "omaha/base/dynamic_link_kernel32.h" #include "omaha/base/file.h" @@ -696,38 +697,29 @@ TEST(UtilsTest, interlocked_exchange_pointer) { EXPECT_EQ(static_cast(NULL), pi); } -TEST(UtilsTest, GetGuid) { +TEST(UtilsTest, GetGuid) { CString guid; EXPECT_HRESULT_SUCCEEDED(GetGuid(&guid)); - // ATL regexp has many problems including: - // * not supporting {n} to repeat a previous item n times. - // * not allowing matching on - unless the items around the dash are - // enclosed in {}. - AtlRE guid_regex(_T("^{\\{{\\h\\h\\h\\h\\h\\h\\h\\h}-{\\h\\h\\h\\h}-{\\h\\h\\h\\h}-{\\h\\h\\h\\h}-{\\h\\h\\h\\h\\h\\h\\h\\h\\h\\h\\h\\h}\\}}$")); // NOLINT - - CString matched_guid; - EXPECT_TRUE(AtlRE::PartialMatch(guid, guid_regex, &matched_guid)); - EXPECT_STREQ(guid, matched_guid); + IID iid = {0}; + EXPECT_HRESULT_SUCCEEDED(::IIDFromString(guid, &iid)); // Missing {}. - guid = _T("5F5280C6-9674-429b-9FEB-551914EF96B8"); - EXPECT_FALSE(AtlRE::PartialMatch(guid, guid_regex)); + EXPECT_HRESULT_FAILED( + ::IIDFromString(_T("5F5280C6-9674-429b-9FEB-551914EF96B8"), &iid)); // Missing -. - guid = _T("{5F5280C6.9674-429b-9FEB-551914EF96B8}"); - EXPECT_FALSE(AtlRE::PartialMatch(guid, guid_regex)); + EXPECT_HRESULT_FAILED( + ::IIDFromString(_T("{5F5280C6.9674-429b-9FEB-551914EF96B8}"), &iid)); // Whitespaces. - guid = _T(" {5F5280C6.9674-429b-9FEB-551914EF96B8}"); - EXPECT_FALSE(AtlRE::PartialMatch(guid, guid_regex)); - - guid = _T("{5F5280C6.9674-429b-9FEB-551914EF96B8} "); - EXPECT_FALSE(AtlRE::PartialMatch(guid, guid_regex)); + EXPECT_HRESULT_FAILED( + ::IIDFromString(_T(" {5F5280C6-9674-429b-9FEB-551914EF96B8}"), &iid)); + EXPECT_HRESULT_FAILED( + ::IIDFromString(_T("{5F5280C6-9674-429b-9FEB-551914EF96B8} "), &iid)); // Empty string. - guid = _T(""); - EXPECT_FALSE(AtlRE::PartialMatch(guid, guid_regex)); + EXPECT_HRESULT_FAILED(::IIDFromString(_T(""), &iid)); } TEST(UtilsTest, GetMessageForSystemErrorCode) { diff --git a/omaha/client/help_url_builder_test.cc b/omaha/client/help_url_builder_test.cc index 71871aa17..f4ce63f8a 100644 --- a/omaha/client/help_url_builder_test.cc +++ b/omaha/client/help_url_builder_test.cc @@ -17,8 +17,10 @@ #include #include #include + +#include #include -#include "omaha/base/atl_regexp.h" + #include "omaha/base/error.h" #include "omaha/base/omaha_version.h" #include "omaha/base/reg_key.h" @@ -49,15 +51,17 @@ int VerifyOSInUrl(const CString& url, int* length) { ASSERT1(length); *length = 0; - const AtlRE expected_os_string = - _T("{(5\\.1)|(5\\.2)|(6\\.0)|(6\\.1)|(6\\.3)|(10\\.0)\\.\\d+\\.\\d+") - _T("&sp=(Service%20Pack%20(1|2|3))?}"); + const std::wregex expected_os_string { + _T("(?:5\\.[12]|6\\.[013]|10\\.0)\\.\\d+\\.\\d+") + _T("&sp=(?:Service%20Pack%20[123])?") + }; - CString os_string; - EXPECT_TRUE(AtlRE::PartialMatch(url, expected_os_string, &os_string)); + std::wcmatch m; + EXPECT_TRUE(std::regex_search(url.GetString(), m, expected_os_string)); + EXPECT_EQ(1, m.size()); - *length = os_string.GetLength(); - return url.Find(os_string); + *length = m.length(0); + return url.Find(m.str(0).c_str()); } } // namespace diff --git a/omaha/common/build.scons b/omaha/common/build.scons index 09ca81a43..3471c9c80 100644 --- a/omaha/common/build.scons +++ b/omaha/common/build.scons @@ -46,7 +46,6 @@ def BuildCommonLib(env): 'update_request.cc', 'update_response.cc', 'url_utils.cc', - 'webplugin_utils.cc', 'web_services_client.cc', 'xml_const.cc', 'xml_parser.cc', diff --git a/omaha/common/command_line.h b/omaha/common/command_line.h index 9b66f4237..7a4bd4367 100644 --- a/omaha/common/command_line.h +++ b/omaha/common/command_line.h @@ -70,7 +70,7 @@ enum CommandLineMode { // Obsolete: COMMANDLINE_MODE_UG = 13, COMMANDLINE_MODE_UA = 14, COMMANDLINE_MODE_RECOVER = 15, - COMMANDLINE_MODE_WEBPLUGIN = 16, + // Obsolete: COMMANDLINE_MODE_WEBPLUGIN = 16, COMMANDLINE_MODE_CODE_RED_CHECK = 17, COMMANDLINE_MODE_COMSERVER = 18, // Obsolete: COMMANDLINE_MODE_LEGACYUI = 19, @@ -142,8 +142,6 @@ struct CommandLineArgs { CString crash_filename; CString custom_info_filename; CString legacy_manifest_path; - CString webplugin_urldomain; - CString webplugin_args; CString code_red_metainstaller_path; CString ping_string; CString offline_dir_name; diff --git a/omaha/common/command_line_builder.cc b/omaha/common/command_line_builder.cc index 29eb40398..fd421e887 100644 --- a/omaha/common/command_line_builder.cc +++ b/omaha/common/command_line_builder.cc @@ -83,8 +83,7 @@ void CommandLineBuilder::set_app_args(const CString& app_args) { } void CommandLineBuilder::set_install_source(const CString& install_source) { - ASSERT1(mode_ == COMMANDLINE_MODE_WEBPLUGIN || - mode_ == COMMANDLINE_MODE_INSTALL || + ASSERT1(mode_ == COMMANDLINE_MODE_INSTALL || mode_ == COMMANDLINE_MODE_HANDOFF_INSTALL || mode_ == COMMANDLINE_MODE_UA); install_source_ = install_source; @@ -108,17 +107,6 @@ void CommandLineBuilder::set_custom_info_filename( custom_info_filename_ = custom_info_filename; } -void CommandLineBuilder::set_webplugin_url_domain( - const CString& webplugin_url_domain) { - ASSERT1(mode_ == COMMANDLINE_MODE_WEBPLUGIN); - webplugin_url_domain_ = webplugin_url_domain; -} - -void CommandLineBuilder::set_webplugin_args(const CString& webplugin_args) { - ASSERT1(mode_ == COMMANDLINE_MODE_WEBPLUGIN); - webplugin_args_ = webplugin_args; -} - void CommandLineBuilder::set_code_red_metainstaller_path( const CString& code_red_metainstaller_path) { ASSERT1(mode_ == COMMANDLINE_MODE_RECOVER); @@ -186,9 +174,6 @@ CString CommandLineBuilder::GetCommandLineArgs() const { case COMMANDLINE_MODE_RECOVER: cmd_line_args = GetRecover(); break; - case COMMANDLINE_MODE_WEBPLUGIN: - cmd_line_args = GetWebPlugin(); - break; case COMMANDLINE_MODE_CODE_RED_CHECK: cmd_line_args = GetCodeRedCheck(); break; @@ -457,30 +442,6 @@ CString CommandLineBuilder::GetRecover() const { return cmd_line; } -CString CommandLineBuilder::GetWebPlugin() const { - ASSERT1(!webplugin_url_domain_.IsEmpty()); - ASSERT1(!webplugin_args_.IsEmpty()); - ASSERT1(!install_source_.IsEmpty()); - if (webplugin_url_domain_.IsEmpty() || - webplugin_args_.IsEmpty() || - install_source_.IsEmpty()) { - return CString(); - } - CString cmd_line; - CString enclosed_webplugin_url_domain_(webplugin_url_domain_); - CString enclosed_webplugin_args_(webplugin_args_); - EnclosePath(&enclosed_webplugin_url_domain_); - EnclosePath(&enclosed_webplugin_args_); - // TODO(omaha): Do we want this to handle the urlencoding for us? - SafeCStringFormat(&cmd_line, _T("/%s %s %s /%s %s"), - kCmdLineWebPlugin, - enclosed_webplugin_url_domain_.GetString(), - enclosed_webplugin_args_.GetString(), - kCmdLineInstallSource, - install_source_.GetString()); - return cmd_line; -} - CString CommandLineBuilder::GetCodeRedCheck() const { return GetSingleSwitch(kCmdLineCodeRedCheck); } diff --git a/omaha/common/command_line_builder.h b/omaha/common/command_line_builder.h index ca9aceaf4..c728c769e 100644 --- a/omaha/common/command_line_builder.h +++ b/omaha/common/command_line_builder.h @@ -66,12 +66,6 @@ class CommandLineBuilder { CString custom_info_filename() const { return custom_info_filename_; } void set_custom_info_filename(const CString& custom_info_filename); - CString webplugin_url_domain() const { return webplugin_url_domain_; } - void set_webplugin_url_domain(const CString& webplugin_url_domain); - - CString webplugin_args() const { return webplugin_args_; } - void set_webplugin_args(const CString& webplugin_args); - CString code_red_metainstaller_path() const { return code_red_metainstaller_path_; } @@ -114,7 +108,6 @@ class CommandLineBuilder { CString GetHandoffInstall() const; CString GetUA() const; CString GetRecover() const; - CString GetWebPlugin() const; CString GetCodeRedCheck() const; CString GetComServer() const; CString GetComBroker() const; @@ -138,8 +131,6 @@ class CommandLineBuilder { CString install_source_; CString crash_filename_; CString custom_info_filename_; - CString webplugin_url_domain_; - CString webplugin_args_; CString code_red_metainstaller_path_; CString ping_string_; CString offline_dir_name_; diff --git a/omaha/common/command_line_builder_unittest.cc b/omaha/common/command_line_builder_unittest.cc index bb1c7578b..4b02a992d 100644 --- a/omaha/common/command_line_builder_unittest.cc +++ b/omaha/common/command_line_builder_unittest.cc @@ -260,24 +260,6 @@ TEST(CommandLineBuilder, BuildCodeRedCheck) { EXPECT_STREQ(_T("/cr"), cmd_line); } -TEST(CommandLineBuilder, BuildWebPlugin) { - CommandLineBuilder builder(COMMANDLINE_MODE_WEBPLUGIN); - ExpectAsserts expect_asserts; - CString cmd_line = builder.GetCommandLineArgs(); - EXPECT_STREQ(_T(""), cmd_line); -} - -TEST(CommandLineBuilder, BuildWebPluginWithUrlArgsAndInstallSource) { - CommandLineBuilder builder(COMMANDLINE_MODE_WEBPLUGIN); - builder.set_webplugin_args(_T("piargs")); - builder.set_webplugin_url_domain(_T("http://www.google.com/")); - builder.set_install_source(_T("oneclick")); - CString cmd_line = builder.GetCommandLineArgs(); - EXPECT_STREQ(_T("/pi \"http://www.google.com/\" \"piargs\"") - _T(" /installsource oneclick"), - cmd_line); -} - TEST(CommandLineBuilder, BuildRecover) { CommandLineBuilder builder(COMMANDLINE_MODE_RECOVER); ExpectAsserts expect_asserts; diff --git a/omaha/common/command_line_unittest.cc b/omaha/common/command_line_unittest.cc index 12e3213a8..13f3ae0cf 100644 --- a/omaha/common/command_line_unittest.cc +++ b/omaha/common/command_line_unittest.cc @@ -58,8 +58,6 @@ void VerifyCommandLineArgs(const CommandLineArgs& expected, EXPECT_STREQ(expected.crash_filename, actual.crash_filename); EXPECT_STREQ(expected.custom_info_filename, actual.custom_info_filename); EXPECT_STREQ(expected.legacy_manifest_path, actual.legacy_manifest_path); - EXPECT_STREQ(expected.webplugin_urldomain, actual.webplugin_urldomain); - EXPECT_STREQ(expected.webplugin_args, actual.webplugin_args); EXPECT_STREQ(expected.code_red_metainstaller_path, actual.code_red_metainstaller_path); EXPECT_STREQ(expected.offline_dir_name, actual.offline_dir_name); @@ -475,27 +473,27 @@ TEST_F(CommandLineTest, ParseCommandLine_InstallEulaRequired) { VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } -// Parse: /install "extraargs" /oem /installsource oneclick +// Parse: /install "extraargs" /oem /installsource taggedmi TEST_F(CommandLineTest, ParseCommandLine_InstallWithOemAndSource) { const TCHAR* kCmdLine = _T("goopdate.exe /install ") YOUTUBEUPLOADEREN_TAG _T(" /oem") - _T(" /installsource oneclick"); + _T(" /installsource taggedmi"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_INSTALL; expected_.is_oem_set = true; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } -// Parse: /install "extraargs" /installsource oneclick +// Parse: /install "extraargs" /installsource taggedmi TEST_F(CommandLineTest, ParseCommandLine_InstallWithSource) { const TCHAR* kCmdLine = _T("goopdate.exe /install ") YOUTUBEUPLOADEREN_TAG - _T(" /installsource oneclick"); + _T(" /installsource taggedmi"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_INSTALL; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } @@ -523,15 +521,15 @@ TEST_F(CommandLineTest, ParseCommandLine_InstallSilentWithOem) { VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } -// Parse: /install "extraargs" /installsource oneclick /silent +// Parse: /install "extraargs" /installsource taggedmi /silent TEST_F(CommandLineTest, ParseCommandLine_InstallSilentWithSource) { const TCHAR* kCmdLine = _T("goopdate.exe /install ") YOUTUBEUPLOADEREN_TAG - _T(" /installsource oneclick") + _T(" /installsource taggedmi") _T(" /silent"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_INSTALL; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); expected_.is_silent_set = true; VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } @@ -547,15 +545,15 @@ TEST_F(CommandLineTest, ParseCommandLine_InstallElevated) { VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } -// Parse: /install "extraargs" /installelevated /installsource oneclick +// Parse: /install "extraargs" /installelevated /installsource taggedmi TEST_F(CommandLineTest, ParseCommandLine_InstallElevatedWithSource) { const TCHAR* kCmdLine = _T("goopdate.exe /install ") YOUTUBEUPLOADEREN_TAG - _T(" /installelevated /installsource oneclick"); + _T(" /installelevated /installsource taggedmi"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_INSTALL; expected_.is_install_elevated = true; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } @@ -589,11 +587,11 @@ TEST_F(CommandLineTest, ParseCommandLine_Handoff) { // Parse: /handoff "extraargs" /installsource "asd" TEST_F(CommandLineTest, ParseCommandLine_HandoffWithSource) { const TCHAR* kCmdLine = _T("goopdate.exe /handoff ") YOUTUBEUPLOADEREN_TAG - _T(" /installsource oneclick"); + _T(" /installsource taggedmi"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_HANDOFF_INSTALL; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } @@ -700,12 +698,12 @@ TEST_F(CommandLineTest, // Parse: /handoff "extraargs" /installsource "asd" /silent TEST_F(CommandLineTest, ParseCommandLine_HandoffSilentWithSource) { const TCHAR* kCmdLine = _T("goopdate.exe /handoff ") YOUTUBEUPLOADEREN_TAG - _T(" /installsource oneclick") + _T(" /installsource taggedmi") _T(" /silent"); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_HANDOFF_INSTALL; - expected_.install_source = _T("oneclick"); + expected_.install_source = _T("taggedmi"); expected_.is_silent_set = true; VerifyArgsWithSingleYouTubeUploaderEnApp(expected_, args_, false, true); } @@ -1016,43 +1014,6 @@ TEST_F(CommandLineTest, ParseCommandLine_CodeRedCheck) { VerifyCommandLineArgs(expected_, args_); } -TEST_F(CommandLineTest, ParseCommandLine_WebPlugin) { - const TCHAR* kCmdLine = _T("goopdate.exe /pi \"http://gears.google.com/\" ") - _T("\"/install foo\" /installsource oneclick "); - EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); - - expected_.mode = COMMANDLINE_MODE_WEBPLUGIN; - expected_.webplugin_urldomain = _T("http://gears.google.com/"); - expected_.webplugin_args = _T("/install foo"); - expected_.install_source = _T("oneclick"); - VerifyCommandLineArgs(expected_, args_); -} - -TEST_F(CommandLineTest, ParseCommandLine_WebPluginUrlEscaped) { - const TCHAR* kCmdLine = _T("goopdate.exe /pi \"http://gears.google.com/\" ") - _T("\"/install%20foo\" /installsource oneclick "); - EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); - - expected_.mode = COMMANDLINE_MODE_WEBPLUGIN; - expected_.webplugin_urldomain = _T("http://gears.google.com/"); - expected_.webplugin_args = _T("/install foo"); - expected_.install_source = _T("oneclick"); - VerifyCommandLineArgs(expected_, args_); -} - -TEST_F(CommandLineTest, ParseCommandLine_WebPluginTestStringTrim) { - const TCHAR* kCmdLine = _T("goopdate.exe /pi ") - _T("\" http://gears.google.com/ \" ") - _T("\"/install foo\" /installsource oneclick "); - EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); - - expected_.mode = COMMANDLINE_MODE_WEBPLUGIN; - expected_.webplugin_urldomain = _T("http://gears.google.com/"); - expected_.webplugin_args = _T("/install foo"); - expected_.install_source = _T("oneclick"); - VerifyCommandLineArgs(expected_, args_); -} - TEST_F(CommandLineTest, ParseCommandLine_LegacyOmaha1UiNoLanguage) { const TCHAR* kCmdLine = _T("goopdate.exe /ui \"manifestfilename.xml\""); EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); @@ -1165,18 +1126,6 @@ TEST_F(CommandLineTest, UiWithLangNoLanguage) { EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); } -TEST_F(CommandLineTest, WebPluginInstallSourceInvalid_IncorrectValue) { - const TCHAR* kCmdLine = _T("goopdate.exe /installsource invalid /pi ") - _T("\" http://gears.google.com/ \" "); - EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); -} - -TEST_F(CommandLineTest, WebPluginInstallSourceInvalid_Empty) { - const TCHAR* kCmdLine = _T("goopdate.exe /installsource /pi ") - _T("\" http://gears.google.com/ \" "); - EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); -} - // Parse: /handoff "extraargs" /lang "en" TEST_F(CommandLineTest, ParseCommandLine_HandoffLegacyOmaha1ToOmaha2) { const TCHAR* kCmdLine = @@ -1194,18 +1143,18 @@ TEST_F(CommandLineTest, _T("goopdate.exe /handoff ") _T("\"appguid={A4F7B07B-B9BD-4a33-B136-96D2ADFB60CB}&") _T("appname=YouTubeUploader&needsadmin=False\"") - _T(" /installsource oneclick /lang en"); + _T(" /installsource taggedmi /lang en"); EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); } -// Parse: /handoff "extraargs" /installsource "oneclick" /lang "en" +// Parse: /handoff "extraargs" /installsource "taggedmi" /lang "en" TEST_F(CommandLineTest, ParseCommandLine_HandoffWithSourceLegacyOmaha1ToOmaha2Both) { const TCHAR* kCmdLine = _T("goopdate.exe /handoff ") _T("\"appguid={A4F7B07B-B9BD-4a33-B136-96D2ADFB60CB}&") _T("appname=YouTubeUploader&needsadmin=False&lang=en\"") - _T(" /installsource oneclick /lang en"); + _T(" /installsource taggedmi /lang en"); EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); } @@ -1220,13 +1169,13 @@ TEST_F(CommandLineTest, ParseCommandLine_InstallLegacyOmaha1) { EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); } -// Parse: /install "extraargs" /installsource oneclick /lang en +// Parse: /install "extraargs" /installsource taggedmi /lang en TEST_F(CommandLineTest, ParseCommandLine_InstallWithSourceLegacyOmaha1) { const TCHAR* kCmdLine = _T("goopdate.exe /install ") _T("\"appguid={A4F7B07B-B9BD-4a33-B136-96D2ADFB60CB}&") _T("appname=YouTubeUploader&needsadmin=False\"") - _T(" /installsource oneclick /lang en"); + _T(" /installsource taggedmi /lang en"); EXPECT_FAILED(ParseCommandLine(kCmdLine, &args_)); } diff --git a/omaha/common/config_manager.cc b/omaha/common/config_manager.cc index 434c77aae..0a0032bef 100644 --- a/omaha/common/config_manager.cc +++ b/omaha/common/config_manager.cc @@ -104,7 +104,7 @@ HRESULT GetDir32(int csidl, } // namespace bool GroupPolicyManager::IsManaged() { - return IsEnrolledToDomain(); + return IsEnrolledToDomain() && RegKey::HasKey(kRegKeyGoopdateGroupPolicy); } HRESULT GroupPolicyManager::GetLastCheckPeriodMinutes(DWORD* minutes) { @@ -119,7 +119,7 @@ HRESULT GroupPolicyManager::GetLastCheckPeriodMinutes(DWORD* minutes) { return hr; } - CORE_LOG(L5, (_T("[Group Policy check period override %d]"), *minutes)); + OPT_LOG(L5, (_T("[Group Policy check period override %d]"), *minutes)); return S_OK; } @@ -414,8 +414,17 @@ ConfigManager::ConfigManager() : dm_policy_manager_(new DMPolicyManager) { true) == 0) : false; - policies_.emplace_back(new GroupPolicyManager); - policies_.push_back(dm_policy_manager_); + DWORD cloud_policy_preferred(0); + if (SUCCEEDED(RegKey::GetValue(kRegKeyGoopdateGroupPolicy, + kRegValueCloudPolicyOverridesPlatformPolicy, + &cloud_policy_preferred)) && + cloud_policy_preferred) { + policies_.push_back(dm_policy_manager_); + policies_.emplace_back(new GroupPolicyManager); + } else { + policies_.emplace_back(new GroupPolicyManager); + policies_.push_back(dm_policy_manager_); + } } CString ConfigManager::GetUserDownloadStorageDir() const { @@ -689,6 +698,8 @@ CPath ConfigManager::GetPolicyResponsesDir() const { void ConfigManager::SetOmahaDMPolicies(const CachedOmahaPolicy& dm_policy) { dm_policy_manager_->set_dm_policy(dm_policy); + REPORT_LOG(L1, (_T("[ConfigManager::SetOmahaDMPolicies][%s]"), + dm_policy.ToString())); } // Returns the override from the registry locations if present. Otherwise, @@ -715,8 +726,8 @@ int ConfigManager::GetLastCheckPeriodSec(bool* is_overridden) const { } hr = policies_[i]->GetLastCheckPeriodMinutes(&minutes); - CORE_LOG(L5, (_T("[GetLastCheckPeriodMinutes][%s][%d]"), - policies_[i]->source(), minutes)); + OPT_LOG(L5, (_T("[GetLastCheckPeriodMinutes][%s][%d]"), + policies_[i]->source(), minutes)); break; } @@ -728,7 +739,7 @@ int ConfigManager::GetLastCheckPeriodSec(bool* is_overridden) const { if (*is_overridden) { if (0 == policy_period_sec) { - CORE_LOG(L5, (_T("[GetLastCheckPeriodSec][0 == policy_period_sec]"))); + OPT_LOG(L5, (_T("[GetLastCheckPeriodSec][0 == policy_period_sec]"))); return 0; } const int period_sec = policy_period_sec > INT_MAX ? @@ -738,7 +749,7 @@ int ConfigManager::GetLastCheckPeriodSec(bool* is_overridden) const { if (period_sec < kMinLastCheckPeriodSec) { return kMinLastCheckPeriodSec; } - CORE_LOG(L5, (_T("[GetLastCheckPeriodSec][period_sec][%d]"), period_sec)); + OPT_LOG(L5, (_T("[GetLastCheckPeriodSec][period_sec][%d]"), period_sec)); return period_sec; } @@ -1165,12 +1176,12 @@ DWORD ConfigManager::GetEffectivePolicyForAppInstalls(const GUID& app_guid) app_guid, &effective_policy); if (SUCCEEDED(hr)) { - CORE_LOG(L5, (_T("[GetEffectivePolicyForAppInstalls][%s][%d]"), - policies_[i]->source(), effective_policy)); + OPT_LOG(L5, (_T("[GetEffectivePolicyForAppInstalls][%s][%d]"), + policies_[i]->source(), effective_policy)); return effective_policy; } - break; + return kInstallPolicyDefault; } OPT_LOG(L5, (_T("[GetEffectivePolicyForAppInstalls][Ignoring policy][%s]") @@ -1191,12 +1202,12 @@ DWORD ConfigManager::GetEffectivePolicyForAppUpdates(const GUID& app_guid) app_guid, &effective_policy); if (SUCCEEDED(hr)) { - CORE_LOG(L5, (_T("[GetEffectivePolicyForAppUpdates][%s][%d]"), - policies_[i]->source(), effective_policy)); + OPT_LOG(L5, (_T("[GetEffectivePolicyForAppUpdates][%s][%d]"), + policies_[i]->source(), effective_policy)); return effective_policy; } - break; + return kUpdatePolicyDefault; } OPT_LOG(L5, (_T("[GetEffectivePolicyForAppUpdates][Ignoring policy][%s]") @@ -1215,12 +1226,12 @@ CString ConfigManager::GetTargetVersionPrefix(const GUID& app_guid) const { HRESULT hr = policies_[i]->GetTargetVersionPrefix(app_guid, &target_version_prefix); if (SUCCEEDED(hr)) { - CORE_LOG(L5, (_T("[GetTargetVersionPrefix][%s][%s]"), - policies_[i]->source(), target_version_prefix)); + OPT_LOG(L5, (_T("[GetTargetVersionPrefix][%s][%s]"), + policies_[i]->source(), target_version_prefix)); return target_version_prefix; } - break; + return CString(); } OPT_LOG(L5, (_T("[GetTargetVersionPrefix][Ignoring policy][%s]") @@ -1241,12 +1252,12 @@ bool ConfigManager::IsRollbackToTargetVersionAllowed(const GUID& app_guid) app_guid, &rollback_allowed); if (SUCCEEDED(hr)) { - CORE_LOG(L5, (_T("[IsRollbackToTargetVersionAllowed][%s][%d]"), - policies_[i]->source(), rollback_allowed)); + OPT_LOG(L5, (_T("[IsRollbackToTargetVersionAllowed][%s][%d]"), + policies_[i]->source(), rollback_allowed)); return rollback_allowed; } - break; + return false; } OPT_LOG(L5, (_T("[IsRollbackToTargetVersionAllowed][Ignoring policy][%s]") @@ -1274,8 +1285,8 @@ HRESULT ConfigManager::GetUpdatesSuppressedTimes( hr = policies_[i]->GetUpdatesSuppressedTimes(start_hour, start_min, duration_min); - CORE_LOG(L5, (_T("[GetUpdatesSuppressedTimes][%s][%d][%d][%d]"), - policies_[i]->source(), *start_hour, *start_min, *duration_min)); + OPT_LOG(L5, (_T("[GetUpdatesSuppressedTimes][%s][%d][%d][%d]"), + policies_[i]->source(), *start_hour, *start_min, *duration_min)); break; } @@ -1286,7 +1297,7 @@ HRESULT ConfigManager::GetUpdatesSuppressedTimes( // UpdatesSuppressedDurationMin is limited to 16 hours. if (*start_hour > 23 || *start_min > 59 || *duration_min > 16 * kMinPerHour) { OPT_LOG(L5, (_T("[GetUpdatesSuppressedTimes][Out of bounds][%x][%x][%x]"), - *start_hour, *start_min, *duration_min)); + *start_hour, *start_min, *duration_min)); return E_UNEXPECTED; } @@ -1388,12 +1399,12 @@ CString ConfigManager::GetDownloadPreferenceGroupPolicy() const { HRESULT hr = policies_[i]->GetDownloadPreferenceGroupPolicy( &download_preference); if (SUCCEEDED(hr) && download_preference == kDownloadPreferenceCacheable) { - CORE_LOG(L5, (_T("[GetDownloadPreferenceGroupPolicy][%s][%s]"), - policies_[i]->source(), download_preference)); + OPT_LOG(L5, (_T("[GetDownloadPreferenceGroupPolicy][%s][%s]"), + policies_[i]->source(), download_preference)); return download_preference; } - break; + return CString(); } OPT_LOG(L5, (_T("[GetDownloadPreferenceGroupPolicy]") @@ -1408,7 +1419,8 @@ CString ConfigManager::GetCloudManagementEnrollmentToken() const { CString enrollment_token; HRESULT hr = RegKey::GetValue(kRegKeyCloudManagementGroupPolicy, kRegValueEnrollmentToken, &enrollment_token); - return SUCCEEDED(hr) ? enrollment_token : CString(); + return (SUCCEEDED(hr) && IsUuid(enrollment_token)) ? enrollment_token : + CString(); } bool ConfigManager::IsCloudManagementEnrollmentMandatory() const { diff --git a/omaha/common/config_manager_unittest.cc b/omaha/common/config_manager_unittest.cc index 7d01054f4..b6c2c174b 100644 --- a/omaha/common/config_manager_unittest.cc +++ b/omaha/common/config_manager_unittest.cc @@ -155,6 +155,12 @@ class ConfigManagerTest EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueIsEnrolledToDomain, IsDomain() ? 1UL : 0UL)); + if (IsDomain()) { + RegKey::CreateKey(kRegKeyGoopdateGroupPolicy); + } else { + RegKey::DeleteKey(kRegKeyGoopdateGroupPolicy); + } + if (IsDM()) { SetCannedCachedOmahaPolicy(); } @@ -164,6 +170,7 @@ class ConfigManagerTest if (IsDM()) { ResetCachedOmahaPolicy(); } + RegKey::DeleteKey(kRegKeyGoopdateGroupPolicy); EXPECT_SUCCEEDED(RegKey::DeleteValue(MACHINE_REG_UPDATE_DEV, kRegValueIsEnrolledToDomain)); RestoreRegistryHives(); diff --git a/omaha/common/const_cmd_line.h b/omaha/common/const_cmd_line.h index 410074163..6e123a9be 100644 --- a/omaha/common/const_cmd_line.h +++ b/omaha/common/const_cmd_line.h @@ -20,10 +20,7 @@ namespace omaha { -// -// Externally initiated modes. -// These modes are invoked by or on metainstallers or by the OneClick plugin . -// +// Externally initiated modes. These modes are invoked by metainstallers. // The "install" switch indicates installing Omaha and the app. const TCHAR* const kCmdLineInstall = _T("install"); @@ -38,12 +35,6 @@ const TCHAR* const kCmdLineUpdate = _T("update"); // Code Red scenario. const TCHAR* const kCmdLineRecover = _T("recover"); -// The "pi" switch indicates that this came from a webplugin. -// Requires two subarguments "siteurl" and "{args}" where -// siteurl is the base URL where the plugin ran from and {args} -// are the args to pass on once validation is complete. -const TCHAR* const kCmdLineWebPlugin = _T("pi"); - // // Main operating modes // @@ -201,13 +192,12 @@ const TCHAR* const kCmdLineInteractive = _T("i"); const TCHAR* const kCmdLineSessionId = _T("sessionid"); // The "installsource" switch that is used to pass the source of installation -// for ping tracking. For example: "/installsource OneClick". +// for ping tracking. For example: "/installsource taggedmi". const TCHAR* const kCmdLineInstallSource = _T("installsource"); // "installsource" values generated internally by Omaha. The server code needs // to be updated when these values change or new values are defined. const TCHAR* const kCmdLineInstallSource_TaggedMetainstaller = _T("taggedmi"); -const TCHAR* const kCmdLineInstallSource_OneClick = _T("oneclick"); const TCHAR* const kCmdLineInstallSource_ClickOnce = _T("clickonce"); const TCHAR* const kCmdLineInstallSource_Offline = _T("offline"); const TCHAR* const kCmdLineInstallSource_InstallDefault = _T("otherinstallcmd"); diff --git a/omaha/common/const_group_policy.h b/omaha/common/const_group_policy.h index 715c060b8..29c85efaa 100644 --- a/omaha/common/const_group_policy.h +++ b/omaha/common/const_group_policy.h @@ -50,6 +50,8 @@ const TCHAR* const kRegValueUpdatesSuppressedStartMin = _T("UpdatesSuppressedStartMin"); const TCHAR* const kRegValueUpdatesSuppressedDurationMin = _T("UpdatesSuppressedDurationMin"); +const TCHAR* const kRegValueCloudPolicyOverridesPlatformPolicy = + _T("CloudPolicyOverridesPlatformPolicy"); // This policy specifies what kind of download URLs could be returned to the // client in the update response and in which order of priority. The client diff --git a/omaha/common/crash_utils_unittest.cc b/omaha/common/crash_utils_unittest.cc index fbeec5caa..62e95e1e7 100644 --- a/omaha/common/crash_utils_unittest.cc +++ b/omaha/common/crash_utils_unittest.cc @@ -16,7 +16,6 @@ #include #include #include "omaha/base/app_util.h" -#include "omaha/base/atl_regexp.h" #include "omaha/base/constants.h" #include "omaha/base/const_addresses.h" #include "omaha/base/const_object_names.h" diff --git a/omaha/common/extra_args_parser.cc b/omaha/common/extra_args_parser.cc index ee03a78a9..19d90bb73 100644 --- a/omaha/common/extra_args_parser.cc +++ b/omaha/common/extra_args_parser.cc @@ -273,7 +273,7 @@ HRESULT ExtraArgsParser::HandleToken(const CString& token, args->runtime_only = true; #if defined(HAS_DEVICE_MANAGEMENT) } else if (name.CompareNoCase(kExtraArgEnrollmentToken) == 0) { - if (value.GetLength() > kEnrollmentTokenMaxLength) { + if (!IsUuid(value)) { return E_INVALIDARG; } args->enrollment_token = value; diff --git a/omaha/common/goopdate_command_line_validator.cc b/omaha/common/goopdate_command_line_validator.cc index 9d921575c..d18565be9 100644 --- a/omaha/common/goopdate_command_line_validator.cc +++ b/omaha/common/goopdate_command_line_validator.cc @@ -153,12 +153,6 @@ HRESULT GoopdateCommandLineValidator::Setup() { CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnReportCrashInteractive); - // gu.exe /pi /installsource - SafeCStringFormat(&cmd_line, _T("/%s domainurl args /%s src"), - kCmdLineWebPlugin, - kCmdLineInstallSource); - CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnWebPlugin); - // gu.exe /cr SafeCStringFormat(&cmd_line, _T("/%s"), kCmdLineCodeRedCheck); CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnCodeRed); @@ -411,45 +405,6 @@ HRESULT GoopdateCommandLineValidator::OnReportCrashInteractive() { &args_->crash_filename); } -HRESULT GoopdateCommandLineValidator::OnWebPlugin() { - HRESULT hr = parser_->GetSwitchArgumentValue(kCmdLineInstallSource, - 0, - &args_->install_source); - if (FAILED(hr)) { - return hr; - } - // Validate install_source value. - args_->install_source.MakeLower(); - if ((args_->install_source.Compare(kCmdLineInstallSource_OneClick) != 0) && - (args_->install_source.Compare(kCmdLineInstallSource_Update3Web) != 0)) { - args_->install_source.Empty(); - return E_INVALIDARG; - } - - args_->mode = COMMANDLINE_MODE_WEBPLUGIN; - - CString urldomain; - hr = parser_->GetSwitchArgumentValue(kCmdLineWebPlugin, - 0, - &urldomain); - if (FAILED(hr)) { - return hr; - } - hr = StringUnescape(urldomain, &args_->webplugin_urldomain); - if (FAILED(hr)) { - return hr; - } - - CString webplugin_args; - hr = parser_->GetSwitchArgumentValue(kCmdLineWebPlugin, - 1, - &webplugin_args); - if (FAILED(hr)) { - return hr; - } - return StringUnescape(webplugin_args, &args_->webplugin_args); -} - HRESULT GoopdateCommandLineValidator::OnCodeRed() { args_->mode = COMMANDLINE_MODE_CODE_RED_CHECK; return S_OK; diff --git a/omaha/common/goopdate_command_line_validator.h b/omaha/common/goopdate_command_line_validator.h index 4d0841728..e9578cdcc 100644 --- a/omaha/common/goopdate_command_line_validator.h +++ b/omaha/common/goopdate_command_line_validator.h @@ -67,7 +67,6 @@ class GoopdateCommandLineValidator { HRESULT OnUpdateApps(); HRESULT OnReportCrash(); HRESULT OnReportCrashInteractive(); - HRESULT OnWebPlugin(); HRESULT OnCodeRed(); HRESULT OnRecover(); HRESULT OnRecoverMachine(); diff --git a/omaha/common/goopdate_utils.cc b/omaha/common/goopdate_utils.cc index c6f1fa1e9..ba74c98e0 100644 --- a/omaha/common/goopdate_utils.cc +++ b/omaha/common/goopdate_utils.cc @@ -37,7 +37,6 @@ #include "omaha/base/scope_guard.h" #include "omaha/base/scoped_impersonation.h" #include "omaha/base/service_utils.h" -#include "omaha/base/signatures.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/system_info.h" @@ -1554,7 +1553,7 @@ HRESULT GetMacHashesViaNDIS(std::vector* mac_hashes) { } DWORD query = OID_802_3_PERMANENT_ADDRESS; - BYTE mac_address[6]; + char mac_address[6]; DWORD mac_size = sizeof(mac_address); if (!::DeviceIoControl(get(file_handle), IOCTL_NDIS_QUERY_GLOBAL_STATS, @@ -1570,11 +1569,11 @@ HRESULT GetMacHashesViaNDIS(std::vector* mac_hashes) { continue; } - std::vector mac_address_buffer(arraysize(mac_address)); - ::memcpy(&mac_address_buffer.front(), mac_address, arraysize(mac_address)); - CStringA hashed_mac_address; - Base64::Encode(mac_address_buffer, &hashed_mac_address, false); + Base64Escape(mac_address, + arraysize(mac_address), + &hashed_mac_address, + true); mac_hashes->push_back(AnsiToWideString(hashed_mac_address, hashed_mac_address.GetLength())); } diff --git a/omaha/common/goopdate_utils_unittest.cc b/omaha/common/goopdate_utils_unittest.cc index d9fd063de..7261e65d3 100644 --- a/omaha/common/goopdate_utils_unittest.cc +++ b/omaha/common/goopdate_utils_unittest.cc @@ -20,11 +20,12 @@ #include #include #include + #include #include +#include #include "omaha/base/app_util.h" -#include "omaha/base/atl_regexp.h" #include "omaha/base/browser_utils.h" #include "omaha/base/constants.h" #include "omaha/base/const_utils.h" @@ -896,17 +897,18 @@ TEST(GoopdateUtilsTest, GetOSInfo) { CString os_version = SystemInfo::GetKernel32OSVersion(); EXPECT_TRUE(!os_version.IsEmpty()); - const AtlRE major_minor_build = _T("{\\d+\\.\\d+\\.\\d+}"); + const std::wregex major_minor_build { _T("\\d+\\.\\d+\\.\\d+") }; - CString expected_os_version; - CString actual_os_version; - EXPECT_TRUE(AtlRE::PartialMatch(os_version, - major_minor_build, - &expected_os_version)); - EXPECT_TRUE(AtlRE::PartialMatch(os_version_getosinfo, - major_minor_build, - &actual_os_version)); - EXPECT_STREQ(expected_os_version, actual_os_version); + std::wcmatch expected_os_version; + EXPECT_TRUE(std::regex_search(os_version.GetString(), + expected_os_version, + major_minor_build)); + std::wcmatch actual_os_version; + EXPECT_TRUE(std::regex_search(os_version.GetString(), + actual_os_version, + major_minor_build)); + EXPECT_STREQ(expected_os_version.str(0).c_str(), + actual_os_version.str(0).c_str()); } class GoopdateUtilsRegistryProtectedTest : public testing::Test { @@ -1829,12 +1831,14 @@ TEST(GoopdateUtilsTest, GetMacHashesViaNDIS) { for (size_t i = 0; i < mac_hashes.size(); ++i) { CStringA mac_hash(WideToUtf8(mac_hashes[i])); - std::vector mac; - EXPECT_SUCCEEDED(Base64::Decode(mac_hash, &mac)); + CStringA mac; + ASSERT_GE(Base64Unescape(mac_hash, &mac), 0); CString mac_string; - for (size_t j = 0; j < mac.size(); ++j) { - mac_string.AppendFormat(_T("%s%02X"), j == 0 ? _T("") : _T(":"), mac[j]); + for (int j = 0; j < mac.GetLength(); ++j) { + // The cast to uint8 is necessary to prevent sign extension. + const uint8 octet = static_cast(mac[j]); + mac_string.AppendFormat(_T("%s%02X"), j == 0 ? _T("") : _T(":"), octet); } ExpectMacMatchViaWMI(mac_string); diff --git a/omaha/common/omaha_customization_unittest.cc b/omaha/common/omaha_customization_unittest.cc index b865f6109..bbe53cbad 100644 --- a/omaha/common/omaha_customization_unittest.cc +++ b/omaha/common/omaha_customization_unittest.cc @@ -65,26 +65,9 @@ TEST(OmahaCustomizationTest, Constants_BuildFiles) { EXPECT_TRUE(::IsEqualGUID(kProxyClsidIsUserGuid, kActualProxyClsidIsUserGuid)); - // VERSION file values. Only the relatively stable ones are tested. - // The versions may or may not match in non-Google Update builds. -#ifdef GOOGLE_UPDATE_BUILD - EXPECT_STREQ("9", ONECLICK_PLUGIN_VERSION_ANSI); - // TODO(omaha): Change the name to ANSI. - EXPECT_STREQ("3", UPDATE_PLUGIN_VERSION_ANSI); -#else - std::wcout << _T("Did not test version values.") << std::endl; -#endif - // Primary omaha_version_utils values. EXPECT_STREQ(_T("npGoogleOneClick"), ONECLICK_PLUGIN_NAME); EXPECT_STREQ(_T("npGoogleUpdate"), UPDATE_PLUGIN_NAME); - - // Filenames from omaha_version_utils. - EXPECT_STREQ( - _T("npGoogleOneClick") _T(ONECLICK_PLUGIN_VERSION_ANSI) _T(".dll"), - ONECLICK_PLUGIN_FILENAME); - EXPECT_STREQ(_T("npGoogleUpdate") _T(UPDATE_PLUGIN_VERSION_ANSI) _T(".dll"), - UPDATE_PLUGIN_FILENAME); } TEST(OmahaCustomizationTest, Constants_Names) { @@ -128,7 +111,6 @@ TEST(OmahaCustomizationTest, Constants_Filenames) { EXPECT_STREQ(_T("GoogleUpdateBroker.exe"), kOmahaBrokerFileName); EXPECT_STREQ(_T("GoogleUpdateCore.exe"), kOmahaCoreFileName); EXPECT_STREQ(_T("GoogleUpdateOnDemand.exe"), kOmahaOnDemandFileName); - EXPECT_STREQ(_T("GoogleUpdateWebPlugin.exe"), kOmahaWebPluginFileName); EXPECT_STREQ(_T("GoogleUpdateSetup.exe"), kOmahaMetainstallerFileName); EXPECT_STREQ(_T("GoogleUpdateComRegisterShell64.exe"), kOmahaCOMRegisterShell64); @@ -315,23 +297,6 @@ TEST(OmahaCustomizationTest, Constants_ScheduledTasks) { EXPECT_GU_STREQ(_T("GoogleUpdateTaskMachine"), kScheduledTaskNameMachinePrefix); // NOLINT } -TEST(OmahaCustomizationTest, Constants_Plugins) { - EXPECT_GU_STREQ(_T("Google.OneClickCtrl.") _T(ONECLICK_PLUGIN_VERSION_ANSI), - kOneClickProgId); - EXPECT_STREQ( - "application/x-vnd.google.oneclickctrl." ONECLICK_PLUGIN_VERSION_ANSI, - kOneClickPluginMimeTypeAnsi); -} - -TEST(OmahaCustomizationTest, Constants_HostCheck) { - EXPECT_EQ(5, arraysize(kSiteLockPatternStrings)); - EXPECT_STREQ(_T("^(gears)|(mail)|(tools)|(www)|(desktop)|(pack)|(chrome)|(drive)\\.google\\.com$"), kSiteLockPatternStrings[0]); // NOLINT - EXPECT_STREQ(_T("^www\\.google\\.(ad)|(bg)|(ca)|(cn)|(cz)|(de)|(es)|(fi)|(fr)|(gr)|(hr)|(hu)|(it)|(ki)|(kr)|(lt)|(lv)|(nl)|(no)|(pl)|(pt)|(ro)|(ru)|(sk)|(sg)|(sl)|(sr)|(vn)$"), kSiteLockPatternStrings[1]); // NOLINT - EXPECT_STREQ(_T("^www\\.google\\.co\\.(hu)|(id)|(il)|(it)|(jp)|(kr)|(th)|(uk)$"), kSiteLockPatternStrings[2]); // NOLINT - EXPECT_STREQ(_T("^www\\.google\\.com\\.(ar)|(au)|(br)|(cn)|(et)|(gr)|(hr)|(ki)|(lv)|(om)|(pl)|(pt)|(ru)|(sg)|(sv)|(tr)|(vn)$"), kSiteLockPatternStrings[3]); // NOLINT - EXPECT_STREQ(_T("^(www\\.)?chrome\\.com$"), kSiteLockPatternStrings[4]); -} - // // ConfigManager keys. // diff --git a/omaha/common/ping_test.cc b/omaha/common/ping_test.cc index 04d1ecf11..8177e5523 100644 --- a/omaha/common/ping_test.cc +++ b/omaha/common/ping_test.cc @@ -91,7 +91,7 @@ TEST_F(PingTest, BuildOmahaPing) { File::Remove(goopdate_utils::BuildGoogleUpdateExePath(false)); // User ping, missing shell. - Ping install_ping_no_shell(false, _T("session"), _T("oneclick")); + Ping install_ping_no_shell(false, _T("session"), _T("taggedmi")); install_ping_no_shell.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping_no_shell.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), @@ -121,7 +121,7 @@ TEST_F(PingTest, BuildOmahaPing) { true)); // User ping, 1.2.183.21 shell. - Ping install_ping_1_2_183_21(false, _T("session"), _T("oneclick")); + Ping install_ping_1_2_183_21(false, _T("session"), _T("taggedmi")); install_ping_1_2_183_21.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping_1_2_183_21.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), @@ -205,7 +205,7 @@ TEST_F(PingTest, BuildAppsPing) { } TEST_F(PingTest, DISABLED_SendString) { - CString request_string = _T(""); // NOLINT + CString request_string = _T(""); // NOLINT EXPECT_HRESULT_SUCCEEDED(Ping::SendString(false, HeadersVector(), request_string)); @@ -215,7 +215,7 @@ TEST_F(PingTest, DISABLED_SendString) { } TEST_F(PingTest, DISABLED_HandlePing) { - CString request_string = _T(""); // NOLINT + CString request_string = _T(""); // NOLINT CStringA request_string_utf8(WideToUtf8(request_string)); CStringA ping_string_utf8; @@ -244,7 +244,7 @@ TEST_F(PingTest, SendInProcess) { command_line_extra_args.language = _T("en"); // User ping. - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); install_ping.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), ping_event); @@ -325,7 +325,7 @@ TEST_F(PingTest, PersistAndSendPersistedPings) { command_line_extra_args.language = _T("en"); // User ping. - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); install_ping.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), ping_event); @@ -376,7 +376,7 @@ TEST_F(PingTest, DISABLED_SendUsingGoogleUpdate) { command_line_extra_args.language = _T("en"); // User ping and wait for completion. - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); install_ping.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), ping_event); @@ -389,7 +389,7 @@ TEST_F(PingTest, DISABLED_SendUsingGoogleUpdate) { TEST_F(PingTest, Send_Empty) { CommandLineExtraArgs command_line_extra_args; - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); EXPECT_EQ(S_FALSE, install_ping.Send(false)); } @@ -408,7 +408,7 @@ TEST_F(PingTest, DISABLED_Send) { command_line_extra_args.language = _T("en"); // User ping and wait for completion. - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); install_ping.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), ping_event); @@ -431,7 +431,7 @@ TEST_F(PingTest, DISABLED_SendFireAndForget) { command_line_extra_args.language = _T("en"); // User ping and do not wait for completion. - Ping install_ping(false, _T("unittest"), _T("oneclick")); + Ping install_ping(false, _T("unittest"), _T("taggedmi")); install_ping.LoadAppDataFromExtraArgs(command_line_extra_args); install_ping.BuildOmahaPing(_T("1.0.0.0"), _T("2.0.0.0"), ping_event); diff --git a/omaha/common/url_utils.cc b/omaha/common/url_utils.cc index f535e118a..827e8fd3a 100644 --- a/omaha/common/url_utils.cc +++ b/omaha/common/url_utils.cc @@ -25,9 +25,8 @@ HRESULT BuildQueryString(const std::vector& query_params, CString query_part; CString encoded_value; - for (std::vector::const_iterator scan = query_params.begin(); - scan != query_params.end(); ++scan) { - HRESULT hr = StringEscape(scan->second, false, &encoded_value); + for (auto const&[key, value] : query_params) { + HRESULT hr = StringEscape(value, false, &encoded_value); if (FAILED(hr)) { return hr; } @@ -35,7 +34,7 @@ HRESULT BuildQueryString(const std::vector& query_params, if (!query_part.IsEmpty()) { query_part.AppendChar(_T('&')); } - query_part.Append(scan->first); + query_part.Append(key); query_part.AppendChar(_T('=')); query_part.Append(encoded_value); } diff --git a/omaha/common/url_utils.h b/omaha/common/url_utils.h index 511cfa8d9..d1306b8fa 100644 --- a/omaha/common/url_utils.h +++ b/omaha/common/url_utils.h @@ -18,7 +18,7 @@ namespace omaha { -typedef std::pair QueryElement; +using QueryElement = std::pair; // Assembles the parameters in |query_params| into |query|, escaping the values // as appropriate. Returns S_OK on success, or a failure HRESULT otherwise. diff --git a/omaha/common/url_utils_unittest.cc b/omaha/common/url_utils_unittest.cc index a5887bcfb..b899cb1bb 100644 --- a/omaha/common/url_utils_unittest.cc +++ b/omaha/common/url_utils_unittest.cc @@ -24,11 +24,20 @@ namespace omaha { TEST(BuildQueryStringTest, Do) { std::vector params; - params.push_back(std::make_pair(_T("one"), _T("1"))); - params.push_back(std::make_pair(_T("2"), _T("two"))); + params.push_back(std::make_pair(L"one", L"1")); + params.push_back(std::make_pair(L"2", L"two")); CString query; EXPECT_HRESULT_SUCCEEDED(BuildQueryString(params, &query)); - EXPECT_STREQ(query, _T("one=1&2=two")); + EXPECT_STREQ(query, L"one=1&2=two"); +} + +TEST(BuildQueryStringTest, EncodesQueryElements) { + std::vector params; + params.push_back(std::make_pair(L"first", L" '`")); + params.push_back(std::make_pair(L"second", L"&=")); + CString query; + EXPECT_HRESULT_SUCCEEDED(BuildQueryString(params, &query)); + EXPECT_STREQ(query, L"first=%20'%60&second=%26="); } } // namespace omaha diff --git a/omaha/common/webplugin_utils.cc b/omaha/common/webplugin_utils.cc deleted file mode 100644 index d694016d0..000000000 --- a/omaha/common/webplugin_utils.cc +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/common/webplugin_utils.h" - -#include "omaha/base/app_util.h" -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/file.h" -#include "omaha/base/logging.h" -#include "omaha/base/path.h" -#include "omaha/base/safe_format.h" -#include "omaha/base/string.h" -#include "omaha/base/system.h" -#include "omaha/base/utils.h" -#include "omaha/base/xml_utils.h" -#include "omaha/common/command_line_builder.h" -#include "omaha/common/const_cmd_line.h" -#include "omaha/common/const_goopdate.h" -#include "omaha/common/goopdate_utils.h" -#include "omaha/common/lang.h" -#include "omaha/net/network_request.h" -#include "omaha/net/simple_request.h" - -namespace omaha { - -namespace webplugin_utils { - -HRESULT SanitizeExtraArgs(const CString& extra_args_in, - CString* extra_args_out) { - ASSERT1(extra_args_out); - - HRESULT hr = StringEscape(extra_args_in, true, extra_args_out); - if (FAILED(hr)) { - return hr; - } - - // Now we unescape a selective white-list of characters. - extra_args_out->Replace(_T("%3D"), _T("=")); - extra_args_out->Replace(_T("%26"), _T("&")); - extra_args_out->Replace(_T("%7B"), _T("{")); - extra_args_out->Replace(_T("%7D"), _T("}")); - extra_args_out->Replace(_T("%25"), _T("%")); - - return hr; -} - -HRESULT BuildWebPluginCommandLine(const CString& url_domain, - const CString& extra_args, - CString* final_cmd_line_args) { - ASSERT1(!extra_args.IsEmpty()); - ASSERT1(final_cmd_line_args); - - CORE_LOG(L2, (_T("[BuildWebPluginCommandLine][%s][%s]"), - url_domain, extra_args)); - - CString extra_args_sanitized; - HRESULT hr = webplugin_utils::SanitizeExtraArgs(extra_args, - &extra_args_sanitized); - if (FAILED(hr)) { - return hr; - } - - CommandLineBuilder install_builder(COMMANDLINE_MODE_INSTALL); - install_builder.set_extra_args(extra_args_sanitized); - CString cmd_line_args(install_builder.GetCommandLineArgs()); - - CString url_domain_encoded; - CString cmd_line_args_encoded; - hr = StringEscape(url_domain, true, &url_domain_encoded); - if (FAILED(hr)) { - return hr; - } - - hr = StringEscape(cmd_line_args, true, &cmd_line_args_encoded); - if (FAILED(hr)) { - return hr; - } - - CommandLineBuilder webplugin_builder(COMMANDLINE_MODE_WEBPLUGIN); - webplugin_builder.set_webplugin_url_domain(url_domain_encoded); - webplugin_builder.set_webplugin_args(cmd_line_args_encoded); - webplugin_builder.set_install_source(kCmdLineInstallSource_OneClick); - CString webplugin_cmd_line(webplugin_builder.GetCommandLineArgs()); - - CString cmd_line_web_plugin; - SafeCStringFormat(&cmd_line_web_plugin, _T("/%s"), kCmdLineWebPlugin); - - if (!String_StartsWith(webplugin_cmd_line, cmd_line_web_plugin, false)) { - return E_UNEXPECTED; - } - - *final_cmd_line_args = - webplugin_cmd_line.Mid(cmd_line_web_plugin.GetLength() + 1); - - CORE_LOG(L2, (_T("[BuildWebPluginCommandLine][%s]"), *final_cmd_line_args)); - return S_OK; -} - -HRESULT IsLanguageSupported(const CString& webplugin_args) { - CString cmd_line; - SafeCStringFormat(&cmd_line, _T("gu.exe %s"), webplugin_args); - CommandLineArgs parsed_args; - HRESULT hr = ParseCommandLine(cmd_line, &parsed_args); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[ParseCommandLine failed][0x%08x]"), hr)); - return hr; - } - - - if (!lang::IsLanguageSupported(parsed_args.extra.language)) { - CORE_LOG(LE, (_T("Language not supported][%s]"), - parsed_args.extra.language)); - return GOOPDATE_E_ONECLICK_LANGUAGE_NOT_SUPPORTED; - } - - return S_OK; -} - -HRESULT BuildOneClickWorkerArgs(const CommandLineArgs& args, - CString* oneclick_args) { - ASSERT1(oneclick_args); - - // Since this is being called via WebPlugin only, we can rebuild the - // command line arguments from the valid params we can send on. - // For example, the web plugin will not send crash_cmd or debug_cmd - // or reg_server or unreg_server so we don't have to worry about those here. - CString cmd_line_args; - CommandLineArgs webplugin_cmdline_args; - - // ParseCommandLine assumes the first argument is the program being run. - // Don't want to enforce that constraint on our callers, so we prepend with a - // fake exe name. - CString args_to_parse; - SafeCStringFormat(&args_to_parse, _T("%s %s"), - kOmahaShellFileName, - args.webplugin_args); - - // Parse the arguments we received as the second parameter to /webplugin. - HRESULT hr = ParseCommandLine(args_to_parse, &webplugin_cmdline_args); - if (FAILED(hr)) { - return hr; - } - - // Silent and other non-standard installs could be malicious. Prevent them. - if (webplugin_cmdline_args.mode != COMMANDLINE_MODE_INSTALL) { - return E_INVALIDARG; - } - if (webplugin_cmdline_args.is_silent_set || - webplugin_cmdline_args.is_eula_required_set) { - return E_INVALIDARG; - } - - CommandLineBuilder builder(COMMANDLINE_MODE_INSTALL); - builder.set_extra_args(webplugin_cmdline_args.extra_args_str); - - // We expect this value from the plugin. - ASSERT1(!args.install_source.IsEmpty()); - if (args.install_source.IsEmpty()) { - return E_INVALIDARG; - } - - builder.set_install_source(args.install_source); - - *oneclick_args = builder.GetCommandLineArgs(); - - return S_OK; -} - -// It is important that current_goopdate_path be the version path and not the -// Update\ path. -HRESULT CopyGoopdateToTempDir(const CPath& current_goopdate_path, - CPath* goopdate_temp_path) { - ASSERT1(goopdate_temp_path); - - // Create a unique directory in the user's temp directory. - GUID guid = GUID_NULL; - HRESULT hr = ::CoCreateGuid(&guid); - if (FAILED(hr)) { - return hr; - } - CString guid_str = GuidToString(guid); - ASSERT1(!guid_str.IsEmpty()); - - CString temp_dir = app_util::GetTempDir(); - ASSERT1(!temp_dir.IsEmpty()); - - CPath temp_path = temp_dir.GetString(); - temp_path.Append(guid_str); - temp_path.Canonicalize(); - - hr = CreateDir(temp_path, NULL); - if (FAILED(hr)) { - return hr; - } - - hr = File::CopyTree(current_goopdate_path, temp_path, true); - if (FAILED(hr)) { - return hr; - } - - CORE_LOG(L2, (_T("[CopyGoopdateToTempDir][temp_path = %s]"), temp_path)); - *goopdate_temp_path = temp_path; - return S_OK; -} - -HRESULT DoOneClickInstall(const CommandLineArgs& args) { - CString cmd_line_args; - HRESULT hr = BuildOneClickWorkerArgs(args, &cmd_line_args); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[BuildOneClickWorkerArgs failed][0x%08x]"), hr)); - return hr; - } - - CORE_LOG(L2, (_T("[DoOneClickInstall][cmd_line_args: %s]"), cmd_line_args)); - - // Check if we're running from the machine dir. - // If we're not, we must be running from user directory since OneClick only - // works against installed versions of Omaha. - CPath current_goopdate_path(app_util::GetCurrentModuleDirectory()); - CPath goopdate_temp_path; - hr = CopyGoopdateToTempDir(current_goopdate_path, &goopdate_temp_path); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[CopyGoopdateToTempDir failed][0x%08x]"), hr)); - return hr; - } - - CPath goopdate_temp_exe_path = goopdate_temp_path; - goopdate_temp_exe_path.Append(kOmahaShellFileName); - - // Launch goopdate again with the updated command line arguments. - hr = System::ShellExecuteProcess(goopdate_temp_exe_path, - cmd_line_args, - NULL, - NULL); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[ShellExecuteProcess failed][%s][0x%08x]"), - goopdate_temp_exe_path, hr)); - return hr; - } - - return S_OK; -} - -} // namespace webplugin_utils - -} // namespace omaha diff --git a/omaha/common/webplugin_utils.h b/omaha/common/webplugin_utils.h deleted file mode 100644 index 0281b80e7..000000000 --- a/omaha/common/webplugin_utils.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_COMMON_WEBPLUGIN_UTILS_H__ -#define OMAHA_COMMON_WEBPLUGIN_UTILS_H__ - -#include -#include -#include -#include "base/basictypes.h" -#include "omaha/common/command_line.h" -#include "omaha/common/config_manager.h" - -namespace omaha { - -namespace webplugin_utils { - -// This function escapes all unsafe characters, and then unescapes a selective -// white-list of characters: '=', '&', '{', '}', '%'. For a properly formatted -// extra args string, extra_args_out will be exactly equal to extra_args_in. -HRESULT SanitizeExtraArgs(const CString& extra_args_in, - CString* extra_args_out); - -// This function builds a sanitized /pi command line. -HRESULT BuildWebPluginCommandLine(const CString& url_domain, - const CString& extra_args, - CString* final_cmd_line_args); - -// Parses the arguments, extracts the language parameter, and verifies that we -// support the requested language. -HRESULT IsLanguageSupported(const CString& webplugin_args); - -// Copies required Goopdate files to a temp location before installing. -HRESULT CopyGoopdateToTempDir(const CPath& current_goopdate_path, - CPath* goopdate_temp_path); - -// Launches google_update.exe based on parameters sent with /webplugin. -HRESULT DoOneClickInstall(const CommandLineArgs& args); - -// Creates request string for the webplugin URL check webservice call. -HRESULT BuildOneClickRequestString(const CommandLineArgs& args, - CString* request_str); - -// Builds up the command line arguments to re-launch google_update.exe -// when called with /pi. -HRESULT BuildOneClickWorkerArgs(const CommandLineArgs& args, CString* args_out); - -} // namespace webplugin_utils - -} // namespace omaha - -#endif // OMAHA_COMMON_WEBPLUGIN_UTILS_H__ diff --git a/omaha/common/webplugin_utils_unittest.cc b/omaha/common/webplugin_utils_unittest.cc deleted file mode 100644 index 3737aa711..000000000 --- a/omaha/common/webplugin_utils_unittest.cc +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/app_util.h" -#include "omaha/base/error.h" -#include "omaha/base/file.h" -#include "omaha/base/path.h" -#include "omaha/base/utils.h" -#include "omaha/common/webplugin_utils.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -namespace webplugin_utils { - -#define YOUTUBEUPLOADEREN_TAG \ - _T("\"appguid={A4F7B07B-B9BD-4a33-B136-96D2ADFB60CB}&") \ - _T("appname=YouTubeUploader&needsadmin=False&lang=en\"") - - -TEST(WebPluginUtilsTest, SanitizeExtraArgs_Valid) { - CString extra_args = _T("appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google%20Chrome&needsadmin=true&lang=en"); - - CString escaped_extra_args; - EXPECT_SUCCEEDED(SanitizeExtraArgs(extra_args, &escaped_extra_args)); - EXPECT_STREQ(extra_args, escaped_extra_args); -} - -TEST(WebPluginUtilsTest, SanitizeExtraArgs_Invalid) { - CString extra_args = _T("\"appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=en\"") - _T(" /offline 1"); - - CString escaped_extra_args; - EXPECT_SUCCEEDED(SanitizeExtraArgs(extra_args, &escaped_extra_args)); - EXPECT_STREQ(_T("%22appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}&") - _T("appname=Google%20Chrome&needsadmin=true&lang=en%22") - _T("%20%2Foffline%201"), - escaped_extra_args); -} - -TEST(WebPluginUtilsTest, BuildWebPluginCommandLine_Valid) { - CString url_domain(_T("http://www.google.com/")); - CString extra_args = _T("appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google%20Chrome&needsadmin=true&lang=en"); - - CString final_cmd_line_args; - EXPECT_SUCCEEDED(BuildWebPluginCommandLine(url_domain, - extra_args, - &final_cmd_line_args)); - EXPECT_STREQ( - _T("\"http:%2F%2Fwww.google.com%2F\" \"%2Finstall%20%22appguid=") - _T("%7B8A69D345-D564-463c-AFF1-A69D9E530F96%7D%26appname=") - _T("Google%2520Chrome%26needsadmin=true%26lang=") - _T("en%22\" /installsource oneclick"), - final_cmd_line_args); -} - -TEST(WebPluginUtilsTest, BuildWebPluginCommandLine_Invalid) { - CString url_domain(_T("http://www.google.com/")); - CString extra_args = _T("\"appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=en\"") - _T(" /offline 1"); - - ExpectAsserts expect_asserts; - CString final_cmd_line_args; - EXPECT_SUCCEEDED(BuildWebPluginCommandLine(url_domain, - extra_args, - &final_cmd_line_args)); - EXPECT_STREQ( - _T("\"http:%2F%2Fwww.google.com%2F\" \"%2Finstall%20%22%2522appguid=") - _T("%7B8A69D345-D564-463c-AFF1-A69D9E530F96%7D%26appname=") - _T("Google%2520Chrome%26needsadmin=true%26lang=") - _T("en%2522%2520%252Foffline%25201%22\" /installsource oneclick"), - final_cmd_line_args); -} - -TEST(WebPluginUtilsTest, BuildOneClickWorkerArgs_Valid) { - CommandLineArgs args; - CString oneclick_args; - - args.install_source = _T("oneclick"); - args.webplugin_args = _T("/install \"appguid=") - _T("{8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=en\""); - EXPECT_EQ(S_OK, BuildOneClickWorkerArgs(args, &oneclick_args)); - - EXPECT_STREQ(_T("/install ") - _T("\"appguid={8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=en\" ") - _T("/installsource oneclick"), - oneclick_args); -} - -// This tests valid command line args that are not valid to be sent through -// to google_update.exe (e.g. /install). -TEST(WebPluginUtilsTest, BuildOneClickWorkerArgs_Invalid) { - CommandLineArgs args; - CString oneclick_args; - - args.install_source = _T("oneclick"); - - args.webplugin_args = _T("/handoff ") YOUTUBEUPLOADEREN_TAG; - EXPECT_EQ(E_INVALIDARG, BuildOneClickWorkerArgs(args, &oneclick_args)); - - args.webplugin_args = _T("/regserver"); - EXPECT_EQ(E_INVALIDARG, BuildOneClickWorkerArgs(args, &oneclick_args)); - - args.webplugin_args = _T("/unregserver"); - EXPECT_EQ(E_INVALIDARG, BuildOneClickWorkerArgs(args, &oneclick_args)); - - args.webplugin_args = _T("/install ") YOUTUBEUPLOADEREN_TAG _T(" /silent"); - EXPECT_EQ(E_INVALIDARG, BuildOneClickWorkerArgs(args, &oneclick_args)); -} - -TEST(WebPluginUtilsTest, CopyGoopdateToTempDir) { - CPath current_goopdate_path(app_util::GetCurrentModuleDirectory()); - current_goopdate_path.Append(_T("unittest_support\\omaha_1.3.x\\")); - CPath goopdate_temp_path; - ASSERT_SUCCEEDED(CopyGoopdateToTempDir(current_goopdate_path, - &goopdate_temp_path)); - - std::vector files; - EXPECT_HRESULT_SUCCEEDED(FindFilesEx(goopdate_temp_path, _T("*.*"), &files)); - - EXPECT_EQ(3, files.size()); - - std::map files_map; - for (size_t file_index = 0; file_index < files.size(); ++file_index) { - files_map[files[file_index]] = 1; - } - - EXPECT_TRUE(files_map.find(_T("GoogleUpdate.exe")) != files_map.end()); - EXPECT_TRUE(files_map.find(_T("goopdate.dll")) != files_map.end()); - EXPECT_TRUE(files_map.find(_T("goopdateres_en.dll")) != files_map.end()); - - EXPECT_HRESULT_SUCCEEDED(DeleteDirectory(goopdate_temp_path)); -} - -TEST(WebPluginUtilsTest, IsLanguageSupported_InvalidArgs) { - CString args = _T("/en"); - EXPECT_FAILED(IsLanguageSupported(args)); -} - -TEST(WebPluginUtilsTest, IsLanguageSupported_LangOK) { - CString args = _T("/install \"appguid=") - _T("{8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=en\""); - EXPECT_SUCCEEDED(IsLanguageSupported(args)); -} - -TEST(WebPluginUtilsTest, IsLanguageSupported_LangNotFound) { - CString args = _T("/install \"appguid=") - _T("{8A69D345-D564-463c-AFF1-A69D9E530F96}") - _T("&appname=Google Chrome&needsadmin=true&lang=zz\""); - - EXPECT_EQ(GOOPDATE_E_ONECLICK_LANGUAGE_NOT_SUPPORTED, - IsLanguageSupported(args)); -} - -} // namespace webplugin_utils - -} // namespace omaha - diff --git a/omaha/goopdate/app_command_ping_delegate.cc b/omaha/goopdate/app_command_ping_delegate.cc index d81071cd9..46bc1e8a0 100644 --- a/omaha/goopdate/app_command_ping_delegate.cc +++ b/omaha/goopdate/app_command_ping_delegate.cc @@ -71,7 +71,7 @@ void AppCommandPingDelegate::SendPing(PingEvent::Types type, PingEventPtr ping_event( new PingEvent(type, result, error_code, reporting_id_)); - Ping ping(is_machine_, session_id_, kCmdLineInstallSource_OneClick); + Ping ping(is_machine_, session_id_, CString()); std::vector apps; apps.push_back(app_guid_); ping.LoadAppDataFromRegistry(apps); diff --git a/omaha/goopdate/app_manager_unittest.cc b/omaha/goopdate/app_manager_unittest.cc index b1a47b924..b044ff53f 100644 --- a/omaha/goopdate/app_manager_unittest.cc +++ b/omaha/goopdate/app_manager_unittest.cc @@ -1485,8 +1485,6 @@ TEST_F(AppManagerTest, ConvertCommandLineToProductData_Succeeds) { args.is_crash_handler_disabled = true; // Not used. args.is_eula_required_set = true; args.is_eula_required_set = true; // Not used. - args.webplugin_urldomain = _T("http://nothing.google.com"); // Not used. - args.webplugin_args = _T("blah"); // Not used. args.install_source = _T("one_click"); args.code_red_metainstaller_path = _T("foo.exe"); // Not used. args.legacy_manifest_path = _T("bar.exe"); // Not used. diff --git a/omaha/goopdate/app_version.cc b/omaha/goopdate/app_version.cc index 21b145b4d..18125a2c5 100644 --- a/omaha/goopdate/app_version.cc +++ b/omaha/goopdate/app_version.cc @@ -21,7 +21,6 @@ #include "omaha/base/logging.h" #include "omaha/base/synchronized.h" #include "omaha/base/utils.h" -#include "omaha/goopdate/file_hash.h" #include "omaha/goopdate/model.h" namespace omaha { @@ -86,7 +85,11 @@ size_t AppVersion::GetNumberOfPackages() const { HRESULT AppVersion::AddPackage(const CString& filename, uint32 size, - const FileHash& hash) { + const CString& hash) { + if (hash.IsEmpty()) { + return E_INVALIDARG; + } + __mutexScope(model()->lock()); Package* package = new Package(this); package->SetFileInfo(filename, size, hash); @@ -145,7 +148,7 @@ STDMETHODIMP AppVersion::get_packageCount(long* count) { // NOLINT return E_FAIL; } - *count = static_cast(num_packages); + *count = static_cast(num_packages); // NOLINT return S_OK; } diff --git a/omaha/goopdate/app_version.h b/omaha/goopdate/app_version.h index 28dcf0831..bcf953e71 100644 --- a/omaha/goopdate/app_version.h +++ b/omaha/goopdate/app_version.h @@ -34,7 +34,6 @@ namespace omaha { class App; class AppBundle; class Package; -struct FileHash; class AppVersion : public ModelObject { public: @@ -64,7 +63,7 @@ class AppVersion : public ModelObject { // Adds a package to this app version. HRESULT AddPackage(const CString& filename, uint32 size, - const FileHash& expected_hash); + const CString& expected_hash); // Returns the list of download servers to use in order of preference. const std::vector& download_base_urls() const; @@ -74,7 +73,6 @@ class AppVersion : public ModelObject { HRESULT AddDownloadBaseUrl(const CString& server_url); private: - // product version "pv". CString version_; diff --git a/omaha/goopdate/build.scons b/omaha/goopdate/build.scons index 4359b79c2..1e4cd6b8c 100644 --- a/omaha/goopdate/build.scons +++ b/omaha/goopdate/build.scons @@ -76,7 +76,6 @@ def BuildCOMForwarder(cmd_line_switch, # Build the broker/legacy on-demand/WebPlugin forwarders. BuildCOMForwarder('/broker', 'GoogleUpdateBroker', False) BuildCOMForwarder('/ondemand', 'GoogleUpdateOnDemand', False) -BuildCOMForwarder('/pi', 'GoogleUpdateWebPlugin', True) def BuildCOMRegisterShell64(): com_register_shell_env = env.CloneAndMake64Bit() diff --git a/omaha/goopdate/crash_unittest.cc b/omaha/goopdate/crash_unittest.cc index dd97979a3..9d77cac3c 100644 --- a/omaha/goopdate/crash_unittest.cc +++ b/omaha/goopdate/crash_unittest.cc @@ -14,8 +14,9 @@ // ======================================================================== #include +#include + #include "omaha/base/app_util.h" -#include "omaha/base/atl_regexp.h" #include "omaha/base/constants.h" #include "omaha/base/const_addresses.h" #include "omaha/base/const_object_names.h" @@ -152,7 +153,7 @@ TEST_F(CrashReporterTest, DISABLED_Report_OmahaCrash) { // Tests sending an out-of-process crash. // This test will write an entry with the source "Chrome" in the Event Log. -// TODO(omaha): This test is disabled because it hangs on Zerg machines with +// TODO(omaha): This test is disabled because it hangs on machines with // network connectivity issues. A google_breakpad::RESULT_FAILED causes a 1 hour // ::Sleep(). TEST_F(CrashReporterTest, DISABLED_Report_ProductCrash) { @@ -184,9 +185,8 @@ TEST_F(CrashReporterTest, DISABLED_Report_ProductCrash) { const CString strings = GetLastCrashEventStrings(); // Verify that the strings include the Id token. - AtlRE crash_id_regex(_T("Id={\\h+}.")); - CString crash_id; - EXPECT_TRUE(AtlRE::PartialMatch(strings, crash_id_regex, &crash_id)); + const std::wregex crash_id_regex {_T("Id=[[:xdigit:]]+\\.")}; + EXPECT_TRUE(std::regex_search(strings.GetString(), crash_id_regex)); // The crash artifacts should be deleted after the crash is reported. EXPECT_FALSE(File::Exists(crash_filename)); diff --git a/omaha/goopdate/dm_client.cc b/omaha/goopdate/dm_client.cc index 835170de5..347d7bb49 100644 --- a/omaha/goopdate/dm_client.cc +++ b/omaha/goopdate/dm_client.cc @@ -26,6 +26,7 @@ #include "omaha/base/safe_format.h" #include "omaha/base/string.h" #include "omaha/base/system_info.h" +#include "omaha/base/utils.h" #include "omaha/common/config_manager.h" #include "omaha/common/goopdate_utils.h" #include "omaha/common/url_utils.h" @@ -64,6 +65,11 @@ HRESULT RegisterIfNeeded(DmStorage* dm_storage) { return S_FALSE; } + if (dm_storage->IsInvalidDMToken()) { + OPT_LOG(L1, (_T("[Cannot register since DM Token is invalid]"))); + return E_FAIL; + } + // No work to be done if a DM token was found. CStringA dm_token = dm_storage->GetDmToken(); if (!dm_token.IsEmpty()) { @@ -91,6 +97,8 @@ HRESULT RegisterIfNeeded(DmStorage* dm_storage) { device_id, &dm_token); if (FAILED(hr)) { + internal::HandleDMResponseError( + hr, ConfigManager::Instance()->GetPolicyResponsesDir()); return hr; } @@ -114,6 +122,11 @@ HRESULT RefreshPolicies() { } DmStorage* const dm_storage = DmStorage::Instance(); + if (dm_storage->IsInvalidDMToken()) { + REPORT_LOG(L1, (_T("[Skipping RefreshPolicies as DMToken is invalid]"))); + return E_FAIL; + } + const CString dm_token = CString(dm_storage->GetDmToken()); if (dm_token.IsEmpty()) { REPORT_LOG(L1, (_T("[Skipping RefreshPolicies as there is no DMToken]"))); @@ -144,6 +157,8 @@ HRESULT RefreshPolicies() { &responses); if (FAILED(hr)) { REPORT_LOG(LE, (_T("[FetchPolicies failed][%#x]"), hr)); + + internal::HandleDMResponseError(hr, policy_responses_dir); return hr; } @@ -283,6 +298,7 @@ HRESULT SendDeviceManagementRequest( // Create a network request and configure its headers. std::unique_ptr request( new NetworkRequest(network_config->session())); + request->AddHeader(_T("Content-Type"), kProtobufContentType); request->AddHeader(_T("Authorization"), authorization_header); // Set it up @@ -314,7 +330,7 @@ HRESULT SendDeviceManagementRequest( } const int http_status_code = request->http_status_code(); - if (http_status_code != 200) { + if (http_status_code != HTTP_STATUS_OK) { REPORT_LOG(LE, (_T("[NetworkRequest::Post failed][status code %d]"), http_status_code)); CStringA error_message; @@ -328,6 +344,18 @@ HRESULT SendDeviceManagementRequest( return S_OK; } +void HandleDMResponseError(HRESULT hr, const CPath& policy_responses_dir) { + if (hr != HRESULTFromHttpStatusCode(HTTP_STATUS_GONE)) { + REPORT_LOG(LE, (_T("Unexpected HTTP error from the DM Server[%#x]"), hr)); + return; + } + + // HTTP_STATUS_GONE implies that the device has been unenrolled. + // Invalidate the DM token and delete cached policies. + VERIFY1(SUCCEEDED(DmStorage::Instance()->InvalidateDMToken())); + DeleteBeforeOrAfterReboot(policy_responses_dir); +} + CString GetAgent() { CString agent; SafeCStringFormat(&agent, _T("%s %s()"), kAppName, GetVersionString()); diff --git a/omaha/goopdate/dm_client.h b/omaha/goopdate/dm_client.h index ad9dff790..d524df663 100644 --- a/omaha/goopdate/dm_client.h +++ b/omaha/goopdate/dm_client.h @@ -16,6 +16,7 @@ #define OMAHA_GOOPDATE_DM_CLIENT_H__ #include +#include #include #include #include @@ -32,6 +33,9 @@ namespace dm_client { // applications from the DMServer. const char kGoogleUpdateMachineLevelApps[] = "google/machine-level-apps"; +// The content-type for all protocol buffer requests. +const TCHAR kProtobufContentType[] = _T("application/protobuf"); + enum RegistrationState { // This client appears to not be managed. In particular, neither a device // management token nor an enrollment token can be found. @@ -79,6 +83,9 @@ HRESULT SendDeviceManagementRequest( const CString& device_id, std::vector> query_params, std::vector* response); + +void HandleDMResponseError(HRESULT hr, const CPath& policy_responses_dir); + CString GetAgent(); CString GetPlatform(); CStringA GetOsVersion(); diff --git a/omaha/goopdate/dm_client_unittest.cc b/omaha/goopdate/dm_client_unittest.cc index 3bb594368..4d04ceb91 100644 --- a/omaha/goopdate/dm_client_unittest.cc +++ b/omaha/goopdate/dm_client_unittest.cc @@ -27,7 +27,10 @@ #include "crypto/rsa_private_key.h" #include "crypto/signature_creator.h" #include "gtest/gtest-matchers.h" +#include "omaha/base/app_util.h" #include "omaha/base/constants.h" +#include "omaha/base/error.h" +#include "omaha/base/path.h" #include "omaha/base/scope_guard.h" #include "omaha/base/string.h" #include "omaha/common/config_manager.h" @@ -427,6 +430,17 @@ class DmClientRequestTest : public ::testing::Test { ON_CALL(**request, GetResponse()).WillByDefault(Return(response)); } + // Populates |request| with a mock HttpRequest that behaves as if the server + // returned a 410 HTTP response. + // Note: always wrap calls to this with ASSERT_NO_FATAL_FAILURE. + void MakeGoneHttpRequest(MockHttpRequest** request) { + *request = new ::testing::NiceMock(); + + // The server responds with 410. + ON_CALL(**request, GetHttpStatusCode()) + .WillByDefault(Return(HTTP_STATUS_GONE)); + } + struct KeyInfo { const std::unique_ptr& signing_private_key; const std::string& signing_public_key; @@ -475,7 +489,8 @@ class DmClientRequestTest : public ::testing::Test { // Expect that the request headers contain the DMToken. EXPECT_CALL(*mock_http_request, set_additional_headers( - CStringHasSubstr(_T("Authorization: GoogleDMToken ") + CStringHasSubstr(_T("Content-Type: application/protobuf") + _T("\r\nAuthorization: GoogleDMToken ") _T("token=dm_token")))); // Expect that the body of the request contains a well-formed fetch policies @@ -663,8 +678,10 @@ TEST_F(DmClientRequestTest, RegisterWithRequest) { // Expect that the request headers contain the enrollment token. EXPECT_CALL(*mock_http_request, set_additional_headers( - CStringHasSubstr(_T("Authorization: GoogleEnrollmentToken ") - _T("token=enrollment_token")))); + CStringHasSubstr(_T("Content-Type: application/protobuf\r\n") + _T("Authorization: GoogleEnrollmentToken ") + _T("token=57FEBE8F-48D0-487B-A788-") + _T("CF1019DCD452")))); // Expect that the body of the request contains a well-formed register browser // request. @@ -673,11 +690,26 @@ TEST_F(DmClientRequestTest, RegisterWithRequest) { // Registration should succeed, providing the expected DMToken. CStringA dm_token; - ASSERT_HRESULT_SUCCEEDED(internal::RegisterWithRequest(mock_http_request, - _T("enrollment_token"), - kDeviceId, - &dm_token)); + ASSERT_HRESULT_SUCCEEDED(internal::RegisterWithRequest( + mock_http_request, + _T("57FEBE8F-48D0-487B-A788-CF1019DCD452"), + kDeviceId, + &dm_token)); EXPECT_STREQ(dm_token.GetString(), kDmToken); + + // Test DM Token invalidation. + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + MockHttpRequest* mock_gone_request = nullptr; + ASSERT_NO_FATAL_FAILURE(MakeGoneHttpRequest(&mock_gone_request)); + + // Registration should fail. + ASSERT_EQ(internal::RegisterWithRequest( + mock_gone_request, + _T("57FEBE8F-48D0-487B-A788-CF1019DCD452"), + kDeviceId, + &dm_token), + HRESULTFromHttpStatusCode(HTTP_STATUS_GONE)); } // Test that DmClient can send a reasonable DevicePolicyRequest and handle a @@ -724,6 +756,21 @@ TEST_F(DmClientRequestTest, FetchPolicies) { // both the hard-coded verification key as well as with the previous private // key kSigningPrivateKey. RunFetchPolicies(new_signing_key_info, &info); + + // Test DM Token invalidation. + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + MockHttpRequest* mock_gone_request = nullptr; + ASSERT_NO_FATAL_FAILURE(MakeGoneHttpRequest(&mock_gone_request)); + + // Fetch Policies should fail. + PolicyResponses responses; + ASSERT_EQ(internal::FetchPolicies(mock_gone_request, + CString(kDmToken), + kDeviceId, + info, + &responses), + HRESULTFromHttpStatusCode(HTTP_STATUS_GONE)); } // Test that we are able to successfully encode and then decode a @@ -732,6 +779,34 @@ TEST_F(DmClientRequestTest, DecodePolicies) { DecodeOmahaPolicies(); } +TEST_F(DmClientRequestTest, HandleDMResponseError) { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_HRESULT_SUCCEEDED(DmStorage::Instance()->StoreDmToken("dm_token")); + + const CPath policy_responses_dir = CPath(ConcatenatePath( + app_util::GetCurrentModuleDirectory(), + _T("Policies"))); + PolicyResponsesMap responses = { + {"google/chrome/machine-level-user", "test-data-chr"}, + {"google/earth/machine-level-user", + "test-data-earth-foo-bar-baz-foo-bar-baz-foo-bar-baz"}, + }; + + PolicyResponses expected_responses = {responses, "expected data"}; + ASSERT_HRESULT_SUCCEEDED(DmStorage::PersistPolicies(policy_responses_dir, + expected_responses)); + + EXPECT_TRUE(policy_responses_dir.FileExists()); + EXPECT_FALSE(DmStorage::Instance()->IsInvalidDMToken()); + internal::HandleDMResponseError( + HRESULTFromHttpStatusCode(HTTP_STATUS_GONE), policy_responses_dir); + EXPECT_FALSE(policy_responses_dir.FileExists()); + EXPECT_TRUE(DmStorage::Instance()->IsInvalidDMToken()); + + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); +} + class DmClientRegistryTest : public RegistryProtectedTest { }; @@ -745,7 +820,8 @@ TEST_F(DmClientRegistryTest, GetRegistrationState) { // Enrollment token without device management token. { - EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(_T("enrollment_token"))); + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); ON_SCOPE_EXIT(DmStorage::DeleteInstance); EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kRegistrationPending); @@ -754,7 +830,8 @@ TEST_F(DmClientRegistryTest, GetRegistrationState) { // Enrollment token and device management token. ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("dm_token")); { - EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(_T("enrollment_token"))); + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); ON_SCOPE_EXIT(DmStorage::DeleteInstance); EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kRegistered); } @@ -765,6 +842,48 @@ TEST_F(DmClientRegistryTest, GetRegistrationState) { ON_SCOPE_EXIT(DmStorage::DeleteInstance); EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kRegistered); } + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("")); +} + +TEST_F(DmClientRegistryTest, RegisterIfNeeded) { + // Invalid DM token exists. + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kInvalidTokenValue)); + { + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(RegisterIfNeeded(DmStorage::Instance()), E_FAIL); + } + + // Valid DM token exists. + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("dm_token")); + { + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(RegisterIfNeeded(DmStorage::Instance()), S_FALSE); + } + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("")); +} + +TEST_F(DmClientRegistryTest, RefreshPolicies) { + // Invalid DM token exists. + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kInvalidTokenValue)); + { + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(RefreshPolicies(), E_FAIL); + } + + // No DM token. + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("")); + { + EXPECT_HRESULT_SUCCEEDED( + DmStorage::CreateInstance(_T("57FEBE8F-48D0-487B-A788-CF1019DCD452"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(RefreshPolicies(), S_FALSE); + } } TEST(DmClientTest, GetAgent) { diff --git a/omaha/goopdate/dm_messages.cc b/omaha/goopdate/dm_messages.cc index 0fcdd3dd1..d7bd214c6 100644 --- a/omaha/goopdate/dm_messages.cc +++ b/omaha/goopdate/dm_messages.cc @@ -14,14 +14,12 @@ #include "omaha/goopdate/dm_messages.h" -#include #include #include #include "crypto/signature_verifier_win.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" -#include "omaha/base/utils.h" #include "wireless/android/enterprise/devicemanagement/proto/dm_api.pb.h" #include "wireless/android/enterprise/devicemanagement/proto/omaha_settings.pb.h" diff --git a/omaha/goopdate/dm_messages.h b/omaha/goopdate/dm_messages.h index 6645fd9da..54b8475cf 100644 --- a/omaha/goopdate/dm_messages.h +++ b/omaha/goopdate/dm_messages.h @@ -16,6 +16,7 @@ #define OMAHA_GOOPDATE_DM_MESSAGES_H__ #include +#include #include #include #include @@ -23,6 +24,8 @@ #include #include "base/basictypes.h" +#include "omaha/base/safe_format.h" +#include "omaha/base/utils.h" #include "omaha/common/const_group_policy.h" namespace omaha { @@ -52,6 +55,17 @@ struct ApplicationSettings { int update = kUpdatePolicyDefault; CString target_version_prefix; bool rollback_to_target_version = false; + + CString ToString() const { + CString result(_T("[ApplicationSettings]")); + SafeCStringAppendFormat(&result, _T("[install][%d]"), install); + SafeCStringAppendFormat(&result, _T("[update][%d]"), update); + SafeCStringAppendFormat(&result, _T("[target_version_prefix][%s]"), + target_version_prefix); + SafeCStringAppendFormat(&result, _T("[rollback_to_target_version][%d]"), + rollback_to_target_version); + return result; + } }; struct GUIDCompare { @@ -73,6 +87,37 @@ struct CachedOmahaPolicy { int update_default = kUpdatePolicyDefault; std::map application_settings; + + CString ToString() const { + CString result(_T("[CachedOmahaPolicy]")); + SafeCStringAppendFormat(&result, + _T("[is_initialized][%d]"), is_initialized); + SafeCStringAppendFormat(&result, + _T("[auto_update_check_period_minutes][%" _T(PRId64) "]"), + auto_update_check_period_minutes); + SafeCStringAppendFormat(&result, + _T("[download_preference][%s]"), download_preference); + SafeCStringAppendFormat(&result, _T("[updates_suppressed]") + _T("[%" _T(PRId64) "][%" _T(PRId64) "][%" _T(PRId64) "]"), + updates_suppressed.start_hour, + updates_suppressed.start_minute, + updates_suppressed.duration_min); + SafeCStringAppendFormat(&result, _T("[proxy_mode][%s]"), proxy_mode); + SafeCStringAppendFormat(&result, _T("[proxy_server][%s]"), proxy_server); + SafeCStringAppendFormat(&result, _T("[proxy_pac_url][%s]"), proxy_pac_url); + SafeCStringAppendFormat(&result, _T("[install_default][%d]"), + install_default); + SafeCStringAppendFormat(&result, _T("[update_default][%d]"), + update_default); + + for (auto elem : application_settings) { + SafeCStringAppendFormat(&result, _T("[application_settings][%s][%s]"), + GuidToString(elem.first), + elem.second.ToString()); + } + + return result; + } }; HRESULT GetCachedPolicyInfo(const std::string& raw_response, diff --git a/omaha/goopdate/dm_storage.cc b/omaha/goopdate/dm_storage.cc index ded8d0dc1..1eb66b6c9 100644 --- a/omaha/goopdate/dm_storage.cc +++ b/omaha/goopdate/dm_storage.cc @@ -44,7 +44,7 @@ CString LoadEnrollmentTokenFromInstall() { kGoogleUpdateAppId), kRegValueCloudManagementEnrollmentToken, &value); - return SUCCEEDED(hr) ? value : CString(); + return (SUCCEEDED(hr) && IsUuid(value)) ? value : CString(); } // Returns an enrollment token provisioned to the computer via Group Policy, or @@ -63,7 +63,7 @@ CString LoadEnrollmentTokenFromLegacyPolicy() { HRESULT hr = RegKey::GetValue(kRegKeyLegacyGroupPolicy, kRegValueCloudManagementEnrollmentTokenPolicy, &value); - return SUCCEEDED(hr) ? value : CString(); + return (SUCCEEDED(hr) && IsUuid(value)) ? value : CString(); } // Returns an enrollment token provisioned to the computer via Group Policy for @@ -75,7 +75,7 @@ CString LoadEnrollmentTokenFromOldLegacyPolicy() { kRegKeyLegacyGroupPolicy, kRegValueMachineLevelUserCloudPolicyEnrollmentToken, &value); - return SUCCEEDED(hr) ? value : CString(); + return (SUCCEEDED(hr) && IsUuid(value)) ? value : CString(); } #endif // defined(HAS_LEGACY_DM_CLIENT) @@ -238,6 +238,22 @@ CStringA DmStorage::GetDmToken() { return dm_token_; } +bool DmStorage::IsValidDMToken() { + if (IsInvalidDMToken()) { + return false; + } + + return !GetDmToken().IsEmpty(); +} + +HRESULT DmStorage::InvalidateDMToken() { + return StoreDmToken(kInvalidTokenValue); +} + +bool DmStorage::IsInvalidDMToken() { + return GetDmToken() == kInvalidTokenValue; +} + HRESULT DmStorage::StoreDmToken(const CStringA& dm_token) { HRESULT hr = StoreDmTokenInKey(dm_token, kRegKeyCompanyEnrollment); if (SUCCEEDED(hr)) { @@ -313,6 +329,11 @@ HRESULT DmStorage::ReadCachedPolicyInfoFile(const CPath& policy_responses_dir, CachedPolicyInfo* info) { ASSERT1(info); + if (!DmStorage::Instance()->IsValidDMToken()) { + REPORT_LOG(L1, (_T("[Skip ReadCachedPolicyInfoFile DMToken not valid]"))); + return E_FAIL; + } + CPath policy_info_file(policy_responses_dir); policy_info_file.Append(kCachedPolicyInfoFileName); @@ -348,6 +369,11 @@ HRESULT DmStorage::ReadCachedOmahaPolicy(const CPath& policy_responses_dir, CachedOmahaPolicy* info) { ASSERT1(info); + if (!DmStorage::Instance()->IsValidDMToken()) { + REPORT_LOG(L1, (_T("[Skip ReadCachedOmahaPolicy DMToken not valid]"))); + return E_FAIL; + } + CStringA encoded_policy_response_dirname; Base64Escape(kGoogleUpdatePolicyType, arraysize(kGoogleUpdatePolicyType) - 1, @@ -387,9 +413,16 @@ HRESULT DmStorage::ReadCachedOmahaPolicy(const CPath& policy_responses_dir, } DmStorage::DmStorage(const CString& runtime_enrollment_token) - : runtime_enrollment_token_(runtime_enrollment_token), + : runtime_enrollment_token_(IsUuid(runtime_enrollment_token) ? + runtime_enrollment_token : + CString()), enrollment_token_source_(kETokenSourceNone), dm_token_source_(kDmTokenSourceNone) { + if (!IsUuid(runtime_enrollment_token)) { + REPORT_LOG(LE, (_T("[DmStorage::DmStorage]") + _T("[runtime_enrollment_token is not a guid][%s]"), + runtime_enrollment_token)); + } } void DmStorage::LoadEnrollmentTokenFromStorage() { diff --git a/omaha/goopdate/dm_storage.h b/omaha/goopdate/dm_storage.h index 65e976bd6..9925f1624 100644 --- a/omaha/goopdate/dm_storage.h +++ b/omaha/goopdate/dm_storage.h @@ -25,6 +25,10 @@ namespace omaha { +// This DM Token value is written into the registry if the server asks the +// client to invalidate the DM Token. +constexpr char kInvalidTokenValue[] = "INVALID_DM_TOKEN"; + // This is the standard name for the file that PersistPolicies() uses for each // {policy_type} that it receives from the DMServer. const TCHAR kPolicyResponseFileName[] = _T("PolicyFetchResponse"); @@ -82,6 +86,16 @@ class DmStorage { // one. Returns an empty string if no device management token is found. CStringA GetDmToken(); + // Returns true if the DM Token is valid, where valid is defined as non-blank + // and not invalidated. + bool IsValidDMToken(); + + // Writes |kInvalidTokenValue| into the registry. + HRESULT InvalidateDMToken(); + + // Returns true if the DM Token has been invalidated. + bool IsInvalidDMToken(); + // Writes |dm_token| into the registry. HRESULT StoreDmToken(const CStringA& dm_token); diff --git a/omaha/goopdate/dm_storage_test_utils.cc b/omaha/goopdate/dm_storage_test_utils.cc index 05d6da500..bc8f99b29 100644 --- a/omaha/goopdate/dm_storage_test_utils.cc +++ b/omaha/goopdate/dm_storage_test_utils.cc @@ -60,6 +60,14 @@ void WriteCompanyDmToken(const char* dm_token) { dm_token)); } +void DeleteDmToken() { + ASSERT_HRESULT_SUCCEEDED(RegKey::DeleteKey(kRegKeyCompanyEnrollment, true)); + +#if defined(HAS_LEGACY_DM_CLIENT) + ASSERT_HRESULT_SUCCEEDED(RegKey::DeleteKey(kRegKeyLegacyEnrollment, true)); +#endif +} + #if defined(HAS_LEGACY_DM_CLIENT) void WriteLegacyPolicyToken(const TCHAR* enrollment_token) { @@ -84,4 +92,4 @@ void WriteLegacyDmToken(const char* dm_token) { #endif // defined(HAS_LEGACY_DM_CLIENT) -} // namespace +} // namespace omaha diff --git a/omaha/goopdate/dm_storage_test_utils.h b/omaha/goopdate/dm_storage_test_utils.h index a191a03b6..e888c350c 100644 --- a/omaha/goopdate/dm_storage_test_utils.h +++ b/omaha/goopdate/dm_storage_test_utils.h @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#ifndef OMAHA_GOOPDATE_DM_STORAGE_TEST_UTILS_H_ +#define OMAHA_GOOPDATE_DM_STORAGE_TEST_UTILS_H_ + #include namespace omaha { @@ -23,6 +26,7 @@ namespace omaha { void WriteInstallToken(const TCHAR* enrollment_token); void WriteCompanyPolicyToken(const TCHAR* enrollment_token); void WriteCompanyDmToken(const char* dm_token); +void DeleteDmToken(); #if defined(HAS_LEGACY_DM_CLIENT) void WriteLegacyPolicyToken(const TCHAR* enrollment_token); @@ -31,3 +35,6 @@ void WriteLegacyDmToken(const char* dm_token); #endif // defined(HAS_LEGACY_DM_CLIENT) } // namespace omaha + +#endif // OMAHA_GOOPDATE_DM_STORAGE_TEST_UTILS_H_ + diff --git a/omaha/goopdate/dm_storage_unittest.cc b/omaha/goopdate/dm_storage_unittest.cc index 99e8a6b75..215193fe9 100644 --- a/omaha/goopdate/dm_storage_unittest.cc +++ b/omaha/goopdate/dm_storage_unittest.cc @@ -157,13 +157,18 @@ class DmStorageTest : public RegistryProtectedTest { } }; -const TCHAR DmStorageTest::kETRuntime[] = _T("runtime"); -const TCHAR DmStorageTest::kETInstall[] = _T("install"); -const TCHAR DmStorageTest::kETCompanyPolicy[] = _T("company_policy"); +const TCHAR DmStorageTest::kETRuntime[] = + _T("57FEBE8F-48D0-487B-A788-CF1019DCD452"); +const TCHAR DmStorageTest::kETInstall[] = + _T("075688CE-FECC-43DA-BBFB-228BF9C75758"); +const TCHAR DmStorageTest::kETCompanyPolicy[] = + _T("098BF4B2-361C-4855-900E-2FB967136C64"); const char DmStorageTest::kDmTCompany[] = "company"; #if defined(HAS_LEGACY_DM_CLIENT) -const TCHAR DmStorageTest::kETLegacyPolicy[] = _T("legacy_policy"); -const TCHAR DmStorageTest::kETOldLegacyPolicy[] = _T("old_legacy_policy"); +const TCHAR DmStorageTest::kETLegacyPolicy[] = + _T("55A78AF7-BA8F-4BE0-A93F-148093050293"); +const TCHAR DmStorageTest::kETOldLegacyPolicy[] = + _T("1FFFB822-E79B-4A8C-85B3-00DB4C7E3785"); const char DmStorageTest::kDmTLegacy[] = "legacy"; #endif // defined(HAS_LEGACY_DM_CLIENT) @@ -294,6 +299,7 @@ TEST_F(DmStorageTest, DmTokenFromCompany) { ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kDmTCompany)); std::unique_ptr dm_storage(NewDmStorage((CString()))); EXPECT_EQ(dm_storage->GetDmToken(), kDmTCompany); + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("")); } #if defined(HAS_LEGACY_DM_CLIENT) @@ -319,9 +325,14 @@ TEST_F(DmStorageTest, DmTokenPrecedence) { ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kDmTCompany)); std::unique_ptr dm_storage(NewDmStorage((CString()))); EXPECT_EQ(dm_storage->GetDmToken(), kDmTCompany); + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("")); } TEST_F(DmStorageTest, PersistPolicies) { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_HRESULT_SUCCEEDED(DmStorage::Instance()->StoreDmToken("dm_token")); + PolicyResponsesMap old_responses = { {"google/chrome/machine-level-user", "test-data-chrome"}, {"google/drive/machine-level-user", "test-data-drive"}, @@ -354,6 +365,36 @@ TEST_F(DmStorageTest, PersistPolicies) { policy_responses_dir, "google/drive/machine-level-user").FileExists()); EXPECT_HRESULT_SUCCEEDED(DeleteDirectory(policy_responses_dir)); + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); +} + +TEST_F(DmStorageTest, IsValidDMToken) { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); + + EXPECT_FALSE(DmStorage::Instance()->IsValidDMToken()); + + EXPECT_HRESULT_SUCCEEDED(DmStorage::Instance()->StoreDmToken("dm_token")); + EXPECT_TRUE(DmStorage::Instance()->IsValidDMToken()); + + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); +} + +TEST_F(DmStorageTest, IsInvalidDMToken) { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); + EXPECT_FALSE(DmStorage::Instance()->IsInvalidDMToken()); + EXPECT_HRESULT_SUCCEEDED(DmStorage::Instance()->StoreDmToken("dm_token")); + EXPECT_FALSE(DmStorage::Instance()->IsInvalidDMToken()); + + EXPECT_HRESULT_SUCCEEDED(DmStorage::Instance()->InvalidateDMToken()); + EXPECT_TRUE(DmStorage::Instance()->IsInvalidDMToken()); + + ASSERT_NO_FATAL_FAILURE(DeleteDmToken()); } // This test must access the true registry, so it doesn't use the DmStorageTest diff --git a/omaha/goopdate/download_manager_unittest.cc b/omaha/goopdate/download_manager_unittest.cc index b48503480..9035486ff 100644 --- a/omaha/goopdate/download_manager_unittest.cc +++ b/omaha/goopdate/download_manager_unittest.cc @@ -34,7 +34,6 @@ #include "omaha/goopdate/app_state_waiting_to_download.h" #include "omaha/goopdate/app_unittest_base.h" #include "omaha/goopdate/download_manager.h" -#include "omaha/goopdate/file_hash.h" #include "omaha/testing/unit_test.h" #include "omaha/third_party/smartany/scoped_any.h" @@ -45,24 +44,10 @@ namespace omaha { namespace { -const FileHash kUpdateBinHashSha1 = { - _T("YF2z/br/S6E3KTca0MT7qziJN44="), _T("") -}; -const FileHash kUpdateBinBothHashes = { - _T("YF2z/br/S6E3KTca0MT7qziJN44="), - _T("e5a00aa9991ac8a5ee3109844d84a55583bd20572ad3ffcd42792f3c36b183ad") -}; -const FileHash kUpdateBin1HashSha1 = { - _T("tbYInfmArVRUD62Ex292vN4LtGQ="), _T("") -}; -const FileHash kUpdateBin1BothHashes = { - _T("tbYInfmArVRUD62Ex292vN4LtGQ="), - _T("f955bdcb6611c4e3033cf5104e01c732001da4a79e23f7771fc6f0216195bd6e") -}; -const FileHash kUpdateBin1HashSha256 = { - _T(""), - _T("f955bdcb6611c4e3033cf5104e01c732001da4a79e23f7771fc6f0216195bd6e") -}; +const CString kUpdateBinHashSha256 = + _T("e5a00aa9991ac8a5ee3109844d84a55583bd20572ad3ffcd42792f3c36b183ad"); +const CString kUpdateBin1HashSha256 = + _T("f955bdcb6611c4e3033cf5104e01c732001da4a79e23f7771fc6f0216195bd6e"); const TCHAR kAppGuid1[] = _T("{0B35E146-D9CB-4145-8A91-43FDCAEBCD1E}"); const TCHAR kAppGuid2[] = _T("{C7F2B395-A01C-4806-AA07-9163F66AFC48}"); @@ -84,10 +69,6 @@ class DownloadAppWorkItem : public UserWorkItem { DISALLOW_COPY_AND_ASSIGN(DownloadAppWorkItem); }; -bool FileHashesEqual(const FileHash& hash1, const FileHash& hash2) { - return hash1.sha256 == hash2.sha256 && hash1.sha1 == hash2.sha1; -} - } // namespace class DownloadManagerTest : public AppTestBase { @@ -174,13 +155,13 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultiplePackagesInOneApp) { "" "" "" "" @@ -200,7 +181,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultiplePackagesInOneApp) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinBothHashes, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); EXPECT_LT(0, app->GetDownloadTimeMs()); @@ -210,7 +191,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultiplePackagesInOneApp) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData1.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); EXPECT_LT(0, app->GetDownloadTimeMs()); @@ -269,7 +250,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleApps) { "" "" "" "" "" @@ -308,7 +289,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleApps) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinBothHashes, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); EXPECT_LT(0, app->GetDownloadTimeMs()); @@ -323,7 +304,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleApps) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData1.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); EXPECT_LT(0, app->GetDownloadTimeMs()); @@ -358,7 +339,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Concurrent) { "" "" "" @@ -374,7 +355,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Concurrent) { "" "" "filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); @@ -448,7 +429,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Concurrent) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData1.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1BothHashes, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); @@ -654,7 +635,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleAppsCommonPackage) { "" "" "" @@ -670,7 +651,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleAppsCommonPackage) { "" "" "" @@ -692,7 +673,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleAppsCommonPackage) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); @@ -706,7 +687,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_MultipleAppsCommonPackage) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); } @@ -731,7 +712,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FileAlreadyInCache) { "" "" "" @@ -751,7 +732,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FileAlreadyInCache) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); EXPECT_LT(0, app->GetDownloadTimeMs()); @@ -778,7 +759,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FileAlreadyInCache) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); // No bytes are downloaded if the package has been cached already. EXPECT_EQ(0, package->bytes_downloaded()); @@ -804,7 +785,7 @@ TEST_F(DownloadManagerUserTest, DISABLED_DownloadApp_404) { "" "" "" @@ -824,18 +805,17 @@ TEST_F(DownloadManagerUserTest, DISABLED_DownloadApp_404) { ASSERT_TRUE(package); EXPECT_STREQ(_T("NoSuchFile-OmahaTest.exe"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(0, package->bytes_downloaded()); EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); } -TEST_F(DownloadManagerUserTest, DownloadApp_Sha1HashFailure) { +TEST_F(DownloadManagerUserTest, DownloadApp_FailWhenOnlySha1Hash) { App* app = NULL; ASSERT_SUCCEEDED(app_bundle_->createApp(CComBSTR(kAppGuid1), &app)); EXPECT_SUCCEEDED(app->put_displayName(CComBSTR(_T("Hash Fail")))); EXPECT_SUCCEEDED(app->put_isEulaAccepted(VARIANT_TRUE)); // Allow download. - // Provides the wrong hash for the package. CStringA buffer_string = "" @@ -848,7 +828,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Sha1HashFailure) { "" "" "" @@ -858,22 +838,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Sha1HashFailure) { "" ""; - EXPECT_HRESULT_SUCCEEDED(LoadBundleFromXml(app_bundle_.get(), buffer_string)); - SetAppStateWaitingToDownload(app); - - EXPECT_EQ(SIGS_E_INVALID_SIGNATURE, download_manager_->DownloadApp(app)); - - const Package* package = app->next_version()->GetPackage(0); - ASSERT_TRUE(package); - EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); - EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha1, package->expected_hash())); - EXPECT_EQ(2048, package->bytes_downloaded()); - EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); - - // All bytes were downloaded even if the validation of the file has failed. - EXPECT_EQ(2048, package->bytes_downloaded()); - EXPECT_LT(0, app->GetDownloadTimeMs()); + EXPECT_FAILED(LoadBundleFromXml(app_bundle_.get(), buffer_string)); } TEST_F(DownloadManagerUserTest, DownloadApp_Sha256HashFailure) { @@ -895,7 +860,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Sha256HashFailure) { "" "" "" @@ -914,7 +879,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Sha256HashFailure) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha256, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); @@ -942,7 +907,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_HashFailure_ActualSmaller) { "" "" "" @@ -962,7 +927,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_HashFailure_ActualSmaller) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048000, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); @@ -989,7 +954,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_HashFailure_ActualLarger) { "" "" "" @@ -1009,7 +974,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_HashFailure_ActualLarger) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(20, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBin1HashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBin1HashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); @@ -1038,7 +1003,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_BaseUrlFallback) { "" "" "" @@ -1056,7 +1021,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_BaseUrlFallback) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); } @@ -1082,7 +1047,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FallbackToNextUrlIfCachingFails) { "" "" "" @@ -1100,7 +1065,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FallbackToNextUrlIfCachingFails) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(2048, package->bytes_downloaded()); EXPECT_TRUE(download_manager_->IsPackageAvailable(package)); } @@ -1124,7 +1089,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_EulaNotAccepted) { "" "" "" @@ -1146,7 +1111,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_EulaNotAccepted) { ASSERT_TRUE(package); EXPECT_STREQ(_T("UpdateData.bin"), package->filename()); EXPECT_EQ(2048, package->expected_size()); - EXPECT_TRUE(FileHashesEqual(kUpdateBinHashSha1, package->expected_hash())); + EXPECT_STREQ(kUpdateBinHashSha256, package->expected_hash()); EXPECT_EQ(0, package->bytes_downloaded()); EXPECT_FALSE(download_manager_->IsPackageAvailable(package)); EXPECT_EQ(0, app->GetDownloadTimeMs()); @@ -1171,7 +1136,7 @@ TEST_F(DownloadManagerUserTest, GetPackage) { "" "" "" @@ -1203,7 +1168,7 @@ TEST_F(DownloadManagerUserTest, GetPackage) { CString filename(ConcatenatePath(dir, package->filename())); std::vector files; files.push_back(filename); - EXPECT_SUCCEEDED(VerifyFileHash(files, kUpdateBinHashSha1.sha1)); + EXPECT_SUCCEEDED(VerifyFileHashSha256(files, kUpdateBinHashSha256)); // Getting the package the second time overwrites the destination file // and succeeds. @@ -1230,7 +1195,7 @@ TEST_F(DownloadManagerUserTest, GetPackage_NotPresent) { "" "" "" diff --git a/omaha/goopdate/file_hash.h b/omaha/goopdate/file_hash.h deleted file mode 100644 index 756ef04b6..000000000 --- a/omaha/goopdate/file_hash.h +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_GOOPDATE_FILE_HASH_ -#define OMAHA_GOOPDATE_FILE_HASH_ - -#include -#include - -namespace omaha { - -// Representation of downloaded file hash values. -struct FileHash { - CString sha1; - CString sha256; -}; - -} // namespace omaha - -#endif // OMAHA_GOOPDATE_FILE_HASH_ diff --git a/omaha/goopdate/goopdate.cc b/omaha/goopdate/goopdate.cc index 9c7a92adc..e36e8719d 100644 --- a/omaha/goopdate/goopdate.cc +++ b/omaha/goopdate/goopdate.cc @@ -33,12 +33,10 @@ // /ua // * Core: // /c -// * Cod Red check: +// * Code Red check: // /cr -// * Cod Red repair: +// * Code Red repair: // /recover [/machine] -// * OneClick: -// /pi "http://www.google.com/" "/install%20%22appguid=%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26lang=en%26appname=Google%2520Chrome%26needsadmin=false" /installsource oneclick // NOLINT // * COM server: // -Embedding @@ -81,7 +79,6 @@ #include "omaha/common/oem_install_utils.h" #include "omaha/common/scheduled_task_utils.h" #include "omaha/common/stats_uploader.h" -#include "omaha/common/webplugin_utils.h" #include "omaha/core/core.h" #include "omaha/goopdate/code_red_check.h" #include "omaha/goopdate/crash.h" @@ -140,7 +137,6 @@ bool CheckRegisteredVersion(const CString& version, case COMMANDLINE_MODE_INSTALL: case COMMANDLINE_MODE_UPDATE: case COMMANDLINE_MODE_RECOVER: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_REGISTER_PRODUCT: case COMMANDLINE_MODE_UNREGISTER_PRODUCT: case COMMANDLINE_MODE_SERVICE_REGISTER: @@ -248,9 +244,6 @@ class GoopdateImpl { // Handles error conditions by showing UI if appropriate. void HandleError(HRESULT hr, bool has_ui_been_displayed); - // Handles response to /pi command. - HRESULT HandleWebPlugin(); - // Handles responses to /cr command. HRESULT HandleCodeRedCheck(); @@ -610,6 +603,12 @@ HRESULT GoopdateImpl::DoMain(HINSTANCE instance, // Continue because we want to load the resources and display an error. } +#if defined(HAS_DEVICE_MANAGEMENT) + // Reference the DmStorage instance here so the singleton can be created + // before use. + VERIFY1(SUCCEEDED(DmStorage::CreateInstance(args_.extra.enrollment_token))); +#endif + // TODO(omaha3): Interactive updates might be useful for debugging or even // on-demand updates of all apps. Figure out how to expose this. For now, no // install source, which should not happen normally, is used as the trigger. @@ -773,12 +772,6 @@ HRESULT GoopdateImpl::ExecuteMode(bool* has_ui_been_displayed) { VERIFY1(SUCCEEDED(SetBackgroundPriorityIfNeeded(mode))); -#if defined(HAS_DEVICE_MANAGEMENT) - // Reference the DmStorage instance here so the singleton can be created - // before use. - VERIFY1(SUCCEEDED(DmStorage::CreateInstance(args_.extra.enrollment_token))); -#endif - #pragma warning(push) // C4061: enumerator 'xxx' in switch of enum 'yyy' is not explicitly handled by // a case label. @@ -862,9 +855,6 @@ HRESULT GoopdateImpl::ExecuteMode(bool* has_ui_been_displayed) { NetworkConfigManager::Instance(); switch (mode) { - case COMMANDLINE_MODE_WEBPLUGIN: - return HandleWebPlugin(); - case COMMANDLINE_MODE_CODE_RED_CHECK: return HandleCodeRedCheck(); @@ -1001,7 +991,6 @@ bool GoopdateImpl::ShouldCheckShutdownEvent(CommandLineMode mode) { case COMMANDLINE_MODE_INSTALL: case COMMANDLINE_MODE_UPDATE: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_CODE_RED_CHECK: case COMMANDLINE_MODE_REGISTER_PRODUCT: case COMMANDLINE_MODE_UNREGISTER_PRODUCT: @@ -1074,7 +1063,6 @@ HRESULT GoopdateImpl::LoadResourceDllIfNecessary(CommandLineMode mode, case COMMANDLINE_MODE_UNREGSERVER: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_CODE_RED_CHECK: case COMMANDLINE_MODE_REGISTER_PRODUCT: case COMMANDLINE_MODE_UNREGISTER_PRODUCT: @@ -1152,19 +1140,6 @@ HRESULT GoopdateImpl::HandleCodeRedCheck() { return S_OK; } -// Even though http://b/1135173 is fixed, there is still a possibility that only -// some of the files will be copied if Setup is currently running. -// TODO(omaha3): If we save and use the metainstaller for OneClick, that may -// address this. - -// If we're called with the /webplugin command, we need to handle it and exit. -// This is called from the browser and the command line arguments come from the -// website so we need to be restrictive of what we let past. If everything from -// the plugin is valid, we'll relaunch goopdate with the proper commands. -HRESULT GoopdateImpl::HandleWebPlugin() { - return webplugin_utils::DoOneClickInstall(args_); -} - HRESULT GoopdateImpl::DoInstall(bool* has_ui_been_displayed) { OPT_LOG(L1, (_T("[GoopdateImpl::DoInstall]"))); ASSERT1(has_ui_been_displayed); @@ -1586,7 +1561,6 @@ bool GoopdateImpl::ShouldSetBackgroundPriority(CommandLineMode mode) { case COMMANDLINE_MODE_SERVICE_REGISTER: case COMMANDLINE_MODE_SERVICE_UNREGISTER: case COMMANDLINE_MODE_INSTALL: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_REGISTER_PRODUCT: case COMMANDLINE_MODE_UNREGISTER_PRODUCT: case COMMANDLINE_MODE_PING: @@ -1844,17 +1818,6 @@ bool IsMachineProcess(CommandLineMode mode, case COMMANDLINE_MODE_COMBROKER: return is_running_from_official_machine_directory; - // The following always runs as the user and is user-initiated. - case COMMANDLINE_MODE_WEBPLUGIN: - // The install location determines user vs. machine. - // This may not be the desired value when doing a cross-install or using - // the opposite plugin (i.e. user plugin is often used before the machine - // one). - ASSERT1(goopdate_utils::IsRunningFromOfficialGoopdateDir(false) || - goopdate_utils::IsRunningFromOfficialGoopdateDir(true) || - _T("omaha_unittest.exe") == app_util::GetCurrentModuleName()); - return is_running_from_official_machine_directory; - // The following all run silently as the user for user installs or Local // System for machine installs. case COMMANDLINE_MODE_UPDATE: @@ -1948,7 +1911,6 @@ bool CanDisplayUi(CommandLineMode mode, bool is_silent) { case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_UPDATE: case COMMANDLINE_MODE_RECOVER: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_CODE_RED_CHECK: case COMMANDLINE_MODE_COMSERVER: case COMMANDLINE_MODE_REGISTER_PRODUCT: diff --git a/omaha/goopdate/goopdate_unittest.cc b/omaha/goopdate/goopdate_unittest.cc index bca7d16af..c3d782688 100644 --- a/omaha/goopdate/goopdate_unittest.cc +++ b/omaha/goopdate/goopdate_unittest.cc @@ -727,7 +727,6 @@ static void EnsureUnitTestUpdatedWithNewModes() { case COMMANDLINE_MODE_HANDOFF_INSTALL: case COMMANDLINE_MODE_UA: case COMMANDLINE_MODE_RECOVER: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_CODE_RED_CHECK: case COMMANDLINE_MODE_COMSERVER: case COMMANDLINE_MODE_REGISTER_PRODUCT: @@ -774,7 +773,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_MachineDirOnly) { } EXPECT_FALSE(FromMachineDirHelper(COMMANDLINE_MODE_UA)); EXPECT_FALSE(FromMachineDirHelper(COMMANDLINE_MODE_RECOVER)); - EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_WEBPLUGIN)); EXPECT_FALSE(FromMachineDirHelper(COMMANDLINE_MODE_CODE_RED_CHECK)); EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_COMSERVER)); { @@ -822,7 +820,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_IsLocalSystemOnly) { } EXPECT_TRUE(IsLocalSystemHelper(COMMANDLINE_MODE_UA)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_RECOVER)); - EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_WEBPLUGIN)); EXPECT_TRUE(IsLocalSystemHelper(COMMANDLINE_MODE_CODE_RED_CHECK)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_COMSERVER)); { @@ -870,7 +867,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_MachineOverrideOnly) { } EXPECT_TRUE(MachineOverrideHelper(COMMANDLINE_MODE_UA)); EXPECT_TRUE(MachineOverrideHelper(COMMANDLINE_MODE_RECOVER)); - EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_WEBPLUGIN)); EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_CODE_RED_CHECK)); EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_COMSERVER)); { @@ -915,7 +911,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_NeedsAdminFalseOnly) { EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_HANDOFF_INSTALL)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_UA)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_RECOVER)); - EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_WEBPLUGIN)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_CODE_RED_CHECK)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_COMSERVER)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_REGISTER_PRODUCT)); @@ -954,7 +949,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_NeedsAdminTrueOnly) { EXPECT_TRUE(NeedsAdminTrueHelper(COMMANDLINE_MODE_HANDOFF_INSTALL)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_UA)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_RECOVER)); - EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_WEBPLUGIN)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_CODE_RED_CHECK)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_COMSERVER)); EXPECT_TRUE(NeedsAdminTrueHelper(COMMANDLINE_MODE_REGISTER_PRODUCT)); diff --git a/omaha/goopdate/install_manager_unittest.cc b/omaha/goopdate/install_manager_unittest.cc index ddc17e6ea..a98a17d51 100644 --- a/omaha/goopdate/install_manager_unittest.cc +++ b/omaha/goopdate/install_manager_unittest.cc @@ -97,13 +97,6 @@ const TCHAR kMsiLogFormat[] = _T("%s.log"); // LastCheckSuccess are automatically populated. const int kNumAutoPopulatedValues = 7; -FileHash CreateFileHash(const CString& sha1, const CString& sha256) { - FileHash hash; - hash.sha1 = sha1; - hash.sha256 = sha256; - return hash; -} - } // namespace // Values and functions in installer_wrapper_unittest.cc. @@ -407,8 +400,7 @@ TEST_F(InstallManagerInstallAppUserTest, TEST_F(InstallManagerInstallAppUserTest, InstallApp_InstallerWithoutFilenameExtension) { - app_->next_version()->AddPackage( - _T("foo"), 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("foo"), 100, _T("sha256hash")); // TODO(omaha): We should be able to eliminate this. SetArgumentsInManifest(CString(), _T("1.2.3.4"), app_); @@ -429,8 +421,7 @@ TEST_F(InstallManagerInstallAppUserTest, TEST_F(InstallManagerInstallAppUserTest, InstallApp_UnsupportedInstallerFilenameExtension) { - app_->next_version()->AddPackage( - _T("foo.bar"), 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("foo.bar"), 100, _T("sha256hash")); // TODO(omaha): We should be able to eliminate this. SetArgumentsInManifest(CString(), _T("1.2.3.4"), app_); @@ -453,8 +444,7 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_InstallerEmtpyFilename) { // Package asserts that the filename and file path are not NULL. ExpectAsserts expect_asserts; - app_->next_version()->AddPackage( - _T(""), 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T(""), 100, _T("sha256hash")); // This test does not call // app_->next_version()->GetPackage(0)->set_local_file_path(). @@ -492,8 +482,7 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_NoPackage) { } TEST_F(InstallManagerInstallAppUserTest, InstallApp_ExeFileDoesNotExist) { - app_->next_version()->AddPackage( - _T("foo.exe"), 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("foo.exe"), 100, _T("sha256hash")); // TODO(omaha): We should be able to eliminate this. SetArgumentsInManifest(CString(), _T("1.2.3.4"), app_); @@ -546,8 +535,7 @@ TEST_F(InstallManagerInstallAppUserTest, kRegValueProductVersion, _T("0.10.69.5"))); - app_->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Exe App")))); SetArgumentsInManifest(arguments, _T("0.10.69.5"), app_); @@ -586,8 +574,7 @@ TEST_F(InstallManagerInstallAppUserTest, kRegValueProductVersion, _T("0.10.69.5"))); - app_->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); SetArgumentsInManifest(arguments, _T("0.10.69.5"), app_); @@ -641,9 +628,9 @@ TEST_F(InstallManagerInstallAppMachineTest, InstallApp_MsiInstallerSucceeds) { EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); // TODO(omaha): This should be just a filename. - app_->next_version()->AddPackage( - kSetupFooV1RelativeLocation, - 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kSetupFooV1RelativeLocation, + 100, + _T("sha256hash")); app_->set_app_guid(StringToGuid(kFooId)); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Foo")))); EXPECT_SUCCEEDED(app_->put_iid(CComBSTR(kIid))); @@ -728,9 +715,9 @@ TEST_F(InstallManagerInstallAppMachineTest, EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); // TODO(omaha): This should be just a filename. - app_->next_version()->AddPackage( - kSetupFooV1RelativeLocation, - 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kSetupFooV1RelativeLocation, + 100, + _T("sha256hash")); app_->set_app_guid(StringToGuid(kFooId)); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Foo")))); @@ -782,9 +769,9 @@ TEST_F(InstallManagerInstallAppMachineTest, TEST_F(InstallManagerInstallAppUserTest, InstallApp_UpdateOmahaSucceeds) { const CString kExistingVersion(_T("0.9.69.5")); - app_->next_version()->AddPackage( - _T("SaveArguments.exe"), - 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("SaveArguments.exe"), + 100, + _T("sha256hash")); app_->set_app_guid(StringToGuid(kGoogleUpdateAppId)); // TODO(omaha3): This isn't supported yet. @@ -827,9 +814,9 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_UpdateOmahaSucceedsWhenClientsKeyAbsent) { const CString kExistingVersion(_T("0.9.69.5")); - app_->next_version()->AddPackage( - _T("SaveArguments.exe"), - 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("SaveArguments.exe"), + 100, + _T("sha256hash")); app_->set_app_guid(StringToGuid(kGoogleUpdateAppId)); // TODO(omaha3): This isn't supported yet. @@ -859,8 +846,7 @@ TEST_F(InstallManagerInstallAppUserTest, CString arguments; arguments.Format(kExecuteCommandAndTerminateSwitch, _T("")); - app_->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T(""))); + app_->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Some App")))); SetArgumentsInManifest(arguments, _T("5.6.7.8"), app_); @@ -898,8 +884,7 @@ TEST_F(InstallManagerInstallAppUserTest, ASSERT_SUCCEEDED(File::Remove(log_path)); ASSERT_FALSE(File::Exists(log_path)); - app_->next_version()->AddPackage( - _T("foo.msi"), 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(_T("foo.msi"), 100, _T("sha256hash")); // TODO(omaha): We should be able to eliminate this. SetArgumentsInManifest(CString(), _T("1.2.3.4"), app_); @@ -942,8 +927,7 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_MsiIsBusy_NoRetries) { CString arguments; arguments.Format(kExecuteCommandAndTerminateSwitch, commands); - app_->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Some App")))); SetArgumentsInManifest(arguments, _T("1.2.3.4"), app_); @@ -996,8 +980,7 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_InstallMultipleApps) { kRegValueProductVersion, _T("0.10.69.5"))); - app_->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app_->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); EXPECT_SUCCEEDED(app_->put_displayName(CComBSTR(_T("Exe App")))); SetArgumentsInManifest(arguments1, _T("0.10.69.5"), app_); @@ -1028,8 +1011,7 @@ TEST_F(InstallManagerInstallAppUserTest, InstallApp_InstallMultipleApps) { kRegValueProductVersion, _T("0.10.69.5"))); - app2->next_version()->AddPackage( - kCmdExecutable, 100, CreateFileHash(_T("hash"), _T("sha256hash"))); + app2->next_version()->AddPackage(kCmdExecutable, 100, _T("sha256hash")); EXPECT_SUCCEEDED(app2->put_displayName(CComBSTR(_T("Exe App")))); SetArgumentsInManifest(arguments2, _T("0.10.69.5"), app2); diff --git a/omaha/goopdate/ondemand.h b/omaha/goopdate/ondemand.h index ced0ed09d..3fa33bf08 100644 --- a/omaha/goopdate/ondemand.h +++ b/omaha/goopdate/ondemand.h @@ -31,6 +31,7 @@ #include "omaha/base/scope_guard.h" #include "omaha/base/synchronized.h" #include "omaha/base/thread_pool_callback.h" +#include "omaha/base/user_rights.h" #include "omaha/base/utils.h" #include "omaha/common/const_goopdate.h" #include "omaha/goopdate/com_proxy.h" diff --git a/omaha/goopdate/package.cc b/omaha/goopdate/package.cc index 5a504a537..c1ded7c9d 100644 --- a/omaha/goopdate/package.cc +++ b/omaha/goopdate/package.cc @@ -122,12 +122,12 @@ void Package::OnRequestRetryScheduled(time64 next_download_retry_time) { void Package::SetFileInfo(const CString& filename, uint64 size, - const FileHash& expected_hash) { + const CString& expected_hash) { __mutexScope(model()->lock()); ASSERT1(!filename.IsEmpty()); ASSERT1(0 < size); - ASSERT1(!expected_hash.sha256.IsEmpty() ||!expected_hash.sha1.IsEmpty()); + ASSERT1(!expected_hash.IsEmpty()); filename_ = filename; expected_size_ = size; @@ -145,9 +145,9 @@ uint64 Package::expected_size() const { return expected_size_; } -FileHash Package::expected_hash() const { +CString Package::expected_hash() const { __mutexScope(model()->lock()); - ASSERT1(!expected_hash_.sha256.IsEmpty() ||!expected_hash_.sha1.IsEmpty()); + ASSERT1(!expected_hash_.IsEmpty()); return expected_hash_; } diff --git a/omaha/goopdate/package.h b/omaha/goopdate/package.h index dd551414d..f3c9c4368 100644 --- a/omaha/goopdate/package.h +++ b/omaha/goopdate/package.h @@ -29,7 +29,6 @@ #include "omaha/base/time.h" #include "omaha/common/progress_sampler.h" #include "omaha/goopdate/com_wrapper_creator.h" -#include "omaha/goopdate/file_hash.h" #include "omaha/goopdate/model_object.h" // TODO(omaha): Consider implementing the NetworkRequestCallback portion in a // PImpl or similar pattern. As it is, every file that includes model.h also @@ -60,14 +59,14 @@ class Package virtual void OnRequestBegin(); virtual void OnRequestRetryScheduled(time64 next_download_retry_time); - void SetFileInfo(const CString& filename, uint64 size, const FileHash& hash); + void SetFileInfo(const CString& filename, uint64 size, const CString& hash); // Returns the name of the file specified in the manifest. CString filename() const; // Returns the expected size of the file in bytes. uint64 expected_size() const; // Returns expected file hashes. - FileHash expected_hash() const; + CString expected_hash() const; uint64 bytes_downloaded() const; @@ -85,7 +84,7 @@ class Package // The name of the package as it appears in the manifest. CString filename_; uint64 expected_size_; - FileHash expected_hash_; + CString expected_hash_; int bytes_downloaded_; int bytes_total_; @@ -108,7 +107,6 @@ class ATL_NO_VTABLE PackageWrapper kMajorTypeLibVersion, kMinorTypeLibVersion> { public: - // IPackage. STDMETHOD(get)(BSTR dir); STDMETHOD(get_isAvailable)(VARIANT_BOOL* is_available); diff --git a/omaha/goopdate/package_cache.cc b/omaha/goopdate/package_cache.cc index 2fa8ac49d..06b2d7bf1 100644 --- a/omaha/goopdate/package_cache.cc +++ b/omaha/goopdate/package_cache.cc @@ -29,7 +29,6 @@ #include "omaha/base/signaturevalidator.h" #include "omaha/base/utils.h" #include "omaha/common/config_manager.h" -#include "omaha/goopdate/file_hash.h" #include "omaha/goopdate/package_cache_internal.h" #include "omaha/goopdate/worker_metrics.h" @@ -142,10 +141,6 @@ void SortPackageInfoByTime(std::vector* packages_info) { PackageSortByTimePredicate); } -CString GetHashString(const FileHash& hash) { - return hash.sha256.IsEmpty() ? hash.sha1 : hash.sha256; -} - } // namespace internal PackageCache::PackageCache() { @@ -179,9 +174,9 @@ HRESULT PackageCache::Initialize(const CString& cache_root) { return S_OK; } -bool PackageCache::IsCached(const Key& key, const FileHash& hash) const { +bool PackageCache::IsCached(const Key& key, const CString& hash) const { CORE_LOG(L3, (_T("[PackageCache::IsCached][key '%s'][hash %s]"), - key.ToString(), internal::GetHashString(hash))); + key.ToString(), hash)); __mutexScope(cache_lock_); @@ -196,10 +191,10 @@ bool PackageCache::IsCached(const Key& key, const FileHash& hash) const { HRESULT PackageCache::Put(const Key& key, const CString& source_file, - const FileHash& hash) { + const CString& hash) { ++metric_worker_package_cache_put_total; CORE_LOG(L3, (_T("[PackageCache::Put][key '%s'][source_file '%s'][hash %s]"), - key.ToString(), source_file, internal::GetHashString(hash))); + key.ToString(), source_file, hash)); __mutexScope(cache_lock_); @@ -238,7 +233,7 @@ HRESULT PackageCache::Put(const Key& key, if (FAILED(hr)) { CORE_LOG(LE, (_T("[failed to verify hash for file '%s'][expected hash %s]"), - destination_file, internal::GetHashString(hash))); + destination_file, hash)); VERIFY1(::DeleteFile(destination_file)); return hr; } @@ -249,9 +244,9 @@ HRESULT PackageCache::Put(const Key& key, HRESULT PackageCache::Get(const Key& key, const CString& destination_file, - const FileHash& hash) const { + const CString& hash) const { CORE_LOG(L3, (_T("[PackageCache::Get][key '%s'][dest file '%s'][hash '%s']"), - key.ToString(), destination_file, internal::GetHashString(hash))); + key.ToString(), destination_file, hash)); __mutexScope(cache_lock_); @@ -274,7 +269,7 @@ HRESULT PackageCache::Get(const Key& key, hr = VerifyHash(source_file, hash); if (FAILED(hr)) { CORE_LOG(LE, (_T("[failed to verify hash for file '%s'][expected hash %s]"), - source_file, internal::GetHashString(hash))); + source_file, hash)); return hr; } @@ -485,19 +480,17 @@ HRESULT PackageCache::BuildCacheFileName(const CString& app_id, } HRESULT PackageCache::VerifyHash(const CString& filename, - const FileHash& expected_hash) { + const CString& expected_hash) { CORE_LOG(L3, (_T("[PackageCache::VerifyHash][%s][%s]"), - filename, internal::GetHashString(expected_hash))); + filename, expected_hash)); HighresTimer verification_timer; std::vector files; files.push_back(filename); - HRESULT hr = expected_hash.sha256.IsEmpty() ? - VerifyFileHash(files, expected_hash.sha1) : - VerifyFileHashSha256(files, expected_hash.sha256); + + HRESULT hr = VerifyFileHashSha256(files, expected_hash); CORE_LOG(L3, (_T("[PackageCache::VerifyHash completed][0x%08x][%d ms]"), hr, verification_timer.GetElapsedMs())); - return hr; } diff --git a/omaha/goopdate/package_cache.h b/omaha/goopdate/package_cache.h index b1352ad74..2ffb2a00f 100644 --- a/omaha/goopdate/package_cache.h +++ b/omaha/goopdate/package_cache.h @@ -25,8 +25,6 @@ namespace omaha { -struct FileHash; - class PackageCache { public: // Defines the key that uniquely identifies the packages in the cache. @@ -67,13 +65,13 @@ class PackageCache { HRESULT Put(const Key& key, const CString& source_file, - const FileHash& hash); + const CString& hash); HRESULT Get(const Key& key, const CString& destination_file, - const FileHash& hash) const; + const CString& hash) const; - bool IsCached(const Key& key, const FileHash& hash) const; + bool IsCached(const Key& key, const CString& hash) const; HRESULT Purge(const Key& key); @@ -98,7 +96,7 @@ class PackageCache { CString cache_root() const; static HRESULT VerifyHash(const CString& filename, - const FileHash& expected_hash); + const CString& expected_hash); private: friend class PackageCacheTest; diff --git a/omaha/goopdate/package_cache_unittest.cc b/omaha/goopdate/package_cache_unittest.cc index 1c4fb2728..f120dbcc7 100644 --- a/omaha/goopdate/package_cache_unittest.cc +++ b/omaha/goopdate/package_cache_unittest.cc @@ -20,7 +20,6 @@ #include "omaha/base/safe_format.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" -#include "omaha/goopdate/file_hash.h" #include "omaha/goopdate/package_cache.h" #include "omaha/testing/unit_test.h" @@ -28,10 +27,8 @@ namespace omaha { namespace { -const TCHAR* kFile1Sha1Hash = _T("ImV9skETZqGFMjs32vbZTvzAYJU="); const TCHAR* kFile1Sha256Hash = _T("49b45f78865621b154fa65089f955182345a67f9746841e43e2d6daa288988d0"); -const TCHAR* kFile2Sha1Hash = _T("Igq6bYaeXFJCjH770knXyJ6V53s="); const TCHAR* kFile2Sha256Hash = _T("f0bbd84d7ec364f6c33161d781b49d840ed792b8b10668c4180b9e6e128d0bc9"); @@ -53,20 +50,14 @@ class PackageCacheTest : public testing::TestWithParam { executable_path, _T("unittest_support\\download_cache_test\\") _T("{89640431-FE64-4da8-9860-1A1085A60E13}\\gears-win32-opt.msi")); - hash_file1_.sha1 = kFile1Sha1Hash; - if (GetParam()) { - hash_file1_.sha256 = kFile1Sha256Hash; - } + hash_file1_ = kFile1Sha256Hash; size_file1_ = 870400; source_file2_ = ConcatenatePath( executable_path, _T("unittest_support\\download_cache_test\\") _T("{7101D597-3481-4971-AD23-455542964072}\\livelysetup.exe")); - hash_file2_.sha1 = kFile2Sha1Hash; - if (GetParam()) { - hash_file2_.sha256 = kFile2Sha256Hash; - } + hash_file2_ = kFile2Sha256Hash; size_file2_ = 479848; EXPECT_TRUE(File::Exists(source_file1_)); @@ -119,38 +110,38 @@ class PackageCacheTest : public testing::TestWithParam { const CString cache_root_; CString source_file1_; - FileHash hash_file1_; + CString hash_file1_; uint64 size_file1_; CString source_file2_; - FileHash hash_file2_; + CString hash_file2_; uint64 size_file2_; PackageCache package_cache_; }; // Tests the members of key when the constructor arguments are empty strings. -TEST_P(PackageCacheTest, DefaultVersion) { +TEST_F(PackageCacheTest, DefaultVersion) { Key key(_T(""), _T(""), _T("")); EXPECT_STREQ(_T(""), key.app_id()); EXPECT_STREQ(_T("0.0.0.0"), key.version()); EXPECT_STREQ(_T(""), key.package_name()); } -TEST_P(PackageCacheTest, Initialize) { +TEST_F(PackageCacheTest, Initialize) { EXPECT_FALSE(package_cache_.cache_root().IsEmpty()); EXPECT_STREQ(cache_root_, package_cache_.cache_root()); EXPECT_EQ(0, package_cache_.Size()); } -TEST_P(PackageCacheTest, InitializeErrors) { +TEST_F(PackageCacheTest, InitializeErrors) { PackageCache package_cache; EXPECT_EQ(E_INVALIDARG, package_cache.Initialize(NULL)); EXPECT_EQ(E_INVALIDARG, package_cache.Initialize(_T(""))); EXPECT_EQ(E_INVALIDARG, package_cache.Initialize(_T("foo"))); } -TEST_P(PackageCacheTest, BuildCacheFileName) { +TEST_F(PackageCacheTest, BuildCacheFileName) { CString actual; EXPECT_HRESULT_SUCCEEDED( BuildCacheFileNameForKey(Key(_T("1"), _T("2"), _T("3")), &actual)); @@ -168,7 +159,7 @@ TEST_P(PackageCacheTest, BuildCacheFileName) { } // Tests Put, Get, IsCached, and Purge calls. -TEST_P(PackageCacheTest, BasicTest) { +TEST_F(PackageCacheTest, BasicTest) { EXPECT_HRESULT_SUCCEEDED(package_cache_.PurgeAll()); Key key1(_T("app1"), _T("ver1"), _T("package1")); @@ -177,9 +168,7 @@ TEST_P(PackageCacheTest, BasicTest) { EXPECT_FALSE(package_cache_.IsCached(key1, hash_file1_)); // Cache one file. - EXPECT_HRESULT_SUCCEEDED(package_cache_.Put(key1, - source_file1_, - hash_file1_)); + EXPECT_SUCCEEDED(package_cache_.Put(key1, source_file1_, hash_file1_)); EXPECT_EQ(size_file1_, package_cache_.Size()); // Check the file is in the cache. @@ -193,45 +182,37 @@ TEST_P(PackageCacheTest, BasicTest) { EXPECT_FALSE(destination_file.IsEmpty()); // Get the file two times. - EXPECT_HRESULT_SUCCEEDED(package_cache_.Get(key1, - destination_file, - hash_file1_)); + EXPECT_SUCCEEDED(package_cache_.Get(key1, destination_file, hash_file1_)); EXPECT_TRUE(File::Exists(destination_file)); - EXPECT_HRESULT_SUCCEEDED(PackageCache::VerifyHash(destination_file, - hash_file1_)); - EXPECT_HRESULT_SUCCEEDED(package_cache_.Get(key1, - destination_file, - hash_file1_)); + EXPECT_SUCCEEDED(PackageCache::VerifyHash(destination_file, hash_file1_)); + + EXPECT_SUCCEEDED(package_cache_.Get(key1, destination_file, hash_file1_)); EXPECT_TRUE(File::Exists(destination_file)); - EXPECT_HRESULT_SUCCEEDED(PackageCache::VerifyHash(destination_file, - hash_file1_)); + + EXPECT_SUCCEEDED(PackageCache::VerifyHash(destination_file, hash_file1_)); EXPECT_TRUE(::DeleteFile(destination_file)); // Cache another file. Key key2(_T("app2"), _T("ver2"), _T("package2")); - EXPECT_HRESULT_SUCCEEDED(package_cache_.Put(key2, - source_file2_, - hash_file2_)); + EXPECT_SUCCEEDED(package_cache_.Put(key2, source_file2_, hash_file2_)); EXPECT_EQ(size_file1_ + size_file2_, package_cache_.Size()); EXPECT_TRUE(package_cache_.IsCached(key2, hash_file2_)); // Cache the same file again. It should be idempotent. - EXPECT_HRESULT_SUCCEEDED(package_cache_.Put(key2, - source_file2_, - hash_file2_)); + EXPECT_SUCCEEDED(package_cache_.Put(key2, source_file2_, hash_file2_)); EXPECT_EQ(size_file1_ + size_file2_, package_cache_.Size()); EXPECT_TRUE(package_cache_.IsCached(key2, hash_file2_)); EXPECT_TRUE(File::Exists(source_file2_)); - EXPECT_HRESULT_SUCCEEDED(package_cache_.Purge(key1)); + EXPECT_SUCCEEDED(package_cache_.Purge(key1)); EXPECT_FALSE(package_cache_.IsCached(key1, hash_file1_)); EXPECT_EQ(size_file2_, package_cache_.Size()); - EXPECT_HRESULT_SUCCEEDED(package_cache_.Purge(key2)); + EXPECT_SUCCEEDED(package_cache_.Purge(key2)); EXPECT_FALSE(package_cache_.IsCached(key2, hash_file2_)); EXPECT_EQ(0, package_cache_.Size()); @@ -247,7 +228,7 @@ TEST_P(PackageCacheTest, BasicTest) { EXPECT_FALSE(File::Exists(destination_file)); } -TEST_P(PackageCacheTest, PutBadHashTest) { +TEST_F(PackageCacheTest, PutBadHashTest) { EXPECT_HRESULT_SUCCEEDED(package_cache_.PurgeAll()); Key key1(_T("app1"), _T("ver1"), _T("package1")); @@ -255,14 +236,9 @@ TEST_P(PackageCacheTest, PutBadHashTest) { // Check the file is not in the cache. EXPECT_FALSE(package_cache_.IsCached(key1, hash_file1_)); - // Try caching one file when the SHA1 hash is not correct. - FileHash bad_hash; - if (GetParam()) { - bad_hash.sha256 = - _T("0000bad0000364f6c33161d781b49d840ed792b8b10668c4180b9e6e128d0bc9"); - } else { - bad_hash.sha1 = _T("JmV9skETZqGFMjs32vbZTvzAYJU="); - } + // Try caching one file when the hash is not correct. + CString bad_hash = + _T("0000bad0000364f6c33161d781b49d840ed792b8b10668c4180b9e6e128d0bc9"); EXPECT_EQ(SIGS_E_INVALID_SIGNATURE, package_cache_.Put(key1, source_file1_, bad_hash)); @@ -272,13 +248,12 @@ TEST_P(PackageCacheTest, PutBadHashTest) { // The key must include the app id, version, and package name for Put and Get // operations. If the version is not provided, "0.0.0.0" is used internally. -TEST_P(PackageCacheTest, BadKeyTest) { +TEST_F(PackageCacheTest, BadKeyTest) { Key key_empty_app(_T(""), _T("b"), _T("c")); Key key_empty_name(_T("a"), _T("b"), _T("")); - FileHash bad_hash; - bad_hash.sha1 = _T("a"); - bad_hash.sha256 = _T("b"); + CString bad_hash; + bad_hash = _T("b"); EXPECT_EQ(E_INVALIDARG, package_cache_.Get(key_empty_app, _T("a"), bad_hash)); EXPECT_EQ(E_INVALIDARG, package_cache_.Get(key_empty_name, _T("a"), bad_hash)); @@ -288,7 +263,7 @@ TEST_P(PackageCacheTest, BadKeyTest) { package_cache_.Put(key_empty_name, _T("a"), bad_hash)); } -TEST_P(PackageCacheTest, PurgeVersionTest) { +TEST_F(PackageCacheTest, PurgeVersionTest) { // Cache two files for two versions of the same app. Key key11(_T("app1"), _T("ver1"), _T("package1")); Key key12(_T("app1"), _T("ver1"), _T("package2")); @@ -334,7 +309,7 @@ TEST_P(PackageCacheTest, PurgeVersionTest) { EXPECT_EQ(0, package_cache_.Size()); } -TEST_P(PackageCacheTest, PurgeAppTest) { +TEST_F(PackageCacheTest, PurgeAppTest) { // Cache two files for two apps. Key key11(_T("app1"), _T("ver1"), _T("package1")); Key key12(_T("app1"), _T("ver1"), _T("package2")); @@ -380,7 +355,7 @@ TEST_P(PackageCacheTest, PurgeAppTest) { EXPECT_EQ(0, package_cache_.Size()); } -TEST_P(PackageCacheTest, PurgeAppLowerVersionsTest) { +TEST_F(PackageCacheTest, PurgeAppLowerVersionsTest) { EXPECT_EQ(E_INVALIDARG, package_cache_.PurgeAppLowerVersions(_T("app1"), _T("1"))); @@ -428,7 +403,7 @@ TEST_P(PackageCacheTest, PurgeAppLowerVersionsTest) { EXPECT_EQ(0, package_cache_.Size()); } -TEST_P(PackageCacheTest, PurgeAll) { +TEST_F(PackageCacheTest, PurgeAll) { // Cache two files for two apps. Key key11(_T("app1"), _T("ver1"), _T("package1")); Key key12(_T("app1"), _T("ver1"), _T("package2")); @@ -465,7 +440,7 @@ TEST_P(PackageCacheTest, PurgeAll) { EXPECT_EQ(0, package_cache_.Size()); } -TEST_P(PackageCacheTest, PurgeOldPackagesIfOverSizeLimit) { +TEST_F(PackageCacheTest, PurgeOldPackagesIfOverSizeLimit) { EXPECT_HRESULT_SUCCEEDED(package_cache_.PurgeAll()); const int kCacheSizeLimitMB = 2; @@ -509,7 +484,7 @@ TEST_P(PackageCacheTest, PurgeOldPackagesIfOverSizeLimit) { EXPECT_LE(package_cache_.Size(), kSizeLimitBytes); } -TEST_P(PackageCacheTest, PurgeExpiredCacheFiles) { +TEST_F(PackageCacheTest, PurgeExpiredCacheFiles) { EXPECT_HRESULT_SUCCEEDED(package_cache_.PurgeAll()); const int kCacheLifeLimitDays = 100; @@ -539,14 +514,12 @@ TEST_P(PackageCacheTest, PurgeExpiredCacheFiles) { EXPECT_FALSE(package_cache_.IsCached(key2, hash_file2_)); } -TEST_P(PackageCacheTest, VerifyHash) { +TEST_F(PackageCacheTest, VerifyHash) { EXPECT_HRESULT_SUCCEEDED(PackageCache::VerifyHash(source_file1_, hash_file1_)); EXPECT_EQ(SIGS_E_INVALID_SIGNATURE, PackageCache::VerifyHash(source_file1_, hash_file2_)); } -INSTANTIATE_TEST_CASE_P(Sha1OrSha256, PackageCacheTest, ::testing::Bool()); - } // namespace omaha diff --git a/omaha/goopdate/update_response_utils.cc b/omaha/goopdate/update_response_utils.cc index dbf03b3e4..4e854b49a 100644 --- a/omaha/goopdate/update_response_utils.cc +++ b/omaha/goopdate/update_response_utils.cc @@ -14,11 +14,14 @@ // ======================================================================== #include "omaha/goopdate/update_response_utils.h" + #include +#include +#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/atl_regexp.h" #include "omaha/base/system_info.h" #include "omaha/common/lang.h" #include "omaha/common/experiment_labels.h" @@ -38,7 +41,7 @@ namespace { // version and it comes from the update response, or with the a dotted quad, // which is the OS version of the host. ULONGLONG OSVersionFromString(const CString& s) { - if (AtlRE::PartialMatch(s, AtlRE(_T("^\\d+\\.\\d+$")))) { + if (std::regex_search(std::wstring(s), std::wregex(_T("^\\d+\\.\\d+$")))) { // Convert from "x.y" to "x.y.0.0" format so we can use the existing // VersionFromString utility function. return VersionFromString(s + _T(".0.0")); @@ -46,8 +49,8 @@ ULONGLONG OSVersionFromString(const CString& s) { // The string is a dotted quad version. VersionFromString handles the error if // the parameter is something else. - ASSERT1(AtlRE::PartialMatch(s, AtlRE(_T("^\\d+\\.\\d+\\.\\d+\\.\\d+$")))); - + ASSERT1(std::regex_search(std::wstring(s), + std::wregex(_T("^\\d+\\.\\d+\\.\\d+\\.\\d+$")))); return VersionFromString(s); } @@ -211,10 +214,9 @@ HRESULT BuildApp(const xml::UpdateResponse* update_response, for (size_t i = 0; i < update_check.install_manifest.packages.size(); ++i) { const xml::InstallPackage& package( update_check.install_manifest.packages[i]); - FileHash hash; - hash.sha1 = package.hash_sha1; - hash.sha256 = package.hash_sha256; - HRESULT hr = next_version->AddPackage(package.name, package.size, hash); + HRESULT hr = next_version->AddPackage(package.name, + package.size, + package.hash_sha256); if (FAILED(hr)) { return hr; } diff --git a/omaha/hammer.bat b/omaha/hammer.bat index b839b0ec9..0f6be5333 100644 --- a/omaha/hammer.bat +++ b/omaha/hammer.bat @@ -48,9 +48,6 @@ goto set_env_variables :: Directory where the Go programming language toolchain is installed. set GOROOT=C:\go -:: Directory where AtlServer files are. -set OMAHA_ATL_SERVER_DIR=c:\atl_server\files - :: This will depend on your OS. If this version of the .Net framework came with :: the OS, then set it to the framework directory :: (something like C:\Windows\Microsoft.NET\Framework\v2.0.50727). diff --git a/omaha/main.scons b/omaha/main.scons index d5350eed5..cca943d14 100644 --- a/omaha/main.scons +++ b/omaha/main.scons @@ -109,11 +109,7 @@ if (_sdk_dir is None): omaha_version_utils.VC80:'platformsdk/v6_1' }[_msc_ver]) _sdk_version = os.getenv('OMAHA_WINDOWS_SDK_10_0_VERSION', None) - -_atl_server_dir = os.getenv('OMAHA_ATL_SERVER_DIR', - '$THIRD_PARTY/atl_server/files') _wtl_dir = os.getenv('OMAHA_WTL_DIR', '$THIRD_PARTY/wtl/files') - _signtool_path = ('python $MAIN_DIR/tools/retry.py 10 5 \"%s/%s\"' % (os.getenv('OMAHA_SIGNTOOL_SDK_DIR'), 'signtool.exe')) @@ -534,7 +530,6 @@ win_env.AppendUnique( ], CPPPATH = [ - _atl_server_dir + '/include', _wtl_dir +'/include', '$GOOGLECLIENT', '$MAIN_DIR', @@ -593,16 +588,8 @@ win_env.AppendUnique( 'TEST_CERTIFICATE=%d' % win_env.Bit('test_certificate'), 'ONECLICK_PLUGIN_NAME=_T(\\"%s\\")' % ( omaha_version_utils.GetONECLICK_PLUGIN_NAME()), - 'ONECLICK_PLUGIN_VERSION_ANSI=\\"%d\\"' % ( - omaha_version_info.oneclick_plugin_version), - 'ONECLICK_PLUGIN_FILENAME=_T(\\"%s\\")' % ( - omaha_version_info.oneclick_plugin_filename), 'UPDATE_PLUGIN_NAME=_T(\\"%s\\")' % ( omaha_version_utils.GetUPDATE_PLUGIN_NAME()), - 'UPDATE_PLUGIN_VERSION_ANSI=\\"%d\\"' % ( - omaha_version_info.update_plugin_version), - 'UPDATE_PLUGIN_FILENAME=_T(\\"%s\\")' % ( - omaha_version_info.update_plugin_filename), 'CRASH_HANDLER_NAME=_T(\\"%s\\")' % omaha_version_utils.GetCRASH_HANDLER_NAME(), ], @@ -739,7 +726,6 @@ _base_dirs = [ _normal_dirs = [ 'installers', 'mi_exe_stub', - 'plugins', 'recovery', ] diff --git a/omaha/net/detector.cc b/omaha/net/detector.cc index d56d886c1..ca94acc44 100644 --- a/omaha/net/detector.cc +++ b/omaha/net/detector.cc @@ -153,7 +153,7 @@ HRESULT GroupPolicyProxyDetector::Detect(ProxyConfig* config) { } bool GroupPolicyProxyDetector::IsManaged() { - return IsEnrolledToDomain(); + return IsEnrolledToDomain() && RegKey::HasKey(kRegKeyGoopdateGroupPolicy); } HRESULT GroupPolicyProxyDetector::GetProxyMode(CString* proxy_mode) { diff --git a/omaha/net/detector_unittest.cc b/omaha/net/detector_unittest.cc index 113007918..9bb996432 100644 --- a/omaha/net/detector_unittest.cc +++ b/omaha/net/detector_unittest.cc @@ -52,12 +52,19 @@ class GroupPolicyProxyDetectorTest kRegValueIsEnrolledToDomain, IsManaged() && !IsUsingDMProxyDetector() ? 1UL : 0UL)); + if (IsManaged() && !IsUsingDMProxyDetector()) { + RegKey::CreateKey(kRegKeyGoopdateGroupPolicy); + } else { + RegKey::DeleteKey(kRegKeyGoopdateGroupPolicy); + } + detector_.reset(IsUsingDMProxyDetector() ? new DMProxyDetector : new GroupPolicyProxyDetector); } virtual void TearDown() { ResetCachedOmahaPolicy(); + RegKey::DeleteKey(kRegKeyGoopdateGroupPolicy); EXPECT_SUCCEEDED(RegKey::DeleteValue(MACHINE_REG_UPDATE_DEV, kRegValueIsEnrolledToDomain)); diff --git a/omaha/net/network_config.cc b/omaha/net/network_config.cc index 86bda8e15..ce5e269b2 100644 --- a/omaha/net/network_config.cc +++ b/omaha/net/network_config.cc @@ -134,8 +134,19 @@ HRESULT NetworkConfig::Initialize() { } Add(new UpdateDevProxyDetector); - Add(new GroupPolicyProxyDetector); - Add(new DMProxyDetector); + + DWORD cloud_policy_preferred(0); + if (SUCCEEDED(RegKey::GetValue(kRegKeyGoopdateGroupPolicy, + kRegValueCloudPolicyOverridesPlatformPolicy, + &cloud_policy_preferred)) && + cloud_policy_preferred) { + Add(new DMProxyDetector); + Add(new GroupPolicyProxyDetector); + } else { + Add(new GroupPolicyProxyDetector); + Add(new DMProxyDetector); + } + Add(new IEWPADProxyDetector); Add(new IEPACProxyDetector); Add(new IENamedProxyDetector); diff --git a/omaha/omaha_version_utils.py b/omaha/omaha_version_utils.py index 40c0fc434..aefce5c19 100644 --- a/omaha/omaha_version_utils.py +++ b/omaha/omaha_version_utils.py @@ -109,29 +109,22 @@ def _IsSupportedOmaha2Version(omaha_version): # All languages supported by this script currently have the same set of # languages, so the omaha_version_info parameter is unused. def _GetMetainstallerPayloadFilenames(prefix, - update_plugin_filename, languages, omaha_version): """Returns list of metainstaller payload files for specified Omaha version.""" - plugin_dll_name = '%s%s' % (prefix, update_plugin_filename) # The list of files below needs to be kept in sync with the list in # SetupFiles::BuildFileLists(). # TODO(omaha): Move the other filename defines in main.scons into this file - # and allow all filenames to be customized. At the moment, while the plugin - # names are generated in one place due to version numbers, most of the other - # files (googleupdate.exe, goopdateres_*.dll, etc.) are hardcoded all over - # the place, and require a ton of point fixes to customize. + # and allow all filenames to be customized. payload_files = [ 'GoogleUpdate.exe', '%s.exe' % _CRASH_HANDLER_NAME, '%sgoopdate.dll' % (prefix), - plugin_dll_name, 'GoogleUpdateHelper.msi', 'GoogleUpdateBroker.exe', 'GoogleUpdateOnDemand.exe', 'GoogleUpdateComRegisterShell64.exe', - 'GoogleUpdateWebPlugin.exe', '%spsmachine.dll' % (prefix), '%spsmachine_64.dll' % (prefix), '%spsuser.dll' % (prefix), @@ -139,7 +132,6 @@ def _GetMetainstallerPayloadFilenames(prefix, ] if _IsSupportedOmaha2Version(omaha_version): - payload_files.remove(plugin_dll_name) payload_files.remove('GoogleUpdateBroker.exe') payload_files.remove('GoogleUpdateOnDemand.exe') payload_files.remove('GoogleUpdateComRegisterShell64.exe') @@ -236,12 +228,7 @@ class OmahaVersionInfo(object): version_minor: Minor version. version_build: Build version. version_patch: Patch version. - oneclick_plugin_version: Version of the OneClick plug-in. - oneclick_plugin_filename: Name of the signed OneClick DLL. - update_plugin_version: Version of the Omaha 3 plug-in. - update_plugin_filename: Name of the signed Omaha 3 plug-in DLL. crash_handler_filename: Name of the Crash Handler EXE. - oneclick_signed_file_info: SignedFileInfo object for the OneClick DLL. """ def __init__(self, version_file): @@ -250,31 +237,11 @@ def __init__(self, version_file): self.filename_prefix = '' - # Objects containing more properties used to build the file. - self.oneclick_signed_file_info = SignedFileInfo( - _ONECLICK_PLUGIN_NAME, - 'dll', - self.oneclick_plugin_version) - self.plugin_signed_file_info = SignedFileInfo( - _UPDATE_PLUGIN_NAME, - 'dll', - self.update_plugin_version) - - # Simple properties for callers that only need the final filename. Not - # affected by internal build changes. - self.oneclick_plugin_filename = self.oneclick_signed_file_info.filename - self.update_plugin_filename = self.plugin_signed_file_info.filename - self.crash_handler_filename = _CRASH_HANDLER_NAME - def _ReadFile(self, version_file): """Reads and stores data from a VERSION file.""" execfile(version_file, globals()) - # Silence Pylint. Values from version_file are not defined in this file. - # E0602: Undefined variable. - # pylint: disable-msg=E0602 - if version_patch > 0: incrementing_value = version_patch incrementing_value_name = 'patch' @@ -291,19 +258,6 @@ def _ReadFile(self, version_file): self.version_build = version_build self.version_patch = version_patch - self.oneclick_plugin_version = oneclick_plugin_version - - # update_plugin_version does not exist in Omaha 2 VERSION file. Handle this. - try: - self.update_plugin_version = update_plugin_version - except NameError: - if _IsSupportedOmaha2Version(self.GetVersion()): - self.update_plugin_version = -1 - else: - raise - - # pylint: enable-msg=E0602 - def MakeTestVersion(self, delta, prefix): """Changes this object to be for a TEST version of Omaha.""" @@ -340,7 +294,6 @@ def GetSupportedLanguages(self): def GetMetainstallerPayloadFilenames(self): """Returns list of metainstaller payload files for this version of Omaha.""" return _GetMetainstallerPayloadFilenames(self.filename_prefix, - self.update_plugin_filename, self.GetSupportedLanguages(), self.GetVersion()) diff --git a/omaha/plugins/base/build.scons b/omaha/plugins/base/build.scons deleted file mode 100644 index 2c28bd491..000000000 --- a/omaha/plugins/base/build.scons +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2009 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ======================================================================== - -Import('env') - -# Build plugin base. -plugin_base_env = env.Clone() -plugin_base_env['CCFLAGS'] = [ - '/wd4100', -], -plugin_base_env.ComponentLibrary( - lib_name='plugin_base', - source=[ - 'np_entry.cc', - 'npn_gate.cc', - 'npp_gate.cc', - ], -) diff --git a/omaha/plugins/base/np_entry.cc b/omaha/plugins/base/np_entry.cc deleted file mode 100644 index c3ad7b3ad..000000000 --- a/omaha/plugins/base/np_entry.cc +++ /dev/null @@ -1,321 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: NPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Netscape Public License - * Version 1.1 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the NPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the NPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -////////////////////////////////////////////////////////////// -// -// Main plugin entry point implementation -- exports from the -// plugin library -// - -#include -#include "omaha/plugins/base/npplat.h" -#include "omaha/plugins/base/pluginbase.h" - -#ifdef _WINDOWS -#define OSCALL WINAPI -#else -#define OSCALL -#endif - -NPNetscapeFuncs NPNFuncs = {sizeof(NPNFuncs)}; - -NPError OSCALL NP_Shutdown() -{ - NS_PluginShutdown(); - return NPERR_NO_ERROR; -} - -static NPError fillPluginFunctionTable(NPPluginFuncs* aNPPFuncs) -{ - if (aNPPFuncs == NULL || aNPPFuncs->size < sizeof(NPPluginFuncs)) { - return NPERR_INVALID_FUNCTABLE_ERROR; - } - - // Set up the plugin function table that Netscape will use to - // call us. Netscape needs to know about our version and size - // and have a UniversalProcPointer for every function we implement. - - aNPPFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; -#ifdef XP_MAC - aNPPFuncs->newp = NewNPP_NewProc(Private_New); - aNPPFuncs->destroy = NewNPP_DestroyProc(Private_Destroy); - aNPPFuncs->setwindow = NewNPP_SetWindowProc(Private_SetWindow); - aNPPFuncs->newstream = NewNPP_NewStreamProc(Private_NewStream); - aNPPFuncs->destroystream = NewNPP_DestroyStreamProc(Private_DestroyStream); - aNPPFuncs->asfile = NewNPP_StreamAsFileProc(Private_StreamAsFile); - aNPPFuncs->writeready = NewNPP_WriteReadyProc(Private_WriteReady); - aNPPFuncs->write = NewNPP_WriteProc(Private_Write); - aNPPFuncs->print = NewNPP_PrintProc(Private_Print); - aNPPFuncs->event = NewNPP_HandleEventProc(Private_HandleEvent); - aNPPFuncs->urlnotify = NewNPP_URLNotifyProc(Private_URLNotify); - aNPPFuncs->getvalue = NewNPP_GetValueProc(Private_GetValue); - aNPPFuncs->setvalue = NewNPP_SetValueProc(Private_SetValue); -#else - aNPPFuncs->newp = NPP_New; - aNPPFuncs->destroy = NPP_Destroy; - aNPPFuncs->setwindow = NPP_SetWindow; - aNPPFuncs->newstream = NPP_NewStream; - aNPPFuncs->destroystream = NPP_DestroyStream; - aNPPFuncs->asfile = NPP_StreamAsFile; - aNPPFuncs->writeready = NPP_WriteReady; - aNPPFuncs->write = NPP_Write; - aNPPFuncs->print = NPP_Print; - aNPPFuncs->event = NPP_HandleEvent; - aNPPFuncs->urlnotify = NPP_URLNotify; - aNPPFuncs->getvalue = NPP_GetValue; - aNPPFuncs->setvalue = NPP_SetValue; -#endif -#ifdef OJI - aNPPFuncs->javaClass = NULL; -#endif - - return NPERR_NO_ERROR; -} - -static NPError fillNetscapeFunctionTable(NPNetscapeFuncs* aNPNFuncs) -{ - if (aNPNFuncs == NULL) { - return NPERR_INVALID_FUNCTABLE_ERROR; - } - - if (HIBYTE(aNPNFuncs->version) > NP_VERSION_MAJOR) { - return NPERR_INCOMPATIBLE_VERSION_ERROR; - } - - memcpy(&NPNFuncs, aNPNFuncs, std::min(static_cast(aNPNFuncs->size), - sizeof(NPNFuncs))); - - if (!NPNFuncs.memalloc || - !NPNFuncs.memfree || - !NPNFuncs.createobject || - !NPNFuncs.retainobject || - !NPNFuncs.releaseobject || - !NPNFuncs.utf8fromidentifier || - !NPNFuncs.releasevariantvalue || - !NPNFuncs.getstringidentifier || - !NPNFuncs.getvalue || - !NPNFuncs.setexception || - !NPNFuncs.getproperty || - // Used only by oneclick plugin. - !NPNFuncs.invokeDefault) { - return NPERR_INVALID_FUNCTABLE_ERROR; - } - - return NPERR_NO_ERROR; -} - -// -// Some exports are different on different platforms -// - -/**************************************************/ -/* */ -/* Windows */ -/* */ -/**************************************************/ -#ifdef XP_WIN - -NPError OSCALL NP_Initialize(NPNetscapeFuncs* aNPNFuncs) -{ - NPError rv = fillNetscapeFunctionTable(aNPNFuncs); - if(rv != NPERR_NO_ERROR) - return rv; - - return NS_PluginInitialize(); -} - -NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* aNPPFuncs) -{ - return fillPluginFunctionTable(aNPPFuncs); -} - -#endif //XP_WIN - -/**************************************************/ -/* */ -/* Unix */ -/* */ -/**************************************************/ -#ifdef XP_UNIX - -NPError NP_Initialize(NPNetscapeFuncs* aNPNFuncs, NPPluginFuncs* aNPPFuncs) -{ - NPError rv = fillNetscapeFunctionTable(aNPNFuncs); - if(rv != NPERR_NO_ERROR) - return rv; - - rv = fillPluginFunctionTable(aNPPFuncs); - if(rv != NPERR_NO_ERROR) - return rv; - - return NS_PluginInitialize(); -} - -char * NP_GetMIMEDescription(void) -{ - return NPP_GetMIMEDescription(); -} - -NPError NP_GetValue(void *future, NPPVariable aVariable, void *aValue) -{ - return NS_PluginGetValue(aVariable, aValue); -} - -#endif //XP_UNIX - -/**************************************************/ -/* */ -/* Mac */ -/* */ -/**************************************************/ -#ifdef XP_MAC - -#if !TARGET_API_MAC_CARBON -QDGlobals* gQDPtr; // Pointer to Netscape's QuickDraw globals -#endif - -short gResFile; // Refnum of the plugin's resource file - -NPError Private_Initialize(void) -{ - NPError rv = NS_PluginInitialize(); - return rv; -} - -void Private_Shutdown(void) -{ - NS_PluginShutdown(); - __destroy_global_chain(); -} - -void SetUpQD(void); - -void SetUpQD(void) -{ - ProcessSerialNumber PSN; - FSSpec myFSSpec; - Str63 name; - ProcessInfoRec infoRec; - OSErr result = noErr; - CFragConnectionID connID; - Str255 errName; - - // Memorize the plugins resource file refnum for later use. - gResFile = CurResFile(); - -#if !TARGET_API_MAC_CARBON - // Ask the system if CFM is available. - long response; - OSErr err = Gestalt(gestaltCFMAttr, &response); - Boolean hasCFM = BitTst(&response, 31-gestaltCFMPresent); - - if (hasCFM) { - // GetProcessInformation takes a process serial number and - // will give us back the name and FSSpec of the application. - // See the Process Manager in IM. - infoRec.processInfoLength = sizeof(ProcessInfoRec); - infoRec.processName = name; - infoRec.processAppSpec = &myFSSpec; - - PSN.highLongOfPSN = 0; - PSN.lowLongOfPSN = kCurrentProcess; - - result = GetProcessInformation(&PSN, &infoRec); - } - else - // If no CFM installed, assume it must be a 68K app. - result = -1; - - if (result == noErr) { - // Now that we know the app name and FSSpec, we can call GetDiskFragment - // to get a connID to use in a subsequent call to FindSymbol (it will also - // return the address of main in app, which we ignore). If GetDiskFragment - // returns an error, we assume the app must be 68K. - Ptr mainAddr; - result = GetDiskFragment(infoRec.processAppSpec, 0L, 0L, infoRec.processName, - kReferenceCFrag, &connID, (Ptr*)&mainAddr, errName); - } - - if (result == noErr) { - // The app is a PPC code fragment, so call FindSymbol - // to get the exported qd symbol so we can access its - // QuickDraw globals. - CFragSymbolClass symClass; - result = FindSymbol(connID, "\pqd", (Ptr*)&gQDPtr, &symClass); - } - else { - // The app is 68K, so use its A5 to compute the address - // of its QuickDraw globals. - gQDPtr = (QDGlobals*)(*((long*)SetCurrentA5()) - (sizeof(QDGlobals) - sizeof(GrafPtr))); - } -#endif /* !TARGET_API_MAC_CARBON */ -} - -NPError main(NPNetscapeFuncs* nsTable, NPPluginFuncs* pluginFuncs, NPP_ShutdownUPP* unloadUpp); - -#if !TARGET_API_MAC_CARBON -#pragma export on -#if GENERATINGCFM -RoutineDescriptor mainRD = BUILD_ROUTINE_DESCRIPTOR(uppNPP_MainEntryProcInfo, main); -#endif -#pragma export off -#endif /* !TARGET_API_MAC_CARBON */ - - -NPError main(NPNetscapeFuncs* aNPNFuncs, NPPluginFuncs* aNPPFuncs, NPP_ShutdownUPP* aUnloadUpp) -{ - NPError rv = NPERR_NO_ERROR; - - if (aUnloadUpp == NULL) - rv = NPERR_INVALID_FUNCTABLE_ERROR; - - if (rv == NPERR_NO_ERROR) - rv = fillNetscapeFunctionTable(aNPNFuncs); - - if (rv == NPERR_NO_ERROR) { - // defer static constructors until the global functions are initialized. - __InitCode__(); - rv = fillPluginFunctionTable(aNPPFuncs); - } - - *aUnloadUpp = NewNPP_ShutdownProc(Private_Shutdown); - SetUpQD(); - rv = Private_Initialize(); - - return rv; -} -#endif //XP_MAC diff --git a/omaha/plugins/base/npn_gate.cc b/omaha/plugins/base/npn_gate.cc deleted file mode 100644 index 5aee8f3a3..000000000 --- a/omaha/plugins/base/npn_gate.cc +++ /dev/null @@ -1,259 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: NPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Netscape Public License - * Version 1.1 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the NPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the NPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - - -//////////////////////////////////////////////////////////// -// -// Implementation of Netscape entry points (NPN_*) -// -#include "omaha/plugins/base/npplat.h" - -extern NPNetscapeFuncs NPNFuncs; - -/* -void NPN_Version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor) -{ - *plugin_major = NP_VERSION_MAJOR; - *plugin_minor = NP_VERSION_MINOR; - *netscape_major = HIBYTE(NPNFuncs.version); - *netscape_minor = LOBYTE(NPNFuncs.version); -} - -NPError NPN_GetURLNotify(NPP instance, const char *url, const char *target, void* notifyData) -{ - int navMinorVers = NPNFuncs.version & 0xFF; - NPError rv = NPERR_NO_ERROR; - - if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) - rv = CallNPN_GetURLNotifyProc(NPNFuncs.geturlnotify, instance, url, target, notifyData); - else - rv = NPERR_INCOMPATIBLE_VERSION_ERROR; - - return rv; -} - -NPError NPN_GetURL(NPP instance, const char *url, const char *target) -{ - NPError rv = CallNPN_GetURLProc(NPNFuncs.geturl, instance, url, target); - return rv; -} - -NPError NPN_PostURLNotify(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData) -{ - int navMinorVers = NPNFuncs.version & 0xFF; - NPError rv = NPERR_NO_ERROR; - - if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) - rv = CallNPN_PostURLNotifyProc(NPNFuncs.posturlnotify, instance, url, window, len, buf, file, notifyData); - else - rv = NPERR_INCOMPATIBLE_VERSION_ERROR; - - return rv; -} - -NPError NPN_PostURL(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file) -{ - NPError rv = CallNPN_PostURLProc(NPNFuncs.posturl, instance, url, window, len, buf, file); - return rv; -} - -NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList) -{ - NPError rv = CallNPN_RequestReadProc(NPNFuncs.requestread, stream, rangeList); - return rv; -} - -NPError NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream) -{ - int navMinorVersion = NPNFuncs.version & 0xFF; - - NPError rv = NPERR_NO_ERROR; - - if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) - rv = CallNPN_NewStreamProc(NPNFuncs.newstream, instance, type, target, stream); - else - rv = NPERR_INCOMPATIBLE_VERSION_ERROR; - - return rv; -} - -int32 NPN_Write(NPP instance, NPStream *stream, int32 len, void *buffer) -{ - int navMinorVersion = NPNFuncs.version & 0xFF; - int32 rv = 0; - - if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) - rv = CallNPN_WriteProc(NPNFuncs.write, instance, stream, len, buffer); - else - rv = -1; - - return rv; -} - -NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason) -{ - int navMinorVersion = NPNFuncs.version & 0xFF; - NPError rv = NPERR_NO_ERROR; - - if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) - rv = CallNPN_DestroyStreamProc(NPNFuncs.destroystream, instance, stream, reason); - else - rv = NPERR_INCOMPATIBLE_VERSION_ERROR; - - return rv; -} - -void NPN_Status(NPP instance, const char *message) -{ - CallNPN_StatusProc(NPNFuncs.status, instance, message); -} - -const char* NPN_UserAgent(NPP instance) -{ - const char * rv = NULL; - rv = CallNPN_UserAgentProc(NPNFuncs.uagent, instance); - return rv; -} -*/ - -void* NPN_MemAlloc(uint32 size) -{ - void* rv = NULL; - return NPNFuncs.memalloc(size); -} - -void NPN_MemFree(void* ptr) -{ - NPNFuncs.memfree(ptr); -} - -/* -uint32 NPN_MemFlush(uint32 size) -{ - uint32 rv = CallNPN_MemFlushProc(NPNFuncs.memflush, size); - return rv; -} - -void NPN_ReloadPlugins(NPBool reloadPages) -{ - CallNPN_ReloadPluginsProc(NPNFuncs.reloadplugins, reloadPages); -} - -#ifdef OJI -JRIEnv* NPN_GetJavaEnv(void) -{ - JRIEnv * rv = NULL; - rv = CallNPN_GetJavaEnvProc(NPNFuncs.getJavaEnv); - return rv; -} - -jref NPN_GetJavaPeer(NPP instance) -{ - jref rv; - rv = CallNPN_GetJavaPeerProc(NPNFuncs.getJavaPeer, instance); - return rv; -} -#endif -*/ - -NPError NPN_GetValue(NPP instance, NPNVariable variable, void *value) -{ - return NPNFuncs.getvalue(instance, variable, value); -} - -/* -NPError NPN_SetValue(NPP instance, NPPVariable variable, void *value) -{ - NPError rv = CallNPN_SetValueProc(NPNFuncs.setvalue, instance, variable, value); - return rv; -} - -void NPN_InvalidateRect(NPP instance, NPRect *invalidRect) -{ - CallNPN_InvalidateRectProc(NPNFuncs.invalidaterect, instance, invalidRect); -} - -void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion) -{ - CallNPN_InvalidateRegionProc(NPNFuncs.invalidateregion, instance, invalidRegion); -} - -void NPN_ForceRedraw(NPP instance) -{ - CallNPN_ForceRedrawProc(NPNFuncs.forceredraw, instance); -} -*/ - -// Used by the Omaha 3 plugin. -NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier) { - return NPNFuncs.utf8fromidentifier(identifier); -} - -NPObject* NPN_RetainObject(NPObject* obj) { - return NPNFuncs.retainobject(obj); -} - -void NPN_ReleaseObject(NPObject* obj) { - NPNFuncs.releaseobject(obj); -} - -NPIdentifier NPN_GetStringIdentifier(const NPUTF8* name) { - return NPNFuncs.getstringidentifier(name); -} - -NPObject* NPN_CreateObject(NPP npp, NPClass* aClass) { - return NPNFuncs.createobject(npp, aClass); -} - -void NPN_SetException(NPObject* obj, const NPUTF8* message) { - NPNFuncs.setexception(obj, message); -} - -void NPN_ReleaseVariantValue(NPVariant* variant) { - NPNFuncs.releasevariantvalue(variant); -} - -bool NPN_GetProperty(NPP npp, NPObject* obj, NPIdentifier propertyName, - NPVariant* result) { - return NPNFuncs.getproperty(npp, obj, propertyName, result); -} - -// Some additional stuff that's used by the oneclick plugin -bool NPN_InvokeDefault(NPP npp, NPObject* obj, const NPVariant* args, - uint32_t argCount, NPVariant* result) { - return NPNFuncs.invokeDefault(npp, obj, args, argCount, result); -} diff --git a/omaha/plugins/base/npp_gate.cc b/omaha/plugins/base/npp_gate.cc deleted file mode 100644 index ee9da881f..000000000 --- a/omaha/plugins/base/npp_gate.cc +++ /dev/null @@ -1,358 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: NPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Netscape Public License - * Version 1.1 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the NPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the NPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - - -//////////////////////////////////////////////////////////// -// -// Implementation of plugin entry points (NPP_*) -// -#include "omaha/plugins/base/pluginbase.h" - -// here the plugin creates a plugin instance object which -// will be associated with this newly created NPP instance and -// will do all the neccessary job -NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPError rv = NPERR_NO_ERROR; - - // create a new plugin instance object - // initialization will be done when the associated window is ready - nsPluginCreateData ds; - - ds.instance = instance; - ds.type = pluginType; - ds.mode = mode; - ds.argc = argc; - ds.argn = argn; - ds.argv = argv; - ds.saved = saved; - - nsPluginInstanceBase * plugin = NS_NewPluginInstance(&ds); - if(plugin == NULL) - return NPERR_OUT_OF_MEMORY_ERROR; - - // associate the plugin instance object with NPP instance - instance->pdata = (void *)plugin; - return rv; -} - -// here is the place to clean up and destroy the nsPluginInstance object -NPError NPP_Destroy (NPP instance, NPSavedData** save) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPError rv = NPERR_NO_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin != NULL) { - plugin->shut(); - NS_DestroyPluginInstance(plugin); - } - return rv; -} - -// during this call we know when the plugin window is ready or -// is about to be destroyed so we can do some gui specific -// initialization and shutdown -NPError NPP_SetWindow (NPP instance, NPWindow* pNPWindow) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - NPError rv = NPERR_NO_ERROR; - - if(pNPWindow == NULL) - return NPERR_GENERIC_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - - if(plugin == NULL) - return NPERR_GENERIC_ERROR; - - // window just created - if(!plugin->isInitialized() && (pNPWindow->window != NULL)) { - if(!plugin->init(pNPWindow)) { - NS_DestroyPluginInstance(plugin); - return NPERR_MODULE_LOAD_FAILED_ERROR; - } - } - - // window goes away - if((pNPWindow->window == NULL) && plugin->isInitialized()) - return plugin->SetWindow(pNPWindow); - - // window resized? - if(plugin->isInitialized() && (pNPWindow->window != NULL)) - return plugin->SetWindow(pNPWindow); - - // this should not happen, nothing to do - if((pNPWindow->window == NULL) && !plugin->isInitialized()) - return plugin->SetWindow(pNPWindow); - - return rv; -} - -NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return NPERR_GENERIC_ERROR; - - NPError rv = plugin->NewStream(type, stream, seekable, stype); - return rv; -} - -int32 NPP_WriteReady (NPP instance, NPStream *stream) -{ - if(instance == NULL) - return 0x0fffffff; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return 0x0fffffff; - - int32 rv = plugin->WriteReady(stream); - return rv; -} - -int32 NPP_Write (NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) -{ - if(instance == NULL) - return len; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return len; - - int32 rv = plugin->Write(stream, offset, len, buffer); - return rv; -} - -NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return NPERR_GENERIC_ERROR; - - NPError rv = plugin->DestroyStream(stream, reason); - return rv; -} - -void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) -{ - if(instance == NULL) - return; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return; - - plugin->StreamAsFile(stream, fname); -} - -void NPP_Print (NPP instance, NPPrint* printInfo) -{ - if(instance == NULL) - return; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return; - - plugin->Print(printInfo); -} - -void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) -{ - if(instance == NULL) - return; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return; - - plugin->URLNotify(url, reason, notifyData); -} - -NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return NPERR_GENERIC_ERROR; - - NPError rv = plugin->GetValue(variable, value); - return rv; -} - -NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) -{ - if(instance == NULL) - return NPERR_INVALID_INSTANCE_ERROR; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return NPERR_GENERIC_ERROR; - - NPError rv = plugin->SetValue(variable, value); - return rv; -} - -int16 NPP_HandleEvent(NPP instance, void* event) -{ - if(instance == NULL) - return 0; - - nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; - if(plugin == NULL) - return 0; - - uint16 rv = plugin->HandleEvent(event); - return rv; -} - -#ifdef OJI -jref NPP_GetJavaClass (void) -{ - return NULL; -} -#endif - -/**************************************************/ -/* */ -/* Mac */ -/* */ -/**************************************************/ - -// Mac needs these wrappers, see npplat.h for more info - -#ifdef XP_MAC - -NPError Private_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) -{ - NPError rv = NPP_New(pluginType, instance, mode, argc, argn, argv, saved); - return rv; -} - -NPError Private_Destroy(NPP instance, NPSavedData** save) -{ - NPError rv = NPP_Destroy(instance, save); - return rv; -} - -NPError Private_SetWindow(NPP instance, NPWindow* window) -{ - NPError rv = NPP_SetWindow(instance, window); - return rv; -} - -NPError Private_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) -{ - NPError rv = NPP_NewStream(instance, type, stream, seekable, stype); - return rv; -} - -int32 Private_WriteReady(NPP instance, NPStream* stream) -{ - int32 rv = NPP_WriteReady(instance, stream); - return rv; -} - -int32 Private_Write(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer) -{ - int32 rv = NPP_Write(instance, stream, offset, len, buffer); - return rv; -} - -void Private_StreamAsFile(NPP instance, NPStream* stream, const char* fname) -{ - NPP_StreamAsFile(instance, stream, fname); -} - - -NPError Private_DestroyStream(NPP instance, NPStream* stream, NPError reason) -{ - NPError rv = NPP_DestroyStream(instance, stream, reason); - return rv; -} - -int16 Private_HandleEvent(NPP instance, void* event) -{ - int16 rv = NPP_HandleEvent(instance, event); - return rv; -} - -void Private_Print(NPP instance, NPPrint* platformPrint) -{ - NPP_Print(instance, platformPrint); -} - -void Private_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) -{ - NPP_URLNotify(instance, url, reason, notifyData); -} - -jref Private_GetJavaClass(void) -{ - return NULL; -} - -NPError Private_GetValue(NPP instance, NPPVariable variable, void *result) -{ - NPError rv = NPP_GetValue(instance, variable, result); - return rv; -} - -NPError Private_SetValue(NPP instance, NPNVariable variable, void *value) -{ - NPError rv = NPP_SetValue(instance, variable, value); - return rv; -} - -#endif //XP_MAC diff --git a/omaha/plugins/base/npplat.h b/omaha/plugins/base/npplat.h deleted file mode 100644 index e9700c75e..000000000 --- a/omaha/plugins/base/npplat.h +++ /dev/null @@ -1,149 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: NPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Netscape Public License - * Version 1.1 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the NPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the NPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#ifndef OMAHA_PLUGINS_COMMON_NPPLAT_H_ -#define OMAHA_PLUGINS_COMMON_NPPLAT_H_ - -/**************************************************/ -/* */ -/* Windows */ -/* */ -/**************************************************/ -#ifdef XP_WIN -#include "windows.h" -#endif //XP_WIN - -/**************************************************/ -/* */ -/* Unix */ -/* */ -/**************************************************/ -#ifdef XP_UNIX -#include -#endif //XP_UNIX - -/**************************************************/ -/* */ -/* Mac */ -/* */ -/**************************************************/ -#ifdef XP_MAC - -#include -#include -#include -#include -#include -#include - -#include "jri.h" - -// The Mixed Mode procInfos defined in npupp.h assume Think C- -// style calling conventions. These conventions are used by -// Metrowerks with the exception of pointer return types, which -// in Metrowerks 68K are returned in A0, instead of the standard -// D0. Thus, since NPN_MemAlloc and NPN_UserAgent return pointers, -// Mixed Mode will return the values to a 68K plugin in D0, but -// a 68K plugin compiled by Metrowerks will expect the result in -// A0. The following pragma forces Metrowerks to use D0 instead. -// -#ifdef __MWERKS__ -#ifndef powerc -#pragma pointers_in_D0 -#endif -#endif - -#ifdef __MWERKS__ -#ifndef powerc -#pragma pointers_in_A0 -#endif -#endif - -// The following fix for static initializers (which fixes a preious -// incompatibility with some parts of PowerPlant, was submitted by -// Jan Ulbrich. -#ifdef __MWERKS__ - #ifdef __cplusplus - extern "C" { - #endif - #ifndef powerc - extern void __InitCode__(void); - #else - extern void __sinit(void); - #define __InitCode__ __sinit - #endif - extern void __destroy_global_chain(void); - #ifdef __cplusplus - } - #endif // __cplusplus -#endif // __MWERKS__ - -// Wrapper functions for all calls from Netscape to the plugin. -// These functions let the plugin developer just create the APIs -// as documented and defined in npapi.h, without needing to -// install those functions in the function table or worry about -// setting up globals for 68K plugins. -NPError Private_Initialize(void); -void Private_Shutdown(void); -NPError Private_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved); -NPError Private_Destroy(NPP instance, NPSavedData** save); -NPError Private_SetWindow(NPP instance, NPWindow* window); -NPError Private_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype); -NPError Private_DestroyStream(NPP instance, NPStream* stream, NPError reason); -int32 Private_WriteReady(NPP instance, NPStream* stream); -int32 Private_Write(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer); -void Private_StreamAsFile(NPP instance, NPStream* stream, const char* fname); -void Private_Print(NPP instance, NPPrint* platformPrint); -int16 Private_HandleEvent(NPP instance, void* event); -void Private_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData); -jref Private_GetJavaClass(void); -NPError Private_GetValue(NPP instance, NPPVariable variable, void *result); -NPError Private_SetValue(NPP instance, NPNVariable variable, void *value); - -#endif //XP_MAC - -#include "third_party/npapi/bindings/nphostapi.h" - -#ifndef HIBYTE -#define HIBYTE(i) (i >> 8) -#endif - -#ifndef LOBYTE -#define LOBYTE(i) (i & 0xff) -#endif - -#endif // OMAHA_PLUGINS_COMMON_NPPLAT_H_ diff --git a/omaha/plugins/base/pluginbase.h b/omaha/plugins/base/pluginbase.h deleted file mode 100644 index 259bc7822..000000000 --- a/omaha/plugins/base/pluginbase.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: NPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Netscape Public License - * Version 1.1 (the "License"); you may not use this file except in - * compliance with the License. You may obtain a copy of the License at - * http://www.mozilla.org/NPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the NPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the NPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#ifndef OMAHA_PLUGINS_COMMON_PLUGINBASE_H_ -#define OMAHA_PLUGINS_COMMON_PLUGINBASE_H_ - -#include "omaha/plugins/base/npplat.h" - -struct nsPluginCreateData -{ - NPP instance; - NPMIMEType type; - uint16 mode; - int16 argc; - char** argn; - char** argv; - NPSavedData* saved; -}; - -#pragma warning(push) -#pragma warning(disable:4100) // unreferenced formal parameter -class nsPluginInstanceBase -{ -public: - // these three methods must be implemented in the derived - // class platform specific way - virtual NPBool init(NPWindow* aWindow) = 0; - virtual void shut() = 0; - virtual NPBool isInitialized() = 0; - - // implement all or part of those methods in the derived - // class as needed - virtual NPError SetWindow(NPWindow* pNPWindow) { return NPERR_NO_ERROR; } - virtual NPError NewStream(NPMIMEType type, NPStream* stream, - NPBool seekable, uint16* stype) { return NPERR_NO_ERROR; } - virtual NPError DestroyStream(NPStream *stream, NPError reason) { return NPERR_NO_ERROR; } - virtual void StreamAsFile(NPStream* stream, const char* fname) { return; } - virtual int32 WriteReady(NPStream *stream) { return 0x0fffffff; } - virtual int32 Write(NPStream *stream, int32 offset, - int32 len, void *buffer) { return len; } - virtual void Print(NPPrint* printInfo) { return; } - virtual uint16 HandleEvent(void* event) { return 0; } - virtual void URLNotify(const char* url, NPReason reason, - void* notifyData) { return; } - virtual NPError GetValue(NPPVariable variable, void *value) { return NPERR_NO_ERROR; } - virtual NPError SetValue(NPNVariable variable, void *value) { return NPERR_NO_ERROR; } -}; -#pragma warning(pop) - -// functions that should be implemented for each specific plugin - -// creation and destruction of the object of the derived class -nsPluginInstanceBase * NS_NewPluginInstance(nsPluginCreateData * aCreateDataStruct); -void NS_DestroyPluginInstance(nsPluginInstanceBase * aPlugin); - -// global plugin initialization and shutdown -NPError NS_PluginInitialize(); -void NS_PluginShutdown(); - -#ifdef XP_UNIX -// global to get plugins name & description -NPError NS_PluginGetValue(NPPVariable aVariable, void *aValue); -#endif - -#endif // OMAHA_PLUGINS_COMMON_PLUGINBASE_H_ diff --git a/omaha/plugins/build.scons b/omaha/plugins/build.scons deleted file mode 100644 index 15a234520..000000000 --- a/omaha/plugins/build.scons +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/python2.4 -# -# Copyright 2009 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ======================================================================== - -Import('env') - -env.BuildSConscript('base') -env.BuildSConscript('update') diff --git a/omaha/plugins/plugin_version.rc b/omaha/plugins/plugin_version.rc deleted file mode 100644 index 15bfcd1ad..000000000 --- a/omaha/plugins/plugin_version.rc +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2007 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// This file contains the unlocalized plugin version resources. - -#include - -// The "040904e4" block (for codepage 1252 Ansi Latin) is required for -// the Netscape Plugin stuff to see the MIMETYPE value in the resource block. - -// TODO(omaha): FileDescription is what shows up in "about:plugins" for -// Mozilla. Format the description to include the url of the project. -// Update: July 2010. I'm not sure why this comment requests the URL. We should -// include the version, though, since that is used by version-checking websites. - -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -VS_VERSION_INFO VERSIONINFO -// Resource Editor does not handle constants from main.scons. -#ifndef APSTUDIO_INVOKED - FILEVERSION VERSION_MAJOR,VERSION_MINOR,VERSION_BUILD,VERSION_PATCH - PRODUCTVERSION VERSION_MAJOR,VERSION_MINOR,VERSION_BUILD,VERSION_PATCH -#endif // APSTUDIO_INVOKED - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#if defined _DEBUG && OFFICIAL_BUILD - FILEFLAGS VS_FF_DEBUG -#elif defined _DEBUG - FILEFLAGS VS_FF_DEBUG | VS_FF_PRIVATEBUILD -#elif !OFFICIAL_BUILD - FILEFLAGS VS_FF_PRIVATEBUILD -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN -// Requires constants from mains.scons that cannot be loaded in Resource Editor. -#ifndef APSTUDIO_INVOKED - VALUE "CompanyName", FULL_COMPANY_NAME_ANSI - VALUE "FileDescription", OMAHA_APP_NAME_ANSI - VALUE "FileVersion", VERSION_NUMBER_STRING - VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", OMAHA_COPYRIGHT_STRING_ENGLISH - VALUE "OriginalFilename", PLUGIN_FILENAME - VALUE "ProductName", OMAHA_APP_NAME_ANSI - VALUE "ProductVersion", VERSION_NUMBER_STRING - #ifdef _DEBUG - VALUE "Debug", "" - #endif - #if !OFFICIAL_BUILD - VALUE "PrivateBuild", BUILD_NUMBER - #endif - - #ifdef MERGED_MIME_TYPE - VALUE "MIMEType", MERGED_MIME_TYPE - #endif -#else - VALUE "_SpecialView", - "Most values are not shown in Resource Editor because they " - "require build file constants." -#endif // APSTUDIO_INVOKED - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END diff --git a/omaha/plugins/update/activex/oneclick_control.cc b/omaha/plugins/update/activex/oneclick_control.cc deleted file mode 100644 index 955cea1c7..000000000 --- a/omaha/plugins/update/activex/oneclick_control.cc +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Implementation of the OneClick Plugin. - -#include "omaha/plugins/update/activex/oneclick_control.h" - -#include -#include -#include -#include - -#include "omaha/base/error.h" -#include "omaha/base/file.h" -#include "omaha/base/string.h" -#include "omaha/base/system.h" -#include "omaha/base/vistautil.h" -#include "omaha/common/command_line.h" -#include "omaha/common/command_line_builder.h" -#include "omaha/common/const_cmd_line.h" -#include "omaha/common/goopdate_utils.h" -#include "omaha/common/update3_utils.h" -#include "omaha/common/webplugin_utils.h" -#include "omaha/goopdate/app_command.h" -#include "omaha/goopdate/app_manager.h" -#include "omaha/third_party/smartany/scoped_any.h" -#include "goopdate/omaha3_idl.h" - -namespace omaha { - -OneClickControl::OneClickControl() { - CORE_LOG(L2, (_T("[OneClickControl::OneClickControl]"))); -} - -OneClickControl::~OneClickControl() { - CORE_LOG(L2, (_T("[OneClickControl::~OneClickControl]"))); -} - -STDMETHODIMP OneClickControl::Install(BSTR cmd_line_args, - VARIANT* success_callback, - VARIANT* failure_callback) { - ASSERT1(cmd_line_args && cmd_line_args[0]); - ASSERT1(VariantIsValidCallback(success_callback)); - ASSERT1(VariantIsValidCallback(failure_callback)); - - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!cmd_line_args || - !cmd_line_args[0] || - !VariantIsValidCallback(success_callback) || - !VariantIsValidCallback(failure_callback) ) { - return E_INVALIDARG; - } - - const TCHAR kExtraArgsInstallPrefix[] = _T("/install \""); - const TCHAR kExtraArgsSuffix[] = _T("\""); - if (!String_StartsWith(cmd_line_args, kExtraArgsInstallPrefix, false) || - !String_EndsWith(cmd_line_args, kExtraArgsSuffix, false)) { - return E_INVALIDARG; - } - - CORE_LOG(L2, (_T("[OneClickControl::Install][cmd_line \"%s\"]"), - static_cast(CW2CT(cmd_line_args)))); - - // We trim cmd_line_args to just the extra args and thunk to Install2(). - CString extra_args(cmd_line_args); - extra_args = extra_args.Mid(arraysize(kExtraArgsInstallPrefix) - 1); - extra_args.Delete(extra_args.GetLength() - 1); - - HRESULT hr = Install2(extra_args.AllocSysString()); - if (SUCCEEDED(hr)) { - InvokeJavascriptCallback(success_callback, NULL); - } else { - CORE_LOG(LE, (_T("[DoOneClickInstallInternal failed][0x%08x]"), hr)); - InvokeJavascriptCallback(failure_callback, &hr); - } - - // Return success in all cases. The failure callback has already been called - // above, and we don't want to cause a failure path to be called again when - // the JavaScript catches the exception. - - return S_OK; -} - -STDMETHODIMP OneClickControl::Install2(BSTR extra_args) { - ASSERT1(extra_args && extra_args[0]); - - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!extra_args || !extra_args[0]) { - return E_INVALIDARG; - } - - CORE_LOG(L2, (_T("[OneClickControl::Install2][extra_args \"%s\"]"), - static_cast(CW2CT(extra_args)))); - - CString browser_url; - HRESULT hr = site_lock_.GetCurrentBrowserUrl(this, &browser_url); - if (FAILED(hr)) { - return hr; - } - - CString url_domain; - hr = SiteLock::GetUrlDomain(browser_url, &url_domain); - if (FAILED(hr)) { - return hr; - } - - // To protect against XSS attacks where an arbitrary extra_args could be - // passed into Install/Install2, BuildWebPluginCommandLine escapes all unsafe - // characters such as space, slash, double-quotes. ShellExecuteProcess is then - // passed a command line that is safe to interpret by the command line parser. - CString final_cmd_line_args; - hr = webplugin_utils::BuildWebPluginCommandLine(url_domain, - extra_args, - &final_cmd_line_args); - - CPath webpluginexe_path(app_util::GetCurrentModuleDirectory()); - VERIFY1(webpluginexe_path.Append(kOmahaWebPluginFileName)); - - scoped_process process_webpluginexe; - hr = System::ShellExecuteProcess(webpluginexe_path, - final_cmd_line_args, - NULL, - address(process_webpluginexe)); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[OneClickControl::Install2]") - _T("[ShellExecuteProcess failed][%s][%s][0x%x]"), - webpluginexe_path, final_cmd_line_args, hr)); - return hr; - } - - return S_OK; -} - -STDMETHODIMP OneClickControl::GetInstalledVersion(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR* version_string) { - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!guid_string || !version_string) { - return E_POINTER; - } - *version_string = NULL; - - CORE_LOG(L2, (_T("[OneClickControl::GetInstalledVersion][%s][%d]"), - guid_string, is_machine)); - - CString version; - HRESULT hr = DoGetInstalledVersion(guid_string, - is_machine == VARIANT_TRUE, - &version); - if (SUCCEEDED(hr)) { - *version_string = version.AllocSysString(); - } - - return S_OK; -} - -STDMETHODIMP OneClickControl::GetOneClickVersion(long* version) { // NOLINT - ASSERT1(version); - - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - CORE_LOG(L2, (_T("[OneClickControl::GetOneClickVersion]"))); - - if (!version) { - return E_POINTER; - } - - *version = atoi(ONECLICK_PLUGIN_VERSION_ANSI); // NOLINT - return S_OK; -} - -STDMETHODIMP OneClickControl::LaunchAppCommand(BSTR, VARIANT_BOOL, BSTR) { - return E_NOTIMPL; -} - -HRESULT OneClickControl::DoGetInstalledVersion(const TCHAR* guid_string, - bool is_machine, - CString* version_string) { - ASSERT1(guid_string); - ASSERT1(version_string); - - GUID app_guid = GUID_NULL; - HRESULT hr = StringToGuidSafe(guid_string, &app_guid); - if (FAILED(hr)) { - return hr; - } - - return AppManager::ReadAppVersionNoLock(is_machine, app_guid, version_string); -} - -bool OneClickControl::VariantIsValidCallback(const VARIANT* callback) { - return callback && - (callback->vt == VT_NULL || - callback->vt == VT_EMPTY || - (callback->vt == VT_DISPATCH && callback->pdispVal)); -} - -HRESULT OneClickControl::InvokeJavascriptCallback(VARIANT* callback, - const HRESULT* opt_param) { - if (!callback || callback->vt == VT_NULL || callback->vt == VT_EMPTY) { - return S_FALSE; - } - - if (callback->vt != VT_DISPATCH || !callback->pdispVal) { - return E_FAIL; - } - - const DISPID kDispId0 = 0; - DISPPARAMS dispparams = {0}; - - CComQIPtr dispatchex = callback->pdispVal; - if (dispatchex) { - DISPID disp_this = DISPID_THIS; - VARIANT var[2]; - var[0].vt = VT_DISPATCH; - var[0].pdispVal = dispatchex; - if (opt_param) { - var[1].vt = VT_I4; - var[1].intVal = *opt_param; - } - - dispparams.rgvarg = var; - dispparams.rgdispidNamedArgs = &disp_this; - dispparams.cNamedArgs = 1; - dispparams.cArgs = opt_param ? 2 : 1; - - return dispatchex->InvokeEx(kDispId0, LOCALE_USER_DEFAULT, - DISPATCH_METHOD, &dispparams, - NULL, NULL, NULL); - } else { - // Fallback on IDispatch if needed. (This route will be used for NPAPI - // functions wrapped via NPFunctionHost.) - - UINT arg_err = 0; - VARIANT var[1]; - - if (opt_param) { - var[0].vt = VT_I4; - var[0].intVal = *opt_param; - dispparams.rgvarg = var; - dispparams.cArgs = 1; - } - - return callback->pdispVal->Invoke(kDispId0, - IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparams, - NULL, - NULL, - &arg_err); - } -} - -} // namespace omaha - -// 4505: unreferenced local function has been removed -#pragma warning(disable : 4505) - diff --git a/omaha/plugins/update/activex/oneclick_control.h b/omaha/plugins/update/activex/oneclick_control.h deleted file mode 100644 index df7064507..000000000 --- a/omaha/plugins/update/activex/oneclick_control.h +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// One-click support for Omaha returning users. - -#ifndef OMAHA_PLUGINS_UPDATE_ACTIVEX_ONECLICK_CONTROL_H_ -#define OMAHA_PLUGINS_UPDATE_ACTIVEX_ONECLICK_CONTROL_H_ - -// TODO(omaha): We may want to move sitelock.h to be the "standard" sitelock.h -// file from Microsoft (and move that file to omaha/external) and then have our -// modifications to sitelock be in a derived class within the plugins -// directory. - -#include -#include -#include -#include -#include -#include - -#include "omaha/base/ATLRegMapEx.h" -#include "omaha/base/const_addresses.h" -#include "omaha/base/constants.h" -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" -#include "omaha/base/omaha_version.h" -#include "omaha/common/goopdate_utils.h" -#include "omaha/plugins/update/config.h" -#include "omaha/plugins/update/resource.h" -#include "omaha/plugins/update/site_lock.h" -#include "plugins/update/activex/update_control_idl.h" - -namespace omaha { - -class OneClickControl; - -typedef IObjectSafetyImpl - OneClickControlSafety; - -// Using 0xffff for the major/minor versions in the IDispatchImpl template will -// make ATL load the typelib directly from the DLL instead of looking up typelib -// registration in registry. The big benefit is that we do not need to register -// the typelib. Also, this is needed for Vista SP1 with UAC off, in which -// oleaut32 does not read typelib information from HKCU, because of a bug. -class ATL_NO_VTABLE OneClickControl - : public CComObjectRootEx, - public CComCoClass, - public IDispatchImpl, - public OneClickControlSafety, - public IObjectWithSiteImpl { - public: - OneClickControl(); - virtual ~OneClickControl(); - - DECLARE_REGISTRY_RESOURCEID_EX(IDR_ONECLICK_RGS) - - BEGIN_REGISTRY_MAP() - REGMAP_ENTRY(_T("CLSID"), GetObjectCLSID()) - REGMAP_ENTRY(_T("PROGID"), kOneclickControlProgId) - REGMAP_ENTRY(_T("HKROOT"), goopdate_utils::GetHKRoot()) - REGMAP_ENTRY(_T("SHELLNAME"), kOmahaWebPluginFileName) - REGMAP_ENTRY(_T("SHELLPATH"), GetShellPathForRegMap()) - - // The following entries are actually for the NPAPI plugin - REGMAP_ENTRY(_T("PLUGINDESCRIPTION"), kAppName) - REGMAP_ENTRY(_T("PLUGINDOMAIN"), kGoopdateServer) - REGMAP_ENTRY(_T("PLUGINVENDOR"), kFullCompanyName) - REGMAP_ENTRY(_T("PLUGINVERSION"), kOneclickPluginVersion) - REGMAP_ENTRY(_T("PLUGINPRODUCT"), kAppName) - REGMAP_ENTRY(_T("PLUGINMIMETYPE"), ONECLICK_MIME_TYPE) - END_REGISTRY_MAP() - - BEGIN_COM_MAP(OneClickControl) - COM_INTERFACE_ENTRY(IDispatch) - COM_INTERFACE_ENTRY(IObjectWithSite) - COM_INTERFACE_ENTRY(IObjectSafety) - END_COM_MAP() - - DECLARE_NOT_AGGREGATABLE(OneClickControl) - DECLARE_PROTECT_FINAL_CONSTRUCT(); - - // Installs the application that the passed-in manifest corresponds to. - STDMETHOD(Install)(BSTR cmd_line_args, - VARIANT* success_callback, - VARIANT* failure_callback); - - STDMETHOD(Install2)(BSTR extra_args); - - // Gets the version of the passed in application guid. If the application is - // not installed, returns an empty string. - STDMETHOD(GetInstalledVersion)(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR* version_string); - - // Gets the version of the plugin. The value is ONECLICK_PLUGIN_VERSION_ANSI. - // TODO(omaha3): If possible without causing incompatibilities, change version - // to a preferred type here and in OneClickWorker. - STDMETHOD(GetOneClickVersion)(long* version); // NOLINT - - // Launches a command defined by an installed application. Fails if the - // command is not successfully started, succeeds otherwise. Returns without - // waiting for the command to complete. - STDMETHOD(LaunchAppCommand)(BSTR app_guid, - VARIANT_BOOL is_machine, - BSTR cmd_id); - - private: - static bool is_machine() { - return goopdate_utils::IsRunningFromOfficialGoopdateDir(true); - } - - static CString GetShellPathForRegMap() { - return goopdate_utils::BuildInstallDirectory(is_machine(), - GetVersionString()); - } - - HRESULT DoGetInstalledVersion(const TCHAR* guid_string, - bool is_machine, - CString* version_string); - - static bool VariantIsValidCallback(const VARIANT* callback); - static HRESULT InvokeJavascriptCallback(VARIANT* callback, - const HRESULT* opt_param); - - SiteLock site_lock_; - - // If Admin, returns the path for Machine Goopdate. Else returns path for User - // Goopdate. - static CString GetGoopdateShellPathForRegMap(); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_ACTIVEX_ONECLICK_CONTROL_H_ - diff --git a/omaha/plugins/update/activex/update3web_control.cc b/omaha/plugins/update/activex/update3web_control.cc deleted file mode 100644 index 96abf4c69..000000000 --- a/omaha/plugins/update/activex/update3web_control.cc +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/activex/update3web_control.h" -#include -#include -#include "omaha/base/error.h" -#include "omaha/base/system.h" -#include "omaha/base/utils.h" -#include "omaha/base/vistautil.h" -#include "omaha/common/command_line.h" -#include "omaha/common/command_line_builder.h" -#include "omaha/common/const_cmd_line.h" -#include "omaha/common/goopdate_utils.h" -#include "omaha/common/update3_utils.h" -#include "omaha/common/webplugin_utils.h" -#include "omaha/goopdate/app_manager.h" -#include "goopdate/omaha3_idl.h" - -namespace omaha { - -Update3WebControl::Update3WebControl() { -} - -// There is a code generation bug in VC8. If a base class with template -// arguments and virtual members is not the first base class with virtual -// methods, the generated code for calling a virtual method on that base class -// will adjust the this pointer one extra time. This results in all sorts of -// strange things happening; typically, the program will crash at a later point. -// To avoid this, all calls to base class methods that have template arguments -// should have all the template arguments specified, since this seems to prevent -// the code generation bug from occuring. - -STDMETHODIMP Update3WebControl::createOmahaMachineServerAsync( - VARIANT_BOOL create_elevated, IDispatch** async_status) { - ASSERT1(async_status); - - CString url; - HRESULT hr = SiteLock::GetCurrentBrowserUrl(this, &url); - if (FAILED(hr)) { - CORE_LOG(LE, (L"[GetCurrentBrowserUrl failed][0x%08x]", hr)); - return hr; - } - - if (!site_lock_.InApprovedDomain(url)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!async_status) { - return E_POINTER; - } - - CComPtr cocreate_async; - hr = update3_utils::CoCreateWithProxyBlanket( - __uuidof(CoCreateAsyncClass), &cocreate_async); - if (FAILED(hr)) { - CORE_LOG(LE, (L"[CoCreate CoCreateAsyncClass failed][0x%08x]", hr)); - return hr; - } - - CComPtr status; - hr = cocreate_async->createOmahaMachineServerAsync(CComBSTR(url), - create_elevated, - &status); - if (FAILED(hr)) { - CORE_LOG(LE, (L"[CreateInstanceAsync failed][0x%08x]", hr)); - return hr; - } - - hr = status->QueryInterface(async_status); - CORE_LOG(L3, (L"[createOmahaMachineServerAsync][0x%p][0x%08x]", this, hr)); - return hr; -} - -STDMETHODIMP Update3WebControl::createOmahaUserServer(IDispatch** server) { - ASSERT1(server); - - CString url; - HRESULT hr = SiteLock::GetCurrentBrowserUrl(this, &url); - if (FAILED(hr)) { - CORE_LOG(LE, (L"[GetCurrentBrowserUrl failed][0x%08x]", hr)); - return hr; - } - - if (!site_lock_.InApprovedDomain(url)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!server) { - return E_POINTER; - } - - CComPtr security; - hr = update3_utils::CoCreateWithProxyBlanket( - __uuidof(GoogleUpdate3WebUserClass), &security); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[security.CoCreateWithProxyBlanket failed][0x%x]"), hr)); - return hr; - } - - hr = security->setOriginURL(CComBSTR(url)); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[setOriginURL failed][0x%08x]"), hr)); - return hr; - } - - hr = security->QueryInterface(server); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[QueryInterface failed][0x%08x]"), hr)); - return hr; - } - - CORE_LOG(L3, (L"[createOmahaUserServer][0x%p][0x%p]", this, *server)); - return hr; -} - -STDMETHODIMP Update3WebControl::getInstalledVersion(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR* version_string) { - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!guid_string || !version_string) { - return E_POINTER; - } - *version_string = NULL; - - CORE_LOG(L2, (_T("[Update3WebControl::getInstalledVersion][%s][%d]"), - guid_string, is_machine)); - - CString version; - HRESULT hr = GetVersionUsingRegistry(guid_string, - is_machine == VARIANT_TRUE, - &version); - if (SUCCEEDED(hr)) { - *version_string = version.AllocSysString(); - } - - return S_OK; -} - -#if 0 -// TODO(omaha3): Not using this method for now. CoCreation of -// GoogleUpdate3WebMachineClass can block, and should be using the async -// creation pattern aka createOmahaMachineServerAsync. -HRESULT Update3WebControl::GetVersionUsingCOMServer(const TCHAR* guid_string, - bool is_machine, - CString* version_string) { - CORE_LOG(L2, (_T("[GoopdateCtrl::GetVersionUsingCOMServer][%s][%d]"), - guid_string, is_machine)); - ASSERT1(guid_string); - ASSERT1(version_string); - - CComPtr update3web; - HRESULT hr = update3_utils::CoCreateWithProxyBlanket( - is_machine ? __uuidof(GoogleUpdate3WebMachineClass) : - __uuidof(GoogleUpdate3WebUserClass), - &update3web); - if (FAILED(hr)) { - CORE_LOG(LE, - (_T("[update3web.CoCreateWithProxyBlanket failed][0x%x]"), hr)); - return hr; - } - - CComPtr app_bundle_dispatch; - hr = update3web->createAppBundleWeb(&app_bundle_dispatch); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[update3web.createAppBundleWeb failed][0x%x]"), hr)); - return hr; - } - - CComPtr app_bundle_web; - hr = app_bundle_dispatch->QueryInterface(&app_bundle_web); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[QueryInterface for IAppBundleWeb failed][0x%x]"), hr)); - return hr; - } - - hr = app_bundle_web->initialize(); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[initialize fail][0x%x]"), hr)); - return hr; - } - - hr = app_bundle_web->createInstalledApp(CComBSTR(guid_string)); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[createInstalledApp fail][%s][0x%x]"), guid_string, hr)); - return hr; - } - - CComPtr app_dispatch; - hr = app_bundle_web->get_appWeb(0, &app_dispatch); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[get_appWeb failed][0x%x]"), hr)); - return hr; - } - - CComPtr app_web; - hr = app_dispatch->QueryInterface(&app_web); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[QueryInterface for IAppWeb failed][0x%x]"), hr)); - return hr; - } - - CComPtr app_version_dispatch; - hr = app_web->get_currentVersionWeb(&app_version_dispatch); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[get_currentVersionWeb failed][0x%x]"), hr)); - return hr; - } - - CComPtr app_version_web; - hr = app_version_dispatch->QueryInterface(&app_version_web); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[QueryInterface for IAppVersionWeb failed][0x%x]"), hr)); - return hr; - } - - CComBSTR version; - hr = app_version_web->get_version(&version); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[get_version failed][0x%x]"), hr)); - return hr; - } - - *version_string = version; - CORE_LOG(L2, (_T("[Update3WebControl::GetVersionUsingCOMServer][%s][%d][%s]"), - guid_string, is_machine, *version_string)); - return S_OK; -} -#endif - -HRESULT Update3WebControl::GetVersionUsingRegistry(const TCHAR* guid_string, - bool is_machine, - CString* version_string) { - CORE_LOG(L2, (_T("[GoopdateCtrl::GetVersionUsingRegistry][%s][%d]"), - guid_string, is_machine)); - ASSERT1(guid_string); - ASSERT1(version_string); - - GUID app_guid = GUID_NULL; - HRESULT hr = StringToGuidSafe(guid_string, &app_guid); - if (FAILED(hr)) { - return hr; - } - - return AppManager::ReadAppVersionNoLock(is_machine, app_guid, version_string); -} - -HRESULT Update3WebControl::crossInstall(BSTR extra_args) { - ASSERT1(extra_args); - - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - if (!extra_args || !extra_args[0]) { - return E_INVALIDARG; - } - - CORE_LOG(L2, (_T("[Update3WebControl::crossInstall][%s]"), extra_args)); - - // Build the full command line as it should eventually be run. (This command - // line will be escaped, including the /install, and stowed in a /pi later.) - - CommandLineBuilder inner_builder(COMMANDLINE_MODE_INSTALL); - inner_builder.set_extra_args(CString(extra_args)); - CString inner_cmd_line_args = inner_builder.GetCommandLineArgs(); - - HRESULT hr = webplugin_utils::IsLanguageSupported(inner_cmd_line_args); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[IsLanguageSupported failed][0x%08x]"), hr)); - return hr; - } - - CString browser_url; - hr = site_lock_.GetCurrentBrowserUrl(this, &browser_url); - if (FAILED(hr)) { - return hr; - } - - CString url_domain; - hr = SiteLock::GetUrlDomain(browser_url, &url_domain); - if (FAILED(hr)) { - return hr; - } - - // Build the outer command line using /pi. - - CString url_domain_encoded; - CString cmd_line_encoded; - hr = StringEscape(url_domain, true, &url_domain_encoded); - if (FAILED(hr)) { - return hr; - } - - hr = StringEscape(inner_cmd_line_args, true, &cmd_line_encoded); - if (FAILED(hr)) { - return hr; - } - - CommandLineBuilder outer_builder(COMMANDLINE_MODE_WEBPLUGIN); - outer_builder.set_webplugin_url_domain(url_domain_encoded); - outer_builder.set_webplugin_args(cmd_line_encoded); - outer_builder.set_install_source(kCmdLineInstallSource_Update3Web); - CString final_cmd_line_args = outer_builder.GetCommandLineArgs(); - - CORE_LOG(L2, (_T("[Update3WebControl::crossInstall]") - _T("[Final command line params: %s]"), - final_cmd_line_args)); - - // Spawn a gu process. - - scoped_process process_goopdate; - - hr = goopdate_utils::StartGoogleUpdateWithArgs(is_machine(), - final_cmd_line_args, - address(process_goopdate)); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[Update3WebControl::crossInstall]") - _T("[Failed StartGoogleUpdateWithArgs][0x%x]"), hr)); - return hr; - } - - return S_OK; -} - -HRESULT Update3WebControl::launchAppCommand(BSTR, VARIANT_BOOL, BSTR) { - return E_NOTIMPL; -} - -Update3WebControl::~Update3WebControl() { -} - -} // namespace omaha diff --git a/omaha/plugins/update/activex/update3web_control.h b/omaha/plugins/update/activex/update3web_control.h deleted file mode 100644 index 0300d3375..000000000 --- a/omaha/plugins/update/activex/update3web_control.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_ACTIVEX_UPDATE3WEB_CONTROL_H_ -#define OMAHA_PLUGINS_UPDATE_ACTIVEX_UPDATE3WEB_CONTROL_H_ - -#include -#include -#include - -#include "base/basictypes.h" -#include "goopdate/omaha3_idl.h" -#include "omaha/base/atlregmapex.h" -#include "omaha/base/const_addresses.h" -#include "omaha/base/constants.h" -#include "omaha/base/omaha_version.h" -#include "common/goopdate_utils.h" -#include "omaha/plugins/update/config.h" -#include "omaha/plugins/update/resource.h" -#include "omaha/plugins/update/site_lock.h" -#include "plugins/update/activex/update_control_idl.h" - -namespace omaha { - -class Update3WebControl; - -typedef IObjectSafetyImpl - Update3WebControlSafety; - -class ATL_NO_VTABLE Update3WebControl - : public CComObjectRootEx, - public CComCoClass, - public IDispatchImpl, - public Update3WebControlSafety, - public IObjectWithSiteImpl { - public: - Update3WebControl(); - - DECLARE_NOT_AGGREGATABLE(Update3WebControl) - DECLARE_REGISTRY_RESOURCEID_EX(IDR_ONECLICK_RGS) - -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) - BEGIN_REGISTRY_MAP() - REGMAP_ENTRY(L"CLSID", GetObjectCLSID()) - REGMAP_ENTRY(L"PROGID", kUpdate3WebControlProgId) - REGMAP_ENTRY(L"HKROOT", goopdate_utils::GetHKRoot()) - REGMAP_ENTRY(L"SHELLNAME", is_machine() ? kOmahaBrokerFileName : - kOmahaOnDemandFileName) - REGMAP_ENTRY(L"SHELLPATH", GetShellPathForRegMap()) - // The following entries are actually for the NPAPI plugin - REGMAP_ENTRY(L"PLUGINDESCRIPTION", kAppName) - REGMAP_ENTRY(L"PLUGINDOMAIN", kGoopdateServer) - REGMAP_ENTRY(L"PLUGINVENDOR", kFullCompanyName) - REGMAP_ENTRY(L"PLUGINVERSION", kUpdate3WebPluginVersion) - REGMAP_ENTRY(L"PLUGINPRODUCT", kAppName) - REGMAP_ENTRY(L"PLUGINMIMETYPE", UPDATE3WEB_MIME_TYPE) - END_REGISTRY_MAP() -#pragma warning(pop) - - BEGIN_COM_MAP(Update3WebControl) - COM_INTERFACE_ENTRY(IDispatch) - COM_INTERFACE_ENTRY(IObjectSafety) - COM_INTERFACE_ENTRY(IObjectWithSite) - END_COM_MAP() - - // IGoogleUpdate3WebControl methods. - STDMETHOD(createOmahaMachineServerAsync)(VARIANT_BOOL create_elevated, - IDispatch** async_status); - STDMETHOD(createOmahaUserServer)(IDispatch** server); - - // Gets the version of the passed in application guid. If the application is - // not installed, returns an empty string. - STDMETHOD(getInstalledVersion)(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR* version_string); - - // OneClick-equivalent API, used for cross-installs. - STDMETHOD(crossInstall)(BSTR extra_args); - - // Launches a command defined by an installed application. Fails if the - // command is not successfully started, succeeds otherwise. Returns without - // waiting for the command to complete. - STDMETHOD(launchAppCommand)(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR cmd_id); - - protected: - virtual ~Update3WebControl(); - - private: - static bool is_machine() { - return goopdate_utils::IsRunningFromOfficialGoopdateDir(true); - } - - static CString GetShellPathForRegMap() { - return goopdate_utils::BuildInstallDirectory(is_machine(), - GetVersionString()); - } - - HRESULT GetVersionUsingCOMServer(const TCHAR* guid_string, - bool is_machine, - CString* version_string); - HRESULT GetVersionUsingRegistry(const TCHAR* guid_string, - bool is_machine, - CString* version_string); - - SiteLock site_lock_; - - friend class Update3WebControlTest; - - DISALLOW_COPY_AND_ASSIGN(Update3WebControl); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_ACTIVEX_UPDATE3WEB_CONTROL_H_ diff --git a/omaha/plugins/update/activex/update3web_control_unittest.cc b/omaha/plugins/update/activex/update3web_control_unittest.cc deleted file mode 100644 index b81d4c9a5..000000000 --- a/omaha/plugins/update/activex/update3web_control_unittest.cc +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/activex/update3web_control.h" -#include -#include -#include -#include "base/basictypes.h" -#include "base/error.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -namespace { - -#define STUBMETHOD(identifier, ...) \ - STDMETHOD(identifier)(__VA_ARGS__) {\ - return E_NOTIMPL;\ - } - -#define STUBGETPROP(identifier, type) \ - STUBMETHOD(get_ ## identifier, type*) - -#define STUBPUTPROP(identifier, type) \ - STUBMETHOD(put_ ## identifier, type) - -#define STUBPROP(identifier, type) \ - STUBGETPROP(identifier, type)\ - STUBPUTPROP(identifier, type) - -class ATL_NO_VTABLE MockWebBrowser2 - : public CComObjectRootEx, - public IServiceProviderImpl, - public IWebBrowser2 { - public: - MockWebBrowser2() : url_("something-like-a-url") {} - virtual ~MockWebBrowser2() {} - - DECLARE_NOT_AGGREGATABLE(MockWebBrowser2); - - BEGIN_COM_MAP(MockWebBrowser2) - COM_INTERFACE_ENTRY(IServiceProvider) - COM_INTERFACE_ENTRY(IWebBrowser2) - END_COM_MAP() - - BEGIN_SERVICE_MAP(MockWebBrowser2) - SERVICE_ENTRY(SID_SWebBrowserApp) - END_SERVICE_MAP() - - // IDispatch - STUBMETHOD(GetIDsOfNames, REFIID, OLECHAR**, unsigned int, LCID, DISPID*); - STUBMETHOD(GetTypeInfo, unsigned int, LCID, ITypeInfo**); - STUBMETHOD(GetTypeInfoCount, UINT*); - STUBMETHOD(Invoke, DISPID, REFIID, LCID, WORD, DISPPARAMS*, VARIANT*, - EXCEPINFO*, unsigned int*); - - // IWebBrowser2 - STUBPROP(AddressBar, VARIANT_BOOL); - STUBGETPROP(Application, IDispatch*); - STUBGETPROP(Busy, VARIANT_BOOL); - STUBMETHOD(ClientToWindow, int*, int*); - STUBGETPROP(Container, IDispatch*); - STUBGETPROP(Document, IDispatch*); - STUBMETHOD(ExecWB, OLECMDID, OLECMDEXECOPT, VARIANT*, VARIANT*); - STUBGETPROP(FullName, BSTR); - STUBPROP(FullScreen, VARIANT_BOOL); - STUBMETHOD(GetProperty, BSTR, VARIANT*); - STUBMETHOD(GoBack, VOID); - STUBMETHOD(GoForward, VOID); - STUBMETHOD(GoHome, VOID); - STUBMETHOD(GoSearch, VOID); - STUBPROP(Height, LONG); - STUBGETPROP(HWND, LONG_PTR); - STUBPROP(Left, LONG); - STUBGETPROP(LocationName, BSTR); - STDMETHOD(get_LocationURL)(BSTR* url) { - *url = CComBSTR(url_).Detach(); - return S_OK; - } - STUBPROP(MenuBar, VARIANT_BOOL); - STUBGETPROP(Name, BSTR); - STUBMETHOD(Navigate, BSTR, VARIANT*, VARIANT*, VARIANT*, VARIANT*); - STUBMETHOD(Navigate2, VARIANT*, VARIANT*, VARIANT*, VARIANT*, VARIANT*); - STUBPROP(Offline, VARIANT_BOOL); - STUBGETPROP(Path, BSTR); - STUBGETPROP(Parent, IDispatch*); - STUBMETHOD(PutProperty, BSTR, VARIANT); - STUBMETHOD(QueryStatusWB, OLECMDID, OLECMDF*); - STUBMETHOD(Quit, VOID); - STUBGETPROP(ReadyState, READYSTATE); - STUBMETHOD(Refresh, VOID); - STUBMETHOD(Refresh2, VARIANT*); - STUBPROP(RegisterAsBrowser, VARIANT_BOOL); - STUBPROP(RegisterAsDropTarget, VARIANT_BOOL); - STUBPROP(Resizable, VARIANT_BOOL); - STUBMETHOD(ShowBrowserBar, VARIANT*, VARIANT*, VARIANT*); - STUBPROP(Silent, VARIANT_BOOL); - STUBPROP(StatusBar, VARIANT_BOOL); - STUBPROP(StatusText, BSTR); - STUBMETHOD(Stop, VOID); - STUBPROP(TheaterMode, VARIANT_BOOL); - STUBPROP(ToolBar, int); - STUBPROP(Top, LONG); - STUBGETPROP(TopLevelContainer, VARIANT_BOOL); - STUBPROP(Type, BSTR); - STUBPROP(Visible, VARIANT_BOOL); - STUBPROP(Width, LONG); - - void set_url(const char* url) { url_ = url; } - - private: - CString url_; - - DISALLOW_COPY_AND_ASSIGN(MockWebBrowser2); -}; - -class ATL_NO_VTABLE MockHTMLDocument2 - : public CComObjectRootEx, - public IServiceProvider, - public IOleClientSite, - public IOleContainer, - public IHTMLDocument2 { - public: - MockHTMLDocument2() {} - virtual ~MockHTMLDocument2() {} - - DECLARE_NOT_AGGREGATABLE(MockHTMLDocument2); - - BEGIN_COM_MAP(MockHTMLDocument2) - COM_INTERFACE_ENTRY(IServiceProvider) - COM_INTERFACE_ENTRY(IOleClientSite) - COM_INTERFACE_ENTRY(IOleContainer) - COM_INTERFACE_ENTRY(IHTMLDocument2) - END_COM_MAP() - - // IServiceProvider - STUBMETHOD(QueryService, REFGUID, REFIID, void**); - - // IOleContainer - STDMETHOD(GetContainer)(IOleContainer** container) { - return QueryInterface(IID_PPV_ARGS(container)); - } - STUBMETHOD(GetMoniker, DWORD, DWORD, IMoniker**); - STUBMETHOD(OnShowWindow, BOOL); - STUBMETHOD(RequestNewObjectLayout); - STUBMETHOD(SaveObject); - STUBMETHOD(ShowObject); - - // IOleContainer - STUBMETHOD(EnumObjects, DWORD, IEnumUnknown**); - STUBMETHOD(LockContainer, BOOL); - - // IDispatch - STUBMETHOD(GetIDsOfNames, REFIID, OLECHAR**, unsigned int, LCID, DISPID*); - STUBMETHOD(GetTypeInfo, unsigned int, LCID, ITypeInfo**); - STUBMETHOD(GetTypeInfoCount, UINT*); - STUBMETHOD(Invoke, DISPID, REFIID, LCID, WORD, DISPPARAMS*, VARIANT*, - EXCEPINFO*, unsigned int*); - - // IParseDisplayName - STUBMETHOD(ParseDisplayName, IBindCtx*, LPOLESTR, ULONG*, IMoniker**); - - // IHTMLDocument2 - STUBGETPROP(activeElement, IHTMLElement*); - STUBPROP(alinkColor, VARIANT); - STUBGETPROP(all, IHTMLElementCollection*); - STUBGETPROP(anchors, IHTMLElementCollection*); - STUBGETPROP(applets, IHTMLElementCollection*); - STUBPROP(bgColor, VARIANT); - STUBGETPROP(body, IHTMLElement*); - STUBPROP(charset, BSTR); - STUBMETHOD(clear, VOID); - STUBMETHOD(close, VOID); - STUBPROP(cookie, BSTR); - STUBMETHOD(createElement, BSTR, IHTMLElement**); - STUBMETHOD(createStyleSheet, BSTR, LONG, IHTMLStyleSheet**); - STUBPROP(defaultCharset, BSTR); - STUBPROP(designMode, BSTR); - STUBPROP(domain, BSTR); - STUBPROP(elementFromPoint, BSTR); - STUBMETHOD(elementFromPoint, LONG, LONG, IHTMLElement**); - STUBGETPROP(embeds, IHTMLElementCollection*); - STUBMETHOD(execCommand, BSTR, VARIANT_BOOL, VARIANT, VARIANT_BOOL*); - STUBMETHOD(execCommandShowHelp, BSTR, VARIANT_BOOL*); - STUBPROP(expando, VARIANT_BOOL); - STUBPROP(fgColor, VARIANT); - STUBGETPROP(fileCreatedDate, BSTR); - STUBGETPROP(fileModifiedDate, BSTR); - STUBGETPROP(fileSize, BSTR); - STUBGETPROP(fileUpdatedDate, BSTR); - STUBGETPROP(forms, IHTMLElementCollection*); - STUBGETPROP(frames, IHTMLFramesCollection2*); - STUBGETPROP(images, IHTMLElementCollection*); - STUBGETPROP(lastModified, BSTR); - STUBPROP(linkColor, VARIANT); - STUBGETPROP(links, IHTMLElementCollection*); - STUBGETPROP(location, IHTMLLocation*); - STUBGETPROP(mimeType, BSTR); - STUBGETPROP(nameProp, BSTR); - STUBPROP(onafterupdate, VARIANT); - STUBPROP(onbeforeupdate, VARIANT); - STUBPROP(onclick, VARIANT); - STUBPROP(ondblclick, VARIANT); - STUBPROP(ondragstart, VARIANT); - STUBPROP(onerrorupdate, VARIANT); - STUBPROP(onhelp, VARIANT); - STUBPROP(onkeydown, VARIANT); - STUBPROP(onkeypress, VARIANT); - STUBPROP(onkeyup, VARIANT); - STUBPROP(onmousedown, VARIANT); - STUBPROP(onmousemove, VARIANT); - STUBPROP(onmouseout, VARIANT); - STUBPROP(onmouseover, VARIANT); - STUBPROP(onmouseup, VARIANT); - STUBPROP(onreadystatechange, VARIANT); - STUBPROP(onrowenter, VARIANT); - STUBPROP(onrowexit, VARIANT); - STUBPROP(onselectstart, VARIANT); - STUBMETHOD(open, BSTR, VARIANT, VARIANT, VARIANT, IDispatch**); - STUBGETPROP(parentWindow, IHTMLWindow2*); - STUBGETPROP(plugins, IHTMLElementCollection*); - STUBPROP(protocol, BSTR); - STUBMETHOD(queryCommandEnabled, BSTR, VARIANT_BOOL*); - STUBMETHOD(queryCommandIndeterm, BSTR, VARIANT_BOOL*); - STUBMETHOD(queryCommandState, BSTR, VARIANT_BOOL*); - STUBMETHOD(queryCommandSupported, BSTR, VARIANT_BOOL*); - STUBMETHOD(queryCommandText, BSTR, BSTR*); - STUBMETHOD(queryCommandValue, BSTR, VARIANT*); - STUBGETPROP(readyState, BSTR); - STUBGETPROP(referrer, BSTR); - STUBGETPROP(Script, IDispatch*); - STUBGETPROP(security, BSTR); - STUBGETPROP(selection, IHTMLSelectionObject*); - STUBGETPROP(scripts, IHTMLElementCollection*); - STUBGETPROP(styleSheets, IHTMLStyleSheetsCollection*); - STUBPROP(title, BSTR); - STUBMETHOD(toString, BSTR*); - STDMETHOD(get_URL)(BSTR* url) { - *url = CComBSTR("something-else-like-a-url").Detach(); - return S_OK; - } - STUBPUTPROP(URL, BSTR); - STUBPROP(vlinkColor, VARIANT); - STUBMETHOD(write, SAFEARRAY*); - STUBMETHOD(writeln, SAFEARRAY*); - - private: - DISALLOW_COPY_AND_ASSIGN(MockHTMLDocument2); -}; - -#undef STUBMETHOD -#undef STUBGETPROP -#undef STUBPUTPROP -#undef STUBPROP - -template -HRESULT CComObjectCreatorHelper(CComObject** ptr) { - if (!ptr) { - return E_POINTER; - } - CComObject* raw_ptr = NULL; - RET_IF_FAILED(CComObject::CreateInstance(&raw_ptr)); - raw_ptr->AddRef(); - *ptr = raw_ptr; - return S_OK; -} - - -} // namespace - -class Update3WebControlTest : public testing::Test { - protected: - virtual void SetUp() { - ASSERT_SUCCEEDED(CComObjectCreatorHelper(&control_)); - } - - virtual void TearDown() { - } - - HRESULT GetCurrentBrowserUrl(CString* url) { - return control_->site_lock_.GetCurrentBrowserUrl(control_, url); - } - - CComPtr > control_; -}; - -TEST_F(Update3WebControlTest, SiteLock) { - CComPtr > browser; - ASSERT_SUCCEEDED(CComObjectCreatorHelper(&browser)); - CComPtr unknown; - ASSERT_SUCCEEDED(browser.QueryInterface(&unknown)); - ASSERT_SUCCEEDED(control_->SetSite(unknown)); - browser->set_url("http://www.google.com/pack/page.html"); - EXPECT_EQ(E_POINTER, - control_->getInstalledVersion(CComBSTR(), VARIANT_FALSE, NULL)); -} - -TEST_F(Update3WebControlTest, SiteLock_Negative) { - CComPtr browser; - ASSERT_SUCCEEDED(CComCoClass::CreateInstance(&browser)); - ASSERT_SUCCEEDED(control_->SetSite(browser)); - EXPECT_EQ(GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED, - control_->getInstalledVersion(CComBSTR(), VARIANT_FALSE, NULL)); -} - -TEST_F(Update3WebControlTest, GetCurrentBrowserUrl_FailIfNoSite) { - CString url; - EXPECT_FALSE(SUCCEEDED(GetCurrentBrowserUrl(&url))); -} - -TEST_F(Update3WebControlTest, GetCurrentBrowserUrl_WithIWebBrowser2) { - CComPtr browser; - ASSERT_SUCCEEDED(CComCoClass::CreateInstance(&browser)); - ASSERT_SUCCEEDED(control_->SetSite(browser)); - CString url; - EXPECT_EQ(S_OK, GetCurrentBrowserUrl(&url)); - EXPECT_STREQ(L"something-like-a-url", url); -} - -TEST_F(Update3WebControlTest, GetCurrentBrowserUrl_WithIHTMLDocument2) { - CComPtr document; - ASSERT_SUCCEEDED(CComCoClass::CreateInstance(&document)); - ASSERT_SUCCEEDED(control_->SetSite(document)); - CString url; - EXPECT_EQ(S_OK, GetCurrentBrowserUrl(&url)); - EXPECT_STREQ(L"something-else-like-a-url", url); -} - -} // namespace omaha diff --git a/omaha/plugins/update/build.scons b/omaha/plugins/update/build.scons deleted file mode 100644 index 05acb1639..000000000 --- a/omaha/plugins/update/build.scons +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/python2.4 -# -# Copyright 2009 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ======================================================================== - - -Import('env') - -# Need to do all these modifications to the non-default env because calling -# EnablePrecompile on the main environment, which customization_test_env clones. -# causes the opt build to fail. -# TODO(omaha): How much of this needs to be used by all libraries that get built -# and how much can be moved to BuildNpGoogleUpdateDll? -update_env = env.Clone() -update_env.Append( - CPPDEFINES = [ - # TODO(omaha): ActiveX plugins are usually apartment-threaded. There's - # no problem with compiling at a higher threading level than required, - # but there is a slight performance penalty for AddRef()/Release(). At - # some point, it may be desirable to switch back to apartment threaded, - # once the unit tests are fixed. - # We also take a 1KiB penalty for using _ATL_FREE_THREADED =) - '_ATL_FREE_THREADED', - ], - CPPFLAGS = [ - '/wd4263', # member function does not override any base class virtual - # member function - '/wd4264', # no override available for virtual member function; - # function is hidden - '/wd4265', # class has virtual functions, but destructor is not virtual - '/wd4310', # cast truncates constant value - '/wd4350', # behavior change: 'member1' called instead of 'member2' - '/wd4548', # expression before comma has no effect; expected expression - # with side-effect - '/wd4986', # exception spec does not match previous declaration - '/wd5038', # data member will be initialized after data member - ], - CPPPATH = [ - '$OBJ_ROOT', # Needed for generated files. - ], - LIBS = [ - '$LIB_DIR/base.lib', - '$LIB_DIR/breakpad.lib', - '$LIB_DIR/client.lib', - '$LIB_DIR/core.lib', - '$LIB_DIR/crx_file.lib', - '$LIB_DIR/google_update_recovery.lib', - '$LIB_DIR/goopdate_lib.lib', - '$LIB_DIR/libprotobuf.lib', - '$LIB_DIR/logging.lib', - '$LIB_DIR/net.lib', - '$LIB_DIR/omaha3_idl.lib', - '$LIB_DIR/security.lib', - '$LIB_DIR/service.lib', - '$LIB_DIR/setup.lib', - '$LIB_DIR/statsreport.lib', - '$LIB_DIR/ui.lib', - env['atls_libs'][env.Bit('debug')], - env['crt_libs'][env.Bit('debug')], - 'bits.lib', - 'comctl32.lib', - 'crypt32.lib', - 'imagehlp.lib', - 'iphlpapi.lib', - 'msi.lib', - 'msimg32.lib', - 'mstask.lib', - 'psapi.lib', - 'netapi32.lib', - 'shlwapi.lib', - 'taskschd.lib', - 'userenv.lib', - 'uxtheme.lib', - 'version.lib', - 'wintrust.lib', - 'wtsapi32.lib', - ], - LINKFLAGS = [ - '/DYNAMICBASE', # Enable ASLR. - '/NXCOMPAT', # Enable NX support. - ], -) -if update_env.Bit('has_device_management'): - update_env.Append( - LIBS = [ - '$LIB_DIR/dm_proto.lib', - ], - ) - -# COM stuff. -midl_env = env.Clone() -midl_env.Tool('midl') -# Generate optimized, stubless proxy/stub code. -midl_env['MIDLFLAGS'] += [ '/Oicf', ] - -# For some reason, calling TypeLibrary() twice on the same environment causes a -# re-link of the test executable when alternating between "hammer" and -# "hammer run_all_tests". -# To work around this, clone the original environment and call TypeLibrary once -# on each. Note that: -# 1) Cloning midl_env BEFORE TypeLibrary() is called does not solve this -# problem. The environment must be cloned from the original env. -# 2) Moving the following code down near npapi_testing_midl_env.TypeLibrary -# does not solve the problem either. -# 3) This problem does not occur if 'update_npapi_testing.lib' is passed as -# a source to other builders instead of as a LIB. -npapi_testing_midl_env = env.Clone() -npapi_testing_midl_env.Tool('midl') -# Generate optimized, stubless proxy/stub code. -npapi_testing_midl_env['MIDLFLAGS'] += [ '/Oicf', ] - -midl_env.TypeLibrary('activex/update_control_idl.idl') -update_control_idl_guids_lib = env.ComponentLibrary( - lib_name='update_control_idl_guids_lib', - source='$OBJ_ROOT/plugins/update/activex/update_control_idl_i.c', -) - -# Built as library to enable unit testing. -inputs = [ - 'activex/update3web_control.cc', - 'activex/oneclick_control.cc', - 'npapi/dispatch_host.cc', - 'npapi/npfunction_host.cc', - 'npapi/urlpropbag.cc', - 'npapi/np_update.cc', - 'npapi/variant_utils.cc', - 'config.cc', - 'site_lock.cc', - ] -update_lib = update_env.ComponentLibrary( - lib_name='update', - source=inputs, -) - - -def BuildNpGoogleUpdateDll(omaha_version_info): - plugin_env = update_env.Clone(COMPONENT_STATIC = False) - - prefix = omaha_version_info.filename_prefix - if prefix: - plugin_env['OBJPREFIX'] = plugin_env.subst(prefix + 'obj/$OBJPREFIX') - - version_string = omaha_version_info.GetVersionString() - plugin_env.Append( - LIBS = [ - '$LIB_DIR/common.lib', - '$LIB_DIR/plugin_base.lib', - 'wininet.lib', - update_control_idl_guids_lib, - update_lib, - ], - RCFLAGS = [ - '/DVERSION_MAJOR=%d' % omaha_version_info.version_major, - '/DVERSION_MINOR=%d' % omaha_version_info.version_minor, - '/DVERSION_BUILD=%d' % omaha_version_info.version_build, - '/DVERSION_PATCH=%d' % omaha_version_info.version_patch, - '/DVERSION_NUMBER_STRING=\\"%s\\"' % version_string, - ], - ) - - - resource = plugin_env.RES(target='%sresource.res' % prefix, - source='resource.rc') - plugin_env.Depends( - resource, - ['$MAIN_DIR/VERSION', - '$OBJ_ROOT/plugins/update/activex/update_control_idl.tlb', - 'oneclick.rgs']) - - target_name = '%s%s' % ( - prefix, - omaha_version_info.plugin_signed_file_info.unsigned_filename_base) - - inputs = [ - 'module.def', - 'module.cc', - resource, - ] - - unsigned_dll = plugin_env.ComponentLibrary( - lib_name=target_name, - source=inputs, - ) - - signed_dll = plugin_env.DualSignedBinary( - target='%s%s' % (prefix, - omaha_version_info.plugin_signed_file_info.filename), - source=unsigned_dll, - ) - - env.Replicate('$STAGING_DIR', signed_dll) - env.Replicate('$STAGING_DIR', [f for f in unsigned_dll if f.suffix == '.pdb']) - - -for omaha_version_info in env['omaha_versions_info']: - BuildNpGoogleUpdateDll(omaha_version_info) - - -# -# Tests -# - -# NPAPI unit test helper library -npapi_testing_midl_env.TypeLibrary('npapi/testing/dispatch_host_test_idl.idl') -update_env.ComponentLibrary( - lib_name = 'update_test_helpers', - source = [ - 'npapi/testing/dispatch_host_test_interface.cc', - 'npapi/testing/stubs.cc', - ] -) - -# NPAPI unit test resource -npapi_test_lib_resources = update_env.RES( - target='npapi/testing/dispatch_host_test.res', - source='npapi/testing/dispatch_host_test.rc'), -# TODO(omaha): we should really just make a proper .rc file scanner. -update_env.Depends( - npapi_test_lib_resources, - '$OBJ_ROOT/plugins/update/npapi/testing/dispatch_host_test_idl.tlb') diff --git a/omaha/plugins/update/config.cc b/omaha/plugins/update/config.cc deleted file mode 100644 index 6a4a2af8c..000000000 --- a/omaha/plugins/update/config.cc +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/config.h" -#include -#include "omaha/base/constants.h" - -namespace omaha { - -const TCHAR kUpdate3WebPluginVersion[] = _T(UPDATE_PLUGIN_VERSION_ANSI); -const TCHAR kUpdate3WebControlProgId[] = COMPANY_NAME_IDENTIFIER _T(".") \ - _T("Update3WebControl.") \ - _T(UPDATE_PLUGIN_VERSION_ANSI); - -const TCHAR kOneclickPluginVersion[] = _T(ONECLICK_PLUGIN_VERSION_ANSI); -const TCHAR kOneclickControlProgId[] = COMPANY_NAME_IDENTIFIER _T(".") \ - _T("OneClickCtrl.") \ - _T(ONECLICK_PLUGIN_VERSION_ANSI); - -} // namespace omaha diff --git a/omaha/plugins/update/config.h b/omaha/plugins/update/config.h deleted file mode 100644 index b76198446..000000000 --- a/omaha/plugins/update/config.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_CONFIG_H_ -#define OMAHA_PLUGINS_UPDATE_CONFIG_H_ - -#include - -namespace omaha { - -// TODO(omaha3): The OneClick MIME type is currently defined one other place in -// the codebase, in base\const_config.h. I'm putting our own definition here; -// we should probably delete the copy in base, and potentially moving this file -// to base as plugin_constants.h. -// -// Note that COMPANY_DOMAIN_BASE_ANSI and *_PLUGIN_VERSION_ANSI are defined -// in omaha\main.scons. - -#define UPDATE3WEB_MIME_TYPE "application/x-vnd." COMPANY_DOMAIN_BASE_ANSI \ - ".update3webcontrol." UPDATE_PLUGIN_VERSION_ANSI - -#define ONECLICK_MIME_TYPE "application/x-vnd." COMPANY_DOMAIN_BASE_ANSI \ - ".oneclickctrl." ONECLICK_PLUGIN_VERSION_ANSI - -#define MERGED_MIME_TYPE UPDATE3WEB_MIME_TYPE "|" ONECLICK_MIME_TYPE - -extern const TCHAR kUpdate3WebPluginVersion[]; -extern const TCHAR kUpdate3WebControlProgId[]; - -extern const TCHAR kOneclickPluginVersion[]; -extern const TCHAR kOneclickControlProgId[]; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_CONFIG_H_ diff --git a/omaha/plugins/update/generate_plugin_idls.py b/omaha/plugins/update/generate_plugin_idls.py deleted file mode 100644 index 069a7aa18..000000000 --- a/omaha/plugins/update/generate_plugin_idls.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/python2.4 -# -# Copyright 2007-2009 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ======================================================================== - -""" -Generates IDL file for the OneClick ActiveX control from the passed-in IDL -template. The input template is a complete IDL file in all but one respect; -It has one replaceable entry for the CLSID for GoopdateOneClickControl. -We generate a GUID using UUIDGEN.EXE, and write out an IDL with a new CLSID. - -""" - -import sys -import os -import getopt -import commands - - -def _GetStatusOutput(cmd): - """Return (status, output) of executing cmd in a shell.""" - if os.name == "nt": - pipe = os.popen(cmd + " 2>&1", 'r') - text = pipe.read() - sts = pipe.close() - if sts is None: sts = 0 - if text[-1:] == '\n': text = text[:-1] - return sts, text - else: - return commands.getstatusoutput(cmd) - - -def _GenerateIDLText(idl_template): - (status, guid) = _GetStatusOutput("uuidgen.exe") - if status != 0: - raise SystemExit("Failed to get GUID: %s" % guid) - - return idl_template % guid - - -def _GenerateIDLFile(idl_template_filename, idl_output_filename): - f_in = open(idl_template_filename, 'r') - idl_template = f_in.read() - f_in.close() - - idl_output = _GenerateIDLText(idl_template) - - f_out = open(idl_output_filename, 'w') - f_out.write(""" - // ** AUTOGENERATED FILE. DO NOT HAND-EDIT ** - """) - f_out.write(idl_output) - f_out.close() - - -def _Usage(): - """Prints out script usage information.""" - print """ -generate_oneclick_idl.py: Write out the given IDL file. - -Usage: - generate_oneclick_idl.py [--help - | --idl_template_file filename - --idl_output_file filename] - -Options: - --help Show this information. - --idl_output_file filename Path/name of output IDL filename. - --idl_template_file filename Path/name of input IDL template. -""" - - -def _Main(): - """Generates IDL file.""" - # use getopt to parse the option and argument list; this may raise, but - # don't catch it - _ARGUMENT_LIST = ["help", "idl_template_file=", "idl_output_file="] - (opts, args) = getopt.getopt(sys.argv[1:], "", _ARGUMENT_LIST) - if not opts or ("--help", "") in opts: - _Usage() - sys.exit() - - idl_template_filename = "" - idl_output_filename = "" - - for (o, v) in opts: - if o == "--idl_template_file": - idl_template_filename = v - if o == "--idl_output_file": - idl_output_filename = v - - # make sure we have work to do - if not idl_template_filename: - raise SystemExit("no idl_template_filename specified") - if not idl_output_filename: - raise SystemExit("no idl_output_filename specified") - - _GenerateIDLFile(idl_template_filename, idl_output_filename) - sys.exit() - - -if __name__ == "__main__": - _Main() - diff --git a/omaha/plugins/update/module.cc b/omaha/plugins/update/module.cc deleted file mode 100644 index f52e0a6fe..000000000 --- a/omaha/plugins/update/module.cc +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include -#include "base/basictypes.h" -#include "omaha/base/omaha_version.h" -#include "goopdate/omaha3_idl.h" -#include "omaha/plugins/update/activex/update3web_control.h" -#include "omaha/plugins/update/activex/oneclick_control.h" -#include "plugins/update/activex/update_control_idl.h" - -namespace omaha { - -OBJECT_ENTRY_AUTO(__uuidof(GoogleUpdateOneClickControlCoClass), OneClickControl) -OBJECT_ENTRY_AUTO(__uuidof(GoogleUpdate3WebControlCoClass), Update3WebControl) - -namespace { - -class GoogleUpdateControlModule - : public CAtlDllModuleT { - public: - GoogleUpdateControlModule() {} - - DECLARE_LIBID(LIBID_GoogleUpdateControlLib); - - private: - DISALLOW_COPY_AND_ASSIGN(GoogleUpdateControlModule); // NOLINT -} _AtlModule; - -} // namespace - -} // namespace omaha - -BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { - switch (reason) { - case DLL_PROCESS_ATTACH: - omaha::InitializeVersionFromModule(instance); - break; - default: - break; - } - - return omaha::_AtlModule.DllMain(reason, reserved); -} - -STDAPI DllCanUnloadNow() { - return omaha::_AtlModule.DllCanUnloadNow(); -} - -STDAPI DllGetClassObject(REFCLSID clsid, REFIID iid, void** ppv) { - return omaha::_AtlModule.DllGetClassObject(clsid, iid, ppv); -} - -STDAPI DllRegisterServer() { - return omaha::_AtlModule.DllRegisterServer(false); -} - -STDAPI DllUnregisterServer() { - return omaha::_AtlModule.DllUnregisterServer(false); -} diff --git a/omaha/plugins/update/module.def b/omaha/plugins/update/module.def deleted file mode 100644 index e98111ec9..000000000 --- a/omaha/plugins/update/module.def +++ /dev/null @@ -1,23 +0,0 @@ -; Copyright 2009 Google Inc. -; -; Licensed under the Apache License, Version 2.0 (the "License"); -; you may not use this file except in compliance with the License. -; You may obtain a copy of the License at -; -; http://www.apache.org/licenses/LICENSE-2.0 -; -; Unless required by applicable law or agreed to in writing, software -; distributed under the License is distributed on an "AS IS" BASIS, -; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -; See the License for the specific language governing permissions and -; limitations under the License. -; ======================================================================== - -EXPORTS - NP_GetEntryPoints @1 - NP_Initialize @2 - NP_Shutdown @3 - DllCanUnloadNow PRIVATE - DllGetClassObject PRIVATE - DllRegisterServer PRIVATE - DllUnregisterServer PRIVATE diff --git a/omaha/plugins/update/npapi/dispatch_host.cc b/omaha/plugins/update/npapi/dispatch_host.cc deleted file mode 100644 index d188031ca..000000000 --- a/omaha/plugins/update/npapi/dispatch_host.cc +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// TODO(omaha): use NPN_SetException to return useful error information. - -#include "omaha/plugins/update/npapi/dispatch_host.h" - -#include -#include "base/logging.h" -#include "base/scope_guard.h" -#include "omaha/base/safe_format.h" -#include "omaha/base/string.h" -#include "omaha/plugins/update/npapi/variant_utils.h" - -namespace omaha { - -namespace { - -void SetExceptionIfFailed(NPObject* object, HRESULT result) { - if (FAILED(result)) { - CStringA message; - SafeCStringAFormat(&message, "0x%08x", result); - NPN_SetException(object, message); - } -} - -} // namespace - -DispatchHost* DispatchHost::CreateInstance(NPP npp, IDispatch* dispatch) { - ASSERT1(dispatch); - DispatchHost* host = static_cast( - NPN_CreateObject(npp, &kNPClass_)); - host->dispatch_ = dispatch; - CORE_LOG(L3, (L"[DispatchHost::DispatchHost][this=0x%p][dispatch=0x%p]", - host, dispatch)); - return host; -} - -DispatchHost::DispatchHost(NPP npp) : npp_(npp) { -} - -DispatchHost::~DispatchHost() { - CORE_LOG(L3, (L"[DispatchHost::~DispatchHost][this=0x%p][dispatch=0x%p]", - this, dispatch_)); -} - -DISPID DispatchHost::GetDispatchId(NPIdentifier name) { - NPUTF8* utf8_name = NPN_UTF8FromIdentifier(name); - CString wide_name = Utf8ToWideChar(utf8_name, lstrlenA(utf8_name)); - NPN_MemFree(utf8_name); - DISPID dispatch_id = DISPID_UNKNOWN; - HRESULT hr = dispatch_.GetIDOfName(wide_name, &dispatch_id); - if (FAILED(hr)) { - return DISPID_UNKNOWN; - } - return dispatch_id; -} - -// Whether or not a member should be treated as a property by NPAPI. A member is -// considered a property for NPAPI if either of the following are true: -// - The property is a getter with exactly one [out, retval] argument. -// - The property is a putter with exactly one [in] argument. -// The reason for this limitation is NPAPI does not support passing additional -// arguments when getting/setting properties. Properties that take additional -// arguments are handled as methods by NPAPI instead. -bool DispatchHost::IsProperty(DISPID dispatch_id) { - CComPtr type_info; - HRESULT hr = dispatch_->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &type_info); - if (FAILED(hr)) { - ASSERT(false, (L"[IsProperty][failed=0x%08x]", hr)); - return false; - } - TYPEATTR* type_attr; - hr = type_info->GetTypeAttr(&type_attr); - if (FAILED(hr)) { - ASSERT(false, (L"[IsProperty][failed=0x%08x]", hr)); - return false; - } - ON_SCOPE_EXIT_OBJ(*type_info.p, &ITypeInfo::ReleaseTypeAttr, type_attr); - - for (int i = 0; i < type_attr->cFuncs; ++i) { - FUNCDESC* func_desc = NULL; - hr = type_info->GetFuncDesc(i, &func_desc); - if (FAILED(hr)) { - ASSERT(false, (L"[IsProperty][failed=0x%08x]", hr)); - return false; - } - ON_SCOPE_EXIT_OBJ(*type_info.p, &ITypeInfo::ReleaseFuncDesc, func_desc); - if (dispatch_id == func_desc->memid) { - if (((func_desc->invkind & DISPATCH_PROPERTYGET) && - func_desc->cParams == 0) || - ((func_desc->invkind & DISPATCH_PROPERTYPUT) && - func_desc->cParams == 1 && - (func_desc->lprgelemdescParam[0].paramdesc.wParamFlags & - PARAMFLAG_FIN))) { - return true; - } - } - } - return false; -} - -// Simple helper to adapt NPAPI method/property invocations to IDispatch::Invoke -// by wrapping/unwrapping NPVariants into VARIANTs. -HRESULT DispatchHost::InvokeHelper(DISPID dispatch_id, WORD flags, - const NPVariant* args, uint32_t arg_count, - NPP npp, NPVariant* result) { - ASSERT1(args || arg_count == 0); - ASSERT1(result); - CORE_LOG(L3, (L"[InvokeHelper][this=0x%p][dispatch=0x%p][flags=0x%x]" - L"[arg_count=%d]", this, dispatch_, flags, arg_count)); - - // Just in case a rogue browser decides to use the return value on failure. - VOID_TO_NPVARIANT(*result); - std::unique_ptr dispatch_args(new CComVariant[arg_count]); - - // IDispatch::Invoke expects arguments in "reverse" order - for (uint32_t i = 0 ; i < arg_count; ++i) { - NPVariantToVariant(npp, args[i], &dispatch_args[arg_count - i - 1]); - } - DISPPARAMS dispatch_params = {}; - dispatch_params.rgvarg = dispatch_args.get(); - dispatch_params.cArgs = arg_count; - CComVariant dispatch_result; - HRESULT hr = dispatch_->Invoke(dispatch_id, IID_NULL, LOCALE_USER_DEFAULT, - flags, &dispatch_params, &dispatch_result, - NULL, NULL); - if (FAILED(hr)) { - CORE_LOG(L3, (L"[InvokeHelper][failed_hr=0x%p]", hr)); - return hr; - } - VariantToNPVariant(npp, dispatch_result, result); - return hr; -} - -NPObject* DispatchHost::Allocate(NPP npp, NPClass* class_functions) { - UNREFERENCED_PARAMETER(class_functions); - return new DispatchHost(npp); -} - -void DispatchHost::Deallocate(NPObject* object) { - delete static_cast(object); -} - -bool DispatchHost::HasMethod(NPObject* object, NPIdentifier name) { - DispatchHost* host = static_cast(object); - DISPID dispatch_id = host->GetDispatchId(name); - return dispatch_id != DISPID_UNKNOWN && !host->IsProperty(dispatch_id); -} - -bool DispatchHost::Invoke(NPObject* object, NPIdentifier name, - const NPVariant* args, uint32_t arg_count, - NPVariant* result) { - DispatchHost* host = static_cast(object); - CORE_LOG(L3, (L"[DispatchHost::Invoke][this=0x%p][dispatch=0x%p]", - host, host->dispatch_)); - HRESULT hr = host->InvokeHelper(host->GetDispatchId(name), - DISPATCH_METHOD | DISPATCH_PROPERTYGET, - args, - arg_count, - host->npp_, - result); - SetExceptionIfFailed(object, hr); - return SUCCEEDED(hr); -} - -bool DispatchHost::InvokeDefault(NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result) { - DispatchHost* host = static_cast(object); - CORE_LOG(L3, (L"[DispatchHost::InvokeDefault][this=0x%p][dispatch=0x%p]", - host, host->dispatch_)); - HRESULT hr = host->InvokeHelper(DISPID_VALUE, - DISPATCH_METHOD | DISPATCH_PROPERTYGET, - args, - arg_count, - host->npp_, - result); - SetExceptionIfFailed(object, hr); - return SUCCEEDED(hr); -} - -bool DispatchHost::HasProperty(NPObject* object, NPIdentifier name) { - DispatchHost* host = static_cast(object); - DISPID dispatch_id = host->GetDispatchId(name); - return dispatch_id != DISPID_UNKNOWN && host->IsProperty(dispatch_id); -} - -bool DispatchHost::GetProperty(NPObject* object, NPIdentifier name, - NPVariant* result) { - DispatchHost* host = static_cast(object); - CORE_LOG(L3, (L"[DispatchHost::GetProperty][this=0x%p][dispatch=0x%p]", - host, host->dispatch_)); - HRESULT hr = host->InvokeHelper(host->GetDispatchId(name), - DISPATCH_PROPERTYGET, - NULL, - 0, - host->npp_, - result); - SetExceptionIfFailed(object, hr); - return SUCCEEDED(hr); -} - -bool DispatchHost::SetProperty(NPObject* object, NPIdentifier name, - const NPVariant* value) { - DispatchHost* host = static_cast(object); - CORE_LOG(L3, (L"[DispatchHost::SetProperty][this=0x%p][dispatch=0x%p]", - host, host->dispatch_)); - DISPID dispatch_id = host->GetDispatchId(name); - CComVariant dispatch_arg; - NPVariantToVariant(host->npp_, *value, &dispatch_arg); - HRESULT hr = host->dispatch_.PutProperty(dispatch_id, &dispatch_arg); - SetExceptionIfFailed(object, hr); - return SUCCEEDED(hr); -} - -bool DispatchHost::RemoveProperty(NPObject* object, NPIdentifier name) { - UNREFERENCED_PARAMETER(object); - UNREFERENCED_PARAMETER(name); - return false; -} - -bool DispatchHost::Enumerate(NPObject* object, NPIdentifier** names, - uint32_t* count) { - UNREFERENCED_PARAMETER(object); - UNREFERENCED_PARAMETER(names); - UNREFERENCED_PARAMETER(count); - return false; -} - -bool DispatchHost::Construct(NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result) { - UNREFERENCED_PARAMETER(object); - UNREFERENCED_PARAMETER(args); - UNREFERENCED_PARAMETER(arg_count); - UNREFERENCED_PARAMETER(result); - return false; -} - -NPClass DispatchHost::kNPClass_ = { - NP_CLASS_STRUCT_VERSION, - Allocate, - Deallocate, - NULL, - HasMethod, - Invoke, - InvokeDefault, - HasProperty, - GetProperty, - SetProperty, - RemoveProperty, - Enumerate, - Construct, -}; - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/dispatch_host.h b/omaha/plugins/update/npapi/dispatch_host.h deleted file mode 100644 index 7bdcb02e5..000000000 --- a/omaha/plugins/update/npapi/dispatch_host.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// DispatchHost hosts an IDispatch object inside a NPObject to allow scripting -// of COM objects from a NPAPI environment. Types are automatically marshalled -// between NPVariant and VARIANT using the functions in variant_utils.h. -// Limitations: -// - IDispatch methods/properties may only take arguments of type VT_VOID, -// VT_NULL, VT_BOOL, VT_I4, VT_R8, and VT_BSTR -// - Multiple out parameters are not supported. -// - IDispatch methods/properties may only return a value of type VT_EMPTY, -// VT_VOID, VT_NULL, VT_BOOL, VT_I4, VT_UI4, VT_R8, VT_BSTR, and VT_DISPATCH -// - A method and property a property that takes additional arguments may not -// have the same identifier--the method will not be callable through -// DispatchHost. - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_DISPATCH_HOST_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_DISPATCH_HOST_H_ - -#include -#include - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace omaha { - -class DispatchHostTest; - -class DispatchHost : public NPObject { - public: - static DispatchHost* CreateInstance(NPP npp, IDispatch* dispatch); - - private: - explicit DispatchHost(NPP npp); - ~DispatchHost(); - - DISPID GetDispatchId(NPIdentifier name); - bool IsProperty(DISPID dispatch_id); - HRESULT InvokeHelper(DISPID dispatch_id, WORD flags, const NPVariant* args, - uint32_t arg_count, NPP npp, NPVariant* result); - - static NPObject* Allocate(NPP npp, NPClass *class_functions); - static void Deallocate(NPObject* object); - static bool HasMethod(NPObject* object, NPIdentifier name); - static bool Invoke(NPObject* object, NPIdentifier name, const NPVariant* args, - uint32_t arg_count, NPVariant* result); - static bool InvokeDefault(NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result); - static bool HasProperty(NPObject* object, NPIdentifier name); - static bool GetProperty(NPObject* object, NPIdentifier name, - NPVariant* result); - static bool SetProperty(NPObject* object, NPIdentifier name, - const NPVariant* value); - static bool RemoveProperty(NPObject* object, NPIdentifier name); - static bool Enumerate(NPObject* object, NPIdentifier** names, - uint32_t* count); - static bool Construct(NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result); - - NPP npp_; - // The hosted dispatch object. - CComPtr dispatch_; - - // The NPObject vtable. - static NPClass kNPClass_; - - friend class DispatchHostTest; - - DISALLOW_COPY_AND_ASSIGN(DispatchHost); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_DISPATCH_HOST_H_ diff --git a/omaha/plugins/update/npapi/dispatch_host_unittest.cc b/omaha/plugins/update/npapi/dispatch_host_unittest.cc deleted file mode 100644 index 1fe08e10a..000000000 --- a/omaha/plugins/update/npapi/dispatch_host_unittest.cc +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/dispatch_host.h" -#include -#include -#include -#include -#include "omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h" -#include "omaha/plugins/update/npapi/testing/stubs.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -class DispatchHostTest : public testing::Test { - protected: - virtual void SetUp() { - CComPtr dispatch; - ASSERT_SUCCEEDED( - CComCoClass::CreateInstance(&dispatch)); - dispatch_host_ = NPN_CreateObject(NULL, &DispatchHost::kNPClass_); - static_cast(dispatch_host_)->dispatch_ = dispatch.Detach(); - VOID_TO_NPVARIANT(result_); - } - - virtual void TearDown() { - NPN_ReleaseObject(dispatch_host_); - for (std::vector::iterator it = args_.begin(); - it != args_.end(); ++it) { - NPN_ReleaseVariantValue(&*it); - } - NPN_ReleaseVariantValue(&result_); - } - - void UseTestInterface2() { - NPN_ReleaseObject(dispatch_host_); - CComPtr dispatch; - ASSERT_SUCCEEDED( - CComCoClass::CreateInstance(&dispatch)); - dispatch_host_ = NPN_CreateObject(NULL, &DispatchHost::kNPClass_); - static_cast(dispatch_host_)->dispatch_ = dispatch.Detach(); - } - - void PushArg(bool value) { - args_.push_back(NPVariant()); - BOOLEAN_TO_NPVARIANT(value, args_.back()); - } - - void PushArg(int32 value) { - args_.push_back(NPVariant()); - INT32_TO_NPVARIANT(value, args_.back()); - } - - void PushArg(double value) { - args_.push_back(NPVariant()); - DOUBLE_TO_NPVARIANT(value, args_.back()); - } - - void PushArg(const char* value) { - args_.push_back(NPVariant()); - - #pragma warning(push) - // conversion from 'size_t' to 'uint32_t', possible loss of data. - #pragma warning(disable : 4267) - - // TODO(omaha): _strdup is an implementation detail of the stubs. - STRINGZ_TO_NPVARIANT(_strdup(value), args_.back()); - - #pragma warning(pop) - } - - NPObject* dispatch_host_; - NPIdentifierFactory id_factory_; - - std::vector args_; - NPVariant result_; -}; - -TEST_F(DispatchHostTest, HasMethod) { - EXPECT_TRUE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("Random"))); - EXPECT_TRUE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("AddAsMethod"))); - - // Property getters with input arguments should be treated as methods. - EXPECT_TRUE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("AddAsProperty"))); - - // Properties and non-existent members are not methods. - EXPECT_FALSE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("Property"))); - EXPECT_FALSE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("ReadOnlyProperty"))); - EXPECT_FALSE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("WriteOnlyProperty"))); - EXPECT_FALSE(NPN_HasMethod(NULL, dispatch_host_, - id_factory_.Create("DoesNotExist"))); -} - -TEST_F(DispatchHostTest, InvokeNoArgs) { - EXPECT_TRUE(NPN_Invoke(NULL, dispatch_host_, id_factory_.Create("Random"), - NULL, 0, &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(42, result_.value.intValue); -} - -TEST_F(DispatchHostTest, InvokeWithArgs) { - PushArg(7); - PushArg(27); - EXPECT_TRUE(NPN_Invoke(NULL, dispatch_host_, - id_factory_.Create("AddAsMethod"), &args_.front(), - static_cast(args_.size()), &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(34, result_.value.intValue); -} - -TEST_F(DispatchHostTest, InvokePropertyWithArgs) { - // Property getters that have input args should be handle by Invoke - PushArg(8); - PushArg(15); - EXPECT_TRUE(NPN_Invoke(NULL, dispatch_host_, - id_factory_.Create("AddAsProperty"), &args_.front(), - static_cast(args_.size()), &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(23, result_.value.intValue); -} - -TEST_F(DispatchHostTest, InvokeNonexistentMethod) { - // Non-existent method, should fail. - INT32_TO_NPVARIANT(0x19821982, result_); - EXPECT_FALSE(NPN_Invoke(NULL, dispatch_host_, - id_factory_.Create("NonExistent"), NULL, 0, - &result_)); - EXPECT_TRUE(NPVARIANT_IS_VOID(result_)); -} - -TEST_F(DispatchHostTest, InvokeWithIncompatibleArgs) { - PushArg("Hello World!"); - PushArg(0x19851985); - INT32_TO_NPVARIANT(0x19881988, result_); - EXPECT_FALSE(NPN_Invoke(NULL, dispatch_host_, - id_factory_.Create("AddAsMethod"), &args_.front(), - static_cast(args_.size()), &result_)); - EXPECT_TRUE(NPVARIANT_IS_VOID(result_)); -} - -TEST_F(DispatchHostTest, InvokeWithIncorrectNumberOfArgs) { - PushArg("Don't panic."); - INT32_TO_NPVARIANT(0x77777777, result_); - EXPECT_FALSE(NPN_Invoke(NULL, dispatch_host_, id_factory_.Create("Random"), - &args_.front(), static_cast(args_.size()), - &result_)); - EXPECT_TRUE(NPVARIANT_IS_VOID(result_)); -} - -TEST_F(DispatchHostTest, InvokeDefault) { - EXPECT_TRUE(NPN_InvokeDefault(NULL, dispatch_host_, NULL, 0, &result_)); - EXPECT_TRUE(NPVARIANT_IS_OBJECT(result_)); -} - -TEST_F(DispatchHostTest, InvokeDefaultPropertyWithArgs) { - UseTestInterface2(); - PushArg(1048576); - EXPECT_TRUE(NPN_InvokeDefault(NULL, dispatch_host_, &args_.front(), - static_cast(args_.size()), &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(1048576 * 2, result_.value.intValue); -} - -// TODO(omaha): implement negative test - -TEST_F(DispatchHostTest, HasProperty) { - EXPECT_TRUE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("Property"))); - EXPECT_TRUE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("ReadOnlyProperty"))); - EXPECT_TRUE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("WriteOnlyProperty"))); - - // Property getters with input arguments should not be treated as properties. - EXPECT_FALSE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("AddAsProperty"))); - - // Methods and non-existent members are not properties. - EXPECT_FALSE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("Random"))); - EXPECT_FALSE(NPN_HasProperty(NULL, dispatch_host_, - id_factory_.Create("DoesNotExist"))); -} - -TEST_F(DispatchHostTest, GetProperty) { - EXPECT_TRUE(NPN_GetProperty(NULL, dispatch_host_, - id_factory_.Create("Property"), &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(0xdeadbeef, result_.value.intValue); -} - -TEST_F(DispatchHostTest, GetPropertyReadOnly) { - EXPECT_TRUE(NPN_GetProperty(NULL, dispatch_host_, - id_factory_.Create("ReadOnlyProperty"), - &result_)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result_)); - EXPECT_EQ(19700101, result_.value.intValue); -} - -TEST_F(DispatchHostTest, SetProperty) { - PushArg(20002000); - EXPECT_TRUE(NPN_SetProperty(NULL, dispatch_host_, - id_factory_.Create("Property"), &args_.front())); -} - -TEST_F(DispatchHostTest, SetPropertyWriteOnly) { - PushArg(20612061); - EXPECT_TRUE(NPN_SetProperty(NULL, dispatch_host_, - id_factory_.Create("WriteOnlyProperty"), - &args_.front())); -} - -TEST_F(DispatchHostTest, Unsupported) { - EXPECT_FALSE(NPN_RemoveProperty(NULL, dispatch_host_, NULL)); - EXPECT_FALSE(NPN_Enumerate(NULL, dispatch_host_, NULL, NULL)); - EXPECT_FALSE(NPN_Construct(NULL, dispatch_host_, NULL, 0, NULL)); -} - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/np_update.cc b/omaha/plugins/update/npapi/np_update.cc deleted file mode 100644 index 948c0fa99..000000000 --- a/omaha/plugins/update/npapi/np_update.cc +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/np_update.h" - -#include -#include - -#include "omaha/base/debug.h" -#include "omaha/base/scope_guard.h" -#include "omaha/base/string.h" -#include "omaha/plugins/update/config.h" -#include "omaha/plugins/update/npapi/dispatch_host.h" -#include "omaha/plugins/update/npapi/urlpropbag.h" -#include "plugins/update/activex/update_control_idl.h" - -NPError NS_PluginInitialize() { - return NPERR_NO_ERROR; -} - -void NS_PluginShutdown() { -} - -nsPluginInstanceBase* NS_NewPluginInstance(nsPluginCreateData* data) { - return new omaha::NPUpdate(data->instance, data->type); -} - -void NS_DestroyPluginInstance(nsPluginInstanceBase* plugin) { - delete plugin; -} - -namespace omaha { - -NPUpdate::NPUpdate(NPP instance, const char* mime_type) - : instance_(instance), - is_initialized_(false), - mime_type_(mime_type), - scriptable_object_(NULL) { - ASSERT1(instance); - // TODO(omaha): initialize COM -} - -NPUpdate::~NPUpdate() { - if (scriptable_object_) { - NPN_ReleaseObject(scriptable_object_); - } -} - -NPBool NPUpdate::init(NPWindow* np_window) { - UNREFERENCED_PARAMETER(np_window); - is_initialized_ = true; - return TRUE; -} - -void NPUpdate::shut() { - is_initialized_ = false; -} - -NPBool NPUpdate::isInitialized() { - // TODO(omaha): figure the right boolean type to return here... - return is_initialized_ ? TRUE : FALSE; -} - -NPError NPUpdate::GetValue(NPPVariable variable, void* value) { - if (!instance_) { - return NPERR_INVALID_INSTANCE_ERROR; - } - - if (NPPVpluginScriptableNPObject != variable || !value) { - return NPERR_INVALID_PARAM; - } - - CString url; - if (!GetCurrentBrowserUrl(&url) || !site_lock_.InApprovedDomain(url)) { - return NPERR_INVALID_URL; - } - - if (!scriptable_object_) { - CComPtr p; - - CLSID clsid; - if (!MapMimeTypeToClsid(&clsid)) { - return NPERR_INVALID_PLUGIN_ERROR; - } - if (FAILED(p.CoCreateInstance(clsid))) { - return NPERR_OUT_OF_MEMORY_ERROR; - } - - // Store the current URL in a property bag and set it as the site of - // the object. - CComPtr pb; - if (FAILED(UrlPropertyBag::Create(url, &pb))) { - return NPERR_GENERIC_ERROR; - } - CComPtr sited_obj; - if (FAILED(p.QueryInterface(&sited_obj))) { - return NPERR_GENERIC_ERROR; - } - if (FAILED(sited_obj->SetSite(pb))) { - return NPERR_GENERIC_ERROR; - } - - scriptable_object_ = DispatchHost::CreateInstance(instance_, p); - } - - if (scriptable_object_) { - NPN_RetainObject(scriptable_object_); - } else { - return NPERR_OUT_OF_MEMORY_ERROR; - } - - *(reinterpret_cast(value)) = scriptable_object_; - return NPERR_NO_ERROR; -} - -bool NPUpdate::MapMimeTypeToClsid(CLSID* clsid) { - ASSERT1(clsid); - // TODO(omaha): We could probably abstract this out to a map that can - // have entries added to it at runtime, making this module fully generic. - // We could also consider extracting the MIME_TYPE resource from the current - // DLL and populating it from that. - if (0 == mime_type_.CompareNoCase(CString(UPDATE3WEB_MIME_TYPE))) { - *clsid = __uuidof(GoogleUpdate3WebControlCoClass); - return true; - } - if (0 == mime_type_.CompareNoCase(CString(ONECLICK_MIME_TYPE))) { - *clsid = __uuidof(GoogleUpdateOneClickControlCoClass); - return true; - } - return false; -} - -bool NPUpdate::GetCurrentBrowserUrl(CString* url) { - ASSERT1(url); - - NPObject* window = NULL; - NPError error = NPN_GetValue(instance_, NPNVWindowNPObject, &window); - if (NPERR_NO_ERROR != error || !window) { - ASSERT(false, (L"NPN_GetValue returned error %d", error)); - return false; - } - ON_SCOPE_EXIT(NPN_ReleaseObject, window); - - NPIdentifier location_id = NPN_GetStringIdentifier("location"); - NPVariant location; - NULL_TO_NPVARIANT(location); - if (!NPN_GetProperty(instance_, window, location_id, &location)) { - ASSERT1(false); - return false; - } - ON_SCOPE_EXIT(NPN_ReleaseVariantValue, &location); - if (!NPVARIANT_IS_OBJECT(location)) { - ASSERT(false, (L"Variant type: %d", location.type)); - return false; - } - - NPIdentifier href_id = NPN_GetStringIdentifier("href"); - NPVariant href; - NULL_TO_NPVARIANT(href); - if (!NPN_GetProperty(instance_, NPVARIANT_TO_OBJECT(location), href_id, - &href)) { - ASSERT1(false); - return false; - } - ON_SCOPE_EXIT(NPN_ReleaseVariantValue, &href); - if (!NPVARIANT_IS_STRING(href)) { - ASSERT(false, (L"Variant type: %d", href.type)); - return false; - } - - *url = Utf8ToWideChar(NPVARIANT_TO_STRING(href).UTF8Characters, - NPVARIANT_TO_STRING(href).UTF8Length); - return true; -} - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/np_update.h b/omaha/plugins/update/npapi/np_update.h deleted file mode 100644 index c8668e7c0..000000000 --- a/omaha/plugins/update/npapi/np_update.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_NP_UPDATE_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_NP_UPDATE_H_ - -#include -#include "base/basictypes.h" -#include "omaha/plugins/base/pluginbase.h" -#include "omaha/plugins/update/site_lock.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace omaha { - -class DispatchHost; - -class NPUpdate : public nsPluginInstanceBase { - public: - explicit NPUpdate(NPP instance, const char* mime_type); - virtual ~NPUpdate(); - - // nsPluginInstanceBase overrides. - virtual NPBool init(NPWindow* np_window); - virtual void shut(); - virtual NPBool isInitialized(); - virtual NPError GetValue(NPPVariable variable, void* value); - - private: - bool GetCurrentBrowserUrl(CString* url); - bool MapMimeTypeToClsid(CLSID* clsid); - - NPP instance_; - bool is_initialized_; - CString mime_type_; - SiteLock site_lock_; - DispatchHost* scriptable_object_; - - friend class NPUpdateTest; - - DISALLOW_COPY_AND_ASSIGN(NPUpdate); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_NP_UPDATE_H_ diff --git a/omaha/plugins/update/npapi/npfunction_host.cc b/omaha/plugins/update/npapi/npfunction_host.cc deleted file mode 100644 index fd2c79219..000000000 --- a/omaha/plugins/update/npapi/npfunction_host.cc +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/npfunction_host.h" - -#include -#include "omaha/base/debug.h" -#include "omaha/base/utils.h" -#include "omaha/plugins/update/npapi/variant_utils.h" - -namespace omaha { - -typedef CComObject CComNpFuncHost; -typedef scoped_any scoped_host; - -HRESULT NpFunctionHost::Create(NPP npp, NPObject* npobj, IDispatch** host) { - ASSERT1(npobj); - ASSERT1(host); - - if (!npobj || !host) { - return E_INVALIDARG; - } - - // Create the host and hand off the NPObject to it. - scoped_host comobj; - HRESULT hr = CComNpFuncHost::CreateInstance(address(comobj)); - if (FAILED(hr)) { - return hr; - } - get(comobj)->AddRef(); - - comobj->npp_ = npp; - comobj->obj_ = npobj; - NPN_RetainObject(npobj); - - return comobj->QueryInterface(host); -} - -STDMETHODIMP NpFunctionHost::GetTypeInfoCount(UINT* pctinfo) { - if (pctinfo == NULL) { - return E_INVALIDARG; - } - *pctinfo = 0; - return S_OK; -} - -STDMETHODIMP NpFunctionHost::GetTypeInfo(UINT iTInfo, - LCID lcid, - ITypeInfo** ppTInfo) { - UNREFERENCED_PARAMETER(iTInfo); - UNREFERENCED_PARAMETER(lcid); - UNREFERENCED_PARAMETER(ppTInfo); - - return E_NOTIMPL; -} - -STDMETHODIMP NpFunctionHost::GetIDsOfNames(REFIID riid, - LPOLESTR* rgszNames, - UINT cNames, - LCID lcid, - DISPID* rgDispId) { - UNREFERENCED_PARAMETER(riid); - UNREFERENCED_PARAMETER(rgszNames); - UNREFERENCED_PARAMETER(cNames); - UNREFERENCED_PARAMETER(lcid); - UNREFERENCED_PARAMETER(rgDispId); - - return E_NOTIMPL; -} - -STDMETHODIMP NpFunctionHost::Invoke(DISPID dispIdMember, - REFIID riid, - LCID lcid, - WORD wFlags, - DISPPARAMS* pDispParams, - VARIANT* pVarResult, - EXCEPINFO* pExcepInfo, - UINT* puArgErr) { - UNREFERENCED_PARAMETER(dispIdMember); - UNREFERENCED_PARAMETER(riid); - UNREFERENCED_PARAMETER(lcid); - UNREFERENCED_PARAMETER(pExcepInfo); - UNREFERENCED_PARAMETER(puArgErr); - - if (wFlags != DISPATCH_METHOD) { - return DISP_E_MEMBERNOTFOUND; - } - - uint32_t num_args = 0; - std::unique_ptr arguments; - if (pDispParams) { - // Javascript doesn't officially support named args, so the current - // implementation ignores any named args that are supplied. However, - // you can cast a function object to a string and it will hold the - // argument names as used in the function definition. Thus, if we - // need to support named arguments in the future, we may be able to - // get the argument names indirectly using NPN_Evaluate() and emulate. - if (pDispParams->cNamedArgs != 0) { - return DISP_E_NONAMEDARGS; - } - if (pDispParams->cArgs != 0) { - num_args = pDispParams->cArgs; - arguments.reset(new NPVariant[num_args]); - for (uint32_t i = 0; i < num_args; ++i) { - // Arguments are stored in rgvarg in reverse order. - VariantToNPVariant(npp_, - pDispParams->rgvarg[num_args - 1 - i], - &arguments[i]); - } - } - } - - NPVariant retval; - VOID_TO_NPVARIANT(retval); - - bool result = NPN_InvokeDefault(npp_, - obj_, - arguments.get(), - num_args, - &retval); - if (result && pVarResult) { - NPVariantToVariant(npp_, retval, pVarResult); - } - NPN_ReleaseVariantValue(&retval); - - return result ? S_OK : E_FAIL; -} - -void NpFunctionHost::FinalRelease() { - ASSERT1(obj_); - if (obj_) { - NPN_ReleaseObject(obj_); - obj_ = NULL; - } -} - -NpFunctionHost::NpFunctionHost() : npp_(NULL), obj_(NULL) {} - -} // namespace omaha - diff --git a/omaha/plugins/update/npapi/npfunction_host.h b/omaha/plugins/update/npapi/npfunction_host.h deleted file mode 100644 index 11587d4c2..000000000 --- a/omaha/plugins/update/npapi/npfunction_host.h +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// NpFunctionHost hosts an NPObject inside an IDispatch interface to allow -// invoking NPAPI functions from a COM environment. Types are automatically -// marshalled between NPVariant and VARIANT using the functions in -// variant_utils.h. (For the reverse -- providing an NPObject interface to -// a COM object implementing IDispatch -- see DispatchHost.) -// -// Note that this currently only supports functions; this does not currently -// support objects. NPN_Enumerate() only provides method/property names, -// not return types or argument counts/types, which makes it impossible to -// properly implement IDispatch::GetTypeInfo(). (However, we can implement -// GetIDsOfNames() if we need it in the future.) - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_NPFUNCTION_HOST_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_NPFUNCTION_HOST_H_ - -#include -#include - -#include "base/basictypes.h" -#include "third_party/npapi/bindings/nphostapi.h" - -namespace omaha { - -class NpFunctionHostTest; - -class ATL_NO_VTABLE NpFunctionHost - : public CComObjectRootEx, - public IDispatch { - public: - static HRESULT Create(NPP npp, NPObject* npobj, IDispatch** host); - - BEGIN_COM_MAP(NpFunctionHost) - COM_INTERFACE_ENTRY(IDispatch) - END_COM_MAP() - - // IDispatch methods. - STDMETHOD(GetTypeInfoCount)(UINT* pctinfo); - STDMETHOD(GetTypeInfo)(UINT iTInfo, - LCID lcid, - ITypeInfo** ppTInfo); - STDMETHOD(GetIDsOfNames)(REFIID riid, - LPOLESTR* rgszNames, - UINT cNames, - LCID lcid, - DISPID* rgDispId); - STDMETHOD(Invoke)(DISPID dispIdMember, - REFIID riid, - LCID lcid, - WORD wFlags, - DISPPARAMS* pDispParams, - VARIANT* pVarResult, - EXCEPINFO* pExcepInfo, - UINT* puArgErr); - - // CComObjectRootEx overrides. - void FinalRelease(); - - protected: - NpFunctionHost(); - virtual ~NpFunctionHost() {} - - private: - NPP npp_; - NPObject* obj_; - - DISALLOW_COPY_AND_ASSIGN(NpFunctionHost); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_NPFUNCTION_HOST_H_ diff --git a/omaha/plugins/update/npapi/npfunction_host_unittest.cc b/omaha/plugins/update/npapi/npfunction_host_unittest.cc deleted file mode 100644 index ca9d8c5af..000000000 --- a/omaha/plugins/update/npapi/npfunction_host_unittest.cc +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/npfunction_host.h" -#include -#include -#include -#include -#include "omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h" -#include "omaha/plugins/update/npapi/testing/stubs.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -class NpFunctionHostTest; - -class MockFunctionNPObject : public NPObject { - public: - static MockFunctionNPObject* CreateInstance(NpFunctionHostTest* creator) { - NPObject* obj = NPN_CreateObject(NULL, &MockFunctionNPObject::kNPClass_); - MockFunctionNPObject* realobj = static_cast(obj); - realobj->creator_ = creator; - return realobj; - } - - static NPObject* Allocate(NPP npp, NPClass* class_functions) { - UNREFERENCED_PARAMETER(class_functions); - return new MockFunctionNPObject(npp); - } - - static void Deallocate(NPObject* object) { - delete static_cast(object); - } - - static bool InvokeDefault(NPObject* object, - const NPVariant* args, - uint32_t arg_count, - NPVariant* result) { - MockFunctionNPObject* realobj = static_cast(object); - return realobj->InvokeDefaultLocal(args, arg_count, result); - } - - bool InvokeDefaultLocal(const NPVariant* args, - uint32_t arg_count, - NPVariant* result); - - protected: - explicit MockFunctionNPObject(NPP npp) : npp_(npp), creator_(NULL) {} - - static NPUTF8* NPN_ReallocateStringZ(const char* string) { - uint32 buflen = static_cast(strlen(string) + 1); - NPUTF8* npnstr = reinterpret_cast(NPN_MemAlloc(buflen)); - memmove(npnstr, string, buflen); - return npnstr; - } - - private: - NPP npp_; - NpFunctionHostTest* creator_; - - // The NPObject vtable. - static NPClass kNPClass_; -}; - -class NpFunctionHostTest : public testing::Test { - protected: - friend class MockFunctionNPObject; - - virtual void SetUp() { - function_ = MockFunctionNPObject::CreateInstance(this); - EXPECT_SUCCEEDED(NpFunctionHost::Create(NULL, function_, &host_)); - } - - virtual void TearDown() { - } - - NPObject* function_; - CComPtr host_; - - std::vector mock_args_; - NPVariant mock_result_; -}; - -NPClass MockFunctionNPObject::kNPClass_ = { - NP_CLASS_STRUCT_VERSION, - Allocate, - Deallocate, - NULL, - NULL, - NULL, - InvokeDefault, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, -}; - -bool MockFunctionNPObject::InvokeDefaultLocal(const NPVariant* args, - uint32_t arg_count, - NPVariant* result) { - const char* kMultiStringReturn = "multi"; - - // The mock NPObject exhibits the following external behavior: - // * If no arguments, return nothing - // * If one argument, return a boolean (true) - // * If two arguments, return a string ("multi") - // * Otherwise, treat it as an invoke failure. - // It also copies the arguments as supplied, and the intended NPVariant - // return value, to the test closure that created it. - - creator_->mock_args_.resize(arg_count); - for (uint32_t i = 0; i < arg_count; ++i) { - creator_->mock_args_[i] = args[i]; - } - - switch (arg_count) { - case 0: - VOID_TO_NPVARIANT(*result); - break; - case 1: - BOOLEAN_TO_NPVARIANT(true, *result); - break; - case 2: - { - #pragma warning(push) - // conversion from 'size_t' to 'uint32_t', possible loss of data. - #pragma warning(disable : 4267) - - NPUTF8* utf8string = NPN_ReallocateStringZ(kMultiStringReturn); - STRINGZ_TO_NPVARIANT(utf8string, *result); - - #pragma warning(pop) - } - break; - default: - return false; - } - - creator_->mock_result_ = *result; - return true; -} - -TEST_F(NpFunctionHostTest, GetTypeInfoCount) { - UINT typeinfos_available = 1; - EXPECT_SUCCEEDED(host_->GetTypeInfoCount(&typeinfos_available)); - EXPECT_EQ(0, typeinfos_available); -} - -TEST_F(NpFunctionHostTest, GetTypeInfo_NotImplemented) { - ITypeInfo* typeinfo = NULL; - - EXPECT_EQ(E_NOTIMPL, host_->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo)); -} - -TEST_F(NpFunctionHostTest, GetIDsOfNames_NotImplemented) { - LPOLESTR member_name = const_cast(L"NonexistentMember"); - DISPID member_dispid = 0; - EXPECT_EQ(E_NOTIMPL, host_->GetIDsOfNames(IID_NULL, &member_name, 1, - LOCALE_SYSTEM_DEFAULT, - &member_dispid)); -} - -TEST_F(NpFunctionHostTest, Invoke_NonMethod_NotSupported) { - EXPECT_EQ(DISP_E_MEMBERNOTFOUND, host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_PROPERTYGET, - NULL, - NULL, - NULL, - NULL)); -} - -TEST_F(NpFunctionHostTest, Invoke_NamedArgs_NotSupported) { - DISPID param_name = 12; - DISPPARAMS params = {}; - params.cNamedArgs = 1; - params.rgdispidNamedArgs = ¶m_name; - EXPECT_EQ(DISP_E_NONAMEDARGS, host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - ¶ms, - NULL, - NULL, - NULL)); -} - -TEST_F(NpFunctionHostTest, Invoke_NoArgs_NullDispParams) { - VARIANT retval = {}; - EXPECT_SUCCEEDED(host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - NULL, - &retval, - NULL, - NULL)); - - EXPECT_EQ(0, static_cast(mock_args_.size())); - - EXPECT_TRUE(NPVARIANT_IS_VOID(mock_result_)); - EXPECT_EQ(VT_EMPTY, retval.vt); - VariantClear(&retval); -} - -TEST_F(NpFunctionHostTest, Invoke_NoArgs_ValidDispParams) { - VARIANT retval = {}; - DISPPARAMS params = {}; - EXPECT_SUCCEEDED(host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - ¶ms, - &retval, - NULL, - NULL)); - - EXPECT_EQ(0, static_cast(mock_args_.size())); - - EXPECT_TRUE(NPVARIANT_IS_VOID(mock_result_)); - EXPECT_EQ(VT_EMPTY, retval.vt); - VariantClear(&retval); -} - -TEST_F(NpFunctionHostTest, Invoke_NoArgs_OneParam) { - const int kTestIntVal = 0xDEADBEEF; - - VARIANT retval = {}; - VARIANT firstparam = {}; - firstparam.vt = VT_I4; - firstparam.intVal = kTestIntVal; - - DISPPARAMS dispparams = {}; - dispparams.cArgs = 1; - dispparams.rgvarg = &firstparam; - - EXPECT_SUCCEEDED(host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparams, - &retval, - NULL, - NULL)); - - EXPECT_EQ(1, mock_args_.size()); - EXPECT_TRUE(NPVARIANT_IS_INT32(mock_args_[0])); - EXPECT_EQ(kTestIntVal, NPVARIANT_TO_INT32(mock_args_[0])); - - EXPECT_TRUE(NPVARIANT_IS_BOOLEAN(mock_result_)); - EXPECT_EQ(true, NPVARIANT_TO_BOOLEAN(mock_result_)); - EXPECT_EQ(VT_BOOL, retval.vt); - EXPECT_EQ(VARIANT_TRUE, retval.boolVal); - VariantClear(&retval); -} - -TEST_F(NpFunctionHostTest, Invoke_NoArgs_TwoParams) { - const double kTestFloatVal = 3.1415927; - - VARIANT retval = {}; - VARIANT params[2] = {}; - params[0].vt = VT_BOOL; // Invoke expects args in reverse order - params[0].intVal = VARIANT_TRUE; - params[1].vt = VT_R8; - params[1].dblVal = kTestFloatVal; - - DISPPARAMS dispparams = {}; - dispparams.cArgs = 2; - dispparams.rgvarg = params; - EXPECT_SUCCEEDED(host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparams, - &retval, - NULL, - NULL)); - - EXPECT_EQ(2, mock_args_.size()); - EXPECT_TRUE(NPVARIANT_IS_DOUBLE(mock_args_[0])); - EXPECT_EQ(kTestFloatVal, NPVARIANT_TO_DOUBLE(mock_args_[0])); - EXPECT_TRUE(NPVARIANT_IS_BOOLEAN(mock_args_[1])); - EXPECT_EQ(true, NPVARIANT_TO_BOOLEAN(mock_args_[1])); - - EXPECT_TRUE(NPVARIANT_IS_STRING(mock_result_)); - // Don't check mock_result's contents; it will have been released by Invoke() - EXPECT_EQ(VT_BSTR, retval.vt); - EXPECT_STREQ(CString("multi"), CString(retval.bstrVal)); - VariantClear(&retval); -} - -TEST_F(NpFunctionHostTest, Invoke_NoArgs_ThreeParams) { - VARIANT retval = {}; - VARIANT params[3] = {}; - for (int i = 0; i < 3; ++i) { - params[i].vt = VT_BOOL; - params[i].intVal = VARIANT_TRUE; - } - - DISPPARAMS dispparams = {}; - dispparams.cArgs = 3; - dispparams.rgvarg = params; - EXPECT_EQ(E_FAIL, host_->Invoke(0, IID_NULL, - LOCALE_SYSTEM_DEFAULT, - DISPATCH_METHOD, - &dispparams, - &retval, - NULL, - NULL)); - EXPECT_EQ(3, mock_args_.size()); -} - - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test.rc b/omaha/plugins/update/npapi/testing/dispatch_host_test.rc deleted file mode 100644 index 0b44ad0ec..000000000 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test.rc +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include -#include "omaha/plugins/update/npapi/testing/resource.h" - -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -IDR_DISPATCH_HOST_TEST_TLB TYPELIB "plugins/update/npapi/testing/dispatch_host_test_idl.tlb" diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test_idl.idl b/omaha/plugins/update/npapi/testing/dispatch_host_test_idl.idl deleted file mode 100644 index dcb1007d6..000000000 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test_idl.idl +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -import "oaidl.idl"; -import "ocidl.idl"; - -[ - object, - uuid(d5c74868-1734-44e1-bab2-187a0ad2bd37), - dual, - pointer_default(unique) -] -interface IDispatchHostTestInterface : IDispatch { - [id(1)] HRESULT Random([out, retval] INT* x); - - [propget] HRESULT Property([out, retval] INT* x); - [propput] HRESULT Property([in] INT x); - - [propget] HRESULT ReadOnlyProperty([out, retval] INT* x); - [propput] HRESULT WriteOnlyProperty([in] INT x); - - [id(2)] HRESULT AddAsMethod([in] INT a, [in] INT b, [out, retval] INT* c); - [id(3), propget] HRESULT AddAsProperty([in] INT a, [in] INT b, - [out, retval] INT* c); - - // TODO(omaha): do we need to test multi-argument property putters? - - [id(DISPID_VALUE)] HRESULT DidYouMeanRecursion([out, retval] IDispatch** me); -}; - -[ - object, - uuid(0abeb84d-6a9c-4c5c-9394-6123c933baec), - dual, - pointer_default(unique) -] -interface IDispatchHostTestInterface2 : IDispatch { - [id(DISPID_VALUE), propget] HRESULT Get([in] INT index, [out, retval] INT* x); -}; - -[ - uuid(65530e7f-4922-49e2-a5ee-c3e172da974a), -] -library DispatchHostTestingLib { - importlib("stdole2.tlb"); - - interface IDispatchHostTestInterface; - interface IDispatchHostTestInterface2; -}; diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.cc b/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.cc deleted file mode 100644 index 07608093f..000000000 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.cc +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h" - -namespace omaha { - -STDMETHODIMP DispatchHostTestInterface::Random(INT* x) { - *x = 42; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::get_Property(INT* x) { - *x = 0xdeadbeef; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::put_Property(INT x) { - UNREFERENCED_PARAMETER(x); - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::get_ReadOnlyProperty(INT* x) { - *x = 19700101; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::put_WriteOnlyProperty(INT x) { - UNREFERENCED_PARAMETER(x); - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::AddAsMethod(INT a, INT b, INT* c) { - *c = a + b; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::get_AddAsProperty( - INT a, INT b, INT* c) { - *c = a + b; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface::DidYouMeanRecursion(IDispatch** me) { - *me = this; - return S_OK; -} - -STDMETHODIMP DispatchHostTestInterface2::get_Get(INT index, INT* x) { - *x = index << 1; - return S_OK; -} - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h b/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h deleted file mode 100644 index 589b22347..000000000 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_DISPATCH_HOST_TEST_INTERFACE_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_DISPATCH_HOST_TEST_INTERFACE_H_ - -#include -#include -#include - -#include "base/basictypes.h" -#include "omaha/base/app_util.h" -#include "omaha/plugins/update/npapi/testing/resource.h" -#include "plugins/update/npapi/testing/dispatch_host_test_idl.h" - -namespace omaha { - -// This class allows for using IDispatchImpl with a specific TypeLib, in a -// module that has multiple TYPELIB resources. Ordinarily, IDispatchImpl will -// only load the first TYPELIB resource in the module, which does not work for -// omaha_unittest.exe. Hence the need for this class. This class loads the TLB -// with the specified resource id, and uses that for subsequent IDispatch -// requests. -// TODO(omaha3): Perhaps move this class into a generic utility header. - -template -class ATL_NO_VTABLE IDispatchImplResId : public IDispatchImpl { - public: - IDispatchImplResId() { - CComPtr type_lib; - CString tlb_path; - - // Format the path as "ModulePath\\ResourceId". Specifying a ResourceId - // allows overriding the default behavior of LoadTypeLib to load the first - // TYPELIB resource from the module. - tlb_path.Format(_T("%s\\%d"), app_util::GetCurrentModuleName(), tlb_res_id); - - HRESULT hr = LoadTypeLib(tlb_path, &type_lib); - if (FAILED(hr)) { - return; - } - - CComPtr type_info; - hr = type_lib->GetTypeInfoOfGuid(*piid, &type_info); - if (FAILED(hr)) { - return; - } - - CComPtr type_info2; - if (SUCCEEDED(type_info->QueryInterface(&type_info2))) { - type_info = type_info2; - } - - // Override the ITypeInfo in the CComTypeInfoHolder, which will be used in - // subsequent calls to the IDispatch methods. - this->_tih.m_pInfo = type_info.Detach(); - } - - virtual ~IDispatchImplResId() {} -}; - -class ATL_NO_VTABLE DispatchHostTestInterface - : public CComObjectRootEx, - public IDispatchImplResId { - public: - DispatchHostTestInterface() {} - virtual ~DispatchHostTestInterface() {} - - DECLARE_NOT_AGGREGATABLE(DispatchHostTestInterface); - - BEGIN_COM_MAP(DispatchHostTestInterface) - COM_INTERFACE_ENTRY(IDispatch) - END_COM_MAP() - - // IDispatchHostTestInterface methods. - STDMETHOD(Random)(INT* x); - - STDMETHOD(get_Property)(INT* x); - STDMETHOD(put_Property)(INT x); - - STDMETHOD(get_ReadOnlyProperty)(INT* x); - STDMETHOD(put_WriteOnlyProperty)(INT x); - - STDMETHOD(AddAsMethod)(INT a, INT b, INT* c); - STDMETHOD(get_AddAsProperty)(INT a, INT b, INT* c); - - STDMETHOD(DidYouMeanRecursion)(IDispatch** me); - - private: - DISALLOW_COPY_AND_ASSIGN(DispatchHostTestInterface); -}; - -class ATL_NO_VTABLE DispatchHostTestInterface2 - : public CComObjectRootEx, - public IDispatchImplResId { - public: - DispatchHostTestInterface2() {} - virtual ~DispatchHostTestInterface2() {} - - DECLARE_NOT_AGGREGATABLE(DispatchHostTestInterface2); - - BEGIN_COM_MAP(DispatchHostTestInterface) - COM_INTERFACE_ENTRY(IDispatch) - END_COM_MAP() - - // IDispatchHostTestInterface2 methods. - STDMETHOD(get_Get)(INT index, INT* x); - - private: - DISALLOW_COPY_AND_ASSIGN(DispatchHostTestInterface2); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_DISPATCH_HOST_TEST_INTERFACE_H_ diff --git a/omaha/plugins/update/npapi/testing/resource.h b/omaha/plugins/update/npapi/testing/resource.h deleted file mode 100644 index 6bfedb3f8..000000000 --- a/omaha/plugins/update/npapi/testing/resource.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_RESOURCE_H__ -#define OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_RESOURCE_H__ - -#define IDR_DISPATCH_HOST_TEST_TLB 3 - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_RESOURCE_H__ diff --git a/omaha/plugins/update/npapi/testing/stubs.cc b/omaha/plugins/update/npapi/testing/stubs.cc deleted file mode 100644 index 30921cc5c..000000000 --- a/omaha/plugins/update/npapi/testing/stubs.cc +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/testing/stubs.h" -#include -#include -#include "base/debug.h" - -namespace omaha { - -NPIdentifierFactory::NPIdentifierFactory() { -} - -NPIdentifierFactory::~NPIdentifierFactory() { - for (std::vector::const_iterator it = identifiers_.begin(); - it != identifiers_.end(); ++it) { - free(*it); - } -} - -NPIdentifier NPIdentifierFactory::Create(const char* name) { - NPIdentifier identifier = _strdup(name); - identifiers_.push_back(identifier); - return identifier; -} - -} // namespace omaha - -extern "C" { -void* NPN_MemAlloc(uint32 size) { - return malloc(size); -} - -void NPN_MemFree(void* ptr) { - free(ptr); -} - -NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier) { - return _strdup(static_cast(identifier)); -} - -NPObject* NPN_CreateObject(NPP npp, NPClass* class_vtable) { - UNREFERENCED_PARAMETER(npp); - ASSERT1(class_vtable); - NPObject* object = class_vtable->allocate(npp, class_vtable); - object->_class = class_vtable; - object->referenceCount = 1; - return object; -} - -NPObject* NPN_RetainObject(NPObject* object) { - ASSERT1(object); - ++object->referenceCount; - return object; -} - -void NPN_ReleaseObject(NPObject* object) { - ASSERT1(object); - ASSERT1(object->referenceCount > 0); - if (--object->referenceCount == 0) { - object->_class->deallocate(object); - } -} - -void NPN_ReleaseVariantValue(NPVariant* variant) { - if (NPVARIANT_IS_STRING(*variant)) { - NPN_MemFree(const_cast(variant->value.stringValue.UTF8Characters)); - } else if (NPVARIANT_IS_OBJECT(*variant)) { - NPN_ReleaseObject(variant->value.objectValue); - } - VOID_TO_NPVARIANT(*variant); - return; -} - -bool NPN_HasMethod(NPP npp, NPObject* object, NPIdentifier name) { - UNREFERENCED_PARAMETER(npp); - return object->_class->hasMethod(object, name); -} - -bool NPN_Invoke(NPP npp, NPObject* object, NPIdentifier name, - const NPVariant* args, uint32_t arg_count, NPVariant* result) { - UNREFERENCED_PARAMETER(npp); - return object->_class->invoke(object, name, args, arg_count, result); -} - -bool NPN_InvokeDefault(NPP npp, NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result) { - UNREFERENCED_PARAMETER(npp); - return object->_class->invokeDefault(object, args, arg_count, result); -} - -bool NPN_HasProperty(NPP npp, NPObject* object, NPIdentifier name) { - UNREFERENCED_PARAMETER(npp); - return object->_class->hasProperty(object, name); -} - -bool NPN_GetProperty(NPP npp, NPObject* object, NPIdentifier name, - NPVariant* result) { - UNREFERENCED_PARAMETER(npp); - return object->_class->getProperty(object, name, result); -} - -bool NPN_SetProperty(NPP npp, NPObject* object, NPIdentifier name, - const NPVariant* value) { - UNREFERENCED_PARAMETER(npp); - return object->_class->setProperty(object, name, value); -} - -bool NPN_RemoveProperty(NPP npp, NPObject* object, NPIdentifier name) { - UNREFERENCED_PARAMETER(npp); - return object->_class->removeProperty(object, name); -} - -bool NPN_Enumerate(NPP npp, NPObject* object, NPIdentifier** names, - uint32_t* count) { - UNREFERENCED_PARAMETER(npp); - return object->_class->enumerate(object, names, count); -} - -bool NPN_Construct(NPP npp, NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result) { - UNREFERENCED_PARAMETER(npp); - return object->_class->construct(object, args, arg_count, result); -} - -void NPN_SetException(NPObject* object, const NPUTF8* message) { - UNREFERENCED_PARAMETER(object); - UNREFERENCED_PARAMETER(message); -} -} // extern "C" diff --git a/omaha/plugins/update/npapi/testing/stubs.h b/omaha/plugins/update/npapi/testing/stubs.h deleted file mode 100644 index 76ba6b316..000000000 --- a/omaha/plugins/update/npapi/testing/stubs.h +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Normally, implementations of these functions are provided by the NPAPI -// runtime. These stub implementations are intended only for use in unit tests. - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_STUBS_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_STUBS_H_ - -#include -#include "third_party/npapi/bindings/nphostapi.h" - -namespace omaha { - -// Not part of NPAPI proper, but useful nonetheless. Note that the stub -// implementation of NPIdentifier does not conform to NPAPI's idea of what an -// NPIdentifier ought to be: specifically, uniqueness is not guaranteed. -class NPIdentifierFactory { - public: - NPIdentifierFactory(); - ~NPIdentifierFactory(); - NPIdentifier Create(const char* name); - - private: - std::vector identifiers_; - - DISALLOW_COPY_AND_ASSIGN(NPIdentifierFactory); -}; - -} // namespace omaha - -extern "C" { -void* NPN_MemAlloc(uint32 size); -void NPN_MemFree(void* ptr); -NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier); -NPObject* NPN_CreateObject(NPP npp, NPClass* class_vtable); -NPObject* NPN_RetainObject(NPObject* object); -void NPN_ReleaseObject(NPObject* object); -void NPN_ReleaseVariantValue(NPVariant* variant); - -bool NPN_HasMethod(NPP npp, NPObject* object, NPIdentifier name); -bool NPN_Invoke(NPP npp, NPObject* object, NPIdentifier name, - const NPVariant* args, uint32_t arg_count, NPVariant* result); -bool NPN_InvokeDefault(NPP npp, NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result); -bool NPN_HasProperty(NPP npp, NPObject* object, NPIdentifier name); -bool NPN_GetProperty(NPP npp, NPObject* object, NPIdentifier name, - NPVariant* result); -bool NPN_SetProperty(NPP npp, NPObject* object, NPIdentifier name, - const NPVariant* value); -bool NPN_RemoveProperty(NPP npp, NPObject* object, NPIdentifier name); -bool NPN_Enumerate(NPP npp, NPObject* object, NPIdentifier** names, - uint32_t* count); -bool NPN_Construct(NPP npp, NPObject* object, const NPVariant* args, - uint32_t arg_count, NPVariant* result); -void NPN_SetException(NPObject* object, const NPUTF8* message); -} // extern "C" - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_TESTING_STUBS_H_ - diff --git a/omaha/plugins/update/npapi/urlpropbag.cc b/omaha/plugins/update/npapi/urlpropbag.cc deleted file mode 100644 index 940a9b494..000000000 --- a/omaha/plugins/update/npapi/urlpropbag.cc +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/urlpropbag.h" - -#include "omaha/base/debug.h" -#include "omaha/base/utils.h" -#include "omaha/plugins/update/npapi/variant_utils.h" - -namespace omaha { - -typedef CComObject CComUrlBag; -typedef scoped_any scoped_bag; - -HRESULT UrlPropertyBag::Create(const TCHAR* url, IPropertyBag** pb) { - ASSERT1(url); - ASSERT1(pb); - - if (!url || !pb) { - return E_INVALIDARG; - } - - // Create the host and hand off the string to it. - scoped_bag comobj; - HRESULT hr = CComUrlBag::CreateInstance(address(comobj)); - if (FAILED(hr)) { - return hr; - } - get(comobj)->AddRef(); - - comobj->url_ = url; - - return comobj->QueryInterface(pb); -} - -STDMETHODIMP UrlPropertyBag::Read(LPCOLESTR pszPropName, VARIANT* pVar, - IErrorLog* pErrorLog) { - UNREFERENCED_PARAMETER(pErrorLog); - - ASSERT1(pszPropName); - ASSERT1(pVar); - if (!pszPropName || !pVar) { - return E_POINTER; - } - - if (0 == _tcscmp(pszPropName, kUrlPropertyBag_Url)) { - V_VT(pVar) = VT_BSTR; - V_BSTR(pVar) = url_.AllocSysString(); - return S_OK; - } - - return E_INVALIDARG; -} - -STDMETHODIMP UrlPropertyBag::Write(LPCOLESTR pszPropName, VARIANT* pVar) { - UNREFERENCED_PARAMETER(pszPropName); - UNREFERENCED_PARAMETER(pVar); - return E_FAIL; -} - -UrlPropertyBag::UrlPropertyBag() {} - -} // namespace omaha - diff --git a/omaha/plugins/update/npapi/urlpropbag.h b/omaha/plugins/update/npapi/urlpropbag.h deleted file mode 100644 index b670bc26d..000000000 --- a/omaha/plugins/update/npapi/urlpropbag.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_URLPROPBAG_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_URLPROPBAG_H_ - -#include -#include -#include - -#include "base/basictypes.h" - -namespace omaha { - -const TCHAR* const kUrlPropertyBag_Url = _T("omaha-urlpropertybag-url"); - -class ATL_NO_VTABLE UrlPropertyBag - : public CComObjectRootEx, - public IPropertyBag { - public: - static HRESULT Create(const TCHAR* url, IPropertyBag** pb); - - BEGIN_COM_MAP(UrlPropertyBag) - COM_INTERFACE_ENTRY(IPropertyBag) - END_COM_MAP() - - // IPropertyBag methods. - STDMETHOD(Read)(LPCOLESTR pszPropName, VARIANT* pVar, IErrorLog* pErrorLog); - STDMETHOD(Write)(LPCOLESTR pszPropName, VARIANT* pVar); - - protected: - UrlPropertyBag(); - virtual ~UrlPropertyBag() {} - - private: - CString url_; - - DISALLOW_COPY_AND_ASSIGN(UrlPropertyBag); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_URLPROPBAG_H_ diff --git a/omaha/plugins/update/npapi/variant_utils.cc b/omaha/plugins/update/npapi/variant_utils.cc deleted file mode 100644 index 4d60e0282..000000000 --- a/omaha/plugins/update/npapi/variant_utils.cc +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// TODO(omaha): verify that the new operator throws on failure to prevent NULL -// pointer exploits. - -#include "omaha/plugins/update/npapi/variant_utils.h" - -#include - -#include -#include "base/debug.h" -#include "base/string.h" -#include "omaha/plugins/update/npapi/dispatch_host.h" -#include "omaha/plugins/update/npapi/npfunction_host.h" - -namespace omaha { - -void NPVariantToVariant(NPP npp, - const NPVariant& source, - VARIANT* destination) { - ASSERT1(destination); - V_VT(destination) = VT_EMPTY; - - switch (source.type) { - case NPVariantType_Void: - V_VT(destination) = VT_EMPTY; - break; - case NPVariantType_Null: - V_VT(destination) = VT_NULL; - break; - case NPVariantType_Bool: - V_VT(destination) = VT_BOOL; - V_BOOL(destination) = source.value.boolValue ? VARIANT_TRUE - : VARIANT_FALSE; - break; - case NPVariantType_Int32: - V_VT(destination) = VT_I4; - V_I4(destination) = source.value.intValue; - break; - case NPVariantType_Double: - V_VT(destination) = VT_R8; - V_R8(destination) = source.value.doubleValue; - break; - case NPVariantType_String: - V_VT(destination) = VT_BSTR; - if (source.value.stringValue.UTF8Length) { - CString string = Utf8ToWideChar(source.value.stringValue.UTF8Characters, - source.value.stringValue.UTF8Length); - V_BSTR(destination) = string.AllocSysString(); - } else { - V_BSTR(destination) = CString().AllocSysString(); - } - break; - case NPVariantType_Object: - V_VT(destination) = VT_DISPATCH; - if (source.value.objectValue) { - NpFunctionHost::Create(npp, source.value.objectValue, - &V_DISPATCH(destination)); - } else { - V_DISPATCH(destination) = NULL; - } - break; - default: - ASSERT1(false); - break; - } -} - -void VariantToNPVariant(NPP npp, - const VARIANT& source, - NPVariant* destination) { - ASSERT1(destination); - VOID_TO_NPVARIANT(*destination); - - switch (V_VT(&source)) { - case VT_EMPTY: - VOID_TO_NPVARIANT(*destination); - break; - case VT_NULL: - NULL_TO_NPVARIANT(*destination); - break; - case VT_BOOL: - BOOLEAN_TO_NPVARIANT(V_BOOL(&source), *destination); - break; - case VT_I4: - INT32_TO_NPVARIANT(V_I4(&source), *destination); - break; - case VT_UI4: - INT32_TO_NPVARIANT(V_UI4(&source), *destination); - break; - case VT_R8: - DOUBLE_TO_NPVARIANT(V_R8(&source), *destination); - break; - case VT_BSTR: - if (V_BSTR(&source)) { - int source_length = ::SysStringLen(V_BSTR(&source)) + 1; - int buffer_length = ::WideCharToMultiByte(CP_UTF8, 0, V_BSTR(&source), - source_length, NULL, 0, NULL, - NULL); - if (buffer_length == 0) { - break; - } - char* buffer = static_cast(NPN_MemAlloc(buffer_length)); - VERIFY1(::WideCharToMultiByte(CP_UTF8, 0, V_BSTR(&source), - source_length, buffer, buffer_length, - NULL, NULL) > 0); - STRINGN_TO_NPVARIANT(buffer, - static_cast(buffer_length - 1), - *destination); - } else { - char* buffer = static_cast(NPN_MemAlloc(1)); - buffer[0] = '\0'; - STRINGN_TO_NPVARIANT(buffer, 0, *destination); - } - break; - case VT_DISPATCH: - if (V_DISPATCH(&source)) { - OBJECT_TO_NPVARIANT( - DispatchHost::CreateInstance(npp, V_DISPATCH(&source)), - *destination); - } - break; - default: - ASSERT(false, (L"Unhandled variant type %d", V_VT(&source))); - break; - } -} - -} // namespace omaha diff --git a/omaha/plugins/update/npapi/variant_utils.h b/omaha/plugins/update/npapi/variant_utils.h deleted file mode 100644 index d28392629..000000000 --- a/omaha/plugins/update/npapi/variant_utils.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Converts between NPVariant and VARIANT types. -// The following two-way conversions are supported: -// NPVariantType_Void <-> VT_EMPTY -// NPVariantType_Null <-> VT_NULL -// NPVariantType_Bool <-> VT_BOOL -// NPVariantType_Int32 <-> VT_I4 -// NPVariantType_Double <-> VT_R8 -// NPVariantType_String <-> VT_BSTR -// -// Furthermore, the following one-way conversions are supported: -// VT_UI4 -> NPVariantType_Int32 -// VT_DISPATCH -> NPVariantType_Object (DispatchHost) -// NPVariantType_Object -> VT_DISPATCH (NpFunctionHost) - -#ifndef OMAHA_PLUGINS_UPDATE_NPAPI_VARIANT_UTILS_H_ -#define OMAHA_PLUGINS_UPDATE_NPAPI_VARIANT_UTILS_H_ - -#include -#include "third_party/npapi/bindings/nphostapi.h" - -namespace omaha { - -void NPVariantToVariant(NPP npp, - const NPVariant& source, - VARIANT* destination); - -void VariantToNPVariant(NPP npp, - const VARIANT& source, - NPVariant* destination); - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_NPAPI_VARIANT_UTILS_H_ diff --git a/omaha/plugins/update/npapi/variant_utils_unittest.cc b/omaha/plugins/update/npapi/variant_utils_unittest.cc deleted file mode 100644 index b26737a47..000000000 --- a/omaha/plugins/update/npapi/variant_utils_unittest.cc +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/npapi/variant_utils.h" -#include -#include -#include -#include -#include -#include "omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h" -#include "omaha/plugins/update/npapi/testing/stubs.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -class VariantUtilsTest : public testing::Test { - protected: - virtual void SetUp() { - VOID_TO_NPVARIANT(np_variant_); - } - - virtual void TearDown() { - NPN_ReleaseVariantValue(&np_variant_); - } - - void TestNPV2V() { - NPVariantToVariant(NULL, np_variant_, &variant_); - ExpectTypesEquivalent(); - } - - void TestV2NPV() { - NPN_ReleaseVariantValue(&np_variant_); - VariantToNPVariant(NULL, variant_, &np_variant_); - ExpectTypesEquivalent(); - } - - void ExpectTypesEquivalent() { - switch (V_VT(&variant_)) { - case VT_EMPTY: - EXPECT_TRUE(NPVARIANT_IS_VOID(np_variant_)); - return; - break; - case VT_NULL: - EXPECT_TRUE(NPVARIANT_IS_NULL(np_variant_)); - return; - break; - case VT_BOOL: - EXPECT_TRUE(NPVARIANT_IS_BOOLEAN(np_variant_)); - return; - break; - case VT_I4: - case VT_UI4: - EXPECT_TRUE(NPVARIANT_IS_INT32(np_variant_)); - return; - break; - case VT_R8: - EXPECT_TRUE(NPVARIANT_IS_DOUBLE(np_variant_)); - return; - break; - case VT_BSTR: - EXPECT_TRUE(NPVARIANT_IS_STRING(np_variant_)); - return; - break; - case VT_DISPATCH: - EXPECT_TRUE(NPVARIANT_IS_OBJECT(np_variant_)); - return; - break; - default: - break; - } - ASSERT(false, (L"Expected equivalent types but got the following instead:\n" - L" np_variant_.type -> %d\n V_VT(&variant_) -> %d\n", - np_variant_.type, V_VT(&variant_))); - } - - NPVariant np_variant_; - CComVariant variant_; -}; - -TEST_F(VariantUtilsTest, NPVariantToVariant_Void) { - VOID_TO_NPVARIANT(np_variant_); - TestNPV2V(); -} - -TEST_F(VariantUtilsTest, NPVariantToVariant_Null) { - NULL_TO_NPVARIANT(np_variant_); - TestNPV2V(); -} - -TEST_F(VariantUtilsTest, NPVariantToVariant_Bool) { - BOOLEAN_TO_NPVARIANT(true, np_variant_); - TestNPV2V(); - EXPECT_EQ(VARIANT_TRUE, V_BOOL(&variant_)); - - BOOLEAN_TO_NPVARIANT(false, np_variant_); - TestNPV2V(); - EXPECT_EQ(VARIANT_FALSE, V_BOOL(&variant_)); -} - -TEST_F(VariantUtilsTest, NPVariantToVariant_Int32) { - INT32_TO_NPVARIANT(std::numeric_limits::min(), np_variant_); - TestNPV2V(); - EXPECT_EQ(std::numeric_limits::min(), V_I4(&variant_)); - - INT32_TO_NPVARIANT(0, np_variant_); - TestNPV2V(); - EXPECT_EQ(0, V_I4(&variant_)); - - INT32_TO_NPVARIANT(std::numeric_limits::max(), np_variant_); - TestNPV2V(); - EXPECT_EQ(std::numeric_limits::max(), V_I4(&variant_)); -} - -TEST_F(VariantUtilsTest, NPVariantToVariant_Double) { - DOUBLE_TO_NPVARIANT(-1, np_variant_); - TestNPV2V(); - EXPECT_DOUBLE_EQ(-1, V_R8(&variant_)); - - DOUBLE_TO_NPVARIANT(0, np_variant_); - TestNPV2V(); - EXPECT_DOUBLE_EQ(0, V_R8(&variant_)); - - DOUBLE_TO_NPVARIANT(static_cast(std::numeric_limits::max()), - np_variant_); - TestNPV2V(); - EXPECT_DOUBLE_EQ(static_cast(std::numeric_limits::max()), - V_R8(&variant_)); -} - -TEST_F(VariantUtilsTest, NPVariantToVariant_String) { - #pragma warning(push) - // conversion from 'size_t' to 'uint32_t', possible loss of data. - #pragma warning(disable : 4267) - - // TODO(omaha): _strdup depends on an implementation detail of the stubs. - STRINGZ_TO_NPVARIANT(_strdup(""), np_variant_); - TestNPV2V(); - EXPECT_STREQ(L"", V_BSTR(&variant_)); - - // Force the length to be zero. - STRINGZ_TO_NPVARIANT(_strdup("junk"), np_variant_); - np_variant_.value.stringValue.UTF8Length = 0; - TestNPV2V(); - EXPECT_STREQ(L"", V_BSTR(&variant_)); - - STRINGZ_TO_NPVARIANT(_strdup("ROBERT'); DROP TABLE Students; --"), - np_variant_); - TestNPV2V(); - EXPECT_STREQ(L"ROBERT'); DROP TABLE Students; --", V_BSTR(&variant_)); - - // Check that NPVariantToVariant properly converts UTF-8 to UTF-16. - STRINGZ_TO_NPVARIANT(_strdup("one: \xe4\xb8\x80"), np_variant_); - TestNPV2V(); - EXPECT_STREQ(L"one: \x4e00", V_BSTR(&variant_)); - - #pragma warning(pop) -} -/* -TEST_F(VariantUtilsTest, NPVariantToVariant_Unsupported) { - // NPVariantType_Object -> VT_DISPATCH conversion is not supported. - ExpectAsserts expect_asserts; - OBJECT_TO_NPVARIANT(NULL, np_variant_); - variant_ = 24; - NPVariantToVariant(NULL, np_variant_, &variant_); - EXPECT_EQ(VT_EMPTY, V_VT(&variant_)); - // Manual cleanup, since OBJECT_TO_NPVARIANT macro was used with a NULL - // NPObject, which is normally illegal. - VOID_TO_NPVARIANT(np_variant_); -} -*/ -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_EMPTY) { - variant_.ChangeType(VT_EMPTY); - TestV2NPV(); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_NULL) { - variant_.ChangeType(VT_NULL); - TestV2NPV(); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_BOOL) { - variant_ = true; - TestV2NPV(); - EXPECT_TRUE(np_variant_.value.boolValue); - - variant_ = false; - TestV2NPV(); - EXPECT_FALSE(np_variant_.value.boolValue); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_I4) { - variant_ = std::numeric_limits::max(); - TestV2NPV(); - EXPECT_EQ(std::numeric_limits::max(), np_variant_.value.intValue); - - variant_ = 0; - TestV2NPV(); - EXPECT_EQ(0, np_variant_.value.intValue); - - variant_ = std::numeric_limits::min(); - TestV2NPV(); - EXPECT_EQ(std::numeric_limits::min(), np_variant_.value.intValue); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_UI4) { - variant_ = 0U; - TestV2NPV(); - EXPECT_EQ(0, np_variant_.value.intValue); - - variant_ = static_cast(std::numeric_limits::max()); - TestV2NPV(); - EXPECT_EQ(std::numeric_limits::max(), np_variant_.value.intValue); - - // MSIE can natively support VT_UI4. Unfortunately, Firefox cannot. - // Check that kuint32max wraps around to -1. - variant_ = std::numeric_limits::max(); - TestV2NPV(); - EXPECT_EQ(-1, np_variant_.value.intValue); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_R8) { - variant_ = 0.0; - TestV2NPV(); - EXPECT_DOUBLE_EQ(0.0, np_variant_.value.doubleValue); - - variant_ = -1.0; - TestV2NPV(); - EXPECT_DOUBLE_EQ(-1.0, np_variant_.value.doubleValue); - - variant_ = static_cast(std::numeric_limits::max()); - TestV2NPV(); - EXPECT_DOUBLE_EQ(static_cast(std::numeric_limits::max()), - np_variant_.value.doubleValue); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_BSTR) { - variant_ = ""; - TestV2NPV(); - EXPECT_STREQ("", np_variant_.value.stringValue.UTF8Characters); - - variant_ = L"sudo make me a sandwich"; - TestV2NPV(); - EXPECT_STREQ("sudo make me a sandwich", - np_variant_.value.stringValue.UTF8Characters); - - // A NULL BSTR should be treated as an empty string. - V_VT(&variant_) = VT_BSTR; - V_BSTR(&variant_) = NULL; - TestV2NPV(); - EXPECT_STREQ("", np_variant_.value.stringValue.UTF8Characters); - - // Check that VariantToNPVariant properly converts UTF-16 to UTF-8. - variant_ = L"one: \x4e00"; - TestV2NPV(); - EXPECT_STREQ("one: \xe4\xb8\x80", - np_variant_.value.stringValue.UTF8Characters); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_VT_DISPATCH) { - CComPtr dispatch; - ASSERT_SUCCEEDED( - CComCoClass::CreateInstance(&dispatch)); - variant_ = dispatch; - TestV2NPV(); - - // Check that the wrapped object's methods can be called. - NPIdentifierFactory identifier; - NPVariant result; - VOID_TO_NPVARIANT(result); - EXPECT_TRUE(NPN_Invoke(NULL, np_variant_.value.objectValue, - identifier.Create("Random"), NULL, 0, &result)); - EXPECT_TRUE(NPVARIANT_IS_INT32(result)); - EXPECT_EQ(42, result.value.intValue); -} - -TEST_F(VariantUtilsTest, VariantToNPVariant_Unsupported) { - // Legal variant types inferred from oaidl.idl and wtypes.h. Note that some - // types that aren't marked as appearing in VARIANTs still have a VARIANT - // field for that type, so they are included anyway... - - // Note that VT_UNKNOWN must not be the last element in the array; otherwise - // CComVariant will attempt to call Release() on a NULL pointer. - const VARTYPE kUnsupportedSimpleTypes[] = { - VT_I2, VT_R4, VT_CY, VT_DATE, VT_ERROR, VT_VARIANT, VT_UNKNOWN, VT_DECIMAL, - VT_RECORD, VT_I1, VT_UI1, VT_UI2, VT_I8, VT_UI8, VT_INT, VT_UINT, VT_BYREF - }; - for (int i = 0; i < arraysize(kUnsupportedSimpleTypes); ++i) { - ExpectAsserts expect_asserts; - V_VT(&variant_) = kUnsupportedSimpleTypes[i]; - INT32_TO_NPVARIANT(42, np_variant_); - TestV2NPV(); - EXPECT_TRUE(NPVARIANT_IS_VOID(np_variant_)); - } - - // Compound modifiers. - const VARTYPE kCompoundModifiers[] = { - VT_ARRAY, VT_BYREF, VT_ARRAY | VT_BYREF - }; - // Compound types. - const VARTYPE kCompoundableTypes[] = { - VT_I2, VT_I4, VT_R4, VT_R8, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_ERROR, - VT_BOOL, VT_VARIANT, VT_UNKNOWN, VT_DECIMAL, VT_RECORD, VT_I1, VT_UI1, - VT_UI2, VT_UI4, VT_I8, VT_UI8, VT_INT, VT_UINT - }; - - for (int i = 0; i < arraysize(kCompoundModifiers); ++i) { - for (int j = 0; j < arraysize(kCompoundableTypes); ++j) { - ExpectAsserts expect_asserts; - V_VT(&variant_) = kCompoundModifiers[i] | kCompoundableTypes[j]; - INT32_TO_NPVARIANT(42, np_variant_); - TestV2NPV(); - EXPECT_TRUE(NPVARIANT_IS_VOID(np_variant_)); - } - } -} - -} // namespace omaha diff --git a/omaha/plugins/update/omaha_customization_update_apis_unittest.cc b/omaha/plugins/update/omaha_customization_update_apis_unittest.cc deleted file mode 100644 index a06acd7f7..000000000 --- a/omaha/plugins/update/omaha_customization_update_apis_unittest.cc +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Tests the constants that vary depending on the customization of Omaha. -// The test checks for the Google Update variations, but can be modified for -// your purposes. - -#include -#include -#include -#include -#include "omaha/base/utils.h" -#include "plugins/update/activex/update_control_idl.h" -#include "omaha/testing/omaha_customization_test.h" - -// Most of the tests are intentionally not using the omaha namespace. Most of -// the values being tested are not in this namespace, and being in the global -// namespace is required by TEST_GU_INT_F to catch conflicts with Google types -// when building non-Google versions. - -class OmahaCustomizationUpdateComInterfaceTest - : public OmahaCustomizationTypeLibComInterfaceTest { - protected: - OmahaCustomizationUpdateComInterfaceTest() - : OmahaCustomizationTypeLibComInterfaceTest(UPDATE_PLUGIN_FILENAME) { - } -}; - -TEST_F(OmahaCustomizationUpdateComInterfaceTest, TypeLib) { - EXPECT_GU_ID_EQ(_T("{b627c883-e979-4873-80b3-ddd0b658b56a}"), - LIBID_GoogleUpdateControlLib); - - EXPECT_SUCCEEDED(GetTypeLibDocumentation()); - EXPECT_STREQ(_T("GoogleUpdateControlLib"), item_name_); - EXPECT_GU_STREQ(_T("Google Update Browser Plugins 3.0 Type Library"), - item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationUpdateComInterfaceTest, - IGoogleUpdateOneClick) { - // TODO(omaha): Test uuid constants after extracting from IDLs. - EXPECT_GU_ID_EQ(_T("{6F65D62B-2F32-4483-9028-176C30B2389D}"), - __uuidof(IGoogleUpdateOneClick)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("IGoogleUpdateOneClick"))); - EXPECT_STREQ(_T("Google Update OneClick Control"), item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationUpdateComInterfaceTest, - IGoogleUpdate3WebControl) { - // TODO(omaha): Test uuid constants after extracting from IDLs. - EXPECT_GU_ID_EQ(_T("{57E37502-65A5-484a-A035-C1608B2626EA}"), - __uuidof(IGoogleUpdate3WebControl)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("IGoogleUpdate3WebControl"))); - EXPECT_STREQ(_T("GoogleUpdate3Web Control"), item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationUpdateComInterfaceTest, - GoogleUpdateOneClickControlCoClass) { - EXPECT_GU_ID_EQ(_T("{c442ac41-9200-4770-8cc0-7cdb4f245c55}"), - __uuidof(GoogleUpdateOneClickControlCoClass)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("GoogleUpdateOneClickControlCoClass"))); - EXPECT_STREQ(_T("Google Update OneClick Control Class"), item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationUpdateComInterfaceTest, - GoogleUpdate3WebControlCoClass) { - EXPECT_GU_ID_EQ(_T("{c3101a8b-0ee1-4612-bfe9-41ffc1a3c19d}"), - __uuidof(GoogleUpdate3WebControlCoClass)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("GoogleUpdate3WebControlCoClass"))); - EXPECT_STREQ(_T("GoogleUpdate3Web Control Class"), item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -// Verifies there are no new interfaces in the TypeLib. -TEST_F(OmahaCustomizationUpdateComInterfaceTest, VerifyNoNewInterfaces) { - EXPECT_EQ(4, type_lib_->GetTypeInfoCount()) - << _T("A new interface may have been added. If so, roll ") - << _T("the plugin version and add test(s) for new interface(s)."); -} diff --git a/omaha/plugins/update/omaha_customization_update_unittest.cc b/omaha/plugins/update/omaha_customization_update_unittest.cc deleted file mode 100644 index fe7fd0146..000000000 --- a/omaha/plugins/update/omaha_customization_update_unittest.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Tests the constants that vary depending on the customization of Omaha. -// The test checks for the Google Update variations, but can be modified for -// your purposes. - -#include "omaha/plugins/update/config.h" -#include "omaha/testing/omaha_customization_test.h" - -namespace omaha { - -TEST(OmahaCustomizationUpdateTest, Constants_BuildFiles) { -// The plugin version may or may not match in non-Google Update builds. -#ifdef GOOGLE_UPDATE_BUILD - EXPECT_STREQ(_T("3"), kUpdate3WebPluginVersion); - EXPECT_STREQ(_T("9"), kOneclickPluginVersion); -#else - std::wcout << _T("Did not test kPluginVersions.") << std::endl; -#endif - - EXPECT_GU_STREQ( - _T("Google.Update3WebControl.") _T(UPDATE_PLUGIN_VERSION_ANSI), - kUpdate3WebControlProgId); - EXPECT_GU_STREQ( - _T("Google.OneClickCtrl.") _T(ONECLICK_PLUGIN_VERSION_ANSI), - kOneclickControlProgId); -} - -} // namespace omaha diff --git a/omaha/plugins/update/oneclick.rgs b/omaha/plugins/update/oneclick.rgs deleted file mode 100644 index 550117f58..000000000 --- a/omaha/plugins/update/oneclick.rgs +++ /dev/null @@ -1,101 +0,0 @@ -'%HKROOT%' -{ - NoRemove SOFTWARE - { - NoRemove MozillaPlugins - { - ForceRemove '@%PLUGINDOMAIN%/%PLUGINPRODUCT%;version=%PLUGINVERSION%' - { - val Path = s '%MODULE%' - val Description = s '%PLUGINDESCRIPTION%' - val ProductName = s '%PLUGINPRODUCT%' - val Vendor = s '%PLUGINVENDOR%' - val Version = s '%PLUGINVERSION%' - MimeTypes - { - '%PLUGINMIMETYPE%' - } - } - } - NoRemove Microsoft - { - NoRemove Windows - { - NoRemove CurrentVersion - { - NoRemove Ext - { - NoRemove PreApproved - { - ForceRemove '%CLSID%' - } - NoRemove Stats - { - ForceRemove '%CLSID%' - { - iexplore - { - AllowedDomains - { - '*' - } - } - } - } - } - } - } - NoRemove 'Internet Explorer' - { - NoRemove 'Low Rights' - { - NoRemove 'ElevationPolicy' - { - ForceRemove '%CLSID%' - { - val AppName = s '%SHELLNAME%' - val AppPath = s '%SHELLPATH%' - val Policy = d '3' - } - } - } - } - } - NoRemove Classes - { - ForceRemove '%PROGID%' = s '%PLUGINPRODUCT% Plugin' - { - CLSID = s '%CLSID%' - } - NoRemove CLSID - { - ForceRemove '%CLSID%' = s '%PLUGINPRODUCT% Plugin' - { - ProgID = s '%PROGID%' - InprocServer32 = s '%MODULE%' - { - val ThreadingModel = s 'Apartment' - } - 'Implemented Categories' - { - '{59FB2056-D625-48D0-A944-1A85B5AB2640}' = s 'CATID_AppContainerCompatible' - } - } - } - NoRemove MIME - { - NoRemove Database - { - NoRemove 'Content Type' - { - ForceRemove '%PLUGINMIMETYPE%' - { - val CLSID = s '%CLSID%' - } - } - } - } - } - } -} - diff --git a/omaha/plugins/update/resource.h b/omaha/plugins/update/resource.h deleted file mode 100644 index 583ea9df5..000000000 --- a/omaha/plugins/update/resource.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_RESOURCE_H_ -#define OMAHA_PLUGINS_UPDATE_RESOURCE_H_ - -#define IDR_ONECLICK_RGS 102 - -#endif // OMAHA_PLUGINS_UPDATE_RESOURCE_H_ diff --git a/omaha/plugins/update/resource.rc b/omaha/plugins/update/resource.rc deleted file mode 100644 index 6c4f72f13..000000000 --- a/omaha/plugins/update/resource.rc +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// These include headers with absolute paths, which Resource Editor cannot load. -#ifndef APSTUDIO_INVOKED -#include "omaha/base/const_config.h" -#include "omaha/plugins/update/config.h" -#include "omaha/plugins/update/resource.h" -#endif // APSTUDIO_INVOKED - -#define PLUGIN_FILENAME UPDATE_PLUGIN_FILENAME -#include "../plugin_version.rc" - -// Path is in the obj directory, which Resource Editor does not look in. -#ifndef APSTUDIO_INVOKED -1 TYPELIB "plugins/update/activex/update_control_idl.tlb" -#endif // APSTUDIO_INVOKED - -IDR_ONECLICK_RGS REGISTRY "oneclick.rgs" - diff --git a/omaha/plugins/update/site_lock.cc b/omaha/plugins/update/site_lock.cc deleted file mode 100644 index 2ec0187ec..000000000 --- a/omaha/plugins/update/site_lock.cc +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/site_lock.h" - -#include -#include -#include -#include - -#include "omaha/base/atl_regexp.h" -#include "omaha/base/constants.h" -#include "omaha/base/error.h" -#include "omaha/base/safe_format.h" -#include "omaha/base/reg_key.h" -#include "omaha/plugins/update/npapi/urlpropbag.h" - -namespace omaha { - -SiteLock::SiteLock() { - for (int i = 0; i < arraysize(kSiteLockPatternStrings); ++i) { - VERIFY1(AddPattern(kSiteLockPatternStrings[i])); - } - - // TODO(omaha): should this be wrapped in a #ifdef DEBUG? - CString dev_pattern_string; - if (SUCCEEDED(RegKey::GetValue(MACHINE_REG_UPDATE_DEV, - kRegValueOneClickHostPattern, - &dev_pattern_string)) && - !dev_pattern_string.IsEmpty()) { - VERIFY1(AddPattern(dev_pattern_string)); - } -} - -SiteLock::~SiteLock() { - for (size_t i = 0; i < patterns_.size(); ++i) { - delete patterns_[i]; - } -} - -bool SiteLock::InApprovedDomain(IObjectWithSite* plugin) { - CString url; - if (FAILED(GetCurrentBrowserUrl(plugin, &url))) { - return false; - } - return InApprovedDomain(url); -} - -bool SiteLock::InApprovedDomain(const WCHAR* url) { - // TODO(omaha): investigate using CUrl to remove dependency on wininet - URL_COMPONENTS components = {sizeof(components)}; - components.dwHostNameLength = 1; - if (!::InternetCrackUrl(url, 0, 0, &components)) { - return false; - } - // On some platforms, InternetCrackUrl() is unreliable and will return - // success but leave lpszHostName NULL. Make sure it's valid. (b/5532393) - if (!components.lpszHostName || components.dwHostNameLength == 0) { - return false; - } - CString hostname(components.lpszHostName, components.dwHostNameLength); - for (std::vector::const_iterator it = patterns_.begin(); - it != patterns_.end(); - ++it) { - AtlMatchContext context; - if ((*it)->Match(hostname, &context)) { - return true; - } - } - - return false; -} - -HRESULT SiteLock::GetCurrentBrowserUrl(IObjectWithSite* plugin, CString* url) { - if (SUCCEEDED(ExtractUrlFromBrowser(plugin, url))) { - return S_OK; - } - if (SUCCEEDED(ExtractUrlFromPropBag(plugin, url))) { - return S_OK; - } - return E_FAIL; -} - -// TODO(omaha): Move this to common\webplugin_utils. -HRESULT SiteLock::GetUrlDomain(const CString& url, CString* url_domain) { - ASSERT1(url_domain); - url_domain->Empty(); - - URL_COMPONENTS urlComponents = {0}; - urlComponents.dwStructSize = sizeof(urlComponents); - urlComponents.dwSchemeLength = 1; - urlComponents.dwHostNameLength = 1; - if (!::InternetCrackUrl(url, 0, 0, &urlComponents)) { - HRESULT hr = HRESULTFromLastError(); - CORE_LOG(L2, (_T("[InternetCrackUrl failed][0x%08x]"), hr)); - return hr; - } - - CString scheme(urlComponents.lpszScheme, urlComponents.dwSchemeLength); - CString host_name(urlComponents.lpszHostName, urlComponents.dwHostNameLength); - ASSERT1(!scheme.IsEmpty()); - ASSERT1(!host_name.IsEmpty()); - - SafeCStringFormat(url_domain, _T("%s://%s/"), scheme, host_name); - return S_OK; -} - -bool SiteLock::AddPattern(const WCHAR* pattern) { - ASSERT1(pattern); - - // An empty pattern will match everything... - if (!*pattern) { - ASSERT1(false); - return false; - } - - auto re = std::make_unique(); - REParseError error = re->Parse(pattern); - if (REPARSE_ERROR_OK != error) { - ASSERT(false, (L"Failed to parse site lock pattern: %s", - pattern)); - return false; - } - patterns_.push_back(re.release()); - return true; -} - -// If the plugin is being hosted inside an NPAPI environment, NPUpdate will set -// a UrlPropertyBag object as our object site. Fetch the URL used to create -// our object from it. -HRESULT SiteLock::ExtractUrlFromPropBag(IObjectWithSite* plugin, CString* url) { - ASSERT1(plugin); - ASSERT1(url); - - CComPtr property_bag; - HRESULT hr = plugin->GetSite(IID_PPV_ARGS(&property_bag)); - if (FAILED(hr)) { - return hr; - } - - CComVariant var; - hr = property_bag->Read(kUrlPropertyBag_Url, &var, NULL); - if (FAILED(hr)) { - return hr; - } - if (var.vt != VT_BSTR || !var.bstrVal) { - return E_UNEXPECTED; - } - *url = var.bstrVal; - return S_OK; -} - -// If the plugin is hosted in an ActiveX environment, IE will set itself as the -// object site. Fetch the current URL from it. -HRESULT SiteLock::ExtractUrlFromBrowser(IObjectWithSite* plugin, CString* url) { - ASSERT1(plugin); - ASSERT1(url); - - CComPtr service_provider; - HRESULT hr = plugin->GetSite(IID_PPV_ARGS(&service_provider)); - if (FAILED(hr)) { - return hr; - } - - CComPtr web_browser; - hr = service_provider->QueryService(SID_SWebBrowserApp, - IID_PPV_ARGS(&web_browser)); - - CComBSTR bstr_url; - if (SUCCEEDED(hr)) { - hr = web_browser->get_LocationURL(&bstr_url); - } else { - // Do things the hard way... - CComPtr client_site; - hr = plugin->GetSite(IID_PPV_ARGS(&client_site)); - if (FAILED(hr)) { - return hr; - } - - CComPtr container; - hr = client_site->GetContainer(&container); - if (FAILED(hr)) { - return hr; - } - - CComPtr html_document; - hr = container.QueryInterface(&html_document); - if (FAILED(hr)) { - return hr; - } - - hr = html_document->get_URL(&bstr_url); - } - - if (SUCCEEDED(hr)) { - *url = bstr_url; - } - - return hr; -} - -} // namespace omaha diff --git a/omaha/plugins/update/site_lock.h b/omaha/plugins/update/site_lock.h deleted file mode 100644 index efaa84775..000000000 --- a/omaha/plugins/update/site_lock.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PLUGINS_UPDATE_SITE_LOCK_H_ -#define OMAHA_PLUGINS_UPDATE_SITE_LOCK_H_ - -#include -#include -#include - -#include "base/basictypes.h" -#include "omaha/base/atl_regexp.h" - -namespace omaha { - -class SiteLock { - public: - SiteLock(); - ~SiteLock(); - - bool InApprovedDomain(IObjectWithSite* url_provider); - bool InApprovedDomain(const WCHAR* url); - - static HRESULT GetCurrentBrowserUrl(IObjectWithSite* plugin, CString* url); - static HRESULT GetUrlDomain(const CString& url, CString* url_domain); - - private: - bool AddPattern(const WCHAR* pattern); - - static HRESULT ExtractUrlFromBrowser(IObjectWithSite* plugin, CString* url); - static HRESULT ExtractUrlFromPropBag(IObjectWithSite* plugin, CString* url); - - std::vector patterns_; - - DISALLOW_COPY_AND_ASSIGN(SiteLock); -}; - -} // namespace omaha - -#endif // OMAHA_PLUGINS_UPDATE_SITE_LOCK_H_ diff --git a/omaha/plugins/update/site_lock_unittest.cc b/omaha/plugins/update/site_lock_unittest.cc deleted file mode 100644 index f9c797ac7..000000000 --- a/omaha/plugins/update/site_lock_unittest.cc +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/plugins/update/site_lock.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -class SiteLockTest : public testing::Test { - protected: - SiteLock site_lock_; -}; - -TEST_F(SiteLockTest, InApprovedDomain_GoogleDotCom) { - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.google.com/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.google.com/pack/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.google.co.uk")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.google.co.uk/pack/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://pack.google.com/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://pack.google.com/pack/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://fake.google.com/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://fake.google.com/pack/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://google.com/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://google.com/pack/")); -} - -TEST_F(SiteLockTest, InApprovedDomain_ChromeDotCom) { - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.chrome.com/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://www.chrome.com/dl/")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://chrome.com")); - EXPECT_TRUE(site_lock_.InApprovedDomain(L"http://chrome.com/dl/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://fake.chrome.com/")); -} - -TEST_F(SiteLockTest, InApprovedDomain_EvilHackerDotCom) { - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://www.evilhacker.com/")); - EXPECT_FALSE(site_lock_.InApprovedDomain(L"http://www.evilhacker.com/dl/")); -} - -} // namespace omaha diff --git a/omaha/setup/setup.cc b/omaha/setup/setup.cc index 3f2f4168c..31736dab4 100644 --- a/omaha/setup/setup.cc +++ b/omaha/setup/setup.cc @@ -123,7 +123,6 @@ void IncrementProcessWaitFailCount(CommandLineMode mode) { case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_INSTALL: case COMMANDLINE_MODE_RECOVER: - case COMMANDLINE_MODE_WEBPLUGIN: case COMMANDLINE_MODE_COMSERVER: case COMMANDLINE_MODE_REGISTER_PRODUCT: case COMMANDLINE_MODE_UNREGISTER_PRODUCT: @@ -584,14 +583,6 @@ HRESULT Setup::SetupGoogleUpdate() { } } - // Registration of browser plugins is only done after the shutdown event has - // been released; this prevents race conditions where a browser could start - // a new install while the shutdown event was still being held. - HRESULT plugin_hr = setup_google_update.InstallBrowserPlugins(); - if (FAILED(plugin_hr)) { - SETUP_LOG(LE, (_T("[InstallBrowserPlugins failed][0x%08x]"), plugin_hr)); - } - // Setup is now complete. metric_setup_phase2_ms.AddSample(phase2_metrics_timer.GetElapsedMs()); diff --git a/omaha/setup/setup_files.cc b/omaha/setup/setup_files.cc index 43e0e74f4..e003c6104 100644 --- a/omaha/setup/setup_files.cc +++ b/omaha/setup/setup_files.cc @@ -321,10 +321,8 @@ HRESULT SetupFiles::BuildFileLists() { // If files are removed from this list, unit tests such as // ShouldInstall_SameVersionOptionalFileMissing may need to be updated. optional_files_.clear(); - optional_files_.push_back(UPDATE_PLUGIN_FILENAME); optional_files_.push_back(kOmahaBrokerFileName); optional_files_.push_back(kOmahaOnDemandFileName); - optional_files_.push_back(kOmahaWebPluginFileName); // Machine-specific files are always installed, to support cross installs from // user to machine and machine to user. diff --git a/omaha/setup/setup_files_unittest.cc b/omaha/setup/setup_files_unittest.cc index 100839a12..160a1b412 100644 --- a/omaha/setup/setup_files_unittest.cc +++ b/omaha/setup/setup_files_unittest.cc @@ -37,7 +37,7 @@ namespace { const int kNumberOfLanguageDlls = 55; const int kNumberOfCoreFiles = 11; const int kNumberOfMetainstallerFiles = 1; -const int kNumberOfOptionalFiles = 4; +const int kNumberOfOptionalFiles = 2; const int kNumberOfInstalledRequiredFiles = kNumberOfLanguageDlls + kNumberOfCoreFiles; // FindFiles returns "." and ".." in addition to the actual files. @@ -73,8 +73,6 @@ void CopyGoopdateFiles(const CString& omaha_path, const CString& version) { kOmahaMetainstallerFileName, kOmahaBrokerFileName, kOmahaOnDemandFileName, - kOmahaWebPluginFileName, - UPDATE_PLUGIN_FILENAME, kPSFileNameMachine, kPSFileNameMachine64, kPSFileNameUser, @@ -186,7 +184,6 @@ class SetupFilesTest : public testing::Test { EXPECT_STREQ(kHelperInstallerName, files[file_index++]); EXPECT_STREQ(kOmahaOnDemandFileName, files[file_index++]); EXPECT_STREQ(kOmahaMetainstallerFileName, files[file_index++]); - EXPECT_STREQ(kOmahaWebPluginFileName, files[file_index++]); EXPECT_STREQ(kOmahaDllName, files[file_index++]); EXPECT_STREQ(_T("goopdateres_am.dll"), files[file_index++]); EXPECT_STREQ(_T("goopdateres_ar.dll"), files[file_index++]); @@ -243,7 +240,6 @@ class SetupFilesTest : public testing::Test { EXPECT_STREQ(_T("goopdateres_vi.dll"), files[file_index++]); EXPECT_STREQ(_T("goopdateres_zh-CN.dll"), files[file_index++]); EXPECT_STREQ(_T("goopdateres_zh-TW.dll"), files[file_index++]); - EXPECT_STREQ(UPDATE_PLUGIN_FILENAME, files[file_index++]); EXPECT_STREQ(kPSFileNameMachine, files[file_index++]); EXPECT_STREQ(kPSFileNameMachine64, files[file_index++]); EXPECT_STREQ(kPSFileNameUser, files[file_index++]); diff --git a/omaha/setup/setup_google_update.cc b/omaha/setup/setup_google_update.cc index 37d20d5a9..cfee3f290 100644 --- a/omaha/setup/setup_google_update.cc +++ b/omaha/setup/setup_google_update.cc @@ -172,8 +172,8 @@ HRESULT SetupGoogleUpdate::FinishInstall() { // Fall through for installs. Omaha will attempt to install using the // in-proc mode. Not installing the launch mechanisms does mean that Omaha - // will not be able to update itself or the product. But OneClick and - // Handoffs should continue to work. + // will not be able to update itself or the product. But Handoffs should + // continue to work. // // extra_code1_ contains the HRESULT from the Scheduled Task install // failure, but it is more useful to send the service install failure in the @@ -198,8 +198,6 @@ HRESULT SetupGoogleUpdate::FinishInstall() { ASSERT1(SUCCEEDED(VerifyCOMLocalServerRegistration(is_machine_))); - // We would prefer to uninstall previous versions last, but the web plugin - // requires that the old plugin is uninstalled before installing the new one. VERIFY1(SUCCEEDED(UninstallPreviousVersions())); // Set the LastOSVersion to the currently installed OS version. This is used @@ -510,10 +508,11 @@ HRESULT SetupGoogleUpdate::InstallUserLaunchMechanisms() { // Sets a value in the Run key in the user registry to start the core. HRESULT SetupGoogleUpdate::ConfigureUserRunAtStartup(bool install) { SETUP_LOG(L3, (_T("SetupGoogleUpdate::ConfigureUserRunAtStartup"))); - // Always send false argument as this method is only called for user - // goopdate installs. - CString core_cmd = BuildCoreProcessCommandLine(); - return ConfigureRunAtStartup(USER_KEY_NAME, kRunValueName, core_cmd, install); + + return ConfigureRunAtStartup(USER_KEY_NAME, + kRunValueName, + BuildCoreProcessCommandLine(), + install); } HRESULT SetupGoogleUpdate::RegisterOrUnregisterCOMLocalServer(bool reg) { @@ -609,38 +608,6 @@ HRESULT SetupGoogleUpdate::UninstallMsiHelper() { return S_OK; } -HRESULT SetupGoogleUpdate::InstallBrowserPlugins() { - SETUP_LOG(L3, (_T("[SetupGoogleUpdate::InstallBrowserPlugins]"))); - ASSERT1(have_called_uninstall_previous_versions_); - // Failure of registration of optional components is acceptable in release - // builds. - HRESULT hr = S_OK; - - CString plugin_path = - BuildSupportFileInstallPath(UPDATE_PLUGIN_FILENAME); - hr = RegisterDll(plugin_path); - if (FAILED(hr)) { - SETUP_LOG(L1, (_T("[Register plugin DLL failed][0x%08x]"), hr)); - } - - return hr; -} - -HRESULT SetupGoogleUpdate::UninstallBrowserPlugins() { - SETUP_LOG(L3, (_T("[SetupGoogleUpdate::UninstallBrowserPlugins]"))); - // Unregistration. Failure is acceptable in release builds. - HRESULT hr = S_OK; - - CString plugin_path = - BuildSupportFileInstallPath(UPDATE_PLUGIN_FILENAME); - hr = UnregisterDll(plugin_path); - if (FAILED(hr)) { - SETUP_LOG(L1, (_T("[Unregister plugin DLL failed][0x%08x]"), hr)); - } - - return hr; -} - CString SetupGoogleUpdate::BuildSupportFileInstallPath( const CString& filename) const { SETUP_LOG(L3, (_T("[SetupGoogleUpdate::BuildSupportFileInstallPath][%s]"), @@ -657,7 +624,9 @@ CString SetupGoogleUpdate::BuildCoreProcessCommandLine() const { CPath full_file_path(goopdate_utils::BuildInstallDirectory( is_machine_, GetVersionString())); VERIFY1(full_file_path.Append(kOmahaCoreFileName)); - return full_file_path; + CString core_command_line(full_file_path); + EnclosePath(&core_command_line); + return core_command_line; } HRESULT SetupGoogleUpdate::UninstallPreviousVersions() { @@ -770,12 +739,6 @@ HRESULT SetupGoogleUpdate::UninstallPreviousVersions() { void SetupGoogleUpdate::Uninstall() { OPT_LOG(L1, (_T("[SetupGoogleUpdate::Uninstall]"))); - HRESULT hr = UninstallBrowserPlugins(); - if (FAILED(hr)) { - SETUP_LOG(LW, (_T("[UninstallBrowserPlugins failed][0x%08x]"), hr)); - ASSERT1(HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND) == hr); - } - // If running from the installed location instead of a temporary location, // we assume that Omaha had been properly installed and can verify the COM // registration. @@ -783,7 +746,7 @@ void SetupGoogleUpdate::Uninstall() { ASSERT1(SUCCEEDED(VerifyCOMLocalServerRegistration(is_machine_))); } - hr = RegisterOrUnregisterCOMLocalServer(false); + HRESULT hr = RegisterOrUnregisterCOMLocalServer(false); if (FAILED(hr)) { SETUP_LOG(LW, (_T("[RegisterOrUnregisterCOMLocalServer failed][0x%08x]"), hr)); diff --git a/omaha/setup/setup_google_update.h b/omaha/setup/setup_google_update.h index 2daaa0553..5f719e015 100644 --- a/omaha/setup/setup_google_update.h +++ b/omaha/setup/setup_google_update.h @@ -30,8 +30,6 @@ class SetupGoogleUpdate { HRESULT FinishInstall(); - HRESULT InstallBrowserPlugins(); - // Installs the helper (MSI). HRESULT InstallMsiHelper(); @@ -83,8 +81,6 @@ class SetupGoogleUpdate { // Uninstalls the helper (MSI). HRESULT UninstallMsiHelper(); - HRESULT UninstallBrowserPlugins(); - // Build the install file path for support files. For example, CString BuildSupportFileInstallPath(const CString& filename) const; diff --git a/omaha/setup/setup_google_update_unittest.cc b/omaha/setup/setup_google_update_unittest.cc index 8d370c2ce..016e1d897 100644 --- a/omaha/setup/setup_google_update_unittest.cc +++ b/omaha/setup/setup_google_update_unittest.cc @@ -81,8 +81,7 @@ void CopyFilesRequiredByFinishInstall(bool is_machine, const CString& version) { kPSFileNameMachine, kPSFileNameMachine64, kPSFileNameUser, - kPSFileNameUser64, - UPDATE_PLUGIN_FILENAME}; + kPSFileNameUser64}; for (size_t i = 0; i < arraysize(files); ++i) { ASSERT_SUCCEEDED(File::Copy( ConcatenatePath(app_util::GetCurrentModuleDirectory(), @@ -303,10 +302,11 @@ class SetupGoogleUpdateTest : public testing::Test { class SetupGoogleUpdateUserTest : public SetupGoogleUpdateTest { protected: SetupGoogleUpdateUserTest() : SetupGoogleUpdateTest(false) { - CString expected_shell_path = - ConcatenatePath(GetGoogleUpdateUserPath(), GetVersionString()); - expected_run_key_value_ = ConcatenatePath(expected_shell_path, - kOmahaCoreFileName); + CString expected_core_command_line = ConcatenatePath( + ConcatenatePath(GetGoogleUpdateUserPath(), GetVersionString()), + kOmahaCoreFileName); + EnclosePath(&expected_core_command_line); + expected_run_key_value_ = expected_core_command_line; } void SetUp() override { diff --git a/omaha/setup/setup_unittest.cc b/omaha/setup/setup_unittest.cc index 7326b1b0f..ca9aa978d 100644 --- a/omaha/setup/setup_unittest.cc +++ b/omaha/setup/setup_unittest.cc @@ -1043,7 +1043,7 @@ TEST_F(SetupRegistryProtectedUserTest, CopyGoopdateFiles(omaha_path_, this_version_); CString path = ConcatenatePath(ConcatenatePath(omaha_path_, this_version_), - UPDATE_PLUGIN_FILENAME); + kPSFileNameMachine64); ASSERT_SUCCEEDED(File::Remove(path)); ASSERT_FALSE(File::Exists(path)); diff --git a/omaha/testing/build.scons b/omaha/testing/build.scons index e027b075f..ebdba99de 100644 --- a/omaha/testing/build.scons +++ b/omaha/testing/build.scons @@ -358,7 +358,6 @@ omaha_unittest_inputs = [ # Base unit tests '../base/app_util_unittest.cc', '../base/atlassert_unittest.cc', - '../base/atl_regexp_unittest.cc', '../base/browser_utils_unittest.cc', '../base/cgi_unittest.cc', '../base/command_line_parser_unittest.cc', @@ -451,7 +450,6 @@ omaha_unittest_inputs = [ '../common/stats_uploader_unittest.cc', '../common/update_request_unittest.cc', '../common/url_utils_unittest.cc', - '../common/webplugin_utils_unittest.cc', '../common/web_services_client_unittest.cc', '../common/xml_parser_unittest.cc', @@ -570,19 +568,6 @@ if omaha_unittest_env.IsBuildingModule('mi_exe_stub'): '../mi_exe_stub/x86_encoder/bcj2_encoder_unittest.cc', ] -if omaha_unittest_env.IsBuildingModule('plugins'): - omaha_unittest_inputs += [ - # Plugin unit tests. - '../plugins/update/omaha_customization_update_apis_unittest.cc', - '../plugins/update/omaha_customization_update_unittest.cc', - '../plugins/update/activex/update3web_control_unittest.cc', - '../plugins/update/npapi/dispatch_host_unittest.cc', - '../plugins/update/npapi/npfunction_host_unittest.cc', - '../plugins/update/npapi/variant_utils_unittest.cc', - '../plugins/update/site_lock_unittest.cc', - '$OBJ_ROOT/plugins/update/npapi/testing/dispatch_host_test.res', - ] - if omaha_unittest_env.IsBuildingModule('recovery'): omaha_unittest_inputs += [ # Recovery unit tests. @@ -660,11 +645,6 @@ omaha_unittest_env.Depends(test, '$STAGING_DIR/GoogleUpdateSetup_repair.exe') # Customization/UI tests depend on goopdate.dll (for TypeLib/resources) omaha_unittest_env.Depends(test, '$TESTS_DIR/goopdate.dll') -# Customization test uses update plugin DLL (npGoogleUpdate3.dll) for TypeLib. -omaha_unittest_env.Depends( - test, - '$STAGING_DIR/%s' % env['omaha_versions_info'][0].update_plugin_filename) - if env.Bit('all'): save_args_env = env.Clone() save_args_env.Append( diff --git a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc index dcb445a15..3ed01f5d8 100644 --- a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc +++ b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc @@ -19,11 +19,6 @@ #include "components/crx_file/crx_verifier.h" -#pragma warning(disable : 4245) -// C4245 : conversion from 'type1' to 'type2', signed/unsigned mismatch -#include -#pragma warning(default : 4245) - #include #include #include @@ -38,6 +33,7 @@ #include "omaha/base/scope_guard.h" #include "omaha/base/security/sha256.h" #include "omaha/base/signatures.h" +#include "omaha/base/string.h" #include "omaha/base/utils.h" #include "omaha/net/cup_ecdsa_utils.h" #include "third_party/chrome/files/src/components/crx_file/crx3.pb.h" @@ -242,11 +238,11 @@ VerifierResult VerifyCrx3( return VerifierResult::ERROR_SIGNATURE_VERIFICATION_FAILED; } - const std::vector v( - public_key_bytes.c_str(), - public_key_bytes.c_str() + public_key_bytes.length()); CStringA encoded; - VERIFY1(SUCCEEDED(omaha::Base64::Encode(v, &encoded, false))); + omaha::Base64Escape(public_key_bytes.c_str(), + public_key_bytes.length(), + &encoded, + true); *public_key = encoded; *crx_id = declared_crx_id; return VerifierResult::OK_FULL; @@ -433,7 +429,7 @@ VerifierResult Verify( } std::shared_ptr file_hash( - omaha::CryptDetails::CreateHasher(true)); + omaha::CryptDetails::CreateHasher()); // Magic number. bool diff = false; diff --git a/omaha/third_party/chrome/files/src/crypto/signature_verifier.cc b/omaha/third_party/chrome/files/src/crypto/signature_verifier.cc index 0656709ec..fe2ac51b4 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_verifier.cc +++ b/omaha/third_party/chrome/files/src/crypto/signature_verifier.cc @@ -31,7 +31,7 @@ namespace crypto { SignatureVerifier::SignatureVerifier() : - hasher_(omaha::CryptDetails::CreateHasher(true)) {} + hasher_(omaha::CryptDetails::CreateHasher()) {} SignatureVerifier::~SignatureVerifier() {} diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi.h deleted file mode 100644 index 1e6e7e2be..000000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi.h +++ /dev/null @@ -1,932 +0,0 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - - -/* - * Netscape client plug-in API spec - */ - - -#ifndef _NPAPI_H_ -#define _NPAPI_H_ - - -/* BEGIN GOOGLE MODIFICATIONS */ - -#ifdef __native_client__ -#include -#else -#include "base/basictypes.h" -#endif /* __native_client__ */ - -/* END GOOGLE MODIFICATIONS */ - -#ifdef INCLUDE_JAVA -#include "jri.h" /* Java Runtime Interface */ -#else -#define jref void * -#define JRIEnv void -#endif - -#ifdef _WIN32 -# ifndef XP_WIN -# define XP_WIN 1 -# endif /* XP_WIN */ -#endif /* _WIN32 */ - -/* BEGIN GOOGLE MODIFICATIONS */ -/* On Linux and Mac, be sure to set Mozilla-specific macros. */ -#if defined(USE_X11) -#define XP_UNIX 1 -#define MOZ_X11 1 -#endif -/* END GOOGLE MODIFICATIONS */ - -#ifdef __MWERKS__ -# define _declspec __declspec -# ifdef macintosh -# ifndef XP_MAC -# define XP_MAC 1 -# endif /* XP_MAC */ -# endif /* macintosh */ -# ifdef __INTEL__ -# undef NULL -# ifndef XP_WIN -# define XP_WIN 1 -# endif /* __INTEL__ */ -# endif /* XP_PC */ -#endif /* __MWERKS__ */ - -#ifdef __SYMBIAN32__ -# ifndef XP_SYMBIAN -# define XP_SYMBIAN 1 -# undef XP_WIN -# endif -#endif /* __SYMBIAN32__ */ - -#if defined(__APPLE_CC__) && !defined(__MACOS_CLASSIC__) && !defined(XP_UNIX) -# define XP_MACOSX -#endif - -#ifdef XP_MAC -#include -#include -#endif - -#if defined(XP_MACOSX) && defined(__LP64__) -#define NP_NO_QUICKDRAW -#define NP_NO_CARBON -#endif - -#ifdef XP_MACOSX -#include -#include -#ifndef NP_NO_CARBON -#include -#endif -#endif - -#if defined(XP_UNIX) -# include -/* BEGIN GOOGLE MODIFICATIONS */ -#if 0 -/* END GOOGLE MODIFICATIONS */ -# if defined(MOZ_X11) -# include -# include -# endif -/* BEGIN GOOGLE MODIFICATIONS */ -#endif -/* END GOOGLE MODIFICATIONS */ -#endif - -#ifdef XP_WIN -#include -#endif - -/*----------------------------------------------------------------------*/ -/* Plugin Version Constants */ -/*----------------------------------------------------------------------*/ - -#define NP_VERSION_MAJOR 0 -/* BEGIN GOOGLE MODIFICATIONS */ -#define NP_VERSION_MINOR 23 /* maximum version currently supported by Chromium */ -/* END GOOGLE MODIFICATIONS */ - - -/*----------------------------------------------------------------------*/ -/* Definition of Basic Types */ -/*----------------------------------------------------------------------*/ - -/* QNX sets the _INT16 and friends defines, but does not typedef the types */ -#ifdef __QNXNTO__ -#undef _UINT16 -#undef _INT16 -#undef _UINT32 -#undef _INT32 -#endif - -#ifndef _UINT16 -#define _UINT16 -typedef unsigned short uint16; -#endif - -#ifndef _UINT32 -#define _UINT32 -#ifdef __LP64__ -typedef unsigned int uint32; -#else /* __LP64__ */ -typedef unsigned long uint32; -#endif /* __LP64__ */ -#endif - -#ifndef _INT16 -#define _INT16 -typedef short int16; -#endif - -#ifndef _INT32 -#define _INT32 -#ifdef __LP64__ -typedef int int32; -#else /* __LP64__ */ -typedef long int32; -#endif /* __LP64__ */ -#endif - -#ifndef FALSE -#define FALSE (0) -#endif -#ifndef TRUE -#define TRUE (1) -#endif -#ifndef NULL -#define NULL (0L) -#endif - -typedef unsigned char NPBool; -typedef int16 NPError; -typedef int16 NPReason; -typedef char* NPMIMEType; - - - -/*----------------------------------------------------------------------*/ -/* Structures and definitions */ -/*----------------------------------------------------------------------*/ - -#if !defined(__LP64__) -#if defined(XP_MAC) || defined(XP_MACOSX) -#pragma options align=mac68k -#endif -#endif /* __LP64__ */ - -/* - * NPP is a plug-in's opaque instance handle - */ -typedef struct _NPP -{ - void* pdata; /* plug-in private data */ - void* ndata; /* netscape private data */ -} NPP_t; - -typedef NPP_t* NPP; - - -typedef struct _NPStream -{ - void* pdata; /* plug-in private data */ - void* ndata; /* netscape private data */ - const char* url; - uint32 end; - uint32 lastmodified; - void* notifyData; - const char* headers; /* Response headers from host. - * Exists only for >= NPVERS_HAS_RESPONSE_HEADERS. - * Used for HTTP only; NULL for non-HTTP. - * Available from NPP_NewStream onwards. - * Plugin should copy this data before storing it. - * Includes HTTP status line and all headers, - * preferably verbatim as received from server, - * headers formatted as in HTTP ("Header: Value"), - * and newlines (\n, NOT \r\n) separating lines. - * Terminated by \n\0 (NOT \n\n\0). */ -} NPStream; - - -typedef struct _NPByteRange -{ - int32 offset; /* negative offset means from the end */ - uint32 length; - struct _NPByteRange* next; -} NPByteRange; - - -typedef struct _NPSavedData -{ - int32 len; - void* buf; -} NPSavedData; - - -typedef struct _NPRect -{ - uint16 top; - uint16 left; - uint16 bottom; - uint16 right; -} NPRect; - - -#ifdef XP_UNIX -/* - * Unix specific structures and definitions - */ - -/* - * Callback Structures. - * - * These are used to pass additional platform specific information. - */ -enum { - NP_SETWINDOW = 1, - NP_PRINT -}; - -typedef struct -{ - int32 type; -} NPAnyCallbackStruct; - -/* BEGIN GOOGLE MODIFICATIONS */ -typedef struct _NPSetWindowCallbackStruct NPSetWindowCallbackStruct; -/* END GOOGLE MODIFICATIONS */ - -typedef struct -{ - int32 type; - FILE* fp; -} NPPrintCallbackStruct; - -#endif /* XP_UNIX */ - - -/* - * The following masks are applied on certain platforms to NPNV and - * NPPV selectors that pass around pointers to COM interfaces. Newer - * compilers on some platforms may generate vtables that are not - * compatible with older compilers. To prevent older plugins from - * not understanding a new browser's ABI, these masks change the - * values of those selectors on those platforms. To remain backwards - * compatible with differenet versions of the browser, plugins can - * use these masks to dynamically determine and use the correct C++ - * ABI that the browser is expecting. This does not apply to Windows - * as Microsoft's COM ABI will likely not change. - */ - -#define NP_ABI_GCC3_MASK 0x10000000 -/* - * gcc 3.x generated vtables on UNIX and OSX are incompatible with - * previous compilers. - */ -#if (defined (XP_UNIX) && defined(__GNUC__) && (__GNUC__ >= 3)) -#define _NP_ABI_MIXIN_FOR_GCC3 NP_ABI_GCC3_MASK -#else -#define _NP_ABI_MIXIN_FOR_GCC3 0 -#endif - -#define NP_ABI_MACHO_MASK 0x01000000 -/* - * On OSX, the Mach-O executable format is significantly - * different than CFM. In addition to having a different - * C++ ABI, it also has has different C calling convention. - * You must use glue code when calling between CFM and - * Mach-O C functions. - */ -#if (defined(TARGET_RT_MAC_MACHO)) -#define _NP_ABI_MIXIN_FOR_MACHO NP_ABI_MACHO_MASK -#else -#define _NP_ABI_MIXIN_FOR_MACHO 0 -#endif - - -#define NP_ABI_MASK (_NP_ABI_MIXIN_FOR_GCC3 | _NP_ABI_MIXIN_FOR_MACHO) - -/* - * List of variable names for which NPP_GetValue shall be implemented - */ -typedef enum { - NPPVpluginNameString = 1, - NPPVpluginDescriptionString, - NPPVpluginWindowBool, - NPPVpluginTransparentBool, - NPPVjavaClass, /* Not implemented in Mozilla 1.0 */ - NPPVpluginWindowSize, - NPPVpluginTimerInterval, - - NPPVpluginScriptableInstance = (10 | NP_ABI_MASK), - NPPVpluginScriptableIID = 11, - - /* Introduced in Mozilla 0.9.9 */ - NPPVjavascriptPushCallerBool = 12, - - /* Introduced in Mozilla 1.0 */ - NPPVpluginKeepLibraryInMemory = 13, - NPPVpluginNeedsXEmbed = 14, - - /* Get the NPObject for scripting the plugin. Introduced in Firefox - * 1.0 (NPAPI minor version 14). - */ - NPPVpluginScriptableNPObject = 15, - - /* Get the plugin value (as \0-terminated UTF-8 string data) for - * form submission if the plugin is part of a form. Use - * NPN_MemAlloc() to allocate memory for the string data. - */ - NPPVformValue = 16, /* Not implemented in WebKit */ - - NPPVpluginUrlRequestsDisplayedBool = 17, /* Not implemented in WebKit */ - - /* Checks if the plugin is interested in receiving the http body of - * failed http requests (http status != 200). - */ - NPPVpluginWantsAllNetworkStreams = 18, - - /* Checks to see if the plug-in would like the browser to load the "src" attribute. */ - NPPVpluginCancelSrcStream = 20 - -#ifdef XP_MACOSX - /* Used for negotiating drawing models */ - , NPPVpluginDrawingModel = 1000, - /* Used for negotiating event models */ - NPPVpluginEventModel = 1001, - /* In the NPDrawingModelCoreAnimation drawing model, the browser asks the plug-in for a Core Animation layer. */ - NPPVpluginCoreAnimationLayer = 1003 -#endif -} NPPVariable; - -/* - * List of variable names for which NPN_GetValue is implemented by Mozilla - */ -typedef enum { - NPNVxDisplay = 1, - NPNVxtAppContext, - NPNVnetscapeWindow, - NPNVjavascriptEnabledBool, - NPNVasdEnabledBool, - NPNVisOfflineBool, - - /* 10 and over are available on Mozilla builds starting with 0.9.4 */ - NPNVserviceManager = (10 | NP_ABI_MASK), - NPNVDOMElement = (11 | NP_ABI_MASK), /* available in Mozilla 1.2 */ - NPNVDOMWindow = (12 | NP_ABI_MASK), - NPNVToolkit = (13 | NP_ABI_MASK), - NPNVSupportsXEmbedBool = 14, - - /* Get the NPObject wrapper for the browser window. */ - NPNVWindowNPObject = 15, - - /* Get the NPObject wrapper for the plugins DOM element. */ - NPNVPluginElementNPObject = 16, - - NPNVSupportsWindowless = 17, - - NPNVprivateModeBool = 18 - -#ifdef XP_MACOSX - /* Used for negotiating drawing models */ - , NPNVpluginDrawingModel = 1000 -#ifndef NP_NO_QUICKDRAW - , NPNVsupportsQuickDrawBool = 2000 -#endif - , NPNVsupportsCoreGraphicsBool = 2001 - , NPNVsupportsOpenGLBool = 2002 /* TRUE if the browser supports the OpenGL drawing model (CGL on Mac) */ - , NPNVsupportsCoreAnimationBool = 2003 /* TRUE if the browser supports the CoreAnimation drawing model */ - -#ifndef NP_NO_CARBON - , NPNVsupportsCarbonBool = 3000 /* TRUE if the browser supports the Carbon event model */ -#endif - , NPNVsupportsCocoaBool = 3001 /* TRUE if the browser supports the Cocoa event model */ -#endif -} NPNVariable; - -typedef enum { - NPNURLVCookie = 501, - NPNURLVProxy -} NPNURLVariable; - -/* BEGIN GOOGLE MODIFICATIONS */ -/* - * The type of Tookkit the widgets use - */ -typedef enum { - NPNVGtk12 = 1, - NPNVGtk2 -} NPNToolkitType; -/* END GOOGLE MODIFICATIONS */ - -/* - * The type of a NPWindow - it specifies the type of the data structure - * returned in the window field. - */ -typedef enum { - NPWindowTypeWindow = 1, - NPWindowTypeDrawable -} NPWindowType; - -#ifdef XP_MACOSX - -/* - * The drawing model for a Mac OS X plugin. These are the possible values for the NPNVpluginDrawingModel variable. - */ - -typedef enum { -#ifndef NP_NO_QUICKDRAW - NPDrawingModelQuickDraw = 0, -#endif - NPDrawingModelCoreGraphics = 1, - NPDrawingModelOpenGL = 2, - NPDrawingModelCoreAnimation = 3 -} NPDrawingModel; - -/* - * The event model for a Mac OS X plugin. These are the possible values for the NPNVpluginEventModel variable. - */ - -typedef enum { -#ifndef NP_NO_CARBON - NPEventModelCarbon = 0, -#endif - NPEventModelCocoa = 1 -} NPEventModel; - -typedef enum { - NPCocoaEventDrawRect = 1, - NPCocoaEventMouseDown, - NPCocoaEventMouseUp, - NPCocoaEventMouseMoved, - NPCocoaEventMouseEntered, - NPCocoaEventMouseExited, - NPCocoaEventMouseDragged, - NPCocoaEventKeyDown, - NPCocoaEventKeyUp, - NPCocoaEventFlagsChanged, - NPCocoaEventFocusChanged, - NPCocoaEventWindowFocusChanged, - NPCocoaEventScrollWheel, - NPCocoaEventTextInput -} NPCocoaEventType; - -typedef struct _NPNSString NPNSString; -typedef struct _NPNSWindow NPNSWindow; -typedef struct _NPNSMenu NPNSMenu; - -typedef struct _NPCocoaEvent { - NPCocoaEventType type; - uint32 version; - - union { - struct { - uint32 modifierFlags; - double pluginX; - double pluginY; - int32 buttonNumber; - int32 clickCount; - double deltaX; - double deltaY; - double deltaZ; - } mouse; - struct { - uint32 modifierFlags; - NPNSString *characters; - NPNSString *charactersIgnoringModifiers; - NPBool isARepeat; - uint16 keyCode; - } key; - struct { - CGContextRef context; - - double x; - double y; - double width; - double height; - } draw; - struct { - NPBool hasFocus; - } focus; - struct { - NPNSString *text; - } text; - } data; -} NPCocoaEvent; - -#endif - -typedef struct _NPWindow -{ - void* window; /* Platform specific window handle */ - int32 x; /* Position of top left corner relative */ - int32 y; /* to a netscape page. */ - uint32 width; /* Maximum window size */ - uint32 height; - NPRect clipRect; /* Clipping rectangle in port coordinates */ - /* Used by MAC only. */ -#if defined(XP_UNIX) && !defined(XP_MACOSX) - void * ws_info; /* Platform-dependent additonal data */ -#endif /* XP_UNIX */ - NPWindowType type; /* Is this a window or a drawable? */ -} NPWindow; - - -typedef struct _NPFullPrint -{ - NPBool pluginPrinted;/* Set TRUE if plugin handled fullscreen printing */ - NPBool printOne; /* TRUE if plugin should print one copy to default printer */ - void* platformPrint; /* Platform-specific printing info */ -} NPFullPrint; - -typedef struct _NPEmbedPrint -{ - NPWindow window; - void* platformPrint; /* Platform-specific printing info */ -} NPEmbedPrint; - -typedef struct _NPPrint -{ - uint16 mode; /* NP_FULL or NP_EMBED */ - union - { - NPFullPrint fullPrint; /* if mode is NP_FULL */ - NPEmbedPrint embedPrint; /* if mode is NP_EMBED */ - } print; -} NPPrint; - -#ifdef XP_MACOSX -/* BEGIN GOOGLE MODIFICATIONS */ -typedef struct _NPNSMenu NPNSMenu; -/* END GOOGLE MODIFICATIONS */ -typedef NPNSMenu NPMenu; -#else -typedef void * NPMenu; -#endif - -typedef enum { - NPCoordinateSpacePlugin = 1, - NPCoordinateSpaceWindow, - NPCoordinateSpaceFlippedWindow, - NPCoordinateSpaceScreen, - NPCoordinateSpaceFlippedScreen -} NPCoordinateSpace; - -#if defined(XP_MAC) || defined(XP_MACOSX) - -#ifndef NP_NO_CARBON -typedef EventRecord NPEvent; -#endif - -#elif defined(XP_WIN) -typedef struct _NPEvent -{ - uint16 event; - uint32 wParam; - uint32 lParam; -} NPEvent; -#elif defined (XP_UNIX) && defined(MOZ_X11) -/* BEGIN GOOGLE MODIFICATIONS */ -typedef union _XEvent XEvent; -/* END GOOGLE MODIFICATIONS */ -typedef XEvent NPEvent; -#else -typedef void* NPEvent; -#endif /* XP_MACOSX */ - -#if defined(XP_MAC) -typedef RgnHandle NPRegion; -#elif defined(XP_MACOSX) -/* - * NPRegion's type depends on the drawing model specified by the plugin (see NPNVpluginDrawingModel). - * NPQDRegion represents a QuickDraw RgnHandle and is used with the QuickDraw drawing model. - * NPCGRegion repesents a graphical region when using any other drawing model. - */ -typedef void *NPRegion; -#ifndef NP_NO_QUICKDRAW -typedef RgnHandle NPQDRegion; -#endif -typedef CGPathRef NPCGRegion; -#elif defined(XP_WIN) -typedef HRGN NPRegion; -#elif defined(XP_UNIX) -/* BEGIN GOOGLE MODIFICATIONS */ -typedef struct _XRegion *Region; -/* END GOOGLE MODIFICATIONS */ -typedef Region NPRegion; -#else -typedef void *NPRegion; -#endif /* XP_MAC */ - -#ifdef XP_MACOSX - -/* - * NP_CGContext is the type of the NPWindow's 'window' when the plugin specifies NPDrawingModelCoreGraphics - * as its drawing model. - */ - -typedef struct NP_CGContext -{ - CGContextRef context; -#ifdef NP_NO_CARBON - NPNSWindow *window; -#else - void *window; /* Can be either an NSWindow or a WindowRef depending on the event model */ -#endif -} NP_CGContext; - -/* - * NP_GLContext is the type of the NPWindow's 'window' when the plugin specifies NPDrawingModelOpenGL as its - * drawing model. - */ - -typedef struct NP_GLContext -{ - CGLContextObj context; -#ifdef NP_NO_CARBON - NPNSWindow *window; -#else - void *window; /* Can be either an NSWindow or a WindowRef depending on the event model */ -#endif -} NP_GLContext; - -#endif /* XP_MACOSX */ - -#if defined(XP_MAC) || defined(XP_MACOSX) - -/* - * Mac-specific structures and definitions. - */ - -#ifndef NP_NO_QUICKDRAW - -/* - * NP_Port is the type of the NPWindow's 'window' when the plugin specifies NPDrawingModelQuickDraw as its - * drawing model, or the plugin does not specify a drawing model. - * - * It is not recommended that new plugins use NPDrawingModelQuickDraw or NP_Port, as QuickDraw has been - * deprecated in Mac OS X 10.5. CoreGraphics is the preferred drawing API. - * - * NP_Port is not available in 64-bit. - */ - -typedef struct NP_Port -{ - CGrafPtr port; /* Grafport */ - int32 portx; /* position inside the topmost window */ - int32 porty; -} NP_Port; - -#endif /* NP_NO_QUICKDRAW */ - -/* - * Non-standard event types that can be passed to HandleEvent - */ -/* BEGIN GOOGLE MODIFICATIONS */ -#ifndef NP_NO_CARBON -enum NPEventType { - NPEventType_GetFocusEvent = (osEvt + 16), - NPEventType_LoseFocusEvent, - NPEventType_AdjustCursorEvent, - NPEventType_MenuCommandEvent, - NPEventType_ClippingChangedEvent, - NPEventType_ScrollingBeginsEvent = 1000, - NPEventType_ScrollingEndsEvent -}; - -#ifdef OBSOLETE -#define getFocusEvent (osEvt + 16) -#define loseFocusEvent (osEvt + 17) -#define adjustCursorEvent (osEvt + 18) -#endif -#endif /* NP_NO_CARBON */ -/* END GOOGLE MODIFICATIONS */ - -#endif /* XP_MACOSX */ - -/* - * Values for mode passed to NPP_New: - */ -#define NP_EMBED 1 -#define NP_FULL 2 - -/* - * Values for stream type passed to NPP_NewStream: - */ -#define NP_NORMAL 1 -#define NP_SEEK 2 -#define NP_ASFILE 3 -#define NP_ASFILEONLY 4 - -#define NP_MAXREADY (((unsigned)(~0)<<1)>>1) - -#if !defined(__LP64__) -#if defined(XP_MAC) || defined(XP_MACOSX) -#pragma options align=reset -#endif -#endif /* __LP64__ */ - - -/*----------------------------------------------------------------------*/ -/* Error and Reason Code definitions */ -/*----------------------------------------------------------------------*/ - -/* - * Values of type NPError: - */ -#define NPERR_BASE 0 -#define NPERR_NO_ERROR (NPERR_BASE + 0) -#define NPERR_GENERIC_ERROR (NPERR_BASE + 1) -#define NPERR_INVALID_INSTANCE_ERROR (NPERR_BASE + 2) -#define NPERR_INVALID_FUNCTABLE_ERROR (NPERR_BASE + 3) -#define NPERR_MODULE_LOAD_FAILED_ERROR (NPERR_BASE + 4) -#define NPERR_OUT_OF_MEMORY_ERROR (NPERR_BASE + 5) -#define NPERR_INVALID_PLUGIN_ERROR (NPERR_BASE + 6) -#define NPERR_INVALID_PLUGIN_DIR_ERROR (NPERR_BASE + 7) -#define NPERR_INCOMPATIBLE_VERSION_ERROR (NPERR_BASE + 8) -#define NPERR_INVALID_PARAM (NPERR_BASE + 9) -#define NPERR_INVALID_URL (NPERR_BASE + 10) -#define NPERR_FILE_NOT_FOUND (NPERR_BASE + 11) -#define NPERR_NO_DATA (NPERR_BASE + 12) -#define NPERR_STREAM_NOT_SEEKABLE (NPERR_BASE + 13) - -/* - * Values of type NPReason: - */ -#define NPRES_BASE 0 -#define NPRES_DONE (NPRES_BASE + 0) -#define NPRES_NETWORK_ERR (NPRES_BASE + 1) -#define NPRES_USER_BREAK (NPRES_BASE + 2) - -/* - * Don't use these obsolete error codes any more. - */ -#define NP_NOERR NP_NOERR_is_obsolete_use_NPERR_NO_ERROR -#define NP_EINVAL NP_EINVAL_is_obsolete_use_NPERR_GENERIC_ERROR -#define NP_EABORT NP_EABORT_is_obsolete_use_NPRES_USER_BREAK - -/* - * Version feature information - */ -#define NPVERS_HAS_STREAMOUTPUT 8 -#define NPVERS_HAS_NOTIFICATION 9 -#define NPVERS_HAS_LIVECONNECT 9 -#define NPVERS_WIN16_HAS_LIVECONNECT 9 -#define NPVERS_68K_HAS_LIVECONNECT 11 -#define NPVERS_HAS_WINDOWLESS 11 -#define NPVERS_HAS_XPCONNECT_SCRIPTING 13 -#define NPVERS_HAS_NPRUNTIME_SCRIPTING 14 -#define NPVERS_HAS_FORM_VALUES 15 -#define NPVERS_HAS_POPUPS_ENABLED_STATE 16 -#define NPVERS_HAS_RESPONSE_HEADERS 17 -#define NPVERS_HAS_NPOBJECT_ENUM 18 -#define NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL 19 -#define NPVERS_HAS_ALL_NETWORK_STREAMS 20 -#define NPVERS_HAS_URL_AND_AUTH_INFO 21 -#define NPVERS_HAS_PRIVATE_MODE 22 -#define NPVERS_MACOSX_HAS_EVENT_MODELS 23 -#define NPVERS_HAS_CANCEL_SRC_STREAM 24 - -/*----------------------------------------------------------------------*/ -/* Function Prototypes */ -/*----------------------------------------------------------------------*/ - -#if defined(_WINDOWS) && !defined(WIN32) -#define NP_LOADDS _loadds -#else -#define NP_LOADDS -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * NPP_* functions are provided by the plugin and called by the navigator. - */ - -#ifdef XP_UNIX -char* NPP_GetMIMEDescription(void); -#endif /* XP_UNIX */ - -NPError NPP_Initialize(void); -void NPP_Shutdown(void); -NPError NP_LOADDS NPP_New(NPMIMEType pluginType, NPP instance, - uint16 mode, int16 argc, char* argn[], - char* argv[], NPSavedData* saved); -NPError NP_LOADDS NPP_Destroy(NPP instance, NPSavedData** save); -NPError NP_LOADDS NPP_SetWindow(NPP instance, NPWindow* window); -NPError NP_LOADDS NPP_NewStream(NPP instance, NPMIMEType type, - NPStream* stream, NPBool seekable, - uint16* stype); -NPError NP_LOADDS NPP_DestroyStream(NPP instance, NPStream* stream, - NPReason reason); -int32 NP_LOADDS NPP_WriteReady(NPP instance, NPStream* stream); -int32 NP_LOADDS NPP_Write(NPP instance, NPStream* stream, int32 offset, - int32 len, void* buffer); -void NP_LOADDS NPP_StreamAsFile(NPP instance, NPStream* stream, - const char* fname); -void NP_LOADDS NPP_Print(NPP instance, NPPrint* platformPrint); -int16 NPP_HandleEvent(NPP instance, void* event); -void NP_LOADDS NPP_URLNotify(NPP instance, const char* url, - NPReason reason, void* notifyData); -jref NP_LOADDS NPP_GetJavaClass(void); -NPError NPP_GetValue(NPP instance, NPPVariable variable, - void *value); -NPError NPP_SetValue(NPP instance, NPNVariable variable, - void *value); - -/* - * NPN_* functions are provided by the navigator and called by the plugin. - */ - -void NPN_Version(int* plugin_major, int* plugin_minor, - int* netscape_major, int* netscape_minor); -NPError NPN_GetURLNotify(NPP instance, const char* url, - const char* target, void* notifyData); -NPError NPN_GetURL(NPP instance, const char* url, - const char* target); -NPError NPN_PostURLNotify(NPP instance, const char* url, - const char* target, uint32 len, - const char* buf, NPBool file, - void* notifyData); -NPError NPN_PostURL(NPP instance, const char* url, - const char* target, uint32 len, - const char* buf, NPBool file); -NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList); -NPError NPN_NewStream(NPP instance, NPMIMEType type, - const char* target, NPStream** stream); -int32 NPN_Write(NPP instance, NPStream* stream, int32 len, - void* buffer); -NPError NPN_DestroyStream(NPP instance, NPStream* stream, - NPReason reason); -void NPN_Status(NPP instance, const char* message); -const char* NPN_UserAgent(NPP instance); -void* NPN_MemAlloc(uint32 size); -void NPN_MemFree(void* ptr); -uint32 NPN_MemFlush(uint32 size); -void NPN_ReloadPlugins(NPBool reloadPages); -JRIEnv* NPN_GetJavaEnv(void); -jref NPN_GetJavaPeer(NPP instance); -NPError NPN_GetValue(NPP instance, NPNVariable variable, - void *value); -NPError NPN_SetValue(NPP instance, NPPVariable variable, - void *value); -void NPN_InvalidateRect(NPP instance, NPRect *invalidRect); -void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion); -void NPN_ForceRedraw(NPP instance); -void NPN_PushPopupsEnabledState(NPP instance, NPBool enabled); -void NPN_PopPopupsEnabledState(NPP instance); -void NPN_PluginThreadAsyncCall(NPP instance, void (*func) (void *), void *userData); -NPError NPN_GetValueForURL(NPP instance, NPNURLVariable variable, const char* url, char** value, uint32* len); -NPError NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char* url, const char* value, uint32 len); -NPError NPN_GetAuthenticationInfo(NPP instance, const char* protocol, const char* host, int32 port, const char* scheme, const char *realm, char** username, uint32* ulen, char** password, uint32* plen); -uint32 NPN_ScheduleTimer(NPP instance, uint32 interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32 timerID)); -void NPN_UnscheduleTimer(NPP instance, uint32 timerID); -NPError NPN_PopUpContextMenu(NPP instance, NPMenu* menu); -NPBool NPN_ConvertPoint(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace); - -#ifdef __cplusplus -} /* end extern "C" */ -#endif - -#endif /* _NPAPI_H_ */ diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions.h deleted file mode 100644 index f8c05f47b..000000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions.h +++ /dev/null @@ -1,646 +0,0 @@ -/* Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef _NP_EXTENSIONS_H_ -#define _NP_EXTENSIONS_H_ - -// Use the shorter include path here so that this file can be used in non- -// Chromium projects, such as the Native Client SDK. -#include "npapi.h" - -/* - * A fake "enum" value for getting browser-implemented Pepper extensions. - * The variable returns a pointer to an NPNExtensions structure. */ -#define NPNVPepperExtensions ((NPNVariable) 4000) - -/* - * A fake "enum" value for getting plugin-implemented Pepper extensions. - * The variable returns a pointer to an NPPExtensions structure. */ -#define NPPVPepperExtensions ((NPPVariable) 4001) - -typedef void NPDeviceConfig; -typedef void NPDeviceContext; -typedef void NPUserData; - -/* unique id for each device interface */ -typedef int32 NPDeviceID; - -typedef struct _NPPoint { - uint16 x; - uint16 y; -} NPPoint; - -typedef enum { - NPThemeItemScrollbarDownArrow = 0, - NPThemeItemScrollbarLeftArrow = 1, - NPThemeItemScrollbarRightArrow = 2, - NPThemeItemScrollbarUpArrow = 3, - NPThemeItemScrollbarHorizontalThumb = 4, - NPThemeItemScrollbarVerticalThumb = 5, - NPThemeItemScrollbarHoriztonalTrack = 6, - NPThemeItemScrollbarVerticalTrack = 7 -} NPThemeItem; - -typedef enum { - NPThemeStateDisabled = 0, - // Mouse is over this item. - NPThemeStateHot = 1, - // Mouse is over another part of this component. This is only used on Windows - // Vista and above. The plugin should pass it in, and the host will convert - // it to NPThemeStateNormal if on other platforms or on Windows XP. - NPThemeStateHover = 2, - NPThemeStateNormal = 3, - NPThemeStatePressed = 4 -} NPThemeState; - -typedef struct _NPThemeParams { - NPThemeItem item; - NPThemeState state; - NPRect location; - // Used for scroll bar tracks, needed for classic theme in Windows which draws - // a checkered pattern. - NPPoint align; -} NPThemeParams; - -typedef struct _NPDeviceBuffer { - void* ptr; - size_t size; -} NPDeviceBuffer; - -/* completion callback for flush device */ -typedef void (*NPDeviceFlushContextCallbackPtr)( - NPP instance, - NPDeviceContext* context, - NPError err, - NPUserData* userData); - -/* query single capabilities of device */ -typedef NPError ( - *NPDeviceQueryCapabilityPtr)(NPP instance, - int32 capability, - int32 *value); -/* query config (configuration == a set of capabilities) */ -typedef NPError ( - *NPDeviceQueryConfigPtr)(NPP instance, - const NPDeviceConfig* request, - NPDeviceConfig* obtain); -/* device initialization */ -typedef NPError (*NPDeviceInitializeContextPtr)( - NPP instance, - const NPDeviceConfig* config, - NPDeviceContext* context); -/* peek at device state */ -typedef NPError (*NPDeviceGetStateContextPtr) ( - NPP instance, - NPDeviceContext* context, - int32 state, - intptr_t* value); -/* poke device state */ -typedef NPError (*NPDeviceSetStateContextPtr) ( - NPP instance, - NPDeviceContext* context, - int32 state, - intptr_t value); -/* flush context, if callback, userData are NULL */ -/* this becomes a blocking call */ -typedef NPError (*NPDeviceFlushContextPtr)( - NPP instance, - NPDeviceContext* context, - NPDeviceFlushContextCallbackPtr callback, - void* userData); -/* destroy device context. Application responsible for */ -/* freeing context, if applicable */ -typedef NPError (*NPDeviceDestroyContextPtr)( - NPP instance, - NPDeviceContext* context); -/* Create a buffer associated with a particular context. The usage of the */ -/* buffer is device specific. The lifetime of the buffer is scoped with the */ -/* lifetime of the context. */ -typedef NPError (*NPDeviceCreateBufferPtr)( - NPP instance, - NPDeviceContext* context, - size_t size, - int32* id); -/* Destroy a buffer associated with a particular context. */ -typedef NPError (*NPDeviceDestroyBufferPtr)( - NPP instance, - NPDeviceContext* context, - int32 id); -/* Map a buffer id to its address. */ -typedef NPError (*NPDeviceMapBufferPtr)( - NPP instance, - NPDeviceContext* context, - int32 id, - NPDeviceBuffer* buffer); -/* Gets the size of the given theme component. For variable sized items like */ -/* vertical scrollbar tracks, the width will be the required width of the */ -/* track while the height will be the minimum height. */ -typedef NPError (*NPDeviceThemeGetSize)( - NPP instance, - NPThemeItem item, - int* width, - int* height); -/* Draw a themed item (i.e. scrollbar arrow). */ -typedef NPError (*NPDeviceThemePaint)( - NPP instance, - NPDeviceContext* context, - NPThemeParams* params); - - -/* forward decl typdef structs */ -typedef struct NPDevice NPDevice; -typedef struct NPNExtensions NPNExtensions; - -// DEPRECATED: this typedef is just for the NaCl code until they switch to NPNExtensions. -// PLEASE REMOVE THIS WHEN THE NACL CODE IS UPDATED. -typedef struct NPNExtensions NPExtensions; - -/* generic device interface */ -struct NPDevice { - NPDeviceQueryCapabilityPtr queryCapability; - NPDeviceQueryConfigPtr queryConfig; - NPDeviceInitializeContextPtr initializeContext; - NPDeviceSetStateContextPtr setStateContext; - NPDeviceGetStateContextPtr getStateContext; - NPDeviceFlushContextPtr flushContext; - NPDeviceDestroyContextPtr destroyContext; - NPDeviceCreateBufferPtr createBuffer; - NPDeviceDestroyBufferPtr destroyBuffer; - NPDeviceMapBufferPtr mapBuffer; - NPDeviceThemeGetSize themeGetSize; - NPDeviceThemePaint themePaint; -}; - -/* returns NULL if deviceID unavailable / unrecognized */ -typedef NPDevice* (*NPAcquireDevicePtr)( - NPP instance, - NPDeviceID device); - -/* Copy UTF-8 string into clipboard */ -typedef void (*NPCopyTextToClipboardPtr)( - NPP instance, - const char* content); - -/* Updates the number of find results for the current search term. If - * there are no matches 0 should be passed in. Only when the plugin has - * finished searching should it pass in the final count with finalResult set to - * true. */ -typedef void (*NPNumberOfFindResultsChangedPtr)( - NPP instance, - int total, - bool finalResult); - - /* Updates the index of the currently selected search item. */ -typedef void (*NPSelectedFindResultChangedPtr)( - NPP instance, - int index); - -/* Supports opening files anywhere on the system after prompting the user to - * pick one. - * - * This API is asynchronous. It will return immediately and the user will be - * prompted in parallel to pick a file. The plugin may continue to receive - * events while the open file dialog is up, and may continue to paint. Plugins - * may want to ignore input events between the call and the callback to avoid - * reentrant behavior. If the return value is not NPERR_NO_ERROR, the callback - * will NOT be executed. - * - * It is an error to call BrowseForFile before a previous call has executed - * the callback. - * - * Setting the flags to "Open" requires that the file exist to allow picking. - * Setting the flags to "Save" allows selecting nonexistant files (which will - * then be created), and will prompt the user if they want to overwrite an - * existing file if it exists. - * - * The plugin may specify a comma-separated list of possible mime types in - * the "extensions" parameter. If no extensions are specified, the dialog box - * will default to allowing all extensions. The first extension in the list - * will be the default. - * - * TODO(brettw) On Windows the extensions traditionally include a text - * description with the extension in the popup, do we want to allow this? - * We should probably also allow the ability to put "All files" in the - * list on Windows. - * - * Once the user has picked a file or has canceled the dialog box, the given - * callback will be called with the results of the operation and the passed in - * "user data" pointer. If the user successfully picked a file, the filename - * will be non-NULL and will contain a pointer to an array of strings, one for - * each file picked (the first file will be file_paths[0]). This buffer will - * become invalid as soon as the call completes, so it is the plugin's - * responsibility to copy the filename(sp if it needs future access to them. - * A NULL file_paths in the callback means the user canceled the dialog box. - * - * The filename will be in UTF-8. It may not actually correspond to the actual - * file on disk on a Linux system, because we'll do our best to convert it from - * the filesystem's locale to UTF-8. Instead, the string will be appropriate for - * displaying to the user which file they picked. - * */ -typedef enum { - NPChooseFile_Open = 1, - NPChooseFile_OpenMultiple = 2, - NPChooseFile_Save = 3, -} NPChooseFileMode; -typedef void (*NPChooseFileCallback)(const char** filePaths, - uint32 pathCount, - void* userData); -typedef NPError (*NPChooseFilePtr)( - NPP instance, - const char* mimeTypes, - NPChooseFileMode mode, - NPChooseFileCallback callback, - void* userData); - -/* Pepper extensions */ -struct NPNExtensions { - /* Device interface acquisition */ - NPAcquireDevicePtr acquireDevice; - /* Clipboard functionality */ - NPCopyTextToClipboardPtr copyTextToClipboard; - /* Find */ - NPNumberOfFindResultsChangedPtr numberOfFindResultsChanged; - NPSelectedFindResultChangedPtr selectedFindResultChanged; - /* File I/O extensions */ - NPChooseFilePtr chooseFile; -}; - -/* Events -------------------------------------------------------------------*/ - -typedef enum { - NPMouseButton_None = -1, - NPMouseButton_Left = 0, - NPMouseButton_Middle = 1, - NPMouseButton_Right = 2 -} NPMouseButtons; - -typedef enum { - NPEventType_Undefined = -1, - NPEventType_MouseDown = 0, - NPEventType_MouseUp = 1, - NPEventType_MouseMove = 2, - NPEventType_MouseEnter = 3, - NPEventType_MouseLeave = 4, - NPEventType_MouseWheel = 5, - NPEventType_RawKeyDown = 6, - NPEventType_KeyDown = 7, - NPEventType_KeyUp = 8, - NPEventType_Char = 9, - NPEventType_Minimize = 10, - NPEventType_Focus = 11, - NPEventType_Device = 12 -} NPEventTypes; - -typedef enum { - NPEventModifier_ShiftKey = 1 << 0, - NPEventModifier_ControlKey = 1 << 1, - NPEventModifier_AltKey = 1 << 2, - NPEventModifier_MetaKey = 1 << 3, - NPEventModifier_IsKeyPad = 1 << 4, - NPEventModifier_IsAutoRepeat = 1 << 5, - NPEventModifier_LeftButtonDown = 1 << 6, - NPEventModifier_MiddleButtonDown = 1 << 7, - NPEventModifier_RightButtonDown = 1 << 8 -} NPEventModifiers; - -typedef struct _NPKeyEvent -{ - uint32 modifier; - uint32 normalizedKeyCode; -} NPKeyEvent; - -typedef struct _NPCharacterEvent -{ - uint32 modifier; - uint16 text[4]; - uint16 unmodifiedText[4]; -} NPCharacterEvent; - -typedef struct _NPMouseEvent -{ - uint32 modifier; - int32 button; - int32 x; - int32 y; - int32 clickCount; -} NPMouseEvent; - -typedef struct _NPMouseWheelEvent -{ - uint32 modifier; - float deltaX; - float deltaY; - float wheelTicksX; - float wheelTicksY; - uint32 scrollByPage; -} NPMouseWheelEvent; - -typedef struct _NPDeviceEvent { - uint32 device_uid; - uint32 subtype; - /* uint8 generic[0]; */ -} NPDeviceEvent; - -typedef struct _NPMinimizeEvent { - int32 value; -} NPMinimizeEvent; - -typedef struct _NPFocusEvent { - int32 value; -} NPFocusEvent; - -typedef struct _NPPepperEvent -{ - uint32 size; - int32 type; - double timeStampSeconds; - union { - NPKeyEvent key; - NPCharacterEvent character; - NPMouseEvent mouse; - NPMouseWheelEvent wheel; - NPMinimizeEvent minimize; - NPFocusEvent focus; - NPDeviceEvent device; - } u; -} NPPepperEvent; - -/* 2D -----------------------------------------------------------------------*/ - -#define NPPepper2DDevice 1 - -typedef struct _NPDeviceContext2DConfig { -} NPDeviceContext2DConfig; - -typedef struct _NPDeviceContext2D -{ - /* Internal value used by the browser to identify this device. */ - void* reserved; - - /* A pointer to the pixel data. This data is 8-bit values in BGRA order in - * memory. Each row will start |stride| bytes after the previous one. - * - * THIS DATA USES PREMULTIPLIED ALPHA. This means that each color channel has - * been multiplied with the corresponding alpha, which makes compositing - * easier. If any color channels have a value greater than the alpha value, - * you'll likely get crazy colors and weird artifacts. */ - void* region; - - /* Length of each row of pixels in bytes. This may be larger than width * 4 - * if there is padding at the end of each row to help with alignment. */ - int32 stride; - - /* The dirty region that the plugin has painted into the buffer. This - * will be initialized to the size of the plugin image in - * initializeContextPtr. The plugin can change the values to only - * update portions of the image. */ - struct { - int32 left; - int32 top; - int32 right; - int32 bottom; - } dirty; -} NPDeviceContext2D; - -/* 3D -----------------------------------------------------------------------*/ - -#define NPPepper3DDevice 2 - -typedef struct _NPDeviceContext3DConfig { - int32 commandBufferSize; -} NPDeviceContext3DConfig; - -typedef enum _NPDeviceContext3DError { - // No error has ocurred. - NPDeviceContext3DError_NoError, - - // The size of a command was invalid. - NPDeviceContext3DError_InvalidSize, - - // An offset was out of bounds. - NPDeviceContext3DError_OutOfBounds, - - // A command was not recognized. - NPDeviceContext3DError_UnknownCommand, - - // The arguments to a command were invalid. - NPDeviceContext3DError_InvalidArguments, - - // The 3D context was lost, for example due to a power management event. The - // context must be destroyed and a new one created. - NPDeviceContext3DError_LostContext, - - // Any other error. - NPDeviceContext3DError_GenericError -} NPDeviceContext3DError; - -typedef struct _NPDeviceContext3D NPDeviceContext3D; - -typedef void (*NPDeviceContext3DRepaintPtr)(NPP npp, - NPDeviceContext3D* context); - -typedef struct _NPDeviceContext3D -{ - void* reserved; - - // If true, then a flush will only complete once the get offset has advanced - // on the GPU thread. If false, then the get offset might have changed but - // the GPU thread will respond as quickly as possible without guaranteeing - // having made any progress in executing pending commands. Set to true - // to ensure that progress is made or when flushing in a loop waiting for the - // GPU to reach a certain state, for example in advancing beyond a particular - // token. Set to false when flushing to query the current state, for example - // whether an error has occurred. - bool waitForProgress; - - // Buffer in which commands are stored. - void* commandBuffer; - int32 commandBufferSize; - - // Offset in command buffer reader has reached. Synchronized on flush. - int32 getOffset; - - // Offset in command buffer writer has reached. Synchronized on flush. - int32 putOffset; - - // Last processed token. Synchronized on flush. - int32 token; - - // Callback invoked on the main thread when the context must be repainted. - // TODO(apatrick): move this out of the context struct like the rest of the - // fields. - NPDeviceContext3DRepaintPtr repaintCallback; - - // Error status. Synchronized on flush. - NPDeviceContext3DError error; -} NPDeviceContext3D; - -/* Audio --------------------------------------------------------------------*/ - -#define NPPepperAudioDevice 3 - -/* min & max sample frame count */ -typedef enum { - NPAudioMinSampleFrameCount = 64, - NPAudioMaxSampleFrameCount = 32768 -} NPAudioSampleFrameCounts; - -/* supported sample rates */ -typedef enum { - NPAudioSampleRate44100Hz = 44100, - NPAudioSampleRate48000Hz = 48000, - NPAudioSampleRate96000Hz = 96000 -} NPAudioSampleRates; - -/* supported sample formats */ -typedef enum { - NPAudioSampleTypeInt16 = 0, - NPAudioSampleTypeFloat32 = 1 -} NPAudioSampleTypes; - -/* supported channel layouts */ -/* there is code that depends on these being the actual number of channels */ -typedef enum { - NPAudioChannelNone = 0, - NPAudioChannelMono = 1, - NPAudioChannelStereo = 2, - NPAudioChannelThree = 3, - NPAudioChannelFour = 4, - NPAudioChannelFive = 5, - NPAudioChannelFiveOne = 6, - NPAudioChannelSeven = 7, - NPAudioChannelSevenOne = 8 -} NPAudioChannels; - -/* audio context states */ -typedef enum { - NPAudioContextStateCallback = 0, - NPAudioContextStateUnderrunCounter = 1 -} NPAudioContextStates; - -/* audio context state values */ -typedef enum { - NPAudioCallbackStop = 0, - NPAudioCallbackStart = 1 -} NPAudioContextStateValues; - -/* audio query capabilities */ -typedef enum { - NPAudioCapabilitySampleRate = 0, - NPAudioCapabilitySampleType = 1, - NPAudioCapabilitySampleFrameCount = 2, - NPAudioCapabilitySampleFrameCount44100Hz = 3, - NPAudioCapabilitySampleFrameCount48000Hz = 4, - NPAudioCapabilitySampleFrameCount96000Hz = 5, - NPAudioCapabilityOutputChannelMap = 6, - NPAudioCapabilityInputChannelMap = 7 -} NPAudioCapabilities; - -typedef struct _NPDeviceContextAudio NPDeviceContextAudio; - -/* user supplied callback function */ -typedef void (*NPAudioCallback)(NPDeviceContextAudio *context); - -typedef struct _NPDeviceContextAudioConfig { - int32 sampleRate; - int32 sampleType; - int32 outputChannelMap; - int32 inputChannelMap; - int32 sampleFrameCount; - uint32 startThread; - uint32 flags; - NPAudioCallback callback; - void *userData; -} NPDeviceContextAudioConfig; - -struct _NPDeviceContextAudio { - NPDeviceContextAudioConfig config; - void *outBuffer; - void *inBuffer; - void *reserved; -}; - -/* Printing related APIs ---------------------------------------------------*/ - -/* Being a print operation. Returns the total number of pages to print at the - * given printableArea size and DPI. printableArea is in points (a point is 1/72 - * of an inch). The plugin is expected to remember the values of printableArea - * and printerDPI for use in subsequent print interface calls. These values - * should be cleared in printEnd. */ -typedef NPError (*NPPPrintBeginPtr) ( - NPP instance, - NPRect* printableArea, - int32 printerDPI, - int32* numPages); -/* Returns the required raster dimensions for the given page. */ -typedef NPError (*NPPGetRasterDimensionsPtr) ( - NPP instance, - int32 pageNumber, - int32* widthInPixels, - int32* heightInPixels); -/* Prints the specified page This allows the plugin to print a raster output. */ -typedef NPError (*NPPPrintPageRasterPtr) ( - NPP instance, - int32 pageNumber, - NPDeviceContext2D* printSurface); -/* Ends the print operation */ -typedef NPError (*NPPPrintEndPtr) (NPP instance); - -/* TODO(sanjeevr) : Provide a vector interface for printing. We need to decide - * on a vector format that can support embedded fonts. A vector format will - * greatly reduce the size of the required output buffer. */ - -typedef struct _NPPPrintExtensions { - NPPPrintBeginPtr printBegin; - NPPGetRasterDimensionsPtr getRasterDimensions; - NPPPrintPageRasterPtr printPageRaster; - NPPPrintEndPtr printEnd; -} NPPPrintExtensions; - -/* Returns NULL if the plugin does not support print extensions */ -typedef NPPPrintExtensions* (*NPPGetPrintExtensionsPtr)(NPP instance); - -/* Find ---------------------------------------------------------------------*/ - -/* Finds the given UTF-8 text starting at the current selection. The number of - * results will be updated asynchronously via numberOfFindResultsChanged. Note - * that multiple StartFind calls can happen before StopFind is called in the - * case of the search term changing. */ -typedef NPError (*NPPStartFindPtr) ( - NPP instance, - const char* text, - bool caseSensitive); - -/* Go to the next/previous result. */ -typedef NPError (*NPPSelectFindResultPtr) ( - NPP instance, - bool forward); - -/* Tells the plugin that the find operation has stopped, so it should clear - * any highlighting. */ -typedef NPError (*NPPStopFindPtr) ( - NPP instance); - -typedef struct _NPPFindExtensions { - NPPStartFindPtr startFind; - NPPSelectFindResultPtr selectFindResult; - NPPStopFindPtr stopFind; -} NPPFindExtensions; - -/* Returns NULL if the plugin does not support find extensions. */ -typedef NPPFindExtensions* (*NPPGetFindExtensionsPtr)(NPP instance); - -/* Zooms plugins. 0 means reset, -1 means zoom out, and +1 means zoom in. */ -typedef NPError (*NPPZoomPtr) ( - NPP instance, - int factor); - -typedef struct _NPPExtensions { - NPPGetPrintExtensionsPtr getPrintExtensions; - NPPGetFindExtensionsPtr getFindExtensions; - NPPZoomPtr zoom; -} NPPExtensions; - -#endif /* _NP_EXTENSIONS_H_ */ diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/nphostapi.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/nphostapi.h deleted file mode 100644 index 69bad70ef..000000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/nphostapi.h +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO: Did not implement JRIGlobalRef function yet. Not sure if this is used? - -#ifndef _NPHOSTAPI_H_ -#define _NPHOSTAPI_H_ - -#include "base/port.h" -#include "third_party/npapi/bindings/npapi.h" -#include "third_party/npapi/bindings/npapi_extensions.h" -#include "third_party/npapi/bindings/npruntime.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// -// NPAPI NPP Function Pointers -// -typedef NPError (*NPP_NewProcPtr)(NPMIMEType pluginType, - NPP instance, - uint16 mode, - int16 argc, - char* argn[], - char* argv[], - NPSavedData* saved); -typedef NPError (*NPP_DestroyProcPtr)(NPP instance, - NPSavedData** save); -typedef NPError (*NPP_SetWindowProcPtr)(NPP instance, - NPWindow* window); -typedef NPError (*NPP_NewStreamProcPtr)(NPP instance, - NPMIMEType type, - NPStream* stream, - NPBool seekable, - uint16* stype); -typedef NPError (*NPP_DestroyStreamProcPtr)(NPP instance, - NPStream* stream, - NPReason reason); -typedef int32 (*NPP_WriteReadyProcPtr)(NPP instance, - NPStream* stream); -typedef int32 (*NPP_WriteProcPtr)(NPP instance, - NPStream* stream, - int32 offset, - int32 len, - void* buffer); -typedef void (*NPP_StreamAsFileProcPtr)(NPP instance, - NPStream* stream, - const char* fname); -typedef void (*NPP_PrintProcPtr)(NPP instance, - NPPrint* platformPrint); -typedef int16 (*NPP_HandleEventProcPtr)(NPP instance, - void* event); -typedef void (*NPP_URLNotifyProcPtr)(NPP instance, - const char* url, - NPReason reason, - void* notifyData); -typedef void* JRIGlobalRef; //not using this right now -typedef NPError (*NPP_GetValueProcPtr)(NPP instance, - NPPVariable variable, - void *ret_alue); -typedef NPError (*NPP_SetValueProcPtr)(NPP instance, - NPNVariable variable, - void *ret_alue); - -// -// NPAPI NPN Function Pointers -// -typedef NPError (*NPN_GetURLProcPtr)(NPP instance, - const char* URL, - const char* window); -typedef NPError (*NPN_PostURLProcPtr)(NPP instance, - const char* URL, - const char* window, - uint32 len, - const char* buf, - NPBool file); -typedef NPError (*NPN_RequestReadProcPtr)(NPStream* stream, - NPByteRange* rangeList); -typedef NPError (*NPN_NewStreamProcPtr)(NPP instance, - NPMIMEType type, - const char* window, - NPStream** stream); -typedef int32 (*NPN_WriteProcPtr)(NPP instance, - NPStream* stream, - int32 len, - void* buffer); -typedef NPError (*NPN_DestroyStreamProcPtr)(NPP instance, - NPStream* stream, - NPReason reason); -typedef void (*NPN_StatusProcPtr)(NPP instance, - const char* message); -typedef const char* (*NPN_UserAgentProcPtr)(NPP instance); -typedef void* (*NPN_MemAllocProcPtr)(uint32 size); -typedef void (*NPN_MemFreeProcPtr)(void* ptr); -typedef uint32 (*NPN_MemFlushProcPtr)(uint32 size); -typedef void (*NPN_ReloadPluginsProcPtr)(NPBool reloadPages); - -typedef void* (*NPN_GetJavaEnvProcPtr)(void); -typedef void* (*NPN_GetJavaPeerProcPtr)(NPP instance); - -typedef NPError (*NPN_GetURLNotifyProcPtr)(NPP instance, - const char* URL, - const char* window, - void* notifyData); -typedef NPError (*NPN_PostURLNotifyProcPtr)(NPP instance, - const char* URL, - const char* window, - uint32 len, - const char* buf, - NPBool file, - void* notifyData); -typedef NPError (*NPN_GetValueProcPtr)(NPP instance, - NPNVariable variable, - void *ret_value); -typedef NPError (*NPN_SetValueProcPtr)(NPP instance, - NPPVariable variable, - void *value); -typedef void (*NPN_InvalidateRectProcPtr)(NPP instance, - NPRect *rect); -typedef void (*NPN_InvalidateRegionProcPtr)(NPP instance, - NPRegion region); -typedef void (*NPN_ForceRedrawProcPtr)(NPP instance); - -typedef void (*NPN_ReleaseVariantValueProcPtr) (NPVariant *variant); - -typedef NPIdentifier (*NPN_GetStringIdentifierProcPtr) (const NPUTF8 *name); -typedef void (*NPN_GetStringIdentifiersProcPtr) (const NPUTF8 **names, - int32_t nameCount, - NPIdentifier *identifiers); -typedef NPIdentifier (*NPN_GetIntIdentifierProcPtr) (int32_t intid); -typedef int32_t (*NPN_IntFromIdentifierProcPtr) (NPIdentifier identifier); -typedef bool (*NPN_IdentifierIsStringProcPtr) (NPIdentifier identifier); -typedef NPUTF8 * (*NPN_UTF8FromIdentifierProcPtr) (NPIdentifier identifier); - -typedef NPObject* (*NPN_CreateObjectProcPtr) (NPP, - NPClass *aClass); -typedef NPObject* (*NPN_RetainObjectProcPtr) (NPObject *obj); -typedef void (*NPN_ReleaseObjectProcPtr) (NPObject *obj); -typedef bool (*NPN_InvokeProcPtr) (NPP npp, - NPObject *obj, - NPIdentifier methodName, - const NPVariant *args, - unsigned argCount, - NPVariant *result); -typedef bool (*NPN_InvokeDefaultProcPtr) (NPP npp, - NPObject *obj, - const NPVariant *args, - unsigned argCount, - NPVariant *result); -typedef bool (*NPN_EvaluateProcPtr) (NPP npp, - NPObject *obj, - NPString *script, - NPVariant *result); -typedef bool (*NPN_GetPropertyProcPtr) (NPP npp, - NPObject *obj, - NPIdentifier propertyName, - NPVariant *result); -typedef bool (*NPN_SetPropertyProcPtr) (NPP npp, - NPObject *obj, - NPIdentifier propertyName, - const NPVariant *value); -typedef bool (*NPN_HasPropertyProcPtr) (NPP, - NPObject *npobj, - NPIdentifier propertyName); -typedef bool (*NPN_HasMethodProcPtr) (NPP npp, - NPObject *npobj, - NPIdentifier methodName); -typedef bool (*NPN_RemovePropertyProcPtr) (NPP npp, - NPObject *obj, - NPIdentifier propertyName); -typedef void (*NPN_SetExceptionProcPtr) (NPObject *obj, - const NPUTF8 *message); -typedef void (*NPN_PushPopupsEnabledStateProcPtr)(NPP npp, - NPBool enabled); -typedef void (*NPN_PopPopupsEnabledStateProcPtr)(NPP npp); -typedef bool (*NPN_EnumerateProcPtr)(NPP npp, - NPObject *obj, - NPIdentifier **identifier, - uint32_t *count); -typedef void (*NPN_PluginThreadAsyncCallProcPtr)(NPP instance, - void (*func)(void *), - void *userData); -typedef bool (*NPN_ConstructProcPtr)(NPP npp, - NPObject* obj, - const NPVariant *args, - uint32_t argCount, - NPVariant *result); -typedef NPError (*NPN_GetValueForURLPtr)(NPP npp, - NPNURLVariable variable, - const char *url, - char **value, - uint32_t *len); -typedef NPError (*NPN_SetValueForURLPtr)(NPP npp, - NPNURLVariable variable, - const char *url, - const char *value, - uint32_t len); -typedef NPError (*NPN_GetAuthenticationInfoPtr)(NPP npp, - const char *protocol, - const char *host, - int32_t port, - const char *scheme, - const char *realm, - char **username, - uint32_t *ulen, - char **password, - uint32_t *plen); -typedef uint32 (*NPN_ScheduleTimerPtr)(NPP npp, - uint32 interval, - NPBool repeat, - void (*timerFunc)(NPP npp, uint32 timerID)); -typedef void (*NPN_UnscheduleTimerPtr)(NPP npp, - uint32 timerID); -typedef NPError (*NPN_PopUpContextMenuPtr)(NPP npp, - NPMenu* menu); -typedef NPBool (*NPN_ConvertPointPtr)(NPP npp, - double sourceX, - double sourceY, - NPCoordinateSpace sourceSpace, - double *destX, - double *destY, - NPCoordinateSpace destSpace); - -// -// NPAPI Function table of NPP functions (functions provided by plugin to host) -// -typedef struct _NPPluginFuncs { - unsigned short size; - unsigned short version; - NPP_NewProcPtr newp; - NPP_DestroyProcPtr destroy; - NPP_SetWindowProcPtr setwindow; - NPP_NewStreamProcPtr newstream; - NPP_DestroyStreamProcPtr destroystream; - NPP_StreamAsFileProcPtr asfile; - NPP_WriteReadyProcPtr writeready; - NPP_WriteProcPtr write; - NPP_PrintProcPtr print; - NPP_HandleEventProcPtr event; - NPP_URLNotifyProcPtr urlnotify; - JRIGlobalRef javaClass; - NPP_GetValueProcPtr getvalue; - NPP_SetValueProcPtr setvalue; -} NPPluginFuncs; - -// -// NPAPI Function table NPN functions (functions provided by host to plugin) -// -typedef struct _NPNetscapeFuncs { - uint16 size; - uint16 version; - NPN_GetURLProcPtr geturl; - NPN_PostURLProcPtr posturl; - NPN_RequestReadProcPtr requestread; - NPN_NewStreamProcPtr newstream; - NPN_WriteProcPtr write; - NPN_DestroyStreamProcPtr destroystream; - NPN_StatusProcPtr status; - NPN_UserAgentProcPtr uagent; - NPN_MemAllocProcPtr memalloc; - NPN_MemFreeProcPtr memfree; - NPN_MemFlushProcPtr memflush; - NPN_ReloadPluginsProcPtr reloadplugins; - NPN_GetJavaEnvProcPtr getJavaEnv; - NPN_GetJavaPeerProcPtr getJavaPeer; - NPN_GetURLNotifyProcPtr geturlnotify; - NPN_PostURLNotifyProcPtr posturlnotify; - NPN_GetValueProcPtr getvalue; - NPN_SetValueProcPtr setvalue; - NPN_InvalidateRectProcPtr invalidaterect; - NPN_InvalidateRegionProcPtr invalidateregion; - NPN_ForceRedrawProcPtr forceredraw; - - NPN_GetStringIdentifierProcPtr getstringidentifier; - NPN_GetStringIdentifiersProcPtr getstringidentifiers; - NPN_GetIntIdentifierProcPtr getintidentifier; - NPN_IdentifierIsStringProcPtr identifierisstring; - NPN_UTF8FromIdentifierProcPtr utf8fromidentifier; - NPN_IntFromIdentifierProcPtr intfromidentifier; - NPN_CreateObjectProcPtr createobject; - NPN_RetainObjectProcPtr retainobject; - NPN_ReleaseObjectProcPtr releaseobject; - NPN_InvokeProcPtr invoke; - NPN_InvokeDefaultProcPtr invokeDefault; - NPN_EvaluateProcPtr evaluate; - NPN_GetPropertyProcPtr getproperty; - NPN_SetPropertyProcPtr setproperty; - NPN_RemovePropertyProcPtr removeproperty; - NPN_HasPropertyProcPtr hasproperty; - NPN_HasMethodProcPtr hasmethod; - NPN_ReleaseVariantValueProcPtr releasevariantvalue; - NPN_SetExceptionProcPtr setexception; - NPN_PushPopupsEnabledStateProcPtr pushpopupsenabledstate; - NPN_PopPopupsEnabledStateProcPtr poppopupsenabledstate; - NPN_EnumerateProcPtr enumerate; - NPN_PluginThreadAsyncCallProcPtr pluginthreadasynccall; - NPN_ConstructProcPtr construct; - NPN_GetValueForURLPtr getvalueforurl; - NPN_SetValueForURLPtr setvalueforurl; - NPN_GetAuthenticationInfoPtr getauthenticationinfo; - NPN_ScheduleTimerPtr scheduletimer; - NPN_UnscheduleTimerPtr unscheduletimer; - NPN_PopUpContextMenuPtr popupcontextmenu; - NPN_ConvertPointPtr convertpoint; -} NPNetscapeFuncs; - -// -// NPAPI library entry points -// -#if defined(OS_POSIX) && !defined(OS_MACOSX) -typedef NPError (API_CALL * NP_InitializeFunc)(NPNetscapeFuncs* pNFuncs, - NPPluginFuncs* pPFuncs); -#else -typedef NPError (API_CALL * NP_InitializeFunc)(NPNetscapeFuncs* pFuncs); -typedef NPError (API_CALL * NP_GetEntryPointsFunc)(NPPluginFuncs* pFuncs); -#endif -typedef NPError (API_CALL * NP_ShutdownFunc)(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _NPHOSTAPI_H_ diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npruntime.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npruntime.h deleted file mode 100644 index e050b21f7..000000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npruntime.h +++ /dev/null @@ -1,396 +0,0 @@ -/* - * Copyright (C) 2004, Apple Computer, Inc. and The Mozilla Foundation. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the names of Apple Computer, Inc. ("Apple") or The Mozilla - * Foundation ("Mozilla") nor the names of their contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE, MOZILLA AND THEIR CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE, MOZILLA OR - * THEIR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Revision 1 (March 4, 2004): - * Initial proposal. - * - * Revision 2 (March 10, 2004): - * All calls into script were made asynchronous. Results are - * provided via the NPScriptResultFunctionPtr callback. - * - * Revision 3 (March 10, 2004): - * Corrected comments to not refer to class retain/release FunctionPtrs. - * - * Revision 4 (March 11, 2004): - * Added additional convenience NPN_SetExceptionWithUTF8(). - * Changed NPHasPropertyFunctionPtr and NPHasMethodFunctionPtr to take NPClass - * pointers instead of NPObject pointers. - * Added NPIsValidIdentifier(). - * - * Revision 5 (March 17, 2004): - * Added context parameter to result callbacks from ScriptObject functions. - * - * Revision 6 (March 29, 2004): - * Renamed functions implemented by user agent to NPN_*. Removed _ from - * type names. - * Renamed "JavaScript" types to "Script". - * - * Revision 7 (April 21, 2004): - * NPIdentifier becomes a void*, was int32_t - * Remove NP_IsValidIdentifier, renamed NP_IdentifierFromUTF8 to NP_GetIdentifier - * Added NPVariant and modified functions to use this new type. - * - * Revision 8 (July 9, 2004): - * Updated to joint Apple-Mozilla license. - * - * Revision 9 (August 12, 2004): - * Changed NPVariantType enum values to form PVariantType_XXX - * Added NPP arguments to NPObject functions. - * Replaced NPVariant functions with macros. - */ -#ifndef _NP_RUNTIME_H_ -#define _NP_RUNTIME_H_ - - -// BEGIN GOOGLE MODIFICATIONS -#include "npapi.h" -#ifndef __native_client__ -typedef uint8 uint8_t; -typedef int8 int8_t; -typedef uint16 uint16_t; -typedef int16 int16_t; -typedef uint32 uint32_t; -typedef int32 int32_t; -typedef int64 int64_t; -typedef uint64 uint64_t; -#endif /* __native_client__ */ -// END GOOGLE MODIFICATIONS - - -#ifdef __cplusplus -extern "C" { -#endif - -/* - This API is used to facilitate binding code written in C to script - objects. The API in this header does not assume the presence of a - user agent. That is, it can be used to bind C code to scripting - environments outside of the context of a user agent. - - However, the normal use of the this API is in the context of a - scripting environment running in a browser or other user agent. - In particular it is used to support the extended Netscape - script-ability API for plugins (NP-SAP). NP-SAP is an extension - of the Netscape plugin API. As such we have adopted the use of - the "NP" prefix for this API. - - The following NP{N|P}Variables were added to the Netscape plugin - API (in npapi.h): - - NPNVWindowNPObject - NPNVPluginElementNPObject - NPPVpluginScriptableNPObject - - These variables are exposed through NPN_GetValue() and - NPP_GetValue() (respectively) and are used to establish the - initial binding between the user agent and native code. The DOM - objects in the user agent can be examined and manipulated using - the NPN_ functions that operate on NPObjects described in this - header. - - To the extent possible the assumptions about the scripting - language used by the scripting environment have been minimized. -*/ - - -/* - Objects (non-primitive data) passed between 'C' and script is - always wrapped in an NPObject. The 'interface' of an NPObject is - described by an NPClass. -*/ -typedef struct NPObject NPObject; -typedef struct NPClass NPClass; - -typedef char NPUTF8; -typedef struct _NPString { - const NPUTF8 *UTF8Characters; - uint32_t UTF8Length; -} NPString; - -typedef enum { - NPVariantType_Void, - NPVariantType_Null, - NPVariantType_Bool, - NPVariantType_Int32, - NPVariantType_Double, - NPVariantType_String, - NPVariantType_Object -} NPVariantType; - -typedef struct _NPVariant { - NPVariantType type; - union { - bool boolValue; - int32_t intValue; - double doubleValue; - NPString stringValue; - NPObject *objectValue; - } value; -} NPVariant; - -/* - NPN_ReleaseVariantValue is called on all 'out' parameters references. - Specifically it is called on variants that are resultant out parameters - in NPGetPropertyFunctionPtr and NPInvokeFunctionPtr. Resultant variants - from these two functions should be initialized using the - NPN_InitializeVariantXXX() functions. - - After calling NPReleaseVariantValue, the type of the variant will - be set to NPVariantUndefinedType. -*/ -void NPN_ReleaseVariantValue (NPVariant *variant); - -#define NPVARIANT_IS_VOID(_v) ((_v).type == NPVariantType_Void) -#define NPVARIANT_IS_NULL(_v) ((_v).type == NPVariantType_Null) -#define NPVARIANT_IS_BOOLEAN(_v) ((_v).type == NPVariantType_Bool) -#define NPVARIANT_IS_INT32(_v) ((_v).type == NPVariantType_Int32) -#define NPVARIANT_IS_DOUBLE(_v) ((_v).type == NPVariantType_Double) -#define NPVARIANT_IS_STRING(_v) ((_v).type == NPVariantType_String) -#define NPVARIANT_IS_OBJECT(_v) ((_v).type == NPVariantType_Object) - -#define NPVARIANT_TO_BOOLEAN(_v) ((_v).value.boolValue) -#define NPVARIANT_TO_INT32(_v) ((_v).value.intValue) -#define NPVARIANT_TO_DOUBLE(_v) ((_v).value.doubleValue) -#define NPVARIANT_TO_STRING(_v) ((_v).value.stringValue) -#define NPVARIANT_TO_OBJECT(_v) ((_v).value.objectValue) - -#define NP_BEGIN_MACRO do { -#define NP_END_MACRO } while (0) - -#define VOID_TO_NPVARIANT(_v) NP_BEGIN_MACRO (_v).type = NPVariantType_Void; (_v).value.objectValue = NULL; NP_END_MACRO -#define NULL_TO_NPVARIANT(_v) NP_BEGIN_MACRO (_v).type = NPVariantType_Null; (_v).value.objectValue = NULL; NP_END_MACRO -#define BOOLEAN_TO_NPVARIANT(_val, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_Bool; (_v).value.boolValue = !!(_val); NP_END_MACRO -#define INT32_TO_NPVARIANT(_val, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_Int32; (_v).value.intValue = _val; NP_END_MACRO -#define DOUBLE_TO_NPVARIANT(_val, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_Double; (_v).value.doubleValue = _val; NP_END_MACRO -#define STRINGZ_TO_NPVARIANT(_val, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_String; NPString str = { _val, strlen(_val) }; (_v).value.stringValue = str; NP_END_MACRO -#define STRINGN_TO_NPVARIANT(_val, _len, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_String; NPString str = { _val, _len }; (_v).value.stringValue = str; NP_END_MACRO -#define OBJECT_TO_NPVARIANT(_val, _v) NP_BEGIN_MACRO (_v).type = NPVariantType_Object; (_v).value.objectValue = _val; NP_END_MACRO - -/* - Type mappings (JavaScript types have been used for illustration - purposes): - - JavaScript to C (NPVariant with type:) - undefined NPVariantType_Void - null NPVariantType_Null - Boolean NPVariantType_Bool - Number NPVariantType_Double or NPVariantType_Int32 - String NPVariantType_String - Object NPVariantType_Object - - C (NPVariant with type:) to JavaScript - NPVariantType_Void undefined - NPVariantType_Null null - NPVariantType_Bool Boolean - NPVariantType_Int32 Number - NPVariantType_Double Number - NPVariantType_String String - NPVariantType_Object Object -*/ - -typedef void *NPIdentifier; - -/* - NPObjects have methods and properties. Methods and properties are - identified with NPIdentifiers. These identifiers may be reflected - in script. NPIdentifiers can be either strings or integers, IOW, - methods and properties can be identified by either strings or - integers (i.e. foo["bar"] vs foo[1]). NPIdentifiers can be - compared using ==. In case of any errors, the requested - NPIdentifier(s) will be NULL. -*/ -NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name); -void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers); -NPIdentifier NPN_GetIntIdentifier(int32_t intid); -bool NPN_IdentifierIsString(NPIdentifier identifier); - -/* - The NPUTF8 returned from NPN_UTF8FromIdentifier SHOULD be freed. -*/ -NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier); - -/* - Get the integer represented by identifier. If identifier is not an - integer identifier, the behaviour is undefined. -*/ -int32_t NPN_IntFromIdentifier(NPIdentifier identifier); - -/* - NPObject behavior is implemented using the following set of - callback functions. - - The NPVariant *result argument of these functions (where - applicable) should be released using NPN_ReleaseVariantValue(). -*/ -typedef NPObject *(*NPAllocateFunctionPtr)(NPP npp, NPClass *aClass); -typedef void (*NPDeallocateFunctionPtr)(NPObject *obj); -typedef void (*NPInvalidateFunctionPtr)(NPObject *obj); -typedef bool (*NPHasMethodFunctionPtr)(NPObject *obj, NPIdentifier name); -typedef bool (*NPInvokeFunctionPtr)(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); -typedef bool (*NPInvokeDefaultFunctionPtr)(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); -typedef bool (*NPHasPropertyFunctionPtr)(NPObject *obj, NPIdentifier name); -typedef bool (*NPGetPropertyFunctionPtr)(NPObject *obj, NPIdentifier name, NPVariant *result); -typedef bool (*NPSetPropertyFunctionPtr)(NPObject *obj, NPIdentifier name, const NPVariant *value); -typedef bool (*NPRemovePropertyFunctionPtr)(NPObject *npobj, NPIdentifier name); -typedef bool (*NPEnumerationFunctionPtr)(NPObject *npobj, NPIdentifier **value, uint32_t *count); -typedef bool (*NPConstructFunctionPtr)(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); - -/* - NPObjects returned by create have a reference count of one. It is the caller's responsibility - to release the returned object. - - NPInvokeFunctionPtr function may return false to indicate a the method could not be invoked. - - NPGetPropertyFunctionPtr and NPSetPropertyFunctionPtr may return false to indicate a property doesn't - exist. - - NPInvalidateFunctionPtr is called by the scripting environment when the native code is - shutdown. Any attempt to message a NPObject instance after the invalidate - callback has been called will result in undefined behavior, even if the - native code is still retaining those NPObject instances. - (The runtime will typically return immediately, with 0 or NULL, from an attempt to - dispatch to a NPObject, but this behavior should not be depended upon.) - - The NPEnumerationFunctionPtr function may pass an array of - NPIdentifiers back to the caller. The callee allocs the memory of - the array using NPN_MemAlloc(), and it's the caller's responsibility - to release it using NPN_MemFree(). -*/ -struct NPClass -{ - uint32_t structVersion; - NPAllocateFunctionPtr allocate; - NPDeallocateFunctionPtr deallocate; - NPInvalidateFunctionPtr invalidate; - NPHasMethodFunctionPtr hasMethod; - NPInvokeFunctionPtr invoke; - NPInvokeDefaultFunctionPtr invokeDefault; - NPHasPropertyFunctionPtr hasProperty; - NPGetPropertyFunctionPtr getProperty; - NPSetPropertyFunctionPtr setProperty; - NPRemovePropertyFunctionPtr removeProperty; - NPEnumerationFunctionPtr enumerate; - NPConstructFunctionPtr construct; -}; - -#define NP_CLASS_STRUCT_VERSION 3 -#define NP_CLASS_STRUCT_VERSION_ENUM 2 -#define NP_CLASS_STRUCT_VERSION_CTOR 3 - -#define NP_CLASS_STRUCT_VERSION_HAS_ENUM(npclass) \ - ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_ENUM) -#define NP_CLASS_STRUCT_VERSION_HAS_CTOR(npclass) \ - ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_CTOR) - -struct NPObject { - NPClass *_class; - uint32_t referenceCount; - // Additional space may be allocated here by types of NPObjects -}; - -/* - If the class has an allocate function, NPN_CreateObject invokes that function, - otherwise a NPObject is allocated and returned. If a class has an allocate - function it is the responsibility of that implementation to set the initial retain - count to 1. -*/ -NPObject *NPN_CreateObject(NPP npp, NPClass *aClass); - -/* - Increment the NPObject's reference count. -*/ -NPObject *NPN_RetainObject (NPObject *obj); - -/* - Decremented the NPObject's reference count. If the reference - count goes to zero, the class's destroy function is invoke if - specified, otherwise the object is freed directly. -*/ -void NPN_ReleaseObject (NPObject *obj); - -/* - Functions to access script objects represented by NPObject. - - Calls to script objects are synchronous. If a function returns a - value, it will be supplied via the result NPVariant - argument. Successful calls will return true, false will be - returned in case of an error. - - Calls made from plugin code to script must be made from the thread - on which the plugin was initialized. -*/ -bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); -bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); -bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script, NPVariant *result); -bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName, NPVariant *result); -bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName, const NPVariant *value); -bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName); -bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName); -bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName); -bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier, uint32_t *count); -bool NPN_Construct(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result); - -// Helper function for evaluating a script in the scope of the NPObject passed in. -// Parameters -// npp -// The plugin's opaque instance handle (Can be NULL) -// popups_allowed -// Indicates if popups created in the context of the script being executed are -// blocked or not. -// npobj -// The NPObject. -// npscript -// The script being executed. -// result -// On return contains the value returned by the script. -// Returns true on success. -bool NPN_EvaluateHelper(NPP npp, bool popups_allowed, NPObject* npobj, - NPString* npscript, NPVariant *result); - -// BEGIN GOOGLE MODIFICATIONS - -void* NPP_GetJavaClass(void); -void* NPN_GetJavaEnv(void); -void* NPN_GetJavaPeer(NPP instance); -void NPN_PluginThreadAsyncCall(NPP id, void (*func)(void *), void *userData); - -// END GOOGLE MODIFICATIONS - -/* - NPN_SetException may be called to trigger a script exception upon return - from entry points into NPObjects. -*/ -void NPN_SetException (NPObject *obj, const NPUTF8 *message); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/omaha/third_party/smartany/scoped_any.h b/omaha/third_party/smartany/scoped_any.h index ab89feef0..c805b4670 100644 --- a/omaha/third_party/smartany/scoped_any.h +++ b/omaha/third_party/smartany/scoped_any.h @@ -118,7 +118,7 @@ class scoped_any { static detail::smartany_static_assert::value> const cannot_dereference_a_handle; assert( valid() ); - return smart_types::to_reference( m_t ); + return safe_types::to_reference( m_t ); } #endif diff --git a/omaha/tools/goopdump/build.scons b/omaha/tools/goopdump/build.scons index 4ebcb3864..0cdb660f2 100644 --- a/omaha/tools/goopdump/build.scons +++ b/omaha/tools/goopdump/build.scons @@ -33,7 +33,6 @@ lib_inputs = [ 'data_dumper_app_manager.cc', 'data_dumper_goopdate.cc', 'data_dumper_network.cc', - 'data_dumper_oneclick.cc', 'data_dumper_osdata.cc', 'dump_log.cc', 'goopdump.cc', diff --git a/omaha/tools/goopdump/data_dumper_oneclick.cc b/omaha/tools/goopdump/data_dumper_oneclick.cc deleted file mode 100644 index 0af6a5cd7..000000000 --- a/omaha/tools/goopdump/data_dumper_oneclick.cc +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/tools/goopdump/data_dumper_oneclick.h" - -#include "omaha/common/reg_key.h" -#include "omaha/tools/goopdump/dump_log.h" -#include "omaha/tools/goopdump/goopdump_cmd_line_parser.h" - -namespace omaha { - -DataDumperOneClick::DataDumperOneClick() { -} - -DataDumperOneClick::~DataDumperOneClick() { -} - -void DataDumperOneClick::DumpOneClickDataForVersion(const DumpLog& dump_log, - int plugin_version) { - - dump_log.WriteLine(_T("Trying Plugin Version: %d"), plugin_version); - - CString oneclick_name; - oneclick_name.Format(_T("Google.OneClickCtrl.%d"), plugin_version); - - CString reg_str; - reg_str.Format(_T("HKCR\\%s"), oneclick_name); - DumpRegValueStr(dump_log, reg_str, NULL); - - CString clsid; - reg_str.Append(_T("\\CLSID")); - DumpRegValueStrRet(dump_log, reg_str, NULL, &clsid); - - reg_str.Format(_T("HKCR\\MIME\\DataBase\\Content Type\\application/%s"), - oneclick_name); - DumpRegValueStr(dump_log, reg_str, _T("CLSID")); - - CString key; - key.Format(_T("HKCR\\CLSID\\%s"), clsid); - - if (!clsid.IsEmpty()) { - DumpRegistryKeyData(dump_log, key); - } - - CString typelib; - CString key2 = key; - key2.Append(_T("\\TypeLib")); - if (SUCCEEDED(RegKey::GetValue(key2, NULL, &typelib))) { - if (!typelib.IsEmpty()) { - key.Format(_T("HKCR\\Typelib\\%s\\1.0\\0\\win32"), typelib); - DumpRegistryKeyData(dump_log, key); - } - } - - dump_log.WriteLine(_T("")); -} - -HRESULT DataDumperOneClick::Process(const DumpLog& dump_log, - const GoopdumpCmdLineArgs& args) { - UNREFERENCED_PARAMETER(args); - - DumpHeader header(dump_log, _T("OneClick Data")); - - CString activex_version_str(ACTIVEX_VERSION_ANSI); - int activex_version = _ttoi(activex_version_str); - - for (int i = 1; i <= activex_version; ++i) { - DumpOneClickDataForVersion(dump_log, i); - } - - return S_OK; -} - -} // namespace omaha - diff --git a/omaha/tools/goopdump/goopdump_cmd_line_parser.cc b/omaha/tools/goopdump/goopdump_cmd_line_parser.cc index 12048d596..fe8988f47 100644 --- a/omaha/tools/goopdump/goopdump_cmd_line_parser.cc +++ b/omaha/tools/goopdump/goopdump_cmd_line_parser.cc @@ -38,7 +38,6 @@ HRESULT ParseGoopdumpCmdLine(int argc, std::vector valid_params; valid_params.push_back(_T("dumpapps")); - valid_params.push_back(_T("oneclick")); valid_params.push_back(_T("monitor")); valid_params.push_back(_T("file")); @@ -72,7 +71,6 @@ HRESULT ParseGoopdumpCmdLine(int argc, // If you don't pass anything, give them everything except monitoring. args->is_dump_general = true; args->is_dump_app_manager = true; - args->is_dump_oneclick = true; args->is_machine = true; args->is_user = true; } @@ -84,13 +82,6 @@ HRESULT ParseGoopdumpCmdLine(int argc, args->is_user = true; } - if (parser.HasSwitch(_T("oneclick"))) { - args->is_dump_general = true; - args->is_dump_oneclick = true; - args->is_machine = true; - args->is_user = true; - } - if (parser.HasSwitch(_T("monitor"))) { args->is_monitor = true; } diff --git a/omaha/tools/goopdump/goopdump_cmd_line_parser.h b/omaha/tools/goopdump/goopdump_cmd_line_parser.h index 96105061a..95cb581b9 100644 --- a/omaha/tools/goopdump/goopdump_cmd_line_parser.h +++ b/omaha/tools/goopdump/goopdump_cmd_line_parser.h @@ -29,14 +29,12 @@ struct GoopdumpCmdLineArgs { is_user(false), is_monitor(false), is_dump_app_manager(false), - is_dump_oneclick(false), is_dump_general(false), is_write_to_file(false) {} bool is_machine; // Display per-machine data. bool is_user; // Display per-user data (for current user only). bool is_monitor; // Is monitor mode (monitors real time activity). bool is_dump_app_manager; // Dump AppManager data. - bool is_dump_oneclick; // Dump OneClick data. bool is_dump_general; // Dump general OS and Omaha data. bool is_write_to_file; // Dump data to file. CString log_filename; // Filename of log to write to.