Skip to content

Commit

Permalink
*: refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
nange committed Dec 9, 2019
1 parent 807ef7a commit 6e96807
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 79 deletions.
2 changes: 1 addition & 1 deletion cmd/client-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func main() {
var writer io.Writer
easyss.Daemon(godaemon)
var err error
writer, err = util.GetLogFileWriter(easyss.LOG_MAX_AGE, easyss.LOG_ROTATION_TIME)
writer, err = util.GetLogFileWriter(easyss.LogMaxAge, easyss.LogRotationTime)
if err != nil {
log.Errorf("get log file output writer err:%v", err)
} else {
Expand Down
67 changes: 48 additions & 19 deletions pac.go → cmd/client-server/pac.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// +build !mips,!mipsle,!mips64,!mips64le,!arm

//go:generate statik -src=./pac
//go:generate statik -src=../pac

package easyss
package main

import (
"fmt"
Expand All @@ -18,12 +18,41 @@ import (
log "github.com/sirupsen/logrus"
)

func (ss *Easyss) SysPAC() {
type PACStatus int

const (
PACON PACStatus = iota + 1
PACOFF
PACONGLOBAL
PACOFFGLOBAL
)

const PacPath = "/proxy.pac"

type PAC struct {
path string
localPort int
ch chan PACStatus
url string
gurl string
}

func NewPAC(localPort int, path, url, grul string) *PAC {
return &PAC{
path: path,
localPort: localPort,
ch: make(chan PACStatus, 1),
url: url,
gurl: grul,
}
}

func (p *PAC) SysPAC() {
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
file, err := statikFS.Open(PacPath)
file, err := statikFS.Open(p.path)
if err != nil {
log.Fatal("open pac.txt err:", err)
}
Expand All @@ -32,12 +61,12 @@ func (ss *Easyss) SysPAC() {
log.Fatal("read pac.txt err:", err)
}

tpl, err := template.New(PacPath).Parse(string(buf))
tpl, err := template.New(p.path).Parse(string(buf))
if err != nil {
log.Fatalf("template parse pac err:%v", err)
}

http.HandleFunc(PacPath, func(w http.ResponseWriter, r *http.Request) {
http.HandleFunc(p.path, func(w http.ResponseWriter, r *http.Request) {
gloabl := false

r.ParseForm()
Expand All @@ -48,24 +77,24 @@ func (ss *Easyss) SysPAC() {

w.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
tpl.Execute(w, map[string]interface{}{
"Port": strconv.Itoa(ss.config.LocalPort),
"Port": strconv.Itoa(p.localPort),
"Global": gloabl,
})
})

if err := ss.pacOn(ss.pac.url); err != nil {
if err := p.pacOn(p.url); err != nil {
log.Fatalf("set system pac err:%v", err)
}
defer ss.pacOff(ss.pac.url)
defer p.pacOff(p.url)

go ss.pacManage()
go p.pacManage()

addr := fmt.Sprintf(":%d", ss.config.LocalPort+1)
addr := fmt.Sprintf(":%d", p.localPort+1)
log.Infof("pac server started on :%v", addr)
http.ListenAndServe(addr, nil)
}

func (ss *Easyss) pacOn(path string) error {
func (p *PAC) pacOn(path string) error {
if err := pac.EnsureHelperToolPresent("pac-cmd", "Set proxy auto config", ""); err != nil {
return errors.WithStack(err)
}
Expand All @@ -76,21 +105,21 @@ func (ss *Easyss) pacOn(path string) error {
return nil
}

func (ss *Easyss) pacOff(path string) error {
func (p *PAC) pacOff(path string) error {
return errors.WithStack(pac.Off(path))
}

func (ss *Easyss) pacManage() {
for status := range ss.pac.ch {
func (p *PAC) pacManage() {
for status := range p.ch {
switch status {
case PACON:
ss.pacOn(ss.pac.url)
p.pacOn(p.url)
case PACOFF:
ss.pacOff(ss.pac.url)
p.pacOff(p.url)
case PACONGLOBAL:
ss.pacOn(ss.pac.gurl)
p.pacOn(p.gurl)
case PACOFFGLOBAL:
ss.pacOff(ss.pac.gurl)
p.pacOff(p.gurl)
default:
log.Errorf("unknown pac status:%v", status)
}
Expand Down
8 changes: 7 additions & 1 deletion cmd/client-server/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
package main

import (
"fmt"

"github.com/getlantern/systray"
"github.com/nange/easyss"
)

func StartEasyss(ss *easyss.Easyss) {
systray.Run(ss.TrayReady, ss.TrayExit) // system tray management
url := fmt.Sprintf("http://localhost:%d%s", ss.LocalPort()+1, PacPath)
gurl := fmt.Sprintf("http://localhost:%d%s?global=true", ss.LocalPort()+1, PacPath)
pac := NewPAC(ss.LocalPort(), PacPath, url, gurl)
st := NewSysTray(ss, pac)
systray.Run(st.TrayReady, st.TrayExit) // system tray management
}
63 changes: 37 additions & 26 deletions tray.go → cmd/client-server/tray.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// +build !mips,!mipsle,!mips64,!mips64le,!arm

package easyss
package main

import (
"fmt"
Expand All @@ -12,26 +12,39 @@ import (
"time"

"github.com/getlantern/systray"
"github.com/nange/easyss"
"github.com/nange/easyss/icon"
"github.com/nange/easyss/util"
log "github.com/sirupsen/logrus"
)

func (ss *Easyss) TrayReady() {
if err := ss.InitTcpPool(); err != nil {
type SysTray struct {
ss *easyss.Easyss
pac *PAC
}

func NewSysTray(ss *easyss.Easyss, pac *PAC) *SysTray {
return &SysTray{
ss: ss,
pac: pac,
}
}

func (st *SysTray) TrayReady() {
if err := st.ss.InitTcpPool(); err != nil {
log.Errorf("init tcp pool error:%v", err)
}
go ss.SysPAC() // system pac configuration
go ss.Local() // start local server
go ss.HttpLocal() // start local http proxy server
go ss.UDPLocal() // start local udp server
go st.pac.SysPAC() // system pac configuration
go st.ss.Local() // start local server
go st.ss.HttpLocal() // start local http proxy server
go st.ss.UDPLocal() // start local udp server

go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Kill, os.Interrupt, syscall.SIGINT, syscall.SIGTERM,
syscall.SIGQUIT)
log.Infof("got signal to exit: %v", <-c)
ss.TrayExit()
st.TrayExit()
}()

systray.SetIcon(icon.Data)
Expand All @@ -56,12 +69,12 @@ func (ss *Easyss) TrayReady() {
cGlobal.Uncheck()
cGlobal.Disable()

ss.pac.ch <- PACOFF
st.pac.ch <- PACOFF
} else {
cPAC.Check()
cGlobal.Enable()

ss.pac.ch <- PACON
st.pac.ch <- PACON
}
log.Infof("pac btn clicked...is checked:%v", cPAC.Checked())
case <-cGlobal.ClickedCh:
Expand All @@ -71,53 +84,51 @@ func (ss *Easyss) TrayReady() {
if cGlobal.Checked() {
cGlobal.Uncheck()
if cPAC.Checked() {
ss.pac.ch <- PACON
st.pac.ch <- PACON
} else {
ss.pac.ch <- PACOFFGLOBAL
st.pac.ch <- PACOFFGLOBAL
}
} else {
cGlobal.Check()
ss.pac.ch <- PACONGLOBAL
st.pac.ch <- PACONGLOBAL
}
log.Infof("global btn clicked... is checked:%v", cGlobal.Checked())
case <-cCatLog.ClickedCh:
log.Infof("cat log btn clicked...")
if err := ss.catLog(); err != nil {
if err := st.catLog(); err != nil {
log.Errorf("cat log err:%v", err)
}

case <-cQuit.ClickedCh:
log.Infof("quit btn clicked quit now...")
systray.Quit()
ss.TrayExit() // on linux there have some bugs, we should invoke trayExit() again
st.TrayExit() // on linux there have some bugs, we should invoke trayExit() again
}
}
}

func (ss *Easyss) catLog() error {
func (st *SysTray) catLog() error {
win := `-FilePath powershell -WorkingDirectory "%s" -ArgumentList "-Command Get-Content %s -Wait %s"`
if runtime.GOOS == "windows" && util.SysSupportPowershell() {
if util.SysPowershellMajorVersion() >= 3 {
win = fmt.Sprintf(win, util.GetCurrentDir(), ss.GetLogFileFullPathName(), "-Tail 100")
win = fmt.Sprintf(win, util.GetCurrentDir(), st.ss.GetLogFileFullPathName(), "-Tail 100")
} else {
win = fmt.Sprintf(win, util.GetCurrentDir(), ss.GetLogFileFullPathName(), "-ReadCount 100")
win = fmt.Sprintf(win, util.GetCurrentDir(), st.ss.GetLogFileFullPathName(), "-ReadCount 100")
}
}

cmdmap := map[string][]string{
"windows": []string{"powershell", "-Command", "Start-Process", win},
"linux": []string{"gnome-terminal", "--geometry=150x40+20+20", "-x", "tail", "-50f", ss.GetLogFileFullPathName()},
"darwin": []string{"open", "-a", "Console", ss.GetLogFileFullPathName()},
"windows": {"powershell", "-Command", "Start-Process", win},
"linux": {"gnome-terminal", "--geometry=150x40+20+20", "-x", "tail", "-50f", st.ss.GetLogFileFullPathName()},
"darwin": {"open", "-a", "Console", st.ss.GetLogFileFullPathName()},
}
cmd := exec.Command(cmdmap[runtime.GOOS][0], cmdmap[runtime.GOOS][1:]...)
return cmd.Start()
}

func (ss *Easyss) TrayExit() {
ss.pac.ch <- PACOFF
if ss.tcpPool != nil {
ss.tcpPool.Close()
}
func (st *SysTray) TrayExit() {
st.pac.ch <- PACOFF
st.ss.Close()
time.Sleep(time.Second) // ensure the pac settings to default value
log.Info("easyss exited...")
os.Exit(0)
Expand Down
1 change: 0 additions & 1 deletion cmd/remote-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ func main() {
} else {
easyss.UpdateConfig(config, &cmdConfig)
}
config.ServerModel = true

ss, err := easyss.New(config)
if err != nil {
Expand Down
26 changes: 8 additions & 18 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,17 @@ import (
)

const (
LOG_MAX_AGE = 48 * time.Hour
LOG_ROTATION_TIME = 12 * time.Hour
)

type PACStatus int

const (
PACON PACStatus = iota + 1
PACOFF
PACONGLOBAL
PACOFFGLOBAL
LogMaxAge = 24 * time.Hour
LogRotationTime = 12 * time.Hour
)

type Config struct {
Server string `json:"server"`
ServerPort int `json:"server_port"`
LocalPort int `json:"local_port"`
Password string `json:"password"`
Method string `json:"method"` // encryption method
Timeout int `json:"timeout"`
ServerModel bool `json:"server_model"`
Server string `json:"server"`
ServerPort int `json:"server_port"`
LocalPort int `json:"local_port"`
Password string `json:"password"`
Method string `json:"method"` // encryption method
Timeout int `json:"timeout"`
}

func ParseConfig(path string) (config *Config, err error) {
Expand Down
28 changes: 15 additions & 13 deletions easyss.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
log "github.com/sirupsen/logrus"
)

const PacPath = "/proxy.pac"

func init() {
log.SetFormatter(&log.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05.000"})
log.SetLevel(log.InfoLevel)
Expand All @@ -24,24 +22,14 @@ func PrintVersion() {
}

type Easyss struct {
config *Config
pac struct {
ch chan PACStatus
url string
gurl string
}
config *Config
tcpPool easypool.Pool

LogFileWriter io.Writer
}

func New(config *Config) (*Easyss, error) {
ss := &Easyss{config: config}
if !config.ServerModel {
ss.pac.ch = make(chan PACStatus)
ss.pac.url = fmt.Sprintf("http://localhost:%d%s", ss.config.LocalPort+1, PacPath)
ss.pac.gurl = fmt.Sprintf("http://localhost:%d%s?global=true", ss.config.LocalPort+1, PacPath)
}

return ss, nil
}
Expand Down Expand Up @@ -70,3 +58,17 @@ func (ss *Easyss) InitTcpPool() error {
ss.tcpPool = tcppool
return err
}

func (ss *Easyss) LocalPort() int {
return ss.config.LocalPort
}

func (ss *Easyss) ServerPort() int {
return ss.config.ServerPort
}

func (ss *Easyss) Close() {
if ss.tcpPool != nil {
ss.tcpPool.Close()
}
}

0 comments on commit 6e96807

Please sign in to comment.