Service.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "Constants.hpp"
  28. #ifndef __WINDOWS__
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <unistd.h>
  32. #include <string.h>
  33. #include <signal.h>
  34. #include <time.h>
  35. #include <fcntl.h>
  36. #include <errno.h>
  37. #include <sys/time.h>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #include <sys/select.h>
  41. #include <sys/wait.h>
  42. #include "Service.hpp"
  43. #include "RuntimeEnvironment.hpp"
  44. #include "Utils.hpp"
  45. #include "Logger.hpp"
  46. namespace ZeroTier {
  47. Service::Service(const RuntimeEnvironment *renv,const char *name,const char *path,void (*handler)(void *,Service &,const Dictionary &),void *arg) :
  48. _r(renv),
  49. _path(path),
  50. _name(name),
  51. _arg(arg),
  52. _handler(handler),
  53. _pid(-1),
  54. _childStdin(0),
  55. _childStdout(0),
  56. _childStderr(0),
  57. _run(true)
  58. {
  59. _thread = Thread::start(this);
  60. }
  61. Service::~Service()
  62. {
  63. _run = false;
  64. long pid = _pid;
  65. if (pid > 0) {
  66. int st = 0;
  67. ::kill(pid,SIGTERM);
  68. for(int i=0;i<20;++i) {
  69. if (waitpid(pid,&st,WNOHANG) == pid) {
  70. pid = 0;
  71. break;
  72. }
  73. Thread::sleep(100);
  74. }
  75. if (pid > 0) {
  76. ::kill(pid,SIGKILL);
  77. waitpid(pid,&st,0);
  78. }
  79. }
  80. Thread::join(_thread);
  81. }
  82. bool Service::send(const Dictionary &msg)
  83. {
  84. if (_childStdin <= 0)
  85. return false;
  86. std::string mser = msg.toString();
  87. if (mser.length() > ZT_SERVICE_MAX_MESSAGE_SIZE)
  88. return false;
  89. // This can technically block. We'll fix this if it ends up being a
  90. // problem.
  91. uint32_t len = Utils::hton((uint32_t)mser.length());
  92. if (write(_childStdin,&len,4) != 4)
  93. return false;
  94. if ((int)write(_childStdin,mser.data(),mser.length()) != (int)mser.length())
  95. return false;
  96. return true;
  97. }
  98. void Service::threadMain()
  99. throw()
  100. {
  101. char buf[131072];
  102. fd_set readfds,writefds,exceptfds;
  103. struct timeval tv;
  104. std::string stderrBuf;
  105. std::string stdoutBuf;
  106. unsigned int stdoutExpecting = 0;
  107. while (_run) {
  108. if (_pid <= 0) {
  109. LOG("launching service %s...",_name.c_str());
  110. int in[2],out[2],err[2];
  111. pipe(in);
  112. pipe(out);
  113. pipe(err);
  114. long pid = vfork();
  115. if (pid < 0) {
  116. LOG("service %s terminating: could not fork!",_name.c_str());
  117. return;
  118. } else if (pid) {
  119. // Parent
  120. close(in[0]);
  121. close(out[1]);
  122. close(err[1]);
  123. Thread::sleep(500); // give child time to start
  124. _childStdin = in[1];
  125. _childStdout = out[0];
  126. _childStderr = err[0];
  127. fcntl(_childStdout,F_SETFL,O_NONBLOCK);
  128. fcntl(_childStderr,F_SETFL,O_NONBLOCK);
  129. _pid = pid;
  130. } else {
  131. // Child
  132. close(in[1]);
  133. close(out[0]);
  134. close(err[0]);
  135. dup2(in[0],STDIN_FILENO);
  136. dup2(out[1],STDOUT_FILENO);
  137. dup2(err[1],STDERR_FILENO);
  138. execl(_path.c_str(),_path.c_str(),_r->homePath.c_str(),(const char *)0);
  139. exit(-1);
  140. }
  141. } else {
  142. int st = 0;
  143. if (waitpid(_pid,&st,WNOHANG) == _pid) {
  144. if (_childStdin > 0) close(_childStdin);
  145. _childStdin = 0;
  146. if (_childStdout > 0) close(_childStdout);
  147. if (_childStderr > 0) close(_childStderr);
  148. _pid = 0;
  149. if (!_run)
  150. return;
  151. LOG("service %s exited with exit code: %d, delaying 1s to attempt relaunch",_name.c_str(),st);
  152. Thread::sleep(1000); // wait to relaunch
  153. continue;
  154. }
  155. }
  156. // If we've made it here, _pid is running last we checked.
  157. FD_ZERO(&readfds);
  158. FD_ZERO(&writefds);
  159. FD_ZERO(&exceptfds);
  160. FD_SET(_childStdout,&readfds);
  161. FD_SET(_childStderr,&readfds);
  162. tv.tv_sec = 1;
  163. tv.tv_usec = 0;
  164. select(std::max(_childStdout,_childStderr)+1,&readfds,&writefds,&exceptfds,&tv);
  165. if (!_run) {
  166. if (_childStdin > 0) close(_childStdin);
  167. _childStdin = 0;
  168. if (_childStdout > 0) close(_childStdout);
  169. if (_childStderr > 0) close(_childStderr);
  170. return;
  171. }
  172. if ((_childStderr > 0)&&(FD_ISSET(_childStderr,&readfds))) {
  173. int n = (int)read(_childStderr,buf,sizeof(buf));
  174. for(int i=0;i<n;++i) {
  175. if ((buf[i] == '\r')||(buf[i] == '\n')) {
  176. stderrBuf = Utils::trim(stderrBuf);
  177. if (stderrBuf.length())
  178. LOG("service %s: %s",_name.c_str(),stderrBuf.c_str());
  179. stderrBuf = "";
  180. } else stderrBuf.push_back(buf[i]);
  181. }
  182. }
  183. if ((_childStdout > 0)&&(FD_ISSET(_childStdout,&readfds))) {
  184. int n = (int)read(_childStdout,buf,sizeof(buf));
  185. for(int i=0;i<n;++i) {
  186. stdoutBuf.push_back(buf[i]);
  187. if (stdoutExpecting) {
  188. if (stdoutBuf.length() == stdoutExpecting) {
  189. try {
  190. _handler(_arg,*this,Dictionary(stdoutBuf));
  191. } catch ( ... ) {
  192. LOG("unexpected exception handling message from service %s",_name.c_str());
  193. }
  194. stdoutBuf = "";
  195. stdoutExpecting = 0;
  196. }
  197. } else if (stdoutBuf.length() == 4) {
  198. stdoutExpecting = Utils::ntoh(*((const uint32_t *)stdoutBuf.data()));
  199. stdoutBuf = "";
  200. if (stdoutExpecting > ZT_SERVICE_MAX_MESSAGE_SIZE) {
  201. LOG("message size overrun from service %s: %u bytes -- restarting service",_name.c_str(),stdoutExpecting);
  202. stdoutExpecting = 0;
  203. kill(_pid,SIGKILL);
  204. break;
  205. }
  206. }
  207. }
  208. }
  209. }
  210. }
  211. } // namespace ZeroTier
  212. #endif // __WINDOWS__