blob: ac50a10f40cd64fc3813820c779216febef337b4 [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
Peter Shih5cafebb2017-06-30 16:36:22 +08006from __future__ import print_function
7
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08008import argparse
Yilin Yangf9fe1932019-11-04 17:09:34 +08009import binascii
10import codecs
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080011import contextlib
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080012import ctypes
13import ctypes.util
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080014import fcntl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080015import hashlib
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080016import json
17import logging
18import os
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +080019import platform
Yilin Yang8b7f5192020-01-08 11:43:00 +080020import queue
Wei-Ning Huang829e0c82015-05-26 14:37:23 +080021import re
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080022import select
Wei-Ning Huanga301f572015-06-03 17:34:21 +080023import signal
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080024import socket
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080025import ssl
Wei-Ning Huangb05cde32015-08-01 09:48:41 +080026import struct
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080027import subprocess
28import sys
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080029import termios
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080030import threading
31import time
Joel Kitching22b89042015-08-06 18:23:29 +080032import traceback
Wei-Ning Huang39169902015-09-19 06:00:23 +080033import tty
Yilin Yangf54fb912020-01-08 11:42:38 +080034import urllib.request
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080035import uuid
36
Wei-Ning Huang2132de32015-04-13 17:24:38 +080037import jsonrpclib
38from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
Wei-Ning Huang2132de32015-04-13 17:24:38 +080039
Yilin Yang42ba5c62020-05-05 10:32:34 +080040from cros.factory.utils import process_utils
41
Yilin Yangf54fb912020-01-08 11:42:38 +080042
Fei Shaobb0a3e62020-06-20 15:41:25 +080043_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', '4499'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080044
Fei Shaobb0a3e62020-06-20 15:41:25 +080045_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', '4455'))
46_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', '4456'))
47_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', '9000'))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080048
49_BUFSIZE = 8192
50_RETRY_INTERVAL = 2
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080051_SEPARATOR = b'\r\n'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080052_PING_TIMEOUT = 3
53_PING_INTERVAL = 5
54_REQUEST_TIMEOUT_SECS = 60
55_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080056_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080057
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080058_CONTROL_START = 128
59_CONTROL_END = 129
60
Wei-Ning Huanga301f572015-06-03 17:34:21 +080061_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080062_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080063
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080064# Stream control
65_STDIN_CLOSED = '##STDIN_CLOSED##'
66
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080067SUCCESS = 'success'
68FAILED = 'failed'
69DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080070
Joel Kitching22b89042015-08-06 18:23:29 +080071
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080072class PingTimeoutError(Exception):
73 pass
74
75
76class RequestError(Exception):
77 pass
78
79
Fei Shaobd07c9a2020-06-15 19:04:50 +080080class BufferedSocket:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080081 """A buffered socket that supports unrecv.
82
83 Allow putting back data back to the socket for the next recv() call.
84 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080085 def __init__(self, sock):
86 self.sock = sock
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080087 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080088
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080089 def fileno(self):
90 return self.sock.fileno()
91
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080092 def Recv(self, bufsize, flags=0):
93 if self._buf:
94 if len(self._buf) >= bufsize:
95 ret = self._buf[:bufsize]
96 self._buf = self._buf[bufsize:]
97 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +080098 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +080099 self._buf = b''
Yilin Yang15a3f8f2020-01-03 17:49:00 +0800100 return ret + self.sock.recv(bufsize - len(ret), flags)
101 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800102
103 def UnRecv(self, buf):
104 self._buf = buf + self._buf
105
106 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800107 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800108
109 def RecvBuf(self):
110 """Only recive from buffer."""
111 ret = self._buf
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800112 self._buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800113 return ret
114
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800115 def Close(self):
116 self.sock.close()
117
118
Fei Shaobd07c9a2020-06-15 19:04:50 +0800119class TLSSettings:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800120 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800121 """Constructor.
122
123 Args:
124 tls_cert_file: TLS certificate in PEM format.
125 enable_tls_without_verify: enable TLS but don't verify certificate.
126 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800127 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800128 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800129 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800130 self._tls_context = None
131
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800132 def _UpdateContext(self):
133 if not self._enabled:
134 self._tls_context = None
135 return
136
137 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
138 self._tls_context.verify_mode = ssl.CERT_REQUIRED
139
140 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800141 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800142 self._tls_context.check_hostname = True
143 try:
144 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800145 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800146 except IOError as e:
147 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
148 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800149 else:
150 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
151 logging.info('TLSSettings: using built-in ca-certificates')
152 else:
153 self._tls_context.verify_mode = ssl.CERT_NONE
154 logging.info('TLSSettings: skipping TLS verification!!!')
155
156 def SetEnabled(self, enabled):
157 logging.info('TLSSettings: enabled: %s', enabled)
158
159 if self._enabled != enabled:
160 self._enabled = enabled
161 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800162
163 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800164 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800165
166 def Context(self):
167 return self._tls_context
168
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800169
Fei Shaobd07c9a2020-06-15 19:04:50 +0800170class Ghost:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800171 """Ghost implements the client protocol of Overlord.
172
173 Ghost provide terminal/shell/logcat functionality and manages the client
174 side connectivity.
175 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800176 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800177
178 MODE_NAME = {
179 NONE: 'NONE',
180 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800181 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800182 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800183 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800184 FILE: 'File',
185 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800186 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800187
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800188 RANDOM_MID = '##random_mid##'
189
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800190 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
191 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Peter Shih220a96d2016-12-22 17:02:16 +0800192 command=None, file_op=None, port=None, tls_mode=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800193 """Constructor.
194
195 Args:
196 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800197 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800198 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800199 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
200 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800201 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800202 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800203 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800204 terminal_sid: the terminal session ID associate with this client. This is
205 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800206 tty_device: the terminal device to open, if tty_device is None, as pseudo
207 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800208 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800209 file_op: a tuple (action, filepath, perm). action is either 'download' or
210 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800211 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800212 tls_mode: can be [True, False, None]. if not None, skip detection of
213 TLS and assume whether server use TLS or not.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800214 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800215 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
216 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800217 if mode == Ghost.SHELL:
218 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800219 if mode == Ghost.FILE:
220 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800221
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800222 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800223 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800224 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800225 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800226 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800227 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800228 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800229 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800230 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800231 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800232 self._ttyname_to_sid = {}
233 self._terminal_sid_to_pid = {}
234 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800235 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800236 self._register_status = DISCONNECTED
237 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800238 self._tls_mode = tls_mode
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800239
240 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800241 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800242 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800243
244 # Protocol specific
245 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800246 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800247 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800248 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800249 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800250 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800251
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800252 def SetIgnoreChild(self, status):
253 # Only ignore child for Agent since only it could spawn child Ghost.
254 if self._mode == Ghost.AGENT:
255 signal.signal(signal.SIGCHLD,
256 signal.SIG_IGN if status else signal.SIG_DFL)
257
258 def GetFileSha1(self, filename):
Yilin Yang0412c272019-12-05 16:57:40 +0800259 with open(filename, 'rb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800260 return hashlib.sha1(f.read()).hexdigest()
261
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800262 def TLSEnabled(self, host, port):
263 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800264 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
265 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800266 # Allow any certificate since we only want to check if server talks TLS.
267 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
268 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800269
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800270 sock = context.wrap_socket(sock, server_hostname=host)
271 sock.settimeout(_CONNECT_TIMEOUT)
272 sock.connect((host, port))
273 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800274 except ssl.SSLError:
275 return False
Stimim Chen3899a912020-07-17 10:52:03 +0800276 except socket.timeout:
277 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800278 except socket.error: # Connect refused or timeout
279 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800280 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800281 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800282
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800283 def Upgrade(self):
284 logging.info('Upgrade: initiating upgrade sequence...')
285
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800286 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800287 https_enabled = self.TLSEnabled(self._connected_addr[0],
288 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800289 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800290 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
291 'abort')
292 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800293
294 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800295 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
296 'without TLS enabled! Possible mis-configuration or '
297 'DNS/IP spoofing detected, abort')
298 return
299
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800300 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800301 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800302 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800303 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800304
305 # Download sha1sum for ghost.py for verification
306 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800307 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800308 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
309 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800310 if f.getcode() != 200:
311 raise RuntimeError('HTTP status %d' % f.getcode())
312 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800313 except (ssl.SSLError, ssl.CertificateError) as e:
314 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
315 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800316 except Exception:
317 logging.error('Upgrade: failed to download sha1sum file, abort')
318 return
319
320 if self.GetFileSha1(scriptpath) == sha1sum:
321 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
322 return
323
324 # Download upgrade version of ghost.py
325 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800326 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800327 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
328 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800329 if f.getcode() != 200:
330 raise RuntimeError('HTTP status %d' % f.getcode())
331 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800332 except (ssl.SSLError, ssl.CertificateError) as e:
333 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
334 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800335 except Exception:
336 logging.error('Upgrade: failed to download upgrade, abort')
337 return
338
339 # Compare SHA1 sum
340 if hashlib.sha1(data).hexdigest() != sha1sum:
341 logging.error('Upgrade: sha1sum mismatch, abort')
342 return
343
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800344 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800345 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800346 f.write(data)
347 except Exception:
348 logging.error('Upgrade: failed to write upgrade onto disk, abort')
349 return
350
351 logging.info('Upgrade: restarting ghost...')
352 self.CloseSockets()
353 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800354 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800355
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800356 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800357 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800358 if self._prop_file:
359 with open(self._prop_file, 'r') as f:
360 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800361 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800362 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800363
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800364 def CloseSockets(self):
365 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800366 if self._platform == 'Linux':
367 for fd in os.listdir('/proc/self/fd/'):
368 try:
369 real_fd = os.readlink('/proc/self/fd/%s' % fd)
370 if real_fd.startswith('socket'):
371 os.close(int(fd))
372 except Exception:
373 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800374
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800375 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800376 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800377 """Spawn a child ghost with specific mode.
378
379 Returns:
380 The spawned child process pid.
381 """
Joel Kitching22b89042015-08-06 18:23:29 +0800382 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800383 self.SetIgnoreChild(False)
384
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800385 pid = os.fork()
386 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800387 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800388 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
389 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800390 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800391 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800392 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800393 sys.exit(0)
394 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800395 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800396 return pid
397
398 def Timestamp(self):
399 return int(time.time())
400
401 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800402 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800403 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800404 ret = re.search('gateway: (.*)', output)
405 if ret:
406 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800407 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800408 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800409 with open('/proc/net/route', 'r') as f:
410 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800411
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800412 ips = []
413 for line in lines:
414 parts = line.split('\t')
415 if parts[2] == '00000000':
416 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800417
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800418 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800419 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800420 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800421 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800422 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800423
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800424 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800425
426 logging.warning('GetGateWayIP: unsupported platform')
427 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800428
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800429 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800430 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800431 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800432
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800433 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800434 match = re.match(r'^https?://(.*):.*$', url)
435 if match:
436 return [match.group(1)]
437 except Exception:
438 pass
439 return []
440
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800441 def GetMachineID(self):
442 """Generates machine-dependent ID string for a machine.
443 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800444 Linux:
445 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800446 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
447 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800448 We follow the listed order to generate machine ID, and fallback to the
449 next alternative if the previous doesn't work.
450
451 Darwin:
452 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800453 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800454 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800455 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800456 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800457 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800458
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800459 # Darwin
460 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800461 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
462 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800463 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
464 if ret:
465 return ret.group(1)
466
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800467 # Try factory device id
468 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800469 from cros.factory.test import session
470 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800471 except Exception:
472 pass
473
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800474 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800475 try:
476 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
477 return f.read().strip()
478 except Exception:
479 pass
480
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800481 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800482 try:
483 macs = []
484 ifaces = sorted(os.listdir('/sys/class/net'))
485 for iface in ifaces:
486 if iface == 'lo':
487 continue
488
489 with open('/sys/class/net/%s/address' % iface, 'r') as f:
490 macs.append(f.read().strip())
491
492 return ';'.join(macs)
493 except Exception:
494 pass
495
Peter Shihcb0e5512017-06-14 16:59:46 +0800496 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800497
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800498 def GetProcessWorkingDirectory(self, pid):
499 if self._platform == 'Linux':
500 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800501 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800502 PROC_PIDVNODEPATHINFO = 9
503 proc_vnodepathinfo_size = 2352
504 vid_path_offset = 152
505
506 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
507 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
508 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
509 ctypes.byref(buf), proc_vnodepathinfo_size)
510 buf = buf.raw[vid_path_offset:]
511 n = buf.index('\0')
512 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800513 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800514
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800515 def Reset(self):
516 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800517 if self._sock is not None:
518 self._sock.Close()
519 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800520 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800521 self._last_ping = 0
522 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800523 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800524 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800525
526 def SendMessage(self, msg):
527 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800528 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800529
530 def SendRequest(self, name, args, handler=None,
531 timeout=_REQUEST_TIMEOUT_SECS):
532 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800533 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800534
535 rid = str(uuid.uuid4())
536 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800537 if timeout >= 0:
538 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800539 self.SendMessage(msg)
540
541 def SendResponse(self, omsg, status, params=None):
542 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
543 self.SendMessage(msg)
544
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800545 def HandleTTYControl(self, fd, control_str):
546 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800547 command = msg['command']
548 params = msg['params']
549 if command == 'resize':
550 # some error happened on websocket
551 if len(params) != 2:
552 return
553 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
554 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
555 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800556 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800557
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800558 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800559 """Spawn a TTY server and forward I/O to the TCP socket."""
560 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800561
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800562 try:
563 if self._tty_device is None:
564 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800565
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800566 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800567 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800568 try:
569 server = GhostRPCServer()
570 server.RegisterTTY(self._session_id, ttyname)
571 server.RegisterSession(self._session_id, os.getpid())
572 except Exception:
573 # If ghost is launched without RPC server, the call will fail but we
574 # can ignore it.
575 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800576
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800577 # The directory that contains the current running ghost script
578 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800579
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800580 env = os.environ.copy()
581 env['USER'] = os.getenv('USER', 'root')
582 env['HOME'] = os.getenv('HOME', '/root')
583 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
584 os.chdir(env['HOME'])
585 os.execve(_SHELL, [_SHELL], env)
586 else:
587 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800588 tty.setraw(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800589 # 0: iflag
590 # 1: oflag
591 # 2: cflag
592 # 3: lflag
593 # 4: ispeed
594 # 5: ospeed
595 # 6: cc
Wei-Ning Huang39169902015-09-19 06:00:23 +0800596 attr = termios.tcgetattr(fd)
Stimim Chen3899a912020-07-17 10:52:03 +0800597 attr[0] &= (termios.IXON | termios.IXOFF)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800598 attr[2] |= termios.CLOCAL
599 attr[2] &= ~termios.CRTSCTS
600 attr[4] = termios.B115200
601 attr[5] = termios.B115200
602 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800603
Stimim Chen3899a912020-07-17 10:52:03 +0800604 nonlocals = {
605 'control_state': None,
606 'control_str': b''
607 }
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800608
609 def _ProcessBuffer(buf):
Stimim Chen3899a912020-07-17 10:52:03 +0800610 write_buffer = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800611 while buf:
612 if nonlocals['control_state']:
Stimim Chen3899a912020-07-17 10:52:03 +0800613 if _CONTROL_END in buf:
614 index = buf.index(_CONTROL_END)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800615 nonlocals['control_str'] += buf[:index]
616 self.HandleTTYControl(fd, nonlocals['control_str'])
617 nonlocals['control_state'] = None
Stimim Chen3899a912020-07-17 10:52:03 +0800618 nonlocals['control_str'] = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800619 buf = buf[index+1:]
620 else:
621 nonlocals['control_str'] += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800622 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800623 else:
Stimim Chen3899a912020-07-17 10:52:03 +0800624 if _CONTROL_START in buf:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800625 nonlocals['control_state'] = _CONTROL_START
Stimim Chen3899a912020-07-17 10:52:03 +0800626 index = buf.index(_CONTROL_START)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800627 write_buffer += buf[:index]
628 buf = buf[index+1:]
629 else:
630 write_buffer += buf
Stimim Chen3899a912020-07-17 10:52:03 +0800631 buf = b''
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800632
633 if write_buffer:
634 os.write(fd, write_buffer)
635
636 _ProcessBuffer(self._sock.RecvBuf())
637
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800638 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800639 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800640
641 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800642 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800643
644 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800645 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800646 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800647 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800648 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800649 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800650 logging.error('SpawnTTYServer: %s', e, exc_info=True)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800651 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800652 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800653
654 logging.info('SpawnTTYServer: terminated')
655 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800656
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800657 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800658 """Spawn a shell server and forward input/output from/to the TCP socket."""
659 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800660
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800661 # Add ghost executable to PATH
662 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
663 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800664 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800665
666 # Execute shell command from HOME directory
667 os.chdir(os.getenv('HOME', '/tmp'))
668
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800669 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800670 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800671 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800672
673 def make_non_block(fd):
674 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
675 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
676
677 make_non_block(p.stdout)
678 make_non_block(p.stderr)
679
680 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800681 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800682
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800683 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800684 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800685 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800686 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800687 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800688
689 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800690 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800691
692 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800693 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800694 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800695 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800696
697 try:
698 idx = ret.index(_STDIN_CLOSED * 2)
699 p.stdin.write(ret[:idx])
700 p.stdin.close()
701 except ValueError:
702 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800703 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800704 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800705 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800706 except Exception as e:
Stimim Chen3899a912020-07-17 10:52:03 +0800707 logging.error('SpawnShellServer: %s', e, exc_info=True)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800708 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800709 # Check if the process is terminated. If not, Send SIGTERM to process,
710 # then wait for 1 second. Send another SIGKILL to make sure the process is
711 # terminated.
712 p.poll()
713 if p.returncode is None:
714 try:
715 p.terminate()
716 time.sleep(1)
717 p.kill()
718 except Exception:
719 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800720
721 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800722 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800723
724 logging.info('SpawnShellServer: terminated')
725 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800726
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800727 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800728 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800729 try:
730 size = os.stat(self._file_op[1]).st_size
731 except OSError as e:
732 logging.error('InitiateFileOperation: download: %s', e)
733 sys.exit(1)
734
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800735 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800736 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800737 'filename': os.path.basename(self._file_op[1]),
738 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800739 elif self._file_op[0] == 'upload':
740 self.SendRequest('clear_to_upload', {}, timeout=-1)
741 self.StartUploadServer()
742 else:
743 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800744
745 def StartDownloadServer(self):
746 logging.info('StartDownloadServer: started')
747
748 try:
749 with open(self._file_op[1], 'rb') as f:
750 while True:
751 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800752 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800753 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800754 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800755 except Exception as e:
756 logging.error('StartDownloadServer: %s', e)
757 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800758 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800759
760 logging.info('StartDownloadServer: terminated')
761 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800762
Wei-Ning Huange2981862015-08-03 15:03:08 +0800763 def StartUploadServer(self):
764 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800765 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800766 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800767 dirname = os.path.dirname(filepath)
768 if not os.path.exists(dirname):
769 try:
770 os.makedirs(dirname)
771 except Exception:
772 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800773
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800774 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800775 if self._file_op[2]:
776 os.fchmod(f.fileno(), self._file_op[2])
777
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800778 f.write(self._sock.RecvBuf())
779
Wei-Ning Huange2981862015-08-03 15:03:08 +0800780 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800781 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800782 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800783 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800784 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800785 break
786 f.write(buf)
787 except socket.error as e:
788 logging.error('StartUploadServer: socket error: %s', e)
789 except Exception as e:
790 logging.error('StartUploadServer: %s', e)
791 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800792 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800793
794 logging.info('StartUploadServer: terminated')
795 sys.exit(0)
796
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800797 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800798 """Spawn a port forwarding server and forward I/O to the TCP socket."""
799 logging.info('SpawnPortForwardServer: started')
800
801 src_sock = None
802 try:
803 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800804 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800805 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800806
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800807 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800808
809 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800810 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800811
812 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800813 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800814 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800815 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800816 src_sock.send(data)
817
818 if src_sock in rd:
819 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800820 if not data:
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800821 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800822 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800823 except Exception as e:
824 logging.error('SpawnPortForwardServer: %s', e)
825 finally:
826 if src_sock:
827 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800828 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800829
830 logging.info('SpawnPortForwardServer: terminated')
831 sys.exit(0)
832
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800833 def Ping(self):
834 def timeout_handler(x):
835 if x is None:
836 raise PingTimeoutError
837
838 self._last_ping = self.Timestamp()
839 self.SendRequest('ping', {}, timeout_handler, 5)
840
Wei-Ning Huangae923642015-09-24 14:08:09 +0800841 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800842 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800843 filepath = params['filename']
844 if not os.path.isabs(filepath):
845 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
846
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800847 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800848 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800849 pass
850 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800851 self.SendResponse(msg, str(e))
852 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800853
854 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800855 file_op=('download', filepath))
856 self.SendResponse(msg, SUCCESS)
857
858 def HandleFileUploadRequest(self, msg):
859 params = msg['params']
860
861 # Resolve upload filepath
862 filename = params['filename']
863 dest_path = filename
864
865 # If dest is specified, use it first
866 dest_path = params.get('dest', '')
867 if dest_path:
868 if not os.path.isabs(dest_path):
869 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
870
871 if os.path.isdir(dest_path):
872 dest_path = os.path.join(dest_path, filename)
873 else:
874 target_dir = os.getenv('HOME', '/tmp')
875
876 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800877 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800878 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
879 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800880 try:
881 target_dir = self.GetProcessWorkingDirectory(pid)
882 except Exception as e:
883 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800884
885 dest_path = os.path.join(target_dir, filename)
886
887 try:
888 os.makedirs(os.path.dirname(dest_path))
889 except Exception:
890 pass
891
892 try:
893 with open(dest_path, 'w') as _:
894 pass
895 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800896 self.SendResponse(msg, str(e))
897 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800898
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800899 # If not check_only, spawn FILE mode ghost agent to handle upload
900 if not params.get('check_only', False):
901 self.SpawnGhost(self.FILE, params['sid'],
902 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800903 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800904
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800905 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800906 command = msg['name']
907 params = msg['params']
908
909 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800910 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800911 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800912 self.SpawnGhost(self.TERMINAL, params['sid'],
913 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800914 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800915 elif command == 'shell':
916 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800917 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800918 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800919 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800920 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800921 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800922 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800923 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800924 elif command == 'forward':
925 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
926 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800927
928 def HandleResponse(self, response):
929 rid = str(response['rid'])
930 if rid in self._requests:
931 handler = self._requests[rid][2]
932 del self._requests[rid]
933 if callable(handler):
934 handler(response)
935 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800936 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800937
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800938 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800939 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800940 try:
941 index = buf.index(_SEPARATOR)
942 except ValueError:
943 self._sock.UnRecv(buf)
944 return
945
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800946 msgs_json = [buf[:index]]
947 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800948 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800949 msgs_json = buf.split(_SEPARATOR)
950 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800951
952 for msg_json in msgs_json:
953 try:
954 msg = json.loads(msg_json)
955 except ValueError:
956 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800957 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800958 continue
959
960 if 'name' in msg:
961 self.HandleRequest(msg)
962 elif 'response' in msg:
963 self.HandleResponse(msg)
964 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800965 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800966
967 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800968 """Scans for pending requests which have timed out.
969
970 If any timed-out requests are discovered, their handler is called with the
971 special response value of None.
972 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800973 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800974 request_time, timeout, handler = self._requests[rid]
975 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800976 if callable(handler):
977 handler(None)
978 else:
979 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800980 del self._requests[rid]
981
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800982 def InitiateDownload(self):
983 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800984 sid = self._ttyname_to_sid[ttyname]
985 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800986 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800987
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800988 def Listen(self):
989 try:
990 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800991 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800992 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800993
994 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800995 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800996
997 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +0800998 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800999 break
1000
Wei-Ning Huanga28cd232016-01-27 15:04:41 +08001001 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001002
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001003 if (self._mode == self.AGENT and
1004 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001005 self.Ping()
1006 self.ScanForTimeoutRequests()
1007
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001008 if not self._download_queue.empty():
1009 self.InitiateDownload()
1010
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001011 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001012 break
1013 except socket.error:
1014 raise RuntimeError('Connection dropped')
1015 except PingTimeoutError:
1016 raise RuntimeError('Connection timeout')
1017 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001018 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001019
1020 self._queue.put('resume')
1021
1022 if self._mode != Ghost.AGENT:
1023 sys.exit(1)
1024
1025 def Register(self):
1026 non_local = {}
1027 for addr in self._overlord_addrs:
1028 non_local['addr'] = addr
1029 def registered(response):
1030 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001031 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001032 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001033
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001034 self._register_status = response['response']
1035 if response['response'] != SUCCESS:
1036 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001037 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001038
1039 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1040 self._connected_addr = non_local['addr']
1041 self.Upgrade() # Check for upgrade
1042 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001043
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001044 try:
1045 logging.info('Trying %s:%d ...', *addr)
1046 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001047
Peter Shih220a96d2016-12-22 17:02:16 +08001048 # Check if server has TLS enabled. Only check if self._tls_mode is
1049 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001050 # Only control channel needs to determine if TLS is enabled. Other mode
1051 # should use the TLSSettings passed in when it was spawned.
1052 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001053 self._tls_settings.SetEnabled(
1054 self.TLSEnabled(*addr) if self._tls_mode is None
1055 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001056
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001057 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1058 sock.settimeout(_CONNECT_TIMEOUT)
1059
1060 try:
1061 if self._tls_settings.Enabled():
1062 tls_context = self._tls_settings.Context()
1063 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1064
1065 sock.connect(addr)
1066 except (ssl.SSLError, ssl.CertificateError) as e:
1067 logging.error('%s: %s', e.__class__.__name__, e)
1068 continue
1069 except IOError as e:
1070 if e.errno == 2: # No such file or directory
1071 logging.error('%s: %s', e.__class__.__name__, e)
1072 continue
1073 raise
1074
1075 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001076
1077 logging.info('Connection established, registering...')
1078 handler = {
1079 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001080 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001081 Ghost.SHELL: self.SpawnShellServer,
1082 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001083 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001084 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001085
1086 # Machine ID may change if MAC address is used (USB-ethernet dongle
1087 # plugged/unplugged)
1088 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001089 self.SendRequest('register',
1090 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001091 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001092 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001093 except socket.error:
1094 pass
1095 else:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001096 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001097 self.Listen()
1098
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001099 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001100
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001101 def Reconnect(self):
1102 logging.info('Received reconnect request from RPC server, reconnecting...')
1103 self._reset.set()
1104
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001105 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001106 status = self._register_status
1107 if self._register_status == SUCCESS:
1108 ip, port = self._sock.sock.getpeername()
1109 status += ' %s:%d' % (ip, port)
1110 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001111
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001112 def AddToDownloadQueue(self, ttyname, filename):
1113 self._download_queue.put((ttyname, filename))
1114
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001115 def RegisterTTY(self, session_id, ttyname):
1116 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001117
1118 def RegisterSession(self, session_id, process_id):
1119 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001120
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001121 def StartLanDiscovery(self):
1122 """Start to listen to LAN discovery packet at
1123 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001124
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001125 def thread_func():
1126 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1127 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1128 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001129 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001130 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1131 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001132 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001133 return
1134
1135 logging.info('LAN Discovery: started')
1136 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001137 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001138
1139 if s in rd:
1140 data, source_addr = s.recvfrom(_BUFSIZE)
1141 parts = data.split()
1142 if parts[0] == 'OVERLORD':
1143 ip, port = parts[1].split(':')
1144 if not ip:
1145 ip = source_addr[0]
1146 self._queue.put((ip, int(port)), True)
1147
1148 try:
1149 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001150 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001151 pass
1152 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001153 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001154 self._queue.put(obj)
1155 elif obj == 'pause':
1156 logging.info('LAN Discovery: paused')
1157 while obj != 'resume':
1158 obj = self._queue.get(True)
1159 logging.info('LAN Discovery: resumed')
1160
1161 t = threading.Thread(target=thread_func)
1162 t.daemon = True
1163 t.start()
1164
1165 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001166 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001167 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1168 logRequests=False)
1169 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001170 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001171 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001172 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001173 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001174 t = threading.Thread(target=rpc_server.serve_forever)
1175 t.daemon = True
1176 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001177
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001178 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001179 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001180 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1181 if addr not in self._overlord_addrs:
1182 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001183
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001184 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001185 logging.info('%s started', self.MODE_NAME[self._mode])
1186 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001187 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001188
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001189 # We don't care about child process's return code, not wait is needed. This
1190 # is used to prevent zombie process from lingering in the system.
1191 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001192
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001193 if lan_disc:
1194 self.StartLanDiscovery()
1195
1196 if rpc_server:
1197 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001198
1199 try:
1200 while True:
1201 try:
1202 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001203 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001204 pass
1205 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001206 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001207 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1208 self._overlord_addrs.append(addr)
1209
1210 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001211 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001212 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001213 # Don't show stack trace for RuntimeError, which we use in this file for
1214 # plausible and expected errors (such as can't connect to server).
1215 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001216 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001217 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001218 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001219 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001220 traceback.print_tb(exc_traceback)
1221 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001222 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001223 time.sleep(_RETRY_INTERVAL)
1224
1225 self.Reset()
1226 except KeyboardInterrupt:
1227 logging.error('Received keyboard interrupt, quit')
1228 sys.exit(0)
1229
1230
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001231def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001232 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001233 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1234
1235
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001236def ForkToBackground():
1237 """Fork process to run in background."""
1238 pid = os.fork()
1239 if pid != 0:
1240 logging.info('Ghost(%d) running in background.', pid)
1241 sys.exit(0)
1242
1243
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001244def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001245 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001246 filepath = os.path.abspath(filename)
1247 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001248 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001249 sys.exit(1)
1250
1251 # Check if we actually have permission to read the file
1252 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001253 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001254 sys.exit(1)
1255
1256 server = GhostRPCServer()
1257 server.AddToDownloadQueue(os.ttyname(0), filepath)
1258 sys.exit(0)
1259
1260
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001261def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001262 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001263 logger = logging.getLogger()
1264 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001265 handler = logging.StreamHandler()
1266 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1267 handler.setFormatter(formatter)
1268 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001269
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001270 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001271 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1272 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001273 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1274 default=None, help='use MID as machine ID')
1275 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1276 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001277 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1278 default=True, help='disable LAN discovery')
1279 parser.add_argument('--no-rpc-server', dest='rpc_server',
1280 action='store_false', default=True,
1281 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001282 parser.add_argument('--tls', dest='tls_mode', default='detect',
1283 choices=('y', 'n', 'detect'),
1284 help="specify 'y' or 'n' to force enable/disable TLS")
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001285 parser.add_argument('--tls-cert-file', metavar='TLS_CERT_FILE',
1286 dest='tls_cert_file', type=str, default=None,
1287 help='file containing the server TLS certificate in PEM '
1288 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001289 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1290 action='store_true', default=False,
1291 help='do not verify certificate if TLS is enabled')
Joel Kitching22b89042015-08-06 18:23:29 +08001292 parser.add_argument('--prop-file', metavar='PROP_FILE', dest='prop_file',
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001293 type=str, default=None,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001294 help='file containing the JSON representation of client '
1295 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001296 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1297 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001298 parser.add_argument('--reset', dest='reset', default=False,
1299 action='store_true',
1300 help='reset ghost and reload all configs')
Peter Shih5cafebb2017-06-30 16:36:22 +08001301 parser.add_argument('--status', dest='status', default=False,
1302 action='store_true',
1303 help='show status of the client')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001304 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str,
1305 nargs='*', help='overlord server address')
1306 args = parser.parse_args()
1307
Peter Shih5cafebb2017-06-30 16:36:22 +08001308 if args.status:
1309 print(GhostRPCServer().GetStatus())
1310 sys.exit()
1311
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001312 if args.fork:
1313 ForkToBackground()
1314
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001315 if args.reset:
1316 GhostRPCServer().Reconnect()
1317 sys.exit()
1318
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001319 if args.download:
1320 DownloadFile(args.download)
1321
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001322 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001323 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001324
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001325 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1326
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001327 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001328 tls_mode = args.tls_mode
1329 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001330 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001331 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001332 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001333
1334
1335if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001336 try:
1337 main()
1338 except Exception as e:
1339 logging.error(e)