Http.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdint.h>
  28. #include <string.h>
  29. #include "Http.hpp"
  30. #include "Phy.hpp"
  31. #include "OSUtils.hpp"
  32. #include "../node/Constants.hpp"
  33. #include "../node/Utils.hpp"
  34. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  35. #include <http_parser.h>
  36. #else
  37. #include "../ext/http-parser/http_parser.h"
  38. #endif
  39. namespace ZeroTier {
  40. namespace {
  41. static int ShttpOnMessageBegin(http_parser *parser);
  42. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length);
  43. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  44. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length);
  45. #else
  46. static int ShttpOnStatus(http_parser *parser);
  47. #endif
  48. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length);
  49. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length);
  50. static int ShttpOnHeadersComplete(http_parser *parser);
  51. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length);
  52. static int ShttpOnMessageComplete(http_parser *parser);
  53. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 1)
  54. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  55. ShttpOnMessageBegin,
  56. ShttpOnUrl,
  57. ShttpOnStatus,
  58. ShttpOnHeaderField,
  59. ShttpOnValue,
  60. ShttpOnHeadersComplete,
  61. ShttpOnBody,
  62. ShttpOnMessageComplete
  63. };
  64. #else
  65. static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
  66. ShttpOnMessageBegin,
  67. ShttpOnUrl,
  68. ShttpOnHeaderField,
  69. ShttpOnValue,
  70. ShttpOnHeadersComplete,
  71. ShttpOnBody,
  72. ShttpOnMessageComplete
  73. };
  74. #endif
  75. struct HttpPhyHandler
  76. {
  77. // not used
  78. inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len) {}
  79. inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
  80. inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  81. {
  82. if (success) {
  83. phy->setNotifyWritable(sock,true);
  84. } else {
  85. *responseBody = "connection failed";
  86. error = true;
  87. done = true;
  88. }
  89. }
  90. inline void phyOnTcpClose(PhySocket *sock,void **uptr)
  91. {
  92. done = true;
  93. }
  94. inline void phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  95. {
  96. lastActivity = OSUtils::now();
  97. http_parser_execute(&parser,&HTTP_PARSER_SETTINGS,(const char *)data,len);
  98. if ((parser.upgrade)||(parser.http_errno != HPE_OK))
  99. phy->close(sock);
  100. }
  101. inline void phyOnTcpWritable(PhySocket *sock,void **uptr)
  102. {
  103. if (writePtr < (unsigned long)writeBuf.length()) {
  104. long n = phy->streamSend(sock,writeBuf.data() + writePtr,(unsigned long)writeBuf.length() - writePtr,true);
  105. if (n > 0)
  106. writePtr += n;
  107. }
  108. if (writePtr >= (unsigned long)writeBuf.length())
  109. phy->setNotifyWritable(sock,false);
  110. }
  111. inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
  112. #ifdef __UNIX_LIKE__
  113. inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
  114. inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
  115. inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
  116. inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
  117. #endif // __UNIX_LIKE__
  118. http_parser parser;
  119. std::string currentHeaderField;
  120. std::string currentHeaderValue;
  121. unsigned long messageSize;
  122. unsigned long writePtr;
  123. uint64_t lastActivity;
  124. std::string writeBuf;
  125. unsigned long maxResponseSize;
  126. std::map<std::string,std::string> *responseHeaders;
  127. std::string *responseBody;
  128. bool error;
  129. bool done;
  130. Phy<HttpPhyHandler *> *phy;
  131. PhySocket *sock;
  132. };
  133. static int ShttpOnMessageBegin(http_parser *parser)
  134. {
  135. return 0;
  136. }
  137. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  138. {
  139. return 0;
  140. }
  141. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  142. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  143. #else
  144. static int ShttpOnStatus(http_parser *parser)
  145. #endif
  146. {
  147. /*
  148. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  149. hh->messageSize += (unsigned long)length;
  150. if (hh->messageSize > hh->maxResponseSize)
  151. return -1;
  152. */
  153. return 0;
  154. }
  155. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  156. {
  157. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  158. hh->messageSize += (unsigned long)length;
  159. if (hh->messageSize > hh->maxResponseSize)
  160. return -1;
  161. if ((hh->currentHeaderField.length())&&(hh->currentHeaderValue.length())) {
  162. (*hh->responseHeaders)[hh->currentHeaderField] = hh->currentHeaderValue;
  163. hh->currentHeaderField = "";
  164. hh->currentHeaderValue = "";
  165. }
  166. for(size_t i=0;i<length;++i)
  167. hh->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  168. return 0;
  169. }
  170. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  171. {
  172. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  173. hh->messageSize += (unsigned long)length;
  174. if (hh->messageSize > hh->maxResponseSize)
  175. return -1;
  176. hh->currentHeaderValue.append(ptr,length);
  177. return 0;
  178. }
  179. static int ShttpOnHeadersComplete(http_parser *parser)
  180. {
  181. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  182. if ((hh->currentHeaderField.length())&&(hh->currentHeaderValue.length()))
  183. (*hh->responseHeaders)[hh->currentHeaderField] = hh->currentHeaderValue;
  184. return 0;
  185. }
  186. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  187. {
  188. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  189. hh->messageSize += (unsigned long)length;
  190. if (hh->messageSize > hh->maxResponseSize)
  191. return -1;
  192. hh->responseBody->append(ptr,length);
  193. return 0;
  194. }
  195. static int ShttpOnMessageComplete(http_parser *parser)
  196. {
  197. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  198. hh->phy->close(hh->sock);
  199. return 0;
  200. }
  201. } // anonymous namespace
  202. unsigned int Http::_do(
  203. const char *method,
  204. unsigned long maxResponseSize,
  205. unsigned long timeout,
  206. const struct sockaddr *remoteAddress,
  207. const char *path,
  208. const std::map<std::string,std::string> &requestHeaders,
  209. const void *requestBody,
  210. unsigned long requestBodyLength,
  211. std::map<std::string,std::string> &responseHeaders,
  212. std::string &responseBody)
  213. {
  214. try {
  215. responseHeaders.clear();
  216. responseBody = "";
  217. HttpPhyHandler handler;
  218. http_parser_init(&(handler.parser),HTTP_RESPONSE);
  219. handler.parser.data = (void *)&handler;
  220. handler.messageSize = 0;
  221. handler.writePtr = 0;
  222. handler.lastActivity = OSUtils::now();
  223. try {
  224. char tmp[1024];
  225. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s %s HTTP/1.1\r\n",method,path);
  226. handler.writeBuf.append(tmp);
  227. for(std::map<std::string,std::string>::const_iterator h(requestHeaders.begin());h!=requestHeaders.end();++h) {
  228. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s: %s\r\n",h->first.c_str(),h->second.c_str());
  229. handler.writeBuf.append(tmp);
  230. }
  231. handler.writeBuf.append("\r\n");
  232. if ((requestBody)&&(requestBodyLength))
  233. handler.writeBuf.append((const char *)requestBody,requestBodyLength);
  234. } catch ( ... ) {
  235. responseBody = "request too large";
  236. return 0;
  237. }
  238. if (maxResponseSize) {
  239. handler.maxResponseSize = maxResponseSize;
  240. } else {
  241. handler.maxResponseSize = 2147483647;
  242. }
  243. handler.responseHeaders = &responseHeaders;
  244. handler.responseBody = &responseBody;
  245. handler.error = false;
  246. handler.done = false;
  247. Phy<HttpPhyHandler *> phy(&handler,true,true);
  248. bool instantConnect = false;
  249. handler.phy = &phy;
  250. handler.sock = phy.tcpConnect((const struct sockaddr *)remoteAddress,instantConnect,(void *)0,true);
  251. if (!handler.sock) {
  252. responseBody = "connection failed (2)";
  253. return 0;
  254. }
  255. while (!handler.done) {
  256. phy.poll(timeout / 2);
  257. if ((timeout)&&((unsigned long)(OSUtils::now() - handler.lastActivity) > timeout)) {
  258. phy.close(handler.sock);
  259. responseBody = "timed out";
  260. return 0;
  261. }
  262. }
  263. return ((handler.error) ? 0 : ((handler.parser.http_errno != HPE_OK) ? 0 : handler.parser.status_code));
  264. } catch (std::exception &exc) {
  265. responseBody = exc.what();
  266. return 0;
  267. } catch ( ... ) {
  268. responseBody = "unknown exception";
  269. return 0;
  270. }
  271. }
  272. } // namespace ZeroTier