/*
*	udp.c
*/
#include "pcdefs.h"
#include "protocol.h"
#include "config.h"
#include "funcdef.h"

struct port _far *ports[NPORTS];

/****************************************************************************/
/*  udpinterpret
*   take incoming UDP packets and make them available to the user level
*   routines.  Currently keeps the last packet coming in to a port.
*
*   Limitations:
*   Can only listen to one UDP port at a time.
*   Port numbers should be assigned like TCP ports are (future).
*/
void
udpinterpret(pkt, len)
union rawether *pkt;
u_int	len;
{
    u_int	i;
    u_char _far *cp;
    struct udpport _far *p;

    for (i = 0; i < NPORTS; i++) {
	p = (struct udpport _far *)ports[i];
	if (!p || p->flag & O_STREAM)
	    continue;
	if (rawudp(pkt).u.dest == p->inport) {
		if (p->infree + len >= WINDOWSIZE - 1 -
		    sizeof(u_long) - 2 * sizeof(u_short)) {
			/* send icmp source quench */
			if (rawudp(pkt).i.ipdest == Scon.myip)
			    neticmpsend(rawudp(pkt).i.ipsource, 4,
				0, &rawudp(pkt).i, sizeof(struct iph) + 8);
		    } else {
			    cp = &p->datain[p->infree];
			    *(u_short _far *)cp = len;
			    cp += sizeof (u_short);
			    *(u_short _far *)cp = rawudp(pkt).u.source;
			    cp += sizeof (u_short);
			    *(u_long _far *)cp = rawudp(pkt).i.ipsource;
			    cp += sizeof (u_long);
			    memcpy(cp, rawudp(pkt).data, len);
			    p->infree += len + sizeof(u_long)
				+ 2 * sizeof(u_short);
		    }
		    return;
	    }
    }

    /*
    *	send a port unreachable
    */
    if (rawudp(pkt).i.ipdest == Scon.myip)
	    neticmpsend(rawudp(pkt).i.ipsource, 3, 3,
		&rawudp(pkt).i, sizeof(struct iph) + 8);
}
