HttpClient.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <vector>
  31. #include <utility>
  32. #include <algorithm>
  33. #include "Constants.hpp"
  34. #include "HttpClient.hpp"
  35. #include "Thread.hpp"
  36. #include "Utils.hpp"
  37. #include "NonCopyable.hpp"
  38. #include "Defaults.hpp"
  39. #ifdef __UNIX_LIKE__
  40. #include <unistd.h>
  41. #include <signal.h>
  42. #include <fcntl.h>
  43. #include <sys/select.h>
  44. #include <sys/types.h>
  45. #include <sys/stat.h>
  46. #include <sys/socket.h>
  47. #endif
  48. namespace ZeroTier {
  49. #ifdef __UNIX_LIKE__
  50. // The *nix implementation calls 'curl' externally rather than linking to it.
  51. // This makes it an optional dependency that can be avoided in tiny systems
  52. // provided you don't want to have automatic software updates... or want to
  53. // do them via another method.
  54. // Paths where "curl" may be found on the system
  55. #define NUM_CURL_PATHS 5
  56. static const char *CURL_PATHS[NUM_CURL_PATHS] = { "/usr/bin/curl","/bin/curl","/usr/local/bin/curl","/usr/sbin/curl","/sbin/curl" };
  57. static const std::string CURL_IN_HOME(ZT_DEFAULTS.defaultHomePath + "/curl");
  58. // Maximum message length
  59. #define CURL_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  60. // Internal private thread class that performs request, notifies handler,
  61. // and then commits suicide by deleting itself.
  62. class P_Req : NonCopyable
  63. {
  64. public:
  65. P_Req(const char *method,const std::string &url,const std::map<std::string,std::string> &headers,unsigned int timeout,void (*handler)(void *,int,const std::string &,bool,const std::string &),void *arg) :
  66. _url(url),
  67. _headers(headers),
  68. _timeout(timeout),
  69. _handler(handler),
  70. _arg(arg)
  71. {
  72. _myThread = Thread::start(this);
  73. }
  74. void threadMain()
  75. {
  76. char *curlArgs[1024];
  77. char buf[16384];
  78. fd_set readfds,writefds,errfds;
  79. struct timeval tv;
  80. std::string curlPath;
  81. for(int i=0;i<NUM_CURL_PATHS;++i) {
  82. if (Utils::fileExists(CURL_PATHS[i])) {
  83. curlPath = CURL_PATHS[i];
  84. break;
  85. }
  86. }
  87. if (!curlPath.length()) {
  88. if (Utils::fileExists(CURL_IN_HOME.c_str()))
  89. curlPath = CURL_IN_HOME;
  90. }
  91. if (!curlPath.length()) {
  92. _handler(_arg,-1,_url,false,"unable to locate 'curl' binary in /usr/bin, /bin, /usr/local/bin, /usr/sbin, or /sbin");
  93. delete this;
  94. return;
  95. }
  96. curlArgs[0] = const_cast <char *>(curlPath.c_str());
  97. curlArgs[1] = const_cast <char *>("-D");
  98. curlArgs[2] = const_cast <char *>("-"); // append headers before output
  99. int argPtr = 3;
  100. std::vector<std::string> headerArgs;
  101. for(std::map<std::string,std::string>::const_iterator h(_headers.begin());h!=_headers.end();++h) {
  102. headerArgs.push_back(h->first);
  103. headerArgs.back().append(": ");
  104. headerArgs.back().append(h->second);
  105. }
  106. for(std::vector<std::string>::iterator h(headerArgs.begin());h!=headerArgs.end();++h) {
  107. if (argPtr >= (1024 - 3)) // leave room for terminating NULL
  108. break;
  109. curlArgs[argPtr++] = const_cast <char *>("-H");
  110. curlArgs[argPtr++] = const_cast <char *>(h->c_str());
  111. }
  112. curlArgs[argPtr] = (char *)0;
  113. int curlStdout[2];
  114. int curlStderr[2];
  115. ::pipe(curlStdout);
  116. ::pipe(curlStderr);
  117. long pid = (long)vfork();
  118. if (pid < 0) {
  119. // fork() failed
  120. ::close(curlStdout[0]);
  121. ::close(curlStdout[1]);
  122. ::close(curlStderr[0]);
  123. ::close(curlStderr[1]);
  124. _handler(_arg,-1,_url,false,"unable to fork()");
  125. delete this;
  126. return;
  127. } else if (pid > 0) {
  128. // fork() succeeded, in parent process
  129. ::close(curlStdout[1]);
  130. ::close(curlStderr[1]);
  131. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  132. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  133. int exitCode = -1;
  134. unsigned long long timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  135. bool timedOut = false;
  136. bool tooLong = false;
  137. for(;;) {
  138. FD_ZERO(&readfds);
  139. FD_ZERO(&writefds);
  140. FD_ZERO(&errfds);
  141. FD_SET(curlStdout[0],&readfds);
  142. FD_SET(curlStderr[0],&readfds);
  143. FD_SET(curlStdout[0],&errfds);
  144. FD_SET(curlStderr[0],&errfds);
  145. tv.tv_sec = 1;
  146. tv.tv_usec = 0;
  147. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  148. if (FD_ISSET(curlStdout[0],&readfds)) {
  149. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  150. if (n > 0)
  151. _body.append(buf,n);
  152. else break;
  153. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  154. ::kill(pid,SIGKILL);
  155. tooLong = true;
  156. break;
  157. }
  158. }
  159. if (FD_ISSET(curlStderr[0],&readfds))
  160. ::read(curlStderr[0],buf,sizeof(buf));
  161. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  162. break;
  163. if (Utils::now() >= timesOutAt) {
  164. ::kill(pid,SIGKILL);
  165. timedOut = true;
  166. break;
  167. }
  168. if (waitpid(pid,&exitCode,WNOHANG) > 0) {
  169. pid = 0;
  170. break;
  171. }
  172. }
  173. if (pid > 0)
  174. waitpid(pid,&exitCode,0);
  175. ::close(curlStdout[0]);
  176. ::close(curlStderr[0]);
  177. if (timedOut)
  178. _handler(_arg,-1,_url,false,"connection timed out");
  179. else if (tooLong)
  180. _handler(_arg,-1,_url,false,"response too long");
  181. else if (exitCode)
  182. _handler(_arg,-1,_url,false,"connection failed (curl returned non-zero exit code)");
  183. else {
  184. unsigned long idx = 0;
  185. // Grab status line and headers, which will prefix output on
  186. // success and will end with an empty line.
  187. std::vector<std::string> headers;
  188. headers.push_back(std::string());
  189. while (idx < _body.length()) {
  190. char c = _body[idx++];
  191. if (c == '\n') {
  192. if (!headers.back().length()) {
  193. headers.pop_back();
  194. break;
  195. }
  196. } else if (c != '\r') // \r's shouldn't be present but ignore them if they are
  197. headers.back().push_back(c);
  198. }
  199. if (headers.empty()||(!headers.front().length())) {
  200. _handler(_arg,-1,_url,false,"HTTP response empty");
  201. delete this;
  202. return;
  203. }
  204. // Parse first line -- HTTP status code and response
  205. size_t scPos = headers.front().find(' ');
  206. if (scPos == std::string::npos) {
  207. _handler(_arg,-1,_url,false,"invalid HTTP response (no status line)");
  208. delete this;
  209. return;
  210. }
  211. ++scPos;
  212. size_t msgPos = headers.front().find(' ',scPos);
  213. if (msgPos == std::string::npos)
  214. msgPos = headers.front().length();
  215. if ((msgPos - scPos) != 3) {
  216. _handler(_arg,-1,_url,false,"invalid HTTP response (no response code)");
  217. delete this;
  218. return;
  219. }
  220. unsigned int rcode = Utils::strToUInt(headers.front().substr(scPos,3).c_str());
  221. if ((!rcode)||(rcode > 999)) {
  222. _handler(_arg,-1,_url,false,"invalid HTTP response (invalid response code)");
  223. delete this;
  224. return;
  225. }
  226. // Serve up the resulting data to the handler
  227. if (rcode == 200)
  228. _handler(_arg,rcode,_url,false,_body.substr(idx));
  229. else _handler(_arg,rcode,_url,false,headers.front().substr(scPos+3));
  230. }
  231. delete this;
  232. return;
  233. } else {
  234. // fork() succeeded, in child process
  235. ::dup2(curlStdout[1],STDOUT_FILENO);
  236. ::close(curlStdout[1]);
  237. ::dup2(curlStderr[1],STDERR_FILENO);
  238. ::close(curlStderr[1]);
  239. ::execv(curlPath.c_str(),curlArgs);
  240. ::exit(-1); // only reached if execv() fails
  241. }
  242. }
  243. const std::string _url;
  244. std::string _body;
  245. std::map<std::string,std::string> _headers;
  246. unsigned int _timeout;
  247. void (*_handler)(void *,int,const std::string &,bool,const std::string &);
  248. void *_arg;
  249. Thread _myThread;
  250. };
  251. HttpClient::Request HttpClient::_do(
  252. const char *method,
  253. const std::string &url,
  254. const std::map<std::string,std::string> &headers,
  255. unsigned int timeout,
  256. void (*handler)(void *,int,const std::string &,bool,const std::string &),
  257. void *arg)
  258. {
  259. }
  260. #endif
  261. } // namespace ZeroTier