/*= -*- c-file-style: "bsd"; indent-tabs-mode: nil; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: rpc.c,v 1.14 2001/07/19 03:49:47 tpot 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.
 */

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


/* TODO: Somewhere in here we could have a reply cache, with some kind
 * of expiry for old requests.  We need to make sure the reply data is
 * not freed until we're sure we're not going to retransmit.
 *
 * I'm not sure that this is terribly valuable, though: for a TCP
 * network, retransmission of requests should only happen when the
 * socket has been dropped, which hopefully is a fairly rare
 * occurrence. */


n4err n4unpack_rpc_reply_hdr(struct n4inbuf *b,
                             uint32_t *xid)
{
    enum rpc_reply_stat replystat;

    CHECK_ERR(n4inbuf_need(b, 4));

    *xid = FROM_NET(UNPACK(b));
    if (UNPACK(b) != TO_NET(RPC_REPLY)) {
        n4log_error("packet is not an RPC_REPLY");
        return N4ERR_RPC_UNEXPECTED;
    }

    replystat = FROM_NET(UNPACK(b));
    if (replystat == RPC_MSG_ACCEPTED) {
        return n4unpack_accepted_reply(*xid, b);
    } else if (replystat == RPC_MSG_DENIED) {
        return n4unpack_denied_reply(*xid, b);
    } else {
        n4log_error("illegal RPC reply_stat %d", replystat);
        return N4ERR_RPC_GARBAGE;
    }
}


n4err n4unpack_accepted_reply(guint32 xid, n4inbuf *inb)
{
    guint32        accept_stat;
    
    /*        struct accepted_reply { */
    /*           opaque_auth verf; */
    /*           union switch (accept_stat stat) { */
    /*           case SUCCESS: */

    CHECK_ERR(n4inbuf_need(inb, 2));
    CHECK_ERR(n4unpack_opaque_auth(inb));
    CHECK_ERR(n4inbuf_need(inb, 1));
    accept_stat = FROM_NET(UNPACK(inb));

    switch (accept_stat) {
    case RPC_SUCCESS:
        n4trace("request xid %#x was accepted and executed", xid);
        return N4OK;
    case RPC_PROG_UNAVAIL:
        n4log_error("request xid %#x failed: program unavailable", xid);
        return N4ERR_RPC_PROG_UNAVAIL;
    case RPC_PROG_MISMATCH: {
        guint32 lowest, highest;

        CHECK_ERR(n4inbuf_need(inb, 2));
        lowest = FROM_NET(UNPACK(inb));
        highest = FROM_NET(UNPACK(inb));

        if (lowest != highest) {
            n4log_error("request xid %#x failed because other party only "
                        "supports versions %u through %u of this program",
                        xid, lowest, highest);
        } else {
            n4log_error("request xid %#x failed because other party only "
                        "supports version %u of this program",
                        xid, lowest);
        }
                    
        return N4ERR_RPC_PROG_VERS;
    } 
    case RPC_PROC_UNAVAIL:
        n4log_error("request xid %#x failed: procedure unavailable", xid);
        return N4ERR_RPC_PROCEDURE_UNAVAIL;
    case RPC_GARBAGE_ARGS:
        n4log_error("request xid %#x failed: other party complains of "
                    "garbage arguments", xid);
        return N4ERR_RPC_GARBAGE;
    case RPC_SYSTEM_ERR:
        n4log_error("request xid %#x failed: other party complains of "
                    "system error", xid);
        return N4ERR_RPC_SYSTEM;
    default:
        n4log_error("request xid %#x failed for unknown reason, "
                    "accept_stat=%u", xid, accept_stat);
        return N4ERR_RPC_GARBAGE;
    }

    return N4OK;
}


n4err n4unpack_denied_reply(guint32 xid, n4inbuf *inb)
{
    guint32      reject_stat;

    reject_stat = FROM_NET(UNPACK(inb));
    
    if (reject_stat == RPC_AUTH_ERROR) {
        n4log_error("request xid %#x was denied because of auth error",
                    xid);
        return N4ERR_RPC_AUTH;
    } else if (reject_stat == RPC_MISMATCH) {
        guint32 lowest, highest;

        CHECK_ERR(n4inbuf_need(inb, 2));
        lowest = FROM_NET(UNPACK(inb));
        highest = FROM_NET(UNPACK(inb));
            
        n4log_error("request xid %#x was denied because of RPC mismatch, "
                    "other party supports versions %u through %u",
                    xid, lowest, highest);
        return N4ERR_RPC_DENIED;
    } else {
        n4log_error("request xid %#x was denied for unknown reason %d",
                    xid, reject_stat);
        return N4ERR_RPC_DENIED;
    }
}


n4err n4pack_rpc_reply_hdr(n4outbuf *b, guint32 xid,
                           int repstat, int substat)
{                                       
    n4outbuf_expand(b, 4);
    PACK(b, TO_NET(xid));
    PACK(b, TO_NET(RPC_REPLY));
    PACK(b, TO_NET(repstat));  /* accept or deny? */
    
    /* now follow any details about the reason for rejection */
    if (repstat == RPC_MSG_ACCEPTED) {
        return n4pack_accepted_reply_hdr(b, substat);
    } else if (repstat == RPC_MSG_DENIED) {
        return n4pack_denied_reply_hdr(b, substat);
    } else {
        n4fatal("bogus reply_stat %d", repstat);
    }
}


n4err n4pack_accepted_reply_hdr(n4outbuf *b,
                                enum rpc_accept_stat substat)
{
    CHECK_ERR(n4pack_null_auth(b));
    
    CHECK_ERR(n4outbuf_expand(b, 1));
    PACK(b, TO_NET(substat));  /* what reason? */
        
    switch (substat) {
    case RPC_SUCCESS:
    case RPC_PROG_UNAVAIL:
    case RPC_PROC_UNAVAIL:
    case RPC_GARBAGE_ARGS:
    case RPC_SYSTEM_ERR:
        /* no more data required */
        break;
        
    case RPC_PROG_MISMATCH:
        n4outbuf_expand(b, 2);
        PACK(b, TO_NET(NFS4_VERSION)); /* lowest supported prog version */
        PACK(b, TO_NET(NFS4_VERSION)); /* highest supported prog version */
        break;
        
    default:
        n4fatal("bogus accept code %d", substat);
    }

    return N4OK;
}


n4err n4pack_denied_reply_hdr(n4outbuf *b,
                              enum rpc_reject_stat substat)
{
    CHECK_ERR(n4outbuf_expand(b, 1));
    PACK(b, TO_NET(substat));  /* what reason? */
        
    switch (substat) {
    case RPC_MISMATCH:
        n4outbuf_expand(b, 2);
        PACK(b, TO_NET(RPC_VERSION2)); /* lowest supported encoding*/
        PACK(b, TO_NET(RPC_VERSION2)); /* highest supported encoding */
        break;
    case RPC_AUTH_ERROR:
        n4_unhandled();
    default:
        n4fatal("bogus deny code %d", substat);
    }

    return N4OK;
}



/** Swallow a request header.  If everything is valid, then set \p
 * program and \p procedure, and leave the input buffer pointing to
 * the start of the parameters, so that the procedure can read them
 * in, and return N4OK.  **/
MKPROTO n4err n4rpc_swallow_req_header(n4inbuf *b, guint32 *xid,
                                       guint32 *procedure)
{
    guint32         prog, vers;
    n4err           err;

    err = n4inbuf_need(b, 6);   /* XID, CALL, RPCVERS, PROG,
                                          PROGVERS, PROC */
    if (err == N4ERR_RPC_SHORT)
        return N4ERR_RPC_NOHEADER;
    else if (err)
        return err;

    *xid = FROM_NET(UNPACK(b));

    switch (FROM_NET(UNPACK(b))) {
    case RPC_REPLY:
        n4log_error("this is an RPC reply, which is kind of surprising");
        return N4ERR_RPC_UNEXPECTED;
    case RPC_CALL:
        /* great! */
        break;
    default:
        n4log_error("bogus RPC msgtype");
        return N4ERR_RPC_GARBAGE;
    } 
    n4trace("got request, xid=%#x", *xid);

    if (UNPACK(b) != TO_NET(RPC_VERSION2)) {
        return N4ERR_RPC_RPCVERS;
    }

    prog = FROM_NET(UNPACK(b));
    if (prog != NFS_PROGRAM) {
        n4log_error("got request for program %ld, "
                     "but we only serve NFS (%ld)",
                     (long) prog, (long) NFS_PROGRAM);
        return N4ERR_RPC_PROG_UNAVAIL;
    }

/*          unsigned int vers; */
    vers = FROM_NET(UNPACK(b));
    if (vers != NFS4_VERSION) {
        n4log_error("can't support NFS version %u", vers);
        return N4ERR_RPC_PROG_VERS;
    }

/*          unsigned int proc; */
    *procedure = FROM_NET(UNPACK(b));
    n4trace("request is for procedure %u", *procedure);
    
    /* Do something useful with it. */
    n4buf_check_inbuf(b);

/*          opaque_auth  cred; */
/*          opaque_auth  verf; */
    CHECK_ERR(n4rpc_swallow_req_auth(b));
        
    return N4OK;
}



/** Make up a new request XID.
 *
 * These are required be unique across requests from this client, and
 * we would prefer them to be unique across all clients.
 *
 * To let them be easily recognized, the value is constrained to start
 * with an 'x' character at the moment.  
 **/
guint32 n4rpc_gen_xid(void)
{
    static guint32 xid_counter = 0;

    if (!xid_counter)
        return xid_counter = ('x' << 24) | ((getpid() << 8) & 0xffff00) | '0';
    else
        return ++xid_counter;
}



n4err n4pack_rpc_call_hdr(n4outbuf *b, guint32 xid,
                          guint32 program,
                          guint32 vers,
                          guint32 procedure)
{
    n4buf_check_outbuf(b);

    if (vers > 20) {
        n4log_warning("generating RPC CALL for suspicious NFS version %d",
                      vers);
        /* continue anyhow; they might have a good reason. */
    }
    
    switch (program) {
    case MOUNT_PROGRAM:
    case NFS_PROGRAM:
    case PMAPPROC_PROGRAM:
        break;
    default:
        n4log_warning("generating RPC CALL for suspicious program %d",
                      program);
        /* continue anyhow; they might be doing it for testing
         * purposes.  But this will catch the case where they've
         * switched the proc and xid parameters. */
    }
    
    if (procedure > 100) {
        n4log_warning("generating RPC CALL for suspicious procedure %d",
                      procedure);
        /* continue anyhow; they might be doing it for testing
         * purposes.  But this will catch the case where they've
         * switched the proc and xid parameters. */
    }
    
    CHECK_ERR(n4outbuf_expand(b, 10));
    
    PACK(b, TO_NET(xid));
    PACK(b, TO_NET(RPC_CALL));
    PACK(b, TO_NET(RPC_VERSION2));
    PACK(b, TO_NET(program));
    PACK(b, TO_NET(vers));
    PACK(b, TO_NET(procedure));
    PACK(b, TO_NET(RPC_AUTH_NONE));
    PACK(b, TO_NET(0));                   /* null opaque */
    PACK(b, TO_NET(RPC_AUTH_NONE));
    PACK(b, TO_NET(0));

    CHECK_ERR(n4buf_check_outbuf(b));

    return N4OK;
}



n4err n4rpc_check_xid(guint32 req_xid,
                      guint32 reply_xid)
{
    if (reply_xid != req_xid) {
        n4log_error("reply for wrong transaction: sent xid %#x, received %#x",
                     req_xid, reply_xid);
        return N4ERR_RPC_UNEXPECTED;
    }
    return N4OK;
}

