void FileTransfer::downloadFile(const std::string filepath) { std::string sourcePath(Plugin::GIT_CACHE_DIR); sourcePath.append("/").append(filepath); Process::Args args; args.push_back(filepath); // TODO: Change this name std::string targetPath("~/keshig-storage/"); targetPath.append(filepath); Poco::ProcessHandle ph = Process::launch("scp", args, 0, 0, 0); if (ph.wait() != 0) throw new Poco::RuntimeException("Failed to upload file"); }
int runcommand_stream(const CommandLine & operation, edServiceOutput outputMode, Poco::Path initialDirectory, const Poco::Process::Env & env, std::string * out) { // streaming as the command runs. int rval = -1; std::ostringstream oss; // sanity check parameters. Poco::Path bfp(operation.command); //poco_assert(utils::fileexists(bfp)); poco_assert(bfp.isFile()); // log the command, getting the args right is non-trivial in some cases so this is useful. std::string cmd = operation.command; for (const auto & entry : operation.args) cmd += " [" + entry + "]"; logmsg(kLDEBUG, "runcommand_stream: " + cmd); try { Poco::Pipe outpipe; Poco::ProcessHandle ph = Poco::Process::launch(operation.command, operation.args, initialDirectory.toString(), 0, &outpipe, &outpipe, env); Poco::PipeInputStream pis(outpipe); Poco::TeeOutputStream tee(oss); if (outputMode==kORaw) // otherwise it's kOSuppressed. tee.addStream(std::cout); Poco::StreamCopier::copyStreamUnbuffered(pis, tee); rval = ph.wait(); } catch (Poco::SystemException & se) { fatal(se.displayText()); } if (out != NULL) *out = oss.str(); if (rval != 0) { std::ostringstream rvalmsg; rvalmsg << bfp.getFileName() << " returned " << rval; logmsg(kLDEBUG, rvalmsg.str()); } return rval; }
int Plugin::replaceWithLink(std::string filepath) { std::cout << "Replacing with link " << filepath.c_str() << std::endl; std::ifstream fstr(filepath.c_str()); MD5Engine md5; DigestOutputStream ostr(md5); Poco::StreamCopier::copyStream(fstr, ostr); ostr.flush(); const DigestEngine::Digest& digest = md5.digest(); std::string sourceMd5 = DigestEngine::digestToHex(digest); std::cout << "File contents MD5 sum: " << sourceMd5.c_str() << std::endl; // Generate new file name UUIDGenerator gen; UUID tmpUuid = gen.createRandom(); std::string uuid = tmpUuid.toString(); std::string newFile(Plugin::GIT_CACHE_DIR); newFile.append("/"); newFile.append(uuid); Process::Args args; args.push_back(filepath); args.push_back(newFile); Poco::ProcessHandle ph = Process::launch("mv", args, 0, 0, 0); // Failback with sudo if (ph.wait() != 0) { args.clear(); args.push_back("mv"); args.push_back(filepath); args.push_back(newFile); ph = Process::launch("sudo", args, 0, 0, 0); } // Check if file was moved File originalFile(filepath); if (originalFile.exists()) { std::cout << "Failed to move original file" << std::endl; return -1; } return 1; }
void Susi::Syscall::Worker::run() { Poco::Pipe outPipe; Poco::Pipe errPipe; Poco::ProcessHandle ph = Poco::Process::launch(_cmd, _args, 0, &outPipe, &errPipe); Poco::PipeInputStream ostr(outPipe); Poco::PipeInputStream estr(errPipe); if(_bg == true) { auto start_payload = Susi::Util::Any::Object{ {"process_type" , _process_type }, {"started", true} }; auto started_event = Susi::Events::createEvent("syscall::startedProcess"); started_event->payload["result"] = start_payload; Susi::Events::publish(std::move(started_event)); } int rc = ph.wait(); Susi::Util::Any end_payload = Susi::Util::Any::Object{ {"process_type" , _process_type }, {"stdout", this->getPipeContent(ostr)}, {"stderr", this->getPipeContent(estr)}, {"return", rc} }; //std::cout<<"Payload:"<<end_payload.toString()<<std::endl; auto end_event = Susi::Events::createEvent("syscall::endProcess"); end_event->payload["result"] = end_payload; Susi::Events::publish(std::move(end_event)); }
void Plugin::addFile(const std::string filepath) { logger().debug("Adding file"); // Check if file exists and it's not a directory File file(filepath); if (!file.exists()) { std::cout << "Failed to add file " << filepath.c_str() << ": file does not exist" << std::endl; return; } if (file.isDirectory()) { std::cout << "Failed to add file " << filepath.c_str() << ": file is a directory" << std::endl; return; } File index(Plugin::GIT_BIN_INDEX); if (!index.exists()) { index.createFile(); } // Find this file in the index if (isFileIndexed(filepath) && file.isLink()) { logger().debug("File already in cache"); auto entry = getIndexEntry(filepath); if (entry == nullptr) { std::cout << "Failed to retrieve index meta data for " << filepath << std::endl; return; } // Not fresh. Update existing index file // Remove file from index before recalculating everything for (auto it = _index.begin(); it != _index.end();) { if ((*it).filepath == filepath) { // Remove link std::cout << "Replacing link with original file" << std::endl; file.remove(); Process::Args restoreArgs; std::string restorePath(Plugin::GIT_CACHE_DIR); restorePath.append("/wf/"); restorePath.append((*it).uuid); restoreArgs.push_back(restorePath); restoreArgs.push_back(filepath); Process::launch("mv", restoreArgs, 0, 0, 0); it = _index.erase(it); } else { it++; } } } // Add new file into index UUIDGenerator gen; IndexEntry e; e.filepath = filepath; e.md5 = getFileMd5(filepath); e.uuid = gen.createRandom().toString(); do { e.uuid = gen.createRandom().toString(); } while (!isUuidUnique(e.uuid)); _index.push_back(e); writeIndex(); // Place two copies of this file into cache // One copy is original file and don't tracked in any way // Second copy is a file we will create link to Process::Args args; args.push_back(filepath); std::string origPath(Plugin::GIT_CACHE_DIR); origPath.append("/of/").append(e.uuid); args.push_back(origPath); Poco::ProcessHandle copyProcess = Process::launch("cp", args, 0, 0, 0); if (copyProcess.wait() != 0) { std::cout << "Failed to move file into git-bin cache" << std::endl; return; } // Second stage copy args.clear(); args.push_back(filepath); std::string workPath(Plugin::GIT_CACHE_DIR); workPath.append("/wf/").append(e.uuid); args.push_back(workPath); copyProcess = Process::launch("mv", args, 0, 0, 0); if (copyProcess.wait() != 0) { std::cout << "Failed to move file on stage 2" << std::endl; return; } // Make a link args.clear(); args.push_back("-s"); Path rel(filepath); std::string relPath; for (int i = 0; i < rel.depth(); i++) { relPath.append("../"); } relPath.append(workPath); args.push_back(relPath); args.push_back(filepath); Poco::ProcessHandle linkProcess = Process::launch("ln", args, 0, 0, 0); if (linkProcess.wait() != 0) { std::cout << "Failed to create link to file" << std::endl; return; } args.clear(); args.push_back("add"); args.push_back(filepath); Poco::ProcessHandle gitAddProcess = Process::launch("git", args, 0, 0, 0); if (gitAddProcess.wait() != 0) { std::cout << "Failed to add file into git index (git add)" << std::endl; return; } }
int main(const std::vector<std::string>& args) { int rc = Poco::Util::Application::EXIT_OK; if (_helpRequested || args.empty()) { displayHelp(); } else { Poco::Timespan connectTimeout = Poco::Timespan(config().getInt("webtunnel.connectTimeout", 30), 0); Poco::Timespan remoteTimeout = Poco::Timespan(config().getInt("webtunnel.remoteTimeout", 300), 0); Poco::Timespan localTimeout = Poco::Timespan(config().getInt("webtunnel.localTimeout", 7200), 0); #if defined(WEBTUNNEL_ENABLE_TLS) bool acceptUnknownCert = config().getBool("tls.acceptUnknownCertificate", true); std::string cipherList = config().getString("tls.ciphers", "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); bool extendedVerification = config().getBool("tls.extendedCertificateVerification", false); std::string caLocation = config().getString("tls.caLocation", ""); Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> pCertificateHandler; if (acceptUnknownCert) pCertificateHandler = new Poco::Net::AcceptCertificateHandler(false); else pCertificateHandler = new Poco::Net::RejectCertificateHandler(false); Poco::Net::Context::Ptr pContext = new Poco::Net::Context(Poco::Net::Context::TLSV1_CLIENT_USE, "", "", caLocation, Poco::Net::Context::VERIFY_RELAXED, 5, true, cipherList); pContext->enableExtendedCertificateVerification(extendedVerification); Poco::Net::SSLManager::instance().initializeClient(0, pCertificateHandler, pContext); #endif if (config().getBool("http.proxy.enable", false)) { logger().information("Proxy enable"); Poco::Net::HTTPClientSession::ProxyConfig proxyConfig; proxyConfig.host = config().getString("http.proxy.host", ""); proxyConfig.port = static_cast<Poco::UInt16>(config().getInt("http.proxy.port", 80)); proxyConfig.username = config().getString("http.proxy.username", ""); proxyConfig.password = config().getString("http.proxy.password", ""); Poco::Net::HTTPClientSession::setGlobalProxyConfig(proxyConfig); } promptLogin(); Poco::URI uri(args[0]); Poco::WebTunnel::LocalPortForwarder forwarder(_localPort, _remotePort, uri, new Poco::WebTunnel::DefaultWebSocketFactory(_username, _password, connectTimeout)); forwarder.setRemoteTimeout(remoteTimeout); forwarder.setLocalTimeout(localTimeout); Poco::UInt16 localPort = forwarder.localPort(); std::string defaultVNCExecutable; #if defined(__APPLE__) defaultVNCExecutable = "open"; #else defaultVNCExecutable = "vncviewer"; #endif std::string vncExecutable = config().getString("vncviewer.executable", defaultVNCExecutable); Poco::Process::Args vncArgs; if (vncExecutable == "open") { vncArgs.push_back("-W"); vncArgs.push_back("-n"); vncArgs.push_back("vnc://localhost:" + Poco::NumberFormatter::format(static_cast<unsigned>(localPort))); } else { vncArgs.push_back("localhost:" + Poco::NumberFormatter::format(static_cast<unsigned>(localPort))); } vncArgs.insert(vncArgs.end(), ++args.begin(), args.end()); logger().debug(Poco::format("Launching VNC client: %s", vncExecutable)); Poco::ProcessHandle ph = Poco::Process::launch(vncExecutable, vncArgs); rc = ph.wait(); logger().debug(Poco::format("VNC client terminated with exit code %d", rc)); } return rc; }