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.

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