/* =============================================================================
 * echoserver.c -- the simplest complete server: read a line, send it back
 * =============================================================================
 *
 * [Idea]
 *   An "echo server" does nothing useful, which is the point: it shows the
 *   SHAPE of every server with no application logic in the way.
 *
 *       open_listenfd()             become reachable at a port
 *       loop:
 *           accept()                wait for a client; get a NEW descriptor
 *           serve that descriptor   read/write it like a file
 *           close()                 done with this client
 *
 *   This is an ITERATIVE server: it finishes with one client before accepting
 *   the next. Simple and strictly ordered -- and a client that stalls blocks
 *   everyone behind it, which is the motivation for the concurrent servers of
 *   Lecture 21.
 *
 * [What it answers]
 *   - What is the difference between a listening and a connected descriptor?
 *   - How does a server know who connected?
 *   - Why read lines with RIO instead of read()?
 *
 * Usage:   ./echoserver [port] [max_connections]
 *          defaults: port 15213, 1 connection (then it exits, so demos end)
 *
 * It binds the LOOPBACK interface only (see netutil.c), so it is reachable
 * from this machine and not from the network.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>   /* accept */
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

/* Serve one connected client: echo every line until it closes the connection. */
static int echo_one(int connfd)
{
    rio_t rio;
    char  buf[MAXLINE];
    int   lines = 0;
    size_t bytes = 0;

    /* Attach a buffered reader to the SOCKET. Exactly the same call that read a
       file in Lecture 18 -- a socket is just a descriptor. */
    rio_readinitb(&rio, connfd);

    ssize_t n;
    while ((n = rio_readlineb(&rio, buf, MAXLINE)) > 0) {
        /* n > 0 bytes, ending in '\n' unless the client closed mid-line.
           Echo them straight back with rio_writen (which cannot short-write). */
        if (rio_writen(connfd, buf, (size_t)n) != n) {
            perror("rio_writen");
            break;
        }
        lines++;
        bytes += (size_t)n;
    }
    /* rio_readlineb returned 0: the client closed its end (EOF). That is the
       normal way a connection ends -- not an error. */
    printf("  served %d line(s), %zu byte(s), then the client closed (EOF)\n",
           lines, bytes);
    return lines;
}

int main(int argc, char **argv)
{
    const char *port = (argc > 1) ? argv[1] : "15213";
    int maxconn      = (argc > 2) ? atoi(argv[2]) : 1;

    /* 1. One LISTENING descriptor: a request queue, never read or written. */
    int listenfd = open_listenfd(port);
    if (listenfd < 0) {
        fprintf(stderr, "echoserver: cannot listen on port %s\n", port);
        return 1;
    }
    printf("[server] listening on 127.0.0.1:%s (listenfd=%d), "
           "will serve %d connection(s)\n", port, listenfd, maxconn);
    fflush(stdout);

    for (int i = 0; i < maxconn; i++) {
        /* 2. accept() blocks until a client connects, then returns a brand-new
         *    CONNECTED descriptor for that one client. listenfd stays open and
         *    keeps queueing others. This is the call that makes one server able
         *    to hold many simultaneous conversations. */
        int connfd = accept(listenfd, NULL, NULL);
        if (connfd < 0) { perror("accept"); break; }

        char who[128] = "unknown";
        peer_name(connfd, who, sizeof(who));
        printf("[server] connection %d accepted from %s (connfd=%d)\n",
               i + 1, who, connfd);
        fflush(stdout);

        /* 3. Serve it, then close THIS descriptor (not the listening one). */
        echo_one(connfd);
        close(connfd);
        printf("[server] closed connfd=%d\n", connfd);
        fflush(stdout);
    }

    close(listenfd);
    printf("[server] done; listening socket closed\n");

    printf("\nObservations (server side)\n--------------------------\n");
    printf("- listenfd and connfd are DIFFERENT descriptors: the first is a\n");
    printf("  queue of connection requests, the second is one conversation.\n");
    printf("- the connected socket was read and written with the same RIO calls\n");
    printf("  that read a file in Lecture 18 -- 'everything is a file' pays off.\n");
    printf("- a line-count of 0 bytes read means EOF: the client closed. That\n");
    printf("  is how a server learns a conversation is over.\n");
    printf("- this server is ITERATIVE: it served its client to completion before\n");
    printf("  it would accept another. One slow client blocks all the rest,\n");
    printf("  which is why Lecture 21 makes servers concurrent.\n");
    return 0;
}
