blob: db39ef47fe345a173aace9ffd60daa7029171c5a [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"
Josh Gao924d35a2016-08-30 15:39:25 -070020#include "adb_unique_fd.h"
Elliott Hughes58305772015-04-17 13:57:15 -070021
Spencer Low22191c32015-08-01 17:29:23 -070022#include <libgen.h>
Elliott Hughesa7090b92015-04-17 17:03:59 -070023#include <stdlib.h>
Elliott Hughes58305772015-04-17 13:57:15 -070024#include <sys/stat.h>
25#include <sys/types.h>
26#include <unistd.h>
27
Elliott Hughese67f1f82015-04-30 17:32:03 -070028#include <algorithm>
Josh Gaoe0b75022016-08-30 15:23:35 -070029#include <vector>
Elliott Hughese67f1f82015-04-30 17:32:03 -070030
Elliott Hughes4f713192015-12-04 22:00:26 -080031#include <android-base/logging.h>
David Purselleaae97e2016-04-07 11:25:48 -070032#include <android-base/parseint.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include <android-base/stringprintf.h>
34#include <android-base/strings.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070035
Josh Gao7d586072015-11-20 15:37:31 -080036#include "adb.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070037#include "adb_trace.h"
Elliott Hughes53daee62015-04-19 13:17:01 -070038#include "sysdeps.h"
39
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -070040#ifdef _WIN32
41# ifndef WIN32_LEAN_AND_MEAN
42# define WIN32_LEAN_AND_MEAN
43# endif
44# include "windows.h"
45# include "shlobj.h"
Josh Gaoe0b75022016-08-30 15:23:35 -070046#else
47#include <pwd.h>
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -070048#endif
49
Josh Gao787f3442015-11-03 18:52:35 -080050ADB_MUTEX_DEFINE(basename_lock);
Spencer Low22191c32015-08-01 17:29:23 -070051ADB_MUTEX_DEFINE(dirname_lock);
52
Josh Gao7d586072015-11-20 15:37:31 -080053#if defined(_WIN32)
54constexpr char kNullFileName[] = "NUL";
55#else
56constexpr char kNullFileName[] = "/dev/null";
57#endif
58
59void close_stdin() {
60 int fd = unix_open(kNullFileName, O_RDONLY);
61 if (fd == -1) {
62 fatal_errno("failed to open %s", kNullFileName);
63 }
64
65 if (TEMP_FAILURE_RETRY(dup2(fd, STDIN_FILENO)) == -1) {
66 fatal_errno("failed to redirect stdin to %s", kNullFileName);
67 }
68 unix_close(fd);
69}
70
Elliott Hughesa7090b92015-04-17 17:03:59 -070071bool getcwd(std::string* s) {
72 char* cwd = getcwd(nullptr, 0);
73 if (cwd != nullptr) *s = cwd;
74 free(cwd);
75 return (cwd != nullptr);
76}
77
Elliott Hughes58305772015-04-17 13:57:15 -070078bool directory_exists(const std::string& path) {
79 struct stat sb;
80 return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
81}
82
Elliott Hughes58305772015-04-17 13:57:15 -070083std::string escape_arg(const std::string& s) {
Elliott Hughes5498ade2015-04-17 20:50:11 -070084 std::string result = s;
Elliott Hughes58305772015-04-17 13:57:15 -070085
Elliott Hughes84b0bf22015-05-15 12:06:00 -070086 // Escape any ' in the string (before we single-quote the whole thing).
87 // The correct way to do this for the shell is to replace ' with '\'' --- that is,
88 // close the existing single-quoted string, escape a single single-quote, and start
89 // a new single-quoted string. Like the C preprocessor, the shell will concatenate
90 // these pieces into one string.
91 for (size_t i = 0; i < s.size(); ++i) {
92 if (s[i] == '\'') {
93 result.insert(i, "'\\'");
94 i += 2;
95 }
Elliott Hughes58305772015-04-17 13:57:15 -070096 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070097
98 // Prefix and suffix the whole string with '.
99 result.insert(result.begin(), '\'');
100 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -0700101 return result;
102}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700103
Elliott Hughes5c742702015-07-30 17:42:01 -0700104std::string adb_basename(const std::string& path) {
Josh Gao787f3442015-11-03 18:52:35 -0800105 // Copy path because basename may modify the string passed in.
106 std::string result(path);
107
108 // Use lock because basename() may write to a process global and return a
109 // pointer to that. Note that this locking strategy only works if all other
110 // callers to dirname in the process also grab this same lock.
111 adb_mutex_lock(&basename_lock);
112
113 // Note that if std::string uses copy-on-write strings, &str[0] will cause
114 // the copy to be made, so there is no chance of us accidentally writing to
115 // the storage for 'path'.
116 char* name = basename(&result[0]);
117
118 // In case dirname returned a pointer to a process global, copy that string
119 // before leaving the lock.
120 result.assign(name);
121
122 adb_mutex_unlock(&basename_lock);
123
124 return result;
Elliott Hughes5c742702015-07-30 17:42:01 -0700125}
126
Spencer Low22191c32015-08-01 17:29:23 -0700127std::string adb_dirname(const std::string& path) {
128 // Copy path because dirname may modify the string passed in.
Josh Gao787f3442015-11-03 18:52:35 -0800129 std::string result(path);
Spencer Low22191c32015-08-01 17:29:23 -0700130
131 // Use lock because dirname() may write to a process global and return a
132 // pointer to that. Note that this locking strategy only works if all other
133 // callers to dirname in the process also grab this same lock.
134 adb_mutex_lock(&dirname_lock);
135
136 // Note that if std::string uses copy-on-write strings, &str[0] will cause
137 // the copy to be made, so there is no chance of us accidentally writing to
138 // the storage for 'path'.
Josh Gao787f3442015-11-03 18:52:35 -0800139 char* parent = dirname(&result[0]);
Spencer Low22191c32015-08-01 17:29:23 -0700140
141 // In case dirname returned a pointer to a process global, copy that string
142 // before leaving the lock.
Josh Gao787f3442015-11-03 18:52:35 -0800143 result.assign(parent);
Spencer Low22191c32015-08-01 17:29:23 -0700144
145 adb_mutex_unlock(&dirname_lock);
146
147 return result;
Alex Vallée14216142015-05-06 17:22:25 -0400148}
149
Spencer Low85c45bd2016-02-10 15:03:50 -0800150// Given a relative or absolute filepath, create the directory hierarchy
Spencer Low22191c32015-08-01 17:29:23 -0700151// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700152bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700153 // TODO: all the callers do unlink && mkdirs && adb_creat ---
154 // that's probably the operation we should expose.
155
156 // Implementation Notes:
157 //
158 // Pros:
159 // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
160 // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
161 // (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
162 // combined with our adb_mkdir() which takes UTF-8).
163 // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
164 // So it does as few stat()s as possible before doing mkdir()s.
165 // Cons:
166 // - Recursive, so it uses stack space relative to number of directory
167 // components.
168
Josh Gao1e611a32016-02-26 13:26:55 -0800169 // If path points to a symlink to a directory, that's fine.
170 struct stat sb;
171 if (stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) {
Spencer Low22191c32015-08-01 17:29:23 -0700172 return true;
173 }
174
Spencer Low85c45bd2016-02-10 15:03:50 -0800175 const std::string parent(adb_dirname(path));
176
Spencer Low22191c32015-08-01 17:29:23 -0700177 // If dirname returned the same path as what we passed in, don't go recursive.
178 // This can happen on Windows when walking up the directory hierarchy and not
179 // finding anything that already exists (unlike POSIX that will eventually
180 // find . or /).
181 if (parent == path) {
182 errno = ENOENT;
183 return false;
184 }
185
Josh Gao45b6fc82015-11-04 14:51:23 -0800186 // Recursively make parent directories of 'path'.
Spencer Low22191c32015-08-01 17:29:23 -0700187 if (!mkdirs(parent)) {
188 return false;
189 }
190
Josh Gao45b6fc82015-11-04 14:51:23 -0800191 // Now that the parent directory hierarchy of 'path' has been ensured,
Spencer Low85c45bd2016-02-10 15:03:50 -0800192 // create path itself.
Josh Gao45b6fc82015-11-04 14:51:23 -0800193 if (adb_mkdir(path, 0775) == -1) {
Spencer Low22191c32015-08-01 17:29:23 -0700194 const int saved_errno = errno;
Spencer Low85c45bd2016-02-10 15:03:50 -0800195 // If someone else created the directory, that is ok.
196 if (directory_exists(path)) {
Spencer Low22191c32015-08-01 17:29:23 -0700197 return true;
198 }
Spencer Low85c45bd2016-02-10 15:03:50 -0800199 // There might be a pre-existing file at 'path', or there might have been some other error.
Spencer Low22191c32015-08-01 17:29:23 -0700200 errno = saved_errno;
201 return false;
202 }
203
204 return true;
Elliott Hughes5c742702015-07-30 17:42:01 -0700205}
206
Yabin Cuiaed3c612015-09-22 15:52:57 -0700207std::string dump_hex(const void* data, size_t byte_count) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700208 byte_count = std::min(byte_count, size_t(16));
209
210 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
211
212 std::string line;
213 for (size_t i = 0; i < byte_count; ++i) {
214 android::base::StringAppendF(&line, "%02x", p[i]);
215 }
216 line.push_back(' ');
217
218 for (size_t i = 0; i < byte_count; ++i) {
Spencer Low363af562015-11-07 18:51:54 -0800219 int ch = p[i];
220 line.push_back(isprint(ch) ? ch : '.');
Elliott Hughese67f1f82015-04-30 17:32:03 -0700221 }
222
Yabin Cuiaed3c612015-09-22 15:52:57 -0700223 return line;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700224}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700225
Elliott Hughesaa245492015-08-03 10:38:08 -0700226std::string perror_str(const char* msg) {
227 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
228}
Yabin Cui6dfef252015-10-06 15:10:05 -0700229
230#if !defined(_WIN32)
Josh Gao3777d2e2016-02-16 17:34:53 -0800231// Windows version provided in sysdeps_win32.cpp
Yabin Cui6dfef252015-10-06 15:10:05 -0700232bool set_file_block_mode(int fd, bool block) {
233 int flags = fcntl(fd, F_GETFL, 0);
234 if (flags == -1) {
235 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd;
236 return false;
237 }
238 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
239 if (fcntl(fd, F_SETFL, flags) != 0) {
240 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags;
241 return false;
242 }
243 return true;
244}
245#endif
David Purselleaae97e2016-04-07 11:25:48 -0700246
247bool forward_targets_are_valid(const std::string& source, const std::string& dest,
248 std::string* error) {
249 if (android::base::StartsWith(source, "tcp:")) {
250 // The source port may be 0 to allow the system to select an open port.
251 int port;
252 if (!android::base::ParseInt(&source[4], &port) || port < 0) {
253 *error = android::base::StringPrintf("Invalid source port: '%s'", &source[4]);
254 return false;
255 }
256 }
257
258 if (android::base::StartsWith(dest, "tcp:")) {
259 // The destination port must be > 0.
260 int port;
261 if (!android::base::ParseInt(&dest[4], &port) || port <= 0) {
262 *error = android::base::StringPrintf("Invalid destination port: '%s'", &dest[4]);
263 return false;
264 }
265 }
266
267 return true;
268}
Yurii Zubrytskyif48adf62016-05-27 11:07:40 -0700269
Josh Gaoe0b75022016-08-30 15:23:35 -0700270std::string adb_get_homedir_path() {
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700271#ifdef _WIN32
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700272 WCHAR path[MAX_PATH];
273 const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
274 if (FAILED(hr)) {
275 D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
276 return {};
277 }
278 std::string home_str;
279 if (!android::base::WideToUTF8(path, &home_str)) {
280 return {};
281 }
282 return home_str;
283#else
284 if (const char* const home = getenv("HOME")) {
285 return home;
286 }
Josh Gaoe0b75022016-08-30 15:23:35 -0700287
288 struct passwd pwent;
289 struct passwd* result;
290 int pwent_max = sysconf(_SC_GETPW_R_SIZE_MAX);
291 std::vector<char> buf(pwent_max);
292 int rc = getpwuid_r(getuid(), &pwent, buf.data(), buf.size(), &result);
293 if (rc == 0 && result) {
294 return result->pw_dir;
295 }
296
297 LOG(FATAL) << "failed to get user home directory";
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700298 return {};
299#endif
300}
Josh Gaoe0b75022016-08-30 15:23:35 -0700301
302std::string adb_get_android_dir_path() {
303 std::string user_dir = adb_get_homedir_path();
304 std::string android_dir = user_dir + OS_PATH_SEPARATOR + ".android";
305 struct stat buf;
306 if (stat(android_dir.c_str(), &buf) == -1) {
307 if (adb_mkdir(android_dir.c_str(), 0750) == -1) {
308 PLOG(FATAL) << "Cannot mkdir '" << android_dir << "'";
309 }
310 }
311 return android_dir;
312}
Josh Gao924d35a2016-08-30 15:39:25 -0700313
314void AdbCloser::Close(int fd) {
315 adb_close(fd);
316}