/* =============================================================================
 * tiny_server.c -- a web server small enough to read in one sitting
 * =============================================================================
 *
 * [Idea]
 *   A web server is an echo server with a protocol. Replace "echo the line" by
 *   "parse an HTTP request, find the file, send an HTTP response" and you have
 *   the Web. The whole protocol used here is text you could type by hand:
 *
 *       request:                        response:
 *       GET /index.html HTTP/1.0        HTTP/1.0 200 OK
 *       Host: localhost                 Content-type: text/html
 *       <blank line>                    Content-length: 123
 *                                       <blank line>
 *                                       <the file's bytes>
 *
 *   That is it. The headers are lines of "Name: value", the blank line ends the
 *   headers, and the body follows.
 *
 * [What it answers]
 *   - What does an HTTP transaction actually look like, byte for byte?
 *   - How does a server map a URI to a file, and report that it cannot?
 *   - What is static content, and where would dynamic content plug in?
 *
 * [Scope]
 *   STATIC content only, served from a directory, one request at a time. It is
 *   deliberately NOT a proxy and NOT concurrent (see the README): the proxy lab
 *   is the student's own work, and concurrency is Lecture 21.
 *
 * Usage:   ./tiny_server [port] [docroot] [max_requests]
 *          defaults: 15214, "www", 1 request (then it exits, so demos end)
 *
 * Binds the LOOPBACK interface only (netutil.c), so it is not on the network.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>   /* accept */
#include <fcntl.h>
#include <sys/stat.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

/* ---------------------------------------------------------------------------
 * Send an error as a proper HTTP response (so a browser shows a page, not a
 * broken connection). Every response needs a status line and headers.
 * --------------------------------------------------------------------------- */
static void serve_error(int fd, const char *status, const char *shortmsg,
                        const char *detail)
{
    char body[MAXLINE], hdr[MAXLINE];

    snprintf(body, sizeof(body),
             "<html><head><title>%s %s</title></head>\r\n"
             "<body><h1>%s %s</h1><p>%s</p>\r\n"
             "<hr><em>tiny_server (CMU 15-213 Lecture 20)</em>\r\n"
             "</body></html>\r\n",
             status, shortmsg, status, shortmsg, detail);

    snprintf(hdr, sizeof(hdr),
             "HTTP/1.0 %s %s\r\n"
             "Content-type: text/html\r\n"
             "Content-length: %zu\r\n"
             "\r\n",
             status, shortmsg, strlen(body));

    rio_writen(fd, hdr, strlen(hdr));
    rio_writen(fd, body, strlen(body));
}

/* Guess a MIME type from the filename's suffix. Browsers need this to know
 * whether to render or download. */
static const char *mime_type(const char *path)
{
    const char *dot = strrchr(path, '.');
    if (dot) {
        if (!strcmp(dot, ".html") || !strcmp(dot, ".htm")) return "text/html";
        if (!strcmp(dot, ".txt"))                          return "text/plain";
        if (!strcmp(dot, ".css"))                          return "text/css";
        if (!strcmp(dot, ".png"))                          return "image/png";
        if (!strcmp(dot, ".jpg") || !strcmp(dot, ".jpeg")) return "image/jpeg";
    }
    return "application/octet-stream";
}

/* ---------------------------------------------------------------------------
 * Serve one static file.
 * --------------------------------------------------------------------------- */
static void serve_static(int fd, const char *path, size_t size)
{
    int filefd = open(path, O_RDONLY);
    if (filefd < 0) {
        serve_error(fd, "403", "Forbidden", "The server cannot read this file.");
        return;
    }

    /* The response head: status line, then headers, then a BLANK line. The
       blank line is what tells the client the body starts next. */
    char hdr[MAXLINE];
    snprintf(hdr, sizeof(hdr),
             "HTTP/1.0 200 OK\r\n"
             "Server: tiny_server\r\n"
             "Content-type: %s\r\n"
             "Content-length: %zu\r\n"
             "\r\n",
             mime_type(path), size);
    rio_writen(fd, hdr, strlen(hdr));

    /* The body: copy the file to the socket with the robust loop of Lecture 18.
       Exactly the file-copy code, with a socket as the destination. */
    char buf[MAXLINE];
    ssize_t n;
    while ((n = rio_readn(filefd, buf, sizeof(buf))) > 0)
        rio_writen(fd, buf, (size_t)n);
    close(filefd);
}

/* ---------------------------------------------------------------------------
 * Handle one HTTP transaction on a connected descriptor.
 * --------------------------------------------------------------------------- */
static void serve_request(int fd, const char *docroot)
{
    rio_t rio;
    char  line[MAXLINE], method[64], uri[MAXLINE], version[64];

    rio_readinitb(&rio, fd);

    /* 1. Read the REQUEST LINE: "METHOD URI VERSION". */
    if (rio_readlineb(&rio, line, MAXLINE) <= 0)
        return;                                 /* client vanished */
    printf("  request line: %s", line);         /* it ends in \r\n already */

    if (sscanf(line, "%63s %8191s %63s", method, uri, version) != 3) {
        serve_error(fd, "400", "Bad Request", "Malformed request line.");
        return;
    }

    /* 2. Read and discard the request HEADERS, up to the blank line. A real
     *    server inspects them (Host, User-Agent, Accept-Encoding, ...). */
    int nhdrs = 0;
    while (rio_readlineb(&rio, line, MAXLINE) > 0) {
        if (!strcmp(line, "\r\n") || !strcmp(line, "\n"))
            break;                              /* blank line: headers done */
        nhdrs++;
    }
    printf("  (%d header line(s) read, then the blank line)\n", nhdrs);

    /* 3. We implement GET only. Anything else gets a clear refusal, which is
     *    what the protocol expects -- not a dropped connection. */
    if (strcasecmp(method, "GET") != 0) {
        serve_error(fd, "501", "Not Implemented",
                    "This server implements GET only.");
        return;
    }

    /* 4. Map the URI to a path under docroot.
     *    "/" means the directory's index page, by convention. */
    if (!strcmp(uri, "/"))
        strcpy(uri, "/index.html");

    /* [Edge cases] Refuse any URI containing "..": without this check a request
       for /../../etc/passwd would escape the document root. Validating
       untrusted input before using it as a path is mandatory in a server, and
       the reason is this one line. */
    if (strstr(uri, "..")) {
        serve_error(fd, "403", "Forbidden", "Path traversal is not allowed.");
        return;
    }

    char path[MAXLINE];
    snprintf(path, sizeof(path), "%s%s", docroot, uri);

    /* 5. Does it exist, and is it an ordinary file? (Lecture 18's stat.) */
    struct stat st;
    if (stat(path, &st) < 0) {
        printf("  -> 404 (no such file: %s)\n", path);
        serve_error(fd, "404", "Not Found", "The requested file does not exist.");
        return;
    }
    if (!S_ISREG(st.st_mode)) {
        serve_error(fd, "403", "Forbidden", "Not a regular file.");
        return;
    }

    printf("  -> 200 OK, serving %s (%lld bytes, %s)\n",
           path, (long long)st.st_size, mime_type(path));
    serve_static(fd, path, (size_t)st.st_size);
}

int main(int argc, char **argv)
{
    const char *port    = (argc > 1) ? argv[1] : "15214";
    const char *docroot = (argc > 2) ? argv[2] : "www";
    int maxreq          = (argc > 3) ? atoi(argv[3]) : 1;

    int listenfd = open_listenfd(port);
    if (listenfd < 0) {
        fprintf(stderr, "tiny_server: cannot listen on port %s\n", port);
        return 1;
    }
    printf("[tiny] serving '%s' on http://127.0.0.1:%s/ "
           "(%d request(s) then exit)\n", docroot, port, maxreq);
    fflush(stdout);

    for (int i = 0; i < maxreq; i++) {
        int connfd = accept(listenfd, NULL, NULL);
        if (connfd < 0) { perror("accept"); break; }

        char who[128] = "unknown";
        peer_name(connfd, who, sizeof(who));
        printf("[tiny] request %d from %s\n", i + 1, who);

        serve_request(connfd, docroot);
        close(connfd);          /* HTTP/1.0: one request per connection */
        fflush(stdout);
    }

    close(listenfd);
    printf("[tiny] done\n");
    return 0;
}
