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.

369 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. 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. private:
  24. InterprocessConnection& owner;
  25. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  26. };
  27. //==============================================================================
  28. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29. const uint32 magicMessageHeaderNumber)
  30. : callbackConnectionState (false),
  31. useMessageThread (callbacksOnMessageThread),
  32. magicMessageHeader (magicMessageHeaderNumber),
  33. pipeReceiveMessageTimeout (-1)
  34. {
  35. thread = new ConnectionThread (*this);
  36. }
  37. InterprocessConnection::~InterprocessConnection()
  38. {
  39. callbackConnectionState = false;
  40. disconnect();
  41. masterReference.clear();
  42. thread = nullptr;
  43. }
  44. //==============================================================================
  45. bool InterprocessConnection::connectToSocket (const String& hostName,
  46. const int portNumber,
  47. const int timeOutMillisecs)
  48. {
  49. disconnect();
  50. const ScopedLock sl (pipeAndSocketLock);
  51. socket = new StreamingSocket();
  52. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  53. {
  54. connectionMadeInt();
  55. thread->startThread();
  56. return true;
  57. }
  58. socket = nullptr;
  59. return false;
  60. }
  61. bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
  62. {
  63. disconnect();
  64. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  65. if (newPipe->openExisting (pipeName))
  66. {
  67. const ScopedLock sl (pipeAndSocketLock);
  68. pipeReceiveMessageTimeout = timeoutMs;
  69. initialiseWithPipe (newPipe.release());
  70. return true;
  71. }
  72. return false;
  73. }
  74. bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs, bool mustNotExist)
  75. {
  76. disconnect();
  77. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  78. if (newPipe->createNewPipe (pipeName, mustNotExist))
  79. {
  80. const ScopedLock sl (pipeAndSocketLock);
  81. pipeReceiveMessageTimeout = timeoutMs;
  82. initialiseWithPipe (newPipe.release());
  83. return true;
  84. }
  85. return false;
  86. }
  87. void InterprocessConnection::disconnect()
  88. {
  89. thread->signalThreadShouldExit();
  90. {
  91. const ScopedLock sl (pipeAndSocketLock);
  92. if (socket != nullptr) socket->close();
  93. if (pipe != nullptr) pipe->close();
  94. }
  95. thread->stopThread (4000);
  96. deletePipeAndSocket();
  97. connectionLostInt();
  98. }
  99. void InterprocessConnection::deletePipeAndSocket()
  100. {
  101. const ScopedLock sl (pipeAndSocketLock);
  102. socket = nullptr;
  103. pipe = nullptr;
  104. }
  105. bool InterprocessConnection::isConnected() const
  106. {
  107. const ScopedLock sl (pipeAndSocketLock);
  108. return ((socket != nullptr && socket->isConnected())
  109. || (pipe != nullptr && pipe->isOpen()))
  110. && thread->isThreadRunning();
  111. }
  112. String InterprocessConnection::getConnectedHostName() const
  113. {
  114. {
  115. const ScopedLock sl (pipeAndSocketLock);
  116. if (pipe == nullptr && socket == nullptr)
  117. return {};
  118. if (socket != nullptr && ! socket->isLocal())
  119. return socket->getHostName();
  120. }
  121. return IPAddress::local().toString();
  122. }
  123. //==============================================================================
  124. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  125. {
  126. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  127. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  128. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  129. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  130. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  131. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  132. }
  133. int InterprocessConnection::writeData (void* data, int dataSize)
  134. {
  135. const ScopedLock sl (pipeAndSocketLock);
  136. if (socket != nullptr)
  137. return socket->write (data, dataSize);
  138. if (pipe != nullptr)
  139. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  140. return 0;
  141. }
  142. //==============================================================================
  143. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  144. {
  145. jassert (socket == nullptr && pipe == nullptr);
  146. socket = newSocket;
  147. connectionMadeInt();
  148. thread->startThread();
  149. }
  150. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  151. {
  152. jassert (socket == nullptr && pipe == nullptr);
  153. pipe = newPipe;
  154. connectionMadeInt();
  155. thread->startThread();
  156. }
  157. //==============================================================================
  158. struct ConnectionStateMessage : public MessageManager::MessageBase
  159. {
  160. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  161. : owner (ipc), connectionMade (connected)
  162. {}
  163. void messageCallback() override
  164. {
  165. if (InterprocessConnection* const ipc = owner)
  166. {
  167. if (connectionMade)
  168. ipc->connectionMade();
  169. else
  170. ipc->connectionLost();
  171. }
  172. }
  173. WeakReference<InterprocessConnection> owner;
  174. bool connectionMade;
  175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  176. };
  177. void InterprocessConnection::connectionMadeInt()
  178. {
  179. if (! callbackConnectionState)
  180. {
  181. callbackConnectionState = true;
  182. if (useMessageThread)
  183. (new ConnectionStateMessage (this, true))->post();
  184. else
  185. connectionMade();
  186. }
  187. }
  188. void InterprocessConnection::connectionLostInt()
  189. {
  190. if (callbackConnectionState)
  191. {
  192. callbackConnectionState = false;
  193. if (useMessageThread)
  194. (new ConnectionStateMessage (this, false))->post();
  195. else
  196. connectionLost();
  197. }
  198. }
  199. struct DataDeliveryMessage : public Message
  200. {
  201. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  202. : owner (ipc), data (d)
  203. {}
  204. void messageCallback() override
  205. {
  206. if (InterprocessConnection* const ipc = owner)
  207. ipc->messageReceived (data);
  208. }
  209. WeakReference<InterprocessConnection> owner;
  210. MemoryBlock data;
  211. };
  212. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  213. {
  214. jassert (callbackConnectionState);
  215. if (useMessageThread)
  216. (new DataDeliveryMessage (this, data))->post();
  217. else
  218. messageReceived (data);
  219. }
  220. //==============================================================================
  221. bool InterprocessConnection::readNextMessageInt()
  222. {
  223. uint32 messageHeader[2];
  224. const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
  225. : pipe ->read (messageHeader, sizeof (messageHeader), -1);
  226. if (bytes == sizeof (messageHeader)
  227. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  228. {
  229. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  230. if (bytesInMessage > 0)
  231. {
  232. MemoryBlock messageData ((size_t) bytesInMessage, true);
  233. int bytesRead = 0;
  234. while (bytesInMessage > 0)
  235. {
  236. if (thread->threadShouldExit())
  237. return false;
  238. const int numThisTime = jmin (bytesInMessage, 65536);
  239. void* const data = addBytesToPointer (messageData.getData(), bytesRead);
  240. const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
  241. : pipe ->read (data, numThisTime, -1);
  242. if (bytesIn <= 0)
  243. break;
  244. bytesRead += bytesIn;
  245. bytesInMessage -= bytesIn;
  246. }
  247. if (bytesRead >= 0)
  248. deliverDataInt (messageData);
  249. }
  250. }
  251. else if (bytes < 0)
  252. {
  253. if (socket != nullptr)
  254. deletePipeAndSocket();
  255. connectionLostInt();
  256. return false;
  257. }
  258. return true;
  259. }
  260. void InterprocessConnection::runThread()
  261. {
  262. while (! thread->threadShouldExit())
  263. {
  264. if (socket != nullptr)
  265. {
  266. const int ready = socket->waitUntilReady (true, 0);
  267. if (ready < 0)
  268. {
  269. deletePipeAndSocket();
  270. connectionLostInt();
  271. break;
  272. }
  273. if (ready == 0)
  274. {
  275. thread->wait (1);
  276. continue;
  277. }
  278. }
  279. else if (pipe != nullptr)
  280. {
  281. if (! pipe->isOpen())
  282. {
  283. deletePipeAndSocket();
  284. connectionLostInt();
  285. break;
  286. }
  287. }
  288. else
  289. {
  290. break;
  291. }
  292. if (thread->threadShouldExit() || ! readNextMessageInt())
  293. break;
  294. }
  295. }
  296. } // namespace juce