updated version, consistent with the kernel patch.
[vde.git] / vde-2 / tunctl / vde_tunctl.c
blob6e439060a099857b3fb0aa044fd862ad2d3ba760
1 /* Copyright 2002 Jeff Dike
2 * Licensed under the GPL
3 */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <pwd.h>
12 #include <net/if.h>
13 #include <sys/ioctl.h>
14 #include <linux/if_tun.h>
16 static void Usage(char *name)
18 fprintf(stderr, "Create: %s [-b] [-u owner] [-t device-name] "
19 "[-f tun-clone-device]\n", name);
20 fprintf(stderr, "Delete: %s -d device-name [-f tun-clone-device]\n\n",
21 name);
22 fprintf(stderr, "The default tun clone device is /dev/net/tun - some systems"
23 " use\n/dev/misc/net/tun instead\n\n");
24 fprintf(stderr, "-b will result in brief output (just the device name)\n");
25 exit(1);
28 int main(int argc, char **argv)
30 struct ifreq ifr;
31 struct passwd *pw;
32 long owner = geteuid();
33 int tap_fd, opt, delete = 0, brief = 0;
34 char *tun = "", *file = "/dev/net/tun", *name = argv[0], *end;
36 while((opt = getopt(argc, argv, "bd:f:t:u:")) > 0){
37 switch(opt) {
38 case 'b':
39 brief = 1;
40 break;
41 case 'd':
42 delete = 1;
43 tun = optarg;
44 break;
45 case 'f':
46 file = optarg;
47 break;
48 case 'u':
49 pw = getpwnam(optarg);
50 if(pw != NULL){
51 owner = pw->pw_uid;
52 break;
54 owner = strtol(optarg, &end, 0);
55 if(*end != '\0'){
56 fprintf(stderr, "'%s' is neither a username nor a numeric uid.\n",
57 optarg);
58 Usage(name);
60 break;
61 case 't':
62 tun = optarg;
63 break;
64 case 'h':
65 default:
66 Usage(name);
70 argv += optind;
71 argc -= optind;
73 if(argc > 0)
74 Usage(name);
76 if((tap_fd = open(file, O_RDWR)) < 0){
77 fprintf(stderr, "Failed to open '%s' : ", file);
78 perror("");
79 exit(1);
82 memset(&ifr, 0, sizeof(ifr));
84 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
85 strncpy(ifr.ifr_name, tun, sizeof(ifr.ifr_name) - 1);
86 if(ioctl(tap_fd, TUNSETIFF, (void *) &ifr) < 0){
87 perror("TUNSETIFF");
88 exit(1);
91 if(delete){
92 if(ioctl(tap_fd, TUNSETPERSIST, 0) < 0){
93 perror("TUNSETPERSIST");
94 exit(1);
96 printf("Set '%s' nonpersistent\n", ifr.ifr_name);
98 else {
99 if(ioctl(tap_fd, TUNSETPERSIST, 1) < 0){
100 perror("TUNSETPERSIST");
101 exit(1);
103 if(ioctl(tap_fd, TUNSETOWNER, owner) < 0){
104 perror("TUNSETPERSIST");
105 exit(1);
107 if(brief)
108 printf("%s\n", ifr.ifr_name);
109 else printf("Set '%s' persistent and owned by uid %ld\n", ifr.ifr_name,
110 owner);
112 return(0);