HttpClient.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. int curlStdout[2];
  134. int curlStderr[2];
  135. ::pipe(curlStdout);
  136. ::pipe(curlStderr);
  137. _pid = (long)vfork();
  138. if (_pid < 0) {
  139. // fork() failed
  140. ::close(curlStdout[0]);
  141. ::close(curlStdout[1]);
  142. ::close(curlStderr[0]);
  143. ::close(curlStderr[1]);
  144. _doH(_arg,-1,_url,"unable to fork()");
  145. delete this;
  146. return;
  147. } else if (_pid > 0) {
  148. // fork() succeeded, in parent process
  149. ::close(curlStdout[1]);
  150. ::close(curlStderr[1]);
  151. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  152. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  153. int exitCode = -1;
  154. unsigned long long timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  155. bool timedOut = false;
  156. bool tooLong = false;
  157. for(;;) {
  158. FD_ZERO(&readfds);
  159. FD_ZERO(&writefds);
  160. FD_ZERO(&errfds);
  161. FD_SET(curlStdout[0],&readfds);
  162. FD_SET(curlStderr[0],&readfds);
  163. FD_SET(curlStdout[0],&errfds);
  164. FD_SET(curlStderr[0],&errfds);
  165. tv.tv_sec = 1;
  166. tv.tv_usec = 0;
  167. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  168. if (FD_ISSET(curlStdout[0],&readfds)) {
  169. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  170. if (n > 0) {
  171. _body.append(buf,n);
  172. // Reset timeout when data is read...
  173. timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  174. } else if (n < 0)
  175. break;
  176. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  177. ::kill(_pid,SIGKILL);
  178. tooLong = true;
  179. break;
  180. }
  181. }
  182. if (FD_ISSET(curlStderr[0],&readfds))
  183. ::read(curlStderr[0],buf,sizeof(buf));
  184. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  185. break;
  186. if (Utils::now() >= timesOutAt) {
  187. ::kill(_pid,SIGKILL);
  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. waitpid(_pid,&exitCode,0);
  211. _pid = 0;
  212. ::close(curlStdout[0]);
  213. ::close(curlStderr[0]);
  214. if (timedOut)
  215. _doH(_arg,-1,_url,"connection timed out");
  216. else if (tooLong)
  217. _doH(_arg,-1,_url,"response too long");
  218. else if (exitCode)
  219. _doH(_arg,-1,_url,"connection failed (curl returned non-zero exit code)");
  220. else {
  221. unsigned long idx = 0;
  222. // Grab status line and headers, which will prefix output on
  223. // success and will end with an empty line.
  224. std::vector<std::string> headers;
  225. headers.push_back(std::string());
  226. while (idx < _body.length()) {
  227. char c = _body[idx++];
  228. if (c == '\n') {
  229. if (!headers.back().length()) {
  230. headers.pop_back();
  231. break;
  232. } else headers.push_back(std::string());
  233. } else if (c != '\r')
  234. headers.back().push_back(c);
  235. }
  236. if (headers.empty()||(!headers.front().length())) {
  237. _doH(_arg,-1,_url,"HTTP response empty");
  238. delete this;
  239. return;
  240. }
  241. // Parse first line -- HTTP status code and response
  242. size_t scPos = headers.front().find(' ');
  243. if (scPos == std::string::npos) {
  244. _doH(_arg,-1,_url,"invalid HTTP response (no status line)");
  245. delete this;
  246. return;
  247. }
  248. ++scPos;
  249. unsigned int rcode = Utils::strToUInt(headers.front().substr(scPos,3).c_str());
  250. if ((!rcode)||(rcode > 999)) {
  251. _doH(_arg,-1,_url,"invalid HTTP response (invalid response code)");
  252. delete this;
  253. return;
  254. }
  255. // Serve up the resulting data to the handler
  256. if (rcode == 200)
  257. _doH(_arg,rcode,_url,_body.substr(idx));
  258. else if ((scPos + 4) < headers.front().length())
  259. _doH(_arg,rcode,_url,headers.front().substr(scPos+4));
  260. else _doH(_arg,rcode,_url,"(no status message from server)");
  261. }
  262. delete this;
  263. return;
  264. } else {
  265. // fork() succeeded, in child process
  266. ::dup2(curlStdout[1],STDOUT_FILENO);
  267. ::close(curlStdout[1]);
  268. ::dup2(curlStderr[1],STDERR_FILENO);
  269. ::close(curlStderr[1]);
  270. ::execv(curlPath.c_str(),curlArgs);
  271. ::exit(-1); // only reached if execv() fails
  272. }
  273. }
  274. inline void cancel()
  275. {
  276. {
  277. Mutex::Lock _l(_cancelled_m);
  278. _cancelled = true;
  279. if (_pid > 0)
  280. ::kill(_pid,SIGKILL);
  281. }
  282. Thread::join(_myThread);
  283. }
  284. private:
  285. inline void _doH(void *arg,int code,const std::string &url,const std::string &body)
  286. {
  287. Mutex::Lock _l(_cancelled_m);
  288. try {
  289. if ((!_cancelled)&&(_handler))
  290. _handler(arg,code,url,body);
  291. } catch ( ... ) {}
  292. }
  293. const std::string _url;
  294. std::string _body;
  295. std::map<std::string,std::string> _headers;
  296. unsigned int _timeout;
  297. void (*_handler)(void *,int,const std::string &,const std::string &);
  298. void *_arg;
  299. HttpClient *_parent;
  300. long _pid;
  301. volatile bool _cancelled;
  302. Mutex _cancelled_m;
  303. Thread _myThread;
  304. };
  305. #endif // __UNIX_LIKE__
  306. #ifdef __WINDOWS__
  307. #define WIN_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  308. // Internal private thread class that performs request, notifies handler,
  309. // and then commits suicide by deleting itself.
  310. class HttpClient_Private_Request : NonCopyable
  311. {
  312. public:
  313. 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) :
  314. _url(url),
  315. _headers(headers),
  316. _timeout(timeout),
  317. _handler(handler),
  318. _arg(arg)
  319. {
  320. _myThread = Thread::start(this);
  321. }
  322. void threadMain()
  323. {
  324. HINTERNET hSession = (HINTERNET)0;
  325. HINTERNET hConnect = (HINTERNET)0;
  326. HINTERNET hRequest = (HINTERNET)0;
  327. try {
  328. hSession = WinHttpOpen(L"ZeroTier One HttpClient/1.0",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  329. if (!hSession) {
  330. _handler(_arg,-1,_url,false,"WinHttpOpen() failed");
  331. goto closeAndReturnFromHttp;
  332. }
  333. int timeoutMs = (int)_timeout * 1000;
  334. WinHttpSetTimeouts(hSession,timeoutMs,timeoutMs,timeoutMs,timeoutMs);
  335. std::wstring_convert< std::codecvt_utf8<wchar_t> > wcconv;
  336. std::wstring wurl(wcconv.from_bytes(_url));
  337. URL_COMPONENTS uc;
  338. memset(&uc,0,sizeof(uc));
  339. uc.dwStructSize = sizeof(uc);
  340. uc.dwSchemeLength = -1;
  341. uc.dwHostNameLength = -1;
  342. uc.dwUrlPathLength = -1;
  343. uc.dwExtraInfoLength = -1;
  344. if (!WinHttpCrackUrl(wurl.c_str(),(DWORD)wurl.length(),0,&uc)) {
  345. _handler(_arg,-1,_url,false,"unable to parse URL: WinHttpCrackUrl() failed");
  346. goto closeAndReturnFromHttp;
  347. }
  348. if ((!uc.lpszHostName)||(!uc.lpszUrlPath)||(!uc.lpszScheme)||(uc.dwHostNameLength <= 0)||(uc.dwUrlPathLength <= 0)||(uc.dwSchemeLength <= 0)) {
  349. _handler(_arg,-1,_url,false,"unable to parse URL: missing scheme, host name, or path");
  350. goto closeAndReturnFromHttp;
  351. }
  352. std::wstring urlScheme(uc.lpszScheme,uc.dwSchemeLength);
  353. std::wstring urlHostName(uc.lpszHostName,uc.dwHostNameLength);
  354. std::wstring urlPath(uc.lpszUrlPath,uc.dwUrlPathLength);
  355. if ((uc.lpszExtraInfo)&&(uc.dwExtraInfoLength > 0))
  356. urlPath.append(uc.lpszExtraInfo,uc.dwExtraInfoLength);
  357. if (urlScheme != L"http") {
  358. _handler(_arg,-1,_url,false,"only 'http' scheme is supported");
  359. goto closeAndReturnFromHttp;
  360. }
  361. hConnect = WinHttpConnect(hSession,urlHostName.c_str(),((uc.nPort > 0) ? uc.nPort : 80),0);
  362. if (!hConnect) {
  363. _handler(_arg,-1,_url,false,"connection failed");
  364. goto closeAndReturnFromHttp;
  365. }
  366. hRequest = WinHttpOpenRequest(hConnect,L"GET",urlPath.c_str(),NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
  367. if (!hRequest) {
  368. _handler(_arg,-1,_url,false,"error sending request (1)");
  369. goto closeAndReturnFromHttp;
  370. }
  371. if (!WinHttpSendRequest(hRequest,WINHTTP_NO_ADDITIONAL_HEADERS,0,WINHTTP_NO_REQUEST_DATA,0,0,0)) {
  372. _handler(_arg,-1,_url,false,"error sending request (2)");
  373. goto closeAndReturnFromHttp;
  374. }
  375. if (WinHttpReceiveResponse(hRequest,NULL)) {
  376. DWORD dwStatusCode = 0;
  377. DWORD dwTmp = sizeof(dwStatusCode);
  378. WinHttpQueryHeaders(hRequest,WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,NULL,&dwStatusCode,&dwTmp,NULL);
  379. DWORD dwSize;
  380. do {
  381. dwSize = 0;
  382. if (!WinHttpQueryDataAvailable(hRequest,&dwSize)) {
  383. _handler(_arg,-1,_url,false,"receive error (1)");
  384. goto closeAndReturnFromHttp;
  385. }
  386. char *outBuffer = new char[dwSize];
  387. DWORD dwRead = 0;
  388. if (!WinHttpReadData(hRequest,(LPVOID)outBuffer,dwSize,&dwRead)) {
  389. _handler(_arg,-1,_url,false,"receive error (2)");
  390. goto closeAndReturnFromHttp;
  391. }
  392. _body.append(outBuffer,dwRead);
  393. delete [] outBuffer;
  394. if (_body.length() > WIN_MAX_MESSAGE_LENGTH) {
  395. _handler(_arg,-1,_url,false,"result too large");
  396. goto closeAndReturnFromHttp;
  397. }
  398. } while (dwSize > 0);
  399. _handler(_arg,dwStatusCode,_url,false,_body);
  400. } else {
  401. _handler(_arg,-1,_url,false,"receive response failed");
  402. }
  403. } catch (std::bad_alloc &exc) {
  404. _handler(_arg,-1,_url,false,"insufficient memory");
  405. } catch ( ... ) {
  406. _handler(_arg,-1,_url,false,"unexpected exception");
  407. }
  408. closeAndReturnFromHttp:
  409. if (hRequest)
  410. WinHttpCloseHandle(hRequest);
  411. if (hConnect)
  412. WinHttpCloseHandle(hConnect);
  413. if (hSession)
  414. WinHttpCloseHandle(hSession);
  415. delete this;
  416. return;
  417. }
  418. const std::string _url;
  419. std::string _body;
  420. std::map<std::string,std::string> _headers;
  421. unsigned int _timeout;
  422. void (*_handler)(void *,int,const std::string &,const std::string &);
  423. void *_arg;
  424. Thread _myThread;
  425. };
  426. #endif // __WINDOWS__
  427. const std::map<std::string,std::string> HttpClient::NO_HEADERS;
  428. HttpClient::HttpClient()
  429. {
  430. }
  431. HttpClient::~HttpClient()
  432. {
  433. std::set<Request> reqs;
  434. {
  435. Mutex::Lock _l(_requests_m);
  436. reqs = _requests;
  437. }
  438. for(std::set<Request>::iterator r(reqs.begin());r!=reqs.end();++r)
  439. this->cancel(*r);
  440. }
  441. void HttpClient::cancel(HttpClient::Request req)
  442. {
  443. {
  444. Mutex::Lock _l(_requests_m);
  445. if (_requests.count(req) == 0)
  446. return;
  447. }
  448. ((HttpClient_Private_Request *)req)->cancel();
  449. }
  450. HttpClient::Request HttpClient::_do(
  451. const char *method,
  452. const std::string &url,
  453. const std::map<std::string,std::string> &headers,
  454. unsigned int timeout,
  455. void (*handler)(void *,int,const std::string &,const std::string &),
  456. void *arg)
  457. {
  458. HttpClient::Request r = (HttpClient::Request)(new HttpClient_Private_Request(this,method,url,headers,timeout,handler,arg));
  459. Mutex::Lock _l(_requests_m);
  460. _requests.insert(r);
  461. return r;
  462. }
  463. } // namespace ZeroTier