/* =============================================================================
 * netutil.c -- open_listenfd / open_clientfd, commented line by line
 * =============================================================================
 *
 * Read netutil.h first for the shape of the sockets interface. This file is the
 * lecture's centerpiece: every call in the server and client columns, in order,
 * with the reason it exists.
 * -----------------------------------------------------------------------------
 */
#include "netutil.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>          /* getaddrinfo, getnameinfo */
#include <sys/socket.h>     /* socket, bind, listen, accept, connect */

#define LISTEN_BACKLOG 16   /* how many pending connections the kernel queues */

/* ---------------------------------------------------------------------------
 * open_clientfd -- the client side: socket() + connect()
 * ---------------------------------------------------------------------------
 */
int open_clientfd(const char *host, const char *port)
{
    struct addrinfo hints, *list, *p;

    /* 1. Ask getaddrinfo for addresses suitable for a TCP CLIENT connection.
     *    ai_socktype=SOCK_STREAM  -> TCP, not UDP
     *    ai_family=AF_UNSPEC      -> accept IPv4 and IPv6 answers
     *    AI_NUMERICSERV           -> the port is digits, not a service name
     *    AI_ADDRCONFIG            -> only return families this host can use
     */
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family   = AF_UNSPEC;
    hints.ai_flags    = AI_NUMERICSERV | AI_ADDRCONFIG;

    int rc = getaddrinfo(host, port, &hints, &list);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo(%s,%s): %s\n", host, port, gai_strerror(rc));
        return -1;
    }

    /* 2. Walk the list and try each address until one connects.
     *    This loop is not optional: 'localhost' resolves to BOTH ::1 and
     *    127.0.0.1 (Lecture 19), and the first one may be unusable. */
    int fd = -1;
    for (p = list; p != NULL; p = p->ai_next) {
        /* socket() creates an unconnected endpoint. The three arguments come
           straight from the addrinfo entry, which is why getaddrinfo is worth
           using: it fills in family/type/protocol consistently. */
        fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (fd < 0)
            continue;                   /* this family is unavailable; try next */

        /* connect() performs TCP's three-way handshake with the server and
           blocks until it completes (or is refused / times out). On success the
           descriptor is a full-duplex byte stream to the peer. */
        if (connect(fd, p->ai_addr, p->ai_addrlen) == 0)
            break;                      /* success */

        close(fd);                      /* [C tip] a failed connect leaves the
                                           socket unusable: close and retry the
                                           NEXT address, never reuse it. */
        fd = -1;
    }

    freeaddrinfo(list);                 /* the list is malloc'd by getaddrinfo */
    return fd;                          /* -1 if every address failed */
}

/* ---------------------------------------------------------------------------
 * open_listenfd -- the server side: socket() + bind() + listen()
 * ---------------------------------------------------------------------------
 */
int open_listenfd(const char *port)
{
    struct addrinfo hints, *list, *p;

    /* 1. Ask for addresses suitable for a SERVER to bind.
     *    AI_PASSIVE means "I intend to bind this, not connect to it".
     *
     *    [Note on the host argument] A production server passes NULL here,
     *    which with AI_PASSIVE yields the wildcard address (0.0.0.0 / ::) and
     *    listens on EVERY network interface. These demos pass "localhost" so
     *    the socket is bound to the LOOPBACK interface only and is reachable
     *    from this machine alone -- the right default for a teaching program,
     *    which should not open a port to the network.
     */
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family   = AF_UNSPEC;
    hints.ai_flags    = AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG;

    int rc = getaddrinfo("localhost", port, &hints, &list);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo(localhost,%s): %s\n", port, gai_strerror(rc));
        return -1;
    }

    int fd = -1;
    for (p = list; p != NULL; p = p->ai_next) {
        fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (fd < 0)
            continue;

        /* SO_REUSEADDR: let us bind this port again immediately after the
           server exits. Without it the port sits in TCP's TIME_WAIT state for
           a minute or two and a quick restart fails with "address already in
           use" -- the single most common annoyance in socket programming. */
        int on = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

        /* bind() claims the address+port for this socket: "messages sent here
           belong to me". It is what makes a server findable. */
        if (bind(fd, p->ai_addr, p->ai_addrlen) == 0)
            break;

        close(fd);
        fd = -1;
    }
    freeaddrinfo(list);

    if (fd < 0)
        return -1;

    /* listen() converts the socket from "could be a client" to a passive
       LISTENING socket: the kernel starts accepting handshakes on our behalf and
       queues up to LISTEN_BACKLOG completed connections for us to accept(). */
    if (listen(fd, LISTEN_BACKLOG) < 0) {
        close(fd);
        return -1;
    }
    return fd;
}

/* ---------------------------------------------------------------------------
 * peer_name -- who is on the other end of this connected descriptor?
 * ---------------------------------------------------------------------------
 * [Idea] getpeername() asks the kernel for the peer's socket address;
 *        getnameinfo() renders it as printable text (Lecture 19).
 */
int peer_name(int fd, char *buf, size_t buflen)
{
    struct sockaddr_storage ss;     /* big enough for IPv4 OR IPv6 */
    socklen_t len = sizeof(ss);
    if (getpeername(fd, (struct sockaddr *)&ss, &len) < 0)
        return -1;

    char host[NI_MAXHOST], serv[NI_MAXSERV];
    if (getnameinfo((struct sockaddr *)&ss, len,
                    host, sizeof(host), serv, sizeof(serv),
                    NI_NUMERICHOST | NI_NUMERICSERV) != 0)
        return -1;

    snprintf(buf, buflen, "%s:%s", host, serv);
    return 0;
}
