/*******************************************************************************
 C *opyright (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 <cstdlib>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <poll.h>

namespace netplus {

socket::socket() {
    _Socket = -1;
    _Type   = -1;
    _Extension = 0;
    std::memset(&_Addr, 0, sizeof(_Addr));
    _AddrLen = sizeof(_Addr);
}

socket::~socket() {
    // no heap free needed
}

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

void netplus::socket::close() {
    if (_Socket < 0) return;

    int fd = _Socket;
    _Socket = -1; // prevent double close races early

    ::shutdown(fd, SHUT_RDWR);

    int rc;
    do {
        rc = ::close(fd);
    } while (rc < 0 && errno == EINTR);
}

void socket::setFlag(int flag, int value) {
    int sockopts;
    do {
        sockopts = ::fcntl(_Socket, F_GETFL, 0);
    } while (sockopts < 0 && errno == EINTR);

    if (sockopts < 0) {
        NetException e;
        e[NetException::Error] << "fcntl(F_GETFL) failed: " << strerror(errno);
        throw e;
    }

    if (value)
        sockopts |= flag;
    else
        sockopts &= ~flag;

    int r;
    do {
        r = ::fcntl(_Socket, F_SETFL, sockopts);
    } while (r < 0 && errno == EINTR);

    if (r < 0) {
        NetException e;
        e[NetException::Error] << "fcntl(F_SETFL) failed: " << strerror(errno);
        throw e;
    }
}


void socket::setTimeout(int msec) {
    timeval timeout{};
    timeout.tv_sec  = msec / 1000;
    timeout.tv_usec = (msec % 1000) * 1000;

    if (::setsockopt(_Socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
        NetException e;
        e[NetException::Error] << "setsockopt SO_RCVTIMEO failed";
        throw e;
    }

    if (::setsockopt(_Socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) {
        NetException e;
        e[NetException::Error] << "setsockopt SO_SNDTIMEO failed";
        throw e;
    }
}

void netplus::socket::copyAddrInfo(ULONG_PTR* dest, ULONG_PTR src, size_t){
    auto* s = reinterpret_cast<addrinfo*>(src);
    if (!s || !s->ai_addr || s->ai_addrlen <= 0)
        return;

    // store sockaddr in _Addr (sockaddr_storage)
    std::memset(&_Addr, 0, sizeof(_Addr));
    std::memcpy(&_Addr, s->ai_addr, std::min<size_t>(sizeof(_Addr), s->ai_addrlen));
    _AddrLen = (socklen_t)s->ai_addrlen;
}


} // namespace netplus
