The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
10KB

  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. struct InterprocessConnection::ConnectionThread : public Thread
  18. {
  19. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  20. void run() override { owner.runThread(); }
  21. private:
  22. InterprocessConnection& owner;
  23. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  24. };
  25. //==============================================================================
  26. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27. const uint32 magicMessageHeaderNumber)
  28. : callbackConnectionState (false),
  29. useMessageThread (callbacksOnMessageThread),
  30. magicMessageHeader (magicMessageHeaderNumber),
  31. pipeReceiveMessageTimeout (-1)
  32. {
  33. thread = new ConnectionThread (*this);
  34. }
  35. InterprocessConnection::~InterprocessConnection()
  36. {
  37. callbackConnectionState = false;
  38. disconnect();
  39. masterReference.clear();
  40. thread = nullptr;
  41. }
  42. //==============================================================================
  43. bool InterprocessConnection::connectToSocket (const String& hostName,
  44. const int portNumber,
  45. const int timeOutMillisecs)
  46. {
  47. disconnect();
  48. const ScopedLock sl (pipeAndSocketLock);
  49. socket = new StreamingSocket();
  50. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  51. {
  52. connectionMadeInt();
  53. thread->startThread();
  54. return true;
  55. }
  56. socket = nullptr;
  57. return false;
  58. }
  59. bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
  60. {
  61. disconnect();
  62. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  63. if (newPipe->openExisting (pipeName))
  64. {
  65. const ScopedLock sl (pipeAndSocketLock);
  66. pipeReceiveMessageTimeout = timeoutMs;
  67. initialiseWithPipe (newPipe.release());
  68. return true;
  69. }
  70. return false;
  71. }
  72. bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs, bool mustNotExist)
  73. {
  74. disconnect();
  75. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  76. if (newPipe->createNewPipe (pipeName, mustNotExist))
  77. {
  78. const ScopedLock sl (pipeAndSocketLock);
  79. pipeReceiveMessageTimeout = timeoutMs;
  80. initialiseWithPipe (newPipe.release());
  81. return true;
  82. }
  83. return false;
  84. }
  85. void InterprocessConnection::disconnect()
  86. {
  87. thread->signalThreadShouldExit();
  88. {
  89. const ScopedLock sl (pipeAndSocketLock);
  90. if (socket != nullptr) socket->close();
  91. if (pipe != nullptr) pipe->close();
  92. }
  93. thread->stopThread (4000);
  94. deletePipeAndSocket();
  95. connectionLostInt();
  96. }
  97. void InterprocessConnection::deletePipeAndSocket()
  98. {
  99. const ScopedLock sl (pipeAndSocketLock);
  100. socket = nullptr;
  101. pipe = nullptr;
  102. }
  103. bool InterprocessConnection::isConnected() const
  104. {
  105. const ScopedLock sl (pipeAndSocketLock);
  106. return ((socket != nullptr && socket->isConnected())
  107. || (pipe != nullptr && pipe->isOpen()))
  108. && thread->isThreadRunning();
  109. }
  110. String InterprocessConnection::getConnectedHostName() const
  111. {
  112. {
  113. const ScopedLock sl (pipeAndSocketLock);
  114. if (pipe == nullptr && socket == nullptr)
  115. return {};
  116. if (socket != nullptr && ! socket->isLocal())
  117. return socket->getHostName();
  118. }
  119. return IPAddress::local().toString();
  120. }
  121. //==============================================================================
  122. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  123. {
  124. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  125. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  126. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  127. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  128. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  129. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  130. }
  131. int InterprocessConnection::writeData (void* data, int dataSize)
  132. {
  133. const ScopedLock sl (pipeAndSocketLock);
  134. if (socket != nullptr)
  135. return socket->write (data, dataSize);
  136. if (pipe != nullptr)
  137. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  138. return 0;
  139. }
  140. //==============================================================================
  141. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  142. {
  143. jassert (socket == nullptr && pipe == nullptr);
  144. socket = newSocket;
  145. connectionMadeInt();
  146. thread->startThread();
  147. }
  148. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  149. {
  150. jassert (socket == nullptr && pipe == nullptr);
  151. pipe = newPipe;
  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 (InterprocessConnection* const ipc = owner)
  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 (InterprocessConnection* const ipc = owner)
  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. bool InterprocessConnection::readNextMessageInt()
  220. {
  221. uint32 messageHeader[2];
  222. const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
  223. : pipe ->read (messageHeader, sizeof (messageHeader), -1);
  224. if (bytes == sizeof (messageHeader)
  225. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  226. {
  227. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  228. if (bytesInMessage > 0)
  229. {
  230. MemoryBlock messageData ((size_t) bytesInMessage, true);
  231. int bytesRead = 0;
  232. while (bytesInMessage > 0)
  233. {
  234. if (thread->threadShouldExit())
  235. return false;
  236. const int numThisTime = jmin (bytesInMessage, 65536);
  237. void* const data = addBytesToPointer (messageData.getData(), bytesRead);
  238. const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
  239. : pipe ->read (data, numThisTime, -1);
  240. if (bytesIn <= 0)
  241. break;
  242. bytesRead += bytesIn;
  243. bytesInMessage -= bytesIn;
  244. }
  245. if (bytesRead >= 0)
  246. deliverDataInt (messageData);
  247. }
  248. }
  249. else if (bytes < 0)
  250. {
  251. if (socket != nullptr)
  252. deletePipeAndSocket();
  253. connectionLostInt();
  254. return false;
  255. }
  256. return true;
  257. }
  258. void InterprocessConnection::runThread()
  259. {
  260. while (! thread->threadShouldExit())
  261. {
  262. if (socket != nullptr)
  263. {
  264. const int ready = socket->waitUntilReady (true, 0);
  265. if (ready < 0)
  266. {
  267. deletePipeAndSocket();
  268. connectionLostInt();
  269. break;
  270. }
  271. if (ready == 0)
  272. {
  273. thread->wait (1);
  274. continue;
  275. }
  276. }
  277. else if (pipe != nullptr)
  278. {
  279. if (! pipe->isOpen())
  280. {
  281. deletePipeAndSocket();
  282. connectionLostInt();
  283. break;
  284. }
  285. }
  286. else
  287. {
  288. break;
  289. }
  290. if (thread->threadShouldExit() || ! readNextMessageInt())
  291. break;
  292. }
  293. }