Service.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 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 <sys/time.h>
  37. #include <sys/types.h>
  38. #include <sys/stat.h>
  39. #include <sys/select.h>
  40. #include <sys/wait.h>
  41. #include "Service.hpp"
  42. #include "RuntimeEnvironment.hpp"
  43. #include "Utils.hpp"
  44. #include "Logger.hpp"
  45. namespace ZeroTier {
  46. Service::Service(const RuntimeEnvironment *renv,const char *name,const char *path,void (*handler)(void *,Service &,const Dictionary &),void *arg) :
  47. _r(renv),
  48. _path(path),
  49. _name(name),
  50. _arg(arg),
  51. _handler(handler),
  52. _pid(-1),
  53. _childStdin(0),
  54. _childStdout(0),
  55. _childStderr(0),
  56. _run(true)
  57. {
  58. start();
  59. }
  60. Service::~Service()
  61. {
  62. _run = false;
  63. long pid = _pid;
  64. if (pid > 0) {
  65. int st = 0;
  66. ::kill(pid,SIGTERM);
  67. for(int i=0;i<20;++i) {
  68. if (waitpid(pid,&st,WNOHANG) == pid) {
  69. pid = 0;
  70. break;
  71. }
  72. Thread::sleep(100);
  73. }
  74. if (pid > 0) {
  75. ::kill(pid,SIGKILL);
  76. waitpid(pid,&st,0);
  77. }
  78. }
  79. join();
  80. }
  81. bool Service::send(const Dictionary &msg)
  82. {
  83. if (_childStdin <= 0)
  84. return false;
  85. std::string mser = msg.toString();
  86. if (mser.length() > ZT_SERVICE_MAX_MESSAGE_SIZE)
  87. return false;
  88. // This can technically block. We'll fix this if it ends up being a
  89. // problem.
  90. uint32_t len = Utils::hton((uint32_t)mser.length());
  91. if (write(_childStdin,&len,4) != 4)
  92. return false;
  93. if ((int)write(_childStdin,mser.data(),mser.length()) != (int)mser.length())
  94. return false;
  95. return true;
  96. }
  97. void Service::main()
  98. throw()
  99. {
  100. char buf[4096];
  101. fd_set readfds,writefds,exceptfds;
  102. struct timeval tv;
  103. std::string stderrBuf;
  104. std::string stdoutBuf;
  105. unsigned int stdoutExpecting = 0;
  106. while (_run) {
  107. if (_pid <= 0) {
  108. LOG("launching service %s...",_name.c_str());
  109. int in[2],out[2],err[2];
  110. pipe(in);
  111. pipe(out);
  112. pipe(err);
  113. long pid = fork();
  114. if (pid < 0) {
  115. LOG("service %s terminating: could not fork!",_name.c_str());
  116. return;
  117. } else if (pid) {
  118. close(in[1]);
  119. close(out[0]);
  120. close(err[0]);
  121. Thread::sleep(500); // give child time to start
  122. _childStdin = in[1];
  123. _childStdout = out[0];
  124. _childStderr = err[0];
  125. fcntl(_childStdout,F_SETFL,O_NONBLOCK);
  126. fcntl(_childStderr,F_SETFL,O_NONBLOCK);
  127. } else {
  128. dup2(in[0],STDIN_FILENO);
  129. dup2(out[1],STDOUT_FILENO);
  130. dup2(err[1],STDERR_FILENO);
  131. close(in[1]);
  132. close(out[0]);
  133. close(err[0]);
  134. execl(_path.c_str(),_path.c_str(),_r->homePath.c_str(),(const char *)0);
  135. exit(-1);
  136. }
  137. } else {
  138. int st = 0;
  139. if (waitpid(_pid,&st,WNOHANG) == _pid) {
  140. if (_childStdin > 0) close(_childStdin);
  141. _childStdin = 0;
  142. if (_childStdout > 0) close(_childStdout);
  143. if (_childStderr > 0) close(_childStderr);
  144. _pid = 0;
  145. if (!_run)
  146. return;
  147. LOG("service %s exited with exit code: %d, delaying 1s to attempt relaunch",_name.c_str(),st);
  148. Thread::sleep(1000); // wait to relaunch
  149. continue;
  150. }
  151. }
  152. FD_ZERO(&readfds);
  153. FD_ZERO(&writefds);
  154. FD_ZERO(&exceptfds);
  155. FD_SET(_childStdout,&readfds);
  156. FD_SET(_childStderr,&readfds);
  157. tv.tv_sec = 1;
  158. tv.tv_usec = 0;
  159. select(std::max(_childStdout,_childStderr)+1,&readfds,&writefds,&exceptfds,&tv);
  160. if (!_run) {
  161. if (_childStdin > 0) close(_childStdin);
  162. _childStdin = 0;
  163. if (_childStdout > 0) close(_childStdout);
  164. if (_childStderr > 0) close(_childStderr);
  165. return;
  166. }
  167. if ((_childStderr > 0)&&(FD_ISSET(_childStderr,&readfds))) {
  168. int n = (int)read(_childStderr,buf,sizeof(buf));
  169. for(int i=0;i<n;++i) {
  170. if ((buf[i] == '\r')||(buf[i] == '\n')) {
  171. stderrBuf = Utils::trim(stderrBuf);
  172. if (stderrBuf.length())
  173. LOG("service %s: %s",_name.c_str(),stderrBuf.c_str());
  174. stderrBuf = "";
  175. } else stderrBuf.push_back(buf[i]);
  176. }
  177. }
  178. if ((_childStdout > 0)&&(FD_ISSET(_childStdout,&readfds))) {
  179. int n = (int)read(_childStdout,buf,sizeof(buf));
  180. for(int i=0;i<n;++i) {
  181. stdoutBuf.push_back(buf[i]);
  182. if (stdoutExpecting) {
  183. if (stdoutBuf.length() == stdoutExpecting) {
  184. try {
  185. _handler(_arg,*this,Dictionary(stdoutBuf));
  186. } catch ( ... ) {
  187. LOG("unexpected exception handling message from service %s",_name.c_str());
  188. }
  189. stdoutBuf = "";
  190. stdoutExpecting = 0;
  191. }
  192. } else if (stdoutBuf.length() == 4) {
  193. stdoutExpecting = Utils::ntoh(*((const uint32_t *)stdoutBuf.data()));
  194. stdoutBuf = "";
  195. if (stdoutExpecting > ZT_SERVICE_MAX_MESSAGE_SIZE) {
  196. LOG("message size overrun from service %s: %u bytes -- restarting service",_name.c_str(),stdoutExpecting);
  197. stdoutExpecting = 0;
  198. kill(_pid,SIGKILL);
  199. break;
  200. }
  201. }
  202. }
  203. }
  204. }
  205. }
  206. } // namespace ZeroTier
  207. #endif // __WINDOWS__