-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
209 lines (177 loc) · 4.57 KB
/
main.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
"github.com/pelletier/go-toml"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetPrefix("ipchange: ")
log.SetOutput(os.Stderr)
}
type IPRoute struct {
Dst string `json:"dst"`
Gateway string `json:"gateway"`
Dev string `json:"dev"`
PrefSrc string `json:"prefsrc"`
Flags []string `json:"flags"`
UID int `json:"uid"`
Cache []string `json:"cache"`
}
// Generated by https://quicktype.io
type IPInfoResponse struct {
IP string `json:"ip"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
LOC string `json:"loc"`
Org string `json:"org"`
Postal string `json:"postal"`
Timezone string `json:"timezone"`
}
// AppConfig holds our application data
type AppStorage struct {
LastCheckTime time.Time
LastIP string
LastNetwork string
LastSubnet string
IPChanged bool
}
// Write a struct to store the api key and url
type AppConfig struct {
Token string
URL string
}
func main() {
// Initialize our application configuration
var storage AppStorage
var config AppConfig
var ipChanged bool
var networkChanged bool
homeDir, _ := os.UserHomeDir()
StorageFilePath := filepath.Join(homeDir, ".local", "ipchange", "storage.toml")
ConfigFilePath := filepath.Join(homeDir, ".local", "ipchange", "config.toml")
LogFilePath := filepath.Join(homeDir, ".local", "ipchange", "ipchange.log")
storagePath, _ := filepath.Abs(os.ExpandEnv(StorageFilePath))
if _, err := os.Stat(storagePath); err == nil {
storage = loadStorage(storagePath)
} else if os.IsNotExist(err) {
err := os.MkdirAll(filepath.Dir(storagePath), 0755)
if err != nil {
log.Println(err)
}
storage = AppStorage{}
}
configPath, _ := filepath.Abs(os.ExpandEnv(ConfigFilePath))
if _, err := os.Stat(configPath); err == nil {
config = loadConfig(configPath)
} else if os.IsNotExist(err) {
err := os.MkdirAll(filepath.Dir(configPath), 0755)
if err != nil {
log.Println(err)
}
config = AppConfig{}
saveConfig(configPath, config)
}
switch runtime.GOOS {
case "linux":
cmd := exec.Command("ip", "--json", "route", "get", "1")
output, err := cmd.Output()
if err != nil {
log.Fatalf("Error executing ip command: %v", err)
}
var routes []IPRoute
if err := json.Unmarshal(output, &routes); err != nil {
log.Fatalf("Error parsing JSON output: %v", err)
}
if len(routes) > 0 {
route := routes[0]
if route.Dev != storage.LastNetwork || route.PrefSrc != storage.LastSubnet {
storage.LastNetwork = route.Dev
storage.LastSubnet = route.PrefSrc
}
}
default:
log.Printf("OS %s is not supported", runtime.GOOS)
}
if networkChanged {
ip, err := getPublicIP(config)
if err != nil {
log.Fatal(err)
}
ipChanged = ip != storage.LastIP
storage.LastIP = ip
storage.LastCheckTime = time.Now()
saveStorage(storagePath, storage)
}
storage.IPChanged = ipChanged
jsonResult, _ := json.Marshal(storage)
fmt.Println(string(jsonResult))
saveLog(LogFilePath, jsonResult)
}
func getPublicIP(info AppConfig) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", info.URL, nil)
if err != nil {
return "", err
}
req.Header.Add("Authorization", "Bearer "+info.Token)
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
var ipinfo IPInfoResponse
err = json.Unmarshal(body, &ipinfo)
if err != nil {
return "", err
}
return ipinfo.IP, nil
}
func loadStorage(path string) AppStorage {
file, _ := os.ReadFile(path)
var storage AppStorage
_ = toml.Unmarshal(file, &storage)
return storage
}
// saveLog appends the log to the log file
// if the file does not exist, create it with 0644 permissions
func saveLog(path string, logData []byte) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return
}
defer file.Close()
// Append a newline to the log data
logData = append(logData, '\n')
if _, err := file.Write(logData); err != nil {
log.Println(err)
}
}
func saveStorage(path string, storage AppStorage) {
file, _ := toml.Marshal(&storage)
_ = os.WriteFile(path, file, 0644)
}
func loadConfig(path string) AppConfig {
file, _ := os.ReadFile(path)
var config AppConfig
_ = toml.Unmarshal(file, &config)
return config
}
func saveConfig(path string, config AppConfig) {
file, _ := toml.Marshal(&config)
_ = os.WriteFile(path, file, 0644)
}