Http.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <sys/types.h>
  32. #include <sys/socket.h>
  33. #include <netdb.h>
  34. #include <vector>
  35. #include <set>
  36. #include <list>
  37. #ifndef _WIN32
  38. #include <unistd.h>
  39. #endif
  40. #include "Http.hpp"
  41. #include "Utils.hpp"
  42. #include "InetAddress.hpp"
  43. static http_parser_settings _http_parser_settings;
  44. namespace ZeroTier {
  45. static bool _sendAll(int fd,const void *buf,unsigned int len)
  46. {
  47. for(;;) {
  48. int n = (int)::send(fd,buf,len,0);
  49. if ((n < 0)&&(errno == EINTR))
  50. continue;
  51. return (n == (int)len);
  52. }
  53. }
  54. const std::map<std::string,std::string> Http::EMPTY_HEADERS;
  55. Http::Request::Request(
  56. Http::Method m,
  57. const std::string &url,
  58. const std::map<std::string,std::string> &rh,
  59. const std::string &rb,
  60. bool (*handler)(Request *,void *,const std::string &,int,const std::map<std::string,std::string> &,const std::string &),
  61. void *arg) :
  62. _url(url),
  63. _requestHeaders(rh),
  64. _handler(handler),
  65. _arg(arg),
  66. _method(m),
  67. _fd(0)
  68. {
  69. _http_parser_settings.on_message_begin = &Http::Request::_http_on_message_begin;
  70. _http_parser_settings.on_url = &Http::Request::_http_on_url;
  71. _http_parser_settings.on_status_complete = &Http::Request::_http_on_status_complete;
  72. _http_parser_settings.on_header_field = &Http::Request::_http_on_header_field;
  73. _http_parser_settings.on_header_value = &Http::Request::_http_on_header_value;
  74. _http_parser_settings.on_headers_complete = &Http::Request::_http_on_headers_complete;
  75. _http_parser_settings.on_body = &Http::Request::_http_on_body;
  76. _http_parser_settings.on_message_complete = &Http::Request::_http_on_message_complete;
  77. start();
  78. }
  79. Http::Request::~Request()
  80. {
  81. if (_fd > 0)
  82. ::close(_fd);
  83. join();
  84. }
  85. void Http::Request::main()
  86. throw()
  87. {
  88. char buf[131072];
  89. try {
  90. http_parser_init(&_parser,HTTP_RESPONSE);
  91. _parser.data = this;
  92. http_parser_url urlParsed;
  93. if (http_parser_parse_url(_url.c_str(),_url.length(),0,&urlParsed)) {
  94. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL parse error");
  95. return;
  96. }
  97. if (!(urlParsed.field_set & (1 << UF_SCHEMA))) {
  98. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL specifies no schema");
  99. return;
  100. }
  101. std::string schema(_url.substr(urlParsed.field_data[UF_SCHEMA].off,urlParsed.field_data[UF_SCHEMA].len));
  102. if (schema == "file") {
  103. const std::string filePath(_url.substr(urlParsed.field_data[UF_PATH].off,urlParsed.field_data[UF_PATH].len));
  104. uint64_t lm = Utils::getLastModified(filePath.c_str());
  105. if (lm) {
  106. const std::map<std::string,std::string>::const_iterator ifModSince(_requestHeaders.find("If-Modified-Since"));
  107. if ((ifModSince != _requestHeaders.end())&&(ifModSince->second.length())) {
  108. uint64_t t64 = Utils::fromRfc1123(ifModSince->second);
  109. if ((t64)&&(lm > t64)) {
  110. suicidalThread = !_handler(this,_arg,_url,304,_responseHeaders,"");
  111. return;
  112. }
  113. }
  114. if (Utils::readFile(filePath.c_str(),_responseBody)) {
  115. _responseHeaders["Last-Modified"] = Utils::toRfc1123(lm);
  116. suicidalThread = !_handler(this,_arg,_url,200,_responseHeaders,_responseBody);
  117. return;
  118. }
  119. }
  120. suicidalThread = !_handler(this,_arg,_url,404,_responseHeaders,"file not found or not readable");
  121. return;
  122. } else if (schema == "http") {
  123. if (!(urlParsed.field_set & (1 << UF_HOST))) {
  124. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL contains no host");
  125. return;
  126. }
  127. std::string host(_url.substr(urlParsed.field_data[UF_HOST].off,urlParsed.field_data[UF_HOST].len));
  128. std::list<InetAddress> v4,v6;
  129. {
  130. struct addrinfo *res = (struct addrinfo *)0;
  131. if (!getaddrinfo(host.c_str(),(const char *)0,(const struct addrinfo *)0,&res)) {
  132. struct addrinfo *p = res;
  133. do {
  134. if (p->ai_family == AF_INET)
  135. v4.push_back(InetAddress(p->ai_addr));
  136. else if (p->ai_family == AF_INET6)
  137. v6.push_back(InetAddress(p->ai_addr));
  138. } while ((p = p->ai_next));
  139. freeaddrinfo(res);
  140. }
  141. }
  142. std::list<InetAddress> *addrList;
  143. if (v4.empty()&&v6.empty()) {
  144. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"could not find address for host in URL");
  145. return;
  146. } else if (v4.empty()) {
  147. addrList = &v6;
  148. } else {
  149. addrList = &v4;
  150. }
  151. InetAddress *addr;
  152. {
  153. addrList->sort();
  154. addrList->unique();
  155. unsigned int i = 0,k = 0;
  156. k = rand() % addrList->size();
  157. std::list<InetAddress>::iterator a(addrList->begin());
  158. while (i++ != k) ++a;
  159. addr = &(*a);
  160. }
  161. int remotePort = ((urlParsed.field_set & (1 << UF_PORT))&&(urlParsed.port)) ? (int)urlParsed.port : (int)80;
  162. if ((remotePort <= 0)||(remotePort > 0xffff)) {
  163. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL port out of range");
  164. return;
  165. }
  166. addr->setPort(remotePort);
  167. _fd = socket(addr->isV6() ? AF_INET6 : AF_INET,SOCK_STREAM,0);
  168. if (_fd <= 0) {
  169. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"could not open socket");
  170. return;
  171. }
  172. for(;;) {
  173. if (connect(_fd,addr->saddr(),addr->saddrLen())) {
  174. if (errno == EINTR)
  175. continue;
  176. ::close(_fd); _fd = 0;
  177. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"connection failed to remote host");
  178. return;
  179. } else break;
  180. }
  181. const char *mstr = "GET";
  182. switch(_method) {
  183. case HTTP_METHOD_HEAD: mstr = "HEAD"; break;
  184. default: break;
  185. }
  186. int mlen = (int)snprintf(buf,sizeof(buf),"%s %s HTTP/1.1\r\nAccept-Encoding: \r\nHost: %s\r\n",mstr,_url.substr(urlParsed.field_data[UF_PATH].off,urlParsed.field_data[UF_PATH].len).c_str(),host.c_str());
  187. if (mlen >= (int)sizeof(buf)) {
  188. ::close(_fd); _fd = 0;
  189. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"URL too long");
  190. return;
  191. }
  192. if (!_sendAll(_fd,buf,mlen)) {
  193. ::close(_fd); _fd = 0;
  194. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
  195. return;
  196. }
  197. for(std::map<std::string,std::string>::const_iterator rh(_requestHeaders.begin());rh!=_requestHeaders.end();++rh) {
  198. mlen = (int)snprintf(buf,sizeof(buf),"%s: %s\r\n",rh->first.c_str(),rh->second.c_str());
  199. if (mlen >= (int)sizeof(buf)) {
  200. ::close(_fd); _fd = 0;
  201. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"header too long");
  202. return;
  203. }
  204. if (!_sendAll(_fd,buf,mlen)) {
  205. ::close(_fd); _fd = 0;
  206. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
  207. return;
  208. }
  209. }
  210. if (!_sendAll(_fd,"\r\n",2)) {
  211. ::close(_fd); _fd = 0;
  212. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"write error");
  213. return;
  214. }
  215. _responseStatusCode = 0;
  216. _messageComplete = false;
  217. for(;;) {
  218. mlen = (int)::recv(_fd,buf,sizeof(buf),0);
  219. if (mlen < 0) {
  220. if (errno != EINTR)
  221. break;
  222. else continue;
  223. }
  224. if (((int)http_parser_execute(&_parser,&_http_parser_settings,buf,mlen) != mlen)||(_parser.upgrade)) {
  225. ::close(_fd); _fd = 0;
  226. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"invalid HTTP response from server");
  227. return;
  228. }
  229. if (_messageComplete) {
  230. ::close(_fd); _fd = 0;
  231. suicidalThread = !_handler(this,_arg,_url,_responseStatusCode,_responseHeaders,_responseBody);
  232. return;
  233. }
  234. }
  235. ::close(_fd); _fd = 0;
  236. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"empty HTTP response from server");
  237. return;
  238. } else {
  239. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"only 'file' and 'http' methods are supported");
  240. return;
  241. }
  242. } catch ( ... ) {
  243. suicidalThread = !_handler(this,_arg,_url,0,_responseHeaders,"unexpected exception retrieving URL");
  244. return;
  245. }
  246. }
  247. int Http::Request::_http_on_message_begin(http_parser *parser)
  248. {
  249. return 0;
  250. }
  251. int Http::Request::_http_on_url(http_parser *parser,const char *data,size_t length)
  252. {
  253. return 0;
  254. }
  255. int Http::Request::_http_on_status_complete(http_parser *parser)
  256. {
  257. Http::Request *r = (Http::Request *)parser->data;
  258. r->_responseStatusCode = parser->status_code;
  259. return 0;
  260. }
  261. int Http::Request::_http_on_header_field(http_parser *parser,const char *data,size_t length)
  262. {
  263. Http::Request *r = (Http::Request *)parser->data;
  264. if ((r->_currentHeaderField.length())&&(r->_responseHeaders.find(r->_currentHeaderField) != r->_responseHeaders.end()))
  265. r->_currentHeaderField.assign("");
  266. r->_currentHeaderField.append(data,length);
  267. return 0;
  268. }
  269. int Http::Request::_http_on_header_value(http_parser *parser,const char *data,size_t length)
  270. {
  271. Http::Request *r = (Http::Request *)parser->data;
  272. if (r->_currentHeaderField.length())
  273. r->_responseHeaders[r->_currentHeaderField].append(data,length);
  274. return 0;
  275. }
  276. int Http::Request::_http_on_headers_complete(http_parser *parser)
  277. {
  278. Http::Request *r = (Http::Request *)parser->data;
  279. return ((r->_method == Http::HTTP_METHOD_HEAD) ? 1 : 0);
  280. }
  281. int Http::Request::_http_on_body(http_parser *parser,const char *data,size_t length)
  282. {
  283. Http::Request *r = (Http::Request *)parser->data;
  284. r->_responseBody.append(data,length);
  285. return 0;
  286. }
  287. int Http::Request::_http_on_message_complete(http_parser *parser)
  288. {
  289. Http::Request *r = (Http::Request *)parser->data;
  290. r->_messageComplete = true;
  291. return 0;
  292. }
  293. } // namespace ZeroTier