ethersim.c 32.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
/*
 * Copyright (C) 1996-1998 by the Board of Trustees
 *    of Leland Stanford Junior University.
 * 
 * This file is part of the SimOS distribution. 
 * See LICENSE file for terms of the license. 
 *
 */

/* 
 * ethersim.c --
 *
 *	 Simuation of a local ethernet with a gateway interface.
 *	 This program simulates a local ethernet with a gateway machine
 *	 attached to it.  The simulated ethernet accepts ethernet packets
 *	 that arrive on the special UDP port.  It is assumed that these
 *	 packets are send by the network module of simos services running
 *	 on top of Unix.  This program decodes the ethernet header and 
 *	 uses it to determine which UDP port to output the packet on.
 *	 This is done by keeping track of the ethernet address of the machine
 *	 sending packets to the ethernet port.
 *
 *	 When this program receives an ethernet packet of type IP to an IP
 *	 destination address outside the subnet of the local ethernet, it
 *	 outputs the packet to the local (phsyical) ethernet attached to 
 *	 the machine.  By doing this the program acts like a gateway machine.
 *
 *	 The program also opens the network interface of the machines and 
 *	 grabs any packets with an IP destination of the simulated subnet.  
 *	 This is done using Sun's NIT protocol and packet filter.  Packets
 *	 addressed to a known simulated host will be forward on to that 
 *	 host's UDP port.  
 *
 *	 NOTES:
 *	    1) Because this program uses NIT to get packets from the outside
 *	       packets arriving at network interfaces other than the one
 *	       specified are not seen.  In particular, packets sent thru
 *	       the loopback (lo0) interface are not seen by this program. 
 *	       This means that processes on the local machine can't talk IP
 *	       to the simulated machines.  
 *	    2) This program is a big security hole because it accepts packets
 *	       from an non-privledged UDP port and forwards them on to the
 *	       local ethernet.  I think that outputPacket() does enough 
 *	       checking to stop this from being a problem.
 *
 */


#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/time.h>

#include <net/if.h>
#include <net/nit_if.h>
#include <net/nit_pf.h>
#include <net/nit_buf.h>
#include <net/packetfilt.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>

#include <arpa/inet.h>

#include <stdio.h>
#include <signal.h>
#include <pwd.h>
#include <setjmp.h>
#include <netdb.h>
#include <errno.h>
#include <strings.h>
#include <varargs.h>
#include <stropts.h>
#include <poll.h>
#include <search.h>
#include <memory.h>
#include <stdlib.h>
#include <unistd.h>

#include "hash.h"

#include "ethersim.h"

#ifdef MACH_NRP
#include <netinet/udp.h>
#include "nd.h"
#endif

/*
 * Program options setable from the command line.
 */

u_long subnetaddr = 0xab404fe0; 	/* Subnet address (i.e. 171.64.79.224). */

int    simportnumber = ETHER_SIM_PORT;  /* UDP port of simulated ethernet. */
int    noipforwarding = 0;		/* Boolean - Don't forward ip packet. */
char   interfacename[32] = "le0";	/* Name of interface to forward IP 
					 * packets on. */
int    verbose = 0;                     /* verbose: tell user about pkts */

u_long   routeraddr = (u_long)-1;
/*
 * Buffer to hold the current packet being transmitted on the ethernet. 
 * This must be big enought to hold an ethernet MTU and its header.  We
 * add 128 bytes for good measure.
 */
char curPacket[ETHERMTU + sizeof(struct ether_header) + 128];

int	simfd;		/* Open file descriptor of simulated ethernet port. */
int	netfd;          /* Open file descriptor of network interface tap. */
#ifdef MACH_NRP
int nrpfd = -1;		/* Open file descriptor of socket or NRP server.  */
char *nrphost = "localhost";  /* Host with NRP server. */
struct sockaddr_in nrpaddr;
int nrpaddrlen;

struct ether_addr my_simetheraddr; /* My simulated ether addr. */
struct in_addr my_simipaddr; /* My simulated ip addr. */
#endif 

/*
 * The ethernet address and IP network address of the interface being used.
 */

struct ether_addr myetheraddr;
u_long mynetaddr;

/*
 * The internet address and netmask of the interface being used.
 */
u_long myinetAddr;
u_long mynetmask;

/*
 * HostInfoRecord - Info kept per simulated host.
 */

typedef struct HostInfoRecord {
    struct ether_addr etheraddr;/* Ethernet address of host. */
    u_long inetAddr;		/* Internet address of host. */
    struct sockaddr fromaddr;	/* Socket the of the simulated machines 
				 * ethernet interface. */
    int	 fromlen;		/* Length in bytes of fromaddr. */

} HostInfoRecord;

/*
 * Hash tables that map 
 *	etheraddrTable - Ethernet addresses to HostInfoRecord.
 *	ipaddrTable    - IP addresses to HostInfoRecord. 
 */

Hash_Table etheraddrTable;
Hash_Table ipaddrTable;



/*
 * Stupid SunOS header missing stuff.
 */
    /* Options stuff. */
extern char *optarg;
extern int optind;
extern int getopt _ARGS_((int argc, char **argv, char *optstring));

extern int fprintf ();  /* fprintf and fscanf are varags so no prototype. */
extern int fscanf ();

extern int fgetc _ARGS_((FILE *stream));

extern void perror _ARGS_((char *msg));
extern int pclose _ARGS_((FILE *stream));

extern int ioctl _ARGS_((int fd, int request, caddr_t arg));

extern int socket _ARGS_((int domain, int type, int protocol));
extern int bind _ARGS_((int s, struct sockaddr *name, int namelen));
extern int recvfrom _ARGS_((int s, char *buf, int len, int flags, 
				struct sockaddr *from, int *fromlen));
extern int sendto _ARGS_((int s, char *msg, int len, int flags, 
				struct sockaddr *to, int tolen));

extern u_long inet_netof _ARGS_((struct in_addr in));

extern void bzero _ARGS_((void *b, int length));
extern void bcopy _ARGS_((void *a, void *b, int length));

extern int poll _ARGS_((struct pollfd *fds, unsigned long nfds, int timeout));
extern int putmsg _ARGS_((int fd, struct strbuf *ctlptr, 
				struct strbuf *dataptr, int flags));

extern long strtol _ARGS_((char *str, char **ptr, int base));


/*
 * offsetof() return the offset of a field into the structure.
 */
#ifndef offsetof
#define	offsetof(_t, _f)  ((int) &(((_t *) 0)->_f))
#endif

#define	NIT_DEV "/dev/nit"

/*
 * Forward routine declartions.
 */
int serviceSimPort _ARGS_((void));
int serviceNetPort _ARGS_((void));
#ifdef MACH_NRP
int serviceNrpPort _ARGS_((void));
int IsMachNRPPacket _ARGS_((struct ether_header *hdrPtr,int  size));
#endif
int initNITdevice  _ARGS_((char *device, u_long subNetAddr, u_long netmask));
int outputPacket   _ARGS_((char *packet, int size));
int lookupInterface _ARGS_((char *interfacename, u_long *inetAddrPtr, 
				u_long *netmaskPtr));
int validPacket _ARGS_((char *packet, int size, struct sockaddr *fromAddr, 
				int fromlen));

#ifdef MACH_NRP

/* Forwards */

#endif

/*
 *----------------------------------------------------------------------
 *
 * main -- 
 *
 *       Main routine and loop for ethersim.
 *
 * Results:
 *      Only returns if an error occurs.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */
int
main(argc, argv)
int argc;
char *argv[];
{
    int	c, errflg;
    struct sockaddr_in addr;
    int	   nfds;
    struct pollfd  fds[3];
    int	   (*serviceRoutine[3])();

    simfd = netfd = -1;
    errflg = 0;

#ifdef MACH_NRP
#define OPTS "vfg:p:n:s:r:"
#else
#define OPTS "vfg:p:n:r:"
#endif
    while ((c = getopt(argc, argv,  OPTS)) != -1) {
       switch (c) {
        case 'v':
	     verbose = 1;
	     break;
	case 'f':
	     noipforwarding = 1;
	     break;
	case 'i':
	     strncpy(interfacename, optarg, sizeof(optarg)-1);
	     break;
	case 'g':
	     subnetaddr = inet_network(optarg);
	     if (subnetaddr == (u_long) -1) {
		 fprintf(stderr, "%s: Malformed gateway address %s\n", argv[0],
					optarg);
		 errflg++;
	     }
	     break;
	case 'r':
	     routeraddr = inet_network(optarg);
	     if (routeraddr == (u_long) -1) {
		 fprintf(stderr, "%s: Malformed router address %s\n", argv[0],
					optarg);
		 errflg++;
	     }
	     break;
	case 'p':
	     simportnumber = atoi(optarg);
	     if (simportnumber < 0) {
		 fprintf(stderr, "%s: Illegal port number %s\n", argv[0], 
						optarg);
		 errflg++;
	     }
	     break;
#ifdef MACH_NRP
	case 's':
	    nrphost = optarg;
	    break;
#endif
	case '?':
	     errflg++;
	}
    }
    if (errflg) {
#ifdef MACH_NRP
	(void)fprintf(stderr, 
		"usage: %s [-v] [-g netaddr] [-p portnumber] [-n netmask] [-s nrphost]\n", 
				argv[0]);
#else
	(void)fprintf(stderr, 
		"usage: %s [-v] [-g netaddr] [-p portnumber] [-n netmask]\n", 
				argv[0]);
#endif
	exit (2);
    }


    /*
     * Create the socket that transmits on the simulated ethernet will be
     * sent.  It is a UDP port number ETHER_SIM_PORT.  The mostly likely
     * cause of failure is another ethersim running causing the bind
     * to fail with address in use.
     */

    simfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (simfd < 0) {
        perror("main: socket");
        exit(1);
    }


    bzero((char *)&addr, sizeof(addr));
    addr.sin_port = htons(simportnumber);
    addr.sin_family = AF_INET;
    if (bind(simfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror("main: bind");
        exit(2);
    }

#ifdef MACH_NRP
    /*
     * Create the socket the commonicates with the nrp server. 
    */
    nrpfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (nrpfd < 0) {
        perror("main: nrp socket");
        exit(1);
    }

    bzero((char *)&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    if (bind(nrpfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror("main: nrp bind");
        exit(2);
    }
    { 
	struct hostent *host;
        host = gethostbyname(nrphost);
	if (!host) {
		perror(nrphost);
		exit(2);
	}
	nrpaddr.sin_family =  host->h_addrtype;
	bcopy(host->h_addr, &nrpaddr.sin_addr, host->h_length);
	nrpaddr.sin_port = htons(IPPORT_NDREQUEST);
	nrpaddrlen = sizeof(nrpaddr);
    }
    bcopy("ETHERS", &my_simetheraddr, 6);  
    my_simipaddr.s_addr =  htonl(subnetaddr | 0xFEFE);
#endif /* MACH_NRP */

    if (!noipforwarding && (geteuid() != 0)) {
	fprintf(stderr, "%s: not running as root - IP forwarding disabled\n",
			argv[0]);
	noipforwarding = 1;
    }

    if (!noipforwarding) {
	if (lookupInterface(interfacename, &myinetAddr, &mynetmask) < 0) {
	    fprintf(stderr, "Couldn't find interface %s\n", interfacename);
	    exit(3);
	}
	{
		struct in_addr tmp;
		tmp.s_addr = myinetAddr;
		mynetaddr = inet_netof(tmp);
	}

	netfd = initNITdevice(interfacename, subnetaddr, mynetmask);
	if (netfd < 0) {
	    fprintf(stderr, "Couldn't initialize network tap\n");
	    exit(3);
	}
    } 
    /*
     * Initialize mapping hash tables.
     */
    Hash_InitTable(&etheraddrTable, 0, 2);
    Hash_InitTable(&ipaddrTable, 0, HASH_ONE_WORD_KEYS);

    /*
     * Loop waiting for packets to arrive.
     */
    nfds = 0;
    fds[nfds].fd = simfd;
    fds[nfds].events = POLLIN;
    serviceRoutine[nfds] = serviceSimPort;
    nfds++;
    if (netfd >= 0) {
	fds[nfds].fd = netfd;
	fds[nfds].events = POLLIN;
    	serviceRoutine[nfds] = serviceNetPort;
	nfds++;
    }
#ifdef MACH_NRP
    if (nrpfd >= 0) {
	fds[nfds].fd = nrpfd;
	fds[nfds].events = POLLIN;
    	serviceRoutine[nfds] = serviceNrpPort;
	nfds++;
    }
#endif

    while (1) {
        int     n;
	int	i;

	fds[0].revents = fds[1].revents = fds[2].revents = 0;
	n = poll(fds, nfds, 50);
	if (n < 0) {
	    if (errno == EINTR) continue;
	    perror("poll");
	    exit(1);
	}
	for (i = 0; i < nfds; i++) { 
		if (fds[i].revents & POLLIN) {
		    (void) serviceRoutine[i]();
		}
	}
    }
}
/*
 *----------------------------------------------------------------------
 *
 * serviceSimPort -- 
 *
 *       Service a request that arrives at the simulated ethernet port.
 *
 * Results:
 *      -1 if problem occur with
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */
int
serviceSimPort()
{
    struct  ether_header  *hdrPtr;
    struct sockaddr from;
    int	    fromlen, n;
    int	    etherAddrKey[2];
    int xfersize;
    Hash_Entry *entryPtr;
    HostInfoRecord *srcHostInfo;
    HostInfoRecord *dstHostInfo;

    if (verbose) {
      fprintf(stderr, "serviceSimPort()\n");
    }

    fromlen = sizeof (from);
    n = recvfrom(simfd, curPacket, sizeof(curPacket), 0, &from, &fromlen);
    if (n < 0) {
	perror("recvfrom");
	return -1;
    }
    if (!validPacket(curPacket, n, &from, fromlen)) {
	return 0;
    }
    if ((n < ETHERMIN + sizeof(struct ether_header)) || 
        (n > ETHERMTU + sizeof(struct ether_header))) {
	fprintf(stderr, "Bad packet size %d\n", n);
	return 0;
    }

    hdrPtr = (struct ether_header *) curPacket;
    if (verbose) {
#define	A(x) (hdrPtr->ether_dhost.ether_addr_octet[x])
#define	B(x) (hdrPtr->ether_shost.ether_addr_octet[x])
	fprintf(stderr, "ETHER: Src %x:%x:%x:%x:%x:%x  Dst %x:%x:%x:%x:%x:%x\n",
                B(0),B(1),B(2),B(3),B(4),B(5), A(0),A(1),A(2),A(3),A(4),A(5));
    }

    /*
     * Ensure that the mapping exists for this ethernet address.
     */
    etherAddrKey[1] = 0;
    bcopy(hdrPtr->ether_shost.ether_addr_octet, (char *) etherAddrKey, 6);
    entryPtr = Hash_CreateEntry(&etheraddrTable, (Address) etherAddrKey, NULL);
    srcHostInfo = (HostInfoRecord *) Hash_GetValue(entryPtr);
    if (srcHostInfo == NULL) {
      srcHostInfo = (HostInfoRecord *) calloc(1, sizeof(HostInfoRecord));
      if (verbose) {
	fprintf(stderr, "setting srcHostInfo %#x\n", srcHostInfo);
      }
      bcopy(hdrPtr->ether_shost.ether_addr_octet, 
	    &srcHostInfo->etheraddr, 6);
      Hash_SetValue(entryPtr, srcHostInfo);
    }
    bcopy((caddr_t)&from, (caddr_t)&srcHostInfo->fromaddr, fromlen);
    srcHostInfo->fromlen = fromlen;
#ifdef MACH_NRP
    {
	int offset;
    if ((offset = IsMachNRPPacket(hdrPtr))) {
	xfersize = sendto(nrpfd, curPacket + offset, n-offset, 0x0, 
				(caddr_t) &nrpaddr,
				nrpaddrlen);
	if (xfersize < 0) {
	    perror("sendto nrp");
	}
        return 0;
    }
    }
#endif
    if (htons(hdrPtr->ether_type) == ETHERTYPE_IP) {
      u_long	inetAddr;

      if (verbose) {
      struct in_addr	sAddr, dAddr;
	fprintf(stderr, "ETHERTYPE_IP packet %#x\n", hdrPtr->ether_type);
        bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_src),
              (char *) &sAddr, sizeof(sAddr));
        bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_dst),
              (char *) &dAddr, sizeof(dAddr));
	fprintf(stderr, "IP: Src %s ", inet_ntoa(sAddr));
 	fprintf(stderr, "Dst %s\n",  inet_ntoa(dAddr));
      }

      bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_src),
	    (char *) &inetAddr, sizeof(inetAddr));
      if (srcHostInfo->inetAddr != inetAddr) {
	if (verbose) {
	  fprintf(stderr, "srcHostInfo->inetAddr != inetAddr\n");
	}
	srcHostInfo->inetAddr = inetAddr;
	entryPtr = Hash_CreateEntry(&ipaddrTable, (Address)inetAddr,NULL);
	Hash_SetValue(entryPtr, srcHostInfo);
      }
    }


#define	A(x) (hdrPtr->ether_dhost.ether_addr_octet[x])
#define	B(x) (hdrPtr->ether_shost.ether_addr_octet[x])
    if ((A(0) == 0xff) && (A(1) == 0xff) && (A(2) == 0xff) &&
	(A(3) == 0xff) && (A(4) == 0xff) && (A(5) == 0xff)) {
	Hash_Search search;
	/*
	 * Broadcast. 
	 */
	if (verbose) {
	  fprintf(stderr, "broadcast packet\n");
	}

        if (ArpRequest(curPacket, n, curPacket, &n)) {
    		if (n < ETHERMIN + sizeof(struct ether_header)) {
			n =  ETHERMIN + sizeof(struct ether_header);
		}
		goto reply;
        }

	for (entryPtr = Hash_EnumFirst(&etheraddrTable, &search); 
	     entryPtr != NULL; entryPtr = Hash_EnumNext(&search)) {
	    dstHostInfo = (HostInfoRecord *) Hash_GetValue(entryPtr);
	    if (dstHostInfo != srcHostInfo) { 
		xfersize = sendto(simfd, curPacket, n, 0x0, 
				    (struct sockaddr *) &dstHostInfo->fromaddr,
				    dstHostInfo->fromlen);
		if (xfersize < 0) {
		    perror("sendto");
		}
	    }
	}
	return 0;
    } 
  reply:
    etherAddrKey[1] = 0;
    bcopy(hdrPtr->ether_dhost.ether_addr_octet, 
				(char *) etherAddrKey, 6);

    entryPtr = Hash_FindEntry(&etheraddrTable, etherAddrKey);
    if (entryPtr != NULL) {
	dstHostInfo = (HostInfoRecord *) Hash_GetValue(entryPtr);

	if (verbose) {
	  fprintf(stderr, "sending packet\n");
	}

	xfersize = sendto(simfd, curPacket, n, 0x0, 
				(struct sockaddr *) &dstHostInfo->fromaddr,
				dstHostInfo->fromlen);
	if (xfersize < 0) {
	    perror("sendto");
	}
        return 0;

    } 

    if ((htons(hdrPtr->ether_type) == ETHERTYPE_IP) && (netfd > 0)) {
	u_long	destAddr;

	if (verbose) {
	  fprintf(stderr, "outputPacket\n");
	}

	bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_dst),
		(char *) &destAddr, sizeof(destAddr));
	destAddr = ntohl(destAddr);
	if ((destAddr & mynetmask) != subnetaddr) {
	    outputPacket(curPacket, n);
	}
        return 0;
    }


    fprintf(stderr, "Unknown dest address %x:%x:%x:%x:%x:%x from %x:%x:%x:%x:%x:%x\n", A(0), A(1), A(2), A(3), A(4), A(5), 
	    B(0), B(1), B(2), B(3), B(4), B(5));

     return 0;

}

/*
 *----------------------------------------------------------------------
 *
 * serviceNetPort -- 
 *
 *       Service a request that arrives at the network interface tap port.
 *
 * Results:
 *      -1 if problem occur with
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */
int
serviceNetPort()
{
    struct  ether_header  *hdrPtr;
    int	     n;
    u_long	inetAddr;
    Hash_Entry  *entryPtr;
    HostInfoRecord *hostInfoRecord;
    int xfersize;

    if (verbose) {
      fprintf(stderr, "serviceNetPort()\n");
    }

    n = read(netfd, curPacket, sizeof(curPacket));
    if (n < 0) {
	perror("read of serviceNetPort");
	return -1;
    }
    if ((n < ETHERMIN + sizeof(struct ether_header)) || 
	(n > ETHERMTU + sizeof(struct ether_header))) {
	fprintf(stderr, "Bad packet size %d\n", n);
	return -1;
    }

    hdrPtr = (struct ether_header *) curPacket;

    if (htons(hdrPtr->ether_type) != ETHERTYPE_IP) {
      if (verbose) {
	fprintf(stderr, "htons(hdrPtr->ether_type) != ETHERTYPE_IP\n");
      }
      return 0;
    }

    bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_dst),
		(char *) &inetAddr, sizeof(inetAddr));
    entryPtr = Hash_FindEntry(&ipaddrTable, (Address)inetAddr);
    if (entryPtr == NULL) {
      if (verbose) {
	fprintf(stderr, "entryPtr == NULL\n");
      }
      return 0;
    }
    hostInfoRecord = (HostInfoRecord *) Hash_GetValue(entryPtr);
    if (verbose) {
       struct in_addr	sAddr, dAddr;
       bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_src),
             (char *) &sAddr, sizeof(sAddr));
       bcopy(curPacket + sizeof(struct ether_header) + offsetof(struct ip, ip_dst),
             (char *) &dAddr, sizeof(dAddr));
       fprintf(stderr, "IP: Src %s ", inet_ntoa(sAddr));
       fprintf(stderr, "Dst %s\n",  inet_ntoa(dAddr));
       fprintf(stderr, "sending...\n");
    }
    xfersize = sendto(simfd, curPacket, n, 0x0, 
				(struct sockaddr *) &hostInfoRecord->fromaddr,
				hostInfoRecord->fromlen);

    if (xfersize < 0) {
	perror("sendto");
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * validPacket -- 
 *
 *       Check to see if we should accept this packet.
 *
 * Results:
 *      1 if packet ok.
 *      0 if we should request it.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

int
validPacket(packet, size, fromAddr, fromlen)
    char *packet;	/* The contents of the packet. */
    int	 size;		/* The size of the packet. */
    struct sockaddr *fromAddr; /* Where the packet was from. */
    int	  fromlen;	       /* The length of fromAddr. */
{
    struct  ether_header  *hdrPtr;
    struct  sockaddr_in   *inaddrPtr;
    u_long  srcAddr;

    hdrPtr = (struct ether_header *) packet;
    if ((size < ETHERMIN + sizeof(struct ether_header)) || 
        (size > ETHERMTU + sizeof(struct ether_header))) {
	fprintf(stderr, "Bad packet size %d\n", size);
	return 0;
    }
    /* 
     * XXX - Do security checking here.  Currently we reject all packets 
     * from hosts outside our network.  We only if we are forwarding
     * packets.
     */
    if (!noipforwarding) { 
	if ((fromAddr->sa_family != AF_INET) || 
	    (fromlen < offsetof(struct sockaddr_in, sin_zero))) {
	    fprintf(stderr, "Packet from bad fromaddr\n");
	    return 0;
	}
	inaddrPtr = (struct sockaddr_in *) fromAddr;
	srcAddr = inet_netof(inaddrPtr->sin_addr);
	if ((srcAddr != mynetaddr) && (srcAddr != IN_LOOPBACKNET)) {
	    fprintf(stderr, "Security violation: Packet from host %s\n",
			    inet_ntoa(inaddrPtr->sin_addr));
	    return 0;
	}
    }
    return 1;
}



/*
 *----------------------------------------------------------------------
 *
 * initNITdevice -- 
 *
 *       Initialize the network interface tap (NIT) file descriptor so
 *	 we can catch IP packets for this subnet.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

int 
initNITdevice(device, subNetAddr, netmask)
    char	    *device;    /* Network interface name. */
    u_long 	   subNetAddr;  /* IP address of the subnet. */
    u_long	   netmask;	/* Network address mask of the interface. */
{
      struct strioctl     si;
      struct ifreq   ifr;
      struct packetfilt pf;
      int   err, cmd;
      int snaplen;
      int fd;

      fd = open(NIT_DEV, O_RDWR, 0);
      if (fd < 0) {
	  perror("open of NIT_DEV");
	  return -1;
      }

      /* Arrange to get discrete messages from the stream. */
      err = ioctl(fd, I_SRDOPT, (char *)RMSGD);
      if (err < 0) {
	  perror("I_SRDOPT RMSGD");
	  goto bad;
      }


      /* Configure the nit device, binding it to the proper
	 underlying interface and setting the snapshot length to
	 include entire ethernet packets. */
      strncpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
      ifr.ifr_name[sizeof ifr.ifr_name - 1] = '\0';
      si.ic_cmd = NIOCBIND;
      si.ic_timout = INFTIM;
      si.ic_len = sizeof ifr;
      si.ic_dp = (char *)&ifr;

      err = ioctl(fd, I_STR, (char *)&si);
      if (err < 0) {
	  perror("I_STR NIOCBIND");
	  goto bad;
      }

      snaplen = 0;
      si.ic_cmd = NIOCSSNAP;
      si.ic_timout = INFTIM;
      si.ic_len = sizeof snaplen;
      si.ic_dp = (char *)&snaplen;
      err = ioctl(fd, I_STR, (char *)&si);
      if (err < 0) {
	  perror("I_STR NIOCSSNAP");
	  goto bad;
      }
      /*
       * Read out the ethernet address so we can fill them into packets
       * being sent.
       */
      si.ic_cmd = SIOCGIFADDR;
      si.ic_timout = INFTIM;
      si.ic_len = sizeof ifr;
      si.ic_dp = (char *)&ifr;
      err = ioctl(fd, I_STR, (char *)&si);
      if (err < 0) {
	  perror("I_STR SIOCGIFADDR");
	  goto bad;
      }
      bcopy(ifr.ifr_addr.sa_data, (char *) &myetheraddr, sizeof(myetheraddr));

      if (!((netmask == 0xff000000) || (netmask == 0xffff0000) || 
            (netmask == 0xffffff00))) {
	  fprintf(stderr, "Code can't handle netmask of 0x%x\n", netmask);
	  goto bad;
      }


      /*
       * Add the packet filter to only return IP packets to the specified
       * network. 
       */

      err = ioctl(fd, I_PUSH, "pf");
      if (err < 0) {
	  perror("I_PUSH pf");
	  exit(1);
      }
      cmd = 0;
      pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short)
		 offsetof(struct ether_header, ether_type)/sizeof(u_short);
      pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_CAND;
      pf.Pf_Filter[cmd++] = htons(ETHERTYPE_IP);

      if (netmask == 0xff000000) {
	  u_short lowval, highval;
	  lowval = (((u_long)subNetAddr) & netmask) >> 16;
	  highval = lowval | 0xff;
	  pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short) 
		      sizeof(struct ether_header)/sizeof(u_short) +
		       offsetof(struct ip, ip_dst)/sizeof(u_short);
	  pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_GE;
          pf.Pf_Filter[cmd++] = lowval;
	  pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short) 
		      sizeof(struct ether_header)/sizeof(u_short) +
		       offsetof(struct ip, ip_dst)/sizeof(u_short);
	  pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_LE;
          pf.Pf_Filter[cmd++] = highval;
	  pf.Pf_Filter[cmd++] = ENF_AND;
      } else {
	  pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short) 
		      sizeof(struct ether_header)/sizeof(u_short) +
		       offsetof(struct ip, ip_dst)/sizeof(u_short);
	  pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_EQ;
          pf.Pf_Filter[cmd++] = (((u_long)subNetAddr) & netmask) >> 16;
	  if (netmask == 0xffffff00) {
	      u_short lowval, highval;
	      lowval = (((u_long)subNetAddr) & netmask) & 0xffff;
	      highval = lowval | 0xff;
	      pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short) 
			  sizeof(struct ether_header)/sizeof(u_short) +
			   offsetof(struct ip, ip_dst)/sizeof(u_short) + 1;
	      pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_GE;
	      pf.Pf_Filter[cmd++] = lowval;
	      pf.Pf_Filter[cmd++] = ENF_PUSHWORD + (u_short) 
			  sizeof(struct ether_header)/sizeof(u_short) +
			   offsetof(struct ip, ip_dst)/sizeof(u_short) + 1;
	      pf.Pf_Filter[cmd++] = ENF_PUSHLIT | ENF_LE;
	      pf.Pf_Filter[cmd++] = highval;
	      pf.Pf_Filter[cmd++] = ENF_AND;
	  }
      }
      pf.Pf_FilterLen = cmd;


      si.ic_cmd = NIOCSETF;
      si.ic_timout = INFTIM;
      si.ic_len = sizeof pf;
      si.ic_dp = (char *)&pf;
      err = ioctl(fd, I_STR, (char *)&si);
      if (err < 0) {
	  perror("I_STR NIOCSETF");
	  goto bad;
      }

      /* Flush the read queue, to get rid of anything that accumulated
	 before the device reached its final configuration. */
      err = ioctl(fd, I_FLUSH, (char *)FLUSHR);
      if (err < 0) {
	  perror("I_STR FLUSHR");
	  goto bad;
      }
      return fd;
  bad:
      (void) close(fd);
      return -1;
}

/*
 *----------------------------------------------------------------------
 *
 * outputPacket -- 
 *
 *
 * Results:
 *      None.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */


int
outputPacket(packet, size)
    char *packet;  /* The contents of the packet. */
    int	 size;     /* The size of the packet. */
{
    struct ether_header	*hdrPtr;
    struct sockaddr protoheader;
    struct strbuf ctlmsgbuf;
    struct strbuf datamsgbuf;
    u_long	dstaddr;

    /*
     * Fill in the correct ethernet address source. 
     */
    hdrPtr = (struct ether_header *) packet;
    hdrPtr->ether_shost = myetheraddr;

    bcopy(packet + sizeof(struct ether_header) + offsetof(struct ip, ip_src),
	  (char *) &dstaddr, sizeof(dstaddr));
    dstaddr = ntohl(dstaddr);

    /*
     * Security: 
     *	1) Don't broadcast or send to all zeros.
     *  2) Must be of type IP.
     *  3) Must have a ip_src address on the simulated subnet.
     */

    if (((A(0) == 0xff) && (A(1) == 0xff) && (A(2) == 0xff) &&
	(A(3) == 0xff) && (A(4) == 0xff) && (A(5) == 0xff)) ||
        ((A(0) == 0) && (A(1) == 0) && (A(2) == 0) &&
	(A(3) == 0) && (A(4) == 0) && (A(5) == 0)) ||
	(htons(hdrPtr->ether_type) != ETHERTYPE_IP) ||
	((dstaddr & mynetmask) != subnetaddr)) {

	fprintf(stderr, 
	    "outputPacket: Tossing packet sent to %x:%x:%x:%x:%x:%x\n",
		A(0), A(1), A(2), A(3), A(4), A(5));
	return 0;
    }

    /*
     * For some reason a write to a NIT device requires that the 
     * ethernet header be passed inside a sockaddr with a AF_UNSPEC
     * family and as a M_PROTO message.
     */
    protoheader.sa_family = AF_UNSPEC;
    bcopy((char *) hdrPtr, protoheader.sa_data, sizeof(struct ether_header));

    ctlmsgbuf.maxlen = sizeof(protoheader);
    ctlmsgbuf.len = sizeof(protoheader);
    ctlmsgbuf.buf = (char *) &protoheader;


    datamsgbuf.maxlen = size - sizeof(struct ether_header);
    datamsgbuf.len = size - sizeof(struct ether_header);
    datamsgbuf.buf = packet + sizeof(struct ether_header);

    if (putmsg(netfd, &ctlmsgbuf, &datamsgbuf, 0) < 0) {
	    perror("outputPacket: putmsg");
	    return (-1);
    }
#ifdef notdef
    fprintf(stderr, "Not sending packet to %x:%x:%x:%x:%x:%x from %x:%x:%x:%x:%x:%x\n", A(0), A(1), A(2), A(3), A(4), A(5), 
	    B(0), B(1), B(2), B(3), B(4), B(5));
#endif	

    return 0;
}
/*
 *----------------------------------------------------------------------
 *
 * lookupInterface -- 
 *
 *       Find the specified interface and read its address and netmask.
 *	
 *
 * Results:
 *     0 if we found things, -1 otherwise.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */

int
lookupInterface(interfacename, inetAddrPtr, netmaskPtr)
    char *interfacename;
    u_long *inetAddrPtr;
    u_long *netmaskPtr;
{
    char cmdBuf[256];
    char inetString[32], netmaskString[32];
    int ch;

    FILE *pfile;

    /* 
     * We cheat and use ifconfig to lookup the info. This should probably
     * be changed to do all kinds of nasty I/O controls to lookup the info.
     */
    sprintf(cmdBuf, "/etc/ifconfig %s", interfacename);
    pfile = popen(cmdBuf, "r");
    if (pfile == (FILE *) NULL) {
	fprintf(stderr, "Can't execute %s\n", cmdBuf);
	return -1;
    }
    /*
     * Skip the first line which should look something like:
     * le0: flags=63<UP,BROADCAST,NOTRAILERS,RUNNING>
     */
    for (ch = fgetc(pfile); (ch != '\n') && (ch != EOF); ch = fgetc(pfile)) 
	;
    if (fscanf(pfile, "\tinet %s netmask %s ", inetString, netmaskString) != 2){
	(void) pclose(pfile);
	return -1;
    }
    *inetAddrPtr = inet_addr(inetString);
    *netmaskPtr = strtol(netmaskString, (char **)NULL, 16);
    if (routeraddr == (u_long) -1) {
	routeraddr = ((*inetAddrPtr) & (*netmaskPtr)) | 1; 
		/* Default to host 1 on the network */
    }
    (void) pclose(pfile);
    return 0;

}

unsigned long
FindGateway(dstaddr)
   unsigned long dstaddr;
{
	if ((dstaddr & mynetmask) == (myinetAddr & mynetmask)) 
	   return dstaddr;
	if ((dstaddr & mynetmask) == subnetaddr) 
	   return -1;
	return routeraddr;
}
	

#ifdef MACH_NRP
int
IsMachNRPPacket(hdrPtr, size)
     struct  ether_header *hdrPtr;
     int size;
{
   struct ip ip;
   struct udphdr udp;
   char *p = (char *) hdrPtr;
   
   if ((sizeof(*hdrPtr) + sizeof(ip) + sizeof(udp)) > size) {
     return 0;
   }
   if (ntohs(hdrPtr->ether_type) != ETHERTYPE_IP) {
	return 0;
   }
   bcopy(p + sizeof(struct ether_header), (char *) &ip, sizeof(ip));
   if (ip.ip_p != IPPROTO_UDP) {
      return 0;
   }
   bcopy(p + sizeof(struct ether_header) + ip.ip_hl*4, (char *) &udp,
	 sizeof(udp));
   if ((ntohs(udp.uh_dport) !=  IPPORT_NDREQUEST)) {
	return 0;
   }
   return sizeof(struct ether_header) + ip.ip_hl*4 + sizeof(udp);

}

int
serviceNrpPort()
{
    int n;
    struct ether_header eh;
    struct ip ip;
    struct udphdr udp;
    struct sockaddr_in tosin;
    char *b;
    unsigned long checksum;
    int udp_length;
    int i;
    int	    etherAddrKey[2];
    int xfersize;
    Hash_Entry *entryPtr;
    HostInfoRecord *dstHostInfo;

    int hdrsize = sizeof(eh) + sizeof(ip) + sizeof(udp);
    b = curPacket + hdrsize - 6 - sizeof(tosin);
    n = read(nrpfd, b, sizeof(curPacket) - hdrsize);
    if (n < 0) {
	perror("read of serviceNrpPort");
	return -1;
    }
    if (n <= 6 + sizeof(tosin)) {
	fprintf(stderr, "Bad NRP packet size %d\n", n);
	return -1;
    }
    bcopy(b,&eh.ether_dhost, 6);
    bcopy(b + 6, &tosin, sizeof(tosin));
    eh.ether_shost = my_simetheraddr;	
    eh.ether_type = htons(ETHERTYPE_IP);

    udp_length = n - 6 - sizeof(tosin) + sizeof(udp);
   bzero((char *) &ip,  sizeof(ip));

   
	ip.ip_v = IPVERSION;
	ip.ip_hl = 5;
	ip.ip_tos = 0;
	ip.ip_len = htons(udp_length + sizeof(ip));
	ip.ip_id = 10;  /* OSF1-AD doesnt care. */
	ip.ip_off = htons(0);
	ip.ip_ttl = 0xff;
	ip.ip_p = IPPROTO_UDP;
	ip.ip_sum = 0;
	ip.ip_src = my_simipaddr;
	ip.ip_dst = tosin.sin_addr;

	for (checksum = i = 0; i < 10; i++) {
		checksum += ((unsigned short *) &ip)[i];
	}
	checksum = (checksum & 0xffff) + (checksum >> 16);
	checksum = (checksum & 0xffff) + (checksum >> 16);
	ip.ip_sum = (~checksum & 0xffff);

	udp.uh_sport = htons(IPPORT_NDREQUEST);
	udp.uh_dport = htons(IPPORT_NDREPLY);
	udp.uh_ulen = htons(udp_length);
	udp.uh_sum = 0;


    bcopy(&eh, curPacket, sizeof(eh)); 
    bcopy(&ip, curPacket + sizeof(eh),  sizeof(ip)); 
    bcopy(&udp, curPacket + sizeof(eh) + sizeof(ip),  sizeof(udp)); 
    etherAddrKey[1] = 0;
    bcopy(eh.ether_dhost.ether_addr_octet, (char *) etherAddrKey, 6);
    entryPtr = Hash_FindEntry(&etheraddrTable, etherAddrKey);
    if (entryPtr != NULL) {
    	int len = sizeof(eh) + udp_length + sizeof(ip);
	dstHostInfo = (HostInfoRecord *) Hash_GetValue(entryPtr);

	xfersize = sendto(simfd, curPacket, len, 0x0, 
				(struct sockaddr *) &dstHostInfo->fromaddr,
				dstHostInfo->fromlen);
	if (xfersize < 0) {
	    perror("sendto");
	}
        return 0;
    }  else {
#undef A
#define A(x)  (etherAddrKey[x]&0xff)
        fprintf(stderr, "Can't find host for NRP reply to %x:%x:%x:%x:%x:%x\n", A(0), A(1), A(2), A(3), A(4), A(5));
  }
	
  return 0;
}


#endif