/*= -*- c-file-style: "linux"; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: xdr.c,v 1.14 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.
 */

#include <includes.h>

/* Design for doing XDR:
 *
 * There's no need to check results on every primitive operation,
 * because there are basically no possible errors since we already
 * know we have enough data.
 *
 * When writing out data, we don't know how much space we will need
 * until we complete the operations.  Eventually we might want some
 * kind of bucket brigade mechanism, but a single growing buffer or
 * fixed-size buffer might be enough at first.  A nice thing about a
 * buffer brigade would be that some elements of it could be written
 * out using sendfile.
 *
 * When reading in data, we know from the lower-level protocol (UDP,
 * or RM over TCP) that we have the entire data.  Therefore there is
 * nothing that can go wrong in terms of parsing: we can only discover
 * semantic problems.  However, before we begin parsing a struct, we
 * do need to make sure they sent us sufficient data and that we're
 * not going to run off the end.
 *
 * When writing out, at the point we realize we will need a certain
 * amount of space, we need to make sure that it is allocated.
 *
 * Alternatively we can set a maximum response size, and truncate our
 * reads to fit within that, though it might be hard to work backwards
 * from the packet size to the read size.
 */



/* TODO: Perhaps if we suffer an error while trying to parse XDR, we
 * should set a pointer indicating how far through the structure we
 * got before getting into trouble.  Then for example we can handle
 * truncated or mangled requests differently if the XID and request
 * type have arrived. */

/* Opaque data is decoded into a pointer into the XDR buffer.  This
 * means you can't free the buffer until you're finished with the
 * decoded buffer.  This is worthwhile, because if the XDR buffer is
 * bulky, then it will be so because of opaque data.  */

/* TODO: Perhaps give an error if the opaque length is larger than it
 * should be, or less than zero. */

/* When reading in data, all we need to do is make the in-memory
 * structure contain a pointer to the data to be written out.  When
 * composing output, I suppose we need to copy it, or add a pointer
 * onto a bucket chain, or something.  We do need to build up all the
 * output before writing it, because we need to size our data marking
 * packet or our UDP packet.
 *
 * When we're serializing a structure, in theory we can know the
 * serialized size by inspection.  In fact, in many cases it will be
 * determined at compile time.  It might be nice to use this to
 * allocate a single buffer up front, rather than growing it as data
 * arrives.  Alternatively we could have a linked chain of data
 * waiting to go out, but that sounds a bit complicated.
 *
 * Or, an even neater idea is to use a different mode of operation of
 * the XDR context that means it only calculates the size of output
 * but does not actually write anything.  Then almost all the code
 * will not need to know or care.
 *
 * I like the idea of doing a writev when we have bulk opaque data
 * to send.  That seems to imply some kind of linked list of data
 * waiting to be sent. */

/* XXX: If we see an illegal enumeration value, then we ought to
 * return an error to the other side of the connection, as well as
 * telling our caller to abort.  However, what message we should send
 * and how depends on exactly what went wrong.  What's a clean way to
 * handle this?  (Or should we not bother?)
 *
 * One good solution if we think the other guy has got really confused
 * might be to drop the connection.
 *
 * The XDR layer should not be making decisions about that sort of
 * thing, anyhow.  However, if an error does occur, perhaps it has to
 * indicate how far through parsing it got before there was a problem:
 * we may need to know whether the XDR and msg_type were read.
 * Alternatively we could just have a special case for those.  */


/* TODO: When reading in a series of integers, do this with a single
 * call.  It's OK to assume that integers in a structure are tightly
 * packed, though we could check this at compile time if we wanted to. */

/* TODO: In most cases, the pack/unpack calls *cannot fail*, because
 * we're only doing a memory-memory transfer.  The only possible
 * failure mode is to run out of space, and we can probably in that
 * case just allow the remaining unpack calls to run on and do nothing
 * -- at the end, we can check that we unpacked exactly the required
 * amount.  This will keep the code simpler, and perhaps faster by
 * avoiding a lot of branches. */

/* TODO: *DON'T* use the same routines for push and pull, because this
 * puts the decision about which mode we're in into all the leaves of
 * the call tree. */

/* TODO: Perhaps we ought to check that the enumeration is in the
 * legal values.  We'd need to eventually autogenerate code that knew
 * about those values and work out what to do if we got something
 * illegal.  If the error occurred in a response then there's nothing
 * we can do except let the caller know.  If we already have a request
 * header and an XID, then really we ought to send back a response
 * saying what they did wrong. */

/* How should we manage allocation of output buffers when we're
 * writing data out?
 *
 * We don't know how much output space will be required until we've
 * actually executed the requests.
 *
 * The response might be of any size, possibly megabytes, though
 * that's not very likely.
 *
 * We want to do only a single write() call if we can, though as long
 * as we're writing enough to fill the TCP send buffers it does not
 * make a huge difference, since we'd block anyhow.  So this implies
 * that we ought to try to allocate buffers of around 32kB, more or
 * less.  If it's a bit less then we'll have to wake up more often,
 * but we can keep the buffer closer to full on each time.
 *
 * Perhaps a linked list of buffers would be reasonable.
 *
 * We don't need to reallocate on each primitive that is serialized.
 * Moderately high-level structures can fairly easily calculate how
 * much space they're going to require.  Then, for each one, they can
 * get a pointer to a newly allocated block that's also pushed onto a
 * list of blocks to go out.  We might as well allocate these blocks
 * at exactly the right size.
 *
 * That's perhaps not quite good enough, because many fragments are
 * likely to be rather small, and we don't want a lot of small
 * buffers.  To start with let's realloc a single large buffer, and
 * then we can be more tricky later.
 *
 * We can also easily walk over the whole list at the end, calculate
 * the length, and prepend an XDR-RM header.  Or, perhaps we want to
 * leave space for the RM header at the start, then go back and fix it
 * up when the final amount is known. */

/* Sun XDR uses ints to represent all enumerations.  This means that
 * they can easily be packed and unpacked, because the length is
 * known.  However, this has the drawback that gdb can't automatically
 * show the right translated value for the enumerated type.  Hmm.  */


/*
 * TODO: Add utilities for sending/receiving nul-terminated strings.
 * There is no terminator on the wire, only a length.  So we need to
 * count the length when going out (easy), and add a null on the way
 * in.
 *
 * Syscalls will expect nul-terminated strings, and they're generally
 * less likely to cause mistakes.
 *
 * Since input is always from a fixed buffer, we could try looking for
 * an 0 immediately after the string, and using it in-place if
 * possible.  Otherwise, we need to copy to a temporary buffer and
 * terminate there.  This will happen in two common cases: when there
 * is padding for the string (not a multiple of 4 bytes), or when it's
 * followed by an integer <0x1000000.
 */


                   /*
                    | Should it subtly irritate, keep it movin' equally. 
                    | Not to know is just the fact, we're a problem nowadays 
                    | An idea is what we lack, doesn't matter anyway. 
                    | All the kids will eat it up, if it's packaged properly
                    |             -- /Aero Zeppelin/, Nirvana
                    */

/*
 * TODO: I guess eventually these ought to be context-specific, but
 * that depends on having a more consistently used context object that
 * is reachable by the XDR code.
 */
struct n4xdr_opts n4xdr_opts;



MKPROTO n4err n4xdr_pack_var(n4outbuf *b, size_t n_bytes,
                             gconstpointer p)
{
    CHECK_ERR(n4outbuf_expand(b, 1 + PADDED(n_bytes)));
    
    PACK(b, TO_NET(n_bytes));

    n4xdr_pack_bytes(b, n_bytes, p);

    return N4OK;
}


n4err n4pack_string(n4outbuf *outb, const char *str) 
{
    /* Note that the trailing NUL is not sent.  Strictly all NFS
       strings can have embedded nuls, bu t in that case you can
       always call pack_var directly. */
    return n4xdr_pack_var(outb, strlen(str), str);
}



n4err n4pack_string_limited(struct n4outbuf *outb,
                            const char *str,
                            size_t limit) 
{
    /* Note that the trailing NUL is not sent.  Strictly all NFS
       strings can have embedded nuls, bu t in that case you can
       always call pack_var directly. */
    n4_assert(strlen(str) + 1 < limit);
    return n4xdr_pack_var(outb, strlen(str), str);
}



MKPROTO void n4xdr_pack_bytes(n4outbuf *b, size_t n_bytes, gconstpointer p)
{    
    size_t padded_len = PADDED(n_bytes) * 4;

    memcpy(b->p, p, n_bytes);

    if (n_bytes & 3) {
        size_t to_pad = padded_len - n_bytes;
        
        guint8 *f = (guint8 *) b->p;
        f += n_bytes;
/*          n4trace("pad %d bytes at end of opaque region", (int) to_pad); */
        bzero(f, to_pad);
    }
    
    b->p += PADDED(n_bytes);
}


/**
 * Unpack a variable-length region without copying it.  If you'd prefer
 * a nul-terminated string instead, use n4unpack_string().
 **/
n4err n4unpack_var(struct n4inbuf *b,
                   size_t *pn_bytes,
                   const char **p)
{
    return n4unpack_var_checked(b, pn_bytes, p, UINT32_MAX);
}


n4err n4unpack_var_checked(struct n4inbuf *b,
                           size_t *pn_bytes,
                           const char **p,
                           uint32_t max_len)
{
    size_t        n_bytes;
    guint8 const  *fill;
    short         to_check;
    int           n_words;
    
    CHECK_ERR(n4inbuf_need(b, 1));
    *pn_bytes = n_bytes = FROM_NET(UNPACK(b));

    if (!n_bytes) {
        *p = NULL;
        return N4OK;
    }
    if (n_bytes > max_len) {
        n4log_error("actual length %ld of opaque stream is longer than "
                    "specified maximum %ld",
                    (long) n_bytes, (long) max_len);
        return N4ERR_RPC_GARBAGE;
    }

    n_words = PADDED(n_bytes);
    CHECK_ERR(n4inbuf_need(b, n_words));

    *p = (gconstpointer) b->p;
    fill = ((guint8 const *) b->p) + n_bytes;
    b->p += n_words;
    
    /* Check the padding is zero, which is required by rfc1831, as
       a test for us getting desynchronized or having bufs. */
    for (to_check = 4*n_words - n_bytes; to_check; to_check--, fill++) {
        if (*fill) {
            n4log_error("non-zero padding after %d byte opaque stream, "
                         "needed %d bytes more",
                         n_bytes, to_check);
            return N4ERR_RPC_GARBAGE;
        }
    }

    return N4OK;
}


/**
 * \todo If there's already a nul after the string in the buffer, then
 * just return that.
 **/
n4err n4unpack_string(TALLOC_CTX *pool, n4inbuf *inb, char **s)
{
    size_t                      len;
    char const                *p;

    CHECK_ERR(n4unpack_var(inb, &len, &p));
    *s = talloc(pool, len+1);
    memcpy(*s, p, len);
    (*s)[len] = '\0';

    return N4OK;
}
