Debian Codegraph @

CodeLite/asyncprocess.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : asyncprocess.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 class wxEvtHandler;
27 class IProcess;
28
29 //#include "asyncprocess.h"
30 #include "asyncprocess.h"
31
32 #include "StringUtils.h"
33 #include "clTempFile.hpp"
34 #include "cl_command_event.h"
35 #include "file_logger.h"
36 #include "fileutils.h"
37 #include "processreaderthread.h"
38 #include "ssh_account_info.h"
39
40 #include <wx/arrstr.h>
41 #include <wx/string.h>
42
43 #ifdef __WXMSW__
44 static bool shell_is_cmd = true;
45 #include "winprocess_impl.h"
46 #else
47 static bool shell_is_cmd = false;
48 #include "unixprocess_impl.h"
49 #endif
50 class __AsyncCallback : public wxEvtHandler
51 {
52 std::function<void(const wxString&)> m_cb;
53 wxString m_output;
54
55 public:
56 __AsyncCallback(std::function<void(const wxString&)> cb)
57 : m_cb(std::move(cb))
58 {
59 Bind(wxEVT_ASYNC_PROCESS_TERMINATED, &__AsyncCallback::OnProcessTerminated, this);
60 Bind(wxEVT_ASYNC_PROCESS_OUTPUT, &__AsyncCallback::OnProcessOutput, this);
61 }
62 ~__AsyncCallback()
63 {
64 Unbind(wxEVT_ASYNC_PROCESS_TERMINATED, &__AsyncCallback::OnProcessTerminated, this);
65 Unbind(wxEVT_ASYNC_PROCESS_OUTPUT, &__AsyncCallback::OnProcessOutput, this);
66 }
67
68 void OnProcessOutput(clProcessEvent& event)
69 {
70 size_t new_len = m_output.length() + event.GetOutput().length();
71 if(new_len > m_output.length()) {
72 m_output.reserve(new_len);
73 m_output << event.GetOutput();
74 }
75 }
76
77 void OnProcessTerminated(clProcessEvent& event)
78 {
79 if(!event.GetOutput().empty()) {
80 m_output << event.GetOutput();
81 }
82 // all the user callback
83 m_cb(m_output);
84 delete event.GetProcess();
85 delete this; // we are no longer needed...
86 }
87 };
88
89 static void __WrapSpacesForShell(wxString& str, size_t flags)
90 {
91 str.Trim().Trim(false);
92 auto tmpArgs = StringUtils::BuildArgv(str);
93 if(tmpArgs.size() > 1) {
94 if(!shell_is_cmd || (flags & IProcessCreateSSH)) {
95 // escape any occurances of "
96 str.Replace("\"", "\\\"");
97 }
98 str.Append("\"").Prepend("\"");
99 }
100 }
101
102 static wxArrayString __WrapInShell(const wxArrayString& args, size_t flags)
103 {
104 wxArrayString tmparr = args;
105 for(wxString& arg : tmparr) {
106 __WrapSpacesForShell(arg, flags);
107 }
108
109 wxString cmd = wxJoin(tmparr, ' ', 0);
110 wxArrayString command;
111
112 bool is_ssh = flags & IProcessCreateSSH;
113 if(shell_is_cmd && !is_ssh) {
114 wxString shell = wxGetenv("COMSPEC");
115 if(shell.IsEmpty()) {
116 shell = "CMD.EXE";
117 }
118 command.Add(shell);
119 command.Add("/C");
120 command.Add("\"" + cmd + "\"");
121
122 } else {
123 command.Add("/bin/sh");
124 command.Add("-c");
125 command.Add("'" + cmd + "'");
126 }
127 return command;
128 }
129
130 static wxArrayString __AddSshCommand(const wxArrayString& args, const wxString& wd, const wxString& sshAccountName,
131 clTempFile& tmpfile, const clEnvList_t* env_list)
132 {
133 #ifndef __WXMSW__
134 wxUnusedVar(tmpfile);
135 #endif
136
137 // we accept both SSHAccountInfo* & wxString* with the account name
138 if(sshAccountName.empty()) {
139 clERROR() << "CreateAsyncProcess: no ssh account name provided" << endl;
140 return args;
141 }
142 wxArrayString a;
143
144 auto accountInfo = SSHAccountInfo::LoadAccount(sshAccountName);
145 if(accountInfo.GetAccountName().empty()) {
146 clERROR() << "CreateAsyncProcess: could not locate ssh account:" << sshAccountName << endl;
147 return args;
148 }
149
150 // determine the ssh client we have
151 wxString ssh_client = "ssh";
152
153 //----------------------------------------------------------
154 // prepare the main command ("args") as a one liner string
155 //----------------------------------------------------------
156 wxArrayString* p_args = const_cast<wxArrayString*>(&args);
157 wxArrayString tmpargs;
158
159 // add any environment variables provided by the caller
160 if(env_list) {
161 for(const std::pair<wxString, wxString>& env_var : *env_list) {
162 tmpargs.Add(env_var.first + "=" + env_var.second);
163 }
164 }
165
166 if(!wd.empty()) {
167 // add working directory
168 tmpargs.Add("cd");
169 tmpargs.Add(wd);
170 tmpargs.Add("&&");
171 }
172
173 // add the command arguments
174 tmpargs.insert(tmpargs.end(), args.begin(), args.end());
175 p_args = &tmpargs;
176
177 wxString oneLiner = wxJoin(*p_args, ' ', 0);
178 #ifdef __WXMSW__
179 oneLiner.Prepend("\"").Append("\"");
180 #else
181 oneLiner.Replace("\"", "\\\""); // escape any double quotes
182 #endif
183
184 //----------------------------------------------------------
185 // build the executing command
186 //----------------------------------------------------------
187
188 // the following are common to both ssh / putty clients
189 a.Add(ssh_client);
190 a.Add(accountInfo.GetUsername() + "@" + accountInfo.GetHost());
191 a.Add("-t"); // force tty
192 a.Add("-p"); // port
193 a.Add(wxString() << accountInfo.GetPort()); // the port number
194
195 //----------------------------------------------------------
196 // we support extra args in the environment variable
197 // CL_SSH_OPTIONS
198 //----------------------------------------------------------
199 wxString sshEnv;
200 if(::wxGetEnv("CL_SSH_OPTIONS", &sshEnv)) {
201 wxArrayString sshOptionsArr = StringUtils::BuildArgv(sshEnv);
202 a.insert(a.end(), sshOptionsArr.begin(), sshOptionsArr.end());
203 }
204
205 a.Add(oneLiner);
206 return a;
207 }
208
209 static void __FixArgs(wxArrayString& args)
210 {
211 for(wxString& arg : args) {
212 // escape LF/CR
213 arg.Replace("\n", "");
214 arg.Replace("\r", "");
215 #if defined(__WXOSX__) || defined(__WXGTK__)
216 arg.Trim().Trim(false);
217 if(arg.length() > 1) {
218 if(arg.StartsWith("'") && arg.EndsWith("'")) {
219 arg.Remove(0, 1);
220 arg.RemoveLast();
221 } else if(arg.StartsWith("\"") && arg.EndsWith("\"")) {
222 arg.Remove(0, 1);
223 arg.RemoveLast();
224 }
225 }
226 #endif
227 }
228 }
229
230 IProcess* CreateAsyncProcess(wxEvtHandler* parent, const std::vector<wxString>& args, size_t flags,
231 const wxString& workingDir, const clEnvList_t* env, const wxString& sshAccountName)
232 {
233 wxArrayString wxargs;
234 wxargs.reserve(args.size());
235 for(const wxString& s : args) {
236 wxargs.Add(s);
237 }
238 return CreateAsyncProcess(parent, wxargs, flags, workingDir, env, sshAccountName);
239 }
240
241 IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxArrayString& args, size_t flags, const wxString& workingDir,
242 const clEnvList_t* env, const wxString& sshAccountName)
243 {
244 clEnvironment e(env);
245 wxArrayString c = args;
246
247 // sanity:
248 // Check that we have SSH executable
249 wxFileName sshpath;
250 if((flags & IProcessCreateSSH) && !FileUtils::FindExe("ssh", sshpath)) {
251 return nullptr;
252 }
253
254 // clDEBUG1() << "1: CreateAsyncProcess called with:" << c << endl;
255
256 if(flags & IProcessWrapInShell) {
257 // wrap the command in OS specific terminal
258 c = __WrapInShell(c, flags);
259 }
260
261 clTempFile tmpfile; // needed for putty clients
262 tmpfile.Persist(); // do not delete this file on destruct
263 if(flags & IProcessCreateSSH) {
264 c = __AddSshCommand(c, workingDir, sshAccountName, tmpfile, env);
265 }
266
267 // needed on linux where fork does not require the extra quoting
268 __FixArgs(c);
269 // clDEBUG1() << "2: CreateAsyncProcess called with:" << c << endl;
270
271 #ifdef __WXMSW__
272 return WinProcessImpl::Execute(parent, c, flags, workingDir);
273 #else
274 return UnixProcessImpl::Execute(parent, c, flags, workingDir);
275 #endif
276 }
277
278 IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDir,
279 const clEnvList_t* env, const wxString& sshAccountName)
280 {
281 auto args = StringUtils::BuildArgv(cmd);
282 return CreateAsyncProcess(parent, args, flags, workingDir, env, sshAccountName);
283 }
284
285 void CreateAsyncProcessCB(const wxString& cmd, std::function<void(const wxString&)> cb, size_t flags,
286 const wxString& workingDir, const clEnvList_t* env)
287 {
288 clEnvironment e(env);
289 CreateAsyncProcess(new __AsyncCallback(move(cb)), cmd, flags, workingDir, env, wxEmptyString);
290 }
291
292 IProcess* CreateSyncProcess(const wxString& cmd, size_t flags, const wxString& workingDir, const clEnvList_t* env)
293 {
294 return CreateAsyncProcess(nullptr, StringUtils::BuildArgv(cmd), flags | IProcessCreateSync, workingDir, env,
295 wxEmptyString);
296 }
297
298 // Static methods:
299 bool IProcess::GetProcessExitCode(int pid, int& exitCode)
300 {
301 wxUnusedVar(pid);
302 wxUnusedVar(exitCode);
303
304 exitCode = 0;
305 return true;
306 }
307
308 void IProcess::SetProcessExitCode(int pid, int exitCode)
309 {
310 wxUnusedVar(pid);
311 wxUnusedVar(exitCode);
312 }
313
314 void IProcess::WaitForTerminate(wxString& output)
315 {
316 if(IsRedirect()) {
317 wxString buff;
318 wxString buffErr;
319 while(Read(buff, buffErr)) {
320 output << buff;
321 if(!buff.IsEmpty() && !buffErr.IsEmpty()) {
322 output << "\n";
323 }
324 output << buffErr;
325 }
326 } else {
327 // Just wait for the process to terminate in a busy loop
328 while(IsAlive()) {
329 wxThread::Sleep(10);
330 }
331 }
332 }
333
334 void IProcess::SuspendAsyncReads()
335 {
336 if(m_thr) {
337 clDEBUG1() << "Suspending process reader thread..." << endl;
338 m_thr->Suspend();
339 clDEBUG1() << "Suspending process reader thread...done" << endl;
340 }
341 }
342
343 void IProcess::ResumeAsyncReads()
344 {
345 if(m_thr) {
346 clDEBUG1() << "Resuming process reader thread..." << endl;
347 m_thr->Resume();
348 clDEBUG1() << "Resuming process reader thread..." << endl;
349 }
350 }