blob: 0c3327fc3e7db52f244640b38f14f2642c736eb9 [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
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>
Josh Gaoe0b75022016-08-30 15:23:35 -070028#include <vector>
Elliott Hughese67f1f82015-04-30 17:32:03 -070029
Colin Cross58021d12017-02-23 21:23:05 -080030#include <android-base/file.h>
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
Spencer Low22191c32015-08-01 17:29:23 -070050
Josh Gao7d586072015-11-20 15:37:31 -080051#if defined(_WIN32)
52constexpr char kNullFileName[] = "NUL";
53#else
54constexpr char kNullFileName[] = "/dev/null";
55#endif
56
57void close_stdin() {
58 int fd = unix_open(kNullFileName, O_RDONLY);
59 if (fd == -1) {
60 fatal_errno("failed to open %s", kNullFileName);
61 }
62
63 if (TEMP_FAILURE_RETRY(dup2(fd, STDIN_FILENO)) == -1) {
64 fatal_errno("failed to redirect stdin to %s", kNullFileName);
65 }
66 unix_close(fd);
67}
68
Elliott Hughesa7090b92015-04-17 17:03:59 -070069bool getcwd(std::string* s) {
70 char* cwd = getcwd(nullptr, 0);
71 if (cwd != nullptr) *s = cwd;
72 free(cwd);
73 return (cwd != nullptr);
74}
75
Elliott Hughes58305772015-04-17 13:57:15 -070076bool directory_exists(const std::string& path) {
77 struct stat sb;
Josh Gaoff468dc2017-03-23 16:05:12 -070078 return stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
Elliott Hughes58305772015-04-17 13:57:15 -070079}
80
Elliott Hughes58305772015-04-17 13:57:15 -070081std::string escape_arg(const std::string& s) {
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.
Ryan Pricharde4fded22018-07-09 23:51:58 -070087
88 std::string result;
89 result.push_back('\'');
90
91 size_t base = 0;
92 while (true) {
93 size_t found = s.find('\'', base);
94 result.append(s, base, found - base);
95 if (found == s.npos) break;
96 result.append("'\\''");
97 base = found + 1;
Elliott Hughes58305772015-04-17 13:57:15 -070098 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070099
Elliott Hughes5498ade2015-04-17 20:50:11 -0700100 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -0700101 return result;
102}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700103
Spencer Low85c45bd2016-02-10 15:03:50 -0800104// Given a relative or absolute filepath, create the directory hierarchy
Spencer Low22191c32015-08-01 17:29:23 -0700105// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700106bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700107 // TODO: all the callers do unlink && mkdirs && adb_creat ---
108 // that's probably the operation we should expose.
109
110 // Implementation Notes:
111 //
112 // Pros:
113 // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
114 // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
115 // (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
116 // combined with our adb_mkdir() which takes UTF-8).
117 // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
118 // So it does as few stat()s as possible before doing mkdir()s.
119 // Cons:
120 // - Recursive, so it uses stack space relative to number of directory
121 // components.
122
Josh Gao1e611a32016-02-26 13:26:55 -0800123 // If path points to a symlink to a directory, that's fine.
124 struct stat sb;
125 if (stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) {
Spencer Low22191c32015-08-01 17:29:23 -0700126 return true;
127 }
128
Colin Cross58021d12017-02-23 21:23:05 -0800129 const std::string parent(android::base::Dirname(path));
Spencer Low85c45bd2016-02-10 15:03:50 -0800130
Spencer Low22191c32015-08-01 17:29:23 -0700131 // If dirname returned the same path as what we passed in, don't go recursive.
132 // This can happen on Windows when walking up the directory hierarchy and not
133 // finding anything that already exists (unlike POSIX that will eventually
134 // find . or /).
135 if (parent == path) {
136 errno = ENOENT;
137 return false;
138 }
139
Josh Gao45b6fc82015-11-04 14:51:23 -0800140 // Recursively make parent directories of 'path'.
Spencer Low22191c32015-08-01 17:29:23 -0700141 if (!mkdirs(parent)) {
142 return false;
143 }
144
Josh Gao45b6fc82015-11-04 14:51:23 -0800145 // Now that the parent directory hierarchy of 'path' has been ensured,
Spencer Low85c45bd2016-02-10 15:03:50 -0800146 // create path itself.
Josh Gao45b6fc82015-11-04 14:51:23 -0800147 if (adb_mkdir(path, 0775) == -1) {
Spencer Low22191c32015-08-01 17:29:23 -0700148 const int saved_errno = errno;
Spencer Low85c45bd2016-02-10 15:03:50 -0800149 // If someone else created the directory, that is ok.
150 if (directory_exists(path)) {
Spencer Low22191c32015-08-01 17:29:23 -0700151 return true;
152 }
Spencer Low85c45bd2016-02-10 15:03:50 -0800153 // There might be a pre-existing file at 'path', or there might have been some other error.
Spencer Low22191c32015-08-01 17:29:23 -0700154 errno = saved_errno;
155 return false;
156 }
157
158 return true;
Elliott Hughes5c742702015-07-30 17:42:01 -0700159}
160
Yabin Cuiaed3c612015-09-22 15:52:57 -0700161std::string dump_hex(const void* data, size_t byte_count) {
Dan Albert9893f932017-06-27 13:26:14 -0700162 size_t truncate_len = 16;
163 bool truncated = false;
164 if (byte_count > truncate_len) {
165 byte_count = truncate_len;
166 truncated = true;
167 }
Elliott Hughese67f1f82015-04-30 17:32:03 -0700168
169 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
170
171 std::string line;
172 for (size_t i = 0; i < byte_count; ++i) {
173 android::base::StringAppendF(&line, "%02x", p[i]);
174 }
175 line.push_back(' ');
176
177 for (size_t i = 0; i < byte_count; ++i) {
Spencer Low363af562015-11-07 18:51:54 -0800178 int ch = p[i];
179 line.push_back(isprint(ch) ? ch : '.');
Elliott Hughese67f1f82015-04-30 17:32:03 -0700180 }
181
Dan Albert9893f932017-06-27 13:26:14 -0700182 if (truncated) {
183 line += " [truncated]";
184 }
185
Yabin Cuiaed3c612015-09-22 15:52:57 -0700186 return line;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700187}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700188
Elliott Hughesaa245492015-08-03 10:38:08 -0700189std::string perror_str(const char* msg) {
190 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
191}
Yabin Cui6dfef252015-10-06 15:10:05 -0700192
193#if !defined(_WIN32)
Josh Gao3777d2e2016-02-16 17:34:53 -0800194// Windows version provided in sysdeps_win32.cpp
Yabin Cui6dfef252015-10-06 15:10:05 -0700195bool set_file_block_mode(int fd, bool block) {
196 int flags = fcntl(fd, F_GETFL, 0);
197 if (flags == -1) {
198 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd;
199 return false;
200 }
201 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
202 if (fcntl(fd, F_SETFL, flags) != 0) {
203 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags;
204 return false;
205 }
206 return true;
207}
208#endif
David Purselleaae97e2016-04-07 11:25:48 -0700209
210bool forward_targets_are_valid(const std::string& source, const std::string& dest,
211 std::string* error) {
212 if (android::base::StartsWith(source, "tcp:")) {
213 // The source port may be 0 to allow the system to select an open port.
214 int port;
215 if (!android::base::ParseInt(&source[4], &port) || port < 0) {
216 *error = android::base::StringPrintf("Invalid source port: '%s'", &source[4]);
217 return false;
218 }
219 }
220
221 if (android::base::StartsWith(dest, "tcp:")) {
222 // The destination port must be > 0.
223 int port;
224 if (!android::base::ParseInt(&dest[4], &port) || port <= 0) {
225 *error = android::base::StringPrintf("Invalid destination port: '%s'", &dest[4]);
226 return false;
227 }
228 }
229
230 return true;
231}
Yurii Zubrytskyif48adf62016-05-27 11:07:40 -0700232
Josh Gaoe0b75022016-08-30 15:23:35 -0700233std::string adb_get_homedir_path() {
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700234#ifdef _WIN32
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700235 WCHAR path[MAX_PATH];
236 const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
237 if (FAILED(hr)) {
238 D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
239 return {};
240 }
241 std::string home_str;
242 if (!android::base::WideToUTF8(path, &home_str)) {
243 return {};
244 }
245 return home_str;
246#else
247 if (const char* const home = getenv("HOME")) {
248 return home;
249 }
Josh Gaoe0b75022016-08-30 15:23:35 -0700250
251 struct passwd pwent;
252 struct passwd* result;
253 int pwent_max = sysconf(_SC_GETPW_R_SIZE_MAX);
254 std::vector<char> buf(pwent_max);
255 int rc = getpwuid_r(getuid(), &pwent, buf.data(), buf.size(), &result);
256 if (rc == 0 && result) {
257 return result->pw_dir;
258 }
259
260 LOG(FATAL) << "failed to get user home directory";
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700261 return {};
262#endif
263}
Josh Gaoe0b75022016-08-30 15:23:35 -0700264
265std::string adb_get_android_dir_path() {
266 std::string user_dir = adb_get_homedir_path();
267 std::string android_dir = user_dir + OS_PATH_SEPARATOR + ".android";
268 struct stat buf;
269 if (stat(android_dir.c_str(), &buf) == -1) {
270 if (adb_mkdir(android_dir.c_str(), 0750) == -1) {
271 PLOG(FATAL) << "Cannot mkdir '" << android_dir << "'";
272 }
273 }
274 return android_dir;
275}
Josh Gao924d35a2016-08-30 15:39:25 -0700276
277void AdbCloser::Close(int fd) {
278 adb_close(fd);
279}
Elliott Hughes2ec36b02017-02-06 16:20:30 -0800280
Elliott Hughes1fc8f6e2017-04-18 14:34:16 -0700281int syntax_error(const char* fmt, ...) {
282 fprintf(stderr, "adb: usage: ");
Elliott Hughes2ec36b02017-02-06 16:20:30 -0800283
284 va_list ap;
285 va_start(ap, fmt);
286 vfprintf(stderr, fmt, ap);
287 va_end(ap);
288
289 fprintf(stderr, "\n");
290 return 1;
291}
Elliott Hughes6eadee82017-06-15 08:35:24 -0700292
293std::string GetLogFilePath() {
294#if defined(_WIN32)
295 const char log_name[] = "adb.log";
296 WCHAR temp_path[MAX_PATH];
297
298 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992%28v=vs.85%29.aspx
299 DWORD nchars = GetTempPathW(arraysize(temp_path), temp_path);
300 if (nchars >= arraysize(temp_path) || nchars == 0) {
301 // If string truncation or some other error.
302 fatal("cannot retrieve temporary file path: %s\n",
303 android::base::SystemErrorCodeToString(GetLastError()).c_str());
304 }
305
306 std::string temp_path_utf8;
307 if (!android::base::WideToUTF8(temp_path, &temp_path_utf8)) {
308 fatal_errno("cannot convert temporary file path from UTF-16 to UTF-8");
309 }
310
311 return temp_path_utf8 + log_name;
312#else
313 const char* tmp_dir = getenv("TMPDIR");
314 if (tmp_dir == nullptr) tmp_dir = "/tmp";
315 return android::base::StringPrintf("%s/adb.%u.log", tmp_dir, getuid());
316#endif
317}