blob: 72ee9015d9c678960269d909d1e743b9c61e4688 [file] [log] [blame]
Elliott Hughes58305772015-04-17 13:57:15 -07001/*
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
Elliott Hughese67f1f82015-04-30 17:32:03 -070017#define TRACE_TAG TRACE_ADB
18
Elliott Hughes58305772015-04-17 13:57:15 -070019#include "adb_utils.h"
20
Spencer Low22191c32015-08-01 17:29:23 -070021#include <libgen.h>
Elliott Hughesa7090b92015-04-17 17:03:59 -070022#include <stdlib.h>
Elliott Hughes58305772015-04-17 13:57:15 -070023#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
26
Elliott Hughese67f1f82015-04-30 17:32:03 -070027#include <algorithm>
28
Elliott Hughes3d5f60d2015-07-18 12:21:30 -070029#include <base/logging.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070030#include <base/stringprintf.h>
Elliott Hughes3d5f60d2015-07-18 12:21:30 -070031#include <base/strings.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070032
33#include "adb_trace.h"
Elliott Hughes53daee62015-04-19 13:17:01 -070034#include "sysdeps.h"
35
Spencer Low22191c32015-08-01 17:29:23 -070036ADB_MUTEX_DEFINE(dirname_lock);
37
Elliott Hughesa7090b92015-04-17 17:03:59 -070038bool 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
Elliott Hughes58305772015-04-17 13:57:15 -070045bool 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
Elliott Hughes58305772015-04-17 13:57:15 -070050std::string escape_arg(const std::string& s) {
Elliott Hughes5498ade2015-04-17 20:50:11 -070051 std::string result = s;
Elliott Hughes58305772015-04-17 13:57:15 -070052
Elliott Hughes84b0bf22015-05-15 12:06:00 -070053 // 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 }
Elliott Hughes58305772015-04-17 13:57:15 -070063 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070064
65 // Prefix and suffix the whole string with '.
66 result.insert(result.begin(), '\'');
67 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -070068 return result;
69}
Elliott Hughese67f1f82015-04-30 17:32:03 -070070
Elliott Hughes5c742702015-07-30 17:42:01 -070071std::string adb_basename(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -070072 size_t base = path.find_last_of(OS_PATH_SEPARATORS);
73 return (base != std::string::npos) ? path.substr(base + 1) : path;
Elliott Hughes5c742702015-07-30 17:42:01 -070074}
75
Spencer Low22191c32015-08-01 17:29:23 -070076std::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;
Alex Vallée14216142015-05-06 17:22:25 -040097}
98
Spencer Low22191c32015-08-01 17:29:23 -070099// Given a relative or absolute filepath, create the parent directory hierarchy
100// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700101bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700102 // 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;
Elliott Hughes5c742702015-07-30 17:42:01 -0700152}
153
Elliott Hughese67f1f82015-04-30 17:32:03 -0700154void 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
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700173 D("%s", line.c_str());
Elliott Hughese67f1f82015-04-30 17:32:03 -0700174}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700175
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}
Elliott Hughesaa245492015-08-03 10:38:08 -0700228
229std::string perror_str(const char* msg) {
230 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
231}