blob: 34fc4bbb7838276e6143cb0ded0ab5e7620f6aea [file] [log] [blame]
Darin Petkovc3fd90c2011-05-11 21:23:001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
[email protected]ded22402009-10-26 22:36:212# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Gilad Arnoldd8d595c2014-03-21 20:00:415"""Devserver module for handling update client requests."""
6
Don Garrettfb15e322016-06-22 02:12:087from __future__ import print_function
8
David Zeuthen52ccd012013-10-31 19:58:269import base64
Gilad Arnolde7819e72014-03-21 19:50:4810import collections
Matthew Sartori497105b2015-12-08 22:01:5711import fcntl
Dale Curtisc9aaf3a2011-08-09 22:47:4012import json
[email protected]ded22402009-10-26 22:36:2113import os
Chris Sosa05491b12010-11-09 01:14:1614import subprocess
Gilad Arnolde74b3812013-04-22 18:27:3815import sys
Gilad Arnoldd0c71752013-12-06 19:48:4516import threading
Darin Petkov2b2ff4b2010-07-27 22:02:0917import time
Gilad Arnold0c9c8602012-10-03 06:58:5818import urllib2
Don Garrett0ad09372010-12-07 00:20:3019import urlparse
Chris Sosa7c931362010-10-12 02:49:0120
Gilad Arnoldabb352e2012-09-23 08:24:2721import cherrypy
22
joychen921e1fb2013-06-28 18:12:2023import build_util
Chris Sosa52148582012-11-15 23:35:5824import autoupdate_lib
Gilad Arnold55a2a372012-10-02 16:46:3225import common_util
joychen7c2054a2013-07-25 18:14:0726import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 22:17:4827import log_util
Gilad Arnolde74b3812013-04-22 18:27:3828# pylint: disable=F0401
Amin Hassani51780c62017-08-10 20:55:3529
30# Allow importing from aosp/system/update_engine/scripts when running from
31# source tree. Used for importing update_payload if it is not in the system
32# path.
33lib_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'aosp',
34 'system', 'update_engine', 'scripts')
35if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
36 sys.path.insert(1, lib_dir)
Gilad Arnolde74b3812013-04-22 18:27:3837import update_payload
Chris Sosa05491b12010-11-09 01:14:1638
Gilad Arnoldc65330c2012-09-20 22:17:4839
joychen121fc9b2013-08-02 21:30:3040# If used by client in place of an pre-update version string, forces an update
41# to the client regardless of the relative versions of the payload and client.
42FORCED_UPDATE = 'ForcedUpdate'
43
44# Files needed to serve an update.
45UPDATE_FILES = (
Don Garrettfb15e322016-06-22 02:12:0846 constants.UPDATE_FILE,
47 constants.STATEFUL_FILE,
48 constants.METADATA_FILE
joychen121fc9b2013-08-02 21:30:3049)
50
Gilad Arnoldc65330c2012-09-20 22:17:4851# Module-local log function.
Chris Sosa6a3697f2013-01-30 00:44:4352def _Log(message, *args):
53 return log_util.LogWithTag('UPDATE', message, *args)
Gilad Arnoldc65330c2012-09-20 22:17:4854
[email protected]ded22402009-10-26 22:36:2155
Gilad Arnold0c9c8602012-10-03 06:58:5856class AutoupdateError(Exception):
57 """Exception classes used by this module."""
58 pass
59
60
Don Garrett0ad09372010-12-07 00:20:3061def _ChangeUrlPort(url, new_port):
62 """Return the URL passed in with a different port"""
63 scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
64 host_port = netloc.split(':')
65
66 if len(host_port) == 1:
67 host_port.append(new_port)
68 else:
69 host_port[1] = new_port
70
Don Garrettfb15e322016-06-22 02:12:0871 print(host_port)
joychen121fc9b2013-08-02 21:30:3072 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-07 00:20:3073
74 return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
75
Chris Sosa6a3697f2013-01-30 00:44:4376def _NonePathJoin(*args):
77 """os.path.join that filters None's from the argument list."""
78 return os.path.join(*filter(None, args))
Don Garrett0ad09372010-12-07 00:20:3079
Chris Sosa6a3697f2013-01-30 00:44:4380
81class HostInfo(object):
Gilad Arnold286a0062012-01-12 21:47:0282 """Records information about an individual host.
83
84 Members:
85 attrs: Static attributes (legacy)
86 log: Complete log of recorded client entries
87 """
88
89 def __init__(self):
90 # A dictionary of current attributes pertaining to the host.
91 self.attrs = {}
92
93 # A list of pairs consisting of a timestamp and a dictionary of recorded
94 # attributes.
95 self.log = []
96
97 def __repr__(self):
98 return 'attrs=%s, log=%s' % (self.attrs, self.log)
99
100 def AddLogEntry(self, entry):
101 """Append a new log entry."""
102 # Append a timestamp.
103 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
104 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
105 # Add entry to hosts' message log.
106 self.log.append(entry)
107
Gilad Arnold286a0062012-01-12 21:47:02108
Chris Sosa6a3697f2013-01-30 00:44:43109class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 21:47:02110 """Records information about a set of hosts who engage in update activity.
111
112 Members:
113 table: Table of information on hosts.
114 """
115
116 def __init__(self):
117 # A dictionary of host information. Keys are normally IP addresses.
118 self.table = {}
119
120 def __repr__(self):
121 return '%s' % self.table
122
123 def GetInitHostInfo(self, host_id):
124 """Return a host's info object, or create a new one if none exists."""
125 return self.table.setdefault(host_id, HostInfo())
126
127 def GetHostInfo(self, host_id):
128 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-30 01:07:27129 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 21:47:02130
131
Chris Sosa6a3697f2013-01-30 00:44:43132class UpdateMetadata(object):
133 """Object containing metadata about an update payload."""
134
David Zeuthen52ccd012013-10-31 19:58:26135 def __init__(self, sha1, sha256, size, is_delta_format, metadata_size,
136 metadata_hash):
Chris Sosa6a3697f2013-01-30 00:44:43137 self.sha1 = sha1
138 self.sha256 = sha256
139 self.size = size
140 self.is_delta_format = is_delta_format
David Zeuthen52ccd012013-10-31 19:58:26141 self.metadata_size = metadata_size
142 self.metadata_hash = metadata_hash
Chris Sosa6a3697f2013-01-30 00:44:43143
144
joychen921e1fb2013-06-28 18:12:20145class Autoupdate(build_util.BuildObject):
Chris Sosa0356d3b2010-09-16 22:46:22146 """Class that contains functionality that handles Chrome OS update pings.
147
148 Members:
Gilad Arnold0c9c8602012-10-03 06:58:58149 urlbase: base URL, other than devserver, for update images.
150 forced_image: path to an image to use for all updates.
151 payload_path: path to pre-generated payload to serve.
152 src_image: if specified, creates a delta payload from this image.
153 proxy_port: port of local proxy to tell client to connect to you
154 through.
Gilad Arnold0c9c8602012-10-03 06:58:58155 board: board for the image. Needed for pre-generating of updates.
156 copy_to_static_root: copies images generated from the cache to ~/static.
157 private_key: path to private key in PEM format.
David Zeuthen52ccd012013-10-31 19:58:26158 private_key_for_metadata_hash_signature: path to private key in PEM format.
159 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 19:52:23160 critical_update: whether provisioned payload is critical.
161 remote_payload: whether provisioned payload is remotely staged.
162 max_updates: maximum number of updates we'll try to provision.
163 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 22:46:22164 """
[email protected]ded22402009-10-26 22:36:21165
joychened64b222013-06-21 23:39:34166 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-03 06:58:58167 _PAYLOAD_URL_PREFIX = '/static/'
168 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
169
Chris Sosa6a3697f2013-01-30 00:44:43170 SHA1_ATTR = 'sha1'
171 SHA256_ATTR = 'sha256'
172 SIZE_ATTR = 'size'
173 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 19:58:26174 METADATA_SIZE_ATTR = 'metadata_size'
175 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-30 00:44:43176
joychen121fc9b2013-08-02 21:30:30177 def __init__(self, xbuddy, urlbase=None, forced_image=None, payload_path=None,
Gabe Black70994862014-09-05 07:50:58178 proxy_port=None, src_image='', board=None,
Chris Sosa0f1ec842011-02-15 00:33:22179 copy_to_static_root=True, private_key=None,
David Zeuthen52ccd012013-10-31 19:58:26180 private_key_for_metadata_hash_signature=None, public_key=None,
Don Garrettfb15e322016-06-22 02:12:08181 critical_update=False, remote_payload=False, max_updates=-1,
Chris Sosa6a3697f2013-01-30 00:44:43182 host_log=False, *args, **kwargs):
Sean O'Connor14b6a0a2010-03-21 06:23:48183 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 21:30:30184 self.xbuddy = xbuddy
185 self.urlbase = urlbase or None
Chris Sosa0356d3b2010-09-16 22:46:22186 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-03 06:58:58187 self.payload_path = payload_path
Chris Sosa62f720b2010-10-27 04:39:48188 self.src_image = src_image
Don Garrett0ad09372010-12-07 00:20:30189 self.proxy_port = proxy_port
joychen562699a2013-08-13 22:22:14190 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-20 00:08:02191 self.copy_to_static_root = copy_to_static_root
Chris Sosa0f1ec842011-02-15 00:33:22192 self.private_key = private_key
David Zeuthen52ccd012013-10-31 19:58:26193 self.private_key_for_metadata_hash_signature = \
194 private_key_for_metadata_hash_signature
195 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 17:36:32196 self.critical_update = critical_update
Gilad Arnold0c9c8602012-10-03 06:58:58197 self.remote_payload = remote_payload
Jay Srinivasanac69d262012-10-31 02:05:53198 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 19:52:23199 self.host_log = host_log
Don Garrettfff4c322010-11-19 21:37:12200
Chris Sosa417e55d2011-01-26 00:40:48201 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-21 06:23:48202
Dale Curtisc9aaf3a2011-08-09 22:47:40203 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 21:47:02204 # information about a given host. A host is identified by its IP address.
205 # The info stored for each host includes a complete log of events for this
206 # host, as well as a dictionary of current attributes derived from events.
207 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 22:47:40208
Gilad Arnolde7819e72014-03-21 19:50:48209 self._update_count_lock = threading.Lock()
Gilad Arnoldd0c71752013-12-06 19:48:45210
Chris Sosa6a3697f2013-01-30 00:44:43211 @classmethod
212 def _ReadMetadataFromStream(cls, stream):
213 """Returns metadata obj from input json stream that implements .read()."""
Chung-yih Wangdcf798a2016-06-23 16:03:24214 data = None
Chris Sosa6a3697f2013-01-30 00:44:43215 file_attr_dict = {}
216 try:
Chung-yih Wangdcf798a2016-06-23 16:03:24217 data = stream.read()
218 file_attr_dict = json.loads(data)
219 except (IOError, ValueError):
220 _Log('Failed to load metadata:%s' % data)
Chris Sosa6a3697f2013-01-30 00:44:43221 return None
222
223 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
224 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
225 size = file_attr_dict.get(cls.SIZE_ATTR)
226 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 19:58:26227 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
228 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
229 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
230 metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43231
232 @staticmethod
233 def _ReadMetadataFromFile(payload_dir):
234 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 21:54:16235 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43236 if os.path.exists(metadata_file):
Matthew Sartori497105b2015-12-08 22:01:57237 metadata_stream = open(metadata_file, 'r')
238 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_SH)
239 metadata = Autoupdate._ReadMetadataFromStream(metadata_stream)
240 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_UN)
241 return metadata
Chris Sosa6a3697f2013-01-30 00:44:43242
243 @classmethod
244 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
245 """Stores metadata object into the metadata_file of the payload_dir"""
246 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
247 cls.SHA256_ATTR: metadata_obj.sha256,
248 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 19:58:26249 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
250 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
251 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 21:54:16252 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Matthew Sartori497105b2015-12-08 22:01:57253 file_handle = open(metadata_file, 'w')
254 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_EX)
255 json.dump(file_dict, file_handle)
256 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_UN)
Chris Sosa6a3697f2013-01-30 00:44:43257
Chris Sosa52148582012-11-15 23:35:58258 @staticmethod
259 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 22:46:22260 """Returns the version of the image based on the name of the directory."""
261 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 15:52:52262 parts = latest_version.split('-')
joychen121fc9b2013-08-02 21:30:30263 # If we can't get a version number from the directory, default to a high
264 # number to allow the update to happen
Paul Hobbs5e7b5a72017-10-04 18:02:39265 # TODO(phobbs) refactor this.
266 return parts[1] if len(parts) == 3 else "999999.0.0"
Chris Sosa0356d3b2010-09-16 22:46:22267
Chris Sosa52148582012-11-15 23:35:58268 @staticmethod
269 def _CanUpdate(client_version, latest_version):
Don Garrettfb15e322016-06-22 02:12:08270 """True if the latest_version is greater than the client_version."""
Chris Sosa6a3697f2013-01-30 00:44:43271 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 15:52:52272
273 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52274 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 15:52:52275
Paul Hobbs5e7b5a72017-10-04 18:02:39276 def _SafeInt(part):
277 try:
278 return int(part)
279 except ValueError:
280 return part
281
joychen121fc9b2013-08-02 21:30:30282 if len(latest_tokens) == len(client_tokens) == 3:
Paul Hobbs5e7b5a72017-10-04 18:02:39283 return map(_SafeInt, latest_tokens) > map(_SafeInt, client_tokens)
Chris Sosa0356d3b2010-09-16 22:46:22284 else:
joychen121fc9b2013-08-02 21:30:30285 # If the directory name isn't a version number, let it pass.
286 return True
Chris Sosa0356d3b2010-09-16 22:46:22287
Chris Sosa52148582012-11-15 23:35:58288 @staticmethod
Gilad Arnolde74b3812013-04-22 18:27:38289 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-26 00:34:49290 try:
Gilad Arnolde74b3812013-04-22 18:27:38291 with open(filename) as payload_file:
292 payload = update_payload.Payload(payload_file)
293 payload.Init()
294 return payload.IsDelta()
295 except (IOError, update_payload.PayloadError):
296 # For unit tests we may not have real files, so it's ok to ignore these
297 # errors.
Andrew de los Reyes5679b972010-10-26 00:34:49298 return False
299
Don Garrettf90edf02010-11-17 01:36:14300 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 22:46:22301 """Generates an update gz given a full path to an image.
302
303 Args:
Gilad Arnoldd8d595c2014-03-21 20:00:41304 src_image: Path to a source image.
Chris Sosa0356d3b2010-09-16 22:46:22305 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 20:00:41306 output_dir: Path to the generated update file.
307
Chris Sosa6a3697f2013-01-30 00:44:43308 Raises:
309 subprocess.CalledProcessError if the update generator fails to generate a
310 stateful payload.
Chris Sosa0356d3b2010-09-16 22:46:22311 """
joychen7c2054a2013-07-25 18:14:07312 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43313 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 22:46:22314
Chris Sosa0f1ec842011-02-15 00:33:22315 update_command = [
Chris Sosa5b8b5eb2012-03-27 18:15:27316 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-30 00:44:43317 '--image', image_path,
David Zeuthen52ccd012013-10-31 19:58:26318 '--out_metadata_hash_file', os.path.join(output_dir,
319 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-30 00:44:43320 '--output', update_path,
Chris Sosa0f1ec842011-02-15 00:33:22321 ]
Chris Sosa4136e692010-10-29 06:42:37322
Chris Sosa52148582012-11-15 23:35:58323 if src_image:
Chris Sosa6a3697f2013-01-30 00:44:43324 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 23:35:58325
Chris Sosa52148582012-11-15 23:35:58326 if self.private_key:
Chris Sosa6a3697f2013-01-30 00:44:43327 update_command.extend(['--private_key', self.private_key])
Chris Sosa0f1ec842011-02-15 00:33:22328
Chris Sosa6a3697f2013-01-30 00:44:43329 _Log('Running %s', ' '.join(update_command))
330 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 22:46:22331
Chris Sosa52148582012-11-15 23:35:58332 @staticmethod
333 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14334 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 22:46:22335
336 Args:
337 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 20:00:41338 output_dir: Directory for emitting the stateful update payload.
339
Chris Sosa908fd6f2010-11-11 01:31:18340 Raises:
Chris Sosa6a3697f2013-01-30 00:44:43341 subprocess.CalledProcessError if the update generator fails to generate a
Chris Sosa908fd6f2010-11-11 01:31:18342 stateful payload.
Chris Sosa0356d3b2010-09-16 22:46:22343 """
Chris Sosa6a3697f2013-01-30 00:44:43344 update_command = [
345 'cros_generate_stateful_update_payload',
346 '--image', image_path,
347 '--output_dir', output_dir,
348 ]
349 _Log('Running %s', ' '.join(update_command))
350 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 22:46:22351
Don Garrettf90edf02010-11-17 01:36:14352 def FindCachedUpdateImageSubDir(self, src_image, dest_image):
353 """Find directory to store a cached update.
354
Gilad Arnold55a2a372012-10-02 16:46:32355 Given one, or two images for an update, this finds which cache directory
356 should hold the update files, even if they don't exist yet.
Don Garrettf90edf02010-11-17 01:36:14357
Gilad Arnold55a2a372012-10-02 16:46:32358 Returns:
359 A directory path for storing a cached update, of the following form:
360 Non-delta updates:
361 CACHE_DIR/<dest_hash>
362 Delta updates:
363 CACHE_DIR/<src_hash>_<dest_hash>
364 Signed updates (self.private_key):
365 CACHE_DIR/<src_hash>_<dest_hash>+<private_key_hash>
Chris Sosa744e1472011-09-08 02:32:50366 """
Gilad Arnold55a2a372012-10-02 16:46:32367 update_dir = ''
Chris Sosa744e1472011-09-08 02:32:50368 if src_image:
Gilad Arnold55a2a372012-10-02 16:46:32369 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-17 01:36:14370
Gilad Arnold55a2a372012-10-02 16:46:32371 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-08 02:32:50372 if self.private_key:
Gilad Arnold55a2a372012-10-02 16:46:32373 update_dir += '+' + common_util.GetFileMd5(self.private_key)
Chris Sosa744e1472011-09-08 02:32:50374
joychen25d25972013-07-30 21:54:16375 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-17 01:36:14376
Don Garrettfff4c322010-11-19 21:37:12377 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-17 01:36:14378 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 22:46:22379
Chris Sosade91f672010-11-16 18:05:44380 Args:
Don Garrettf90edf02010-11-17 01:36:14381 image_path: full path to the image.
Chris Sosa6a3697f2013-01-30 00:44:43382 output_dir: the directory to write the update payloads to
Gilad Arnoldd8d595c2014-03-21 20:00:41383
Chris Sosa6a3697f2013-01-30 00:44:43384 Raises:
385 AutoupdateError if it failed to generate either update or stateful
386 payload.
Chris Sosade91f672010-11-16 18:05:44387 """
Chris Sosa6a3697f2013-01-30 00:44:43388 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 17:29:43389
Chris Sosa6a3697f2013-01-30 00:44:43390 # Delete any previous state in this directory.
391 os.system('rm -rf "%s"' % output_dir)
392 os.makedirs(output_dir)
[email protected]ded22402009-10-26 22:36:21393
Chris Sosa6a3697f2013-01-30 00:44:43394 try:
395 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
396 self.GenerateStatefulFile(image_path, output_dir)
397 except subprocess.CalledProcessError:
398 os.system('rm -rf "%s"' % output_dir)
399 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-17 01:36:14400
Chris Sosa75490802013-10-01 00:21:45401 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-17 01:36:14402 """Force generates an update payload based on the given image_path.
[email protected]ded22402009-10-26 22:36:21403
Chris Sosa0356d3b2010-09-16 22:46:22404 Args:
405 image_path: full path to the image.
Gilad Arnoldd8d595c2014-03-21 20:00:41406
Chris Sosa0356d3b2010-09-16 22:46:22407 Returns:
joychen121fc9b2013-08-02 21:30:30408 update directory relative to static_image_dir.
Gilad Arnoldd8d595c2014-03-21 20:00:41409
Chris Sosa6a3697f2013-01-30 00:44:43410 Raises:
411 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 22:46:22412 """
Chris Sosa6a3697f2013-01-30 00:44:43413 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f12010-11-05 00:33:16414
joychen121fc9b2013-08-02 21:30:30415 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-26 00:40:48416 if self.pregenerated_path:
417 return self.pregenerated_path
Don Garrettfff4c322010-11-19 21:37:12418
Chris Sosa75490802013-10-01 00:21:45419 # Which sub_dir should hold our cached update image.
420 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-30 00:44:43421 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-26 00:40:48422
joychen121fc9b2013-08-02 21:30:30423 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-10-01 00:21:45424 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 21:30:30425
426 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 18:14:07427 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 21:30:30428 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 21:54:16429 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-26 00:40:48430 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 21:30:30431 if not (os.path.exists(cache_update_payload) and
432 os.path.exists(cache_stateful_payload)):
433 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-17 01:36:14434
joychen121fc9b2013-08-02 21:30:30435 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-30 00:44:43436 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-22 02:59:21437
Chris Sosa6a3697f2013-01-30 00:44:43438 # Generate the cache file.
joychen121fc9b2013-08-02 21:30:30439 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-17 01:36:14440
joychen121fc9b2013-08-02 21:30:30441 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 22:46:22442
Chris Sosa75490802013-10-01 00:21:45443 def _SymlinkUpdateFiles(self, target_dir, link_dir):
444 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 21:30:30445
446 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-10-01 00:21:45447 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 22:46:22448
449 Args:
Chris Sosa75490802013-10-01 00:21:45450 target_dir: Location of the target files.
451 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 22:46:22452 """
Chris Sosa75490802013-10-01 00:21:45453 _Log('Linking %s to %s', target_dir, link_dir)
454 if link_dir == target_dir:
455 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 21:30:30456 return
457 for f in UPDATE_FILES:
Chris Sosa75490802013-10-01 00:21:45458 link = os.path.join(link_dir, f)
459 target = os.path.join(target_dir, f)
Alex Deymo3e2d4952013-09-04 04:49:41460 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 22:46:22461
joychen121fc9b2013-08-02 21:30:30462 def GetUpdateForLabel(self, client_version, label,
463 image_name=constants.TEST_IMAGE_FILE):
464 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 22:46:22465
joychen121fc9b2013-08-02 21:30:30466 Args:
467 client_version: Current version of the client or FORCED_UPDATE
468 label: the relative directory inside the static dir
469 image_name: If the image type was specified by the update rpc, we try to
470 find an image with this file name first. This is by default
471 "chromiumos_test_image.bin" but can also take any of the values in
472 devserver_constants.ALL_IMAGES
Gilad Arnoldd8d595c2014-03-21 20:00:41473
Chris Sosa6a3697f2013-01-30 00:44:43474 Returns:
joychen121fc9b2013-08-02 21:30:30475 A relative path to the directory with the update payload.
476 This is the label if an update did not need to be generated, but can
477 be label/cache/hashed_dir_for_update.
Gilad Arnoldd8d595c2014-03-21 20:00:41478
Chris Sosa6a3697f2013-01-30 00:44:43479 Raises:
joychen121fc9b2013-08-02 21:30:30480 AutoupdateError: If client version is higher than available update found
481 at the directory given by the label.
Don Garrettf90edf02010-11-17 01:36:14482 """
joychen121fc9b2013-08-02 21:30:30483 _Log('Update label/file: %s/%s', label, image_name)
484 static_image_dir = _NonePathJoin(self.static_dir, label)
485 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
486 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 18:14:07487
joychen121fc9b2013-08-02 21:30:30488 # Update the client only if client version is older than available update.
489 latest_version = self._GetVersionFromDir(static_image_dir)
490 if not (client_version == FORCED_UPDATE or
491 self._CanUpdate(client_version, latest_version)):
492 raise AutoupdateError(
493 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 20:09:35494
joychen121fc9b2013-08-02 21:30:30495 if label and os.path.exists(static_update_path):
496 # An update payload was found for the given label, return it.
497 return label
498 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
499 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45500 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
501 # Add links from the static directory to the update.
502 cache_path = _NonePathJoin(self.static_dir, rel_path)
503 self._SymlinkUpdateFiles(cache_path, static_image_dir)
504 return label
Don Garrett0c880e22010-11-18 02:13:37505
joychen121fc9b2013-08-02 21:30:30506 # The label didn't resolve.
507 return None
Chris Sosa2c048f12010-10-27 23:05:27508
509 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-26 00:40:48510 """Pre-generates an update and prints out the relative path it.
511
Chris Sosa6a3697f2013-01-30 00:44:43512 Returns relative path of the update.
Chris Sosa65d339b2013-01-22 02:59:21513
Chris Sosa6a3697f2013-01-30 00:44:43514 Raises:
515 AutoupdateError if it failed to generate the payload.
516 """
517 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 21:30:30518 # Does not work with labels so just use static dir. (empty label)
519 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Don Garrettfb15e322016-06-22 02:12:08520 print('PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
521 constants.UPDATE_FILE))
Chris Sosa417e55d2011-01-26 00:40:48522 return pregenerated_update
Chris Sosa2c048f12010-10-27 23:05:27523
Gilad Arnold0c9c8602012-10-03 06:58:58524 def _GetRemotePayloadAttrs(self, url):
525 """Returns hashes, size and delta flag of a remote update payload.
526
527 Obtain attributes of a payload file available on a remote devserver. This
528 is based on the assumption that the payload URL uses the /static prefix. We
529 need to make sure that both clients (requests) and remote devserver
530 (provisioning) preserve this invariant.
531
532 Args:
533 url: URL of statically staged remote file (http://host:port/static/...)
Gilad Arnoldd8d595c2014-03-21 20:00:41534
Gilad Arnold0c9c8602012-10-03 06:58:58535 Returns:
David Zeuthen52ccd012013-10-31 19:58:26536 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-03 06:58:58537 """
538 if self._PAYLOAD_URL_PREFIX not in url:
539 raise AutoupdateError(
540 'Payload URL does not have the expected prefix (%s)' %
541 self._PAYLOAD_URL_PREFIX)
Chris Sosa6a3697f2013-01-30 00:44:43542
joychened64b222013-06-21 23:39:34543 if self._OLD_PAYLOAD_URL_PREFIX in url:
544 fileinfo_url = url.replace(self._OLD_PAYLOAD_URL_PREFIX,
545 self._FILEINFO_URL_PREFIX)
546 else:
547 fileinfo_url = url.replace(self._PAYLOAD_URL_PREFIX,
548 self._FILEINFO_URL_PREFIX)
549
Chris Sosa6a3697f2013-01-30 00:44:43550 _Log('Retrieving file info for remote payload via %s', fileinfo_url)
Gilad Arnold0c9c8602012-10-03 06:58:58551 try:
552 conn = urllib2.urlopen(fileinfo_url)
Chris Sosa6a3697f2013-01-30 00:44:43553 metadata_obj = Autoupdate._ReadMetadataFromStream(conn)
554 # These fields are required for remote calls.
555 if not metadata_obj:
556 raise AutoupdateError('Failed to obtain remote payload info')
Gilad Arnold0c9c8602012-10-03 06:58:58557
Chris Sosa6a3697f2013-01-30 00:44:43558 return metadata_obj
559 except IOError as e:
560 raise AutoupdateError('Failed to obtain remote payload info: %s', e)
561
David Zeuthen52ccd012013-10-31 19:58:26562 @staticmethod
563 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 18:38:16564 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 19:58:26565
566 Args:
567 payload_dir: The payload directory.
Gilad Arnoldd8d595c2014-03-21 20:00:41568
David Zeuthen52ccd012013-10-31 19:58:26569 Returns:
David Zeuthenf27f1502013-11-13 18:38:16570 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 19:58:26571 """
572 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 18:38:16573 if os.path.exists(path):
574 return base64.b64encode(open(path, 'rb').read())
575 else:
576 return None
David Zeuthen52ccd012013-10-31 19:58:26577
578 @staticmethod
579 def _GetMetadataSize(payload_filename):
580 """Gets the size of the metadata in a payload file.
581
582 Args:
583 payload_filename: Path to the payload file.
Gilad Arnoldd8d595c2014-03-21 20:00:41584
David Zeuthen52ccd012013-10-31 19:58:26585 Returns:
586 The size of the payload metadata, as reported in the payload header.
587 """
Alex Deymoa6ac00d2015-10-15 16:14:58588 try:
589 with open(payload_filename) as payload_file:
590 payload = update_payload.Payload(payload_file)
591 payload.Init()
592 return payload.metadata_size
593 except (IOError, update_payload.PayloadError):
594 # For unit tests we may not have real files, so it's ok to ignore these
595 # errors.
David Zeuthen52ccd012013-10-31 19:58:26596 return 0
David Zeuthen52ccd012013-10-31 19:58:26597
Chris Sosa6a3697f2013-01-30 00:44:43598 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-03 06:58:58599 """Returns hashes, size and delta flag of a local update payload.
600
601 Args:
Chris Sosa6a3697f2013-01-30 00:44:43602 payload_dir: Path to the directory the payload is in.
Gilad Arnoldd8d595c2014-03-21 20:00:41603
Gilad Arnold0c9c8602012-10-03 06:58:58604 Returns:
David Zeuthen52ccd012013-10-31 19:58:26605 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-03 06:58:58606 """
joychen7c2054a2013-07-25 18:14:07607 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-30 00:44:43608 if not os.path.exists(filename):
609 raise AutoupdateError('update.gz not present in payload dir %s' %
610 payload_dir)
Gilad Arnold0c9c8602012-10-03 06:58:58611
Chris Sosa6a3697f2013-01-30 00:44:43612 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
613 if not metadata_obj or not (metadata_obj.sha1 and
614 metadata_obj.sha256 and
615 metadata_obj.size):
616 sha1 = common_util.GetFileSha1(filename)
617 sha256 = common_util.GetFileSha256(filename)
618 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 18:27:38619 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 19:58:26620 metadata_size = self._GetMetadataSize(filename)
621 metadata_hash = self._GetMetadataHash(payload_dir)
622 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
623 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-30 00:44:43624 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 22:46:22625
Chris Sosa6a3697f2013-01-30 00:44:43626 return metadata_obj
627
628 def _ProcessUpdateComponents(self, app, event):
Gilad Arnolde7819e72014-03-21 19:50:48629 """Processes the components of an update request.
Chris Sosa6a3697f2013-01-30 00:44:43630
Gilad Arnolde7819e72014-03-21 19:50:48631 Args:
632 app: An app component of an update request.
633 event: An event component of an update request.
634
635 Returns:
636 A named tuple containing attributes of the update requests as the
637 following fields: 'forced_update_label', 'client_version', 'board',
638 'event_result' and 'event_type'.
Chris Sosa0356d3b2010-09-16 22:46:22639 """
Chris Sosa6a3697f2013-01-30 00:44:43640 # Initialize an empty dictionary for event attributes to log.
641 log_message = {}
Jay Srinivasanac69d262012-10-31 02:05:53642
Dale Curtisc9aaf3a2011-08-09 22:47:40643 # Determine request IP, strip any IPv6 data for simplicity.
644 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 21:47:02645 # Obtain (or init) info object for this client.
646 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
647
joychen121fc9b2013-08-02 21:30:30648 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-30 00:44:43649 board = None
650 if app:
651 client_version = app.getAttribute('version')
652 channel = app.getAttribute('track')
653 board = (app.hasAttribute('board') and app.getAttribute('board')
Don Garrettfb15e322016-06-22 02:12:08654 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-30 00:44:43655 # Add attributes to log message
656 log_message['version'] = client_version
657 log_message['track'] = channel
658 log_message['board'] = board
659 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 22:47:40660
Gilad Arnolde7819e72014-03-21 19:50:48661 event_result = None
662 event_type = None
Dale Curtisc9aaf3a2011-08-09 22:47:40663 if event:
Gilad Arnold286a0062012-01-12 21:47:02664 event_result = int(event[0].getAttribute('eventresult'))
665 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 22:33:21666 client_previous_version = (event[0].getAttribute('previousversion')
667 if event[0].hasAttribute('previousversion')
668 else None)
Gilad Arnold286a0062012-01-12 21:47:02669 # Store attributes to legacy host info structure
670 curr_host_info.attrs['last_event_status'] = event_result
671 curr_host_info.attrs['last_event_type'] = event_type
672 # Add attributes to log message
673 log_message['event_result'] = event_result
674 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 22:33:21675 if client_previous_version is not None:
676 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 21:47:02677
Gilad Arnold8318eac2012-10-04 19:52:23678 # Log host event, if so instructed.
679 if self.host_log:
680 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 22:47:40681
Gilad Arnolde7819e72014-03-21 19:50:48682 UpdateRequestAttrs = collections.namedtuple(
683 'UpdateRequestAttrs',
684 ('forced_update_label', 'client_version', 'board', 'event_result',
685 'event_type'))
686
687 return UpdateRequestAttrs(
688 curr_host_info.attrs.pop('forced_update_label', None),
689 client_version, board, event_result, event_type)
Chris Sosa6a3697f2013-01-30 00:44:43690
Chris Sosa4b951602014-04-10 03:26:07691 @classmethod
692 def _CheckOmahaRequest(cls, app):
693 """Checks |app| component of Omaha Request for correctly formed data.
694
695 Raises:
696 common_util.DevServerHTTPError: if any check fails. All 400 error codes to
697 indicate a bad HTTP request.
698 """
699 if not app:
700 raise common_util.DevServerHTTPError(
701 400, 'Missing app component in Omaha Request')
702
703 hardware_class = app.getAttribute('hardware_class')
704 if not hardware_class:
705 raise common_util.DevServerHTTPError(
706 400, 'hardware_class is required in Omaha Request')
707
708 track = app.getAttribute('track')
Chris Sosafc715442014-04-10 03:45:23709 if not (track and track.endswith('-channel')):
Chris Sosa4b951602014-04-10 03:26:07710 raise common_util.DevServerHTTPError(
Chris Sosafc715442014-04-10 03:45:23711 400, 'Omaha requests need a valid update channel')
Chris Sosa4b951602014-04-10 03:26:07712
David Rileyee75de22017-11-02 17:48:15713 def GetDevserverUrl(self):
714 """Returns the devserver url base."""
Chris Sosa6a3697f2013-01-30 00:44:43715 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
716 if x_forwarded_host:
717 hostname = 'http://' + x_forwarded_host
718 else:
719 hostname = cherrypy.request.base
720
David Rileyee75de22017-11-02 17:48:15721 return hostname
722
723 def GetStaticUrl(self):
724 """Returns the static url base that should prefix all payload responses."""
725 hostname = self.GetDevserverUrl()
726
Chris Sosa6a3697f2013-01-30 00:44:43727 if self.urlbase:
728 static_urlbase = self.urlbase
Chris Sosa6a3697f2013-01-30 00:44:43729 else:
730 static_urlbase = '%s/static' % hostname
731
732 # If we have a proxy port, adjust the URL we instruct the client to
733 # use to go through the proxy.
734 if self.proxy_port:
735 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
736
737 _Log('Using static url base %s', static_urlbase)
738 _Log('Handling update ping as %s', hostname)
739 return static_urlbase
740
joychen121fc9b2013-08-02 21:30:30741 def GetPathToPayload(self, label, client_version, board):
742 """Find a payload locally.
743
744 See devserver's update rpc for documentation.
745
746 Args:
747 label: from update request
748 client_version: from update request
749 board: from update request
Gilad Arnoldd8d595c2014-03-21 20:00:41750
751 Returns:
joychen121fc9b2013-08-02 21:30:30752 The relative path to an update from the static_dir
Gilad Arnoldd8d595c2014-03-21 20:00:41753
joychen121fc9b2013-08-02 21:30:30754 Raises:
755 AutoupdateError: If the update could not be found.
756 """
757 path_to_payload = None
758 #TODO(joychen): deprecate --payload flag
759 if self.payload_path:
760 # Copy the image from the path to '/forced_payload'
761 label = 'forced_payload'
762 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
763 dest_stateful = os.path.join(self.static_dir, label,
764 constants.STATEFUL_FILE)
Alex Deymo48e970d2015-09-23 21:34:41765 dest_meta = os.path.join(self.static_dir, label, constants.METADATA_FILE)
joychen121fc9b2013-08-02 21:30:30766
767 src_path = os.path.abspath(self.payload_path)
768 src_stateful = os.path.join(os.path.dirname(src_path),
769 constants.STATEFUL_FILE)
770 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-04 04:49:41771 common_util.SymlinkFile(src_path, dest_path)
Alex Deymo48e970d2015-09-23 21:34:41772 # The old metadata file should be regenerated whenever a new payload is
773 # used.
774 try:
775 os.unlink(dest_meta)
776 except OSError:
777 pass
joychen121fc9b2013-08-02 21:30:30778 if os.path.exists(src_stateful):
779 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-04 04:49:41780 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 21:30:30781 else:
782 _Log('WARN: %s not found. Expected for dev and test builds',
783 constants.STATEFUL_FILE)
784 if os.path.exists(dest_stateful):
785 os.remove(dest_stateful)
786 path_to_payload = self.GetUpdateForLabel(client_version, label)
787 #TODO(joychen): deprecate --image flag
788 elif self.forced_image:
joychendbfe6c92013-08-17 03:03:49789 if self.forced_image.startswith('xbuddy:'):
790 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-17 03:03:49791 xbuddy_label = self.forced_image.split(':')[1]
792 self.forced_image = None
joychen365a5742013-08-21 17:41:18793 # Make sure the xbuddy path target is in the directory.
794 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
795 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 23:45:12796 self.GetPathToPayload(xbuddy_label, client_version, board)
797 else:
798 src_path = os.path.abspath(self.forced_image)
799 if os.path.exists(src_path) and common_util.IsInsideChroot():
800 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-10-01 00:21:45801 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
802 # Add links from the static directory to the update.
803 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
804 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 21:30:30805 else:
806 label = label or ''
807 label_list = label.split('/')
808 # Suppose that the path follows old protocol of indexing straight
809 # into static_dir with board/version label.
810 # Attempt to get the update in that directory, generating if necc.
811 path_to_payload = self.GetUpdateForLabel(client_version, label)
812 if path_to_payload is None:
813 # There was no update or image found in the directory.
814 # Let XBuddy find an image, and then generate an update to it.
815 if label_list[0] == 'xbuddy':
816 # If path explicitly calls xbuddy, pop off the tag.
817 label_list.pop()
Chris Sosa75490802013-10-01 00:21:45818 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 21:30:30819 if image_name not in constants.ALL_IMAGES:
820 raise AutoupdateError(
821 "Use an image alias: dev, base, test, or recovery.")
822 # Path has been resolved, try to get the image.
823 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
824 image_name)
825 if path_to_payload is None:
826 # Neither image nor update payload found after translation.
827 # Try to get an update to a test image from GS using the label.
828 path_to_payload, _image_name = self.xbuddy.Get(
829 ['remote', label, 'full_payload'])
830
831 # One of the above options should have gotten us a relative path.
832 if path_to_payload is None:
833 raise AutoupdateError('Failed to get an update for: %s' % label)
834 else:
Chris Sosa75490802013-10-01 00:21:45835 return path_to_payload
joychen121fc9b2013-08-02 21:30:30836
David Zeuthen52ccd012013-10-31 19:58:26837 @staticmethod
838 def _SignMetadataHash(private_key_path, metadata_hash):
839 """Signs metadata hash.
840
841 Signs a metadata hash with a private key. This includes padding the
842 hash with PKCS#1 v1.5 padding as well as an ASN.1 header.
843
844 Args:
845 private_key_path: The path to a private key to use for signing.
846 metadata_hash: A raw SHA-256 hash (32 bytes).
Gilad Arnoldd8d595c2014-03-21 20:00:41847
David Zeuthen52ccd012013-10-31 19:58:26848 Returns:
849 The raw signature.
850 """
851 args = ['openssl', 'rsautl', '-pkcs', '-sign', '-inkey', private_key_path]
852 padded_metadata_hash = ('\x30\x31\x30\x0d\x06\x09\x60\x86'
853 '\x48\x01\x65\x03\x04\x02\x01\x05'
854 '\x00\x04\x20') + metadata_hash
855 child = subprocess.Popen(args,
856 stdin=subprocess.PIPE,
857 stdout=subprocess.PIPE)
858 signature, _ = child.communicate(input=padded_metadata_hash)
859 return signature
860
joychen121fc9b2013-08-02 21:30:30861 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-30 00:44:43862 """Handles an update ping from an update client.
863
864 Args:
865 data: XML blob from client.
866 label: optional label for the update.
Gilad Arnoldd8d595c2014-03-21 20:00:41867
Chris Sosa6a3697f2013-01-30 00:44:43868 Returns:
869 Update payload message for client.
870 """
871 # Get the static url base that will form that base of our update url e.g.
872 # http://hostname:8080/static/update.gz.
David Rileyee75de22017-11-02 17:48:15873 static_urlbase = self.GetStaticUrl()
Chris Sosa6a3697f2013-01-30 00:44:43874
875 # Parse the XML we got into the components we care about.
876 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
Amin Hassanid7a913a2018-03-13 22:19:24877 appid = app.getAttribute('appid')
Chris Sosa6a3697f2013-01-30 00:44:43878
Chris Sosab26b1202013-08-16 23:40:55879 # Process attributes of the update check.
Gilad Arnolde7819e72014-03-21 19:50:48880 request_attrs = self._ProcessUpdateComponents(app, event)
Chris Sosab26b1202013-08-16 23:40:55881
joychen121fc9b2013-08-02 21:30:30882 if not update_check:
Gilad Arnolde7819e72014-03-21 19:50:48883 if ((request_attrs.event_type ==
884 autoupdate_lib.EVENT_TYPE_UPDATE_DOWNLOAD_STARTED) and
885 request_attrs.event_result == autoupdate_lib.EVENT_RESULT_SUCCESS):
886 with self._update_count_lock:
887 if self.max_updates == 0:
888 _Log('Received too many download_started notifications. This '
889 'probably means a bug in the test environment, such as too '
890 'many clients running concurrently. Alternatively, it could '
891 'be a bug in the update client.')
892 elif self.max_updates > 0:
893 self.max_updates -= 1
joychen121fc9b2013-08-02 21:30:30894
Gilad Arnolde7819e72014-03-21 19:50:48895 _Log('A non-update event notification received. Returning an ack.')
Amin Hassanid7a913a2018-03-13 22:19:24896 return autoupdate_lib.GetEventResponse(protocol, appid)
Gilad Arnolde7819e72014-03-21 19:50:48897
898 if request_attrs.forced_update_label:
Chris Sosa6a3697f2013-01-30 00:44:43899 if label:
900 _Log('Label: %s set but being overwritten to %s by request', label,
Gilad Arnolde7819e72014-03-21 19:50:48901 request_attrs.forced_update_label)
902 label = request_attrs.forced_update_label
Chris Sosa6a3697f2013-01-30 00:44:43903
Gilad Arnolde7819e72014-03-21 19:50:48904 # Make sure that we did not already exceed the max number of allowed update
905 # responses. Note that the counter is only decremented when the client
906 # reports an actual download, to avoid race conditions between concurrent
907 # update requests from the same client due to a timeout.
joychen121fc9b2013-08-02 21:30:30908 if self.max_updates == 0:
Gilad Arnolde7819e72014-03-21 19:50:48909 _Log('Request received but max number of updates already served.')
Amin Hassanid7a913a2018-03-13 22:19:24910 return autoupdate_lib.GetNoUpdateResponse(protocol, appid)
joychen121fc9b2013-08-02 21:30:30911
Gilad Arnolde7819e72014-03-21 19:50:48912 _Log('Update Check Received. Client is using protocol version: %s',
913 protocol)
joychen121fc9b2013-08-02 21:30:30914
Chris Sosa6a3697f2013-01-30 00:44:43915 # Finally its time to generate the omaha response to give to client that
916 # lets them know where to find the payload and its associated metadata.
917 metadata_obj = None
918
919 try:
Gilad Arnold0c9c8602012-10-03 06:58:58920 # Are we provisioning a remote or local payload?
921 if self.remote_payload:
Chris Sosa4b951602014-04-10 03:26:07922
923 self._CheckOmahaRequest(app)
924
Gilad Arnold0c9c8602012-10-03 06:58:58925 # If no explicit label was provided, use the value of --payload.
Chris Sosa6a3697f2013-01-30 00:44:43926 if not label:
Gilad Arnold0c9c8602012-10-03 06:58:58927 label = self.payload_path
Chris Sosa0356d3b2010-09-16 22:46:22928
Chris Sosa52f15bc2013-08-14 00:14:15929 # TODO(sosa): Remove backwards-compatible hack.
Chris Sosab26b1202013-08-16 23:40:55930 if not '.bin' in label:
Chris Sosa52f15bc2013-08-14 00:14:15931 url = _NonePathJoin(static_urlbase, label, 'update.gz')
932 else:
933 url = _NonePathJoin(static_urlbase, label)
Chris Sosa5d342a22010-09-28 23:54:41934
Gilad Arnold0c9c8602012-10-03 06:58:58935 # Get remote payload attributes.
Chris Sosa6a3697f2013-01-30 00:44:43936 metadata_obj = self._GetRemotePayloadAttrs(url)
Gilad Arnold0c9c8602012-10-03 06:58:58937 else:
Gilad Arnolde7819e72014-03-21 19:50:48938 path_to_payload = self.GetPathToPayload(
939 label, request_attrs.client_version, request_attrs.board)
joychen121fc9b2013-08-02 21:30:30940 url = _NonePathJoin(static_urlbase, path_to_payload,
joychen7c2054a2013-07-25 18:14:07941 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 21:30:30942 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-30 00:44:43943 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-30 00:44:43944 except AutoupdateError as e:
945 # Raised if we fail to generate an update payload.
946 _Log('Failed to process an update: %r', e)
Amin Hassanid7a913a2018-03-13 22:19:24947 return autoupdate_lib.GetNoUpdateResponse(protocol, appid)
Chris Sosa6a3697f2013-01-30 00:44:43948
David Zeuthen52ccd012013-10-31 19:58:26949 # Sign the metadata hash, if requested.
950 signed_metadata_hash = None
951 if self.private_key_for_metadata_hash_signature:
952 signed_metadata_hash = base64.b64encode(Autoupdate._SignMetadataHash(
953 self.private_key_for_metadata_hash_signature,
954 base64.b64decode(metadata_obj.metadata_hash)))
955
956 # Include public key, if requested.
957 public_key_data = None
958 if self.public_key:
959 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
960
Chris Sosa4b951602014-04-10 03:26:07961 update_response = autoupdate_lib.GetUpdateResponse(
Chris Sosa6a3697f2013-01-30 00:44:43962 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 19:58:26963 metadata_obj.is_delta_format, metadata_obj.metadata_size,
Amin Hassanid7a913a2018-03-13 22:19:24964 signed_metadata_hash, public_key_data, protocol, appid,
965 self.critical_update)
Dale Curtisc9aaf3a2011-08-09 22:47:40966
Gilad Arnolde7819e72014-03-21 19:50:48967 _Log('Responding to client to use url %s to get image', url)
Gilad Arnoldd0c71752013-12-06 19:48:45968 return update_response
969
Dale Curtisc9aaf3a2011-08-09 22:47:40970 def HandleHostInfoPing(self, ip):
971 """Returns host info dictionary for the given IP in JSON format."""
972 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 21:47:02973 if ip in self.host_infos.table:
974 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
975
976 def HandleHostLogPing(self, ip):
977 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 22:28:27978 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 21:47:02979 if ip == 'all':
980 return json.dumps(
981 dict([(key, self.host_infos.table[key].log)
982 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 22:28:27983
984 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 21:47:02985 if ip in self.host_infos.table:
986 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 22:47:40987
Gilad Arnold4ba437d2012-10-05 22:28:27988 # If no events were logged for this IP, return an empty log.
989 return json.dumps([])
990
Dale Curtisc9aaf3a2011-08-09 22:47:40991 def HandleSetUpdatePing(self, ip, label):
992 """Sets forced_update_label for a given host."""
993 assert ip, 'No ip provided.'
994 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 21:47:02995 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label