Imported Upstream version 0.3.5
[anytun.git] / src / win32 / sysExec.hpp
1 /*
2  *  anytun
3  *
4  *  The secure anycast tunneling protocol (satp) defines a protocol used
5  *  for communication between any combination of unicast and anycast
6  *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
7  *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
8  *  ethernet, ip, arp ...). satp directly includes cryptography and
9  *  message authentication based on the methods used by SRTP.  It is
10  *  intended to deliver a generic, scaleable and secure solution for
11  *  tunneling and relaying of packets of any protocol.
12  *
13  *
14  *  Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl,
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License as published by
21  *  the Free Software Foundation, either version 3 of the License, or
22  *  any later version.
23  *
24  *  Anytun is distributed in the hope that it will be useful,
25  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *  GNU General Public License for more details.
28  *
29  *  You should have received a copy of the GNU General Public License
30  *  along with Anytun.  If not, see <http://www.gnu.org/licenses/>.
31  *
32  *  In addition, as a special exception, the copyright holders give
33  *  permission to link the code of portions of this program with the
34  *  OpenSSL library under certain conditions as described in each
35  *  individual source file, and distribute linked combinations
36  *  including the two.
37  *  You must obey the GNU General Public License in all respects
38  *  for all of the code used other than OpenSSL.  If you modify
39  *  file(s) with this exception, you may extend this exception to your
40  *  version of the file(s), but you are not obligated to do so.  If you
41  *  do not wish to do so, delete this exception statement from your
42  *  version.  If you delete this exception statement from all source
43  *  files in the program, then also delete it here.
44  */
45
46 #pragma once
47 #ifndef ANYTUN_sysexec_hpp_INCLUDED
48 #define ANYTUN_sysexec_hpp_INCLUDED
49
50 #include <algorithm>
51 #include <iostream> // todo remove
52 #include <windows.h>
53
54 SysExec::~SysExec()
55 {
56   if(!closed_) {
57     CloseHandle(process_info_.hProcess);
58     CloseHandle(process_info_.hThread);
59   }
60 }
61
62 STARTUPINFOA getStartupInfo()
63 {
64   STARTUPINFOA startup_info;
65   startup_info.cb = sizeof(STARTUPINFOA);
66   GetStartupInfoA(&startup_info);
67
68   //startup_info.dwFlags = STARTF_USESTDHANDLES;
69   //startup_info.hStdInput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;
70   //startup_info.hStdOutput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;
71   //startup_info.hStdError = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE;
72   startup_info.dwFlags |= STARTF_USESHOWWINDOW;
73   startup_info.wShowWindow = SW_HIDE;
74
75   return startup_info;
76 }
77
78 char const* const BATCH_FILE_EXTS[] = { ".bat", ".cmd" };
79 int const BATCH_FILE_EXTS_COUNT = sizeof(BATCH_FILE_EXTS) / sizeof(BATCH_FILE_EXTS[0]);
80
81 bool endsWith(std::string const& string, std::string const& suffix)
82 {
83   return string.find(suffix, string.size() - suffix.size()) != std::string::npos;
84 }
85
86 void SysExec::doExec(StringVector args, StringList env_param)
87 {
88   std::vector<char> arguments;
89
90   bool isBatchFile = false;
91   for(int i = 0; i < BATCH_FILE_EXTS_COUNT; ++i) {
92     if(endsWith(script_, BATCH_FILE_EXTS[i])) {
93       isBatchFile = true;
94       break;
95     }
96   }
97
98   if(isBatchFile) {
99     std::string const BATCH_INTERPRETER = "cmd /c \"";
100     arguments.insert(arguments.end(), BATCH_INTERPRETER.begin(), BATCH_INTERPRETER.end());
101   }
102   arguments.push_back('\"');
103   arguments.insert(arguments.end(), script_.begin(), script_.end());
104   arguments.push_back('\"');
105   arguments.push_back(' ');
106
107   for(StringVector::const_iterator it = args.begin(); it != args.end(); ++it) {
108     arguments.push_back('\"');
109     arguments.insert(arguments.end(), it->begin(), it->end());
110     arguments.push_back('\"');
111     arguments.push_back(' ');
112   }
113
114   if(isBatchFile) {
115     arguments.push_back('\"');
116   }
117   arguments.push_back(0);
118
119   STARTUPINFOA startup_info = getStartupInfo();
120
121   std::map<std::string, std::string> envDict;
122   for(StringList::const_iterator it = env_param.begin(); it != env_param.begin(); ++it) {
123     size_t delimiter_pos = it->find('=');
124     envDict.insert(std::make_pair(it->substr(0, delimiter_pos), it->substr(delimiter_pos + 1)));
125   }
126   std::vector<char> env;
127   for(std::map<std::string, std::string>::iterator it = envDict.begin(); it != envDict.end(); ++it) {
128     env.insert(env.end(), it->first.begin(), it->first.end());
129     env.push_back(0);
130   }
131   env.push_back(0);
132
133   if(!CreateProcessA(NULL,
134                      &arguments[0],
135                      NULL,
136                      NULL,
137                      false,
138                      0,
139                      &env[0],
140                      NULL,
141                      &startup_info,
142                      &process_info_
143                     )) {
144     cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' CreateProcess() error: " << GetLastError();
145     return;
146   }
147 }
148
149 int SysExec::waitForScript()
150 {
151   DWORD result = WaitForSingleObject(process_info_.hProcess, INFINITE);
152   assert(WAIT_OBJECT_0 == result); // WAIT_FAILED, WAIT_TIMEOUT ... ???
153   bool success = GetExitCodeProcess(process_info_.hProcess, &return_code_) != 0;
154   assert(true == success); // false -> HU?
155
156   CloseHandle(process_info_.hProcess);
157   CloseHandle(process_info_.hThread);
158   closed_ = true;
159
160   return static_cast<int>(return_code_);
161 }
162
163 void SysExec::waitAndDestroy(SysExec*& s)
164 {
165   if(!s) {
166     return;
167   }
168
169   s->waitForScript();
170   cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << s->return_code_;
171
172   delete(s);
173   s = NULL;
174 }
175
176 #endif // ANYTUN_sysexec_hpp_INCLUDED