Merge "ADB security logging"
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 484e561..3005652 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -35,6 +35,7 @@
#include <android-base/logging.h>
#include <android-base/macros.h>
+#include <android-base/parsenetaddress.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
@@ -1037,7 +1038,7 @@
std::string host;
int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
std::string error;
- if (!parse_host_and_port(address, &serial, &host, &port, &error)) {
+ if (!android::base::ParseNetAddress(address, &host, &port, &serial, &error)) {
return SendFail(reply_fd, android::base::StringPrintf("couldn't parse '%s': %s",
address.c_str(), error.c_str()));
}
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index b132118..474d1b4 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -208,59 +208,6 @@
return line;
}
-bool parse_host_and_port(const std::string& address,
- std::string* canonical_address,
- std::string* host, int* port,
- std::string* error) {
- host->clear();
-
- bool ipv6 = true;
- bool saw_port = false;
- size_t colons = std::count(address.begin(), address.end(), ':');
- size_t dots = std::count(address.begin(), address.end(), '.');
- std::string port_str;
- if (address[0] == '[') {
- // [::1]:123
- if (address.rfind("]:") == std::string::npos) {
- *error = android::base::StringPrintf("bad IPv6 address '%s'", address.c_str());
- return false;
- }
- *host = address.substr(1, (address.find("]:") - 1));
- port_str = address.substr(address.rfind("]:") + 2);
- saw_port = true;
- } else if (dots == 0 && colons >= 2 && colons <= 7) {
- // ::1
- *host = address;
- } else if (colons <= 1) {
- // 1.2.3.4 or some.accidental.domain.com
- ipv6 = false;
- std::vector<std::string> pieces = android::base::Split(address, ":");
- *host = pieces[0];
- if (pieces.size() > 1) {
- port_str = pieces[1];
- saw_port = true;
- }
- }
-
- if (host->empty()) {
- *error = android::base::StringPrintf("no host in '%s'", address.c_str());
- return false;
- }
-
- if (saw_port) {
- if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 || *port > 65535) {
- *error = android::base::StringPrintf("bad port number '%s' in '%s'",
- port_str.c_str(), address.c_str());
- return false;
- }
- }
-
- *canonical_address = android::base::StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port);
- LOG(DEBUG) << "parsed " << address << " as " << *host << " and " << *port
- << " (" << *canonical_address << ")";
- return true;
-}
-
std::string perror_str(const char* msg) {
return android::base::StringPrintf("%s: %s", msg, strerror(errno));
}
diff --git a/adb/adb_utils.h b/adb/adb_utils.h
index 388d7dd..f1149b3 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -35,17 +35,6 @@
std::string dump_hex(const void* ptr, size_t byte_count);
-// Parses 'address' into 'host' and 'port'.
-// If no port is given, takes the default from *port.
-// 'canonical_address' then becomes "host:port" or "[host]:port" as appropriate.
-// Note that no real checking is done that 'host' or 'port' is valid; that's
-// left to getaddrinfo(3).
-// Returns false on failure and sets *error to an appropriate message.
-bool parse_host_and_port(const std::string& address,
- std::string* canonical_address,
- std::string* host, int* port,
- std::string* error);
-
std::string perror_str(const char* msg);
bool set_file_block_mode(int fd, bool block);
diff --git a/adb/adb_utils_test.cpp b/adb/adb_utils_test.cpp
index 4508bca..794dce6 100644
--- a/adb/adb_utils_test.cpp
+++ b/adb/adb_utils_test.cpp
@@ -111,88 +111,6 @@
EXPECT_EQ("/system/bin", adb_dirname("/system/bin/sh/"));
}
-TEST(adb_utils, parse_host_and_port) {
- std::string canonical_address;
- std::string host;
- int port;
- std::string error;
-
- // Name, default port.
- port = 123;
- ASSERT_TRUE(parse_host_and_port("www.google.com", &canonical_address, &host, &port, &error));
- ASSERT_EQ("www.google.com:123", canonical_address);
- ASSERT_EQ("www.google.com", host);
- ASSERT_EQ(123, port);
-
- // Name, explicit port.
- ASSERT_TRUE(parse_host_and_port("www.google.com:666", &canonical_address, &host, &port, &error));
- ASSERT_EQ("www.google.com:666", canonical_address);
- ASSERT_EQ("www.google.com", host);
- ASSERT_EQ(666, port);
-
- // IPv4, default port.
- port = 123;
- ASSERT_TRUE(parse_host_and_port("1.2.3.4", &canonical_address, &host, &port, &error));
- ASSERT_EQ("1.2.3.4:123", canonical_address);
- ASSERT_EQ("1.2.3.4", host);
- ASSERT_EQ(123, port);
-
- // IPv4, explicit port.
- ASSERT_TRUE(parse_host_and_port("1.2.3.4:666", &canonical_address, &host, &port, &error));
- ASSERT_EQ("1.2.3.4:666", canonical_address);
- ASSERT_EQ("1.2.3.4", host);
- ASSERT_EQ(666, port);
-
- // Simple IPv6, default port.
- port = 123;
- ASSERT_TRUE(parse_host_and_port("::1", &canonical_address, &host, &port, &error));
- ASSERT_EQ("[::1]:123", canonical_address);
- ASSERT_EQ("::1", host);
- ASSERT_EQ(123, port);
-
- // Simple IPv6, explicit port.
- ASSERT_TRUE(parse_host_and_port("[::1]:666", &canonical_address, &host, &port, &error));
- ASSERT_EQ("[::1]:666", canonical_address);
- ASSERT_EQ("::1", host);
- ASSERT_EQ(666, port);
-
- // Hairy IPv6, default port.
- port = 123;
- ASSERT_TRUE(parse_host_and_port("fe80::200:5aee:feaa:20a2", &canonical_address, &host, &port, &error));
- ASSERT_EQ("[fe80::200:5aee:feaa:20a2]:123", canonical_address);
- ASSERT_EQ("fe80::200:5aee:feaa:20a2", host);
- ASSERT_EQ(123, port);
-
- // Simple IPv6, explicit port.
- ASSERT_TRUE(parse_host_and_port("[fe80::200:5aee:feaa:20a2]:666", &canonical_address, &host, &port, &error));
- ASSERT_EQ("[fe80::200:5aee:feaa:20a2]:666", canonical_address);
- ASSERT_EQ("fe80::200:5aee:feaa:20a2", host);
- ASSERT_EQ(666, port);
-
- // Invalid IPv4.
- EXPECT_FALSE(parse_host_and_port("1.2.3.4:", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("1.2.3.4::", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("1.2.3.4:hello", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port(":123", &canonical_address, &host, &port, &error));
-
- // Invalid IPv6.
- EXPECT_FALSE(parse_host_and_port(":1", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("::::::::1", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]:", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]::", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]:hello", &canonical_address, &host, &port, &error));
-
- // Invalid ports.
- EXPECT_FALSE(parse_host_and_port("[::1]:-1", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]:0", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("[::1]:65536", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("1.2.3.4:-1", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("1.2.3.4:0", &canonical_address, &host, &port, &error));
- EXPECT_FALSE(parse_host_and_port("1.2.3.4:65536", &canonical_address, &host, &port, &error));
-}
-
void test_mkdirs(const std::string basepath) {
EXPECT_TRUE(mkdirs(basepath));
EXPECT_NE(-1, adb_creat(basepath.c_str(), 0600));
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index a025ed7..f886698 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -443,13 +443,32 @@
return android::base::StringPrintf("%s:%s", prefix, command);
}
-// Returns the FeatureSet for the indicated transport.
-static FeatureSet GetFeatureSet(TransportType transport_type, const char* serial) {
+namespace {
+
+enum class ErrorAction {
+ kPrintToStderr,
+ kDoNotPrint
+};
+
+} // namespace
+
+// Fills |feature_set| using the target indicated by |transport_type| and |serial|. Returns false
+// and clears |feature_set| on failure. |error_action| selects whether to also print error messages
+// on failure.
+static bool GetFeatureSet(TransportType transport_type, const char* serial, FeatureSet* feature_set,
+ ErrorAction error_action) {
std::string result, error;
+
if (adb_query(format_host_command("features", transport_type, serial), &result, &error)) {
- return StringToFeatureSet(result);
+ *feature_set = StringToFeatureSet(result);
+ return true;
}
- return FeatureSet();
+
+ if (error_action == ErrorAction::kPrintToStderr) {
+ fprintf(stderr, "error: %s\n", error.c_str());
+ }
+ feature_set->clear();
+ return false;
}
static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
@@ -695,7 +714,10 @@
static int adb_shell(int argc, const char** argv,
TransportType transport_type, const char* serial) {
- FeatureSet features = GetFeatureSet(transport_type, serial);
+ FeatureSet features;
+ if (!GetFeatureSet(transport_type, serial, &features, ErrorAction::kPrintToStderr)) {
+ return 1;
+ }
bool use_shell_protocol = CanUseFeature(features, kFeatureShell2);
if (!use_shell_protocol) {
@@ -1065,23 +1087,33 @@
static int send_shell_command(TransportType transport_type, const char* serial,
const std::string& command,
bool disable_shell_protocol) {
- // Only use shell protocol if it's supported and the caller doesn't want
- // to explicitly disable it.
- bool use_shell_protocol = false;
- if (!disable_shell_protocol) {
- FeatureSet features = GetFeatureSet(transport_type, serial);
- use_shell_protocol = CanUseFeature(features, kFeatureShell2);
- }
-
- std::string service_string = ShellServiceString(use_shell_protocol, "", command);
-
int fd;
+ bool use_shell_protocol = false;
+
while (true) {
- std::string error;
- fd = adb_connect(service_string, &error);
- if (fd >= 0) {
- break;
+ bool attempt_connection = true;
+
+ // Use shell protocol if it's supported and the caller doesn't explicitly disable it.
+ if (!disable_shell_protocol) {
+ FeatureSet features;
+ if (GetFeatureSet(transport_type, serial, &features, ErrorAction::kDoNotPrint)) {
+ use_shell_protocol = CanUseFeature(features, kFeatureShell2);
+ } else {
+ // Device was unreachable.
+ attempt_connection = false;
+ }
}
+
+ if (attempt_connection) {
+ std::string error;
+ std::string service_string = ShellServiceString(use_shell_protocol, "", command);
+
+ fd = adb_connect(service_string, &error);
+ if (fd >= 0) {
+ break;
+ }
+ }
+
fprintf(stderr,"- waiting for device -\n");
adb_sleep_ms(1000);
wait_for_device("wait-for-device", transport_type, serial);
@@ -1698,7 +1730,11 @@
}
else if (!strcmp(argv[0], "install")) {
if (argc < 2) return usage();
- FeatureSet features = GetFeatureSet(transport_type, serial);
+ FeatureSet features;
+ if (!GetFeatureSet(transport_type, serial, &features, ErrorAction::kPrintToStderr)) {
+ return 1;
+ }
+
if (CanUseFeature(features, kFeatureCmd)) {
return install_app(transport_type, serial, argc, argv);
}
@@ -1710,7 +1746,11 @@
}
else if (!strcmp(argv[0], "uninstall")) {
if (argc < 2) return usage();
- FeatureSet features = GetFeatureSet(transport_type, serial);
+ FeatureSet features;
+ if (!GetFeatureSet(transport_type, serial, &features, ErrorAction::kPrintToStderr)) {
+ return 1;
+ }
+
if (CanUseFeature(features, kFeatureCmd)) {
return uninstall_app(transport_type, serial, argc, argv);
}
@@ -1809,7 +1849,11 @@
}
else if (!strcmp(argv[0], "features")) {
// Only list the features common to both the adb client and the device.
- FeatureSet features = GetFeatureSet(transport_type, serial);
+ FeatureSet features;
+ if (!GetFeatureSet(transport_type, serial, &features, ErrorAction::kPrintToStderr)) {
+ return 1;
+ }
+
for (const std::string& name : features) {
if (CanUseFeature(features, name)) {
printf("%s\n", name.c_str());
diff --git a/adb/services.cpp b/adb/services.cpp
index cd33e7b..9cbf787 100644
--- a/adb/services.cpp
+++ b/adb/services.cpp
@@ -32,6 +32,7 @@
#endif
#include <android-base/file.h>
+#include <android-base/parsenetaddress.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <cutils/sockets.h>
@@ -396,7 +397,7 @@
std::string serial;
std::string host;
int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
- if (!parse_host_and_port(address, &serial, &host, &port, response)) {
+ if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
return;
}
diff --git a/base/Android.mk b/base/Android.mk
index cba70d4..18f8686 100644
--- a/base/Android.mk
+++ b/base/Android.mk
@@ -19,6 +19,7 @@
libbase_src_files := \
file.cpp \
logging.cpp \
+ parsenetaddress.cpp \
stringprintf.cpp \
strings.cpp \
test_utils.cpp \
@@ -30,6 +31,7 @@
file_test.cpp \
logging_test.cpp \
parseint_test.cpp \
+ parsenetaddress_test.cpp \
stringprintf_test.cpp \
strings_test.cpp \
test_main.cpp \
diff --git a/base/include/android-base/parsenetaddress.h b/base/include/android-base/parsenetaddress.h
new file mode 100644
index 0000000..2de5ac9
--- /dev/null
+++ b/base/include/android-base/parsenetaddress.h
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+#ifndef BASE_PARSENETADDRESS_H
+#define BASE_PARSENETADDRESS_H
+
+#include <string>
+
+namespace android {
+namespace base {
+
+// Parses |address| into |host| and |port|.
+//
+// If |address| doesn't contain a port number, the default value is taken from
+// |port|. If |canonical_address| is non-null it will be set to "host:port" or
+// "[host]:port" as appropriate.
+//
+// On failure, returns false and fills |error|.
+bool ParseNetAddress(const std::string& address, std::string* host, int* port,
+ std::string* canonical_address, std::string* error);
+
+} // namespace base
+} // namespace android
+
+#endif // BASE_PARSENETADDRESS_H
diff --git a/base/parsenetaddress.cpp b/base/parsenetaddress.cpp
new file mode 100644
index 0000000..dd80f6d
--- /dev/null
+++ b/base/parsenetaddress.cpp
@@ -0,0 +1,82 @@
+/*
+ * 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 "android-base/parsenetaddress.h"
+
+#include <algorithm>
+
+#include "android-base/stringprintf.h"
+#include "android-base/strings.h"
+
+namespace android {
+namespace base {
+
+bool ParseNetAddress(const std::string& address, std::string* host, int* port,
+ std::string* canonical_address, std::string* error) {
+ host->clear();
+
+ bool ipv6 = true;
+ bool saw_port = false;
+ size_t colons = std::count(address.begin(), address.end(), ':');
+ size_t dots = std::count(address.begin(), address.end(), '.');
+ std::string port_str;
+ if (address[0] == '[') {
+ // [::1]:123
+ if (address.rfind("]:") == std::string::npos) {
+ *error = StringPrintf("bad IPv6 address '%s'", address.c_str());
+ return false;
+ }
+ *host = address.substr(1, (address.find("]:") - 1));
+ port_str = address.substr(address.rfind("]:") + 2);
+ saw_port = true;
+ } else if (dots == 0 && colons >= 2 && colons <= 7) {
+ // ::1
+ *host = address;
+ } else if (colons <= 1) {
+ // 1.2.3.4 or some.accidental.domain.com
+ ipv6 = false;
+ std::vector<std::string> pieces = Split(address, ":");
+ *host = pieces[0];
+ if (pieces.size() > 1) {
+ port_str = pieces[1];
+ saw_port = true;
+ }
+ }
+
+ if (host->empty()) {
+ *error = StringPrintf("no host in '%s'", address.c_str());
+ return false;
+ }
+
+ if (saw_port) {
+ if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 ||
+ *port > 65535) {
+ *error = StringPrintf("bad port number '%s' in '%s'", port_str.c_str(),
+ address.c_str());
+ return false;
+ }
+ }
+
+ if (canonical_address != nullptr) {
+ *canonical_address =
+ StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port);
+ }
+
+ return true;
+}
+
+} // namespace base
+} // namespace android
diff --git a/base/parsenetaddress_test.cpp b/base/parsenetaddress_test.cpp
new file mode 100644
index 0000000..a3bfac8
--- /dev/null
+++ b/base/parsenetaddress_test.cpp
@@ -0,0 +1,127 @@
+/*
+ * 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 "android-base/parsenetaddress.h"
+
+#include <gtest/gtest.h>
+
+using android::base::ParseNetAddress;
+
+TEST(ParseNetAddressTest, TestUrl) {
+ std::string canonical, host, error;
+ int port = 123;
+
+ EXPECT_TRUE(
+ ParseNetAddress("www.google.com", &host, &port, &canonical, &error));
+ EXPECT_EQ("www.google.com:123", canonical);
+ EXPECT_EQ("www.google.com", host);
+ EXPECT_EQ(123, port);
+
+ EXPECT_TRUE(
+ ParseNetAddress("www.google.com:666", &host, &port, &canonical, &error));
+ EXPECT_EQ("www.google.com:666", canonical);
+ EXPECT_EQ("www.google.com", host);
+ EXPECT_EQ(666, port);
+}
+
+TEST(ParseNetAddressTest, TestIpv4) {
+ std::string canonical, host, error;
+ int port = 123;
+
+ EXPECT_TRUE(ParseNetAddress("1.2.3.4", &host, &port, &canonical, &error));
+ EXPECT_EQ("1.2.3.4:123", canonical);
+ EXPECT_EQ("1.2.3.4", host);
+ EXPECT_EQ(123, port);
+
+ EXPECT_TRUE(ParseNetAddress("1.2.3.4:666", &host, &port, &canonical, &error));
+ EXPECT_EQ("1.2.3.4:666", canonical);
+ EXPECT_EQ("1.2.3.4", host);
+ EXPECT_EQ(666, port);
+}
+
+TEST(ParseNetAddressTest, TestIpv6) {
+ std::string canonical, host, error;
+ int port = 123;
+
+ EXPECT_TRUE(ParseNetAddress("::1", &host, &port, &canonical, &error));
+ EXPECT_EQ("[::1]:123", canonical);
+ EXPECT_EQ("::1", host);
+ EXPECT_EQ(123, port);
+
+ EXPECT_TRUE(ParseNetAddress("fe80::200:5aee:feaa:20a2", &host, &port,
+ &canonical, &error));
+ EXPECT_EQ("[fe80::200:5aee:feaa:20a2]:123", canonical);
+ EXPECT_EQ("fe80::200:5aee:feaa:20a2", host);
+ EXPECT_EQ(123, port);
+
+ EXPECT_TRUE(ParseNetAddress("[::1]:666", &host, &port, &canonical, &error));
+ EXPECT_EQ("[::1]:666", canonical);
+ EXPECT_EQ("::1", host);
+ EXPECT_EQ(666, port);
+
+ EXPECT_TRUE(ParseNetAddress("[fe80::200:5aee:feaa:20a2]:666", &host, &port,
+ &canonical, &error));
+ EXPECT_EQ("[fe80::200:5aee:feaa:20a2]:666", canonical);
+ EXPECT_EQ("fe80::200:5aee:feaa:20a2", host);
+ EXPECT_EQ(666, port);
+}
+
+TEST(ParseNetAddressTest, TestInvalidAddress) {
+ std::string canonical, host;
+ int port;
+
+ std::string failure_cases[] = {
+ // Invalid IPv4.
+ "1.2.3.4:",
+ "1.2.3.4::",
+ ":123",
+
+ // Invalid IPv6.
+ ":1",
+ "::::::::1",
+ "[::1",
+ "[::1]",
+ "[::1]:",
+ "[::1]::",
+
+ // Invalid port.
+ "1.2.3.4:-1",
+ "1.2.3.4:0",
+ "1.2.3.4:65536"
+ "1.2.3.4:hello",
+ "[::1]:-1",
+ "[::1]:0",
+ "[::1]:65536",
+ "[::1]:hello",
+ };
+
+ for (const auto& address : failure_cases) {
+ // Failure should give some non-empty error string.
+ std::string error;
+ EXPECT_FALSE(ParseNetAddress(address, &host, &port, &canonical, &error));
+ EXPECT_NE("", error);
+ }
+}
+
+// Null canonical address argument.
+TEST(ParseNetAddressTest, TestNullCanonicalAddress) {
+ std::string host, error;
+ int port = 42;
+
+ EXPECT_TRUE(ParseNetAddress("www.google.com", &host, &port, nullptr, &error));
+ EXPECT_TRUE(ParseNetAddress("1.2.3.4", &host, &port, nullptr, &error));
+ EXPECT_TRUE(ParseNetAddress("::1", &host, &port, nullptr, &error));
+}
diff --git a/bootstat/Android.mk b/bootstat/Android.mk
index 348db88..bbb903d 100644
--- a/bootstat/Android.mk
+++ b/bootstat/Android.mk
@@ -62,6 +62,8 @@
LOCAL_C_INCLUDES := $(bootstat_c_includes)
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_SRC_FILES := $(bootstat_lib_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_STATIC_LIBRARY)
@@ -76,6 +78,8 @@
LOCAL_C_INCLUDES := $(bootstat_c_includes)
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_SRC_FILES := $(bootstat_lib_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_STATIC_LIBRARY)
@@ -90,6 +94,8 @@
LOCAL_C_INCLUDES := $(bootstat_c_includes)
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_SRC_FILES := $(bootstat_lib_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_HOST_STATIC_LIBRARY)
@@ -104,7 +110,10 @@
LOCAL_C_INCLUDES := $(bootstat_c_includes)
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_STATIC_LIBRARIES := libbootstat
+LOCAL_INIT_RC := bootstat.rc
LOCAL_SRC_FILES := $(bootstat_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_EXECUTABLE)
@@ -119,6 +128,8 @@
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_STATIC_LIBRARIES := libbootstat_debug libgmock
LOCAL_SRC_FILES := $(bootstat_test_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_NATIVE_TEST)
@@ -133,5 +144,7 @@
LOCAL_SHARED_LIBRARIES := $(bootstat_shared_libs)
LOCAL_STATIC_LIBRARIES := libbootstat_host_debug libgmock_host
LOCAL_SRC_FILES := $(bootstat_test_src_files)
+# Clang is required because of C++14
+LOCAL_CLANG := true
include $(BUILD_HOST_NATIVE_TEST)
diff --git a/bootstat/boot_event_record_store.cpp b/bootstat/boot_event_record_store.cpp
index 4dab92e..1bdcf2b 100644
--- a/bootstat/boot_event_record_store.cpp
+++ b/bootstat/boot_event_record_store.cpp
@@ -21,6 +21,7 @@
#include <sys/stat.h>
#include <utime.h>
#include <cstdlib>
+#include <utility>
#include <android-base/file.h>
#include <android-base/logging.h>
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
new file mode 100644
index 0000000..2c37dd2
--- /dev/null
+++ b/bootstat/bootstat.rc
@@ -0,0 +1,14 @@
+# This file is the LOCAL_INIT_RC file for the bootstat command.
+
+on post-fs-data
+ mkdir /data/misc/bootstat 0700 root root
+
+# This marker, boot animation stopped, is considered the point at which the
+# the user may interact with the device, so it is a good proxy for the boot
+# complete signal.
+on property:init.svc.bootanim=stopped
+ # Record boot_complete timing event.
+ exec - root root -- /system/bin/bootstat -r boot_complete
+
+ # Log all boot events.
+ exec - root root -- /system/bin/bootstat -l
diff --git a/bootstat/event_log_list_builder.cpp b/bootstat/event_log_list_builder.cpp
index 7eb355a..241e3d5 100644
--- a/bootstat/event_log_list_builder.cpp
+++ b/bootstat/event_log_list_builder.cpp
@@ -17,6 +17,7 @@
#include "event_log_list_builder.h"
#include <cinttypes>
+#include <memory>
#include <string>
#include <android-base/logging.h>
#include <log/log.h>
diff --git a/fastboot/.clang-format b/fastboot/.clang-format
index 6737535..bcb8d8a 100644
--- a/fastboot/.clang-format
+++ b/fastboot/.clang-format
@@ -1,11 +1,14 @@
BasedOnStyle: Google
AllowShortBlocksOnASingleLine: false
-AllowShortFunctionsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Inline
ColumnLimit: 100
CommentPragmas: NOLINT:.*
DerivePointerAlignment: false
IndentWidth: 4
+ContinuationIndentWidth: 8
+ConstructorInitializerIndentWidth: 8
+AccessModifierOffset: -2
PointerAlignment: Left
TabWidth: 4
UseTab: Never
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index 8cbc79b..fcec5b1 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -24,7 +24,15 @@
$(LOCAL_PATH)/../../extras/ext4_utils \
$(LOCAL_PATH)/../../extras/f2fs_utils \
-LOCAL_SRC_FILES := protocol.cpp engine.cpp bootimg_utils.cpp fastboot.cpp util.cpp fs.cpp
+LOCAL_SRC_FILES := \
+ bootimg_utils.cpp \
+ engine.cpp \
+ fastboot.cpp \
+ fs.cpp\
+ protocol.cpp \
+ socket.cpp \
+ util.cpp \
+
LOCAL_MODULE := fastboot
LOCAL_MODULE_TAGS := debug
LOCAL_MODULE_HOST_OS := darwin linux windows
@@ -33,15 +41,15 @@
LOCAL_CFLAGS += -DFASTBOOT_REVISION='"$(fastboot_version)"'
-LOCAL_SRC_FILES_linux := socket_unix.cpp usb_linux.cpp util_linux.cpp
-LOCAL_STATIC_LIBRARIES_linux := libcutils libselinux
+LOCAL_SRC_FILES_linux := usb_linux.cpp util_linux.cpp
+LOCAL_STATIC_LIBRARIES_linux := libselinux
-LOCAL_SRC_FILES_darwin := socket_unix.cpp usb_osx.cpp util_osx.cpp
-LOCAL_STATIC_LIBRARIES_darwin := libcutils libselinux
+LOCAL_SRC_FILES_darwin := usb_osx.cpp util_osx.cpp
+LOCAL_STATIC_LIBRARIES_darwin := libselinux
LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
LOCAL_CFLAGS_darwin := -Wno-unused-parameter
-LOCAL_SRC_FILES_windows := socket_windows.cpp usb_windows.cpp util_windows.cpp
+LOCAL_SRC_FILES_windows := usb_windows.cpp util_windows.cpp
LOCAL_STATIC_LIBRARIES_windows := AdbWinApi
LOCAL_REQUIRED_MODULES_windows := AdbWinApi
LOCAL_LDLIBS_windows := -lws2_32
@@ -56,6 +64,7 @@
libz \
libdiagnose_usb \
libbase \
+ libcutils \
# libf2fs_dlutils_host will dlopen("libf2fs_fmt_host_dyn")
LOCAL_CFLAGS_linux := -DUSE_F2FS
@@ -97,20 +106,14 @@
LOCAL_MODULE := fastboot_test
LOCAL_MODULE_HOST_OS := darwin linux windows
-LOCAL_SRC_FILES := socket_test.cpp
-LOCAL_STATIC_LIBRARIES := libbase
+LOCAL_SRC_FILES := socket.cpp socket_test.cpp
+LOCAL_STATIC_LIBRARIES := libbase libcutils
LOCAL_CFLAGS += -Wall -Wextra -Werror -Wunreachable-code
-LOCAL_SRC_FILES_linux := socket_unix.cpp
-LOCAL_STATIC_LIBRARIES_linux := libcutils
-
-LOCAL_SRC_FILES_darwin := socket_unix.cpp
LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
LOCAL_CFLAGS_darwin := -Wno-unused-parameter
-LOCAL_STATIC_LIBRARIES_darwin := libcutils
-LOCAL_SRC_FILES_windows := socket_windows.cpp
LOCAL_LDLIBS_windows := -lws2_32
include $(BUILD_HOST_NATIVE_TEST)
diff --git a/fastboot/socket.cpp b/fastboot/socket.cpp
new file mode 100644
index 0000000..d41f1fe
--- /dev/null
+++ b/fastboot/socket.cpp
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "socket.h"
+
+#include <android-base/stringprintf.h>
+
+Socket::Socket(cutils_socket_t sock) : sock_(sock) {}
+
+Socket::~Socket() {
+ Close();
+}
+
+int Socket::Close() {
+ int ret = 0;
+
+ if (sock_ != INVALID_SOCKET) {
+ ret = socket_close(sock_);
+ sock_ = INVALID_SOCKET;
+ }
+
+ return ret;
+}
+
+bool Socket::SetReceiveTimeout(int timeout_ms) {
+ if (timeout_ms != receive_timeout_ms_) {
+ if (socket_set_receive_timeout(sock_, timeout_ms) == 0) {
+ receive_timeout_ms_ = timeout_ms;
+ return true;
+ }
+ return false;
+ }
+
+ return true;
+}
+
+ssize_t Socket::ReceiveAll(void* data, size_t length, int timeout_ms) {
+ size_t total = 0;
+
+ while (total < length) {
+ ssize_t bytes = Receive(reinterpret_cast<char*>(data) + total, length - total, timeout_ms);
+
+ if (bytes == -1) {
+ if (total == 0) {
+ return -1;
+ }
+ break;
+ }
+ total += bytes;
+ }
+
+ return total;
+}
+
+// Implements the Socket interface for UDP.
+class UdpSocket : public Socket {
+ public:
+ enum class Type { kClient, kServer };
+
+ UdpSocket(Type type, cutils_socket_t sock);
+
+ ssize_t Send(const void* data, size_t length) override;
+ ssize_t Receive(void* data, size_t length, int timeout_ms) override;
+
+ private:
+ std::unique_ptr<sockaddr_storage> addr_;
+ socklen_t addr_size_ = 0;
+
+ DISALLOW_COPY_AND_ASSIGN(UdpSocket);
+};
+
+UdpSocket::UdpSocket(Type type, cutils_socket_t sock) : Socket(sock) {
+ // Only servers need to remember addresses; clients are connected to a server in NewClient()
+ // so will send to that server without needing to specify the address again.
+ if (type == Type::kServer) {
+ addr_.reset(new sockaddr_storage);
+ addr_size_ = sizeof(*addr_);
+ memset(addr_.get(), 0, addr_size_);
+ }
+}
+
+ssize_t UdpSocket::Send(const void* data, size_t length) {
+ return TEMP_FAILURE_RETRY(sendto(sock_, reinterpret_cast<const char*>(data), length, 0,
+ reinterpret_cast<sockaddr*>(addr_.get()), addr_size_));
+}
+
+ssize_t UdpSocket::Receive(void* data, size_t length, int timeout_ms) {
+ if (!SetReceiveTimeout(timeout_ms)) {
+ return -1;
+ }
+
+ socklen_t* addr_size_ptr = nullptr;
+ if (addr_ != nullptr) {
+ // Reset addr_size as it may have been modified by previous recvfrom() calls.
+ addr_size_ = sizeof(*addr_);
+ addr_size_ptr = &addr_size_;
+ }
+
+ return TEMP_FAILURE_RETRY(recvfrom(sock_, reinterpret_cast<char*>(data), length, 0,
+ reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr));
+}
+
+// Implements the Socket interface for TCP.
+class TcpSocket : public Socket {
+ public:
+ TcpSocket(cutils_socket_t sock) : Socket(sock) {}
+
+ ssize_t Send(const void* data, size_t length) override;
+ ssize_t Receive(void* data, size_t length, int timeout_ms) override;
+
+ std::unique_ptr<Socket> Accept() override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(TcpSocket);
+};
+
+ssize_t TcpSocket::Send(const void* data, size_t length) {
+ size_t total = 0;
+
+ while (total < length) {
+ ssize_t bytes = TEMP_FAILURE_RETRY(
+ send(sock_, reinterpret_cast<const char*>(data) + total, length - total, 0));
+
+ if (bytes == -1) {
+ if (total == 0) {
+ return -1;
+ }
+ break;
+ }
+ total += bytes;
+ }
+
+ return total;
+}
+
+ssize_t TcpSocket::Receive(void* data, size_t length, int timeout_ms) {
+ if (!SetReceiveTimeout(timeout_ms)) {
+ return -1;
+ }
+
+ return TEMP_FAILURE_RETRY(recv(sock_, reinterpret_cast<char*>(data), length, 0));
+}
+
+std::unique_ptr<Socket> TcpSocket::Accept() {
+ cutils_socket_t handler = accept(sock_, nullptr, nullptr);
+ if (handler == INVALID_SOCKET) {
+ return nullptr;
+ }
+ return std::unique_ptr<TcpSocket>(new TcpSocket(handler));
+}
+
+std::unique_ptr<Socket> Socket::NewClient(Protocol protocol, const std::string& host, int port,
+ std::string* error) {
+ if (protocol == Protocol::kUdp) {
+ cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_DGRAM);
+ if (sock != INVALID_SOCKET) {
+ return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kClient, sock));
+ }
+ } else {
+ cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_STREAM);
+ if (sock != INVALID_SOCKET) {
+ return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
+ }
+ }
+
+ if (error) {
+ *error = android::base::StringPrintf("Failed to connect to %s:%d", host.c_str(), port);
+ }
+ return nullptr;
+}
+
+// This functionality is currently only used by tests so we don't need any error messages.
+std::unique_ptr<Socket> Socket::NewServer(Protocol protocol, int port) {
+ if (protocol == Protocol::kUdp) {
+ cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_DGRAM);
+ if (sock != INVALID_SOCKET) {
+ return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kServer, sock));
+ }
+ } else {
+ cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_STREAM);
+ if (sock != INVALID_SOCKET) {
+ return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
+ }
+ }
+
+ return nullptr;
+}
diff --git a/fastboot/socket.h b/fastboot/socket.h
index 888b530..3e66c27 100644
--- a/fastboot/socket.h
+++ b/fastboot/socket.h
@@ -26,36 +26,41 @@
* SUCH DAMAGE.
*/
-// This file provides a class interface for cross-platform UDP functionality. The main fastboot
+// This file provides a class interface for cross-platform socket functionality. The main fastboot
// engine should not be using this interface directly, but instead should use a higher-level
-// interface that enforces the fastboot UDP protocol.
+// interface that enforces the fastboot protocol.
#ifndef SOCKET_H_
#define SOCKET_H_
-#include "android-base/macros.h"
-
#include <memory>
#include <string>
-// UdpSocket interface to be implemented for each platform.
-class UdpSocket {
+#include <android-base/macros.h>
+#include <cutils/sockets.h>
+
+// Socket interface to be implemented for each platform.
+class Socket {
public:
+ enum class Protocol { kTcp, kUdp };
+
// Creates a new client connection. Clients are connected to a specific hostname/port and can
// only send to that destination.
// On failure, |error| is filled (if non-null) and nullptr is returned.
- static std::unique_ptr<UdpSocket> NewUdpClient(const std::string& hostname, int port,
- std::string* error);
+ static std::unique_ptr<Socket> NewClient(Protocol protocol, const std::string& hostname,
+ int port, std::string* error);
// Creates a new server bound to local |port|. This is only meant for testing, during normal
// fastboot operation the device acts as the server.
- // The server saves sender addresses in Receive(), and uses the most recent address during
+ // A UDP server saves sender addresses in Receive(), and uses the most recent address during
// calls to Send().
- static std::unique_ptr<UdpSocket> NewUdpServer(int port);
+ static std::unique_ptr<Socket> NewServer(Protocol protocol, int port);
- virtual ~UdpSocket() = default;
+ // Destructor closes the socket if it's open.
+ virtual ~Socket();
- // Sends |length| bytes of |data|. Returns the number of bytes actually sent or -1 on error.
+ // Sends |length| bytes of |data|. For TCP sockets this will continue trying to send until all
+ // bytes are transmitted. Returns the number of bytes actually sent or -1 on error.
virtual ssize_t Send(const void* data, size_t length) = 0;
// Waits up to |timeout_ms| to receive up to |length| bytes of data. |timout_ms| of 0 will
@@ -63,14 +68,29 @@
// errno will be set to EAGAIN or EWOULDBLOCK.
virtual ssize_t Receive(void* data, size_t length, int timeout_ms) = 0;
+ // Calls Receive() until exactly |length| bytes have been received or an error occurs.
+ virtual ssize_t ReceiveAll(void* data, size_t length, int timeout_ms);
+
// Closes the socket. Returns 0 on success, -1 on error.
- virtual int Close() = 0;
+ virtual int Close();
+
+ // Accepts an incoming TCP connection. No effect for UDP sockets. Returns a new Socket
+ // connected to the client on success, nullptr on failure.
+ virtual std::unique_ptr<Socket> Accept() { return nullptr; }
protected:
// Protected constructor to force factory function use.
- UdpSocket() = default;
+ Socket(cutils_socket_t sock);
- DISALLOW_COPY_AND_ASSIGN(UdpSocket);
+ // Update the socket receive timeout if necessary.
+ bool SetReceiveTimeout(int timeout_ms);
+
+ cutils_socket_t sock_ = INVALID_SOCKET;
+
+ private:
+ int receive_timeout_ms_ = 0;
+
+ DISALLOW_COPY_AND_ASSIGN(Socket);
};
#endif // SOCKET_H_
diff --git a/fastboot/socket_test.cpp b/fastboot/socket_test.cpp
index 6ada964..1fd9d7c 100644
--- a/fastboot/socket_test.cpp
+++ b/fastboot/socket_test.cpp
@@ -14,184 +14,113 @@
* limitations under the License.
*/
-// Tests UDP functionality using loopback connections. Requires that kDefaultPort is available
+// Tests UDP functionality using loopback connections. Requires that kTestPort is available
// for loopback communication on the host. These tests also assume that no UDP packets are lost,
// which should be the case for loopback communication, but is not guaranteed.
#include "socket.h"
-#include <errno.h>
-#include <time.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
#include <gtest/gtest.h>
enum {
// This port must be available for loopback communication.
- kDefaultPort = 54321,
+ kTestPort = 54321,
// Don't wait forever in a unit test.
- kDefaultTimeoutMs = 3000,
+ kTestTimeoutMs = 3000,
};
-static const char kReceiveStringError[] = "Error receiving string";
-
-// Test fixture to provide some helper functions. Makes each test a little simpler since we can
-// just check a bool for socket creation and don't have to pass hostname or port information.
-class SocketTest : public ::testing::Test {
- protected:
- bool StartServer(int port = kDefaultPort) {
- server_ = UdpSocket::NewUdpServer(port);
- return server_ != nullptr;
+// Creates connected sockets |server| and |client|. Returns true on success.
+bool MakeConnectedSockets(Socket::Protocol protocol, std::unique_ptr<Socket>* server,
+ std::unique_ptr<Socket>* client, const std::string hostname = "localhost",
+ int port = kTestPort) {
+ *server = Socket::NewServer(protocol, port);
+ if (*server == nullptr) {
+ ADD_FAILURE() << "Failed to create server.";
+ return false;
}
- bool StartClient(const std::string hostname = "localhost", int port = kDefaultPort) {
- client_ = UdpSocket::NewUdpClient(hostname, port, nullptr);
- return client_ != nullptr;
+ *client = Socket::NewClient(protocol, hostname, port, nullptr);
+ if (*client == nullptr) {
+ ADD_FAILURE() << "Failed to create client.";
+ return false;
}
- bool StartClient2(const std::string hostname = "localhost", int port = kDefaultPort) {
- client2_ = UdpSocket::NewUdpClient(hostname, port, nullptr);
- return client2_ != nullptr;
+ // TCP passes the client off to a new socket.
+ if (protocol == Socket::Protocol::kTcp) {
+ *server = (*server)->Accept();
+ if (*server == nullptr) {
+ ADD_FAILURE() << "Failed to accept client connection.";
+ return false;
+ }
}
- std::unique_ptr<UdpSocket> server_, client_, client2_;
-};
+ return true;
+}
-// Sends a string over a UdpSocket. Returns true if the full string (without terminating char)
+// Sends a string over a Socket. Returns true if the full string (without terminating char)
// was sent.
-static bool SendString(UdpSocket* udp, const std::string& message) {
- return udp->Send(message.c_str(), message.length()) == static_cast<ssize_t>(message.length());
+static bool SendString(Socket* sock, const std::string& message) {
+ return sock->Send(message.c_str(), message.length()) == static_cast<ssize_t>(message.length());
}
-// Receives a string from a UdpSocket. Returns the string, or kReceiveStringError on failure.
-static std::string ReceiveString(UdpSocket* udp, size_t receive_size = 128) {
- std::vector<char> buffer(receive_size);
-
- ssize_t result = udp->Receive(buffer.data(), buffer.size(), kDefaultTimeoutMs);
- if (result >= 0) {
- return std::string(buffer.data(), result);
- }
- return kReceiveStringError;
-}
-
-// Calls Receive() on the UdpSocket with the given timeout. Returns true if the call timed out.
-static bool ReceiveTimeout(UdpSocket* udp, int timeout_ms) {
- char buffer[1];
-
- errno = 0;
- return udp->Receive(buffer, 1, timeout_ms) == -1 && (errno == EAGAIN || errno == EWOULDBLOCK);
+// Receives a string from a Socket. Returns true if the full string (without terminating char)
+// was received.
+static bool ReceiveString(Socket* sock, const std::string& message) {
+ std::string received(message.length(), '\0');
+ ssize_t bytes = sock->ReceiveAll(&received[0], received.length(), kTestTimeoutMs);
+ return static_cast<size_t>(bytes) == received.length() && received == message;
}
// Tests sending packets client -> server, then server -> client.
-TEST_F(SocketTest, SendAndReceive) {
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient());
+TEST(SocketTest, TestSendAndReceive) {
+ std::unique_ptr<Socket> server, client;
- EXPECT_TRUE(SendString(client_.get(), "foo"));
- EXPECT_EQ("foo", ReceiveString(server_.get()));
+ for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
+ ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
- EXPECT_TRUE(SendString(server_.get(), "bar baz"));
- EXPECT_EQ("bar baz", ReceiveString(client_.get()));
+ EXPECT_TRUE(SendString(client.get(), "foo"));
+ EXPECT_TRUE(ReceiveString(server.get(), "foo"));
+
+ EXPECT_TRUE(SendString(server.get(), "bar baz"));
+ EXPECT_TRUE(ReceiveString(client.get(), "bar baz"));
+ }
}
// Tests sending and receiving large packets.
-TEST_F(SocketTest, LargePackets) {
- std::string message(512, '\0');
+TEST(SocketTest, TestLargePackets) {
+ std::string message(1024, '\0');
+ std::unique_ptr<Socket> server, client;
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient());
+ for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
+ ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
- // Run through the test a few times.
- for (int i = 0; i < 10; ++i) {
- // Use a different message each iteration to prevent false positives.
- for (size_t j = 0; j < message.length(); ++j) {
- message[j] = static_cast<char>(i + j);
+ // Run through the test a few times.
+ for (int i = 0; i < 10; ++i) {
+ // Use a different message each iteration to prevent false positives.
+ for (size_t j = 0; j < message.length(); ++j) {
+ message[j] = static_cast<char>(i + j);
+ }
+
+ EXPECT_TRUE(SendString(client.get(), message));
+ EXPECT_TRUE(ReceiveString(server.get(), message));
}
-
- EXPECT_TRUE(SendString(client_.get(), message));
- EXPECT_EQ(message, ReceiveString(server_.get(), message.length()));
}
}
-// Tests IPv4 client/server.
-TEST_F(SocketTest, IPv4) {
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient("127.0.0.1"));
+// Tests UDP receive overflow when the UDP packet is larger than the receive buffer.
+TEST(SocketTest, TestUdpReceiveOverflow) {
+ std::unique_ptr<Socket> server, client;
+ ASSERT_TRUE(MakeConnectedSockets(Socket::Protocol::kUdp, &server, &client));
- EXPECT_TRUE(SendString(client_.get(), "foo"));
- EXPECT_EQ("foo", ReceiveString(server_.get()));
+ EXPECT_TRUE(SendString(client.get(), "1234567890"));
- EXPECT_TRUE(SendString(server_.get(), "bar"));
- EXPECT_EQ("bar", ReceiveString(client_.get()));
-}
-
-// Tests IPv6 client/server.
-TEST_F(SocketTest, IPv6) {
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient("::1"));
-
- EXPECT_TRUE(SendString(client_.get(), "foo"));
- EXPECT_EQ("foo", ReceiveString(server_.get()));
-
- EXPECT_TRUE(SendString(server_.get(), "bar"));
- EXPECT_EQ("bar", ReceiveString(client_.get()));
-}
-
-// Tests receive timeout. The timing verification logic must be very coarse to make sure different
-// systems running different loads can all pass these tests.
-TEST_F(SocketTest, ReceiveTimeout) {
- time_t start_time;
-
- ASSERT_TRUE(StartServer());
-
- // Make sure a 20ms timeout completes in 1 second or less.
- start_time = time(nullptr);
- EXPECT_TRUE(ReceiveTimeout(server_.get(), 20));
- EXPECT_LE(difftime(time(nullptr), start_time), 1.0);
-
- // Make sure a 1250ms timeout takes 1 second or more.
- start_time = time(nullptr);
- EXPECT_TRUE(ReceiveTimeout(server_.get(), 1250));
- EXPECT_LE(1.0, difftime(time(nullptr), start_time));
-}
-
-// Tests receive overflow (the UDP packet is larger than the receive buffer).
-TEST_F(SocketTest, ReceiveOverflow) {
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient());
-
- EXPECT_TRUE(SendString(client_.get(), "1234567890"));
-
- // This behaves differently on different systems; some give us a truncated UDP packet, others
- // will error out and not return anything at all.
- std::string rx_string = ReceiveString(server_.get(), 5);
-
- // If we didn't get an error then the packet should have been truncated.
- if (rx_string != kReceiveStringError) {
- EXPECT_EQ("12345", rx_string);
+ // This behaves differently on different systems, either truncating the packet or returning -1.
+ char buffer[5];
+ ssize_t bytes = server->Receive(buffer, 5, kTestTimeoutMs);
+ if (bytes == 5) {
+ EXPECT_EQ(0, memcmp(buffer, "12345", 5));
+ } else {
+ EXPECT_EQ(-1, bytes);
}
}
-
-// Tests multiple clients sending to the same server.
-TEST_F(SocketTest, MultipleClients) {
- ASSERT_TRUE(StartServer());
- ASSERT_TRUE(StartClient());
- ASSERT_TRUE(StartClient2());
-
- EXPECT_TRUE(SendString(client_.get(), "client"));
- EXPECT_TRUE(SendString(client2_.get(), "client2"));
-
- // Receive the packets and send a response for each (note that packets may be received
- // out-of-order).
- for (int i = 0; i < 2; ++i) {
- std::string received = ReceiveString(server_.get());
- EXPECT_TRUE(SendString(server_.get(), received + " response"));
- }
-
- EXPECT_EQ("client response", ReceiveString(client_.get()));
- EXPECT_EQ("client2 response", ReceiveString(client2_.get()));
-}
diff --git a/fastboot/socket_unix.cpp b/fastboot/socket_unix.cpp
deleted file mode 100644
index 462256a..0000000
--- a/fastboot/socket_unix.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "socket.h"
-
-#include <errno.h>
-#include <netdb.h>
-
-#include <android-base/stringprintf.h>
-#include <cutils/sockets.h>
-
-class UnixUdpSocket : public UdpSocket {
- public:
- enum class Type { kClient, kServer };
-
- UnixUdpSocket(int fd, Type type);
- ~UnixUdpSocket() override;
-
- ssize_t Send(const void* data, size_t length) override;
- ssize_t Receive(void* data, size_t length, int timeout_ms) override;
- int Close() override;
-
- private:
- int fd_;
- int receive_timeout_ms_ = 0;
- std::unique_ptr<sockaddr_storage> addr_;
- socklen_t addr_size_ = 0;
-
- DISALLOW_COPY_AND_ASSIGN(UnixUdpSocket);
-};
-
-UnixUdpSocket::UnixUdpSocket(int fd, Type type) : fd_(fd) {
- // Only servers need to remember addresses; clients are connected to a server in NewUdpClient()
- // so will send to that server without needing to specify the address again.
- if (type == Type::kServer) {
- addr_.reset(new sockaddr_storage);
- addr_size_ = sizeof(*addr_);
- memset(addr_.get(), 0, addr_size_);
- }
-}
-
-UnixUdpSocket::~UnixUdpSocket() {
- Close();
-}
-
-ssize_t UnixUdpSocket::Send(const void* data, size_t length) {
- return TEMP_FAILURE_RETRY(
- sendto(fd_, data, length, 0, reinterpret_cast<sockaddr*>(addr_.get()), addr_size_));
-}
-
-ssize_t UnixUdpSocket::Receive(void* data, size_t length, int timeout_ms) {
- // Only set socket timeout if it's changed.
- if (receive_timeout_ms_ != timeout_ms) {
- timeval tv;
- tv.tv_sec = timeout_ms / 1000;
- tv.tv_usec = (timeout_ms % 1000) * 1000;
- if (setsockopt(fd_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
- return -1;
- }
- receive_timeout_ms_ = timeout_ms;
- }
-
- socklen_t* addr_size_ptr = nullptr;
- if (addr_ != nullptr) {
- // Reset addr_size as it may have been modified by previous recvfrom() calls.
- addr_size_ = sizeof(*addr_);
- addr_size_ptr = &addr_size_;
- }
- return TEMP_FAILURE_RETRY(recvfrom(fd_, data, length, 0,
- reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr));
-}
-
-int UnixUdpSocket::Close() {
- int result = 0;
- if (fd_ != -1) {
- result = close(fd_);
- fd_ = -1;
- }
- return result;
-}
-
-std::unique_ptr<UdpSocket> UdpSocket::NewUdpClient(const std::string& host, int port,
- std::string* error) {
- int getaddrinfo_error = 0;
- int fd = socket_network_client_timeout(host.c_str(), port, SOCK_DGRAM, 0, &getaddrinfo_error);
- if (fd == -1) {
- if (error) {
- *error = android::base::StringPrintf(
- "Failed to connect to %s:%d: %s", host.c_str(), port,
- getaddrinfo_error ? gai_strerror(getaddrinfo_error) : strerror(errno));
- }
- return nullptr;
- }
-
- return std::unique_ptr<UdpSocket>(new UnixUdpSocket(fd, UnixUdpSocket::Type::kClient));
-}
-
-std::unique_ptr<UdpSocket> UdpSocket::NewUdpServer(int port) {
- int fd = socket_inaddr_any_server(port, SOCK_DGRAM);
- if (fd == -1) {
- // This is just used in testing, no need for an error message.
- return nullptr;
- }
-
- return std::unique_ptr<UdpSocket>(new UnixUdpSocket(fd, UnixUdpSocket::Type::kServer));
-}
diff --git a/fastboot/socket_windows.cpp b/fastboot/socket_windows.cpp
deleted file mode 100644
index 4ad379f..0000000
--- a/fastboot/socket_windows.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "socket.h"
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-
-#include <memory>
-
-#include <android-base/stringprintf.h>
-
-// Windows UDP socket functionality.
-class WindowsUdpSocket : public UdpSocket {
- public:
- enum class Type { kClient, kServer };
-
- WindowsUdpSocket(SOCKET sock, Type type);
- ~WindowsUdpSocket() override;
-
- ssize_t Send(const void* data, size_t len) override;
- ssize_t Receive(void* data, size_t len, int timeout_ms) override;
- int Close() override;
-
- private:
- SOCKET sock_;
- int receive_timeout_ms_ = 0;
- std::unique_ptr<sockaddr_storage> addr_;
- int addr_size_ = 0;
-
- DISALLOW_COPY_AND_ASSIGN(WindowsUdpSocket);
-};
-
-WindowsUdpSocket::WindowsUdpSocket(SOCKET sock, Type type) : sock_(sock) {
- // Only servers need to remember addresses; clients are connected to a server in NewUdpClient()
- // so will send to that server without needing to specify the address again.
- if (type == Type::kServer) {
- addr_.reset(new sockaddr_storage);
- addr_size_ = sizeof(*addr_);
- memset(addr_.get(), 0, addr_size_);
- }
-}
-
-WindowsUdpSocket::~WindowsUdpSocket() {
- Close();
-}
-
-ssize_t WindowsUdpSocket::Send(const void* data, size_t len) {
- return sendto(sock_, reinterpret_cast<const char*>(data), len, 0,
- reinterpret_cast<sockaddr*>(addr_.get()), addr_size_);
-}
-
-ssize_t WindowsUdpSocket::Receive(void* data, size_t len, int timeout_ms) {
- // Only set socket timeout if it's changed.
- if (receive_timeout_ms_ != timeout_ms) {
- if (setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout_ms),
- sizeof(timeout_ms)) < 0) {
- return -1;
- }
- receive_timeout_ms_ = timeout_ms;
- }
-
- int* addr_size_ptr = nullptr;
- if (addr_ != nullptr) {
- // Reset addr_size as it may have been modified by previous recvfrom() calls.
- addr_size_ = sizeof(*addr_);
- addr_size_ptr = &addr_size_;
- }
- int result = recvfrom(sock_, reinterpret_cast<char*>(data), len, 0,
- reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr);
- if (result < 0 && WSAGetLastError() == WSAETIMEDOUT) {
- errno = EAGAIN;
- }
- return result;
-}
-
-int WindowsUdpSocket::Close() {
- int result = 0;
- if (sock_ != INVALID_SOCKET) {
- result = closesocket(sock_);
- sock_ = INVALID_SOCKET;
- }
- return result;
-}
-
-static int GetProtocol(int sock_type) {
- switch (sock_type) {
- case SOCK_DGRAM:
- return IPPROTO_UDP;
- case SOCK_STREAM:
- return IPPROTO_TCP;
- default:
- // 0 lets the system decide which protocol to use.
- return 0;
- }
-}
-
-// Windows implementation of this libcutils function. This function does not make any calls to
-// WSAStartup() or WSACleanup() so that must be handled by the caller.
-// TODO(dpursell): share this code with adb.
-static SOCKET socket_network_client(const std::string& host, int port, int type) {
- // First resolve the host and port parameters into a usable network address.
- addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- hints.ai_socktype = type;
- hints.ai_protocol = GetProtocol(type);
-
- addrinfo* address = nullptr;
- getaddrinfo(host.c_str(), android::base::StringPrintf("%d", port).c_str(), &hints, &address);
- if (address == nullptr) {
- return INVALID_SOCKET;
- }
-
- // Now create and connect the socket.
- SOCKET sock = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
- if (sock == INVALID_SOCKET) {
- freeaddrinfo(address);
- return INVALID_SOCKET;
- }
-
- if (connect(sock, address->ai_addr, address->ai_addrlen) == SOCKET_ERROR) {
- closesocket(sock);
- freeaddrinfo(address);
- return INVALID_SOCKET;
- }
-
- freeaddrinfo(address);
- return sock;
-}
-
-// Windows implementation of this libcutils function. This implementation creates a dual-stack
-// server socket that can accept incoming IPv4 or IPv6 packets. This function does not make any
-// calls to WSAStartup() or WSACleanup() so that must be handled by the caller.
-// TODO(dpursell): share this code with adb.
-static SOCKET socket_inaddr_any_server(int port, int type) {
- SOCKET sock = socket(AF_INET6, type, GetProtocol(type));
- if (sock == INVALID_SOCKET) {
- return INVALID_SOCKET;
- }
-
- // Enforce exclusive addresses (1), and enable dual-stack so both IPv4 and IPv6 work (2).
- // (1) https://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx.
- // (2) https://msdn.microsoft.com/en-us/library/windows/desktop/bb513665(v=vs.85).aspx.
- int exclusive = 1;
- DWORD v6_only = 0;
- if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char*>(&exclusive),
- sizeof(exclusive)) == SOCKET_ERROR ||
- setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&v6_only),
- sizeof(v6_only)) == SOCKET_ERROR) {
- closesocket(sock);
- return INVALID_SOCKET;
- }
-
- // Bind the socket to our local port.
- sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- addr.sin6_port = htons(port);
- addr.sin6_addr = in6addr_any;
- if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == SOCKET_ERROR) {
- closesocket(sock);
- return INVALID_SOCKET;
- }
-
- return sock;
-}
-
-// Documentation at https://msdn.microsoft.com/en-us/library/windows/desktop/ms741549(v=vs.85).aspx
-// claims WSACleanup() should be called before program exit, but general consensus seems to be that
-// it hasn't actually been necessary for a long time, possibly since Windows 3.1.
-//
-// Both adb (1) and Chrome (2) purposefully avoid WSACleanup(), and since no adverse affects have
-// been found we may as well do the same here to keep this code simpler.
-// (1) https://android.googlesource.com/platform/system/core.git/+/master/adb/sysdeps_win32.cpp#816
-// (2) https://code.google.com/p/chromium/codesearch#chromium/src/net/base/winsock_init.cc&l=35
-static bool InitWinsock() {
- static bool init_success = false;
-
- if (!init_success) {
- WSADATA wsaData;
- init_success = (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0);
- }
-
- return init_success;
-}
-
-std::unique_ptr<UdpSocket> UdpSocket::NewUdpClient(const std::string& host, int port,
- std::string* error) {
- if (!InitWinsock()) {
- if (error) {
- *error = android::base::StringPrintf("Failed to initialize Winsock (error %d)",
- WSAGetLastError());
- }
- return nullptr;
- }
-
- SOCKET sock = socket_network_client(host, port, SOCK_DGRAM);
- if (sock == INVALID_SOCKET) {
- if (error) {
- *error = android::base::StringPrintf("Failed to connect to %s:%d (error %d)",
- host.c_str(), port, WSAGetLastError());
- }
- return nullptr;
- }
-
- return std::unique_ptr<UdpSocket>(new WindowsUdpSocket(sock, WindowsUdpSocket::Type::kClient));
-}
-
-// This functionality is currently only used by tests so we don't need any error messages.
-std::unique_ptr<UdpSocket> UdpSocket::NewUdpServer(int port) {
- if (!InitWinsock()) {
- return nullptr;
- }
-
- SOCKET sock = socket_inaddr_any_server(port, SOCK_DGRAM);
- if (sock == INVALID_SOCKET) {
- return nullptr;
- }
-
- return std::unique_ptr<UdpSocket>(new WindowsUdpSocket(sock, WindowsUdpSocket::Type::kServer));
-}
diff --git a/include/cutils/sockets.h b/include/cutils/sockets.h
index 2d3c743..e25c555 100644
--- a/include/cutils/sockets.h
+++ b/include/cutils/sockets.h
@@ -24,10 +24,20 @@
#include <stdbool.h>
#if defined(_WIN32)
+
#include <winsock2.h>
+#include <ws2tcpip.h>
+
typedef int socklen_t;
+typedef SOCKET cutils_socket_t;
+
#else
+
#include <sys/socket.h>
+
+typedef int cutils_socket_t;
+#define INVALID_SOCKET (-1)
+
#endif
#define ANDROID_SOCKET_ENV_PREFIX "ANDROID_SOCKET_"
@@ -45,7 +55,7 @@
* This is inline and not in libcutils proper because we want to use this in
* third-party daemons with minimal modification.
*/
-static inline int android_get_control_socket(const char *name)
+static inline int android_get_control_socket(const char* name)
{
char key[64];
snprintf(key, sizeof(key), ANDROID_SOCKET_ENV_PREFIX "%s", name);
@@ -74,17 +84,52 @@
// Normal filesystem namespace
#define ANDROID_SOCKET_NAMESPACE_FILESYSTEM 2
-extern int socket_loopback_client(int port, int type);
-extern int socket_network_client(const char *host, int port, int type);
-extern int socket_network_client_timeout(const char *host, int port, int type,
- int timeout, int* getaddrinfo_error);
-extern int socket_loopback_server(int port, int type);
-extern int socket_local_server(const char *name, int namespaceId, int type);
-extern int socket_local_server_bind(int s, const char *name, int namespaceId);
-extern int socket_local_client_connect(int fd,
- const char *name, int namespaceId, int type);
-extern int socket_local_client(const char *name, int namespaceId, int type);
-extern int socket_inaddr_any_server(int port, int type);
+/*
+ * Functions to create sockets for some common usages.
+ *
+ * All these functions are implemented for Unix, but only a few are implemented
+ * for Windows. Those which are can be identified by the cutils_socket_t
+ * return type. The idea is to be able to use this return value with the
+ * standard Unix socket functions on any platform.
+ *
+ * On Unix the returned cutils_socket_t is a standard int file descriptor and
+ * can always be used as normal with all file descriptor functions.
+ *
+ * On Windows utils_socket_t is an unsigned int pointer, and is only valid
+ * with functions that specifically take a socket, e.g. send(), sendto(),
+ * recv(), and recvfrom(). General file descriptor functions such as read(),
+ * write(), and close() will not work with utils_socket_t and will require
+ * special handling.
+ *
+ * These functions return INVALID_SOCKET (-1) on failure for all platforms.
+ */
+int socket_loopback_client(int port, int type);
+cutils_socket_t socket_network_client(const char* host, int port, int type);
+int socket_network_client_timeout(const char* host, int port, int type,
+ int timeout, int* getaddrinfo_error);
+int socket_loopback_server(int port, int type);
+int socket_local_server(const char* name, int namespaceId, int type);
+int socket_local_server_bind(int s, const char* name, int namespaceId);
+int socket_local_client_connect(int fd, const char *name, int namespaceId,
+ int type);
+int socket_local_client(const char* name, int namespaceId, int type);
+cutils_socket_t socket_inaddr_any_server(int port, int type);
+
+/*
+ * Closes a cutils_socket_t. Windows doesn't allow calling close() on a socket
+ * so this is a cross-platform way to close a cutils_socket_t.
+ *
+ * Returns 0 on success.
+ */
+int socket_close(cutils_socket_t sock);
+
+/*
+ * Sets socket receive timeout using SO_RCVTIMEO. Setting |timeout_ms| to 0
+ * disables receive timeouts.
+ *
+ * Return 0 on success.
+ */
+int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms);
/*
* socket_peer_is_trusted - Takes a socket which is presumed to be a
@@ -101,4 +146,4 @@
}
#endif
-#endif /* __CUTILS_SOCKETS_H */
+#endif /* __CUTILS_SOCKETS_H */
diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h
index 9876e34..85d6c19 100644
--- a/include/private/android_filesystem_config.h
+++ b/include/private/android_filesystem_config.h
@@ -87,6 +87,7 @@
#define AID_METRICSD 1043 /* metricsd process */
#define AID_WEBSERV 1044 /* webservd process */
#define AID_DEBUGGERD 1045 /* debuggerd unprivileged user */
+#define AID_MEDIA_CODEC 1046 /* mediacodec process */
#define AID_SHELL 2000 /* adb and debug shell user */
#define AID_CACHE 2001 /* cache access */
@@ -192,6 +193,7 @@
{ "metricsd", AID_METRICSD },
{ "webserv", AID_WEBSERV },
{ "debuggerd", AID_DEBUGGERD, },
+ { "mediacodec", AID_MEDIA_CODEC, },
{ "shell", AID_SHELL, },
{ "cache", AID_CACHE, },
diff --git a/init/readme.txt b/init/readme.txt
index 5a1cf44..ef85ccf 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -40,17 +40,43 @@
These directories are intended for all Actions and Services used after
file system mounting.
+One may specify paths in the mount_all command line to have it import
+.rc files at the specified paths instead of the default ones listed above.
+This is primarily for supporting factory mode and other non-standard boot
+modes. The three default paths should be used for the normal boot process.
+
The intention of these directories is as follows
1) /system/etc/init/ is for core system items such as
- SurfaceFlinger and MediaService.
+ SurfaceFlinger, MediaService, and logcatd.
2) /vendor/etc/init/ is for SoC vendor items such as actions or
daemons needed for core SoC functionality.
3) /odm/etc/init/ is for device manufacturer items such as
actions or daemons needed for motion sensor or other peripheral
functionality.
-One may specify paths in the mount_all command line to have it import
-.rc files at the specified paths instead of the default ones described above.
+All services whose binaries reside on the system, vendor, or odm
+partitions should have their service entries placed into a
+corresponding init .rc file, located in the /etc/init/
+directory of the partition where they reside. There is a build
+system macro, LOCAL_INIT_RC, that handles this for developers. Each
+init .rc file should additionally contain any actions associated with
+its service.
+
+An example is the logcatd.rc and Android.mk files located in the
+system/core/logcat directory. The LOCAL_INIT_RC macro in the
+Android.mk file places logcatd.rc in /system/etc/init/ during the
+build process. Init loads logcatd.rc during the mount_all command and
+allows the service to be run and the action to be queued when
+appropriate.
+
+This break up of init .rc files according to their daemon is preferred
+to the previously used monolithic init .rc files. This approach
+ensures that the only service entries that init reads and the only
+actions that init performs correspond to services whose binaries are in
+fact present on the file system, which was not the case with the
+monolithic init .rc files. This additionally will aid in merge
+conflict resolution when multiple services are added to the system, as
+each one will go into a separate file.
Actions
-------
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index 5d3dd86..6cffb11 100644
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -48,7 +48,6 @@
Backtrace.cpp \
BacktraceCurrent.cpp \
BacktraceMap.cpp \
- BacktraceOffline.cpp \
BacktracePtrace.cpp \
thread_utils.c \
ThreadEntry.cpp \
@@ -61,25 +60,6 @@
liblog \
libunwind \
-# Use shared llvm library on device to save space.
-libbacktrace_shared_libraries_target := \
- libLLVM \
-
-# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
-# which is not included in the prebuilt.
-libbacktrace_static_libraries_host := \
- libcutils \
- libLLVMObject \
- libLLVMBitReader \
- libLLVMMC \
- libLLVMMCParser \
- libLLVMCore \
- libLLVMSupport \
-
-libbacktrace_ldlibs_host := \
- -lpthread \
- -lrt \
-
module := libbacktrace
module_tag := optional
build_type := target
@@ -98,6 +78,40 @@
libbacktrace_static_libraries :=
#-------------------------------------------------------------------------
+# The libbacktrace_offline shared library.
+#-------------------------------------------------------------------------
+libbacktrace_offline_src_files := \
+ BacktraceOffline.cpp \
+
+libbacktrace_offline_shared_libraries := \
+ libbacktrace \
+ liblog \
+ libunwind \
+
+# Use shared llvm library on device to save space.
+libbacktrace_offline_shared_libraries_target := \
+ libLLVM \
+
+# Use static llvm libraries on host to remove dependency on 32-bit llvm shared library
+# which is not included in the prebuilt.
+libbacktrace_offline_static_libraries_host := \
+ libLLVMObject \
+ libLLVMBitReader \
+ libLLVMMC \
+ libLLVMMCParser \
+ libLLVMCore \
+ libLLVMSupport \
+
+module := libbacktrace_offline
+module_tag := optional
+build_type := target
+build_target := SHARED_LIBRARY
+include $(LOCAL_PATH)/Android.build.mk
+build_type := host
+libbacktrace_multilib := both
+include $(LOCAL_PATH)/Android.build.mk
+
+#-------------------------------------------------------------------------
# The libbacktrace_test library needed by backtrace_test.
#-------------------------------------------------------------------------
libbacktrace_test_cflags := \
@@ -141,6 +155,7 @@
backtrace_test_shared_libraries := \
libbacktrace_test \
libbacktrace \
+ libbacktrace_offline \
libbase \
libcutils \
libunwind \
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index 3c8f879..baa3d0f 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -28,7 +28,6 @@
#include <backtrace/BacktraceMap.h>
#include "BacktraceLog.h"
-#include "BacktraceOffline.h"
#include "thread_utils.h"
#include "UnwindCurrent.h"
#include "UnwindPtrace.h"
@@ -149,8 +148,3 @@
return new UnwindPtrace(pid, tid, map);
}
}
-
-Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
- const backtrace_stackinfo_t& stack, bool cache_file) {
- return new BacktraceOffline(pid, tid, map, stack, cache_file);
-}
diff --git a/libbacktrace/BacktraceOffline.cpp b/libbacktrace/BacktraceOffline.cpp
index abc186b..e84ae74 100644
--- a/libbacktrace/BacktraceOffline.cpp
+++ b/libbacktrace/BacktraceOffline.cpp
@@ -659,3 +659,8 @@
}
return nullptr;
}
+
+Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
+ const backtrace_stackinfo_t& stack, bool cache_file) {
+ return new BacktraceOffline(pid, tid, map, stack, cache_file);
+}
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index dd08108..25b056b 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -39,26 +39,33 @@
libcutils_nonwindows_sources := \
fs.c \
multiuser.c \
- socket_inaddr_any_server.c \
- socket_local_client.c \
- socket_local_server.c \
- socket_loopback_client.c \
- socket_loopback_server.c \
- socket_network_client.c \
- sockets.c \
+ socket_inaddr_any_server_unix.c \
+ socket_local_client_unix.c \
+ socket_local_server_unix.c \
+ socket_loopback_client_unix.c \
+ socket_loopback_server_unix.c \
+ socket_network_client_unix.c \
+ sockets_unix.c \
str_parms.c \
libcutils_nonwindows_host_sources := \
ashmem-host.c \
- trace-host.c
+ trace-host.c \
+libcutils_windows_host_sources := \
+ socket_inaddr_any_server_windows.c \
+ socket_network_client_windows.c \
+ sockets_windows.c \
# Shared and static library for host
+# Note: when linking this library on Windows, you must also link to Winsock2
+# using "LOCAL_LDLIBS_windows := -lws2_32".
# ========================================================
LOCAL_MODULE := libcutils
LOCAL_SRC_FILES := $(libcutils_common_sources) dlmalloc_stubs.c
LOCAL_SRC_FILES_darwin := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
LOCAL_SRC_FILES_linux := $(libcutils_nonwindows_sources) $(libcutils_nonwindows_host_sources)
+LOCAL_SRC_FILES_windows := $(libcutils_windows_host_sources)
LOCAL_STATIC_LIBRARIES := liblog
LOCAL_CFLAGS := -Werror -Wall -Wextra
LOCAL_MULTILIB := both
diff --git a/libcutils/socket_inaddr_any_server.c b/libcutils/socket_inaddr_any_server_unix.c
similarity index 97%
rename from libcutils/socket_inaddr_any_server.c
rename to libcutils/socket_inaddr_any_server_unix.c
index e1b7d84..387258f 100644
--- a/libcutils/socket_inaddr_any_server.c
+++ b/libcutils/socket_inaddr_any_server_unix.c
@@ -20,12 +20,10 @@
#include <string.h>
#include <unistd.h>
-#if !defined(_WIN32)
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
-#endif
#include <cutils/sockets.h>
diff --git a/libcutils/socket_inaddr_any_server_windows.c b/libcutils/socket_inaddr_any_server_windows.c
new file mode 100644
index 0000000..c15200a
--- /dev/null
+++ b/libcutils/socket_inaddr_any_server_windows.c
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <errno.h>
+
+#include <cutils/sockets.h>
+
+#define LISTEN_BACKLOG 4
+
+extern bool initialize_windows_sockets();
+
+SOCKET socket_inaddr_any_server(int port, int type) {
+ if (!initialize_windows_sockets()) {
+ return INVALID_SOCKET;
+ }
+
+ SOCKET sock = socket(AF_INET6, type, 0);
+ if (sock == INVALID_SOCKET) {
+ return INVALID_SOCKET;
+ }
+
+ // Enforce exclusive addresses so nobody can steal the port from us (1),
+ // and enable dual-stack so both IPv4 and IPv6 work (2).
+ // (1) https://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx.
+ // (2) https://msdn.microsoft.com/en-us/library/windows/desktop/bb513665(v=vs.85).aspx.
+ int exclusive = 1;
+ DWORD v6_only = 0;
+ if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&exclusive,
+ sizeof(exclusive)) == SOCKET_ERROR ||
+ setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&v6_only,
+ sizeof(v6_only)) == SOCKET_ERROR) {
+ closesocket(sock);
+ return INVALID_SOCKET;
+ }
+
+ // Bind the socket to our local port.
+ struct sockaddr_in6 addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin6_family = AF_INET6;
+ addr.sin6_port = htons(port);
+ addr.sin6_addr = in6addr_any;
+ if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
+ closesocket(sock);
+ return INVALID_SOCKET;
+ }
+
+ // Start listening for connections if this is a TCP socket.
+ if (type == SOCK_STREAM && listen(sock, LISTEN_BACKLOG) == SOCKET_ERROR) {
+ closesocket(sock);
+ return INVALID_SOCKET;
+ }
+
+ return sock;
+}
diff --git a/libcutils/socket_local_client.c b/libcutils/socket_local_client_unix.c
similarity index 98%
rename from libcutils/socket_local_client.c
rename to libcutils/socket_local_client_unix.c
index 2526146..92fb9f1 100644
--- a/libcutils/socket_local_client.c
+++ b/libcutils/socket_local_client_unix.c
@@ -37,7 +37,7 @@
#include <sys/select.h>
#include <sys/types.h>
-#include "socket_local.h"
+#include "socket_local_unix.h"
#define UNUSED __attribute__((unused))
diff --git a/libcutils/socket_local_server.c b/libcutils/socket_local_server_unix.c
similarity index 98%
rename from libcutils/socket_local_server.c
rename to libcutils/socket_local_server_unix.c
index c9acdad..db9e1e0 100644
--- a/libcutils/socket_local_server.c
+++ b/libcutils/socket_local_server_unix.c
@@ -39,7 +39,7 @@
#include <sys/types.h>
#include <netinet/in.h>
-#include "socket_local.h"
+#include "socket_local_unix.h"
#define LISTEN_BACKLOG 4
diff --git a/libcutils/socket_local.h b/libcutils/socket_local_unix.h
similarity index 100%
rename from libcutils/socket_local.h
rename to libcutils/socket_local_unix.h
diff --git a/libcutils/socket_loopback_client.c b/libcutils/socket_loopback_client_unix.c
similarity index 100%
rename from libcutils/socket_loopback_client.c
rename to libcutils/socket_loopback_client_unix.c
diff --git a/libcutils/socket_loopback_server.c b/libcutils/socket_loopback_server_unix.c
similarity index 100%
rename from libcutils/socket_loopback_server.c
rename to libcutils/socket_loopback_server_unix.c
diff --git a/libcutils/socket_network_client.c b/libcutils/socket_network_client_unix.c
similarity index 100%
rename from libcutils/socket_network_client.c
rename to libcutils/socket_network_client_unix.c
diff --git a/libcutils/socket_network_client_windows.c b/libcutils/socket_network_client_windows.c
new file mode 100644
index 0000000..ab1a52f
--- /dev/null
+++ b/libcutils/socket_network_client_windows.c
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <cutils/sockets.h>
+
+extern bool initialize_windows_sockets();
+
+SOCKET socket_network_client(const char* host, int port, int type) {
+ if (!initialize_windows_sockets()) {
+ return INVALID_SOCKET;
+ }
+
+ // First resolve the host and port parameters into a usable network address.
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_socktype = type;
+
+ struct addrinfo* address = NULL;
+ char port_str[16];
+ snprintf(port_str, sizeof(port_str), "%d", port);
+ if (getaddrinfo(host, port_str, &hints, &address) != 0 || address == NULL) {
+ if (address != NULL) {
+ freeaddrinfo(address);
+ }
+ return INVALID_SOCKET;
+ }
+
+ // Now create and connect the socket.
+ SOCKET sock = socket(address->ai_family, address->ai_socktype,
+ address->ai_protocol);
+ if (sock == INVALID_SOCKET) {
+ freeaddrinfo(address);
+ return INVALID_SOCKET;
+ }
+
+ if (connect(sock, address->ai_addr, address->ai_addrlen) == SOCKET_ERROR) {
+ closesocket(sock);
+ freeaddrinfo(address);
+ return INVALID_SOCKET;
+ }
+
+ freeaddrinfo(address);
+ return sock;
+}
diff --git a/libcutils/sockets.c b/libcutils/sockets_unix.c
similarity index 82%
rename from libcutils/sockets.c
rename to libcutils/sockets_unix.c
index d438782..5eddc4b 100644
--- a/libcutils/sockets.c
+++ b/libcutils/sockets_unix.c
@@ -45,3 +45,14 @@
return true;
}
+
+int socket_close(int sock) {
+ return close(sock);
+}
+
+int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms) {
+ struct timeval tv;
+ tv.tv_sec = timeout_ms / 1000;
+ tv.tv_usec = (timeout_ms % 1000) * 1000;
+ return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+}
diff --git a/libcutils/sockets_windows.c b/libcutils/sockets_windows.c
new file mode 100644
index 0000000..1bf2933
--- /dev/null
+++ b/libcutils/sockets_windows.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <cutils/sockets.h>
+
+// https://msdn.microsoft.com/en-us/library/windows/desktop/ms741549(v=vs.85).aspx
+// claims WSACleanup() should be called before program exit, but general
+// consensus seems to be that it hasn't actually been necessary for a long time,
+// likely since Windows 3.1. Additionally, trying to properly use WSACleanup()
+// can be extremely tricky and cause deadlock when using threads or atexit().
+//
+// Both adb (1) and Chrome (2) purposefully avoid WSACleanup() with no issues.
+// (1) https://android.googlesource.com/platform/system/core.git/+/master/adb/sysdeps_win32.cpp
+// (2) https://code.google.com/p/chromium/codesearch#chromium/src/net/base/winsock_init.cc
+bool initialize_windows_sockets() {
+ // There's no harm in calling WSAStartup() multiple times but no benefit
+ // either, we may as well skip it after the first.
+ static bool init_success = false;
+
+ if (!init_success) {
+ WSADATA wsaData;
+ init_success = (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0);
+ }
+
+ return init_success;
+}
+
+int socket_close(cutils_socket_t sock) {
+ return closesocket(sock);
+}
+
+int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms) {
+ return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_ms,
+ sizeof(timeout_ms));
+}
diff --git a/libcutils/tests/Android.mk b/libcutils/tests/Android.mk
index cf70345..4da5ed6 100644
--- a/libcutils/tests/Android.mk
+++ b/libcutils/tests/Android.mk
@@ -15,6 +15,9 @@
LOCAL_PATH := $(call my-dir)
test_src_files := \
+ sockets_test.cpp \
+
+test_src_files_nonwindows := \
test_str_parms.cpp \
test_target_only_src_files := \
@@ -55,7 +58,7 @@
include $(CLEAR_VARS)
LOCAL_MODULE := libcutils_test
-LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_SRC_FILES := $(test_src_files) $(test_src_files_nonwindows)
LOCAL_SHARED_LIBRARIES := $(test_libraries)
LOCAL_MULTILIB := both
LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
@@ -65,9 +68,13 @@
include $(CLEAR_VARS)
LOCAL_MODULE := libcutils_test_static
LOCAL_SRC_FILES := $(test_src_files)
+LOCAL_SRC_FILES_darwin := $(test_src_files_nonwindows)
+LOCAL_SRC_FILES_linux := $(test_src_files_nonwindows)
LOCAL_STATIC_LIBRARIES := $(test_libraries)
+LOCAL_LDLIBS_windows := -lws2_32
LOCAL_CXX_STL := libc++_static
LOCAL_MULTILIB := both
LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_MODULE_HOST_OS := darwin linux windows
include $(BUILD_HOST_NATIVE_TEST)
diff --git a/libcutils/tests/sockets_test.cpp b/libcutils/tests/sockets_test.cpp
new file mode 100644
index 0000000..966dfe7
--- /dev/null
+++ b/libcutils/tests/sockets_test.cpp
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2015 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.
+ */
+
+// Tests socket functionality using loopback connections. Requires IPv4 and
+// IPv6 capabilities, and that kTestPort is available for loopback
+// communication. These tests also assume that no UDP packets are lost,
+// which should be the case for loopback communication, but is not guaranteed.
+
+#include <cutils/sockets.h>
+
+#include <time.h>
+
+#include <gtest/gtest.h>
+
+enum {
+ // This port must be available for loopback communication.
+ kTestPort = 54321
+};
+
+// Makes sure the passed sockets are valid, sends data between them, and closes
+// them. Any failures are logged with gtest.
+//
+// On Mac recvfrom() will not fill in the address for TCP sockets, so we need
+// separate logic paths depending on socket type.
+static void TestConnectedSockets(cutils_socket_t server, cutils_socket_t client,
+ int type) {
+ ASSERT_NE(INVALID_SOCKET, server);
+ ASSERT_NE(INVALID_SOCKET, client);
+
+ char buffer[3];
+ sockaddr_storage addr;
+ socklen_t addr_size = sizeof(addr);
+
+ // Send client -> server first to get the UDP client's address.
+ ASSERT_EQ(3, send(client, "foo", 3, 0));
+ if (type == SOCK_DGRAM) {
+ EXPECT_EQ(3, recvfrom(server, buffer, 3, 0,
+ reinterpret_cast<sockaddr*>(&addr), &addr_size));
+ } else {
+ EXPECT_EQ(3, recv(server, buffer, 3, 0));
+ }
+ EXPECT_EQ(0, memcmp(buffer, "foo", 3));
+
+ // Now send server -> client.
+ if (type == SOCK_DGRAM) {
+ ASSERT_EQ(3, sendto(server, "bar", 3, 0,
+ reinterpret_cast<sockaddr*>(&addr), addr_size));
+ } else {
+ ASSERT_EQ(3, send(server, "bar", 3, 0));
+ }
+ EXPECT_EQ(3, recv(client, buffer, 3, 0));
+ EXPECT_EQ(0, memcmp(buffer, "bar", 3));
+
+ EXPECT_EQ(0, socket_close(server));
+ EXPECT_EQ(0, socket_close(client));
+}
+
+// Tests receive timeout. The timing verification logic must be very coarse to
+// make sure different systems can all pass these tests.
+void TestReceiveTimeout(cutils_socket_t sock) {
+ time_t start_time;
+ char buffer[32];
+
+ // Make sure a 20ms timeout completes in 1 second or less.
+ EXPECT_EQ(0, socket_set_receive_timeout(sock, 20));
+ start_time = time(nullptr);
+ EXPECT_EQ(-1, recv(sock, buffer, sizeof(buffer), 0));
+ EXPECT_LE(difftime(time(nullptr), start_time), 1.0);
+
+ // Make sure a 1250ms timeout takes 1 second or more.
+ EXPECT_EQ(0, socket_set_receive_timeout(sock, 1250));
+ start_time = time(nullptr);
+ EXPECT_EQ(-1, recv(sock, buffer, sizeof(buffer), 0));
+ EXPECT_LE(1.0, difftime(time(nullptr), start_time));
+}
+
+// Tests socket_inaddr_any_server() and socket_network_client() for IPv4 UDP.
+TEST(SocketsTest, TestIpv4UdpLoopback) {
+ cutils_socket_t server = socket_inaddr_any_server(kTestPort, SOCK_DGRAM);
+ cutils_socket_t client = socket_network_client("127.0.0.1", kTestPort,
+ SOCK_DGRAM);
+
+ TestConnectedSockets(server, client, SOCK_DGRAM);
+}
+
+// Tests socket_inaddr_any_server() and socket_network_client() for IPv4 TCP.
+TEST(SocketsTest, TestIpv4TcpLoopback) {
+ cutils_socket_t server = socket_inaddr_any_server(kTestPort, SOCK_STREAM);
+ ASSERT_NE(INVALID_SOCKET, server);
+
+ cutils_socket_t client = socket_network_client("127.0.0.1", kTestPort,
+ SOCK_STREAM);
+ cutils_socket_t handler = accept(server, nullptr, nullptr);
+ EXPECT_EQ(0, socket_close(server));
+
+ TestConnectedSockets(handler, client, SOCK_STREAM);
+}
+
+// Tests socket_inaddr_any_server() and socket_network_client() for IPv6 UDP.
+TEST(SocketsTest, TestIpv6UdpLoopback) {
+ cutils_socket_t server = socket_inaddr_any_server(kTestPort, SOCK_DGRAM);
+ cutils_socket_t client = socket_network_client("::1", kTestPort,
+ SOCK_DGRAM);
+
+ TestConnectedSockets(server, client, SOCK_DGRAM);
+}
+
+// Tests socket_inaddr_any_server() and socket_network_client() for IPv6 TCP.
+TEST(SocketsTest, TestIpv6TcpLoopback) {
+ cutils_socket_t server = socket_inaddr_any_server(kTestPort, SOCK_STREAM);
+ ASSERT_NE(INVALID_SOCKET, server);
+
+ cutils_socket_t client = socket_network_client("::1", kTestPort,
+ SOCK_STREAM);
+ cutils_socket_t handler = accept(server, nullptr, nullptr);
+ EXPECT_EQ(0, socket_close(server));
+
+ TestConnectedSockets(handler, client, SOCK_STREAM);
+}
+
+// Tests setting a receive timeout for UDP sockets.
+TEST(SocketsTest, TestUdpReceiveTimeout) {
+ cutils_socket_t sock = socket_inaddr_any_server(kTestPort, SOCK_DGRAM);
+ ASSERT_NE(INVALID_SOCKET, sock);
+
+ TestReceiveTimeout(sock);
+
+ EXPECT_EQ(0, socket_close(sock));
+}
+
+// Tests setting a receive timeout for TCP sockets.
+TEST(SocketsTest, TestTcpReceiveTimeout) {
+ cutils_socket_t server = socket_inaddr_any_server(kTestPort, SOCK_STREAM);
+ ASSERT_NE(INVALID_SOCKET, server);
+
+ cutils_socket_t client = socket_network_client("localhost", kTestPort,
+ SOCK_STREAM);
+ cutils_socket_t handler = accept(server, nullptr, nullptr);
+ EXPECT_EQ(0, socket_close(server));
+
+ TestReceiveTimeout(handler);
+
+ EXPECT_EQ(0, socket_close(client));
+ EXPECT_EQ(0, socket_close(handler));
+}
diff --git a/liblog/logd_write.c b/liblog/logd_write.c
index 55b965b..4946073 100644
--- a/liblog/logd_write.c
+++ b/liblog/logd_write.c
@@ -204,14 +204,36 @@
if (vec[0].iov_len < 4) {
return -EINVAL;
}
- if ((last_uid != AID_SYSTEM) && (last_uid != AID_ROOT)) {
+ /* Matches clientHasLogCredentials() in logd */
+ if ((last_uid != AID_SYSTEM) && (last_uid != AID_ROOT) && (last_uid != AID_LOG)) {
uid_t uid = geteuid();
- if ((uid != AID_SYSTEM) && (uid != AID_ROOT)) {
+ if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
gid_t gid = getgid();
- if ((gid != AID_SYSTEM) && (gid != AID_ROOT)) {
+ if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
gid = getegid();
- if ((gid != AID_SYSTEM) && (gid != AID_ROOT)) {
- return -EPERM;
+ if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
+ int num_groups;
+ gid_t *groups;
+
+ num_groups = getgroups(0, NULL);
+ if (num_groups <= 0) {
+ return -EPERM;
+ }
+ groups = calloc(num_groups, sizeof(gid_t));
+ if (!groups) {
+ return -ENOMEM;
+ }
+ num_groups = getgroups(num_groups, groups);
+ while (num_groups > 0) {
+ if (groups[num_groups - 1] == AID_LOG) {
+ break;
+ }
+ --num_groups;
+ }
+ free(groups);
+ if (num_groups <= 0) {
+ return -EPERM;
+ }
}
}
}
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
index 4eff891..32a65ea 100644
--- a/libnativebridge/native_bridge.cc
+++ b/libnativebridge/native_bridge.cc
@@ -413,19 +413,14 @@
if (errno == ENOENT) {
if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
- fprintf(stderr, "Cannot create code cache directory %s: %s.",
- app_code_cache_dir, strerror(errno));
ReleaseAppCodeCacheDir();
}
} else {
ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
- fprintf(stderr, "Cannot stat code cache directory %s: %s.",
- app_code_cache_dir, strerror(errno));
ReleaseAppCodeCacheDir();
}
} else if (!S_ISDIR(st.st_mode)) {
ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
- fprintf(stderr, "Code cache is not a directory %s.", app_code_cache_dir);
ReleaseAppCodeCacheDir();
}
diff --git a/libpixelflinger/codeflinger/CodeCache.cpp b/libpixelflinger/codeflinger/CodeCache.cpp
index d770302..4b498c1 100644
--- a/libpixelflinger/codeflinger/CodeCache.cpp
+++ b/libpixelflinger/codeflinger/CodeCache.cpp
@@ -63,7 +63,7 @@
#define USAGE_ERROR_ACTION(m,p) \
heap_error("ARGUMENT IS INVALID HEAP ADDRESS", __FUNCTION__, p)
-#include "../../../../bionic/libc/upstream-dlmalloc/malloc.c"
+#include "../../../../external/dlmalloc/malloc.c"
static void heap_error(const char* msg, const char* function, void* p) {
ALOG(LOG_FATAL, LOG_TAG, "@@@ ABORTING: CODE FLINGER: %s IN %s addr=%p",
diff --git a/logd/tests/Android.mk b/logd/tests/Android.mk
index a7c6b53..808087a 100644
--- a/logd/tests/Android.mk
+++ b/logd/tests/Android.mk
@@ -43,6 +43,6 @@
LOCAL_MODULE := $(test_module_prefix)unit-tests
LOCAL_MODULE_TAGS := $(test_tags)
LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_SHARED_LIBRARIES := libcutils
+LOCAL_SHARED_LIBRARIES := libbase libcutils liblog
LOCAL_SRC_FILES := $(test_src_files)
include $(BUILD_NATIVE_TEST)
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 7d0dd44..de19790 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -15,16 +15,20 @@
*/
#include <fcntl.h>
+#include <inttypes.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
+#include <string>
+
#include <gtest/gtest.h>
-#include "cutils/sockets.h"
-#include "log/log.h"
-#include "log/logger.h"
+#include <android-base/stringprintf.h>
+#include <cutils/sockets.h>
+#include <log/log.h>
+#include <log/logger.h>
/*
* returns statistics
@@ -198,6 +202,10 @@
static void dump_log_msg(const char *prefix,
log_msg *msg, unsigned int version, int lid) {
+ std::cout << std::flush;
+ std::cerr << std::flush;
+ fflush(stdout);
+ fflush(stderr);
switch(msg->entry.hdr_size) {
case 0:
version = 1;
@@ -282,6 +290,7 @@
}
}
fprintf(stderr, "}\n");
+ fflush(stderr);
}
TEST(logd, both) {
@@ -524,7 +533,8 @@
ASSERT_GT(totalSize, nowSpamSize * 2);
}
-TEST(logd, timeout) {
+// b/26447386 confirm fixed
+void timeout_negative(const char *command) {
log_msg msg_wrap, msg_timeout;
bool content_wrap = false, content_timeout = false, written = false;
unsigned int alarm_wrap = 0, alarm_timeout = 0;
@@ -538,6 +548,8 @@
SOCK_SEQPACKET);
ASSERT_LT(0, fd);
+ std::string ask(command);
+
struct sigaction ignore, old_sigaction;
memset(&ignore, 0, sizeof(ignore));
ignore.sa_handler = caught_signal;
@@ -545,8 +557,8 @@
sigaction(SIGALRM, &ignore, &old_sigaction);
unsigned int old_alarm = alarm(3);
- static const char ask[] = "dumpAndClose lids=0,1,2,3,4,5 timeout=6";
- written = write(fd, ask, sizeof(ask)) == sizeof(ask);
+ size_t len = ask.length() + 1;
+ written = write(fd, ask.c_str(), len) == (ssize_t)len;
if (!written) {
alarm(old_alarm);
sigaction(SIGALRM, &old_sigaction, NULL);
@@ -559,6 +571,9 @@
alarm_wrap = alarm(5);
content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+ if (!content_timeout) { // make sure we hit dumpAndClose
+ content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+ }
alarm_timeout = alarm((old_alarm <= 0)
? old_alarm
@@ -569,7 +584,7 @@
close(fd);
- if (!content_wrap && !alarm_wrap && content_timeout && !alarm_timeout) {
+ if (!content_wrap && !alarm_wrap && content_timeout && alarm_timeout) {
break;
}
}
@@ -583,6 +598,113 @@
}
EXPECT_TRUE(written);
+ EXPECT_TRUE(content_wrap);
+ EXPECT_NE(0U, alarm_wrap);
+ EXPECT_TRUE(content_timeout);
+ EXPECT_NE(0U, alarm_timeout);
+}
+
+TEST(logd, timeout_no_start) {
+ timeout_negative("dumpAndClose lids=0,1,2,3,4,5 timeout=6");
+}
+
+TEST(logd, timeout_start_epoch) {
+ timeout_negative("dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=0.000000000");
+}
+
+// b/26447386 refined behavior
+TEST(logd, timeout) {
+ log_msg msg_wrap, msg_timeout;
+ bool content_wrap = false, content_timeout = false, written = false;
+ unsigned int alarm_wrap = 0, alarm_timeout = 0;
+ // A few tries to get it right just in case wrap kicks in due to
+ // content providers being active during the test
+ int i = 5;
+ log_time now(android_log_clockid());
+ now.tv_sec -= 30; // reach back a moderate period of time
+
+ while (--i) {
+ int fd = socket_local_client("logdr",
+ ANDROID_SOCKET_NAMESPACE_RESERVED,
+ SOCK_SEQPACKET);
+ ASSERT_LT(0, fd);
+
+ std::string ask = android::base::StringPrintf(
+ "dumpAndClose lids=0,1,2,3,4,5 timeout=6 start=%"
+ PRIu32 ".%09" PRIu32,
+ now.tv_sec, now.tv_nsec);
+
+ struct sigaction ignore, old_sigaction;
+ memset(&ignore, 0, sizeof(ignore));
+ ignore.sa_handler = caught_signal;
+ sigemptyset(&ignore.sa_mask);
+ sigaction(SIGALRM, &ignore, &old_sigaction);
+ unsigned int old_alarm = alarm(3);
+
+ size_t len = ask.length() + 1;
+ written = write(fd, ask.c_str(), len) == (ssize_t)len;
+ if (!written) {
+ alarm(old_alarm);
+ sigaction(SIGALRM, &old_sigaction, NULL);
+ close(fd);
+ continue;
+ }
+
+ content_wrap = recv(fd, msg_wrap.buf, sizeof(msg_wrap), 0) > 0;
+
+ alarm_wrap = alarm(5);
+
+ content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+ if (!content_timeout) { // make sure we hit dumpAndClose
+ content_timeout = recv(fd, msg_timeout.buf, sizeof(msg_timeout), 0) > 0;
+ }
+
+ alarm_timeout = alarm((old_alarm <= 0)
+ ? old_alarm
+ : (old_alarm > (1 + 3 - alarm_wrap))
+ ? old_alarm - 3 + alarm_wrap
+ : 2);
+ sigaction(SIGALRM, &old_sigaction, NULL);
+
+ close(fd);
+
+ if (!content_wrap && !alarm_wrap && content_timeout && alarm_timeout) {
+ break;
+ }
+
+ // modify start time in case content providers are relatively
+ // active _or_ inactive during the test.
+ if (content_timeout) {
+ log_time msg(msg_timeout.entry.sec, msg_timeout.entry.nsec);
+ EXPECT_FALSE(msg < now);
+ if (msg > now) {
+ now = msg;
+ now.tv_sec += 30;
+ msg = log_time(android_log_clockid());
+ if (now > msg) {
+ now = msg;
+ --now.tv_sec;
+ }
+ }
+ } else {
+ now.tv_sec -= 120; // inactive, reach further back!
+ }
+ }
+
+ if (content_wrap) {
+ dump_log_msg("wrap", &msg_wrap, 3, -1);
+ }
+
+ if (content_timeout) {
+ dump_log_msg("timeout", &msg_timeout, 3, -1);
+ }
+
+ if (content_wrap || !content_timeout) {
+ fprintf(stderr, "now=%" PRIu32 ".%09" PRIu32 "\n",
+ now.tv_sec, now.tv_nsec);
+ }
+
+ EXPECT_TRUE(written);
EXPECT_FALSE(content_wrap);
EXPECT_EQ(0U, alarm_wrap);
EXPECT_TRUE(content_timeout);
diff --git a/metricsd/.clang-format b/metricsd/.clang-format
index 65d8277..c98efc2 100644
--- a/metricsd/.clang-format
+++ b/metricsd/.clang-format
@@ -2,6 +2,7 @@
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
+BinPackArguments: false
BinPackParameters: false
CommentPragmas: NOLINT:.*
DerivePointerAlignment: false
diff --git a/metricsd/uploader/metrics_log.cc b/metricsd/uploader/metrics_log.cc
index 39655e6..fcaa8c1 100644
--- a/metricsd/uploader/metrics_log.cc
+++ b/metricsd/uploader/metrics_log.cc
@@ -85,5 +85,6 @@
}
bool MetricsLog::PopulateSystemProfile(SystemProfileSetter* profile_setter) {
+ CHECK(profile_setter);
return profile_setter->Populate(uma_proto());
}
diff --git a/metricsd/uploader/system_profile_cache.cc b/metricsd/uploader/system_profile_cache.cc
index 70f6afd..e6f6617 100644
--- a/metricsd/uploader/system_profile_cache.cc
+++ b/metricsd/uploader/system_profile_cache.cc
@@ -80,6 +80,10 @@
} else {
reader.Load();
auto client = update_engine::UpdateEngineClient::CreateInstance();
+ if (!client) {
+ LOG(ERROR) << "failed to create the update engine client";
+ return false;
+ }
if (!client->GetChannel(&channel)) {
LOG(ERROR) << "failed to read the current channel from update engine.";
return false;
diff --git a/rootdir/init.rc b/rootdir/init.rc
index d322402..e400c85 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -28,6 +28,10 @@
on init
sysclktz 0
+ # Mix device-specific information into the entropy pool
+ copy /proc/cmdline /dev/urandom
+ copy /default.prop /dev/urandom
+
# Backward compatibility.
symlink /system/etc /etc
symlink /sys/kernel/debug /d
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index b735dc3..6ef491c 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -1,6 +1,13 @@
subsystem adf
devname uevent_devname
+# ueventd can only set permissions on device nodes and their associated
+# sysfs attributes, not on arbitrary paths.
+#
+# format for /dev rules: devname mode uid gid
+# format for /sys rules: nodename attr mode uid gid
+# shortcut: "mtd@NN" expands to "/dev/mtd/mtdNN"
+
/dev/null 0666 root root
/dev/zero 0666 root root
/dev/full 0666 root root