Client.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  4. * Copyright (c) 2022, Thomas Keppler <serenity@tkeppler.de>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/Debug.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/MemoryStream.h>
  12. #include <AK/QuickSort.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/URL.h>
  15. #include <LibCore/DateTime.h>
  16. #include <LibCore/DeprecatedFile.h>
  17. #include <LibCore/DirIterator.h>
  18. #include <LibCore/File.h>
  19. #include <LibCore/MappedFile.h>
  20. #include <LibCore/MimeData.h>
  21. #include <LibFileSystem/FileSystem.h>
  22. #include <LibHTTP/HttpRequest.h>
  23. #include <LibHTTP/HttpResponse.h>
  24. #include <WebServer/Client.h>
  25. #include <WebServer/Configuration.h>
  26. #include <stdio.h>
  27. #include <sys/stat.h>
  28. #include <unistd.h>
  29. namespace WebServer {
  30. Client::Client(NonnullOwnPtr<Core::BufferedTCPSocket> socket, Core::Object* parent)
  31. : Core::Object(parent)
  32. , m_socket(move(socket))
  33. {
  34. }
  35. void Client::die()
  36. {
  37. m_socket->close();
  38. deferred_invoke([this] { remove_from_parent(); });
  39. }
  40. void Client::start()
  41. {
  42. m_socket->on_ready_to_read = [this] {
  43. if (auto result = on_ready_to_read(); result.is_error()) {
  44. result.error().visit(
  45. [](AK::Error const& error) {
  46. warnln("Internal error: {}", error);
  47. },
  48. [](HTTP::HttpRequest::ParseError const& error) {
  49. warnln("HTTP request parsing error: {}", HTTP::HttpRequest::parse_error_to_string(error));
  50. });
  51. die();
  52. }
  53. };
  54. }
  55. ErrorOr<void, Client::WrappedError> Client::on_ready_to_read()
  56. {
  57. // FIXME: Mostly copied from LibWeb/WebDriver/Client.cpp. As noted there, this should be move the LibHTTP and made spec compliant.
  58. auto buffer = TRY(ByteBuffer::create_uninitialized(m_socket->buffer_size()));
  59. for (;;) {
  60. if (!TRY(m_socket->can_read_without_blocking()))
  61. break;
  62. auto data = TRY(m_socket->read_some(buffer));
  63. TRY(m_remaining_request.try_append(StringView { data }));
  64. if (m_socket->is_eof())
  65. break;
  66. }
  67. if (m_remaining_request.is_empty())
  68. return {};
  69. auto request = TRY(m_remaining_request.to_byte_buffer());
  70. dbgln_if(WEBSERVER_DEBUG, "Got raw request: '{}'", DeprecatedString::copy(request));
  71. auto maybe_parsed_request = HTTP::HttpRequest::from_raw_request(TRY(m_remaining_request.to_byte_buffer()));
  72. if (maybe_parsed_request.is_error()) {
  73. if (maybe_parsed_request.error() == HTTP::HttpRequest::ParseError::RequestIncomplete) {
  74. // If request is not complete we need to wait for more data to arrive
  75. return {};
  76. }
  77. return maybe_parsed_request.error();
  78. }
  79. m_remaining_request.clear();
  80. TRY(handle_request(maybe_parsed_request.value()));
  81. return {};
  82. }
  83. ErrorOr<bool> Client::handle_request(HTTP::HttpRequest const& request)
  84. {
  85. auto resource_decoded = URL::percent_decode(request.resource());
  86. if constexpr (WEBSERVER_DEBUG) {
  87. dbgln("Got HTTP request: {} {}", request.method_name(), request.resource());
  88. for (auto& header : request.headers()) {
  89. dbgln(" {} => {}", header.name, header.value);
  90. }
  91. }
  92. if (request.method() != HTTP::HttpRequest::Method::GET) {
  93. TRY(send_error_response(501, request));
  94. return false;
  95. }
  96. // Check for credentials if they are required
  97. if (Configuration::the().credentials().has_value()) {
  98. bool has_authenticated = verify_credentials(request.headers());
  99. if (!has_authenticated) {
  100. auto const basic_auth_header = TRY("WWW-Authenticate: Basic realm=\"WebServer\", charset=\"UTF-8\""_string);
  101. Vector<String> headers {};
  102. TRY(headers.try_append(basic_auth_header));
  103. TRY(send_error_response(401, request, move(headers)));
  104. return false;
  105. }
  106. }
  107. auto requested_path = TRY(String::from_deprecated_string(LexicalPath::join("/"sv, resource_decoded).string()));
  108. dbgln_if(WEBSERVER_DEBUG, "Canonical requested path: '{}'", requested_path);
  109. auto real_path = TRY(String::formatted("{}{}", Configuration::the().document_root_path(), requested_path));
  110. if (FileSystem::is_directory(real_path.bytes_as_string_view())) {
  111. if (!resource_decoded.ends_with('/')) {
  112. TRY(send_redirect(TRY(String::formatted("{}/", requested_path)), request));
  113. return true;
  114. }
  115. auto index_html_path = TRY(String::formatted("{}/index.html", real_path));
  116. if (!FileSystem::exists(index_html_path)) {
  117. TRY(handle_directory_listing(requested_path, real_path, request));
  118. return true;
  119. }
  120. real_path = index_html_path;
  121. }
  122. auto file = Core::DeprecatedFile::construct(real_path.bytes_as_string_view());
  123. if (!file->open(Core::OpenMode::ReadOnly)) {
  124. TRY(send_error_response(404, request));
  125. return false;
  126. }
  127. if (file->is_device()) {
  128. TRY(send_error_response(403, request));
  129. return false;
  130. }
  131. auto stream = TRY(Core::File::open(real_path.bytes_as_string_view(), Core::File::OpenMode::Read));
  132. auto const info = ContentInfo {
  133. .type = TRY(String::from_utf8(Core::guess_mime_type_based_on_filename(real_path.bytes_as_string_view()))),
  134. .length = TRY(FileSystem::size(real_path.bytes_as_string_view()))
  135. };
  136. TRY(send_response(*stream, request, move(info)));
  137. return true;
  138. }
  139. ErrorOr<void> Client::send_response(Stream& response, HTTP::HttpRequest const& request, ContentInfo content_info)
  140. {
  141. StringBuilder builder;
  142. TRY(builder.try_append("HTTP/1.0 200 OK\r\n"sv));
  143. TRY(builder.try_append("Server: WebServer (SerenityOS)\r\n"sv));
  144. TRY(builder.try_append("X-Frame-Options: SAMEORIGIN\r\n"sv));
  145. TRY(builder.try_append("X-Content-Type-Options: nosniff\r\n"sv));
  146. TRY(builder.try_append("Pragma: no-cache\r\n"sv));
  147. if (content_info.type == "text/plain")
  148. TRY(builder.try_appendff("Content-Type: {}; charset=utf-8\r\n", content_info.type));
  149. else
  150. TRY(builder.try_appendff("Content-Type: {}\r\n", content_info.type));
  151. TRY(builder.try_appendff("Content-Length: {}\r\n", content_info.length));
  152. TRY(builder.try_append("\r\n"sv));
  153. auto builder_contents = TRY(builder.to_byte_buffer());
  154. TRY(m_socket->write_until_depleted(builder_contents));
  155. log_response(200, request);
  156. char buffer[PAGE_SIZE];
  157. do {
  158. auto size = TRY(response.read_some({ buffer, sizeof(buffer) })).size();
  159. if (response.is_eof() && size == 0)
  160. break;
  161. ReadonlyBytes write_buffer { buffer, size };
  162. while (!write_buffer.is_empty()) {
  163. auto nwritten = TRY(m_socket->write_some(write_buffer));
  164. if (nwritten == 0) {
  165. dbgln("EEEEEE got 0 bytes written!");
  166. }
  167. write_buffer = write_buffer.slice(nwritten);
  168. }
  169. } while (true);
  170. auto keep_alive = false;
  171. if (auto it = request.headers().find_if([](auto& header) { return header.name.equals_ignoring_ascii_case("Connection"sv); }); !it.is_end()) {
  172. if (it->value.trim_whitespace().equals_ignoring_ascii_case("keep-alive"sv))
  173. keep_alive = true;
  174. }
  175. if (!keep_alive)
  176. m_socket->close();
  177. return {};
  178. }
  179. ErrorOr<void> Client::send_redirect(StringView redirect_path, HTTP::HttpRequest const& request)
  180. {
  181. StringBuilder builder;
  182. TRY(builder.try_append("HTTP/1.0 301 Moved Permanently\r\n"sv));
  183. TRY(builder.try_append("Location: "sv));
  184. TRY(builder.try_append(redirect_path));
  185. TRY(builder.try_append("\r\n"sv));
  186. TRY(builder.try_append("\r\n"sv));
  187. auto builder_contents = TRY(builder.to_byte_buffer());
  188. TRY(m_socket->write_until_depleted(builder_contents));
  189. log_response(301, request);
  190. return {};
  191. }
  192. static DeprecatedString folder_image_data()
  193. {
  194. static DeprecatedString cache;
  195. if (cache.is_empty()) {
  196. auto file = Core::MappedFile::map("/res/icons/16x16/filetype-folder.png"sv).release_value_but_fixme_should_propagate_errors();
  197. // FIXME: change to TRY() and make method fallible
  198. cache = MUST(encode_base64(file->bytes())).to_deprecated_string();
  199. }
  200. return cache;
  201. }
  202. static DeprecatedString file_image_data()
  203. {
  204. static DeprecatedString cache;
  205. if (cache.is_empty()) {
  206. auto file = Core::MappedFile::map("/res/icons/16x16/filetype-unknown.png"sv).release_value_but_fixme_should_propagate_errors();
  207. // FIXME: change to TRY() and make method fallible
  208. cache = MUST(encode_base64(file->bytes())).to_deprecated_string();
  209. }
  210. return cache;
  211. }
  212. ErrorOr<void> Client::handle_directory_listing(String const& requested_path, String const& real_path, HTTP::HttpRequest const& request)
  213. {
  214. StringBuilder builder;
  215. TRY(builder.try_append("<!DOCTYPE html>\n"sv));
  216. TRY(builder.try_append("<html>\n"sv));
  217. TRY(builder.try_append("<head><meta charset=\"utf-8\">\n"sv));
  218. TRY(builder.try_append("<title>Index of "sv));
  219. TRY(builder.try_append(escape_html_entities(requested_path)));
  220. TRY(builder.try_append("</title><style>\n"sv));
  221. TRY(builder.try_append(".folder { width: 16px; height: 16px; background-image: url('data:image/png;base64,"sv));
  222. TRY(builder.try_append(folder_image_data()));
  223. TRY(builder.try_append("'); }\n"sv));
  224. TRY(builder.try_append(".file { width: 16px; height: 16px; background-image: url('data:image/png;base64,"sv));
  225. TRY(builder.try_append(file_image_data()));
  226. TRY(builder.try_append("'); }\n"sv));
  227. TRY(builder.try_append("</style></head><body>\n"sv));
  228. TRY(builder.try_append("<h1>Index of "sv));
  229. TRY(builder.try_append(escape_html_entities(requested_path)));
  230. TRY(builder.try_append("</h1>\n"sv));
  231. TRY(builder.try_append("<hr>\n"sv));
  232. TRY(builder.try_append("<code><table>\n"sv));
  233. Core::DirIterator dt(real_path.bytes_as_string_view());
  234. Vector<DeprecatedString> names;
  235. while (dt.has_next())
  236. TRY(names.try_append(dt.next_path()));
  237. quick_sort(names);
  238. for (auto& name : names) {
  239. StringBuilder path_builder;
  240. TRY(path_builder.try_append(real_path));
  241. TRY(path_builder.try_append('/'));
  242. // NOTE: In the root directory of the webserver, ".." should be equal to ".", since we don't want
  243. // the user to see e.g. the size of the parent directory (and it isn't unveiled, so stat fails).
  244. if (requested_path == "/" && name == "..")
  245. TRY(path_builder.try_append("."sv));
  246. else
  247. TRY(path_builder.try_append(name));
  248. struct stat st;
  249. memset(&st, 0, sizeof(st));
  250. int rc = stat(path_builder.to_deprecated_string().characters(), &st);
  251. if (rc < 0) {
  252. perror("stat");
  253. }
  254. bool is_directory = S_ISDIR(st.st_mode);
  255. TRY(builder.try_append("<tr>"sv));
  256. TRY(builder.try_appendff("<td><div class=\"{}\"></div></td>", is_directory ? "folder" : "file"));
  257. TRY(builder.try_append("<td><a href=\"./"sv));
  258. TRY(builder.try_append(URL::percent_encode(name)));
  259. // NOTE: For directories, we append a slash so we don't always hit the redirect case,
  260. // which adds a slash anyways.
  261. if (is_directory)
  262. TRY(builder.try_append('/'));
  263. TRY(builder.try_append("\">"sv));
  264. TRY(builder.try_append(escape_html_entities(name)));
  265. TRY(builder.try_append("</a></td><td>&nbsp;</td>"sv));
  266. TRY(builder.try_appendff("<td>{:10}</td><td>&nbsp;</td>", st.st_size));
  267. TRY(builder.try_append("<td>"sv));
  268. TRY(builder.try_append(TRY(Core::DateTime::from_timestamp(st.st_mtime).to_string())));
  269. TRY(builder.try_append("</td>"sv));
  270. TRY(builder.try_append("</tr>\n"sv));
  271. }
  272. TRY(builder.try_append("</table></code>\n"sv));
  273. TRY(builder.try_append("<hr>\n"sv));
  274. TRY(builder.try_append("<i>Generated by WebServer (SerenityOS)</i>\n"sv));
  275. TRY(builder.try_append("</body>\n"sv));
  276. TRY(builder.try_append("</html>\n"sv));
  277. auto response = builder.to_deprecated_string();
  278. FixedMemoryStream stream { response.bytes() };
  279. return send_response(stream, request, { .type = TRY("text/html"_string), .length = response.length() });
  280. }
  281. ErrorOr<void> Client::send_error_response(unsigned code, HTTP::HttpRequest const& request, Vector<String> const& headers)
  282. {
  283. auto reason_phrase = HTTP::HttpResponse::reason_phrase_for_code(code);
  284. StringBuilder content_builder;
  285. TRY(content_builder.try_append("<!DOCTYPE html><html><body><h1>"sv));
  286. TRY(content_builder.try_appendff("{} ", code));
  287. TRY(content_builder.try_append(reason_phrase));
  288. TRY(content_builder.try_append("</h1></body></html>"sv));
  289. StringBuilder header_builder;
  290. TRY(header_builder.try_appendff("HTTP/1.0 {} ", code));
  291. TRY(header_builder.try_append(reason_phrase));
  292. TRY(header_builder.try_append("\r\n"sv));
  293. for (auto& header : headers) {
  294. TRY(header_builder.try_append(header));
  295. TRY(header_builder.try_append("\r\n"sv));
  296. }
  297. TRY(header_builder.try_append("Content-Type: text/html; charset=UTF-8\r\n"sv));
  298. TRY(header_builder.try_appendff("Content-Length: {}\r\n", content_builder.length()));
  299. TRY(header_builder.try_append("\r\n"sv));
  300. TRY(m_socket->write_until_depleted(TRY(header_builder.to_byte_buffer())));
  301. TRY(m_socket->write_until_depleted(TRY(content_builder.to_byte_buffer())));
  302. log_response(code, request);
  303. return {};
  304. }
  305. void Client::log_response(unsigned code, HTTP::HttpRequest const& request)
  306. {
  307. outln("{} :: {:03d} :: {} {}", Core::DateTime::now().to_deprecated_string(), code, request.method_name(), request.url().serialize().substring(1));
  308. }
  309. bool Client::verify_credentials(Vector<HTTP::HttpRequest::Header> const& headers)
  310. {
  311. VERIFY(Configuration::the().credentials().has_value());
  312. auto& configured_credentials = Configuration::the().credentials().value();
  313. for (auto& header : headers) {
  314. if (header.name.equals_ignoring_ascii_case("Authorization"sv)) {
  315. auto provided_credentials = HTTP::HttpRequest::parse_http_basic_authentication_header(header.value);
  316. if (provided_credentials.has_value() && configured_credentials.username == provided_credentials->username && configured_credentials.password == provided_credentials->password)
  317. return true;
  318. }
  319. }
  320. return false;
  321. }
  322. }