Client.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Client.h"
  7. #include <AK/Base64.h>
  8. #include <AK/Debug.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/MappedFile.h>
  11. #include <AK/MemoryStream.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/URLParser.h>
  14. #include <LibCore/DateTime.h>
  15. #include <LibCore/DirIterator.h>
  16. #include <LibCore/File.h>
  17. #include <LibCore/FileStream.h>
  18. #include <LibCore/MimeData.h>
  19. #include <LibHTTP/HttpRequest.h>
  20. #include <inttypes.h>
  21. #include <stdio.h>
  22. #include <sys/stat.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. namespace WebServer {
  26. Client::Client(NonnullRefPtr<Core::TCPSocket> socket, const String& root, Core::Object* parent)
  27. : Core::Object(parent)
  28. , m_socket(socket)
  29. , m_root_path(root)
  30. {
  31. }
  32. void Client::die()
  33. {
  34. remove_from_parent();
  35. }
  36. void Client::start()
  37. {
  38. m_socket->on_ready_to_read = [this] {
  39. StringBuilder builder;
  40. for (;;) {
  41. auto line = m_socket->read_line();
  42. if (line.is_empty())
  43. break;
  44. builder.append(line);
  45. builder.append("\r\n");
  46. }
  47. auto request = builder.to_byte_buffer();
  48. dbgln_if(WEBSERVER_DEBUG, "Got raw request: '{}'", String::copy(request));
  49. handle_request(request);
  50. die();
  51. };
  52. }
  53. void Client::handle_request(ReadonlyBytes raw_request)
  54. {
  55. auto request_or_error = HTTP::HttpRequest::from_raw_request(raw_request);
  56. if (!request_or_error.has_value())
  57. return;
  58. auto& request = request_or_error.value();
  59. if constexpr (WEBSERVER_DEBUG) {
  60. dbgln("Got HTTP request: {} {}", request.method_name(), request.resource());
  61. for (auto& header : request.headers()) {
  62. dbgln(" {} => {}", header.name, header.value);
  63. }
  64. }
  65. if (request.method() != HTTP::HttpRequest::Method::GET) {
  66. send_error_response(403, "Forbidden!", request);
  67. return;
  68. }
  69. auto requested_path = LexicalPath::join("/", request.resource()).string();
  70. dbgln_if(WEBSERVER_DEBUG, "Canonical requested path: '{}'", requested_path);
  71. StringBuilder path_builder;
  72. path_builder.append(m_root_path);
  73. path_builder.append('/');
  74. path_builder.append(requested_path);
  75. auto real_path = path_builder.to_string();
  76. if (Core::File::is_directory(real_path)) {
  77. if (!request.resource().ends_with("/")) {
  78. StringBuilder red;
  79. red.append(requested_path);
  80. red.append("/");
  81. send_redirect(red.to_string(), request);
  82. return;
  83. }
  84. StringBuilder index_html_path_builder;
  85. index_html_path_builder.append(real_path);
  86. index_html_path_builder.append("/index.html");
  87. auto index_html_path = index_html_path_builder.to_string();
  88. if (!Core::File::exists(index_html_path)) {
  89. handle_directory_listing(requested_path, real_path, request);
  90. return;
  91. }
  92. real_path = index_html_path;
  93. }
  94. auto file = Core::File::construct(real_path);
  95. if (!file->open(Core::OpenMode::ReadOnly)) {
  96. send_error_response(404, "Not found!", request);
  97. return;
  98. }
  99. Core::InputFileStream stream { file };
  100. send_response(stream, request, Core::guess_mime_type_based_on_filename(real_path));
  101. }
  102. void Client::send_response(InputStream& response, const HTTP::HttpRequest& request, const String& content_type)
  103. {
  104. StringBuilder builder;
  105. builder.append("HTTP/1.0 200 OK\r\n");
  106. builder.append("Server: WebServer (SerenityOS)\r\n");
  107. builder.append("X-Frame-Options: SAMEORIGIN\r\n");
  108. builder.append("X-Content-Type-Options: nosniff\r\n");
  109. builder.append("Pragma: no-cache\r\n");
  110. builder.append("Content-Type: ");
  111. builder.append(content_type);
  112. builder.append("\r\n");
  113. builder.append("\r\n");
  114. m_socket->write(builder.to_string());
  115. log_response(200, request);
  116. char buffer[PAGE_SIZE];
  117. do {
  118. auto size = response.read({ buffer, sizeof(buffer) });
  119. if (response.unreliable_eof() && size == 0)
  120. break;
  121. m_socket->write({ buffer, size });
  122. } while (true);
  123. }
  124. void Client::send_redirect(StringView redirect_path, const HTTP::HttpRequest& request)
  125. {
  126. StringBuilder builder;
  127. builder.append("HTTP/1.0 301 Moved Permanently\r\n");
  128. builder.append("Location: ");
  129. builder.append(redirect_path);
  130. builder.append("\r\n");
  131. builder.append("\r\n");
  132. m_socket->write(builder.to_string());
  133. log_response(301, request);
  134. }
  135. static String folder_image_data()
  136. {
  137. static String cache;
  138. if (cache.is_empty()) {
  139. auto file_or_error = MappedFile::map("/res/icons/16x16/filetype-folder.png");
  140. VERIFY(!file_or_error.is_error());
  141. cache = encode_base64(file_or_error.value()->bytes());
  142. }
  143. return cache;
  144. }
  145. static String file_image_data()
  146. {
  147. static String cache;
  148. if (cache.is_empty()) {
  149. auto file_or_error = MappedFile::map("/res/icons/16x16/filetype-unknown.png");
  150. VERIFY(!file_or_error.is_error());
  151. cache = encode_base64(file_or_error.value()->bytes());
  152. }
  153. return cache;
  154. }
  155. void Client::handle_directory_listing(const String& requested_path, const String& real_path, const HTTP::HttpRequest& request)
  156. {
  157. StringBuilder builder;
  158. builder.append("<!DOCTYPE html>\n");
  159. builder.append("<html>\n");
  160. builder.append("<head><title>Index of ");
  161. builder.append(escape_html_entities(requested_path));
  162. builder.append("</title><style>\n");
  163. builder.append(".folder { width: 16px; height: 16px; background-image: url('data:image/png;base64,");
  164. builder.append(folder_image_data());
  165. builder.append("'); }\n");
  166. builder.append(".file { width: 16px; height: 16px; background-image: url('data:image/png;base64,");
  167. builder.append(file_image_data());
  168. builder.append("'); }\n");
  169. builder.append("</style></head><body>\n");
  170. builder.append("<h1>Index of ");
  171. builder.append(escape_html_entities(requested_path));
  172. builder.append("</h1>\n");
  173. builder.append("<hr>\n");
  174. builder.append("<code><table>\n");
  175. Core::DirIterator dt(real_path);
  176. while (dt.has_next()) {
  177. auto name = dt.next_path();
  178. StringBuilder path_builder;
  179. path_builder.append(real_path);
  180. path_builder.append('/');
  181. path_builder.append(name);
  182. struct stat st;
  183. memset(&st, 0, sizeof(st));
  184. int rc = stat(path_builder.to_string().characters(), &st);
  185. if (rc < 0) {
  186. perror("stat");
  187. }
  188. bool is_directory = S_ISDIR(st.st_mode) || name.is_one_of(".", "..");
  189. builder.append("<tr>");
  190. builder.appendff("<td><div class=\"{}\"></div></td>", is_directory ? "folder" : "file");
  191. builder.append("<td><a href=\"");
  192. builder.append(urlencode(name));
  193. builder.append("\">");
  194. builder.append(escape_html_entities(name));
  195. builder.append("</a></td><td>&nbsp;</td>");
  196. builder.appendff("<td>{:10}</td><td>&nbsp;</td>", st.st_size);
  197. builder.append("<td>");
  198. builder.append(Core::DateTime::from_timestamp(st.st_mtime).to_string());
  199. builder.append("</td>");
  200. builder.append("</tr>\n");
  201. }
  202. builder.append("</table></code>\n");
  203. builder.append("<hr>\n");
  204. builder.append("<i>Generated by WebServer (SerenityOS)</i>\n");
  205. builder.append("</body>\n");
  206. builder.append("</html>\n");
  207. auto response = builder.to_string();
  208. InputMemoryStream stream { response.bytes() };
  209. send_response(stream, request, "text/html");
  210. }
  211. void Client::send_error_response(unsigned code, const StringView& message, const HTTP::HttpRequest& request)
  212. {
  213. StringBuilder builder;
  214. builder.appendff("HTTP/1.0 {} ", code);
  215. builder.append(message);
  216. builder.append("\r\n\r\n");
  217. builder.append("<!DOCTYPE html><html><body><h1>");
  218. builder.appendff("{} ", code);
  219. builder.append(message);
  220. builder.append("</h1></body></html>");
  221. m_socket->write(builder.to_string());
  222. log_response(code, request);
  223. }
  224. void Client::log_response(unsigned code, const HTTP::HttpRequest& request)
  225. {
  226. printf("%s :: %03u :: %s %s\n",
  227. Core::DateTime::now().to_string().characters(),
  228. code,
  229. request.method_name().characters(),
  230. request.resource().characters());
  231. }
  232. }