/*******************************************************************************
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.
*******************************************************************************/

#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <mswsock.h>

#include <iostream>
#include <cstring>
#include <mutex>
#include <atomic>

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

namespace netplus {

    // -------------------------------------------------------------------------
    // Global Winsock init (thread-safe, once)
    // -------------------------------------------------------------------------
    static std::once_flag g_wsa_once;
    static std::atomic<bool> g_wsa_ok{false};

    static void ensureWSA() {
        std::call_once(g_wsa_once, []() {
            WSADATA wsa{};
            int rc = ::WSAStartup(MAKEWORD(2, 2), &wsa);
            g_wsa_ok.store(rc == 0, std::memory_order_release);
        });

        if (!g_wsa_ok.load(std::memory_order_acquire)) {
            NetException e;
            e[NetException::Critical] << "WSAStartup failed";
            throw e;
        }
    }

    // -------------------------------------------------------------------------
    // socket::socket
    // -------------------------------------------------------------------------
    socket::socket() {
        ensureWSA();

        _Socket = INVALID_SOCKET;
        _Type   = -1;
        _Extension = 0;

        // allocate addrinfo container
        _SocketInfo = (ULONG_PTR)std::malloc(sizeof(addrinfo));
        _SocketInfoLen = sizeof(addrinfo);

        if (!_SocketInfo) {
            NetException e;
            e[NetException::Critical] << "socket::socket malloc failed";
            throw e;
        }

        std::memset((void*)_SocketInfo, 0, sizeof(addrinfo));
    }

    // -------------------------------------------------------------------------
    // socket::~socket
    // -------------------------------------------------------------------------
    socket::~socket() {
        // do NOT WSACleanup here!!!

        // cleanup stored addrinfo
        auto* ai = reinterpret_cast<addrinfo*>(_SocketInfo);
        if (ai) {
            if (ai->ai_addr) {
                std::free(ai->ai_addr);
                ai->ai_addr = nullptr;
            }
            if (ai->ai_canonname) {
                std::free(ai->ai_canonname);
                ai->ai_canonname = nullptr;
            }
            ai->ai_next = nullptr;

            std::free(ai);
            _SocketInfo = 0;
        }

        _SocketInfoLen = 0;
    }

    // -------------------------------------------------------------------------
    // socket::close
    // -------------------------------------------------------------------------
    void socket::close() {
        if (_Socket != INVALID_SOCKET) {
            ::closesocket(_Socket);
            _Socket = INVALID_SOCKET;
        }
    }

    // -------------------------------------------------------------------------
    // socket::fd
    // -------------------------------------------------------------------------
    SOCKET socket::fd() {
        return _Socket;
    }

    // -------------------------------------------------------------------------
    // socket::setFlag
    // Windows: only useful flag is nonblocking (FIONBIO)
    // -------------------------------------------------------------------------
    void socket::setFlag(int flag, int value) {
        (void)flag; // ignore

        u_long mode = (value != 0) ? 1UL : 0UL;
        if (::ioctlsocket(_Socket, FIONBIO, &mode) != 0) {
            NetException e;
            e[NetException::Error] << "socket::setFlag ioctlsocket failed: " << WSAGetLastError();
            throw e;
        }
    }

    // -------------------------------------------------------------------------
    // socket::setTimeout
    // usec = microseconds -> Windows expects milliseconds
    // -------------------------------------------------------------------------
    void socket::setTimeout(int usec) {
        if (_Socket == INVALID_SOCKET) return;

        int ms = (usec <= 0) ? 0 : (usec / 1000);

        if (::setsockopt(_Socket, SOL_SOCKET, SO_RCVTIMEO,
                         (const char*)&ms, sizeof(ms)) != 0) {
            NetException e;
            e[NetException::Error] << "socket::setTimeout SO_RCVTIMEO failed: " << WSAGetLastError();
            throw e;
        }

        if (::setsockopt(_Socket, SOL_SOCKET, SO_SNDTIMEO,
                         (const char*)&ms, sizeof(ms)) != 0) {
            NetException e;
            e[NetException::Error] << "socket::setTimeout SO_SNDTIMEO failed: " << WSAGetLastError();
            throw e;
        }
    }

    // -------------------------------------------------------------------------
    // socket::copyAddrInfo
    // Deep-copy addrinfo + sockaddr
    // dest must already be allocated (socket ctor does that)
    // -------------------------------------------------------------------------
    void socket::copyAddrInfo(ULONG_PTR* dest, ULONG_PTR src, size_t srclen) {
        if (!dest || !src) return;

        auto* s = reinterpret_cast<addrinfo*>(src);
        auto* d = reinterpret_cast<addrinfo*>(*dest);

        if (!s || !d) return;

        // wipe dest
        std::memset(d, 0, srclen);

        // copy primitive fields
        d->ai_flags    = s->ai_flags;
        d->ai_family   = s->ai_family;
        d->ai_socktype = s->ai_socktype;
        d->ai_protocol = s->ai_protocol;

        d->ai_next = nullptr;
        d->ai_canonname = nullptr;

        // deep-copy sockaddr
        d->ai_addrlen = s->ai_addrlen;

        if (d->ai_addr) {
            std::free(d->ai_addr);
            d->ai_addr = nullptr;
        }

        if (s->ai_addr && s->ai_addrlen > 0) {
            d->ai_addr = reinterpret_cast<sockaddr*>(std::malloc(s->ai_addrlen));
            if (!d->ai_addr) {
                NetException e;
                e[NetException::Critical] << "socket::copyAddrInfo malloc ai_addr failed";
                throw e;
            }
            std::memcpy(d->ai_addr, s->ai_addr, s->ai_addrlen);
        }

        // canonname optional
        if (d->ai_canonname) {
            std::free(d->ai_canonname);
            d->ai_canonname = nullptr;
        }
        if (s->ai_canonname) {
            size_t n = std::strlen(s->ai_canonname) + 1;
            d->ai_canonname = (char*)std::malloc(n);
            if (d->ai_canonname)
                std::memcpy(d->ai_canonname, s->ai_canonname, n);
        }
    }


} // namespace netplus
