| 59 | } |
| 60 | |
| 61 | bool SFTPTestServer::start() { |
| 62 | if (started_) { |
| 63 | return true; |
| 64 | } |
| 65 | #ifdef WIN32 |
| 66 | throw std::runtime_error("Not implemented"); |
| 67 | #else |
| 68 | /* Delete possible previous port.txt */ |
| 69 | port_file_path_ = utils::file::FileUtils::concat_path(working_directory_, "port.txt"); |
| 70 | if (!port_file_path_.empty()) { |
| 71 | logger_->log_debug("Deleting port file %s", port_file_path_.c_str()); |
| 72 | ::unlink(port_file_path_.c_str()); |
| 73 | } |
| 74 | |
| 75 | auto server_log_file_path = utils::file::FileUtils::concat_path(working_directory_, "log.txt"); |
| 76 | |
| 77 | /* fork */ |
| 78 | pid_t pid = fork(); |
| 79 | if (pid == 0) { |
| 80 | /* execv */ |
| 81 | std::vector<char*> args(4U); |
| 82 | args[0] = strdup("/bin/sh"); |
| 83 | args[1] = strdup("-c"); |
| 84 | args[2] = strdup(("exec java -Djava.security.egd=file:/dev/./urandom -jar " + jar_path_ + " -w " + working_directory_ + " -k " + host_key_file_ + " >" + server_log_file_path + " 2>&1").c_str()); |
| 85 | args[3] = nullptr; |
| 86 | execv("/bin/sh", args.data()); |
| 87 | std::cerr << "Failed to start server, errno: " << strerror(errno) << std::endl; |
| 88 | exit(-1); |
| 89 | } else if (pid < 0) { |
| 90 | logger_->log_error("Failed to fork, error: %s", strerror(errno)); |
| 91 | return false; |
| 92 | } else { |
| 93 | server_pid_ = pid; |
| 94 | |
| 95 | /* Wait for port.txt to be created */ |
| 96 | for (size_t i = 0; i < 15; i++) { |
| 97 | std::ifstream port_file(port_file_path_); |
| 98 | if (port_file.is_open() && port_file.good()) { |
| 99 | uint16_t port; |
| 100 | if (port_file >> port) { |
| 101 | port_ = port; |
| 102 | started_ = true; |
| 103 | logger_->log_debug("Found port file after %zu seconds", i); |
| 104 | return true; |
| 105 | } |
| 106 | } |
| 107 | logger_->log_debug("Could not find port file after %zu seconds", i); |
| 108 | std::this_thread::sleep_for(std::chrono::seconds(1)); |
| 109 | } |
| 110 | |
| 111 | /* We could not find the port file, but the server has been started. Try to kill it. */ |
| 112 | this->stop(); |
| 113 | } |
| 114 | #endif |
| 115 | |
| 116 | return false; |
| 117 | } |
| 118 |
no test coverage detected