juce_InterprocessConnection.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. struct InterprocessConnection::ConnectionThread : public Thread
  20. {
  21. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  22. void run() override { owner.runThread(); }
  23. InterprocessConnection& owner;
  24. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  25. };
  26. //==============================================================================
  27. InterprocessConnection::InterprocessConnection (bool callbacksOnMessageThread, uint32 magicMessageHeaderNumber)
  28. : useMessageThread (callbacksOnMessageThread),
  29. magicMessageHeader (magicMessageHeaderNumber)
  30. {
  31. thread.reset (new ConnectionThread (*this));
  32. }
  33. InterprocessConnection::~InterprocessConnection()
  34. {
  35. callbackConnectionState = false;
  36. disconnect();
  37. masterReference.clear();
  38. thread.reset();
  39. }
  40. //==============================================================================
  41. bool InterprocessConnection::connectToSocket (const String& hostName,
  42. int portNumber, int timeOutMillisecs)
  43. {
  44. disconnect();
  45. const ScopedLock sl (pipeAndSocketLock);
  46. socket.reset (new StreamingSocket());
  47. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  48. {
  49. threadIsRunning = true;
  50. connectionMadeInt();
  51. thread->startThread();
  52. return true;
  53. }
  54. socket.reset();
  55. return false;
  56. }
  57. bool InterprocessConnection::connectToPipe (const String& pipeName, int timeoutMs)
  58. {
  59. disconnect();
  60. std::unique_ptr<NamedPipe> newPipe (new NamedPipe());
  61. if (newPipe->openExisting (pipeName))
  62. {
  63. const ScopedLock sl (pipeAndSocketLock);
  64. pipeReceiveMessageTimeout = timeoutMs;
  65. initialiseWithPipe (newPipe.release());
  66. return true;
  67. }
  68. return false;
  69. }
  70. bool InterprocessConnection::createPipe (const String& pipeName, int timeoutMs, bool mustNotExist)
  71. {
  72. disconnect();
  73. std::unique_ptr<NamedPipe> newPipe (new NamedPipe());
  74. if (newPipe->createNewPipe (pipeName, mustNotExist))
  75. {
  76. const ScopedLock sl (pipeAndSocketLock);
  77. pipeReceiveMessageTimeout = timeoutMs;
  78. initialiseWithPipe (newPipe.release());
  79. return true;
  80. }
  81. return false;
  82. }
  83. void InterprocessConnection::disconnect()
  84. {
  85. thread->signalThreadShouldExit();
  86. {
  87. const ScopedLock sl (pipeAndSocketLock);
  88. if (socket != nullptr) socket->close();
  89. if (pipe != nullptr) pipe->close();
  90. }
  91. thread->stopThread (4000);
  92. deletePipeAndSocket();
  93. connectionLostInt();
  94. }
  95. void InterprocessConnection::deletePipeAndSocket()
  96. {
  97. const ScopedLock sl (pipeAndSocketLock);
  98. socket.reset();
  99. pipe.reset();
  100. }
  101. bool InterprocessConnection::isConnected() const
  102. {
  103. const ScopedLock sl (pipeAndSocketLock);
  104. return ((socket != nullptr && socket->isConnected())
  105. || (pipe != nullptr && pipe->isOpen()))
  106. && threadIsRunning;
  107. }
  108. String InterprocessConnection::getConnectedHostName() const
  109. {
  110. {
  111. const ScopedLock sl (pipeAndSocketLock);
  112. if (pipe == nullptr && socket == nullptr)
  113. return {};
  114. if (socket != nullptr && ! socket->isLocal())
  115. return socket->getHostName();
  116. }
  117. return IPAddress::local().toString();
  118. }
  119. //==============================================================================
  120. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  121. {
  122. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  123. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  124. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  125. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  126. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  127. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  128. }
  129. int InterprocessConnection::writeData (void* data, int dataSize)
  130. {
  131. const ScopedLock sl (pipeAndSocketLock);
  132. if (socket != nullptr)
  133. return socket->write (data, dataSize);
  134. if (pipe != nullptr)
  135. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  136. return 0;
  137. }
  138. //==============================================================================
  139. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  140. {
  141. jassert (socket == nullptr && pipe == nullptr);
  142. socket.reset (newSocket);
  143. threadIsRunning = true;
  144. connectionMadeInt();
  145. thread->startThread();
  146. }
  147. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  148. {
  149. jassert (socket == nullptr && pipe == nullptr);
  150. pipe.reset (newPipe);
  151. threadIsRunning = true;
  152. connectionMadeInt();
  153. thread->startThread();
  154. }
  155. //==============================================================================
  156. struct ConnectionStateMessage : public MessageManager::MessageBase
  157. {
  158. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  159. : owner (ipc), connectionMade (connected)
  160. {}
  161. void messageCallback() override
  162. {
  163. if (auto* ipc = owner.get())
  164. {
  165. if (connectionMade)
  166. ipc->connectionMade();
  167. else
  168. ipc->connectionLost();
  169. }
  170. }
  171. WeakReference<InterprocessConnection> owner;
  172. bool connectionMade;
  173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  174. };
  175. void InterprocessConnection::connectionMadeInt()
  176. {
  177. if (! callbackConnectionState)
  178. {
  179. callbackConnectionState = true;
  180. if (useMessageThread)
  181. (new ConnectionStateMessage (this, true))->post();
  182. else
  183. connectionMade();
  184. }
  185. }
  186. void InterprocessConnection::connectionLostInt()
  187. {
  188. if (callbackConnectionState)
  189. {
  190. callbackConnectionState = false;
  191. if (useMessageThread)
  192. (new ConnectionStateMessage (this, false))->post();
  193. else
  194. connectionLost();
  195. }
  196. }
  197. struct DataDeliveryMessage : public Message
  198. {
  199. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  200. : owner (ipc), data (d)
  201. {}
  202. void messageCallback() override
  203. {
  204. if (auto* ipc = owner.get())
  205. ipc->messageReceived (data);
  206. }
  207. WeakReference<InterprocessConnection> owner;
  208. MemoryBlock data;
  209. };
  210. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  211. {
  212. jassert (callbackConnectionState);
  213. if (useMessageThread)
  214. (new DataDeliveryMessage (this, data))->post();
  215. else
  216. messageReceived (data);
  217. }
  218. //==============================================================================
  219. int InterprocessConnection::readData (void* data, int num)
  220. {
  221. if (socket != nullptr)
  222. return socket->read (data, num, true);
  223. if (pipe != nullptr)
  224. return pipe->read (data, num, pipeReceiveMessageTimeout);
  225. jassertfalse;
  226. return -1;
  227. }
  228. bool InterprocessConnection::readNextMessage()
  229. {
  230. uint32 messageHeader[2];
  231. auto bytes = readData (messageHeader, sizeof (messageHeader));
  232. if (bytes == (int) sizeof (messageHeader)
  233. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  234. {
  235. auto bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  236. if (bytesInMessage > 0)
  237. {
  238. MemoryBlock messageData ((size_t) bytesInMessage, true);
  239. int bytesRead = 0;
  240. while (bytesInMessage > 0)
  241. {
  242. if (thread->threadShouldExit())
  243. return false;
  244. auto numThisTime = jmin (bytesInMessage, 65536);
  245. auto bytesIn = readData (addBytesToPointer (messageData.getData(), bytesRead), numThisTime);
  246. if (bytesIn <= 0)
  247. break;
  248. bytesRead += bytesIn;
  249. bytesInMessage -= bytesIn;
  250. }
  251. if (bytesRead >= 0)
  252. deliverDataInt (messageData);
  253. }
  254. return true;
  255. }
  256. if (bytes < 0)
  257. {
  258. if (socket != nullptr)
  259. deletePipeAndSocket();
  260. connectionLostInt();
  261. }
  262. return false;
  263. }
  264. void InterprocessConnection::runThread()
  265. {
  266. while (! thread->threadShouldExit())
  267. {
  268. if (socket != nullptr)
  269. {
  270. auto ready = socket->waitUntilReady (true, 100);
  271. if (ready < 0)
  272. {
  273. deletePipeAndSocket();
  274. connectionLostInt();
  275. break;
  276. }
  277. if (ready == 0)
  278. {
  279. thread->wait (1);
  280. continue;
  281. }
  282. }
  283. else if (pipe != nullptr)
  284. {
  285. if (! pipe->isOpen())
  286. {
  287. deletePipeAndSocket();
  288. connectionLostInt();
  289. break;
  290. }
  291. }
  292. else
  293. {
  294. break;
  295. }
  296. if (thread->threadShouldExit() || ! readNextMessage())
  297. break;
  298. }
  299. threadIsRunning = false;
  300. }
  301. } // namespace juce