Audio plugin host https://kx.studio/carla
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.

558 lines
14KB

  1. /*
  2. * Carla Pipe utils based on lv2fil UI code
  3. * Copyright (C) 2009 Nedko Arnaudov <nedko@arnaudov.name>
  4. * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2 of
  9. * the License, or any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  17. */
  18. #ifndef CARLA_PIPE_UTILS_HPP_INCLUDED
  19. #define CARLA_PIPE_UTILS_HPP_INCLUDED
  20. #include "CarlaUtils.hpp"
  21. #include "CarlaString.hpp"
  22. #include <cerrno>
  23. #include <clocale>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <sys/wait.h>
  27. #define WAIT_START_TIMEOUT 3000 /* ms */
  28. #define WAIT_ZOMBIE_TIMEOUT 3000 /* ms */
  29. #define WAIT_STEP 100 /* ms */
  30. // -----------------------------------------------------------------------
  31. class CarlaPipeServer
  32. {
  33. protected:
  34. CarlaPipeServer()
  35. : fPipeRecv(-1),
  36. fPipeSend(-1),
  37. fPid(-1),
  38. fReading(false)
  39. {
  40. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  41. fTmpBuf[0xff] = '\0';
  42. }
  43. // -------------------------------------------------------------------
  44. public:
  45. virtual ~CarlaPipeServer()
  46. {
  47. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  48. stop();
  49. }
  50. bool start(const char* const filename, const char* const arg1, const char* const arg2)
  51. {
  52. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  53. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  54. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  55. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  56. //----------------------------------------------------------------
  57. const char* argv[5];
  58. //----------------------------------------------------------------
  59. // argv[0] => filename
  60. argv[0] = filename;
  61. //----------------------------------------------------------------
  62. // argv[1-2] => args
  63. argv[1] = arg1;
  64. argv[2] = arg2;
  65. //----------------------------------------------------------------
  66. // argv[3-4] => pipes
  67. int pipe1[2]; // written by host process, read by plugin UI process
  68. int pipe2[2]; // written by plugin UI process, read by host process
  69. if (::pipe(pipe1) != 0)
  70. {
  71. fail("pipe1 creation failed");
  72. return false;
  73. }
  74. if (::pipe(pipe2) != 0)
  75. {
  76. ::close(pipe1[0]);
  77. ::close(pipe1[1]);
  78. fail("pipe2 creation failed");
  79. return false;
  80. }
  81. char uiPipeRecv[100+1];
  82. char uiPipeSend[100+1];
  83. std::snprintf(uiPipeRecv, 100, "%d", pipe1[0]); // [0] means reading end
  84. std::snprintf(uiPipeSend, 100, "%d", pipe2[1]); // [1] means writting end
  85. uiPipeRecv[100] = '\0';
  86. uiPipeSend[100] = '\0';
  87. argv[3] = uiPipeRecv; // reading end
  88. argv[4] = uiPipeSend; // writting end
  89. //----------------------------------------------------------------
  90. // fork
  91. int ret = -1;
  92. if ((! fork_exec(argv, &ret)) || ret == -1)
  93. {
  94. ::close(pipe1[0]);
  95. ::close(pipe1[1]);
  96. ::close(pipe2[0]);
  97. ::close(pipe2[1]);
  98. fail("fork_exec() failed");
  99. return false;
  100. }
  101. fPid = ret;
  102. // fork duplicated the handles, close pipe ends that are used by the child process
  103. ::close(pipe1[0]);
  104. ::close(pipe2[1]);
  105. fPipeSend = pipe1[1]; // [1] means writting end
  106. fPipeRecv = pipe2[0]; // [0] means reading end
  107. // set non-block
  108. try {
  109. ret = fcntl(fPipeRecv, F_SETFL, fcntl(fPipeRecv, F_GETFL) | O_NONBLOCK);
  110. } catch (...) {
  111. ret = -1;
  112. fail("failed to set pipe as non-block");
  113. }
  114. //----------------------------------------------------------------
  115. // wait a while for child process to confirm it is alive
  116. if (ret != -1)
  117. {
  118. char ch;
  119. ssize_t ret2;
  120. for (int i=0; ;)
  121. {
  122. try {
  123. ret2 = ::read(fPipeRecv, &ch, 1);
  124. }
  125. catch (...) {
  126. fail("failed to read from pipe");
  127. break;
  128. }
  129. switch (ret2)
  130. {
  131. case -1:
  132. if (errno == EAGAIN)
  133. {
  134. if (i < WAIT_START_TIMEOUT / WAIT_STEP)
  135. {
  136. carla_msleep(WAIT_STEP);
  137. ++i;
  138. continue;
  139. }
  140. carla_stderr("we have waited for child with pid %d to appear for %.1f seconds and we are giving up", (int)fPid, (float)WAIT_START_TIMEOUT / 1000.0f);
  141. }
  142. else
  143. carla_stderr("read() failed: %s", std::strerror(errno));
  144. break;
  145. case 1:
  146. if (ch == '\n') {
  147. // success
  148. return true;
  149. }
  150. carla_stderr("read() has wrong first char '%c'", ch);
  151. break;
  152. default:
  153. carla_stderr("read() returned %i", int(ret2));
  154. break;
  155. }
  156. break;
  157. }
  158. carla_stderr("force killing misbehaved child %i (start)", int(fPid));
  159. }
  160. if (kill(fPid, SIGKILL) == -1)
  161. {
  162. carla_stderr("kill() failed: %s (start)\n", strerror(errno));
  163. }
  164. // wait a while child to exit, we dont like zombie processes
  165. wait_child(fPid);
  166. // close pipes
  167. try {
  168. ::close(fPipeRecv);
  169. } catch (...) {}
  170. try {
  171. ::close(fPipeSend);
  172. } catch (...) {}
  173. fPipeRecv = -1;
  174. fPipeSend = -1;
  175. fPid = -1;
  176. return false;
  177. }
  178. void stop() noexcept
  179. {
  180. carla_debug("CarlaPipeServer::stop()");
  181. if (fPipeSend == -1 || fPipeRecv == -1 || fPid == -1)
  182. return;
  183. try {
  184. ::write(fPipeSend, "quit\n", 5);
  185. } catch (...) {}
  186. waitChildClose();
  187. try {
  188. ::close(fPipeRecv);
  189. } catch (...) {}
  190. try {
  191. ::close(fPipeSend);
  192. } catch (...) {}
  193. fPipeRecv = -1;
  194. fPipeSend = -1;
  195. fPid = -1;
  196. }
  197. void idle()
  198. {
  199. const char* locale = nullptr;
  200. for (;;)
  201. {
  202. const char* const msg(readline());
  203. if (msg == nullptr)
  204. break;
  205. if (locale == nullptr)
  206. {
  207. locale = carla_strdup(setlocale(LC_NUMERIC, nullptr));
  208. setlocale(LC_NUMERIC, "POSIX");
  209. }
  210. fReading = true;
  211. msgReceived(msg);
  212. fReading = false;
  213. delete[] msg;
  214. }
  215. if (locale != nullptr)
  216. {
  217. setlocale(LC_NUMERIC, locale);
  218. delete[] locale;
  219. }
  220. }
  221. // -------------------------------------------------------------------
  222. bool readNextLineAsBool(bool& value)
  223. {
  224. CARLA_SAFE_ASSERT_RETURN(fReading, false);
  225. if (const char* const msg = readline())
  226. {
  227. value = (std::strcmp(msg, "true") == 0);
  228. delete[] msg;
  229. return true;
  230. }
  231. return false;
  232. }
  233. bool readNextLineAsInt(int& value)
  234. {
  235. CARLA_SAFE_ASSERT_RETURN(fReading, false);
  236. if (const char* const msg = readline())
  237. {
  238. value = std::atoi(msg);
  239. delete[] msg;
  240. return true;
  241. }
  242. return false;
  243. }
  244. bool readNextLineAsFloat(float& value)
  245. {
  246. CARLA_SAFE_ASSERT_RETURN(fReading, false);
  247. if (const char* const msg = readline())
  248. {
  249. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  250. delete[] msg;
  251. return ret;
  252. }
  253. return false;
  254. }
  255. bool readNextLineAsString(const char*& value)
  256. {
  257. CARLA_SAFE_ASSERT_RETURN(fReading, false);
  258. if (const char* const msg = readline())
  259. {
  260. value = msg;
  261. return true;
  262. }
  263. return false;
  264. }
  265. // -------------------------------------------------------------------
  266. void writeMsg(const char* const msg) const noexcept
  267. {
  268. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  269. try {
  270. ::write(fPipeSend, msg, std::strlen(msg));
  271. } catch (...) {}
  272. }
  273. void writeMsg(const char* const msg, size_t size) const noexcept
  274. {
  275. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  276. try {
  277. ::write(fPipeSend, msg, size);
  278. } catch (...) {}
  279. }
  280. void writeAndFixMsg(const char* const msg)
  281. {
  282. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  283. const size_t size(std::strlen(msg));
  284. char fixedMsg[size+1];
  285. std::strcpy(fixedMsg, msg);
  286. for (size_t i=0; i < size; ++i)
  287. {
  288. if (fixedMsg[i] == '\n')
  289. fixedMsg[i] = '\r';
  290. }
  291. fixedMsg[size-1] = '\n';
  292. fixedMsg[size] = '\0';
  293. try {
  294. ::write(fPipeSend, fixedMsg, size);
  295. } catch (...) {}
  296. }
  297. void waitChildClose()
  298. {
  299. if (! wait_child(fPid))
  300. {
  301. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  302. if (kill(fPid, SIGKILL) == -1)
  303. carla_stderr2("kill() failed: %s (exit)", strerror(errno));
  304. else
  305. wait_child(fPid);
  306. }
  307. }
  308. // -------------------------------------------------------------------
  309. protected:
  310. virtual void fail(const char* const error)
  311. {
  312. carla_stderr2(error);
  313. }
  314. virtual void msgReceived(const char* const msg) = 0;
  315. // -------------------------------------------------------------------
  316. private:
  317. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  318. int fPipeSend; // the pipe end that is used for sending messages to UI
  319. pid_t fPid;
  320. bool fReading;
  321. char fTmpBuf[0xff+1];
  322. CarlaString fTmpStr;
  323. // -------------------------------------------------------------------
  324. const char* readline()
  325. {
  326. char ch;
  327. char* ptr = fTmpBuf;
  328. ssize_t ret;
  329. fTmpStr.clear();
  330. for (int i=0; i < 0xff; ++i)
  331. {
  332. try {
  333. ret = read(fPipeRecv, &ch, 1);
  334. }
  335. catch (...) {
  336. break;
  337. }
  338. if (ret == 1 && ch != '\n')
  339. {
  340. if (ch == '\r')
  341. ch = '\n';
  342. *ptr++ = ch;
  343. if (i+1 == 0xff)
  344. {
  345. i = 0;
  346. ptr = fTmpBuf;
  347. fTmpStr += fTmpBuf;
  348. }
  349. continue;
  350. }
  351. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  352. {
  353. if (ptr != fTmpBuf)
  354. {
  355. *ptr = '\0';
  356. fTmpStr += fTmpBuf;
  357. }
  358. return fTmpStr.dup();
  359. }
  360. break;
  361. }
  362. return nullptr;
  363. }
  364. static bool fork_exec(const char* const argv[5], int* const retp) noexcept
  365. {
  366. const pid_t ret = *retp = vfork();
  367. switch (ret)
  368. {
  369. case 0: /* child process */
  370. execlp(argv[0], argv[0], argv[1], argv[2], argv[3], argv[4], nullptr);
  371. carla_stderr2("vfork exec failed: %s", std::strerror(errno));
  372. return false;
  373. case -1: /* error */
  374. carla_stderr2("vfork() failed: %s", std::strerror(errno));
  375. return false;
  376. }
  377. return true;
  378. }
  379. static bool wait_child(const pid_t pid)
  380. {
  381. if (pid == -1)
  382. {
  383. carla_stderr2("Can't wait for pid -1");
  384. return false;
  385. }
  386. pid_t ret;
  387. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  388. {
  389. try {
  390. ret = ::waitpid(pid, nullptr, WNOHANG);
  391. }
  392. catch (...) {
  393. break;
  394. }
  395. if (ret != 0)
  396. {
  397. if (ret == pid)
  398. return true;
  399. if (ret == -1)
  400. {
  401. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  402. return false;
  403. }
  404. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  405. return false;
  406. }
  407. carla_msleep(WAIT_STEP); /* wait 100 ms */
  408. }
  409. carla_stderr2("we waited for child with pid %i to exit for %.1f seconds and we are giving up", int(pid), float(WAIT_START_TIMEOUT)/1000.0f);
  410. return false;
  411. }
  412. };
  413. // -----------------------------------------------------------------------
  414. class CarlaPipeClient
  415. {
  416. protected:
  417. CarlaPipeClient()
  418. {
  419. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  420. }
  421. // -------------------------------------------------------------------
  422. public:
  423. virtual ~CarlaPipeClient()
  424. {
  425. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  426. stop();
  427. }
  428. void stop()
  429. {
  430. }
  431. };
  432. // -----------------------------------------------------------------------
  433. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED