VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/common/webutils.py@ 72633

Last change on this file since 72633 was 72633, checked in by vboxsync, 6 years ago

webutils.py: Fixed the fNoProxies parameter for downloadFile(). [pylint]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 6.8 KB
Line 
1# -*- coding: utf-8 -*-
2# $Id: webutils.py 72633 2018-06-20 15:44:09Z vboxsync $
3
4"""
5Common Web Utility Functions.
6"""
7
8__copyright__ = \
9"""
10Copyright (C) 2012-2017 Oracle Corporation
11
12This file is part of VirtualBox Open Source Edition (OSE), as
13available from http://www.virtualbox.org. This file is free software;
14you can redistribute it and/or modify it under the terms of the GNU
15General Public License (GPL) as published by the Free Software
16Foundation, in version 2 as it comes in the "COPYING" file of the
17VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19
20The contents of this file may alternatively be used under the terms
21of the Common Development and Distribution License Version 1.0
22(CDDL) only, as it comes in the "COPYING.CDDL" file of the
23VirtualBox OSE distribution, in which case the provisions of the
24CDDL are applicable instead of those of the GPL.
25
26You may elect to license modified versions of this file under the
27terms and conditions of either the GPL or the CDDL or both.
28"""
29__version__ = "$Revision: 72633 $"
30
31# Standard Python imports.
32import os;
33import sys;
34import unittest;
35
36# Python 3 hacks:
37if sys.version_info[0] < 3:
38 from urllib2 import quote as urllib_quote; # pylint: disable=import-error,no-name-in-module
39 from urllib import urlencode as urllib_urlencode; # pylint: disable=import-error,no-name-in-module
40 from urllib import urlopen as urllib_urlopen; # pylint: disable=import-error,no-name-in-module
41else:
42 from urllib.parse import quote as urllib_quote; # pylint: disable=import-error,no-name-in-module
43 from urllib.parse import urlencode as urllib_urlencode; # pylint: disable=import-error,no-name-in-module
44 from urllib.request import urlopen as urllib_urlopen; # pylint: disable=import-error,no-name-in-module
45 import urllib.request; # pylint: disable=import-error,no-name-in-module
46
47# Validation Kit imports.
48from common import utils;
49
50
51def escapeElem(sText):
52 """
53 Escapes special character to HTML-safe sequences.
54 """
55 sText = sText.replace('&', '&amp;')
56 sText = sText.replace('<', '&lt;')
57 return sText.replace('>', '&gt;')
58
59def escapeAttr(sText):
60 """
61 Escapes special character to HTML-safe sequences.
62 """
63 sText = sText.replace('&', '&amp;')
64 sText = sText.replace('<', '&lt;')
65 sText = sText.replace('>', '&gt;')
66 return sText.replace('"', '&quot;')
67
68def escapeElemToStr(oObject):
69 """
70 Stringifies the object and hands it to escapeElem.
71 """
72 if utils.isString(oObject):
73 return escapeElem(oObject);
74 return escapeElem(str(oObject));
75
76def escapeAttrToStr(oObject):
77 """
78 Stringifies the object and hands it to escapeAttr. May return unicode string.
79 """
80 if utils.isString(oObject):
81 return escapeAttr(oObject);
82 return escapeAttr(str(oObject));
83
84def escapeAttrJavaScriptStringDQ(sText):
85 """ Escapes a javascript string that is to be emitted between double quotes. """
86 if '"' not in sText:
87 chMin = min(sText);
88 if ord(chMin) >= 0x20:
89 return sText;
90
91 sRet = '';
92 for ch in sText:
93 if ch == '"':
94 sRet += '\\"';
95 elif ord(ch) >= 0x20:
96 sRet += ch;
97 elif ch == '\n':
98 sRet += '\\n';
99 elif ch == '\r':
100 sRet += '\\r';
101 elif ch == '\t':
102 sRet += '\\t';
103 else:
104 sRet += '\\x%02x' % (ch,);
105 return sRet;
106
107def quoteUrl(sText):
108 """
109 See urllib.quote().
110 """
111 return urllib_quote(sText);
112
113def encodeUrlParams(dParams):
114 """
115 See urllib.urlencode().
116 """
117 return urllib_urlencode(dParams, doseq=True)
118
119def hasSchema(sUrl):
120 """
121 Checks if the URL has a schema (e.g. http://) or is file/server relative.
122 Returns True if schema is present, False if not.
123 """
124 iColon = sUrl.find(':');
125 if iColon > 0:
126 sSchema = sUrl[0:iColon];
127 if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower() and sSchema.isalpha():
128 return True;
129 return False;
130
131def getFilename(sUrl):
132 """
133 Extracts the filename from the URL.
134 """
135 ## @TODO This isn't entirely correct. Use the urlparser instead!
136 sFilename = os.path.basename(sUrl.replace('/', os.path.sep));
137 return sFilename;
138
139
140def downloadFile(sUrlFile, sDstFile, sLocalPrefix, fnLog, fnError = None, fNoProxies=True):
141 """
142 Downloads the given file if an URL is given, otherwise assume it's
143 something on the build share and copy it from there.
144
145 Raises no exceptions, returns log + success indicator instead.
146
147 Note! This method may use proxies configured on the system and the
148 http_proxy, ftp_proxy, no_proxy environment variables.
149
150 """
151 if fnError is None:
152 fnError = fnLog;
153
154 if sUrlFile.startswith('http://') \
155 or sUrlFile.startswith('https://') \
156 or sUrlFile.startswith('ftp://'):
157 # Download the file.
158 fnLog('Downloading "%s" to "%s"...' % (sUrlFile, sDstFile));
159 try:
160 ## @todo We get 404.html content instead of exceptions here, which is confusing and should be addressed.
161 if not fNoProxies:
162 oSrc = urllib_urlopen(sUrlFile);
163 elif sys.version_info[0] < 3:
164 oSrc = urllib_urlopen(sUrlFile, proxies = dict());
165 else:
166 oProxyHandler = urllib.request.ProxyHandler(proxies = dict()); # pylint: disable=no-member
167 oOpener = urllib.request.build_opener(oProxyHandler) # pylint: disable=no-member
168 oSrc = oOpener.open(sUrlFile);
169 oDst = utils.openNoInherit(sDstFile, 'wb');
170 oDst.write(oSrc.read());
171 oDst.close();
172 oSrc.close();
173 except Exception as oXcpt:
174 fnError('Error downloading "%s" to "%s": %s' % (sUrlFile, sDstFile, oXcpt));
175 return False;
176 else:
177 # Assumes file from the build share.
178 sSrcPath = os.path.join(sLocalPrefix, sUrlFile);
179 fnLog('Copying "%s" to "%s"...' % (sSrcPath, sDstFile));
180 try:
181 utils.copyFileSimple(sSrcPath, sDstFile);
182 except Exception as oXcpt:
183 fnError('Error copying "%s" to "%s": %s' % (sSrcPath, sDstFile, oXcpt));
184 return False;
185
186 return True;
187
188
189
190#
191# Unit testing.
192#
193
194# pylint: disable=C0111
195class CommonUtilsTestCase(unittest.TestCase):
196 def testHasSchema(self):
197 self.assertTrue(hasSchema('http://www.oracle.com/'));
198 self.assertTrue(hasSchema('https://virtualbox.com/'));
199 self.assertFalse(hasSchema('://virtualbox.com/'));
200 self.assertFalse(hasSchema('/usr/bin'));
201 self.assertFalse(hasSchema('usr/bin'));
202 self.assertFalse(hasSchema('bin'));
203 self.assertFalse(hasSchema('C:\\WINNT'));
204
205if __name__ == '__main__':
206 unittest.main();
207 # not reached.
208
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette