blob: 552b5c236f8aea1dc9e76b2357be3ef38cf15704 [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
Don Garrettfb15e322016-06-21 19:12:08 -07007from __future__ import print_function
8
David Zeuthen52ccd012013-10-31 12:58:26 -07009import base64
Gilad Arnolde7819e72014-03-21 12:50:48 -070010import collections
Matthew Sartori497105b2015-12-08 14:01:57 -080011import fcntl
Dale Curtisc9aaf3a2011-08-09 15:47:40 -070012import json
rtc@google.comded22402009-10-26 22:36:21 +000013import os
Chris Sosa05491b12010-11-08 17:14:16 -080014import subprocess
Gilad Arnolde74b3812013-04-22 11:27:38 -070015import sys
Gilad Arnoldd0c71752013-12-06 11:48:45 -080016import threading
Darin Petkov2b2ff4b2010-07-27 15:02:09 -070017import time
Gilad Arnold0c9c8602012-10-02 23:58:58 -070018import urllib2
Don Garrett0ad09372010-12-06 16:20:30 -080019import urlparse
Chris Sosa7c931362010-10-11 19:49:01 -070020
Gilad Arnoldabb352e2012-09-23 01:24:27 -070021import cherrypy
22
joychen921e1fb2013-06-28 11:12:20 -070023import build_util
Chris Sosa52148582012-11-15 15:35:58 -080024import autoupdate_lib
Gilad Arnold55a2a372012-10-02 09:46:32 -070025import common_util
joychen7c2054a2013-07-25 11:14:07 -070026import devserver_constants as constants
Gilad Arnoldc65330c2012-09-20 15:17:48 -070027import log_util
Gilad Arnolde74b3812013-04-22 11:27:38 -070028# pylint: disable=F0401
Amin Hassani51780c62017-08-10 13:55:35 -070029
30# Allow importing from aosp/system/update_engine/scripts when running from
31# source tree. Used for importing update_payload if it is not in the system
32# path.
33lib_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'aosp',
34 'system', 'update_engine', 'scripts')
35if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
36 sys.path.insert(1, lib_dir)
Gilad Arnolde74b3812013-04-22 11:27:38 -070037import update_payload
Chris Sosa05491b12010-11-08 17:14:16 -080038
Gilad Arnoldc65330c2012-09-20 15:17:48 -070039
joychen121fc9b2013-08-02 14:30:30 -070040# If used by client in place of an pre-update version string, forces an update
41# to the client regardless of the relative versions of the payload and client.
42FORCED_UPDATE = 'ForcedUpdate'
43
44# Files needed to serve an update.
45UPDATE_FILES = (
Don Garrettfb15e322016-06-21 19:12:08 -070046 constants.UPDATE_FILE,
47 constants.STATEFUL_FILE,
48 constants.METADATA_FILE
joychen121fc9b2013-08-02 14:30:30 -070049)
50
Gilad Arnoldc65330c2012-09-20 15:17:48 -070051# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080052def _Log(message, *args):
53 return log_util.LogWithTag('UPDATE', message, *args)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070054
rtc@google.comded22402009-10-26 22:36:21 +000055
Gilad Arnold0c9c8602012-10-02 23:58:58 -070056class AutoupdateError(Exception):
57 """Exception classes used by this module."""
58 pass
59
60
Don Garrett0ad09372010-12-06 16:20:30 -080061def _ChangeUrlPort(url, new_port):
62 """Return the URL passed in with a different port"""
63 scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
64 host_port = netloc.split(':')
65
66 if len(host_port) == 1:
67 host_port.append(new_port)
68 else:
69 host_port[1] = new_port
70
Don Garrettfb15e322016-06-21 19:12:08 -070071 print(host_port)
joychen121fc9b2013-08-02 14:30:30 -070072 netloc = '%s:%s' % tuple(host_port)
Don Garrett0ad09372010-12-06 16:20:30 -080073
74 return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
75
Chris Sosa6a3697f2013-01-29 16:44:43 -080076def _NonePathJoin(*args):
77 """os.path.join that filters None's from the argument list."""
78 return os.path.join(*filter(None, args))
Don Garrett0ad09372010-12-06 16:20:30 -080079
Chris Sosa6a3697f2013-01-29 16:44:43 -080080
81class HostInfo(object):
Gilad Arnold286a0062012-01-12 13:47:02 -080082 """Records information about an individual host.
83
84 Members:
85 attrs: Static attributes (legacy)
86 log: Complete log of recorded client entries
87 """
88
89 def __init__(self):
90 # A dictionary of current attributes pertaining to the host.
91 self.attrs = {}
92
93 # A list of pairs consisting of a timestamp and a dictionary of recorded
94 # attributes.
95 self.log = []
96
97 def __repr__(self):
98 return 'attrs=%s, log=%s' % (self.attrs, self.log)
99
100 def AddLogEntry(self, entry):
101 """Append a new log entry."""
102 # Append a timestamp.
103 assert not 'timestamp' in entry, 'Oops, timestamp field already in use'
104 entry['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
105 # Add entry to hosts' message log.
106 self.log.append(entry)
107
Gilad Arnold286a0062012-01-12 13:47:02 -0800108
Chris Sosa6a3697f2013-01-29 16:44:43 -0800109class HostInfoTable(object):
Gilad Arnold286a0062012-01-12 13:47:02 -0800110 """Records information about a set of hosts who engage in update activity.
111
112 Members:
113 table: Table of information on hosts.
114 """
115
116 def __init__(self):
117 # A dictionary of host information. Keys are normally IP addresses.
118 self.table = {}
119
120 def __repr__(self):
121 return '%s' % self.table
122
123 def GetInitHostInfo(self, host_id):
124 """Return a host's info object, or create a new one if none exists."""
125 return self.table.setdefault(host_id, HostInfo())
126
127 def GetHostInfo(self, host_id):
128 """Return an info object for given host, if such exists."""
Chris Sosa1885d032012-11-29 17:07:27 -0800129 return self.table.get(host_id)
Gilad Arnold286a0062012-01-12 13:47:02 -0800130
131
Chris Sosa6a3697f2013-01-29 16:44:43 -0800132class UpdateMetadata(object):
133 """Object containing metadata about an update payload."""
134
David Zeuthen52ccd012013-10-31 12:58:26 -0700135 def __init__(self, sha1, sha256, size, is_delta_format, metadata_size,
136 metadata_hash):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800137 self.sha1 = sha1
138 self.sha256 = sha256
139 self.size = size
140 self.is_delta_format = is_delta_format
David Zeuthen52ccd012013-10-31 12:58:26 -0700141 self.metadata_size = metadata_size
142 self.metadata_hash = metadata_hash
Chris Sosa6a3697f2013-01-29 16:44:43 -0800143
144
joychen921e1fb2013-06-28 11:12:20 -0700145class Autoupdate(build_util.BuildObject):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700146 """Class that contains functionality that handles Chrome OS update pings.
147
148 Members:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700149 urlbase: base URL, other than devserver, for update images.
150 forced_image: path to an image to use for all updates.
151 payload_path: path to pre-generated payload to serve.
152 src_image: if specified, creates a delta payload from this image.
153 proxy_port: port of local proxy to tell client to connect to you
154 through.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700155 board: board for the image. Needed for pre-generating of updates.
156 copy_to_static_root: copies images generated from the cache to ~/static.
157 private_key: path to private key in PEM format.
David Zeuthen52ccd012013-10-31 12:58:26 -0700158 private_key_for_metadata_hash_signature: path to private key in PEM format.
159 public_key: path to public key in PEM format.
Gilad Arnold8318eac2012-10-04 12:52:23 -0700160 critical_update: whether provisioned payload is critical.
161 remote_payload: whether provisioned payload is remotely staged.
162 max_updates: maximum number of updates we'll try to provision.
163 host_log: record full history of host update events.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700164 """
rtc@google.comded22402009-10-26 22:36:21 +0000165
joychened64b222013-06-21 16:39:34 -0700166 _OLD_PAYLOAD_URL_PREFIX = '/static/archive'
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700167 _PAYLOAD_URL_PREFIX = '/static/'
168 _FILEINFO_URL_PREFIX = '/api/fileinfo/'
169
Chris Sosa6a3697f2013-01-29 16:44:43 -0800170 SHA1_ATTR = 'sha1'
171 SHA256_ATTR = 'sha256'
172 SIZE_ATTR = 'size'
173 ISDELTA_ATTR = 'is_delta'
David Zeuthen52ccd012013-10-31 12:58:26 -0700174 METADATA_SIZE_ATTR = 'metadata_size'
175 METADATA_HASH_ATTR = 'metadata_hash'
Chris Sosa6a3697f2013-01-29 16:44:43 -0800176
joychen121fc9b2013-08-02 14:30:30 -0700177 def __init__(self, xbuddy, urlbase=None, forced_image=None, payload_path=None,
Gabe Black70994862014-09-05 00:50:58 -0700178 proxy_port=None, src_image='', board=None,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800179 copy_to_static_root=True, private_key=None,
David Zeuthen52ccd012013-10-31 12:58:26 -0700180 private_key_for_metadata_hash_signature=None, public_key=None,
Don Garrettfb15e322016-06-21 19:12:08 -0700181 critical_update=False, remote_payload=False, max_updates=-1,
Chris Sosa6a3697f2013-01-29 16:44:43 -0800182 host_log=False, *args, **kwargs):
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700183 super(Autoupdate, self).__init__(*args, **kwargs)
joychen121fc9b2013-08-02 14:30:30 -0700184 self.xbuddy = xbuddy
185 self.urlbase = urlbase or None
Chris Sosa0356d3b2010-09-16 15:46:22 -0700186 self.forced_image = forced_image
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700187 self.payload_path = payload_path
Chris Sosa62f720b2010-10-26 21:39:48 -0700188 self.src_image = src_image
Don Garrett0ad09372010-12-06 16:20:30 -0800189 self.proxy_port = proxy_port
joychen562699a2013-08-13 15:22:14 -0700190 self.board = board or self.GetDefaultBoardID()
Chris Sosa08d55a22011-01-19 16:08:02 -0800191 self.copy_to_static_root = copy_to_static_root
Chris Sosa0f1ec842011-02-14 16:33:22 -0800192 self.private_key = private_key
David Zeuthen52ccd012013-10-31 12:58:26 -0700193 self.private_key_for_metadata_hash_signature = \
194 private_key_for_metadata_hash_signature
195 self.public_key = public_key
Satoru Takabayashid733cbe2011-11-15 09:36:32 -0800196 self.critical_update = critical_update
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700197 self.remote_payload = remote_payload
Jay Srinivasanac69d262012-10-30 19:05:53 -0700198 self.max_updates = max_updates
Gilad Arnold8318eac2012-10-04 12:52:23 -0700199 self.host_log = host_log
Don Garrettfff4c322010-11-19 13:37:12 -0800200
Chris Sosa417e55d2011-01-25 16:40:48 -0800201 self.pregenerated_path = None
Sean O'Connor14b6a0a2010-03-20 23:23:48 -0700202
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700203 # Initialize empty host info cache. Used to keep track of various bits of
Gilad Arnold286a0062012-01-12 13:47:02 -0800204 # information about a given host. A host is identified by its IP address.
205 # The info stored for each host includes a complete log of events for this
206 # host, as well as a dictionary of current attributes derived from events.
207 self.host_infos = HostInfoTable()
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700208
Gilad Arnolde7819e72014-03-21 12:50:48 -0700209 self._update_count_lock = threading.Lock()
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800210
Chris Sosa6a3697f2013-01-29 16:44:43 -0800211 @classmethod
212 def _ReadMetadataFromStream(cls, stream):
213 """Returns metadata obj from input json stream that implements .read()."""
Chung-yih Wangdcf798a2016-06-24 00:03:24 +0800214 data = None
Chris Sosa6a3697f2013-01-29 16:44:43 -0800215 file_attr_dict = {}
216 try:
Chung-yih Wangdcf798a2016-06-24 00:03:24 +0800217 data = stream.read()
218 file_attr_dict = json.loads(data)
219 except (IOError, ValueError):
220 _Log('Failed to load metadata:%s' % data)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800221 return None
222
223 sha1 = file_attr_dict.get(cls.SHA1_ATTR)
224 sha256 = file_attr_dict.get(cls.SHA256_ATTR)
225 size = file_attr_dict.get(cls.SIZE_ATTR)
226 is_delta = file_attr_dict.get(cls.ISDELTA_ATTR)
David Zeuthen52ccd012013-10-31 12:58:26 -0700227 metadata_size = file_attr_dict.get(cls.METADATA_SIZE_ATTR)
228 metadata_hash = file_attr_dict.get(cls.METADATA_HASH_ATTR)
229 return UpdateMetadata(sha1, sha256, size, is_delta, metadata_size,
230 metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800231
232 @staticmethod
233 def _ReadMetadataFromFile(payload_dir):
234 """Returns metadata object from the metadata_file in the payload_dir"""
joychen25d25972013-07-30 14:54:16 -0700235 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800236 if os.path.exists(metadata_file):
Matthew Sartori497105b2015-12-08 14:01:57 -0800237 metadata_stream = open(metadata_file, 'r')
238 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_SH)
239 metadata = Autoupdate._ReadMetadataFromStream(metadata_stream)
240 fcntl.lockf(metadata_stream.fileno(), fcntl.LOCK_UN)
241 return metadata
Chris Sosa6a3697f2013-01-29 16:44:43 -0800242
243 @classmethod
244 def _StoreMetadataToFile(cls, payload_dir, metadata_obj):
245 """Stores metadata object into the metadata_file of the payload_dir"""
246 file_dict = {cls.SHA1_ATTR: metadata_obj.sha1,
247 cls.SHA256_ATTR: metadata_obj.sha256,
248 cls.SIZE_ATTR: metadata_obj.size,
David Zeuthen52ccd012013-10-31 12:58:26 -0700249 cls.ISDELTA_ATTR: metadata_obj.is_delta_format,
250 cls.METADATA_SIZE_ATTR: metadata_obj.metadata_size,
251 cls.METADATA_HASH_ATTR: metadata_obj.metadata_hash}
joychen25d25972013-07-30 14:54:16 -0700252 metadata_file = os.path.join(payload_dir, constants.METADATA_FILE)
Matthew Sartori497105b2015-12-08 14:01:57 -0800253 file_handle = open(metadata_file, 'w')
254 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_EX)
255 json.dump(file_dict, file_handle)
256 fcntl.lockf(file_handle.fileno(), fcntl.LOCK_UN)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800257
Chris Sosa52148582012-11-15 15:35:58 -0800258 @staticmethod
259 def _GetVersionFromDir(image_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700260 """Returns the version of the image based on the name of the directory."""
261 latest_version = os.path.basename(image_dir)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700262 parts = latest_version.split('-')
joychen121fc9b2013-08-02 14:30:30 -0700263 # If we can't get a version number from the directory, default to a high
264 # number to allow the update to happen
265 return parts[1] if len(parts) == 3 else "9999.0.0"
Chris Sosa0356d3b2010-09-16 15:46:22 -0700266
Chris Sosa52148582012-11-15 15:35:58 -0800267 @staticmethod
268 def _CanUpdate(client_version, latest_version):
Don Garrettfb15e322016-06-21 19:12:08 -0700269 """True if the latest_version is greater than the client_version."""
Chris Sosa6a3697f2013-01-29 16:44:43 -0800270 _Log('client version %s latest version %s', client_version, latest_version)
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700271
272 client_tokens = client_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700273 latest_tokens = latest_version.replace('_', '').split('.')
Daniel Erat8a0bc4a2011-09-30 08:52:52 -0700274
joychen121fc9b2013-08-02 14:30:30 -0700275 if len(latest_tokens) == len(client_tokens) == 3:
276 return latest_tokens > client_tokens
Chris Sosa0356d3b2010-09-16 15:46:22 -0700277 else:
joychen121fc9b2013-08-02 14:30:30 -0700278 # If the directory name isn't a version number, let it pass.
279 return True
Chris Sosa0356d3b2010-09-16 15:46:22 -0700280
Chris Sosa52148582012-11-15 15:35:58 -0800281 @staticmethod
Gilad Arnolde74b3812013-04-22 11:27:38 -0700282 def IsDeltaFormatFile(filename):
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700283 try:
Gilad Arnolde74b3812013-04-22 11:27:38 -0700284 with open(filename) as payload_file:
285 payload = update_payload.Payload(payload_file)
286 payload.Init()
287 return payload.IsDelta()
288 except (IOError, update_payload.PayloadError):
289 # For unit tests we may not have real files, so it's ok to ignore these
290 # errors.
Andrew de los Reyes5679b972010-10-25 17:34:49 -0700291 return False
292
Don Garrettf90edf02010-11-16 17:36:14 -0800293 def GenerateUpdateFile(self, src_image, image_path, output_dir):
Chris Sosa0356d3b2010-09-16 15:46:22 -0700294 """Generates an update gz given a full path to an image.
295
296 Args:
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700297 src_image: Path to a source image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700298 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700299 output_dir: Path to the generated update file.
300
Chris Sosa6a3697f2013-01-29 16:44:43 -0800301 Raises:
302 subprocess.CalledProcessError if the update generator fails to generate a
303 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700304 """
joychen7c2054a2013-07-25 11:14:07 -0700305 update_path = os.path.join(output_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800306 _Log('Generating update image %s', update_path)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700307
Chris Sosa0f1ec842011-02-14 16:33:22 -0800308 update_command = [
Chris Sosa5b8b5eb2012-03-27 11:15:27 -0700309 'cros_generate_update_payload',
Chris Sosa6a3697f2013-01-29 16:44:43 -0800310 '--image', image_path,
David Zeuthen52ccd012013-10-31 12:58:26 -0700311 '--out_metadata_hash_file', os.path.join(output_dir,
312 constants.METADATA_HASH_FILE),
Chris Sosa6a3697f2013-01-29 16:44:43 -0800313 '--output', update_path,
Chris Sosa0f1ec842011-02-14 16:33:22 -0800314 ]
Chris Sosa4136e692010-10-28 23:42:37 -0700315
Chris Sosa52148582012-11-15 15:35:58 -0800316 if src_image:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800317 update_command.extend(['--src_image', src_image])
Chris Sosa52148582012-11-15 15:35:58 -0800318
Chris Sosa52148582012-11-15 15:35:58 -0800319 if self.private_key:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800320 update_command.extend(['--private_key', self.private_key])
Chris Sosa0f1ec842011-02-14 16:33:22 -0800321
Chris Sosa6a3697f2013-01-29 16:44:43 -0800322 _Log('Running %s', ' '.join(update_command))
323 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700324
Chris Sosa52148582012-11-15 15:35:58 -0800325 @staticmethod
326 def GenerateStatefulFile(image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800327 """Generates a stateful update payload given a full path to an image.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700328
329 Args:
330 image_path: Full path to image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700331 output_dir: Directory for emitting the stateful update payload.
332
Chris Sosa908fd6f2010-11-10 17:31:18 -0800333 Raises:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800334 subprocess.CalledProcessError if the update generator fails to generate a
Chris Sosa908fd6f2010-11-10 17:31:18 -0800335 stateful payload.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700336 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800337 update_command = [
338 'cros_generate_stateful_update_payload',
339 '--image', image_path,
340 '--output_dir', output_dir,
341 ]
342 _Log('Running %s', ' '.join(update_command))
343 subprocess.check_call(update_command)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700344
Don Garrettf90edf02010-11-16 17:36:14 -0800345 def FindCachedUpdateImageSubDir(self, src_image, dest_image):
346 """Find directory to store a cached update.
347
Gilad Arnold55a2a372012-10-02 09:46:32 -0700348 Given one, or two images for an update, this finds which cache directory
349 should hold the update files, even if they don't exist yet.
Don Garrettf90edf02010-11-16 17:36:14 -0800350
Gilad Arnold55a2a372012-10-02 09:46:32 -0700351 Returns:
352 A directory path for storing a cached update, of the following form:
353 Non-delta updates:
354 CACHE_DIR/<dest_hash>
355 Delta updates:
356 CACHE_DIR/<src_hash>_<dest_hash>
357 Signed updates (self.private_key):
358 CACHE_DIR/<src_hash>_<dest_hash>+<private_key_hash>
Chris Sosa744e1472011-09-07 19:32:50 -0700359 """
Gilad Arnold55a2a372012-10-02 09:46:32 -0700360 update_dir = ''
Chris Sosa744e1472011-09-07 19:32:50 -0700361 if src_image:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700362 update_dir += common_util.GetFileMd5(src_image) + '_'
Don Garrettf90edf02010-11-16 17:36:14 -0800363
Gilad Arnold55a2a372012-10-02 09:46:32 -0700364 update_dir += common_util.GetFileMd5(dest_image)
Chris Sosa744e1472011-09-07 19:32:50 -0700365 if self.private_key:
Gilad Arnold55a2a372012-10-02 09:46:32 -0700366 update_dir += '+' + common_util.GetFileMd5(self.private_key)
Chris Sosa744e1472011-09-07 19:32:50 -0700367
joychen25d25972013-07-30 14:54:16 -0700368 return os.path.join(constants.CACHE_DIR, update_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800369
Don Garrettfff4c322010-11-19 13:37:12 -0800370 def GenerateUpdateImage(self, image_path, output_dir):
Don Garrettf90edf02010-11-16 17:36:14 -0800371 """Force generates an update payload based on the given image_path.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700372
Chris Sosade91f672010-11-16 10:05:44 -0800373 Args:
Don Garrettf90edf02010-11-16 17:36:14 -0800374 image_path: full path to the image.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800375 output_dir: the directory to write the update payloads to
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700376
Chris Sosa6a3697f2013-01-29 16:44:43 -0800377 Raises:
378 AutoupdateError if it failed to generate either update or stateful
379 payload.
Chris Sosade91f672010-11-16 10:05:44 -0800380 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800381 _Log('Generating update for image %s', image_path)
Andrew de los Reyes9a528712010-06-30 10:29:43 -0700382
Chris Sosa6a3697f2013-01-29 16:44:43 -0800383 # Delete any previous state in this directory.
384 os.system('rm -rf "%s"' % output_dir)
385 os.makedirs(output_dir)
rtc@google.comded22402009-10-26 22:36:21 +0000386
Chris Sosa6a3697f2013-01-29 16:44:43 -0800387 try:
388 self.GenerateUpdateFile(self.src_image, image_path, output_dir)
389 self.GenerateStatefulFile(image_path, output_dir)
390 except subprocess.CalledProcessError:
391 os.system('rm -rf "%s"' % output_dir)
392 raise AutoupdateError('Failed to generate update in %s' % output_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800393
Chris Sosa75490802013-09-30 17:21:45 -0700394 def GenerateUpdateImageWithCache(self, image_path):
Don Garrettf90edf02010-11-16 17:36:14 -0800395 """Force generates an update payload based on the given image_path.
rtc@google.comded22402009-10-26 22:36:21 +0000396
Chris Sosa0356d3b2010-09-16 15:46:22 -0700397 Args:
398 image_path: full path to the image.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700399
Chris Sosa0356d3b2010-09-16 15:46:22 -0700400 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700401 update directory relative to static_image_dir.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700402
Chris Sosa6a3697f2013-01-29 16:44:43 -0800403 Raises:
404 AutoupdateError if it we need to generate a payload and fail to do so.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700405 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800406 _Log('Generating update for src %s image %s', self.src_image, image_path)
Chris Sosae67b78f2010-11-04 17:33:16 -0700407
joychen121fc9b2013-08-02 14:30:30 -0700408 # If it was pregenerated, don't regenerate.
Chris Sosa417e55d2011-01-25 16:40:48 -0800409 if self.pregenerated_path:
410 return self.pregenerated_path
Don Garrettfff4c322010-11-19 13:37:12 -0800411
Chris Sosa75490802013-09-30 17:21:45 -0700412 # Which sub_dir should hold our cached update image.
413 cache_sub_dir = self.FindCachedUpdateImageSubDir(self.src_image, image_path)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800414 _Log('Caching in sub_dir "%s"', cache_sub_dir)
Chris Sosa417e55d2011-01-25 16:40:48 -0800415
joychen121fc9b2013-08-02 14:30:30 -0700416 # The cached payloads exist in a cache dir.
Chris Sosa75490802013-09-30 17:21:45 -0700417 cache_dir = os.path.join(self.static_dir, cache_sub_dir)
joychen121fc9b2013-08-02 14:30:30 -0700418
419 cache_update_payload = os.path.join(cache_dir,
joychen7c2054a2013-07-25 11:14:07 -0700420 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700421 cache_stateful_payload = os.path.join(cache_dir,
joychen25d25972013-07-30 14:54:16 -0700422 constants.STATEFUL_FILE)
Chris Sosa417e55d2011-01-25 16:40:48 -0800423 # Check to see if this cache directory is valid.
joychen121fc9b2013-08-02 14:30:30 -0700424 if not (os.path.exists(cache_update_payload) and
425 os.path.exists(cache_stateful_payload)):
426 self.GenerateUpdateImage(image_path, cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800427
joychen121fc9b2013-08-02 14:30:30 -0700428 # Don't regenerate the image for this devserver instance.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800429 self.pregenerated_path = cache_sub_dir
Chris Sosa65d339b2013-01-21 18:59:21 -0800430
Chris Sosa6a3697f2013-01-29 16:44:43 -0800431 # Generate the cache file.
joychen121fc9b2013-08-02 14:30:30 -0700432 self.GetLocalPayloadAttrs(cache_dir)
Don Garrettf90edf02010-11-16 17:36:14 -0800433
joychen121fc9b2013-08-02 14:30:30 -0700434 return cache_sub_dir
Chris Sosa0356d3b2010-09-16 15:46:22 -0700435
Chris Sosa75490802013-09-30 17:21:45 -0700436 def _SymlinkUpdateFiles(self, target_dir, link_dir):
437 """Symlinks the update-related files from target_dir to link_dir.
joychen121fc9b2013-08-02 14:30:30 -0700438
439 Every time an update is called, clear existing files/symlinks in the
Chris Sosa75490802013-09-30 17:21:45 -0700440 link_dir, and replace them with symlinks to the target_dir.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700441
442 Args:
Chris Sosa75490802013-09-30 17:21:45 -0700443 target_dir: Location of the target files.
444 link_dir: Directory where the links should exist after.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700445 """
Chris Sosa75490802013-09-30 17:21:45 -0700446 _Log('Linking %s to %s', target_dir, link_dir)
447 if link_dir == target_dir:
448 _Log('Cannot symlink into the same directory.')
joychen121fc9b2013-08-02 14:30:30 -0700449 return
450 for f in UPDATE_FILES:
Chris Sosa75490802013-09-30 17:21:45 -0700451 link = os.path.join(link_dir, f)
452 target = os.path.join(target_dir, f)
Alex Deymo3e2d4952013-09-03 21:49:41 -0700453 common_util.SymlinkFile(target, link)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700454
joychen121fc9b2013-08-02 14:30:30 -0700455 def GetUpdateForLabel(self, client_version, label,
456 image_name=constants.TEST_IMAGE_FILE):
457 """Given a label, get an update from the directory.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700458
joychen121fc9b2013-08-02 14:30:30 -0700459 Args:
460 client_version: Current version of the client or FORCED_UPDATE
461 label: the relative directory inside the static dir
462 image_name: If the image type was specified by the update rpc, we try to
463 find an image with this file name first. This is by default
464 "chromiumos_test_image.bin" but can also take any of the values in
465 devserver_constants.ALL_IMAGES
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700466
Chris Sosa6a3697f2013-01-29 16:44:43 -0800467 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700468 A relative path to the directory with the update payload.
469 This is the label if an update did not need to be generated, but can
470 be label/cache/hashed_dir_for_update.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700471
Chris Sosa6a3697f2013-01-29 16:44:43 -0800472 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700473 AutoupdateError: If client version is higher than available update found
474 at the directory given by the label.
Don Garrettf90edf02010-11-16 17:36:14 -0800475 """
joychen121fc9b2013-08-02 14:30:30 -0700476 _Log('Update label/file: %s/%s', label, image_name)
477 static_image_dir = _NonePathJoin(self.static_dir, label)
478 static_update_path = _NonePathJoin(static_image_dir, constants.UPDATE_FILE)
479 static_image_path = _NonePathJoin(static_image_dir, image_name)
joychen7c2054a2013-07-25 11:14:07 -0700480
joychen121fc9b2013-08-02 14:30:30 -0700481 # Update the client only if client version is older than available update.
482 latest_version = self._GetVersionFromDir(static_image_dir)
483 if not (client_version == FORCED_UPDATE or
484 self._CanUpdate(client_version, latest_version)):
485 raise AutoupdateError(
486 'Update check received but no update available for client')
Don Garrettee25e552010-11-23 12:09:35 -0800487
joychen121fc9b2013-08-02 14:30:30 -0700488 if label and os.path.exists(static_update_path):
489 # An update payload was found for the given label, return it.
490 return label
491 elif os.path.exists(static_image_path) and common_util.IsInsideChroot():
492 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700493 rel_path = self.GenerateUpdateImageWithCache(static_image_path)
494 # Add links from the static directory to the update.
495 cache_path = _NonePathJoin(self.static_dir, rel_path)
496 self._SymlinkUpdateFiles(cache_path, static_image_dir)
497 return label
Don Garrett0c880e22010-11-17 18:13:37 -0800498
joychen121fc9b2013-08-02 14:30:30 -0700499 # The label didn't resolve.
500 return None
Chris Sosa2c048f12010-10-27 16:05:27 -0700501
502 def PreGenerateUpdate(self):
Chris Sosa417e55d2011-01-25 16:40:48 -0800503 """Pre-generates an update and prints out the relative path it.
504
Chris Sosa6a3697f2013-01-29 16:44:43 -0800505 Returns relative path of the update.
Chris Sosa65d339b2013-01-21 18:59:21 -0800506
Chris Sosa6a3697f2013-01-29 16:44:43 -0800507 Raises:
508 AutoupdateError if it failed to generate the payload.
509 """
510 _Log('Pre-generating the update payload')
joychen121fc9b2013-08-02 14:30:30 -0700511 # Does not work with labels so just use static dir. (empty label)
512 pregenerated_update = self.GetPathToPayload('', FORCED_UPDATE, self.board)
Don Garrettfb15e322016-06-21 19:12:08 -0700513 print('PREGENERATED_UPDATE=%s' % _NonePathJoin(pregenerated_update,
514 constants.UPDATE_FILE))
Chris Sosa417e55d2011-01-25 16:40:48 -0800515 return pregenerated_update
Chris Sosa2c048f12010-10-27 16:05:27 -0700516
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700517 def _GetRemotePayloadAttrs(self, url):
518 """Returns hashes, size and delta flag of a remote update payload.
519
520 Obtain attributes of a payload file available on a remote devserver. This
521 is based on the assumption that the payload URL uses the /static prefix. We
522 need to make sure that both clients (requests) and remote devserver
523 (provisioning) preserve this invariant.
524
525 Args:
526 url: URL of statically staged remote file (http://host:port/static/...)
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700527
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700528 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700529 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700530 """
531 if self._PAYLOAD_URL_PREFIX not in url:
532 raise AutoupdateError(
533 'Payload URL does not have the expected prefix (%s)' %
534 self._PAYLOAD_URL_PREFIX)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800535
joychened64b222013-06-21 16:39:34 -0700536 if self._OLD_PAYLOAD_URL_PREFIX in url:
537 fileinfo_url = url.replace(self._OLD_PAYLOAD_URL_PREFIX,
538 self._FILEINFO_URL_PREFIX)
539 else:
540 fileinfo_url = url.replace(self._PAYLOAD_URL_PREFIX,
541 self._FILEINFO_URL_PREFIX)
542
Chris Sosa6a3697f2013-01-29 16:44:43 -0800543 _Log('Retrieving file info for remote payload via %s', fileinfo_url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700544 try:
545 conn = urllib2.urlopen(fileinfo_url)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800546 metadata_obj = Autoupdate._ReadMetadataFromStream(conn)
547 # These fields are required for remote calls.
548 if not metadata_obj:
549 raise AutoupdateError('Failed to obtain remote payload info')
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700550
Chris Sosa6a3697f2013-01-29 16:44:43 -0800551 return metadata_obj
552 except IOError as e:
553 raise AutoupdateError('Failed to obtain remote payload info: %s', e)
554
David Zeuthen52ccd012013-10-31 12:58:26 -0700555 @staticmethod
556 def _GetMetadataHash(payload_dir):
David Zeuthenf27f1502013-11-13 10:38:16 -0800557 """Gets the metadata hash, if it exists.
David Zeuthen52ccd012013-10-31 12:58:26 -0700558
559 Args:
560 payload_dir: The payload directory.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700561
David Zeuthen52ccd012013-10-31 12:58:26 -0700562 Returns:
David Zeuthenf27f1502013-11-13 10:38:16 -0800563 The metadata hash, base-64 encoded or None if there is no metadata hash.
David Zeuthen52ccd012013-10-31 12:58:26 -0700564 """
565 path = os.path.join(payload_dir, constants.METADATA_HASH_FILE)
David Zeuthenf27f1502013-11-13 10:38:16 -0800566 if os.path.exists(path):
567 return base64.b64encode(open(path, 'rb').read())
568 else:
569 return None
David Zeuthen52ccd012013-10-31 12:58:26 -0700570
571 @staticmethod
572 def _GetMetadataSize(payload_filename):
573 """Gets the size of the metadata in a payload file.
574
575 Args:
576 payload_filename: Path to the payload file.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700577
David Zeuthen52ccd012013-10-31 12:58:26 -0700578 Returns:
579 The size of the payload metadata, as reported in the payload header.
580 """
Alex Deymoa6ac00d2015-10-15 09:14:58 -0700581 try:
582 with open(payload_filename) as payload_file:
583 payload = update_payload.Payload(payload_file)
584 payload.Init()
585 return payload.metadata_size
586 except (IOError, update_payload.PayloadError):
587 # For unit tests we may not have real files, so it's ok to ignore these
588 # errors.
David Zeuthen52ccd012013-10-31 12:58:26 -0700589 return 0
David Zeuthen52ccd012013-10-31 12:58:26 -0700590
Chris Sosa6a3697f2013-01-29 16:44:43 -0800591 def GetLocalPayloadAttrs(self, payload_dir):
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700592 """Returns hashes, size and delta flag of a local update payload.
593
594 Args:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800595 payload_dir: Path to the directory the payload is in.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700596
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700597 Returns:
David Zeuthen52ccd012013-10-31 12:58:26 -0700598 A UpdateMetadata object.
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700599 """
joychen7c2054a2013-07-25 11:14:07 -0700600 filename = os.path.join(payload_dir, constants.UPDATE_FILE)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800601 if not os.path.exists(filename):
602 raise AutoupdateError('update.gz not present in payload dir %s' %
603 payload_dir)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700604
Chris Sosa6a3697f2013-01-29 16:44:43 -0800605 metadata_obj = Autoupdate._ReadMetadataFromFile(payload_dir)
606 if not metadata_obj or not (metadata_obj.sha1 and
607 metadata_obj.sha256 and
608 metadata_obj.size):
609 sha1 = common_util.GetFileSha1(filename)
610 sha256 = common_util.GetFileSha256(filename)
611 size = common_util.GetFileSize(filename)
Gilad Arnolde74b3812013-04-22 11:27:38 -0700612 is_delta_format = self.IsDeltaFormatFile(filename)
David Zeuthen52ccd012013-10-31 12:58:26 -0700613 metadata_size = self._GetMetadataSize(filename)
614 metadata_hash = self._GetMetadataHash(payload_dir)
615 metadata_obj = UpdateMetadata(sha1, sha256, size, is_delta_format,
616 metadata_size, metadata_hash)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800617 Autoupdate._StoreMetadataToFile(payload_dir, metadata_obj)
Chris Sosa0356d3b2010-09-16 15:46:22 -0700618
Chris Sosa6a3697f2013-01-29 16:44:43 -0800619 return metadata_obj
620
621 def _ProcessUpdateComponents(self, app, event):
Gilad Arnolde7819e72014-03-21 12:50:48 -0700622 """Processes the components of an update request.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800623
Gilad Arnolde7819e72014-03-21 12:50:48 -0700624 Args:
625 app: An app component of an update request.
626 event: An event component of an update request.
627
628 Returns:
629 A named tuple containing attributes of the update requests as the
630 following fields: 'forced_update_label', 'client_version', 'board',
631 'event_result' and 'event_type'.
Chris Sosa0356d3b2010-09-16 15:46:22 -0700632 """
Chris Sosa6a3697f2013-01-29 16:44:43 -0800633 # Initialize an empty dictionary for event attributes to log.
634 log_message = {}
Jay Srinivasanac69d262012-10-30 19:05:53 -0700635
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700636 # Determine request IP, strip any IPv6 data for simplicity.
637 client_ip = cherrypy.request.remote.ip.split(':')[-1]
Gilad Arnold286a0062012-01-12 13:47:02 -0800638 # Obtain (or init) info object for this client.
639 curr_host_info = self.host_infos.GetInitHostInfo(client_ip)
640
joychen121fc9b2013-08-02 14:30:30 -0700641 client_version = FORCED_UPDATE
Chris Sosa6a3697f2013-01-29 16:44:43 -0800642 board = None
643 if app:
644 client_version = app.getAttribute('version')
645 channel = app.getAttribute('track')
646 board = (app.hasAttribute('board') and app.getAttribute('board')
Don Garrettfb15e322016-06-21 19:12:08 -0700647 or self.GetDefaultBoardID())
Chris Sosa6a3697f2013-01-29 16:44:43 -0800648 # Add attributes to log message
649 log_message['version'] = client_version
650 log_message['track'] = channel
651 log_message['board'] = board
652 curr_host_info.attrs['last_known_version'] = client_version
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700653
Gilad Arnolde7819e72014-03-21 12:50:48 -0700654 event_result = None
655 event_type = None
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700656 if event:
Gilad Arnold286a0062012-01-12 13:47:02 -0800657 event_result = int(event[0].getAttribute('eventresult'))
658 event_type = int(event[0].getAttribute('eventtype'))
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700659 client_previous_version = (event[0].getAttribute('previousversion')
660 if event[0].hasAttribute('previousversion')
661 else None)
Gilad Arnold286a0062012-01-12 13:47:02 -0800662 # Store attributes to legacy host info structure
663 curr_host_info.attrs['last_event_status'] = event_result
664 curr_host_info.attrs['last_event_type'] = event_type
665 # Add attributes to log message
666 log_message['event_result'] = event_result
667 log_message['event_type'] = event_type
Gilad Arnoldb11a8942012-03-13 15:33:21 -0700668 if client_previous_version is not None:
669 log_message['previous_version'] = client_previous_version
Gilad Arnold286a0062012-01-12 13:47:02 -0800670
Gilad Arnold8318eac2012-10-04 12:52:23 -0700671 # Log host event, if so instructed.
672 if self.host_log:
673 curr_host_info.AddLogEntry(log_message)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700674
Gilad Arnolde7819e72014-03-21 12:50:48 -0700675 UpdateRequestAttrs = collections.namedtuple(
676 'UpdateRequestAttrs',
677 ('forced_update_label', 'client_version', 'board', 'event_result',
678 'event_type'))
679
680 return UpdateRequestAttrs(
681 curr_host_info.attrs.pop('forced_update_label', None),
682 client_version, board, event_result, event_type)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800683
Chris Sosa4b951602014-04-09 20:26:07 -0700684 @classmethod
685 def _CheckOmahaRequest(cls, app):
686 """Checks |app| component of Omaha Request for correctly formed data.
687
688 Raises:
689 common_util.DevServerHTTPError: if any check fails. All 400 error codes to
690 indicate a bad HTTP request.
691 """
692 if not app:
693 raise common_util.DevServerHTTPError(
694 400, 'Missing app component in Omaha Request')
695
696 hardware_class = app.getAttribute('hardware_class')
697 if not hardware_class:
698 raise common_util.DevServerHTTPError(
699 400, 'hardware_class is required in Omaha Request')
700
701 track = app.getAttribute('track')
Chris Sosafc715442014-04-09 20:45:23 -0700702 if not (track and track.endswith('-channel')):
Chris Sosa4b951602014-04-09 20:26:07 -0700703 raise common_util.DevServerHTTPError(
Chris Sosafc715442014-04-09 20:45:23 -0700704 400, 'Omaha requests need a valid update channel')
Chris Sosa4b951602014-04-09 20:26:07 -0700705
Chris Sosa6a3697f2013-01-29 16:44:43 -0800706 def _GetStaticUrl(self):
707 """Returns the static url base that should prefix all payload responses."""
708 x_forwarded_host = cherrypy.request.headers.get('X-Forwarded-Host')
709 if x_forwarded_host:
710 hostname = 'http://' + x_forwarded_host
711 else:
712 hostname = cherrypy.request.base
713
714 if self.urlbase:
715 static_urlbase = self.urlbase
Chris Sosa6a3697f2013-01-29 16:44:43 -0800716 else:
717 static_urlbase = '%s/static' % hostname
718
719 # If we have a proxy port, adjust the URL we instruct the client to
720 # use to go through the proxy.
721 if self.proxy_port:
722 static_urlbase = _ChangeUrlPort(static_urlbase, self.proxy_port)
723
724 _Log('Using static url base %s', static_urlbase)
725 _Log('Handling update ping as %s', hostname)
726 return static_urlbase
727
joychen121fc9b2013-08-02 14:30:30 -0700728 def GetPathToPayload(self, label, client_version, board):
729 """Find a payload locally.
730
731 See devserver's update rpc for documentation.
732
733 Args:
734 label: from update request
735 client_version: from update request
736 board: from update request
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700737
738 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700739 The relative path to an update from the static_dir
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700740
joychen121fc9b2013-08-02 14:30:30 -0700741 Raises:
742 AutoupdateError: If the update could not be found.
743 """
744 path_to_payload = None
745 #TODO(joychen): deprecate --payload flag
746 if self.payload_path:
747 # Copy the image from the path to '/forced_payload'
748 label = 'forced_payload'
749 dest_path = os.path.join(self.static_dir, label, constants.UPDATE_FILE)
750 dest_stateful = os.path.join(self.static_dir, label,
751 constants.STATEFUL_FILE)
Alex Deymo48e970d2015-09-23 14:34:41 -0700752 dest_meta = os.path.join(self.static_dir, label, constants.METADATA_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700753
754 src_path = os.path.abspath(self.payload_path)
755 src_stateful = os.path.join(os.path.dirname(src_path),
756 constants.STATEFUL_FILE)
757 common_util.MkDirP(os.path.join(self.static_dir, label))
Alex Deymo3e2d4952013-09-03 21:49:41 -0700758 common_util.SymlinkFile(src_path, dest_path)
Alex Deymo48e970d2015-09-23 14:34:41 -0700759 # The old metadata file should be regenerated whenever a new payload is
760 # used.
761 try:
762 os.unlink(dest_meta)
763 except OSError:
764 pass
joychen121fc9b2013-08-02 14:30:30 -0700765 if os.path.exists(src_stateful):
766 # The stateful payload is optional.
Alex Deymo3e2d4952013-09-03 21:49:41 -0700767 common_util.SymlinkFile(src_stateful, dest_stateful)
joychen121fc9b2013-08-02 14:30:30 -0700768 else:
769 _Log('WARN: %s not found. Expected for dev and test builds',
770 constants.STATEFUL_FILE)
771 if os.path.exists(dest_stateful):
772 os.remove(dest_stateful)
773 path_to_payload = self.GetUpdateForLabel(client_version, label)
774 #TODO(joychen): deprecate --image flag
775 elif self.forced_image:
joychendbfe6c92013-08-16 20:03:49 -0700776 if self.forced_image.startswith('xbuddy:'):
777 # This is trying to use an xbuddy path in place of a path to an image.
joychendbfe6c92013-08-16 20:03:49 -0700778 xbuddy_label = self.forced_image.split(':')[1]
779 self.forced_image = None
joychen365a5742013-08-21 10:41:18 -0700780 # Make sure the xbuddy path target is in the directory.
781 path_to_payload, _image_name = self.xbuddy.Get(xbuddy_label.split('/'))
782 # Pretend to have called update with this update path to payload.
Chris Sosa54ef81e2013-08-27 16:45:12 -0700783 self.GetPathToPayload(xbuddy_label, client_version, board)
784 else:
785 src_path = os.path.abspath(self.forced_image)
786 if os.path.exists(src_path) and common_util.IsInsideChroot():
787 # Image was found for the given label. Generate update if we can.
Chris Sosa75490802013-09-30 17:21:45 -0700788 path_to_payload = self.GenerateUpdateImageWithCache(src_path)
789 # Add links from the static directory to the update.
790 cache_path = _NonePathJoin(self.static_dir, path_to_payload)
791 self._SymlinkUpdateFiles(cache_path, self.static_dir)
joychen121fc9b2013-08-02 14:30:30 -0700792 else:
793 label = label or ''
794 label_list = label.split('/')
795 # Suppose that the path follows old protocol of indexing straight
796 # into static_dir with board/version label.
797 # Attempt to get the update in that directory, generating if necc.
798 path_to_payload = self.GetUpdateForLabel(client_version, label)
799 if path_to_payload is None:
800 # There was no update or image found in the directory.
801 # Let XBuddy find an image, and then generate an update to it.
802 if label_list[0] == 'xbuddy':
803 # If path explicitly calls xbuddy, pop off the tag.
804 label_list.pop()
Chris Sosa75490802013-09-30 17:21:45 -0700805 x_label, image_name = self.xbuddy.Translate(label_list, board=board)
joychen121fc9b2013-08-02 14:30:30 -0700806 if image_name not in constants.ALL_IMAGES:
807 raise AutoupdateError(
808 "Use an image alias: dev, base, test, or recovery.")
809 # Path has been resolved, try to get the image.
810 path_to_payload = self.GetUpdateForLabel(client_version, x_label,
811 image_name)
812 if path_to_payload is None:
813 # Neither image nor update payload found after translation.
814 # Try to get an update to a test image from GS using the label.
815 path_to_payload, _image_name = self.xbuddy.Get(
816 ['remote', label, 'full_payload'])
817
818 # One of the above options should have gotten us a relative path.
819 if path_to_payload is None:
820 raise AutoupdateError('Failed to get an update for: %s' % label)
821 else:
Chris Sosa75490802013-09-30 17:21:45 -0700822 return path_to_payload
joychen121fc9b2013-08-02 14:30:30 -0700823
David Zeuthen52ccd012013-10-31 12:58:26 -0700824 @staticmethod
825 def _SignMetadataHash(private_key_path, metadata_hash):
826 """Signs metadata hash.
827
828 Signs a metadata hash with a private key. This includes padding the
829 hash with PKCS#1 v1.5 padding as well as an ASN.1 header.
830
831 Args:
832 private_key_path: The path to a private key to use for signing.
833 metadata_hash: A raw SHA-256 hash (32 bytes).
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700834
David Zeuthen52ccd012013-10-31 12:58:26 -0700835 Returns:
836 The raw signature.
837 """
838 args = ['openssl', 'rsautl', '-pkcs', '-sign', '-inkey', private_key_path]
839 padded_metadata_hash = ('\x30\x31\x30\x0d\x06\x09\x60\x86'
840 '\x48\x01\x65\x03\x04\x02\x01\x05'
841 '\x00\x04\x20') + metadata_hash
842 child = subprocess.Popen(args,
843 stdin=subprocess.PIPE,
844 stdout=subprocess.PIPE)
845 signature, _ = child.communicate(input=padded_metadata_hash)
846 return signature
847
joychen121fc9b2013-08-02 14:30:30 -0700848 def HandleUpdatePing(self, data, label=''):
Chris Sosa6a3697f2013-01-29 16:44:43 -0800849 """Handles an update ping from an update client.
850
851 Args:
852 data: XML blob from client.
853 label: optional label for the update.
Gilad Arnoldd8d595c2014-03-21 13:00:41 -0700854
Chris Sosa6a3697f2013-01-29 16:44:43 -0800855 Returns:
856 Update payload message for client.
857 """
858 # Get the static url base that will form that base of our update url e.g.
859 # http://hostname:8080/static/update.gz.
860 static_urlbase = self._GetStaticUrl()
861
862 # Parse the XML we got into the components we care about.
863 protocol, app, event, update_check = autoupdate_lib.ParseUpdateRequest(data)
864
Chris Sosab26b1202013-08-16 16:40:55 -0700865 # Process attributes of the update check.
Gilad Arnolde7819e72014-03-21 12:50:48 -0700866 request_attrs = self._ProcessUpdateComponents(app, event)
Chris Sosab26b1202013-08-16 16:40:55 -0700867
joychen121fc9b2013-08-02 14:30:30 -0700868 if not update_check:
Gilad Arnolde7819e72014-03-21 12:50:48 -0700869 if ((request_attrs.event_type ==
870 autoupdate_lib.EVENT_TYPE_UPDATE_DOWNLOAD_STARTED) and
871 request_attrs.event_result == autoupdate_lib.EVENT_RESULT_SUCCESS):
872 with self._update_count_lock:
873 if self.max_updates == 0:
874 _Log('Received too many download_started notifications. This '
875 'probably means a bug in the test environment, such as too '
876 'many clients running concurrently. Alternatively, it could '
877 'be a bug in the update client.')
878 elif self.max_updates > 0:
879 self.max_updates -= 1
joychen121fc9b2013-08-02 14:30:30 -0700880
Gilad Arnolde7819e72014-03-21 12:50:48 -0700881 _Log('A non-update event notification received. Returning an ack.')
882 return autoupdate_lib.GetEventResponse(protocol)
883
884 if request_attrs.forced_update_label:
Chris Sosa6a3697f2013-01-29 16:44:43 -0800885 if label:
886 _Log('Label: %s set but being overwritten to %s by request', label,
Gilad Arnolde7819e72014-03-21 12:50:48 -0700887 request_attrs.forced_update_label)
888 label = request_attrs.forced_update_label
Chris Sosa6a3697f2013-01-29 16:44:43 -0800889
Gilad Arnolde7819e72014-03-21 12:50:48 -0700890 # Make sure that we did not already exceed the max number of allowed update
891 # responses. Note that the counter is only decremented when the client
892 # reports an actual download, to avoid race conditions between concurrent
893 # update requests from the same client due to a timeout.
joychen121fc9b2013-08-02 14:30:30 -0700894 if self.max_updates == 0:
Gilad Arnolde7819e72014-03-21 12:50:48 -0700895 _Log('Request received but max number of updates already served.')
joychen121fc9b2013-08-02 14:30:30 -0700896 return autoupdate_lib.GetNoUpdateResponse(protocol)
897
Gilad Arnolde7819e72014-03-21 12:50:48 -0700898 _Log('Update Check Received. Client is using protocol version: %s',
899 protocol)
joychen121fc9b2013-08-02 14:30:30 -0700900
Chris Sosa6a3697f2013-01-29 16:44:43 -0800901 # Finally its time to generate the omaha response to give to client that
902 # lets them know where to find the payload and its associated metadata.
903 metadata_obj = None
904
905 try:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700906 # Are we provisioning a remote or local payload?
907 if self.remote_payload:
Chris Sosa4b951602014-04-09 20:26:07 -0700908
909 self._CheckOmahaRequest(app)
910
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700911 # If no explicit label was provided, use the value of --payload.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800912 if not label:
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700913 label = self.payload_path
Chris Sosa0356d3b2010-09-16 15:46:22 -0700914
Chris Sosa52f15bc2013-08-13 17:14:15 -0700915 # TODO(sosa): Remove backwards-compatible hack.
Chris Sosab26b1202013-08-16 16:40:55 -0700916 if not '.bin' in label:
Chris Sosa52f15bc2013-08-13 17:14:15 -0700917 url = _NonePathJoin(static_urlbase, label, 'update.gz')
918 else:
919 url = _NonePathJoin(static_urlbase, label)
Chris Sosa5d342a22010-09-28 16:54:41 -0700920
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700921 # Get remote payload attributes.
Chris Sosa6a3697f2013-01-29 16:44:43 -0800922 metadata_obj = self._GetRemotePayloadAttrs(url)
Gilad Arnold0c9c8602012-10-02 23:58:58 -0700923 else:
Gilad Arnolde7819e72014-03-21 12:50:48 -0700924 path_to_payload = self.GetPathToPayload(
925 label, request_attrs.client_version, request_attrs.board)
joychen121fc9b2013-08-02 14:30:30 -0700926 url = _NonePathJoin(static_urlbase, path_to_payload,
joychen7c2054a2013-07-25 11:14:07 -0700927 constants.UPDATE_FILE)
joychen121fc9b2013-08-02 14:30:30 -0700928 local_payload_dir = _NonePathJoin(self.static_dir, path_to_payload)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800929 metadata_obj = self.GetLocalPayloadAttrs(local_payload_dir)
Chris Sosa6a3697f2013-01-29 16:44:43 -0800930 except AutoupdateError as e:
931 # Raised if we fail to generate an update payload.
932 _Log('Failed to process an update: %r', e)
933 return autoupdate_lib.GetNoUpdateResponse(protocol)
934
David Zeuthen52ccd012013-10-31 12:58:26 -0700935 # Sign the metadata hash, if requested.
936 signed_metadata_hash = None
937 if self.private_key_for_metadata_hash_signature:
938 signed_metadata_hash = base64.b64encode(Autoupdate._SignMetadataHash(
939 self.private_key_for_metadata_hash_signature,
940 base64.b64decode(metadata_obj.metadata_hash)))
941
942 # Include public key, if requested.
943 public_key_data = None
944 if self.public_key:
945 public_key_data = base64.b64encode(open(self.public_key, 'r').read())
946
Chris Sosa4b951602014-04-09 20:26:07 -0700947 update_response = autoupdate_lib.GetUpdateResponse(
Chris Sosa6a3697f2013-01-29 16:44:43 -0800948 metadata_obj.sha1, metadata_obj.sha256, metadata_obj.size, url,
David Zeuthen52ccd012013-10-31 12:58:26 -0700949 metadata_obj.is_delta_format, metadata_obj.metadata_size,
950 signed_metadata_hash, public_key_data, protocol, self.critical_update)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700951
Gilad Arnolde7819e72014-03-21 12:50:48 -0700952 _Log('Responding to client to use url %s to get image', url)
Gilad Arnoldd0c71752013-12-06 11:48:45 -0800953 return update_response
954
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700955 def HandleHostInfoPing(self, ip):
956 """Returns host info dictionary for the given IP in JSON format."""
957 assert ip, 'No ip provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800958 if ip in self.host_infos.table:
959 return json.dumps(self.host_infos.GetHostInfo(ip).attrs)
960
961 def HandleHostLogPing(self, ip):
962 """Returns a complete log of events for host in JSON format."""
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700963 # If all events requested, return a dictionary of logs keyed by IP address.
Gilad Arnold286a0062012-01-12 13:47:02 -0800964 if ip == 'all':
965 return json.dumps(
966 dict([(key, self.host_infos.table[key].log)
967 for key in self.host_infos.table]))
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700968
969 # Otherwise we're looking for a specific IP address, so find its log.
Gilad Arnold286a0062012-01-12 13:47:02 -0800970 if ip in self.host_infos.table:
971 return json.dumps(self.host_infos.GetHostInfo(ip).log)
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700972
Gilad Arnold4ba437d2012-10-05 15:28:27 -0700973 # If no events were logged for this IP, return an empty log.
974 return json.dumps([])
975
Dale Curtisc9aaf3a2011-08-09 15:47:40 -0700976 def HandleSetUpdatePing(self, ip, label):
977 """Sets forced_update_label for a given host."""
978 assert ip, 'No ip provided.'
979 assert label, 'No label provided.'
Gilad Arnold286a0062012-01-12 13:47:02 -0800980 self.host_infos.GetInitHostInfo(ip).attrs['forced_update_label'] = label