Roll leveldb to r76.
[chromium-blink-merge.git] / chrome_frame / utils.h
blob95b9756b9e55e9bae831decd5bc5dc0094efe59d
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 #ifndef CHROME_FRAME_UTILS_H_
6 #define CHROME_FRAME_UTILS_H_
8 #include <OAidl.h>
9 #include <objidl.h>
10 #include <windows.h>
11 #include <wininet.h>
12 #include <string>
13 #include <vector>
15 #include "base/basictypes.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/strings/string16.h"
19 #include "base/win/scoped_comptr.h"
20 #include "ui/gfx/rect.h"
21 #include "url/gurl.h"
23 class RegistryListPreferencesHolder;
24 interface IBrowserService;
25 interface IWebBrowser2;
26 struct ContextMenuModel;
28 namespace base {
29 class FilePath;
32 // utils.h : Various utility functions and classes
33 extern const char kGCFProtocol[];
35 extern const wchar_t kAllowUnsafeURLs[];
36 extern const wchar_t kChromeContentPrefix[];
37 extern const wchar_t kChromeFrameAccessibleMode[];
38 extern const wchar_t kChromeFrameAttachTabPattern[];
39 extern const wchar_t kChromeFrameConfigKey[];
40 extern const wchar_t kChromeFrameHeadlessMode[];
41 extern const wchar_t kChromeFrameUnpinnedMode[];
42 extern const wchar_t kChromeMimeType[];
43 extern const wchar_t kChromeProtocolPrefix[];
44 extern const wchar_t kEnableBuggyBhoIntercept[];
45 extern const wchar_t kEnableGCFRendererByDefault[];
46 extern const wchar_t kExcludeUAFromDomainList[];
47 extern const wchar_t kIexploreProfileName[];
48 extern const wchar_t kRenderInGCFUrlList[];
49 extern const wchar_t kRenderInHostUrlList[];
50 extern const wchar_t kRundllProfileName[];
51 extern const wchar_t kUseBackgroundThreadForSubResources[];
53 // This function is very similar to the AtlRegisterTypeLib function except
54 // that it takes a parameter that specifies whether to register the typelib
55 // for the current user only or on a machine-wide basis
56 // Refer to the MSDN documentation for AtlRegisterTypeLib for a description of
57 // the arguments
58 HRESULT UtilRegisterTypeLib(HINSTANCE tlb_instance,
59 LPCOLESTR index,
60 bool for_current_user_only);
62 // This function is very similar to the AtlUnRegisterTypeLib function except
63 // that it takes a parameter that specifies whether to unregister the typelib
64 // for the current user only or on a machine-wide basis
65 // Refer to the MSDN documentation for AtlUnRegisterTypeLib for a description
66 // of the arguments
67 HRESULT UtilUnRegisterTypeLib(HINSTANCE tlb_instance,
68 LPCOLESTR index,
69 bool for_current_user_only);
71 HRESULT UtilRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
73 HRESULT UtilUnRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
75 HRESULT UtilRegisterTypeLib(ITypeLib* typelib,
76 LPCWSTR typelib_path,
77 LPCWSTR help_dir,
78 bool for_current_user_only);
80 HRESULT UtilUnRegisterTypeLib(ITypeLib* typelib,
81 bool for_current_user_only);
83 // Clears a marker that causes legacy NPAPI registration to persist across
84 // updates. Returns false if the marker could not be removed.
85 bool UtilRemovePersistentNPAPIMarker();
87 // Given an HTML fragment, this function looks for the
88 // <meta http-equiv="X-UA-Compatible"> tag and extracts the value of the
89 // "content" attribute
90 // This method will currently return a false positive if the tag appears
91 // inside a string in a <SCRIPT> block.
92 HRESULT UtilGetXUACompatContentValue(const std::wstring& html_string,
93 std::wstring* content_value);
95 // Returns a string from ChromeFrame's string table by resource. Must be
96 // provided with a valid resource id.
97 std::wstring GetResourceString(int resource_id);
99 // Displays a message box indicating that there was a version mismatch between
100 // ChromeFrame and the running instance of Chrome.
101 // server_version is the version of the running instance of Chrome.
102 void DisplayVersionMismatchWarning(HWND parent,
103 const std::string& server_version);
105 // This class provides a base implementation for ATL modules which want to
106 // perform all their registration under HKCU. This class overrides the
107 // RegisterServer and UnregisterServer methods and registers the type libraries
108 // under HKCU (the rest of the registration is made under HKCU by changing the
109 // appropriate .RGS files)
110 template < class BaseAtlModule >
111 class AtlPerUserModule : public BaseAtlModule {
112 public:
113 HRESULT RegisterServer(BOOL reg_typelib = FALSE,
114 const CLSID* clsid = NULL) throw() {
115 HRESULT hr = BaseAtlModule::RegisterServer(FALSE, clsid);
116 if (FAILED(hr)) {
117 return hr;
119 if (reg_typelib) {
120 hr = UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
122 return hr;
125 HRESULT UnregisterServer(BOOL unreg_typelib,
126 const CLSID* clsid = NULL) throw() {
127 HRESULT hr = BaseAtlModule::UnregisterServer(FALSE, clsid);
128 if (FAILED(hr)) {
129 return hr;
131 if (unreg_typelib) {
132 hr = UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
134 return hr;
138 // Creates a javascript statement for execution from the function name and
139 // arguments passed in.
140 std::string CreateJavascript(const std::string& function_name,
141 const std::string args);
143 // Use to prevent the DLL from being unloaded while there are still living
144 // objects with outstanding references.
145 class AddRefModule {
146 public:
147 AddRefModule();
148 ~AddRefModule();
151 // Retrieves the executable name of the process hosting us. If
152 // |include_extension| is false, then we strip the extension from the name.
153 std::wstring GetHostProcessName(bool include_extension);
155 typedef enum BrowserType {
156 BROWSER_INVALID = -1,
157 BROWSER_UNKNOWN,
158 BROWSER_IE,
161 BrowserType GetBrowserType();
163 typedef enum IEVersion {
164 IE_INVALID,
165 NON_IE,
166 IE_UNSUPPORTED,
167 IE_6,
168 IE_7,
169 IE_8,
170 IE_9,
171 IE_10,
174 // The renderer to be used for a page. Values for Chrome also convey the
175 // reason why Chrome is used.
176 enum RendererType {
177 RENDERER_TYPE_UNDETERMINED = 0,
178 RENDERER_TYPE_CHROME_MIN,
179 // NOTE: group all _CHROME_ values together below here, as they are used for
180 // generating metrics reported via UMA (adjust MIN/MAX as needed).
181 RENDERER_TYPE_CHROME_GCF_PROTOCOL = RENDERER_TYPE_CHROME_MIN,
182 RENDERER_TYPE_CHROME_HTTP_EQUIV,
183 RENDERER_TYPE_CHROME_RESPONSE_HEADER,
184 RENDERER_TYPE_CHROME_DEFAULT_RENDERER,
185 RENDERER_TYPE_CHROME_OPT_IN_URL,
186 RENDERER_TYPE_CHROME_WIDGET,
187 // NOTE: all _CHOME_ values must go above here (adjust MIN/MAX as needed).
188 RENDERER_TYPE_CHROME_MAX = RENDERER_TYPE_CHROME_WIDGET,
189 RENDERER_TYPE_OTHER,
192 // Returns true if the given RendererType represents Chrome.
193 bool IsChrome(RendererType renderer_type);
195 // Convenience macro for logging a sample for the launch type metric.
196 #define UMA_LAUNCH_TYPE_COUNT(sample) \
197 UMA_HISTOGRAM_CUSTOM_COUNTS("ChromeFrame.LaunchType", sample, \
198 RENDERER_TYPE_CHROME_MIN, RENDERER_TYPE_CHROME_MAX, \
199 RENDERER_TYPE_CHROME_MAX + 1 - RENDERER_TYPE_CHROME_MIN)
201 // To get the IE version when Chrome Frame is hosted in IE. Make sure that
202 // the hosting browser is IE before calling this function, otherwise NON_IE
203 // will be returned.
205 // Versions newer than the newest supported version are reported as the newest
206 // supported version.
207 IEVersion GetIEVersion();
209 // Returns the actual major version of the IE in which the current process is
210 // hosted. Returns 0 if the current process is not IE or any other error occurs.
211 uint32 GetIEMajorVersion();
213 base::FilePath GetIETemporaryFilesFolder();
215 // Retrieves the file version from a module handle without extra round trips
216 // to the disk (as happens with the regular GetFileVersionInfo API).
218 // @param module A handle to the module for which to retrieve the version info.
219 // @param high On successful return holds the most significant part of the file
220 // version. Must be non-null.
221 // @param low On successful return holds the least significant part of the file
222 // version. May be NULL.
223 // @returns true if the version info was successfully retrieved.
224 bool GetModuleVersion(HMODULE module, uint32* high, uint32* low);
226 // Return if the IEXPLORE is in private mode. The IEIsInPrivateBrowsing() checks
227 // whether current process is IEXPLORE.
228 bool IsIEInPrivate();
230 // Calls [ieframe|shdocvw]!DoFileDownload to initiate a download.
231 HRESULT DoFileDownloadInIE(const wchar_t* url);
233 // Construct a menu from the model sent from Chrome.
234 HMENU BuildContextMenu(const ContextMenuModel& menu_model);
236 // Uses GURL internally to append 'relative' to 'document'
237 std::string ResolveURL(const std::string& document,
238 const std::string& relative);
240 // Returns true iff the two urls have the same scheme, same host and same port.
241 bool HaveSameOrigin(const std::string& url1, const std::string& url2);
243 // Get a boolean configuration value from registry.
244 bool GetConfigBool(bool default_value, const wchar_t* value_name);
246 // Gets an integer configuration value from the registry.
247 int GetConfigInt(int default_value, const wchar_t* value_name);
249 // Gets a 64-bit integer configuration value from the registry.
250 int64 GetConfigInt64(int64 default_value, const wchar_t* value_name);
252 // Sets an integer configuration value in the registry.
253 bool SetConfigInt(const wchar_t* value_name, int value);
255 // Sets a boolean integer configuration value in the registry.
256 bool SetConfigBool(const wchar_t* value_name, bool value);
258 // Sets a 64-bit integer configuration value in the registry.
259 bool SetConfigInt64(const wchar_t* value_name, int64 value);
261 // Deletes the configuration value passed in.
262 bool DeleteConfigValue(const wchar_t* value_name);
264 // Returns true if we are running in headless mode in which case we need to
265 // gather crash dumps, etc to send them to the crash server.
266 bool IsHeadlessMode();
268 // Returns true if we are running in accessible mode in which we need to enable
269 // renderer accessibility for use in automation.
270 bool IsAccessibleMode();
272 // Returns true if we are running in unpinned mode in which case DLL
273 // eviction should be possible.
274 bool IsUnpinnedMode();
276 // Returns true if all HTML pages should be rendered in GCF by default.
277 bool IsGcfDefaultRenderer();
279 // Returns true if the presence of
280 // <meta http-equiv="X-UA-Compatible" content="chrome=1">
281 // in HTML pages should be ignored
282 bool SkipMetadataCheck();
284 // Check if this url is opting into Chrome Frame based on static settings.
285 // Returns one of:
286 // - RENDERER_TYPE_UNDETERMINED if not opt-in or if explicit opt-out
287 // - RENDERER_TYPE_CHROME_DEFAULT_RENDERER
288 // - RENDERER_TYPE_CHROME_OPT_IN_URL
289 RendererType RendererTypeForUrl(const std::wstring& url);
291 // Check if we should try to remove the CF user agent based on registry
292 // settings.
293 bool ShouldRemoveUAForUrl(const string16& url);
295 // Testing methods that return the backing stores behind RendererTypeForUrl and
296 // ShouldRemoveUAForUrl. Intended to allow unit testing code that calls the
297 // above methods.
298 // TODO(robertshield): All of the FooForUrl code should be removed from here
299 // and further refactored.
300 RegistryListPreferencesHolder& GetRendererTypePreferencesHolderForTesting();
301 RegistryListPreferencesHolder& GetUserAgentPreferencesHolderForTesting();
303 // A shortcut for QueryService
304 template <typename T>
305 HRESULT DoQueryService(const IID& service_id, IUnknown* unk, T** service) {
306 DCHECK(service);
307 if (!unk)
308 return E_INVALIDARG;
310 base::win::ScopedComPtr<IServiceProvider> service_provider;
311 HRESULT hr = service_provider.QueryFrom(unk);
312 if (service_provider)
313 hr = service_provider->QueryService(service_id, service);
315 DCHECK(FAILED(hr) || *service);
316 return hr;
319 // Navigates an IWebBrowser2 object to a moniker.
320 // |headers| can be NULL.
321 HRESULT NavigateBrowserToMoniker(IUnknown* browser, IMoniker* moniker,
322 const wchar_t* headers, IBindCtx* bind_ctx,
323 const wchar_t* fragment, IStream* post_data,
324 VARIANT* flags);
326 // Raises a flag on the current thread (using TLS) to indicate that an
327 // in-progress navigation should be rendered in chrome frame.
328 void MarkBrowserOnThreadForCFNavigation(IBrowserService* browser);
330 // Checks if this browser instance has been marked as currently navigating
331 // to a CF document. If clear_flag is set to true, the tls flag is cleared but
332 // only if the browser has been marked.
333 bool CheckForCFNavigation(IBrowserService* browser, bool clear_flag);
335 // Returns true if the URL passed in is something which can be handled by
336 // Chrome. If this function returns false then we should fail the navigation.
337 // When is_privileged is true, chrome extension URLs will be considered valid.
338 bool IsValidUrlScheme(const GURL& url, bool is_privileged);
340 // Returns the raw http headers for the current request given an
341 // IWinInetHttpInfo pointer.
342 std::string GetRawHttpHeaders(IWinInetHttpInfo* info);
344 // Can be used to determine whether a given request is being performed for
345 // a sub-frame or iframe in Internet Explorer. This can be called
346 // from various places, notably in request callbacks and the like.
348 // |service_provider| must not be NULL and should be a pointer to something
349 // that implements IServiceProvider (if it isn't this method returns false).
351 // Returns true if this method can determine with some certainty that the
352 // request did NOT originate from a top level frame, returns false otherwise.
353 bool IsSubFrameRequest(IUnknown* service_provider);
355 // See COM_INTERFACE_BLIND_DELEGATE below for details.
356 template <class T>
357 STDMETHODIMP CheckOutgoingInterface(void* obj, REFIID iid, void** ret,
358 DWORD cookie) {
359 T* instance = reinterpret_cast<T*>(obj);
360 HRESULT hr = E_NOINTERFACE;
361 IUnknown* delegate = instance ? instance->delegate() : NULL;
362 if (delegate) {
363 hr = delegate->QueryInterface(iid, ret);
364 #if !defined(NDEBUG)
365 if (SUCCEEDED(hr)) {
366 wchar_t iid_string[64] = {0};
367 StringFromGUID2(iid, iid_string, arraysize(iid_string));
368 DVLOG(1) << __FUNCTION__ << " Giving out wrapped interface: "
369 << iid_string;
371 #endif
374 return hr;
377 // See COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS below for details.
378 template <class T>
379 STDMETHODIMP QueryInterfaceIfDelegateSupports(void* obj, REFIID iid,
380 void** ret, DWORD cookie) {
381 HRESULT hr = E_NOINTERFACE;
382 T* instance = reinterpret_cast<T*>(obj);
383 IUnknown* delegate = instance ? instance->delegate() : NULL;
384 if (delegate) {
385 base::win::ScopedComPtr<IUnknown> original;
386 hr = delegate->QueryInterface(iid,
387 reinterpret_cast<void**>(original.Receive()));
388 if (original) {
389 IUnknown* supported_interface = reinterpret_cast<IUnknown*>(
390 reinterpret_cast<DWORD_PTR>(obj) + cookie);
391 supported_interface->AddRef();
392 *ret = supported_interface;
393 hr = S_OK;
397 return hr;
400 // Same as COM_INTERFACE_ENTRY but relies on the class to implement a
401 // delegate() method that returns a pointer to the delegated COM object.
402 #define COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS(x) \
403 COM_INTERFACE_ENTRY_FUNC(_ATL_IIDOF(x), \
404 offsetofclass(x, _ComMapClass), \
405 QueryInterfaceIfDelegateSupports<_ComMapClass>)
407 // Queries the delegated COM object for an interface, bypassing the wrapper.
408 #define COM_INTERFACE_BLIND_DELEGATE() \
409 COM_INTERFACE_ENTRY_FUNC_BLIND(0, CheckOutgoingInterface<_ComMapClass>)
411 std::wstring GuidToString(const GUID& guid);
413 // The urls retrieved from the IMoniker interface don't contain the anchor
414 // portion of the actual url navigated to. This function checks whether the
415 // url passed in the bho_url parameter contains an anchor and if yes checks
416 // whether it matches the url retrieved from the moniker. If yes it returns
417 // the bho url, if not the moniker url.
418 std::wstring GetActualUrlFromMoniker(IMoniker* moniker,
419 IBindCtx* bind_context,
420 const std::wstring& bho_url);
422 // Checks if a window is a top level window
423 bool IsTopLevelWindow(HWND window);
425 // Seeks a stream back to position 0.
426 HRESULT RewindStream(IStream* stream);
428 // Fired when we want to notify IE about privacy changes.
429 #define WM_FIRE_PRIVACY_CHANGE_NOTIFICATION (WM_APP + 1)
431 // Sent (not posted) when a request needs to be downloaded in the host browser
432 // instead of Chrome. WPARAM is 0 and LPARAM is a pointer to an IMoniker
433 // object.
434 // NOTE: Since the message is sent synchronously, the handler should only
435 // start asynchronous operations in order to not block the sender unnecessarily.
436 #define WM_DOWNLOAD_IN_HOST (WM_APP + 2)
438 // This structure contains the parameters sent over to initiate a download
439 // request in the host browser.
440 struct DownloadInHostParams {
441 base::win::ScopedComPtr<IBindCtx> bind_ctx;
442 base::win::ScopedComPtr<IMoniker> moniker;
443 base::win::ScopedComPtr<IStream> post_data;
444 std::string request_headers;
447 // Maps the InternetCookieState enum to the corresponding CookieAction values
448 // used for IE privacy stuff.
449 int32 MapCookieStateToCookieAction(InternetCookieState cookie_state);
451 // Parses the url passed in and returns a GURL instance without the fragment.
452 GURL GetUrlWithoutFragment(const wchar_t* url);
454 // Compares the URLs passed in after removing the fragments from them.
455 bool CompareUrlsWithoutFragment(const wchar_t* url1, const wchar_t* url2);
457 // Returns the Referrer from the HTTP headers and additional headers.
458 std::string FindReferrerFromHeaders(const wchar_t* headers,
459 const wchar_t* additional_headers);
461 // Returns the HTTP headers from the binding passed in.
462 std::string GetHttpHeadersFromBinding(IBinding* binding);
464 // Returns the HTTP response code from the binding passed in.
465 int GetHttpResponseStatusFromBinding(IBinding* binding);
467 // Returns the clipboard format for text/html.
468 CLIPFORMAT GetTextHtmlClipboardFormat();
470 // Returns true iff the mime type is text/html.
471 bool IsTextHtmlMimeType(const wchar_t* mime_type);
473 // Returns true iff the clipboard format is text/html.
474 bool IsTextHtmlClipFormat(CLIPFORMAT cf);
476 // Returns true if we can detect that we are running as SYSTEM, false otherwise.
477 bool IsSystemProcess();
479 // STL helper class that implements a functor to delete objects.
480 // E.g: std::for_each(v.begin(), v.end(), utils::DeleteObject());
481 namespace utils {
482 class DeleteObject {
483 public:
484 template <typename T>
485 void operator()(T* obj) {
486 delete obj;
491 // Convert various protocol flags to text representation. Used for logging.
492 std::string BindStatus2Str(ULONG bind_status);
493 std::string PiFlags2Str(DWORD flags);
494 std::string Bscf2Str(DWORD flags);
496 // Reads data from a stream into a string.
497 HRESULT ReadStream(IStream* stream, size_t size, std::string* data);
499 // Parses urls targeted at ChromeFrame. This class maintains state like
500 // whether a url is prefixed with the gcf: prefix, whether it is being
501 // attached to an existing external tab, etc.
502 class ChromeFrameUrl {
503 public:
504 ChromeFrameUrl();
506 // Parses the url passed in. Returns true on success.
507 bool Parse(const std::wstring& url);
509 bool is_chrome_protocol() const {
510 return is_chrome_protocol_;
513 bool attach_to_external_tab() const {
514 return attach_to_external_tab_;
517 uint64 cookie() const {
518 return cookie_;
521 int disposition() const {
522 return disposition_;
525 const gfx::Rect& dimensions() const {
526 return dimensions_;
529 const GURL& gurl() const {
530 return parsed_url_;
533 const std::string& profile_name() const {
534 return profile_name_;
537 private:
538 // If we are attaching to an existing external tab, this function parses the
539 // suffix portion of the URL which contains the attach_external_tab prefix.
540 bool ParseAttachExternalTabUrl();
542 // Clear state.
543 void Reset();
545 bool attach_to_external_tab_;
546 bool is_chrome_protocol_;
547 uint64 cookie_;
548 gfx::Rect dimensions_;
549 int disposition_;
551 GURL parsed_url_;
552 std::string profile_name_;
555 class NavigationConstraints;
556 // Returns true if we can navigate to this URL.
557 // These decisions are controlled by the NavigationConstraints object passed
558 // in.
559 bool CanNavigate(const GURL& url,
560 NavigationConstraints* navigation_constraints);
562 // Helper function to spin a message loop and dispatch messages while waiting
563 // for a handle to be signaled.
564 void WaitWithMessageLoop(HANDLE* handles, int count, DWORD timeout);
566 // Enumerates values in a key and adds them to an array.
567 // The names of the values are not returned.
568 void EnumerateKeyValues(HKEY parent_key, const wchar_t* sub_key_name,
569 std::vector<std::wstring>* values);
571 // Interprets the value of an X-UA-Compatible header (or <meta> tag equivalent)
572 // and indicates whether the header value contains a Chrome Frame directive
573 // matching a given host browser version.
575 // The header is a series of name-value pairs, with the names being HTTP tokens
576 // and the values being either tokens or quoted-strings. Names and values are
577 // joined by '=' and pairs are delimited by either ';' or ','. LWS may be used
578 // liberally before and between names, values, '=', and ';' or ','. See RFC 2616
579 // for definitions of token, quoted-string, and LWS. See Microsoft's
580 // documentation of the X-UA-COMPATIBLE header here:
581 // http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
583 // At most one 'Chrome=<FILTER>' entry is expected in the header value. The
584 // first valid instance is used. The value of "<FILTER>" (possibly after
585 // unquoting) is interpreted as follows:
587 // "1" - Always active
588 // "IE7" - Active for IE major version 7 or lower
590 // For example:
591 // X-UA-Compatible: IE=8; Chrome=IE6
593 // The string is first interpreted using ';' as a delimiter. It is reevaluated
594 // using ',' iff no valid 'chrome=' value is found.
595 bool CheckXUaCompatibleDirective(const std::string& directive,
596 int ie_major_version);
598 // Returns the version of the current module as a string.
599 std::wstring GetCurrentModuleVersion();
601 // Returns true if ChromeFrame is the currently loaded document.
602 bool IsChromeFrameDocument(IWebBrowser2* web_browser);
604 // Increases the wininet connection limit for HTTP 1.0/1.1 connections to the
605 // value passed in. This is only done if the existing connection limit is
606 // lesser than the connection limit passed in. This function attempts to
607 // increase the connection count once per process.
608 // Returns true on success.
609 bool IncreaseWinInetConnections(DWORD connections);
611 // Sets |profile_path| to the path for the Chrome Frame |profile_name|
612 // profile.
613 void GetChromeFrameProfilePath(const string16& profile_name,
614 base::FilePath* profile_path);
616 #endif // CHROME_FRAME_UTILS_H_