Client.cpp 7.2 KB

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