HttpClient.cpp 8.9 KB

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