dns.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package logic
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "sort"
  8. validator "github.com/go-playground/validator/v10"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/txn2/txeh"
  13. )
  14. // SetDNS - sets the dns on file
  15. func SetDNS() error {
  16. hostfile, err := txeh.NewHosts(&txeh.HostsConfig{})
  17. if err != nil {
  18. return err
  19. }
  20. var corefilestring string
  21. networks, err := GetNetworks()
  22. if err != nil && !database.IsEmptyRecord(err) {
  23. return err
  24. }
  25. for _, net := range networks {
  26. corefilestring = corefilestring + net.NetID + " "
  27. dns, err := GetDNS(net.NetID)
  28. if err != nil && !database.IsEmptyRecord(err) {
  29. return err
  30. }
  31. for _, entry := range dns {
  32. hostfile.AddHost(entry.Address, entry.Name)
  33. }
  34. }
  35. dns := GetExtclientDNS()
  36. for _, entry := range dns {
  37. hostfile.AddHost(entry.Address, entry.Name)
  38. }
  39. if corefilestring == "" {
  40. corefilestring = "example.com"
  41. }
  42. err = hostfile.SaveAs("./config/dnsconfig/netmaker.hosts")
  43. if err != nil {
  44. return err
  45. }
  46. /* if something goes wrong with server DNS, check here
  47. // commented out bc we were not using IsSplitDNS
  48. if servercfg.IsSplitDNS() {
  49. err = SetCorefile(corefilestring)
  50. }
  51. */
  52. return err
  53. }
  54. // GetDNS - gets the DNS of a current network
  55. func GetDNS(network string) ([]models.DNSEntry, error) {
  56. dns, err := GetNodeDNS(network)
  57. if err != nil && !database.IsEmptyRecord(err) {
  58. return dns, err
  59. }
  60. customdns, err := GetCustomDNS(network)
  61. if err != nil && !database.IsEmptyRecord(err) {
  62. return dns, err
  63. }
  64. dns = append(dns, customdns...)
  65. return dns, nil
  66. }
  67. // GetExtclientDNS - gets all extclients dns entries
  68. func GetExtclientDNS() []models.DNSEntry {
  69. extclients, err := GetAllExtClients()
  70. if err != nil {
  71. return []models.DNSEntry{}
  72. }
  73. var dns []models.DNSEntry
  74. for _, extclient := range extclients {
  75. var entry = models.DNSEntry{}
  76. entry.Name = fmt.Sprintf("%s.%s", extclient.ClientID, extclient.Network)
  77. entry.Network = extclient.Network
  78. if extclient.Address != "" {
  79. entry.Address = extclient.Address
  80. }
  81. if extclient.Address6 != "" {
  82. entry.Address6 = extclient.Address6
  83. }
  84. dns = append(dns, entry)
  85. }
  86. return dns
  87. }
  88. // GetNodeDNS - gets the DNS of a network node
  89. func GetNodeDNS(network string) ([]models.DNSEntry, error) {
  90. var dns []models.DNSEntry
  91. nodes, err := GetNetworkNodes(network)
  92. if err != nil {
  93. return dns, err
  94. }
  95. for _, node := range nodes {
  96. if node.Network != network {
  97. continue
  98. }
  99. host, err := GetHost(node.HostID.String())
  100. if err != nil {
  101. continue
  102. }
  103. var entry = models.DNSEntry{}
  104. entry.Name = fmt.Sprintf("%s.%s", host.Name, network)
  105. entry.Network = network
  106. if node.Address.IP != nil {
  107. entry.Address = node.Address.IP.String()
  108. }
  109. if node.Address6.IP != nil {
  110. entry.Address6 = node.Address6.IP.String()
  111. }
  112. dns = append(dns, entry)
  113. }
  114. return dns, nil
  115. }
  116. // GetCustomDNS - gets the custom DNS of a network
  117. func GetCustomDNS(network string) ([]models.DNSEntry, error) {
  118. var dns []models.DNSEntry
  119. collection, err := database.FetchRecords(database.DNS_TABLE_NAME)
  120. if err != nil {
  121. return dns, err
  122. }
  123. for _, value := range collection { // filter for entries based on network
  124. var entry models.DNSEntry
  125. if err := json.Unmarshal([]byte(value), &entry); err != nil {
  126. continue
  127. }
  128. if entry.Network == network {
  129. dns = append(dns, entry)
  130. }
  131. }
  132. return dns, err
  133. }
  134. // SetCorefile - sets the core file of the system
  135. func SetCorefile(domains string) error {
  136. dir, err := os.Getwd()
  137. if err != nil {
  138. return err
  139. }
  140. _, err = os.Stat(dir + "/config/dnsconfig")
  141. if os.IsNotExist(err) {
  142. err = os.MkdirAll(dir+"/config/dnsconfig", 0744)
  143. }
  144. if err != nil {
  145. logger.Log(0, "couldnt find or create /config/dnsconfig")
  146. return err
  147. }
  148. corefile := domains + ` {
  149. reload 15s
  150. hosts /root/dnsconfig/netmaker.hosts {
  151. fallthrough
  152. }
  153. forward . 8.8.8.8 8.8.4.4
  154. log
  155. }
  156. `
  157. corebytes := []byte(corefile)
  158. err = os.WriteFile(dir+"/config/dnsconfig/Corefile", corebytes, 0644)
  159. if err != nil {
  160. return err
  161. }
  162. return err
  163. }
  164. // GetAllDNS - gets all dns entries
  165. func GetAllDNS() ([]models.DNSEntry, error) {
  166. var dns []models.DNSEntry
  167. networks, err := GetNetworks()
  168. if err != nil && !database.IsEmptyRecord(err) {
  169. return []models.DNSEntry{}, err
  170. }
  171. for _, net := range networks {
  172. netdns, err := GetDNS(net.NetID)
  173. if err != nil {
  174. return []models.DNSEntry{}, nil
  175. }
  176. dns = append(dns, netdns...)
  177. }
  178. return dns, nil
  179. }
  180. // GetDNSEntryNum - gets which entry the dns was
  181. func GetDNSEntryNum(domain string, network string) (int, error) {
  182. num := 0
  183. entries, err := GetDNS(network)
  184. if err != nil {
  185. return 0, err
  186. }
  187. for i := 0; i < len(entries); i++ {
  188. if domain == entries[i].Name {
  189. num++
  190. }
  191. }
  192. return num, nil
  193. }
  194. // SortDNSEntrys - Sorts slice of DNSEnteys by their Address alphabetically with numbers first
  195. func SortDNSEntrys(unsortedDNSEntrys []models.DNSEntry) {
  196. sort.Slice(unsortedDNSEntrys, func(i, j int) bool {
  197. return unsortedDNSEntrys[i].Address < unsortedDNSEntrys[j].Address
  198. })
  199. }
  200. // ValidateDNSCreate - checks if an entry is valid
  201. func ValidateDNSCreate(entry models.DNSEntry) error {
  202. v := validator.New()
  203. _ = v.RegisterValidation("whitespace", func(f1 validator.FieldLevel) bool {
  204. match, _ := regexp.MatchString(`\s`, entry.Name)
  205. return !match
  206. })
  207. _ = v.RegisterValidation("name_unique", func(fl validator.FieldLevel) bool {
  208. num, err := GetDNSEntryNum(entry.Name, entry.Network)
  209. return err == nil && num == 0
  210. })
  211. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  212. _, err := GetParentNetwork(entry.Network)
  213. return err == nil
  214. })
  215. err := v.Struct(entry)
  216. if err != nil {
  217. for _, e := range err.(validator.ValidationErrors) {
  218. logger.Log(1, e.Error())
  219. }
  220. }
  221. return err
  222. }
  223. // ValidateDNSUpdate - validates a DNS update
  224. func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error {
  225. v := validator.New()
  226. _ = v.RegisterValidation("whitespace", func(f1 validator.FieldLevel) bool {
  227. match, _ := regexp.MatchString(`\s`, entry.Name)
  228. return !match
  229. })
  230. _ = v.RegisterValidation("name_unique", func(fl validator.FieldLevel) bool {
  231. //if name & net not changing name we are good
  232. if change.Name == entry.Name && change.Network == entry.Network {
  233. return true
  234. }
  235. num, err := GetDNSEntryNum(change.Name, change.Network)
  236. return err == nil && num == 0
  237. })
  238. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  239. _, err := GetParentNetwork(change.Network)
  240. return err == nil
  241. })
  242. err := v.Struct(change)
  243. if err != nil {
  244. for _, e := range err.(validator.ValidationErrors) {
  245. logger.Log(1, e.Error())
  246. }
  247. }
  248. return err
  249. }
  250. // DeleteDNS - deletes a DNS entry
  251. func DeleteDNS(domain string, network string) error {
  252. key, err := GetRecordKey(domain, network)
  253. if err != nil {
  254. return err
  255. }
  256. err = database.DeleteRecord(database.DNS_TABLE_NAME, key)
  257. return err
  258. }
  259. // CreateDNS - creates a DNS entry
  260. func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error) {
  261. k, err := GetRecordKey(entry.Name, entry.Network)
  262. if err != nil {
  263. return models.DNSEntry{}, err
  264. }
  265. data, err := json.Marshal(&entry)
  266. if err != nil {
  267. return models.DNSEntry{}, err
  268. }
  269. err = database.Insert(k, string(data), database.DNS_TABLE_NAME)
  270. return entry, err
  271. }