github.com/theQRL/go-zond@v0.1.1/cmd/devp2p/dns_cloudflare.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"strings"
    24  
    25  	"github.com/cloudflare/cloudflare-go"
    26  	"github.com/theQRL/go-zond/log"
    27  	"github.com/theQRL/go-zond/p2p/dnsdisc"
    28  	"github.com/urfave/cli/v2"
    29  )
    30  
    31  var (
    32  	cloudflareTokenFlag = &cli.StringFlag{
    33  		Name:    "token",
    34  		Usage:   "CloudFlare API token",
    35  		EnvVars: []string{"CLOUDFLARE_API_TOKEN"},
    36  	}
    37  	cloudflareZoneIDFlag = &cli.StringFlag{
    38  		Name:  "zoneid",
    39  		Usage: "CloudFlare Zone ID (optional)",
    40  	}
    41  )
    42  
    43  type cloudflareClient struct {
    44  	*cloudflare.API
    45  	zoneID string
    46  }
    47  
    48  // newCloudflareClient sets up a CloudFlare API client from command line flags.
    49  func newCloudflareClient(ctx *cli.Context) *cloudflareClient {
    50  	token := ctx.String(cloudflareTokenFlag.Name)
    51  	if token == "" {
    52  		exit(errors.New("need cloudflare API token to proceed"))
    53  	}
    54  	api, err := cloudflare.NewWithAPIToken(token)
    55  	if err != nil {
    56  		exit(fmt.Errorf("can't create Cloudflare client: %v", err))
    57  	}
    58  	return &cloudflareClient{
    59  		API:    api,
    60  		zoneID: ctx.String(cloudflareZoneIDFlag.Name),
    61  	}
    62  }
    63  
    64  // deploy uploads the given tree to CloudFlare DNS.
    65  func (c *cloudflareClient) deploy(name string, t *dnsdisc.Tree) error {
    66  	if err := c.checkZone(name); err != nil {
    67  		return err
    68  	}
    69  	records := t.ToTXT(name)
    70  	return c.uploadRecords(name, records)
    71  }
    72  
    73  // checkZone verifies permissions on the CloudFlare DNS Zone for name.
    74  func (c *cloudflareClient) checkZone(name string) error {
    75  	if c.zoneID == "" {
    76  		log.Info(fmt.Sprintf("Finding CloudFlare zone ID for %s", name))
    77  		id, err := c.ZoneIDByName(name)
    78  		if err != nil {
    79  			return err
    80  		}
    81  		c.zoneID = id
    82  	}
    83  	log.Info(fmt.Sprintf("Checking Permissions on zone %s", c.zoneID))
    84  	zone, err := c.ZoneDetails(context.Background(), c.zoneID)
    85  	if err != nil {
    86  		return err
    87  	}
    88  	if !strings.HasSuffix(name, "."+zone.Name) {
    89  		return fmt.Errorf("CloudFlare zone name %q does not match name %q to be deployed", zone.Name, name)
    90  	}
    91  	needPerms := map[string]bool{"#zone:edit": false, "#zone:read": false}
    92  	for _, perm := range zone.Permissions {
    93  		if _, ok := needPerms[perm]; ok {
    94  			needPerms[perm] = true
    95  		}
    96  	}
    97  	for _, ok := range needPerms {
    98  		if !ok {
    99  			return fmt.Errorf("wrong permissions on zone %s: %v", c.zoneID, needPerms)
   100  		}
   101  	}
   102  	return nil
   103  }
   104  
   105  // uploadRecords updates the TXT records at a particular subdomain. All non-root records
   106  // will have a TTL of "infinity" and all existing records not in the new map will be
   107  // nuked!
   108  func (c *cloudflareClient) uploadRecords(name string, records map[string]string) error {
   109  	// Convert all names to lowercase.
   110  	lrecords := make(map[string]string, len(records))
   111  	for name, r := range records {
   112  		lrecords[strings.ToLower(name)] = r
   113  	}
   114  	records = lrecords
   115  
   116  	log.Info(fmt.Sprintf("Retrieving existing TXT records on %s", name))
   117  	entries, err := c.DNSRecords(context.Background(), c.zoneID, cloudflare.DNSRecord{Type: "TXT"})
   118  	if err != nil {
   119  		return err
   120  	}
   121  	existing := make(map[string]cloudflare.DNSRecord)
   122  	for _, entry := range entries {
   123  		if !strings.HasSuffix(entry.Name, name) {
   124  			continue
   125  		}
   126  		existing[strings.ToLower(entry.Name)] = entry
   127  	}
   128  
   129  	// Iterate over the new records and inject anything missing.
   130  	log.Info("Updating DNS entries")
   131  	created := 0
   132  	updated := 0
   133  	skipped := 0
   134  	for path, val := range records {
   135  		old, exists := existing[path]
   136  		if !exists {
   137  			// Entry is unknown, push a new one to Cloudflare.
   138  			log.Debug(fmt.Sprintf("Creating %s = %q", path, val))
   139  			created++
   140  			ttl := rootTTL
   141  			if path != name {
   142  				ttl = treeNodeTTLCloudflare // Max TTL permitted by Cloudflare
   143  			}
   144  			record := cloudflare.DNSRecord{Type: "TXT", Name: path, Content: val, TTL: ttl}
   145  			_, err = c.CreateDNSRecord(context.Background(), c.zoneID, record)
   146  		} else if old.Content != val {
   147  			// Entry already exists, only change its content.
   148  			log.Info(fmt.Sprintf("Updating %s from %q to %q", path, old.Content, val))
   149  			updated++
   150  			old.Content = val
   151  			err = c.UpdateDNSRecord(context.Background(), c.zoneID, old.ID, old)
   152  		} else {
   153  			skipped++
   154  			log.Debug(fmt.Sprintf("Skipping %s = %q", path, val))
   155  		}
   156  		if err != nil {
   157  			return fmt.Errorf("failed to publish %s: %v", path, err)
   158  		}
   159  	}
   160  	log.Info("Updated DNS entries", "new", created, "updated", updated, "untouched", skipped)
   161  	// Iterate over the old records and delete anything stale.
   162  	deleted := 0
   163  	log.Info("Deleting stale DNS entries")
   164  	for path, entry := range existing {
   165  		if _, ok := records[path]; ok {
   166  			continue
   167  		}
   168  		// Stale entry, nuke it.
   169  		log.Debug(fmt.Sprintf("Deleting %s = %q", path, entry.Content))
   170  		deleted++
   171  		if err := c.DeleteDNSRecord(context.Background(), c.zoneID, entry.ID); err != nil {
   172  			return fmt.Errorf("failed to delete %s: %v", path, err)
   173  		}
   174  	}
   175  	log.Info("Deleted stale DNS entries", "count", deleted)
   176  	return nil
   177  }