void Pipe2Sock::OnShutdown() { if (listen_pipe.IsOpen()) listen_pipe.Close(); if (socket.IsOpen()) { if(dst_addr.IsMulticast()) { socket.LeaveGroup(dst_addr); } socket.Close(); } PLOG(PL_ERROR, "pipe2Sock: Done.\n"); } // end Pipe2Sock::OnShutdown()
void deletePath(const char* path) { struct stat statbuf; if (stat(path, &statbuf) == 0) { if (S_ISDIR(statbuf.st_mode)) { deleteRecursive(path); rmdir(path); } else { unlink(path); } } else { PLOG(ERROR) << "deletePath stat failed for " << path;; } }
/** * @brief log debug messages to a datagram ProtoPipe (PLOG only) */ bool OpenDebugPipe(const char* pipeName) { #ifndef SIMULATE if (!debug_pipe.Connect(pipeName)) { PLOG(PL_ERROR, "OpenDebugPipe: error opening/connecting debug_pipe!\n"); return false; } return true; #else return false; #endif // if/else !SIMULATE } // end OpenDebugPipe()
// The implementation of AddBootEventValue makes use of the mtime file // attribute to store the value associated with a boot event in order to // optimize on-disk size requirements and small-file thrashing. void BootEventRecordStore::AddBootEventWithValue( const std::string& event, int32_t value) { std::string record_path = GetBootEventPath(event); int record_fd = creat(record_path.c_str(), S_IRUSR | S_IWUSR); if (record_fd == -1) { PLOG(ERROR) << "Failed to create " << record_path; return; } // Writing the value as content in the record file is a debug measure to // ensure the validity of the file mtime value, i.e., to check that the record // file mtime values are not changed once set. // TODO(jhawkins): Remove this block. if (!android::base::WriteStringToFd(std::to_string(value), record_fd)) { PLOG(ERROR) << "Failed to write value to " << record_path; close(record_fd); return; } // Fill out the stat structure for |record_path| in order to get the atime to // set in the utime() call. struct stat file_stat; if (stat(record_path.c_str(), &file_stat) == -1) { PLOG(ERROR) << "Failed to read " << record_path; close(record_fd); return; } // Set the |modtime| of the file to store the value of the boot event while // preserving the |actime| (as read by stat). struct utimbuf times = {/* actime */ file_stat.st_atime, /* modtime */ value}; if (utime(record_path.c_str(), ×) == -1) { PLOG(ERROR) << "Failed to set mtime for " << record_path; close(record_fd); return; } close(record_fd); }
// On Android devices, we rely on the kernel to provide buffered read. // So we can recover automatically from EOVERFLOW. static int remote_read(apacket* p, usb_handle* usb) { if (usb_read(usb, &p->msg, sizeof(amessage)) != sizeof(amessage)) { PLOG(ERROR) << "remote usb: read terminated (message)"; return -1; } if (p->msg.data_length) { if (p->msg.data_length > MAX_PAYLOAD) { PLOG(ERROR) << "remote usb: read overflow (data length = " << p->msg.data_length << ")"; return -1; } p->payload.resize(p->msg.data_length); if (usb_read(usb, &p->payload[0], p->payload.size()) != static_cast<int>(p->payload.size())) { PLOG(ERROR) << "remote usb: terminated (data)"; return -1; } } return 0; }
bool Fifo::write(const struct iovec* iov, size_t iovcnt) noexcept { if (folly::writevNoInt(fd_, iov, iovcnt) == -1) { if (errno != EAGAIN) { PLOG(WARNING) << "Error writing to debug pipe."; } if (errno == EPIPE) { disconnect(); } return false; } return true; }
bool ProtoXml::IterParser::Open(const char* fileName, const char* filterPath) { Close(); // just in case already open if (NULL == (reader_ptr = xmlNewTextReaderFilename(fileName))) { PLOG(PL_ERROR, "ProtoXml::IterParser::Open() xmlNewTextReaderFilename() error: %s\n", GetErrorString()); return false; } if (NULL != filterPath) IterFilterBase::SetFilter(filterPath); return true; } // end ProtoXml::IterParser::Open()
int reverse_service(const char* command) { int s[2]; if (adb_socketpair(s)) { PLOG(ERROR) << "cannot create service socket pair."; return -1; } VLOG(SERVICES) << "service socketpair: " << s[0] << ", " << s[1]; if (handle_forward_request(command, kTransportAny, nullptr, s[1]) < 0) { SendFail(s[1], "not a reverse forwarding command"); } adb_close(s[1]); return s[0]; }
static void write_persistent_property(const char *name, const char *value) { char tempPath[PATH_MAX]; char path[PATH_MAX]; int fd; snprintf(tempPath, sizeof(tempPath), "%s/.temp.XXXXXX", PERSISTENT_PROPERTY_DIR); fd = mkstemp(tempPath); if (fd < 0) { PLOG(ERROR) << "Unable to write persistent property to temp file " << tempPath; return; } write(fd, value, strlen(value)); fsync(fd); close(fd); snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name); if (rename(tempPath, path)) { PLOG(ERROR) << "Unable to rename persistent property file " << tempPath << " to " << path; unlink(tempPath); } }
virtual CipherKey randomKey(int length) { CipherKey key(length); if (length == 0) return key; #ifdef HAVE_SEC_RANDOM_H if (SecRandomCopyBytes(kSecRandomDefault, key.size(), key.data()) < 0) { PLOG(ERROR) << "random key generation failure for length " << length; key.reset(); } #else #error No random number generator provided. #endif return key; }
static int commit_transaction(db_con_t * _h) { PGresult *mr; mr = PQexec(CON_CONNECTION(_h), "COMMIT"); if(!mr || PQresultStatus(mr) != PGRES_COMMAND_OK) { PLOG("commit_transaction", "error"); return -1; } PQclear(mr); return(0); }
void db_close(db_con_t* _h) { DLOG("db_close", "entry"); if(! _h) { PLOG("db_close", "no handle passed, ignored"); return; } disconnect_db(_h); aug_free(_h); }
inline bool su(const std::string& user) { struct passwd* passwd; if ((passwd = ::getpwnam(user.c_str())) == NULL) { PLOG(ERROR) << "Failed to get user information for '" << user << "', getpwnam"; return false; } if (::setgid(passwd->pw_gid) < 0) { PLOG(ERROR) << "Failed to set group id, setgid"; return false; } if (::setuid(passwd->pw_uid) < 0) { PLOG(ERROR) << "Failed to set user id, setuid"; return false; } return true; }
void TrimTask::run() { acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock); for (const auto& path : mPaths) { LOG(DEBUG) << "Starting trim of " << path; int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); if (fd < 0) { PLOG(WARNING) << "Failed to open " << path; continue; } struct fstrim_range range; memset(&range, 0, sizeof(range)); range.len = ULLONG_MAX; nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME); if (ioctl(fd, (mFlags & Flags::kDeepTrim) ? FIDTRIM : FITRIM, &range)) { PLOG(WARNING) << "Trim failed on " << path; notifyResult(path, -1, -1); } else { nsecs_t delta = systemTime(SYSTEM_TIME_BOOTTIME) - start; LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in " << nanoseconds_to_milliseconds(delta) << "ms"; notifyResult(path, range.len, delta); } close(fd); if (mFlags & Flags::kBenchmarkAfter) { #if BENCHMARK_ENABLED BenchmarkPrivate(path); #else LOG(DEBUG) << "Benchmark disabled"; #endif } } release_wake_lock(kWakeLock); }
bool generate_verity_tree(const std::string& data_filename, const std::string& verity_filename, HashTreeBuilder* builder, const std::vector<unsigned char>& salt_content, size_t block_size, bool sparse, bool verbose) { android::base::unique_fd data_fd(open(data_filename.c_str(), O_RDONLY)); if (data_fd == -1) { PLOG(ERROR) << "failed to open " << data_filename; return false; } struct sparse_file* file; if (sparse) { file = sparse_file_import(data_fd, false, false); } else { file = sparse_file_import_auto(data_fd, false, verbose); } if (!file) { LOG(ERROR) << "failed to read file " << data_filename; return false; } int64_t len = sparse_file_len(file, false, false); if (len % block_size != 0) { LOG(ERROR) << "file size " << len << " is not a multiple of " << block_size << " byte"; return false; } // Initialize the builder to compute the hash tree. if (!builder->Initialize(len, salt_content)) { LOG(ERROR) << "Failed to initialize HashTreeBuilder"; return false; } auto hash_callback = [](void* priv, const void* data, size_t len) { auto sparse_hasher = static_cast<HashTreeBuilder*>(priv); return sparse_hasher->Update(static_cast<const unsigned char*>(data), len) ? 0 : 1; }; sparse_file_callback(file, false, false, hash_callback, builder); sparse_file_destroy(file); if (!builder->BuildHashTree()) { return false; } return builder->WriteHashTreeToFile(verity_filename); }
int64_t WdtSocket::ioWithAbortCheck(F readOrWrite, T tbuf, int64_t numBytes, int timeoutMs, bool tryFull) { WDT_CHECK(threadCtx_.getAbortChecker() != nullptr) << "abort checker can not be null"; bool checkAbort = (threadCtx_.getOptions().abort_check_interval_millis > 0); auto startTime = Clock::now(); int64_t doneBytes = 0; int retries = 0; while (doneBytes < numBytes) { const int64_t ret = readOrWrite(fd_, tbuf + doneBytes, numBytes - doneBytes); if (ret < 0) { // error if (errno != EINTR && errno != EAGAIN) { PLOG(ERROR) << "non-retryable error encountered during socket io " << fd_ << " " << doneBytes << " " << retries; return (doneBytes > 0 ? doneBytes : ret); } } else if (ret == 0) { // eof VLOG(1) << "EOF received during socket io. fd : " << fd_ << ", finished bytes : " << doneBytes << ", retries : " << retries; return doneBytes; } else { // success doneBytes += ret; if (!tryFull) { // do not have to read/write entire data return doneBytes; } } if (checkAbort && threadCtx_.getAbortChecker()->shouldAbort()) { LOG(ERROR) << "transfer aborted during socket io " << fd_ << " " << doneBytes << " " << retries; return (doneBytes > 0 ? doneBytes : -1); } if (timeoutMs > 0) { int duration = durationMillis(Clock::now() - startTime); if (duration >= timeoutMs) { LOG(INFO) << "socket io timed out after " << duration << " ms, retries " << retries << " fd " << fd_ << " doneBytes " << doneBytes; return (doneBytes > 0 ? doneBytes : -1); } } retries++; } VLOG_IF(1, retries > 1) << "socket io for " << doneBytes << " bytes took " << retries << " retries"; return doneBytes; }
int copyFile(const char *fromPath, const char *toPath) { auto start = std::chrono::steady_clock::now(); android::base::unique_fd fromFd(open(fromPath, O_RDONLY)); if (fromFd == -1) { PLOG(ERROR) << "Failed to open copy from " << fromPath; return -1; } android::base::unique_fd toFd(open(toPath, O_CREAT | O_WRONLY, FILE_PERM)); if (toFd == -1) { PLOG(ERROR) << "Failed to open copy to " << toPath; return -1; } off_t offset = 0; struct stat sstat = {}; if (stat(fromPath, &sstat) == -1) return -1; off_t length = sstat.st_size; int ret = 0; while (offset < length) { ssize_t transfer_length = std::min(length - offset, (off_t) FILE_COPY_SIZE); ret = sendfile(toFd, fromFd, &offset, transfer_length); if (ret != transfer_length) { ret = -1; PLOG(ERROR) << "Copying failed!"; break; } } auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = end - start; LOG(DEBUG) << "Copied a file with MTP. Time: " << diff.count() << " s, Size: " << length << ", Rate: " << ((double) length) / diff.count() << " bytes/s"; chown(toPath, getuid(), FILE_GROUP); return ret == -1 ? -1 : 0; }
// Note: This function does not wake up suspended fd_wait. This is fine // since stop_and_join is only called on program's termination // (g_task_control.stop()), suspended bthreads do not block quit of // worker pthreads and completion of g_task_control.stop(). int stop_and_join() { if (!started()) { return 0; } // No matter what this function returns, _epfd will be set to -1 // (making started() false) to avoid latter stop_and_join() to // enter again. const int saved_epfd = _epfd; _epfd = -1; // epoll_wait cannot be woken up by closing _epfd. We wake up // epoll_wait by inserting a fd continuously triggering EPOLLOUT. // Visibility of _stop: constant EPOLLOUT forces epoll_wait to see // _stop (to be true) finally. _stop = true; int closing_epoll_pipe[2]; if (pipe(closing_epoll_pipe)) { PLOG(FATAL) << "Fail to create closing_epoll_pipe"; return -1; } epoll_event evt = { EPOLLOUT, { NULL } }; if (epoll_ctl(saved_epfd, EPOLL_CTL_ADD, closing_epoll_pipe[1], &evt) < 0) { PLOG(FATAL) << "Fail to add closing_epoll_pipe into epfd=" << saved_epfd; return -1; } const int rc = bthread_join(_tid, NULL); if (rc) { LOG(FATAL) << "Fail to join EpollThread, " << berror(rc); return -1; } close(closing_epoll_pipe[0]); close(closing_epoll_pipe[1]); close(saved_epfd); return 0; }
void fdevent_subproc_setup() { int s[2]; if(adb_socketpair(s)) { PLOG(FATAL) << "cannot create shell-exit socket-pair"; } D("fdevent_subproc: socket pair (%d, %d)", s[0], s[1]); SHELL_EXIT_NOTIFY_FD = s[0]; fdevent *fde = fdevent_create(s[1], fdevent_subproc_event_func, NULL); CHECK(fde != nullptr) << "cannot create fdevent for shell-exit handler"; fdevent_add(fde, FDE_READ); }
status_t PublicVolume::initAsecStage() { std::string legacyPath(mRawPath + "/android_secure"); std::string securePath(mRawPath + "/.android_secure"); // Recover legacy secure path if (!access(legacyPath.c_str(), R_OK | X_OK) && access(securePath.c_str(), R_OK | X_OK)) { if (rename(legacyPath.c_str(), securePath.c_str())) { PLOG(WARNING) << getId() << " failed to rename legacy ASEC dir"; } } if (TEMP_FAILURE_RETRY(mkdir(securePath.c_str(), 0700))) { if (errno != EEXIST) { PLOG(WARNING) << getId() << " creating ASEC stage failed"; return -errno; } } BindMount(securePath, kAsecPath); return OK; }
void lssdp_process_packet_libevent(evutil_socket_t sock, short event, void *arg) { unsigned int addr_len = 0; unsigned char pkt_buf[SSDP_MAX_PKT_LEN]; memset(pkt_buf, 0, SSDP_MAX_PKT_LEN); struct sockaddr_in sout; memset(&sout, 0, sizeof(struct sockaddr_in)); size_t plen; plen = recvfrom(sock, pkt_buf, SSDP_MAX_PKT_LEN, 0, (struct sockaddr *)&sout, &addr_len); if(plen){ if(SSDP_DEBUG) PLOG(PLOG_LEVEL_DEBUG,"recv buf: %s\n", pkt_buf); lssdp_process_packet(sock, (struct sockaddr *)&sout, pkt_buf, plen); } }
bool ProtoDebugWindow::Create() { Destroy(); parent_thread_id = GetCurrentThreadId(); if (!(thread_handle = CreateThread(NULL, 0, RunInThread, this, 0, &thread_id))) { return true; } else { PLOG(PL_ERROR, "ProtoDebugWindow::Create() CreateThread() error: %s\n", GetErrorString()); return false; } } // end ProtoDebugWindow::Create()
void BootEventRecordStore::AddBootEvent(const std::string& name) { std::string uptime_str; if (!android::base::ReadFileToString("/proc/uptime", &uptime_str)) { LOG(ERROR) << "Failed to read /proc/uptime"; } std::string record_path = GetBootEventPath(name); if (creat(record_path.c_str(), S_IRUSR | S_IWUSR) == -1) { PLOG(ERROR) << "Failed to create " << record_path; } struct stat file_stat; if (stat(record_path.c_str(), &file_stat) == -1) { PLOG(ERROR) << "Failed to read " << record_path; } // Cast intentionally rounds down. time_t uptime = static_cast<time_t>(strtod(uptime_str.c_str(), NULL)); struct utimbuf times = {file_stat.st_atime, uptime}; if (utime(record_path.c_str(), ×) == -1) { PLOG(ERROR) << "Failed to set mtime for " << record_path; } }
void PProfService::contention( ::google::protobuf::RpcController* controller_base, const ::brpc::ProfileRequest* /*request*/, ::brpc::ProfileResponse* /*response*/, ::google::protobuf::Closure* done) { ClosureGuard done_guard(done); Controller* cntl = static_cast<Controller*>(controller_base); cntl->http_response().set_content_type("text/plain"); int sleep_sec = ReadSeconds(cntl); if (sleep_sec <= 0) { if (!cntl->Failed()) { cntl->SetFailed(EINVAL, "You have to specify ?seconds=N. If you're " "using pprof, add --seconds=N"); } return; } // Log requester std::ostringstream client_info; client_info << cntl->remote_side(); if (cntl->auth_context()) { client_info << "(auth=" << cntl->auth_context()->user() << ')'; } else { client_info << "(no auth)"; } LOG(INFO) << client_info.str() << " requests for contention profile for " << sleep_sec << " seconds"; char prof_name[256]; if (MakeProfName(PROFILING_CONTENTION, prof_name, sizeof(prof_name)) != 0) { cntl->SetFailed(errno, "Fail to create .prof file, %s", berror()); return; } if (!bthread::ContentionProfilerStart(prof_name)) { cntl->SetFailed(EAGAIN, "Another profiler is running, try again later"); return; } if (bthread_usleep(sleep_sec * 1000000L) != 0) { PLOG(WARNING) << "Profiling has been interrupted"; } bthread::ContentionProfilerStop(); butil::fd_guard fd(open(prof_name, O_RDONLY)); if (fd < 0) { cntl->SetFailed(ENOENT, "Fail to open %s", prof_name); return; } butil::IOPortal portal; portal.append_from_file_descriptor(fd, ULONG_MAX); cntl->response_attachment().swap(portal); }
bool RemovePossibleFile(const std::string& filename) { struct stat st; if (stat(filename.c_str(), &st) == 0) { if (!S_ISREG(st.st_mode)) { LOG(ERROR) << filename << " is not a file."; return false; } if (unlink(filename.c_str()) == -1) { PLOG(ERROR) << "unlink(" << filename << ") failed"; return false; } } return true; }
int e4crypt_install_keyring() { key_serial_t device_keyring = add_key("keyring", "e4crypt", 0, 0, KEY_SPEC_SESSION_KEYRING); if (device_keyring == -1) { PLOG(ERROR) << "Failed to create keyring"; return -1; } LOG(INFO) << "Keyring created with id " << device_keyring << " in process " << getpid(); return 0; }
xmlNodePtr ProtoXml::IterParser::GetNext() { //TRACE("enter ProtoXml::IterParser::GetNext() prev_node:%s\n", prev_node ? (const char*)prev_node->name : "(null)"); int result; // If we didn't just return a "prev_node", then read the // very next sequential node w/ xmlTextReaderRead(), else // skip entire "prev_node" sub-tree w/ xmlTextReaderNext() if (NULL == prev_node) result = xmlTextReaderRead(reader_ptr); else result = xmlTextReaderNext(reader_ptr); prev_node = NULL; switch (result) { case 0: return NULL; case -1: PLOG(PL_ERROR, "ProtoXml::IterParser::GetNext() xmlTextReaderRead error!\n"); return NULL; default: break; } do { int nodeType = xmlTextReaderNodeType(reader_ptr); if (XML_READER_TYPE_ELEMENT != nodeType) continue; const char* nodeName = (const char*)xmlTextReaderConstLocalName(reader_ptr); if (NULL == nodeName) { PLOG(PL_ERROR, "ProtoXml::IterParser::GetNext() xmlTextReaderConstLocalName() error\n"); return NULL; } int nodeDepth = xmlTextReaderDepth(reader_ptr); if (nodeDepth < 0) { PLOG(PL_ERROR, "ProtoXml::IterParser::GetNext() xmlTextReaderDepth() error\n"); return NULL; } if (!IterFilterBase::UpdateCurrentPath(nodeDepth, nodeName)) { PLOG(PL_WARN, "ProtoXml::IterParser::GetNext() error: unable to update current path\n"); continue; } if (!IterFilterBase::IsMatch()) continue; // no match, so continue prev_node = xmlTextReaderExpand(reader_ptr); if (NULL == prev_node) PLOG(PL_ERROR, "ProtoXml::IterParser::GetNext() xmlTextReaderExpand() error!\n"); return prev_node; } while ((result = xmlTextReaderRead(reader_ptr)) > 0); if (result < 0) PLOG(PL_ERROR, "ProtoXml::IterParser::GetNext() xmlTextReaderRead() error!\n"); return NULL; } // end ProtoXml::IterParser::GetNext()
void load_recovery_id_prop() { std::string ro_hardware = property_get("ro.hardware"); if (ro_hardware.empty()) { LOG(ERROR) << "ro.hardware not set - unable to load recovery id"; return; } std::string fstab_filename = FSTAB_PREFIX + ro_hardware; std::unique_ptr<fstab, void(*)(fstab*)> tab(fs_mgr_read_fstab(fstab_filename.c_str()), fs_mgr_free_fstab); if (!tab) { PLOG(ERROR) << "unable to read fstab " << fstab_filename; return; } fstab_rec* rec = fs_mgr_get_entry_for_mount_point(tab.get(), RECOVERY_MOUNT_POINT); if (rec == NULL) { LOG(ERROR) << "/recovery not specified in fstab"; return; } int fd = open(rec->blk_device, O_RDONLY); if (fd == -1) { PLOG(ERROR) << "error opening block device " << rec->blk_device; return; } boot_img_hdr hdr; if (android::base::ReadFully(fd, &hdr, sizeof(hdr))) { std::string hex = bytes_to_hex(reinterpret_cast<uint8_t*>(hdr.id), sizeof(hdr.id)); property_set("ro.recovery_id", hex.c_str()); } else { PLOG(ERROR) << "error reading /recovery"; } close(fd); }
bool MemoryMapping::mlock(LockMode lock) { size_t amountSucceeded = 0; locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, amountSucceeded); if (locked_) { return true; } auto msg(folly::format( "mlock({}) failed at {}", mapLength_, amountSucceeded).str()); if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) { PLOG(WARNING) << msg; } else { PLOG(FATAL) << msg; } // only part of the buffer was mlocked, unlock it back if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, amountSucceeded)) { PLOG(WARNING) << "munlock()"; } return false; }
bool read_file(const char* path, std::string* content) { content->clear(); int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY|O_NOFOLLOW|O_CLOEXEC)); if (fd == -1) { return false; } // For security reasons, disallow world-writable // or group-writable files. struct stat sb; if (fstat(fd, &sb) == -1) { PLOG(ERROR) << "fstat failed for '" << path << "'"; return false; } if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) { PLOG(ERROR) << "skipping insecure file '" << path << "'"; return false; } bool okay = android::base::ReadFdToString(fd, content); close(fd); return okay; }