firefox_profile.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # Licensed to the Software Freedom Conservancy (SFC) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The SFC licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import with_statement
  18. import base64
  19. import copy
  20. import json
  21. import os
  22. import re
  23. import shutil
  24. import sys
  25. import tempfile
  26. import zipfile
  27. try:
  28. from cStringIO import StringIO as BytesIO
  29. except ImportError:
  30. from io import BytesIO
  31. from xml.dom import minidom
  32. from selenium.webdriver.common.proxy import ProxyType
  33. from selenium.common.exceptions import WebDriverException
  34. WEBDRIVER_EXT = "webdriver.xpi"
  35. WEBDRIVER_PREFERENCES = "webdriver_prefs.json"
  36. EXTENSION_NAME = "fxdriver@googlecode.com"
  37. class AddonFormatError(Exception):
  38. """Exception for not well-formed add-on manifest files"""
  39. class FirefoxProfile(object):
  40. ANONYMOUS_PROFILE_NAME = "WEBDRIVER_ANONYMOUS_PROFILE"
  41. DEFAULT_PREFERENCES = None
  42. def __init__(self, profile_directory=None):
  43. """
  44. Initialises a new instance of a Firefox Profile
  45. :args:
  46. - profile_directory: Directory of profile that you want to use.
  47. This defaults to None and will create a new
  48. directory when object is created.
  49. """
  50. if not FirefoxProfile.DEFAULT_PREFERENCES:
  51. with open(os.path.join(os.path.dirname(__file__),
  52. WEBDRIVER_PREFERENCES)) as default_prefs:
  53. FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs)
  54. self.default_preferences = copy.deepcopy(
  55. FirefoxProfile.DEFAULT_PREFERENCES['mutable'])
  56. self.native_events_enabled = True
  57. self.profile_dir = profile_directory
  58. self.tempfolder = None
  59. if self.profile_dir is None:
  60. self.profile_dir = self._create_tempfolder()
  61. else:
  62. self.tempfolder = tempfile.mkdtemp()
  63. newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy")
  64. shutil.copytree(self.profile_dir, newprof,
  65. ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock"))
  66. self.profile_dir = newprof
  67. self._read_existing_userjs(os.path.join(self.profile_dir, "user.js"))
  68. self.extensionsDir = os.path.join(self.profile_dir, "extensions")
  69. self.userPrefs = os.path.join(self.profile_dir, "user.js")
  70. # Public Methods
  71. def set_preference(self, key, value):
  72. """
  73. sets the preference that we want in the profile.
  74. """
  75. self.default_preferences[key] = value
  76. def add_extension(self, extension=WEBDRIVER_EXT):
  77. self._install_extension(extension)
  78. def update_preferences(self):
  79. for key, value in FirefoxProfile.DEFAULT_PREFERENCES['frozen'].items():
  80. self.default_preferences[key] = value
  81. self._write_user_prefs(self.default_preferences)
  82. # Properties
  83. @property
  84. def path(self):
  85. """
  86. Gets the profile directory that is currently being used
  87. """
  88. return self.profile_dir
  89. @property
  90. def port(self):
  91. """
  92. Gets the port that WebDriver is working on
  93. """
  94. return self._port
  95. @port.setter
  96. def port(self, port):
  97. """
  98. Sets the port that WebDriver will be running on
  99. """
  100. if not isinstance(port, int):
  101. raise WebDriverException("Port needs to be an integer")
  102. try:
  103. port = int(port)
  104. if port < 1 or port > 65535:
  105. raise WebDriverException("Port number must be in the range 1..65535")
  106. except (ValueError, TypeError):
  107. raise WebDriverException("Port needs to be an integer")
  108. self._port = port
  109. self.set_preference("webdriver_firefox_port", self._port)
  110. @property
  111. def accept_untrusted_certs(self):
  112. return self.default_preferences["webdriver_accept_untrusted_certs"]
  113. @accept_untrusted_certs.setter
  114. def accept_untrusted_certs(self, value):
  115. if value not in [True, False]:
  116. raise WebDriverException("Please pass in a Boolean to this call")
  117. self.set_preference("webdriver_accept_untrusted_certs", value)
  118. @property
  119. def assume_untrusted_cert_issuer(self):
  120. return self.default_preferences["webdriver_assume_untrusted_issuer"]
  121. @assume_untrusted_cert_issuer.setter
  122. def assume_untrusted_cert_issuer(self, value):
  123. if value not in [True, False]:
  124. raise WebDriverException("Please pass in a Boolean to this call")
  125. self.set_preference("webdriver_assume_untrusted_issuer", value)
  126. @property
  127. def native_events_enabled(self):
  128. return self.default_preferences['webdriver_enable_native_events']
  129. @native_events_enabled.setter
  130. def native_events_enabled(self, value):
  131. if value not in [True, False]:
  132. raise WebDriverException("Please pass in a Boolean to this call")
  133. self.set_preference("webdriver_enable_native_events", value)
  134. @property
  135. def encoded(self):
  136. """
  137. A zipped, base64 encoded string of profile directory
  138. for use with remote WebDriver JSON wire protocol
  139. """
  140. self.update_preferences()
  141. fp = BytesIO()
  142. zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED)
  143. path_root = len(self.path) + 1 # account for trailing slash
  144. for base, dirs, files in os.walk(self.path):
  145. for fyle in files:
  146. filename = os.path.join(base, fyle)
  147. zipped.write(filename, filename[path_root:])
  148. zipped.close()
  149. return base64.b64encode(fp.getvalue()).decode('UTF-8')
  150. def set_proxy(self, proxy):
  151. import warnings
  152. warnings.warn(
  153. "This method has been deprecated. Please pass in the proxy object to the Driver Object",
  154. DeprecationWarning)
  155. if proxy is None:
  156. raise ValueError("proxy can not be None")
  157. if proxy.proxy_type is ProxyType.UNSPECIFIED:
  158. return
  159. self.set_preference("network.proxy.type", proxy.proxy_type['ff_value'])
  160. if proxy.proxy_type is ProxyType.MANUAL:
  161. self.set_preference("network.proxy.no_proxies_on", proxy.no_proxy)
  162. self._set_manual_proxy_preference("ftp", proxy.ftp_proxy)
  163. self._set_manual_proxy_preference("http", proxy.http_proxy)
  164. self._set_manual_proxy_preference("ssl", proxy.ssl_proxy)
  165. self._set_manual_proxy_preference("socks", proxy.socks_proxy)
  166. elif proxy.proxy_type is ProxyType.PAC:
  167. self.set_preference("network.proxy.autoconfig_url", proxy.proxy_autoconfig_url)
  168. def _set_manual_proxy_preference(self, key, setting):
  169. if setting is None or setting is '':
  170. return
  171. host_details = setting.split(":")
  172. self.set_preference("network.proxy.%s" % key, host_details[0])
  173. if len(host_details) > 1:
  174. self.set_preference("network.proxy.%s_port" % key, int(host_details[1]))
  175. def _create_tempfolder(self):
  176. """
  177. Creates a temp folder to store User.js and the extension
  178. """
  179. return tempfile.mkdtemp()
  180. def _write_user_prefs(self, user_prefs):
  181. """
  182. writes the current user prefs dictionary to disk
  183. """
  184. with open(self.userPrefs, "w") as f:
  185. for key, value in user_prefs.items():
  186. f.write('user_pref("%s", %s);\n' % (key, json.dumps(value)))
  187. def _read_existing_userjs(self, userjs):
  188. import warnings
  189. PREF_RE = re.compile(r'user_pref\("(.*)",\s(.*)\)')
  190. try:
  191. with open(userjs) as f:
  192. for usr in f:
  193. matches = re.search(PREF_RE, usr)
  194. try:
  195. self.default_preferences[matches.group(1)] = json.loads(matches.group(2))
  196. except Exception:
  197. warnings.warn("(skipping) failed to json.loads existing preference: " +
  198. matches.group(1) + matches.group(2))
  199. except Exception:
  200. # The profile given hasn't had any changes made, i.e no users.js
  201. pass
  202. def _install_extension(self, addon, unpack=True):
  203. """
  204. Installs addon from a filepath, url
  205. or directory of addons in the profile.
  206. - path: url, path to .xpi, or directory of addons
  207. - unpack: whether to unpack unless specified otherwise in the install.rdf
  208. """
  209. if addon == WEBDRIVER_EXT:
  210. addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
  211. tmpdir = None
  212. xpifile = None
  213. if addon.endswith('.xpi'):
  214. tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1])
  215. compressed_file = zipfile.ZipFile(addon, 'r')
  216. for name in compressed_file.namelist():
  217. if name.endswith('/'):
  218. if not os.path.isdir(os.path.join(tmpdir, name)):
  219. os.makedirs(os.path.join(tmpdir, name))
  220. else:
  221. if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))):
  222. os.makedirs(os.path.dirname(os.path.join(tmpdir, name)))
  223. data = compressed_file.read(name)
  224. with open(os.path.join(tmpdir, name), 'wb') as f:
  225. f.write(data)
  226. xpifile = addon
  227. addon = tmpdir
  228. # determine the addon id
  229. addon_details = self._addon_details(addon)
  230. addon_id = addon_details.get('id')
  231. assert addon_id, 'The addon id could not be found: %s' % addon
  232. # copy the addon to the profile
  233. extensions_path = os.path.join(self.profile_dir, 'extensions')
  234. addon_path = os.path.join(extensions_path, addon_id)
  235. if not unpack and not addon_details['unpack'] and xpifile:
  236. if not os.path.exists(extensions_path):
  237. os.makedirs(extensions_path)
  238. shutil.copy(xpifile, addon_path + '.xpi')
  239. else:
  240. if not os.path.exists(addon_path):
  241. shutil.copytree(addon, addon_path, symlinks=True)
  242. # remove the temporary directory, if any
  243. if tmpdir:
  244. shutil.rmtree(tmpdir)
  245. def _addon_details(self, addon_path):
  246. """
  247. Returns a dictionary of details about the addon.
  248. :param addon_path: path to the add-on directory or XPI
  249. Returns::
  250. {'id': u'rainbow@colors.org', # id of the addon
  251. 'version': u'1.4', # version of the addon
  252. 'name': u'Rainbow', # name of the addon
  253. 'unpack': False } # whether to unpack the addon
  254. """
  255. details = {
  256. 'id': None,
  257. 'unpack': False,
  258. 'name': None,
  259. 'version': None
  260. }
  261. def get_namespace_id(doc, url):
  262. attributes = doc.documentElement.attributes
  263. namespace = ""
  264. for i in range(attributes.length):
  265. if attributes.item(i).value == url:
  266. if ":" in attributes.item(i).name:
  267. # If the namespace is not the default one remove 'xlmns:'
  268. namespace = attributes.item(i).name.split(':')[1] + ":"
  269. break
  270. return namespace
  271. def get_text(element):
  272. """Retrieve the text value of a given node"""
  273. rc = []
  274. for node in element.childNodes:
  275. if node.nodeType == node.TEXT_NODE:
  276. rc.append(node.data)
  277. return ''.join(rc).strip()
  278. if not os.path.exists(addon_path):
  279. raise IOError('Add-on path does not exist: %s' % addon_path)
  280. try:
  281. if zipfile.is_zipfile(addon_path):
  282. # Bug 944361 - We cannot use 'with' together with zipFile because
  283. # it will cause an exception thrown in Python 2.6.
  284. try:
  285. compressed_file = zipfile.ZipFile(addon_path, 'r')
  286. manifest = compressed_file.read('install.rdf')
  287. finally:
  288. compressed_file.close()
  289. elif os.path.isdir(addon_path):
  290. with open(os.path.join(addon_path, 'install.rdf'), 'r') as f:
  291. manifest = f.read()
  292. else:
  293. raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path)
  294. except (IOError, KeyError) as e:
  295. raise AddonFormatError(str(e), sys.exc_info()[2])
  296. try:
  297. doc = minidom.parseString(manifest)
  298. # Get the namespaces abbreviations
  299. em = get_namespace_id(doc, 'http://www.mozilla.org/2004/em-rdf#')
  300. rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
  301. description = doc.getElementsByTagName(rdf + 'Description').item(0)
  302. if description is None:
  303. description = doc.getElementsByTagName('Description').item(0)
  304. for node in description.childNodes:
  305. # Remove the namespace prefix from the tag for comparison
  306. entry = node.nodeName.replace(em, "")
  307. if entry in details.keys():
  308. details.update({entry: get_text(node)})
  309. if details.get('id') is None:
  310. for i in range(description.attributes.length):
  311. attribute = description.attributes.item(i)
  312. if attribute.name == em + 'id':
  313. details.update({'id': attribute.value})
  314. except Exception as e:
  315. raise AddonFormatError(str(e), sys.exc_info()[2])
  316. # turn unpack into a true/false value
  317. if isinstance(details['unpack'], str):
  318. details['unpack'] = details['unpack'].lower() == 'true'
  319. # If no ID is set, the add-on is invalid
  320. if details.get('id') is None:
  321. raise AddonFormatError('Add-on id could not be found.')
  322. return details