blob: fd61bda61b39310ed79fa06d8dd034ae0af71795 [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
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Elliott Hughese67f1f82015-04-30 17:32:03 -070018
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
Josh Gao787f3442015-11-03 18:52:35 -080036ADB_MUTEX_DEFINE(basename_lock);
Spencer Low22191c32015-08-01 17:29:23 -070037ADB_MUTEX_DEFINE(dirname_lock);
38
Elliott Hughesa7090b92015-04-17 17:03:59 -070039bool getcwd(std::string* s) {
40 char* cwd = getcwd(nullptr, 0);
41 if (cwd != nullptr) *s = cwd;
42 free(cwd);
43 return (cwd != nullptr);
44}
45
Elliott Hughes58305772015-04-17 13:57:15 -070046bool directory_exists(const std::string& path) {
47 struct stat sb;
48 return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
49}
50
Elliott Hughes58305772015-04-17 13:57:15 -070051std::string escape_arg(const std::string& s) {
Elliott Hughes5498ade2015-04-17 20:50:11 -070052 std::string result = s;
Elliott Hughes58305772015-04-17 13:57:15 -070053
Elliott Hughes84b0bf22015-05-15 12:06:00 -070054 // Escape any ' in the string (before we single-quote the whole thing).
55 // The correct way to do this for the shell is to replace ' with '\'' --- that is,
56 // close the existing single-quoted string, escape a single single-quote, and start
57 // a new single-quoted string. Like the C preprocessor, the shell will concatenate
58 // these pieces into one string.
59 for (size_t i = 0; i < s.size(); ++i) {
60 if (s[i] == '\'') {
61 result.insert(i, "'\\'");
62 i += 2;
63 }
Elliott Hughes58305772015-04-17 13:57:15 -070064 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070065
66 // Prefix and suffix the whole string with '.
67 result.insert(result.begin(), '\'');
68 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -070069 return result;
70}
Elliott Hughese67f1f82015-04-30 17:32:03 -070071
Elliott Hughes5c742702015-07-30 17:42:01 -070072std::string adb_basename(const std::string& path) {
Josh Gao787f3442015-11-03 18:52:35 -080073 // Copy path because basename may modify the string passed in.
74 std::string result(path);
75
76 // Use lock because basename() may write to a process global and return a
77 // pointer to that. Note that this locking strategy only works if all other
78 // callers to dirname in the process also grab this same lock.
79 adb_mutex_lock(&basename_lock);
80
81 // Note that if std::string uses copy-on-write strings, &str[0] will cause
82 // the copy to be made, so there is no chance of us accidentally writing to
83 // the storage for 'path'.
84 char* name = basename(&result[0]);
85
86 // In case dirname returned a pointer to a process global, copy that string
87 // before leaving the lock.
88 result.assign(name);
89
90 adb_mutex_unlock(&basename_lock);
91
92 return result;
Elliott Hughes5c742702015-07-30 17:42:01 -070093}
94
Spencer Low22191c32015-08-01 17:29:23 -070095std::string adb_dirname(const std::string& path) {
96 // Copy path because dirname may modify the string passed in.
Josh Gao787f3442015-11-03 18:52:35 -080097 std::string result(path);
Spencer Low22191c32015-08-01 17:29:23 -070098
99 // Use lock because dirname() may write to a process global and return a
100 // pointer to that. Note that this locking strategy only works if all other
101 // callers to dirname in the process also grab this same lock.
102 adb_mutex_lock(&dirname_lock);
103
104 // Note that if std::string uses copy-on-write strings, &str[0] will cause
105 // the copy to be made, so there is no chance of us accidentally writing to
106 // the storage for 'path'.
Josh Gao787f3442015-11-03 18:52:35 -0800107 char* parent = dirname(&result[0]);
Spencer Low22191c32015-08-01 17:29:23 -0700108
109 // In case dirname returned a pointer to a process global, copy that string
110 // before leaving the lock.
Josh Gao787f3442015-11-03 18:52:35 -0800111 result.assign(parent);
Spencer Low22191c32015-08-01 17:29:23 -0700112
113 adb_mutex_unlock(&dirname_lock);
114
115 return result;
Alex Vallée14216142015-05-06 17:22:25 -0400116}
117
Spencer Low22191c32015-08-01 17:29:23 -0700118// Given a relative or absolute filepath, create the parent directory hierarchy
119// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700120bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700121 // TODO: all the callers do unlink && mkdirs && adb_creat ---
122 // that's probably the operation we should expose.
123
124 // Implementation Notes:
125 //
126 // Pros:
127 // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
128 // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
129 // (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
130 // combined with our adb_mkdir() which takes UTF-8).
131 // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
132 // So it does as few stat()s as possible before doing mkdir()s.
133 // Cons:
134 // - Recursive, so it uses stack space relative to number of directory
135 // components.
136
Josh Gao45b6fc82015-11-04 14:51:23 -0800137 if (directory_exists(path)) {
Spencer Low22191c32015-08-01 17:29:23 -0700138 return true;
139 }
140
141 // If dirname returned the same path as what we passed in, don't go recursive.
142 // This can happen on Windows when walking up the directory hierarchy and not
143 // finding anything that already exists (unlike POSIX that will eventually
144 // find . or /).
Josh Gao45b6fc82015-11-04 14:51:23 -0800145 const std::string parent(adb_dirname(path));
146
Spencer Low22191c32015-08-01 17:29:23 -0700147 if (parent == path) {
148 errno = ENOENT;
149 return false;
150 }
151
Josh Gao45b6fc82015-11-04 14:51:23 -0800152 // Recursively make parent directories of 'path'.
Spencer Low22191c32015-08-01 17:29:23 -0700153 if (!mkdirs(parent)) {
154 return false;
155 }
156
Josh Gao45b6fc82015-11-04 14:51:23 -0800157 // Now that the parent directory hierarchy of 'path' has been ensured,
Spencer Low22191c32015-08-01 17:29:23 -0700158 // create parent itself.
Josh Gao45b6fc82015-11-04 14:51:23 -0800159 if (adb_mkdir(path, 0775) == -1) {
Spencer Low22191c32015-08-01 17:29:23 -0700160 // Can't just check for errno == EEXIST because it might be a file that
161 // exists.
162 const int saved_errno = errno;
163 if (directory_exists(parent)) {
164 return true;
165 }
166 errno = saved_errno;
167 return false;
168 }
169
170 return true;
Elliott Hughes5c742702015-07-30 17:42:01 -0700171}
172
Yabin Cuiaed3c612015-09-22 15:52:57 -0700173std::string dump_hex(const void* data, size_t byte_count) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700174 byte_count = std::min(byte_count, size_t(16));
175
176 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
177
178 std::string line;
179 for (size_t i = 0; i < byte_count; ++i) {
180 android::base::StringAppendF(&line, "%02x", p[i]);
181 }
182 line.push_back(' ');
183
184 for (size_t i = 0; i < byte_count; ++i) {
185 int c = p[i];
186 if (c < 32 || c > 127) {
187 c = '.';
188 }
189 line.push_back(c);
190 }
191
Yabin Cuiaed3c612015-09-22 15:52:57 -0700192 return line;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700193}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700194
195bool parse_host_and_port(const std::string& address,
196 std::string* canonical_address,
197 std::string* host, int* port,
198 std::string* error) {
199 host->clear();
200
201 bool ipv6 = true;
202 bool saw_port = false;
203 size_t colons = std::count(address.begin(), address.end(), ':');
204 size_t dots = std::count(address.begin(), address.end(), '.');
205 std::string port_str;
206 if (address[0] == '[') {
207 // [::1]:123
208 if (address.rfind("]:") == std::string::npos) {
209 *error = android::base::StringPrintf("bad IPv6 address '%s'", address.c_str());
210 return false;
211 }
212 *host = address.substr(1, (address.find("]:") - 1));
213 port_str = address.substr(address.rfind("]:") + 2);
214 saw_port = true;
215 } else if (dots == 0 && colons >= 2 && colons <= 7) {
216 // ::1
217 *host = address;
218 } else if (colons <= 1) {
219 // 1.2.3.4 or some.accidental.domain.com
220 ipv6 = false;
221 std::vector<std::string> pieces = android::base::Split(address, ":");
222 *host = pieces[0];
223 if (pieces.size() > 1) {
224 port_str = pieces[1];
225 saw_port = true;
226 }
227 }
228
229 if (host->empty()) {
230 *error = android::base::StringPrintf("no host in '%s'", address.c_str());
231 return false;
232 }
233
234 if (saw_port) {
235 if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 || *port > 65535) {
236 *error = android::base::StringPrintf("bad port number '%s' in '%s'",
237 port_str.c_str(), address.c_str());
238 return false;
239 }
240 }
241
242 *canonical_address = android::base::StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port);
243 LOG(DEBUG) << "parsed " << address << " as " << *host << " and " << *port
244 << " (" << *canonical_address << ")";
245 return true;
246}
Elliott Hughesaa245492015-08-03 10:38:08 -0700247
248std::string perror_str(const char* msg) {
249 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
250}
Yabin Cui6dfef252015-10-06 15:10:05 -0700251
252#if !defined(_WIN32)
253bool set_file_block_mode(int fd, bool block) {
254 int flags = fcntl(fd, F_GETFL, 0);
255 if (flags == -1) {
256 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd;
257 return false;
258 }
259 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
260 if (fcntl(fd, F_SETFL, flags) != 0) {
261 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags;
262 return false;
263 }
264 return true;
265}
266#endif