blob: 6d69e9f18cc3824ee29f94584209592c3f1efc48 [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
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800276 except socket.error: # Connect refused or timeout
277 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800278 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800279 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800280
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800281 def Upgrade(self):
282 logging.info('Upgrade: initiating upgrade sequence...')
283
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800284 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800285 https_enabled = self.TLSEnabled(self._connected_addr[0],
286 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800287 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800288 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
289 'abort')
290 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800291
292 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800293 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
294 'without TLS enabled! Possible mis-configuration or '
295 'DNS/IP spoofing detected, abort')
296 return
297
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800298 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800299 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800300 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800301 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800302
303 # Download sha1sum for ghost.py for verification
304 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800305 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800306 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
307 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800308 if f.getcode() != 200:
309 raise RuntimeError('HTTP status %d' % f.getcode())
310 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800311 except (ssl.SSLError, ssl.CertificateError) as e:
312 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
313 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800314 except Exception:
315 logging.error('Upgrade: failed to download sha1sum file, abort')
316 return
317
318 if self.GetFileSha1(scriptpath) == sha1sum:
319 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
320 return
321
322 # Download upgrade version of ghost.py
323 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800324 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800325 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
326 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800327 if f.getcode() != 200:
328 raise RuntimeError('HTTP status %d' % f.getcode())
329 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800330 except (ssl.SSLError, ssl.CertificateError) as e:
331 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
332 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800333 except Exception:
334 logging.error('Upgrade: failed to download upgrade, abort')
335 return
336
337 # Compare SHA1 sum
338 if hashlib.sha1(data).hexdigest() != sha1sum:
339 logging.error('Upgrade: sha1sum mismatch, abort')
340 return
341
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800342 try:
Yilin Yang235e5982019-12-26 10:36:22 +0800343 with open(scriptpath, 'wb') as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800344 f.write(data)
345 except Exception:
346 logging.error('Upgrade: failed to write upgrade onto disk, abort')
347 return
348
349 logging.info('Upgrade: restarting ghost...')
350 self.CloseSockets()
351 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800352 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800353
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800354 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800355 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800356 if self._prop_file:
357 with open(self._prop_file, 'r') as f:
358 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800359 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800360 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800361
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800362 def CloseSockets(self):
363 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800364 if self._platform == 'Linux':
365 for fd in os.listdir('/proc/self/fd/'):
366 try:
367 real_fd = os.readlink('/proc/self/fd/%s' % fd)
368 if real_fd.startswith('socket'):
369 os.close(int(fd))
370 except Exception:
371 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800372
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800373 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800374 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800375 """Spawn a child ghost with specific mode.
376
377 Returns:
378 The spawned child process pid.
379 """
Joel Kitching22b89042015-08-06 18:23:29 +0800380 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800381 self.SetIgnoreChild(False)
382
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800383 pid = os.fork()
384 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800385 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800386 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
387 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800388 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800389 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800390 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800391 sys.exit(0)
392 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800393 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800394 return pid
395
396 def Timestamp(self):
397 return int(time.time())
398
399 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800400 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800401 output = process_utils.CheckOutput(['route', '-n', 'get', 'default'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800402 ret = re.search('gateway: (.*)', output)
403 if ret:
404 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800405 return []
Fei Shao12ecf382020-06-23 18:32:26 +0800406 if self._platform == 'Linux':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800407 with open('/proc/net/route', 'r') as f:
408 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800409
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800410 ips = []
411 for line in lines:
412 parts = line.split('\t')
413 if parts[2] == '00000000':
414 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800415
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800416 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800417 h = codecs.decode(parts[2], 'hex')
Yilin Yangacd3c792020-05-05 10:00:30 +0800418 ips.append('.'.join([str(x) for x in reversed(h)]))
Yilin Yangf9fe1932019-11-04 17:09:34 +0800419 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800420 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800421
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800422 return ips
Fei Shao12ecf382020-06-23 18:32:26 +0800423
424 logging.warning('GetGateWayIP: unsupported platform')
425 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800426
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800427 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800428 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800429 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800430
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800431 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800432 match = re.match(r'^https?://(.*):.*$', url)
433 if match:
434 return [match.group(1)]
435 except Exception:
436 pass
437 return []
438
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800439 def GetMachineID(self):
440 """Generates machine-dependent ID string for a machine.
441 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800442 Linux:
443 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800444 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
445 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800446 We follow the listed order to generate machine ID, and fallback to the
447 next alternative if the previous doesn't work.
448
449 Darwin:
450 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800451 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800452 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800453 return str(uuid.uuid4())
Fei Shao12ecf382020-06-23 18:32:26 +0800454 if self._mid:
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800455 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800456
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800457 # Darwin
458 if self._platform == 'Darwin':
Yilin Yang42ba5c62020-05-05 10:32:34 +0800459 output = process_utils.CheckOutput(['ioreg', '-rd1', '-c',
460 'IOPlatformExpertDevice'])
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800461 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
462 if ret:
463 return ret.group(1)
464
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800465 # Try factory device id
466 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800467 from cros.factory.test import session
468 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800469 except Exception:
470 pass
471
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800472 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800473 try:
474 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
475 return f.read().strip()
476 except Exception:
477 pass
478
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800479 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800480 try:
481 macs = []
482 ifaces = sorted(os.listdir('/sys/class/net'))
483 for iface in ifaces:
484 if iface == 'lo':
485 continue
486
487 with open('/sys/class/net/%s/address' % iface, 'r') as f:
488 macs.append(f.read().strip())
489
490 return ';'.join(macs)
491 except Exception:
492 pass
493
Peter Shihcb0e5512017-06-14 16:59:46 +0800494 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800495
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800496 def GetProcessWorkingDirectory(self, pid):
497 if self._platform == 'Linux':
498 return os.readlink('/proc/%d/cwd' % pid)
Fei Shao12ecf382020-06-23 18:32:26 +0800499 if self._platform == 'Darwin':
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800500 PROC_PIDVNODEPATHINFO = 9
501 proc_vnodepathinfo_size = 2352
502 vid_path_offset = 152
503
504 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
505 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
506 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
507 ctypes.byref(buf), proc_vnodepathinfo_size)
508 buf = buf.raw[vid_path_offset:]
509 n = buf.index('\0')
510 return buf[:n]
Fei Shao12ecf382020-06-23 18:32:26 +0800511 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800512
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800513 def Reset(self):
514 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800515 if self._sock is not None:
516 self._sock.Close()
517 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800518 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800519 self._last_ping = 0
520 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800521 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800522 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800523
524 def SendMessage(self, msg):
525 """Serialize the message and send it through the socket."""
Yilin Yang6b9ec9d2019-12-09 11:04:06 +0800526 self._sock.Send(json.dumps(msg).encode('utf-8') + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800527
528 def SendRequest(self, name, args, handler=None,
529 timeout=_REQUEST_TIMEOUT_SECS):
530 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800531 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800532
533 rid = str(uuid.uuid4())
534 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800535 if timeout >= 0:
536 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800537 self.SendMessage(msg)
538
539 def SendResponse(self, omsg, status, params=None):
540 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
541 self.SendMessage(msg)
542
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800543 def HandleTTYControl(self, fd, control_str):
544 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800545 command = msg['command']
546 params = msg['params']
547 if command == 'resize':
548 # some error happened on websocket
549 if len(params) != 2:
550 return
551 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
552 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
553 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800554 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800555
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800556 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800557 """Spawn a TTY server and forward I/O to the TCP socket."""
558 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800559
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800560 try:
561 if self._tty_device is None:
562 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800563
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800564 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800565 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800566 try:
567 server = GhostRPCServer()
568 server.RegisterTTY(self._session_id, ttyname)
569 server.RegisterSession(self._session_id, os.getpid())
570 except Exception:
571 # If ghost is launched without RPC server, the call will fail but we
572 # can ignore it.
573 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800574
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800575 # The directory that contains the current running ghost script
576 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800577
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800578 env = os.environ.copy()
579 env['USER'] = os.getenv('USER', 'root')
580 env['HOME'] = os.getenv('HOME', '/root')
581 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
582 os.chdir(env['HOME'])
583 os.execve(_SHELL, [_SHELL], env)
584 else:
585 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800586 tty.setraw(fd)
587 attr = termios.tcgetattr(fd)
588 attr[0] &= ~(termios.IXON | termios.IXOFF)
589 attr[2] |= termios.CLOCAL
590 attr[2] &= ~termios.CRTSCTS
591 attr[4] = termios.B115200
592 attr[5] = termios.B115200
593 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800594
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800595 nonlocals = {'control_state': None, 'control_str': ''}
596
597 def _ProcessBuffer(buf):
598 write_buffer = ''
599 while buf:
600 if nonlocals['control_state']:
601 if chr(_CONTROL_END) in buf:
602 index = buf.index(chr(_CONTROL_END))
603 nonlocals['control_str'] += buf[:index]
604 self.HandleTTYControl(fd, nonlocals['control_str'])
605 nonlocals['control_state'] = None
606 nonlocals['control_str'] = ''
607 buf = buf[index+1:]
608 else:
609 nonlocals['control_str'] += buf
610 buf = ''
611 else:
612 if chr(_CONTROL_START) in buf:
613 nonlocals['control_state'] = _CONTROL_START
614 index = buf.index(chr(_CONTROL_START))
615 write_buffer += buf[:index]
616 buf = buf[index+1:]
617 else:
618 write_buffer += buf
619 buf = ''
620
621 if write_buffer:
622 os.write(fd, write_buffer)
623
624 _ProcessBuffer(self._sock.RecvBuf())
625
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800626 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800627 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800628
629 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800630 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800631
632 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800633 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800634 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800635 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800636 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800637 except Exception as e:
638 logging.error('SpawnTTYServer: %s', e)
639 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800640 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800641
642 logging.info('SpawnTTYServer: terminated')
643 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800644
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800645 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800646 """Spawn a shell server and forward input/output from/to the TCP socket."""
647 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800648
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800649 # Add ghost executable to PATH
650 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
651 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800652 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800653
654 # Execute shell command from HOME directory
655 os.chdir(os.getenv('HOME', '/tmp'))
656
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800657 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800658 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800659 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800660
661 def make_non_block(fd):
662 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
663 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
664
665 make_non_block(p.stdout)
666 make_non_block(p.stderr)
667
668 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800669 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800670
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800671 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800672 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800673 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800674 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800675 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800676
677 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800678 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800679
680 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800681 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800682 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800683 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800684
685 try:
686 idx = ret.index(_STDIN_CLOSED * 2)
687 p.stdin.write(ret[:idx])
688 p.stdin.close()
689 except ValueError:
690 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800691 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800692 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800693 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800694 except Exception as e:
695 logging.error('SpawnShellServer: %s', e)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800696 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800697 # Check if the process is terminated. If not, Send SIGTERM to process,
698 # then wait for 1 second. Send another SIGKILL to make sure the process is
699 # terminated.
700 p.poll()
701 if p.returncode is None:
702 try:
703 p.terminate()
704 time.sleep(1)
705 p.kill()
706 except Exception:
707 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800708
709 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800710 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800711
712 logging.info('SpawnShellServer: terminated')
713 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800714
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800715 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800716 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800717 try:
718 size = os.stat(self._file_op[1]).st_size
719 except OSError as e:
720 logging.error('InitiateFileOperation: download: %s', e)
721 sys.exit(1)
722
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800723 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800724 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800725 'filename': os.path.basename(self._file_op[1]),
726 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800727 elif self._file_op[0] == 'upload':
728 self.SendRequest('clear_to_upload', {}, timeout=-1)
729 self.StartUploadServer()
730 else:
731 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800732
733 def StartDownloadServer(self):
734 logging.info('StartDownloadServer: started')
735
736 try:
737 with open(self._file_op[1], 'rb') as f:
738 while True:
739 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800740 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800741 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800742 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800743 except Exception as e:
744 logging.error('StartDownloadServer: %s', e)
745 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800746 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800747
748 logging.info('StartDownloadServer: terminated')
749 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800750
Wei-Ning Huange2981862015-08-03 15:03:08 +0800751 def StartUploadServer(self):
752 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800753 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800754 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800755 dirname = os.path.dirname(filepath)
756 if not os.path.exists(dirname):
757 try:
758 os.makedirs(dirname)
759 except Exception:
760 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800761
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800762 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800763 if self._file_op[2]:
764 os.fchmod(f.fileno(), self._file_op[2])
765
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800766 f.write(self._sock.RecvBuf())
767
Wei-Ning Huange2981862015-08-03 15:03:08 +0800768 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800769 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800770 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800771 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800772 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800773 break
774 f.write(buf)
775 except socket.error as e:
776 logging.error('StartUploadServer: socket error: %s', e)
777 except Exception as e:
778 logging.error('StartUploadServer: %s', e)
779 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800780 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800781
782 logging.info('StartUploadServer: terminated')
783 sys.exit(0)
784
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800785 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800786 """Spawn a port forwarding server and forward I/O to the TCP socket."""
787 logging.info('SpawnPortForwardServer: started')
788
789 src_sock = None
790 try:
791 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800792 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800793 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800794
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800795 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800796
797 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800798 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800799
800 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800801 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800802 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800803 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800804 src_sock.send(data)
805
806 if src_sock in rd:
807 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800808 if not data:
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800809 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800810 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800811 except Exception as e:
812 logging.error('SpawnPortForwardServer: %s', e)
813 finally:
814 if src_sock:
815 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800816 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800817
818 logging.info('SpawnPortForwardServer: terminated')
819 sys.exit(0)
820
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800821 def Ping(self):
822 def timeout_handler(x):
823 if x is None:
824 raise PingTimeoutError
825
826 self._last_ping = self.Timestamp()
827 self.SendRequest('ping', {}, timeout_handler, 5)
828
Wei-Ning Huangae923642015-09-24 14:08:09 +0800829 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800830 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800831 filepath = params['filename']
832 if not os.path.isabs(filepath):
833 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
834
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800835 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800836 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800837 pass
838 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800839 self.SendResponse(msg, str(e))
840 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800841
842 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800843 file_op=('download', filepath))
844 self.SendResponse(msg, SUCCESS)
845
846 def HandleFileUploadRequest(self, msg):
847 params = msg['params']
848
849 # Resolve upload filepath
850 filename = params['filename']
851 dest_path = filename
852
853 # If dest is specified, use it first
854 dest_path = params.get('dest', '')
855 if dest_path:
856 if not os.path.isabs(dest_path):
857 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
858
859 if os.path.isdir(dest_path):
860 dest_path = os.path.join(dest_path, filename)
861 else:
862 target_dir = os.getenv('HOME', '/tmp')
863
864 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800865 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800866 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
867 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800868 try:
869 target_dir = self.GetProcessWorkingDirectory(pid)
870 except Exception as e:
871 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800872
873 dest_path = os.path.join(target_dir, filename)
874
875 try:
876 os.makedirs(os.path.dirname(dest_path))
877 except Exception:
878 pass
879
880 try:
881 with open(dest_path, 'w') as _:
882 pass
883 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800884 self.SendResponse(msg, str(e))
885 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800886
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800887 # If not check_only, spawn FILE mode ghost agent to handle upload
888 if not params.get('check_only', False):
889 self.SpawnGhost(self.FILE, params['sid'],
890 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800891 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800892
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800893 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800894 command = msg['name']
895 params = msg['params']
896
897 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800898 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800899 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800900 self.SpawnGhost(self.TERMINAL, params['sid'],
901 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800902 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800903 elif command == 'shell':
904 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800905 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800906 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800907 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800908 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800909 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800910 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800911 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800912 elif command == 'forward':
913 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
914 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800915
916 def HandleResponse(self, response):
917 rid = str(response['rid'])
918 if rid in self._requests:
919 handler = self._requests[rid][2]
920 del self._requests[rid]
921 if callable(handler):
922 handler(response)
923 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800924 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800925
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800926 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800927 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800928 try:
929 index = buf.index(_SEPARATOR)
930 except ValueError:
931 self._sock.UnRecv(buf)
932 return
933
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800934 msgs_json = [buf[:index]]
935 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800936 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800937 msgs_json = buf.split(_SEPARATOR)
938 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800939
940 for msg_json in msgs_json:
941 try:
942 msg = json.loads(msg_json)
943 except ValueError:
944 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800945 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800946 continue
947
948 if 'name' in msg:
949 self.HandleRequest(msg)
950 elif 'response' in msg:
951 self.HandleResponse(msg)
952 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800953 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800954
955 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800956 """Scans for pending requests which have timed out.
957
958 If any timed-out requests are discovered, their handler is called with the
959 special response value of None.
960 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800961 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800962 request_time, timeout, handler = self._requests[rid]
963 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800964 if callable(handler):
965 handler(None)
966 else:
967 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800968 del self._requests[rid]
969
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800970 def InitiateDownload(self):
971 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800972 sid = self._ttyname_to_sid[ttyname]
973 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800974 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800975
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800976 def Listen(self):
977 try:
978 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800979 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800980 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800981
982 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800983 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800984
985 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +0800986 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800987 break
988
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800989 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800990
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800991 if (self._mode == self.AGENT and
992 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800993 self.Ping()
994 self.ScanForTimeoutRequests()
995
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800996 if not self._download_queue.empty():
997 self.InitiateDownload()
998
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800999 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001000 break
1001 except socket.error:
1002 raise RuntimeError('Connection dropped')
1003 except PingTimeoutError:
1004 raise RuntimeError('Connection timeout')
1005 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001006 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001007
1008 self._queue.put('resume')
1009
1010 if self._mode != Ghost.AGENT:
1011 sys.exit(1)
1012
1013 def Register(self):
1014 non_local = {}
1015 for addr in self._overlord_addrs:
1016 non_local['addr'] = addr
1017 def registered(response):
1018 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001019 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001020 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001021
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001022 self._register_status = response['response']
1023 if response['response'] != SUCCESS:
1024 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001025 raise RuntimeError('Register: ' + response['response'])
Fei Shao0e4e2c62020-06-23 18:22:26 +08001026
1027 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1028 self._connected_addr = non_local['addr']
1029 self.Upgrade() # Check for upgrade
1030 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001031
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001032 try:
1033 logging.info('Trying %s:%d ...', *addr)
1034 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001035
Peter Shih220a96d2016-12-22 17:02:16 +08001036 # Check if server has TLS enabled. Only check if self._tls_mode is
1037 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001038 # Only control channel needs to determine if TLS is enabled. Other mode
1039 # should use the TLSSettings passed in when it was spawned.
1040 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001041 self._tls_settings.SetEnabled(
1042 self.TLSEnabled(*addr) if self._tls_mode is None
1043 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001044
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001045 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1046 sock.settimeout(_CONNECT_TIMEOUT)
1047
1048 try:
1049 if self._tls_settings.Enabled():
1050 tls_context = self._tls_settings.Context()
1051 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1052
1053 sock.connect(addr)
1054 except (ssl.SSLError, ssl.CertificateError) as e:
1055 logging.error('%s: %s', e.__class__.__name__, e)
1056 continue
1057 except IOError as e:
1058 if e.errno == 2: # No such file or directory
1059 logging.error('%s: %s', e.__class__.__name__, e)
1060 continue
1061 raise
1062
1063 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001064
1065 logging.info('Connection established, registering...')
1066 handler = {
1067 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001068 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001069 Ghost.SHELL: self.SpawnShellServer,
1070 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001071 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001072 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001073
1074 # Machine ID may change if MAC address is used (USB-ethernet dongle
1075 # plugged/unplugged)
1076 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001077 self.SendRequest('register',
1078 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001079 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001080 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001081 except socket.error:
1082 pass
1083 else:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001084 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001085 self.Listen()
1086
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001087 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001088
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001089 def Reconnect(self):
1090 logging.info('Received reconnect request from RPC server, reconnecting...')
1091 self._reset.set()
1092
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001093 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001094 status = self._register_status
1095 if self._register_status == SUCCESS:
1096 ip, port = self._sock.sock.getpeername()
1097 status += ' %s:%d' % (ip, port)
1098 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001099
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001100 def AddToDownloadQueue(self, ttyname, filename):
1101 self._download_queue.put((ttyname, filename))
1102
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001103 def RegisterTTY(self, session_id, ttyname):
1104 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001105
1106 def RegisterSession(self, session_id, process_id):
1107 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001108
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001109 def StartLanDiscovery(self):
1110 """Start to listen to LAN discovery packet at
1111 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001112
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001113 def thread_func():
1114 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1115 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1116 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001117 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001118 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1119 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001120 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001121 return
1122
1123 logging.info('LAN Discovery: started')
1124 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001125 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001126
1127 if s in rd:
1128 data, source_addr = s.recvfrom(_BUFSIZE)
1129 parts = data.split()
1130 if parts[0] == 'OVERLORD':
1131 ip, port = parts[1].split(':')
1132 if not ip:
1133 ip = source_addr[0]
1134 self._queue.put((ip, int(port)), True)
1135
1136 try:
1137 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001138 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001139 pass
1140 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001141 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001142 self._queue.put(obj)
1143 elif obj == 'pause':
1144 logging.info('LAN Discovery: paused')
1145 while obj != 'resume':
1146 obj = self._queue.get(True)
1147 logging.info('LAN Discovery: resumed')
1148
1149 t = threading.Thread(target=thread_func)
1150 t.daemon = True
1151 t.start()
1152
1153 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001154 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001155 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1156 logRequests=False)
1157 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001158 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001159 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001160 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001161 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001162 t = threading.Thread(target=rpc_server.serve_forever)
1163 t.daemon = True
1164 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001165
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001166 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001167 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001168 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1169 if addr not in self._overlord_addrs:
1170 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001171
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001172 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001173 logging.info('%s started', self.MODE_NAME[self._mode])
1174 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001175 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001176
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001177 # We don't care about child process's return code, not wait is needed. This
1178 # is used to prevent zombie process from lingering in the system.
1179 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001180
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001181 if lan_disc:
1182 self.StartLanDiscovery()
1183
1184 if rpc_server:
1185 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001186
1187 try:
1188 while True:
1189 try:
1190 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001191 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001192 pass
1193 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001194 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001195 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1196 self._overlord_addrs.append(addr)
1197
1198 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001199 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001200 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001201 # Don't show stack trace for RuntimeError, which we use in this file for
1202 # plausible and expected errors (such as can't connect to server).
1203 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001204 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001205 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001206 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001207 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001208 traceback.print_tb(exc_traceback)
1209 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001210 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001211 time.sleep(_RETRY_INTERVAL)
1212
1213 self.Reset()
1214 except KeyboardInterrupt:
1215 logging.error('Received keyboard interrupt, quit')
1216 sys.exit(0)
1217
1218
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001219def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001220 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001221 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1222
1223
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001224def ForkToBackground():
1225 """Fork process to run in background."""
1226 pid = os.fork()
1227 if pid != 0:
1228 logging.info('Ghost(%d) running in background.', pid)
1229 sys.exit(0)
1230
1231
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001232def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001233 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001234 filepath = os.path.abspath(filename)
1235 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001236 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001237 sys.exit(1)
1238
1239 # Check if we actually have permission to read the file
1240 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001241 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001242 sys.exit(1)
1243
1244 server = GhostRPCServer()
1245 server.AddToDownloadQueue(os.ttyname(0), filepath)
1246 sys.exit(0)
1247
1248
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001249def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001250 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001251 logger = logging.getLogger()
1252 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001253 handler = logging.StreamHandler()
1254 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1255 handler.setFormatter(formatter)
1256 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001257
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001258 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001259 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1260 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001261 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1262 default=None, help='use MID as machine ID')
1263 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1264 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001265 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1266 default=True, help='disable LAN discovery')
1267 parser.add_argument('--no-rpc-server', dest='rpc_server',
1268 action='store_false', default=True,
1269 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001270 parser.add_argument('--tls', dest='tls_mode', default='detect',
1271 choices=('y', 'n', 'detect'),
1272 help="specify 'y' or 'n' to force enable/disable TLS")
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001273 parser.add_argument('--tls-cert-file', metavar='TLS_CERT_FILE',
1274 dest='tls_cert_file', type=str, default=None,
1275 help='file containing the server TLS certificate in PEM '
1276 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001277 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1278 action='store_true', default=False,
1279 help='do not verify certificate if TLS is enabled')
Joel Kitching22b89042015-08-06 18:23:29 +08001280 parser.add_argument('--prop-file', metavar='PROP_FILE', dest='prop_file',
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001281 type=str, default=None,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001282 help='file containing the JSON representation of client '
1283 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001284 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1285 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001286 parser.add_argument('--reset', dest='reset', default=False,
1287 action='store_true',
1288 help='reset ghost and reload all configs')
Peter Shih5cafebb2017-06-30 16:36:22 +08001289 parser.add_argument('--status', dest='status', default=False,
1290 action='store_true',
1291 help='show status of the client')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001292 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str,
1293 nargs='*', help='overlord server address')
1294 args = parser.parse_args()
1295
Peter Shih5cafebb2017-06-30 16:36:22 +08001296 if args.status:
1297 print(GhostRPCServer().GetStatus())
1298 sys.exit()
1299
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001300 if args.fork:
1301 ForkToBackground()
1302
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001303 if args.reset:
1304 GhostRPCServer().Reconnect()
1305 sys.exit()
1306
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001307 if args.download:
1308 DownloadFile(args.download)
1309
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001310 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001311 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001312
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001313 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1314
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001315 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001316 tls_mode = args.tls_mode
1317 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001318 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001319 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001320 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001321
1322
1323if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001324 try:
1325 main()
1326 except Exception as e:
1327 logging.error(e)