adb_utils.cpp revision 7a3f8d6691b3fbd8014a98de8455dbcfcc9629e4
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 <libgen.h>
22#include <stdlib.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
26
27#include <algorithm>
28
29#include <base/logging.h>
30#include <base/stringprintf.h>
31#include <base/strings.h>
32
33#include "adb_trace.h"
34#include "sysdeps.h"
35
36ADB_MUTEX_DEFINE(dirname_lock);
37
38bool getcwd(std::string* s) {
39  char* cwd = getcwd(nullptr, 0);
40  if (cwd != nullptr) *s = cwd;
41  free(cwd);
42  return (cwd != nullptr);
43}
44
45bool directory_exists(const std::string& path) {
46  struct stat sb;
47  return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
48}
49
50std::string escape_arg(const std::string& s) {
51  std::string result = s;
52
53  // Escape any ' in the string (before we single-quote the whole thing).
54  // The correct way to do this for the shell is to replace ' with '\'' --- that is,
55  // close the existing single-quoted string, escape a single single-quote, and start
56  // a new single-quoted string. Like the C preprocessor, the shell will concatenate
57  // these pieces into one string.
58  for (size_t i = 0; i < s.size(); ++i) {
59    if (s[i] == '\'') {
60      result.insert(i, "'\\'");
61      i += 2;
62    }
63  }
64
65  // Prefix and suffix the whole string with '.
66  result.insert(result.begin(), '\'');
67  result.push_back('\'');
68  return result;
69}
70
71std::string adb_basename(const std::string& path) {
72  size_t base = path.find_last_of(OS_PATH_SEPARATORS);
73  return (base != std::string::npos) ? path.substr(base + 1) : path;
74}
75
76std::string adb_dirname(const std::string& path) {
77  // Copy path because dirname may modify the string passed in.
78  std::string parent_storage(path);
79
80  // Use lock because dirname() may write to a process global and return a
81  // pointer to that. Note that this locking strategy only works if all other
82  // callers to dirname in the process also grab this same lock.
83  adb_mutex_lock(&dirname_lock);
84
85  // Note that if std::string uses copy-on-write strings, &str[0] will cause
86  // the copy to be made, so there is no chance of us accidentally writing to
87  // the storage for 'path'.
88  char* parent = dirname(&parent_storage[0]);
89
90  // In case dirname returned a pointer to a process global, copy that string
91  // before leaving the lock.
92  const std::string result(parent);
93
94  adb_mutex_unlock(&dirname_lock);
95
96  return result;
97}
98
99// Given a relative or absolute filepath, create the parent directory hierarchy
100// as needed. Returns true if the hierarchy is/was setup.
101bool mkdirs(const std::string& path) {
102  // TODO: all the callers do unlink && mkdirs && adb_creat ---
103  // that's probably the operation we should expose.
104
105  // Implementation Notes:
106  //
107  // Pros:
108  // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
109  // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
110  //   (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
111  //   combined with our adb_mkdir() which takes UTF-8).
112  // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
113  //   So it does as few stat()s as possible before doing mkdir()s.
114  // Cons:
115  // - Recursive, so it uses stack space relative to number of directory
116  //   components.
117
118  const std::string parent(adb_dirname(path));
119
120  if (directory_exists(parent)) {
121    return true;
122  }
123
124  // If dirname returned the same path as what we passed in, don't go recursive.
125  // This can happen on Windows when walking up the directory hierarchy and not
126  // finding anything that already exists (unlike POSIX that will eventually
127  // find . or /).
128  if (parent == path) {
129    errno = ENOENT;
130    return false;
131  }
132
133  // Recursively make parent directories of 'parent'.
134  if (!mkdirs(parent)) {
135    return false;
136  }
137
138  // Now that the parent directory hierarchy of 'parent' has been ensured,
139  // create parent itself.
140  if (adb_mkdir(parent, 0775) == -1) {
141    // Can't just check for errno == EEXIST because it might be a file that
142    // exists.
143    const int saved_errno = errno;
144    if (directory_exists(parent)) {
145      return true;
146    }
147    errno = saved_errno;
148    return false;
149  }
150
151  return true;
152}
153
154void dump_hex(const void* data, size_t byte_count) {
155    byte_count = std::min(byte_count, size_t(16));
156
157    const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
158
159    std::string line;
160    for (size_t i = 0; i < byte_count; ++i) {
161        android::base::StringAppendF(&line, "%02x", p[i]);
162    }
163    line.push_back(' ');
164
165    for (size_t i = 0; i < byte_count; ++i) {
166        int c = p[i];
167        if (c < 32 || c > 127) {
168            c = '.';
169        }
170        line.push_back(c);
171    }
172
173    D("%s", line.c_str());
174}
175
176bool parse_host_and_port(const std::string& address,
177                         std::string* canonical_address,
178                         std::string* host, int* port,
179                         std::string* error) {
180    host->clear();
181
182    bool ipv6 = true;
183    bool saw_port = false;
184    size_t colons = std::count(address.begin(), address.end(), ':');
185    size_t dots = std::count(address.begin(), address.end(), '.');
186    std::string port_str;
187    if (address[0] == '[') {
188      // [::1]:123
189      if (address.rfind("]:") == std::string::npos) {
190        *error = android::base::StringPrintf("bad IPv6 address '%s'", address.c_str());
191        return false;
192      }
193      *host = address.substr(1, (address.find("]:") - 1));
194      port_str = address.substr(address.rfind("]:") + 2);
195      saw_port = true;
196    } else if (dots == 0 && colons >= 2 && colons <= 7) {
197      // ::1
198      *host = address;
199    } else if (colons <= 1) {
200      // 1.2.3.4 or some.accidental.domain.com
201      ipv6 = false;
202      std::vector<std::string> pieces = android::base::Split(address, ":");
203      *host = pieces[0];
204      if (pieces.size() > 1) {
205        port_str = pieces[1];
206        saw_port = true;
207      }
208    }
209
210    if (host->empty()) {
211      *error = android::base::StringPrintf("no host in '%s'", address.c_str());
212      return false;
213    }
214
215    if (saw_port) {
216      if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 || *port > 65535) {
217        *error = android::base::StringPrintf("bad port number '%s' in '%s'",
218                                             port_str.c_str(), address.c_str());
219        return false;
220      }
221    }
222
223    *canonical_address = android::base::StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port);
224    LOG(DEBUG) << "parsed " << address << " as " << *host << " and " << *port
225               << " (" << *canonical_address << ")";
226    return true;
227}
228
229std::string perror_str(const char* msg) {
230    return android::base::StringPrintf("%s: %s", msg, strerror(errno));
231}
232