blob: fe930cbbda166b8c3ffd330b6ff627b6a2e8443e [file] [log] [blame]
Darin Petkovc3fd90c2011-05-11 14:23:00 -07001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
rtc@google.comded22402009-10-26 22:36:21 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
David Zeuthen52ccd012013-10-31 12:58:26 -07005import base64
Dale Curtisc9aaf3a2011-08-09 15:47:40 -07006import json
rtc@google.comded22402009-10-26 22:36:21 +00007import os
David Zeuthen52ccd012013-10-31 12:58:26 -07008import struct
Chris Sosa05491b12010-11-08 17:14:16 -08009import subprocess
Gilad Arnolde74b3812013-04-22 11:27:38 -070010import sys
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070011import time
Gilad Arnold0c9c8602012-10-02 23:58:58 -070012import urllib2
Don Garrett0ad09372010-12-06 16:20:30 -080013import urlparse
Chris Sosa7c931362010-10-11 19:49:01 -070014
Gilad Arnoldabb352e2012-09-23 01:24:27 -070015import cherrypy
16
Gilad Arnolde74b3812013-04-22 11:27:38 -070017# Allow importing from dev/host/lib when running from source tree.
18lib_dir = os.path.join(os.path.dirname(__file__), 'host', 'lib')
19if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
20 sys.path.insert(1, lib_dir)
21
joychen921e1fb2013-06-28 11:12:20 -070022import build_util
Chris Sosa52148582012-11-15 15:35:58 -080023import autoupdate_lib
Gilad Arnold55a2a372012-10-02 09:46:32 -070024import common_util
joychen7c2054a2013-07-25 11:14:07 -070025import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 15:17:48 -070026import log_util
Gilad Arnolde74b3812013-04-22 11:27:38 -070027# pylint: disable=F0401
28import update_payload
Chris Sosa05491b12010-11-08 17:14:16 -080029
Gilad Arnoldc65330c2012-09-20 15:17:48 -070030
joychen121fc9b2013-08-02 14:30:30 -070031# If used by client in place of an pre-update version string, forces an update
32# to the client regardless of the relative versions of the payload and client.
33FORCED_UPDATE = 'ForcedUpdate'
34
35# Files needed to serve an update.
36UPDATE_FILES = (
37 constants.UPDATE_FILE,
38 constants.STATEFUL_FILE,
39 constants.METADATA_FILE
40)
41
Gilad Arnoldc65330c2012-09-20 15:17:48 -070042# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080043def _Log(message, *args):
44 return log_util.LogWithTag('UPDATE', message, *args)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070045
rtc@google.comded22402009-10-26 22:36:21 +000046
Gilad Arnold0c9c8602012-10-02 23:58:58 -070047class AutoupdateError(Exception):
48 """Exception classes used by this module."""
49 pass
50
51
Don Garrett0ad09372010-12-06 16:20:30 -080052def _ChangeUrlPort(url, new_port):
53 """Return the URL passed in with a different port"""
54 scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
55 host_port = netloc.split(':')
56
57 if len(host_port) == 1:
58 host_port.append(new_port)
59 else:
60 host_port[1] = new_port
61
62 print host_port
joychen121fc9b2013-08-02 14:30:30 -070063 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-06 16:20:30 -080064
65 return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
66
Chris Sosa6a3697f2013-01-29 16:44:43 -080067def _NonePathJoin(*args):
68 """os.path.join that filters None's from the argument list."""
69 return os.path.join(*filter(None, args))
Don Garrett0ad09372010-12-06 16:20:30 -080070
Chris Sosa6a3697f2013-01-29 16:44:43 -080071
72class HostInfo(object):
Gilad Arnold286a0062012-01-12 13:47:02 -080073 """Records information about an individual host.
74
75 Members:
76 attrs: Static attributes (legacy)
77 log: Complete log of recorded client entries
78 """
79
80 def __init__(self):
81 # A dictionary of current attributes pertaining to the host.
82 self.attrs = {}
83
84 # A list of pairs consisting of a timestamp and a dictionary of recorded
85 # attributes.
86 self.log = []
87
88 def __repr__(self):
89 return 'attrs=%s, log=%s' % (self.attrs, self.log)
90
91 def AddLogEntry(self, entry):
92 """Append a new log entry."""
93 # Append a timestamp.
94 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
95 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
96 # Add entry to hosts' message log.
97 self.log.append(entry)
98
Gilad Arnold286a0062012-01-12 13:47:02 -080099
Chris Sosa6a3697f2013-01-29 16:44:43 -0800100class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 13:47:02 -0800101 """Records information about a set of hosts who engage in update activity.
102
103 Members:
104 table: Table of information on hosts.
105 """
106
107 def __init__(self):
108 # A dictionary of host information. Keys are normally IP addresses.
109 self.table = {}
110
111 def __repr__(self):
112 return '%s' % self.table
113
114 def GetInitHostInfo(self, host_id):
115 """Return a host's info object, or create a new one if none exists."""
116 return self.table.setdefault(host_id, HostInfo())
117
118 def GetHostInfo(self, host_id):
119 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-29 17:07:27 -0800120 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 13:47:02 -0800121
122
Chris Sosa6a3697f2013-01-29 16:44:43 -0800123class UpdateMetadata(object):
124 """Object containing metadata about an update payload."""
125
David Zeuthen52ccd012013-10-31 12:58:26 -0700126 def __init__(self, sha1, sha256, size, is_delta_format, metadata_size,
127 metadata_hash):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800128 self.sha1 = sha1
129 self.sha256 = sha256
130 self.size = size
131 self.is_delta_format = is_delta_format
David Zeuthen52ccd012013-10-31 12:58:26 -0700132 self.metadata_size = metadata_size
133 self.metadata_hash = metadata_hash
Chris Sosa6a3697f2013-01-29 16:44:43 -0800134
135
joychen921e1fb2013-06-28 11:12:20 -0700136class Autoupdate(build_util.BuildObject):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700137 """Class that contains functionality that handles Chrome OS update pings.
138
139 Members:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700140 urlbase: base URL, other than devserver, for update images.
141 forced_image: path to an image to use for all updates.
142 payload_path: path to pre-generated payload to serve.
143 src_image: if specified, creates a delta payload from this image.
144 proxy_port: port of local proxy to tell client to connect to you
145 through.
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700146 patch_kernel: Patch the kernel when generating updates
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700147 board: board for the image. Needed for pre-generating of updates.
148 copy_to_static_root: copies images generated from the cache to ~/static.
149 private_key: path to private key in PEM format.
David Zeuthen52ccd012013-10-31 12:58:26 -0700150 private_key_for_metadata_hash_signature: path to private key in PEM format.
151 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 12:52:23 -0700152 critical_update: whether provisioned payload is critical.
153 remote_payload: whether provisioned payload is remotely staged.
154 max_updates: maximum number of updates we'll try to provision.
155 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700156 """
rtc@google.comded22402009-10-26 22:36:21 +0000157
joychened64b222013-06-21 16:39:34 -0700158 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700159 _PAYLOAD_URL_PREFIX = '/static/'
160 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
161
Chris Sosa6a3697f2013-01-29 16:44:43 -0800162 SHA1_ATTR = 'sha1'
163 SHA256_ATTR = 'sha256'
164 SIZE_ATTR = 'size'
165 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 12:58:26 -0700166 METADATA_SIZE_ATTR = 'metadata_size'
167 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-29 16:44:43 -0800168
joychen121fc9b2013-08-02 14:30:30 -0700169 def __init__(self, xbuddy, urlbase=None, forced_image=None, payload_path=None,
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700170 proxy_port=None, src_image='', patch_kernel=True, board=None,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800171 copy_to_static_root=True, private_key=None,
David Zeuthen52ccd012013-10-31 12:58:26 -0700172 private_key_for_metadata_hash_signature=None, public_key=None,
Chris Sosa52148582012-11-15 15:35:58 -0800173 critical_update=False, remote_payload=False, max_updates= -1,
Chris Sosa6a3697f2013-01-29 16:44:43 -0800174 host_log=False, *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700175 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 14:30:30 -0700176 self.xbuddy = xbuddy
177 self.urlbase = urlbase or None
Chris Sosa0356d3b2010-09-16 15:46:22 -0700178 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700179 self.payload_path = payload_path
Chris Sosa62f720b2010-10-26 21:39:48 -0700180 self.src_image = src_image
Don Garrett0ad09372010-12-06 16:20:30 -0800181 self.proxy_port = proxy_port
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700182 self.patch_kernel = patch_kernel
joychen562699a2013-08-13 15:22:14 -0700183 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-19 16:08:02 -0800184 self.copy_to_static_root = copy_to_static_root
Chris Sosa0f1ec842011-02-14 16:33:22 -0800185 self.private_key = private_key
David Zeuthen52ccd012013-10-31 12:58:26 -0700186 self.private_key_for_metadata_hash_signature = \
187 private_key_for_metadata_hash_signature
188 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800189 self.critical_update = critical_update
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700190 self.remote_payload = remote_payload
Jay Srinivasanac69d262012-10-30 19:05:53 -0700191 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 12:52:23 -0700192 self.host_log = host_log
Don Garrettfff4c322010-11-19 13:37:12 -0800193
Chris Sosa417e55d2011-01-25 16:40:48 -0800194 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700195
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700196 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 13:47:02 -0800197 # information about a given host. A host is identified by its IP address.
198 # The info stored for each host includes a complete log of events for this
199 # host, as well as a dictionary of current attributes derived from events.
200 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700201
Chris Sosa6a3697f2013-01-29 16:44:43 -0800202 @classmethod
203 def _ReadMetadataFromStream(cls, stream):
204 """Returns metadata obj from input json stream that implements .read()."""
205 file_attr_dict = {}
206 try:
207 file_attr_dict = json.loads(stream.read())
208 except IOError:
209 return None
210
211 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
212 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
213 size = file_attr_dict.get(cls.SIZE_ATTR)
214 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 12:58:26 -0700215 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
216 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
217 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
218 metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800219
220 @staticmethod
221 def _ReadMetadataFromFile(payload_dir):
222 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 14:54:16 -0700223 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800224 if os.path.exists(metadata_file):
225 with open(metadata_file, 'r') as metadata_stream:
226 return Autoupdate._ReadMetadataFromStream(metadata_stream)
227
228 @classmethod
229 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
230 """Stores metadata object into the metadata_file of the payload_dir"""
231 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
232 cls.SHA256_ATTR: metadata_obj.sha256,
233 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 12:58:26 -0700234 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
235 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
236 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 14:54:16 -0700237 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800238 with open(metadata_file, 'w') as file_handle:
239 json.dump(file_dict, file_handle)
240
Chris Sosa52148582012-11-15 15:35:58 -0800241 @staticmethod
242 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700243 """Returns the version of the image based on the name of the directory."""
244 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700245 parts = latest_version.split('-')
joychen121fc9b2013-08-02 14:30:30 -0700246 # If we can't get a version number from the directory, default to a high
247 # number to allow the update to happen
248 return parts[1] if len(parts) == 3 else "9999.0.0"
Chris Sosa0356d3b2010-09-16 15:46:22 -0700249
Chris Sosa52148582012-11-15 15:35:58 -0800250 @staticmethod
251 def _CanUpdate(client_version, latest_version):
Don Garrettf90edf02010-11-16 17:36:14 -0800252 """Returns true if the latest_version is greater than the client_version.
253 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800254 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700255
256 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700257 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700258
joychen121fc9b2013-08-02 14:30:30 -0700259 if len(latest_tokens) == len(client_tokens) == 3:
260 return latest_tokens > client_tokens
Chris Sosa0356d3b2010-09-16 15:46:22 -0700261 else:
joychen121fc9b2013-08-02 14:30:30 -0700262 # If the directory name isn't a version number, let it pass.
263 return True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700264
Chris Sosa52148582012-11-15 15:35:58 -0800265 @staticmethod
Gilad Arnolde74b3812013-04-22 11:27:38 -0700266 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700267 try:
Gilad Arnolde74b3812013-04-22 11:27:38 -0700268 with open(filename) as payload_file:
269 payload = update_payload.Payload(payload_file)
270 payload.Init()
271 return payload.IsDelta()
272 except (IOError, update_payload.PayloadError):
273 # For unit tests we may not have real files, so it's ok to ignore these
274 # errors.
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700275 return False
276
Don Garrettf90edf02010-11-16 17:36:14 -0800277 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700278 """Generates an update gz given a full path to an image.
279
280 Args:
281 image_path: Full path to image.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800282 Raises:
283 subprocess.CalledProcessError if the update generator fails to generate a
284 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700285 """
joychen7c2054a2013-07-25 11:14:07 -0700286 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800287 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700288
Chris Sosa0f1ec842011-02-14 16:33:22 -0800289 update_command = [
Chris Sosa5b8b5eb2012-03-27 11:15:27 -0700290 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-29 16:44:43 -0800291 '--image', image_path,
David Zeuthen52ccd012013-10-31 12:58:26 -0700292 '--out_metadata_hash_file', os.path.join(output_dir,
293 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-29 16:44:43 -0800294 '--output', update_path,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800295 ]
Chris Sosa4136e692010-10-28 23:42:37 -0700296
Chris Sosa52148582012-11-15 15:35:58 -0800297 if src_image:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800298 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 15:35:58 -0800299
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700300 if self.patch_kernel:
Chris Sosa52148582012-11-15 15:35:58 -0800301 update_command.append('--patch_kernel')
302
303 if self.private_key:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800304 update_command.extend(['--private_key', self.private_key])
Chris Sosa0f1ec842011-02-14 16:33:22 -0800305
Chris Sosa6a3697f2013-01-29 16:44:43 -0800306 _Log('Running %s', ' '.join(update_command))
307 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700308
Chris Sosa52148582012-11-15 15:35:58 -0800309 @staticmethod
310 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800311 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700312
313 Args:
314 image_path: Full path to image.
Chris Sosa908fd6f2010-11-10 17:31:18 -0800315 Raises:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800316 subprocess.CalledProcessError if the update generator fails to generate a
Chris Sosa908fd6f2010-11-10 17:31:18 -0800317 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700318 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800319 update_command = [
320 'cros_generate_stateful_update_payload',
321 '--image', image_path,
322 '--output_dir', output_dir,
323 ]
324 _Log('Running %s', ' '.join(update_command))
325 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700326
Don Garrettf90edf02010-11-16 17:36:14 -0800327 def FindCachedUpdateImageSubDir(self, src_image, dest_image):
328 """Find directory to store a cached update.
329
Gilad Arnold55a2a372012-10-02 09:46:32 -0700330 Given one, or two images for an update, this finds which cache directory
331 should hold the update files, even if they don't exist yet.
Don Garrettf90edf02010-11-16 17:36:14 -0800332
Gilad Arnold55a2a372012-10-02 09:46:32 -0700333 Returns:
334 A directory path for storing a cached update, of the following form:
335 Non-delta updates:
336 CACHE_DIR/<dest_hash>
337 Delta updates:
338 CACHE_DIR/<src_hash>_<dest_hash>
339 Signed updates (self.private_key):
340 CACHE_DIR/<src_hash>_<dest_hash>+<private_key_hash>
Chris Sosa744e1472011-09-07 19:32:50 -0700341 """
Gilad Arnold55a2a372012-10-02 09:46:32 -0700342 update_dir = ''
Chris Sosa744e1472011-09-07 19:32:50 -0700343 if src_image:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700344 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-16 17:36:14 -0800345
Gilad Arnold55a2a372012-10-02 09:46:32 -0700346 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-07 19:32:50 -0700347 if self.private_key:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700348 update_dir += '+' + common_util.GetFileMd5(self.private_key)
Chris Sosa744e1472011-09-07 19:32:50 -0700349
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700350 if self.patch_kernel:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700351 update_dir += '+patched_kernel'
Chris Sosa9fba7562012-01-31 10:15:47 -0800352
joychen25d25972013-07-30 14:54:16 -0700353 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800354
Don Garrettfff4c322010-11-19 13:37:12 -0800355 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800356 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700357
Chris Sosade91f672010-11-16 10:05:44 -0800358 Args:
Don Garrettf90edf02010-11-16 17:36:14 -0800359 image_path: full path to the image.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800360 output_dir: the directory to write the update payloads to
361 Raises:
362 AutoupdateError if it failed to generate either update or stateful
363 payload.
Chris Sosade91f672010-11-16 10:05:44 -0800364 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800365 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700366
Chris Sosa6a3697f2013-01-29 16:44:43 -0800367 # Delete any previous state in this directory.
368 os.system('rm -rf "%s"' % output_dir)
369 os.makedirs(output_dir)
rtc@google.comded22402009-10-26 22:36:21 +0000370
Chris Sosa6a3697f2013-01-29 16:44:43 -0800371 try:
372 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
373 self.GenerateStatefulFile(image_path, output_dir)
374 except subprocess.CalledProcessError:
375 os.system('rm -rf "%s"' % output_dir)
376 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800377
Chris Sosa75490802013-09-30 17:21:45 -0700378 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-16 17:36:14 -0800379 """Force generates an update payload based on the given image_path.
rtc@google.comded22402009-10-26 22:36:21 +0000380
Chris Sosa0356d3b2010-09-16 15:46:22 -0700381 Args:
382 image_path: full path to the image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700383 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700384 update directory relative to static_image_dir.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800385 Raises:
386 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700387 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800388 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f2010-11-04 17:33:16 -0700389
joychen121fc9b2013-08-02 14:30:30 -0700390 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-25 16:40:48 -0800391 if self.pregenerated_path:
392 return self.pregenerated_path
Don Garrettfff4c322010-11-19 13:37:12 -0800393
Chris Sosa75490802013-09-30 17:21:45 -0700394 # Which sub_dir should hold our cached update image.
395 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800396 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-25 16:40:48 -0800397
joychen121fc9b2013-08-02 14:30:30 -0700398 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-09-30 17:21:45 -0700399 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 14:30:30 -0700400
401 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 11:14:07 -0700402 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700403 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 14:54:16 -0700404 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-25 16:40:48 -0800405 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 14:30:30 -0700406 if not (os.path.exists(cache_update_payload) and
407 os.path.exists(cache_stateful_payload)):
408 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800409
joychen121fc9b2013-08-02 14:30:30 -0700410 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800411 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-21 18:59:21 -0800412
Chris Sosa6a3697f2013-01-29 16:44:43 -0800413 # Generate the cache file.
joychen121fc9b2013-08-02 14:30:30 -0700414 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800415
joychen121fc9b2013-08-02 14:30:30 -0700416 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 15:46:22 -0700417
Chris Sosa75490802013-09-30 17:21:45 -0700418 def _SymlinkUpdateFiles(self, target_dir, link_dir):
419 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 14:30:30 -0700420
421 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-09-30 17:21:45 -0700422 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700423
424 Args:
Chris Sosa75490802013-09-30 17:21:45 -0700425 target_dir: Location of the target files.
426 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700427 """
Chris Sosa75490802013-09-30 17:21:45 -0700428 _Log('Linking %s to %s', target_dir, link_dir)
429 if link_dir == target_dir:
430 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 14:30:30 -0700431 return
432 for f in UPDATE_FILES:
Chris Sosa75490802013-09-30 17:21:45 -0700433 link = os.path.join(link_dir, f)
434 target = os.path.join(target_dir, f)
Alex Deymo3e2d4952013-09-03 21:49:41 -0700435 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700436
joychen121fc9b2013-08-02 14:30:30 -0700437 def GetUpdateForLabel(self, client_version, label,
438 image_name=constants.TEST_IMAGE_FILE):
439 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700440
joychen121fc9b2013-08-02 14:30:30 -0700441 Args:
442 client_version: Current version of the client or FORCED_UPDATE
443 label: the relative directory inside the static dir
444 image_name: If the image type was specified by the update rpc, we try to
445 find an image with this file name first. This is by default
446 "chromiumos_test_image.bin" but can also take any of the values in
447 devserver_constants.ALL_IMAGES
Chris Sosa6a3697f2013-01-29 16:44:43 -0800448 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700449 A relative path to the directory with the update payload.
450 This is the label if an update did not need to be generated, but can
451 be label/cache/hashed_dir_for_update.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800452 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700453 AutoupdateError: If client version is higher than available update found
454 at the directory given by the label.
Don Garrettf90edf02010-11-16 17:36:14 -0800455 """
joychen121fc9b2013-08-02 14:30:30 -0700456 _Log('Update label/file: %s/%s', label, image_name)
457 static_image_dir = _NonePathJoin(self.static_dir, label)
458 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
459 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 11:14:07 -0700460
joychen121fc9b2013-08-02 14:30:30 -0700461 # Update the client only if client version is older than available update.
462 latest_version = self._GetVersionFromDir(static_image_dir)
463 if not (client_version == FORCED_UPDATE or
464 self._CanUpdate(client_version, latest_version)):
465 raise AutoupdateError(
466 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 12:09:35 -0800467
joychen121fc9b2013-08-02 14:30:30 -0700468 if label and os.path.exists(static_update_path):
469 # An update payload was found for the given label, return it.
470 return label
471 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
472 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700473 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
474 # Add links from the static directory to the update.
475 cache_path = _NonePathJoin(self.static_dir, rel_path)
476 self._SymlinkUpdateFiles(cache_path, static_image_dir)
477 return label
Don Garrett0c880e22010-11-17 18:13:37 -0800478
joychen121fc9b2013-08-02 14:30:30 -0700479 # The label didn't resolve.
480 return None
Chris Sosa2c048f12010-10-27 16:05:27 -0700481
482 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-25 16:40:48 -0800483 """Pre-generates an update and prints out the relative path it.
484
Chris Sosa6a3697f2013-01-29 16:44:43 -0800485 Returns relative path of the update.
Chris Sosa65d339b2013-01-21 18:59:21 -0800486
Chris Sosa6a3697f2013-01-29 16:44:43 -0800487 Raises:
488 AutoupdateError if it failed to generate the payload.
489 """
490 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 14:30:30 -0700491 # Does not work with labels so just use static dir. (empty label)
492 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800493 print 'PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
joychen7c2054a2013-07-25 11:14:07 -0700494 constants.UPDATE_FILE)
Chris Sosa417e55d2011-01-25 16:40:48 -0800495 return pregenerated_update
Chris Sosa2c048f12010-10-27 16:05:27 -0700496
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700497 def _GetRemotePayloadAttrs(self, url):
498 """Returns hashes, size and delta flag of a remote update payload.
499
500 Obtain attributes of a payload file available on a remote devserver. This
501 is based on the assumption that the payload URL uses the /static prefix. We
502 need to make sure that both clients (requests) and remote devserver
503 (provisioning) preserve this invariant.
504
505 Args:
506 url: URL of statically staged remote file (http://host:port/static/...)
507 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700508 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700509 """
510 if self._PAYLOAD_URL_PREFIX not in url:
511 raise AutoupdateError(
512 'Payload URL does not have the expected prefix (%s)' %
513 self._PAYLOAD_URL_PREFIX)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800514
joychened64b222013-06-21 16:39:34 -0700515 if self._OLD_PAYLOAD_URL_PREFIX in url:
516 fileinfo_url = url.replace(self._OLD_PAYLOAD_URL_PREFIX,
517 self._FILEINFO_URL_PREFIX)
518 else:
519 fileinfo_url = url.replace(self._PAYLOAD_URL_PREFIX,
520 self._FILEINFO_URL_PREFIX)
521
Chris Sosa6a3697f2013-01-29 16:44:43 -0800522 _Log('Retrieving file info for remote payload via %s', fileinfo_url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700523 try:
524 conn = urllib2.urlopen(fileinfo_url)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800525 metadata_obj = Autoupdate._ReadMetadataFromStream(conn)
526 # These fields are required for remote calls.
527 if not metadata_obj:
528 raise AutoupdateError('Failed to obtain remote payload info')
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700529
Chris Sosa6a3697f2013-01-29 16:44:43 -0800530 return metadata_obj
531 except IOError as e:
532 raise AutoupdateError('Failed to obtain remote payload info: %s', e)
533
David Zeuthen52ccd012013-10-31 12:58:26 -0700534 @staticmethod
535 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 10:38:16 -0800536 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 12:58:26 -0700537
538 Args:
539 payload_dir: The payload directory.
540 Returns:
David Zeuthenf27f1502013-11-13 10:38:16 -0800541 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 12:58:26 -0700542 """
543 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 10:38:16 -0800544 if os.path.exists(path):
545 return base64.b64encode(open(path, 'rb').read())
546 else:
547 return None
David Zeuthen52ccd012013-10-31 12:58:26 -0700548
549 @staticmethod
550 def _GetMetadataSize(payload_filename):
551 """Gets the size of the metadata in a payload file.
552
553 Args:
554 payload_filename: Path to the payload file.
555 Returns:
556 The size of the payload metadata, as reported in the payload header.
557 """
558 # Handle corner-case where unit tests pass in empty payload files.
559 if os.path.getsize(payload_filename) < 20:
560 return 0
561 stream = open(payload_filename, 'rb')
562 stream.seek(16)
563 return struct.unpack('>I', stream.read(4))[0] + 20
564
Chris Sosa6a3697f2013-01-29 16:44:43 -0800565 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700566 """Returns hashes, size and delta flag of a local update payload.
567
568 Args:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800569 payload_dir: Path to the directory the payload is in.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700570 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700571 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700572 """
joychen7c2054a2013-07-25 11:14:07 -0700573 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800574 if not os.path.exists(filename):
575 raise AutoupdateError('update.gz not present in payload dir %s' %
576 payload_dir)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700577
Chris Sosa6a3697f2013-01-29 16:44:43 -0800578 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
579 if not metadata_obj or not (metadata_obj.sha1 and
580 metadata_obj.sha256 and
581 metadata_obj.size):
582 sha1 = common_util.GetFileSha1(filename)
583 sha256 = common_util.GetFileSha256(filename)
584 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 11:27:38 -0700585 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 12:58:26 -0700586 metadata_size = self._GetMetadataSize(filename)
587 metadata_hash = self._GetMetadataHash(payload_dir)
588 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
589 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800590 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700591
Chris Sosa6a3697f2013-01-29 16:44:43 -0800592 return metadata_obj
593
594 def _ProcessUpdateComponents(self, app, event):
595 """Processes the app and event components of an update request.
596
597 Returns tuple containing forced_update_label, client_version, and board.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700598 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800599 # Initialize an empty dictionary for event attributes to log.
600 log_message = {}
Jay Srinivasanac69d262012-10-30 19:05:53 -0700601
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700602 # Determine request IP, strip any IPv6 data for simplicity.
603 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 13:47:02 -0800604 # Obtain (or init) info object for this client.
605 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
606
joychen121fc9b2013-08-02 14:30:30 -0700607 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-29 16:44:43 -0800608 board = None
609 if app:
610 client_version = app.getAttribute('version')
611 channel = app.getAttribute('track')
612 board = (app.hasAttribute('board') and app.getAttribute('board')
joychenb0dfe552013-07-30 10:02:06 -0700613 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-29 16:44:43 -0800614 # Add attributes to log message
615 log_message['version'] = client_version
616 log_message['track'] = channel
617 log_message['board'] = board
618 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700619
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700620 if event:
Gilad Arnold286a0062012-01-12 13:47:02 -0800621 event_result = int(event[0].getAttribute('eventresult'))
622 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700623 client_previous_version = (event[0].getAttribute('previousversion')
624 if event[0].hasAttribute('previousversion')
625 else None)
Gilad Arnold286a0062012-01-12 13:47:02 -0800626 # Store attributes to legacy host info structure
627 curr_host_info.attrs['last_event_status'] = event_result
628 curr_host_info.attrs['last_event_type'] = event_type
629 # Add attributes to log message
630 log_message['event_result'] = event_result
631 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700632 if client_previous_version is not None:
633 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 13:47:02 -0800634
Gilad Arnold8318eac2012-10-04 12:52:23 -0700635 # Log host event, if so instructed.
636 if self.host_log:
637 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700638
Chris Sosa6a3697f2013-01-29 16:44:43 -0800639 return (curr_host_info.attrs.pop('forced_update_label', None),
640 client_version, board)
641
642 def _GetStaticUrl(self):
643 """Returns the static url base that should prefix all payload responses."""
644 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
645 if x_forwarded_host:
646 hostname = 'http://' + x_forwarded_host
647 else:
648 hostname = cherrypy.request.base
649
650 if self.urlbase:
651 static_urlbase = self.urlbase
Chris Sosa6a3697f2013-01-29 16:44:43 -0800652 else:
653 static_urlbase = '%s/static' % hostname
654
655 # If we have a proxy port, adjust the URL we instruct the client to
656 # use to go through the proxy.
657 if self.proxy_port:
658 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
659
660 _Log('Using static url base %s', static_urlbase)
661 _Log('Handling update ping as %s', hostname)
662 return static_urlbase
663
joychen121fc9b2013-08-02 14:30:30 -0700664 def GetPathToPayload(self, label, client_version, board):
665 """Find a payload locally.
666
667 See devserver's update rpc for documentation.
668
669 Args:
670 label: from update request
671 client_version: from update request
672 board: from update request
673 Return:
674 The relative path to an update from the static_dir
675 Raises:
676 AutoupdateError: If the update could not be found.
677 """
678 path_to_payload = None
679 #TODO(joychen): deprecate --payload flag
680 if self.payload_path:
681 # Copy the image from the path to '/forced_payload'
682 label = 'forced_payload'
683 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
684 dest_stateful = os.path.join(self.static_dir, label,
685 constants.STATEFUL_FILE)
686
687 src_path = os.path.abspath(self.payload_path)
688 src_stateful = os.path.join(os.path.dirname(src_path),
689 constants.STATEFUL_FILE)
690 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-03 21:49:41 -0700691 common_util.SymlinkFile(src_path, dest_path)
joychen121fc9b2013-08-02 14:30:30 -0700692 if os.path.exists(src_stateful):
693 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-03 21:49:41 -0700694 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 14:30:30 -0700695 else:
696 _Log('WARN: %s not found. Expected for dev and test builds',
697 constants.STATEFUL_FILE)
698 if os.path.exists(dest_stateful):
699 os.remove(dest_stateful)
700 path_to_payload = self.GetUpdateForLabel(client_version, label)
701 #TODO(joychen): deprecate --image flag
702 elif self.forced_image:
joychendbfe6c92013-08-16 20:03:49 -0700703 if self.forced_image.startswith('xbuddy:'):
704 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-16 20:03:49 -0700705 xbuddy_label = self.forced_image.split(':')[1]
706 self.forced_image = None
joychen365a5742013-08-21 10:41:18 -0700707 # Make sure the xbuddy path target is in the directory.
708 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
709 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 16:45:12 -0700710 self.GetPathToPayload(xbuddy_label, client_version, board)
711 else:
712 src_path = os.path.abspath(self.forced_image)
713 if os.path.exists(src_path) and common_util.IsInsideChroot():
714 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700715 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
716 # Add links from the static directory to the update.
717 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
718 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 14:30:30 -0700719 else:
720 label = label or ''
721 label_list = label.split('/')
722 # Suppose that the path follows old protocol of indexing straight
723 # into static_dir with board/version label.
724 # Attempt to get the update in that directory, generating if necc.
725 path_to_payload = self.GetUpdateForLabel(client_version, label)
726 if path_to_payload is None:
727 # There was no update or image found in the directory.
728 # Let XBuddy find an image, and then generate an update to it.
729 if label_list[0] == 'xbuddy':
730 # If path explicitly calls xbuddy, pop off the tag.
731 label_list.pop()
Chris Sosa75490802013-09-30 17:21:45 -0700732 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 14:30:30 -0700733 if image_name not in constants.ALL_IMAGES:
734 raise AutoupdateError(
735 "Use an image alias: dev, base, test, or recovery.")
736 # Path has been resolved, try to get the image.
737 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
738 image_name)
739 if path_to_payload is None:
740 # Neither image nor update payload found after translation.
741 # Try to get an update to a test image from GS using the label.
742 path_to_payload, _image_name = self.xbuddy.Get(
743 ['remote', label, 'full_payload'])
744
745 # One of the above options should have gotten us a relative path.
746 if path_to_payload is None:
747 raise AutoupdateError('Failed to get an update for: %s' % label)
748 else:
Chris Sosa75490802013-09-30 17:21:45 -0700749 return path_to_payload
joychen121fc9b2013-08-02 14:30:30 -0700750
David Zeuthen52ccd012013-10-31 12:58:26 -0700751 @staticmethod
752 def _SignMetadataHash(private_key_path, metadata_hash):
753 """Signs metadata hash.
754
755 Signs a metadata hash with a private key. This includes padding the
756 hash with PKCS#1 v1.5 padding as well as an ASN.1 header.
757
758 Args:
759 private_key_path: The path to a private key to use for signing.
760 metadata_hash: A raw SHA-256 hash (32 bytes).
761 Returns:
762 The raw signature.
763 """
764 args = ['openssl', 'rsautl', '-pkcs', '-sign', '-inkey', private_key_path]
765 padded_metadata_hash = ('\x30\x31\x30\x0d\x06\x09\x60\x86'
766 '\x48\x01\x65\x03\x04\x02\x01\x05'
767 '\x00\x04\x20') + metadata_hash
768 child = subprocess.Popen(args,
769 stdin=subprocess.PIPE,
770 stdout=subprocess.PIPE)
771 signature, _ = child.communicate(input=padded_metadata_hash)
772 return signature
773
joychen121fc9b2013-08-02 14:30:30 -0700774 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800775 """Handles an update ping from an update client.
776
777 Args:
778 data: XML blob from client.
779 label: optional label for the update.
780 Returns:
781 Update payload message for client.
782 """
783 # Get the static url base that will form that base of our update url e.g.
784 # http://hostname:8080/static/update.gz.
785 static_urlbase = self._GetStaticUrl()
786
787 # Parse the XML we got into the components we care about.
788 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
789
Chris Sosab26b1202013-08-16 16:40:55 -0700790 # Process attributes of the update check.
791 forced_update_label, client_version, board = self._ProcessUpdateComponents(
792 app, event)
793
joychen121fc9b2013-08-02 14:30:30 -0700794 if not update_check:
795 # TODO(sosa): Generate correct non-updatecheck payload to better test
796 # update clients.
797 _Log('Non-update check received. Returning blank payload')
798 return autoupdate_lib.GetNoUpdateResponse(protocol)
799
Chris Sosa6a3697f2013-01-29 16:44:43 -0800800 if forced_update_label:
801 if label:
802 _Log('Label: %s set but being overwritten to %s by request', label,
803 forced_update_label)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800804 label = forced_update_label
805
joychen121fc9b2013-08-02 14:30:30 -0700806 if self.max_updates == 0:
807 # In case max_updates is used, return no response if max reached.
808 _Log('Request received but max number of updates handled')
809 return autoupdate_lib.GetNoUpdateResponse(protocol)
810
811 _Log('Update Check Received. Client is using protocol version: %s',
812 protocol)
813 self.max_updates -= 1
814
Chris Sosa6a3697f2013-01-29 16:44:43 -0800815 # Finally its time to generate the omaha response to give to client that
816 # lets them know where to find the payload and its associated metadata.
817 metadata_obj = None
818
819 try:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700820 # Are we provisioning a remote or local payload?
821 if self.remote_payload:
822 # If no explicit label was provided, use the value of --payload.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800823 if not label:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700824 label = self.payload_path
Chris Sosa0356d3b2010-09-16 15:46:22 -0700825
Chris Sosa52f15bc2013-08-13 17:14:15 -0700826 # TODO(sosa): Remove backwards-compatible hack.
Chris Sosab26b1202013-08-16 16:40:55 -0700827 if not '.bin' in label:
Chris Sosa52f15bc2013-08-13 17:14:15 -0700828 url = _NonePathJoin(static_urlbase, label, 'update.gz')
829 else:
830 url = _NonePathJoin(static_urlbase, label)
Chris Sosa5d342a22010-09-28 16:54:41 -0700831
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700832 # Get remote payload attributes.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800833 metadata_obj = self._GetRemotePayloadAttrs(url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700834 else:
joychen121fc9b2013-08-02 14:30:30 -0700835 path_to_payload = self.GetPathToPayload(label, client_version, board)
836 url = _NonePathJoin(static_urlbase, path_to_payload,
joychen7c2054a2013-07-25 11:14:07 -0700837 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700838 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800839 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800840 except AutoupdateError as e:
841 # Raised if we fail to generate an update payload.
842 _Log('Failed to process an update: %r', e)
843 return autoupdate_lib.GetNoUpdateResponse(protocol)
844
David Zeuthen52ccd012013-10-31 12:58:26 -0700845 # Sign the metadata hash, if requested.
846 signed_metadata_hash = None
847 if self.private_key_for_metadata_hash_signature:
848 signed_metadata_hash = base64.b64encode(Autoupdate._SignMetadataHash(
849 self.private_key_for_metadata_hash_signature,
850 base64.b64decode(metadata_obj.metadata_hash)))
851
852 # Include public key, if requested.
853 public_key_data = None
854 if self.public_key:
855 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
856
Chris Sosa6a3697f2013-01-29 16:44:43 -0800857 _Log('Responding to client to use url %s to get image', url)
858 return autoupdate_lib.GetUpdateResponse(
859 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 12:58:26 -0700860 metadata_obj.is_delta_format, metadata_obj.metadata_size,
861 signed_metadata_hash, public_key_data, protocol, self.critical_update)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700862
863 def HandleHostInfoPing(self, ip):
864 """Returns host info dictionary for the given IP in JSON format."""
865 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800866 if ip in self.host_infos.table:
867 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
868
869 def HandleHostLogPing(self, ip):
870 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700871 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 13:47:02 -0800872 if ip == 'all':
873 return json.dumps(
874 dict([(key, self.host_infos.table[key].log)
875 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700876
877 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 13:47:02 -0800878 if ip in self.host_infos.table:
879 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700880
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700881 # If no events were logged for this IP, return an empty log.
882 return json.dumps([])
883
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700884 def HandleSetUpdatePing(self, ip, label):
885 """Sets forced_update_label for a given host."""
886 assert ip, 'No ip provided.'
887 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800888 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label