Service.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. execl(_path.c_str(),_path.c_str(),_r->homePath.c_str(),(const char *)0);
  131. exit(-1);
  132. }
  133. } else {
  134. int st = 0;
  135. if (waitpid(_pid,&st,WNOHANG) == _pid) {
  136. if (_childStdin > 0) close(_childStdin);
  137. _childStdin = 0;
  138. if (_childStdout > 0) close(_childStdout);
  139. if (_childStderr > 0) close(_childStderr);
  140. _pid = 0;
  141. if (!_run)
  142. return;
  143. LOG("service %s exited with exit code: %d, delaying 1s to attempt relaunch",_name.c_str(),st);
  144. Thread::sleep(1000); // wait to relaunch
  145. continue;
  146. }
  147. }
  148. // If we've made it here, _pid is running last we checked.
  149. FD_ZERO(&readfds);
  150. FD_ZERO(&writefds);
  151. FD_ZERO(&exceptfds);
  152. FD_SET(_childStdout,&readfds);
  153. FD_SET(_childStderr,&readfds);
  154. tv.tv_sec = 1;
  155. tv.tv_usec = 0;
  156. ::select(std::max(_childStdout,_childStderr)+1,&readfds,&writefds,&exceptfds,&tv);
  157. if (!_run) {
  158. if (_childStdin > 0) ::close(_childStdin);
  159. _childStdin = 0;
  160. if (_childStdout > 0) ::close(_childStdout);
  161. if (_childStderr > 0) ::close(_childStderr);
  162. return;
  163. }
  164. if ((_childStderr > 0)&&(FD_ISSET(_childStderr,&readfds))) {
  165. int n = (int)::read(_childStderr,buf,sizeof(buf));
  166. for(int i=0;i<n;++i) {
  167. if ((buf[i] == '\r')||(buf[i] == '\n')) {
  168. stderrBuf = Utils::trim(stderrBuf);
  169. if (stderrBuf.length())
  170. LOG("service %s: %s",_name.c_str(),stderrBuf.c_str());
  171. stderrBuf = "";
  172. } else stderrBuf.push_back(buf[i]);
  173. }
  174. }
  175. if ((_childStdout > 0)&&(FD_ISSET(_childStdout,&readfds))) {
  176. int n = (int)::read(_childStdout,buf,sizeof(buf));
  177. for(int i=0;i<n;++i) {
  178. if ((buf[i] == '\n')||(buf[i] == '\r')) {
  179. if (buf[i] == '\n')
  180. ++eolsInARow;
  181. } else eolsInARow = 0;
  182. if (eolsInARow >= 2) {
  183. // Two CRs in a row ends a message
  184. try {
  185. _handler(_arg,*this,Dictionary(stdoutBuf));
  186. stdoutBuf = "";
  187. } catch ( ... ) {} // handlers should not throw
  188. } else stdoutBuf.push_back(buf[i]);
  189. }
  190. }
  191. }
  192. }
  193. } // namespace ZeroTier
  194. #endif // __WINDOWS__