blob: 8f585b7f82353719d3a01261ef066008e3c31fd4 [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08002# Copyright 2015 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08006import argparse
Yilin Yangf9fe1932019-11-04 17:09:34 +08007import binascii
8import codecs
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08009import contextlib
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080010import ctypes
11import ctypes.util
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080012import fcntl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080013import hashlib
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080014import json
15import logging
16import os
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080017import platform
Yilin Yang8b7f5192020-01-08 11:43:00 +080018import queue
Wei-Ning Huang829e0c82015-05-26 14:37:23 +080019import re
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080020import select
Wei-Ning Huanga301f572015-06-03 17:34:21 +080021import signal
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080022import socket
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080023import ssl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080024import struct
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080025import subprocess
26import sys
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080027import termios
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080028import threading
29import time
Joel Kitching22b89042015-08-06 18:23:29 +080030import traceback
Wei-Ning Huang39169902015-09-19 06:00:23 +080031import tty
Yilin Yangf54fb912020-01-08 11:42:38 +080032import urllib.request
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080033import uuid
34
Wei-Ning Huang2132de32015-04-13 17:24:38 +080035import jsonrpclib
36from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
Wei-Ning Huang2132de32015-04-13 17:24:38 +080037
Yilin Yang64dd8592020-11-10 16:16:23 +080038from cros.factory.gooftool import cros_config as cros_config_module
39from cros.factory.test import state
40from cros.factory.test.state import TestState
Yilin Yang1512d972020-11-19 13:34:42 +080041from cros.factory.test.test_lists import manager
Yilin Yang64dd8592020-11-10 16:16:23 +080042from cros.factory.utils import net_utils
Yilin Yang42ba5c62020-05-05 10:32:34 +080043from cros.factory.utils import process_utils
Cheng Yueh59a29662020-12-02 12:20:18 +080044from cros.factory.utils import sys_interface
Yilin Yang64dd8592020-11-10 16:16:23 +080045from cros.factory.utils import sys_utils
46from cros.factory.utils.type_utils import Enum
Yilin Yang42ba5c62020-05-05 10:32:34 +080047
Yilin Yangf54fb912020-01-08 11:42:38 +080048
Fei Shaobb0a3e62020-06-20 15:41:25 +080049_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', '4499'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080050
Fei Shaobb0a3e62020-06-20 15:41:25 +080051_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', '4455'))
52_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', '4456'))
53_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', '9000'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080054
55_BUFSIZE = 8192
56_RETRY_INTERVAL = 2
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080057_SEPARATOR = b'\r\n'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080058_PING_TIMEOUT = 3
59_PING_INTERVAL = 5
60_REQUEST_TIMEOUT_SECS = 60
61_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080062_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080063
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080064_CONTROL_START = 128
65_CONTROL_END = 129
66
Wei-Ning Huanga301f572015-06-03 17:34:21 +080067_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080068_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080069
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080070# Stream control
71_STDIN_CLOSED = '##STDIN_CLOSED##'
72
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080073SUCCESS = 'success'
74FAILED = 'failed'
75DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080076
Joel Kitching22b89042015-08-06 18:23:29 +080077
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080078class PingTimeoutError(Exception):
79 pass
80
81
82class RequestError(Exception):
83 pass
84
85
Fei Shaobd07c9a2020-06-15 19:04:50 +080086class BufferedSocket:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080087 """A buffered socket that supports unrecv.
88
89 Allow putting back data back to the socket for the next recv() call.
90 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080091 def __init__(self, sock):
92 self.sock = sock
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080093 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080094
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080095 def fileno(self):
96 return self.sock.fileno()
97
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080098 def Recv(self, bufsize, flags=0):
99 if self._buf:
100 if len(self._buf) >= bufsize:
101 ret = self._buf[:bufsize]
102 self._buf = self._buf[bufsize:]
103 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800104 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800105 self._buf = b''
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800106 return ret + self.sock.recv(bufsize - len(ret), flags)
107 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800108
109 def UnRecv(self, buf):
110 self._buf = buf + self._buf
111
112 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800113 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800114
115 def RecvBuf(self):
116 """Only recive from buffer."""
117 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800118 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800119 return ret
120
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800121 def Close(self):
122 self.sock.close()
123
124
Fei Shaobd07c9a2020-06-15 19:04:50 +0800125class TLSSettings:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800126 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800127 """Constructor.
128
129 Args:
130 tls_cert_file: TLS certificate in PEM format.
131 enable_tls_without_verify: enable TLS but don't verify certificate.
132 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800133 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800134 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800135 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800136 self._tls_context = None
137
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800138 def _UpdateContext(self):
139 if not self._enabled:
140 self._tls_context = None
141 return
142
143 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
144 self._tls_context.verify_mode = ssl.CERT_REQUIRED
145
146 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800147 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800148 self._tls_context.check_hostname = True
149 try:
150 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800151 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800152 except IOError as e:
153 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
154 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800155 else:
156 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
157 logging.info('TLSSettings: using built-in ca-certificates')
158 else:
159 self._tls_context.verify_mode = ssl.CERT_NONE
160 logging.info('TLSSettings: skipping TLS verification!!!')
161
162 def SetEnabled(self, enabled):
163 logging.info('TLSSettings: enabled: %s', enabled)
164
165 if self._enabled != enabled:
166 self._enabled = enabled
167 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800168
169 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800170 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800171
172 def Context(self):
173 return self._tls_context
174
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800175
Fei Shaobd07c9a2020-06-15 19:04:50 +0800176class Ghost:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800177 """Ghost implements the client protocol of Overlord.
178
179 Ghost provide terminal/shell/logcat functionality and manages the client
180 side connectivity.
181 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800182 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800183
184 MODE_NAME = {
185 NONE: 'NONE',
186 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800187 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800188 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800189 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800190 FILE: 'File',
191 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800192 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800193
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800194 RANDOM_MID = '##random_mid##'
195
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800196 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
197 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Yilin Yang77668412021-02-02 10:53:36 +0800198 command=None, file_op=None, port=None, tls_mode=None,
199 ovl_path=None, certificate_dir=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800200 """Constructor.
201
202 Args:
203 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800204 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800205 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800206 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
207 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800208 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800209 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800210 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800211 terminal_sid: the terminal session ID associate with this client. This is
212 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800213 tty_device: the terminal device to open, if tty_device is None, as pseudo
214 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800215 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800216 file_op: a tuple (action, filepath, perm). action is either 'download' or
217 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800218 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800219 tls_mode: can be [True, False, None]. if not None, skip detection of
220 TLS and assume whether server use TLS or not.
Yilin Yang77668412021-02-02 10:53:36 +0800221 ovl_path: path to ovl tool.
222 certificate_dir: path to overlord certificate directory
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800223 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800224 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
225 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800226 if mode == Ghost.SHELL:
227 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800228 if mode == Ghost.FILE:
229 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800230
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800231 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800232 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800233 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800234 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800235 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800236 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800237 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800238 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800239 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800240 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800241 self._ttyname_to_sid = {}
242 self._terminal_sid_to_pid = {}
243 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800244 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800245 self._register_status = DISCONNECTED
246 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800247 self._tls_mode = tls_mode
Yilin Yang77668412021-02-02 10:53:36 +0800248 self._ovl_path = ovl_path
249 self._certificate_dir = certificate_dir
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800250
Yilin Yang89a136c2021-01-05 15:25:05 +0800251 # The information of track_connection is lost after ghost restart.
252 self._track_connection = None
253 self._track_connection_timeout_secs = 900
254
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800255 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800256 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800257 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800258
259 # Protocol specific
260 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800261 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800262 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800263 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800264 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800265 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800266
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800267 def SetIgnoreChild(self, status):
268 # Only ignore child for Agent since only it could spawn child Ghost.
269 if self._mode == Ghost.AGENT:
270 signal.signal(signal.SIGCHLD,
271 signal.SIG_IGN if status else signal.SIG_DFL)
272
273 def GetFileSha1(self, filename):
Yilin Yang0412c272019-12-05 16:57:40 +0800274 with open(filename, 'rb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800275 return hashlib.sha1(f.read()).hexdigest()
276
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800277 def TLSEnabled(self, host, port):
278 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800279 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
280 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800281 # Allow any certificate since we only want to check if server talks TLS.
282 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
283 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800284
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800285 sock = context.wrap_socket(sock, server_hostname=host)
286 sock.settimeout(_CONNECT_TIMEOUT)
287 sock.connect((host, port))
288 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800289 except ssl.SSLError:
290 return False
Stimim Chen3899a912020-07-17 10:52:03 +0800291 except socket.timeout:
292 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800293 except socket.error: # Connect refused or timeout
294 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800295 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800296 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800297
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800298 def Upgrade(self):
299 logging.info('Upgrade: initiating upgrade sequence...')
300
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800301 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800302 https_enabled = self.TLSEnabled(self._connected_addr[0],
303 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800304 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800305 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
306 'abort')
307 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800308
309 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800310 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
311 'without TLS enabled! Possible mis-configuration or '
312 'DNS/IP spoofing detected, abort')
313 return
314
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800315 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800316 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800317 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800318 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800319
320 # Download sha1sum for ghost.py for verification
321 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800322 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800323 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
324 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800325 if f.getcode() != 200:
326 raise RuntimeError('HTTP status %d' % f.getcode())
327 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800328 except (ssl.SSLError, ssl.CertificateError) as e:
329 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
330 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800331 except Exception:
332 logging.error('Upgrade: failed to download sha1sum file, abort')
333 return
334
335 if self.GetFileSha1(scriptpath) == sha1sum:
336 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
337 return
338
339 # Download upgrade version of ghost.py
340 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800341 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800342 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
343 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800344 if f.getcode() != 200:
345 raise RuntimeError('HTTP status %d' % f.getcode())
346 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800347 except (ssl.SSLError, ssl.CertificateError) as e:
348 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
349 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800350 except Exception:
351 logging.error('Upgrade: failed to download upgrade, abort')
352 return
353
354 # Compare SHA1 sum
355 if hashlib.sha1(data).hexdigest() != sha1sum:
356 logging.error('Upgrade: sha1sum mismatch, abort')
357 return
358
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800359 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800360 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800361 f.write(data)
362 except Exception:
363 logging.error('Upgrade: failed to write upgrade onto disk, abort')
364 return
365
366 logging.info('Upgrade: restarting ghost...')
367 self.CloseSockets()
368 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800369 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800370
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800371 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800372 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800373 if self._prop_file:
374 with open(self._prop_file, 'r') as f:
375 self._properties = json.loads(f.read())
Yilin Yang77668412021-02-02 10:53:36 +0800376 if self._ovl_path:
377 self._properties['ovl_path'] = self._ovl_path
378 if self._certificate_dir:
379 self._properties['certificate_dir'] = self._certificate_dir
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800380 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800381 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800382
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800383 def CloseSockets(self):
384 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800385 if self._platform == 'Linux':
386 for fd in os.listdir('/proc/self/fd/'):
387 try:
388 real_fd = os.readlink('/proc/self/fd/%s' % fd)
389 if real_fd.startswith('socket'):
390 os.close(int(fd))
391 except Exception:
392 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800393
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800394 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800395 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800396 """Spawn a child ghost with specific mode.
397
398 Returns:
399 The spawned child process pid.
400 """
Joel Kitching22b89042015-08-06 18:23:29 +0800401 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800402 self.SetIgnoreChild(False)
403
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800404 pid = os.fork()
405 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800406 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800407 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
408 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800409 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800410 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800411 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800412 sys.exit(0)
413 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800414 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800415 return pid
416
417 def Timestamp(self):
418 return int(time.time())
419
420 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800421 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800422 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800423 ret = re.search('gateway: (.*)', output)
424 if ret:
425 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800426 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800427 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800428 with open('/proc/net/route', 'r') as f:
429 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800430
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800431 ips = []
432 for line in lines:
433 parts = line.split('\t')
434 if parts[2] == '00000000':
435 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800436
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800437 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800438 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800439 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800440 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800441 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800442
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800443 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800444
445 logging.warning('GetGateWayIP: unsupported platform')
446 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800447
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800448 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800449 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800450 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800451
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800452 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800453 match = re.match(r'^https?://(.*):.*$', url)
454 if match:
455 return [match.group(1)]
456 except Exception:
457 pass
458 return []
459
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800460 def GetMachineID(self):
461 """Generates machine-dependent ID string for a machine.
462 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800463 Linux:
464 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800465 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
466 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800467 We follow the listed order to generate machine ID, and fallback to the
468 next alternative if the previous doesn't work.
469
470 Darwin:
471 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800472 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800473 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800474 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800475 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800476 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800477
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800478 # Darwin
479 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800480 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
481 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800482 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
483 if ret:
484 return ret.group(1)
485
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800486 # Try factory device id
487 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800488 from cros.factory.test import session
489 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800490 except Exception:
491 pass
492
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800493 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800494 try:
495 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
496 return f.read().strip()
497 except Exception:
498 pass
499
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800500 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800501 try:
502 macs = []
503 ifaces = sorted(os.listdir('/sys/class/net'))
504 for iface in ifaces:
505 if iface == 'lo':
506 continue
507
508 with open('/sys/class/net/%s/address' % iface, 'r') as f:
509 macs.append(f.read().strip())
510
511 return ';'.join(macs)
512 except Exception:
513 pass
514
Peter Shihcb0e5512017-06-14 16:59:46 +0800515 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800516
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800517 def GetProcessWorkingDirectory(self, pid):
518 if self._platform == 'Linux':
519 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800520 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800521 PROC_PIDVNODEPATHINFO = 9
522 proc_vnodepathinfo_size = 2352
523 vid_path_offset = 152
524
525 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
526 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
527 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
528 ctypes.byref(buf), proc_vnodepathinfo_size)
529 buf = buf.raw[vid_path_offset:]
530 n = buf.index('\0')
531 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800532 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800533
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800534 def Reset(self):
535 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800536 if self._sock is not None:
537 self._sock.Close()
538 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800539 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800540 self._last_ping = 0
541 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800542 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800543 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800544
545 def SendMessage(self, msg):
546 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800547 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800548
549 def SendRequest(self, name, args, handler=None,
550 timeout=_REQUEST_TIMEOUT_SECS):
551 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800552 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800553
554 rid = str(uuid.uuid4())
555 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800556 if timeout >= 0:
557 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800558 self.SendMessage(msg)
559
560 def SendResponse(self, omsg, status, params=None):
561 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
562 self.SendMessage(msg)
563
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800564 def HandleTTYControl(self, fd, control_str):
565 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800566 command = msg['command']
567 params = msg['params']
568 if command == 'resize':
569 # some error happened on websocket
570 if len(params) != 2:
571 return
572 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
573 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
574 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800575 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800576
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800577 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800578 """Spawn a TTY server and forward I/O to the TCP socket."""
579 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800580
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800581 try:
582 if self._tty_device is None:
583 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800584
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800585 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800586 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800587 try:
588 server = GhostRPCServer()
589 server.RegisterTTY(self._session_id, ttyname)
590 server.RegisterSession(self._session_id, os.getpid())
591 except Exception:
592 # If ghost is launched without RPC server, the call will fail but we
593 # can ignore it.
594 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800595
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800596 # The directory that contains the current running ghost script
597 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800598
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800599 env = os.environ.copy()
600 env['USER'] = os.getenv('USER', 'root')
601 env['HOME'] = os.getenv('HOME', '/root')
602 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
603 os.chdir(env['HOME'])
604 os.execve(_SHELL, [_SHELL], env)
605 else:
606 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800607 tty.setraw(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800608 # 0: iflag
609 # 1: oflag
610 # 2: cflag
611 # 3: lflag
612 # 4: ispeed
613 # 5: ospeed
614 # 6: cc
Wei-Ning Huang39169902015-09-19 06:00:23 +0800615 attr = termios.tcgetattr(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800616 attr[0] &= (termios.IXON | termios.IXOFF)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800617 attr[2] |= termios.CLOCAL
618 attr[2] &= ~termios.CRTSCTS
619 attr[4] = termios.B115200
620 attr[5] = termios.B115200
621 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800622
Stimim Chen3899a912020-07-17 10:52:03 +0800623 nonlocals = {
624 'control_state': None,
625 'control_str': b''
626 }
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800627
628 def _ProcessBuffer(buf):
Stimim Chen3899a912020-07-17 10:52:03 +0800629 write_buffer = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800630 while buf:
631 if nonlocals['control_state']:
Stimim Chen3899a912020-07-17 10:52:03 +0800632 if _CONTROL_END in buf:
633 index = buf.index(_CONTROL_END)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800634 nonlocals['control_str'] += buf[:index]
635 self.HandleTTYControl(fd, nonlocals['control_str'])
636 nonlocals['control_state'] = None
Stimim Chen3899a912020-07-17 10:52:03 +0800637 nonlocals['control_str'] = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800638 buf = buf[index+1:]
639 else:
640 nonlocals['control_str'] += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800641 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800642 else:
Stimim Chen3899a912020-07-17 10:52:03 +0800643 if _CONTROL_START in buf:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800644 nonlocals['control_state'] = _CONTROL_START
Stimim Chen3899a912020-07-17 10:52:03 +0800645 index = buf.index(_CONTROL_START)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800646 write_buffer += buf[:index]
647 buf = buf[index+1:]
648 else:
649 write_buffer += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800650 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800651
652 if write_buffer:
653 os.write(fd, write_buffer)
654
655 _ProcessBuffer(self._sock.RecvBuf())
656
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800657 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800658 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800659
660 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800661 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800662
663 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800664 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800665 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800666 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800667 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800668 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800669 logging.error('SpawnTTYServer: %s', e, exc_info=True)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800670 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800671 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800672
673 logging.info('SpawnTTYServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800674 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800675
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800676 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800677 """Spawn a shell server and forward input/output from/to the TCP socket."""
678 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800679
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800680 # Add ghost executable to PATH
681 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
682 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800683 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800684
685 # Execute shell command from HOME directory
686 os.chdir(os.getenv('HOME', '/tmp'))
687
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800688 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800689 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800690 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800691
692 def make_non_block(fd):
693 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
694 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
695
696 make_non_block(p.stdout)
697 make_non_block(p.stderr)
698
699 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800700 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800701
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800702 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800703 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800704 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800705 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800706 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800707
708 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800709 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800710
711 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800712 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800713 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800714 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800715
716 try:
717 idx = ret.index(_STDIN_CLOSED * 2)
718 p.stdin.write(ret[:idx])
719 p.stdin.close()
720 except ValueError:
721 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800722 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800723 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800724 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800725 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800726 logging.error('SpawnShellServer: %s', e, exc_info=True)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800727 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800728 # Check if the process is terminated. If not, Send SIGTERM to process,
729 # then wait for 1 second. Send another SIGKILL to make sure the process is
730 # terminated.
731 p.poll()
732 if p.returncode is None:
733 try:
734 p.terminate()
735 time.sleep(1)
736 p.kill()
737 except Exception:
738 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800739
740 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800741 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800742
743 logging.info('SpawnShellServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800744 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800745
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800746 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800747 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800748 try:
749 size = os.stat(self._file_op[1]).st_size
750 except OSError as e:
751 logging.error('InitiateFileOperation: download: %s', e)
752 sys.exit(1)
753
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800754 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800755 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800756 'filename': os.path.basename(self._file_op[1]),
757 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800758 elif self._file_op[0] == 'upload':
759 self.SendRequest('clear_to_upload', {}, timeout=-1)
760 self.StartUploadServer()
761 else:
762 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800763
764 def StartDownloadServer(self):
765 logging.info('StartDownloadServer: started')
766
767 try:
768 with open(self._file_op[1], 'rb') as f:
769 while True:
770 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800771 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800772 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800773 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800774 except Exception as e:
775 logging.error('StartDownloadServer: %s', e)
776 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800777 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800778
779 logging.info('StartDownloadServer: terminated')
Yilin Yangb5030952021-01-19 12:44:32 +0800780 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800781
Wei-Ning Huange2981862015-08-03 15:03:08 +0800782 def StartUploadServer(self):
783 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800784 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800785 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800786 dirname = os.path.dirname(filepath)
787 if not os.path.exists(dirname):
788 try:
789 os.makedirs(dirname)
790 except Exception:
791 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800792
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800793 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800794 if self._file_op[2]:
795 os.fchmod(f.fileno(), self._file_op[2])
796
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800797 f.write(self._sock.RecvBuf())
798
Wei-Ning Huange2981862015-08-03 15:03:08 +0800799 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800800 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800801 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800802 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800803 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800804 break
805 f.write(buf)
806 except socket.error as e:
807 logging.error('StartUploadServer: socket error: %s', e)
808 except Exception as e:
809 logging.error('StartUploadServer: %s', e)
810 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800811 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800812
813 logging.info('StartUploadServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800814 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huange2981862015-08-03 15:03:08 +0800815
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800816 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800817 """Spawn a port forwarding server and forward I/O to the TCP socket."""
818 logging.info('SpawnPortForwardServer: started')
819
820 src_sock = None
821 try:
822 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800823 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800824 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800825
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800826 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800827
828 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800829 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800830
831 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800832 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800833 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800834 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800835 src_sock.send(data)
836
837 if src_sock in rd:
838 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800839 if not data:
Yilin Yang969b8012020-12-16 14:38:00 +0800840 continue
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800841 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800842 except Exception as e:
843 logging.error('SpawnPortForwardServer: %s', e)
844 finally:
845 if src_sock:
846 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800847 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800848
849 logging.info('SpawnPortForwardServer: terminated')
Yilin Yanga03fd0a2020-10-23 16:58:14 +0800850 os._exit(0) # pylint: disable=protected-access
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800851
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800852 def Ping(self):
853 def timeout_handler(x):
854 if x is None:
855 raise PingTimeoutError
856
857 self._last_ping = self.Timestamp()
858 self.SendRequest('ping', {}, timeout_handler, 5)
859
Wei-Ning Huangae923642015-09-24 14:08:09 +0800860 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800861 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800862 filepath = params['filename']
863 if not os.path.isabs(filepath):
864 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
865
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800866 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800867 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800868 pass
869 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800870 self.SendResponse(msg, str(e))
871 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800872
873 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800874 file_op=('download', filepath))
875 self.SendResponse(msg, SUCCESS)
876
877 def HandleFileUploadRequest(self, msg):
878 params = msg['params']
879
880 # Resolve upload filepath
881 filename = params['filename']
882 dest_path = filename
883
884 # If dest is specified, use it first
885 dest_path = params.get('dest', '')
886 if dest_path:
887 if not os.path.isabs(dest_path):
888 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
889
890 if os.path.isdir(dest_path):
891 dest_path = os.path.join(dest_path, filename)
892 else:
893 target_dir = os.getenv('HOME', '/tmp')
894
895 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800896 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800897 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
898 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800899 try:
900 target_dir = self.GetProcessWorkingDirectory(pid)
901 except Exception as e:
902 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800903
904 dest_path = os.path.join(target_dir, filename)
905
906 try:
907 os.makedirs(os.path.dirname(dest_path))
908 except Exception:
909 pass
910
911 try:
912 with open(dest_path, 'w') as _:
913 pass
914 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800915 self.SendResponse(msg, str(e))
916 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800917
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800918 # If not check_only, spawn FILE mode ghost agent to handle upload
919 if not params.get('check_only', False):
920 self.SpawnGhost(self.FILE, params['sid'],
921 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800922 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800923
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800924 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800925 command = msg['name']
926 params = msg['params']
927
928 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800929 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800930 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800931 self.SpawnGhost(self.TERMINAL, params['sid'],
932 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800933 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800934 elif command == 'shell':
935 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800936 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800937 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800938 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800939 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800940 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800941 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800942 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800943 elif command == 'forward':
944 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
945 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800946
947 def HandleResponse(self, response):
948 rid = str(response['rid'])
949 if rid in self._requests:
950 handler = self._requests[rid][2]
951 del self._requests[rid]
952 if callable(handler):
953 handler(response)
954 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800955 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800956
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800957 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800958 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800959 try:
960 index = buf.index(_SEPARATOR)
961 except ValueError:
962 self._sock.UnRecv(buf)
963 return
964
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800965 msgs_json = [buf[:index]]
966 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800967 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800968 msgs_json = buf.split(_SEPARATOR)
969 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800970
971 for msg_json in msgs_json:
972 try:
973 msg = json.loads(msg_json)
974 except ValueError:
975 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800976 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800977 continue
978
979 if 'name' in msg:
980 self.HandleRequest(msg)
981 elif 'response' in msg:
982 self.HandleResponse(msg)
983 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800984 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800985
986 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800987 """Scans for pending requests which have timed out.
988
989 If any timed-out requests are discovered, their handler is called with the
990 special response value of None.
991 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800992 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800993 request_time, timeout, handler = self._requests[rid]
994 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800995 if callable(handler):
996 handler(None)
997 else:
998 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800999 del self._requests[rid]
1000
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001001 def InitiateDownload(self):
1002 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001003 sid = self._ttyname_to_sid[ttyname]
1004 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +08001005 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001006
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001007 def Listen(self):
1008 try:
1009 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001010 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +08001011 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001012
1013 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001014 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001015
1016 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +08001017 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +08001018 break
1019
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001020 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001021
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001022 if (self._mode == self.AGENT and
1023 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001024 self.Ping()
1025 self.ScanForTimeoutRequests()
1026
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001027 if not self._download_queue.empty():
1028 self.InitiateDownload()
1029
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001030 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001031 break
1032 except socket.error:
1033 raise RuntimeError('Connection dropped')
1034 except PingTimeoutError:
1035 raise RuntimeError('Connection timeout')
1036 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001037 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001038
1039 self._queue.put('resume')
1040
1041 if self._mode != Ghost.AGENT:
1042 sys.exit(1)
1043
1044 def Register(self):
1045 non_local = {}
1046 for addr in self._overlord_addrs:
1047 non_local['addr'] = addr
1048 def registered(response):
1049 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001050 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001051 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001052
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001053 self._register_status = response['response']
1054 if response['response'] != SUCCESS:
1055 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001056 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001057
1058 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1059 self._connected_addr = non_local['addr']
1060 self.Upgrade() # Check for upgrade
1061 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001062
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001063 try:
1064 logging.info('Trying %s:%d ...', *addr)
1065 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001066
Peter Shih220a96d2016-12-22 17:02:16 +08001067 # Check if server has TLS enabled. Only check if self._tls_mode is
1068 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001069 # Only control channel needs to determine if TLS is enabled. Other mode
1070 # should use the TLSSettings passed in when it was spawned.
1071 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001072 self._tls_settings.SetEnabled(
1073 self.TLSEnabled(*addr) if self._tls_mode is None
1074 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001075
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001076 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1077 sock.settimeout(_CONNECT_TIMEOUT)
1078
1079 try:
1080 if self._tls_settings.Enabled():
1081 tls_context = self._tls_settings.Context()
1082 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1083
1084 sock.connect(addr)
1085 except (ssl.SSLError, ssl.CertificateError) as e:
1086 logging.error('%s: %s', e.__class__.__name__, e)
1087 continue
1088 except IOError as e:
1089 if e.errno == 2: # No such file or directory
1090 logging.error('%s: %s', e.__class__.__name__, e)
1091 continue
1092 raise
1093
1094 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001095
1096 logging.info('Connection established, registering...')
1097 handler = {
1098 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001099 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001100 Ghost.SHELL: self.SpawnShellServer,
1101 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001102 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001103 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001104
1105 # Machine ID may change if MAC address is used (USB-ethernet dongle
1106 # plugged/unplugged)
1107 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001108 self.SendRequest('register',
1109 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001110 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001111 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001112 except socket.error:
1113 pass
1114 else:
Yilin Yangcb5e8922020-12-16 10:30:44 +08001115 # We only send dut data when it's agent mode.
1116 if self._mode == Ghost.AGENT:
1117 self.SendData()
Yilin Yang89a136c2021-01-05 15:25:05 +08001118 if self._track_connection is not None:
1119 self.TrackConnection(self._track_connection,
1120 self._track_connection_timeout_secs)
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001121 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001122 self.Listen()
1123
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001124 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001125
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001126 def Reconnect(self):
1127 logging.info('Received reconnect request from RPC server, reconnecting...')
1128 self._reset.set()
1129
Yilin Yang64dd8592020-11-10 16:16:23 +08001130 def CollectPytestAndStatus(self):
1131 STATUS = Enum(['failed', 'running', 'idle'])
1132 goofy = state.GetInstance()
1133 tests = goofy.GetTests()
1134
1135 # Ignore parents
1136 tests = [x for x in tests if not x.get('parent')]
1137
1138 scheduled_tests = (
1139 goofy.GetTestRunStatus(None).get('scheduled_tests') or [])
1140 scheduled_tests = {t['path']
1141 for t in scheduled_tests}
1142 tests = [x for x in tests if x['path'] in scheduled_tests]
1143 data = {
1144 'pytest': '',
1145 'status': STATUS.idle
1146 }
1147
1148 def parse_pytest_name(test):
1149 # test['path'] format: 'test_list_name:pytest_name'
1150 return test['path'][test['path'].index(':') + 1:]
1151
1152 for test in filter(lambda t: t['status'] == TestState.ACTIVE, tests):
1153 data['pytest'] = parse_pytest_name(test)
1154 data['status'] = STATUS.running
1155 return data
1156
1157 for test in filter(lambda t: t['status'] == TestState.FAILED, tests):
1158 data['pytest'] = parse_pytest_name(test)
1159 data['status'] = STATUS.failed
1160 return data
1161
1162 if tests:
1163 data['pytest'] = parse_pytest_name(tests[0])
1164
1165 return data
1166
1167 def CollectModelName(self):
1168 return {
1169 'model': cros_config_module.CrosConfig().GetModelName()
1170 }
1171
1172 def CollectIP(self):
1173 ip_addrs = []
1174 for interface in net_utils.GetNetworkInterfaces():
1175 ip = net_utils.GetEthernetIp(interface)[0]
1176 if ip:
1177 ip_addrs.append(ip)
1178
1179 return {
1180 'ip': ip_addrs
1181 }
1182
1183 def CollectData(self):
1184 """Collect dut data.
1185
1186 Data includes:
1187 1. status: Current test status
1188 2. pytest: Current pytest
1189 3. model: Model name
1190 4. ip: IP
1191 """
1192 data = {}
1193 data.update(self.CollectPytestAndStatus())
1194 data.update(self.CollectModelName())
1195 data.update(self.CollectIP())
1196
1197 return data
1198
1199 def SendData(self):
1200 if not sys_utils.InCrOSDevice():
1201 return
1202
1203 data = self.CollectData()
1204 logging.info('data = %s', data)
1205
1206 self.SendRequest('update_dut_data', data)
1207
Yilin Yang90c60c42020-11-11 14:45:08 +08001208 def TrackConnection(self, enabled, timeout_secs):
1209 logging.info('TrackConnection, enabled = %s, timeout_secs = %d', enabled,
1210 timeout_secs)
1211
Yilin Yang89a136c2021-01-05 15:25:05 +08001212 self._track_connection = enabled
1213 self._track_connection_timeout_secs = timeout_secs
Yilin Yang90c60c42020-11-11 14:45:08 +08001214 self.SendRequest('track_connection', {
1215 'enabled': enabled,
1216 'timeout_secs': timeout_secs
1217 })
1218
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001219 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001220 status = self._register_status
1221 if self._register_status == SUCCESS:
1222 ip, port = self._sock.sock.getpeername()
1223 status += ' %s:%d' % (ip, port)
1224 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001225
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001226 def AddToDownloadQueue(self, ttyname, filename):
1227 self._download_queue.put((ttyname, filename))
1228
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001229 def RegisterTTY(self, session_id, ttyname):
1230 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001231
1232 def RegisterSession(self, session_id, process_id):
1233 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001234
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001235 def StartLanDiscovery(self):
1236 """Start to listen to LAN discovery packet at
1237 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001238
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001239 def thread_func():
1240 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1241 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1242 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001243 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001244 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1245 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001246 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001247 return
1248
1249 logging.info('LAN Discovery: started')
1250 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001251 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001252
1253 if s in rd:
1254 data, source_addr = s.recvfrom(_BUFSIZE)
1255 parts = data.split()
1256 if parts[0] == 'OVERLORD':
1257 ip, port = parts[1].split(':')
1258 if not ip:
1259 ip = source_addr[0]
1260 self._queue.put((ip, int(port)), True)
1261
1262 try:
1263 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001264 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001265 pass
1266 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001267 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001268 self._queue.put(obj)
1269 elif obj == 'pause':
1270 logging.info('LAN Discovery: paused')
1271 while obj != 'resume':
1272 obj = self._queue.get(True)
1273 logging.info('LAN Discovery: resumed')
1274
1275 t = threading.Thread(target=thread_func)
1276 t.daemon = True
1277 t.start()
1278
1279 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001280 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001281 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1282 logRequests=False)
Yilin Yang64dd8592020-11-10 16:16:23 +08001283 rpc_server.register_function(self.SendData, 'SendData')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001284 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001285 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001286 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001287 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Yilin Yang90c60c42020-11-11 14:45:08 +08001288 rpc_server.register_function(self.TrackConnection, 'TrackConnection')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001289 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001290 t = threading.Thread(target=rpc_server.serve_forever)
1291 t.daemon = True
1292 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001293
Yilin Yang1512d972020-11-19 13:34:42 +08001294 def ApplyTestListParams(self):
1295 mgr = manager.Manager()
Cheng Yueh59a29662020-12-02 12:20:18 +08001296 device = sys_interface.SystemInterface()
1297 constants = mgr.GetTestListByID(mgr.GetActiveTestListId(device)).constants
Yilin Yang1512d972020-11-19 13:34:42 +08001298
1299 if 'overlord' not in constants:
1300 return
1301
1302 if 'overlord_urls' in constants['overlord']:
1303 for addr in [(x, _OVERLORD_PORT) for x in
1304 constants['overlord']['overlord_urls']]:
1305 if addr not in self._overlord_addrs:
1306 self._overlord_addrs.append(addr)
1307
1308 # This is sugar for ODM to turn off the verification quickly if they forgot.
1309 # So we don't support to turn on again.
1310 # If we want to turn on, we need to restart the ghost daemon.
1311 if 'tls_no_verify' in constants['overlord']:
1312 if constants['overlord']['tls_no_verify']:
1313 self._tls_settings = TLSSettings(None, False)
1314
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001315 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001316 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001317 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1318 if addr not in self._overlord_addrs:
1319 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001320
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001321 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001322 logging.info('%s started', self.MODE_NAME[self._mode])
1323 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001324 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001325
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001326 # We don't care about child process's return code, not wait is needed. This
1327 # is used to prevent zombie process from lingering in the system.
1328 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001329
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001330 if lan_disc:
1331 self.StartLanDiscovery()
1332
1333 if rpc_server:
1334 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001335
1336 try:
1337 while True:
1338 try:
1339 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001340 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001341 pass
1342 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001343 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001344 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1345 self._overlord_addrs.append(addr)
1346
Yilin Yang1512d972020-11-19 13:34:42 +08001347 if self._mode == Ghost.AGENT:
1348 self.ApplyTestListParams()
1349
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001350 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001351 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001352 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001353 # Don't show stack trace for RuntimeError, which we use in this file for
1354 # plausible and expected errors (such as can't connect to server).
1355 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001356 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001357 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001358 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001359 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001360 traceback.print_tb(exc_traceback)
1361 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001362 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001363 time.sleep(_RETRY_INTERVAL)
1364
1365 self.Reset()
1366 except KeyboardInterrupt:
1367 logging.error('Received keyboard interrupt, quit')
1368 sys.exit(0)
1369
1370
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001371def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001372 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001373 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1374
1375
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001376def ForkToBackground():
1377 """Fork process to run in background."""
1378 pid = os.fork()
1379 if pid != 0:
1380 logging.info('Ghost(%d) running in background.', pid)
1381 sys.exit(0)
1382
1383
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001384def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001385 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001386 filepath = os.path.abspath(filename)
1387 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001388 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001389 sys.exit(1)
1390
1391 # Check if we actually have permission to read the file
1392 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001393 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001394 sys.exit(1)
1395
1396 server = GhostRPCServer()
1397 server.AddToDownloadQueue(os.ttyname(0), filepath)
1398 sys.exit(0)
1399
1400
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001401def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001402 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001403 logger = logging.getLogger()
1404 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001405 handler = logging.StreamHandler()
1406 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1407 handler.setFormatter(formatter)
1408 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001409
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001410 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001411 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1412 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001413 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1414 default=None, help='use MID as machine ID')
1415 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1416 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001417 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1418 default=True, help='disable LAN discovery')
1419 parser.add_argument('--no-rpc-server', dest='rpc_server',
1420 action='store_false', default=True,
1421 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001422 parser.add_argument('--tls', dest='tls_mode', default='detect',
1423 choices=('y', 'n', 'detect'),
1424 help="specify 'y' or 'n' to force enable/disable TLS")
Yilin Yang64dd8592020-11-10 16:16:23 +08001425 parser.add_argument(
1426 '--tls-cert-file', metavar='TLS_CERT_FILE', dest='tls_cert_file',
1427 type=str, default=None,
1428 help='file containing the server TLS certificate in PEM '
1429 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001430 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1431 action='store_true', default=False,
1432 help='do not verify certificate if TLS is enabled')
Yilin Yang64dd8592020-11-10 16:16:23 +08001433 parser.add_argument(
1434 '--prop-file', metavar='PROP_FILE', dest='prop_file', type=str,
1435 default=None, help='file containing the JSON representation of client '
1436 'properties')
Yilin Yang77668412021-02-02 10:53:36 +08001437 parser.add_argument('--ovl-path', metavar='OVL_PATH', dest='ovl_path',
1438 type=str, default=None, help='path to ovl tool')
1439 parser.add_argument('--certificate-dir', metavar='CERTIFICATE_DIR',
1440 dest='certificate_dir', type=str, default=None,
1441 help='path to overlord certificate directory')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001442 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1443 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001444 parser.add_argument('--reset', dest='reset', default=False,
1445 action='store_true',
1446 help='reset ghost and reload all configs')
Yilin Yang64dd8592020-11-10 16:16:23 +08001447 parser.add_argument('--send-data', dest='send_data', default=False,
1448 action='store_true',
1449 help='send client data to overlord server')
Peter Shih5cafebb2017-06-30 16:36:22 +08001450 parser.add_argument('--status', dest='status', default=False,
1451 action='store_true',
1452 help='show status of the client')
Yilin Yang90c60c42020-11-11 14:45:08 +08001453 parser.add_argument('--track-connection', dest='track_connection',
1454 default=None, choices=('y', 'n'),
1455 help="specify 'y' or 'n' to track connection or not")
1456 parser.add_argument('--timeout-seconds', dest='timeout_secs', type=int,
1457 default=900,
1458 help='timeout seconds when track the connection')
Yilin Yang64dd8592020-11-10 16:16:23 +08001459 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str, nargs='*',
1460 help='overlord server address')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001461 args = parser.parse_args()
1462
Peter Shih5cafebb2017-06-30 16:36:22 +08001463 if args.status:
1464 print(GhostRPCServer().GetStatus())
1465 sys.exit()
1466
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001467 if args.fork:
1468 ForkToBackground()
1469
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001470 if args.reset:
1471 GhostRPCServer().Reconnect()
1472 sys.exit()
1473
Yilin Yang64dd8592020-11-10 16:16:23 +08001474 if args.send_data:
1475 GhostRPCServer().SendData()
1476 sys.exit()
1477
Yilin Yang90c60c42020-11-11 14:45:08 +08001478 if args.track_connection:
1479 GhostRPCServer().TrackConnection(args.track_connection == 'y',
1480 args.timeout_secs)
1481 sys.exit()
1482
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001483 if args.download:
1484 DownloadFile(args.download)
1485
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001486 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001487 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001488
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001489 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1490
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001491 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001492 tls_mode = args.tls_mode
1493 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Yilin Yang77668412021-02-02 10:53:36 +08001494 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid, prop_file=prop_file,
1495 tls_mode=tls_mode, ovl_path=args.ovl_path,
1496 certificate_dir=args.certificate_dir)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001497 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001498
1499
1500if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001501 try:
1502 main()
1503 except Exception as e:
1504 logging.error(e)