HttpClient.cpp 16 KB

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