HttpClient.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 "../node/Constants.hpp"
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #ifdef __WINDOWS__
  32. #include <WinSock2.h>
  33. #include <Windows.h>
  34. #include <winhttp.h>
  35. #include <locale>
  36. #include <codecvt>
  37. #endif // __WINDOWS__
  38. #ifdef __UNIX_LIKE__
  39. #include <unistd.h>
  40. #include <signal.h>
  41. #include <fcntl.h>
  42. #include <sys/select.h>
  43. #include <sys/types.h>
  44. #include <sys/stat.h>
  45. #include <sys/socket.h>
  46. #include <sys/wait.h>
  47. #endif // __UNIX_LIKE__
  48. #include <vector>
  49. #include <utility>
  50. #include <algorithm>
  51. #include "HttpClient.hpp"
  52. #include "Thread.hpp"
  53. #include "OSUtils.hpp"
  54. namespace ZeroTier {
  55. #ifdef __UNIX_LIKE__
  56. // The *nix implementation calls 'curl' externally rather than linking to it.
  57. // This makes it an optional dependency that can be avoided in tiny systems
  58. // provided you don't want to have automatic software updates... or want to
  59. // do them via another method.
  60. #ifdef __APPLE__
  61. // TODO: get proxy configuration
  62. #endif
  63. // Paths where "curl" may be found on the system
  64. #define NUM_CURL_PATHS 6
  65. static const char *CURL_PATHS[NUM_CURL_PATHS] = { "/usr/bin/curl","/bin/curl","/usr/local/bin/curl","/usr/sbin/curl","/sbin/curl","/usr/libexec/curl" };
  66. // Maximum message length
  67. #define CURL_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  68. // Internal private thread class that performs request, notifies handler,
  69. // and then commits suicide by deleting itself.
  70. class HttpClient_Private_Request
  71. {
  72. public:
  73. HttpClient_Private_Request(HttpClient *parent,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 &,const std::string &),void *arg) :
  74. _url(url),
  75. _headers(headers),
  76. _timeout(timeout),
  77. _handler(handler),
  78. _arg(arg),
  79. _parent(parent),
  80. _pid(0),
  81. _cancelled(false)
  82. {
  83. _myThread = Thread::start(this);
  84. }
  85. ~HttpClient_Private_Request()
  86. {
  87. Mutex::Lock _l(_parent->_requests_m);
  88. _parent->_requests.erase((HttpClient::Request)this);
  89. }
  90. void threadMain()
  91. {
  92. char *curlArgs[1024];
  93. char buf[16384];
  94. fd_set readfds,writefds,errfds;
  95. struct timeval tv;
  96. std::string curlPath;
  97. for(int i=0;i<NUM_CURL_PATHS;++i) {
  98. if (OSUtils::fileExists(CURL_PATHS[i])) {
  99. curlPath = CURL_PATHS[i];
  100. break;
  101. }
  102. }
  103. if (!curlPath.length()) {
  104. _doH(_arg,-1,_url,"unable to locate 'curl' binary in /usr/bin, /bin, /usr/local/bin, /usr/sbin, or /sbin");
  105. delete this;
  106. return;
  107. }
  108. if (!_url.length()) {
  109. _doH(_arg,-1,_url,"cannot fetch empty URL");
  110. delete this;
  111. return;
  112. }
  113. curlArgs[0] = const_cast <char *>(curlPath.c_str());
  114. curlArgs[1] = const_cast <char *>("-D");
  115. curlArgs[2] = const_cast <char *>("-"); // append headers before output
  116. int argPtr = 3;
  117. std::vector<std::string> headerArgs;
  118. for(std::map<std::string,std::string>::const_iterator h(_headers.begin());h!=_headers.end();++h) {
  119. headerArgs.push_back(h->first);
  120. headerArgs.back().append(": ");
  121. headerArgs.back().append(h->second);
  122. }
  123. for(std::vector<std::string>::iterator h(headerArgs.begin());h!=headerArgs.end();++h) {
  124. if (argPtr >= (1024 - 4)) // leave room for terminating NULL and URL
  125. break;
  126. curlArgs[argPtr++] = const_cast <char *>("-H");
  127. curlArgs[argPtr++] = const_cast <char *>(h->c_str());
  128. }
  129. curlArgs[argPtr++] = const_cast <char *>(_url.c_str());
  130. curlArgs[argPtr] = (char *)0;
  131. if (_cancelled) {
  132. delete this;
  133. return;
  134. }
  135. int curlStdout[2];
  136. int curlStderr[2];
  137. ::pipe(curlStdout);
  138. ::pipe(curlStderr);
  139. _pid = (long)vfork();
  140. if (_pid < 0) {
  141. // fork() failed
  142. ::close(curlStdout[0]);
  143. ::close(curlStdout[1]);
  144. ::close(curlStderr[0]);
  145. ::close(curlStderr[1]);
  146. _doH(_arg,-1,_url,"unable to fork()");
  147. delete this;
  148. return;
  149. } else if (_pid > 0) {
  150. // fork() succeeded, in parent process
  151. ::close(curlStdout[1]);
  152. ::close(curlStderr[1]);
  153. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  154. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  155. int exitCode = -1;
  156. unsigned long long timesOutAt = OSUtils::now() + ((unsigned long long)_timeout * 1000ULL);
  157. bool timedOut = false;
  158. bool tooLong = false;
  159. while (!_cancelled) {
  160. FD_ZERO(&readfds);
  161. FD_ZERO(&writefds);
  162. FD_ZERO(&errfds);
  163. FD_SET(curlStdout[0],&readfds);
  164. FD_SET(curlStderr[0],&readfds);
  165. FD_SET(curlStdout[0],&errfds);
  166. FD_SET(curlStderr[0],&errfds);
  167. tv.tv_sec = 1;
  168. tv.tv_usec = 0;
  169. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  170. if (FD_ISSET(curlStdout[0],&readfds)) {
  171. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  172. if (n > 0) {
  173. _body.append(buf,n);
  174. // Reset timeout when data is read...
  175. timesOutAt = OSUtils::now() + ((unsigned long long)_timeout * 1000ULL);
  176. } else if (n < 0)
  177. break;
  178. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  179. tooLong = true;
  180. break;
  181. }
  182. }
  183. if (FD_ISSET(curlStderr[0],&readfds))
  184. ::read(curlStderr[0],buf,sizeof(buf));
  185. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  186. break;
  187. if (OSUtils::now() >= timesOutAt) {
  188. timedOut = true;
  189. break;
  190. }
  191. if (waitpid(_pid,&exitCode,WNOHANG) > 0) {
  192. for(;;) {
  193. // Drain output...
  194. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  195. if (n <= 0)
  196. break;
  197. else {
  198. _body.append(buf,n);
  199. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  200. tooLong = true;
  201. break;
  202. }
  203. }
  204. }
  205. _pid = 0;
  206. break;
  207. }
  208. }
  209. if (_pid > 0) {
  210. ::kill(_pid,SIGKILL);
  211. waitpid(_pid,&exitCode,0);
  212. }
  213. _pid = 0;
  214. ::close(curlStdout[0]);
  215. ::close(curlStderr[0]);
  216. if (timedOut)
  217. _doH(_arg,-1,_url,"connection timed out");
  218. else if (tooLong)
  219. _doH(_arg,-1,_url,"response too long");
  220. else if (exitCode)
  221. _doH(_arg,-1,_url,"connection failed (curl returned non-zero exit code)");
  222. else {
  223. unsigned long idx = 0;
  224. // Grab status line and headers, which will prefix output on
  225. // success and will end with an empty line.
  226. std::vector<std::string> headers;
  227. headers.push_back(std::string());
  228. while (idx < _body.length()) {
  229. char c = _body[idx++];
  230. if (c == '\n') {
  231. if (!headers.back().length()) {
  232. headers.pop_back();
  233. break;
  234. } else headers.push_back(std::string());
  235. } else if (c != '\r')
  236. headers.back().push_back(c);
  237. }
  238. if (headers.empty()||(!headers.front().length())) {
  239. _doH(_arg,-1,_url,"HTTP response empty");
  240. delete this;
  241. return;
  242. }
  243. // Parse first line -- HTTP status code and response
  244. size_t scPos = headers.front().find(' ');
  245. if (scPos == std::string::npos) {
  246. _doH(_arg,-1,_url,"invalid HTTP response (no status line)");
  247. delete this;
  248. return;
  249. }
  250. ++scPos;
  251. unsigned int rcode = OSUtils::strToUInt(headers.front().substr(scPos,3).c_str());
  252. if ((!rcode)||(rcode > 999)) {
  253. _doH(_arg,-1,_url,"invalid HTTP response (invalid response code)");
  254. delete this;
  255. return;
  256. }
  257. // Serve up the resulting data to the handler
  258. if (rcode == 200)
  259. _doH(_arg,rcode,_url,_body.substr(idx));
  260. else if ((scPos + 4) < headers.front().length())
  261. _doH(_arg,rcode,_url,headers.front().substr(scPos+4));
  262. else _doH(_arg,rcode,_url,"(no status message from server)");
  263. }
  264. delete this;
  265. return;
  266. } else {
  267. // fork() succeeded, in child process
  268. ::dup2(curlStdout[1],STDOUT_FILENO);
  269. ::close(curlStdout[1]);
  270. ::dup2(curlStderr[1],STDERR_FILENO);
  271. ::close(curlStderr[1]);
  272. ::execv(curlPath.c_str(),curlArgs);
  273. ::exit(-1); // only reached if execv() fails
  274. }
  275. }
  276. inline void cancel()
  277. {
  278. {
  279. Mutex::Lock _l(_cancelled_m);
  280. _cancelled = true;
  281. if (_pid > 0)
  282. ::kill(_pid,SIGKILL);
  283. }
  284. Thread::join(_myThread);
  285. }
  286. private:
  287. inline void _doH(void *arg,int code,const std::string &url,const std::string &body)
  288. {
  289. Mutex::Lock _l(_cancelled_m);
  290. try {
  291. if ((!_cancelled)&&(_handler))
  292. _handler(arg,code,url,body);
  293. } catch ( ... ) {}
  294. }
  295. const std::string _url;
  296. std::string _body;
  297. std::map<std::string,std::string> _headers;
  298. unsigned int _timeout;
  299. void (*_handler)(void *,int,const std::string &,const std::string &);
  300. void *_arg;
  301. HttpClient *_parent;
  302. long _pid;
  303. volatile bool _cancelled;
  304. Mutex _cancelled_m;
  305. Thread _myThread;
  306. };
  307. #endif // __UNIX_LIKE__
  308. #ifdef __WINDOWS__
  309. #define WIN_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  310. // Internal private thread class that performs request, notifies handler,
  311. // and then commits suicide by deleting itself.
  312. class HttpClient_Private_Request : NonCopyable
  313. {
  314. public:
  315. HttpClient_Private_Request(HttpClient *parent,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 &,const std::string &),void *arg) :
  316. _url(url),
  317. _headers(headers),
  318. _timeout(timeout),
  319. _handler(handler),
  320. _arg(arg),
  321. _parent(parent),
  322. _hRequest((HINTERNET)0)
  323. {
  324. _myThread = Thread::start(this);
  325. }
  326. ~HttpClient_Private_Request()
  327. {
  328. Mutex::Lock _l(_parent->_requests_m);
  329. _parent->_requests.erase((HttpClient::Request)this);
  330. }
  331. void threadMain()
  332. {
  333. HINTERNET hSession = (HINTERNET)0;
  334. HINTERNET hConnect = (HINTERNET)0;
  335. HINTERNET hRequest = (HINTERNET)0;
  336. try {
  337. hSession = WinHttpOpen(L"ZeroTier One HttpClient/1.0 (WinHttp)",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  338. if (!hSession) {
  339. _handler(_arg,-1,_url,"WinHttpOpen() failed");
  340. goto closeAndReturnFromHttp;
  341. }
  342. int timeoutMs = (int)_timeout * 1000;
  343. WinHttpSetTimeouts(hSession,timeoutMs,timeoutMs,timeoutMs,timeoutMs);
  344. std::wstring_convert< std::codecvt_utf8<wchar_t> > wcconv;
  345. std::wstring wurl(wcconv.from_bytes(_url));
  346. URL_COMPONENTS uc;
  347. memset(&uc,0,sizeof(uc));
  348. uc.dwStructSize = sizeof(uc);
  349. uc.dwSchemeLength = -1;
  350. uc.dwHostNameLength = -1;
  351. uc.dwUrlPathLength = -1;
  352. uc.dwExtraInfoLength = -1;
  353. if (!WinHttpCrackUrl(wurl.c_str(),(DWORD)wurl.length(),0,&uc)) {
  354. _handler(_arg,-1,_url,"unable to parse URL: WinHttpCrackUrl() failed");
  355. goto closeAndReturnFromHttp;
  356. }
  357. if ((!uc.lpszHostName)||(!uc.lpszUrlPath)||(!uc.lpszScheme)||(uc.dwHostNameLength <= 0)||(uc.dwUrlPathLength <= 0)||(uc.dwSchemeLength <= 0)) {
  358. _handler(_arg,-1,_url,"unable to parse URL: missing scheme, host name, or path");
  359. goto closeAndReturnFromHttp;
  360. }
  361. std::wstring urlScheme(uc.lpszScheme,uc.dwSchemeLength);
  362. std::wstring urlHostName(uc.lpszHostName,uc.dwHostNameLength);
  363. std::wstring urlPath(uc.lpszUrlPath,uc.dwUrlPathLength);
  364. if ((uc.lpszExtraInfo)&&(uc.dwExtraInfoLength > 0))
  365. urlPath.append(uc.lpszExtraInfo,uc.dwExtraInfoLength);
  366. if (urlScheme != L"http") {
  367. _handler(_arg,-1,_url,"only 'http' scheme is supported");
  368. goto closeAndReturnFromHttp;
  369. }
  370. hConnect = WinHttpConnect(hSession,urlHostName.c_str(),((uc.nPort > 0) ? uc.nPort : 80),0);
  371. if (!hConnect) {
  372. _handler(_arg,-1,_url,"connection failed");
  373. goto closeAndReturnFromHttp;
  374. }
  375. {
  376. Mutex::Lock _rl(_hRequest_m);
  377. _hRequest = WinHttpOpenRequest(hConnect,L"GET",urlPath.c_str(),NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
  378. if (!_hRequest) {
  379. _handler(_arg,-1,_url,"error sending request (1)");
  380. goto closeAndReturnFromHttp;
  381. }
  382. if (!WinHttpSendRequest(_hRequest,WINHTTP_NO_ADDITIONAL_HEADERS,0,WINHTTP_NO_REQUEST_DATA,0,0,0)) {
  383. _handler(_arg,-1,_url,"error sending request (2)");
  384. goto closeAndReturnFromHttp;
  385. }
  386. hRequest = _hRequest;
  387. }
  388. if (WinHttpReceiveResponse(hRequest,NULL)) {
  389. DWORD dwStatusCode = 0;
  390. DWORD dwTmp = sizeof(dwStatusCode);
  391. WinHttpQueryHeaders(hRequest,WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,NULL,&dwStatusCode,&dwTmp,NULL);
  392. DWORD dwSize;
  393. do {
  394. dwSize = 0;
  395. if (!WinHttpQueryDataAvailable(hRequest,&dwSize)) {
  396. _handler(_arg,-1,_url,"receive error (1)");
  397. goto closeAndReturnFromHttp;
  398. }
  399. {
  400. Mutex::Lock _rl(_hRequest_m);
  401. if (!_hRequest) {
  402. _handler(_arg,-1,_url,"request cancelled");
  403. goto closeAndReturnFromHttp;
  404. }
  405. }
  406. char *outBuffer = new char[dwSize];
  407. DWORD dwRead = 0;
  408. if (!WinHttpReadData(hRequest,(LPVOID)outBuffer,dwSize,&dwRead)) {
  409. _handler(_arg,-1,_url,"receive error (2)");
  410. goto closeAndReturnFromHttp;
  411. }
  412. {
  413. Mutex::Lock _rl(_hRequest_m);
  414. if (!_hRequest) {
  415. _handler(_arg,-1,_url,"request cancelled");
  416. goto closeAndReturnFromHttp;
  417. }
  418. _body.append(outBuffer,dwRead);
  419. delete [] outBuffer;
  420. if (_body.length() > WIN_MAX_MESSAGE_LENGTH) {
  421. _handler(_arg,-1,_url,"result too large");
  422. goto closeAndReturnFromHttp;
  423. }
  424. }
  425. } while ((dwSize > 0)&&(_hRequest));
  426. {
  427. Mutex::Lock _rl(_hRequest_m);
  428. if (!_hRequest) {
  429. _handler(_arg,-1,_url,"request cancelled");
  430. goto closeAndReturnFromHttp;
  431. }
  432. _handler(_arg,dwStatusCode,_url,_body);
  433. }
  434. } else {
  435. _handler(_arg,-1,_url,"receive response failed");
  436. }
  437. } catch ( ... ) {
  438. _handler(_arg,-1,_url,"unexpected exception");
  439. }
  440. closeAndReturnFromHttp:
  441. {
  442. Mutex::Lock _rl(_hRequest_m);
  443. if (_hRequest) {
  444. WinHttpCloseHandle(_hRequest);
  445. _hRequest = (HINTERNET)0;
  446. }
  447. }
  448. if (hConnect)
  449. WinHttpCloseHandle(hConnect);
  450. if (hSession)
  451. WinHttpCloseHandle(hSession);
  452. delete this;
  453. return;
  454. }
  455. inline void cancel()
  456. {
  457. Mutex::Lock _rl(_hRequest_m);
  458. if (_hRequest) {
  459. WinHttpCloseHandle(_hRequest);
  460. _hRequest = (HINTERNET)0;
  461. }
  462. }
  463. const std::string _url;
  464. std::string _body;
  465. std::map<std::string,std::string> _headers;
  466. unsigned int _timeout;
  467. void (*_handler)(void *,int,const std::string &,const std::string &);
  468. void *_arg;
  469. HttpClient *_parent;
  470. HINTERNET _hRequest;
  471. Mutex _hRequest_m;
  472. Thread _myThread;
  473. };
  474. #endif // __WINDOWS__
  475. const std::map<std::string,std::string> HttpClient::NO_HEADERS;
  476. HttpClient::HttpClient()
  477. {
  478. }
  479. HttpClient::~HttpClient()
  480. {
  481. std::set<Request> reqs;
  482. {
  483. Mutex::Lock _l(_requests_m);
  484. reqs = _requests;
  485. }
  486. for(std::set<Request>::iterator r(reqs.begin());r!=reqs.end();++r)
  487. this->cancel(*r);
  488. for(;;) {
  489. _requests_m.lock();
  490. if (_requests.empty()) {
  491. _requests_m.unlock();
  492. break;
  493. } else {
  494. _requests_m.unlock();
  495. Thread::sleep(250);
  496. }
  497. }
  498. }
  499. void HttpClient::cancel(HttpClient::Request req)
  500. {
  501. Mutex::Lock _l(_requests_m);
  502. if (_requests.count(req) == 0)
  503. return;
  504. ((HttpClient_Private_Request *)req)->cancel();
  505. }
  506. HttpClient::Request HttpClient::_do(
  507. const char *method,
  508. const std::string &url,
  509. const std::map<std::string,std::string> &headers,
  510. unsigned int timeout,
  511. void (*handler)(void *,int,const std::string &,const std::string &),
  512. void *arg)
  513. {
  514. HttpClient::Request r = (HttpClient::Request)(new HttpClient_Private_Request(this,method,url,headers,timeout,handler,arg));
  515. Mutex::Lock _l(_requests_m);
  516. _requests.insert(r);
  517. return r;
  518. }
  519. } // namespace ZeroTier