blob: dba79d4268498a62f6896520ead4edd72b440abb [file] [log] [blame]
Mike Frysinger63bb3c72019-09-01 15:16:26 -04001#!/usr/bin/env python2
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
Wei-Ning Huang1cea6112015-03-02 12:45:34 +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
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080034import urllib2
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
Peter Shihc56c5b62016-12-22 12:30:57 +080041_GHOST_RPC_PORT = int(os.getenv('GHOST_RPC_PORT', 4499))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080042
Peter Shihc56c5b62016-12-22 12:30:57 +080043_OVERLORD_PORT = int(os.getenv('OVERLORD_PORT', 4455))
44_OVERLORD_LAN_DISCOVERY_PORT = int(os.getenv('OVERLORD_LD_PORT', 4456))
45_OVERLORD_HTTP_PORT = int(os.getenv('OVERLORD_HTTP_PORT', 9000))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080046
47_BUFSIZE = 8192
48_RETRY_INTERVAL = 2
49_SEPARATOR = '\r\n'
50_PING_TIMEOUT = 3
51_PING_INTERVAL = 5
52_REQUEST_TIMEOUT_SECS = 60
53_SHELL = os.getenv('SHELL', '/bin/bash')
Wei-Ning Huang7dbf4a72016-03-02 20:16:20 +080054_DEFAULT_BIND_ADDRESS = 'localhost'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080055
Moja Hsuc9ecc8b2015-07-13 11:39:17 +080056_CONTROL_START = 128
57_CONTROL_END = 129
58
Wei-Ning Huanga301f572015-06-03 17:34:21 +080059_BLOCK_SIZE = 4096
Wei-Ning Huange0def6a2015-11-05 15:41:24 +080060_CONNECT_TIMEOUT = 3
Wei-Ning Huanga301f572015-06-03 17:34:21 +080061
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +080062# Stream control
63_STDIN_CLOSED = '##STDIN_CLOSED##'
64
Wei-Ning Huang7ec55342015-09-17 08:46:06 +080065SUCCESS = 'success'
66FAILED = 'failed'
67DISCONNECTED = 'disconnected'
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080068
Joel Kitching22b89042015-08-06 18:23:29 +080069
Wei-Ning Huang1cea6112015-03-02 12:45:34 +080070class PingTimeoutError(Exception):
71 pass
72
73
74class RequestError(Exception):
75 pass
76
77
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080078class BufferedSocket(object):
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080079 """A buffered socket that supports unrecv.
80
81 Allow putting back data back to the socket for the next recv() call.
82 """
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080083 def __init__(self, sock):
84 self.sock = sock
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080085 self._buf = ''
86
Wei-Ning Huangf5311a02016-02-04 15:23:46 +080087 def fileno(self):
88 return self.sock.fileno()
89
Wei-Ning Huanga28cd232016-01-27 15:04:41 +080090 def Recv(self, bufsize, flags=0):
91 if self._buf:
92 if len(self._buf) >= bufsize:
93 ret = self._buf[:bufsize]
94 self._buf = self._buf[bufsize:]
95 return ret
Yilin Yang15a3f8f2020-01-03 17:49:00 +080096 ret = self._buf
97 self._buf = ''
98 return ret + self.sock.recv(bufsize - len(ret), flags)
99 return self.sock.recv(bufsize, flags)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800100
101 def UnRecv(self, buf):
102 self._buf = buf + self._buf
103
104 def Send(self, *args, **kwargs):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800105 return self.sock.send(*args, **kwargs)
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800106
107 def RecvBuf(self):
108 """Only recive from buffer."""
109 ret = self._buf
110 self._buf = ''
111 return ret
112
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800113 def Close(self):
114 self.sock.close()
115
116
117class TLSSettings(object):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800118 def __init__(self, tls_cert_file, verify):
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800119 """Constructor.
120
121 Args:
122 tls_cert_file: TLS certificate in PEM format.
123 enable_tls_without_verify: enable TLS but don't verify certificate.
124 """
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800125 self._enabled = False
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800126 self._tls_cert_file = tls_cert_file
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800127 self._verify = verify
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800128 self._tls_context = None
129
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800130 def _UpdateContext(self):
131 if not self._enabled:
132 self._tls_context = None
133 return
134
135 self._tls_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
136 self._tls_context.verify_mode = ssl.CERT_REQUIRED
137
138 if self._verify:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800139 if self._tls_cert_file:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800140 self._tls_context.check_hostname = True
141 try:
142 self._tls_context.load_verify_locations(self._tls_cert_file)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800143 logging.info('TLSSettings: using user-supplied ca-certificate')
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800144 except IOError as e:
145 logging.error('TLSSettings: %s: %s', self._tls_cert_file, e)
146 sys.exit(1)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800147 else:
148 self._tls_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
149 logging.info('TLSSettings: using built-in ca-certificates')
150 else:
151 self._tls_context.verify_mode = ssl.CERT_NONE
152 logging.info('TLSSettings: skipping TLS verification!!!')
153
154 def SetEnabled(self, enabled):
155 logging.info('TLSSettings: enabled: %s', enabled)
156
157 if self._enabled != enabled:
158 self._enabled = enabled
159 self._UpdateContext()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800160
161 def Enabled(self):
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800162 return self._enabled
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800163
164 def Context(self):
165 return self._tls_context
166
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800167
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800168class Ghost(object):
169 """Ghost implements the client protocol of Overlord.
170
171 Ghost provide terminal/shell/logcat functionality and manages the client
172 side connectivity.
173 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800174 NONE, AGENT, TERMINAL, SHELL, LOGCAT, FILE, FORWARD = range(7)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800175
176 MODE_NAME = {
177 NONE: 'NONE',
178 AGENT: 'Agent',
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800179 TERMINAL: 'Terminal',
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800180 SHELL: 'Shell',
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800181 LOGCAT: 'Logcat',
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800182 FILE: 'File',
183 FORWARD: 'Forward'
Peter Shihe6afab32018-09-11 17:16:48 +0800184 }
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800185
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800186 RANDOM_MID = '##random_mid##'
187
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800188 def __init__(self, overlord_addrs, tls_settings=None, mode=AGENT, mid=None,
189 sid=None, prop_file=None, terminal_sid=None, tty_device=None,
Peter Shih220a96d2016-12-22 17:02:16 +0800190 command=None, file_op=None, port=None, tls_mode=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800191 """Constructor.
192
193 Args:
194 overlord_addrs: a list of possible address of overlord.
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800195 tls_settings: a TLSSetting object.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800196 mode: client mode, either AGENT, SHELL or LOGCAT
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800197 mid: a str to set for machine ID. If mid equals Ghost.RANDOM_MID, machine
198 id is randomly generated.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800199 sid: session ID. If the connection is requested by overlord, sid should
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800200 be set to the corresponding session id assigned by overlord.
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800201 prop_file: properties file filename.
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800202 terminal_sid: the terminal session ID associate with this client. This is
203 use for file download.
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800204 tty_device: the terminal device to open, if tty_device is None, as pseudo
205 terminal will be opened instead.
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800206 command: the command to execute when we are in SHELL mode.
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800207 file_op: a tuple (action, filepath, perm). action is either 'download' or
208 'upload'. perm is the permission to set for the file.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800209 port: port number to forward.
Peter Shih220a96d2016-12-22 17:02:16 +0800210 tls_mode: can be [True, False, None]. if not None, skip detection of
211 TLS and assume whether server use TLS or not.
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800212 """
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800213 assert mode in [Ghost.AGENT, Ghost.TERMINAL, Ghost.SHELL, Ghost.FILE,
214 Ghost.FORWARD]
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800215 if mode == Ghost.SHELL:
216 assert command is not None
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800217 if mode == Ghost.FILE:
218 assert file_op is not None
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800219
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800220 self._platform = platform.system()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800221 self._overlord_addrs = overlord_addrs
Wei-Ning Huangad330c52015-03-12 20:34:18 +0800222 self._connected_addr = None
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800223 self._tls_settings = tls_settings
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +0800224 self._mid = mid
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800225 self._sock = None
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800226 self._mode = mode
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800227 self._machine_id = self.GetMachineID()
Wei-Ning Huangfed95862015-08-07 03:17:11 +0800228 self._session_id = sid if sid is not None else str(uuid.uuid4())
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800229 self._terminal_session_id = terminal_sid
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800230 self._ttyname_to_sid = {}
231 self._terminal_sid_to_pid = {}
232 self._prop_file = prop_file
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800233 self._properties = {}
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800234 self._register_status = DISCONNECTED
235 self._reset = threading.Event()
Peter Shih220a96d2016-12-22 17:02:16 +0800236 self._tls_mode = tls_mode
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800237
238 # RPC
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800239 self._requests = {}
240 self._queue = Queue.Queue()
241
242 # Protocol specific
243 self._last_ping = 0
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800244 self._tty_device = tty_device
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800245 self._shell_command = command
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800246 self._file_op = file_op
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800247 self._download_queue = Queue.Queue()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800248 self._port = port
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800249
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800250 def SetIgnoreChild(self, status):
251 # Only ignore child for Agent since only it could spawn child Ghost.
252 if self._mode == Ghost.AGENT:
253 signal.signal(signal.SIGCHLD,
254 signal.SIG_IGN if status else signal.SIG_DFL)
255
256 def GetFileSha1(self, filename):
257 with open(filename, 'r') as f:
258 return hashlib.sha1(f.read()).hexdigest()
259
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800260 def TLSEnabled(self, host, port):
261 """Determine if TLS is enabled on given server address."""
Wei-Ning Huang58833882015-09-16 16:52:37 +0800262 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
263 try:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800264 # Allow any certificate since we only want to check if server talks TLS.
265 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
266 context.verify_mode = ssl.CERT_NONE
Wei-Ning Huang58833882015-09-16 16:52:37 +0800267
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800268 sock = context.wrap_socket(sock, server_hostname=host)
269 sock.settimeout(_CONNECT_TIMEOUT)
270 sock.connect((host, port))
271 return True
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800272 except ssl.SSLError:
273 return False
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800274 except socket.error: # Connect refused or timeout
275 raise
Wei-Ning Huang58833882015-09-16 16:52:37 +0800276 except Exception:
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800277 return False # For whatever reason above failed, assume False
Wei-Ning Huang58833882015-09-16 16:52:37 +0800278
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800279 def Upgrade(self):
280 logging.info('Upgrade: initiating upgrade sequence...')
281
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800282 try:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800283 https_enabled = self.TLSEnabled(self._connected_addr[0],
284 _OVERLORD_HTTP_PORT)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800285 except socket.error:
Wei-Ning Huangb6605d22016-06-22 17:33:37 +0800286 logging.error('Upgrade: failed to connect to Overlord HTTP server, '
287 'abort')
288 return
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800289
290 if self._tls_settings.Enabled() and not https_enabled:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800291 logging.error('Upgrade: TLS enforced but found Overlord HTTP server '
292 'without TLS enabled! Possible mis-configuration or '
293 'DNS/IP spoofing detected, abort')
294 return
295
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800296 scriptpath = os.path.abspath(sys.argv[0])
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800297 url = 'http%s://%s:%d/upgrade/ghost.py' % (
Wei-Ning Huang47c79b82016-05-24 01:24:46 +0800298 's' if https_enabled else '', self._connected_addr[0],
Wei-Ning Huang03f9f762015-09-16 21:51:35 +0800299 _OVERLORD_HTTP_PORT)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800300
301 # Download sha1sum for ghost.py for verification
302 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800303 with contextlib.closing(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800304 urllib2.urlopen(url + '.sha1', timeout=_CONNECT_TIMEOUT,
305 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800306 if f.getcode() != 200:
307 raise RuntimeError('HTTP status %d' % f.getcode())
308 sha1sum = f.read().strip()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800309 except (ssl.SSLError, ssl.CertificateError) as e:
310 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
311 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800312 except Exception:
313 logging.error('Upgrade: failed to download sha1sum file, abort')
314 return
315
316 if self.GetFileSha1(scriptpath) == sha1sum:
317 logging.info('Upgrade: ghost is already up-to-date, skipping upgrade')
318 return
319
320 # Download upgrade version of ghost.py
321 try:
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800322 with contextlib.closing(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800323 urllib2.urlopen(url, timeout=_CONNECT_TIMEOUT,
324 context=self._tls_settings.Context())) as f:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800325 if f.getcode() != 200:
326 raise RuntimeError('HTTP status %d' % f.getcode())
327 data = f.read()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800328 except (ssl.SSLError, ssl.CertificateError) as e:
329 logging.error('Upgrade: %s: %s', e.__class__.__name__, e)
330 return
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800331 except Exception:
332 logging.error('Upgrade: failed to download upgrade, abort')
333 return
334
335 # Compare SHA1 sum
336 if hashlib.sha1(data).hexdigest() != sha1sum:
337 logging.error('Upgrade: sha1sum mismatch, abort')
338 return
339
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800340 try:
341 with open(scriptpath, 'w') as f:
342 f.write(data)
343 except Exception:
344 logging.error('Upgrade: failed to write upgrade onto disk, abort')
345 return
346
347 logging.info('Upgrade: restarting ghost...')
348 self.CloseSockets()
349 self.SetIgnoreChild(False)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800350 os.execve(scriptpath, [scriptpath] + sys.argv[1:], os.environ)
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800351
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800352 def LoadProperties(self):
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800353 try:
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800354 if self._prop_file:
355 with open(self._prop_file, 'r') as f:
356 self._properties = json.loads(f.read())
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800357 except Exception as e:
Peter Shih769b0772018-02-26 14:44:28 +0800358 logging.error('LoadProperties: %s', e)
Wei-Ning Huang7d029b12015-03-06 10:32:15 +0800359
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800360 def CloseSockets(self):
361 # Close sockets opened by parent process, since we don't use it anymore.
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800362 if self._platform == 'Linux':
363 for fd in os.listdir('/proc/self/fd/'):
364 try:
365 real_fd = os.readlink('/proc/self/fd/%s' % fd)
366 if real_fd.startswith('socket'):
367 os.close(int(fd))
368 except Exception:
369 pass
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800370
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800371 def SpawnGhost(self, mode, sid=None, terminal_sid=None, tty_device=None,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800372 command=None, file_op=None, port=None):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800373 """Spawn a child ghost with specific mode.
374
375 Returns:
376 The spawned child process pid.
377 """
Joel Kitching22b89042015-08-06 18:23:29 +0800378 # Restore the default signal handler, so our child won't have problems.
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800379 self.SetIgnoreChild(False)
380
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800381 pid = os.fork()
382 if pid == 0:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800383 self.CloseSockets()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800384 g = Ghost([self._connected_addr], tls_settings=self._tls_settings,
385 mode=mode, mid=Ghost.RANDOM_MID, sid=sid,
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800386 terminal_sid=terminal_sid, tty_device=tty_device,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800387 command=command, file_op=file_op, port=port)
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800388 g.Start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800389 sys.exit(0)
390 else:
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800391 self.SetIgnoreChild(True)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800392 return pid
393
394 def Timestamp(self):
395 return int(time.time())
396
397 def GetGateWayIP(self):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800398 if self._platform == 'Darwin':
399 output = subprocess.check_output(['route', '-n', 'get', 'default'])
400 ret = re.search('gateway: (.*)', output)
401 if ret:
402 return [ret.group(1)]
Peter Shiha78867d2018-02-26 14:17:51 +0800403 return []
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800404 elif self._platform == 'Linux':
405 with open('/proc/net/route', 'r') as f:
406 lines = f.readlines()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800407
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800408 ips = []
409 for line in lines:
410 parts = line.split('\t')
411 if parts[2] == '00000000':
412 continue
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800413
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800414 try:
Yilin Yangf9fe1932019-11-04 17:09:34 +0800415 h = codecs.decode(parts[2], 'hex')
416 # TODO(kerker) Remove when py3 upgrade complete
417 if PY2:
418 ips.append('%d.%d.%d.%d' % tuple(ord(x) for x in reversed(h)))
419 else:
420 ips.append('.'.join([str(x) for x in reversed(h)]))
421 except (TypeError, binascii.Error):
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800422 pass
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800423
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800424 return ips
425 else:
426 logging.warning('GetGateWayIP: unsupported platform')
427 return []
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800428
Hung-Te Lin41ff8f32017-08-30 08:10:39 +0800429 def GetFactoryServerIP(self):
Wei-Ning Huang829e0c82015-05-26 14:37:23 +0800430 try:
Peter Shihcb0e5512017-06-14 16:59:46 +0800431 import factory_common # pylint: disable=unused-variable
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:
Peter Shihcb0e5512017-06-14 16:59:46 +0800470 import factory_common # pylint: disable=unused-variable
Hung-Te Linda8eb992017-09-28 03:27:12 +0800471 from cros.factory.test import session
472 return session.GetDeviceID()
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800473 except Exception:
474 pass
475
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800476 # Try DMI product UUID
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800477 try:
478 with open('/sys/class/dmi/id/product_uuid', 'r') as f:
479 return f.read().strip()
480 except Exception:
481 pass
482
Wei-Ning Huang1d7603b2015-07-03 17:38:56 +0800483 # Use MAC address if non is available
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800484 try:
485 macs = []
486 ifaces = sorted(os.listdir('/sys/class/net'))
487 for iface in ifaces:
488 if iface == 'lo':
489 continue
490
491 with open('/sys/class/net/%s/address' % iface, 'r') as f:
492 macs.append(f.read().strip())
493
494 return ';'.join(macs)
495 except Exception:
496 pass
497
Peter Shihcb0e5512017-06-14 16:59:46 +0800498 raise RuntimeError("can't generate machine ID")
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800499
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800500 def GetProcessWorkingDirectory(self, pid):
501 if self._platform == 'Linux':
502 return os.readlink('/proc/%d/cwd' % pid)
503 elif self._platform == 'Darwin':
504 PROC_PIDVNODEPATHINFO = 9
505 proc_vnodepathinfo_size = 2352
506 vid_path_offset = 152
507
508 proc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libproc'))
509 buf = ctypes.create_string_buffer('\0' * proc_vnodepathinfo_size)
510 proc.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0,
511 ctypes.byref(buf), proc_vnodepathinfo_size)
512 buf = buf.raw[vid_path_offset:]
513 n = buf.index('\0')
514 return buf[:n]
515 else:
516 raise RuntimeError('GetProcessWorkingDirectory: unsupported platform')
517
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800518 def Reset(self):
519 """Reset state and clear request handlers."""
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800520 if self._sock is not None:
521 self._sock.Close()
522 self._sock = None
Wei-Ning Huang2132de32015-04-13 17:24:38 +0800523 self._reset.clear()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800524 self._last_ping = 0
525 self._requests = {}
Wei-Ning Huang23ed0162015-09-18 14:42:03 +0800526 self.LoadProperties()
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800527 self._register_status = DISCONNECTED
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800528
529 def SendMessage(self, msg):
530 """Serialize the message and send it through the socket."""
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800531 self._sock.Send(json.dumps(msg) + _SEPARATOR)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800532
533 def SendRequest(self, name, args, handler=None,
534 timeout=_REQUEST_TIMEOUT_SECS):
535 if handler and not callable(handler):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800536 raise RequestError('Invalid request handler for msg "%s"' % name)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800537
538 rid = str(uuid.uuid4())
539 msg = {'rid': rid, 'timeout': timeout, 'name': name, 'params': args}
Wei-Ning Huange2981862015-08-03 15:03:08 +0800540 if timeout >= 0:
541 self._requests[rid] = [self.Timestamp(), timeout, handler]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800542 self.SendMessage(msg)
543
544 def SendResponse(self, omsg, status, params=None):
545 msg = {'rid': omsg['rid'], 'response': status, 'params': params}
546 self.SendMessage(msg)
547
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800548 def HandleTTYControl(self, fd, control_str):
549 msg = json.loads(control_str)
Moja Hsuc9ecc8b2015-07-13 11:39:17 +0800550 command = msg['command']
551 params = msg['params']
552 if command == 'resize':
553 # some error happened on websocket
554 if len(params) != 2:
555 return
556 winsize = struct.pack('HHHH', params[0], params[1], 0, 0)
557 fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
558 else:
559 logging.warn('Invalid request command "%s"', command)
560
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800561 def SpawnTTYServer(self, unused_var):
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800562 """Spawn a TTY server and forward I/O to the TCP socket."""
563 logging.info('SpawnTTYServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800564
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800565 try:
566 if self._tty_device is None:
567 pid, fd = os.forkpty()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800568
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800569 if pid == 0:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800570 ttyname = os.ttyname(sys.stdout.fileno())
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800571 try:
572 server = GhostRPCServer()
573 server.RegisterTTY(self._session_id, ttyname)
574 server.RegisterSession(self._session_id, os.getpid())
575 except Exception:
576 # If ghost is launched without RPC server, the call will fail but we
577 # can ignore it.
578 pass
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800579
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800580 # The directory that contains the current running ghost script
581 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800582
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800583 env = os.environ.copy()
584 env['USER'] = os.getenv('USER', 'root')
585 env['HOME'] = os.getenv('HOME', '/root')
586 env['PATH'] = os.getenv('PATH') + ':%s' % script_dir
587 os.chdir(env['HOME'])
588 os.execve(_SHELL, [_SHELL], env)
589 else:
590 fd = os.open(self._tty_device, os.O_RDWR)
Wei-Ning Huang39169902015-09-19 06:00:23 +0800591 tty.setraw(fd)
592 attr = termios.tcgetattr(fd)
593 attr[0] &= ~(termios.IXON | termios.IXOFF)
594 attr[2] |= termios.CLOCAL
595 attr[2] &= ~termios.CRTSCTS
596 attr[4] = termios.B115200
597 attr[5] = termios.B115200
598 termios.tcsetattr(fd, termios.TCSANOW, attr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800599
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800600 nonlocals = {'control_state': None, 'control_str': ''}
601
602 def _ProcessBuffer(buf):
603 write_buffer = ''
604 while buf:
605 if nonlocals['control_state']:
606 if chr(_CONTROL_END) in buf:
607 index = buf.index(chr(_CONTROL_END))
608 nonlocals['control_str'] += buf[:index]
609 self.HandleTTYControl(fd, nonlocals['control_str'])
610 nonlocals['control_state'] = None
611 nonlocals['control_str'] = ''
612 buf = buf[index+1:]
613 else:
614 nonlocals['control_str'] += buf
615 buf = ''
616 else:
617 if chr(_CONTROL_START) in buf:
618 nonlocals['control_state'] = _CONTROL_START
619 index = buf.index(chr(_CONTROL_START))
620 write_buffer += buf[:index]
621 buf = buf[index+1:]
622 else:
623 write_buffer += buf
624 buf = ''
625
626 if write_buffer:
627 os.write(fd, write_buffer)
628
629 _ProcessBuffer(self._sock.RecvBuf())
630
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800631 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800632 rd, unused_wd, unused_xd = select.select([self._sock, fd], [], [])
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800633
634 if fd in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800635 self._sock.Send(os.read(fd, _BUFSIZE))
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800636
637 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800638 buf = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800639 if not buf:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800640 raise RuntimeError('connection terminated')
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800641 _ProcessBuffer(buf)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800642 except Exception as e:
643 logging.error('SpawnTTYServer: %s', e)
644 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800645 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800646
647 logging.info('SpawnTTYServer: terminated')
648 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800649
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800650 def SpawnShellServer(self, unused_var):
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800651 """Spawn a shell server and forward input/output from/to the TCP socket."""
652 logging.info('SpawnShellServer: started')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800653
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800654 # Add ghost executable to PATH
655 script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
656 env = os.environ.copy()
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800657 env['PATH'] = '%s:%s' % (script_dir, os.getenv('PATH'))
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800658
659 # Execute shell command from HOME directory
660 os.chdir(os.getenv('HOME', '/tmp'))
661
Wei-Ning Huang0f4a5372015-03-09 15:12:07 +0800662 p = subprocess.Popen(self._shell_command, stdin=subprocess.PIPE,
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800663 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800664 shell=True, env=env)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800665
666 def make_non_block(fd):
667 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
668 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
669
670 make_non_block(p.stdout)
671 make_non_block(p.stderr)
672
673 try:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800674 p.stdin.write(self._sock.RecvBuf())
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800675
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800676 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800677 rd, unused_wd, unused_xd = select.select(
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800678 [p.stdout, p.stderr, self._sock], [], [])
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800679 if p.stdout in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800680 self._sock.Send(p.stdout.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800681
682 if p.stderr in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800683 self._sock.Send(p.stderr.read(_BUFSIZE))
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800684
685 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800686 ret = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800687 if not ret:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800688 raise RuntimeError('connection terminated')
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800689
690 try:
691 idx = ret.index(_STDIN_CLOSED * 2)
692 p.stdin.write(ret[:idx])
693 p.stdin.close()
694 except ValueError:
695 p.stdin.write(ret)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800696 p.poll()
Peter Shihe6afab32018-09-11 17:16:48 +0800697 if p.returncode is not None:
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800698 break
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800699 except Exception as e:
700 logging.error('SpawnShellServer: %s', e)
Wei-Ning Huangf14c84e2015-08-03 15:03:08 +0800701 finally:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800702 # Check if the process is terminated. If not, Send SIGTERM to process,
703 # then wait for 1 second. Send another SIGKILL to make sure the process is
704 # terminated.
705 p.poll()
706 if p.returncode is None:
707 try:
708 p.terminate()
709 time.sleep(1)
710 p.kill()
711 except Exception:
712 pass
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800713
714 p.wait()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800715 self._sock.Close()
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800716
717 logging.info('SpawnShellServer: terminated')
718 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800719
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800720 def InitiateFileOperation(self, unused_var):
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800721 if self._file_op[0] == 'download':
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800722 try:
723 size = os.stat(self._file_op[1]).st_size
724 except OSError as e:
725 logging.error('InitiateFileOperation: download: %s', e)
726 sys.exit(1)
727
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800728 self.SendRequest('request_to_download',
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800729 {'terminal_sid': self._terminal_session_id,
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800730 'filename': os.path.basename(self._file_op[1]),
731 'size': size})
Wei-Ning Huange2981862015-08-03 15:03:08 +0800732 elif self._file_op[0] == 'upload':
733 self.SendRequest('clear_to_upload', {}, timeout=-1)
734 self.StartUploadServer()
735 else:
736 logging.error('InitiateFileOperation: unknown file operation, ignored')
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800737
738 def StartDownloadServer(self):
739 logging.info('StartDownloadServer: started')
740
741 try:
742 with open(self._file_op[1], 'rb') as f:
743 while True:
744 data = f.read(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800745 if not data:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800746 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800747 self._sock.Send(data)
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800748 except Exception as e:
749 logging.error('StartDownloadServer: %s', e)
750 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800751 self._sock.Close()
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800752
753 logging.info('StartDownloadServer: terminated')
754 sys.exit(0)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800755
Wei-Ning Huange2981862015-08-03 15:03:08 +0800756 def StartUploadServer(self):
757 logging.info('StartUploadServer: started')
Wei-Ning Huange2981862015-08-03 15:03:08 +0800758 try:
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800759 filepath = self._file_op[1]
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800760 dirname = os.path.dirname(filepath)
761 if not os.path.exists(dirname):
762 try:
763 os.makedirs(dirname)
764 except Exception:
765 pass
Wei-Ning Huange2981862015-08-03 15:03:08 +0800766
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800767 with open(filepath, 'wb') as f:
Wei-Ning Huang8ee3bcd2015-10-01 17:10:01 +0800768 if self._file_op[2]:
769 os.fchmod(f.fileno(), self._file_op[2])
770
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800771 f.write(self._sock.RecvBuf())
772
Wei-Ning Huange2981862015-08-03 15:03:08 +0800773 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800774 rd, unused_wd, unused_xd = select.select([self._sock], [], [])
Wei-Ning Huange2981862015-08-03 15:03:08 +0800775 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800776 buf = self._sock.Recv(_BLOCK_SIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800777 if not buf:
Wei-Ning Huange2981862015-08-03 15:03:08 +0800778 break
779 f.write(buf)
780 except socket.error as e:
781 logging.error('StartUploadServer: socket error: %s', e)
782 except Exception as e:
783 logging.error('StartUploadServer: %s', e)
784 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800785 self._sock.Close()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800786
787 logging.info('StartUploadServer: terminated')
788 sys.exit(0)
789
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800790 def SpawnPortForwardServer(self, unused_var):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800791 """Spawn a port forwarding server and forward I/O to the TCP socket."""
792 logging.info('SpawnPortForwardServer: started')
793
794 src_sock = None
795 try:
796 src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Wei-Ning Huange0def6a2015-11-05 15:41:24 +0800797 src_sock.settimeout(_CONNECT_TIMEOUT)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800798 src_sock.connect(('localhost', self._port))
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800799
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800800 src_sock.send(self._sock.RecvBuf())
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800801
802 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800803 rd, unused_wd, unused_xd = select.select([self._sock, src_sock], [], [])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800804
805 if self._sock in rd:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800806 data = self._sock.Recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800807 if not data:
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +0800808 raise RuntimeError('connection terminated')
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800809 src_sock.send(data)
810
811 if src_sock in rd:
812 data = src_sock.recv(_BUFSIZE)
Peter Shihaacbc2f2017-06-16 14:39:29 +0800813 if not data:
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800814 break
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800815 self._sock.Send(data)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800816 except Exception as e:
817 logging.error('SpawnPortForwardServer: %s', e)
818 finally:
819 if src_sock:
820 src_sock.close()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800821 self._sock.Close()
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800822
823 logging.info('SpawnPortForwardServer: terminated')
824 sys.exit(0)
825
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800826 def Ping(self):
827 def timeout_handler(x):
828 if x is None:
829 raise PingTimeoutError
830
831 self._last_ping = self.Timestamp()
832 self.SendRequest('ping', {}, timeout_handler, 5)
833
Wei-Ning Huangae923642015-09-24 14:08:09 +0800834 def HandleFileDownloadRequest(self, msg):
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800835 params = msg['params']
Wei-Ning Huangae923642015-09-24 14:08:09 +0800836 filepath = params['filename']
837 if not os.path.isabs(filepath):
838 filepath = os.path.join(os.getenv('HOME', '/tmp'), filepath)
839
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800840 try:
Wei-Ning Huang11c35022015-10-21 16:52:32 +0800841 with open(filepath, 'r') as _:
Wei-Ning Huang46a3fc92015-10-06 02:35:27 +0800842 pass
843 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800844 self.SendResponse(msg, str(e))
845 return
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800846
847 self.SpawnGhost(self.FILE, params['sid'],
Wei-Ning Huangae923642015-09-24 14:08:09 +0800848 file_op=('download', filepath))
849 self.SendResponse(msg, SUCCESS)
850
851 def HandleFileUploadRequest(self, msg):
852 params = msg['params']
853
854 # Resolve upload filepath
855 filename = params['filename']
856 dest_path = filename
857
858 # If dest is specified, use it first
859 dest_path = params.get('dest', '')
860 if dest_path:
861 if not os.path.isabs(dest_path):
862 dest_path = os.path.join(os.getenv('HOME', '/tmp'), dest_path)
863
864 if os.path.isdir(dest_path):
865 dest_path = os.path.join(dest_path, filename)
866 else:
867 target_dir = os.getenv('HOME', '/tmp')
868
869 # Terminal session ID found, upload to it's current working directory
Peter Shihe6afab32018-09-11 17:16:48 +0800870 if 'terminal_sid' in params:
Wei-Ning Huangae923642015-09-24 14:08:09 +0800871 pid = self._terminal_sid_to_pid.get(params['terminal_sid'], None)
872 if pid:
Wei-Ning Huanga0e55b82016-02-10 14:32:07 +0800873 try:
874 target_dir = self.GetProcessWorkingDirectory(pid)
875 except Exception as e:
876 logging.error(e)
Wei-Ning Huangae923642015-09-24 14:08:09 +0800877
878 dest_path = os.path.join(target_dir, filename)
879
880 try:
881 os.makedirs(os.path.dirname(dest_path))
882 except Exception:
883 pass
884
885 try:
886 with open(dest_path, 'w') as _:
887 pass
888 except Exception as e:
Peter Shiha78867d2018-02-26 14:17:51 +0800889 self.SendResponse(msg, str(e))
890 return
Wei-Ning Huangae923642015-09-24 14:08:09 +0800891
Wei-Ning Huangd6f69762015-10-01 21:02:07 +0800892 # If not check_only, spawn FILE mode ghost agent to handle upload
893 if not params.get('check_only', False):
894 self.SpawnGhost(self.FILE, params['sid'],
895 file_op=('upload', dest_path, params.get('perm', None)))
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800896 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang552cd702015-08-12 16:11:13 +0800897
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800898 def HandleRequest(self, msg):
Wei-Ning Huange2981862015-08-03 15:03:08 +0800899 command = msg['name']
900 params = msg['params']
901
902 if command == 'upgrade':
Wei-Ning Huangb05cde32015-08-01 09:48:41 +0800903 self.Upgrade()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800904 elif command == 'terminal':
Wei-Ning Huangb8461202015-09-01 20:07:41 +0800905 self.SpawnGhost(self.TERMINAL, params['sid'],
906 tty_device=params['tty_device'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800907 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800908 elif command == 'shell':
909 self.SpawnGhost(self.SHELL, params['sid'], command=params['command'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +0800910 self.SendResponse(msg, SUCCESS)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800911 elif command == 'file_download':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800912 self.HandleFileDownloadRequest(msg)
Wei-Ning Huange2981862015-08-03 15:03:08 +0800913 elif command == 'clear_to_download':
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800914 self.StartDownloadServer()
Wei-Ning Huange2981862015-08-03 15:03:08 +0800915 elif command == 'file_upload':
Wei-Ning Huangae923642015-09-24 14:08:09 +0800916 self.HandleFileUploadRequest(msg)
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800917 elif command == 'forward':
918 self.SpawnGhost(self.FORWARD, params['sid'], port=params['port'])
919 self.SendResponse(msg, SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800920
921 def HandleResponse(self, response):
922 rid = str(response['rid'])
923 if rid in self._requests:
924 handler = self._requests[rid][2]
925 del self._requests[rid]
926 if callable(handler):
927 handler(response)
928 else:
Joel Kitching22b89042015-08-06 18:23:29 +0800929 logging.warning('Received unsolicited response, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800930
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800931 def ParseMessage(self, buf, single=True):
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800932 if single:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +0800933 try:
934 index = buf.index(_SEPARATOR)
935 except ValueError:
936 self._sock.UnRecv(buf)
937 return
938
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800939 msgs_json = [buf[:index]]
940 self._sock.UnRecv(buf[index + 2:])
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800941 else:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800942 msgs_json = buf.split(_SEPARATOR)
943 self._sock.UnRecv(msgs_json.pop())
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800944
945 for msg_json in msgs_json:
946 try:
947 msg = json.loads(msg_json)
948 except ValueError:
949 # Ignore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800950 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800951 continue
952
953 if 'name' in msg:
954 self.HandleRequest(msg)
955 elif 'response' in msg:
956 self.HandleResponse(msg)
957 else: # Ingnore mal-formed message.
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +0800958 logging.error('mal-formed JSON request, ignored')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800959
960 def ScanForTimeoutRequests(self):
Joel Kitching22b89042015-08-06 18:23:29 +0800961 """Scans for pending requests which have timed out.
962
963 If any timed-out requests are discovered, their handler is called with the
964 special response value of None.
965 """
Yilin Yang78fa12e2019-09-25 14:21:10 +0800966 for rid in list(self._requests):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800967 request_time, timeout, handler = self._requests[rid]
968 if self.Timestamp() - request_time > timeout:
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800969 if callable(handler):
970 handler(None)
971 else:
972 logging.error('Request %s timeout', rid)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800973 del self._requests[rid]
974
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800975 def InitiateDownload(self):
976 ttyname, filename = self._download_queue.get()
Wei-Ning Huangd521f282015-08-07 05:28:04 +0800977 sid = self._ttyname_to_sid[ttyname]
978 self.SpawnGhost(self.FILE, terminal_sid=sid,
Wei-Ning Huangae923642015-09-24 14:08:09 +0800979 file_op=('download', filename))
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800980
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800981 def Listen(self):
982 try:
983 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +0800984 rds, unused_wd, unused_xd = select.select([self._sock], [], [],
Yilin Yang14d02a22019-11-01 11:32:03 +0800985 _PING_INTERVAL // 2)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800986
987 if self._sock in rds:
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800988 data = self._sock.Recv(_BUFSIZE)
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800989
990 # Socket is closed
Peter Shihaacbc2f2017-06-16 14:39:29 +0800991 if not data:
Wei-Ning Huang09c19612015-11-24 16:29:09 +0800992 break
993
Wei-Ning Huanga28cd232016-01-27 15:04:41 +0800994 self.ParseMessage(data, self._register_status != SUCCESS)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800995
Wei-Ning Huanga301f572015-06-03 17:34:21 +0800996 if (self._mode == self.AGENT and
997 self.Timestamp() - self._last_ping > _PING_INTERVAL):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +0800998 self.Ping()
999 self.ScanForTimeoutRequests()
1000
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001001 if not self._download_queue.empty():
1002 self.InitiateDownload()
1003
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001004 if self._reset.is_set():
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001005 break
1006 except socket.error:
1007 raise RuntimeError('Connection dropped')
1008 except PingTimeoutError:
1009 raise RuntimeError('Connection timeout')
1010 finally:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001011 self.Reset()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001012
1013 self._queue.put('resume')
1014
1015 if self._mode != Ghost.AGENT:
1016 sys.exit(1)
1017
1018 def Register(self):
1019 non_local = {}
1020 for addr in self._overlord_addrs:
1021 non_local['addr'] = addr
1022 def registered(response):
1023 if response is None:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001024 self._reset.set()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001025 raise RuntimeError('Register request timeout')
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001026
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001027 self._register_status = response['response']
1028 if response['response'] != SUCCESS:
1029 self._reset.set()
Peter Shih220a96d2016-12-22 17:02:16 +08001030 raise RuntimeError('Register: ' + response['response'])
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001031 else:
1032 logging.info('Registered with Overlord at %s:%d', *non_local['addr'])
1033 self._connected_addr = non_local['addr']
1034 self.Upgrade() # Check for upgrade
1035 self._queue.put('pause', True)
Wei-Ning Huang63c16092015-09-18 16:20:27 +08001036
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001037 try:
1038 logging.info('Trying %s:%d ...', *addr)
1039 self.Reset()
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001040
Peter Shih220a96d2016-12-22 17:02:16 +08001041 # Check if server has TLS enabled. Only check if self._tls_mode is
1042 # None.
Wei-Ning Huangb6605d22016-06-22 17:33:37 +08001043 # Only control channel needs to determine if TLS is enabled. Other mode
1044 # should use the TLSSettings passed in when it was spawned.
1045 if self._mode == Ghost.AGENT:
Peter Shih220a96d2016-12-22 17:02:16 +08001046 self._tls_settings.SetEnabled(
1047 self.TLSEnabled(*addr) if self._tls_mode is None
1048 else self._tls_mode)
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001049
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001050 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1051 sock.settimeout(_CONNECT_TIMEOUT)
1052
1053 try:
1054 if self._tls_settings.Enabled():
1055 tls_context = self._tls_settings.Context()
1056 sock = tls_context.wrap_socket(sock, server_hostname=addr[0])
1057
1058 sock.connect(addr)
1059 except (ssl.SSLError, ssl.CertificateError) as e:
1060 logging.error('%s: %s', e.__class__.__name__, e)
1061 continue
1062 except IOError as e:
1063 if e.errno == 2: # No such file or directory
1064 logging.error('%s: %s', e.__class__.__name__, e)
1065 continue
1066 raise
1067
1068 self._sock = BufferedSocket(sock)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001069
1070 logging.info('Connection established, registering...')
1071 handler = {
1072 Ghost.AGENT: registered,
Wei-Ning Huangb8461202015-09-01 20:07:41 +08001073 Ghost.TERMINAL: self.SpawnTTYServer,
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001074 Ghost.SHELL: self.SpawnShellServer,
1075 Ghost.FILE: self.InitiateFileOperation,
Wei-Ning Huangdadbeb62015-09-20 00:38:27 +08001076 Ghost.FORWARD: self.SpawnPortForwardServer,
Peter Shihe6afab32018-09-11 17:16:48 +08001077 }[self._mode]
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001078
1079 # Machine ID may change if MAC address is used (USB-ethernet dongle
1080 # plugged/unplugged)
1081 self._machine_id = self.GetMachineID()
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001082 self.SendRequest('register',
1083 {'mode': self._mode, 'mid': self._machine_id,
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001084 'sid': self._session_id,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001085 'properties': self._properties}, handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001086 except socket.error:
1087 pass
1088 else:
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001089 sock.settimeout(None)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001090 self.Listen()
1091
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001092 raise RuntimeError('Cannot connect to any server')
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001093
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001094 def Reconnect(self):
1095 logging.info('Received reconnect request from RPC server, reconnecting...')
1096 self._reset.set()
1097
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001098 def GetStatus(self):
Peter Shih5cafebb2017-06-30 16:36:22 +08001099 status = self._register_status
1100 if self._register_status == SUCCESS:
1101 ip, port = self._sock.sock.getpeername()
1102 status += ' %s:%d' % (ip, port)
1103 return status
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001104
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001105 def AddToDownloadQueue(self, ttyname, filename):
1106 self._download_queue.put((ttyname, filename))
1107
Wei-Ning Huangd521f282015-08-07 05:28:04 +08001108 def RegisterTTY(self, session_id, ttyname):
1109 self._ttyname_to_sid[ttyname] = session_id
Wei-Ning Huange2981862015-08-03 15:03:08 +08001110
1111 def RegisterSession(self, session_id, process_id):
1112 self._terminal_sid_to_pid[session_id] = process_id
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001113
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001114 def StartLanDiscovery(self):
1115 """Start to listen to LAN discovery packet at
1116 _OVERLORD_LAN_DISCOVERY_PORT."""
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001117
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001118 def thread_func():
1119 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1120 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1121 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001122 try:
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001123 s.bind(('0.0.0.0', _OVERLORD_LAN_DISCOVERY_PORT))
1124 except socket.error as e:
Moja Hsuc9ecc8b2015-07-13 11:39:17 +08001125 logging.error('LAN discovery: %s, abort', e)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001126 return
1127
1128 logging.info('LAN Discovery: started')
1129 while True:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001130 rd, unused_wd, unused_xd = select.select([s], [], [], 1)
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001131
1132 if s in rd:
1133 data, source_addr = s.recvfrom(_BUFSIZE)
1134 parts = data.split()
1135 if parts[0] == 'OVERLORD':
1136 ip, port = parts[1].split(':')
1137 if not ip:
1138 ip = source_addr[0]
1139 self._queue.put((ip, int(port)), True)
1140
1141 try:
1142 obj = self._queue.get(False)
1143 except Queue.Empty:
1144 pass
1145 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001146 if not isinstance(obj, str):
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001147 self._queue.put(obj)
1148 elif obj == 'pause':
1149 logging.info('LAN Discovery: paused')
1150 while obj != 'resume':
1151 obj = self._queue.get(True)
1152 logging.info('LAN Discovery: resumed')
1153
1154 t = threading.Thread(target=thread_func)
1155 t.daemon = True
1156 t.start()
1157
1158 def StartRPCServer(self):
Joel Kitching22b89042015-08-06 18:23:29 +08001159 logging.info('RPC Server: started')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001160 rpc_server = SimpleJSONRPCServer((_DEFAULT_BIND_ADDRESS, _GHOST_RPC_PORT),
1161 logRequests=False)
1162 rpc_server.register_function(self.Reconnect, 'Reconnect')
Wei-Ning Huang7ec55342015-09-17 08:46:06 +08001163 rpc_server.register_function(self.GetStatus, 'GetStatus')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001164 rpc_server.register_function(self.RegisterTTY, 'RegisterTTY')
Wei-Ning Huange2981862015-08-03 15:03:08 +08001165 rpc_server.register_function(self.RegisterSession, 'RegisterSession')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001166 rpc_server.register_function(self.AddToDownloadQueue, 'AddToDownloadQueue')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001167 t = threading.Thread(target=rpc_server.serve_forever)
1168 t.daemon = True
1169 t.start()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001170
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001171 def ScanServer(self):
Hung-Te Lin41ff8f32017-08-30 08:10:39 +08001172 for meth in [self.GetGateWayIP, self.GetFactoryServerIP]:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001173 for addr in [(x, _OVERLORD_PORT) for x in meth()]:
1174 if addr not in self._overlord_addrs:
1175 self._overlord_addrs.append(addr)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001176
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001177 def Start(self, lan_disc=False, rpc_server=False):
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001178 logging.info('%s started', self.MODE_NAME[self._mode])
1179 logging.info('MID: %s', self._machine_id)
Wei-Ning Huangfed95862015-08-07 03:17:11 +08001180 logging.info('SID: %s', self._session_id)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001181
Wei-Ning Huangb05cde32015-08-01 09:48:41 +08001182 # We don't care about child process's return code, not wait is needed. This
1183 # is used to prevent zombie process from lingering in the system.
1184 self.SetIgnoreChild(True)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001185
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001186 if lan_disc:
1187 self.StartLanDiscovery()
1188
1189 if rpc_server:
1190 self.StartRPCServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001191
1192 try:
1193 while True:
1194 try:
1195 addr = self._queue.get(False)
1196 except Queue.Empty:
1197 pass
1198 else:
Peter Shihaacbc2f2017-06-16 14:39:29 +08001199 if isinstance(addr, tuple) and addr not in self._overlord_addrs:
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001200 logging.info('LAN Discovery: got overlord address %s:%d', *addr)
1201 self._overlord_addrs.append(addr)
1202
1203 try:
Wei-Ning Huang829e0c82015-05-26 14:37:23 +08001204 self.ScanServer()
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001205 self.Register()
Joel Kitching22b89042015-08-06 18:23:29 +08001206 # Don't show stack trace for RuntimeError, which we use in this file for
1207 # plausible and expected errors (such as can't connect to server).
1208 except RuntimeError as e:
Yilin Yang58948af2019-10-30 18:28:55 +08001209 logging.info('%s, retrying in %ds', str(e), _RETRY_INTERVAL)
Joel Kitching22b89042015-08-06 18:23:29 +08001210 time.sleep(_RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001211 except Exception as e:
Wei-Ning Huang9083b7c2016-01-26 16:44:11 +08001212 unused_x, unused_y, exc_traceback = sys.exc_info()
Joel Kitching22b89042015-08-06 18:23:29 +08001213 traceback.print_tb(exc_traceback)
1214 logging.info('%s: %s, retrying in %ds',
Yilin Yang58948af2019-10-30 18:28:55 +08001215 e.__class__.__name__, str(e), _RETRY_INTERVAL)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001216 time.sleep(_RETRY_INTERVAL)
1217
1218 self.Reset()
1219 except KeyboardInterrupt:
1220 logging.error('Received keyboard interrupt, quit')
1221 sys.exit(0)
1222
1223
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001224def GhostRPCServer():
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001225 """Returns handler to Ghost's JSON RPC server."""
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001226 return jsonrpclib.Server('http://localhost:%d' % _GHOST_RPC_PORT)
1227
1228
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001229def ForkToBackground():
1230 """Fork process to run in background."""
1231 pid = os.fork()
1232 if pid != 0:
1233 logging.info('Ghost(%d) running in background.', pid)
1234 sys.exit(0)
1235
1236
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001237def DownloadFile(filename):
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001238 """Initiate a client-initiated file download."""
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001239 filepath = os.path.abspath(filename)
1240 if not os.path.exists(filepath):
Joel Kitching22b89042015-08-06 18:23:29 +08001241 logging.error('file `%s\' does not exist', filename)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001242 sys.exit(1)
1243
1244 # Check if we actually have permission to read the file
1245 if not os.access(filepath, os.R_OK):
Joel Kitching22b89042015-08-06 18:23:29 +08001246 logging.error('can not open %s for reading', filepath)
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001247 sys.exit(1)
1248
1249 server = GhostRPCServer()
1250 server.AddToDownloadQueue(os.ttyname(0), filepath)
1251 sys.exit(0)
1252
1253
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001254def main():
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001255 # Setup logging format
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001256 logger = logging.getLogger()
1257 logger.setLevel(logging.INFO)
Wei-Ning Huang5f3fa8f2015-10-24 15:08:48 +08001258 handler = logging.StreamHandler()
1259 formatter = logging.Formatter('%(asctime)s %(message)s', '%Y/%m/%d %H:%M:%S')
1260 handler.setFormatter(formatter)
1261 logger.addHandler(handler)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001262
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001263 parser = argparse.ArgumentParser()
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001264 parser.add_argument('--fork', dest='fork', action='store_true', default=False,
1265 help='fork procecess to run in background')
Wei-Ning Huangc9c97f02015-05-19 15:05:42 +08001266 parser.add_argument('--mid', metavar='MID', dest='mid', action='store',
1267 default=None, help='use MID as machine ID')
1268 parser.add_argument('--rand-mid', dest='mid', action='store_const',
1269 const=Ghost.RANDOM_MID, help='use random machine ID')
Wei-Ning Huang2132de32015-04-13 17:24:38 +08001270 parser.add_argument('--no-lan-disc', dest='lan_disc', action='store_false',
1271 default=True, help='disable LAN discovery')
1272 parser.add_argument('--no-rpc-server', dest='rpc_server',
1273 action='store_false', default=True,
1274 help='disable RPC server')
Peter Shih220a96d2016-12-22 17:02:16 +08001275 parser.add_argument('--tls', dest='tls_mode', default='detect',
1276 choices=('y', 'n', 'detect'),
1277 help="specify 'y' or 'n' to force enable/disable TLS")
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001278 parser.add_argument('--tls-cert-file', metavar='TLS_CERT_FILE',
1279 dest='tls_cert_file', type=str, default=None,
1280 help='file containing the server TLS certificate in PEM '
1281 'format')
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001282 parser.add_argument('--tls-no-verify', dest='tls_no_verify',
1283 action='store_true', default=False,
1284 help='do not verify certificate if TLS is enabled')
Joel Kitching22b89042015-08-06 18:23:29 +08001285 parser.add_argument('--prop-file', metavar='PROP_FILE', dest='prop_file',
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001286 type=str, default=None,
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001287 help='file containing the JSON representation of client '
1288 'properties')
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001289 parser.add_argument('--download', metavar='FILE', dest='download', type=str,
1290 default=None, help='file to download')
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001291 parser.add_argument('--reset', dest='reset', default=False,
1292 action='store_true',
1293 help='reset ghost and reload all configs')
Peter Shih5cafebb2017-06-30 16:36:22 +08001294 parser.add_argument('--status', dest='status', default=False,
1295 action='store_true',
1296 help='show status of the client')
Wei-Ning Huang7d029b12015-03-06 10:32:15 +08001297 parser.add_argument('overlord_ip', metavar='OVERLORD_IP', type=str,
1298 nargs='*', help='overlord server address')
1299 args = parser.parse_args()
1300
Peter Shih5cafebb2017-06-30 16:36:22 +08001301 if args.status:
1302 print(GhostRPCServer().GetStatus())
1303 sys.exit()
1304
Wei-Ning Huang8037c182015-09-19 04:41:50 +08001305 if args.fork:
1306 ForkToBackground()
1307
Wei-Ning Huang23ed0162015-09-18 14:42:03 +08001308 if args.reset:
1309 GhostRPCServer().Reconnect()
1310 sys.exit()
1311
Wei-Ning Huanga301f572015-06-03 17:34:21 +08001312 if args.download:
1313 DownloadFile(args.download)
1314
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001315 addrs = [('localhost', _OVERLORD_PORT)]
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001316 addrs = [(x, _OVERLORD_PORT) for x in args.overlord_ip] + addrs
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001317
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001318 prop_file = os.path.abspath(args.prop_file) if args.prop_file else None
1319
Wei-Ning Huang47c79b82016-05-24 01:24:46 +08001320 tls_settings = TLSSettings(args.tls_cert_file, not args.tls_no_verify)
Peter Shih220a96d2016-12-22 17:02:16 +08001321 tls_mode = args.tls_mode
1322 tls_mode = {'y': True, 'n': False, 'detect': None}[tls_mode]
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001323 g = Ghost(addrs, tls_settings, Ghost.AGENT, args.mid,
Peter Shih220a96d2016-12-22 17:02:16 +08001324 prop_file=prop_file, tls_mode=tls_mode)
Wei-Ning Huang11c35022015-10-21 16:52:32 +08001325 g.Start(args.lan_disc, args.rpc_server)
Wei-Ning Huang1cea6112015-03-02 12:45:34 +08001326
1327
1328if __name__ == '__main__':
Wei-Ning Huangf5311a02016-02-04 15:23:46 +08001329 try:
1330 main()
1331 except Exception as e:
1332 logging.error(e)