Tomato 1.26 beta (1780)
[tomato.git] / release / src / router / miniupnpd / ipfw / ipfwaux.h
blobd47b6095ba82315115bf0edcf2501b3f64cf55bd
2 #ifndef __IPFWAUX_H__
3 #define __IPFWAUX_H__
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <netinet/in.h>
8 #include <netinet/ip_fw.h>
10 #define IP_FW_BASE (IP_FW_ADD - 5)
11 #define IP_FW_INIT (IP_FW_BASE + 1)
12 #define IP_FW_TERM (IP_FW_BASE + 2)
14 static int ipfw_exec(int optname, void * optval, uintptr_t optlen) {
15 static int sock = -1;
16 int result;
18 switch (optname) {
19 case IP_FW_INIT:
20 if (sock == -1)
21 sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
22 if (sock < 0) {
23 syslog(LOG_ERR, "socket(SOCK_RAW): %m");
24 return -1;
26 break;
27 case IP_FW_TERM:
28 if (sock != -1)
29 close(sock);
30 sock = -1;
31 break;
32 case IP_FW_ADD:
33 case IP_FW_DEL:
34 result = setsockopt(sock, IPPROTO_IP, optname, optval, optlen);
35 if (result == -1) {
36 syslog(LOG_ERR, "setsockopt(): %m");
37 return -1;
39 break;
40 case IP_FW_GET:
41 result = getsockopt(sock, IPPROTO_IP, optname, optval, (socklen_t *)optlen);
42 if (result == -1) {
43 syslog(LOG_ERR, "getsockopt(): %m");
44 return -1;
46 break;
47 default:
48 syslog(LOG_ERR, "unhandled option");
49 return -1;
52 return 0;
55 static void ipfw_free_ruleset(struct ip_fw ** rules) {
56 if (rules == NULL || *rules == NULL)
57 return;
58 free(*rules);
59 *rules = NULL;
62 static int ipfw_fetch_ruleset(struct ip_fw ** rules, int * total_fetched, int count) {
63 int fetched;
64 socklen_t size;
66 if (rules == NULL || *total_fetched < 0 || count < 1)
67 return -1;
69 size = sizeof(struct ip_fw) * (*total_fetched + count);
70 *rules = (struct ip_fw *)realloc(*rules, size);
71 if (*rules == NULL) {
72 syslog(LOG_ERR, "realloc(): %m");
73 return -1;
76 (*rules)->version = IP_FW_CURRENT_API_VERSION;
77 if (ipfw_exec(IP_FW_GET, *rules, (uintptr_t)&size) < 0)
78 return -1;
79 fetched = *total_fetched;
80 *total_fetched = size / sizeof(struct ip_fw);
82 return *total_fetched - fetched;
85 static int ipfw_validate_protocol(int value) {
86 switch (value) {
87 case IPPROTO_TCP:
88 case IPPROTO_UDP:
89 break;
90 default:
91 syslog(LOG_ERR, "invalid protocol");
92 return -1;
94 return 0;
97 static int ipfw_validate_ifname(const char * const value) {
98 int len = strlen(value);
99 if (len < 2 || len > FW_IFNLEN) {
100 syslog(LOG_ERR, "invalid interface name");
101 return -1;
103 return 0;
106 #endif