2
0

HTTPServer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #include "HTTPServer.h"
  2. #include <cstring>
  3. bell::HTTPServer::HTTPServer(int serverPort) { this->serverPort = serverPort; }
  4. unsigned char bell::HTTPServer::h2int(char c) {
  5. if (c >= '0' && c <= '9') {
  6. return ((unsigned char)c - '0');
  7. }
  8. if (c >= 'a' && c <= 'f') {
  9. return ((unsigned char)c - 'a' + 10);
  10. }
  11. if (c >= 'A' && c <= 'F') {
  12. return ((unsigned char)c - 'A' + 10);
  13. }
  14. return (0);
  15. }
  16. std::string bell::HTTPServer::urlDecode(std::string str) {
  17. std::string encodedString = "";
  18. char c;
  19. char code0;
  20. char code1;
  21. for (int i = 0; i < str.length(); i++) {
  22. c = str[i];
  23. if (c == '+') {
  24. encodedString += ' ';
  25. } else if (c == '%') {
  26. i++;
  27. code0 = str[i];
  28. i++;
  29. code1 = str[i];
  30. c = (h2int(code0) << 4) | h2int(code1);
  31. encodedString += c;
  32. } else {
  33. encodedString += c;
  34. }
  35. }
  36. return encodedString;
  37. }
  38. std::vector<std::string> bell::HTTPServer::splitUrl(const std::string &url,
  39. char delimiter) {
  40. std::stringstream ssb(url);
  41. std::string segment;
  42. std::vector<std::string> seglist;
  43. while (std::getline(ssb, segment, delimiter)) {
  44. seglist.push_back(segment);
  45. }
  46. return seglist;
  47. }
  48. void bell::HTTPServer::registerHandler(RequestType requestType,
  49. const std::string &routeUrl,
  50. httpHandler handler) {
  51. if (routes.find(routeUrl) == routes.end()) {
  52. routes.insert({routeUrl, std::vector<HTTPRoute>()});
  53. }
  54. this->routes[routeUrl].push_back(HTTPRoute{
  55. .requestType = requestType,
  56. .handler = handler,
  57. });
  58. }
  59. void bell::HTTPServer::listen() {
  60. BELL_LOG(info, "http", "Starting server at port %d", this->serverPort);
  61. // setup address
  62. struct addrinfo hints, *server;
  63. memset(&hints, 0, sizeof hints);
  64. hints.ai_family = AF_INET;
  65. hints.ai_socktype = SOCK_STREAM;
  66. hints.ai_flags = AI_PASSIVE;
  67. getaddrinfo(NULL, std::to_string(serverPort).c_str(), &hints, &server);
  68. int sockfd =
  69. socket(server->ai_family, server->ai_socktype, server->ai_protocol);
  70. struct sockaddr_in clientname;
  71. socklen_t incomingSockSize;
  72. int yes = true;
  73. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*) &yes, sizeof(int)) < 0) {
  74. throw std::runtime_error("setsockopt failed: " +
  75. std::string(strerror(errno)));
  76. }
  77. if (bind(sockfd, server->ai_addr, server->ai_addrlen) < 0) {
  78. throw std::runtime_error("bind failed on port " +
  79. std::to_string(this->serverPort) + ": " +
  80. std::string(strerror(errno)));
  81. }
  82. if (::listen(sockfd, 5) < 0) {
  83. throw std::runtime_error("listen failed on port " +
  84. std::to_string(this->serverPort) + ": " +
  85. std::string(strerror(errno)));
  86. }
  87. FD_ZERO(&activeFdSet);
  88. FD_SET(sockfd, &activeFdSet);
  89. for (int maxfd = sockfd;;) {
  90. /* Block until input arrives on one or more active sockets. */
  91. readFdSet = activeFdSet;
  92. struct timeval tv = {0, 100000};
  93. if (select(maxfd + 1, &readFdSet, NULL, NULL, &tv) < 0) {
  94. BELL_LOG(error, "http", "Error in select");
  95. perror("select");
  96. // exit(EXIT_FAILURE);
  97. }
  98. /* Service listening socket. */
  99. if (FD_ISSET(sockfd, &readFdSet)) {
  100. int newFd;
  101. incomingSockSize = sizeof(clientname);
  102. newFd = accept(sockfd, (struct sockaddr*)&clientname,
  103. &incomingSockSize);
  104. if (newFd < 0) {
  105. perror("accept");
  106. exit(EXIT_FAILURE);
  107. }
  108. FD_SET(newFd, &activeFdSet);
  109. HTTPConnection conn = { .buffer = std::vector<uint8_t>(128),
  110. .httpMethod = "" };
  111. this->connections.insert({ newFd, conn });
  112. }
  113. /* Service other sockets and update set & max */
  114. maxfd = sockfd;
  115. for (auto it = this->connections.cbegin();
  116. it != this->connections.cend() /* not hoisted */;
  117. /* no increment */) {
  118. int fd = (*it).first;
  119. if ((*it).second.toBeClosed) {
  120. close(fd);
  121. FD_CLR(fd, &activeFdSet);
  122. this->connections.erase(
  123. it++); // or "it = m.erase(it)" since C++11
  124. }
  125. else {
  126. if (fd != sockfd && FD_ISSET(fd, &readFdSet)) {
  127. /* Data arriving on an already-connected socket. */
  128. readFromClient(fd);
  129. }
  130. if (fd > maxfd) maxfd = fd;
  131. ++it;
  132. }
  133. }
  134. }
  135. }
  136. void bell::HTTPServer::readFromClient(int clientFd) {
  137. HTTPConnection &conn = this->connections[clientFd];
  138. int nbytes = recv(clientFd, (char*) &conn.buffer[0], conn.buffer.size(), 0);
  139. if (nbytes < 0) {
  140. BELL_LOG(error, "http", "Error reading from client");
  141. perror("recv");
  142. this->closeConnection(clientFd);
  143. } else if (nbytes == 0) {
  144. this->closeConnection(clientFd);
  145. } else {
  146. conn.currentLine +=
  147. std::string(conn.buffer.data(), conn.buffer.data() + nbytes);
  148. READBODY:
  149. if (!conn.isReadingBody) {
  150. while (conn.currentLine.find("\r\n") != std::string::npos) {
  151. auto line =
  152. conn.currentLine.substr(0, conn.currentLine.find("\r\n"));
  153. conn.currentLine = conn.currentLine.substr(
  154. conn.currentLine.find("\r\n") + 2, conn.currentLine.size());
  155. if (line.find("GET ") != std::string::npos ||
  156. line.find("POST ") != std::string::npos ||
  157. line.find("OPTIONS ") != std::string::npos) {
  158. conn.httpMethod = line;
  159. }
  160. if (line.find("Content-Length: ") != std::string::npos) {
  161. conn.contentLength =
  162. std::stoi(line.substr(16, line.size() - 1));
  163. }
  164. // detect hostname for captive portal
  165. if (line.find("Host: connectivitycheck.gstatic.com") !=
  166. std::string::npos) {
  167. conn.isCaptivePortal = true;
  168. BELL_LOG(info, "http", "Captive portal request detected");
  169. }
  170. if (line.size() == 0) {
  171. if (conn.contentLength != 0) {
  172. conn.isReadingBody = true;
  173. goto READBODY;
  174. } else {
  175. if (!conn.isCaptivePortal) {
  176. findAndHandleRoute(conn.httpMethod,
  177. conn.currentLine, clientFd);
  178. } else {
  179. this->redirectCaptivePortal(clientFd);
  180. }
  181. }
  182. }
  183. }
  184. } else {
  185. if (conn.currentLine.size() >= conn.contentLength) {
  186. findAndHandleRoute(conn.httpMethod, conn.currentLine, clientFd);
  187. }
  188. }
  189. }
  190. }
  191. void bell::HTTPServer::closeConnection(int connection) {
  192. this->connections[connection].toBeClosed = true;
  193. }
  194. void bell::HTTPServer::writeResponseEvents(int connFd) {
  195. std::lock_guard lock(this->responseMutex);
  196. std::stringstream stream;
  197. stream << "HTTP/1.1 200 OK\r\n";
  198. stream << "Server: bell-http\r\n";
  199. stream << "Connection: keep-alive\r\n";
  200. stream << "Content-type: text/event-stream\r\n";
  201. stream << "Cache-Control: no-cache\r\n";
  202. stream << "Access-Control-Allow-Origin: *\r\n";
  203. stream << "Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, "
  204. "OPTIONS\r\n";
  205. stream << "Access-Control-Allow-Headers: Origin, Content-Type, "
  206. "X-Auth-Token\r\n";
  207. stream << "\r\n";
  208. auto responseStr = stream.str();
  209. write(connFd, responseStr.c_str(), responseStr.size());
  210. this->connections[connFd].isEventConnection = true;
  211. }
  212. void bell::HTTPServer::writeResponse(const HTTPResponse &response) {
  213. std::lock_guard lock(this->responseMutex);
  214. auto fileSize = response.body.size();
  215. if (response.responseReader != nullptr) {
  216. fileSize = response.responseReader->getTotalSize();
  217. }
  218. std::stringstream stream;
  219. stream << "HTTP/1.1 " << response.status << " OK\r\n";
  220. stream << "Server: bell-http\r\n";
  221. stream << "Connection: close\r\n";
  222. stream << "Content-type: " << response.contentType << "\r\n";
  223. if (response.useGzip) {
  224. stream << "Content-encoding: gzip"
  225. << "\r\n";
  226. }
  227. stream << "Access-Control-Allow-Origin: *\r\n";
  228. stream << "Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS\r\n";
  229. stream << "Access-Control-Expose-Headers: Location\r\n";
  230. stream << "Access-Control-Allow-Headers: Origin, Content-Type, "
  231. "X-Auth-Token\r\n";
  232. // go over every item in request->extraHeaders
  233. for (auto &header : response.extraHeaders) {
  234. stream << header << "\r\n";
  235. }
  236. stream << "\r\n";
  237. if (response.body.size() > 0) {
  238. stream << response.body;
  239. }
  240. auto responseStr = stream.str();
  241. write(response.connectionFd, responseStr.c_str(), responseStr.size());
  242. if (response.responseReader != nullptr) {
  243. size_t read;
  244. do {
  245. read = response.responseReader->read(responseBuffer.data(),
  246. responseBuffer.size());
  247. if (read > 0) {
  248. write(response.connectionFd, responseBuffer.data(), read);
  249. }
  250. } while (read > 0);
  251. }
  252. this->closeConnection(response.connectionFd);
  253. }
  254. void bell::HTTPServer::respond(const HTTPResponse &response) {
  255. writeResponse(response);
  256. }
  257. void bell::HTTPServer::redirectCaptivePortal(int connectionFd) {
  258. std::lock_guard lock(this->responseMutex);
  259. std::stringstream stream;
  260. stream << "HTTP/1.1 302 Found\r\n";
  261. stream << "Server: bell-http\r\n";
  262. stream << "Connection: close\r\n";
  263. stream << "Location: http://euphonium.audio\r\n\r\n";
  264. stream << "Content-Length: 9\r\n";
  265. stream << "302 Found";
  266. auto responseStr = stream.str();
  267. write(connectionFd, responseStr.c_str(), responseStr.size());
  268. this->closeConnection(connectionFd);
  269. }
  270. void bell::HTTPServer::redirectTo(const std::string &url, int connectionFd) {
  271. std::lock_guard lock(this->responseMutex);
  272. std::stringstream stream;
  273. stream << "HTTP/1.1 301 Moved Permanently\r\n";
  274. stream << "Server: bell-http\r\n";
  275. stream << "Connection: close\r\n";
  276. stream << "Location: " << url << "\r\n\r\n";
  277. auto responseStr = stream.str();
  278. write(connectionFd, responseStr.c_str(), responseStr.size());
  279. this->closeConnection(connectionFd);
  280. }
  281. void bell::HTTPServer::publishEvent(std::string eventName,
  282. std::string eventData) {
  283. std::lock_guard lock(this->responseMutex);
  284. BELL_LOG(info, "http", "Publishing event");
  285. std::stringstream stream;
  286. stream << "event: " << eventName << "\n";
  287. stream << "data: " << eventData << "\n\n";
  288. auto responseStr = stream.str();
  289. // Reply to all event-connections
  290. for (auto it = this->connections.cbegin(); it != this->connections.cend();
  291. ++it) {
  292. if ((*it).second.isEventConnection) {
  293. write(it->first, responseStr.c_str(), responseStr.size());
  294. }
  295. }
  296. }
  297. std::map<std::string, std::string>
  298. bell::HTTPServer::parseQueryString(const std::string &queryString) {
  299. std::map<std::string, std::string> query;
  300. auto prefixedString = "&" + queryString;
  301. while (prefixedString.find('&') != std::string::npos) {
  302. auto keyStart = prefixedString.find('&');
  303. auto keyEnd = prefixedString.find('=');
  304. // Find second occurence of "&" in prefixedString
  305. auto valueEnd = prefixedString.find('&', keyStart + 1);
  306. if (valueEnd == std::string::npos) {
  307. valueEnd = prefixedString.size();
  308. }
  309. auto key = prefixedString.substr(keyStart + 1, keyEnd - 1);
  310. auto value = prefixedString.substr(keyEnd + 1, valueEnd - keyEnd - 1);
  311. query[key] = urlDecode(value);
  312. prefixedString = prefixedString.substr(valueEnd);
  313. }
  314. return query;
  315. }
  316. void bell::HTTPServer::findAndHandleRoute(std::string &url, std::string &body,
  317. int connectionFd) {
  318. std::map<std::string, std::string> pathParams;
  319. std::map<std::string, std::string> queryParams;
  320. if (url.find("OPTIONS /") != std::string::npos) {
  321. std::stringstream stream;
  322. stream << "HTTP/1.1 200 OK\r\n";
  323. stream << "Server: bell-http\r\n";
  324. stream << "Allow: OPTIONS, GET, HEAD, POST\r\n";
  325. stream << "Connection: close\r\n";
  326. stream << "Access-Control-Allow-Origin: *\r\n";
  327. stream << "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n";
  328. stream << "Access-Control-Allow-Headers: Origin, Content-Type, "
  329. "X-Auth-Token\r\n";
  330. stream << "\r\n";
  331. auto responseStr = stream.str();
  332. write(connectionFd, responseStr.c_str(), responseStr.size());
  333. closeConnection(connectionFd);
  334. return;
  335. }
  336. if (url.find("GET /events") != std::string::npos) {
  337. // Handle SSE endpoint here
  338. writeResponseEvents(connectionFd);
  339. return;
  340. }
  341. for (const auto &routeSet : this->routes) {
  342. for (const auto &route : routeSet.second) {
  343. std::string path = url;
  344. if (url.find("GET ") != std::string::npos &&
  345. route.requestType == RequestType::GET) {
  346. path = path.substr(4);
  347. } else if (url.find("POST ") != std::string::npos &&
  348. route.requestType == RequestType::POST) {
  349. path = path.substr(5);
  350. } else {
  351. continue;
  352. }
  353. path = path.substr(0, path.find(' '));
  354. if (path.find('?') != std::string::npos) {
  355. auto urlEncodedSplit = splitUrl(path, '?');
  356. path = urlEncodedSplit[0];
  357. queryParams = this->parseQueryString(urlEncodedSplit[1]);
  358. }
  359. auto routeSplit = splitUrl(routeSet.first, '/');
  360. auto urlSplit = splitUrl(path, '/');
  361. bool matches = true;
  362. pathParams.clear();
  363. if (routeSplit.size() == urlSplit.size()) {
  364. for (int x = 0; x < routeSplit.size(); x++) {
  365. if (routeSplit[x] != urlSplit[x]) {
  366. if (routeSplit[x][0] == ':') {
  367. pathParams.insert(
  368. {routeSplit[x].substr(1), urlSplit[x]});
  369. } else {
  370. matches = false;
  371. }
  372. }
  373. }
  374. } else {
  375. matches = false;
  376. }
  377. if (routeSplit.back().find('*') != std::string::npos &&
  378. urlSplit[1] == routeSplit[1]) {
  379. matches = true;
  380. for (int x = 1; x <= routeSplit.size() - 2; x++) {
  381. if (urlSplit[x] != routeSplit[x]) {
  382. matches = false;
  383. }
  384. }
  385. }
  386. if (matches) {
  387. if (body.find('&') != std::string::npos) {
  388. queryParams = this->parseQueryString(body);
  389. }
  390. HTTPRequest req = {.urlParams = pathParams,
  391. .queryParams = queryParams,
  392. .body = body,
  393. .url = path,
  394. .handlerId = 0,
  395. .connection = connectionFd};
  396. route.handler(req);
  397. return;
  398. }
  399. }
  400. }
  401. writeResponse(HTTPResponse{
  402. .connectionFd = connectionFd,
  403. .status = 404,
  404. .body = "Not found",
  405. });
  406. }