IPCWindows.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 "IPCWindows.h"
  29. typedef std::wstring IPCWString;
  30. namespace Atomic
  31. {
  32. static const wchar_t kPipePrefix[] = L"\\\\.\\pipe\\";
  33. static const int kPipeBufferSz = 4 * 1024;
  34. static LONG g_pipe_seq = 0;
  35. HANDLE PipePair::OpenPipeServer(const wchar_t* name, bool read)
  36. {
  37. IPCWString pipename(kPipePrefix);
  38. pipename.append(name);
  39. DWORD openMode = read ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND;
  40. return ::CreateNamedPipeW(pipename.c_str(), openMode,
  41. PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
  42. 1, kPipeBufferSz, kPipeBufferSz, 200, NULL);
  43. }
  44. HANDLE PipePair::OpenPipeClient(const wchar_t* name, bool read)
  45. {
  46. IPCWString pipename(kPipePrefix);
  47. pipename.append(name);
  48. SECURITY_ATTRIBUTES sa;
  49. sa.bInheritHandle = TRUE;
  50. sa.lpSecurityDescriptor = NULL;
  51. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  52. DWORD accessMode = read ? GENERIC_READ : GENERIC_WRITE;
  53. for (;;) {
  54. HANDLE pipe = ::CreateFileW(pipename.c_str(), accessMode, 0, &sa,
  55. OPEN_EXISTING, 0, NULL);
  56. if (INVALID_HANDLE_VALUE == pipe) {
  57. if (ERROR_PIPE_BUSY != ::GetLastError()) {
  58. return pipe;
  59. }
  60. // wait and retry.
  61. ::Sleep(25);
  62. }
  63. else {
  64. // success.
  65. return pipe;
  66. }
  67. }
  68. }
  69. PipePair::PipePair() :
  70. srvRead_(INVALID_IPCHANDLE_VALUE),
  71. srvWrite_(INVALID_IPCHANDLE_VALUE),
  72. clnRead_(INVALID_IPCHANDLE_VALUE),
  73. clnWrite_(INVALID_IPCHANDLE_VALUE)
  74. {
  75. // Come up with a reasonable unique name.
  76. const wchar_t kPipePattern[] = L"ko.%x.%x.%x";
  77. wchar_t serverReadName[8 * 3 + sizeof(kPipePattern)];
  78. ::wsprintfW(serverReadName, kPipePattern, ::GetCurrentProcessId(), ::GetTickCount(),
  79. ::InterlockedIncrement(&g_pipe_seq));
  80. wchar_t serverWriteName[8 * 3 + sizeof(kPipePattern)];
  81. ::wsprintfW(serverWriteName, kPipePattern, ::GetCurrentProcessId(), ::GetTickCount() + 1,
  82. ::InterlockedIncrement(&g_pipe_seq));
  83. srvRead_ = OpenPipeServer(serverReadName, true);
  84. srvWrite_ = OpenPipeServer(serverWriteName, false);
  85. // Don't allow client impersonation.
  86. clnRead_ = OpenPipeClient(serverWriteName, true);
  87. clnWrite_ = OpenPipeClient(serverReadName, false);
  88. /*
  89. if (INVALID_HANDLE_VALUE == client)
  90. {
  91. ::CloseHandle(server);
  92. return;
  93. }
  94. */
  95. if (!::ConnectNamedPipe(srvRead_, NULL))
  96. {
  97. if (ERROR_PIPE_CONNECTED != ::GetLastError())
  98. {
  99. // ::CloseHandle(server);
  100. //::CloseHandle(client);
  101. return;
  102. }
  103. }
  104. if (!::ConnectNamedPipe(srvWrite_, NULL))
  105. {
  106. if (ERROR_PIPE_CONNECTED != ::GetLastError())
  107. {
  108. // ::CloseHandle(server);
  109. //::CloseHandle(client);
  110. return;
  111. }
  112. }
  113. }
  114. PipeWin::PipeWin() : pipeRead_(INVALID_IPCHANDLE_VALUE), pipeWrite_(INVALID_IPCHANDLE_VALUE), readerThread_(this)
  115. {
  116. }
  117. PipeWin::~PipeWin()
  118. {
  119. readerThread_.Kill();
  120. if (pipeRead_ != INVALID_HANDLE_VALUE)
  121. {
  122. ::DisconnectNamedPipe(pipeRead_); // $$$ disconect is valid on the server side.
  123. ::CloseHandle(pipeRead_);
  124. }
  125. if (pipeWrite_ != INVALID_HANDLE_VALUE)
  126. {
  127. ::DisconnectNamedPipe(pipeWrite_); // $$$ disconect is valid on the server side.
  128. ::CloseHandle(pipeWrite_);
  129. }
  130. }
  131. bool PipeWin::OpenClient(IPCHandle pipeRead, IPCHandle pipeWrite)
  132. {
  133. pipeRead_ = pipeRead;
  134. pipeWrite_ = pipeWrite;
  135. readerThread_.Run();
  136. return true;
  137. }
  138. bool PipeWin::OpenServer(IPCHandle pipeRead, IPCHandle pipeWrite)
  139. {
  140. pipeRead_ = pipeRead;
  141. pipeWrite_ = pipeWrite;
  142. readerThread_.Run();
  143. return true;
  144. }
  145. bool PipeWin::Write(const void* buf, size_t sz)
  146. {
  147. DWORD written = 0;
  148. if (TRUE == ::WriteFile(pipeWrite_, buf, (DWORD) sz, &written, NULL))
  149. return true;
  150. return false;
  151. }
  152. void PipeWin::ReaderThread::Kill()
  153. {
  154. if (handle_)
  155. {
  156. BOOL result = TerminateThread((HANDLE)handle_, 0);
  157. result = CloseHandle((HANDLE)handle_);
  158. handle_ = 0;
  159. }
  160. }
  161. void PipeWin::ReaderThread::ThreadFunction()
  162. {
  163. while(shouldRun_)
  164. {
  165. if (readSize_)
  166. continue;
  167. DWORD bytesRead = 0;
  168. if (TRUE == ::ReadFile(pipeWin_->pipeRead_, &buf_[0], 4096, &bytesRead, NULL))
  169. {
  170. readSize_ = (unsigned) bytesRead;
  171. }
  172. }
  173. }
  174. bool PipeWin::Read(void* buf, size_t* sz)
  175. {
  176. *sz = 0;
  177. if (readerThread_.readSize_)
  178. {
  179. memcpy(buf, &readerThread_.buf_[0], readerThread_.readSize_);
  180. *sz = readerThread_.readSize_;
  181. readerThread_.readSize_ = 0;
  182. }
  183. return true;
  184. }
  185. char* PipeTransport::Receive(size_t* size)
  186. {
  187. if (buf_.Size() < kBufferSz)
  188. {
  189. buf_.Resize(kBufferSz);
  190. }
  191. *size = kBufferSz;
  192. if (!Read(&buf_[0], size))
  193. {
  194. return NULL;
  195. }
  196. return &buf_[0];
  197. }
  198. IPCProcess::IPCProcess(Context* context, IPCHandle clientRead, IPCHandle clientWrite, IPCHandle pid) : Object(context),
  199. pid_(pid),
  200. clientRead_(clientRead),
  201. clientWrite_(clientWrite)
  202. {
  203. }
  204. IPCProcess::~IPCProcess()
  205. {
  206. }
  207. bool IPCProcess::IsRunning()
  208. {
  209. DWORD exitCode;
  210. if (!GetExitCodeProcess(pid_, &exitCode))
  211. return false;
  212. return exitCode == STILL_ACTIVE;
  213. }
  214. bool IPCProcess::Launch(const String& command, const Vector<String>& args, const String& initialDirectory)
  215. {
  216. STARTUPINFOW si = { sizeof(si) };
  217. PROCESS_INFORMATION pi = { 0 };
  218. // CreateProcess wants a single string
  219. String sargs;
  220. sargs.Join(args, " ");
  221. // convert to wide
  222. WString wcommand(command);
  223. // prepend the command and convert to wide
  224. WString wargs("\"" + command + "\" " + sargs);
  225. // The child process inherits the pipe handle.
  226. if (!::CreateProcessW(wcommand.CString(), (LPWSTR) wargs.CString(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  227. return false;
  228. }
  229. pid_ = pi.hProcess;
  230. ::CloseHandle(pi.hThread);
  231. return true;
  232. }
  233. }
  234. #endif