/*
 * Micro-X -- an X server for DOS
 * Copyright (C) 1992 StarNet Communications Corp.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * StarNet Communications Corp.
 * 550 Lakeside Dr. #3
 * Sunnyvale CA 94086 US
 * http://www.starnet.com
 * x-dos@starnet.com
 */
/*
*	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);
}
