chromeos: dbus: add Bluetooth properties support
[chromium-blink-merge.git] / chrome_frame / utils.h
blobb3899c380612d5d31b2b63d0c7c7675afb95bcd0
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/threading/thread.h"
19 #include "base/win/scoped_comptr.h"
20 #include "googleurl/src/gurl.h"
21 #include "ui/gfx/rect.h"
23 class FilePath;
24 interface IBrowserService;
25 interface IWebBrowser2;
26 struct ContextMenuModel;
28 // utils.h : Various utility functions and classes
30 extern const wchar_t kChromeContentPrefix[];
31 extern const char kGCFProtocol[];
32 extern const wchar_t kChromeProtocolPrefix[];
33 extern const wchar_t kChromeFrameHeadlessMode[];
34 extern const wchar_t kChromeFrameAccessibleMode[];
35 extern const wchar_t kChromeFrameUnpinnedMode[];
36 extern const wchar_t kAllowUnsafeURLs[];
37 extern const wchar_t kEnableBuggyBhoIntercept[];
38 extern const wchar_t kChromeMimeType[];
39 extern const wchar_t kChromeFrameAttachTabPattern[];
40 extern const wchar_t kChromeFrameConfigKey[];
41 extern const wchar_t kRenderInGCFUrlList[];
42 extern const wchar_t kRenderInHostUrlList[];
43 extern const wchar_t kEnableGCFRendererByDefault[];
44 extern const wchar_t kIexploreProfileName[];
45 extern const wchar_t kRundllProfileName[];
46 extern const wchar_t kUseBackgroundThreadForSubResources[];
48 // This function is very similar to the AtlRegisterTypeLib function except
49 // that it takes a parameter that specifies whether to register the typelib
50 // for the current user only or on a machine-wide basis
51 // Refer to the MSDN documentation for AtlRegisterTypeLib for a description of
52 // the arguments
53 HRESULT UtilRegisterTypeLib(HINSTANCE tlb_instance,
54 LPCOLESTR index,
55 bool for_current_user_only);
57 // This function is very similar to the AtlUnRegisterTypeLib function except
58 // that it takes a parameter that specifies whether to unregister the typelib
59 // for the current user only or on a machine-wide basis
60 // Refer to the MSDN documentation for AtlUnRegisterTypeLib for a description
61 // of the arguments
62 HRESULT UtilUnRegisterTypeLib(HINSTANCE tlb_instance,
63 LPCOLESTR index,
64 bool for_current_user_only);
66 HRESULT UtilRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
68 HRESULT UtilUnRegisterTypeLib(LPCWSTR typelib_path, bool for_current_user_only);
70 HRESULT UtilRegisterTypeLib(ITypeLib* typelib,
71 LPCWSTR typelib_path,
72 LPCWSTR help_dir,
73 bool for_current_user_only);
75 HRESULT UtilUnRegisterTypeLib(ITypeLib* typelib,
76 bool for_current_user_only);
78 // Clears a marker that causes legacy NPAPI registration to persist across
79 // updates. Returns false if the marker could not be removed.
80 bool UtilRemovePersistentNPAPIMarker();
82 // Given an HTML fragment, this function looks for the
83 // <meta http-equiv="X-UA-Compatible"> tag and extracts the value of the
84 // "content" attribute
85 // This method will currently return a false positive if the tag appears
86 // inside a string in a <SCRIPT> block.
87 HRESULT UtilGetXUACompatContentValue(const std::wstring& html_string,
88 std::wstring* content_value);
90 // Returns a string from ChromeFrame's string table by resource. Must be
91 // provided with a valid resource id.
92 std::wstring GetResourceString(int resource_id);
94 // Displays a message box indicating that there was a version mismatch between
95 // ChromeFrame and the running instance of Chrome.
96 // server_version is the version of the running instance of Chrome.
97 void DisplayVersionMismatchWarning(HWND parent,
98 const std::string& server_version);
100 // This class provides a base implementation for ATL modules which want to
101 // perform all their registration under HKCU. This class overrides the
102 // RegisterServer and UnregisterServer methods and registers the type libraries
103 // under HKCU (the rest of the registration is made under HKCU by changing the
104 // appropriate .RGS files)
105 template < class BaseAtlModule >
106 class AtlPerUserModule : public BaseAtlModule {
107 public:
108 HRESULT RegisterServer(BOOL reg_typelib = FALSE,
109 const CLSID* clsid = NULL) throw() {
110 HRESULT hr = BaseAtlModule::RegisterServer(FALSE, clsid);
111 if (FAILED(hr)) {
112 return hr;
114 if (reg_typelib) {
115 hr = UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
117 return hr;
120 HRESULT UnregisterServer(BOOL unreg_typelib,
121 const CLSID* clsid = NULL) throw() {
122 HRESULT hr = BaseAtlModule::UnregisterServer(FALSE, clsid);
123 if (FAILED(hr)) {
124 return hr;
126 if (unreg_typelib) {
127 hr = UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib, NULL, false);
129 return hr;
133 // Creates a javascript statement for execution from the function name and
134 // arguments passed in.
135 std::string CreateJavascript(const std::string& function_name,
136 const std::string args);
138 // Use to prevent the DLL from being unloaded while there are still living
139 // objects with outstanding references.
140 class AddRefModule {
141 public:
142 AddRefModule();
143 ~AddRefModule();
146 // Retrieves the executable name of the process hosting us. If
147 // |include_extension| is false, then we strip the extension from the name.
148 std::wstring GetHostProcessName(bool include_extension);
150 typedef enum BrowserType {
151 BROWSER_INVALID = -1,
152 BROWSER_UNKNOWN,
153 BROWSER_IE,
156 BrowserType GetBrowserType();
158 typedef enum IEVersion {
159 IE_INVALID,
160 NON_IE,
161 IE_UNSUPPORTED,
162 IE_6,
163 IE_7,
164 IE_8,
165 IE_9,
166 IE_10,
169 // The renderer to be used for a page. Values for Chrome also convey the
170 // reason why Chrome is used.
171 enum RendererType {
172 RENDERER_TYPE_UNDETERMINED = 0,
173 RENDERER_TYPE_CHROME_MIN,
174 // NOTE: group all _CHROME_ values together below here, as they are used for
175 // generating metrics reported via UMA (adjust MIN/MAX as needed).
176 RENDERER_TYPE_CHROME_GCF_PROTOCOL = RENDERER_TYPE_CHROME_MIN,
177 RENDERER_TYPE_CHROME_HTTP_EQUIV,
178 RENDERER_TYPE_CHROME_RESPONSE_HEADER,
179 RENDERER_TYPE_CHROME_DEFAULT_RENDERER,
180 RENDERER_TYPE_CHROME_OPT_IN_URL,
181 RENDERER_TYPE_CHROME_WIDGET,
182 // NOTE: all _CHOME_ values must go above here (adjust MIN/MAX as needed).
183 RENDERER_TYPE_CHROME_MAX = RENDERER_TYPE_CHROME_WIDGET,
184 RENDERER_TYPE_OTHER,
187 // Returns true if the given RendererType represents Chrome.
188 bool IsChrome(RendererType renderer_type);
190 // Convenience macro for logging a sample for the launch type metric.
191 #define UMA_LAUNCH_TYPE_COUNT(sample) \
192 UMA_HISTOGRAM_CUSTOM_COUNTS("ChromeFrame.LaunchType", sample, \
193 RENDERER_TYPE_CHROME_MIN, RENDERER_TYPE_CHROME_MAX, \
194 RENDERER_TYPE_CHROME_MAX + 1 - RENDERER_TYPE_CHROME_MIN)
196 // To get the IE version when Chrome Frame is hosted in IE. Make sure that
197 // the hosting browser is IE before calling this function, otherwise NON_IE
198 // will be returned.
200 // Versions newer than the newest supported version are reported as the newest
201 // supported version.
202 IEVersion GetIEVersion();
204 // Returns the actual major version of the IE in which the current process is
205 // hosted. Returns 0 if the current process is not IE or any other error occurs.
206 uint32 GetIEMajorVersion();
208 FilePath GetIETemporaryFilesFolder();
210 // Retrieves the file version from a module handle without extra round trips
211 // to the disk (as happens with the regular GetFileVersionInfo API).
213 // @param module A handle to the module for which to retrieve the version info.
214 // @param high On successful return holds the most significant part of the file
215 // version. Must be non-null.
216 // @param low On successful return holds the least significant part of the file
217 // version. May be NULL.
218 // @returns true if the version info was successfully retrieved.
219 bool GetModuleVersion(HMODULE module, uint32* high, uint32* low);
221 // Return if the IEXPLORE is in private mode. The IEIsInPrivateBrowsing() checks
222 // whether current process is IEXPLORE.
223 bool IsIEInPrivate();
225 // Calls [ieframe|shdocvw]!DoFileDownload to initiate a download.
226 HRESULT DoFileDownloadInIE(const wchar_t* url);
228 // Construct a menu from the model sent from Chrome.
229 HMENU BuildContextMenu(const ContextMenuModel& menu_model);
231 // Uses GURL internally to append 'relative' to 'document'
232 std::string ResolveURL(const std::string& document,
233 const std::string& relative);
235 // Returns true iff the two urls have the same scheme, same host and same port.
236 bool HaveSameOrigin(const std::string& url1, const std::string& url2);
238 // Get a boolean configuration value from registry.
239 bool GetConfigBool(bool default_value, const wchar_t* value_name);
241 // Gets an integer configuration value from the registry.
242 int GetConfigInt(int default_value, const wchar_t* value_name);
244 // Sets an integer configuration value in the registry.
245 bool SetConfigInt(const wchar_t* value_name, int value);
247 // Sets a boolean integer configuration value in the registry.
248 bool SetConfigBool(const wchar_t* value_name, bool value);
250 // Deletes the configuration value passed in.
251 bool DeleteConfigValue(const wchar_t* value_name);
253 // Returns true if we are running in headless mode in which case we need to
254 // gather crash dumps, etc to send them to the crash server.
255 bool IsHeadlessMode();
257 // Returns true if we are running in accessible mode in which we need to enable
258 // renderer accessibility for use in automation.
259 bool IsAccessibleMode();
261 // Returns true if we are running in unpinned mode in which case DLL
262 // eviction should be possible.
263 bool IsUnpinnedMode();
265 // Returns true if all HTML pages should be rendered in GCF by default.
266 bool IsGcfDefaultRenderer();
268 // Check if this url is opting into Chrome Frame based on static settings.
269 // Returns one of:
270 // - RENDERER_TYPE_UNDETERMINED if not opt-in or if explicit opt-out
271 // - RENDERER_TYPE_CHROME_DEFAULT_RENDERER
272 // - RENDERER_TYPE_CHROME_OPT_IN_URL
273 RendererType RendererTypeForUrl(const std::wstring& url);
275 // A shortcut for QueryService
276 template <typename T>
277 HRESULT DoQueryService(const IID& service_id, IUnknown* unk, T** service) {
278 DCHECK(service);
279 if (!unk)
280 return E_INVALIDARG;
282 base::win::ScopedComPtr<IServiceProvider> service_provider;
283 HRESULT hr = service_provider.QueryFrom(unk);
284 if (service_provider)
285 hr = service_provider->QueryService(service_id, service);
287 DCHECK(FAILED(hr) || *service);
288 return hr;
291 // Navigates an IWebBrowser2 object to a moniker.
292 // |headers| can be NULL.
293 HRESULT NavigateBrowserToMoniker(IUnknown* browser, IMoniker* moniker,
294 const wchar_t* headers, IBindCtx* bind_ctx,
295 const wchar_t* fragment, IStream* post_data,
296 VARIANT* flags);
298 // Raises a flag on the current thread (using TLS) to indicate that an
299 // in-progress navigation should be rendered in chrome frame.
300 void MarkBrowserOnThreadForCFNavigation(IBrowserService* browser);
302 // Checks if this browser instance has been marked as currently navigating
303 // to a CF document. If clear_flag is set to true, the tls flag is cleared but
304 // only if the browser has been marked.
305 bool CheckForCFNavigation(IBrowserService* browser, bool clear_flag);
307 // Returns true if the URL passed in is something which can be handled by
308 // Chrome. If this function returns false then we should fail the navigation.
309 // When is_privileged is true, chrome extension URLs will be considered valid.
310 bool IsValidUrlScheme(const GURL& url, bool is_privileged);
312 // Returns the raw http headers for the current request given an
313 // IWinInetHttpInfo pointer.
314 std::string GetRawHttpHeaders(IWinInetHttpInfo* info);
316 // Can be used to determine whether a given request is being performed for
317 // a sub-frame or iframe in Internet Explorer. This can be called
318 // from various places, notably in request callbacks and the like.
320 // |service_provider| must not be NULL and should be a pointer to something
321 // that implements IServiceProvider (if it isn't this method returns false).
323 // Returns true if this method can determine with some certainty that the
324 // request did NOT originate from a top level frame, returns false otherwise.
325 bool IsSubFrameRequest(IUnknown* service_provider);
327 // See COM_INTERFACE_BLIND_DELEGATE below for details.
328 template <class T>
329 STDMETHODIMP CheckOutgoingInterface(void* obj, REFIID iid, void** ret,
330 DWORD cookie) {
331 T* instance = reinterpret_cast<T*>(obj);
332 HRESULT hr = E_NOINTERFACE;
333 IUnknown* delegate = instance ? instance->delegate() : NULL;
334 if (delegate) {
335 hr = delegate->QueryInterface(iid, ret);
336 #if !defined(NDEBUG)
337 if (SUCCEEDED(hr)) {
338 wchar_t iid_string[64] = {0};
339 StringFromGUID2(iid, iid_string, arraysize(iid_string));
340 DVLOG(1) << __FUNCTION__ << " Giving out wrapped interface: "
341 << iid_string;
343 #endif
346 return hr;
349 // See COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS below for details.
350 template <class T>
351 STDMETHODIMP QueryInterfaceIfDelegateSupports(void* obj, REFIID iid,
352 void** ret, DWORD cookie) {
353 HRESULT hr = E_NOINTERFACE;
354 T* instance = reinterpret_cast<T*>(obj);
355 IUnknown* delegate = instance ? instance->delegate() : NULL;
356 if (delegate) {
357 base::win::ScopedComPtr<IUnknown> original;
358 hr = delegate->QueryInterface(iid,
359 reinterpret_cast<void**>(original.Receive()));
360 if (original) {
361 IUnknown* supported_interface = reinterpret_cast<IUnknown*>(
362 reinterpret_cast<DWORD_PTR>(obj) + cookie);
363 supported_interface->AddRef();
364 *ret = supported_interface;
365 hr = S_OK;
369 return hr;
372 // Same as COM_INTERFACE_ENTRY but relies on the class to implement a
373 // delegate() method that returns a pointer to the delegated COM object.
374 #define COM_INTERFACE_ENTRY_IF_DELEGATE_SUPPORTS(x) \
375 COM_INTERFACE_ENTRY_FUNC(_ATL_IIDOF(x), \
376 offsetofclass(x, _ComMapClass), \
377 QueryInterfaceIfDelegateSupports<_ComMapClass>)
379 // Queries the delegated COM object for an interface, bypassing the wrapper.
380 #define COM_INTERFACE_BLIND_DELEGATE() \
381 COM_INTERFACE_ENTRY_FUNC_BLIND(0, CheckOutgoingInterface<_ComMapClass>)
383 // Thread that enters STA and has a UI message loop.
384 class STAThread : public base::Thread {
385 public:
386 explicit STAThread(const char *name) : Thread(name) {}
387 ~STAThread() {
388 Stop();
390 bool Start() {
391 return StartWithOptions(Options(MessageLoop::TYPE_UI, 0));
393 protected:
394 // Called just prior to starting the message loop
395 virtual void Init() {
396 ::CoInitialize(0);
399 // Called just after the message loop ends
400 virtual void CleanUp() {
401 ::CoUninitialize();
405 std::wstring GuidToString(const GUID& guid);
407 // The urls retrieved from the IMoniker interface don't contain the anchor
408 // portion of the actual url navigated to. This function checks whether the
409 // url passed in the bho_url parameter contains an anchor and if yes checks
410 // whether it matches the url retrieved from the moniker. If yes it returns
411 // the bho url, if not the moniker url.
412 std::wstring GetActualUrlFromMoniker(IMoniker* moniker,
413 IBindCtx* bind_context,
414 const std::wstring& bho_url);
416 // Checks if a window is a top level window
417 bool IsTopLevelWindow(HWND window);
419 // Seeks a stream back to position 0.
420 HRESULT RewindStream(IStream* stream);
422 // Fired when we want to notify IE about privacy changes.
423 #define WM_FIRE_PRIVACY_CHANGE_NOTIFICATION (WM_APP + 1)
425 // Sent (not posted) when a request needs to be downloaded in the host browser
426 // instead of Chrome. WPARAM is 0 and LPARAM is a pointer to an IMoniker
427 // object.
428 // NOTE: Since the message is sent synchronously, the handler should only
429 // start asynchronous operations in order to not block the sender unnecessarily.
430 #define WM_DOWNLOAD_IN_HOST (WM_APP + 2)
432 // This structure contains the parameters sent over to initiate a download
433 // request in the host browser.
434 struct DownloadInHostParams {
435 base::win::ScopedComPtr<IBindCtx> bind_ctx;
436 base::win::ScopedComPtr<IMoniker> moniker;
437 base::win::ScopedComPtr<IStream> post_data;
438 std::string request_headers;
441 // Maps the InternetCookieState enum to the corresponding CookieAction values
442 // used for IE privacy stuff.
443 int32 MapCookieStateToCookieAction(InternetCookieState cookie_state);
445 // Parses the url passed in and returns a GURL instance without the fragment.
446 GURL GetUrlWithoutFragment(const wchar_t* url);
448 // Compares the URLs passed in after removing the fragments from them.
449 bool CompareUrlsWithoutFragment(const wchar_t* url1, const wchar_t* url2);
451 // Returns the Referrer from the HTTP headers and additional headers.
452 std::string FindReferrerFromHeaders(const wchar_t* headers,
453 const wchar_t* additional_headers);
455 // Returns the HTTP headers from the binding passed in.
456 std::string GetHttpHeadersFromBinding(IBinding* binding);
458 // Returns the HTTP response code from the binding passed in.
459 int GetHttpResponseStatusFromBinding(IBinding* binding);
461 // Returns the clipboard format for text/html.
462 CLIPFORMAT GetTextHtmlClipboardFormat();
464 // Returns true iff the mime type is text/html.
465 bool IsTextHtmlMimeType(const wchar_t* mime_type);
467 // Returns true iff the clipboard format is text/html.
468 bool IsTextHtmlClipFormat(CLIPFORMAT cf);
470 // Returns true if we can detect that we are running as SYSTEM, false otherwise.
471 bool IsSystemProcess();
473 // STL helper class that implements a functor to delete objects.
474 // E.g: std::for_each(v.begin(), v.end(), utils::DeleteObject());
475 namespace utils {
476 class DeleteObject {
477 public:
478 template <typename T>
479 void operator()(T* obj) {
480 delete obj;
485 // Convert various protocol flags to text representation. Used for logging.
486 std::string BindStatus2Str(ULONG bind_status);
487 std::string PiFlags2Str(DWORD flags);
488 std::string Bscf2Str(DWORD flags);
490 // Reads data from a stream into a string.
491 HRESULT ReadStream(IStream* stream, size_t size, std::string* data);
493 // Parses urls targeted at ChromeFrame. This class maintains state like
494 // whether a url is prefixed with the gcf: prefix, whether it is being
495 // attached to an existing external tab, etc.
496 class ChromeFrameUrl {
497 public:
498 ChromeFrameUrl();
500 // Parses the url passed in. Returns true on success.
501 bool Parse(const std::wstring& url);
503 bool is_chrome_protocol() const {
504 return is_chrome_protocol_;
507 bool attach_to_external_tab() const {
508 return attach_to_external_tab_;
511 uint64 cookie() const {
512 return cookie_;
515 int disposition() const {
516 return disposition_;
519 const gfx::Rect& dimensions() const {
520 return dimensions_;
523 const GURL& gurl() const {
524 return parsed_url_;
527 const std::string& profile_name() const {
528 return profile_name_;
531 private:
532 // If we are attaching to an existing external tab, this function parses the
533 // suffix portion of the URL which contains the attach_external_tab prefix.
534 bool ParseAttachExternalTabUrl();
536 // Clear state.
537 void Reset();
539 bool attach_to_external_tab_;
540 bool is_chrome_protocol_;
541 uint64 cookie_;
542 gfx::Rect dimensions_;
543 int disposition_;
545 GURL parsed_url_;
546 std::string profile_name_;
549 class NavigationConstraints;
550 // Returns true if we can navigate to this URL.
551 // These decisions are controlled by the NavigationConstraints object passed
552 // in.
553 bool CanNavigate(const GURL& url,
554 NavigationConstraints* navigation_constraints);
556 // Utility function that prevents the current module from ever being unloaded.
557 // Call if you make irreversible patches.
558 void PinModule();
560 // Helper function to spin a message loop and dispatch messages while waiting
561 // for a handle to be signaled.
562 void WaitWithMessageLoop(HANDLE* handles, int count, DWORD timeout);
564 // Enumerates values in a key and adds them to an array.
565 // The names of the values are not returned.
566 void EnumerateKeyValues(HKEY parent_key, const wchar_t* sub_key_name,
567 std::vector<std::wstring>* values);
569 // Interprets the value of an X-UA-Compatible header (or <meta> tag equivalent)
570 // and indicates whether the header value contains a Chrome Frame directive
571 // matching a given host browser version.
573 // The header is a series of name-value pairs, with the names being HTTP tokens
574 // and the values being either tokens or quoted-strings. Names and values are
575 // joined by '=' and pairs are delimited by either ';' or ','. LWS may be used
576 // liberally before and between names, values, '=', and ';' or ','. See RFC 2616
577 // for definitions of token, quoted-string, and LWS. See Microsoft's
578 // documentation of the X-UA-COMPATIBLE header here:
579 // http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx
581 // At most one 'Chrome=<FILTER>' entry is expected in the header value. The
582 // first valid instance is used. The value of "<FILTER>" (possibly after
583 // unquoting) is interpreted as follows:
585 // "1" - Always active
586 // "IE7" - Active for IE major version 7 or lower
588 // For example:
589 // X-UA-Compatible: IE=8; Chrome=IE6
591 // The string is first interpreted using ';' as a delimiter. It is reevaluated
592 // using ',' iff no valid 'chrome=' value is found.
593 bool CheckXUaCompatibleDirective(const std::string& directive,
594 int ie_major_version);
596 // Returns the version of the current module as a string.
597 std::wstring GetCurrentModuleVersion();
599 // Returns true if ChromeFrame is the currently loaded document.
600 bool IsChromeFrameDocument(IWebBrowser2* web_browser);
602 // Increases the wininet connection limit for HTTP 1.0/1.1 connections to the
603 // value passed in. This is only done if the existing connection limit is
604 // lesser than the connection limit passed in. This function attempts to
605 // increase the connection count once per process.
606 // Returns true on success.
607 bool IncreaseWinInetConnections(DWORD connections);
609 #endif // CHROME_FRAME_UTILS_H_