Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
mrzack99s committed Sep 26, 2020
2 parents 6076f1b + 63f3fda commit 50e4f7b
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 230 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ WSL2-forwarding-port-cli is command line tools for wsl2 forwarding port configur


## Requirement
- wsl2-forwarding-port-engine version >0.2.x [go to repository](https://github.com/mrzack99s/wsl2-forwarding-port-engine)
- wsl2-forwarding-port-engine version >0.3.x [go to repository](https://github.com/mrzack99s/wsl2-forwarding-port-engine)

## How to install

1. Open WSL2
2. Download the binary with the command
```
curl -LO https://github.com/mrzack99s/wsl2-forwarding-port-cli/releases/download/v2.1.0/wfp-cli
curl -LO https://github.com/mrzack99s/wsl2-forwarding-port-cli/releases/download/v2.2.0/wfp-cli
```
3. Make the wfp-cli binary executable.
```
Expand Down
15 changes: 9 additions & 6 deletions cmds/lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ package cmds

import (
"fmt"

"github.com/mrzack99s/wsl2-forwarding-port-cli/configs"
"strings"
)

func Lists() {
func Lists(taskListStr string) {
fmt.Println("--------------------------------------------------------------------")
fmt.Printf("%-10s%-22s%-12s%-12s%-12s\n", "ID", "WSL2 IPADDR", "PROTOCOL", "SPORT", "DPORT")
fmt.Println("--------------------------------------------------------------------")
if len(configs.RulesTable.Rules) > 0 {
for _, rule := range configs.RulesTable.Rules {
fmt.Printf("%-10s%-22s%-12s%-12s%-12s\n", rule.Id, rule.IpAddress, rule.Protocol, rule.SourcePort, rule.DestinationPort)
if taskListStr != "FAILLED" {
taskList := strings.Split(taskListStr, "@@")
if len(taskList) > 0 {
for _, rule := range taskList {
ruleArgs := strings.Split(rule, "@")
fmt.Printf("%-10s%-22s%-12s%-12s%-12s\n", ruleArgs[0], ruleArgs[1], ruleArgs[2], ruleArgs[3], ruleArgs[4])
}
}
}

Expand Down
28 changes: 0 additions & 28 deletions configs/parse-forwarding-table.go

This file was deleted.

228 changes: 52 additions & 176 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,91 +2,25 @@ package main

import (
"bufio"
"crypto/sha256"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"strings"

"github.com/mrzack99s/wsl2-forwarding-port-cli/structs"

"github.com/mrzack99s/wsl2-forwarding-port-cli/cmds"

"github.com/mrzack99s/wsl2-forwarding-port-cli/configs"

"github.com/mrzack99s/wsl2-forwarding-port-cli/cliparses"
"github.com/mrzack99s/wsl2-forwarding-port-cli/cmds"
"github.com/mrzack99s/wsl2-forwarding-port-cli/supports"
)

func checkFile(filename string) error {
_, err := os.Stat(os.Getenv("HOME") + "/." + filename)
if os.IsNotExist(err) {
_, err := os.Create(os.Getenv("HOME") + "/." + filename)
os.Chmod(os.Getenv("HOME")+"/."+filename, 0644)
if err != nil {
return err
}
}
return nil
}

func writeFile(filename string, rulesTable structs.RulesTable) {
file, _ := json.MarshalIndent(rulesTable, "", " ")
_ = ioutil.WriteFile(os.Getenv("HOME")+"/."+filename, file, 0644)
}

func asSha256(o interface{}) string {
h := sha256.New()
h.Write([]byte(fmt.Sprintf("%v", o)))

return fmt.Sprintf("%x", h.Sum(nil))
}

func checkAlreadyRuleByID(id string) bool {
for _, rule := range configs.RulesTable.Rules {
if id == rule.Id {
return true
}
}
return false
}

func FindElement(id string) (int, structs.RuleStruct, error) {
for i, rule := range configs.RulesTable.Rules {
if rule.Id == id {
return i, rule, nil
}
}
return -1, structs.RuleStruct{}, errors.New("No found")
}

func checkAlreadyRuleBySPortAndProto(port string, proto string) bool {
for _, rule := range configs.RulesTable.Rules {
if port == rule.SourcePort && proto == rule.Protocol {
return true
}
}
return false
}

func main() {

if len(os.Args) < 2 {
supports.Help()
os.Exit(0)
}

filename := "forwarding_rules.json"
if checkFile(filename) != nil {
fmt.Println("Json load error!!!")
os.Exit(0)
}

out, _ := exec.Command("bash", "-c", "ip route | grep default | awk '{print $3}'").Output()
winIp := strings.TrimSpace(string(out))

Expand All @@ -103,26 +37,8 @@ func main() {
return
}

configs.ParseForwardingTable(filename)

var protoPtr, portPtr *string

var ip string
ip = ""
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}

for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
}
}
}

switch os.Args[1] {
case "create":
createCommand := flag.NewFlagSet("create", flag.ExitOnError)
Expand All @@ -131,31 +47,48 @@ func main() {
createCommand.Parse(os.Args[2:])
createArgs := cliparses.CreateGetArgs(createCommand, protoPtr, portPtr)

rule := structs.RuleStruct{
IpAddress: ip,
Protocol: createArgs[0],
SourcePort: createArgs[1],
DestinationPort: createArgs[2],
message := []byte("create@" + createArgs[0] + "@" + createArgs[1] + "@" + createArgs[2])
_, err = udpConn.Write(message)

for {
buffer := make([]byte, 65535)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
} else {
if strings.TrimSpace(string(buffer[0:n])) == "SUCCESS" {
fmt.Println("Inserted success")
break
} else if strings.TrimSpace(string(buffer[0:n])) == "ALREADY" {
fmt.Println("The rule is already.....")
break
} else {
break
}
}
}
hash := asSha256(rule)
substringhash := hash[:8]

alreadyRule := checkAlreadyRuleByID(substringhash)
if !alreadyRule && !checkAlreadyRuleBySPortAndProto(rule.SourcePort, rule.Protocol) {
udpConn.Close()

message := []byte("create@" + substringhash + "@" + rule.Protocol + "@" + rule.SourcePort + "@" + rule.DestinationPort)
case "delete":
if len(os.Args) < 3 {
supports.DeleteHelp()
os.Exit(0)
} else {

id := os.Args[2]

message := []byte("delete@" + id)
_, err = udpConn.Write(message)

status := false
//Keep calling this function
for {
buffer := make([]byte, 2048)
buffer := make([]byte, 65535)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
} else {
if strings.TrimSpace(string(buffer[0:n])) == "SUCCESS" {
status = true
fmt.Println("Deleted success")
break
} else if strings.TrimSpace(string(buffer[0:n])) == "ALREADY" {
fmt.Println("The rule is already.....")
Expand All @@ -166,72 +99,8 @@ func main() {
}
}

if status {
rule.Id = substringhash
configs.RulesTable.AppendRules(rule)
writeFile(filename, configs.RulesTable)
fmt.Println("Inserted success")
}

udpConn.Close()

} else {
if alreadyRule {
fmt.Println("The rule is already.....")
} else {
fmt.Println("The source port has duplicate.....")
}
}
case "delete":
if len(os.Args) < 3 {
supports.DeleteHelp()
os.Exit(0)
} else {

id := os.Args[2]

if checkAlreadyRuleByID(id) {
index, _, err := FindElement(id)
if err == nil {

message := []byte("delete@" + id)
_, err = udpConn.Write(message)

status := false
//Keep calling this function
for {
buffer := make([]byte, 2048)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
} else {
if strings.TrimSpace(string(buffer[0:n])) == "SUCCESS" {
status = true
break
} else if strings.TrimSpace(string(buffer[0:n])) == "ALREADY" {
fmt.Println("The rule is already.....")
break
} else {
break
}
}
}

if status {
length := len(configs.RulesTable.Rules)

configs.RulesTable.Rules[index] = configs.RulesTable.Rules[length-1] // Copy last element to index i
configs.RulesTable.Rules[length-1] = structs.RuleStruct{} // Erase last element )
configs.RulesTable.Rules = configs.RulesTable.Rules[:length-1] // Truncate slice
writeFile(filename, configs.RulesTable)
fmt.Println("Delete success")
}

udpConn.Close()
}
} else {
fmt.Println("Not have the rule in table.....")
}
}

case "purge":
Expand All @@ -242,34 +111,41 @@ func main() {
message := []byte("purge@Y")
_, err = udpConn.Write(message)

status := false
//Keep calling this function
for {
buffer := make([]byte, 2048)
buffer := make([]byte, 65535)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
} else {
if strings.TrimSpace(string(buffer[0:n])) == "SUCCESS" {
status = true
fmt.Println("Purge success")
break
} else {
break
}
}
}
if status {
configs.RulesTable.Rules = nil
writeFile(filename, configs.RulesTable)
fmt.Println("Purge success")
}

}

case "ls":
cmds.Lists()
message := []byte("get@ls")
_, err = udpConn.Write(message)
bufStr := ""

for {
buffer := make([]byte, 65535)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
} else {
bufStr = strings.TrimSpace(string(buffer[0:n]))
break
}
}
cmds.Lists(bufStr)

case "version":
cliVersion := "2.1.0"
cliVersion := "2.2.0"
if len(os.Args) < 3 {
supports.VersionHelp()
} else {
Expand All @@ -283,7 +159,7 @@ func main() {
//Keep calling this function
engineVersion := ""
for {
buffer := make([]byte, 2048)
buffer := make([]byte, 65535)
n, _, err := udpConn.ReadFromUDP(buffer)
if err != nil {
break
Expand Down
Loading

0 comments on commit 50e4f7b

Please sign in to comment.