/*= -*- c-file-style: "linux"; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: xdrrm.c,v 1.17 2001/09/10 05:59:29 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.
 */


                    /*
                     | Life is like an onion: you peel off layer after
                     | layer and then you find there is nothing in it.
                     |           -- James Huneker
                     */

#define LOG_DOMAIN "n4xdr"
#include "includes.h"

const size_t N4_MAX_PACKET_LEN = 1 << 20;




/** \file xdr-rm.c
 * \brief ONC RPC data marking protocol.
 *
 * This is used to form XDR-level packets on top of stream protocols
 * like TCP.  At this stage we don't know anything about the contents
 * -- they could be a request or a reply, etc.
 *
 * Each packet is preceded by an XDR integer, whose high bit tells
 * whether this is the last packet of a multi-packet message.  The
 * lower bits give the length of this packet.  Packets from different
 * messages may NOT be interleaved.
 *
 * There is a fairly strong abstraction layer just above this in the
 * program, across which we pass only XDR RM packets.  This allows for
 * different implementations in the future.  For example, we might
 * allow transport across UDP which (I think) does not have any prefix
 * words.  Or, we might want to experiment with a parent listener
 * process that passes received messages through a shared memory
 * buffer to child disk IO processes.
 *
 * \note Buffers are always destroyed by transmission.  When sending a
 * fragmented buffer we need to write over it to store the prefix
 * words.  This is OK because we don't implement or expect
 * retransmissions over TCP.  The TCP stack already stores a backup
 * copy of the data until it has been ack'ed by the receiver's stack,
 * so it's silly for us to do it in userspace too.
 *
 * \sa RFC1831 */

/*
 * XXX: Are there any circumstances in which it would be better to
 * transmit a message as several RM blocks?  I can't think of any.
 *
 * TODO: tridge suggests an option to force packets to be broken into
 * smaller fragments, so that we can at least test our defragmentation
 * code.  A difficulty here is that we won't have space in the buffer
 * for the prefixes for anything but the first fragment, so we have to
 * either make copies, or overwrite the buffer, or do two write()s for
 * each fragment.
 *
 * TODO: Allow the server code to pass data out as a fragment before
 * the whole packet is ready.  If we're reading bulk data, then this
 * allows us to use less buffer space on the server.  However, you can
 * only do this if you're really sure you're not going to change the
 * data earlier in the message.  For example, the COMPOUND REPLY
 * header can't be sent until we know how many operations completed
 * and what the final status was.
 *
 * TODO: We probably want to allow the administrator to set a maximum
 * length for generated packets, in case one of the clients has a
 * build in buffer.  It's not clear how to implement this, though: I
 * guess we could simply drop the packet, or replace it with a server
 * failure error, but that's not very constructive.
 *
 * For most of the cases where the reply can be substantially long,
 * the client has some kind of control over how much data will be
 * generated (e.g. by setting the length of the read request, or the
 * allowable output size for the READDIR request.  So really we have
 * to trust them to make that reasonable.
 */

/**
 * Send an output buffer as an XDR packet.
 **/
n4err n4xdr_send_outbuf(int fd,
                        struct n4outbuf *b)
{
    size_t      len;
    n4err       err;

    if (fd == N4_NO_FD) {
        n4log_error("can't send packet to closed file descriptor");
        return NFS4ERR_IO;
    }

    CHECK_ERR(n4buf_calc_outbuf_len_bytes(b, &len));

    if (len > (size_t) 0x7ffffff) {
        n4fatal("can't handle RPC record this long!");
    } else if (len == 0) {
        n4fatal("can't transmit a 0-byte RPC record");
    } else if (len & 3) {
        n4fatal("packet does not end on word boundary");
    }

    /* See if the packet needs fragmentation */
    if (n4xdr_opts.max_fragment_size  &&  len > n4xdr_opts.max_fragment_size) {
        n4log_notice("packet of %ld bytes must be fragmented", (long) len);
        err = n4write_fragmented(fd, b, len, n4xdr_opts.max_fragment_size);
    } else {
        err = n4write_one_frag(fd, b->start, len, TRUE);
    }

    /* Scrub out the buffer, just to make it perfectly clear that it's
       now corrupt. */
    n4xdr_whack(b->start, len);
    
    return err;
}


n4err n4xdr_whack(uint32_t *b, size_t len)
{
    memset(b, '#', len);
    return N4OK;
}


n4err n4write_one_frag(int fd,
                       uint32_t *start,
                       size_t bytes,
                       gboolean is_last)
{
    uint32_t                    d;

    /* Update prefix field in pre-allocated space.  Then write the
       whole packet in one go. */
    d = (bytes - 4);
    if (is_last)
        d |= 1<<31;
    
    *start = g_htonl(d);

    n4log_binary(N4LOG_DEBUG, start, bytes,
                 "prefix plus %d byte fragment contents:",
                 bytes - 4);
    CHECK_ERR(n4_send_full(fd, start, bytes));

    return N4OK;
}


/**
 * Transmit a record as a series of fragments.
 *
 * Since we only reserve space for a single prefix, when sending
 * fragments we have to make up our own prefixes as we go along.  This
 * destroys the buffer, but that's OK because we don't do retransmits.
 *
 * \p frag_max_bytes is the maximum length of the fragments, including
 * the prefix.  So, the actual amount of data carried in each is one
 * word less.
 *
 * \p record_bytes includes extra single word reserved for the prefix.
 **/
n4err n4write_fragmented(int fd,
                         const struct n4outbuf *outb,
                         size_t record_bytes,
                         size_t frag_max_bytes)
{
    uint32_t            *frag_start;
    size_t              frag_bytes;
    gboolean            is_last = FALSE;

    /* Fragments MUST be word-aligned, or it all gets horribly messy */
    frag_max_bytes &= ~3;
    if (frag_max_bytes < 8) {
        n4log_error("fragment maximum size of %d is too small to "
                    "make any progress", frag_max_bytes);
        return N4ERR_CONFIG;
    }
    
    frag_start = outb->start;
    
    while (record_bytes > 4) {
        if (record_bytes > frag_max_bytes) {
            frag_bytes = frag_max_bytes;
        } else {
            is_last = TRUE;
            frag_bytes = record_bytes;
        }
        
        CHECK_ERR(n4write_one_frag(fd, frag_start, frag_bytes, is_last));
        /* On the first packet, frag_start points to the reserved word
         * before the first word of data.  We advance by frag_bytes,
         * so it now points to a new prefix word before the next
         * frag. */
        frag_start += frag_bytes/4 - 1;
        record_bytes -= frag_bytes - 4;
    }

    return N4OK;
}




/**
 * \brief Read a whole XDR-RM record into a newly allocated buffer.
 */
n4err n4xdr_recv_record(TALLOC_CTX *ctx, int fd,
                        guint32 **p, size_t *plen)
{
    guint32   *buf = 0;
    n4err     err;
    int       is_first = 1, is_last;
    size_t              msg_len = 0, frag_off = 0;
    uint32_t            *where;

    do {
        guint32   prefix;
        size_t    frag_len;
        
        err = n4_read_full(fd, &prefix, sizeof prefix);
        if (err == N4ERR_CONN_CLOSED && is_first) {
            /* This is basically the one point in the protocol at which
             * the connection may politely be closed. */
            return err;
        } else if (err) {
            n4log_error("failed to read XDR record marking fragment prefix");
            return err;
        }
    
        prefix = g_ntohl(prefix);

        is_last = prefix & 1<<31;

        frag_len = ((size_t) prefix) & ~(1<<31);
        if (frag_len > N4_MAX_PACKET_LEN) {
            n4log_error("record-marking prefix %#lx indicates an unreasonably "
                         "long packet -- perhaps this is not XDR-RM?",
                         (long) frag_len);
            return N4ERR_RPC_GARBAGE;
        }

        n4trace("want to read %ld byte %s RPC Record Marking fragment",
                 (long) frag_len, is_last ? "final" : "continuing");

        frag_off = msg_len;     /* Offset for start of this frag */
        msg_len += frag_len;    /* New total length */
        
        if (buf) {
            /* already allocated; grow */
            buf = talloc_realloc(ctx, buf, msg_len);
        } else {
            n4_assert(is_first);
            buf = talloc(ctx, msg_len);
        }
        if (!buf) {
            n4log_error("couldn't allocate space for %ld byte RPC fragment",
                         (long) msg_len);
            return N4ERR_MEM;
        }

        /* Calculate location to receive this fragment. */
        where = buf + frag_off/4;
        CHECK_ERR(n4recv_fragment_contents(fd, where, frag_len));
        
        is_first = 0;
    } while (!is_last);

    if (frag_off) {
        /* only if there was more than one fragment */
#if 0
        n4log_binary(N4LOG_DEBUG, buf, msg_len,
                     "reassembled %d byte packet",
                     msg_len);
#endif
    }
    
    *p = buf;
    *plen = msg_len;

    return N4OK;
}



n4err n4recv_fragment_contents(int fd, gpointer buf,
                                           size_t frag_len)
{
    CHECK_ERR(n4_read_full(fd, buf, frag_len));

    n4log_binary(N4LOG_DEBUG, buf, frag_len, "%d byte fragment contents:",
                 frag_len);

    return N4OK;
}
    


n4err n4xdr_recv_inbuf(TALLOC_CTX *pool, int fd, n4inbuf *inbuf)
{
    guint32 *p;
    size_t len;
    n4err   err;

    if ((err = n4xdr_recv_record(pool, fd, &p, &len)))
        return err;

    if (len & 3) {
        n4log_warning("XDR packet has odd length %ld", (long) len);
        /* Continue anyhow, although this certainly means a truncated
           packet or trailing garbage. */
    }

    inbuf->pool = pool;
    inbuf->start = inbuf->p = p;
    inbuf->packet_bytes = len;

    return N4OK;
}
