re-introduce old nss im too tired for this

This commit is contained in:
wuggy 2026-06-30 06:37:32 +01:00
commit 3a838106b9
2871 changed files with 1374431 additions and 1762417 deletions

169
security/nss/gtests/google_test/gtest/scripts/upload.py Executable file → Normal file
View file

@ -1,33 +1,18 @@
#!/usr/bin/env python
#
# Copyright 2007, Google Inc.
# All rights reserved.
# Copyright 2007 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# http://www.apache.org/licenses/LICENSE-2.0
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool for uploading diffs from a version control system to the codereview app.
@ -46,7 +31,7 @@ against by using the '--rev' option.
# This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306.
import http.cookiejar
import cookielib
import getpass
import logging
import md5
@ -57,9 +42,9 @@ import re
import socket
import subprocess
import sys
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import urllib.parse
import urllib
import urllib2
import urlparse
try:
import readline
@ -94,15 +79,15 @@ def GetEmail(prompt):
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
except IOError as e:
except IOError, e:
pass
email = input(prompt + ": ").strip()
email = raw_input(prompt + ": ").strip()
if email:
try:
last_email_file = open(last_email_file_name, "w")
last_email_file.write(email)
last_email_file.close()
except IOError as e:
except IOError, e:
pass
else:
email = last_email
@ -118,20 +103,20 @@ def StatusUpdate(msg):
msg: The string to print.
"""
if verbosity > 0:
print(msg)
print msg
def ErrorExit(msg):
"""Print an error message to stderr and exit."""
print(msg, file=sys.stderr)
print >>sys.stderr, msg
sys.exit(1)
class ClientLoginError(urllib.error.HTTPError):
class ClientLoginError(urllib2.HTTPError):
"""Raised to indicate there was an error authenticating with ClientLogin."""
def __init__(self, url, code, msg, headers, args):
urllib.error.HTTPError.__init__(self, url, code, msg, headers, None)
urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
self.args = args
self.reason = args["Error"]
@ -177,10 +162,10 @@ class AbstractRpcServer(object):
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib.request.Request(url, data=data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.items():
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req
@ -204,7 +189,7 @@ class AbstractRpcServer(object):
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/accounts/ClientLogin",
data=urllib.parse.urlencode({
data=urllib.urlencode({
"Email": email,
"Passwd": password,
"service": "ah",
@ -218,7 +203,7 @@ class AbstractRpcServer(object):
response_dict = dict(x.split("=")
for x in response_body.split("\n") if x)
return response_dict["Auth"]
except urllib.error.HTTPError as e:
except urllib2.HTTPError, e:
if e.code == 403:
body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
@ -240,14 +225,14 @@ class AbstractRpcServer(object):
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("http://%s/_ah/login?%s" %
(self.host, urllib.parse.urlencode(args)))
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib.error.HTTPError as e:
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib.error.HTTPError(req.get_full_url(), response.code, response.msg,
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True
@ -270,34 +255,34 @@ class AbstractRpcServer(object):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError as e:
except ClientLoginError, e:
if e.reason == "BadAuthentication":
print("Invalid username or password.", file=sys.stderr)
print >>sys.stderr, "Invalid username or password."
continue
if e.reason == "CaptchaRequired":
print((
print >>sys.stderr, (
"Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again."), file=sys.stderr)
"and verify you are a human. Then try again.")
break
if e.reason == "NotVerified":
print("Account not verified.", file=sys.stderr)
print >>sys.stderr, "Account not verified."
break
if e.reason == "TermsNotAgreed":
print("User has not agreed to TOS.", file=sys.stderr)
print >>sys.stderr, "User has not agreed to TOS."
break
if e.reason == "AccountDeleted":
print("The user account has been deleted.", file=sys.stderr)
print >>sys.stderr, "The user account has been deleted."
break
if e.reason == "AccountDisabled":
print("The user account has been disabled.", file=sys.stderr)
print >>sys.stderr, "The user account has been disabled."
break
if e.reason == "ServiceDisabled":
print(("The user's access to the service has been "
"disabled."), file=sys.stderr)
print >>sys.stderr, ("The user's access to the service has been "
"disabled.")
break
if e.reason == "ServiceUnavailable":
print("The service is not available; try again later.", file=sys.stderr)
print >>sys.stderr, "The service is not available; try again later."
break
raise
self._GetAuthCookie(auth_token)
@ -334,7 +319,7 @@ class AbstractRpcServer(object):
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.parse.urlencode(args)
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
@ -342,7 +327,7 @@ class AbstractRpcServer(object):
response = f.read()
f.close()
return response
except urllib.error.HTTPError as e:
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
@ -372,35 +357,35 @@ class HttpRpcServer(AbstractRpcServer):
Returns:
A urllib2.OpenerDirector object.
"""
opener = urllib.request.OpenerDirector()
opener.add_handler(urllib.request.ProxyHandler())
opener.add_handler(urllib.request.UnknownHandler())
opener.add_handler(urllib.request.HTTPHandler())
opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
opener.add_handler(urllib.request.HTTPSHandler())
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
if self.save_cookies:
self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
self.cookie_jar = http.cookiejar.MozillaCookieJar(self.cookie_file)
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
if os.path.exists(self.cookie_file):
try:
self.cookie_jar.load()
self.authenticated = True
StatusUpdate("Loaded authentication cookies from %s" %
self.cookie_file)
except (http.cookiejar.LoadError, IOError):
except (cookielib.LoadError, IOError):
# Failed to load cookies - just ignore them.
pass
else:
# Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0o600)
fd = os.open(self.cookie_file, os.O_CREAT, 0600)
os.close(fd)
# Always chmod the cookie file
os.chmod(self.cookie_file, 0o600)
os.chmod(self.cookie_file, 0600)
else:
# Don't save cookies across runs of update.py.
self.cookie_jar = http.cookiejar.CookieJar()
opener.add_handler(urllib.request.HTTPCookieProcessor(self.cookie_jar))
self.cookie_jar = cookielib.CookieJar()
opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
return opener
@ -575,7 +560,7 @@ def RunShellWithReturnCode(command, print_output=False,
line = p.stdout.readline()
if not line:
break
print(line.strip("\n"))
print line.strip("\n")
output_array.append(line)
output = "".join(output_array)
else:
@ -583,7 +568,7 @@ def RunShellWithReturnCode(command, print_output=False,
p.wait()
errout = p.stderr.read()
if print_output and errout:
print(errout, file=sys.stderr)
print >>sys.stderr, errout
p.stdout.close()
p.stderr.close()
return output, p.returncode
@ -629,11 +614,11 @@ class VersionControlSystem(object):
"""Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles()
if unknown_files:
print("The following files are not added to version control:")
print "The following files are not added to version control:"
for line in unknown_files:
print(line)
print line
prompt = "Are you sure to continue?(y/N) "
answer = input(prompt).strip()
answer = raw_input(prompt).strip()
if answer != "y":
ErrorExit("User aborted")
@ -685,13 +670,13 @@ class VersionControlSystem(object):
else:
type = "current"
if len(content) > MAX_UPLOAD_SIZE:
print(("Not uploading the %s file for %s because it's too large." %
(type, filename)))
print ("Not uploading the %s file for %s because it's too large." %
(type, filename))
file_too_large = True
content = ""
checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large:
print("Uploading %s file for %s" % (type, filename))
print "Uploading %s file for %s" % (type, filename)
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename),
("status", status),
@ -713,7 +698,7 @@ class VersionControlSystem(object):
patches = dict()
[patches.setdefault(v, k) for k, v in patch_list]
for filename in list(patches.keys()):
for filename in patches.keys():
base_content, new_content, is_binary, status = files[filename]
file_id_str = patches.get(filename)
if file_id_str.find("nobase") != -1:
@ -770,8 +755,8 @@ class SubversionVCS(VersionControlSystem):
words = line.split()
if len(words) == 2 and words[0] == "URL:":
url = words[1]
scheme, netloc, path, params, query, fragment = urllib.parse.urlparse(url)
username, netloc = urllib.parse.splituser(netloc)
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
username, netloc = urllib.splituser(netloc)
if username:
logging.info("Removed username from base URL")
if netloc.endswith("svn.python.org"):
@ -789,12 +774,12 @@ class SubversionVCS(VersionControlSystem):
logging.info("Guessed CollabNet base = %s", base)
elif netloc.endswith(".googlecode.com"):
path = path + "/"
base = urllib.parse.urlunparse(("http", netloc, path, params,
base = urlparse.urlunparse(("http", netloc, path, params,
query, fragment))
logging.info("Guessed Google Code base = %s", base)
else:
path = path + "/"
base = urllib.parse.urlunparse((scheme, netloc, path, params,
base = urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
logging.info("Guessed base = %s", base)
return base
@ -1202,8 +1187,8 @@ def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
rv = []
for patch in patches:
if len(patch[1]) > MAX_UPLOAD_SIZE:
print(("Not uploading the patch for " + patch[0] +
" because the file is too large."))
print ("Not uploading the patch for " + patch[0] +
" because the file is too large.")
continue
form_fields = [("filename", patch[0])]
if not options.download_base:
@ -1211,7 +1196,7 @@ def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print("Uploading patch for " + patch[0])
print "Uploading patch for " + patch[0]
response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines()
if not lines or lines[0] != "OK":
@ -1238,8 +1223,7 @@ def GuessVCS(options):
out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0:
return MercurialVCS(options, out.strip())
except OSError as e:
errno, message = e.args
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have hg installed.
raise
@ -1255,8 +1239,7 @@ def GuessVCS(options):
"--is-inside-work-tree"])
if returncode == 0:
return GitVCS(options)
except OSError as e:
errno, message = e.args
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have git installed.
raise
@ -1303,12 +1286,12 @@ def RealMain(argv, data=None):
data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data)
if verbosity >= 1:
print("Upload server:", options.server, "(change with -s/--server)")
print "Upload server:", options.server, "(change with -s/--server)"
if options.issue:
prompt = "Message describing this patch set: "
else:
prompt = "New issue subject: "
message = options.message or input(prompt).strip()
message = options.message or raw_input(prompt).strip()
if not message:
ErrorExit("A non-empty message is required")
rpc_server = GetRpcServer(options)
@ -1341,7 +1324,7 @@ def RealMain(argv, data=None):
# Send a hash of all the base file so the server can determine if a copy
# already exists in an earlier patchset.
base_hashes = ""
for file, info in files.items():
for file, info in files.iteritems():
if not info[0] is None:
checksum = md5.new(info[0]).hexdigest()
if base_hashes:
@ -1355,7 +1338,7 @@ def RealMain(argv, data=None):
if not options.download_base:
form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE:
print("Patch is large, so uploading file patches separately.")
print "Patch is large, so uploading file patches separately."
uploaded_diff_file = []
form_fields.append(("separate_patches", "1"))
else:
@ -1395,7 +1378,7 @@ def main():
try:
RealMain(sys.argv)
except KeyboardInterrupt:
print()
print
StatusUpdate("Interrupted.")
sys.exit(1)