blob: 31ec8af2a367533681d8e1a9a7c04fe5aa0d1691 [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 Hughes4f713192015-12-04 22:00:26 -080029#include <android-base/logging.h>
David Purselleaae97e2016-04-07 11:25:48 -070030#include <android-base/parseint.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080031#include <android-base/stringprintf.h>
32#include <android-base/strings.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070033
Josh Gao7d586072015-11-20 15:37:31 -080034#include "adb.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070035#include "adb_trace.h"
Elliott Hughes53daee62015-04-19 13:17:01 -070036#include "sysdeps.h"
37
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -070038#ifdef _WIN32
39# ifndef WIN32_LEAN_AND_MEAN
40# define WIN32_LEAN_AND_MEAN
41# endif
42# include "windows.h"
43# include "shlobj.h"
44#endif
45
Josh Gao787f3442015-11-03 18:52:35 -080046ADB_MUTEX_DEFINE(basename_lock);
Spencer Low22191c32015-08-01 17:29:23 -070047ADB_MUTEX_DEFINE(dirname_lock);
48
Josh Gao7d586072015-11-20 15:37:31 -080049#if defined(_WIN32)
50constexpr char kNullFileName[] = "NUL";
51#else
52constexpr char kNullFileName[] = "/dev/null";
53#endif
54
55void close_stdin() {
56 int fd = unix_open(kNullFileName, O_RDONLY);
57 if (fd == -1) {
58 fatal_errno("failed to open %s", kNullFileName);
59 }
60
61 if (TEMP_FAILURE_RETRY(dup2(fd, STDIN_FILENO)) == -1) {
62 fatal_errno("failed to redirect stdin to %s", kNullFileName);
63 }
64 unix_close(fd);
65}
66
Elliott Hughesa7090b92015-04-17 17:03:59 -070067bool getcwd(std::string* s) {
68 char* cwd = getcwd(nullptr, 0);
69 if (cwd != nullptr) *s = cwd;
70 free(cwd);
71 return (cwd != nullptr);
72}
73
Elliott Hughes58305772015-04-17 13:57:15 -070074bool directory_exists(const std::string& path) {
75 struct stat sb;
76 return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
77}
78
Elliott Hughes58305772015-04-17 13:57:15 -070079std::string escape_arg(const std::string& s) {
Elliott Hughes5498ade2015-04-17 20:50:11 -070080 std::string result = s;
Elliott Hughes58305772015-04-17 13:57:15 -070081
Elliott Hughes84b0bf22015-05-15 12:06:00 -070082 // Escape any ' in the string (before we single-quote the whole thing).
83 // The correct way to do this for the shell is to replace ' with '\'' --- that is,
84 // close the existing single-quoted string, escape a single single-quote, and start
85 // a new single-quoted string. Like the C preprocessor, the shell will concatenate
86 // these pieces into one string.
87 for (size_t i = 0; i < s.size(); ++i) {
88 if (s[i] == '\'') {
89 result.insert(i, "'\\'");
90 i += 2;
91 }
Elliott Hughes58305772015-04-17 13:57:15 -070092 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070093
94 // Prefix and suffix the whole string with '.
95 result.insert(result.begin(), '\'');
96 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -070097 return result;
98}
Elliott Hughese67f1f82015-04-30 17:32:03 -070099
Elliott Hughes5c742702015-07-30 17:42:01 -0700100std::string adb_basename(const std::string& path) {
Josh Gao787f3442015-11-03 18:52:35 -0800101 // Copy path because basename may modify the string passed in.
102 std::string result(path);
103
104 // Use lock because basename() may write to a process global and return a
105 // pointer to that. Note that this locking strategy only works if all other
106 // callers to dirname in the process also grab this same lock.
107 adb_mutex_lock(&basename_lock);
108
109 // Note that if std::string uses copy-on-write strings, &str[0] will cause
110 // the copy to be made, so there is no chance of us accidentally writing to
111 // the storage for 'path'.
112 char* name = basename(&result[0]);
113
114 // In case dirname returned a pointer to a process global, copy that string
115 // before leaving the lock.
116 result.assign(name);
117
118 adb_mutex_unlock(&basename_lock);
119
120 return result;
Elliott Hughes5c742702015-07-30 17:42:01 -0700121}
122
Spencer Low22191c32015-08-01 17:29:23 -0700123std::string adb_dirname(const std::string& path) {
124 // Copy path because dirname may modify the string passed in.
Josh Gao787f3442015-11-03 18:52:35 -0800125 std::string result(path);
Spencer Low22191c32015-08-01 17:29:23 -0700126
127 // Use lock because dirname() may write to a process global and return a
128 // pointer to that. Note that this locking strategy only works if all other
129 // callers to dirname in the process also grab this same lock.
130 adb_mutex_lock(&dirname_lock);
131
132 // Note that if std::string uses copy-on-write strings, &str[0] will cause
133 // the copy to be made, so there is no chance of us accidentally writing to
134 // the storage for 'path'.
Josh Gao787f3442015-11-03 18:52:35 -0800135 char* parent = dirname(&result[0]);
Spencer Low22191c32015-08-01 17:29:23 -0700136
137 // In case dirname returned a pointer to a process global, copy that string
138 // before leaving the lock.
Josh Gao787f3442015-11-03 18:52:35 -0800139 result.assign(parent);
Spencer Low22191c32015-08-01 17:29:23 -0700140
141 adb_mutex_unlock(&dirname_lock);
142
143 return result;
Alex Vallée14216142015-05-06 17:22:25 -0400144}
145
Spencer Low85c45bd2016-02-10 15:03:50 -0800146// Given a relative or absolute filepath, create the directory hierarchy
Spencer Low22191c32015-08-01 17:29:23 -0700147// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700148bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700149 // TODO: all the callers do unlink && mkdirs && adb_creat ---
150 // that's probably the operation we should expose.
151
152 // Implementation Notes:
153 //
154 // Pros:
155 // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
156 // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
157 // (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
158 // combined with our adb_mkdir() which takes UTF-8).
159 // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
160 // So it does as few stat()s as possible before doing mkdir()s.
161 // Cons:
162 // - Recursive, so it uses stack space relative to number of directory
163 // components.
164
Josh Gao1e611a32016-02-26 13:26:55 -0800165 // If path points to a symlink to a directory, that's fine.
166 struct stat sb;
167 if (stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) {
Spencer Low22191c32015-08-01 17:29:23 -0700168 return true;
169 }
170
Spencer Low85c45bd2016-02-10 15:03:50 -0800171 const std::string parent(adb_dirname(path));
172
Spencer Low22191c32015-08-01 17:29:23 -0700173 // If dirname returned the same path as what we passed in, don't go recursive.
174 // This can happen on Windows when walking up the directory hierarchy and not
175 // finding anything that already exists (unlike POSIX that will eventually
176 // find . or /).
177 if (parent == path) {
178 errno = ENOENT;
179 return false;
180 }
181
Josh Gao45b6fc82015-11-04 14:51:23 -0800182 // Recursively make parent directories of 'path'.
Spencer Low22191c32015-08-01 17:29:23 -0700183 if (!mkdirs(parent)) {
184 return false;
185 }
186
Josh Gao45b6fc82015-11-04 14:51:23 -0800187 // Now that the parent directory hierarchy of 'path' has been ensured,
Spencer Low85c45bd2016-02-10 15:03:50 -0800188 // create path itself.
Josh Gao45b6fc82015-11-04 14:51:23 -0800189 if (adb_mkdir(path, 0775) == -1) {
Spencer Low22191c32015-08-01 17:29:23 -0700190 const int saved_errno = errno;
Spencer Low85c45bd2016-02-10 15:03:50 -0800191 // If someone else created the directory, that is ok.
192 if (directory_exists(path)) {
Spencer Low22191c32015-08-01 17:29:23 -0700193 return true;
194 }
Spencer Low85c45bd2016-02-10 15:03:50 -0800195 // There might be a pre-existing file at 'path', or there might have been some other error.
Spencer Low22191c32015-08-01 17:29:23 -0700196 errno = saved_errno;
197 return false;
198 }
199
200 return true;
Elliott Hughes5c742702015-07-30 17:42:01 -0700201}
202
Yabin Cuiaed3c612015-09-22 15:52:57 -0700203std::string dump_hex(const void* data, size_t byte_count) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700204 byte_count = std::min(byte_count, size_t(16));
205
206 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
207
208 std::string line;
209 for (size_t i = 0; i < byte_count; ++i) {
210 android::base::StringAppendF(&line, "%02x", p[i]);
211 }
212 line.push_back(' ');
213
214 for (size_t i = 0; i < byte_count; ++i) {
Spencer Low363af562015-11-07 18:51:54 -0800215 int ch = p[i];
216 line.push_back(isprint(ch) ? ch : '.');
Elliott Hughese67f1f82015-04-30 17:32:03 -0700217 }
218
Yabin Cuiaed3c612015-09-22 15:52:57 -0700219 return line;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700220}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700221
Elliott Hughesaa245492015-08-03 10:38:08 -0700222std::string perror_str(const char* msg) {
223 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
224}
Yabin Cui6dfef252015-10-06 15:10:05 -0700225
226#if !defined(_WIN32)
Josh Gao3777d2e2016-02-16 17:34:53 -0800227// Windows version provided in sysdeps_win32.cpp
Yabin Cui6dfef252015-10-06 15:10:05 -0700228bool set_file_block_mode(int fd, bool block) {
229 int flags = fcntl(fd, F_GETFL, 0);
230 if (flags == -1) {
231 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd;
232 return false;
233 }
234 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
235 if (fcntl(fd, F_SETFL, flags) != 0) {
236 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags;
237 return false;
238 }
239 return true;
240}
241#endif
David Purselleaae97e2016-04-07 11:25:48 -0700242
243bool forward_targets_are_valid(const std::string& source, const std::string& dest,
244 std::string* error) {
245 if (android::base::StartsWith(source, "tcp:")) {
246 // The source port may be 0 to allow the system to select an open port.
247 int port;
248 if (!android::base::ParseInt(&source[4], &port) || port < 0) {
249 *error = android::base::StringPrintf("Invalid source port: '%s'", &source[4]);
250 return false;
251 }
252 }
253
254 if (android::base::StartsWith(dest, "tcp:")) {
255 // The destination port must be > 0.
256 int port;
257 if (!android::base::ParseInt(&dest[4], &port) || port <= 0) {
258 *error = android::base::StringPrintf("Invalid destination port: '%s'", &dest[4]);
259 return false;
260 }
261 }
262
263 return true;
264}
Yurii Zubrytskyi2cdb9242016-05-27 11:11:22 -0700265
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700266std::string adb_get_homedir_path(bool check_env_first) {
267#ifdef _WIN32
268 if (check_env_first) {
269 if (const char* const home = getenv("ANDROID_SDK_HOME")) {
270 return home;
271 }
272 }
273
274 WCHAR path[MAX_PATH];
275 const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
276 if (FAILED(hr)) {
277 D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
278 return {};
279 }
280 std::string home_str;
281 if (!android::base::WideToUTF8(path, &home_str)) {
282 return {};
283 }
284 return home_str;
285#else
286 if (const char* const home = getenv("HOME")) {
287 return home;
288 }
289 return {};
290#endif
291}