3f7cfc4789f15cd0c205f309ed98b28faf730f35
[tpg/acess2.git] / Usermode / Applications / ifconfig_src / main.c
1 /*
2  * Acess2 IFCONFIG command
3  */
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <stdint.h>
7 #include <string.h>
8 #include <acess/sys.h>
9
10 // === CONSTANTS ===
11 #define FILENAME_MAX    255
12 #define IPSTACK_ROOT    "/Devices/ip"
13
14 // TODO: Move this to a header
15 #define ntohs(v)        (((v&0xFF)<<8)|((v>>8)&0xFF))
16
17 // === PROTOTYPES ===
18 void    PrintUsage(const char *ProgName);
19 void    DumpInterfaces(void);
20 void    DumpInterface(const char *Name);
21  int    AddInterface(const char *Device);
22  int    DoAutoConfig(const char *Device);
23  int    SetAddress(int IFNum, const char *Address);
24  int    ParseIPAddres(const char *Address, uint8_t *Dest, int *SubnetBits);
25
26 // === CODE ===
27 /**
28  * \brief Program entrypoint
29  */
30 int main(int argc, char *argv[])
31 {
32          int    ret;
33         // No args, dump interfaces
34         if(argc == 1) {
35                 DumpInterfaces();
36                 return 0;
37         }
38         
39         // Add a new interface
40         if( strcmp(argv[1], "add") == 0 ) {
41                 if( argc < 4 ) {
42                         fprintf(stderr, "ERROR: '%s add' requires two arguments, %i passed\n", argv[0], argc-2);
43                         PrintUsage(argv[0]);
44                         return -1;
45                 }
46                 // TODO: Also set the IP address as the usage says it does
47                 ret = AddInterface( argv[2] );
48                 if(ret < 0)     return ret;
49                 ret = SetAddress( ret, argv[3] );
50                 return ret;
51         }
52         
53         // Delete an interface
54         if( strcmp(argv[1], "del") == 0 ) {
55                 if( argc < 3 ) {
56                         fprintf(stderr, "ERROR: '%s del' requires an argument\n", argv[0]);
57                         PrintUsage(argv[0]);
58                         return -1;
59                 }
60                 // TODO:
61         }
62         
63         // Autoconfigure an interface
64         // NOTE: Debugging hack (see the function for more details)
65         if( strcmp(argv[1], "autoconf") == 0 ) {
66                 DoAutoConfig(argv[2]);
67                 return 0;
68         }
69         
70         // Print usage instructions
71         PrintUsage(argv[0]);
72         
73         return 0;
74 }
75
76 /**
77  * \brief Print usage instructions
78  */
79 void PrintUsage(const char *ProgName)
80 {
81         fprintf(stderr, "Usage:\n");
82         fprintf(stderr, "    %s add <device> <ip>/<prefix>\n", ProgName);
83         fprintf(stderr, "        Add a new interface listening on <device> with the specified\n");
84         fprintf(stderr, "        address.\n");
85         fprintf(stderr, "    %s del <interface>\n", ProgName);
86         fprintf(stderr, "    %s set <interface> <option> <value>\n", ProgName);
87         fprintf(stderr, "        Set an option on an interface, a list of valid options follows\n");
88         fprintf(stderr, "        gw      IPv4 default gateway\n");
89         fprintf(stderr, "    %s [<interface>]\n", ProgName);
90         fprintf(stderr, "        Print the current interfaces (or only <interface> if passed)\n");
91         fprintf(stderr, "\n");
92         fprintf(stderr, "A note on Acess's IP Stack:\n");
93         fprintf(stderr, "    Each interface corresponds to only one IP address (either IPv4\n");
94         fprintf(stderr, "    or IPv6). A network device can have multiple interfaces bound\n");
95         fprintf(stderr, "    to it, allowing multiple addresses for one network connection\n");
96         fprintf(stderr, "\n");
97 }
98
99 /**
100  * \brief Dump all interfaces
101  */
102 void DumpInterfaces(void)
103 {
104          int    dp;
105         char    filename[FILENAME_MAX+1];
106         
107         dp = open(IPSTACK_ROOT, OPENFLAG_READ);
108         
109         while( readdir(dp, filename) )
110         {
111                 if(filename[0] == '.')  continue;
112                 DumpInterface(filename);
113         }
114         
115         close(dp);
116 }
117
118 /**
119  * \brief Dump an interface
120  */
121 void DumpInterface(const char *Name)
122 {
123          int    fd;
124          int    type;
125         char    path[sizeof(IPSTACK_ROOT)+1+FILENAME_MAX+1] = IPSTACK_ROOT"/";
126         
127         strcat(path, Name);
128         
129         fd = open(path, OPENFLAG_READ);
130         if(fd == -1) {
131                 printf("%s:\tUnable to open ('%s')\n", Name, path);
132                 return ;
133         }
134         
135         type = ioctl(fd, 4, NULL);
136         
137         printf("%s:\t", Name);
138         {
139                  int    call_num = ioctl(fd, 3, "get_device");
140                  int    len = ioctl(fd, call_num, NULL);
141                 char    *buf = malloc(len+1);
142                 ioctl(fd, call_num, buf);
143                 printf("'%s'\t", buf);
144                 free(buf);
145         }
146         // Get the address type
147         switch(type)
148         {
149         case 0: // Disabled/Unset
150                 printf("DISABLED\n");
151                 break;
152         case 4: // IPv4
153                 {
154                 uint8_t ip[4];
155                  int    subnet;
156                 printf("IPv4\n");
157                 ioctl(fd, 5, ip);       // Get IP Address
158                 subnet = ioctl(fd, 7, NULL);    // Get Subnet Bits
159                 printf("\tAddress: %i.%i.%i.%i/%i\n", ip[0], ip[1], ip[2], ip[3], subnet);
160                 ioctl(fd, 8, ip);       // Get Gateway
161                 printf("\tGateway: %i.%i.%i.%i\n", ip[0], ip[1], ip[2], ip[3]);
162                 }
163                 break;
164         case 6: // IPv6
165                 {
166                 uint16_t        ip[8];
167                  int    subnet;
168                 printf("IPv6\n");
169                 ioctl(fd, 5, ip);       // Get IP Address
170                 subnet = ioctl(fd, 7, NULL);    // Get Subnet Bits
171                 printf("\t%x:%x:%x:%x:%x:%x:%x:%x/%i\n",
172                         ntohs(ip[0]), ntohs(ip[1]), ntohs(ip[2]), ntohs(ip[3]),
173                         ntohs(ip[4]), ntohs(ip[5]), ntohs(ip[6]), ntohs(ip[7]),
174                         subnet);
175                 }
176                 break;
177         default:        // Unknow
178                 printf("UNKNOWN (%i)\n", type);
179                 break;
180         }
181         printf("\n");
182                         
183         close(fd);
184 }
185
186 /**
187  * \brief Create a new interface using the passed device
188  * \param Device        Network device to bind to
189  */
190 int AddInterface(const char *Device)
191 {
192          int    dp, ret;
193         
194         dp = open(IPSTACK_ROOT, OPENFLAG_READ);
195         ret = ioctl(dp, 4, (void*)Device);
196         close(dp);
197         
198         if( ret < 0 ) {
199                 fprintf(stderr, "Unable to add '%s' as a network interface\n", Device);
200                 return -1;
201         }
202         
203         printf("-- Added '"IPSTACK_ROOT"/%i' using device %s\n", ret, Device);
204         
205         return ret;
206 }
207
208 void AddRoute(const char *Interface, void *Dest, int MaskBits, void *NextHop)
209 {
210          int    fd;
211          int    num;
212         char    tmp[sizeof(IPSTACK_ROOT"/routes/") + 5];        // enough for 4 digits
213         
214         // Create route
215         fd = open(IPSTACK_ROOT"/routes", 0);
216         num = ioctl(fd, ioctl(fd, 3, "add_route"), Interface);
217         close(fd);
218         
219         // Open route
220         sprintf(tmp, IPSTACK_ROOT"/routes/%i", num);
221         fd = open(tmp, 0);
222         
223         ioctl(fd, ioctl(fd, 3, "set_network"), Dest);
224         ioctl(fd, ioctl(fd, 3, "set_nexthop"), NextHop);
225         ioctl(fd, ioctl(fd, 3, "getset_subnetbits"), &MaskBits);
226         
227         close(fd);
228         
229 }
230
231 /**
232  * \note Debugging HACK!
233  * \brief Autoconfigure the specified device to 10.0.2.55/8 using
234  *        10.0.2.1 as the gateway.
235  */
236 int DoAutoConfig(const char *Device)
237 {
238          int    tmp, fd;
239         char    path[sizeof(IPSTACK_ROOT)+5+1]; // ip000
240         uint8_t addr[4] = {10,0,2,55};
241         uint8_t gw[4] = {10,0,2,1};
242          int    subnet = 8;
243         
244         tmp = AddInterface(Device);
245         if( tmp < 0 )   return tmp;
246         
247         sprintf(path, IPSTACK_ROOT"/%i", tmp);
248         
249         fd = open(path, OPENFLAG_READ);
250         if( fd == -1 ) {
251                 fprintf(stderr, "Unable to open '%s'\n", path);
252                 return -1;
253         }
254         
255         tmp = 4;        // IPv4
256         tmp = ioctl(fd, ioctl(fd, 3, "getset_type"), &tmp);
257         if( tmp != 4 ) {
258                 fprintf(stderr, "Error in setting address type (got %i, expected 4)\n", tmp);
259                 return -1;
260         }
261         // Set Address
262         ioctl(fd, ioctl(fd, 3, "set_address"), addr);
263         // Set Subnet
264         ioctl(fd, ioctl(fd, 3, "getset_subnet"), &subnet);
265         // Set Gateway
266         ioctl(fd, ioctl(fd, 3, "set_gateway"), gw);
267         
268         close(fd);
269         
270         printf("Set address to %i.%i.%i.%i/%i (GW: %i.%i.%i.%i)\n",
271                 addr[0], addr[1], addr[2], addr[3],
272                 subnet,
273                 gw[0], gw[1], gw[2], gw[3]);
274         
275         return 0;
276 }
277
278 /**
279  * \brief Set the address on an interface from a textual IP address
280  */
281 int     SetAddress(int IFNum, const char *Address)
282 {
283         uint8_t addr[16];
284          int    type;
285         char    path[sizeof(IPSTACK_ROOT)+1+5+1];       // ip000
286          int    tmp, fd, subnet;
287         
288         // Parse IP Address
289         type = ParseIPAddres(Address, addr, &subnet);
290         if(type == 0) {
291                 fprintf(stderr, "'%s' cannot be parsed as an IP address\n", Address);
292                 return -1;
293         }
294         
295         // Open file
296         sprintf(path, IPSTACK_ROOT"/%i", IFNum);
297         fd = open(path, OPENFLAG_READ);
298         if( fd == -1 ) {
299                 fprintf(stderr, "Unable to open '%s'\n", path);
300                 return -1;
301         }
302         
303         tmp = type;
304         tmp = ioctl(fd, ioctl(fd, 3, "getset_type"), &tmp);
305         if( tmp != type ) {
306                 fprintf(stderr, "Error in setting address type (got %i, expected %i)\n", tmp, type);
307                 close(fd);
308                 return -1;
309         }
310         // Set Address
311         ioctl(fd, ioctl(fd, 3, "set_address"), addr);
312         
313         // Set Subnet
314         ioctl(fd, ioctl(fd, 3, "getset_subnet"), &subnet);
315         
316         close(fd);
317         
318         // Dump!
319         //DumpInterface( path+sizeof(IPSTACK_ROOT)+1 );
320         
321         return 0;
322 }
323
324 /**
325  * \brief Parse an IP Address
326  * \return 0 for unknown, 4 for IPv4 and 6 for IPv6
327  */
328 int ParseIPAddres(const char *Address, uint8_t *Dest, int *SubnetBits)
329 {
330         const char      *p = Address;
331         
332         // Check first block
333         while(*p && *p >= '0' && *p <= '9')     p ++;
334         
335         // IPv4?
336         if(*p == '.')
337         {
338                  int    i = 0, j;
339                  int    val;
340                 
341                 for( j = 0; Address[i] && j < 4; j ++ )
342                 {
343                         val = 0;
344                         for( ; '0' <= Address[i] && Address[i] <= '9'; i++ )
345                         {
346                                 val = val*10 + Address[i] - '0';
347                         }
348                         if(val > 255) {
349                                 //printf("val > 255 (%i)\n", val);
350                                 return 0;
351                         }
352                         Dest[j] = val;
353                         
354                         if(Address[i] == '.')
355                                 i ++;
356                 }
357                 if( j != 4 ) {
358                         //printf("4 parts expected, %i found\n", j);
359                         return 0;
360                 }
361                 // Parse subnet size
362                 if(Address[i] == '/') {
363                         val = 0;
364                         i ++;
365                         while('0' <= Address[i] && Address[i] <= '9') {
366                                 val *= 10;
367                                 val += Address[i] - '0';
368                                 i ++;
369                         }
370                         if(val > 32) {
371                                 printf("Notice: Subnet size >32 (%i)\n", val);
372                         }
373                         *SubnetBits = val;
374                 }
375                 if(Address[i] != '\0') {
376                         //printf("EOS != '\\0', '%c'\n", Address[i]);
377                         return 0;
378                 }
379                 return 4;
380         }
381         
382         // IPv6
383         if(*p == ':' || ('a' <= *p && *p <= 'f') || ('A' <= *p && *p <= 'F'))
384         {
385                  int    i = 0;
386                  int    j, k;
387                  int    val, split = -1, end;
388                 uint16_t        hi[8], low[8];
389                 
390                 for( j = 0; Address[i] && j < 8; j ++ )
391                 {
392                         if(Address[i] == '/')
393                                 break;
394                         
395                         if(Address[i] == ':') {
396                                 if(split != -1) {
397                                         printf("Two '::'s\n");
398                                         return 0;
399                                 }
400                                 split = j;
401                                 i ++;
402                                 continue;
403                         }
404                         
405                         val = 0;
406                         for( k = 0; Address[i] && Address[i] != ':' && Address[i] != '/'; i++, k++ )
407                         {
408                                 val *= 16;
409                                 if('0' <= Address[i] && Address[i] <= '9')
410                                         val += Address[i] - '0';
411                                 else if('A' <= Address[i] && Address[i] <= 'F')
412                                         val += Address[i] - 'A' + 10;
413                                 else if('a' <= Address[i] && Address[i] <= 'f')
414                                         val += Address[i] - 'a' + 10;
415                                 else {
416                                         printf("%c unexpected\n", Address[i]);
417                                         return 0;
418                                 }
419                         }
420                         
421                         if(val > 0xFFFF) {
422                                 printf("val (0x%x) > 0xFFFF\n", val);
423                                 return 0;
424                         }
425                         
426                         if(split == -1)
427                                 hi[j] = val;
428                         else
429                                 low[j-split] = val;
430                         
431                         if( Address[i] == ':' ) {
432                                 i ++;
433                         }
434                 }
435                 end = j;
436                 
437                 // Parse subnet size
438                 if(Address[i] == '/') {
439                         val = 0;
440                         while('0' <= Address[i] && Address[i] <= '9') {
441                                 val *= 10;
442                                 val += Address[i] - '0';
443                                 i ++;
444                         }
445                         if(val > 128) {
446                                 printf("Notice: Subnet size >128 (%i)\n", val);
447                         }
448                         *SubnetBits = val;
449                 }
450                 
451                 for( j = 0; j < split; j ++ )
452                 {
453                         //printf("%04x:", hi[j]);
454                         Dest[j*2] = hi[j]>>8;
455                         Dest[j*2+1] = hi[j]&0xFF;
456                 }
457                 for( ; j < 8 - (end - split); j++ )
458                 {
459                         //printf("0000:", hi[j]);
460                         Dest[j*2] = 0;
461                         Dest[j*2+1] = 0;
462                 }
463                 for( k = 0; j < 8; j ++, k++)
464                 {
465                         //printf("%04x:", low[k]);
466                         Dest[j*2] = low[k]>>8;
467                         Dest[j*2+1] = low[k]&0xFF;
468                 }
469                 return 6;
470         }
471         // Unknown type
472         return 0;
473 }

UCC git Repository :: git.ucc.asn.au