Client.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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/LexicalPath.h>
  28. #include <AK/StringBuilder.h>
  29. #include <AK/URLParser.h>
  30. #include <LibCore/DateTime.h>
  31. #include <LibCore/DirIterator.h>
  32. #include <LibCore/File.h>
  33. #include <LibCore/MimeData.h>
  34. #include <LibHTTP/HttpRequest.h>
  35. #include <stdio.h>
  36. #include <sys/stat.h>
  37. #include <time.h>
  38. #include <unistd.h>
  39. namespace WebServer {
  40. Client::Client(NonnullRefPtr<Core::TCPSocket> socket, const String& root, Core::Object* parent)
  41. : Core::Object(parent)
  42. , m_socket(socket)
  43. , m_root_path(root)
  44. {
  45. }
  46. void Client::die()
  47. {
  48. remove_from_parent();
  49. }
  50. void Client::start()
  51. {
  52. m_socket->on_ready_to_read = [this] {
  53. auto raw_request = m_socket->read_all();
  54. if (raw_request.is_null()) {
  55. die();
  56. return;
  57. }
  58. dbg() << "Got raw request: '" << String::copy(raw_request) << "'";
  59. handle_request(move(raw_request));
  60. die();
  61. };
  62. }
  63. void Client::handle_request(ByteBuffer raw_request)
  64. {
  65. auto request_or_error = HTTP::HttpRequest::from_raw_request(raw_request);
  66. if (!request_or_error.has_value())
  67. return;
  68. auto& request = request_or_error.value();
  69. dbg() << "Got HTTP request: " << request.method_name() << " " << request.resource();
  70. for (auto& header : request.headers()) {
  71. dbg() << " " << header.name << " => " << header.value;
  72. }
  73. if (request.method() != HTTP::HttpRequest::Method::GET) {
  74. send_error_response(403, "Forbidden!", request);
  75. return;
  76. }
  77. auto requested_path = LexicalPath::canonicalized_path(request.resource());
  78. dbg() << "Canonical requested path: '" << requested_path << "'";
  79. StringBuilder path_builder;
  80. path_builder.append(m_root_path);
  81. path_builder.append('/');
  82. path_builder.append(requested_path);
  83. auto real_path = path_builder.to_string();
  84. if (Core::File::is_directory(real_path)) {
  85. if (!request.resource().ends_with("/")) {
  86. StringBuilder red;
  87. red.append(requested_path);
  88. red.append("/");
  89. send_redirect(red.to_string(), request);
  90. return;
  91. }
  92. StringBuilder index_html_path_builder;
  93. index_html_path_builder.append(real_path);
  94. index_html_path_builder.append("/index.html");
  95. auto index_html_path = index_html_path_builder.to_string();
  96. if (!Core::File::exists(index_html_path)) {
  97. handle_directory_listing(requested_path, real_path, request);
  98. return;
  99. }
  100. real_path = index_html_path;
  101. }
  102. auto file = Core::File::construct(real_path);
  103. if (!file->open(Core::File::ReadOnly)) {
  104. send_error_response(404, "Not found!", request);
  105. return;
  106. }
  107. send_response(file->read_all(), request, Core::guess_mime_type_based_on_filename(request.url()));
  108. }
  109. void Client::send_response(StringView response, const HTTP::HttpRequest& request, const String& content_type)
  110. {
  111. StringBuilder builder;
  112. builder.append("HTTP/1.0 200 OK\r\n");
  113. builder.append("Server: WebServer (SerenityOS)\r\n");
  114. builder.append("Content-Type: ");
  115. builder.append(content_type);
  116. builder.append("\r\n");
  117. builder.append("\r\n");
  118. m_socket->write(builder.to_string());
  119. m_socket->write(response);
  120. log_response(200, request);
  121. }
  122. void Client::send_redirect(StringView redirect_path, const HTTP::HttpRequest& request)
  123. {
  124. StringBuilder builder;
  125. builder.append("HTTP/1.0 301 Moved Permanently\r\n");
  126. builder.append("Location: ");
  127. builder.append(redirect_path);
  128. builder.append("\r\n");
  129. builder.append("\r\n");
  130. m_socket->write(builder.to_string());
  131. log_response(301, request);
  132. }
  133. void Client::handle_directory_listing(const String& requested_path, const String& real_path, const HTTP::HttpRequest& request)
  134. {
  135. StringBuilder builder;
  136. builder.append("<!DOCTYPE html>\n");
  137. builder.append("<html>\n");
  138. builder.append("<head><title>Index of ");
  139. builder.append(escape_html_entities(requested_path));
  140. builder.append("</title></head>\n");
  141. builder.append("<body>\n");
  142. builder.append("<h1>Index of ");
  143. builder.append(escape_html_entities(requested_path));
  144. builder.append("</h1>\n");
  145. builder.append("<hr>\n");
  146. builder.append("<table>\n");
  147. Core::DirIterator dt(real_path);
  148. while (dt.has_next()) {
  149. auto name = dt.next_path();
  150. builder.append("<tr><td><a href=\"");
  151. builder.append(urlencode(name));
  152. builder.append("\">");
  153. builder.append(escape_html_entities(name));
  154. builder.append("</a></td>");
  155. StringBuilder path_builder;
  156. path_builder.append(real_path);
  157. path_builder.append('/');
  158. path_builder.append(name);
  159. struct stat st;
  160. memset(&st, 0, sizeof(st));
  161. int rc = stat(path_builder.to_string().characters(), &st);
  162. if (rc < 0) {
  163. perror("stat");
  164. }
  165. builder.appendf("<td>%10d</td>", st.st_size);
  166. builder.append("<td>");
  167. builder.append(Core::DateTime::from_timestamp(st.st_mtime).to_string());
  168. builder.append("</td>");
  169. builder.append("</tr>\n");
  170. }
  171. builder.append("</table>\n");
  172. builder.append("<hr>\n");
  173. builder.append("<i>Generated by WebServer (SerenityOS)</i>\n");
  174. builder.append("</body>\n");
  175. builder.append("</html>\n");
  176. send_response(builder.to_string(), request, "text/html");
  177. }
  178. void Client::send_error_response(unsigned code, const StringView& message, const HTTP::HttpRequest& request)
  179. {
  180. StringBuilder builder;
  181. builder.appendf("HTTP/1.0 %u ", code);
  182. builder.append(message);
  183. builder.append("\r\n\r\n");
  184. builder.append("<!DOCTYPE html><html><body><h1>");
  185. builder.appendf("%u ", code);
  186. builder.append(message);
  187. builder.append("</h1></body></html>");
  188. m_socket->write(builder.to_string());
  189. log_response(code, request);
  190. }
  191. void Client::log_response(unsigned code, const HTTP::HttpRequest& request)
  192. {
  193. printf("%s :: %03u :: %s %s\n",
  194. Core::DateTime::now().to_string().characters(),
  195. code,
  196. request.method_name().characters(),
  197. request.resource().characters());
  198. }
  199. }