/* taptap - link two /dev/net/tun to form virtual ethernet

  Copyright (c) 2003, Hans Rosenfeld

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
  HANS ROSENFELD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  Except as contained in this notice, the name of Hans Rosenfeld shall not
  be used in advertising or otherwise to promote the sale, use or other dealings
  in this Software without prior written authorization from Hans Rosenfeld.

  (This Copyright notice / Disclaimer was copied from SIMH (c) Robert M Supnik)

*/

#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef __NetBSD__
#include <linux/if.h>
#include <linux/if_tun.h>
#endif
#include <sys/ioctl.h>

int main(int argc, char **argv)
{
       int dev1,dev2,cnt;
       unsigned char buf[1518];
#ifndef __NetBSD__
       struct ifreq ifr;
#endif


       if(argc <= 2) {
               fprintf(stderr, "usage: taptap dev1 dev2\n");
               exit(1);
       }

       if( ((dev1 = open(argv[1], O_RDWR)) < 0) ||
           ((dev2 = open(argv[2], O_RDWR)) < 0) ) {
               perror("open()");
               exit(1);
       }

#ifndef __NetBSD__
       memset(&ifr, 0, sizeof(ifr));

       ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
       strncpy(ifr.ifr_name, "tun%d", IFNAMSIZ);
       if(ioctl(dev1, TUNSETIFF, (void*) &ifr) < 0) {
               perror("ioctl()");
               exit(2);
       }
       ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
       strncpy(ifr.ifr_name, "tun%d", IFNAMSIZ);
       if(ioctl(dev2, TUNSETIFF, (void*) &ifr) < 0) {
               perror("ioctl()");
               exit(2);
       }
#endif

       daemon(0,0);

       if(fork())
               while(1) {
                       cnt=read(dev1,(void*)&buf,1518);
                       write(dev2,(void*)&buf,cnt);
               }
       else
               while(1) {
                       cnt=read(dev2,(void*)&buf,1518);
                       write(dev1,(void*)&buf,cnt);
               }
}