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.

596 lines
15KB

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