Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / installer / gcapi / gcapi.cc
blobae22fa811d3b628cd2910475a5f52ba0b4138d23
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // NOTE: This code is a legacy utility API for partners to check whether
6 // Chrome can be installed and launched. Recent updates are being made
7 // to add new functionality. These updates use code from Chromium, the old
8 // coded against the win32 api directly. If you have an itch to shave a
9 // yak, feel free to re-write the old code too.
11 #include "chrome/installer/gcapi/gcapi.h"
13 #include <sddl.h>
14 #define STRSAFE_NO_DEPRECATE
15 #include <windows.h>
16 #include <strsafe.h>
17 #include <tlhelp32.h>
19 #include <cstdlib>
20 #include <iterator>
21 #include <limits>
22 #include <set>
23 #include <string>
25 #include "base/basictypes.h"
26 #include "base/command_line.h"
27 #include "base/files/file_path.h"
28 #include "base/process/launch.h"
29 #include "base/strings/string16.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/string_util.h"
32 #include "base/time/time.h"
33 #include "base/win/registry.h"
34 #include "base/win/scoped_com_initializer.h"
35 #include "base/win/scoped_comptr.h"
36 #include "base/win/scoped_handle.h"
37 #include "chrome/installer/gcapi/gcapi_omaha_experiment.h"
38 #include "chrome/installer/gcapi/gcapi_reactivation.h"
39 #include "chrome/installer/launcher_support/chrome_launcher_support.h"
40 #include "chrome/installer/util/google_update_constants.h"
41 #include "chrome/installer/util/google_update_settings.h"
42 #include "chrome/installer/util/util_constants.h"
43 #include "chrome/installer/util/wmi.h"
44 #include "google_update/google_update_idl.h"
46 using base::Time;
47 using base::TimeDelta;
48 using base::win::RegKey;
49 using base::win::ScopedCOMInitializer;
50 using base::win::ScopedComPtr;
51 using base::win::ScopedHandle;
53 namespace {
55 const wchar_t kChromeRegClientsKey[] =
56 L"Software\\Google\\Update\\Clients\\"
57 L"{8A69D345-D564-463c-AFF1-A69D9E530F96}";
58 const wchar_t kChromeRegClientStateKey[] =
59 L"Software\\Google\\Update\\ClientState\\"
60 L"{8A69D345-D564-463c-AFF1-A69D9E530F96}";
62 const wchar_t kGCAPITempKey[] = L"Software\\Google\\GCAPITemp";
64 const wchar_t kChromeRegVersion[] = L"pv";
65 const wchar_t kNoChromeOfferUntil[] =
66 L"SOFTWARE\\Google\\No Chrome Offer Until";
68 const wchar_t kC1FPendingKey[] =
69 L"Software\\Google\\Common\\Rlz\\Events\\C";
70 const wchar_t kC1FSentKey[] =
71 L"Software\\Google\\Common\\Rlz\\StatefulEvents\\C";
72 const wchar_t kC1FKey[] = L"C1F";
74 const wchar_t kRelaunchBrandcodeValue[] = L"RelaunchBrandcode";
75 const wchar_t kRelaunchAllowedAfterValue[] = L"RelaunchAllowedAfter";
77 // Prefix used to match the window class for Chrome windows.
78 const wchar_t kChromeWindowClassPrefix[] = L"Chrome_WidgetWin_";
80 // Return the company name specified in the file version info resource.
81 bool GetCompanyName(const wchar_t* filename, wchar_t* buffer, DWORD out_len) {
82 wchar_t file_version_info[8192];
83 DWORD handle = 0;
84 DWORD buffer_size = 0;
86 buffer_size = ::GetFileVersionInfoSize(filename, &handle);
87 // Cannot stats the file or our buffer size is too small (very unlikely).
88 if (buffer_size == 0 || buffer_size > _countof(file_version_info))
89 return false;
91 buffer_size = _countof(file_version_info);
92 memset(file_version_info, 0, buffer_size);
93 if (!::GetFileVersionInfo(filename, handle, buffer_size, file_version_info))
94 return false;
96 DWORD data_len = 0;
97 LPVOID data = NULL;
98 // Retrieve the language and codepage code if exists.
99 buffer_size = 0;
100 if (!::VerQueryValue(file_version_info, TEXT("\\VarFileInfo\\Translation"),
101 reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len)))
102 return false;
103 if (data_len != 4)
104 return false;
106 wchar_t info_name[256];
107 DWORD lang = 0;
108 // Formulate the string to retrieve the company name of the specific
109 // language codepage.
110 memcpy(&lang, data, 4);
111 ::StringCchPrintf(info_name, _countof(info_name),
112 L"\\StringFileInfo\\%02X%02X%02X%02X\\CompanyName",
113 (lang & 0xff00)>>8, (lang & 0xff), (lang & 0xff000000)>>24,
114 (lang & 0xff0000)>>16);
116 data_len = 0;
117 if (!::VerQueryValue(file_version_info, info_name,
118 reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len)))
119 return false;
120 if (data_len <= 0 || data_len >= (out_len / sizeof(wchar_t)))
121 return false;
123 memset(buffer, 0, out_len);
124 ::StringCchCopyN(buffer,
125 (out_len / sizeof(wchar_t)),
126 reinterpret_cast<const wchar_t*>(data),
127 data_len);
128 return true;
131 // Offsets the current date by |months|. |months| must be between 0 and 12.
132 // The returned date is in the YYYYMMDD format.
133 DWORD FormatDateOffsetByMonths(int months) {
134 DCHECK(months >= 0 && months <= 12);
136 SYSTEMTIME now;
137 GetLocalTime(&now);
138 now.wMonth += months;
139 if (now.wMonth > 12) {
140 now.wMonth -= 12;
141 now.wYear += 1;
144 return now.wYear * 10000 + now.wMonth * 100 + now.wDay;
147 // Return true if we can re-offer Chrome; false, otherwise.
148 // Each partner can only offer Chrome once every six months.
149 bool CanReOfferChrome(BOOL set_flag) {
150 wchar_t filename[MAX_PATH+1];
151 wchar_t company[MAX_PATH];
153 // If we cannot retrieve the version info of the executable or company
154 // name, we allow the Chrome to be offered because there is no past
155 // history to be found.
156 if (::GetModuleFileName(NULL, filename, MAX_PATH) == 0)
157 return true;
158 if (!GetCompanyName(filename, company, sizeof(company)))
159 return true;
161 bool can_re_offer = true;
162 DWORD disposition = 0;
163 HKEY key = NULL;
164 if (::RegCreateKeyEx(HKEY_LOCAL_MACHINE, kNoChromeOfferUntil,
165 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE,
166 NULL, &key, &disposition) == ERROR_SUCCESS) {
167 // Get today's date, and format it as YYYYMMDD numeric value.
168 DWORD today = FormatDateOffsetByMonths(0);
170 // Cannot re-offer, if the timer already exists and is not expired yet.
171 DWORD value_type = REG_DWORD;
172 DWORD value_data = 0;
173 DWORD value_length = sizeof(DWORD);
174 if (::RegQueryValueEx(key, company, 0, &value_type,
175 reinterpret_cast<LPBYTE>(&value_data),
176 &value_length) == ERROR_SUCCESS &&
177 REG_DWORD == value_type &&
178 value_data > today) {
179 // The time has not expired, we cannot offer Chrome.
180 can_re_offer = false;
181 } else {
182 // Delete the old or invalid value.
183 ::RegDeleteValue(key, company);
184 if (set_flag) {
185 // Set expiration date for offer as six months from today,
186 // represented as a YYYYMMDD numeric value.
187 DWORD value = FormatDateOffsetByMonths(6);
188 ::RegSetValueEx(key, company, 0, REG_DWORD, (LPBYTE)&value,
189 sizeof(DWORD));
193 ::RegCloseKey(key);
196 return can_re_offer;
199 bool IsChromeInstalled(HKEY root_key) {
200 RegKey key;
201 return key.Open(root_key,
202 kChromeRegClientsKey,
203 KEY_READ | KEY_WOW64_32KEY) == ERROR_SUCCESS &&
204 key.HasValue(kChromeRegVersion);
207 // Returns true if the |subkey| in |root| has the kC1FKey entry set to 1.
208 bool RegKeyHasC1F(HKEY root, const wchar_t* subkey) {
209 RegKey key;
210 DWORD value;
211 return key.Open(root, subkey, KEY_READ | KEY_WOW64_32KEY) == ERROR_SUCCESS &&
212 key.ReadValueDW(kC1FKey, &value) == ERROR_SUCCESS &&
213 value == static_cast<DWORD>(1);
216 bool IsC1FSent() {
217 // The C1F RLZ key can either be in HKCU or in HKLM (the HKLM RLZ key is made
218 // readable to all-users via rlz_lib::CreateMachineState()) and can either be
219 // in sent or pending state. Return true if there is a match for any of these
220 // 4 states.
221 return RegKeyHasC1F(HKEY_CURRENT_USER, kC1FSentKey) ||
222 RegKeyHasC1F(HKEY_CURRENT_USER, kC1FPendingKey) ||
223 RegKeyHasC1F(HKEY_LOCAL_MACHINE, kC1FSentKey) ||
224 RegKeyHasC1F(HKEY_LOCAL_MACHINE, kC1FPendingKey);
227 enum WindowsVersion {
228 VERSION_BELOW_XP_SP2,
229 VERSION_XP_SP2_UP_TO_VISTA, // "but not including"
230 VERSION_VISTA_OR_HIGHER,
232 WindowsVersion GetWindowsVersion() {
233 OSVERSIONINFOEX version_info = { sizeof version_info };
234 GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));
236 // Windows Vista is version 6.0.
237 if (version_info.dwMajorVersion >= 6)
238 return VERSION_VISTA_OR_HIGHER;
240 // Windows XP is version 5.1. (5.2 is Windows Server 2003/XP Pro x64.)
241 if ((version_info.dwMajorVersion < 5) || (version_info.dwMinorVersion < 1))
242 return VERSION_BELOW_XP_SP2;
244 // For XP itself, we only support SP2 and above.
245 return ((version_info.dwMinorVersion > 1) ||
246 (version_info.wServicePackMajor >= 2)) ?
247 VERSION_XP_SP2_UP_TO_VISTA : VERSION_BELOW_XP_SP2;
250 // Note this function should not be called on old Windows versions where these
251 // Windows API are not available. We always invoke this function after checking
252 // that current OS is Vista or later.
253 bool VerifyAdminGroup() {
254 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
255 PSID Group;
256 BOOL check = ::AllocateAndInitializeSid(&NtAuthority, 2,
257 SECURITY_BUILTIN_DOMAIN_RID,
258 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0,
259 0, 0, 0,
260 &Group);
261 if (check) {
262 if (!::CheckTokenMembership(NULL, Group, &check))
263 check = FALSE;
265 ::FreeSid(Group);
266 return (check == TRUE);
269 bool VerifyHKLMAccess() {
270 wchar_t str[] = L"test";
271 bool result = false;
272 DWORD disposition = 0;
273 HKEY key = NULL;
275 if (::RegCreateKeyEx(HKEY_LOCAL_MACHINE, kGCAPITempKey, 0, NULL,
276 REG_OPTION_NON_VOLATILE,
277 KEY_READ | KEY_WRITE | KEY_WOW64_32KEY, NULL,
278 &key, &disposition) == ERROR_SUCCESS) {
279 if (::RegSetValueEx(key, str, 0, REG_SZ, (LPBYTE)str,
280 (DWORD)lstrlen(str)) == ERROR_SUCCESS) {
281 result = true;
282 RegDeleteValue(key, str);
285 RegCloseKey(key);
287 // If we create the main key, delete the entire key.
288 if (disposition == REG_CREATED_NEW_KEY)
289 RegDeleteKey(HKEY_LOCAL_MACHINE, kGCAPITempKey);
292 return result;
295 bool IsRunningElevated() {
296 // This method should be called only for Vista or later.
297 if ((GetWindowsVersion() < VERSION_VISTA_OR_HIGHER) ||
298 !VerifyAdminGroup())
299 return false;
301 HANDLE process_token;
302 if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token))
303 return false;
305 TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
306 DWORD size_returned = 0;
307 if (!::GetTokenInformation(process_token, TokenElevationType,
308 &elevation_type, sizeof(elevation_type),
309 &size_returned)) {
310 ::CloseHandle(process_token);
311 return false;
314 ::CloseHandle(process_token);
315 return (elevation_type == TokenElevationTypeFull);
318 bool GetUserIdForProcess(size_t pid, wchar_t** user_sid) {
319 HANDLE process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid);
320 if (process_handle == NULL)
321 return false;
323 HANDLE process_token;
324 bool result = false;
325 if (::OpenProcessToken(process_handle, TOKEN_QUERY, &process_token)) {
326 DWORD size = 0;
327 ::GetTokenInformation(process_token, TokenUser, NULL, 0, &size);
328 if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
329 ::GetLastError() == ERROR_SUCCESS) {
330 DWORD actual_size = 0;
331 BYTE* token_user = new BYTE[size];
332 if ((::GetTokenInformation(process_token, TokenUser, token_user, size,
333 &actual_size)) &&
334 (actual_size <= size)) {
335 PSID sid = reinterpret_cast<TOKEN_USER*>(token_user)->User.Sid;
336 if (::ConvertSidToStringSid(sid, user_sid))
337 result = true;
339 delete[] token_user;
341 ::CloseHandle(process_token);
343 ::CloseHandle(process_handle);
344 return result;
347 struct SetWindowPosParams {
348 int x;
349 int y;
350 int width;
351 int height;
352 DWORD flags;
353 HWND window_insert_after;
354 bool success;
355 std::set<HWND> shunted_hwnds;
358 BOOL CALLBACK ChromeWindowEnumProc(HWND hwnd, LPARAM lparam) {
359 wchar_t window_class[MAX_PATH] = {};
360 SetWindowPosParams* params = reinterpret_cast<SetWindowPosParams*>(lparam);
362 if (!params->shunted_hwnds.count(hwnd) &&
363 ::GetClassName(hwnd, window_class, arraysize(window_class)) &&
364 base::StartsWith(window_class, kChromeWindowClassPrefix,
365 base::CompareCase::INSENSITIVE_ASCII) &&
366 ::SetWindowPos(hwnd, params->window_insert_after, params->x, params->y,
367 params->width, params->height, params->flags)) {
368 params->shunted_hwnds.insert(hwnd);
369 params->success = true;
372 // Return TRUE to ensure we hit all possible top-level Chrome windows as per
373 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms633498.aspx
374 return TRUE;
377 // Returns true and populates |chrome_exe_path| with the path to chrome.exe if
378 // a valid installation can be found.
379 bool GetGoogleChromePath(base::FilePath* chrome_exe_path) {
380 HKEY install_key = HKEY_LOCAL_MACHINE;
381 if (!IsChromeInstalled(install_key)) {
382 install_key = HKEY_CURRENT_USER;
383 if (!IsChromeInstalled(install_key)) {
384 return false;
388 // Now grab the uninstall string from the appropriate ClientState key
389 // and use that as the base for a path to chrome.exe.
390 *chrome_exe_path = chrome_launcher_support::GetChromePathForInstallationLevel(
391 install_key == HKEY_LOCAL_MACHINE
392 ? chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION
393 : chrome_launcher_support::USER_LEVEL_INSTALLATION,
394 false /* is_sxs */);
395 return !chrome_exe_path->empty();
398 } // namespace
400 BOOL __stdcall GoogleChromeCompatibilityCheck(BOOL set_flag,
401 int shell_mode,
402 DWORD* reasons) {
403 DWORD local_reasons = 0;
405 WindowsVersion windows_version = GetWindowsVersion();
406 // System requirements?
407 if (windows_version == VERSION_BELOW_XP_SP2)
408 local_reasons |= GCCC_ERROR_OSNOTSUPPORTED;
410 if (IsChromeInstalled(HKEY_LOCAL_MACHINE))
411 local_reasons |= GCCC_ERROR_SYSTEMLEVELALREADYPRESENT;
413 if (IsChromeInstalled(HKEY_CURRENT_USER))
414 local_reasons |= GCCC_ERROR_USERLEVELALREADYPRESENT;
416 if (shell_mode == GCAPI_INVOKED_UAC_ELEVATION) {
417 // Only check that we have HKLM write permissions if we specify that
418 // GCAPI is being invoked from an elevated shell, or in admin mode
419 if (!VerifyHKLMAccess()) {
420 local_reasons |= GCCC_ERROR_ACCESSDENIED;
421 } else if ((windows_version == VERSION_VISTA_OR_HIGHER) &&
422 !VerifyAdminGroup()) {
423 // For Vista or later check for elevation since even for admin user we could
424 // be running in non-elevated mode. We require integrity level High.
425 local_reasons |= GCCC_ERROR_INTEGRITYLEVEL;
429 // Then only check whether we can re-offer, if everything else is OK.
430 if (local_reasons == 0 && !CanReOfferChrome(set_flag))
431 local_reasons |= GCCC_ERROR_ALREADYOFFERED;
433 // Done. Copy/return results.
434 if (reasons != NULL)
435 *reasons = local_reasons;
437 return (local_reasons == 0);
440 BOOL __stdcall LaunchGoogleChrome() {
441 base::FilePath chrome_exe_path;
442 if (!GetGoogleChromePath(&chrome_exe_path))
443 return false;
445 ScopedCOMInitializer com_initializer;
446 if (::CoInitializeSecurity(NULL, -1, NULL, NULL,
447 RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
448 RPC_C_IMP_LEVEL_IDENTIFY, NULL,
449 EOAC_DYNAMIC_CLOAKING, NULL) != S_OK) {
450 return false;
453 bool impersonation_success = false;
454 if (IsRunningElevated()) {
455 wchar_t* curr_proc_sid;
456 if (!GetUserIdForProcess(GetCurrentProcessId(), &curr_proc_sid)) {
457 return false;
460 DWORD pid = 0;
461 ::GetWindowThreadProcessId(::GetShellWindow(), &pid);
462 if (pid <= 0) {
463 ::LocalFree(curr_proc_sid);
464 return false;
467 wchar_t* exp_proc_sid;
468 if (GetUserIdForProcess(pid, &exp_proc_sid)) {
469 if (_wcsicmp(curr_proc_sid, exp_proc_sid) == 0) {
470 ScopedHandle process_handle(
471 ::OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION,
472 TRUE,
473 pid));
474 if (process_handle.IsValid()) {
475 HANDLE process_token = NULL;
476 HANDLE user_token = NULL;
477 if (::OpenProcessToken(process_handle.Get(),
478 TOKEN_DUPLICATE | TOKEN_QUERY,
479 &process_token) &&
480 ::DuplicateTokenEx(process_token,
481 TOKEN_IMPERSONATE | TOKEN_QUERY |
482 TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE,
483 NULL, SecurityImpersonation,
484 TokenPrimary, &user_token) &&
485 (::ImpersonateLoggedOnUser(user_token) != 0)) {
486 impersonation_success = true;
488 if (user_token)
489 ::CloseHandle(user_token);
490 if (process_token)
491 ::CloseHandle(process_token);
494 ::LocalFree(exp_proc_sid);
497 ::LocalFree(curr_proc_sid);
498 if (!impersonation_success) {
499 return false;
503 base::CommandLine chrome_command(chrome_exe_path);
505 bool ret = false;
506 ScopedComPtr<IProcessLauncher> ipl;
507 if (SUCCEEDED(ipl.CreateInstance(__uuidof(ProcessLauncherClass),
508 NULL,
509 CLSCTX_LOCAL_SERVER))) {
510 if (SUCCEEDED(ipl->LaunchCmdLine(
511 chrome_command.GetCommandLineString().c_str())))
512 ret = true;
513 ipl.Release();
514 } else {
515 // Couldn't get Omaha's process launcher, Omaha may not be installed at
516 // system level. Try just running Chrome instead.
517 ret = base::LaunchProcess(chrome_command.GetCommandLineString(),
518 base::LaunchOptions()).IsValid();
521 if (impersonation_success)
522 ::RevertToSelf();
523 return ret;
526 BOOL __stdcall LaunchGoogleChromeWithDimensions(int x,
527 int y,
528 int width,
529 int height,
530 bool in_background) {
531 if (in_background) {
532 base::FilePath chrome_exe_path;
533 if (!GetGoogleChromePath(&chrome_exe_path))
534 return false;
536 // When launching in the background, use WMI to ensure that chrome.exe is
537 // is not our child process. This prevents it from pushing itself to
538 // foreground.
539 base::CommandLine chrome_command(chrome_exe_path);
541 ScopedCOMInitializer com_initializer;
542 if (!installer::WMIProcess::Launch(chrome_command.GetCommandLineString(),
543 NULL)) {
544 // For some reason WMI failed. Try and launch the old fashioned way,
545 // knowing that visual glitches will occur when the window pops up.
546 if (!LaunchGoogleChrome())
547 return false;
550 } else {
551 if (!LaunchGoogleChrome())
552 return false;
555 HWND hwnd_insert_after = in_background ? HWND_BOTTOM : NULL;
556 DWORD set_window_flags = in_background ? SWP_NOACTIVATE : SWP_NOZORDER;
558 if (x == -1 && y == -1)
559 set_window_flags |= SWP_NOMOVE;
561 if (width == -1 && height == -1)
562 set_window_flags |= SWP_NOSIZE;
564 SetWindowPosParams enum_params = { x, y, width, height, set_window_flags,
565 hwnd_insert_after, false };
567 // Chrome may have been launched, but the window may not have appeared
568 // yet. Wait for it to appear for 10 seconds, but exit if it takes longer
569 // than that.
570 int ms_elapsed = 0;
571 int timeout = 10000;
572 bool found_window = false;
573 while (ms_elapsed < timeout) {
574 // Enum all top-level windows looking for Chrome windows.
575 ::EnumWindows(ChromeWindowEnumProc, reinterpret_cast<LPARAM>(&enum_params));
577 // Give it five more seconds after finding the first window until we stop
578 // shoving new windows into the background.
579 if (!found_window && enum_params.success) {
580 found_window = true;
581 timeout = ms_elapsed + 5000;
584 Sleep(10);
585 ms_elapsed += 10;
588 return found_window;
591 BOOL __stdcall LaunchGoogleChromeInBackground() {
592 return LaunchGoogleChromeWithDimensions(-1, -1, -1, -1, true);
595 int __stdcall GoogleChromeDaysSinceLastRun() {
596 int days_since_last_run = std::numeric_limits<int>::max();
598 if (IsChromeInstalled(HKEY_LOCAL_MACHINE) ||
599 IsChromeInstalled(HKEY_CURRENT_USER)) {
600 RegKey client_state(HKEY_CURRENT_USER,
601 kChromeRegClientStateKey,
602 KEY_QUERY_VALUE | KEY_WOW64_32KEY);
603 if (client_state.Valid()) {
604 base::string16 last_run;
605 int64 last_run_value = 0;
606 if (client_state.ReadValue(google_update::kRegLastRunTimeField,
607 &last_run) == ERROR_SUCCESS &&
608 base::StringToInt64(last_run, &last_run_value)) {
609 Time last_run_time = Time::FromInternalValue(last_run_value);
610 TimeDelta difference = Time::NowFromSystemTime() - last_run_time;
612 // We can end up with negative numbers here, given changes in system
613 // clock time or due to TimeDelta's int64 -> int truncation.
614 int new_days_since_last_run = difference.InDays();
615 if (new_days_since_last_run >= 0 &&
616 new_days_since_last_run < days_since_last_run) {
617 days_since_last_run = new_days_since_last_run;
623 if (days_since_last_run == std::numeric_limits<int>::max()) {
624 days_since_last_run = -1;
627 return days_since_last_run;
630 BOOL __stdcall CanOfferReactivation(const wchar_t* brand_code,
631 int shell_mode,
632 DWORD* error_code) {
633 DCHECK(error_code);
635 if (!brand_code) {
636 if (error_code)
637 *error_code = REACTIVATE_ERROR_INVALID_INPUT;
638 return FALSE;
641 int days_since_last_run = GoogleChromeDaysSinceLastRun();
642 if (days_since_last_run >= 0 &&
643 days_since_last_run < kReactivationMinDaysDormant) {
644 if (error_code)
645 *error_code = REACTIVATE_ERROR_NOTDORMANT;
646 return FALSE;
649 // Only run the code below when this function is invoked from a standard,
650 // non-elevated cmd shell. This is because this section of code looks at
651 // values in HKEY_CURRENT_USER, and we only want to look at the logged-in
652 // user's HKCU, not the admin user's HKCU.
653 if (shell_mode == GCAPI_INVOKED_STANDARD_SHELL) {
654 if (!IsChromeInstalled(HKEY_LOCAL_MACHINE) &&
655 !IsChromeInstalled(HKEY_CURRENT_USER)) {
656 if (error_code)
657 *error_code = REACTIVATE_ERROR_NOTINSTALLED;
658 return FALSE;
661 if (HasBeenReactivated()) {
662 if (error_code)
663 *error_code = REACTIVATE_ERROR_ALREADY_REACTIVATED;
664 return FALSE;
668 return TRUE;
671 BOOL __stdcall ReactivateChrome(const wchar_t* brand_code,
672 int shell_mode,
673 DWORD* error_code) {
674 BOOL result = FALSE;
675 if (CanOfferReactivation(brand_code,
676 shell_mode,
677 error_code)) {
678 if (SetReactivationBrandCode(brand_code, shell_mode)) {
679 // Currently set this as a best-effort thing. We return TRUE if
680 // reactivation succeeded regardless of the experiment label result.
681 SetReactivationExperimentLabels(brand_code, shell_mode);
683 result = TRUE;
684 } else {
685 if (error_code)
686 *error_code = REACTIVATE_ERROR_REACTIVATION_FAILED;
690 return result;
693 BOOL __stdcall CanOfferRelaunch(const wchar_t** partner_brandcode_list,
694 int partner_brandcode_list_length,
695 int shell_mode,
696 DWORD* error_code) {
697 DCHECK(error_code);
699 if (!partner_brandcode_list || partner_brandcode_list_length <= 0) {
700 if (error_code)
701 *error_code = RELAUNCH_ERROR_INVALID_INPUT;
702 return FALSE;
705 // These conditions need to be satisfied for relaunch:
706 // a) Chrome should be installed;
707 if (!IsChromeInstalled(HKEY_LOCAL_MACHINE) &&
708 (shell_mode != GCAPI_INVOKED_STANDARD_SHELL ||
709 !IsChromeInstalled(HKEY_CURRENT_USER))) {
710 if (error_code)
711 *error_code = RELAUNCH_ERROR_NOTINSTALLED;
712 return FALSE;
715 // b) the installed brandcode should belong to that partner (in
716 // brandcode_list);
717 base::string16 installed_brandcode;
718 bool valid_brandcode = false;
719 if (GoogleUpdateSettings::GetBrand(&installed_brandcode)) {
720 for (int i = 0; i < partner_brandcode_list_length; ++i) {
721 if (!_wcsicmp(installed_brandcode.c_str(), partner_brandcode_list[i])) {
722 valid_brandcode = true;
723 break;
728 if (!valid_brandcode) {
729 if (error_code)
730 *error_code = RELAUNCH_ERROR_INVALID_PARTNER;
731 return FALSE;
734 // c) C1F ping should not have been sent;
735 if (IsC1FSent()) {
736 if (error_code)
737 *error_code = RELAUNCH_ERROR_PINGS_SENT;
738 return FALSE;
741 // d) a minimum period (30 days) must have passed since Chrome was last used;
742 int days_since_last_run = GoogleChromeDaysSinceLastRun();
743 if (days_since_last_run >= 0 &&
744 days_since_last_run < kRelaunchMinDaysDormant) {
745 if (error_code)
746 *error_code = RELAUNCH_ERROR_NOTDORMANT;
747 return FALSE;
750 // e) a minimum period (6 months) must have passed since the previous
751 // relaunch offer for the current user;
752 RegKey key;
753 DWORD min_relaunch_date;
754 if (key.Open(HKEY_CURRENT_USER,
755 kChromeRegClientStateKey,
756 KEY_QUERY_VALUE | KEY_WOW64_32KEY) == ERROR_SUCCESS &&
757 key.ReadValueDW(kRelaunchAllowedAfterValue,
758 &min_relaunch_date) == ERROR_SUCCESS &&
759 FormatDateOffsetByMonths(0) < min_relaunch_date) {
760 if (error_code)
761 *error_code = RELAUNCH_ERROR_ALREADY_RELAUNCHED;
762 return FALSE;
765 return TRUE;
768 BOOL __stdcall SetRelaunchOffered(const wchar_t** partner_brandcode_list,
769 int partner_brandcode_list_length,
770 const wchar_t* relaunch_brandcode,
771 int shell_mode,
772 DWORD* error_code) {
773 if (!CanOfferRelaunch(partner_brandcode_list, partner_brandcode_list_length,
774 shell_mode, error_code))
775 return FALSE;
777 // Store the relaunched brand code and the minimum date for relaunch (6 months
778 // from now), and set the Omaha experiment label.
779 RegKey key;
780 if (key.Create(HKEY_CURRENT_USER,
781 kChromeRegClientStateKey,
782 KEY_SET_VALUE | KEY_WOW64_32KEY) != ERROR_SUCCESS ||
783 key.WriteValue(kRelaunchBrandcodeValue,
784 relaunch_brandcode) != ERROR_SUCCESS ||
785 key.WriteValue(kRelaunchAllowedAfterValue,
786 FormatDateOffsetByMonths(6)) != ERROR_SUCCESS ||
787 !SetRelaunchExperimentLabels(relaunch_brandcode, shell_mode)) {
788 if (error_code)
789 *error_code = RELAUNCH_ERROR_RELAUNCH_FAILED;
790 return FALSE;
793 return TRUE;