/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include "socket.h"
#include "exception.h"
#include "error.h"

#include <cstdio>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/un.h>
#include <sys/uio.h>       // iovec, sendmmsg, recvmmsg
#include <netinet/udp.h>   // SOL_UDP / IPPROTO_UDP

// FreeBSD uses IPPROTO_UDP where Linux uses SOL_UDP
#ifndef SOL_UDP
#define SOL_UDP IPPROTO_UDP
#endif

// Linux-specific: constants may be missing in old kernel headers or on FreeBSD.
// probeGSOGRO() will fail gracefully — setsockopt returns ENOPROTOOPT.
#ifndef UDP_SEGMENT
#define UDP_SEGMENT 103
#endif
#ifndef UDP_GRO
#define UDP_GRO 104
#endif

// macOS lacks sendmmsg/recvmmsg; FreeBSD 11+ and Linux have them.
#if defined(__APPLE__)
#define NETPLUS_NO_MMSG 1
#endif

namespace netplus {

udp::udp() : socket() {
    _Socket = -1;
    _Type = sockettype::UDP;
}

udp::udp(SOCKET sock) : socket() {
    _Socket = sock;
    _Type   = sockettype::UDP;
}

udp::~udp() {
    if (_Socket >= 0)
        socket::close();
}

udp::udp(const std::string& addr, int port, int maxconnections, int sockopts)
: socket() {
    _Maxconnections = maxconnections;
    _Type = sockettype::UDP;

    if (sockopts == -1)
        sockopts = SO_REUSEADDR;

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags    = AI_PASSIVE;

    addrinfo* result = nullptr;
    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.empty() ? nullptr : addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        NetException e;
        e[NetException::Critical] << "udp getaddrinfo: " << gai_strerror(gai);
        throw e;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {
        _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (_Socket < 0)
            continue;

        setAddrFromAI(rp);
        break;
    }

    ::freeaddrinfo(result);

    if (_Socket < 0) {
        NetException e;
        e[NetException::Critical] << "Failed to create UDP socket";
        throw e;
    }

    int opt = 1;
    if (sockopts & SO_REUSEADDR)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif

}

udp::udp(const std::string& uxsocket, int maxconnections, int sockopts)
: socket() {
    _Maxconnections=maxconnections;
    _Type = sockettype::UDP;

    if ((_Socket = ::socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) {
        NetException e;
        e[NetException::Critical] << "Can't create Unix UDP Socket";
        throw e;
    }

    sockaddr_un un{};
    un.sun_family = AF_UNIX;
    std::snprintf(un.sun_path, sizeof(un.sun_path), "%s", uxsocket.c_str());

    std::memset(&_Addr, 0, sizeof(_Addr));
    std::memcpy(&_Addr, &un, sizeof(un));
    _AddrLen = sizeof(un);

    int opt = 1;
    if (sockopts == -1) sockopts = SO_REUSEADDR;

    if (sockopts & SO_REUSEADDR)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif
}

void udp::bind() {
    if (_Bound) return;
    if (::bind(_Socket, reinterpret_cast<sockaddr*>(&_Addr), _AddrLen) < 0) {
        NetException e;
        e[NetException::Error] << "udp::bind failed: " << strerror(errno);
        throw e;
    }
    _Bound = true;
}

void udp::listen() {
    // UDP has no listen
    _Listening = true;
}

void udp::setNonBlock() {
    setFlag(O_NONBLOCK, 1);
}

void udp::setBlock() {
    setFlag(O_NONBLOCK, 0);
}

int udp::getMaxconnections() {
    return _Maxconnections;
}

udp& udp::operator=(SOCKET s) {
    _Socket = s;
    return *this;
}

void udp::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    // UDP accept = no-op
    (void)csock;
    (void)nonblock;
}

size_t udp::sendData(buffer& data, int flags) {
    const char* p = data.ptr ? data.data.ptr : data.data.buf;
    ssize_t s = ::send(_Socket, p, data.size, flags);

    if (s < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::sendData would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "udp::sendData failed: " << strerror(errno);
        throw e;
    }

    return (size_t)s;
}

size_t udp::sendTo(buffer& data, int flags) {
    const char* p = data.ptr ? data.data.ptr : data.data.buf;
    ssize_t s = ::sendto(_Socket, p, data.size, flags,
                         reinterpret_cast<const sockaddr*>(&_Addr), _AddrLen);

    if (s < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::sendTo would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "udp::sendTo failed: " << strerror(errno);
        throw e;
    }

    return (size_t)s;
}

size_t udp::recvData(buffer& data, int flags) {
    sockaddr_storage peer{};
    socklen_t peerLen = sizeof(peer);

    ssize_t r = ::recvfrom(_Socket, data.data.buf, data.size, flags,
                           reinterpret_cast<sockaddr*>(&peer), &peerLen);

    if (r > 0) {
        data.size = (size_t)r;
        return (size_t)r;
    }
    if (r == 0) return 0;

    if (errno == EAGAIN || errno == EWOULDBLOCK) {
        NetException e;
        e[NetException::Note] << "udp::recvData would block";
        throw e;
    }

    NetException e;
    e[NetException::Error] << "udp::recvData failed: " << strerror(errno);
    throw e;
}

void netplus::udp::connect(const std::string& addr, int port,bool ){
    NetException exception;

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;      // IPv4 oder IPv6
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = IPPROTO_UDP;

    addrinfo* result = nullptr;

    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        exception[NetException::Error]
            << "udp::connect: getaddrinfo failed: " << gai_strerror(gai);
        throw exception;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {

        // ✅ Socket erstellen falls nicht da
        if (_Socket < 0) {
            _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
            if (_Socket < 0)
                continue;
        }

        // ✅ connect UDP (bindet Default Peer)
        if (::connect(_Socket, rp->ai_addr, rp->ai_addrlen) == 0) {

            // ✅ Adresse sauber speichern (deep copy)
            copyAddrInfo(&_SocketInfo,
                         reinterpret_cast<ULONG_PTR>(rp),
                         sizeof(addrinfo));

            _SocketInfoLen = rp->ai_addrlen;

            ::freeaddrinfo(result);
            return;
        }

        // Fehler -> neuen Socket versuchen
        ::close(_Socket);
        _Socket = -1;
    }

    ::freeaddrinfo(result);

    exception[NetException::Error]
        << "udp::connect: could not connect to " << addr << ":" << port
        << " (" << strerror(errno) << ")";
    throw exception;
}

void udp::getAddress(std::string& addr) {
    char buf[INET6_ADDRSTRLEN]{};
    sockaddr* sa = reinterpret_cast<sockaddr*>(&_Addr);

    if (sa->sa_family == AF_INET) {
        inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, buf, sizeof(buf));
        addr = buf;
    } else if (sa->sa_family == AF_INET6) {
        inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, buf, sizeof(buf));
        addr = buf;
    } else {
        addr = "";
    }
}

void udp::flush_out() {
}

// ============================================================================
// UDP GSO/GRO: Probe kernel support at socket init
// ============================================================================

void udp::probeGSOGRO(uint16_t segment_size) {
    _gso_segment_size = segment_size;
    _gso_enabled = false;
    _gro_enabled = false;

    if (_Socket < 0) return;

    // Probe UDP_SEGMENT (GSO) — a setsockopt that succeeds means the
    // kernel supports generic segmentation offload for UDP.
    uint16_t seg = segment_size;
    if (::setsockopt(_Socket, SOL_UDP, UDP_SEGMENT, &seg, sizeof(seg)) == 0) {
        _gso_enabled = true;
    }

    // Probe UDP_GRO
    int gro_val = 1;
    if (::setsockopt(_Socket, SOL_UDP, UDP_GRO, &gro_val, sizeof(gro_val)) == 0) {
        _gro_enabled = true;
    }
}

// ============================================================================
// UDP Batched Send: sendmmsg + GSO when available
// ============================================================================

ssize_t udp::sendBatch(
    const std::vector<std::pair<const uint8_t*, size_t>>& datagrams,
    sockaddr_storage* dest, socklen_t dest_len)
{
    if (datagrams.empty()) return 0;
    if (_Socket < 0) return -1;

    const size_t count = datagrams.size();

    // --- GSO path: coalesce uniform-sized datagrams into one sendmsg ---
    if (_gso_enabled && count > 1) {
        bool uniform = true;
        size_t seg_size = datagrams[0].second;
        // Last datagram may be shorter (tail segment) — GSO allows that.
        for (size_t i = 1; i < count - 1; ++i) {
            if (datagrams[i].second != seg_size) { uniform = false; break; }
        }

        if (uniform) {
            // Build one big buffer
            size_t total_bytes = 0;
            for (auto& [p, l] : datagrams) total_bytes += l;

            std::vector<uint8_t> coalesced(total_bytes);
            size_t off = 0;
            for (auto& [p, l] : datagrams) {
                std::memcpy(coalesced.data() + off, p, l);
                off += l;
            }

            struct iovec iov;
            iov.iov_base = coalesced.data();
            iov.iov_len  = coalesced.size();

            // cmsg carrying UDP_SEGMENT size
            union {
                char buf[CMSG_SPACE(sizeof(uint16_t))];
                struct cmsghdr align;
            } cmsg_buf;

            struct msghdr msg{};
            if (dest) {
                msg.msg_name    = dest;
                msg.msg_namelen = dest_len;
            }
            msg.msg_iov        = &iov;
            msg.msg_iovlen     = 1;
            msg.msg_control    = cmsg_buf.buf;
            msg.msg_controllen = sizeof(cmsg_buf.buf);

            struct cmsghdr* cm = CMSG_FIRSTHDR(&msg);
            cm->cmsg_level = SOL_UDP;
            cm->cmsg_type  = UDP_SEGMENT;
            cm->cmsg_len   = CMSG_LEN(sizeof(uint16_t));
            *reinterpret_cast<uint16_t*>(CMSG_DATA(cm)) =
                static_cast<uint16_t>(seg_size);

            ssize_t ret = ::sendmsg(_Socket, &msg, MSG_DONTWAIT);
            if (ret > 0) return static_cast<ssize_t>(count);
            // GSO failed — fall through to sendmmsg
        }
    }

    // --- sendmmsg path ---
#ifdef NETPLUS_NO_MMSG
    // Fallback: sendto loop for platforms without sendmmsg
    int sent = 0;
    for (size_t i = 0; i < count; ++i) {
        ssize_t r;
        if (dest) {
            r = ::sendto(_Socket, datagrams[i].first, datagrams[i].second,
                         MSG_DONTWAIT, reinterpret_cast<sockaddr*>(dest), dest_len);
        } else {
            r = ::send(_Socket, datagrams[i].first, datagrams[i].second, MSG_DONTWAIT);
        }
        if (r < 0) break;
        ++sent;
    }
#else
    std::vector<struct iovec> iovecs(count);
    std::vector<struct mmsghdr> msgs(count);
    std::memset(msgs.data(), 0, sizeof(struct mmsghdr) * count);

    for (size_t i = 0; i < count; ++i) {
        iovecs[i].iov_base = const_cast<uint8_t*>(datagrams[i].first);
        iovecs[i].iov_len  = datagrams[i].second;
        msgs[i].msg_hdr.msg_iov    = &iovecs[i];
        msgs[i].msg_hdr.msg_iovlen = 1;
        if (dest) {
            msgs[i].msg_hdr.msg_name    = dest;
            msgs[i].msg_hdr.msg_namelen = dest_len;
        }
    }

    int sent = ::sendmmsg(_Socket, msgs.data(),
                          static_cast<unsigned int>(count), MSG_DONTWAIT);
#endif
    return sent;
}

// ============================================================================
// UDP Batched Recv: recvmmsg + GRO splitting
// ============================================================================

size_t udp::recvBatch(std::vector<std::vector<uint8_t>>& out, int max_count) {
    std::vector<sockaddr_storage> dummy_addrs;
    return recvBatchAddr(out, dummy_addrs, max_count);
}

size_t udp::recvBatchAddr(std::vector<std::vector<uint8_t>>& out,
                           std::vector<sockaddr_storage>& addrs,
                           int max_count) {
    out.clear();
    addrs.clear();
    if (_Socket < 0) return 0;

    const int batch = std::min(max_count, 64);

#ifdef NETPLUS_NO_MMSG
    // Fallback: recvfrom loop for platforms without recvmmsg
    static thread_local std::vector<uint8_t> recv_buf(65535);
    for (int i = 0; i < batch; ++i) {
        sockaddr_storage peer{};
        socklen_t peer_len = sizeof(peer);
        ssize_t n = ::recvfrom(_Socket, recv_buf.data(), recv_buf.size(),
                               MSG_DONTWAIT,
                               reinterpret_cast<sockaddr*>(&peer), &peer_len);
        if (n <= 0) break;
        out.emplace_back(recv_buf.data(), recv_buf.data() + n);
        addrs.push_back(peer);
    }
    return out.size();
#else
    // Use thread_local static buffers to avoid 64×65KB heap allocation per call.
    // These are reused across calls on the same thread.
    static constexpr int MAX_BATCH = 64;
    static thread_local std::vector<uint8_t> flat_buf(MAX_BATCH * 65535);
    static thread_local struct iovec iovecs[MAX_BATCH];
    static thread_local struct mmsghdr msgs[MAX_BATCH];
    static thread_local sockaddr_storage peer_addrs[MAX_BATCH];
    static constexpr size_t CMSG_BUF_SIZE = CMSG_SPACE(sizeof(uint16_t));
    static thread_local char cmsg_bufs[MAX_BATCH * CMSG_BUF_SIZE];

    std::memset(msgs, 0, sizeof(struct mmsghdr) * batch);
    std::memset(peer_addrs, 0, sizeof(sockaddr_storage) * batch);

    for (int i = 0; i < batch; ++i) {
        iovecs[i].iov_base = flat_buf.data() + i * 65535;
        iovecs[i].iov_len  = 65535;
        msgs[i].msg_hdr.msg_iov     = &iovecs[i];
        msgs[i].msg_hdr.msg_iovlen  = 1;
        msgs[i].msg_hdr.msg_name    = &peer_addrs[i];
        msgs[i].msg_hdr.msg_namelen = sizeof(sockaddr_storage);
        if (_gro_enabled) {
            msgs[i].msg_hdr.msg_control    = &cmsg_bufs[i * CMSG_BUF_SIZE];
            msgs[i].msg_hdr.msg_controllen = CMSG_BUF_SIZE;
        }
    }

    struct timespec timeout = {0, 0}; // non-blocking
    int received = ::recvmmsg(_Socket, msgs, batch, MSG_DONTWAIT, &timeout);
    if (received <= 0) return 0;

    for (int i = 0; i < received; ++i) {
        size_t total_len = msgs[i].msg_len;
        if (total_len == 0) continue;

        uint8_t* base = flat_buf.data() + i * 65535;

        // Check for GRO coalescing
        uint16_t gro_seg = 0;
        if (_gro_enabled) {
            for (struct cmsghdr* cm = CMSG_FIRSTHDR(&msgs[i].msg_hdr);
                 cm != nullptr;
                 cm = CMSG_NXTHDR(&msgs[i].msg_hdr, cm)) {
                if (cm->cmsg_level == SOL_UDP && cm->cmsg_type == UDP_GRO) {
                    gro_seg = *reinterpret_cast<uint16_t*>(CMSG_DATA(cm));
                    break;
                }
            }
        }

        if (gro_seg > 0 && total_len > gro_seg) {
            // Split coalesced GRO buffer into individual datagrams
            size_t off = 0;
            while (off < total_len) {
                size_t seg_len = std::min(static_cast<size_t>(gro_seg),
                                          total_len - off);
                out.emplace_back(base + off, base + off + seg_len);
                addrs.push_back(peer_addrs[i]);
                off += seg_len;
            }
        } else {
            out.emplace_back(base, base + total_len);
            addrs.push_back(peer_addrs[i]);
        }
    }

    return out.size();
#endif // NETPLUS_NO_MMSG
}

} // namespace netplus
