Service.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 "Constants.hpp"
  43. #include "Service.hpp"
  44. #include "RuntimeEnvironment.hpp"
  45. #include "Utils.hpp"
  46. #include "Logger.hpp"
  47. namespace ZeroTier {
  48. Service::Service(const RuntimeEnvironment *renv,const char *name,const char *path,void (*handler)(void *,Service &,const Dictionary &),void *arg) :
  49. _r(renv),
  50. _path(path),
  51. _name(name),
  52. _arg(arg),
  53. _handler(handler),
  54. _pid(-1),
  55. _childStdin(0),
  56. _childStdout(0),
  57. _childStderr(0),
  58. _run(true)
  59. {
  60. _thread = Thread::start(this);
  61. }
  62. Service::~Service()
  63. {
  64. _run = false;
  65. long pid = _pid;
  66. if (pid > 0) {
  67. int st = 0;
  68. ::kill(pid,SIGTERM);
  69. for(int i=0;i<20;++i) {
  70. if (waitpid(pid,&st,WNOHANG) == pid) {
  71. pid = 0;
  72. break;
  73. }
  74. Thread::sleep(100);
  75. }
  76. if (pid > 0) {
  77. ::kill(pid,SIGKILL);
  78. waitpid(pid,&st,0);
  79. }
  80. }
  81. Thread::join(_thread);
  82. }
  83. bool Service::send(const Dictionary &msg)
  84. {
  85. if (_childStdin <= 0)
  86. return false;
  87. std::string mser(msg.toString());
  88. mser.append(ZT_EOL_S);
  89. return ((long)::write(_childStdin,mser.data(),mser.length()) == (long)mser.length());
  90. }
  91. void Service::threadMain()
  92. throw()
  93. {
  94. char buf[16384];
  95. fd_set readfds,writefds,exceptfds;
  96. struct timeval tv;
  97. int eolsInARow = 0;
  98. std::string stderrBuf,stdoutBuf;
  99. while (_run) {
  100. if (_pid <= 0) {
  101. LOG("launching service %s...",_name.c_str());
  102. int in[2],out[2],err[2];
  103. pipe(in);
  104. pipe(out);
  105. pipe(err);
  106. long pid = vfork();
  107. if (pid < 0) {
  108. LOG("service %s terminating: could not fork!",_name.c_str());
  109. return;
  110. } else if (pid) {
  111. // Parent
  112. close(in[0]);
  113. close(out[1]);
  114. close(err[1]);
  115. Thread::sleep(500); // give child time to start
  116. _childStdin = in[1];
  117. _childStdout = out[0];
  118. _childStderr = err[0];
  119. fcntl(_childStdout,F_SETFL,O_NONBLOCK);
  120. fcntl(_childStderr,F_SETFL,O_NONBLOCK);
  121. _pid = pid;
  122. } else {
  123. // Child
  124. close(in[1]);
  125. close(out[0]);
  126. close(err[0]);
  127. dup2(in[0],STDIN_FILENO);
  128. dup2(out[1],STDOUT_FILENO);
  129. dup2(err[1],STDERR_FILENO);
  130. setenv("ZT_HOME",RR->homePath.c_str(),1);
  131. chdir(RR->homePath.c_str());
  132. execl(_path.c_str(),_path.c_str(),RR->homePath.c_str(),(const char *)0);
  133. exit(-1);
  134. }
  135. } else {
  136. int st = 0;
  137. if (waitpid(_pid,&st,WNOHANG) == _pid) {
  138. if (_childStdin > 0) close(_childStdin);
  139. _childStdin = 0;
  140. if (_childStdout > 0) close(_childStdout);
  141. if (_childStderr > 0) close(_childStderr);
  142. _pid = 0;
  143. if (!_run)
  144. return;
  145. LOG("service %s exited with exit code: %d, delaying 1s to attempt relaunch",_name.c_str(),st);
  146. Thread::sleep(1000); // wait to relaunch
  147. continue;
  148. }
  149. }
  150. // If we've made it here, _pid is running last we checked.
  151. FD_ZERO(&readfds);
  152. FD_ZERO(&writefds);
  153. FD_ZERO(&exceptfds);
  154. FD_SET(_childStdout,&readfds);
  155. FD_SET(_childStderr,&readfds);
  156. tv.tv_sec = 1;
  157. tv.tv_usec = 0;
  158. ::select(std::max(_childStdout,_childStderr)+1,&readfds,&writefds,&exceptfds,&tv);
  159. if (!_run) {
  160. if (_childStdin > 0) ::close(_childStdin);
  161. _childStdin = 0;
  162. if (_childStdout > 0) ::close(_childStdout);
  163. if (_childStderr > 0) ::close(_childStderr);
  164. return;
  165. }
  166. if ((_childStderr > 0)&&(FD_ISSET(_childStderr,&readfds))) {
  167. int n = (int)::read(_childStderr,buf,sizeof(buf));
  168. for(int i=0;i<n;++i) {
  169. if ((buf[i] == '\r')||(buf[i] == '\n')) {
  170. stderrBuf = Utils::trim(stderrBuf);
  171. if (stderrBuf.length())
  172. LOG("service %s: %s",_name.c_str(),stderrBuf.c_str());
  173. stderrBuf = "";
  174. } else stderrBuf.push_back(buf[i]);
  175. }
  176. }
  177. if ((_childStdout > 0)&&(FD_ISSET(_childStdout,&readfds))) {
  178. int n = (int)::read(_childStdout,buf,sizeof(buf));
  179. for(int i=0;i<n;++i) {
  180. if ((buf[i] == '\n')||(buf[i] == '\r')) {
  181. if (buf[i] == '\n')
  182. ++eolsInARow;
  183. } else eolsInARow = 0;
  184. if (eolsInARow >= 2) {
  185. // Two CRs in a row ends a message
  186. try {
  187. _handler(_arg,*this,Dictionary(stdoutBuf));
  188. stdoutBuf = "";
  189. } catch ( ... ) {} // handlers should not throw
  190. } else stdoutBuf.push_back(buf[i]);
  191. }
  192. }
  193. }
  194. }
  195. } // namespace ZeroTier
  196. #endif // __WINDOWS__