forked from inhies/cjdcmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addpeer.go
433 lines (389 loc) · 10.7 KB
/
addpeer.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
* You may redistribute this program and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"bufio"
"encoding/json"
"fmt"
"github.com/inhies/go-cjdns/config"
"net"
"os"
"strings"
)
func addPassword(data []string) {
// Load the config file
if File == "" {
var cjdnsAdmin *CjdnsAdmin
var err error
if !userSpecifiedCjdnsadmin {
cjdnsAdmin, err = loadCjdnsadmin()
if err != nil {
fmt.Println("Unable to load configuration file:", err)
return
}
} else {
cjdnsAdmin, err = readCjdnsadmin(userCjdnsadmin)
if err != nil {
fmt.Println("Error loading cjdnsadmin file:", err)
return
}
}
File = cjdnsAdmin.Config
if File == "" {
fmt.Println("Please specify the configuration file in your .cjdnsadmin file or pass the --file flag.")
return
}
}
fmt.Printf("Loading configuration from: %v... ", File)
conf, err := config.LoadExtConfig(File)
if err != nil {
fmt.Println("Error loading config:", err)
return
}
fmt.Printf("Loaded\n")
var input string
if len(data) == 0 {
fmt.Printf("You didnt supply a password, should I generate one for you? [Y/n]: ")
if gotYes(true) {
for {
input = randString(15, 50)
fmt.Printf("Generated: '%v' Accept? [Y/n]: ", input)
if gotYes(true) {
break
}
}
} else {
// No password supplied, not going to generate one, I quit!
return
}
} else {
input = data[0]
}
if _, ok := conf["authorizedPasswords"]; !ok {
conf["authorizedPasswords"] = make([]interface{}, 0)
fmt.Println("Your configuration file does not contain an 'authorizedPasswords' section, so one was created for you")
}
passwords := conf["authorizedPasswords"].([]interface{})
for loc, p := range passwords {
x := p.(map[string]interface{})
if x["password"] == input {
fmt.Printf("Password '%v' exists with the following information:\n", input)
for f, v := range x {
fmt.Printf("\t\"%v\":\"%v\"\n", f, v)
}
fmt.Printf("Update password with new information? [Y/n]: ")
if gotYes(true) {
// Remove the entry we are replacing
passwords = append(passwords[:loc], passwords[loc+1:]...)
break
} else {
return
}
}
}
pass := make(map[string]interface{})
pass["password"] = input
is := conf["interfaces"].(map[string]interface{})
if len(is) == 0 {
fmt.Println("No valid interfaces found!")
return
} else if len(is) > 1 {
fmt.Println("You have multiple interfaces to choose from, enter yes or no, or press enter for the default option:")
}
var useIface string
var i []interface{}
selectIF:
for {
for key, _ := range is {
if len(is) > 1 {
fmt.Printf("Add password to '%v' [Y/n]: ", key)
if gotYes(true) {
i = is[key].([]interface{})
useIface = key
break selectIF
}
} else if len(is) == 1 {
i = is[key].([]interface{})
useIface = key
}
}
if useIface == "" {
fmt.Println("You must select an interface to add to!")
continue
}
break
}
var iX map[string]interface{}
if len(i) > 1 {
fmt.Printf("You have multiple '%v' options to choose from, enter yes or no, or press enter for the default option\n", useIface)
selectIF2:
for _, iFace := range i {
temp := iFace.(map[string]interface{})
fmt.Printf("Add peer to '%v %v' [Y/n]: ", useIface, temp["bind"])
if gotYes(true) {
iX = iFace.(map[string]interface{})
break
}
}
if iX == nil {
fmt.Println("You must select an interface to add to!")
goto selectIF2
}
} else if len(i) == 1 {
iX = i[0].(map[string]interface{})
} else {
fmt.Printf("No valid settings for '%v' found!\n", useIface)
return
}
// Optionally add meta information
for {
r := bufio.NewReader(os.Stdin)
fmt.Printf("Enter a field name for any extra information, or press enter to skip: ")
fName, _ := r.ReadString('\n')
fName = strings.TrimSpace(fName)
if len(fName) == 0 {
break
}
fmt.Printf("Enter a the content for field '%v' or press enter to cancel: ", fName)
fData, _ := r.ReadString('\n')
fData = strings.TrimSpace(fData)
if len(fData) == 0 {
continue
}
pass[fName] = fData
continue
}
fmt.Println("Password information:")
for f, v := range pass {
fmt.Printf("\t\"%v\":\"%v\"\n", f, v)
}
fmt.Printf("Add this password? [Y/n]: ")
if gotYes(true) {
conf["authorizedPasswords"] = append(passwords, pass)
fmt.Println("Password added")
} else {
fmt.Println("Cancelled adding password")
return
}
// Get the permissions from the input file
stats, err := os.Stat(File)
if err != nil {
fmt.Println("Error getting permissions for original file:", err)
return
}
if File != "" && OutFile == "" {
OutFile = File
}
// Check if the output file exists and prompt befoer overwriting
if _, err := os.Stat(OutFile); err == nil {
fmt.Printf("Overwrite %v? [y/N]: ", OutFile)
if !gotYes(false) {
return
}
}
fmt.Printf("Saving configuration to: %v... ", OutFile)
err = config.SaveConfig(OutFile, conf, stats.Mode())
if err != nil {
fmt.Println("\nError saving config:", err)
return
}
fmt.Printf("Saved\n")
var bind string
if strings.ToLower(useIface) == "ethinterface" {
iFace, err := net.InterfaceByName(iX["bind"].(string))
if err != nil {
fmt.Println("Unable to get interface's MAC address, you'll have to enter it yourself")
bind = "UNKNOWN"
} else {
bind = iFace.HardwareAddr.String()
}
} else {
bind = iX["bind"].(string)
}
fmt.Println("Here are the details to be shared with your new peer:")
fmt.Printf("\"%v\":{\n", bind)
fmt.Printf("\t\"password\":\"%v\",\n", pass["password"].(string))
fmt.Printf("\t\"publicKey\":\"%v\"\n", conf["publicKey"].(string))
fmt.Printf("}\n")
}
func addPeer(data []string) {
if len(data) == 0 {
fmt.Println("You must enter the peering details surrounded by single qoutes '<peer details>'")
return
}
input := data[0]
// Strip comments, just in case, and surround with {} to make it valid JSON
raw, err := stripComments([]byte("{" + input + "}"))
if err != nil {
fmt.Println("Comment errors: ", err)
return
}
// Convert from JSON to an object
var object map[string]interface{}
err = json.Unmarshal(raw, &object)
if err != nil {
fmt.Println("JSON Error:", err)
return
}
// Load the config file
if File == "" {
cjdAdmin, err := loadCjdnsadmin()
if err != nil {
fmt.Println("Unable to load configuration file:", err)
return
}
File = cjdAdmin.Config
if File == "" {
fmt.Println("Please specify the configuration file in your .cjdnsadmin file or pass the --file flag.")
return
}
}
fmt.Printf("Loading configuration from: %v... ", File)
conf, err := config.LoadExtConfig(File)
if err != nil {
fmt.Println("Error loading config:", err)
return
}
fmt.Printf("Loaded\n")
if _, ok := conf["interfaces"]; !ok {
fmt.Println("Your configuration file does not contain an 'interfaces' section")
return
}
is := conf["interfaces"].(map[string]interface{})
if len(is) == 0 {
fmt.Println("No valid interfaces found!")
return
} else if len(is) > 1 {
fmt.Println("You have multiple interfaces to choose from, enter yes or no, or press enter for the default option:")
}
var useIface string
var i []interface{}
selectIF:
for {
for key, _ := range is {
if len(is) > 1 {
fmt.Printf("Add peer to '%v' [Y/n]: ", key)
if gotYes(true) {
i = is[key].([]interface{})
useIface = key
break selectIF
}
} else if len(is) == 1 {
i = is[key].([]interface{})
useIface = key
}
}
if useIface == "" {
fmt.Println("You must select an interface to add to!")
continue
}
break
}
var iX map[string]interface{}
if len(i) > 1 {
fmt.Printf("You have multiple '%v' options to choose from, enter yes or no, or press enter for the default option\n", useIface)
selectIF2:
for _, iFace := range i {
temp := iFace.(map[string]interface{})
fmt.Printf("Add peer to '%v %v' [Y/n]: ", useIface, temp["bind"])
if gotYes(true) {
iX = iFace.(map[string]interface{})
break
}
}
if iX == nil {
fmt.Println("You must select an interface to add to!")
goto selectIF2
}
} else if len(i) == 1 {
iX = i[0].(map[string]interface{})
} else {
fmt.Printf("No valid settings for '%v' found!\n", useIface)
return
}
peers := iX["connectTo"].(map[string]interface{})
for key, data := range object {
var peer map[string]interface{}
if peers[key] != nil {
peer = peers[key].(map[string]interface{})
fmt.Printf("Peer '%v' exists with the following information:\n", key)
for f, v := range peer {
fmt.Printf("\t\"%v\":\"%v\"\n", f, v)
}
fmt.Printf("Update peer with new information? [Y/n]: ")
if gotYes(true) {
peer = data.(map[string]interface{})
fmt.Printf("Updating peer '%v'\n", key)
} else {
fmt.Printf("Skipped updating peer '%v'\n", key)
continue
}
} else {
fmt.Printf("Adding new peer '%v'\n", key)
peer = data.(map[string]interface{})
}
// Optionally add meta information
for {
r := bufio.NewReader(os.Stdin)
fmt.Printf("Enter a field name for any extra information, or press enter to skip: ")
fName, _ := r.ReadString('\n')
fName = strings.TrimSpace(fName)
if len(fName) == 0 {
break
}
fmt.Printf("Enter a the content for field '%v' or press enter to cancel: ", fName)
fData, _ := r.ReadString('\n')
fData = strings.TrimSpace(fData)
if len(fData) == 0 {
continue
}
peer[fName] = fData
continue
}
fmt.Println("Peer information:")
for f, v := range peer {
fmt.Printf("\t\"%v\":\"%v\"\n", f, v)
}
fmt.Printf("Add this peer? [Y/n]: ")
if gotYes(true) {
peers[key] = peer
fmt.Println("Peer added")
} else {
fmt.Println("Skipped adding peer")
}
}
// Get the permissions from the input file
stats, err := os.Stat(File)
if err != nil {
fmt.Println("Error getting permissions for original file:", err)
return
}
if File != "" && OutFile == "" {
OutFile = File
}
// Check if the output file exists and prompt befoer overwriting
if _, err := os.Stat(OutFile); err == nil {
fmt.Printf("Overwrite %v? [y/N]: ", OutFile)
if !gotYes(false) {
return
}
}
fmt.Printf("Saving configuration to: %v... ", OutFile)
err = config.SaveConfig(OutFile, conf, stats.Mode())
if err != nil {
fmt.Println("Error saving config:", err)
return
}
fmt.Printf("Saved\n")
}