HttpClient.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. #ifdef __WINDOWS__
  50. #include <locale>
  51. #include <codecvt>
  52. #include <Windows.h>
  53. #include <winhttp.h>
  54. #endif
  55. namespace ZeroTier {
  56. const std::map<std::string,std::string> HttpClient::NO_HEADERS;
  57. #ifdef __UNIX_LIKE__
  58. // The *nix implementation calls 'curl' externally rather than linking to it.
  59. // This makes it an optional dependency that can be avoided in tiny systems
  60. // provided you don't want to have automatic software updates... or want to
  61. // do them via another method.
  62. #ifdef __APPLE__
  63. // TODO: get proxy configuration
  64. #endif
  65. // Paths where "curl" may be found on the system
  66. #define NUM_CURL_PATHS 5
  67. static const char *CURL_PATHS[NUM_CURL_PATHS] = { "/usr/bin/curl","/bin/curl","/usr/local/bin/curl","/usr/sbin/curl","/sbin/curl" };
  68. // Maximum message length
  69. #define CURL_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  70. // Internal private thread class that performs request, notifies handler,
  71. // and then commits suicide by deleting itself.
  72. class P_Req : NonCopyable
  73. {
  74. public:
  75. 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) :
  76. _url(url),
  77. _headers(headers),
  78. _timeout(timeout),
  79. _handler(handler),
  80. _arg(arg)
  81. {
  82. _myThread = Thread::start(this);
  83. }
  84. void threadMain()
  85. {
  86. char *curlArgs[1024];
  87. char buf[16384];
  88. fd_set readfds,writefds,errfds;
  89. struct timeval tv;
  90. std::string curlPath;
  91. for(int i=0;i<NUM_CURL_PATHS;++i) {
  92. if (Utils::fileExists(CURL_PATHS[i])) {
  93. curlPath = CURL_PATHS[i];
  94. break;
  95. }
  96. }
  97. if (!curlPath.length()) {
  98. _handler(_arg,-1,_url,false,"unable to locate 'curl' binary in /usr/bin, /bin, /usr/local/bin, /usr/sbin, or /sbin");
  99. delete this;
  100. return;
  101. }
  102. if (!_url.length()) {
  103. _handler(_arg,-1,_url,false,"cannot fetch empty URL");
  104. delete this;
  105. return;
  106. }
  107. curlArgs[0] = const_cast <char *>(curlPath.c_str());
  108. curlArgs[1] = const_cast <char *>("-D");
  109. curlArgs[2] = const_cast <char *>("-"); // append headers before output
  110. int argPtr = 3;
  111. std::vector<std::string> headerArgs;
  112. for(std::map<std::string,std::string>::const_iterator h(_headers.begin());h!=_headers.end();++h) {
  113. headerArgs.push_back(h->first);
  114. headerArgs.back().append(": ");
  115. headerArgs.back().append(h->second);
  116. }
  117. for(std::vector<std::string>::iterator h(headerArgs.begin());h!=headerArgs.end();++h) {
  118. if (argPtr >= (1024 - 4)) // leave room for terminating NULL and URL
  119. break;
  120. curlArgs[argPtr++] = const_cast <char *>("-H");
  121. curlArgs[argPtr++] = const_cast <char *>(h->c_str());
  122. }
  123. curlArgs[argPtr++] = const_cast <char *>(_url.c_str());
  124. curlArgs[argPtr] = (char *)0;
  125. int curlStdout[2];
  126. int curlStderr[2];
  127. ::pipe(curlStdout);
  128. ::pipe(curlStderr);
  129. long pid = (long)vfork();
  130. if (pid < 0) {
  131. // fork() failed
  132. ::close(curlStdout[0]);
  133. ::close(curlStdout[1]);
  134. ::close(curlStderr[0]);
  135. ::close(curlStderr[1]);
  136. _handler(_arg,-1,_url,false,"unable to fork()");
  137. delete this;
  138. return;
  139. } else if (pid > 0) {
  140. // fork() succeeded, in parent process
  141. ::close(curlStdout[1]);
  142. ::close(curlStderr[1]);
  143. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  144. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  145. int exitCode = -1;
  146. unsigned long long timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  147. bool timedOut = false;
  148. bool tooLong = false;
  149. for(;;) {
  150. FD_ZERO(&readfds);
  151. FD_ZERO(&writefds);
  152. FD_ZERO(&errfds);
  153. FD_SET(curlStdout[0],&readfds);
  154. FD_SET(curlStderr[0],&readfds);
  155. FD_SET(curlStdout[0],&errfds);
  156. FD_SET(curlStderr[0],&errfds);
  157. tv.tv_sec = 1;
  158. tv.tv_usec = 0;
  159. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  160. if (FD_ISSET(curlStdout[0],&readfds)) {
  161. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  162. if (n > 0) {
  163. _body.append(buf,n);
  164. // Reset timeout when data is read...
  165. timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  166. } else if (n < 0)
  167. break;
  168. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  169. ::kill(pid,SIGKILL);
  170. tooLong = true;
  171. break;
  172. }
  173. }
  174. if (FD_ISSET(curlStderr[0],&readfds))
  175. ::read(curlStderr[0],buf,sizeof(buf));
  176. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  177. break;
  178. if (Utils::now() >= timesOutAt) {
  179. ::kill(pid,SIGKILL);
  180. timedOut = true;
  181. break;
  182. }
  183. if (waitpid(pid,&exitCode,WNOHANG) > 0) {
  184. for(;;) {
  185. // Drain output...
  186. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  187. if (n <= 0)
  188. break;
  189. else {
  190. _body.append(buf,n);
  191. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  192. tooLong = true;
  193. break;
  194. }
  195. }
  196. }
  197. pid = 0;
  198. break;
  199. }
  200. }
  201. if (pid > 0)
  202. waitpid(pid,&exitCode,0);
  203. ::close(curlStdout[0]);
  204. ::close(curlStderr[0]);
  205. if (timedOut)
  206. _handler(_arg,-1,_url,false,"connection timed out");
  207. else if (tooLong)
  208. _handler(_arg,-1,_url,false,"response too long");
  209. else if (exitCode)
  210. _handler(_arg,-1,_url,false,"connection failed (curl returned non-zero exit code)");
  211. else {
  212. unsigned long idx = 0;
  213. // Grab status line and headers, which will prefix output on
  214. // success and will end with an empty line.
  215. std::vector<std::string> headers;
  216. headers.push_back(std::string());
  217. while (idx < _body.length()) {
  218. char c = _body[idx++];
  219. if (c == '\n') {
  220. if (!headers.back().length()) {
  221. headers.pop_back();
  222. break;
  223. } else headers.push_back(std::string());
  224. } else if (c != '\r')
  225. headers.back().push_back(c);
  226. }
  227. if (headers.empty()||(!headers.front().length())) {
  228. _handler(_arg,-1,_url,false,"HTTP response empty");
  229. delete this;
  230. return;
  231. }
  232. // Parse first line -- HTTP status code and response
  233. size_t scPos = headers.front().find(' ');
  234. if (scPos == std::string::npos) {
  235. _handler(_arg,-1,_url,false,"invalid HTTP response (no status line)");
  236. delete this;
  237. return;
  238. }
  239. ++scPos;
  240. unsigned int rcode = Utils::strToUInt(headers.front().substr(scPos,3).c_str());
  241. if ((!rcode)||(rcode > 999)) {
  242. _handler(_arg,-1,_url,false,"invalid HTTP response (invalid response code)");
  243. delete this;
  244. return;
  245. }
  246. // Serve up the resulting data to the handler
  247. if (rcode == 200)
  248. _handler(_arg,rcode,_url,false,_body.substr(idx));
  249. else if ((scPos + 4) < headers.front().length())
  250. _handler(_arg,rcode,_url,false,headers.front().substr(scPos+4));
  251. else _handler(_arg,rcode,_url,false,"(no status message from server)");
  252. }
  253. delete this;
  254. return;
  255. } else {
  256. // fork() succeeded, in child process
  257. ::dup2(curlStdout[1],STDOUT_FILENO);
  258. ::close(curlStdout[1]);
  259. ::dup2(curlStderr[1],STDERR_FILENO);
  260. ::close(curlStderr[1]);
  261. ::execv(curlPath.c_str(),curlArgs);
  262. ::exit(-1); // only reached if execv() fails
  263. }
  264. }
  265. const std::string _url;
  266. std::string _body;
  267. std::map<std::string,std::string> _headers;
  268. unsigned int _timeout;
  269. void (*_handler)(void *,int,const std::string &,bool,const std::string &);
  270. void *_arg;
  271. Thread _myThread;
  272. };
  273. HttpClient::Request HttpClient::_do(
  274. const char *method,
  275. const std::string &url,
  276. const std::map<std::string,std::string> &headers,
  277. unsigned int timeout,
  278. void (*handler)(void *,int,const std::string &,bool,const std::string &),
  279. void *arg)
  280. {
  281. return (HttpClient::Request)(new P_Req(method,url,headers,timeout,handler,arg));
  282. }
  283. #endif
  284. #ifdef __WINDOWS__
  285. #define WIN_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  286. // Internal private thread class that performs request, notifies handler,
  287. // and then commits suicide by deleting itself.
  288. class P_Req : NonCopyable
  289. {
  290. public:
  291. 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) :
  292. _url(url),
  293. _headers(headers),
  294. _timeout(timeout),
  295. _handler(handler),
  296. _arg(arg)
  297. {
  298. _myThread = Thread::start(this);
  299. }
  300. void threadMain()
  301. {
  302. HINTERNET hSession = (HINTERNET)0;
  303. HINTERNET hConnect = (HINTERNET)0;
  304. HINTERNET hRequest = (HINTERNET)0;
  305. try {
  306. hSession = WinHttpOpen(L"ZeroTier One HttpClient/1.0",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  307. if (!hSession) {
  308. _handler(_arg,-1,_url,false,"WinHttpOpen() failed");
  309. goto closeAndReturnFromHttp;
  310. }
  311. int timeoutMs = (int)_timeout * 1000;
  312. WinHttpSetTimeouts(hSession,timeoutMs,timeoutMs,timeoutMs,timeoutMs);
  313. std::wstring_convert< std::codecvt_utf8<wchar_t> > wcconv;
  314. std::wstring wurl(wcconv.from_bytes(_url));
  315. URL_COMPONENTS uc;
  316. memset(&uc,0,sizeof(uc));
  317. uc.dwStructSize = sizeof(uc);
  318. uc.dwSchemeLength = -1;
  319. uc.dwHostNameLength = -1;
  320. uc.dwUrlPathLength = -1;
  321. uc.dwExtraInfoLength = -1;
  322. if (!WinHttpCrackUrl(wurl.c_str(),wurl.length(),0,&uc)) {
  323. _handler(_arg,-1,_url,false,"unable to parse URL: WinHttpCrackUrl() failed");
  324. goto closeAndReturnFromHttp;
  325. }
  326. if ((!uc.lpszHostName)||(!uc.lpszUrlPath)||(!uc.lpszScheme)||(uc.dwHostNameLength <= 0)||(uc.dwUrlPathLength <= 0)||(uc.dwSchemeLength <= 0)) {
  327. _handler(_arg,-1,_url,false,"unable to parse URL: missing scheme, host name, or path");
  328. goto closeAndReturnFromHttp;
  329. }
  330. std::wstring urlScheme(uc.lpszScheme,uc.dwSchemeLength);
  331. std::wstring urlHostName(uc.lpszHostName,uc.dwHostNameLength);
  332. std::wstring urlPath(uc.lpszUrlPath,uc.dwUrlPathLength);
  333. if ((uc.lpszExtraInfo)&&(uc.dwExtraInfoLength > 0))
  334. urlPath.append(uc.lpszExtraInfo,uc.dwExtraInfoLength);
  335. if (urlScheme != L"http") {
  336. _handler(_arg,-1,_url,false,"only 'http' scheme is supported");
  337. goto closeAndReturnFromHttp;
  338. }
  339. hConnect = WinHttpConnect(hSession,urlHostName.c_str(),((uc.nPort > 0) ? uc.nPort : 80),0);
  340. if (!hConnect) {
  341. _handler(_arg,-1,_url,false,"connection failed");
  342. goto closeAndReturnFromHttp;
  343. }
  344. hRequest = WinHttpOpenRequest(hConnect,L"GET",NULL,NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
  345. if (!hRequest) {
  346. _handler(_arg,-1,_url,false,"error sending request");
  347. goto closeAndReturnFromHttp;
  348. }
  349. if (WinHttpReceiveResponse(hRequest,NULL)) {
  350. DWORD dwStatusCode = 0;
  351. DWORD dwTmp = sizeof(dwStatusCode);
  352. WinHttpQueryHeaders(hRequest,WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,NULL,&dwStatusCode,&dwTmp,NULL);
  353. DWORD dwSize;
  354. do {
  355. dwSize = 0;
  356. if (!WinHttpQueryDataAvailable(hRequest,&dwSize)) {
  357. _handler(_arg,-1,_url,false,"receive error (1)");
  358. goto closeAndReturnFromHttp;
  359. }
  360. char *outBuffer = new char[dwSize];
  361. DWORD dwRead = 0;
  362. if (!WinHttpReadData(hRequest,(LPVOID)outBuffer,dwSize,&dwRead)) {
  363. _handler(_arg,-1,_url,false,"receive error (2)");
  364. goto closeAndReturnFromHttp;
  365. }
  366. _body.append(outBuffer,dwRead);
  367. delete [] outBuffer;
  368. if (_body.length() > WIN_MAX_MESSAGE_LENGTH) {
  369. _handler(_arg,-1,_url,false,"result too large");
  370. goto closeAndReturnFromHttp;
  371. }
  372. } while (dwSize > 0);
  373. _handler(_arg,dwStatusCode,_url,false,_body);
  374. }
  375. } catch (std::bad_alloc &exc) {
  376. _handler(_arg,-1,_url,false,"insufficient memory");
  377. } catch ( ... ) {
  378. _handler(_arg,-1,_url,false,"unexpected exception");
  379. }
  380. closeAndReturnFromHttp:
  381. if (hRequest)
  382. WinHttpCloseHandle(hRequest);
  383. if (hConnect)
  384. WinHttpCloseHandle(hConnect);
  385. if (hSession)
  386. WinHttpCloseHandle(hSession);
  387. delete this;
  388. return;
  389. }
  390. const std::string _url;
  391. std::string _body;
  392. std::map<std::string,std::string> _headers;
  393. unsigned int _timeout;
  394. void (*_handler)(void *,int,const std::string &,bool,const std::string &);
  395. void *_arg;
  396. Thread _myThread;
  397. };
  398. HttpClient::Request HttpClient::_do(
  399. const char *method,
  400. const std::string &url,
  401. const std::map<std::string,std::string> &headers,
  402. unsigned int timeout,
  403. void (*handler)(void *,int,const std::string &,bool,const std::string &),
  404. void *arg)
  405. {
  406. return (HttpClient::Request)(new P_Req(method,url,headers,timeout,handler,arg));
  407. }
  408. #endif
  409. } // namespace ZeroTier