shell_util.h revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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.
4//
5// This file declares methods that are useful for integrating Chrome in
6// Windows shell. These methods are all static and currently part of
7// ShellUtil class.
8
9#ifndef CHROME_INSTALLER_UTIL_SHELL_UTIL_H_
10#define CHROME_INSTALLER_UTIL_SHELL_UTIL_H_
11
12#include <windows.h>
13
14#include <map>
15#include <vector>
16
17#include "base/basictypes.h"
18#include "base/files/file_path.h"
19#include "base/logging.h"
20#include "base/string16.h"
21#include "chrome/installer/util/work_item_list.h"
22
23class BrowserDistribution;
24
25// This is a utility class that provides common shell integration methods
26// that can be used by installer as well as Chrome.
27class ShellUtil {
28 public:
29  // Input to any methods that make changes to OS shell.
30  enum ShellChange {
31    CURRENT_USER = 0x1,  // Make any shell changes only at the user level
32    SYSTEM_LEVEL = 0x2   // Make any shell changes only at the system level
33  };
34
35  // Chrome's default handler state for a given protocol.
36  enum DefaultState {
37    UNKNOWN_DEFAULT,
38    NOT_DEFAULT,
39    IS_DEFAULT,
40  };
41
42  // Typical shortcut directories. Resolved in GetShortcutPath().
43  enum ShortcutLocation {
44    SHORTCUT_LOCATION_DESKTOP,
45    SHORTCUT_LOCATION_QUICK_LAUNCH,
46    SHORTCUT_LOCATION_START_MENU,
47  };
48
49  enum ShortcutOperation {
50    // Create a new shortcut (overwriting if necessary).
51    SHELL_SHORTCUT_CREATE_ALWAYS,
52    // Create the per-user shortcut only if its system-level equivalent (with
53    // the same name) is not present.
54    SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL,
55    // Overwrite an existing shortcut (fail if the shortcut doesn't exist).
56    // If the arguments are not specified on the new shortcut, keep the old
57    // shortcut's arguments.
58    SHELL_SHORTCUT_REPLACE_EXISTING,
59    // Update specified properties only on an existing shortcut.
60    SHELL_SHORTCUT_UPDATE_EXISTING,
61  };
62
63  // Properties for shortcuts. Properties set will be applied to
64  // the shortcut on creation/update. On update, unset properties are ignored;
65  // on create (and replaced) unset properties might have a default value (see
66  // individual property setters below for details).
67  // Callers are encouraged to use the setters provided which take care of
68  // setting |options| as desired.
69  struct ShortcutProperties {
70    enum IndividualProperties {
71      PROPERTIES_TARGET = 1 << 0,
72      PROPERTIES_ARGUMENTS = 1 << 1,
73      PROPERTIES_DESCRIPTION = 1 << 2,
74      PROPERTIES_ICON = 1 << 3,
75      PROPERTIES_APP_ID = 1 << 4,
76      PROPERTIES_SHORTCUT_NAME = 1 << 5,
77      PROPERTIES_DUAL_MODE = 1 << 6,
78    };
79
80    explicit ShortcutProperties(ShellChange level_in)
81        : level(level_in), icon_index(0), dual_mode(false),
82          pin_to_taskbar(false), options(0U) {}
83
84    // Sets the target executable to launch from this shortcut.
85    // This is mandatory when creating a shortcut.
86    void set_target(const base::FilePath& target_in) {
87      target = target_in;
88      options |= PROPERTIES_TARGET;
89    }
90
91    // Sets the arguments to be passed to |target| when launching from this
92    // shortcut.
93    // The length of this string must be less than MAX_PATH.
94    void set_arguments(const string16& arguments_in) {
95      // Size restriction as per MSDN at
96      // http://msdn.microsoft.com/library/windows/desktop/bb774954.aspx.
97      DCHECK(arguments_in.length() < MAX_PATH);
98      arguments = arguments_in;
99      options |= PROPERTIES_ARGUMENTS;
100    }
101
102    // Sets the localized description of the shortcut.
103    // The length of this string must be less than MAX_PATH.
104    void set_description(const string16& description_in) {
105      // Size restriction as per MSDN at
106      // http://msdn.microsoft.com/library/windows/desktop/bb774955.aspx.
107      DCHECK(description_in.length() < MAX_PATH);
108      description = description_in;
109      options |= PROPERTIES_DESCRIPTION;
110    }
111
112    // Sets the path to the icon (icon_index set to 0).
113    // icon index unless otherwise specified in master_preferences).
114    void set_icon(const base::FilePath& icon_in, int icon_index_in) {
115      icon = icon_in;
116      icon_index = icon_index_in;
117      options |= PROPERTIES_ICON;
118    }
119
120    // Sets the app model id for the shortcut (Win7+).
121    void set_app_id(const string16& app_id_in) {
122      app_id = app_id_in;
123      options |= PROPERTIES_APP_ID;
124    }
125
126    // Forces the shortcut's name to |shortcut_name_in|.
127    // Default: the current distribution's GetAppShortcutName().
128    // The ".lnk" extension will automatically be added to this name.
129    void set_shortcut_name(const string16& shortcut_name_in) {
130      shortcut_name = shortcut_name_in;
131      options |= PROPERTIES_SHORTCUT_NAME;
132    }
133
134    // Sets whether this is a dual mode shortcut (Win8+).
135    // NOTE: Only the default (no arguments and default browser appid) browser
136    // shortcut in the Start menu (Start screen on Win8+) should be made dual
137    // mode.
138    void set_dual_mode(bool dual_mode_in) {
139      dual_mode = dual_mode_in;
140      options |= PROPERTIES_DUAL_MODE;
141    }
142
143    // Sets whether to pin this shortcut to the taskbar after creating it
144    // (ignored if the shortcut is only being updated).
145    // Note: This property doesn't have a mask in |options|.
146    void set_pin_to_taskbar(bool pin_to_taskbar_in) {
147      pin_to_taskbar = pin_to_taskbar_in;
148    }
149
150    bool has_target() const {
151      return (options & PROPERTIES_TARGET) != 0;
152    }
153
154    bool has_arguments() const {
155      return (options & PROPERTIES_ARGUMENTS) != 0;
156    }
157
158    bool has_description() const {
159      return (options & PROPERTIES_DESCRIPTION) != 0;
160    }
161
162    bool has_icon() const {
163      return (options & PROPERTIES_ICON) != 0;
164    }
165
166    bool has_app_id() const {
167      return (options & PROPERTIES_APP_ID) != 0;
168    }
169
170    bool has_shortcut_name() const {
171      return (options & PROPERTIES_SHORTCUT_NAME) != 0;
172    }
173
174    bool has_dual_mode() const {
175      return (options & PROPERTIES_DUAL_MODE) != 0;
176    }
177
178    // The level to install this shortcut at (CURRENT_USER for a per-user
179    // shortcut and SYSTEM_LEVEL for an all-users shortcut).
180    ShellChange level;
181
182    base::FilePath target;
183    string16 arguments;
184    string16 description;
185    base::FilePath icon;
186    int icon_index;
187    string16 app_id;
188    string16 shortcut_name;
189    bool dual_mode;
190    bool pin_to_taskbar;
191    // Bitfield made of IndividualProperties. Properties set in |options| will
192    // be used to create/update the shortcut, others will be ignored on update
193    // and possibly replaced by default values on create (see individual
194    // property setters above for details on default values).
195    uint32 options;
196  };
197
198  // Relative path of the URL Protocol registry entry (prefixed with '\').
199  static const wchar_t* kRegURLProtocol;
200
201  // Relative path of DefaultIcon registry entry (prefixed with '\').
202  static const wchar_t* kRegDefaultIcon;
203
204  // Relative path of "shell" registry key.
205  static const wchar_t* kRegShellPath;
206
207  // Relative path of shell open command in Windows registry
208  // (i.e. \\shell\\open\\command).
209  static const wchar_t* kRegShellOpen;
210
211  // Relative path of registry key under which applications need to register
212  // to control Windows Start menu links.
213  static const wchar_t* kRegStartMenuInternet;
214
215  // Relative path of Classes registry entry under which file associations
216  // are added on Windows.
217  static const wchar_t* kRegClasses;
218
219  // Relative path of RegisteredApplications registry entry under which
220  // we add Chrome as a Windows application
221  static const wchar_t* kRegRegisteredApplications;
222
223  // The key path and key name required to register Chrome on Windows such
224  // that it can be launched from Start->Run just by name (chrome.exe).
225  static const wchar_t* kAppPathsRegistryKey;
226  static const wchar_t* kAppPathsRegistryPathName;
227
228  // Name that we give to Chrome file association handler ProgId.
229  static const wchar_t* kChromeHTMLProgId;
230
231  // Description of Chrome file association handler ProgId.
232  static const wchar_t* kChromeHTMLProgIdDesc;
233
234  // Registry path that stores url associations on Vista.
235  static const wchar_t* kRegVistaUrlPrefs;
236
237  // File extensions that Chrome registers itself for.
238  static const wchar_t* kFileAssociations[];
239
240  // Protocols that Chrome registers itself as the default handler for
241  // when the user makes Chrome the default browser.
242  static const wchar_t* kBrowserProtocolAssociations[];
243
244  // Protocols that Chrome registers itself as being capable of handling.
245  static const wchar_t* kPotentialProtocolAssociations[];
246
247  // Registry value name that is needed for ChromeHTML ProgId
248  static const wchar_t* kRegUrlProtocol;
249
250  // Relative registry path from \Software\Classes\ChromeHTML to the ProgId
251  // Application definitions.
252  static const wchar_t* kRegApplication;
253
254  // Registry value name for the AppUserModelId of an application.
255  static const wchar_t* kRegAppUserModelId;
256
257  // Registry value name for the description of an application.
258  static const wchar_t* kRegApplicationDescription;
259
260  // Registry value name for an application's name.
261  static const wchar_t* kRegApplicationName;
262
263  // Registry value name for the path to an application's icon.
264  static const wchar_t* kRegApplicationIcon;
265
266  // Registry value name for an application's company.
267  static const wchar_t* kRegApplicationCompany;
268
269  // Relative path of ".exe" registry key.
270  static const wchar_t* kRegExePath;
271
272  // Registry value name of the open verb.
273  static const wchar_t* kRegVerbOpen;
274
275  // Registry value name of the opennewwindow verb.
276  static const wchar_t* kRegVerbOpenNewWindow;
277
278  // Registry value name of the run verb.
279  static const wchar_t* kRegVerbRun;
280
281  // Registry value name for command entries.
282  static const wchar_t* kRegCommand;
283
284  // Registry value name for the DelegateExecute verb handler.
285  static const wchar_t* kRegDelegateExecute;
286
287  // Registry value name for the OpenWithProgids entry for file associations.
288  static const wchar_t* kRegOpenWithProgids;
289
290  // Returns true if |chrome_exe| is registered in HKLM with |suffix|.
291  // Note: This only checks one deterministic key in HKLM for |chrome_exe| and
292  // doesn't otherwise validate a full Chrome install in HKLM.
293  static bool QuickIsChromeRegisteredInHKLM(BrowserDistribution* dist,
294                                            const string16& chrome_exe,
295                                            const string16& suffix);
296
297  // Sets |path| to the path for a shortcut at the |location| desired for the
298  // given |level| (CURRENT_USER for per-user path and SYSTEM_LEVEL for
299  // all-users path).
300  // Returns false on failure.
301  static bool GetShortcutPath(ShellUtil::ShortcutLocation location,
302                              BrowserDistribution* dist,
303                              ShellChange level,
304                              base::FilePath* path);
305
306  // Updates shortcut in |location| (or creates it if |options| specify
307  // SHELL_SHORTCUT_CREATE_ALWAYS).
308  // |dist| gives the type of browser distribution currently in use.
309  // |properties| and |operation| affect this method as described on their
310  // invidividual definitions above.
311  static bool CreateOrUpdateShortcut(
312      ShellUtil::ShortcutLocation location,
313      BrowserDistribution* dist,
314      const ShellUtil::ShortcutProperties& properties,
315      ShellUtil::ShortcutOperation operation);
316
317  // Returns the string "|icon_path|,|icon_index|" (see, for example,
318  // http://msdn.microsoft.com/library/windows/desktop/dd391573.aspx).
319  static string16 FormatIconLocation(const string16& icon_path, int icon_index);
320
321  // This method returns the command to open URLs/files using chrome. Typically
322  // this command is written to the registry under shell\open\command key.
323  // |chrome_exe|: the full path to chrome.exe
324  static string16 GetChromeShellOpenCmd(const string16& chrome_exe);
325
326  // This method returns the command to be called by the DelegateExecute verb
327  // handler to launch chrome on Windows 8. Typically this command is written to
328  // the registry under the HKCR\Chrome\.exe\shell\(open|run)\command key.
329  // |chrome_exe|: the full path to chrome.exe
330  static string16 GetChromeDelegateCommand(const string16& chrome_exe);
331
332  // Gets a mapping of all registered browser names (excluding browsers in the
333  // |dist| distribution) and their reinstall command (which usually sets
334  // browser as default).
335  // Given browsers can be registered in HKCU (as of Win7) and/or in HKLM, this
336  // method looks in both and gives precedence to values in HKCU as per the msdn
337  // standard: http://goo.gl/xjczJ.
338  static void GetRegisteredBrowsers(BrowserDistribution* dist,
339                                    std::map<string16, string16>* browsers);
340
341  // Returns the suffix this user's Chrome install is registered with.
342  // Always returns the empty string on system-level installs.
343  //
344  // This method is meant for external methods which need to know the suffix of
345  // the current install at run-time, not for install-time decisions.
346  // There are no guarantees that this suffix will not change later:
347  // (e.g. if two user-level installs were previously installed in parallel on
348  // the same machine, both without admin rights and with no user-level install
349  // having claimed the non-suffixed HKLM registrations, they both have no
350  // suffix in their progId entries (as per the old suffix rules). If they were
351  // to both fully register (i.e. click "Make Chrome Default" and go through
352  // UAC; or upgrade to Win8 and get the automatic no UAC full registration)
353  // they would then both get a suffixed registration as per the new suffix
354  // rules).
355  //
356  // |chrome_exe| The path to the currently installed (or running) chrome.exe.
357  static string16 GetCurrentInstallationSuffix(BrowserDistribution* dist,
358                                               const string16& chrome_exe);
359
360  // Returns the application name of the program under |dist|.
361  // This application name will be suffixed as is appropriate for the current
362  // install.
363  // This is the name that is registered with Default Programs on Windows and
364  // that should thus be used to "make chrome default" and such.
365  static string16 GetApplicationName(BrowserDistribution* dist,
366                                     const string16& chrome_exe);
367
368  // Returns the AppUserModelId for |dist|. This identifier is unconditionally
369  // suffixed with a unique id for this user on user-level installs (in contrast
370  // to other registration entries which are suffixed as described in
371  // GetCurrentInstallationSuffix() above).
372  static string16 GetBrowserModelId(BrowserDistribution* dist,
373                                    bool is_per_user_install);
374
375  // Returns an AppUserModelId composed of each member of |components| separated
376  // by dots.
377  // The returned appid is guaranteed to be no longer than
378  // chrome::kMaxAppModelIdLength (some of the components might have been
379  // shortened to enforce this).
380  static string16 BuildAppModelId(const std::vector<string16>& components);
381
382  // Returns true if Chrome can make itself the default browser without relying
383  // on the Windows shell to prompt the user. This is the case for versions of
384  // Windows prior to Windows 8.
385  static bool CanMakeChromeDefaultUnattended();
386
387  // Returns the DefaultState of Chrome for HTTP and HTTPS.
388  static DefaultState GetChromeDefaultState();
389
390  // Returns the DefaultState of Chrome for |protocol|.
391  static DefaultState GetChromeDefaultProtocolClientState(
392      const string16& protocol);
393
394  // Make Chrome the default browser. This function works by going through
395  // the url protocols and file associations that are related to general
396  // browsing, e.g. http, https, .html etc., and requesting to become the
397  // default handler for each. If any of these fails the operation will return
398  // false to indicate failure, which is consistent with the return value of
399  // ShellIntegration::GetDefaultBrowser.
400  //
401  // In the case of failure any successful changes will be left, however no
402  // more changes will be attempted.
403  // TODO(benwells): Attempt to undo any changes that were successfully made.
404  // http://crbug.com/83970
405  //
406  // shell_change: Defined whether to register as default browser at system
407  //               level or user level. If value has ShellChange::SYSTEM_LEVEL
408  //               we should be running as admin user.
409  // chrome_exe: The chrome.exe path to register as default browser.
410  // elevate_if_not_admin: On Vista if user is not admin, try to elevate for
411  //                       Chrome registration.
412  static bool MakeChromeDefault(BrowserDistribution* dist,
413                                int shell_change,
414                                const string16& chrome_exe,
415                                bool elevate_if_not_admin);
416
417  // Shows and waits for the Windows 8 "How do you want to open webpages?"
418  // dialog if Chrome is not already the default HTTP/HTTPS handler. Also does
419  // XP-era registrations if Chrome is chosen or was already the default. Do
420  // not use on pre-Win8 OSes.
421  //
422  // |dist| gives the type of browser distribution currently in use.
423  // |chrome_exe| The chrome.exe path to register as default browser.
424  static bool ShowMakeChromeDefaultSystemUI(BrowserDistribution* dist,
425                                            const string16& chrome_exe);
426
427  // Make Chrome the default application for a protocol.
428  // chrome_exe: The chrome.exe path to register as default browser.
429  // protocol: The protocol to register as the default handler for.
430  static bool MakeChromeDefaultProtocolClient(BrowserDistribution* dist,
431                                              const string16& chrome_exe,
432                                              const string16& protocol);
433
434  // Shows and waits for the Windows 8 "How do you want to open links of this
435  // type?" dialog if Chrome is not already the default |protocol|
436  // handler. Also does XP-era registrations if Chrome is chosen or was already
437  // the default for |protocol|. Do not use on pre-Win8 OSes.
438  //
439  // |dist| gives the type of browser distribution currently in use.
440  // |chrome_exe| The chrome.exe path to register as default browser.
441  // |protocol| is the protocol being registered.
442  static bool ShowMakeChromeDefaultProtocolClientSystemUI(
443      BrowserDistribution* dist,
444      const string16& chrome_exe,
445      const string16& protocol);
446
447  // Registers Chrome as a potential default browser and handler for filetypes
448  // and protocols.
449  // If Chrome is already registered, this method is a no-op.
450  // This method requires write access to HKLM (prior to Win8) so is just a
451  // best effort deal.
452  // If write to HKLM is required, but fails, and:
453  // - |elevate_if_not_admin| is true (and OS is Vista or above):
454  //   tries to launch setup.exe with admin priviledges (by prompting the user
455  //   with a UAC) to do these tasks.
456  // - |elevate_if_not_admin| is false (or OS is XP):
457  //   adds the ProgId entries to HKCU. These entries will not make Chrome show
458  //   in Default Programs but they are still useful because Chrome can be
459  //   registered to run when the user clicks on an http link or an html file.
460  //
461  // |chrome_exe| full path to chrome.exe.
462  // |unique_suffix| Optional input. If given, this function appends the value
463  // to default browser entries names that it creates in the registry.
464  // Currently, this is only used to continue an install with the same suffix
465  // when elevating and calling setup.exe with admin privileges as described
466  // above.
467  // |elevate_if_not_admin| if true will make this method try alternate methods
468  // as described above. This should only be true when following a user action
469  // (e.g. "Make Chrome Default") as it allows this method to UAC.
470  //
471  // Returns true if Chrome is successfully registered (or already registered).
472  static bool RegisterChromeBrowser(BrowserDistribution* dist,
473                                    const string16& chrome_exe,
474                                    const string16& unique_suffix,
475                                    bool elevate_if_not_admin);
476
477  // This method declares to Windows that Chrome is capable of handling the
478  // given protocol. This function will call the RegisterChromeBrowser function
479  // to register with Windows as capable of handling the protocol, if it isn't
480  // currently registered as capable.
481  // Declaring the capability of handling a protocol is necessary to register
482  // as the default handler for the protocol in Vista and later versions of
483  // Windows.
484  //
485  // If called by the browser and elevation is required, it will elevate by
486  // calling setup.exe which will again call this function with elevate false.
487  //
488  // |chrome_exe| full path to chrome.exe.
489  // |unique_suffix| Optional input. If given, this function appends the value
490  // to default browser entries names that it creates in the registry.
491  // |protocol| The protocol to register as being capable of handling.s
492  // |elevate_if_not_admin| if true will make this method try alternate methods
493  // as described above.
494  static bool RegisterChromeForProtocol(BrowserDistribution* dist,
495                                        const string16& chrome_exe,
496                                        const string16& unique_suffix,
497                                        const string16& protocol,
498                                        bool elevate_if_not_admin);
499
500  // Removes installed shortcut(s) at |location|.
501  // |target_exe|: Shortcut target exe; shortcuts will only be deleted when
502  // their target is |target_exe|.
503  // |level|: CURRENT_USER to remove the per-user shortcut and SYSTEM_LEVEL to
504  // remove the all-users shortcut.
505  // |shortcut_name|: If non-null, remove the shortcut named |shortcut_name| at
506  // location; otherwise remove all shortcuts to |target_exe| at |location|.
507  // If |location| is SHORTCUT_LOCATION_START_MENU, the shortcut folder specific
508  // to |dist| is deleted.
509  // Also attempts to unpin the removed shortcut(s) from the taskbar.
510  // Returns true if the shortcut(s) were successfully deleted (or there were
511  // none at |location| pointing to |target_exe|).
512  static bool RemoveShortcut(ShellUtil::ShortcutLocation location,
513                             BrowserDistribution* dist,
514                             const base::FilePath& target_exe,
515                             ShellChange level,
516                             const string16* shortcut_name);
517
518  // Enumerates all shortcuts pinned to the taskbar and deletes those pointing
519  // to |target_exe|.
520  // base::win::TaskbarUnpinShortcutLink() should be prefered, but this is
521  // useful on uninstall as the parent shortcut of a pin might no longer exist
522  // (thus making it impossible to unpin it via that API).
523  static void RemoveTaskbarShortcuts(const string16& target_exe);
524
525  // This will remove all secondary tiles from the start screen for |dist|.
526  static void RemoveStartScreenShortcuts(BrowserDistribution* dist,
527                                         const string16& target_exe);
528
529  // Sets |suffix| to the base 32 encoding of the md5 hash of this user's sid
530  // preceded by a dot.
531  // This is guaranteed to be unique on the machine and 27 characters long
532  // (including the '.').
533  // This suffix is then meant to be added to all registration that may conflict
534  // with another user-level Chrome install.
535  // Note that prior to Chrome 21, the suffix registered used to be the user's
536  // username (see GetOldUserSpecificRegistrySuffix() below). We still honor old
537  // installs registered that way, but it was wrong because some of the
538  // characters allowed in a username are not allowed in a ProgId.
539  // Returns true unless the OS call to retrieve the username fails.
540  // NOTE: Only the installer should use this suffix directly. Other callers
541  // should call GetCurrentInstallationSuffix().
542  static bool GetUserSpecificRegistrySuffix(string16* suffix);
543
544  // Sets |suffix| to this user's username preceded by a dot. This suffix should
545  // only be used to support legacy installs that used this suffixing
546  // style.
547  // Returns true unless the OS call to retrieve the username fails.
548  // NOTE: Only the installer should use this suffix directly. Other callers
549  // should call GetCurrentInstallationSuffix().
550  static bool GetOldUserSpecificRegistrySuffix(string16* suffix);
551
552  // Returns the base32 encoding (using the [A-Z2-7] alphabet) of |bytes|.
553  // |size| is the length of |bytes|.
554  // Note: This method does not suffix the output with '=' signs as technically
555  // required by the base32 standard for inputs that aren't a multiple of 5
556  // bytes.
557  static string16 ByteArrayToBase32(const uint8* bytes, size_t size);
558
559 private:
560  DISALLOW_COPY_AND_ASSIGN(ShellUtil);
561};
562
563
564#endif  // CHROME_INSTALLER_UTIL_SHELL_UTIL_H_
565