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.

591 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 readNextLineAsLong(long& value)
  244. {
  245. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  246. if (const char* const msg = readline())
  247. {
  248. value = std::atol(msg);
  249. delete[] msg;
  250. return true;
  251. }
  252. return false;
  253. }
  254. bool readNextLineAsFloat(float& value)
  255. {
  256. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  257. if (const char* const msg = readline())
  258. {
  259. const bool ret(std::sscanf(msg, "%f", &value) == 1);
  260. delete[] msg;
  261. return ret;
  262. }
  263. return false;
  264. }
  265. bool readNextLineAsString(const char*& value)
  266. {
  267. CARLA_SAFE_ASSERT_RETURN(fIsReading, false);
  268. if (const char* const msg = readline())
  269. {
  270. value = msg;
  271. return true;
  272. }
  273. return false;
  274. }
  275. // -------------------------------------------------------------------
  276. void writeMsg(const char* const msg) const noexcept
  277. {
  278. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  279. try {
  280. ::write(fPipeSend, msg, std::strlen(msg));
  281. } catch (...) {}
  282. }
  283. void writeMsg(const char* const msg, size_t size) const noexcept
  284. {
  285. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  286. try {
  287. ::write(fPipeSend, msg, size);
  288. } catch (...) {}
  289. }
  290. void writeAndFixMsg(const char* const msg)
  291. {
  292. CARLA_SAFE_ASSERT_RETURN(fPipeSend != -1,);
  293. const size_t size(msg != nullptr ? std::strlen(msg) : 0);
  294. char fixedMsg[size+2];
  295. if (size > 0)
  296. {
  297. std::strcpy(fixedMsg, msg);
  298. for (size_t i=0; i < size; ++i)
  299. {
  300. if (fixedMsg[i] == '\n')
  301. fixedMsg[i] = '\r';
  302. }
  303. if (fixedMsg[size+1] == '\r')
  304. {
  305. fixedMsg[size-1] = '\n';
  306. fixedMsg[size] = '\0';
  307. fixedMsg[size+1] = '\0';
  308. }
  309. else
  310. {
  311. fixedMsg[size] = '\n';
  312. fixedMsg[size+1] = '\0';
  313. }
  314. }
  315. else
  316. {
  317. fixedMsg[0] = '\n';
  318. fixedMsg[1] = '\0';
  319. }
  320. try {
  321. ::write(fPipeSend, fixedMsg, size+1);
  322. } catch (...) {}
  323. }
  324. void waitChildClose()
  325. {
  326. if (! wait_child(fPid))
  327. {
  328. carla_stderr2("force killing misbehaved child %i (exit)", int(fPid));
  329. if (kill(fPid, SIGKILL) == -1)
  330. carla_stderr2("kill() failed: %s (exit)", strerror(errno));
  331. else
  332. wait_child(fPid);
  333. }
  334. }
  335. // -------------------------------------------------------------------
  336. protected:
  337. virtual void fail(const char* const error)
  338. {
  339. carla_stderr2(error);
  340. }
  341. virtual void msgReceived(const char* const msg) = 0;
  342. // -------------------------------------------------------------------
  343. private:
  344. int fPipeRecv; // the pipe end that is used for receiving messages from UI
  345. int fPipeSend; // the pipe end that is used for sending messages to UI
  346. bool fIsReading;
  347. pid_t fPid;
  348. char fTmpBuf[0xff+1];
  349. CarlaString fTmpStr;
  350. // -------------------------------------------------------------------
  351. const char* readline()
  352. {
  353. char ch;
  354. char* ptr = fTmpBuf;
  355. ssize_t ret;
  356. fTmpStr.clear();
  357. for (int i=0; i < 0xff; ++i)
  358. {
  359. try {
  360. ret = read(fPipeRecv, &ch, 1);
  361. }
  362. catch (...) {
  363. break;
  364. }
  365. if (ret == 1 && ch != '\n')
  366. {
  367. if (ch == '\r')
  368. ch = '\n';
  369. *ptr++ = ch;
  370. if (i+1 == 0xff)
  371. {
  372. i = 0;
  373. ptr = fTmpBuf;
  374. fTmpStr += fTmpBuf;
  375. }
  376. continue;
  377. }
  378. if (fTmpStr.isNotEmpty() || ptr != fTmpBuf)
  379. {
  380. if (ptr != fTmpBuf)
  381. {
  382. *ptr = '\0';
  383. fTmpStr += fTmpBuf;
  384. }
  385. return fTmpStr.dup();
  386. }
  387. break;
  388. }
  389. return nullptr;
  390. }
  391. static bool fork_exec(const char* const argv[5], int* const retp)
  392. {
  393. const pid_t ret = *retp = vfork();
  394. switch (ret)
  395. {
  396. case 0: /* child process */
  397. execlp(argv[0], argv[0], argv[1], argv[2], argv[3], argv[4], nullptr);
  398. carla_stderr2("exec failed: %s", std::strerror(errno));
  399. _exit(0);
  400. return false;
  401. case -1: /* error */
  402. carla_stderr2("fork() failed: %s", std::strerror(errno));
  403. _exit(0);
  404. return false;
  405. }
  406. return true;
  407. }
  408. static bool wait_child(const pid_t pid)
  409. {
  410. if (pid == -1)
  411. {
  412. carla_stderr2("Can't wait for pid -1");
  413. return false;
  414. }
  415. pid_t ret;
  416. for (int i=0, maxTime=WAIT_ZOMBIE_TIMEOUT/WAIT_STEP; i < maxTime; ++i)
  417. {
  418. try {
  419. ret = ::waitpid(pid, nullptr, WNOHANG);
  420. }
  421. catch (...) {
  422. break;
  423. }
  424. if (ret != 0)
  425. {
  426. if (ret == pid)
  427. return true;
  428. if (ret == -1)
  429. {
  430. carla_stderr2("waitpid(%i) failed: %s", int(pid), std::strerror(errno));
  431. return false;
  432. }
  433. carla_stderr2("we waited for child pid %i to exit but we got pid %i instead", int(pid), int(ret));
  434. return false;
  435. }
  436. carla_msleep(WAIT_STEP); /* wait 100 ms */
  437. }
  438. 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);
  439. return false;
  440. }
  441. };
  442. // -----------------------------------------------------------------------
  443. class CarlaPipeClient
  444. {
  445. protected:
  446. CarlaPipeClient()
  447. {
  448. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  449. }
  450. // -------------------------------------------------------------------
  451. public:
  452. virtual ~CarlaPipeClient()
  453. {
  454. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  455. stop();
  456. }
  457. void stop()
  458. {
  459. }
  460. };
  461. // -----------------------------------------------------------------------
  462. #endif // CARLA_PIPE_UTILS_HPP_INCLUDED