owrt/uci_firewall_custom_rules.go

110 lines
2.4 KiB
Go

package owrt
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
// UCIFirewallCustomRule is the description of an Wireless interface (cf Openwrt doc) on top of an Wireless Device
type UCIFirewallCustomRule struct {
Name string
Rule string
UCI *UCI
}
// NewUCIFirewallCustomRule builds a new UCIFirewallCustomRule instance
func NewUCIFirewallCustomRule(client *UCI) *UCIFirewallCustomRule {
return &UCIFirewallCustomRule{
UCI: client,
}
}
// Create add a new firewall rule in UCI Configuration
func (cr *UCIFirewallCustomRule) Create() error {
var file *os.File
customFWFile := cr.UCI.CustomFirewallFile
fmt.Printf("DEBUG %s\n", customFWFile)
_, stErr := os.Stat(customFWFile)
if os.IsNotExist(stErr) {
var err error
file, err = os.Create(customFWFile)
if err != nil {
return err
}
} else {
var oErr error
file, oErr = os.OpenFile(customFWFile, os.O_RDWR, 0644)
if oErr != nil {
return oErr
}
}
defer file.Close()
line := fmt.Sprintf("%s # %s", cr.Rule, cr.Name)
_, err := file.WriteString(line)
return err
}
// Save commit and relaod configuration (writes it to files !)
func (cr *UCIFirewallCustomRule) Save() error {
reload := cr.UCI.Reload()
if reload.ReturnCode != 0 {
return fmt.Errorf("%d - %s - %s - %s",
reload.ReturnCode,
reload.Command,
reload.Stdout,
reload.Stderr)
}
sErr := cr.UCI.Service("firewall", "restart")
return sErr
}
// Delete remove wifi interface from UCI Configuration
func (cr *UCIFirewallCustomRule) Delete() error {
input, err := ioutil.ReadFile(cr.UCI.CustomFirewallFile)
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
var out []string
for _, line := range lines {
if !strings.Contains(line, cr.Name) {
out = append(out, line)
}
}
output := strings.Join(out, "\n")
err = ioutil.WriteFile(cr.UCI.CustomFirewallFile, []byte(output), 0644)
return err
}
// Update add a new entry for wifi interface in UCI Configuration
func (cr *UCIFirewallCustomRule) Update() error {
input, err := ioutil.ReadFile(cr.UCI.CustomFirewallFile)
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
var out []string
for _, line := range lines {
if strings.Contains(line, cr.Name) {
nContent := fmt.Sprintf("%s # %s", cr.Rule, cr.Name)
out = append(out, nContent)
} else {
out = append(out, line)
}
}
output := strings.Join(out, "\n")
err = ioutil.WriteFile(cr.UCI.CustomFirewallFile, []byte(output), 0644)
return err
}