HttpClient.cpp 16 KB

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