blob: 1eacf44ed05905b93cadf8432dfba72e09a13fb8 [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
Gilad Arnoldd8d595c2014-03-21 13:00:41 -07005"""Devserver module for handling update client requests."""
6
David Zeuthen52ccd012013-10-31 12:58:26 -07007import base64
Dale Curtisc9aaf3a2011-08-09 15:47:40 -07008import json
rtc@google.comded22402009-10-26 22:36:21 +00009import os
Gilad Arnoldd0c71752013-12-06 11:48:45 -080010import random
David Zeuthen52ccd012013-10-31 12:58:26 -070011import struct
Chris Sosa05491b12010-11-08 17:14:16 -080012import subprocess
Gilad Arnolde74b3812013-04-22 11:27:38 -070013import sys
Gilad Arnoldd0c71752013-12-06 11:48:45 -080014import threading
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070015import time
Gilad Arnold0c9c8602012-10-02 23:58:58 -070016import urllib2
Don Garrett0ad09372010-12-06 16:20:30 -080017import urlparse
Chris Sosa7c931362010-10-11 19:49:01 -070018
Gilad Arnoldabb352e2012-09-23 01:24:27 -070019import cherrypy
20
Gilad Arnolde74b3812013-04-22 11:27:38 -070021# Allow importing from dev/host/lib when running from source tree.
22lib_dir = os.path.join(os.path.dirname(__file__), 'host', 'lib')
23if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
24 sys.path.insert(1, lib_dir)
25
joychen921e1fb2013-06-28 11:12:20 -070026import build_util
Chris Sosa52148582012-11-15 15:35:58 -080027import autoupdate_lib
Gilad Arnold55a2a372012-10-02 09:46:32 -070028import common_util
joychen7c2054a2013-07-25 11:14:07 -070029import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 15:17:48 -070030import log_util
Gilad Arnolde74b3812013-04-22 11:27:38 -070031# pylint: disable=F0401
32import update_payload
Chris Sosa05491b12010-11-08 17:14:16 -080033
Gilad Arnoldc65330c2012-09-20 15:17:48 -070034
joychen121fc9b2013-08-02 14:30:30 -070035# If used by client in place of an pre-update version string, forces an update
36# to the client regardless of the relative versions of the payload and client.
37FORCED_UPDATE = 'ForcedUpdate'
38
39# Files needed to serve an update.
40UPDATE_FILES = (
41 constants.UPDATE_FILE,
42 constants.STATEFUL_FILE,
43 constants.METADATA_FILE
44)
45
Gilad Arnoldc65330c2012-09-20 15:17:48 -070046# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080047def _Log(message, *args):
48 return log_util.LogWithTag('UPDATE', message, *args)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070049
rtc@google.comded22402009-10-26 22:36:21 +000050
Gilad Arnold0c9c8602012-10-02 23:58:58 -070051class AutoupdateError(Exception):
52 """Exception classes used by this module."""
53 pass
54
55
Don Garrett0ad09372010-12-06 16:20:30 -080056def _ChangeUrlPort(url, new_port):
57 """Return the URL passed in with a different port"""
58 scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
59 host_port = netloc.split(':')
60
61 if len(host_port) == 1:
62 host_port.append(new_port)
63 else:
64 host_port[1] = new_port
65
66 print host_port
joychen121fc9b2013-08-02 14:30:30 -070067 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-06 16:20:30 -080068
69 return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
70
Chris Sosa6a3697f2013-01-29 16:44:43 -080071def _NonePathJoin(*args):
72 """os.path.join that filters None's from the argument list."""
73 return os.path.join(*filter(None, args))
Don Garrett0ad09372010-12-06 16:20:30 -080074
Chris Sosa6a3697f2013-01-29 16:44:43 -080075
76class HostInfo(object):
Gilad Arnold286a0062012-01-12 13:47:02 -080077 """Records information about an individual host.
78
79 Members:
80 attrs: Static attributes (legacy)
81 log: Complete log of recorded client entries
82 """
83
84 def __init__(self):
85 # A dictionary of current attributes pertaining to the host.
86 self.attrs = {}
87
88 # A list of pairs consisting of a timestamp and a dictionary of recorded
89 # attributes.
90 self.log = []
91
92 def __repr__(self):
93 return 'attrs=%s, log=%s' % (self.attrs, self.log)
94
95 def AddLogEntry(self, entry):
96 """Append a new log entry."""
97 # Append a timestamp.
98 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
99 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
100 # Add entry to hosts' message log.
101 self.log.append(entry)
102
Gilad Arnold286a0062012-01-12 13:47:02 -0800103
Chris Sosa6a3697f2013-01-29 16:44:43 -0800104class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 13:47:02 -0800105 """Records information about a set of hosts who engage in update activity.
106
107 Members:
108 table: Table of information on hosts.
109 """
110
111 def __init__(self):
112 # A dictionary of host information. Keys are normally IP addresses.
113 self.table = {}
114
115 def __repr__(self):
116 return '%s' % self.table
117
118 def GetInitHostInfo(self, host_id):
119 """Return a host's info object, or create a new one if none exists."""
120 return self.table.setdefault(host_id, HostInfo())
121
122 def GetHostInfo(self, host_id):
123 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-29 17:07:27 -0800124 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 13:47:02 -0800125
126
Chris Sosa6a3697f2013-01-29 16:44:43 -0800127class UpdateMetadata(object):
128 """Object containing metadata about an update payload."""
129
David Zeuthen52ccd012013-10-31 12:58:26 -0700130 def __init__(self, sha1, sha256, size, is_delta_format, metadata_size,
131 metadata_hash):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800132 self.sha1 = sha1
133 self.sha256 = sha256
134 self.size = size
135 self.is_delta_format = is_delta_format
David Zeuthen52ccd012013-10-31 12:58:26 -0700136 self.metadata_size = metadata_size
137 self.metadata_hash = metadata_hash
Chris Sosa6a3697f2013-01-29 16:44:43 -0800138
139
joychen921e1fb2013-06-28 11:12:20 -0700140class Autoupdate(build_util.BuildObject):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700141 """Class that contains functionality that handles Chrome OS update pings.
142
143 Members:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700144 urlbase: base URL, other than devserver, for update images.
145 forced_image: path to an image to use for all updates.
146 payload_path: path to pre-generated payload to serve.
147 src_image: if specified, creates a delta payload from this image.
148 proxy_port: port of local proxy to tell client to connect to you
149 through.
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700150 patch_kernel: Patch the kernel when generating updates
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700151 board: board for the image. Needed for pre-generating of updates.
152 copy_to_static_root: copies images generated from the cache to ~/static.
153 private_key: path to private key in PEM format.
David Zeuthen52ccd012013-10-31 12:58:26 -0700154 private_key_for_metadata_hash_signature: path to private key in PEM format.
155 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 12:52:23 -0700156 critical_update: whether provisioned payload is critical.
157 remote_payload: whether provisioned payload is remotely staged.
158 max_updates: maximum number of updates we'll try to provision.
159 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700160 """
rtc@google.comded22402009-10-26 22:36:21 +0000161
joychened64b222013-06-21 16:39:34 -0700162 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700163 _PAYLOAD_URL_PREFIX = '/static/'
164 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
165
Chris Sosa6a3697f2013-01-29 16:44:43 -0800166 SHA1_ATTR = 'sha1'
167 SHA256_ATTR = 'sha256'
168 SIZE_ATTR = 'size'
169 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 12:58:26 -0700170 METADATA_SIZE_ATTR = 'metadata_size'
171 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-29 16:44:43 -0800172
joychen121fc9b2013-08-02 14:30:30 -0700173 def __init__(self, xbuddy, urlbase=None, forced_image=None, payload_path=None,
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700174 proxy_port=None, src_image='', patch_kernel=True, board=None,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800175 copy_to_static_root=True, private_key=None,
David Zeuthen52ccd012013-10-31 12:58:26 -0700176 private_key_for_metadata_hash_signature=None, public_key=None,
Chris Sosa52148582012-11-15 15:35:58 -0800177 critical_update=False, remote_payload=False, max_updates= -1,
Chris Sosa6a3697f2013-01-29 16:44:43 -0800178 host_log=False, *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700179 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 14:30:30 -0700180 self.xbuddy = xbuddy
181 self.urlbase = urlbase or None
Chris Sosa0356d3b2010-09-16 15:46:22 -0700182 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700183 self.payload_path = payload_path
Chris Sosa62f720b2010-10-26 21:39:48 -0700184 self.src_image = src_image
Don Garrett0ad09372010-12-06 16:20:30 -0800185 self.proxy_port = proxy_port
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700186 self.patch_kernel = patch_kernel
joychen562699a2013-08-13 15:22:14 -0700187 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-19 16:08:02 -0800188 self.copy_to_static_root = copy_to_static_root
Chris Sosa0f1ec842011-02-14 16:33:22 -0800189 self.private_key = private_key
David Zeuthen52ccd012013-10-31 12:58:26 -0700190 self.private_key_for_metadata_hash_signature = \
191 private_key_for_metadata_hash_signature
192 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800193 self.critical_update = critical_update
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700194 self.remote_payload = remote_payload
Jay Srinivasanac69d262012-10-30 19:05:53 -0700195 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 12:52:23 -0700196 self.host_log = host_log
Don Garrettfff4c322010-11-19 13:37:12 -0800197
Chris Sosa417e55d2011-01-25 16:40:48 -0800198 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700199
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700200 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 13:47:02 -0800201 # information about a given host. A host is identified by its IP address.
202 # The info stored for each host includes a complete log of events for this
203 # host, as well as a dictionary of current attributes derived from events.
204 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700205
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800206 self.curr_request_id = -1
207 self._update_response_lock = threading.Lock()
208
Chris Sosa6a3697f2013-01-29 16:44:43 -0800209 @classmethod
210 def _ReadMetadataFromStream(cls, stream):
211 """Returns metadata obj from input json stream that implements .read()."""
212 file_attr_dict = {}
213 try:
214 file_attr_dict = json.loads(stream.read())
215 except IOError:
216 return None
217
218 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
219 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
220 size = file_attr_dict.get(cls.SIZE_ATTR)
221 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 12:58:26 -0700222 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
223 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
224 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
225 metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800226
227 @staticmethod
228 def _ReadMetadataFromFile(payload_dir):
229 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 14:54:16 -0700230 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800231 if os.path.exists(metadata_file):
232 with open(metadata_file, 'r') as metadata_stream:
233 return Autoupdate._ReadMetadataFromStream(metadata_stream)
234
235 @classmethod
236 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
237 """Stores metadata object into the metadata_file of the payload_dir"""
238 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
239 cls.SHA256_ATTR: metadata_obj.sha256,
240 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 12:58:26 -0700241 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
242 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
243 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 14:54:16 -0700244 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800245 with open(metadata_file, 'w') as file_handle:
246 json.dump(file_dict, file_handle)
247
Chris Sosa52148582012-11-15 15:35:58 -0800248 @staticmethod
249 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700250 """Returns the version of the image based on the name of the directory."""
251 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700252 parts = latest_version.split('-')
joychen121fc9b2013-08-02 14:30:30 -0700253 # If we can't get a version number from the directory, default to a high
254 # number to allow the update to happen
255 return parts[1] if len(parts) == 3 else "9999.0.0"
Chris Sosa0356d3b2010-09-16 15:46:22 -0700256
Chris Sosa52148582012-11-15 15:35:58 -0800257 @staticmethod
258 def _CanUpdate(client_version, latest_version):
Don Garrettf90edf02010-11-16 17:36:14 -0800259 """Returns true if the latest_version is greater than the client_version.
260 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800261 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700262
263 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700264 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700265
joychen121fc9b2013-08-02 14:30:30 -0700266 if len(latest_tokens) == len(client_tokens) == 3:
267 return latest_tokens > client_tokens
Chris Sosa0356d3b2010-09-16 15:46:22 -0700268 else:
joychen121fc9b2013-08-02 14:30:30 -0700269 # If the directory name isn't a version number, let it pass.
270 return True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700271
Chris Sosa52148582012-11-15 15:35:58 -0800272 @staticmethod
Gilad Arnolde74b3812013-04-22 11:27:38 -0700273 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700274 try:
Gilad Arnolde74b3812013-04-22 11:27:38 -0700275 with open(filename) as payload_file:
276 payload = update_payload.Payload(payload_file)
277 payload.Init()
278 return payload.IsDelta()
279 except (IOError, update_payload.PayloadError):
280 # For unit tests we may not have real files, so it's ok to ignore these
281 # errors.
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700282 return False
283
Don Garrettf90edf02010-11-16 17:36:14 -0800284 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700285 """Generates an update gz given a full path to an image.
286
287 Args:
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700288 src_image: Path to a source image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700289 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700290 output_dir: Path to the generated update file.
291
Chris Sosa6a3697f2013-01-29 16:44:43 -0800292 Raises:
293 subprocess.CalledProcessError if the update generator fails to generate a
294 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700295 """
joychen7c2054a2013-07-25 11:14:07 -0700296 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800297 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700298
Chris Sosa0f1ec842011-02-14 16:33:22 -0800299 update_command = [
Chris Sosa5b8b5eb2012-03-27 11:15:27 -0700300 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-29 16:44:43 -0800301 '--image', image_path,
David Zeuthen52ccd012013-10-31 12:58:26 -0700302 '--out_metadata_hash_file', os.path.join(output_dir,
303 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-29 16:44:43 -0800304 '--output', update_path,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800305 ]
Chris Sosa4136e692010-10-28 23:42:37 -0700306
Chris Sosa52148582012-11-15 15:35:58 -0800307 if src_image:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800308 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 15:35:58 -0800309
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700310 if self.patch_kernel:
Chris Sosa52148582012-11-15 15:35:58 -0800311 update_command.append('--patch_kernel')
312
313 if self.private_key:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800314 update_command.extend(['--private_key', self.private_key])
Chris Sosa0f1ec842011-02-14 16:33:22 -0800315
Chris Sosa6a3697f2013-01-29 16:44:43 -0800316 _Log('Running %s', ' '.join(update_command))
317 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700318
Chris Sosa52148582012-11-15 15:35:58 -0800319 @staticmethod
320 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800321 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700322
323 Args:
324 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700325 output_dir: Directory for emitting the stateful update payload.
326
Chris Sosa908fd6f2010-11-10 17:31:18 -0800327 Raises:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800328 subprocess.CalledProcessError if the update generator fails to generate a
Chris Sosa908fd6f2010-11-10 17:31:18 -0800329 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700330 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800331 update_command = [
332 'cros_generate_stateful_update_payload',
333 '--image', image_path,
334 '--output_dir', output_dir,
335 ]
336 _Log('Running %s', ' '.join(update_command))
337 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700338
Don Garrettf90edf02010-11-16 17:36:14 -0800339 def FindCachedUpdateImageSubDir(self, src_image, dest_image):
340 """Find directory to store a cached update.
341
Gilad Arnold55a2a372012-10-02 09:46:32 -0700342 Given one, or two images for an update, this finds which cache directory
343 should hold the update files, even if they don't exist yet.
Don Garrettf90edf02010-11-16 17:36:14 -0800344
Gilad Arnold55a2a372012-10-02 09:46:32 -0700345 Returns:
346 A directory path for storing a cached update, of the following form:
347 Non-delta updates:
348 CACHE_DIR/<dest_hash>
349 Delta updates:
350 CACHE_DIR/<src_hash>_<dest_hash>
351 Signed updates (self.private_key):
352 CACHE_DIR/<src_hash>_<dest_hash>+<private_key_hash>
Chris Sosa744e1472011-09-07 19:32:50 -0700353 """
Gilad Arnold55a2a372012-10-02 09:46:32 -0700354 update_dir = ''
Chris Sosa744e1472011-09-07 19:32:50 -0700355 if src_image:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700356 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-16 17:36:14 -0800357
Gilad Arnold55a2a372012-10-02 09:46:32 -0700358 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-07 19:32:50 -0700359 if self.private_key:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700360 update_dir += '+' + common_util.GetFileMd5(self.private_key)
Chris Sosa744e1472011-09-07 19:32:50 -0700361
Chris Sosa3ae4dc12013-03-29 11:47:00 -0700362 if self.patch_kernel:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700363 update_dir += '+patched_kernel'
Chris Sosa9fba7562012-01-31 10:15:47 -0800364
joychen25d25972013-07-30 14:54:16 -0700365 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800366
Don Garrettfff4c322010-11-19 13:37:12 -0800367 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800368 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700369
Chris Sosade91f672010-11-16 10:05:44 -0800370 Args:
Don Garrettf90edf02010-11-16 17:36:14 -0800371 image_path: full path to the image.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800372 output_dir: the directory to write the update payloads to
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700373
Chris Sosa6a3697f2013-01-29 16:44:43 -0800374 Raises:
375 AutoupdateError if it failed to generate either update or stateful
376 payload.
Chris Sosade91f672010-11-16 10:05:44 -0800377 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800378 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700379
Chris Sosa6a3697f2013-01-29 16:44:43 -0800380 # Delete any previous state in this directory.
381 os.system('rm -rf "%s"' % output_dir)
382 os.makedirs(output_dir)
rtc@google.comded22402009-10-26 22:36:21 +0000383
Chris Sosa6a3697f2013-01-29 16:44:43 -0800384 try:
385 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
386 self.GenerateStatefulFile(image_path, output_dir)
387 except subprocess.CalledProcessError:
388 os.system('rm -rf "%s"' % output_dir)
389 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800390
Chris Sosa75490802013-09-30 17:21:45 -0700391 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-16 17:36:14 -0800392 """Force generates an update payload based on the given image_path.
rtc@google.comded22402009-10-26 22:36:21 +0000393
Chris Sosa0356d3b2010-09-16 15:46:22 -0700394 Args:
395 image_path: full path to the image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700396
Chris Sosa0356d3b2010-09-16 15:46:22 -0700397 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700398 update directory relative to static_image_dir.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700399
Chris Sosa6a3697f2013-01-29 16:44:43 -0800400 Raises:
401 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700402 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800403 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f2010-11-04 17:33:16 -0700404
joychen121fc9b2013-08-02 14:30:30 -0700405 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-25 16:40:48 -0800406 if self.pregenerated_path:
407 return self.pregenerated_path
Don Garrettfff4c322010-11-19 13:37:12 -0800408
Chris Sosa75490802013-09-30 17:21:45 -0700409 # Which sub_dir should hold our cached update image.
410 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800411 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-25 16:40:48 -0800412
joychen121fc9b2013-08-02 14:30:30 -0700413 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-09-30 17:21:45 -0700414 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 14:30:30 -0700415
416 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 11:14:07 -0700417 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700418 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 14:54:16 -0700419 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-25 16:40:48 -0800420 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 14:30:30 -0700421 if not (os.path.exists(cache_update_payload) and
422 os.path.exists(cache_stateful_payload)):
423 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800424
joychen121fc9b2013-08-02 14:30:30 -0700425 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800426 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-21 18:59:21 -0800427
Chris Sosa6a3697f2013-01-29 16:44:43 -0800428 # Generate the cache file.
joychen121fc9b2013-08-02 14:30:30 -0700429 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800430
joychen121fc9b2013-08-02 14:30:30 -0700431 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 15:46:22 -0700432
Chris Sosa75490802013-09-30 17:21:45 -0700433 def _SymlinkUpdateFiles(self, target_dir, link_dir):
434 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 14:30:30 -0700435
436 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-09-30 17:21:45 -0700437 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700438
439 Args:
Chris Sosa75490802013-09-30 17:21:45 -0700440 target_dir: Location of the target files.
441 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700442 """
Chris Sosa75490802013-09-30 17:21:45 -0700443 _Log('Linking %s to %s', target_dir, link_dir)
444 if link_dir == target_dir:
445 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 14:30:30 -0700446 return
447 for f in UPDATE_FILES:
Chris Sosa75490802013-09-30 17:21:45 -0700448 link = os.path.join(link_dir, f)
449 target = os.path.join(target_dir, f)
Alex Deymo3e2d4952013-09-03 21:49:41 -0700450 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700451
joychen121fc9b2013-08-02 14:30:30 -0700452 def GetUpdateForLabel(self, client_version, label,
453 image_name=constants.TEST_IMAGE_FILE):
454 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700455
joychen121fc9b2013-08-02 14:30:30 -0700456 Args:
457 client_version: Current version of the client or FORCED_UPDATE
458 label: the relative directory inside the static dir
459 image_name: If the image type was specified by the update rpc, we try to
460 find an image with this file name first. This is by default
461 "chromiumos_test_image.bin" but can also take any of the values in
462 devserver_constants.ALL_IMAGES
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700463
Chris Sosa6a3697f2013-01-29 16:44:43 -0800464 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700465 A relative path to the directory with the update payload.
466 This is the label if an update did not need to be generated, but can
467 be label/cache/hashed_dir_for_update.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700468
Chris Sosa6a3697f2013-01-29 16:44:43 -0800469 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700470 AutoupdateError: If client version is higher than available update found
471 at the directory given by the label.
Don Garrettf90edf02010-11-16 17:36:14 -0800472 """
joychen121fc9b2013-08-02 14:30:30 -0700473 _Log('Update label/file: %s/%s', label, image_name)
474 static_image_dir = _NonePathJoin(self.static_dir, label)
475 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
476 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 11:14:07 -0700477
joychen121fc9b2013-08-02 14:30:30 -0700478 # Update the client only if client version is older than available update.
479 latest_version = self._GetVersionFromDir(static_image_dir)
480 if not (client_version == FORCED_UPDATE or
481 self._CanUpdate(client_version, latest_version)):
482 raise AutoupdateError(
483 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 12:09:35 -0800484
joychen121fc9b2013-08-02 14:30:30 -0700485 if label and os.path.exists(static_update_path):
486 # An update payload was found for the given label, return it.
487 return label
488 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
489 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700490 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
491 # Add links from the static directory to the update.
492 cache_path = _NonePathJoin(self.static_dir, rel_path)
493 self._SymlinkUpdateFiles(cache_path, static_image_dir)
494 return label
Don Garrett0c880e22010-11-17 18:13:37 -0800495
joychen121fc9b2013-08-02 14:30:30 -0700496 # The label didn't resolve.
497 return None
Chris Sosa2c048f12010-10-27 16:05:27 -0700498
499 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-25 16:40:48 -0800500 """Pre-generates an update and prints out the relative path it.
501
Chris Sosa6a3697f2013-01-29 16:44:43 -0800502 Returns relative path of the update.
Chris Sosa65d339b2013-01-21 18:59:21 -0800503
Chris Sosa6a3697f2013-01-29 16:44:43 -0800504 Raises:
505 AutoupdateError if it failed to generate the payload.
506 """
507 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 14:30:30 -0700508 # Does not work with labels so just use static dir. (empty label)
509 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800510 print 'PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
joychen7c2054a2013-07-25 11:14:07 -0700511 constants.UPDATE_FILE)
Chris Sosa417e55d2011-01-25 16:40:48 -0800512 return pregenerated_update
Chris Sosa2c048f12010-10-27 16:05:27 -0700513
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700514 def _GetRemotePayloadAttrs(self, url):
515 """Returns hashes, size and delta flag of a remote update payload.
516
517 Obtain attributes of a payload file available on a remote devserver. This
518 is based on the assumption that the payload URL uses the /static prefix. We
519 need to make sure that both clients (requests) and remote devserver
520 (provisioning) preserve this invariant.
521
522 Args:
523 url: URL of statically staged remote file (http://host:port/static/...)
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700524
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700525 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700526 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700527 """
528 if self._PAYLOAD_URL_PREFIX not in url:
529 raise AutoupdateError(
530 'Payload URL does not have the expected prefix (%s)' %
531 self._PAYLOAD_URL_PREFIX)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800532
joychened64b222013-06-21 16:39:34 -0700533 if self._OLD_PAYLOAD_URL_PREFIX in url:
534 fileinfo_url = url.replace(self._OLD_PAYLOAD_URL_PREFIX,
535 self._FILEINFO_URL_PREFIX)
536 else:
537 fileinfo_url = url.replace(self._PAYLOAD_URL_PREFIX,
538 self._FILEINFO_URL_PREFIX)
539
Chris Sosa6a3697f2013-01-29 16:44:43 -0800540 _Log('Retrieving file info for remote payload via %s', fileinfo_url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700541 try:
542 conn = urllib2.urlopen(fileinfo_url)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800543 metadata_obj = Autoupdate._ReadMetadataFromStream(conn)
544 # These fields are required for remote calls.
545 if not metadata_obj:
546 raise AutoupdateError('Failed to obtain remote payload info')
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700547
Chris Sosa6a3697f2013-01-29 16:44:43 -0800548 return metadata_obj
549 except IOError as e:
550 raise AutoupdateError('Failed to obtain remote payload info: %s', e)
551
David Zeuthen52ccd012013-10-31 12:58:26 -0700552 @staticmethod
553 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 10:38:16 -0800554 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 12:58:26 -0700555
556 Args:
557 payload_dir: The payload directory.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700558
David Zeuthen52ccd012013-10-31 12:58:26 -0700559 Returns:
David Zeuthenf27f1502013-11-13 10:38:16 -0800560 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 12:58:26 -0700561 """
562 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 10:38:16 -0800563 if os.path.exists(path):
564 return base64.b64encode(open(path, 'rb').read())
565 else:
566 return None
David Zeuthen52ccd012013-10-31 12:58:26 -0700567
568 @staticmethod
569 def _GetMetadataSize(payload_filename):
570 """Gets the size of the metadata in a payload file.
571
572 Args:
573 payload_filename: Path to the payload file.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700574
David Zeuthen52ccd012013-10-31 12:58:26 -0700575 Returns:
576 The size of the payload metadata, as reported in the payload header.
577 """
578 # Handle corner-case where unit tests pass in empty payload files.
579 if os.path.getsize(payload_filename) < 20:
580 return 0
581 stream = open(payload_filename, 'rb')
582 stream.seek(16)
583 return struct.unpack('>I', stream.read(4))[0] + 20
584
Chris Sosa6a3697f2013-01-29 16:44:43 -0800585 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700586 """Returns hashes, size and delta flag of a local update payload.
587
588 Args:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800589 payload_dir: Path to the directory the payload is in.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700590
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700591 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700592 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700593 """
joychen7c2054a2013-07-25 11:14:07 -0700594 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800595 if not os.path.exists(filename):
596 raise AutoupdateError('update.gz not present in payload dir %s' %
597 payload_dir)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700598
Chris Sosa6a3697f2013-01-29 16:44:43 -0800599 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
600 if not metadata_obj or not (metadata_obj.sha1 and
601 metadata_obj.sha256 and
602 metadata_obj.size):
603 sha1 = common_util.GetFileSha1(filename)
604 sha256 = common_util.GetFileSha256(filename)
605 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 11:27:38 -0700606 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 12:58:26 -0700607 metadata_size = self._GetMetadataSize(filename)
608 metadata_hash = self._GetMetadataHash(payload_dir)
609 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
610 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800611 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700612
Chris Sosa6a3697f2013-01-29 16:44:43 -0800613 return metadata_obj
614
615 def _ProcessUpdateComponents(self, app, event):
616 """Processes the app and event components of an update request.
617
618 Returns tuple containing forced_update_label, client_version, and board.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700619 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800620 # Initialize an empty dictionary for event attributes to log.
621 log_message = {}
Jay Srinivasanac69d262012-10-30 19:05:53 -0700622
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700623 # Determine request IP, strip any IPv6 data for simplicity.
624 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 13:47:02 -0800625 # Obtain (or init) info object for this client.
626 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
627
joychen121fc9b2013-08-02 14:30:30 -0700628 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-29 16:44:43 -0800629 board = None
630 if app:
631 client_version = app.getAttribute('version')
632 channel = app.getAttribute('track')
633 board = (app.hasAttribute('board') and app.getAttribute('board')
joychenb0dfe552013-07-30 10:02:06 -0700634 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-29 16:44:43 -0800635 # Add attributes to log message
636 log_message['version'] = client_version
637 log_message['track'] = channel
638 log_message['board'] = board
639 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700640
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700641 if event:
Gilad Arnold286a0062012-01-12 13:47:02 -0800642 event_result = int(event[0].getAttribute('eventresult'))
643 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700644 client_previous_version = (event[0].getAttribute('previousversion')
645 if event[0].hasAttribute('previousversion')
646 else None)
Gilad Arnold286a0062012-01-12 13:47:02 -0800647 # Store attributes to legacy host info structure
648 curr_host_info.attrs['last_event_status'] = event_result
649 curr_host_info.attrs['last_event_type'] = event_type
650 # Add attributes to log message
651 log_message['event_result'] = event_result
652 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700653 if client_previous_version is not None:
654 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 13:47:02 -0800655
Gilad Arnold8318eac2012-10-04 12:52:23 -0700656 # Log host event, if so instructed.
657 if self.host_log:
658 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700659
Chris Sosa6a3697f2013-01-29 16:44:43 -0800660 return (curr_host_info.attrs.pop('forced_update_label', None),
661 client_version, board)
662
663 def _GetStaticUrl(self):
664 """Returns the static url base that should prefix all payload responses."""
665 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
666 if x_forwarded_host:
667 hostname = 'http://' + x_forwarded_host
668 else:
669 hostname = cherrypy.request.base
670
671 if self.urlbase:
672 static_urlbase = self.urlbase
Chris Sosa6a3697f2013-01-29 16:44:43 -0800673 else:
674 static_urlbase = '%s/static' % hostname
675
676 # If we have a proxy port, adjust the URL we instruct the client to
677 # use to go through the proxy.
678 if self.proxy_port:
679 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
680
681 _Log('Using static url base %s', static_urlbase)
682 _Log('Handling update ping as %s', hostname)
683 return static_urlbase
684
joychen121fc9b2013-08-02 14:30:30 -0700685 def GetPathToPayload(self, label, client_version, board):
686 """Find a payload locally.
687
688 See devserver's update rpc for documentation.
689
690 Args:
691 label: from update request
692 client_version: from update request
693 board: from update request
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700694
695 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700696 The relative path to an update from the static_dir
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700697
joychen121fc9b2013-08-02 14:30:30 -0700698 Raises:
699 AutoupdateError: If the update could not be found.
700 """
701 path_to_payload = None
702 #TODO(joychen): deprecate --payload flag
703 if self.payload_path:
704 # Copy the image from the path to '/forced_payload'
705 label = 'forced_payload'
706 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
707 dest_stateful = os.path.join(self.static_dir, label,
708 constants.STATEFUL_FILE)
709
710 src_path = os.path.abspath(self.payload_path)
711 src_stateful = os.path.join(os.path.dirname(src_path),
712 constants.STATEFUL_FILE)
713 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-03 21:49:41 -0700714 common_util.SymlinkFile(src_path, dest_path)
joychen121fc9b2013-08-02 14:30:30 -0700715 if os.path.exists(src_stateful):
716 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-03 21:49:41 -0700717 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 14:30:30 -0700718 else:
719 _Log('WARN: %s not found. Expected for dev and test builds',
720 constants.STATEFUL_FILE)
721 if os.path.exists(dest_stateful):
722 os.remove(dest_stateful)
723 path_to_payload = self.GetUpdateForLabel(client_version, label)
724 #TODO(joychen): deprecate --image flag
725 elif self.forced_image:
joychendbfe6c92013-08-16 20:03:49 -0700726 if self.forced_image.startswith('xbuddy:'):
727 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-16 20:03:49 -0700728 xbuddy_label = self.forced_image.split(':')[1]
729 self.forced_image = None
joychen365a5742013-08-21 10:41:18 -0700730 # Make sure the xbuddy path target is in the directory.
731 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
732 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 16:45:12 -0700733 self.GetPathToPayload(xbuddy_label, client_version, board)
734 else:
735 src_path = os.path.abspath(self.forced_image)
736 if os.path.exists(src_path) and common_util.IsInsideChroot():
737 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700738 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
739 # Add links from the static directory to the update.
740 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
741 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 14:30:30 -0700742 else:
743 label = label or ''
744 label_list = label.split('/')
745 # Suppose that the path follows old protocol of indexing straight
746 # into static_dir with board/version label.
747 # Attempt to get the update in that directory, generating if necc.
748 path_to_payload = self.GetUpdateForLabel(client_version, label)
749 if path_to_payload is None:
750 # There was no update or image found in the directory.
751 # Let XBuddy find an image, and then generate an update to it.
752 if label_list[0] == 'xbuddy':
753 # If path explicitly calls xbuddy, pop off the tag.
754 label_list.pop()
Chris Sosa75490802013-09-30 17:21:45 -0700755 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 14:30:30 -0700756 if image_name not in constants.ALL_IMAGES:
757 raise AutoupdateError(
758 "Use an image alias: dev, base, test, or recovery.")
759 # Path has been resolved, try to get the image.
760 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
761 image_name)
762 if path_to_payload is None:
763 # Neither image nor update payload found after translation.
764 # Try to get an update to a test image from GS using the label.
765 path_to_payload, _image_name = self.xbuddy.Get(
766 ['remote', label, 'full_payload'])
767
768 # One of the above options should have gotten us a relative path.
769 if path_to_payload is None:
770 raise AutoupdateError('Failed to get an update for: %s' % label)
771 else:
Chris Sosa75490802013-09-30 17:21:45 -0700772 return path_to_payload
joychen121fc9b2013-08-02 14:30:30 -0700773
David Zeuthen52ccd012013-10-31 12:58:26 -0700774 @staticmethod
775 def _SignMetadataHash(private_key_path, metadata_hash):
776 """Signs metadata hash.
777
778 Signs a metadata hash with a private key. This includes padding the
779 hash with PKCS#1 v1.5 padding as well as an ASN.1 header.
780
781 Args:
782 private_key_path: The path to a private key to use for signing.
783 metadata_hash: A raw SHA-256 hash (32 bytes).
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700784
David Zeuthen52ccd012013-10-31 12:58:26 -0700785 Returns:
786 The raw signature.
787 """
788 args = ['openssl', 'rsautl', '-pkcs', '-sign', '-inkey', private_key_path]
789 padded_metadata_hash = ('\x30\x31\x30\x0d\x06\x09\x60\x86'
790 '\x48\x01\x65\x03\x04\x02\x01\x05'
791 '\x00\x04\x20') + metadata_hash
792 child = subprocess.Popen(args,
793 stdin=subprocess.PIPE,
794 stdout=subprocess.PIPE)
795 signature, _ = child.communicate(input=padded_metadata_hash)
796 return signature
797
joychen121fc9b2013-08-02 14:30:30 -0700798 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800799 """Handles an update ping from an update client.
800
801 Args:
802 data: XML blob from client.
803 label: optional label for the update.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700804
Chris Sosa6a3697f2013-01-29 16:44:43 -0800805 Returns:
806 Update payload message for client.
807 """
808 # Get the static url base that will form that base of our update url e.g.
809 # http://hostname:8080/static/update.gz.
810 static_urlbase = self._GetStaticUrl()
811
812 # Parse the XML we got into the components we care about.
813 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
814
Chris Sosab26b1202013-08-16 16:40:55 -0700815 # Process attributes of the update check.
816 forced_update_label, client_version, board = self._ProcessUpdateComponents(
817 app, event)
818
joychen121fc9b2013-08-02 14:30:30 -0700819 if not update_check:
820 # TODO(sosa): Generate correct non-updatecheck payload to better test
821 # update clients.
822 _Log('Non-update check received. Returning blank payload')
823 return autoupdate_lib.GetNoUpdateResponse(protocol)
824
Chris Sosa6a3697f2013-01-29 16:44:43 -0800825 if forced_update_label:
826 if label:
827 _Log('Label: %s set but being overwritten to %s by request', label,
828 forced_update_label)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800829 label = forced_update_label
830
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800831 # Make sure that we did not already exceed the max number of allowed
832 # responses; note that this is merely an optimization, as the definitive
833 # check and updating of the counter is done later, right before returning a
834 # response.
joychen121fc9b2013-08-02 14:30:30 -0700835 if self.max_updates == 0:
joychen121fc9b2013-08-02 14:30:30 -0700836 _Log('Request received but max number of updates handled')
837 return autoupdate_lib.GetNoUpdateResponse(protocol)
838
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800839 request_id = random.randint(0, sys.maxint)
840 self.curr_request_id = request_id
841 _Log('Update Check Received (id=%d). Client is using protocol version: %s',
842 request_id, protocol)
joychen121fc9b2013-08-02 14:30:30 -0700843
Chris Sosa6a3697f2013-01-29 16:44:43 -0800844 # Finally its time to generate the omaha response to give to client that
845 # lets them know where to find the payload and its associated metadata.
846 metadata_obj = None
847
848 try:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700849 # Are we provisioning a remote or local payload?
850 if self.remote_payload:
851 # If no explicit label was provided, use the value of --payload.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800852 if not label:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700853 label = self.payload_path
Chris Sosa0356d3b2010-09-16 15:46:22 -0700854
Chris Sosa52f15bc2013-08-13 17:14:15 -0700855 # TODO(sosa): Remove backwards-compatible hack.
Chris Sosab26b1202013-08-16 16:40:55 -0700856 if not '.bin' in label:
Chris Sosa52f15bc2013-08-13 17:14:15 -0700857 url = _NonePathJoin(static_urlbase, label, 'update.gz')
858 else:
859 url = _NonePathJoin(static_urlbase, label)
Chris Sosa5d342a22010-09-28 16:54:41 -0700860
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700861 # Get remote payload attributes.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800862 metadata_obj = self._GetRemotePayloadAttrs(url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700863 else:
joychen121fc9b2013-08-02 14:30:30 -0700864 path_to_payload = self.GetPathToPayload(label, client_version, board)
865 url = _NonePathJoin(static_urlbase, path_to_payload,
joychen7c2054a2013-07-25 11:14:07 -0700866 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700867 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800868 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800869 except AutoupdateError as e:
870 # Raised if we fail to generate an update payload.
871 _Log('Failed to process an update: %r', e)
872 return autoupdate_lib.GetNoUpdateResponse(protocol)
873
David Zeuthen52ccd012013-10-31 12:58:26 -0700874 # Sign the metadata hash, if requested.
875 signed_metadata_hash = None
876 if self.private_key_for_metadata_hash_signature:
877 signed_metadata_hash = base64.b64encode(Autoupdate._SignMetadataHash(
878 self.private_key_for_metadata_hash_signature,
879 base64.b64decode(metadata_obj.metadata_hash)))
880
881 # Include public key, if requested.
882 public_key_data = None
883 if self.public_key:
884 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
885
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800886 update_response = autoupdate_lib.GetUpdateResponse(
Chris Sosa6a3697f2013-01-29 16:44:43 -0800887 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 12:58:26 -0700888 metadata_obj.is_delta_format, metadata_obj.metadata_size,
889 signed_metadata_hash, public_key_data, protocol, self.critical_update)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700890
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800891 # Make sure we can proceed with the response (critical section).
892 with self._update_response_lock:
893 # If the number of responses sent already exceeds the max allowed, abort.
894 if self.max_updates == 0:
895 _Log('Max allowed number of update responses already sent, '
896 'aborting this one (id=%d)', request_id)
897 return autoupdate_lib.GetNoUpdateResponse(protocol)
898
899 # If there's been a more recent request, we assume the client timed out
900 # on this request and should not respond to it.
901 # IMPORTANT: we want to do this as close as posible to where we commit to
902 # making a response, i.e. right before we update the response tally. This
903 # is why this check happens in the critical section.
904 curr_request_id = self.curr_request_id
905 if curr_request_id != request_id:
906 _Log('A more recent request was received (id=%d), aborting this one '
907 '(id=%d)', curr_request_id, request_id)
908 return autoupdate_lib.GetNoUpdateResponse(protocol)
909
910 # Update the counter, committing to make the response.
911 self.max_updates -= 1
912
913 # At this point, we're good to go with the response.
914 _Log('Responding to client to use url %s to get image (id=%d)', url,
915 request_id)
916 return update_response
917
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700918 def HandleHostInfoPing(self, ip):
919 """Returns host info dictionary for the given IP in JSON format."""
920 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800921 if ip in self.host_infos.table:
922 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
923
924 def HandleHostLogPing(self, ip):
925 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700926 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 13:47:02 -0800927 if ip == 'all':
928 return json.dumps(
929 dict([(key, self.host_infos.table[key].log)
930 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700931
932 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 13:47:02 -0800933 if ip in self.host_infos.table:
934 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700935
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700936 # If no events were logged for this IP, return an empty log.
937 return json.dumps([])
938
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700939 def HandleSetUpdatePing(self, ip, label):
940 """Sets forced_update_label for a given host."""
941 assert ip, 'No ip provided.'
942 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800943 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label