-
Notifications
You must be signed in to change notification settings - Fork 1
/
state.go
128 lines (105 loc) · 2.28 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Froxy - HTTP over SSH proxy
//
// Copyright (C) 2019 and up by Alexander Pevzner ([email protected])
// See LICENSE for license terms and conditions
//
// Froxy persistent state
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"os"
"github.com/alexpevzner/froxy/internal/sysdep"
)
//
// The persistent state
//
type State struct {
Port int `json:"port"` // TCP port Froxy runs on
Server ServerParams `json:"server"` // Server parameters
Sites []SiteParams `json:"sites"` // List of forwarded sites
}
//
// Server parameters
//
type ServerParams struct {
Addr string `json:"addr,omitempty"` // Server address
Login string `json:"login,omitempty"` // Server login
Password string `json:"password,omitempty"` // Server password
Keyid string `json:"keyid,omitempty"` // Key ID
}
//
// Site parameters
//
type SiteParams struct {
Host string `json:"host,omitempty"` // Host name
Rec bool `json:"rec,omitempty"` // Recursive (with subdomains)
Block bool `json:"block,omitempty"` // Block the site
}
//
// Load state
//
func (state *State) Load(file string) error {
// Reset the state
state.Server = ServerParams{}
state.Sites = []SiteParams{}
// Read the state file
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
err = sysdep.FileLock(f, false, true)
if err != nil {
return err
}
defer sysdep.FileUnlock(f)
data, err := ioutil.ReadAll(f)
if err != nil {
return err
}
// Parse the state
err = json.Unmarshal(data, &state)
return err
}
//
// Save state
//
func (state *State) Save(file string) error {
// Allocate buffer
buf := &bytes.Buffer{}
// Setup JSON encoder
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
// Encode into the buffer
err := enc.Encode(state)
if err != nil {
panic(err) // Should never happen
}
// Write to file
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
err = sysdep.FileLock(f, true, true)
if err != nil {
f.Close()
return err
}
err = f.Truncate(0)
if err == nil {
n, err2 := f.Write(buf.Bytes())
if err2 == nil && n < buf.Len() {
err2 = io.ErrShortWrite
}
err = err2
}
sysdep.FileUnlock(f)
if err2 := f.Close(); err == nil {
err = err2
}
return err
}