/*
 * MIT License
 *
 * Copyright (c) 2019 Jianhui Zhao <zhaojh329@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <arpa/inet.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netdb.h>
#include <ev.h>

#include "list.h"
#include "net.h"
#include "log/log.h"

struct net_context {
    struct ev_timer tmr;
    struct ev_io iow;
    char addr[128];
    int sock;
    void *arg;

    void (*on_connected)(int sock, void *arg);
};

static const char *port2str(int port)
{
    static char buffer[sizeof("65535\0")];

    if (port < 0 || port > 65535)
        return NULL;

    snprintf(buffer, sizeof(buffer), "%u", port);

    return buffer;
}

static void sockaddr_to_str(const struct sockaddr *addr, char *buf, size_t len)
{
    char ip[INET6_ADDRSTRLEN] = "";
    int port;

    if (addr->sa_family == AF_INET) {
        struct sockaddr_in *in = (struct sockaddr_in *)addr;
        inet_ntop(AF_INET, &in->sin_addr, ip, sizeof(ip));
        port = ntohs(in->sin_port);
    } else {
        struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr;
        inet_ntop(AF_INET6, &in6->sin6_addr, ip, sizeof(ip));
        port = ntohs(in6->sin6_port);
    }

    snprintf(buf, len, "%s:%d", ip, port);
}

static void sock_write_cb(struct ev_loop *loop, struct ev_io *w, int revents)
{
    struct net_context *ctx = container_of(w, struct net_context, iow);
    int err = 0;
    socklen_t len = sizeof(err);
    int ret;

    ev_io_stop(loop, w);
    ev_timer_stop(loop, &ctx->tmr);

    ret = getsockopt(w->fd, SOL_SOCKET, SO_ERROR, &err, &len);
    if (ret < 0) {
        log_err("getsockopt: %s\n", strerror(errno));
        goto err;
    }

    if (err > 0) {
        log_err("connect '%s' failed: %s\n", ctx->addr, strerror(err));
        goto err;
    }

    ctx->on_connected(w->fd, ctx->arg);
    free(ctx);
    return;

err:
    close(w->fd);
    ctx->on_connected(-1, ctx->arg);
    free(ctx);
}

static void timer_cb(struct ev_loop *loop, struct ev_timer *w, int revents)
{
    struct net_context *ctx = container_of(w, struct net_context, tmr);

    log_err("connect '%s' timeout\n", ctx->addr);

    ev_io_stop(loop, &ctx->iow);
    close(ctx->sock);
    ctx->on_connected(-1, ctx->arg);
    free(ctx);
}

static void wait_connect(struct ev_loop *loop, int sock, int timeout,
                        const struct sockaddr *addr,
                        void (*on_connected)(int sock, void *arg), void *arg)
{
    struct net_context *ctx = calloc(1, sizeof(struct net_context));

    ctx->sock = sock;
    ctx->arg = arg;
    ctx->on_connected = on_connected;

    sockaddr_to_str(addr, ctx->addr, sizeof(ctx->addr));

    ev_timer_init(&ctx->tmr, timer_cb, timeout, 0);
    ev_timer_start(loop, &ctx->tmr);

    ev_io_init(&ctx->iow, sock_write_cb, sock, EV_WRITE);
    ev_io_start(loop, &ctx->iow);
}

int tcp_connect_sockaddr(struct ev_loop *loop, const struct sockaddr *addr, socklen_t addrlen,
                void (*on_connected)(int sock, void *arg), void *arg)
{
    int sock;

    sock = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
    if (sock < 0) {
        log_err("create socket failed: %s\n", strerror(errno));
        return -1;
    }

    if (connect(sock, addr, addrlen) < 0) {
        if (errno != EINPROGRESS) {
            char buf[128];
            sockaddr_to_str(addr, buf, sizeof(buf));
            log_err("connect '%s' failed: %s\n", buf, strerror(errno));
            goto err;
        }
        wait_connect(loop, sock, 3, addr, on_connected, arg);
    } else {
        on_connected(sock, arg);
    }

    return sock;

err:
    close(sock);
    return -1;
}

static int getaddr_by_name(int socktype, const char *host, int port,
        struct sockaddr *dest, int *addrlen)
{
    struct addrinfo *result, *rp;
    struct addrinfo hints = {
        .ai_family = AF_UNSPEC,
        .ai_socktype = socktype,
        .ai_flags = AI_ADDRCONFIG
    };
    int ret;

    ret = getaddrinfo(host, port2str(port), &hints, &result);
    if (ret) {
        if (ret == EAI_SYSTEM) {
            log_err("getaddrinfo failed: %s\n", strerror(errno));
            return -1;
        }

        log_err("getaddrinfo failed: %s\n", gai_strerror(ret));
        return -1;
    }

    ret = -1;

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        if (rp->ai_family == AF_INET || rp->ai_family == AF_INET6) {
            memcpy(dest, rp->ai_addr, rp->ai_addrlen);
            *addrlen = rp->ai_addrlen;
            ret = 0;
            break;
        }
    }

    freeaddrinfo(result);

    return ret;
}

int tcp_connect(struct ev_loop *loop, const char *host, int port,
                void (*on_connected)(int sock, void *arg), void *arg)
{
    struct sockaddr addr;
    int addrlen;

    log_debug("connecting to %s:%d\n", host, port);

    if (getaddr_by_name(SOCK_STREAM, host, port, &addr, &addrlen)) {
        log_err("getaddrinfo failed: Not found addr\n");
        return -1;
    }

    return tcp_connect_sockaddr(loop, &addr, addrlen, on_connected, arg);
}

int udp_connect(struct ev_loop *loop, const char *host, int port,
                void (*on_connected)(int sock, void *arg), void *arg)
{
    struct sockaddr addr;
    int addrlen;
    int sock;
    int ret;

    log_debug("connecting to %s:%d\n", host, port);

    if (getaddr_by_name(SOCK_DGRAM, host, port, &addr, &addrlen)) {
        log_err("getaddrinfo failed: Not found addr\n");
        return -1;
    }

    sock = socket(addr.sa_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
    if (sock < 0) {
        log_err("create socket failed: %s\n", strerror(errno));
        return -1;
    }

    ret = connect(sock, &addr, addrlen);
    if (ret < 0) {
        close(sock);
        log_err("connect '%s:%d' failed: %s\n", host, port, strerror(errno));
        return -1;
    }

    on_connected(sock, arg);

    return sock;
}
