Initial code

Bug: misc:36

Change-Id: I659ce2684ec02960ffa2bdf1636aeccd44f3010e
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4c49bd7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.env
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c8175f7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,3 @@
+# hgu-sipsettings-reverter
+
+A tool to revert the unwanted changes made by Telefónica to the SIP settings in the HGU Askey 3505VW all-in-one router.
diff --git a/client/client.go b/client/client.go
new file mode 100644
index 0000000..9ba79f6
--- /dev/null
+++ b/client/client.go
@@ -0,0 +1,95 @@
+package hguclient
+
+import (
+	"errors"
+	"io"
+	"net/http"
+	"net/http/cookiejar"
+	"net/url"
+	"strings"
+
+	"golang.org/x/net/publicsuffix"
+)
+
+const URL_INDEX = "/"
+const URL_LOGIN = "/te_acceso_router.cgi"
+const URL_SIPBASIC = "/voicesip_basic.html"
+const URL_SIPSTOP = "/voicesipstop.cmd"
+const URL_SIPSTART = "/voicesipstart.cmd"
+
+const LOGGED_OUT_SCRIPT = "<script language='javascript'>\nwindow.top.location = \"/\";\n</script>"
+const LOGGED_OUT_SCRIPT_HOME = "src='te_acceso_router.html'"
+
+type Client struct {
+	httpClient http.Client
+	endpoint   string
+	password   string
+}
+
+func New(endpoint string, password string) (*Client, error) {
+	jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
+	if err != nil {
+		return nil, err
+	}
+
+	client := &Client{
+		httpClient: http.Client{
+			Jar: jar,
+		},
+		endpoint: endpoint,
+		password: password,
+	}
+	return client, nil
+}
+
+func (c *Client) LogIn() error {
+	// Visit the homepage to generate the current sessionId cookie
+	c.httpClient.Get(c.endpoint)
+
+	// Log in
+	resp, err := c.httpClient.PostForm(c.endpoint+URL_LOGIN, url.Values{
+		"loginPassword": []string{c.password},
+	})
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != 200 {
+		return errors.New("Status code is not 200.")
+	}
+
+	return nil
+}
+
+func (c *Client) Get(path string, autoLogIn bool) (string, error) {
+	resp, err := c.httpClient.Get(c.endpoint + path)
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != 200 {
+		return "", errors.New("Status code is not 200.")
+	}
+	bodyb, err := io.ReadAll(resp.Body)
+	if err != nil {
+		return "", err
+	}
+	body := string(bodyb)
+
+	if !strings.Contains(body, LOGGED_OUT_SCRIPT) {
+		return body, nil
+	}
+	if !autoLogIn {
+		return "", errors.New("User needs to log in")
+	}
+	c.LogIn()
+	return c.Get(path, false)
+}
+
+func (c *Client) IsLoggedIn() (bool, error) {
+  body, err := c.Get("", false)
+  if err != nil {
+    return false, err
+  }
+  return !strings.Contains(body, LOGGED_OUT_SCRIPT_HOME), nil
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..dacd1e9
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,5 @@
+module gomodules.avm99963.com/hgu-sipsettings-reverter
+
+go 1.16
+
+require golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d // indirect
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..f6c12d5
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,7 @@
+golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d h1:1n1fc535VhN8SYtD4cDUyNlfpAF2ROMM9+11equK3hs=
+golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
diff --git a/sip_reverter.go b/sip_reverter.go
new file mode 100644
index 0000000..3cfcb16
--- /dev/null
+++ b/sip_reverter.go
@@ -0,0 +1,134 @@
+package main
+
+import (
+	"errors"
+	"fmt"
+	"log"
+	"net/url"
+	"os"
+	"regexp"
+	"strconv"
+	"time"
+
+	hguclient "gomodules.avm99963.com/hgu-sipsettings-reverter/client"
+)
+
+var (
+	obProxyAddrRe = regexp.MustCompile(`oa0 = "([\d\.]*)";`)
+	obProxyPortRe = regexp.MustCompile(`op0 = "(\d*)";`)
+	ipInterfaceRe = regexp.MustCompile(`var ifn = '([^']*)';`)
+)
+
+type OutboundProxySettings struct {
+	Address     string
+	Port        int
+	IpInterface string
+}
+
+func GetOutboundProxySettings(client *hguclient.Client) (*OutboundProxySettings, error) {
+	loggedIn, err := client.IsLoggedIn()
+	if err != nil {
+		return nil, err
+	}
+	if !loggedIn {
+		log.Println("Not logged in, logging in...")
+		err := client.LogIn()
+		if err != nil {
+			return nil, err
+		}
+	}
+	body, err := client.Get(hguclient.URL_SIPBASIC, false)
+	if err != nil {
+		return nil, err
+	}
+	addrMatches := obProxyAddrRe.FindStringSubmatch(body)
+	if len(addrMatches) < 2 {
+		return nil, errors.New("Can't find outbound proxy address in settings.")
+	}
+	addr := addrMatches[1]
+	portMatches := obProxyPortRe.FindStringSubmatch(body)
+	if len(portMatches) < 2 {
+		return nil, errors.New("Can't find oubound proxy port in settings.")
+	}
+	port, err := strconv.Atoi(portMatches[1])
+	if err != nil {
+		return nil, err
+	}
+	ipMatches := ipInterfaceRe.FindStringSubmatch(body)
+	if len(ipMatches) < 2 {
+		return nil, errors.New("Can't find IP interface in settings.")
+	}
+	ip := ipMatches[1]
+	return &OutboundProxySettings{
+		Address:     addr,
+		Port:        port,
+		IpInterface: ip,
+	}, nil
+}
+
+func check(client *hguclient.Client, correctSettings *OutboundProxySettings) error {
+	currentSettings, err := GetOutboundProxySettings(client)
+	if err != nil {
+		log.Fatalln(err)
+	}
+	if *currentSettings == *correctSettings {
+    log.Println("Settings are ok.")
+		return nil
+	}
+	log.Println(fmt.Sprintf("Settings are incorrect! Current settings: %v. Correct settings: %v.", currentSettings, correctSettings))
+	_, err = client.Get("/voicesipstop.cmd", false)
+	if err != nil {
+		return errors.New(fmt.Sprintf("Couldn't stop SIP: %v", err))
+	}
+	eAddr := url.QueryEscape(correctSettings.Address)
+	ePort := url.QueryEscape(strconv.Itoa(correctSettings.Port))
+	eInt := url.QueryEscape(correctSettings.IpInterface)
+	startUrl := "/voicesipstart.cmd?currentview=basic&ifName=" + eInt + "&obProxyAddr0=" + eAddr + "&obProxyPort0=" + ePort
+	_, err = client.Get(startUrl, false)
+	if err != nil {
+		return errors.New(fmt.Sprintf("Couldn't start SIP: %v", err))
+	}
+	log.Println("Settings have been fixed")
+	return nil
+}
+
+func mustGetEnv(name string) string {
+	env, ok := os.LookupEnv(name)
+	if !ok {
+		log.Fatalln(fmt.Sprintf("%v environment variable must be set.", name))
+	}
+	return env
+}
+
+func main() {
+	log.Println("Starting sip_reverter")
+
+	endpoint := mustGetEnv("SIPREVERTER_HGU_ENDPOINT")
+	password := mustGetEnv("SIPREVERTER_HGU_PASSWORD")
+
+	address := mustGetEnv("SIPREVERTER_CONF_ADDRESS")
+	portString := mustGetEnv("SIPREVERTER_CONF_PORT")
+	port, err := strconv.Atoi(portString)
+	if err != nil {
+		log.Fatalln(fmt.Sprintf("Can't parse port: %v", err))
+	}
+	ipInterface := mustGetEnv("SIPREVERTER_CONF_INTERFACE")
+	correctObProxySettings := &OutboundProxySettings{
+		Address:     address,
+		Port:        port,
+		IpInterface: ipInterface,
+	}
+
+	client, err := hguclient.New(endpoint, password)
+	if err != nil {
+		log.Fatalln(err)
+	}
+
+	for {
+		err := check(client, correctObProxySettings)
+		if err != nil {
+			log.Println(fmt.Sprintf("Error while checking: %v", err))
+		}
+		time.Sleep(90 * time.Second)
+	}
+}