IpcConnection.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <stdarg.h>
  32. #include <stdexcept>
  33. #include "IpcConnection.hpp"
  34. #ifndef __WINDOWS__
  35. #include <unistd.h>
  36. #include <sys/ioctl.h>
  37. #include <sys/socket.h>
  38. #include <sys/un.h>
  39. #include <sys/socket.h>
  40. #include <sys/select.h>
  41. #endif
  42. namespace ZeroTier {
  43. IpcConnection::IpcConnection(const char *endpoint,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
  44. _handler(commandHandler),
  45. _arg(arg),
  46. _timeout(timeout),
  47. #ifdef __WINDOWS__
  48. _sock(INVALID_HANDLE_VALUE),
  49. _incoming(false),
  50. #else
  51. _sock(-1),
  52. #endif
  53. _run(true),
  54. _running(true)
  55. {
  56. #ifdef __WINDOWS__
  57. _sock = CreateFileA(endpoint,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_EXISTING,0,NULL);
  58. if (_sock == INVALID_HANDLE_VALUE)
  59. throw std::runtime_error("IPC endpoint unreachable");
  60. DWORD pipeMode = PIPE_READMODE_BYTE;
  61. SetNamedPipeHandleState(_sock,&pipeMode,NULL,NULL);
  62. #else
  63. struct sockaddr_un unaddr;
  64. unaddr.sun_family = AF_UNIX;
  65. strncpy(unaddr.sun_path,endpoint,sizeof(unaddr.sun_path));
  66. unaddr.sun_path[sizeof(unaddr.sun_path) - 1] = (char)0;
  67. _sock = socket(AF_UNIX,SOCK_STREAM,0);
  68. if (_sock <= 0)
  69. throw std::runtime_error("unable to create socket of type AF_UNIX");
  70. if (connect(_sock,(struct sockaddr *)&unaddr,sizeof(unaddr))) {
  71. ::close(_sock);
  72. throw std::runtime_error("IPC endpoint unreachable");
  73. }
  74. #endif
  75. _thread = Thread::start(this);
  76. }
  77. #ifdef __WINDOWS__
  78. IpcConnection::IpcConnection(HANDLE s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
  79. #else
  80. IpcConnection::IpcConnection(int s,unsigned int timeout,void (*commandHandler)(void *,IpcConnection *,IpcConnection::EventType,const char *),void *arg) :
  81. #endif
  82. _handler(commandHandler),
  83. _arg(arg),
  84. _timeout(timeout),
  85. _sock(s),
  86. #ifdef __WINDOWS__
  87. _incoming(true),
  88. #endif
  89. _run(true),
  90. _running(true)
  91. {
  92. _thread = Thread::start(this);
  93. }
  94. IpcConnection::~IpcConnection()
  95. {
  96. _writeLock.lock();
  97. _run = false;
  98. _writeLock.unlock();
  99. #ifdef __WINDOWS__
  100. while (_running) {
  101. Thread::cancelIO(_thread); // cause Windows to break from blocking read and detect shutdown
  102. Sleep(100);
  103. }
  104. #else // !__WINDOWS__
  105. int s = _sock;
  106. _sock = 0;
  107. if (s > 0) {
  108. ::shutdown(s,SHUT_RDWR);
  109. ::close(s);
  110. }
  111. Thread::join(_thread);
  112. #endif // __WINDOWS__ / !__WINDOWS__
  113. }
  114. void IpcConnection::printf(const char *format,...)
  115. {
  116. va_list ap;
  117. int n;
  118. char tmp[65536];
  119. va_start(ap,format);
  120. n = (int)::vsnprintf(tmp,sizeof(tmp),format,ap);
  121. va_end(ap);
  122. if (n <= 0)
  123. return;
  124. Mutex::Lock _l(_writeLock);
  125. #ifdef __WINDOWS__
  126. _writeBuf.append(tmp,n);
  127. Thread::cancelIO(_thread); // cause Windows to break from blocking read and service write buffer
  128. #else
  129. if (_sock > 0)
  130. ::write(_sock,tmp,n);
  131. #endif
  132. }
  133. void IpcConnection::threadMain()
  134. throw()
  135. {
  136. char tmp[16384];
  137. char linebuf[16384];
  138. unsigned int lineptr = 0;
  139. char c;
  140. #ifdef __WINDOWS__
  141. DWORD n,i;
  142. std::string wbuf;
  143. #else // !__WINDOWS__
  144. int s,n,i;
  145. fd_set readfds,writefds,errorfds;
  146. struct timeval tout;
  147. #ifdef SO_NOSIGPIPE
  148. if (_sock > 0) {
  149. i = 1;
  150. ::setsockopt(_sock,SOL_SOCKET,SO_NOSIGPIPE,(char *)&i,sizeof(i));
  151. }
  152. #endif // SO_NOSIGPIPE
  153. #endif // __WINDOWS__ / !__WINDOWS__
  154. while (_run) {
  155. #ifdef __WINDOWS__
  156. /* Note that we do not use fucking timeouts in Windows, since it does seem
  157. * to properly detect named pipe endpoint close. But we do use a write buffer
  158. * because Windows won't let you divorce reading and writing threads without
  159. * all that OVERLAPPED cruft. */
  160. {
  161. Mutex::Lock _l(_writeLock);
  162. if (!_run)
  163. break;
  164. if (_writeBuf.length() > 0) {
  165. wbuf.append(_writeBuf);
  166. _writeBuf.clear();
  167. }
  168. }
  169. if (wbuf.length() > 0) {
  170. n = 0;
  171. if ((WriteFile(_sock,wbuf.data(),(DWORD)(wbuf.length()),&n,NULL))&&(n > 0)) {
  172. if (n < (DWORD)wbuf.length())
  173. wbuf.erase(0,n);
  174. else wbuf.clear();
  175. } else if (GetLastError() != ERROR_OPERATION_ABORTED)
  176. break;
  177. FlushFileBuffers(_sock);
  178. }
  179. if (!_run)
  180. break;
  181. n = 0;
  182. if ((!ReadFile(_sock,tmp,sizeof(tmp),&n,NULL))||(n <= 0)) {
  183. if (GetLastError() == ERROR_OPERATION_ABORTED)
  184. n = 0;
  185. else break;
  186. }
  187. if (!_run)
  188. break;
  189. #else // !__WINDOWS__
  190. /* So today I learned that there is no reliable way to detect a half-closed
  191. * Unix domain socket. So to make sure we don't leave orphaned sockets around
  192. * we just use fucking timeouts. If a socket fucking times out, we break from
  193. * the I/O loop and terminate the thread. But this IpcConnection code is ugly
  194. * so maybe the OS is simply offended by it and refuses to reveal its mysteries
  195. * to me. Oh well... this IPC code will probably get canned when we go to
  196. * local HTTP RESTful interfaces or soemthing like that. */
  197. if ((s = _sock) <= 0)
  198. break;
  199. FD_ZERO(&readfds);
  200. FD_ZERO(&writefds);
  201. FD_ZERO(&errorfds);
  202. FD_SET(s,&readfds);
  203. FD_SET(s,&errorfds);
  204. tout.tv_sec = _timeout; // use a fucking timeout
  205. tout.tv_usec = 0;
  206. if (select(s+1,&readfds,&writefds,&errorfds,&tout) <= 0) {
  207. break; // socket has fucking timed out
  208. } else {
  209. if (FD_ISSET(s,&errorfds))
  210. break; // socket has an exception... sometimes works
  211. else {
  212. n = (int)::read(s,tmp,sizeof(tmp));
  213. if ((n <= 0)||(_sock <= 0))
  214. break; // read returned error... sometimes works
  215. }
  216. }
  217. #endif // __WINDOWS__ / !__WINDOWS__
  218. for(i=0;i<n;++i) {
  219. c = (linebuf[lineptr] = tmp[i]);
  220. if ((c == '\r')||(c == '\n')||(c == (char)0)||(lineptr == (sizeof(linebuf) - 1))) {
  221. if (lineptr) {
  222. linebuf[lineptr] = (char)0;
  223. _handler(_arg,this,IPC_EVENT_COMMAND,linebuf);
  224. lineptr = 0;
  225. }
  226. } else ++lineptr;
  227. }
  228. }
  229. _writeLock.lock();
  230. bool r = _run;
  231. _writeLock.unlock();
  232. #ifdef __WINDOWS__
  233. if (_incoming)
  234. DisconnectNamedPipe(_sock);
  235. CloseHandle(_sock);
  236. _running = false;
  237. #endif // __WINDOWS__
  238. if (r)
  239. _handler(_arg,this,IPC_EVENT_CONNECTION_CLOSED,(const char *)0);
  240. }
  241. } // namespace ZeroTier