Import luanet library
[project/luci.git] / libs / luanet / src / vconfig.c
1 /*
2  *  Licensed under the Apache License, Version 2.0 (the "License");
3  *  you may not use this file except in compliance with the License.
4  *  You may obtain a copy of the License at
5  *
6  *      http://www.apache.org/licenses/LICENSE-2.0
7  *
8  *  Unless required by applicable law or agreed to in writing, software
9  *  distributed under the License is distributed on an "AS IS" BASIS,
10  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  *  See the License for the specific language governing permissions and
12  *  limitations under the License.
13  *
14  *   Copyright (C) 2008 John Crispin <blogic@openwrt.org> 
15  *   Copyright (C) 2008 Steven Barth <steven@midlink.org>
16  */
17
18 #include <net/if.h>
19 #include <net/if_arp.h>
20 #include <net/route.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <linux/sockios.h>
25 #include <linux/if_vlan.h>
26 #include <iwlib.h>
27 #include <dirent.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <stdlib.h>
31
32 #include <lua.h>
33 #include <lualib.h>
34 #include <lauxlib.h>
35
36 extern int sock_ifconfig;
37
38
39 static inline int _vlan_add(lua_State *L, int i)
40 {
41         struct vlan_ioctl_args ifr;
42         int a = (i == ADD_VLAN_CMD)?(2):(1);
43         char *ifname;
44         if(lua_gettop(L) != a)
45         {
46                 lua_pushstring(L, "invalid arg list");
47                 lua_error(L);
48                 return 0;
49         }
50         ifname = (char *)lua_tostring (L, 1);
51         ifr.cmd = i;
52         if(i == ADD_VLAN_CMD)
53                 ifr.u.VID = (int)lua_tointeger (L, 2);
54         strncpy(ifr.device1, ifname, IFNAMSIZ);
55         if(!ioctl(sock_ifconfig, SIOCSIFVLAN, &ifr))
56                 lua_pushboolean(L, 1);
57         else
58                 lua_pushboolean(L, 0);
59         return 1;
60 }
61
62 int vlan_add(lua_State *L)
63 {
64         return _vlan_add(L, ADD_VLAN_CMD);
65 }
66
67 int vlan_del(lua_State *L)
68 {
69         return _vlan_add(L, DEL_VLAN_CMD);
70 }
71
72 int vlan_getall(lua_State *L)
73 {
74         struct dirent **namelist;
75         int n = 0, i, count = 0;
76         count = scandir("/proc/net/vlan/", &namelist, NULL, alphasort);
77         if (count < 0)
78                 return 0;
79         lua_newtable(L);
80         for (i = 0; i < count; i++)
81         {
82                 if(strcmp(namelist[i]->d_name, "config") && (*namelist[i]->d_name != '.'))
83                 {
84                         n++;
85                         lua_pushinteger(L, n);
86                         lua_pushstring(L, namelist[i]->d_name);
87                         lua_settable(L, -3);
88                 }
89                 free(namelist[i]);
90         }
91         free(namelist);
92         return 1;
93 }