Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit cfb21412 authored by Josh Gao's avatar Josh Gao
Browse files

adb: factor out socket specification.

Move the logic for string socket specification out to separate
functions to facilitate using arbitrary sockets for the adb command
socket.

Bug: http://b/30445394
Change-Id: Icd8fdb853272edc029fb3a0f5b18e941dc8ef52c
Test: adb_test, adbd_test, test_device.py
parent e461b379
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -52,6 +52,7 @@ LIBADB_SRC_FILES := \
    adb_utils.cpp \
    fdevent.cpp \
    sockets.cpp \
    socket_spec.cpp \
    transport.cpp \
    transport_local.cpp \
    transport_usb.cpp \
+11 −46
Original line number Diff line number Diff line
@@ -23,12 +23,10 @@
#include <android-base/strings.h>
#include <cutils/sockets.h>

#include "socket_spec.h"
#include "sysdeps.h"
#include "transport.h"

// Not static because it is used in commandline.c.
int gListenAll = 0;

// A listener is an entity which binds to a local port and, upon receiving a connection on that
// port, creates an asocket to connect the new local connection to a specific remote service.
//
@@ -120,48 +118,6 @@ static void listener_disconnect(void* arg, atransport*) {
    }
}

int local_name_to_fd(alistener* listener, int* resolved_tcp_port, std::string* error) {
    if (android::base::StartsWith(listener->local_name, "tcp:")) {
        int requested_port = atoi(&listener->local_name[4]);
        int sock = -1;
        if (gListenAll > 0) {
            sock = network_inaddr_any_server(requested_port, SOCK_STREAM, error);
        } else {
            sock = network_loopback_server(requested_port, SOCK_STREAM, error);
        }

        // If the caller requested port 0, update the listener name with the resolved port.
        if (sock >= 0 && requested_port == 0) {
            int local_port = adb_socket_get_local_port(sock);
            if (local_port > 0) {
                listener->local_name = android::base::StringPrintf("tcp:%d", local_port);
                if (resolved_tcp_port != nullptr) {
                    *resolved_tcp_port = local_port;
                }
            }
        }

        return sock;
    }
#if !defined(_WIN32)  // No Unix-domain sockets on Windows.
    // It's nonsensical to support the "reserved" space on the adb host side.
    if (android::base::StartsWith(listener->local_name, "local:")) {
        return network_local_server(&listener->local_name[6], ANDROID_SOCKET_NAMESPACE_ABSTRACT,
                                    SOCK_STREAM, error);
    } else if (android::base::StartsWith(listener->local_name, "localabstract:")) {
        return network_local_server(&listener->local_name[14], ANDROID_SOCKET_NAMESPACE_ABSTRACT,
                                    SOCK_STREAM, error);
    } else if (android::base::StartsWith(listener->local_name, "localfilesystem:")) {
        return network_local_server(&listener->local_name[16], ANDROID_SOCKET_NAMESPACE_FILESYSTEM,
                                    SOCK_STREAM, error);
    }

#endif
    *error = android::base::StringPrintf("unknown local portname '%s'",
                                         listener->local_name.c_str());
    return -1;
}

// Write the list of current listeners (network redirections) into a string.
std::string format_listeners() {
    std::string result;
@@ -230,11 +186,20 @@ InstallStatus install_listener(const std::string& local_name, const char* connec

    std::unique_ptr<alistener> listener(new alistener(local_name, connect_to));

    listener->fd = local_name_to_fd(listener.get(), resolved_tcp_port, error);
    int resolved = 0;
    listener->fd = socket_spec_listen(listener->local_name, error, &resolved);
    if (listener->fd < 0) {
        return INSTALL_STATUS_CANNOT_BIND;
    }

    // If the caller requested port 0, update the listener name with the resolved port.
    if (resolved != 0) {
        listener->local_name = android::base::StringPrintf("tcp:%d", resolved);
        if (resolved_tcp_port) {
            *resolved_tcp_port = resolved;
        }
    }

    close_on_exec(listener->fd);
    if (listener->connect_to == "*smartsocket*") {
        fdevent_install(&listener->fde, listener->fd, ss_listener_event_func, listener.get());
+6 −29
Original line number Diff line number Diff line
@@ -49,6 +49,7 @@
#include "remount_service.h"
#include "services.h"
#include "shell_service.h"
#include "socket_spec.h"
#include "sysdeps.h"
#include "transport.h"

@@ -278,36 +279,12 @@ static int create_service_thread(void (*func)(int, void *), void *cookie)
int service_to_fd(const char* name, const atransport* transport) {
    int ret = -1;

    if(!strncmp(name, "tcp:", 4)) {
        int port = atoi(name + 4);
        name = strchr(name + 4, ':');
        if(name == 0) {
    if (is_socket_spec(name)) {
        std::string error;
            ret = network_loopback_client(port, SOCK_STREAM, &error);
            if (ret >= 0)
                disable_tcp_nagle(ret);
        } else {
#if ADB_HOST
            std::string error;
            ret = network_connect(name + 1, port, SOCK_STREAM, 0, &error);
#else
            return -1;
#endif
        ret = socket_spec_connect(name, &error);
        if (ret < 0) {
            LOG(ERROR) << "failed to connect to socket '" << name << "': " << error;
        }
#if !defined(_WIN32)   /* winsock doesn't implement unix domain sockets */
    } else if(!strncmp(name, "local:", 6)) {
        ret = socket_local_client(name + 6,
                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
    } else if(!strncmp(name, "localreserved:", 14)) {
        ret = socket_local_client(name + 14,
                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
    } else if(!strncmp(name, "localabstract:", 14)) {
        ret = socket_local_client(name + 14,
                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
    } else if(!strncmp(name, "localfilesystem:", 16)) {
        ret = socket_local_client(name + 16,
                ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
#endif
#if !ADB_HOST
    } else if(!strncmp("dev:", name, 4)) {
        ret = unix_open(name + 4, O_RDWR | O_CLOEXEC);

adb/socket_spec.cpp

0 → 100644
+220 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "socket_spec.h"

#include <string>
#include <unordered_map>
#include <vector>

#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <cutils/sockets.h>

#include "adb.h"
#include "sysdeps.h"

using android::base::StartsWith;
using android::base::StringPrintf;

#if defined(__linux__)
#define ADB_LINUX 1
#else
#define ADB_LINUX 0
#endif

#if defined(_WIN32)
#define ADB_WINDOWS 1
#else
#define ADB_WINDOWS 0
#endif

// Not static because it is used in commandline.c.
int gListenAll = 0;

struct LocalSocketType {
    int socket_namespace;
    bool available;
};

static auto& kLocalSocketTypes = *new std::unordered_map<std::string, LocalSocketType>({
#if ADB_HOST
    { "local", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
#else
    { "local", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_WINDOWS } },
#endif

    { "localreserved", { ANDROID_SOCKET_NAMESPACE_RESERVED, !ADB_HOST } },
    { "localabstract", { ANDROID_SOCKET_NAMESPACE_ABSTRACT, ADB_LINUX } },
    { "localfilesystem", { ANDROID_SOCKET_NAMESPACE_FILESYSTEM, !ADB_WINDOWS } },
});

static bool parse_tcp_spec(const std::string& spec, std::string* hostname, int* port,
                           std::string* error) {
    std::vector<std::string> fragments = android::base::Split(spec, ":");
    if (fragments.size() == 1 || fragments.size() > 3) {
        *error = StringPrintf("invalid tcp specification: '%s'", spec.c_str());
        return false;
    }

    if (fragments[0] != "tcp") {
        *error = StringPrintf("specification is not tcp: '%s'", spec.c_str());
        return false;
    }

    // strtol accepts leading whitespace.
    const std::string& port_str = fragments.back();
    if (port_str.empty() || port_str[0] < '0' || port_str[0] > '9') {
        *error = StringPrintf("invalid port '%s'", port_str.c_str());
        return false;
    }

    char* parsed_end;
    long parsed_port = strtol(port_str.c_str(), &parsed_end, 10);
    if (*parsed_end != '\0') {
        *error = StringPrintf("trailing chars in port: '%s'", port_str.c_str());
        return false;
    }
    if (parsed_port > 65535) {
        *error = StringPrintf("invalid port %ld", parsed_port);
        return false;
    }

    // tcp:123 is valid, tcp::123 isn't.
    if (fragments.size() == 2) {
        // Empty hostname.
        if (hostname) {
            *hostname = "";
        }
    } else {
        if (fragments[1].empty()) {
            *error = StringPrintf("empty host in '%s'", spec.c_str());
            return false;
        }
        if (hostname) {
            *hostname = fragments[1];
        }
    }

    if (port) {
        *port = parsed_port;
    }

    return true;
}

static bool tcp_host_is_local(const std::string& hostname) {
    // FIXME
    return hostname.empty() || hostname == "localhost";
}

bool is_socket_spec(const std::string& spec) {
    for (const auto& it : kLocalSocketTypes) {
        std::string prefix = it.first + ":";
        if (StartsWith(spec, prefix.c_str())) {
            return true;
        }
    }
    return StartsWith(spec, "tcp:");
}

int socket_spec_connect(const std::string& spec, std::string* error) {
    if (StartsWith(spec, "tcp:")) {
        std::string hostname;
        int port;
        if (!parse_tcp_spec(spec, &hostname, &port, error)) {
            return -1;
        }

        int result;
        if (tcp_host_is_local(hostname)) {
            result = network_loopback_client(port, SOCK_STREAM, error);
        } else {
#if ADB_HOST
            result = network_connect(hostname, port, SOCK_STREAM, 0, error);
#else
            // Disallow arbitrary connections in adbd.
            *error = "adbd does not support arbitrary tcp connections";
            return -1;
#endif
        }

        if (result >= 0) {
            disable_tcp_nagle(result);
        }
        return result;
    }

    for (const auto& it : kLocalSocketTypes) {
        std::string prefix = it.first + ":";
        if (StartsWith(spec, prefix.c_str())) {
            if (!it.second.available) {
                *error = StringPrintf("socket type %s is unavailable on this platform",
                                      it.first.c_str());
                return -1;
            }

            return network_local_client(&spec[prefix.length()], it.second.socket_namespace,
                                        SOCK_STREAM, error);
        }
    }

    *error = StringPrintf("unknown socket specification '%s'", spec.c_str());
    return -1;
}

int socket_spec_listen(const std::string& spec, std::string* error, int* resolved_tcp_port) {
    if (StartsWith(spec, "tcp:")) {
        std::string hostname;
        int port;
        if (!parse_tcp_spec(spec, &hostname, &port, error)) {
            return -1;
        }

        int result;
        if (hostname.empty() && gListenAll) {
            result = network_inaddr_any_server(port, SOCK_STREAM, error);
        } else if (tcp_host_is_local(hostname)) {
            result = network_loopback_server(port, SOCK_STREAM, error);
        } else {
            // TODO: Implement me.
            *error = "listening on specified hostname currently unsupported";
            return -1;
        }

        if (result >= 0 && port == 0 && resolved_tcp_port) {
            *resolved_tcp_port = adb_socket_get_local_port(result);
        }
        return result;
    }

    for (const auto& it : kLocalSocketTypes) {
        std::string prefix = it.first + ":";
        if (StartsWith(spec, prefix.c_str())) {
            if (!it.second.available) {
                *error = StringPrintf("attempted to listen on unavailable socket type: '%s'",
                                      spec.c_str());
                return -1;
            }

            return network_local_server(&spec[prefix.length()], it.second.socket_namespace,
                                        SOCK_STREAM, error);
        }
    }

    *error = StringPrintf("unknown socket specification '%s'", spec.c_str());
    return -1;
}

adb/socket_spec.h

0 → 100644
+26 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <string>

// Returns true if the argument starts with a plausible socket prefix.
bool is_socket_spec(const std::string& spec);

int socket_spec_connect(const std::string& spec, std::string* error);
int socket_spec_listen(const std::string& spec, std::string* error,
                       int* resolved_tcp_port = nullptr);
Loading