Http.cpp 8.5 KB

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