Client.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Client.h"
  27. #include <AK/Base64.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/MappedFile.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/URLParser.h>
  32. #include <LibCore/DateTime.h>
  33. #include <LibCore/DirIterator.h>
  34. #include <LibCore/File.h>
  35. #include <LibCore/MimeData.h>
  36. #include <LibHTTP/HttpRequest.h>
  37. #include <stdio.h>
  38. #include <sys/stat.h>
  39. #include <time.h>
  40. #include <unistd.h>
  41. namespace WebServer {
  42. Client::Client(NonnullRefPtr<Core::TCPSocket> socket, const String& root, Core::Object* parent)
  43. : Core::Object(parent)
  44. , m_socket(socket)
  45. , m_root_path(root)
  46. {
  47. }
  48. void Client::die()
  49. {
  50. remove_from_parent();
  51. }
  52. void Client::start()
  53. {
  54. m_socket->on_ready_to_read = [this] {
  55. auto raw_request = m_socket->read_all();
  56. if (raw_request.is_null()) {
  57. die();
  58. return;
  59. }
  60. dbg() << "Got raw request: '" << String::copy(raw_request) << "'";
  61. handle_request(move(raw_request));
  62. die();
  63. };
  64. }
  65. void Client::handle_request(ByteBuffer raw_request)
  66. {
  67. auto request_or_error = HTTP::HttpRequest::from_raw_request(raw_request);
  68. if (!request_or_error.has_value())
  69. return;
  70. auto& request = request_or_error.value();
  71. dbg() << "Got HTTP request: " << request.method_name() << " " << request.resource();
  72. for (auto& header : request.headers()) {
  73. dbg() << " " << header.name << " => " << header.value;
  74. }
  75. if (request.method() != HTTP::HttpRequest::Method::GET) {
  76. send_error_response(403, "Forbidden!", request);
  77. return;
  78. }
  79. auto requested_path = LexicalPath::canonicalized_path(request.resource());
  80. dbg() << "Canonical requested path: '" << requested_path << "'";
  81. StringBuilder path_builder;
  82. path_builder.append(m_root_path);
  83. path_builder.append('/');
  84. path_builder.append(requested_path);
  85. auto real_path = path_builder.to_string();
  86. if (Core::File::is_directory(real_path)) {
  87. if (!request.resource().ends_with("/")) {
  88. StringBuilder red;
  89. red.append(requested_path);
  90. red.append("/");
  91. send_redirect(red.to_string(), request);
  92. return;
  93. }
  94. StringBuilder index_html_path_builder;
  95. index_html_path_builder.append(real_path);
  96. index_html_path_builder.append("/index.html");
  97. auto index_html_path = index_html_path_builder.to_string();
  98. if (!Core::File::exists(index_html_path)) {
  99. handle_directory_listing(requested_path, real_path, request);
  100. return;
  101. }
  102. real_path = index_html_path;
  103. }
  104. auto file = Core::File::construct(real_path);
  105. if (!file->open(Core::File::ReadOnly)) {
  106. send_error_response(404, "Not found!", request);
  107. return;
  108. }
  109. send_response(file->read_all(), request, Core::guess_mime_type_based_on_filename(request.url()));
  110. }
  111. void Client::send_response(StringView response, const HTTP::HttpRequest& request, const String& content_type)
  112. {
  113. StringBuilder builder;
  114. builder.append("HTTP/1.0 200 OK\r\n");
  115. builder.append("Server: WebServer (SerenityOS)\r\n");
  116. builder.append("Content-Type: ");
  117. builder.append(content_type);
  118. builder.append("\r\n");
  119. builder.append("\r\n");
  120. m_socket->write(builder.to_string());
  121. m_socket->write(response);
  122. log_response(200, request);
  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. MappedFile image("/res/icons/16x16/filetype-folder.png");
  140. cache = encode_base64({ image.data(), image.size() });
  141. }
  142. return cache;
  143. }
  144. static String file_image_data()
  145. {
  146. static String cache;
  147. if (cache.is_empty()) {
  148. MappedFile image("/res/icons/16x16/filetype-unknown.png");
  149. cache = encode_base64({ image.data(), image.size() });
  150. }
  151. return cache;
  152. }
  153. void Client::handle_directory_listing(const String& requested_path, const String& real_path, const HTTP::HttpRequest& request)
  154. {
  155. StringBuilder builder;
  156. builder.append("<!DOCTYPE html>\n");
  157. builder.append("<html>\n");
  158. builder.append("<head><title>Index of ");
  159. builder.append(escape_html_entities(requested_path));
  160. builder.append("</title><style>\n");
  161. builder.append(".folder { width: 16px; height: 16px; background-image: url('data:image/png;base64,");
  162. builder.append(folder_image_data());
  163. builder.append("'); }\n");
  164. builder.append(".file { width: 16px; height: 16px; background-image: url('data:image/png;base64,");
  165. builder.append(file_image_data());
  166. builder.append("'); }\n");
  167. builder.append("</style></head><body>\n");
  168. builder.append("<h1>Index of ");
  169. builder.append(escape_html_entities(requested_path));
  170. builder.append("</h1>\n");
  171. builder.append("<hr>\n");
  172. builder.append("<code><table>\n");
  173. Core::DirIterator dt(real_path);
  174. while (dt.has_next()) {
  175. auto name = dt.next_path();
  176. StringBuilder path_builder;
  177. path_builder.append(real_path);
  178. path_builder.append('/');
  179. path_builder.append(name);
  180. struct stat st;
  181. memset(&st, 0, sizeof(st));
  182. int rc = stat(path_builder.to_string().characters(), &st);
  183. if (rc < 0) {
  184. perror("stat");
  185. }
  186. bool is_directory = S_ISDIR(st.st_mode) || name.is_one_of(".", "..");
  187. builder.append("<tr>");
  188. builder.appendf("<td><div class=\"%s\"></div></td>", is_directory ? "folder" : "file");
  189. builder.append("<td><a href=\"");
  190. builder.append(urlencode(name));
  191. builder.append("\">");
  192. builder.append(escape_html_entities(name));
  193. builder.append("</a></td><td>&nbsp;</td>");
  194. builder.appendf("<td>%10d</td><td>&nbsp;</td>", st.st_size);
  195. builder.append("<td>");
  196. builder.append(Core::DateTime::from_timestamp(st.st_mtime).to_string());
  197. builder.append("</td>");
  198. builder.append("</tr>\n");
  199. }
  200. builder.append("</table></code>\n");
  201. builder.append("<hr>\n");
  202. builder.append("<i>Generated by WebServer (SerenityOS)</i>\n");
  203. builder.append("</body>\n");
  204. builder.append("</html>\n");
  205. send_response(builder.to_string(), request, "text/html");
  206. }
  207. void Client::send_error_response(unsigned code, const StringView& message, const HTTP::HttpRequest& request)
  208. {
  209. StringBuilder builder;
  210. builder.appendf("HTTP/1.0 %u ", code);
  211. builder.append(message);
  212. builder.append("\r\n\r\n");
  213. builder.append("<!DOCTYPE html><html><body><h1>");
  214. builder.appendf("%u ", code);
  215. builder.append(message);
  216. builder.append("</h1></body></html>");
  217. m_socket->write(builder.to_string());
  218. log_response(code, request);
  219. }
  220. void Client::log_response(unsigned code, const HTTP::HttpRequest& request)
  221. {
  222. printf("%s :: %03u :: %s %s\n",
  223. Core::DateTime::now().to_string().characters(),
  224. code,
  225. request.method_name().characters(),
  226. request.resource().characters());
  227. }
  228. }