Http.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 < writeSize) {
  104. long n = phy->streamSend(sock,writeBuf + writePtr,writeSize - writePtr,true);
  105. if (n > 0)
  106. writePtr += n;
  107. }
  108. if (writePtr >= writeSize)
  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. unsigned long writeSize;
  125. char writeBuf[32768];
  126. unsigned long maxResponseSize;
  127. std::map<std::string,std::string> *responseHeaders;
  128. std::string *responseBody;
  129. bool error;
  130. bool done;
  131. Phy<HttpPhyHandler *> *phy;
  132. PhySocket *sock;
  133. };
  134. static int ShttpOnMessageBegin(http_parser *parser)
  135. {
  136. return 0;
  137. }
  138. static int ShttpOnUrl(http_parser *parser,const char *ptr,size_t length)
  139. {
  140. return 0;
  141. }
  142. #if (HTTP_PARSER_VERSION_MAJOR >= 2) && (HTTP_PARSER_VERSION_MINOR >= 2)
  143. static int ShttpOnStatus(http_parser *parser,const char *ptr,size_t length)
  144. #else
  145. static int ShttpOnStatus(http_parser *parser)
  146. #endif
  147. {
  148. /*
  149. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  150. hh->messageSize += (unsigned long)length;
  151. if (hh->messageSize > hh->maxResponseSize)
  152. return -1;
  153. */
  154. return 0;
  155. }
  156. static int ShttpOnHeaderField(http_parser *parser,const char *ptr,size_t length)
  157. {
  158. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  159. hh->messageSize += (unsigned long)length;
  160. if (hh->messageSize > hh->maxResponseSize)
  161. return -1;
  162. if ((hh->currentHeaderField.length())&&(hh->currentHeaderValue.length())) {
  163. (*hh->responseHeaders)[hh->currentHeaderField] = hh->currentHeaderValue;
  164. hh->currentHeaderField = "";
  165. hh->currentHeaderValue = "";
  166. }
  167. for(size_t i=0;i<length;++i)
  168. hh->currentHeaderField.push_back(OSUtils::toLower(ptr[i]));
  169. return 0;
  170. }
  171. static int ShttpOnValue(http_parser *parser,const char *ptr,size_t length)
  172. {
  173. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  174. hh->messageSize += (unsigned long)length;
  175. if (hh->messageSize > hh->maxResponseSize)
  176. return -1;
  177. hh->currentHeaderValue.append(ptr,length);
  178. return 0;
  179. }
  180. static int ShttpOnHeadersComplete(http_parser *parser)
  181. {
  182. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  183. if ((hh->currentHeaderField.length())&&(hh->currentHeaderValue.length()))
  184. (*hh->responseHeaders)[hh->currentHeaderField] = hh->currentHeaderValue;
  185. return 0;
  186. }
  187. static int ShttpOnBody(http_parser *parser,const char *ptr,size_t length)
  188. {
  189. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  190. hh->messageSize += (unsigned long)length;
  191. if (hh->messageSize > hh->maxResponseSize)
  192. return -1;
  193. hh->responseBody->append(ptr,length);
  194. return 0;
  195. }
  196. static int ShttpOnMessageComplete(http_parser *parser)
  197. {
  198. HttpPhyHandler *hh = reinterpret_cast<HttpPhyHandler *>(parser->data);
  199. hh->phy->close(hh->sock);
  200. return 0;
  201. }
  202. } // anonymous namespace
  203. unsigned int Http::_do(
  204. const char *method,
  205. unsigned long maxResponseSize,
  206. unsigned long timeout,
  207. const struct sockaddr *remoteAddress,
  208. const char *path,
  209. const std::map<std::string,std::string> &requestHeaders,
  210. const void *requestBody,
  211. unsigned long requestBodyLength,
  212. std::map<std::string,std::string> &responseHeaders,
  213. std::string &responseBody)
  214. {
  215. try {
  216. responseHeaders.clear();
  217. responseBody = "";
  218. HttpPhyHandler handler;
  219. http_parser_init(&(handler.parser),HTTP_RESPONSE);
  220. handler.parser.data = (void *)&handler;
  221. handler.messageSize = 0;
  222. handler.writePtr = 0;
  223. handler.lastActivity = OSUtils::now();
  224. try {
  225. handler.writeSize = Utils::snprintf(handler.writeBuf,sizeof(handler.writeBuf),"%s %s HTTP/1.1\r\n",method,path);
  226. for(std::map<std::string,std::string>::const_iterator h(requestHeaders.begin());h!=requestHeaders.end();++h)
  227. handler.writeSize += Utils::snprintf(handler.writeBuf + handler.writeSize,sizeof(handler.writeBuf) - handler.writeSize,"%s: %s\r\n",h->first.c_str(),h->second.c_str());
  228. handler.writeSize += Utils::snprintf(handler.writeBuf + handler.writeSize,sizeof(handler.writeBuf) - handler.writeSize,"\r\n");
  229. if ((requestBody)&&(requestBodyLength)) {
  230. if ((handler.writeSize + requestBodyLength) > sizeof(handler.writeBuf)) {
  231. responseBody = "request too large";
  232. return 0;
  233. }
  234. memcpy(handler.writeBuf + handler.writeSize,requestBody,requestBodyLength);
  235. handler.writeSize += requestBodyLength;
  236. }
  237. } catch ( ... ) {
  238. responseBody = "request too large";
  239. return 0;
  240. }
  241. handler.maxResponseSize = maxResponseSize;
  242. handler.responseHeaders = &responseHeaders;
  243. handler.responseBody = &responseBody;
  244. handler.error = false;
  245. handler.done = false;
  246. Phy<HttpPhyHandler *> phy(&handler,true,true);
  247. bool instantConnect = false;
  248. handler.phy = &phy;
  249. handler.sock = phy.tcpConnect((const struct sockaddr *)remoteAddress,instantConnect,(void *)0,true);
  250. if (!handler.sock) {
  251. responseBody = "connection failed (2)";
  252. return 0;
  253. }
  254. while (!handler.done) {
  255. phy.poll(timeout / 2);
  256. if ((timeout)&&((unsigned long)(OSUtils::now() - handler.lastActivity) > timeout)) {
  257. phy.close(handler.sock);
  258. responseBody = "timed out";
  259. return 0;
  260. }
  261. }
  262. return ((handler.error) ? 0 : ((handler.parser.http_errno != HPE_OK) ? 0 : handler.parser.status_code));
  263. } catch (std::exception &exc) {
  264. responseBody = exc.what();
  265. return 0;
  266. } catch ( ... ) {
  267. responseBody = "unknown exception";
  268. return 0;
  269. }
  270. }
  271. } // namespace ZeroTier