-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·2696 lines (2240 loc) · 71.6 KB
/
main.go
File metadata and controls
executable file
·2696 lines (2240 loc) · 71.6 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
_ "net/http/pprof"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"slices"
"sort"
"strconv"
"strings"
"syscall"
"github.com/charmbracelet/x/term"
_ "modernc.org/sqlite"
)
// initDB opens a connection to the SQLite database and ensures all necessary
// It's designed to be idempotent.
func initDB(filepath string) error {
var err error
// Open the database file. It will be created if it doesn't exist.
db, err = sql.Open("sqlite", filepath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
// A map of table names to their CREATE statements for clarity and organization.
tables := map[string]string{
"sshprofiles": `
CREATE TABLE IF NOT EXISTS sshprofiles (
host TEXT PRIMARY KEY,
password TEXT,
note TEXT,
url TEXT,
folder TEXT
);`,
"encryption_key": `
CREATE TABLE IF NOT EXISTS encryption_key (
id INTEGER PRIMARY KEY CHECK (id = 1), -- Ensures only one row can exist
key BLOB NOT NULL
);`,
"console_profiles": `
CREATE TABLE IF NOT EXISTS console_profiles (
host TEXT PRIMARY KEY,
baud_rate INTEGER NOT NULL,
device TEXT NOT NULL,
parity TEXT,
stop_bit TEXT,
data_bits INTEGER,
folder TEXT
);`,
}
// Execute each CREATE TABLE statement.
for name, stmt := range tables {
if _, err := db.Exec(stmt); err != nil {
return fmt.Errorf("failed to create table '%s': %w", name, err)
}
}
// Add url and sshkey_passphrase columns to an existing database
rows, err := db.Query("PRAGMA table_info(sshprofiles)")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
urlColumnExists := false
passphraseColumnExists := false
for rows.Next() {
var (
cid int
name string
dataType string
notNull int
dfltVal sql.NullString
pk int
)
if err := rows.Scan(&cid, &name, &dataType, ¬Null, &dfltVal, &pk); err != nil {
log.Fatal(err)
}
if name == "url" {
urlColumnExists = true
}
if name == "sshkey_passphrase" {
passphraseColumnExists = true
}
}
if !urlColumnExists {
_, err := db.Exec("ALTER TABLE sshprofiles ADD COLUMN url TEXT")
if err != nil {
log.Fatalf("failed to add url column: %v", err)
}
fmt.Println("Successfully added the 'url' column.")
}
if !passphraseColumnExists {
_, err := db.Exec("ALTER TABLE sshprofiles ADD COLUMN sshkey_passphrase TEXT")
if err != nil {
log.Fatalf("failed to add sshkey_passphrase column: %v", err)
}
fmt.Println("Successfully added the 'sshkey_passphrase' column.")
}
return nil
}
func OpenSqlCli() {
// Ping the database to verify the connection is alive.
err := db.Ping()
if err != nil {
log.Fatalf("Error connecting to database: %v", err)
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
// Blocks until a signal is received.
<-sigs
// 5. Perform cleanup actions here.
if db != nil {
db.Close()
fmt.Println("\nDatabase connection closed.")
}
os.Exit(0)
}()
fmt.Printf("Connected to SQLite database\n")
fmt.Println("Enter SQL commands. Type 'exit' or 'quit' to close the CLI.")
fmt.Println("Type '.tables' to list all tables.")
scanner := bufio.NewScanner(os.Stdin) // Create a new scanner to read input from stdin.
// Start an infinite loop to continuously prompt for SQL commands.
for {
fmt.Print("SQL> ") // Prompt the user for input.
if !scanner.Scan() {
break // Break the loop if there's no more input (e.g., EOF).
}
command := strings.TrimSpace(scanner.Text()) // Read the line and trim leading/trailing whitespace.
lowerCommand := strings.ToLower(command)
// Check for exit commands.
if lowerCommand == "exit" || lowerCommand == "quit" {
fmt.Println("Exiting SQL CLI.")
break // Exit the loop and the function.
}
// Check for exit commands.
if lowerCommand == "exit" || lowerCommand == "quit" {
fmt.Println("Exiting SQL CLI.")
break // Exit the loop and the function.
}
if lowerCommand == ".tables" {
rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
if err != nil {
fmt.Printf("Error listing tables: %v\n", err)
continue
}
defer rows.Close()
fmt.Println("Tables:")
var tableName string
for rows.Next() {
if err := rows.Scan(&tableName); err != nil {
fmt.Printf("Error scanning table name: %v\n", err)
continue
}
fmt.Printf("- %s\n", tableName)
}
if err = rows.Err(); err != nil {
fmt.Printf("Error iterating table rows: %v\n", err)
}
continue // Continue to the next prompt after listing tables.
}
if command == "" {
continue // If the command is empty, just prompt again.
}
// Determine if the command is a SELECT query.
// This is a simple check; a more robust solution might parse the SQL.
if strings.HasPrefix(strings.ToLower(command), "select") {
// Execute SELECT queries.
rows, err := db.Query(command)
if err != nil {
fmt.Printf("Error executing query: %v\n", err)
continue // Continue to the next iteration of the loop.
}
defer rows.Close() // Ensure rows are closed after processing.
// Get column names from the query result.
columns, err := rows.Columns()
if err != nil {
fmt.Printf("Error getting columns: %v\n", err)
continue
}
// Prepare a slice to hold column values.
// Each element is an interface{} because we don't know the exact type beforehand.
values := make([]any, len(columns))
// Prepare a slice of pointers to interface{} for scanning.
// This allows Scan to write to the values slice.
scanArgs := make([]any, len(columns))
for i := range values {
scanArgs[i] = &values[i]
}
// Calculate maximum column widths for pretty printing.
colWidths := make(map[string]int)
for _, col := range columns {
colWidths[col] = len(col) // Initialize with column name length.
}
// Store all rows to calculate max widths before printing.
var allRows [][]string
for rows.Next() {
err = rows.Scan(scanArgs...) // Scan the row into the scanArgs (which point to values).
if err != nil {
fmt.Printf("Error scanning row: %v\n", err)
continue
}
rowValues := make([]string, len(columns))
for i, val := range values {
// Handle potential nil values from the database.
if val == nil {
rowValues[i] = "NULL"
} else {
rowValues[i] = fmt.Sprintf("%v", val) // Convert value to string.
}
// Update max width for the current column.
if len(rowValues[i]) > colWidths[columns[i]] {
colWidths[columns[i]] = len(rowValues[i])
}
}
allRows = append(allRows, rowValues)
}
// Print header.
for _, col := range columns {
fmt.Printf("%-*s ", colWidths[col], col) // Left-align column name.
}
fmt.Println()
// Print separator line.
for _, col := range columns {
fmt.Printf("%s ", strings.Repeat("-", colWidths[col])) // Print dashes for separator.
}
fmt.Println()
// Print data rows.
for _, row := range allRows {
for i, val := range row {
fmt.Printf("%-*s ", colWidths[columns[i]], val) // Left-align data.
}
fmt.Println()
}
if err = rows.Err(); err != nil {
fmt.Printf("Error iterating rows: %v\n", err)
}
} else {
// Execute DML (INSERT, UPDATE, DELETE) and DDL queries.
result, err := db.Exec(command)
if err != nil {
fmt.Printf("Error executing command: %v\n", err)
continue
}
// Print results for DML operations.
rowsAffected, err := result.RowsAffected()
if err != nil {
fmt.Printf("Error getting rows affected: %v\n", err)
} else {
fmt.Printf("%d row(s) affected.\n", rowsAffected)
}
}
if scanner.Err() != nil {
fmt.Printf("Error reading input: %v\n", scanner.Err())
break
}
}
}
func readFolderForHostFromDB(host string) (string, error) {
var folder string
query := "SELECT folder FROM sshprofiles WHERE host = ? AND folder IS NOT NULL"
row := db.QueryRow(query, host)
err := row.Scan(&folder)
if err == sql.ErrNoRows {
return "", fmt.Errorf("host not found in folder query: %s", host)
} else if err != nil {
return "", fmt.Errorf("read folder query failed: %w", err)
}
return folder, nil
}
func addConsoleConfig(profile ConsoleConfig) error {
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("failed to begin the db transaction for console profile update:%v", err)
}
stmt, err := tx.Prepare(`
INSERT INTO console_profiles(host,baud_rate,device,parity,stop_bit,data_bits,folder)
VALUES(?,?,?,?,?,?,?)
ON CONFLICT(host) DO UPDATE SET folder = excluded.folder,
baud_rate = excluded.baud_rate,
device = excluded.device,
parity = excluded.parity,
stop_bit = excluded.stop_bit,
data_bits = excluded.data_bits;
`)
if err != nil {
return fmt.Errorf("failed to prepare the db for console profile update:%v", err)
}
defer stmt.Close()
_, err = stmt.Exec(profile.Host, profile.BaudRate, profile.Device, profile.Parity, profile.StopBit, profile.DataBits, profile.Folder)
if err != nil {
return fmt.Errorf("failed to update the console profile for the host %v: %v", profile.Host, err)
}
return tx.Commit()
}
func removeConsoleConfig(h string) error {
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("failed to begin the db transaction for console profile deletion: %v", err)
}
stmt, err := tx.Prepare("DELETE FROM console_profiles WHERE host = ?;")
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(h)
if err != nil {
return err
}
fmt.Printf("Console profile for %s has been removed successfully.\n", h)
return tx.Commit()
}
func readAllConsoleProfiles() (ConsoleConfigs, error) {
var consoleProfiles ConsoleConfigs
rows, err := db.Query("SELECT host, baud_rate, device, parity, stop_bit, data_bits, folder FROM console_profiles")
if err != nil {
log.Println("Error querying console profiles:", err)
return consoleProfiles, err
}
defer rows.Close()
for rows.Next() {
var profile ConsoleConfig
if err := rows.Scan(&profile.Host, &profile.BaudRate, &profile.Device, &profile.Parity, &profile.StopBit, &profile.DataBits, &profile.Folder); err != nil {
log.Println("Error scanning console profile:", err)
continue
}
consoleProfiles = append(consoleProfiles, profile)
}
if err := rows.Err(); err != nil {
log.Println("Error reading console profiles:", err)
}
return consoleProfiles, nil
}
func doConfigBackup(mode string) {
if mode == "all" || mode == "config" {
configFilePath, err := setupFilesFolders()
if err != nil {
log.Println("failed to get the config file path")
}
backupConfigFilePath := configFilePath + "_backup"
srcConfigFile, err := os.Open(configFilePath)
if err != nil {
log.Println(err)
}
defer srcConfigFile.Close()
dstConfigFile, err := os.Create(backupConfigFilePath)
if err != nil {
log.Println(err)
}
defer dstConfigFile.Close()
_, err = io.Copy(dstConfigFile, srcConfigFile)
if err != nil {
log.Println(err)
}
}
if mode == "all" || mode == "db" {
homeDir, _ := os.UserHomeDir()
databaseFile := filepath.Join(homeDir, ".ssh", "sshcli.db")
backupDatabaseFile := databaseFile + "_backup"
srcDatabase, err := os.Open(databaseFile)
if err != nil {
log.Println(err)
}
defer srcDatabase.Close()
dstDatabse, err := os.Create(backupDatabaseFile)
if err != nil {
log.Println(err)
}
defer dstDatabse.Close()
_, err = io.Copy(dstDatabse, srcDatabase)
if err != nil {
log.Println(err)
}
}
}
func openBrowser(url string) error {
var err error = nil
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err
}
func checkShellCommands(c string) error {
if _, err := exec.LookPath(c); err != nil {
return fmt.Errorf("%v command is not available in the default system shell", c)
}
return nil
}
func getDefaultEditor() string {
editors := []string{"vim", "nvim", "vi", "nano"}
if runtime.GOOS == "windows" {
return "notepad"
} else {
for _, editor := range editors {
if _, err := exec.LookPath(editor); err == nil {
return editor
}
}
}
return "vi"
}
func runSudoCommand(pass, tool string) error {
cmd := exec.Command("sudo", tool)
cmd.Stdin = bytes.NewBufferString(pass)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return fmt.Errorf("command failed: %w", err)
}
return nil
}
func fixKeyPath(keyPath string) string {
if runtime.GOOS == "windows" {
if strings.Contains(keyPath, "/") && strings.Contains(keyPath, `\`) {
keyPath = strings.ReplaceAll(keyPath, "/", "")
} else if strings.Contains(keyPath, "/") {
keyPath = strings.ReplaceAll(keyPath, "/", `\`)
}
keyPath = strings.ReplaceAll(keyPath, "~", "%USERPROFILE%")
} else {
if strings.HasPrefix(keyPath, "~") {
homeDir, _ := os.UserHomeDir()
keyPath = strings.ReplaceAll(keyPath, "~", homeDir)
}
if strings.Contains(keyPath, "/") && strings.Contains(keyPath, `\`) {
keyPath = strings.ReplaceAll(keyPath, `\`, "")
} else if strings.Contains(keyPath, `\`) {
keyPath = strings.ReplaceAll(keyPath, `\`, `/`)
}
}
keyPath = filepath.Clean(keyPath)
if runtime.GOOS == "windows" {
for _, env := range os.Environ() {
parts := strings.SplitN(env, "=", 2)
if len(parts) != 2 {
continue
}
name, value := parts[0], parts[1]
keyPath = strings.ReplaceAll(keyPath, "%"+name+"%", value)
}
}
return keyPath
}
// func timer(name string) func() {
// start := time.Now()
// return func() {
// fmt.Printf("%s took %v\n", name, time.Since(start))
// }
// }
func cleanTheString(s, mode string) string {
// remove colors
s = strings.ReplaceAll(s, magenta, "")
s = strings.ReplaceAll(s, green, "")
s = strings.ReplaceAll(s, red, "")
s = strings.ReplaceAll(s, yellow, "")
s = strings.ReplaceAll(s, reset, "")
s = strings.ReplaceAll(s, BOLD, "")
if strings.ToLower(mode) == "keyboard" {
s = s[4:]
}
// remove icons
if strings.ToLower(mode) == "all" {
s = strings.TrimPrefix(s, sshIcon+" ")
s = strings.TrimPrefix(s, consoleIcon+" ")
s = strings.TrimPrefix(s, folderIcon+" ")
}
// remove spaces
s = strings.TrimSpace(s)
return s
}
func SetNullValue(hostname, column string) error {
q := fmt.Sprintf("UPDATE sshprofiles SET '%s' = ? WHERE host = '%s'", column, hostname)
_, err := db.Exec(q, nil)
return err
}
func cleanupDatabase() error {
allHosts, err := getHosts()
if err != nil {
return err
}
allHosts.removeItemFromStruct("*")
placeholders := make([]string, len(*allHosts))
args := make([]any, len(*allHosts))
for i, v := range *allHosts {
placeholders[i] = "?"
args[i] = v.Host
}
querySelection := fmt.Sprintf("SELECT host FROM sshprofiles WHERE host NOT IN (%s)", strings.Join(placeholders, ","))
rows, err := db.Query(querySelection, args...)
if err != nil {
return err
}
defer rows.Close()
var targets []string
for rows.Next() {
var h string
if err := rows.Scan(&h); err == nil {
fmt.Printf(" - %s\n", h)
targets = append(targets, h)
}
}
if len(targets) == 0 {
fmt.Println("All records are already in order!")
return nil
}
fmt.Printf("\nAre you sure you want to delete these %d records from ~/.ssh/sshcli.db file? (y/N): ", len(targets))
var response string
fmt.Scanln(&response)
if strings.ToLower(response) != "y" {
fmt.Println("Cleanup aborted.")
return nil
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
queryDelete := fmt.Sprintf("DELETE FROM sshprofiles WHERE host NOT IN (%s)", strings.Join(placeholders, ","))
result, err := tx.Exec(queryDelete, args...)
if err != nil {
return err
}
rowsDeleted, _ := result.RowsAffected()
fmt.Printf("Successfully deleted %d rows.\n", rowsDeleted)
return tx.Commit()
}
func processCliArgs() (ConsoleConfig, *string) {
host := flag.String("host", "", "Host alias")
action := flag.String("action", "", "Action to perform: add, remove")
BaudRate := flag.String("baudrate", "9600", "BaudRate, default is 9600")
DataBits := flag.String("data_bits", "8", "databits, default is 8")
StopBit := flag.String("stop_bit", "1", "stop bit, default is 1")
Parity := flag.String("parity", "none", "parity, default is none")
device := flag.String("device", "/dev/tty.usbserial-1140", "device path, default is /dev/tty.usbserial-1140")
version := flag.Bool("version", false, "prints the compile time (version)")
sanitizeDB := flag.Bool("cleanup", false, "delete sqlite records that are not in the ssh config file")
secure := flag.Bool("secure", false, "Masks the sensitive data")
sql := flag.Bool("sql", false, "Direct access to the sshcli.db file to run sql queries")
flag.Parse()
if *version {
fmt.Println(CompileTime[1:])
os.Exit(0)
}
if *sanitizeDB {
var err error
configPath, err = setupFilesFolders()
if err != nil {
log.Fatalln(err.Error())
}
doConfigBackup("all")
if err := cleanupDatabase(); err != nil {
fmt.Println(err)
}
os.Exit(0)
}
if *sql {
OpenSqlCli()
db.Close()
os.Exit(0)
}
if *secure {
isSecure = true
}
var consoleProfile ConsoleConfig
consoleProfile = ConsoleConfig{
Host: *host,
BaudRate: *BaudRate,
Device: *device,
Parity: *Parity,
StopBit: *StopBit,
DataBits: *DataBits,
}
return consoleProfile, action
}
func customPanicHandler() {
if r := recover(); r != nil {
stack := debug.Stack()
lines := bytes.Split(stack, []byte("\n"))
for i, line := range lines {
if idx := bytes.LastIndex(line, []byte("/go/")); idx != -1 {
lines[i] = line[idx+4:]
} else if idx := bytes.Index(line, []byte(":")); idx != -1 {
lines[i] = line[idx:]
}
}
sanitizedStack := bytes.Join(lines, []byte("\n"))
fmt.Printf("Panic: %v\n%s", r, sanitizedStack)
os.Exit(1)
}
}
func handleExitSignal(err error) {
if strings.EqualFold(strings.TrimSpace(err.Error()), "^C") {
} else {
fmt.Printf("Prompt failed %v\n", err)
}
}
func createFile(filePath string) error {
file, err := os.Create(filePath)
if err != nil {
fmt.Println("Error creating file:", err)
return err
}
defer file.Close()
fmt.Printf(" [>] %sThe %v file has been created successfully\n%s", green, filePath, reset)
return nil
}
func setupFilesFolders() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get user home directory: %w", err)
}
p := filepath.Join(homeDir, ".ssh", "config")
if _, err := os.Stat(p); err != nil {
if err := createFile(p); err != nil {
fmt.Printf("%sfailed to create/access the config file : %v%s", red, p, reset)
return "", fmt.Errorf("failed to create/access the config file: %w", err)
}
file, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Println(err)
return "", fmt.Errorf("Failed to read the config file: %w", err)
}
defer file.Close()
writer := bufio.NewWriter(file)
defaultHosts := AllConfigs{
SSHConfig{
Host: "vm1",
HostName: "172.16.0.1",
User: "root",
Port: "22",
IdentityFile: filepath.Join(homeDir, ".ssh", "id_rsa"),
}}
textBlock := defaultHosts.constructConfigContent()
for _, line := range textBlock {
fmt.Fprintln(writer, line)
}
if err := writer.Flush(); err != nil {
return "", fmt.Errorf("failed to write SSH config file: %w", err)
}
}
return p, nil
}
func (s *AllConfigs) removeItemFromStruct(hostToRemove string) {
for i, c := range *s {
if c.Host == hostToRemove {
*s = append((*s)[:i], (*s)[i+1:]...)
return
}
}
}
func (s *AllConfigs) AddSocksToProfile(hostName string) error {
var socksPort string
fmt.Print("Enter Socks5 port # (eg. 1080) or press enter to assign automatically: ")
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
socksPort = scanner.Text()
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Error reading the socks port from stdin:", err)
}
if len(socksPort) == 0 {
//read https_proxy value and use use it
p, err := findAvailablePort()
if err != nil {
return err
}
socksPort = strconv.Itoa(p)
} else {
p, err := strconv.Atoi(socksPort)
if err != nil {
return fmt.Errorf("wrong port number: %s", socksPort)
}
if p < 0 || p > 65535 {
return fmt.Errorf("port number out of range: %s", socksPort)
}
}
if h := s.extractHost(hostName); h != nil {
h.DynamicSocks = append(h.DynamicSocks, "DynamicForward "+socksPort)
if err := s.pushConfigToFile(); err != nil {
return fmt.Errorf("error adding/updating profile: %w", err)
}
return nil
} else {
return fmt.Errorf("error extracting host: %s", hostName)
}
}
func (s *AllConfigs) constructConfigContent() []string {
configLines := []string{}
for _, c := range *s {
configLines = append(configLines, "Host "+c.Host)
if len(c.HostName) != 0 {
configLines = append(configLines, " HostName "+c.HostName)
}
if len(c.User) != 0 {
configLines = append(configLines, " User "+c.User)
}
if len(c.Port) != 0 {
configLines = append(configLines, " Port "+c.Port)
}
if len(c.IdentityFile) != 0 {
configLines = append(configLines, " IdentityFile "+c.IdentityFile)
}
if len(c.Proxy) != 0 {
configLines = append(configLines, " ProxyCommand "+c.Proxy)
}
if len(c.Sockets) != 0 {
for _, socket := range c.Sockets {
configLines = append(configLines, " "+socket)
}
}
if len(c.DynamicSocks) != 0 {
for _, s := range c.DynamicSocks {
configLines = append(configLines, " "+s)
}
}
if len(c.OtherAttribs) != 0 {
for _, o := range c.OtherAttribs {
configLines = append(configLines, " "+o)
}
}
configLines = append(configLines, "")
}
return configLines
}
func (s *AllConfigs) pushConfigToFile() error {
for _, newC := range *s {
if strings.Contains(newC.Host, " ") {
log.Printf("can't use whitespace in ssh profile name: %s", newC.Host)
os.Exit(1)
}
}
file, err := os.OpenFile(configPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return fmt.Errorf("failed to create SSH config file: %w", err)
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, line := range s.constructConfigContent() {
fmt.Fprintln(writer, line)
}
if err := writer.Flush(); err != nil {
return fmt.Errorf("failed to write SSH config file: %w", err)
}
return nil
}
func getHosts() (*AllConfigs, error) {
allHosts := &AllConfigs{}
var currentHost *SSHConfig
file, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("Failed to read the config file: %w", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if value, ok := strings.CutPrefix(line, "Host "); ok {
if strings.Contains(value, " ") {
continue
}
host := value
// This means the host was already filled with content and now we are at the new host line
if currentHost != nil {
*allHosts = append(*allHosts, *currentHost)
}
// So we Generate a new host
currentHost = &SSHConfig{Host: host}
if fName, err := readFolderForHostFromDB(host); err == nil && fName != "NULL" && fName != "" {
currentHost.Folder = fName
}
} else if currentHost != nil {
if value, ok := strings.CutPrefix(line, "HostName "); ok {
currentHost.HostName = value
} else if value, ok := strings.CutPrefix(line, "User "); ok {
currentHost.User = value
} else if value, ok := strings.CutPrefix(line, "Port "); ok {
currentHost.Port = value
} else if value, ok := strings.CutPrefix(line, "ProxyCommand "); ok {
currentHost.Proxy = value
} else if value, ok := strings.CutPrefix(line, "IdentityFile "); ok {
currentHost.IdentityFile = value
} else if strings.Contains(line, "RemoteForward ") || strings.Contains(line, "LocalForward ") {
currentHost.Sockets = append(currentHost.Sockets, line)
} else if strings.Contains(line, "DynamicForward ") {
currentHost.DynamicSocks = append(currentHost.DynamicSocks, line)
} else {
if len(strings.TrimSpace(line)) > 0 {
currentHost.OtherAttribs = append(currentHost.OtherAttribs, value)
}
}
}
}
if currentHost != nil {
*allHosts = append(*allHosts, *currentHost)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("getHosts Scanner error: %w", err)
}
sort.Slice(*allHosts, func(i, j int) bool {
return (*allHosts)[i].Host < (*allHosts)[j].Host
})
return allHosts, nil
}
func (s *AllConfigs) getFolderList() (map[string]string, error) {
folderhost := map[string]string{}
query := "SELECT host,folder FROM sshprofiles WHERE folder IS NOT NULL;"
rows, err := db.Query(query)
if err != nil {
return folderhost, fmt.Errorf("error querying folders: %w", err)
}
defer rows.Close()
for rows.Next() {
var folder string
var host string
if err := rows.Scan(&host, &folder); err != nil {
log.Println("Error scanning folder:", err)
continue
}