summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/remote-debugging/adb/xpcshell/adb.py
blob: 4b720a1f862f19adb0b0b7d2da70848877a16422 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
A fake ADB binary
"""

import os
import socketserver
import sys

HOST = "127.0.0.1"
PORT = 5037


class ADBRequestHandler(socketserver.BaseRequestHandler):
    def sendData(self, data):
        header = "OKAY%04x" % len(data)
        all_data = header + data
        total_length = len(all_data)
        sent_length = 0
        # Make sure send all data to the client.
        # Though the data length here is pretty small but sometimes when the
        # client is on heavy load (e.g. MOZ_CHAOSMODE) we can't send the whole
        # data at once.
        while sent_length < total_length:
            sent = self.request.send(all_data[sent_length:].encode("utf-8", "replace"))
            sent_length = sent_length + sent

    def handle(self):
        while True:
            data = self.request.recv(4096).decode("utf-8", "replace")
            if "host:kill" in data:
                self.sendData("")
                # Implicitly close all open sockets by exiting the program.
                # This should be done ASAP, because upon receiving the OKAY,
                # the client expects adb to have released the server's port.
                os._exit(0)
                break
            elif "host:version" in data:
                self.sendData("001F")
                self.request.close()
                break
            elif "host:track-devices" in data:
                self.sendData("1234567890\tdevice")
                break


class ADBServer(socketserver.TCPServer):
    def __init__(self, server_address):
        # Create a socketserver with bind_and_activate 'False' to set
        # allow_reuse_address before binding.
        socketserver.TCPServer.__init__(
            self, server_address, ADBRequestHandler, bind_and_activate=False
        )


if len(sys.argv) == 2 and sys.argv[1] == "start-server":
    # daemonize
    if os.fork() > 0:
        sys.exit(0)
    os.setsid()
    if os.fork() > 0:
        sys.exit(0)

    server = ADBServer((HOST, PORT))
    server.allow_reuse_address = True
    server.server_bind()
    server.server_activate()
    server.serve_forever()