HttpClient.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 "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(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. {
  324. _myThread = Thread::start(this);
  325. }
  326. void threadMain()
  327. {
  328. HINTERNET hSession = (HINTERNET)0;
  329. HINTERNET hConnect = (HINTERNET)0;
  330. HINTERNET hRequest = (HINTERNET)0;
  331. try {
  332. hSession = WinHttpOpen(L"ZeroTier One HttpClient/1.0",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  333. if (!hSession) {
  334. _handler(_arg,-1,_url,false,"WinHttpOpen() failed");
  335. goto closeAndReturnFromHttp;
  336. }
  337. int timeoutMs = (int)_timeout * 1000;
  338. WinHttpSetTimeouts(hSession,timeoutMs,timeoutMs,timeoutMs,timeoutMs);
  339. std::wstring_convert< std::codecvt_utf8<wchar_t> > wcconv;
  340. std::wstring wurl(wcconv.from_bytes(_url));
  341. URL_COMPONENTS uc;
  342. memset(&uc,0,sizeof(uc));
  343. uc.dwStructSize = sizeof(uc);
  344. uc.dwSchemeLength = -1;
  345. uc.dwHostNameLength = -1;
  346. uc.dwUrlPathLength = -1;
  347. uc.dwExtraInfoLength = -1;
  348. if (!WinHttpCrackUrl(wurl.c_str(),(DWORD)wurl.length(),0,&uc)) {
  349. _handler(_arg,-1,_url,false,"unable to parse URL: WinHttpCrackUrl() failed");
  350. goto closeAndReturnFromHttp;
  351. }
  352. if ((!uc.lpszHostName)||(!uc.lpszUrlPath)||(!uc.lpszScheme)||(uc.dwHostNameLength <= 0)||(uc.dwUrlPathLength <= 0)||(uc.dwSchemeLength <= 0)) {
  353. _handler(_arg,-1,_url,false,"unable to parse URL: missing scheme, host name, or path");
  354. goto closeAndReturnFromHttp;
  355. }
  356. std::wstring urlScheme(uc.lpszScheme,uc.dwSchemeLength);
  357. std::wstring urlHostName(uc.lpszHostName,uc.dwHostNameLength);
  358. std::wstring urlPath(uc.lpszUrlPath,uc.dwUrlPathLength);
  359. if ((uc.lpszExtraInfo)&&(uc.dwExtraInfoLength > 0))
  360. urlPath.append(uc.lpszExtraInfo,uc.dwExtraInfoLength);
  361. if (urlScheme != L"http") {
  362. _handler(_arg,-1,_url,false,"only 'http' scheme is supported");
  363. goto closeAndReturnFromHttp;
  364. }
  365. hConnect = WinHttpConnect(hSession,urlHostName.c_str(),((uc.nPort > 0) ? uc.nPort : 80),0);
  366. if (!hConnect) {
  367. _handler(_arg,-1,_url,false,"connection failed");
  368. goto closeAndReturnFromHttp;
  369. }
  370. hRequest = WinHttpOpenRequest(hConnect,L"GET",urlPath.c_str(),NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
  371. if (!hRequest) {
  372. _handler(_arg,-1,_url,false,"error sending request (1)");
  373. goto closeAndReturnFromHttp;
  374. }
  375. if (!WinHttpSendRequest(hRequest,WINHTTP_NO_ADDITIONAL_HEADERS,0,WINHTTP_NO_REQUEST_DATA,0,0,0)) {
  376. _handler(_arg,-1,_url,false,"error sending request (2)");
  377. goto closeAndReturnFromHttp;
  378. }
  379. if (WinHttpReceiveResponse(hRequest,NULL)) {
  380. DWORD dwStatusCode = 0;
  381. DWORD dwTmp = sizeof(dwStatusCode);
  382. WinHttpQueryHeaders(hRequest,WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,NULL,&dwStatusCode,&dwTmp,NULL);
  383. DWORD dwSize;
  384. do {
  385. dwSize = 0;
  386. if (!WinHttpQueryDataAvailable(hRequest,&dwSize)) {
  387. _handler(_arg,-1,_url,false,"receive error (1)");
  388. goto closeAndReturnFromHttp;
  389. }
  390. char *outBuffer = new char[dwSize];
  391. DWORD dwRead = 0;
  392. if (!WinHttpReadData(hRequest,(LPVOID)outBuffer,dwSize,&dwRead)) {
  393. _handler(_arg,-1,_url,false,"receive error (2)");
  394. goto closeAndReturnFromHttp;
  395. }
  396. _body.append(outBuffer,dwRead);
  397. delete [] outBuffer;
  398. if (_body.length() > WIN_MAX_MESSAGE_LENGTH) {
  399. _handler(_arg,-1,_url,false,"result too large");
  400. goto closeAndReturnFromHttp;
  401. }
  402. } while (dwSize > 0);
  403. _handler(_arg,dwStatusCode,_url,false,_body);
  404. } else {
  405. _handler(_arg,-1,_url,false,"receive response failed");
  406. }
  407. } catch (std::bad_alloc &exc) {
  408. _handler(_arg,-1,_url,false,"insufficient memory");
  409. } catch ( ... ) {
  410. _handler(_arg,-1,_url,false,"unexpected exception");
  411. }
  412. closeAndReturnFromHttp:
  413. if (hRequest)
  414. WinHttpCloseHandle(hRequest);
  415. if (hConnect)
  416. WinHttpCloseHandle(hConnect);
  417. if (hSession)
  418. WinHttpCloseHandle(hSession);
  419. delete this;
  420. return;
  421. }
  422. const std::string _url;
  423. std::string _body;
  424. std::map<std::string,std::string> _headers;
  425. unsigned int _timeout;
  426. void (*_handler)(void *,int,const std::string &,const std::string &);
  427. void *_arg;
  428. Thread _myThread;
  429. };
  430. #endif // __WINDOWS__
  431. const std::map<std::string,std::string> HttpClient::NO_HEADERS;
  432. HttpClient::HttpClient()
  433. {
  434. }
  435. HttpClient::~HttpClient()
  436. {
  437. std::set<Request> reqs;
  438. {
  439. Mutex::Lock _l(_requests_m);
  440. reqs = _requests;
  441. }
  442. for(std::set<Request>::iterator r(reqs.begin());r!=reqs.end();++r)
  443. this->cancel(*r);
  444. for(;;) {
  445. _requests_m.lock();
  446. if (_requests.empty()) {
  447. _requests_m.unlock();
  448. break;
  449. } else {
  450. _requests_m.unlock();
  451. Thread::sleep(250);
  452. }
  453. }
  454. }
  455. void HttpClient::cancel(HttpClient::Request req)
  456. {
  457. Mutex::Lock _l(_requests_m);
  458. if (_requests.count(req) == 0)
  459. return;
  460. ((HttpClient_Private_Request *)req)->cancel();
  461. }
  462. HttpClient::Request HttpClient::_do(
  463. const char *method,
  464. const std::string &url,
  465. const 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. {
  470. HttpClient::Request r = (HttpClient::Request)(new HttpClient_Private_Request(this,method,url,headers,timeout,handler,arg));
  471. Mutex::Lock _l(_requests_m);
  472. _requests.insert(r);
  473. return r;
  474. }
  475. } // namespace ZeroTier