-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1463 lines (1235 loc) · 43.8 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
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"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type IPAndMAC struct {
IP string
MAC string
}
type Device struct {
Hostname string
IP string
}
// get a cookie from a header
func getCookie(header http.Header, key string) string {
for _, values := range header {
for _, v := range values {
if strings.HasPrefix(v, key+"=") {
cookieData := strings.TrimSpace(strings.TrimPrefix(v, key+"="))
semicolonIndex := strings.Index(cookieData, ";")
if semicolonIndex == -1 { // No semicolon found, return the whole string
return cookieData
}
return cookieData[:semicolonIndex] // Return the substring before the first semicolon
}
}
}
return ""
}
// get the auth token
func getToken(PHPSESSID string, serverIP string) (string, string, error) {
url := "http://" + serverIP + "/admin/index.php"
method := "GET"
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return "", "", err
}
req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
req.Header.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Add("Cache-Control", "max-age=0")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Cookie", "PHPSESSID="+PHPSESSID)
req.Header.Add("DNT", "1")
req.Header.Add("Referer", "http://"+serverIP+"/admin/login.php")
req.Header.Add("Upgrade-Insecure-Requests", "1")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return "", "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return "", "", err
}
bodyStr := string(body)
// Find the start index of the token div
tokenStart := strings.Index(bodyStr, "<div id=\"token\" hidden>")
if tokenStart == -1 {
return "", "", errors.New("token not found in body")
}
// Correct the start index to the beginning of the actual token
tokenStartCorrected := tokenStart + len("<div id=\"token\" hidden>")
// Find the end index of the token div
tokenEnd := strings.Index(bodyStr[tokenStartCorrected:], "</div>")
if tokenEnd == -1 {
return "", "", errors.New("token not found in body")
}
// Correct the token end index relative to the entire body
tokenEndCorrected := tokenStartCorrected + tokenEnd
// Extract the token
token := bodyStr[tokenStartCorrected:tokenEndCorrected]
// get the updated PHPSESSID cookie
newPHPSESSID := getCookie(res.Header, "PHPSESSID")
if newPHPSESSID == "" {
return "", "", errors.New("PHPSESSID not found in response")
}
return token, newPHPSESSID, nil
}
func authenticate(serverIP string, password string) (string, string, error) {
url := "http://" + serverIP + "/admin/login.php"
method := "POST"
payload := strings.NewReader("pw=" + password)
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// don't follow redirects
return http.ErrUseLastResponse
},
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return "", "", err
}
req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
req.Header.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Add("Cache-Control", "max-age=0")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("DNT", "1")
req.Header.Add("Origin", "http://"+serverIP)
req.Header.Add("Referer", "http://"+serverIP+"/admin/login.php")
req.Header.Add("Upgrade-Insecure-Requests", "1")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return "", "", err
}
defer res.Body.Close()
// get the PHPSESSID cookie
PHPSESSID := getCookie(res.Header, "PHPSESSID")
if PHPSESSID == "" {
return "", "", errors.New("PHPSESSID not found in response")
}
token, newPHPSESSID, err := getToken(PHPSESSID, serverIP)
if err != nil {
fmt.Println(err)
return "", "", err
}
return newPHPSESSID, token, nil
}
func createClient(serverIP string, clientIP string, fileComment string, PHPSESSID string, token string) error {
url := "http://" + serverIP + "/admin/scripts/pi-hole/php/groups.php"
method := "POST"
// add the params using string interpolation
payload := strings.NewReader(`action=add_client&ip=` + clientIP + `&comment=` + fileComment + `&token=` + token)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return errors.New("failed to create request")
}
req.Header.Add("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Add("Cookie", "PHPSESSID="+PHPSESSID+"; PHPSESSID="+PHPSESSID)
req.Header.Add("DNT", "1")
req.Header.Add("Origin", "http://"+serverIP)
req.Header.Add("Referer", "http://"+serverIP+"/admin/groups-clients.php")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
req.Header.Add("X-Requested-With", "XMLHttpRequest")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return errors.New("failed to send request")
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return errors.New("failed to read response")
}
// {"success":true,"message":null}
// if response contains text Wrong token! Please re-login on the Pi-hole dashboard.
if strings.Contains(string(body), "Wrong token! Please re-login on the Pi-hole dashboard.") {
return errors.New("token error, try again")
}
// convert body to json
var jsonResponse map[string]interface{}
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
fmt.Println(err)
return errors.New("failed to parse response")
}
success := jsonResponse["success"].(bool)
if !success {
// if the message contains 'UNIQUE constraint failed: client.ip' then the client already exists
if strings.Contains(string(body), "UNIQUE constraint failed: client.ip") {
fmt.Println("Client already exists")
///// TODO: RENAME things. This is a mess
///// COMMENT is the one from pihole
///// DESCRIPTION is the one from the file
// ip is already added - check if the description (piholeComment) is the same with findClientID
clientID, groups, piholeComment, err := findClientID(fileComment, clientIP, serverIP, PHPSESSID, token)
if err != nil {
fmt.Println(err)
return err
}
if piholeComment != fileComment {
// hostname/comment/description is different - update
fmt.Println("Hostname/comment/description is different - updating client ID", clientID)
err = updateClient(clientID, groups, fileComment, serverIP, PHPSESSID, token)
if err != nil {
fmt.Println(err)
return err
}
// comment was updated - return success
return nil
} else {
// hostname/comment/description is the same - return success
return nil
}
}
// unknown error
fmt.Println("failed to add client")
fmt.Println(jsonResponse["message"])
return errors.New("failed to add client")
}
fmt.Println("client added!")
return nil
}
// Edit a client - all values must be passed, even if they are the same
func updateClient(clientID string, groups []int, comment string, serverIP string, PHPSESSID string, token string) error {
apiURL := "http://" + serverIP + "/admin/scripts/pi-hole/php/groups.php"
method := "POST"
var payload strings.Builder
// Start by writing the initial part of the payload
payload.WriteString(`action=edit_client&id=` + clientID + `&token=` + token + `&comment=` + comment)
// For each group, add a &groups[]= parameter
for _, group := range groups {
payload.WriteString("&groups%5B%5D=" + strconv.Itoa(group))
}
finalPayload := payload.String()
reader := strings.NewReader(finalPayload)
// for each group, add a &groups[]= parameter
for _, group := range groups {
payload.WriteString("&groups%5B%5D=" + strconv.Itoa(group))
}
client := &http.Client{}
req, err := http.NewRequest(method, apiURL, reader)
if err != nil {
fmt.Println(err)
return err
}
req.Header.Add("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Add("Cookie", "PHPSESSID="+PHPSESSID+"; PHPSESSID="+PHPSESSID)
req.Header.Add("DNT", "1")
req.Header.Add("Origin", "http://"+serverIP)
req.Header.Add("Referer", "http://"+serverIP+"/admin/groups-clients.php")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
req.Header.Add("X-Requested-With", "XMLHttpRequest")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return err
}
// body is json - check for success/error
var jsonResponse map[string]interface{}
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
fmt.Println(err)
return err
}
success := jsonResponse["success"].(bool)
if !success {
fmt.Println("failed to update client")
fmt.Println(jsonResponse["message"])
return errors.New("failed to update client")
}
fmt.Println("client updated!")
return nil
}
func parseStaticHosts(filePath string) ([]Device, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open file: %v", err)
}
defer file.Close()
var devices []Device
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "host") && strings.HasSuffix(line, "}") {
fields := strings.Fields(line)
if len(fields) < 6 {
continue
}
hostname := strings.Trim(fields[1], "{ ")
ip := ""
for i := 0; i < len(fields); i++ {
if fields[i] == "fixed-address" && i+1 < len(fields) {
ip = strings.Trim(fields[i+1], ";")
break
}
}
if hostname != "" && ip != "" {
devices = append(devices, Device{Hostname: hostname, IP: ip})
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read file: %v", err)
}
return devices, nil
}
// dhcpd.conf categories for lease ranges
// returns an map of category name to [startIP, endIP]
func findDHCPCategories(filePath string) (map[string][2]int, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open DHCP config file: %w", err)
}
defer file.Close()
categories := make(map[string][2]int)
scanner := bufio.NewScanner(file)
digitRegex := regexp.MustCompile(`\d+`) // Regular expression to extract digits
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "##") && strings.Contains(line, "-") {
line = strings.Trim(line, "# ") // Trim spaces and # from both ends
parts := strings.SplitN(line, ":", 2) // Split only into two parts
if len(parts) == 2 {
categoryName := strings.TrimSpace(parts[0])
rangeStr := strings.TrimSpace(parts[1])
rangeParts := strings.Fields(rangeStr) // Split by whitespace and get range
if len(rangeParts) >= 2 {
// Extract only digits from each part using regex
startStr := digitRegex.FindString(rangeParts[0])
endStr := digitRegex.FindString(rangeParts[len(rangeParts)-1])
startIP, errStart := strconv.Atoi(startStr)
endIP, errEnd := strconv.Atoi(endStr)
if errStart == nil && errEnd == nil {
categories[categoryName] = [2]int{startIP, endIP} // Add the category to the map
}
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read DHCP config file: %w", err)
}
return categories, nil
}
func createStaticHost(hostname, currentIP, dhcpdConfPath, leasesPath, category string) error {
fmt.Println("Creating static host entry for", hostname, "with current IP", currentIP)
categories, err := findDHCPCategories(dhcpdConfPath)
if err != nil {
return err
}
range_, exists := categories[category]
if !exists {
return fmt.Errorf("category '%s' not found", category)
}
nextIP, err := findNextAvailableIP(range_[0], range_[1], dhcpdConfPath)
if err != nil {
return err
}
fmt.Println("Next available IP for", category, ":", nextIP)
// find the MAC address of device with current IP
macAddress, err := findMacAddress(currentIP, leasesPath)
if err != nil {
return fmt.Errorf("failed to find MAC address: %v", err)
}
// check if the host or MAC address already exists in the DHCP config file
exists, checkErr := checkIfHostExists(hostname, macAddress, dhcpdConfPath)
if checkErr != nil {
return fmt.Errorf("failed to check if host or MAC address exists: %v", err)
}
if exists {
return fmt.Errorf("host or MAC address already exists in DHCP config file")
}
addErr := addHostToCategory(hostname, macAddress, nextIP, category, dhcpdConfPath)
if addErr != nil {
return addErr
}
// remove the lease
removeErr := removeLease(macAddress, currentIP, leasesPath)
if removeErr != nil {
return removeErr
}
return nil
}
func removeLease(mac, ip, leasesPath string) error {
fmt.Println("Removing lease for", mac, ip)
// Open the original file for reading
file, err := os.Open(leasesPath)
if err != nil {
return fmt.Errorf("failed to open leases file: %v", err)
}
defer file.Close()
var buffer bytes.Buffer
var leaseBuffer bytes.Buffer
var inLeaseBlock bool
scanner := bufio.NewScanner(file)
// Scan each line in the file
for scanner.Scan() {
line := scanner.Text()
// Detect start of a lease block
if strings.HasPrefix(line, "lease") {
inLeaseBlock = true
leaseBuffer.WriteString(line + "\n")
continue
}
if inLeaseBlock {
leaseBuffer.WriteString(line + "\n") // Continue capturing the lease block
// Check if the end of a lease block
if strings.TrimSpace(line) == "}" {
if strings.Contains(leaseBuffer.String(), mac) || strings.Contains(leaseBuffer.String(), ip) {
fmt.Println("Found and deleting lease entry for", mac, ip)
// Clear leaseBuffer to not write this block back, effectively deleting it
leaseBuffer.Reset()
} else {
buffer.Write(leaseBuffer.Bytes()) // Write back non-matching lease block
}
inLeaseBlock = false // Reset the flag after processing a lease block
leaseBuffer.Reset() // Clear the lease buffer after processing it
}
} else {
buffer.WriteString(line + "\n") // Write lines outside of lease blocks directly to the main buffer
}
}
// Check for scanning errors
if err := scanner.Err(); err != nil {
return fmt.Errorf("error reading leases file: %v", err)
}
// Open the file for writing to overwrite with new data
err = os.WriteFile(leasesPath, buffer.Bytes(), 0644)
if err != nil {
return fmt.Errorf("failed to write to leases file: %v", err)
}
return nil
}
// check if the host or MAC address already exists in the DHCP config file
func checkIfHostExists(hostname, macAddress, dhcpdConfPath string) (bool, error) {
// Open the DHCP configuration file
file, err := os.Open(dhcpdConfPath)
if err != nil {
return false, fmt.Errorf("failed to open DHCP config file: %v", err)
}
defer file.Close()
// Create a scanner to read through the file line by line
scanner := bufio.NewScanner(file)
// Scan each line in the file
for scanner.Scan() {
line := scanner.Text()
// Look for lines that start with "host" which indicate a host entry
if strings.HasPrefix(line, "host") {
// Check if the current line contains the hostname or MAC address
if strings.Contains(line, hostname) || strings.Contains(line, macAddress) {
return true, nil
}
}
}
// Check for scanning errors
if err := scanner.Err(); err != nil {
return false, fmt.Errorf("error reading from DHCP config file: %v", err)
}
// If no match is found and no error occurred, return false
return false, nil
}
// find where to add the new host entry
func addHostToCategory(hostname, macAddress string, nextIP int, category, filePath string) error {
// Open the original file for reading
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open DHCP config file: %v", err)
}
defer file.Close()
var buffer bytes.Buffer
scanner := bufio.NewScanner(file)
inCategory := false
lastHostWritten := false
appendHere := false
// Iterate through the file to find the appropriate category
for scanner.Scan() {
line := scanner.Text()
// Detect the start of the desired category
if strings.Contains(line, fmt.Sprintf("## %s", category)) {
inCategory = true
buffer.WriteString(line + "\n")
continue
}
// Detect the start of a new category while in the desired category
if inCategory && strings.HasPrefix(line, "##") {
appendHere = true // Mark that the new host should be appended just before this line
}
// If within the category and no new category has started
if inCategory && !appendHere {
buffer.WriteString(line + "\n")
// If line starts with "host" keep track of it
if strings.HasPrefix(line, "host") {
lastHostWritten = true
}
} else if appendHere && lastHostWritten {
// Insert new host entry here as we are at the end of the category
newHostEntry := fmt.Sprintf("host %s { hardware ethernet %s; fixed-address 10.45.1.%d; }\n", hostname, macAddress, nextIP)
buffer.WriteString(newHostEntry)
buffer.WriteString(line + "\n")
appendHere = false
inCategory = false
lastHostWritten = false // Reset after inserting
} else {
// Write other lines normally
buffer.WriteString(line + "\n")
}
}
// If the category is the last one and no new category was detected after, append the new host at the end
if inCategory && lastHostWritten && !appendHere {
newHostEntry := fmt.Sprintf("host %s { hardware ethernet %s; fixed-address 10.45.1.%d; }\n", hostname, macAddress, nextIP)
buffer.WriteString(newHostEntry)
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error while reading DHCP config file: %v", err)
}
// Write the updated content back to the file
if err := os.WriteFile(filePath, buffer.Bytes(), 0644); err != nil {
return fmt.Errorf("failed to write updated DHCP config file: %v", err)
}
return nil
}
func findNextAvailableIP(startIP, endIP int, dhcpdConfPath string) (int, error) {
usedIPs := make(map[int]bool)
file, err := os.Open(dhcpdConfPath)
if err != nil {
return 0, fmt.Errorf("failed to open DHCP config file: %v", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "host") {
parts := strings.Fields(line)
// Loop through parts to find the fixed-address entry
for i, part := range parts {
if part == "fixed-address" && i+1 < len(parts) {
ipStr := strings.TrimSuffix(parts[i+1], ";")
if ip, err := strconv.Atoi(strings.Split(ipStr, ".")[3]); err == nil {
usedIPs[ip] = true
}
}
}
}
}
for ip := startIP; ip <= endIP; ip++ {
if !usedIPs[ip] {
return ip, nil
}
}
return 0, fmt.Errorf("no available IPs in the range from %d to %d", startIP, endIP)
}
func findMacAddress(ip, leasesPath string) (string, error) {
file, err := os.Open(leasesPath)
if err != nil {
return "", fmt.Errorf("failed to open leases file: %v", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var foundIP bool
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, fmt.Sprintf("lease %s {", ip)) {
foundIP = true
}
if foundIP && strings.Contains(line, "hardware ethernet") {
parts := strings.Fields(line)
if len(parts) >= 3 {
return strings.Trim(parts[2], ";"), nil
}
}
if foundIP && strings.Contains(line, "}") {
break
}
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("failed to read leases file: %v", err)
}
return "", fmt.Errorf("MAC address not found for IP %s", ip)
}
func findAllIPsInLeasesFile(filePath string) ([]IPAndMAC, error) {
// Open the file
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open leases file: %v", err)
}
defer file.Close()
var entries []IPAndMAC
scanner := bufio.NewScanner(file)
// Read file line by line
for scanner.Scan() {
line := scanner.Text()
// Check if the line starts with 'lease' to identify the beginning of a lease block
if strings.HasPrefix(line, "lease") {
fields := strings.Fields(line)
if len(fields) >= 2 {
ip := fields[1] // The second element should be the IP address
// Continue scanning until 'hardware ethernet' is found
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, " hardware ethernet") {
fields = strings.Fields(line)
if len(fields) >= 3 {
mac := strings.TrimSuffix(fields[2], ";")
entries = append(entries, IPAndMAC{IP: ip, MAC: mac})
break
}
}
}
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading leases file: %v", err)
}
// Sort the slice of IPAndMAC structs
sort.Slice(entries, func(i, j int) bool {
ipA, ipB := net.ParseIP(entries[i].IP), net.ParseIP(entries[j].IP)
if ipA == nil || ipB == nil {
return false // Handle parsing errors
}
ipA4, ipB4 := ipA.To4(), ipB.To4()
if ipA4 != nil && ipB4 != nil {
return bytes.Compare(ipA4, ipB4) < 0
}
return false // Handle non-IPv4 cases
})
return entries, nil
}
// returns the server IP, PHPSESSID, and token
// clientSync - just get auth, or sync with DHCP
func sync(dhcpdConfPath, serverIP string, clientSync bool) (string, string, string, error) {
// Get the password from a file
passwordFile, err := os.Open("pihole-password.txt")
if err != nil {
log.Panic(err) // Proper error handling in case the file cannot be opened
}
defer passwordFile.Close() // Ensure that file.Close() is called at the end of the function
passwordScanner := bufio.NewScanner(passwordFile)
var password string
if passwordScanner.Scan() {
password = strings.TrimSpace(passwordScanner.Text())
}
if err := passwordScanner.Err(); err != nil {
log.Panicf("Failed to read password: %v", err)
}
PHPSESSID, token, err := authenticate(serverIP, password)
if err != nil {
fmt.Println(err)
return "", "", "", err
}
if !clientSync {
fmt.Println("not syncing with DHCP")
return serverIP, PHPSESSID, token, nil
}
fmt.Println("syncing with DHCP")
devices, err := parseStaticHosts(dhcpdConfPath)
if err != nil {
fmt.Println("Error:", err)
return "", "", "", err
}
for _, device := range devices {
fmt.Printf("Adding %s with IP %s\n", device.Hostname, device.IP)
// add a client
maxRetries := 5
retryCount := 0
for retryCount < maxRetries {
err := createClient(serverIP, device.IP, device.Hostname, PHPSESSID, token)
if err != nil {
if err.Error() == "token error, try again" {
fmt.Println("Retry due to token error:", retryCount+1)
retryCount++
// wait for a second * retryCount
time.Sleep(time.Duration(retryCount) * time.Second)
// reauthenticate
PHPSESSID, token, err = authenticate(serverIP, password)
if err != nil {
fmt.Println("Error:", err)
break
}
continue
} else {
fmt.Println("Error:", err)
break
}
}
fmt.Println("Success on attempt", retryCount+1)
break
}
if retryCount == maxRetries {
fmt.Println("Failed after", maxRetries, "attempts")
}
}
return serverIP, PHPSESSID, token, nil
}
// Find a Pi-hole client ID by hostname and IP address
func findClientID(hostname string, ip string, serverIP string, PHPSESSID string, token string) (string, []int, string, error) {
url := "http://" + serverIP + "/admin/scripts/pi-hole/php/groups.php"
method := "POST"
payload := strings.NewReader(`action=get_clients&token=` + token)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return "", nil, "", err
}
req.Header.Add("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Add("Cookie", "PHPSESSID="+PHPSESSID)
req.Header.Add("DNT", "1")
req.Header.Add("Origin", "http://"+serverIP)
req.Header.Add("Referer", "http://"+serverIP+"/admin/groups-clients.php")
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
req.Header.Add("X-Requested-With", "XMLHttpRequest")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return "", nil, "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return "", nil, "", err
}
// body is json - clients under data
var jsonResponse map[string]interface{}
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
fmt.Println(err)
return "", nil, "", errors.New("failed to parse response")
}
if data, ok := jsonResponse["data"].([]interface{}); ok {
for _, client := range data {
clientMap, ok := client.(map[string]interface{})
if !ok {
fmt.Println("Error parsing client data")
continue
}
// Convert id to string safely
clientID := fmt.Sprintf("%v", clientMap["id"]) // Using fmt.Sprintf to handle integer ID
clientComment := ""
if comment, ok := clientMap["comment"].(string); ok {
clientComment = comment
}
clientIP := ""
if ip, ok := clientMap["ip"].(string); ok {
clientIP = ip
}
// get the groups the client is in
groups := clientMap["groups"].([]interface{})
var groupIDs []int
for _, group := range groups {
groupStr := fmt.Sprintf("%v", group) // Convert group to string if not already
groupID, err := strconv.Atoi(groupStr) // Convert string to int
if err != nil {
log.Printf("Error converting group ID to integer: %s", err)
continue // Skip this group if conversion fails
}
groupIDs = append(groupIDs, groupID) // Append the converted integer
}
// find the client by hostname and IP address
if hostname == clientComment && ip == clientIP {
return clientID, groupIDs, clientComment, nil
} // fallback - compare just the hostname
if hostname == clientComment {
return clientID, groupIDs, clientComment, nil
} // fallback - compare just the IP address
if ip == clientIP {
return clientID, groupIDs, clientComment, nil
}
}
} else {
fmt.Println("Error: data field is not an array")
return "", nil, "", errors.New("data field is not an array")
}
return "", nil, "", nil
}
// Toggle the groups of a client, blocking or unblocking
func toggleBlock(hostname string, ip string, serverIP string, PHPSESSID string, token string) error {
fmt.Println("!!!!!!! Toggling block for", hostname, ip)
// find the client by hostname and IP address
clientID, currentGroups, comment, err := findClientID(hostname, ip, serverIP, PHPSESSID, token)
if err != nil {
fmt.Println(err)
return err
}
fmt.Println("Found Client ID:", clientID)
// Determine if the client is in group 0 or 1 and toggle accordingly
var newGroups []int
inGroup0 := false
inGroup1 := false
// Check if the client is in group 0 or 1 and prepare new list excluding 0 and 1
for _, group := range currentGroups {
if group == 0 {
inGroup0 = true
} else if group == 1 {
inGroup1 = true
} else {
newGroups = append(newGroups, group)
}
}
// Toggle the group
if inGroup0 {
fmt.Println("Switching from group 0 to group 1")
newGroups = append(newGroups, 1)
} else if inGroup1 {
fmt.Println("Switching from group 1 to group 0")
newGroups = append(newGroups, 0)
}
// If neither group 0 nor 1 was found, decide on the default behavior
if !inGroup0 && !inGroup1 {
fmt.Println("Client is not in group 0 or 1, adding to group 0 by default")
newGroups = append(newGroups, 0)
}
fmt.Println("New groups:", newGroups)
// Update the client with the new group settings
return updateClient(clientID, newGroups, comment, serverIP, PHPSESSID, token)
}
func main() {
dhcpdConfPath := "dhcpd.conf"
dhcpdLeasesPath := "dhcpd.leases"
var serverIP, PHPSESSID, token string
var err error
serverIP = "10.45.1.2"
// sync once to get the initial values
serverIP, _, _, err = sync(dhcpdConfPath, serverIP, true)
if err != nil {
fmt.Println(err)
return
}