コード例 #1
0
ファイル: main.go プロジェクト: mpdroog/dnsd
func main() {
	var (
		addr string
	)
	flag.StringVar(&addr, "l", "[::]:53", "listen on (both tcp and udp)")
	flag.StringVar(&listd, "d", "./list.d", "Dir with blacklisted domain files")
	handler := &Handle{}

	Adlist = make(map[string]bool)
	if e := filepath.Walk(listd, visit); e != nil {
		panic(e)
	}

	//for _, addr := range strings.Split(listen, ",") {
	fmt.Printf("DNS Listen %s\n", addr)
	go func() {
		if err := dns.ListenAndServe(addr, "udp", handler); err != nil {
			panic(err)
		}
	}()

	if err := dns.ListenAndServe(addr, "tcp", handler); err != nil {
		panic(err)
	}
	//}
}
コード例 #2
0
ファイル: dns.go プロジェクト: dustywilson/netcore
func dnsSetup(cfg *Config) chan error {
	log.Println("DNSSETUP")

	// FIXME: Make the default TTL into a configuration parameter
	// FIXME: Check whether this default is being applied to unanswered queries
	defaultTTL := uint32(10800) // this is the default TTL = 3 hours

	cache := dnscache.New(dnsCacheBufferSize, cfg.DNSCacheMaxTTL(), cfg.DNSCacheMissingTTL(), func(c dnscache.Context, q dns.Question) []dns.RR {
		return answerQuestion(cfg, c, &q, defaultTTL, 0)
	})

	dns.HandleFunc(".", func(w dns.ResponseWriter, req *dns.Msg) { dnsQueryServe(cfg, cache, w, req) })
	cfg.db.InitDNS()
	exit := make(chan error, 1)

	go func() {
		exit <- dns.ListenAndServe("0.0.0.0:53", "tcp", nil) // TODO: should use cfg to define the listening ip/port
	}()

	go func() {
		exit <- dns.ListenAndServe("0.0.0.0:53", "udp", nil) // TODO: should use cfg to define the listening ip/port
	}()

	return exit
}
コード例 #3
0
ファイル: server.go プロジェクト: fangdingjun/gdns
func main() {
	parse_flags()

	var err error
	if enable_cache {
		// create cache
		dns_cache, err = lru.New(1000)
		if err != nil {
			log.Fatal(err)
		}
	}

	dns.HandleFunc(".", handleRoot)

	logger = NewLogger(logfile, debug)

	logger.Info("Listen on %s\n", bind_addr)

	go func() {
		/* listen tcp */
		err := dns.ListenAndServe(bind_addr, "tcp", nil)
		if err != nil {
			log.Fatal(err)
		}
	}()

	/* listen udp */
	err = dns.ListenAndServe(bind_addr, "udp", nil)
	if err != nil {
		log.Fatal(err)
	}
}
コード例 #4
0
func main() {

	var (
		S_SERVERS       string
		S_LISTEN        string
		S_ACCESS        string
		timeout         int
		max_entries     int64
		expire_interval int64
	)

	flag.StringVar(&S_SERVERS, "proxy", "127.0.0.1:53", "we proxy requests to those servers")
	flag.StringVar(&S_LISTEN, "listen", "[::1]:5353,127.0.0.1:5353",
		"listen on (both tcp and udp), [ipv6address]:port, ipv4address:port")
	flag.StringVar(&S_ACCESS, "access", "0.0.0.0/0", "allow those networks, use 0.0.0.0/0 to allow everything")
	flag.IntVar(&timeout, "timeout", 5, "timeout")
	flag.Int64Var(&expire_interval, "expire_interval", 300, "delete expired entries every N seconds")
	flag.BoolVar(&DEBUG, "debug", false, "enable/disable debug")
	flag.Int64Var(&max_entries, "max_cache_entries", 2000000, "max cache entries")

	flag.Parse()
	servers := strings.Split(S_SERVERS, ",")
	proxyer := ServerProxy{
		giant:       new(sync.RWMutex),
		ACCESS:      make([]*net.IPNet, 0),
		SERVERS:     servers,
		s_len:       len(servers),
		NOW:         time.Now().UTC().Unix(),
		entries:     0,
		timeout:     time.Duration(timeout) * time.Second,
		max_entries: max_entries}

	for _, mask := range strings.Split(S_ACCESS, ",") {
		_, cidr, err := net.ParseCIDR(mask)
		if err != nil {
			panic(err)
		}
		_D("added access for %s\n", mask)
		proxyer.ACCESS = append(proxyer.ACCESS, cidr)
	}
	for _, addr := range strings.Split(S_LISTEN, ",") {
		_D("listening @ :%s\n", addr)
		go func() {
			if err := dns.ListenAndServe(addr, "udp", proxyer); err != nil {
				log.Fatal(err)
			}
		}()

		go func() {
			if err := dns.ListenAndServe(addr, "tcp", proxyer); err != nil {
				log.Fatal(err)
			}
		}()
	}

	for {
		proxyer.NOW = time.Now().UTC().Unix()
		time.Sleep(time.Duration(1) * time.Second)
	}
}
コード例 #5
0
ファイル: server.go プロジェクト: jhadvig/origin
// Run is a blocking operation that starts the server listening on the DNS ports.
func (s *server) Run() error {
	mux := dns.NewServeMux()
	mux.Handle(".", s)

	dnsReadyMsg := func(addr, net string) {
		if s.config.DNSSEC == "" {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d]", s.config.Domain, net, addr, s.config.RCache)
		} else {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d], signing with %s [scache %d]", s.config.Domain, net, addr, s.config.RCache, s.config.DNSSEC, s.config.SCache)
		}
	}

	s.group.Add(1)
	go func() {
		defer s.group.Done()
		if err := dns.ListenAndServe(s.config.DnsAddr, s.dnsTCPclient.Net, mux); err != nil {
			log.Fatalf("skydns: %s", err)
		}
	}()
	dnsReadyMsg(s.config.DnsAddr, s.dnsTCPclient.Net)
	s.group.Add(1)
	go func() {
		defer s.group.Done()
		if err := dns.ListenAndServe(s.config.DnsAddr, s.dnsUDPclient.Net, mux); err != nil {
			log.Fatalf("skydns: %s", err)
		}
	}()
	dnsReadyMsg(s.config.DnsAddr, s.dnsUDPclient.Net)

	s.group.Wait()
	return nil
}
コード例 #6
0
ファイル: trivialdns.go プロジェクト: e-max/trivialdns
func main() {
	flag.Parse()

	tdns := &TrivialDnsServer{
		Servers:  readUpstreamServersFromConfig(),
		Database: readDatabaseFromConfig(),
		stats:    make(map[string]int),
	}

	log.Printf("Starting with nameservers %v", tdns.Servers)
	log.Printf("Starting with database %v", tdns.Database)

	addr := ":53"

	go func() {
		if err := dns.ListenAndServe(addr, "udp", tdns); err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		if err := dns.ListenAndServe(addr, "tcp", tdns); err != nil {
			log.Fatal(err)
		}
	}()

	log.Printf("DNS server started")
	log.Printf("Starting web interface on %s", *webListenAddr)
	http.HandleFunc("/", tdns.WebIndexPage)
	http.HandleFunc("/save_hosts", tdns.WebSaveHosts)
	http.ListenAndServe(*webListenAddr, nil)
}
コード例 #7
0
ファイル: as112.go プロジェクト: vonwenm/golang-dns
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() * 4)
	for z, rr := range zones {
		rrx := rr.(*dns.SOA) // Needed to create the actual RR, and not an reference.
		dns.HandleFunc(z, func(w dns.ResponseWriter, r *dns.Msg) {
			m := new(dns.Msg)
			m.SetReply(r)
			m.Authoritative = true
			m.Ns = []dns.RR{rrx}
			w.WriteMsg(m)
		})
	}
	go func() {
		err := dns.ListenAndServe(":8053", "tcp", nil)
		if err != nil {
			log.Fatal("Failed to set tcp listener %s\n", err.Error())
		}
	}()
	go func() {
		err := dns.ListenAndServe(":8053", "udp", nil)
		if err != nil {
			log.Fatal("Failed to set udp listener %s\n", err.Error())
		}
	}()
	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	for {
		select {
		case s := <-sig:
			log.Fatalf("Signal (%d) received, stopping\n", s)
		}
	}
}
コード例 #8
0
ファイル: dnsproxy1.go プロジェクト: wjzhangq/dnsproxy
func main() {
	dns.HandleFunc(".", proxyServe)

	failure := make(chan error, 1)

	go func(failure chan error) {
		failure <- dns.ListenAndServe(*local, "tcp", nil)
	}(failure)

	go func(failure chan error) {
		failure <- dns.ListenAndServe(*local, "udp", nil)
	}(failure)

	log.Printf("ready for accept connection on tcp/upd %s ...\n", *local)
	fmt.Println(<-failure)
}
コード例 #9
0
ファイル: dns.go プロジェクト: potatosalad/gow
func ListenAndServeDNS(address string) error {
	dns.HandleFunc("dev.", localhostDNSHandler)

	err := dns.ListenAndServe(address, "udp", nil)
	if err != nil {
		return err
	}
	return nil
}
コード例 #10
0
ファイル: dns.go プロジェクト: pgpst/tunnel
func (d *DNS) ListenAndServe() error {
	udpErr := make(chan error)
	tcpErr := make(chan error)
	go func() {
		udpErr <- dns.ListenAndServe(d.Config.Bind, "udp", dns.HandlerFunc(d.handler))
	}()
	go func() {
		tcpErr <- dns.ListenAndServe(d.Config.Bind, "tcp", dns.HandlerFunc(d.handler))
	}()

	select {
	case err := <-udpErr:
		return err
	case err := <-tcpErr:
		return err
	}

	return nil
}
コード例 #11
0
ファイル: dnstox.go プロジェクト: albertito/dnss
func (s *Server) classicServe() {
	glog.Infof("DNS listening on %s", s.Addr)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		err := dns.ListenAndServe(s.Addr, "udp", dns.HandlerFunc(s.Handler))
		glog.Fatalf("Exiting UDP: %v", err)
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		err := dns.ListenAndServe(s.Addr, "tcp", dns.HandlerFunc(s.Handler))
		glog.Fatalf("Exiting TCP: %v", err)
	}()

	wg.Wait()
}
コード例 #12
0
ファイル: dns.go プロジェクト: yinqiwen/gsnova
func initDNS() {
	if GConf.LocalDNS.CacheSize > 0 {
		dnsCache, _ = lru.New(GConf.LocalDNS.CacheSize)
	}
	if len(GConf.LocalDNS.Listen) > 0 {
		err := dns.ListenAndServe(GConf.LocalDNS.Listen, "udp", dns.HandlerFunc(proxyDNS))
		if nil != err {
			log.Printf("Failed to start dns server:%v", err)
		}
	}
}
コード例 #13
0
ファイル: idyns.go プロジェクト: inve1/idyns
// TODO: make port and bind address configurable
func serve(net, name, secret string) {
	switch name {
	case "":
		err := dns.ListenAndServe(":53", net, nil)
		if err != nil {
			fmt.Printf("Failed to setup the "+net+" server: %s\n", err.Error())
		}
	default:
		server := &dns.Server{Addr: ":53", Net: net, TsigSecret: map[string]string{name: secret}}
		err := server.ListenAndServe()
		if err != nil {
			fmt.Printf("Failed to setup the "+net+" server: %s\n", err.Error())
		}
	}
}
コード例 #14
0
ファイル: main.go プロジェクト: gliderlabs/pkg
func main() {
	keenProject := os.Getenv("KEEN_PROJECT")
	keenWriteKey := os.Getenv("KEEN_WRITE_KEY")
	githubProject := os.Getenv("GITHUB_PROJECT")
	githubToken := os.Getenv("GITHUB_ACCESS_TOKEN")

	host := os.Getenv("HOST")
	if host == "" {
		host = "0.0.0.0"
	}

	port := os.Getenv("PORT")
	if port == "" {
		port = "53"
	}

	addr := net.JoinHostPort(host, port)

	if keenProject == "" || keenWriteKey == "" || githubProject == "" {
		log.Fatal("Please set KEEN_PROJECT, KEEN_WRITE_KEY, and GITHUB_PROJECT")
	}

	keenClient := &keen.Client{WriteKey: keenWriteKey, ProjectID: keenProject}
	keenBatchClient := keen.NewBatchClient(keenClient, *keenFlushInterval)

	var authClient *http.Client

	if githubToken != "" {
		authClient = oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: githubToken},
		))
	}

	githubClient := github.NewClient(authClient)

	tracker := UsageTracker{
		keenClient:    keenBatchClient,
		githubClient:  githubClient,
		githubProject: githubProject,
	}

	err := dns.ListenAndServe(addr, "udp", &tracker)
	if err != nil {
		log.Fatal(err)
	}
}
コード例 #15
0
ファイル: gfc.go プロジェクト: zincxenon/CodeTest
func main () {

    var servers []string
    args := flag.Args ()

    if len(args) > 0 {
        servers = append (servers, args...)
    } else {
        servers = DEFAULT_SERVERS
    }

    LOG.Printf ("Servers: %s", servers)

    proxyer := Proxy{servers}

    if err := dns.ListenAndServe ("127.0.0.1:53", "udp", proxyer); err != nil {
        LOG.Fatal (err)
    }
}
コード例 #16
0
ファイル: shield.go プロジェクト: valm0unt/fks
func main() {
	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	cache := NewCache()
	dns.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) { serve(w, r, cache) })

	// Only listen on UDP
	go func() {
		if err := dns.ListenAndServe(*listen, "udp", nil); err != nil {
			log.Fatalf("fks-shield: failed to setup %s %s", *listen, "udp")
		}
	}()
	go func() {
		for {
			// Every 10 sec run the cache cleaner
			time.Sleep(10 * 1e9)
			cache.Evict()
		}
	}()

	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt)

forever:
	for {
		select {
		case <-sig:
			log.Printf("fks-shield: signal received, stopping")
			break forever
		}
	}
}
コード例 #17
0
ファイル: camnetdns.go プロジェクト: pombredanne/camlistore
func main() {
	launchConfig.MaybeDeploy()
	addr := flag.String("addr", defaultListenAddr(), "specify address for server to listen on")
	flag.Parse()

	memkv := sorted.NewMemoryKeyValue()
	if err := memkv.Set("6401800c.camlistore.net.", "159.203.246.79"); err != nil {
		panic(err)
	}
	if err := memkv.Set("camlistore.net.", "104.154.231.160"); err != nil {
		panic(err)
	}
	if err := memkv.Set("www.camlistore.net.", "104.154.231.160"); err != nil {
		panic(err)
	}

	ds := NewDNSServer(memkv)

	log.Printf("serving DNS on %s\n", *addr)
	if err := dns.ListenAndServe(*addr, "udp", ds); err != nil {
		log.Fatal(err)
	}
}
コード例 #18
0
ファイル: server.go プロジェクト: wealthworks/skydns
// Run is a blocking operation that starts the server listening on the DNS ports.
func (s *server) Run() error {
	mux := dns.NewServeMux()
	mux.Handle(".", s)

	dnsReadyMsg := func(addr, net string) {
		if s.config.DNSSEC == "" {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d]", s.config.Domain, net, addr, s.config.RCache)
		} else {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d], signing with %s [scache %d]", s.config.Domain, net, addr, s.config.RCache, s.config.DNSSEC, s.config.SCache)
		}
	}

	if s.config.Systemd {
		packetConns, err := activation.PacketConns(false)
		if err != nil {
			return err
		}
		listeners, err := activation.Listeners(true)
		if err != nil {
			return err
		}
		if len(packetConns) == 0 && len(listeners) == 0 {
			return fmt.Errorf("no UDP or TCP sockets supplied by systemd")
		}
		for _, p := range packetConns {
			if u, ok := p.(*net.UDPConn); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(nil, u, mux); err != nil {
						log.Fatalf("skydns: %s", err)
					}
				}()
				dnsReadyMsg(u.LocalAddr().String(), "udp")
			}
		}
		for _, l := range listeners {
			if t, ok := l.(*net.TCPListener); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(t, nil, mux); err != nil {
						log.Fatalf("skydns: %s", err)
					}
				}()
				dnsReadyMsg(t.Addr().String(), "tcp")
			}
		}
	} else {
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "tcp", mux); err != nil {
				log.Fatalf("skydns: %s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "tcp")
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "udp", mux); err != nil {
				log.Fatalf("skydns: %s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "udp")
	}

	s.group.Wait()
	return nil
}
コード例 #19
0
ファイル: dnsserver.go プロジェクト: raceli/dnsserver
// Listen for DNS requests. listenSpec is a dotted-quad + port, e.g.,
// 127.0.0.1:53. This function blocks and only returns when the DNS service is
// no longer functioning.
func (ds *DNSServer) Listen(listenSpec string) error {
	return dns.ListenAndServe(listenSpec, "udp", ds)
}
コード例 #20
0
func main() {
	fmt.Printf("Starting ClientProxy\n")
	var (
		S_SERVERS       string
		S_LISTEN        string
		S_ACCESS        string
		timeout         int
		max_entries     int64
		expire_interval int64
		S_DNS_SERVERS   string
		start_TLS       bool
		TLS_Path        string
	)
	flag.BoolVar(&LOG, "log", false, "whether print all query")
	flag.StringVar(&S_SERVERS, "proxy", "24.104.150.237", "we proxy requests to those servers,input like fci.biilab.cn") //Not sure use IP or URL, default server undefined
	flag.StringVar(&S_LISTEN, "listen", "[::]:53", "listen on (both tcp and udp)")
	flag.StringVar(&S_ACCESS, "access", "127.0.0.0/8,10.0.0.0/8", "allow those networks, use 0.0.0.0/0 to allow everything")
	flag.IntVar(&timeout, "timeout", 5, "timeout")
	flag.Int64Var(&expire_interval, "expire_interval", 300, "delete expired entries every N seconds")
	flag.BoolVar(&DEBUG, "debug", false, "enable/disable debug")
	flag.Int64Var(&max_entries, "max_cache_entries", 2000000, "max cache entries")
	flag.StringVar(&S_DNS_SERVERS, "dns_server", "114.114.114.114:53", "DNS server for initial server lookup")
	flag.BoolVar(&start_TLS, "start_TLS", false, "Whether use HTTPS to increase privacy.")
	flag.StringVar(&TLS_Path, "certificate_path", "", "The path of certificate, use no input to let client not validate certificate")
	flag.Parse()
	servers := strings.Split(S_SERVERS, ",")
	dns_servers := strings.Split(S_DNS_SERVERS, ",")
	UDPproxyer := ClientProxy{
		giant:       new(sync.RWMutex),
		ACCESS:      make([]*net.IPNet, 0),
		SERVERS:     servers,
		s_len:       len(servers),
		NOW:         time.Now().UTC().Unix(),
		entries:     0,
		timeout:     time.Duration(timeout) * time.Second,
		max_entries: max_entries,
		TransPro:    UDPcode,
		DNS_SERVERS: dns_servers,
		start_TLS:   start_TLS,
		TLS_Path:    TLS_Path}
	TCPproxyer := ClientProxy{
		giant:       new(sync.RWMutex),
		ACCESS:      make([]*net.IPNet, 0),
		SERVERS:     servers,
		s_len:       len(servers),
		NOW:         time.Now().UTC().Unix(),
		entries:     0,
		timeout:     time.Duration(timeout) * time.Second,
		max_entries: max_entries,
		TransPro:    TCPcode,
		DNS_SERVERS: dns_servers,
		start_TLS:   start_TLS,
		TLS_Path:    TLS_Path}
	for _, mask := range strings.Split(S_ACCESS, ",") {
		_, cidr, err := net.ParseCIDR(mask)
		if err != nil {
			panic(err)
		}
		_D("added access for %s\n", mask)
		UDPproxyer.ACCESS = append(UDPproxyer.ACCESS, cidr)
		TCPproxyer.ACCESS = append(TCPproxyer.ACCESS, cidr)
	}
	err := UDPproxyer.getServerIP()
	if err != nil {
		_D("can not get server address, %s\n", err)
		return
	}
	err = TCPproxyer.getServerIP()
	if err != nil {
		_D("can not get server address, %s\n", err)
		return
	}
	for _, addr := range strings.Split(S_LISTEN, ",") {
		fmt.Printf("listening @ %s\n", addr)
		go func() {
			if err := dns.ListenAndServe(addr, "udp", UDPproxyer); err != nil {
				log.Fatal(err)
			}
		}()

		go func() {
			if err := dns.ListenAndServe(addr, "tcp", TCPproxyer); err != nil {
				log.Fatal(err)
			}
		}()
	}
	fmt.Printf("Start to work\n")
	for {
		UDPproxyer.NOW = time.Now().UTC().Unix()
		time.Sleep(time.Duration(1) * time.Second)
	}
}
コード例 #21
0
ファイル: nasello.go プロジェクト: piger/nasello
func serve(net string, address string) {
	err := dns.ListenAndServe(address, net, nil)
	if err != nil {
		log.Fatalf("Failed to setup the "+net+" server: %s\n", err.Error())
	}
}
コード例 #22
0
ファイル: dnsrouter.go プロジェクト: EtienneBruines/dnsrouter
func main() {
	var err error

	config, err = readConfig("config.dns")
	if err != nil {
		log.Fatal(err)
	}

	// Cleanup all running containers
	client := getDocker()
	list, err := client.ListContainers(docker.ListContainersOptions{All: true})
	if err != nil {
		log.Fatal(err)
	}

ConfigLoop:
	for _, conf := range config {
		created := false

		// See if it already exists
		for _, c := range list {
			for _, name := range c.Names {
				if strings.Index(name, "/"+Prefix+conf.Name) == 0 {
					// Inspect to get info about it
					container, err := client.InspectContainer(c.ID)
					if err != nil {
						// Didn't exist, so let's create it and we're done
						if _, ok := err.(*docker.NoSuchContainer); ok {
							container, err = createContainer(client, conf)
							if err != nil {
								log.Println("Error creating container at startup:", err)
								continue ConfigLoop
							}
							created = true
							continue
						} else {
							log.Println("Error inspecting container at startup:", err)
							continue ConfigLoop
						}
					}

					// Stop it if it's running
					if container.State.Running {
						err = client.StopContainer(c.ID, 1)
						if err != nil {
							log.Println("Error stopping container at startup:", err)
							continue ConfigLoop
						}
					}

					// Get information about the image the container is based on - if it's the same one
					outdated := false

					image, err := client.InspectImage(conf.Dockername)
					if err != nil {
						outdated = true
					} else {
						outdated = container.Created.Before(image.Created)
					}

					// Recreate it if it's outdated
					if outdated {
						log.Println(conf.Dockername, container.Image)
						// So delete
						removeOpts := docker.RemoveContainerOptions{ID: c.ID}
						err = client.RemoveContainer(removeOpts)
						if err != nil {
							log.Println("Error removing container at startup:", err)
							continue ConfigLoop
						}

						// And create
						_, err = createContainer(client, conf)
						if err != nil {
							log.Println("Error creating container at startup:", err)
							continue ConfigLoop
						}
					}
					created = true
				}
			}
		}

		if !created {
			_, err = createContainer(client, conf)
			if err != nil {
				log.Println("Error creating container at startup:", err)
				continue ConfigLoop
			}
		}
	}
	log.Println("Initialized")

	for _, c := range config {
		for _, hostname := range c.Hostnames {
			dns.HandleFunc(hostname, c.GenerateServeDNS(hostname))
		}
	}

	go dns.ListenAndServe("localhost:"+strconv.Itoa(port), "tcp", nil)
	go dns.ListenAndServe("localhost:"+strconv.Itoa(port), "udp", nil)

	log.Printf("Server listening on port %d on TCP and UDP\n", port)

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case s := <-sig:
			log.Printf("Signal (%d) received, stopping\n", s)
			break forever
		}
	}
}
コード例 #23
0
ファイル: server.go プロジェクト: janeczku/go-dnsmasq
// Run is a blocking operation that starts the server listening on the DNS ports.
func (s *server) Run() error {
	mux := dns.NewServeMux()
	mux.Handle(".", s)

	dnsReadyMsg := func(addr, net string) {
		rCacheState := "disabled"
		if s.config.RCache > 0 {
			rCacheState = fmt.Sprintf("capacity: %d", s.config.RCache)
		}
		log.Infof("Ready for queries on %s://%s [cache: %s]", net, addr, rCacheState)
	}

	if s.config.Systemd {
		packetConns, err := activation.PacketConns(false)
		if err != nil {
			return err
		}
		listeners, err := activation.Listeners(true)
		if err != nil {
			return err
		}
		if len(packetConns) == 0 && len(listeners) == 0 {
			return fmt.Errorf("No UDP or TCP sockets supplied by systemd")
		}
		for _, p := range packetConns {
			if u, ok := p.(*net.UDPConn); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(nil, u, mux); err != nil {
						log.Fatalf("%s", err)
					}
				}()
				dnsReadyMsg(u.LocalAddr().String(), "udp")
			}
		}
		for _, l := range listeners {
			if t, ok := l.(*net.TCPListener); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(t, nil, mux); err != nil {
						log.Fatalf("%s", err)
					}
				}()
				dnsReadyMsg(t.Addr().String(), "tcp")
			}
		}
	} else {
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "tcp", mux); err != nil {
				log.Fatalf("%s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "tcp")
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "udp", mux); err != nil {
				log.Fatalf("%s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "udp")
	}

	s.group.Wait()
	return nil
}
コード例 #24
0
ファイル: main.go プロジェクト: levenlabs/struggledns
func main() {
	l := lever.New("struggledns", nil)
	l.Add(lever.Param{
		Name:        "--listen-addr",
		Description: "Address to listen on for dns requests. Will bind to both tcp and udp",
		Default:     ":53",
	})
	l.Add(lever.Param{
		Name:        "--fwd-to",
		Description: "Address (ip:port) of a dns server to attempt forward requests to. Specify multiple times to make multiple request attempts. Order specified dictates precedence should more than one server respond for a request",
	})
	l.Add(lever.Param{
		Name:        "--parallel",
		Description: "If sent the query will be sent to all addresses in parallel",
		Flag:        true,
	})
	l.Add(lever.Param{
		Name:        "--timeout",
		Description: "Timeout in milliseconds for each request",
		Default:     "300",
	})
	l.Add(lever.Param{
		Name:        "--log-level",
		Description: "Minimum log level to show, either debug, info, warn, error, or fatal",
		Default:     "warn",
	})
	l.Add(lever.Param{
		Name:        "--allow-truncated",
		Description: "If we should allow truncated responses to be proxied",
		Flag:        true,
	})
	if version != "" {
		l.Add(lever.Param{
			Name:        "--version",
			Aliases:     []string{"-v"},
			Description: "Print version info",
			Flag:        true,
		})
	}
	l.Parse()

	if l.ParamFlag("--version") {
		fmt.Println(version)
		return
	}

	addr, _ := l.ParamStr("--listen-addr")
	dnsServers, _ := l.ParamStrs("--fwd-to")
	combineGroups := l.ParamFlag("--parallel")
	timeout, _ := l.ParamInt("--timeout")

	logLevel, _ := l.ParamStr("--log-level")
	llog.SetLevelFromString(logLevel)

	allowTruncated = l.ParamFlag("--allow-truncated")

	if combineGroups {
		//combine all the servers sent into one group
		dnsServerGroups = make([][]string, 1)
		var groupServers []string
		for i := range dnsServers {
			groupServers = strings.Split(dnsServers[i], ",")
			dnsServerGroups[0] = append(dnsServerGroups[0], groupServers...)
		}
	} else {
		dnsServerGroups = make([][]string, len(dnsServers))
		for i := range dnsServers {
			dnsServerGroups[i] = strings.Split(dnsServers[i], ",")
		}
	}

	client = dns.Client{
		//since this is UDP, the Dial/Write timeouts don't mean much
		//we really only care about setting the read
		DialTimeout:  time.Millisecond * 100,
		WriteTimeout: time.Millisecond * 100,
		ReadTimeout:  time.Millisecond * time.Duration(timeout),
		UDPSize:      4096,
	}

	handler := dns.HandlerFunc(handleRequest)
	go func() {
		llog.Info("listening on udp", llog.KV{"addr": addr})
		err := dns.ListenAndServe(addr, "udp", handler)
		llog.Fatal("error listening on udp", llog.KV{"err": err})
	}()
	go func() {
		llog.Info("listening on tcp", llog.KV{"addr": addr})
		err := dns.ListenAndServe(addr, "tcp", handler)
		llog.Fatal("error listening on tcp", llog.KV{"err": err})
	}()

	select {}
}
コード例 #25
0
ファイル: camnetdns.go プロジェクト: camlistore/camlistore
func main() {
	launchConfig.MaybeDeploy()
	flag.Parse()

	var kv keyValue
	var httpsListenAddr string
	if metadata.OnGCE() {
		httpsListenAddr = ":443"
		dsClient, err := datastore.NewClient(context.Background(), GCEProjectID)
		if err != nil {
			log.Fatalf("Error creating datastore client for records: %v", err)
		}
		kv = cachedStore{
			dsClient: dsClient,
			cache:    lru.New(cacheSize),
		}
	} else {
		httpsListenAddr = ":4430"
		kv = memkv{skv: sorted.NewMemoryKeyValue()}
	}
	if err := kv.Set("6401800c.camlistore.net.", "159.203.246.79"); err != nil {
		log.Fatalf("Error adding %v:%v record: %v", "6401800c.camlistore.net.", "159.203.246.79", err)
	}
	if err := kv.Set(domain, *flagServerIP); err != nil {
		log.Fatalf("Error adding %v:%v record: %v", domain, *flagServerIP, err)
	}
	if err := kv.Set("www.camlistore.net.", *flagServerIP); err != nil {
		log.Fatalf("Error adding %v:%v record: %v", "www.camlistore.net.", *flagServerIP, err)
	}

	ds := newDNSServer(kv)
	cs := &gpgchallenge.Server{
		OnSuccess: func(identity string, address string) error {
			log.Printf("Adding %v.camlistore.net. as %v", identity, address)
			return ds.dataSource.Set(strings.ToLower(identity+".camlistore.net."), address)
		},
	}

	tcperr := make(chan error, 1)
	udperr := make(chan error, 1)
	httperr := make(chan error, 1)
	log.Printf("serving DNS on %s\n", *addr)
	go func() {
		tcperr <- dns.ListenAndServe(*addr, "tcp", ds)
	}()
	go func() {
		udperr <- dns.ListenAndServe(*addr, "udp", ds)
	}()
	if metadata.OnGCE() {
		// TODO(mpl): if we want to get a cert for anything
		// *.camlistore.net, it's a bit of a chicken and egg problem, since
		// we need camnetdns itself to be already running and answering DNS
		// queries. It's probably doable, but easier for now to just ask
		// one for camnetdns.camlistore.org, since that name is not
		// resolved by camnetdns.
		hostname := strings.TrimSuffix(authorityNS, ".")
		m := autocert.Manager{
			Prompt:     autocert.AcceptTOS,
			HostPolicy: autocert.HostWhitelist(hostname),
			Cache:      autocert.DirCache(osutil.DefaultLetsEncryptCache()),
		}
		ln, err := tls.Listen("tcp", httpsListenAddr, &tls.Config{
			Rand:           rand.Reader,
			Time:           time.Now,
			NextProtos:     []string{http2.NextProtoTLS, "http/1.1"},
			MinVersion:     tls.VersionTLS12,
			GetCertificate: m.GetCertificate,
		})
		if err != nil {
			log.Fatalf("Error listening on %v: %v", httpsListenAddr, err)
		}
		go func() {
			httperr <- http.Serve(ln, cs)
		}()
	}
	select {
	case err := <-tcperr:
		log.Fatalf("DNS over TCP error: %v", err)
	case err := <-udperr:
		log.Fatalf("DNS error: %v", err)
	case err := <-httperr:
		log.Fatalf("HTTP server error: %v", err)
	}
}