HttpClient.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 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. #ifdef __WINDOWS__
  29. #include <WinSock2.h>
  30. #include <Windows.h>
  31. #include <winhttp.h>
  32. #include <locale>
  33. #include <codecvt>
  34. #endif
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  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
  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. const std::map<std::string,std::string> HttpClient::NO_HEADERS;
  58. #ifdef __UNIX_LIKE__
  59. // The *nix implementation calls 'curl' externally rather than linking to it.
  60. // This makes it an optional dependency that can be avoided in tiny systems
  61. // provided you don't want to have automatic software updates... or want to
  62. // do them via another method.
  63. #ifdef __APPLE__
  64. // TODO: get proxy configuration
  65. #endif
  66. // Paths where "curl" may be found on the system
  67. #define NUM_CURL_PATHS 5
  68. static const char *CURL_PATHS[NUM_CURL_PATHS] = { "/usr/bin/curl","/bin/curl","/usr/local/bin/curl","/usr/sbin/curl","/sbin/curl" };
  69. // Maximum message length
  70. #define CURL_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  71. // Internal private thread class that performs request, notifies handler,
  72. // and then commits suicide by deleting itself.
  73. class P_Req : NonCopyable
  74. {
  75. public:
  76. P_Req(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 &,bool,const std::string &),void *arg) :
  77. _url(url),
  78. _headers(headers),
  79. _timeout(timeout),
  80. _handler(handler),
  81. _arg(arg)
  82. {
  83. _myThread = Thread::start(this);
  84. }
  85. void threadMain()
  86. {
  87. char *curlArgs[1024];
  88. char buf[16384];
  89. fd_set readfds,writefds,errfds;
  90. struct timeval tv;
  91. std::string curlPath;
  92. for(int i=0;i<NUM_CURL_PATHS;++i) {
  93. if (Utils::fileExists(CURL_PATHS[i])) {
  94. curlPath = CURL_PATHS[i];
  95. break;
  96. }
  97. }
  98. if (!curlPath.length()) {
  99. _handler(_arg,-1,_url,false,"unable to locate 'curl' binary in /usr/bin, /bin, /usr/local/bin, /usr/sbin, or /sbin");
  100. delete this;
  101. return;
  102. }
  103. if (!_url.length()) {
  104. _handler(_arg,-1,_url,false,"cannot fetch empty URL");
  105. delete this;
  106. return;
  107. }
  108. curlArgs[0] = const_cast <char *>(curlPath.c_str());
  109. curlArgs[1] = const_cast <char *>("-D");
  110. curlArgs[2] = const_cast <char *>("-"); // append headers before output
  111. int argPtr = 3;
  112. std::vector<std::string> headerArgs;
  113. for(std::map<std::string,std::string>::const_iterator h(_headers.begin());h!=_headers.end();++h) {
  114. headerArgs.push_back(h->first);
  115. headerArgs.back().append(": ");
  116. headerArgs.back().append(h->second);
  117. }
  118. for(std::vector<std::string>::iterator h(headerArgs.begin());h!=headerArgs.end();++h) {
  119. if (argPtr >= (1024 - 4)) // leave room for terminating NULL and URL
  120. break;
  121. curlArgs[argPtr++] = const_cast <char *>("-H");
  122. curlArgs[argPtr++] = const_cast <char *>(h->c_str());
  123. }
  124. curlArgs[argPtr++] = const_cast <char *>(_url.c_str());
  125. curlArgs[argPtr] = (char *)0;
  126. int curlStdout[2];
  127. int curlStderr[2];
  128. ::pipe(curlStdout);
  129. ::pipe(curlStderr);
  130. long pid = (long)vfork();
  131. if (pid < 0) {
  132. // fork() failed
  133. ::close(curlStdout[0]);
  134. ::close(curlStdout[1]);
  135. ::close(curlStderr[0]);
  136. ::close(curlStderr[1]);
  137. _handler(_arg,-1,_url,false,"unable to fork()");
  138. delete this;
  139. return;
  140. } else if (pid > 0) {
  141. // fork() succeeded, in parent process
  142. ::close(curlStdout[1]);
  143. ::close(curlStderr[1]);
  144. fcntl(curlStdout[0],F_SETFL,O_NONBLOCK);
  145. fcntl(curlStderr[0],F_SETFL,O_NONBLOCK);
  146. int exitCode = -1;
  147. unsigned long long timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  148. bool timedOut = false;
  149. bool tooLong = false;
  150. for(;;) {
  151. FD_ZERO(&readfds);
  152. FD_ZERO(&writefds);
  153. FD_ZERO(&errfds);
  154. FD_SET(curlStdout[0],&readfds);
  155. FD_SET(curlStderr[0],&readfds);
  156. FD_SET(curlStdout[0],&errfds);
  157. FD_SET(curlStderr[0],&errfds);
  158. tv.tv_sec = 1;
  159. tv.tv_usec = 0;
  160. select(std::max(curlStdout[0],curlStderr[0])+1,&readfds,&writefds,&errfds,&tv);
  161. if (FD_ISSET(curlStdout[0],&readfds)) {
  162. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  163. if (n > 0) {
  164. _body.append(buf,n);
  165. // Reset timeout when data is read...
  166. timesOutAt = Utils::now() + ((unsigned long long)_timeout * 1000ULL);
  167. } else if (n < 0)
  168. break;
  169. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  170. ::kill(pid,SIGKILL);
  171. tooLong = true;
  172. break;
  173. }
  174. }
  175. if (FD_ISSET(curlStderr[0],&readfds))
  176. ::read(curlStderr[0],buf,sizeof(buf));
  177. if (FD_ISSET(curlStdout[0],&errfds)||FD_ISSET(curlStderr[0],&errfds))
  178. break;
  179. if (Utils::now() >= timesOutAt) {
  180. ::kill(pid,SIGKILL);
  181. timedOut = true;
  182. break;
  183. }
  184. if (waitpid(pid,&exitCode,WNOHANG) > 0) {
  185. for(;;) {
  186. // Drain output...
  187. int n = (int)::read(curlStdout[0],buf,sizeof(buf));
  188. if (n <= 0)
  189. break;
  190. else {
  191. _body.append(buf,n);
  192. if (_body.length() > CURL_MAX_MESSAGE_LENGTH) {
  193. tooLong = true;
  194. break;
  195. }
  196. }
  197. }
  198. pid = 0;
  199. break;
  200. }
  201. }
  202. if (pid > 0)
  203. waitpid(pid,&exitCode,0);
  204. ::close(curlStdout[0]);
  205. ::close(curlStderr[0]);
  206. if (timedOut)
  207. _handler(_arg,-1,_url,false,"connection timed out");
  208. else if (tooLong)
  209. _handler(_arg,-1,_url,false,"response too long");
  210. else if (exitCode)
  211. _handler(_arg,-1,_url,false,"connection failed (curl returned non-zero exit code)");
  212. else {
  213. unsigned long idx = 0;
  214. // Grab status line and headers, which will prefix output on
  215. // success and will end with an empty line.
  216. std::vector<std::string> headers;
  217. headers.push_back(std::string());
  218. while (idx < _body.length()) {
  219. char c = _body[idx++];
  220. if (c == '\n') {
  221. if (!headers.back().length()) {
  222. headers.pop_back();
  223. break;
  224. } else headers.push_back(std::string());
  225. } else if (c != '\r')
  226. headers.back().push_back(c);
  227. }
  228. if (headers.empty()||(!headers.front().length())) {
  229. _handler(_arg,-1,_url,false,"HTTP response empty");
  230. delete this;
  231. return;
  232. }
  233. // Parse first line -- HTTP status code and response
  234. size_t scPos = headers.front().find(' ');
  235. if (scPos == std::string::npos) {
  236. _handler(_arg,-1,_url,false,"invalid HTTP response (no status line)");
  237. delete this;
  238. return;
  239. }
  240. ++scPos;
  241. unsigned int rcode = Utils::strToUInt(headers.front().substr(scPos,3).c_str());
  242. if ((!rcode)||(rcode > 999)) {
  243. _handler(_arg,-1,_url,false,"invalid HTTP response (invalid response code)");
  244. delete this;
  245. return;
  246. }
  247. // Serve up the resulting data to the handler
  248. if (rcode == 200)
  249. _handler(_arg,rcode,_url,false,_body.substr(idx));
  250. else if ((scPos + 4) < headers.front().length())
  251. _handler(_arg,rcode,_url,false,headers.front().substr(scPos+4));
  252. else _handler(_arg,rcode,_url,false,"(no status message from server)");
  253. }
  254. delete this;
  255. return;
  256. } else {
  257. // fork() succeeded, in child process
  258. ::dup2(curlStdout[1],STDOUT_FILENO);
  259. ::close(curlStdout[1]);
  260. ::dup2(curlStderr[1],STDERR_FILENO);
  261. ::close(curlStderr[1]);
  262. ::execv(curlPath.c_str(),curlArgs);
  263. ::exit(-1); // only reached if execv() fails
  264. }
  265. }
  266. const std::string _url;
  267. std::string _body;
  268. std::map<std::string,std::string> _headers;
  269. unsigned int _timeout;
  270. void (*_handler)(void *,int,const std::string &,bool,const std::string &);
  271. void *_arg;
  272. Thread _myThread;
  273. };
  274. HttpClient::Request HttpClient::_do(
  275. const char *method,
  276. const std::string &url,
  277. const std::map<std::string,std::string> &headers,
  278. unsigned int timeout,
  279. void (*handler)(void *,int,const std::string &,bool,const std::string &),
  280. void *arg)
  281. {
  282. return (HttpClient::Request)(new P_Req(method,url,headers,timeout,handler,arg));
  283. }
  284. #endif
  285. #ifdef __WINDOWS__
  286. #define WIN_MAX_MESSAGE_LENGTH (1024 * 1024 * 64)
  287. // Internal private thread class that performs request, notifies handler,
  288. // and then commits suicide by deleting itself.
  289. class P_Req : NonCopyable
  290. {
  291. public:
  292. P_Req(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 &,bool,const std::string &),void *arg) :
  293. _url(url),
  294. _headers(headers),
  295. _timeout(timeout),
  296. _handler(handler),
  297. _arg(arg)
  298. {
  299. _myThread = Thread::start(this);
  300. }
  301. void threadMain()
  302. {
  303. HINTERNET hSession = (HINTERNET)0;
  304. HINTERNET hConnect = (HINTERNET)0;
  305. HINTERNET hRequest = (HINTERNET)0;
  306. try {
  307. hSession = WinHttpOpen(L"ZeroTier One HttpClient/1.0",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
  308. if (!hSession) {
  309. _handler(_arg,-1,_url,false,"WinHttpOpen() failed");
  310. goto closeAndReturnFromHttp;
  311. }
  312. int timeoutMs = (int)_timeout * 1000;
  313. WinHttpSetTimeouts(hSession,timeoutMs,timeoutMs,timeoutMs,timeoutMs);
  314. std::wstring_convert< std::codecvt_utf8<wchar_t> > wcconv;
  315. std::wstring wurl(wcconv.from_bytes(_url));
  316. URL_COMPONENTS uc;
  317. memset(&uc,0,sizeof(uc));
  318. uc.dwStructSize = sizeof(uc);
  319. uc.dwSchemeLength = -1;
  320. uc.dwHostNameLength = -1;
  321. uc.dwUrlPathLength = -1;
  322. uc.dwExtraInfoLength = -1;
  323. if (!WinHttpCrackUrl(wurl.c_str(),wurl.length(),0,&uc)) {
  324. _handler(_arg,-1,_url,false,"unable to parse URL: WinHttpCrackUrl() failed");
  325. goto closeAndReturnFromHttp;
  326. }
  327. if ((!uc.lpszHostName)||(!uc.lpszUrlPath)||(!uc.lpszScheme)||(uc.dwHostNameLength <= 0)||(uc.dwUrlPathLength <= 0)||(uc.dwSchemeLength <= 0)) {
  328. _handler(_arg,-1,_url,false,"unable to parse URL: missing scheme, host name, or path");
  329. goto closeAndReturnFromHttp;
  330. }
  331. std::wstring urlScheme(uc.lpszScheme,uc.dwSchemeLength);
  332. std::wstring urlHostName(uc.lpszHostName,uc.dwHostNameLength);
  333. std::wstring urlPath(uc.lpszUrlPath,uc.dwUrlPathLength);
  334. if ((uc.lpszExtraInfo)&&(uc.dwExtraInfoLength > 0))
  335. urlPath.append(uc.lpszExtraInfo,uc.dwExtraInfoLength);
  336. if (urlScheme != L"http") {
  337. _handler(_arg,-1,_url,false,"only 'http' scheme is supported");
  338. goto closeAndReturnFromHttp;
  339. }
  340. hConnect = WinHttpConnect(hSession,urlHostName.c_str(),((uc.nPort > 0) ? uc.nPort : 80),0);
  341. if (!hConnect) {
  342. _handler(_arg,-1,_url,false,"connection failed");
  343. goto closeAndReturnFromHttp;
  344. }
  345. hRequest = WinHttpOpenRequest(hConnect,L"GET",NULL,NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
  346. if (!hRequest) {
  347. _handler(_arg,-1,_url,false,"error sending request");
  348. goto closeAndReturnFromHttp;
  349. }
  350. if (WinHttpReceiveResponse(hRequest,NULL)) {
  351. DWORD dwStatusCode = 0;
  352. DWORD dwTmp = sizeof(dwStatusCode);
  353. WinHttpQueryHeaders(hRequest,WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER,NULL,&dwStatusCode,&dwTmp,NULL);
  354. DWORD dwSize;
  355. do {
  356. dwSize = 0;
  357. if (!WinHttpQueryDataAvailable(hRequest,&dwSize)) {
  358. _handler(_arg,-1,_url,false,"receive error (1)");
  359. goto closeAndReturnFromHttp;
  360. }
  361. char *outBuffer = new char[dwSize];
  362. DWORD dwRead = 0;
  363. if (!WinHttpReadData(hRequest,(LPVOID)outBuffer,dwSize,&dwRead)) {
  364. _handler(_arg,-1,_url,false,"receive error (2)");
  365. goto closeAndReturnFromHttp;
  366. }
  367. _body.append(outBuffer,dwRead);
  368. delete [] outBuffer;
  369. if (_body.length() > WIN_MAX_MESSAGE_LENGTH) {
  370. _handler(_arg,-1,_url,false,"result too large");
  371. goto closeAndReturnFromHttp;
  372. }
  373. } while (dwSize > 0);
  374. _handler(_arg,dwStatusCode,_url,false,_body);
  375. }
  376. } catch (std::bad_alloc &exc) {
  377. _handler(_arg,-1,_url,false,"insufficient memory");
  378. } catch ( ... ) {
  379. _handler(_arg,-1,_url,false,"unexpected exception");
  380. }
  381. closeAndReturnFromHttp:
  382. if (hRequest)
  383. WinHttpCloseHandle(hRequest);
  384. if (hConnect)
  385. WinHttpCloseHandle(hConnect);
  386. if (hSession)
  387. WinHttpCloseHandle(hSession);
  388. delete this;
  389. return;
  390. }
  391. const std::string _url;
  392. std::string _body;
  393. std::map<std::string,std::string> _headers;
  394. unsigned int _timeout;
  395. void (*_handler)(void *,int,const std::string &,bool,const std::string &);
  396. void *_arg;
  397. Thread _myThread;
  398. };
  399. HttpClient::Request HttpClient::_do(
  400. const char *method,
  401. const std::string &url,
  402. const std::map<std::string,std::string> &headers,
  403. unsigned int timeout,
  404. void (*handler)(void *,int,const std::string &,bool,const std::string &),
  405. void *arg)
  406. {
  407. return (HttpClient::Request)(new P_Req(method,url,headers,timeout,handler,arg));
  408. }
  409. #endif
  410. } // namespace ZeroTier