tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

adb.py (2331B)


      1 #!/usr/bin/env python
      2 # This Source Code Form is subject to the terms of the Mozilla Public
      3 # License, v. 2.0. If a copy of the MPL was not distributed with this
      4 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
      5 
      6 """
      7 A fake ADB binary
      8 """
      9 
     10 import os
     11 import socketserver
     12 import sys
     13 
     14 HOST = "127.0.0.1"
     15 PORT = 5037
     16 
     17 
     18 class ADBRequestHandler(socketserver.BaseRequestHandler):
     19    def sendData(self, data):
     20        header = "OKAY%04x" % len(data)
     21        all_data = header + data
     22        total_length = len(all_data)
     23        sent_length = 0
     24        # Make sure send all data to the client.
     25        # Though the data length here is pretty small but sometimes when the
     26        # client is on heavy load (e.g. MOZ_CHAOSMODE) we can't send the whole
     27        # data at once.
     28        while sent_length < total_length:
     29            sent = self.request.send(all_data[sent_length:].encode("utf-8", "replace"))
     30            sent_length = sent_length + sent
     31 
     32    def handle(self):
     33        while True:
     34            data = self.request.recv(4096).decode("utf-8", "replace")
     35            if "host:kill" in data:
     36                self.sendData("")
     37                # Implicitly close all open sockets by exiting the program.
     38                # This should be done ASAP, because upon receiving the OKAY,
     39                # the client expects adb to have released the server's port.
     40                os._exit(0)
     41                break
     42            elif "host:version" in data:
     43                self.sendData("001F")
     44                self.request.close()
     45                break
     46            elif "host:track-devices" in data:
     47                self.sendData("1234567890\tdevice")
     48                break
     49 
     50 
     51 class ADBServer(socketserver.TCPServer):
     52    def __init__(self, server_address):
     53        # Create a socketserver with bind_and_activate 'False' to set
     54        # allow_reuse_address before binding.
     55        socketserver.TCPServer.__init__(
     56            self, server_address, ADBRequestHandler, bind_and_activate=False
     57        )
     58 
     59 
     60 if len(sys.argv) == 2 and sys.argv[1] == "start-server":
     61    # daemonize
     62    if os.fork() > 0:
     63        sys.exit(0)
     64    os.setsid()
     65    if os.fork() > 0:
     66        sys.exit(0)
     67 
     68    server = ADBServer((HOST, PORT))
     69    server.allow_reuse_address = True
     70    server.server_bind()
     71    server.server_activate()
     72    server.serve_forever()