HttpClient.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. curlArgs[0] = const_cast <char *>(curlPath.c_str());
  101. curlArgs[1] = const_cast <char *>("-D");
  102. curlArgs[2] = const_cast <char *>("-"); // append headers before output
  103. int argPtr = 3;
  104. std::vector<std::string> headerArgs;
  105. for(std::map<std::string,std::string>::const_iterator h(_headers.begin());h!=_headers.end();++h) {
  106. headerArgs.push_back(h->first);
  107. headerArgs.back().append(": ");
  108. headerArgs.back().append(h->second);
  109. }
  110. for(std::vector<std::string>::iterator h(headerArgs.begin());h!=headerArgs.end();++h) {
  111. if (argPtr >= (1024 - 4)) // leave room for terminating NULL and URL
  112. break;
  113. curlArgs[argPtr++] = const_cast <char *>("-H");
  114. curlArgs[argPtr++] = const_cast <char *>(h->c_str());
  115. }
  116. curlArgs[argPtr++] = const_cast <char *>(_url.c_str());
  117. curlArgs[argPtr] = (char *)0;
  118. int curlStdout[2];
  119. int curlStderr[2];
  120. ::pipe(curlStdout);
  121. ::pipe(curlStderr);
  122. long pid = (long)vfork();
  123. if (pid < 0) {
  124. // fork() failed
  125. ::close(curlStdout[0]);
  126. ::close(curlStdout[1]);
  127. ::close(curlStderr[0]);
  128. ::close(curlStderr[1]);
  129. _handler(_arg,-1,_url,false,"unable to fork()");
  130. delete this;
  131. return;
  132. } else if (pid > 0) {
  133. // fork() succeeded, in parent process
  134. ::close(curlStdout[1]);
  135. ::close(curlStderr[1]);
  136. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  137. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  138. int exitCode = -1;
  139. unsigned long long timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  140. bool timedOut = false;
  141. bool tooLong = false;
  142. for(;;) {
  143. FD_ZERO(&readfds);
  144. FD_ZERO(&writefds);
  145. FD_ZERO(&errfds);
  146. FD_SET(curlStdout[0],&readfds);
  147. FD_SET(curlStderr[0],&readfds);
  148. FD_SET(curlStdout[0],&errfds);
  149. FD_SET(curlStderr[0],&errfds);
  150. tv.tv_sec = 1;
  151. tv.tv_usec = 0;
  152. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  153. if (FD_ISSET(curlStdout[0],&readfds)) {
  154. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  155. if (n > 0)
  156. _body.append(buf,n);
  157. else if (n < 0)
  158. break;
  159. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  160. ::kill(pid,SIGKILL);
  161. tooLong = true;
  162. break;
  163. }
  164. }
  165. if (FD_ISSET(curlStderr[0],&readfds))
  166. ::read(curlStderr[0],buf,sizeof(buf));
  167. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  168. break;
  169. if (Utils::now() >= timesOutAt) {
  170. ::kill(pid,SIGKILL);
  171. timedOut = true;
  172. break;
  173. }
  174. if (waitpid(pid,&exitCode,WNOHANG) > 0) {
  175. pid = 0;
  176. break;
  177. }
  178. }
  179. if (pid > 0)
  180. waitpid(pid,&exitCode,0);
  181. ::close(curlStdout[0]);
  182. ::close(curlStderr[0]);
  183. if (timedOut)
  184. _handler(_arg,-1,_url,false,"connection timed out");
  185. else if (tooLong)
  186. _handler(_arg,-1,_url,false,"response too long");
  187. else if (exitCode)
  188. _handler(_arg,-1,_url,false,"connection failed (curl returned non-zero exit code)");
  189. else {
  190. unsigned long idx = 0;
  191. // Grab status line and headers, which will prefix output on
  192. // success and will end with an empty line.
  193. std::vector<std::string> headers;
  194. headers.push_back(std::string());
  195. while (idx < _body.length()) {
  196. char c = _body[idx++];
  197. if (c == '\n') {
  198. if (!headers.back().length()) {
  199. headers.pop_back();
  200. break;
  201. } else headers.push_back(std::string());
  202. } else if (c != '\r')
  203. headers.back().push_back(c);
  204. }
  205. if (headers.empty()||(!headers.front().length())) {
  206. _handler(_arg,-1,_url,false,"HTTP response empty");
  207. delete this;
  208. return;
  209. }
  210. // Parse first line -- HTTP status code and response
  211. size_t scPos = headers.front().find(' ');
  212. if (scPos == std::string::npos) {
  213. _handler(_arg,-1,_url,false,"invalid HTTP response (no status line)");
  214. delete this;
  215. return;
  216. }
  217. ++scPos;
  218. unsigned int rcode = Utils::strToUInt(headers.front().substr(scPos,3).c_str());
  219. if ((!rcode)||(rcode > 999)) {
  220. _handler(_arg,-1,_url,false,"invalid HTTP response (invalid response code)");
  221. delete this;
  222. return;
  223. }
  224. // Serve up the resulting data to the handler
  225. if (rcode == 200)
  226. _handler(_arg,rcode,_url,false,_body.substr(idx));
  227. else if ((scPos + 4) < headers.front().length())
  228. _handler(_arg,rcode,_url,false,headers.front().substr(scPos+4));
  229. else _handler(_arg,rcode,_url,false,"(no status message from server)");
  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. return (HttpClient::Request)(new P_Req(method,url,headers,timeout,handler,arg));
  260. }
  261. #endif
  262. } // namespace ZeroTier