/*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: sock.c,v 1.13 2001/07/19 03:54:26 mbp Exp $
 * 
 * Copyright (C) 2001 by Martin Pool <mbp@samba.org>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

                    /*
                     | Nothing motivates a man more than to see his boss
                     | put in an honest day's work.
                     */

/* Networking utility functions.  See RFC2133 for a description of the
 * extended IPv6 API we use here.
 *
 * To make this use IPv6 for hosts that have both kinds of address,
 * set the environment variable RES_OPTIONS=inet6. */


#define LOG_DOMAIN "n4net"

#include "includes.h"

#include <signal.h>
#include <arpa/inet.h>

#include <netinet/in.h>
#include <netinet/tcp.h>

#include <sys/socket.h>

#define N4_SNDBUFSIZE (64 << 10)
#define N4_RCVBUFSIZE (64 << 10)


/**
 * Open a socket of the specified type, port and address for incoming
 * data.  Type should be SOCK_STREAM or SOCK_DGRAM.
 **/
int n4net_open_socket_in(int type, int port)
{
    struct sockaddr_in sock;
    int fd;
    int one=1;

    /**
     * FIXME:  Make this work for IP6 too.
     **/

    bzero((char *)&sock,sizeof(sock));

#ifdef HAVE_SOCK_SIN_LEN
    sock.sin_len = sizeof(sock);
#endif
    sock.sin_port = htons( port );
    sock.sin_family = AF_INET;

    fd = socket(PF_INET, type, 0);
    if (fd == -1) { 
        n4log_error("socket creation failed: %s", strerror(errno));
        return -1;
    }

    n4net_set_buf(fd, SO_SNDBUF, N4_SNDBUFSIZE);
    n4net_set_buf(fd, SO_RCVBUF, N4_RCVBUFSIZE);
    
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));

    /* now we've got a socket - we need to bind it */
    if (bind(fd, (struct sockaddr * ) &sock,sizeof(sock)) < 0) { 
        return(-1); 
    }

    return fd;
}




/**
 * Caller should free the structure returned in \p *addr.
 */
n4err n4_sockaddr_parse(const char *host, int port,
                        struct sockaddr **addr,
                        size_t *addr_len)
{
    struct hostent      *hostent;
    struct sockaddr_in  *sa4;
    struct sockaddr_in6 *sa6;

    hostent = gethostbyname(host);

    if (!hostent) {
        g_error("error finding host %s: %s", host, hstrerror(h_errno));
        return N4ERR_NET;
    }

    if (hostent->h_addrtype == AF_INET6) {
        sa6 = g_new0(struct sockaddr_in6, 1);

        sa6->sin6_family = AF_INET6;
        sa6->sin6_port = htons(port);
        memcpy(&sa6->sin6_addr, hostent->h_addr, hostent->h_length);

        *addr = (struct sockaddr *) sa6;
        *addr_len = sizeof *sa6;
    } else {
        sa4 = g_new0(struct sockaddr_in, 1);

        sa4->sin_family = AF_INET;
        sa4->sin_port = htons(port);
        memcpy(&sa4->sin_addr, hostent->h_addr, hostent->h_length);

        *addr = (struct sockaddr *) sa4;
        *addr_len = sizeof *sa4;
    }

    return N4OK;
}


n4err n4socket_open_out_byname(char const *hostname,
                               int port,
                               int sock_style,
                               int *fd)
{
    struct sockaddr *addr;
    size_t          addr_len;
    n4err           err;

    if ((err = n4_sockaddr_parse(hostname, port, &addr, &addr_len))) {
        n4log_error("error resolving %s:%d: %s", hostname, port,
                    strerror(errno));
        return err;
    }

    if ((err = n4socket_open_out(addr, addr_len, sock_style, fd))) {
        n4log_error("error connecting to host %s:%d: %s",
                    hostname, port, strerror(errno));
        return err;
    }

    return N4OK;
}


n4err n4socket_open_out(const struct sockaddr *addr,
                        size_t addr_len,
                        int sock_style,
                        int *fd)
{
    int         ret;

    /* Create a socket to write to */
    if ((*fd = socket(addr->sa_family, sock_style, IPPROTO_TCP)) == -1) {
	n4log_error("error creating socket: %s", strerror(errno));
	return N4ERR_NET;
    }

    CHECK_ERR(n4net_set_buf(*fd, SO_SNDBUF, N4_SNDBUFSIZE));
    CHECK_ERR(n4net_set_buf(*fd, SO_RCVBUF, N4_RCVBUFSIZE));
    ret = connect(*fd, addr, addr_len);

    if (ret < 0) {
	n4log_error("error connecting: %s", strerror(errno));
        return N4ERR_NET;
    }

    return N4OK;
}


n4err n4net_set_buf(int fd, int which_buf, int bufsize)
{
    socklen_t   optsize;
    char const  *name;

    switch (which_buf) {
    case SO_SNDBUF:
        name = "send";
        break;
    case SO_RCVBUF:
        name = "receive";
        break;
    default:
        n4fatal("bogus sockopt value %d", which_buf);
    }

    /* We want to always use large buffers for maximum throughput and
     * to avoid Nagle or delayed-ACK delays. */
    optsize = sizeof bufsize;
    if ((setsockopt(fd, SOL_SOCKET, which_buf, &bufsize, optsize)) == -1) {
        n4log_error("error setting fd%d socket %s buffer size: %s",
                     fd, name, strerror(errno));
        /* continue */
    }
    optsize = sizeof bufsize;
    if ((getsockopt(fd, SOL_SOCKET, which_buf, &bufsize, &optsize)) == -1) {
        n4log_error("error retrieving fd%d socket %s buffer size: %s",
                     fd, name, strerror(errno));
    } else {
/*          n4log_info("fd%d socket %s buffer set to %d bytes", */
/*                      fd, name, bufsize); */
    }

    return N4OK;
}


n4err n4_read_full(int fd, void *p, size_t len)
{
    size_t cnt;
    int rc;
    char *buf = (char *) p;

    for (cnt = 0; cnt < len; ) {
        /* MSG_WAITALL is a suggestion from Anton: we can't proceed
         * until we receive the whole packet, so we might as well
         * block until we get it all. */
        rc = recv(fd, buf, len - cnt, MSG_WAITALL);
        /* TODO: Perhaps eventually time out here. */
        if (rc == -1) {
            if (errno == EINTR)
                continue;
            n4log_error("recv error: %s", strerror(errno));
            return N4ERR_NET;
        } else if (rc == 0) {
            if (cnt == 0) {
                /* If we fail immediately, that's possibly harmless --
                 * higher level code will know if this is a point at
                 * which the connection may be dropped. */
                n4log_info("remote host closed connection");
                return N4ERR_CONN_CLOSED;
            } else {
                /* Failing halfway through is worse. */
                n4log_error("remote host dropped connection; "
                             "read only %ld of %ld atomic bytes",
                             (long) cnt, (long) len);
                return N4ERR_SHORT_READ;
            }
        } 
        buf += rc;
        cnt += rc;
    }

    return N4OK;
}



/**
 * \brief Write data to a file descriptor, looping until it has all been
 * written or an error occurs.
 **/
n4err n4_send_full(int fd, const void *p, size_t len)
{
    int                 cnt, rc;
    char                *buf = (char *) p;

    cnt = len;
    while (cnt > 0) {
        rc = send(fd, buf, cnt, 0);
        if (rc == -1) {
            if (errno == EINTR)
                continue;
            n4log_crit("send error on fd%d: %s", fd, strerror(errno));
            return n4err_from_unix(errno);
        }
        if (rc == 0) {
            n4log_crit("end of file on write fd%d after %d bytes",
                       fd, len - cnt);
            return NFS4ERR_IO;
        }
        buf += rc;
        cnt -= rc;
    }
    return N4OK;
}

		
/* Serve a single request on stdin/stdout.  This is useful for running
   under inetd, if you want to do that.  It's also good for debugging
   -- you can just pipe in the test data without the hassle of binding
   ports.

   Call this instead of start_accept_loop. */
void n4d_serve_inetd(int (*fn)(int, int, struct sockaddr *))
{
    fn(STDIN_FILENO, STDOUT_FILENO, NULL);
}



/**
 * Ignore SIGPIPE, so that we get EPIPE on broken network sockets.
 * That's easier to handle.
 *
 * This does mean if output from n4client is redirected to a pipe and
 * it breaks then we'll keep on blindly writing unless we check for
 * errors, which is not great.
 **/
n4err n4net_ignore_sigpipe(void) 
{
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        n4log_error("error turning off SIGPIPE: %s", strerror(errno));
        return N4ERR_NET;
    }
    return N4OK;
}

    
/**
 * Determine if a file descriptor is in fact a socket.  Code borrowed
 * from rsync.
 **/
int socket_p(int fd)
{
    int v, l;
    l = sizeof(int);

    /* Parameters to getsockopt, setsockopt etc are very
     * unstandardized across platforms, so don't be surprised if
     * there are compiler warnings on e.g. SCO OpenServer.  It
     * seems they all eventually get the right idea.
     *
     * Debian says: ``The fifth argument of getsockopt and
     * setsockopt is in reality an int [*] (and this is what BSD
     * 4.* and libc4 and libc5 have).  Some POSIX confusion
     * resulted in the present socklen_t.  The draft standard has
     * not been adopted yet, but glibc2 already follows it and
     * also has socklen_t [*]. See also accept(2).''
     *
     * We now return to your regularly scheduled programming.  */
    return getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0;
}


