adb_utils.cpp revision d48dbd89c8661607b338b696c14c9609050f3f29
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define TRACE_TAG TRACE_ADB
18
19#include "adb_utils.h"
20
21#include <stdlib.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24#include <unistd.h>
25
26#include <algorithm>
27
28#include <base/logging.h>
29#include <base/stringprintf.h>
30#include <base/strings.h>
31#include <cutils/sockets.h>
32
33#include "adb_trace.h"
34#include "sysdeps.h"
35
36#if defined(_WIN32)
37#include <ws2tcpip.h>
38#else
39#include <netdb.h>
40#endif
41
42bool getcwd(std::string* s) {
43  char* cwd = getcwd(nullptr, 0);
44  if (cwd != nullptr) *s = cwd;
45  free(cwd);
46  return (cwd != nullptr);
47}
48
49bool directory_exists(const std::string& path) {
50  struct stat sb;
51  return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
52}
53
54std::string escape_arg(const std::string& s) {
55  std::string result = s;
56
57  // Escape any ' in the string (before we single-quote the whole thing).
58  // The correct way to do this for the shell is to replace ' with '\'' --- that is,
59  // close the existing single-quoted string, escape a single single-quote, and start
60  // a new single-quoted string. Like the C preprocessor, the shell will concatenate
61  // these pieces into one string.
62  for (size_t i = 0; i < s.size(); ++i) {
63    if (s[i] == '\'') {
64      result.insert(i, "'\\'");
65      i += 2;
66    }
67  }
68
69  // Prefix and suffix the whole string with '.
70  result.insert(result.begin(), '\'');
71  result.push_back('\'');
72  return result;
73}
74
75int mkdirs(const char *path)
76{
77    int ret;
78    char *x = (char *)path + 1;
79
80    for(;;) {
81        x = adb_dirstart(x);
82        if(x == 0) return 0;
83        *x = 0;
84        ret = adb_mkdir(path, 0775);
85        *x = OS_PATH_SEPARATOR;
86        if((ret < 0) && (errno != EEXIST)) {
87            return ret;
88        }
89        x++;
90    }
91    return 0;
92}
93
94void dump_hex(const void* data, size_t byte_count) {
95    byte_count = std::min(byte_count, size_t(16));
96
97    const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
98
99    std::string line;
100    for (size_t i = 0; i < byte_count; ++i) {
101        android::base::StringAppendF(&line, "%02x", p[i]);
102    }
103    line.push_back(' ');
104
105    for (size_t i = 0; i < byte_count; ++i) {
106        int c = p[i];
107        if (c < 32 || c > 127) {
108            c = '.';
109        }
110        line.push_back(c);
111    }
112
113    DR("%s\n", line.c_str());
114}
115
116bool parse_host_and_port(const std::string& address,
117                         std::string* canonical_address,
118                         std::string* host, int* port,
119                         std::string* error) {
120    host->clear();
121
122    bool ipv6 = true;
123    bool saw_port = false;
124    size_t colons = std::count(address.begin(), address.end(), ':');
125    size_t dots = std::count(address.begin(), address.end(), '.');
126    std::string port_str;
127    if (address[0] == '[') {
128      // [::1]:123
129      if (address.rfind("]:") == std::string::npos) {
130        *error = android::base::StringPrintf("bad IPv6 address '%s'", address.c_str());
131        return false;
132      }
133      *host = address.substr(1, (address.find("]:") - 1));
134      port_str = address.substr(address.rfind("]:") + 2);
135      saw_port = true;
136    } else if (dots == 0 && colons >= 2 && colons <= 7) {
137      // ::1
138      *host = address;
139    } else if (colons <= 1) {
140      // 1.2.3.4 or some.accidental.domain.com
141      ipv6 = false;
142      std::vector<std::string> pieces = android::base::Split(address, ":");
143      *host = pieces[0];
144      if (pieces.size() > 1) {
145        port_str = pieces[1];
146        saw_port = true;
147      }
148    }
149
150    if (host->empty()) {
151      *error = android::base::StringPrintf("no host in '%s'", address.c_str());
152      return false;
153    }
154
155    if (saw_port) {
156      if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 || *port > 65535) {
157        *error = android::base::StringPrintf("bad port number '%s' in '%s'",
158                                             port_str.c_str(), address.c_str());
159        return false;
160      }
161    }
162
163    *canonical_address = android::base::StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port);
164    LOG(DEBUG) << "parsed " << address << " as " << *host << " and " << *port
165               << " (" << *canonical_address << ")";
166    return true;
167}
168
169int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
170    int getaddrinfo_error = 0;
171    int fd = socket_network_client_timeout(host.c_str(), port, type, timeout, &getaddrinfo_error);
172    if (fd != -1) {
173        return fd;
174    }
175    if (getaddrinfo_error != 0) {
176        // TODO: gai_strerror is not thread safe on Win32.
177        *error = gai_strerror(getaddrinfo_error);
178    } else {
179        *error = strerror(errno);
180    }
181    return -1;
182}
183