adb_utils.cpp revision 4f71319df011d796a60a43fc1bc68e16fbf7d321
1/* 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 17#define TRACE_TAG ADB 18 19#include "adb_utils.h" 20 21#include <libgen.h> 22#include <stdlib.h> 23#include <sys/stat.h> 24#include <sys/types.h> 25#include <unistd.h> 26 27#include <algorithm> 28 29#include <android-base/logging.h> 30#include <android-base/stringprintf.h> 31#include <android-base/strings.h> 32 33#include "adb_trace.h" 34#include "sysdeps.h" 35 36ADB_MUTEX_DEFINE(basename_lock); 37ADB_MUTEX_DEFINE(dirname_lock); 38 39bool 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 46bool 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 51std::string escape_arg(const std::string& s) { 52 std::string result = s; 53 54 // 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 } 64 } 65 66 // Prefix and suffix the whole string with '. 67 result.insert(result.begin(), '\''); 68 result.push_back('\''); 69 return result; 70} 71 72std::string adb_basename(const std::string& path) { 73 // 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; 93} 94 95std::string adb_dirname(const std::string& path) { 96 // Copy path because dirname may modify the string passed in. 97 std::string result(path); 98 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'. 107 char* parent = dirname(&result[0]); 108 109 // In case dirname returned a pointer to a process global, copy that string 110 // before leaving the lock. 111 result.assign(parent); 112 113 adb_mutex_unlock(&dirname_lock); 114 115 return result; 116} 117 118// Given a relative or absolute filepath, create the parent directory hierarchy 119// as needed. Returns true if the hierarchy is/was setup. 120bool mkdirs(const std::string& path) { 121 // 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 137 if (directory_exists(path)) { 138 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 /). 145 const std::string parent(adb_dirname(path)); 146 147 if (parent == path) { 148 errno = ENOENT; 149 return false; 150 } 151 152 // Recursively make parent directories of 'path'. 153 if (!mkdirs(parent)) { 154 return false; 155 } 156 157 // Now that the parent directory hierarchy of 'path' has been ensured, 158 // create parent itself. 159 if (adb_mkdir(path, 0775) == -1) { 160 // 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; 171} 172 173std::string dump_hex(const void* data, size_t byte_count) { 174 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 ch = p[i]; 186 line.push_back(isprint(ch) ? ch : '.'); 187 } 188 189 return line; 190} 191 192bool parse_host_and_port(const std::string& address, 193 std::string* canonical_address, 194 std::string* host, int* port, 195 std::string* error) { 196 host->clear(); 197 198 bool ipv6 = true; 199 bool saw_port = false; 200 size_t colons = std::count(address.begin(), address.end(), ':'); 201 size_t dots = std::count(address.begin(), address.end(), '.'); 202 std::string port_str; 203 if (address[0] == '[') { 204 // [::1]:123 205 if (address.rfind("]:") == std::string::npos) { 206 *error = android::base::StringPrintf("bad IPv6 address '%s'", address.c_str()); 207 return false; 208 } 209 *host = address.substr(1, (address.find("]:") - 1)); 210 port_str = address.substr(address.rfind("]:") + 2); 211 saw_port = true; 212 } else if (dots == 0 && colons >= 2 && colons <= 7) { 213 // ::1 214 *host = address; 215 } else if (colons <= 1) { 216 // 1.2.3.4 or some.accidental.domain.com 217 ipv6 = false; 218 std::vector<std::string> pieces = android::base::Split(address, ":"); 219 *host = pieces[0]; 220 if (pieces.size() > 1) { 221 port_str = pieces[1]; 222 saw_port = true; 223 } 224 } 225 226 if (host->empty()) { 227 *error = android::base::StringPrintf("no host in '%s'", address.c_str()); 228 return false; 229 } 230 231 if (saw_port) { 232 if (sscanf(port_str.c_str(), "%d", port) != 1 || *port <= 0 || *port > 65535) { 233 *error = android::base::StringPrintf("bad port number '%s' in '%s'", 234 port_str.c_str(), address.c_str()); 235 return false; 236 } 237 } 238 239 *canonical_address = android::base::StringPrintf(ipv6 ? "[%s]:%d" : "%s:%d", host->c_str(), *port); 240 LOG(DEBUG) << "parsed " << address << " as " << *host << " and " << *port 241 << " (" << *canonical_address << ")"; 242 return true; 243} 244 245std::string perror_str(const char* msg) { 246 return android::base::StringPrintf("%s: %s", msg, strerror(errno)); 247} 248 249#if !defined(_WIN32) 250bool set_file_block_mode(int fd, bool block) { 251 int flags = fcntl(fd, F_GETFL, 0); 252 if (flags == -1) { 253 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd; 254 return false; 255 } 256 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); 257 if (fcntl(fd, F_SETFL, flags) != 0) { 258 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags; 259 return false; 260 } 261 return true; 262} 263#endif 264