blob: 78d27cb2b577d0cc6a514ed31cb60dd603fd8e17 [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
Yilin Yangf9fe1932019-11-04 17:09:34 +080039from six import PY2
Wei-Ning Huang2132de32015-04-13 17:24:38 +080040
Yilin Yangf54fb912020-01-08 11:42:38 +080041
Peter Shihc56c5b62016-12-22 12:30:57 +080042_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', 4499))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080043
Peter Shihc56c5b62016-12-22 12:30:57 +080044_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', 4455))
45_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', 4456))
46_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', 9000))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080047
48_BUFSIZE = 8192
49_RETRY_INTERVAL = 2
50_SEPARATOR = '\r\n'
51_PING_TIMEOUT = 3
52_PING_INTERVAL = 5
53_REQUEST_TIMEOUT_SECS = 60
54_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080055_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080056
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080057_CONTROL_START = 128
58_CONTROL_END = 129
59
Wei-Ning Huanga301f572015-06-03 17:34:21 +080060_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080061_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080062
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080063# Stream control
64_STDIN_CLOSED = '##STDIN_CLOSED##'
65
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080066SUCCESS = 'success'
67FAILED = 'failed'
68DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080069
Joel Kitching22b89042015-08-06 18:23:29 +080070
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080071class PingTimeoutError(Exception):
72 pass
73
74
75class RequestError(Exception):
76 pass
77
78
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080079class BufferedSocket(object):
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080080 """A buffered socket that supports unrecv.
81
82 Allow putting back data back to the socket for the next recv() call.
83 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080084 def __init__(self, sock):
85 self.sock = sock
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080086 self._buf = ''
87
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080088 def fileno(self):
89 return self.sock.fileno()
90
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080091 def Recv(self, bufsize, flags=0):
92 if self._buf:
93 if len(self._buf) >= bufsize:
94 ret = self._buf[:bufsize]
95 self._buf = self._buf[bufsize:]
96 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +080097 ret = self._buf
98 self._buf = ''
99 return ret + self.sock.recv(bufsize - len(ret), flags)
100 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800101
102 def UnRecv(self, buf):
103 self._buf = buf + self._buf
104
105 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800106 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800107
108 def RecvBuf(self):
109 """Only recive from buffer."""
110 ret = self._buf
111 self._buf = ''
112 return ret
113
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800114 def Close(self):
115 self.sock.close()
116
117
118class TLSSettings(object):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800119 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800120 """Constructor.
121
122 Args:
123 tls_cert_file: TLS certificate in PEM format.
124 enable_tls_without_verify: enable TLS but don't verify certificate.
125 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800126 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800127 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800128 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800129 self._tls_context = None
130
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800131 def _UpdateContext(self):
132 if not self._enabled:
133 self._tls_context = None
134 return
135
136 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
137 self._tls_context.verify_mode = ssl.CERT_REQUIRED
138
139 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800140 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800141 self._tls_context.check_hostname = True
142 try:
143 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800144 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800145 except IOError as e:
146 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
147 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800148 else:
149 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
150 logging.info('TLSSettings: using built-in ca-certificates')
151 else:
152 self._tls_context.verify_mode = ssl.CERT_NONE
153 logging.info('TLSSettings: skipping TLS verification!!!')
154
155 def SetEnabled(self, enabled):
156 logging.info('TLSSettings: enabled: %s', enabled)
157
158 if self._enabled != enabled:
159 self._enabled = enabled
160 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800161
162 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800163 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800164
165 def Context(self):
166 return self._tls_context
167
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800168
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800169class Ghost(object):
170 """Ghost implements the client protocol of Overlord.
171
172 Ghost provide terminal/shell/logcat functionality and manages the client
173 side connectivity.
174 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800175 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800176
177 MODE_NAME = {
178 NONE: 'NONE',
179 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800180 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800181 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800182 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800183 FILE: 'File',
184 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800185 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800186
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800187 RANDOM_MID = '##random_mid##'
188
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800189 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
190 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Peter Shih220a96d2016-12-22 17:02:16 +0800191 command=None, file_op=None, port=None, tls_mode=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800192 """Constructor.
193
194 Args:
195 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800196 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800197 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800198 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
199 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800200 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800201 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800202 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800203 terminal_sid: the terminal session ID associate with this client. This is
204 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800205 tty_device: the terminal device to open, if tty_device is None, as pseudo
206 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800207 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800208 file_op: a tuple (action, filepath, perm). action is either 'download' or
209 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800210 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800211 tls_mode: can be [True, False, None]. if not None, skip detection of
212 TLS and assume whether server use TLS or not.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800213 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800214 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
215 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800216 if mode == Ghost.SHELL:
217 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800218 if mode == Ghost.FILE:
219 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800220
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800221 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800222 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800223 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800224 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800225 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800226 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800227 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800228 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800229 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800230 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800231 self._ttyname_to_sid = {}
232 self._terminal_sid_to_pid = {}
233 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800234 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800235 self._register_status = DISCONNECTED
236 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800237 self._tls_mode = tls_mode
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800238
239 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800240 self._requests = {}
Yilin Yang8b7f5192020-01-08 11:43:00 +0800241 self._queue = queue.Queue()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800242
243 # Protocol specific
244 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800245 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800246 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800247 self._file_op = file_op
Yilin Yang8b7f5192020-01-08 11:43:00 +0800248 self._download_queue = queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800249 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800250
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800251 def SetIgnoreChild(self, status):
252 # Only ignore child for Agent since only it could spawn child Ghost.
253 if self._mode == Ghost.AGENT:
254 signal.signal(signal.SIGCHLD,
255 signal.SIG_IGN if status else signal.SIG_DFL)
256
257 def GetFileSha1(self, filename):
258 with open(filename, 'r') as f:
259 return hashlib.sha1(f.read()).hexdigest()
260
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800261 def TLSEnabled(self, host, port):
262 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800263 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
264 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800265 # Allow any certificate since we only want to check if server talks TLS.
266 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
267 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800268
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800269 sock = context.wrap_socket(sock, server_hostname=host)
270 sock.settimeout(_CONNECT_TIMEOUT)
271 sock.connect((host, port))
272 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800273 except ssl.SSLError:
274 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800275 except socket.error: # Connect refused or timeout
276 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800277 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800278 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800279
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800280 def Upgrade(self):
281 logging.info('Upgrade: initiating upgrade sequence...')
282
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800283 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800284 https_enabled = self.TLSEnabled(self._connected_addr[0],
285 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800286 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800287 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
288 'abort')
289 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800290
291 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800292 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
293 'without TLS enabled! Possible mis-configuration or '
294 'DNS/IP spoofing detected, abort')
295 return
296
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800297 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800298 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800299 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800300 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800301
302 # Download sha1sum for ghost.py for verification
303 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800304 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800305 urllib.request.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
306 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800307 if f.getcode() != 200:
308 raise RuntimeError('HTTP status %d' % f.getcode())
309 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800310 except (ssl.SSLError, ssl.CertificateError) as e:
311 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
312 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800313 except Exception:
314 logging.error('Upgrade: failed to download sha1sum file, abort')
315 return
316
317 if self.GetFileSha1(scriptpath) == sha1sum:
318 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
319 return
320
321 # Download upgrade version of ghost.py
322 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800323 with contextlib.closing(
Yilin Yangf54fb912020-01-08 11:42:38 +0800324 urllib.request.urlopen(url, timeout=_CONNECT_TIMEOUT,
325 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800326 if f.getcode() != 200:
327 raise RuntimeError('HTTP status %d' % f.getcode())
328 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800329 except (ssl.SSLError, ssl.CertificateError) as e:
330 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
331 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800332 except Exception:
333 logging.error('Upgrade: failed to download upgrade, abort')
334 return
335
336 # Compare SHA1 sum
337 if hashlib.sha1(data).hexdigest() != sha1sum:
338 logging.error('Upgrade: sha1sum mismatch, abort')
339 return
340
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800341 try:
342 with open(scriptpath, 'w') as f:
343 f.write(data)
344 except Exception:
345 logging.error('Upgrade: failed to write upgrade onto disk, abort')
346 return
347
348 logging.info('Upgrade: restarting ghost...')
349 self.CloseSockets()
350 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800351 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800352
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800353 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800354 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800355 if self._prop_file:
356 with open(self._prop_file, 'r') as f:
357 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800358 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800359 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800360
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800361 def CloseSockets(self):
362 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800363 if self._platform == 'Linux':
364 for fd in os.listdir('/proc/self/fd/'):
365 try:
366 real_fd = os.readlink('/proc/self/fd/%s' % fd)
367 if real_fd.startswith('socket'):
368 os.close(int(fd))
369 except Exception:
370 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800371
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800372 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800373 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800374 """Spawn a child ghost with specific mode.
375
376 Returns:
377 The spawned child process pid.
378 """
Joel Kitching22b89042015-08-06 18:23:29 +0800379 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800380 self.SetIgnoreChild(False)
381
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800382 pid = os.fork()
383 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800384 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800385 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
386 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800387 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800388 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800389 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800390 sys.exit(0)
391 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800392 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800393 return pid
394
395 def Timestamp(self):
396 return int(time.time())
397
398 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800399 if self._platform == 'Darwin':
400 output = subprocess.check_output(['route', '-n', 'get', 'default'])
401 ret = re.search('gateway: (.*)', output)
402 if ret:
403 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800404 return []
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800405 elif self._platform == 'Linux':
406 with open('/proc/net/route', 'r') as f:
407 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800408
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800409 ips = []
410 for line in lines:
411 parts = line.split('\t')
412 if parts[2] == '00000000':
413 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800414
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800415 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800416 h = codecs.decode(parts[2], 'hex')
417 # TODO(kerker) Remove when py3 upgrade complete
418 if PY2:
419 ips.append('%d.%d.%d.%d' % tuple(ord(x) for x in reversed(h)))
420 else:
421 ips.append('.'.join([str(x) for x in reversed(h)]))
422 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800423 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800424
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800425 return ips
426 else:
427 logging.warning('GetGateWayIP: unsupported platform')
428 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800429
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800430 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800431 try:
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800432 from cros.factory.test import server_proxy
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800433
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800434 url = server_proxy.GetServerURL()
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800435 match = re.match(r'^https?://(.*):.*$', url)
436 if match:
437 return [match.group(1)]
438 except Exception:
439 pass
440 return []
441
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800442 def GetMachineID(self):
443 """Generates machine-dependent ID string for a machine.
444 There are many ways to generate a machine ID:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800445 Linux:
446 1. factory device_id
Peter Shih5f1f48c2017-06-26 14:12:00 +0800447 2. /sys/class/dmi/id/product_uuid (only available on intel machines)
448 3. MAC address
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800449 We follow the listed order to generate machine ID, and fallback to the
450 next alternative if the previous doesn't work.
451
452 Darwin:
453 All Darwin system should have the IOPlatformSerialNumber attribute.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800454 """
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800455 if self._mid == Ghost.RANDOM_MID:
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800456 return str(uuid.uuid4())
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800457 elif self._mid:
458 return self._mid
Wei-Ning Huangaed90452015-03-23 17:50:21 +0800459
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800460 # Darwin
461 if self._platform == 'Darwin':
462 output = subprocess.check_output(['ioreg', '-rd1', '-c',
463 'IOPlatformExpertDevice'])
464 ret = re.search('"IOPlatformSerialNumber" = "(.*)"', output)
465 if ret:
466 return ret.group(1)
467
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800468 # Try factory device id
469 try:
Hung-Te Linda8eb992017-09-28 03:27:12 +0800470 from cros.factory.test import session
471 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800472 except Exception:
473 pass
474
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800475 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800476 try:
477 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
478 return f.read().strip()
479 except Exception:
480 pass
481
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800482 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800483 try:
484 macs = []
485 ifaces = sorted(os.listdir('/sys/class/net'))
486 for iface in ifaces:
487 if iface == 'lo':
488 continue
489
490 with open('/sys/class/net/%s/address' % iface, 'r') as f:
491 macs.append(f.read().strip())
492
493 return ';'.join(macs)
494 except Exception:
495 pass
496
Peter Shihcb0e5512017-06-14 16:59:46 +0800497 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800498
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800499 def GetProcessWorkingDirectory(self, pid):
500 if self._platform == 'Linux':
501 return os.readlink('/proc/%d/cwd' % pid)
502 elif self._platform == 'Darwin':
503 PROC_PIDVNODEPATHINFO = 9
504 proc_vnodepathinfo_size = 2352
505 vid_path_offset = 152
506
507 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
508 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
509 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
510 ctypes.byref(buf), proc_vnodepathinfo_size)
511 buf = buf.raw[vid_path_offset:]
512 n = buf.index('\0')
513 return buf[:n]
514 else:
515 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
516
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800517 def Reset(self):
518 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800519 if self._sock is not None:
520 self._sock.Close()
521 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800522 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800523 self._last_ping = 0
524 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800525 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800526 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800527
528 def SendMessage(self, msg):
529 """Serialize the message and send it through the socket."""
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800530 self._sock.Send(json.dumps(msg) + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800531
532 def SendRequest(self, name, args, handler=None,
533 timeout=_REQUEST_TIMEOUT_SECS):
534 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800535 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800536
537 rid = str(uuid.uuid4())
538 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800539 if timeout >= 0:
540 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800541 self.SendMessage(msg)
542
543 def SendResponse(self, omsg, status, params=None):
544 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
545 self.SendMessage(msg)
546
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800547 def HandleTTYControl(self, fd, control_str):
548 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800549 command = msg['command']
550 params = msg['params']
551 if command == 'resize':
552 # some error happened on websocket
553 if len(params) != 2:
554 return
555 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
556 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
557 else:
Yilin Yang9881b1e2019-12-11 11:47:33 +0800558 logging.warning('Invalid request command "%s"', command)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800559
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800560 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800561 """Spawn a TTY server and forward I/O to the TCP socket."""
562 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800563
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800564 try:
565 if self._tty_device is None:
566 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800567
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800568 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800569 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800570 try:
571 server = GhostRPCServer()
572 server.RegisterTTY(self._session_id, ttyname)
573 server.RegisterSession(self._session_id, os.getpid())
574 except Exception:
575 # If ghost is launched without RPC server, the call will fail but we
576 # can ignore it.
577 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800578
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800579 # The directory that contains the current running ghost script
580 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800581
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800582 env = os.environ.copy()
583 env['USER'] = os.getenv('USER', 'root')
584 env['HOME'] = os.getenv('HOME', '/root')
585 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
586 os.chdir(env['HOME'])
587 os.execve(_SHELL, [_SHELL], env)
588 else:
589 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800590 tty.setraw(fd)
591 attr = termios.tcgetattr(fd)
592 attr[0] &= ~(termios.IXON | termios.IXOFF)
593 attr[2] |= termios.CLOCAL
594 attr[2] &= ~termios.CRTSCTS
595 attr[4] = termios.B115200
596 attr[5] = termios.B115200
597 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800598
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800599 nonlocals = {'control_state': None, 'control_str': ''}
600
601 def _ProcessBuffer(buf):
602 write_buffer = ''
603 while buf:
604 if nonlocals['control_state']:
605 if chr(_CONTROL_END) in buf:
606 index = buf.index(chr(_CONTROL_END))
607 nonlocals['control_str'] += buf[:index]
608 self.HandleTTYControl(fd, nonlocals['control_str'])
609 nonlocals['control_state'] = None
610 nonlocals['control_str'] = ''
611 buf = buf[index+1:]
612 else:
613 nonlocals['control_str'] += buf
614 buf = ''
615 else:
616 if chr(_CONTROL_START) in buf:
617 nonlocals['control_state'] = _CONTROL_START
618 index = buf.index(chr(_CONTROL_START))
619 write_buffer += buf[:index]
620 buf = buf[index+1:]
621 else:
622 write_buffer += buf
623 buf = ''
624
625 if write_buffer:
626 os.write(fd, write_buffer)
627
628 _ProcessBuffer(self._sock.RecvBuf())
629
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800630 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800631 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800632
633 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800634 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800635
636 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800637 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800638 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800639 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800640 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800641 except Exception as e:
642 logging.error('SpawnTTYServer: %s', e)
643 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800644 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800645
646 logging.info('SpawnTTYServer: terminated')
647 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800648
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800649 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800650 """Spawn a shell server and forward input/output from/to the TCP socket."""
651 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800652
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800653 # Add ghost executable to PATH
654 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
655 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800656 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800657
658 # Execute shell command from HOME directory
659 os.chdir(os.getenv('HOME', '/tmp'))
660
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800661 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800662 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800663 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800664
665 def make_non_block(fd):
666 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
667 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
668
669 make_non_block(p.stdout)
670 make_non_block(p.stderr)
671
672 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800673 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800674
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800675 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800676 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800677 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800678 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800679 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800680
681 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800682 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800683
684 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800685 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800686 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800687 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800688
689 try:
690 idx = ret.index(_STDIN_CLOSED * 2)
691 p.stdin.write(ret[:idx])
692 p.stdin.close()
693 except ValueError:
694 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800695 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800696 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800697 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800698 except Exception as e:
699 logging.error('SpawnShellServer: %s', e)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800700 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800701 # Check if the process is terminated. If not, Send SIGTERM to process,
702 # then wait for 1 second. Send another SIGKILL to make sure the process is
703 # terminated.
704 p.poll()
705 if p.returncode is None:
706 try:
707 p.terminate()
708 time.sleep(1)
709 p.kill()
710 except Exception:
711 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800712
713 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800714 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800715
716 logging.info('SpawnShellServer: terminated')
717 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800718
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800719 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800720 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800721 try:
722 size = os.stat(self._file_op[1]).st_size
723 except OSError as e:
724 logging.error('InitiateFileOperation: download: %s', e)
725 sys.exit(1)
726
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800727 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800728 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800729 'filename': os.path.basename(self._file_op[1]),
730 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800731 elif self._file_op[0] == 'upload':
732 self.SendRequest('clear_to_upload', {}, timeout=-1)
733 self.StartUploadServer()
734 else:
735 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800736
737 def StartDownloadServer(self):
738 logging.info('StartDownloadServer: started')
739
740 try:
741 with open(self._file_op[1], 'rb') as f:
742 while True:
743 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800744 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800745 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800746 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800747 except Exception as e:
748 logging.error('StartDownloadServer: %s', e)
749 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800750 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800751
752 logging.info('StartDownloadServer: terminated')
753 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800754
Wei-Ning Huange2981862015-08-03 15:03:08 +0800755 def StartUploadServer(self):
756 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800757 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800758 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800759 dirname = os.path.dirname(filepath)
760 if not os.path.exists(dirname):
761 try:
762 os.makedirs(dirname)
763 except Exception:
764 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800765
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800766 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800767 if self._file_op[2]:
768 os.fchmod(f.fileno(), self._file_op[2])
769
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800770 f.write(self._sock.RecvBuf())
771
Wei-Ning Huange2981862015-08-03 15:03:08 +0800772 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800773 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800774 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800775 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800776 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800777 break
778 f.write(buf)
779 except socket.error as e:
780 logging.error('StartUploadServer: socket error: %s', e)
781 except Exception as e:
782 logging.error('StartUploadServer: %s', e)
783 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800784 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800785
786 logging.info('StartUploadServer: terminated')
787 sys.exit(0)
788
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800789 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800790 """Spawn a port forwarding server and forward I/O to the TCP socket."""
791 logging.info('SpawnPortForwardServer: started')
792
793 src_sock = None
794 try:
795 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800796 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800797 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800798
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800799 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800800
801 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800802 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800803
804 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800805 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800806 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800807 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800808 src_sock.send(data)
809
810 if src_sock in rd:
811 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800812 if not data:
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800813 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800814 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800815 except Exception as e:
816 logging.error('SpawnPortForwardServer: %s', e)
817 finally:
818 if src_sock:
819 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800820 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800821
822 logging.info('SpawnPortForwardServer: terminated')
823 sys.exit(0)
824
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800825 def Ping(self):
826 def timeout_handler(x):
827 if x is None:
828 raise PingTimeoutError
829
830 self._last_ping = self.Timestamp()
831 self.SendRequest('ping', {}, timeout_handler, 5)
832
Wei-Ning Huangae923642015-09-24 14:08:09 +0800833 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800834 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800835 filepath = params['filename']
836 if not os.path.isabs(filepath):
837 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
838
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800839 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800840 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800841 pass
842 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800843 self.SendResponse(msg, str(e))
844 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800845
846 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800847 file_op=('download', filepath))
848 self.SendResponse(msg, SUCCESS)
849
850 def HandleFileUploadRequest(self, msg):
851 params = msg['params']
852
853 # Resolve upload filepath
854 filename = params['filename']
855 dest_path = filename
856
857 # If dest is specified, use it first
858 dest_path = params.get('dest', '')
859 if dest_path:
860 if not os.path.isabs(dest_path):
861 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
862
863 if os.path.isdir(dest_path):
864 dest_path = os.path.join(dest_path, filename)
865 else:
866 target_dir = os.getenv('HOME', '/tmp')
867
868 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800869 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800870 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
871 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800872 try:
873 target_dir = self.GetProcessWorkingDirectory(pid)
874 except Exception as e:
875 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800876
877 dest_path = os.path.join(target_dir, filename)
878
879 try:
880 os.makedirs(os.path.dirname(dest_path))
881 except Exception:
882 pass
883
884 try:
885 with open(dest_path, 'w') as _:
886 pass
887 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800888 self.SendResponse(msg, str(e))
889 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800890
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800891 # If not check_only, spawn FILE mode ghost agent to handle upload
892 if not params.get('check_only', False):
893 self.SpawnGhost(self.FILE, params['sid'],
894 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800895 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800896
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800897 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800898 command = msg['name']
899 params = msg['params']
900
901 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800902 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800903 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800904 self.SpawnGhost(self.TERMINAL, params['sid'],
905 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800906 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800907 elif command == 'shell':
908 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800909 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800910 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800911 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800912 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800913 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800914 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800915 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800916 elif command == 'forward':
917 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
918 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800919
920 def HandleResponse(self, response):
921 rid = str(response['rid'])
922 if rid in self._requests:
923 handler = self._requests[rid][2]
924 del self._requests[rid]
925 if callable(handler):
926 handler(response)
927 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800928 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800929
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800930 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800931 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800932 try:
933 index = buf.index(_SEPARATOR)
934 except ValueError:
935 self._sock.UnRecv(buf)
936 return
937
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800938 msgs_json = [buf[:index]]
939 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800940 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800941 msgs_json = buf.split(_SEPARATOR)
942 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800943
944 for msg_json in msgs_json:
945 try:
946 msg = json.loads(msg_json)
947 except ValueError:
948 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800949 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800950 continue
951
952 if 'name' in msg:
953 self.HandleRequest(msg)
954 elif 'response' in msg:
955 self.HandleResponse(msg)
956 else: # Ingnore 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
959 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800960 """Scans for pending requests which have timed out.
961
962 If any timed-out requests are discovered, their handler is called with the
963 special response value of None.
964 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800965 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800966 request_time, timeout, handler = self._requests[rid]
967 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800968 if callable(handler):
969 handler(None)
970 else:
971 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800972 del self._requests[rid]
973
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800974 def InitiateDownload(self):
975 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800976 sid = self._ttyname_to_sid[ttyname]
977 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800978 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800979
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800980 def Listen(self):
981 try:
982 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800983 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800984 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800985
986 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800987 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800988
989 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +0800990 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800991 break
992
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800993 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800994
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800995 if (self._mode == self.AGENT and
996 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800997 self.Ping()
998 self.ScanForTimeoutRequests()
999
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001000 if not self._download_queue.empty():
1001 self.InitiateDownload()
1002
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001003 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001004 break
1005 except socket.error:
1006 raise RuntimeError('Connection dropped')
1007 except PingTimeoutError:
1008 raise RuntimeError('Connection timeout')
1009 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001010 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001011
1012 self._queue.put('resume')
1013
1014 if self._mode != Ghost.AGENT:
1015 sys.exit(1)
1016
1017 def Register(self):
1018 non_local = {}
1019 for addr in self._overlord_addrs:
1020 non_local['addr'] = addr
1021 def registered(response):
1022 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001023 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001024 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001025
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001026 self._register_status = response['response']
1027 if response['response'] != SUCCESS:
1028 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001029 raise RuntimeError('Register: ' + response['response'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001030 else:
1031 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1032 self._connected_addr = non_local['addr']
1033 self.Upgrade() # Check for upgrade
1034 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001035
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001036 try:
1037 logging.info('Trying %s:%d ...', *addr)
1038 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001039
Peter Shih220a96d2016-12-22 17:02:16 +08001040 # Check if server has TLS enabled. Only check if self._tls_mode is
1041 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001042 # Only control channel needs to determine if TLS is enabled. Other mode
1043 # should use the TLSSettings passed in when it was spawned.
1044 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001045 self._tls_settings.SetEnabled(
1046 self.TLSEnabled(*addr) if self._tls_mode is None
1047 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001048
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001049 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1050 sock.settimeout(_CONNECT_TIMEOUT)
1051
1052 try:
1053 if self._tls_settings.Enabled():
1054 tls_context = self._tls_settings.Context()
1055 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1056
1057 sock.connect(addr)
1058 except (ssl.SSLError, ssl.CertificateError) as e:
1059 logging.error('%s: %s', e.__class__.__name__, e)
1060 continue
1061 except IOError as e:
1062 if e.errno == 2: # No such file or directory
1063 logging.error('%s: %s', e.__class__.__name__, e)
1064 continue
1065 raise
1066
1067 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001068
1069 logging.info('Connection established, registering...')
1070 handler = {
1071 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001072 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001073 Ghost.SHELL: self.SpawnShellServer,
1074 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001075 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001076 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001077
1078 # Machine ID may change if MAC address is used (USB-ethernet dongle
1079 # plugged/unplugged)
1080 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001081 self.SendRequest('register',
1082 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001083 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001084 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001085 except socket.error:
1086 pass
1087 else:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001088 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001089 self.Listen()
1090
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001091 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001092
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001093 def Reconnect(self):
1094 logging.info('Received reconnect request from RPC server, reconnecting...')
1095 self._reset.set()
1096
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001097 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001098 status = self._register_status
1099 if self._register_status == SUCCESS:
1100 ip, port = self._sock.sock.getpeername()
1101 status += ' %s:%d' % (ip, port)
1102 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001103
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001104 def AddToDownloadQueue(self, ttyname, filename):
1105 self._download_queue.put((ttyname, filename))
1106
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001107 def RegisterTTY(self, session_id, ttyname):
1108 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001109
1110 def RegisterSession(self, session_id, process_id):
1111 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001112
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001113 def StartLanDiscovery(self):
1114 """Start to listen to LAN discovery packet at
1115 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001116
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001117 def thread_func():
1118 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1119 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1120 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001121 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001122 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1123 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001124 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001125 return
1126
1127 logging.info('LAN Discovery: started')
1128 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001129 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001130
1131 if s in rd:
1132 data, source_addr = s.recvfrom(_BUFSIZE)
1133 parts = data.split()
1134 if parts[0] == 'OVERLORD':
1135 ip, port = parts[1].split(':')
1136 if not ip:
1137 ip = source_addr[0]
1138 self._queue.put((ip, int(port)), True)
1139
1140 try:
1141 obj = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001142 except queue.Empty:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001143 pass
1144 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001145 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001146 self._queue.put(obj)
1147 elif obj == 'pause':
1148 logging.info('LAN Discovery: paused')
1149 while obj != 'resume':
1150 obj = self._queue.get(True)
1151 logging.info('LAN Discovery: resumed')
1152
1153 t = threading.Thread(target=thread_func)
1154 t.daemon = True
1155 t.start()
1156
1157 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001158 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001159 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1160 logRequests=False)
1161 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001162 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001163 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001164 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001165 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001166 t = threading.Thread(target=rpc_server.serve_forever)
1167 t.daemon = True
1168 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001169
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001170 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001171 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001172 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1173 if addr not in self._overlord_addrs:
1174 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001175
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001176 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001177 logging.info('%s started', self.MODE_NAME[self._mode])
1178 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001179 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001180
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001181 # We don't care about child process's return code, not wait is needed. This
1182 # is used to prevent zombie process from lingering in the system.
1183 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001184
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001185 if lan_disc:
1186 self.StartLanDiscovery()
1187
1188 if rpc_server:
1189 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001190
1191 try:
1192 while True:
1193 try:
1194 addr = self._queue.get(False)
Yilin Yang8b7f5192020-01-08 11:43:00 +08001195 except queue.Empty:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001196 pass
1197 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001198 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001199 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1200 self._overlord_addrs.append(addr)
1201
1202 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001203 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001204 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001205 # Don't show stack trace for RuntimeError, which we use in this file for
1206 # plausible and expected errors (such as can't connect to server).
1207 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001208 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001209 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001210 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001211 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001212 traceback.print_tb(exc_traceback)
1213 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001214 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001215 time.sleep(_RETRY_INTERVAL)
1216
1217 self.Reset()
1218 except KeyboardInterrupt:
1219 logging.error('Received keyboard interrupt, quit')
1220 sys.exit(0)
1221
1222
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001223def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001224 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001225 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1226
1227
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001228def ForkToBackground():
1229 """Fork process to run in background."""
1230 pid = os.fork()
1231 if pid != 0:
1232 logging.info('Ghost(%d) running in background.', pid)
1233 sys.exit(0)
1234
1235
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001236def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001237 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001238 filepath = os.path.abspath(filename)
1239 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001240 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001241 sys.exit(1)
1242
1243 # Check if we actually have permission to read the file
1244 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001245 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001246 sys.exit(1)
1247
1248 server = GhostRPCServer()
1249 server.AddToDownloadQueue(os.ttyname(0), filepath)
1250 sys.exit(0)
1251
1252
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001253def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001254 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001255 logger = logging.getLogger()
1256 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001257 handler = logging.StreamHandler()
1258 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1259 handler.setFormatter(formatter)
1260 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001261
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001262 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001263 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1264 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001265 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1266 default=None, help='use MID as machine ID')
1267 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1268 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001269 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1270 default=True, help='disable LAN discovery')
1271 parser.add_argument('--no-rpc-server', dest='rpc_server',
1272 action='store_false', default=True,
1273 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001274 parser.add_argument('--tls', dest='tls_mode', default='detect',
1275 choices=('y', 'n', 'detect'),
1276 help="specify 'y' or 'n' to force enable/disable TLS")
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001277 parser.add_argument('--tls-cert-file', metavar='TLS_CERT_FILE',
1278 dest='tls_cert_file', type=str, default=None,
1279 help='file containing the server TLS certificate in PEM '
1280 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001281 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1282 action='store_true', default=False,
1283 help='do not verify certificate if TLS is enabled')
Joel Kitching22b89042015-08-06 18:23:29 +08001284 parser.add_argument('--prop-file', metavar='PROP_FILE', dest='prop_file',
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001285 type=str, default=None,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001286 help='file containing the JSON representation of client '
1287 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001288 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1289 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001290 parser.add_argument('--reset', dest='reset', default=False,
1291 action='store_true',
1292 help='reset ghost and reload all configs')
Peter Shih5cafebb2017-06-30 16:36:22 +08001293 parser.add_argument('--status', dest='status', default=False,
1294 action='store_true',
1295 help='show status of the client')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001296 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str,
1297 nargs='*', help='overlord server address')
1298 args = parser.parse_args()
1299
Peter Shih5cafebb2017-06-30 16:36:22 +08001300 if args.status:
1301 print(GhostRPCServer().GetStatus())
1302 sys.exit()
1303
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001304 if args.fork:
1305 ForkToBackground()
1306
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001307 if args.reset:
1308 GhostRPCServer().Reconnect()
1309 sys.exit()
1310
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001311 if args.download:
1312 DownloadFile(args.download)
1313
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001314 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001315 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001316
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001317 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1318
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001319 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001320 tls_mode = args.tls_mode
1321 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001322 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001323 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001324 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001325
1326
1327if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001328 try:
1329 main()
1330 except Exception as e:
1331 logging.error(e)