Debian Codegraph @

CodeLite/clSSHAgent.cpp

raw
1 #include "asyncprocess.h"
2 #include "clSSHAgent.hpp"
3 #include "file_logger.h"
4 #include "fileutils.h"
5 #include "procutils.h"
6 #include <wx/filename.h>
7 #include <wx/utils.h>
8
9 #ifndef __WXMSW__
10 static wxString& AddQuotesIfNeeded(wxString& str)
11 {
12 if(str.Contains(" ")) {
13 str.Prepend("\"").Append("\"");
14 }
15 return str;
16 }
17 #endif
18
19 clSSHAgent::clSSHAgent() { Start(); }
20
21 clSSHAgent::~clSSHAgent() { Stop(); }
22
23 void clSSHAgent::Start()
24 {
25 wxFileName sshAgent;
26 if(!FileUtils::FindExe("ssh-agent", sshAgent)) {
27 clDEBUG() << "Could not find ssh-agent executable";
28 return;
29 }
30 clDEBUG() << "Found ssh-agent:" << sshAgent;
31
32 // Check if an instance of ssh-agent is already running
33 #ifdef __WXMSW__
34 PidVec_t P = ProcUtils::PS("ssh-agent");
35 if(P.empty()) {
36 clDEBUG() << "Could not find a running instance of ssh-agent, starting one...";
37 m_process = ::CreateAsyncProcess(nullptr, sshAgent.GetFullPath(),
38 IProcessCreateWithHiddenConsole | IProcessCreateDefault);
39 if(m_process) {
40 clDEBUG() << "Started" << sshAgent << "with process ID:" << m_process->GetPid() << clEndl;
41 } else {
42 clWARNING() << "Failed to start" << sshAgent << "ssh-agent daemon" << clEndl;
43 }
44 } else {
45 clDEBUG() << "Found ssh-agent running at pid:" << P.begin()->pid;
46 }
47 #else
48 wxFileName fnSocketPath(clStandardPaths::Get().GetUserDataDir(), "ssh-agent.");
49 fnSocketPath.AppendDir("tmp");
50 fnSocketPath.SetFullName(fnSocketPath.GetFullName() + (wxString() << ::wxGetProcessId()));
51 fnSocketPath.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
52 wxString socketPath = fnSocketPath.GetFullPath();
53 AddQuotesIfNeeded(socketPath);
54
55 wxString command = sshAgent.GetFullPath();
56 AddQuotesIfNeeded(command);
57 command << " -D -a " << socketPath;
58
59 m_process = ::CreateAsyncProcess(nullptr, command);
60 if(!m_process) {
61 clWARNING() << "Failed to launch" << command << clEndl;
62 } else {
63 clDEBUG() << "Starting ssh-agent:" << command << ". pid:" << m_process->GetPid();
64 // Call it on the next event loop, this will give the ssh-agent time to start
65
66 wxString SSH_AUTH_SOCK;
67 wxString SSH_AGENT_PID;
68 SSH_AGENT_PID << m_process->GetPid();
69 SSH_AUTH_SOCK = fnSocketPath.GetFullPath();
70 ::wxSetEnv("SSH_AUTH_SOCK", SSH_AUTH_SOCK);
71 ::wxSetEnv("SSH_AGENT_PID", SSH_AGENT_PID);
72 clDEBUG() << "SSH_AUTH_SOCK is set to:" << SSH_AUTH_SOCK;
73 clDEBUG() << "SSH_AGENT_PID is set to:" << SSH_AGENT_PID;
74 // Run ssh-add
75 }
76 #endif
77
78 // Execute ssh-add
79 sshAgent.SetFullName("ssh-add");
80 ProcUtils::SafeExecuteCommand(sshAgent.GetFullPath());
81 }
82
83 void clSSHAgent::Stop()
84 {
85 if(m_process) {
86 m_process->Terminate();
87 wxDELETE(m_process);
88 }
89 }