Release 1.1.1
[l2tpns.git] / nsctl.c
1 #include <stdio.h>
2 #include <arpa/inet.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <malloc.h>
6 #include <netdb.h>
7 #include <string.h>
8 #include <sys/time.h>
9 #include <sys/types.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <signal.h>
13 #include <stdarg.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <time.h>
17 #include "control.h"
18
19 struct { char *command; int pkt_type; int params; } commands[] = {
20 { "load_plugin", PKT_LOAD_PLUGIN, 1 },
21 { "unload_plugin", PKT_UNLOAD_PLUGIN, 1 },
22 { "garden", PKT_GARDEN, 1 },
23 { "ungarden", PKT_UNGARDEN, 1 },
24 };
25
26 char *dest_host = NULL;
27 unsigned int dest_port = 1702;
28 int udpfd;
29
30 int main(int argc, char *argv[])
31 {
32 int len = 0;
33 int dest_ip = 0;
34 int pkt_type = 0;
35 char *packet = NULL;
36 int i;
37
38 setbuf(stdout, NULL);
39
40 if (argc < 3)
41 {
42 printf("Usage: %s <host> <command> [args...]\n", argv[0]);
43 return 1;
44 }
45
46 dest_host = strdup(argv[1]);
47
48 {
49 // Init socket
50 int on = 1;
51 struct sockaddr_in addr;
52
53 memset(&addr, 0, sizeof(addr));
54 addr.sin_family = AF_INET;
55 addr.sin_port = htons(1703);
56 udpfd = socket(AF_INET, SOCK_DGRAM, 17);
57 setsockopt(udpfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
58 if (bind(udpfd, (void *) &addr, sizeof(addr)) < 0)
59 {
60 perror("bind");
61 return(1);
62 }
63 }
64
65 {
66 struct hostent *h = gethostbyname(dest_host);
67 if (h) dest_ip = ntohl(*(unsigned int *)h->h_addr);
68 if (!dest_ip) dest_ip = ntohl(inet_addr(dest_host));
69 if (!dest_ip)
70 {
71 printf("Can't resolve \"%s\"\n", dest_host);
72 return 0;
73 }
74 }
75
76 if (!(packet = calloc(1400, 1)))
77 {
78 perror("calloc");
79 return(1);
80 }
81
82 srand(time(NULL));
83
84 // Deal with command & params
85 for (i = 0; i < (sizeof(commands) / sizeof(commands[0])); i++)
86 {
87 if (strcasecmp(commands[i].command, argv[2]) == 0)
88 {
89 int p;
90 pkt_type = commands[i].pkt_type;
91 len = new_packet(pkt_type, packet);
92 if (argc < (commands[i].params + 3))
93 {
94 printf("Not enough parameters for %s\n", argv[2]);
95 return 1;
96 }
97 for (p = 0; p < commands[i].params; p++)
98 {
99 strncpy((packet + len), argv[p + 3], 1400 - len - 1);
100 len += strlen(argv[p + 3]) + 1;
101 }
102 break;
103 }
104 }
105 if (!pkt_type)
106 {
107 printf("Unknown command\n");
108 return 1;
109 }
110
111 send_packet(udpfd, dest_ip, dest_port, packet, len);
112
113 {
114 int n;
115 fd_set r;
116 struct timeval timeout;
117
118 FD_ZERO(&r);
119 FD_SET(udpfd, &r);
120 timeout.tv_sec = 1;
121 timeout.tv_usec = 0;
122
123 n = select(udpfd + 1, &r, 0, 0, &timeout);
124 if (n <= 0)
125 {
126 printf("Timeout waiting for packet\n");
127 return 0;
128 }
129 }
130 if ((len = read_packet(udpfd, packet)))
131 {
132 printf("Received ");
133 dump_packet(packet, stdout);
134 }
135
136 return 0;
137 }
138