HttpClient.cpp 8.7 KB

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