IPCWindows.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #ifdef ATOMIC_PLATFORM_WINDOWS
  23. #include <Windows.h>
  24. #include <Sddl.h>
  25. #include <AccCtrl.h>
  26. #include <Aclapi.h>
  27. #include <string>
  28. #include "../Core/Timer.h"
  29. #include "../IO/Log.h"
  30. #include "IPCWindows.h"
  31. #include "IPC.h"
  32. typedef std::wstring IPCWString;
  33. namespace Atomic
  34. {
  35. static const wchar_t kPipePrefix[] = L"\\\\.\\pipe\\";
  36. // start with 1 megabyte of buffer, this will grow if a request exceeds this size
  37. // however, it will block during resize
  38. static const int kPipeBufferSz = ATOMIC_WINDOWS_IPC_BUFFER_SIZE;
  39. static LONG g_pipe_seq = 0;
  40. HANDLE PipePair::OpenPipeServer(const wchar_t* name, bool read)
  41. {
  42. IPCWString pipename(kPipePrefix);
  43. pipename.append(name);
  44. DWORD openMode = read ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND;
  45. return ::CreateNamedPipeW(pipename.c_str(), openMode,
  46. PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
  47. 1, kPipeBufferSz, kPipeBufferSz, 200, NULL);
  48. }
  49. HANDLE PipePair::OpenPipeClient(const wchar_t* name, bool read)
  50. {
  51. IPCWString pipename(kPipePrefix);
  52. pipename.append(name);
  53. SECURITY_ATTRIBUTES sa;
  54. sa.bInheritHandle = TRUE;
  55. sa.lpSecurityDescriptor = NULL;
  56. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  57. DWORD accessMode = read ? GENERIC_READ : GENERIC_WRITE;
  58. for (;;) {
  59. HANDLE pipe = ::CreateFileW(pipename.c_str(), accessMode, 0, &sa,
  60. OPEN_EXISTING, 0, NULL);
  61. if (INVALID_HANDLE_VALUE == pipe) {
  62. if (ERROR_PIPE_BUSY != ::GetLastError()) {
  63. return pipe;
  64. }
  65. // wait and retry.
  66. ::Sleep(25);
  67. }
  68. else {
  69. // success.
  70. return pipe;
  71. }
  72. }
  73. }
  74. PipePair::PipePair() :
  75. srvRead_(INVALID_IPCHANDLE_VALUE),
  76. srvWrite_(INVALID_IPCHANDLE_VALUE),
  77. clnRead_(INVALID_IPCHANDLE_VALUE),
  78. clnWrite_(INVALID_IPCHANDLE_VALUE)
  79. {
  80. // Come up with a reasonable unique name.
  81. const wchar_t kPipePattern[] = L"ko.%x.%x.%x";
  82. wchar_t serverReadName[8 * 3 + sizeof(kPipePattern)];
  83. ::wsprintfW(serverReadName, kPipePattern, ::GetCurrentProcessId(), ::GetTickCount(),
  84. ::InterlockedIncrement(&g_pipe_seq));
  85. wchar_t serverWriteName[8 * 3 + sizeof(kPipePattern)];
  86. ::wsprintfW(serverWriteName, kPipePattern, ::GetCurrentProcessId(), ::GetTickCount() + 1,
  87. ::InterlockedIncrement(&g_pipe_seq));
  88. srvRead_ = OpenPipeServer(serverReadName, true);
  89. srvWrite_ = OpenPipeServer(serverWriteName, false);
  90. // Don't allow client impersonation.
  91. clnRead_ = OpenPipeClient(serverWriteName, true);
  92. clnWrite_ = OpenPipeClient(serverReadName, false);
  93. /*
  94. if (INVALID_HANDLE_VALUE == client)
  95. {
  96. ::CloseHandle(server);
  97. return;
  98. }
  99. */
  100. if (!::ConnectNamedPipe(srvRead_, NULL))
  101. {
  102. if (ERROR_PIPE_CONNECTED != ::GetLastError())
  103. {
  104. // ::CloseHandle(server);
  105. //::CloseHandle(client);
  106. return;
  107. }
  108. }
  109. if (!::ConnectNamedPipe(srvWrite_, NULL))
  110. {
  111. if (ERROR_PIPE_CONNECTED != ::GetLastError())
  112. {
  113. // ::CloseHandle(server);
  114. //::CloseHandle(client);
  115. return;
  116. }
  117. }
  118. }
  119. PipeWin::PipeWin() : pipeRead_(INVALID_IPCHANDLE_VALUE), pipeWrite_(INVALID_IPCHANDLE_VALUE), readerThread_(this)
  120. {
  121. }
  122. PipeWin::~PipeWin()
  123. {
  124. readerThread_.Kill();
  125. if (pipeRead_ != INVALID_HANDLE_VALUE)
  126. {
  127. ::DisconnectNamedPipe(pipeRead_); // $$$ disconect is valid on the server side.
  128. ::CloseHandle(pipeRead_);
  129. }
  130. if (pipeWrite_ != INVALID_HANDLE_VALUE)
  131. {
  132. ::DisconnectNamedPipe(pipeWrite_); // $$$ disconect is valid on the server side.
  133. ::CloseHandle(pipeWrite_);
  134. }
  135. }
  136. bool PipeWin::OpenClient(IPCHandle pipeRead, IPCHandle pipeWrite)
  137. {
  138. pipeRead_ = pipeRead;
  139. pipeWrite_ = pipeWrite;
  140. readerThread_.Run();
  141. return true;
  142. }
  143. bool PipeWin::OpenServer(IPCHandle pipeRead, IPCHandle pipeWrite)
  144. {
  145. pipeRead_ = pipeRead;
  146. pipeWrite_ = pipeWrite;
  147. readerThread_.Run();
  148. return true;
  149. }
  150. bool PipeWin::Write(const void* buf, size_t sz)
  151. {
  152. DWORD written = 0;
  153. if (TRUE == ::WriteFile(pipeWrite_, buf, (DWORD) sz, &written, NULL))
  154. return true;
  155. return false;
  156. }
  157. void PipeWin::ReaderThread::Kill()
  158. {
  159. if (handle_)
  160. {
  161. BOOL result = TerminateThread((HANDLE)handle_, 0);
  162. result = CloseHandle((HANDLE)handle_);
  163. handle_ = 0;
  164. }
  165. }
  166. void PipeWin::ReaderThread::ThreadFunction()
  167. {
  168. while(shouldRun_)
  169. {
  170. if (readSize_)
  171. continue;
  172. DWORD bytesRead = 0;
  173. if (TRUE == ::ReadFile(pipeWin_->pipeRead_, &buf_[0], ATOMIC_WINDOWS_IPC_BUFFER_SIZE, &bytesRead, NULL))
  174. {
  175. readSize_ = (unsigned) bytesRead;
  176. }
  177. Time::Sleep(10);
  178. }
  179. }
  180. bool PipeWin::Read(void* buf, size_t* sz)
  181. {
  182. *sz = 0;
  183. if (readerThread_.readSize_)
  184. {
  185. memcpy(buf, &readerThread_.buf_[0], readerThread_.readSize_);
  186. *sz = readerThread_.readSize_;
  187. readerThread_.readSize_ = 0;
  188. }
  189. return true;
  190. }
  191. char* PipeTransport::Receive(size_t* size)
  192. {
  193. if (buf_.Size() < kBufferSz)
  194. {
  195. buf_.Resize(kBufferSz);
  196. }
  197. *size = kBufferSz;
  198. if (!Read(&buf_[0], size))
  199. {
  200. return NULL;
  201. }
  202. return &buf_[0];
  203. }
  204. IPCProcess::IPCProcess(Context* context, IPCHandle clientRead, IPCHandle clientWrite, IPCHandle pid) : Object(context),
  205. pid_(pid),
  206. clientRead_(clientRead),
  207. clientWrite_(clientWrite)
  208. {
  209. }
  210. IPCProcess::~IPCProcess()
  211. {
  212. }
  213. bool IPCProcess::Terminate()
  214. {
  215. if (TerminateProcess(pid_, 0))
  216. {
  217. WaitForSingleObject(pid_, 1000);
  218. return true;
  219. }
  220. return false;
  221. }
  222. bool IPCProcess::IsRunning()
  223. {
  224. DWORD exitCode;
  225. if (!GetExitCodeProcess(pid_, &exitCode))
  226. return false;
  227. return exitCode == STILL_ACTIVE;
  228. }
  229. bool IPCProcess::Launch(const String& command, const Vector<String>& args, const String& initialDirectory)
  230. {
  231. STARTUPINFOW si = { sizeof(si) };
  232. PROCESS_INFORMATION pi = { 0 };
  233. // CreateProcess wants a single string
  234. String sargs;
  235. sargs.Join(args, " ");
  236. // convert to wide
  237. WString wcommand(command);
  238. // prepend the command and convert to wide
  239. WString wargs("\"" + command + "\" " + sargs);
  240. // The child process inherits the pipe handle.
  241. if (!::CreateProcessW(wcommand.CString(), (LPWSTR) wargs.CString(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  242. return false;
  243. }
  244. IPC* ipc = GetSubsystem<IPC>();
  245. IPCHandle jobHandle = ipc->GetJobHandle();
  246. if (jobHandle)
  247. {
  248. if (0 == AssignProcessToJobObject(jobHandle, pi.hProcess))
  249. {
  250. ATOMIC_LOGERROR("IPCProcess::Launch - unable to assign job");
  251. }
  252. }
  253. pid_ = pi.hProcess;
  254. ::CloseHandle(pi.hThread);
  255. return true;
  256. }
  257. }
  258. #endif