Пример #1
0
func TestParseMXNegativeTests(t *testing.T) {

	/* helper functions */

	dns.HandleFunc(".", rootZone)
	defer dns.HandleRemove(".")

	hosts := make(map[uint16][]string)

	hosts[dns.TypeMX] = []string{
		"mail.matching.com. 0 IN MX 5 mail.matching.com.",
		"mail.matching.com. 0 IN MX 10 mail2.matching.com.",
		"mail.matching.com. 0 IN MX 15 mail3.matching.com.",
	}
	hosts[dns.TypeAAAA] = []string{
		"mail.matching.com. 0 IN AAAA 2001:4860:1:2001::80",
	}

	hosts[dns.TypeA] = []string{
		"mail.matching.com. 0 IN A 172.18.0.2",
		"mail2.matching.com. 0 IN A 172.20.20.20",
		"mail3.matching.com. 0 IN A 172.100.0.1",
	}
	mxMatchingCom := generateZone(hosts)
	dns.HandleFunc("matching.com.", mxMatchingCom)
	defer dns.HandleRemove("matching.com.")

	s, addr, err := runLocalUDPServer(dnsServer)
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer s.Shutdown()
	Nameserver = addr
	/* ***************** */
	ip := net.IP{127, 0, 0, 1}
	domain := "matching.com"
	p := NewParser(domain, domain, ip, stub)

	testcases := []TokenTestCase{
		TokenTestCase{&Token{tMX, qPlus, "matching.com"}, Pass, false},
		TokenTestCase{&Token{tMX, qPlus, ""}, Pass, false},
		//TokenTestCase{&Token{tMX, qPlus, "google.com"}, Pass, false},
		TokenTestCase{&Token{tMX, qPlus, "idontexist"}, Pass, false},
		TokenTestCase{&Token{tMX, qMinus, "matching.com"}, Fail, false},
	}

	var match bool
	var result SPFResult

	for _, testcase := range testcases {
		match, result = p.parseMX(testcase.Input)
		if testcase.Match != match {
			t.Error("Match mismatch, expected ", testcase.Match, " got ", match)
		}
		if testcase.Result != result {
			t.Error("Result mismatch, expected ", testcase.Result, " got ", result)
		}
	}
}
Пример #2
0
// TestParseExists executes tests for exists term.
func TestParseExists(t *testing.T) {

	dns.HandleFunc(".", rootZone)
	defer dns.HandleRemove(".")

	hosts := make(map[uint16][]string)
	hosts[dns.TypeA] = []string{
		"postitive.matching.net. 0 IN A 172.20.20.20",
		"postitive.matching.net. 0 IN A 172.18.0.1",
		"postitive.matching.net. 0 IN A 172.18.0.2",
	}
	dns.HandleFunc("positive.matching.net.", generateZone(hosts))
	defer dns.HandleRemove("positive.matching.net.")

	hosts = make(map[uint16][]string)
	hosts[dns.TypeA] = []string{
		"postitive.matching.com. 0 IN A 172.20.20.20",
		"postitive.matching.com. 0 IN A 172.18.0.1",
		"postitive.matching.com. 0 IN A 172.18.0.2",
	}
	dns.HandleFunc("positive.matching.com.", generateZone(hosts))
	defer dns.HandleRemove("positive.matching.com.")
	s, addr, err := runLocalUDPServer(dnsServer)
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer s.Shutdown()
	Nameserver = addr

	domain := "matching.com"
	p := NewParser(domain, domain, ip, stub)
	testcases := []TokenTestCase{
		TokenTestCase{&Token{tExists, qPlus, "positive.matching.net"}, Pass, true},
		TokenTestCase{&Token{tExists, qMinus, "positive.matching.net"}, Fail, true},
		TokenTestCase{&Token{tExists, qMinus, "idontexist.matching.net"}, Fail, false},
		TokenTestCase{&Token{tExists, qMinus, "idontexist.%{d}"}, Fail, false},
		TokenTestCase{&Token{tExists, qTilde, "positive.%{d}"}, Softfail, true},
		TokenTestCase{&Token{tExists, qTilde, "positive.%{d}"}, Softfail, true},
		TokenTestCase{&Token{tExists, qTilde, ""}, Permerror, true},
		TokenTestCase{&Token{tExists, qTilde, "invalidsyntax%{}"}, Permerror, true},
	}

	for _, testcase := range testcases {
		match, result := p.parseExists(testcase.Input)
		if testcase.Match != match {
			t.Error("Match mismatch, expected ", testcase.Match, " got ", match)
		}
		if testcase.Result != result {
			t.Error("Result mismatch, expected ", testcase.Result, " got ", result)
		}
	}
}
Пример #3
0
func TestHandleExplanation(t *testing.T) {
	const domain = "matching.com"
	// static.exp.matching.com.        IN      TXT "Invalid SPF record"
	// ip.exp.matching.com.            IN      TXT "%{i} is not one of %{d}'s designated mail servers."
	// redirect.exp.matching.com.      IN      TXT "See http://%{d}/why.html?s=%{s}&i=%{i}"

	dns.HandleFunc(".", rootZone)
	defer dns.HandleRemove(".")

	hosts := make(map[uint16][]string)
	hosts[dns.TypeTXT] = []string{
		"static.exp.matching.com. 0 IN TXT \"Invalid SPF record\"",
	}
	dns.HandleFunc("static.exp.matching.com.", generateZone(hosts))
	defer dns.HandleRemove("static.exp.matching.com.")

	hosts = make(map[uint16][]string)
	hosts[dns.TypeTXT] = []string{
		"ip.exp.matching.com. 0 in TXT \"%{i} is not one of %{d}'s designated mail servers.\"",
	}
	dns.HandleFunc("ip.exp.matching.com.", generateZone(hosts))
	defer dns.HandleRemove("ip.exp.matching.com.")

	s, addr, err := runLocalUDPServer(dnsServer)
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer s.Shutdown()
	Nameserver = addr

	ExpTestCases := []ExpTestCase{
		ExpTestCase{"v=spf1 -all exp=static.exp.matching.com",
			"Invalid SPF record"},
		ExpTestCase{"v=spf1 -all exp=ip.exp.matching.com",
			"127.0.0.1 is not one of matching.com's designated mail servers."},
		// TODO(zaccone): Cover this testcase
		//ExpTestCase{"v=spf1 -all exp=redirect.exp.matching.com",
		//ExpT"See http://matching.com/why.html?s=&i="},
	}

	for _, testcase := range ExpTestCases {

		p := NewParser(domain, domain, ip, testcase.Query)
		_, exp, err := p.Parse()
		if err != nil {
			t.Error("Unexpected error while parsing: ", err)
		} else if exp != testcase.Explanation {
			t.Errorf("Explanation mismatch, expected %s, got %s\n",
				testcase.Explanation, exp)
		}
	}
}
Пример #4
0
// LaunchDNS starts a (TCP and UDP) DNS server for the Resolver,
// returning a error channel to which errors are asynchronously sent.
func (res *Resolver) LaunchDNS() <-chan error {
	// Handers for Mesos requests
	dns.HandleFunc(res.config.Domain+".", panicRecover(res.HandleMesos))
	// Handler for nonMesos requests
	dns.HandleFunc(".", panicRecover(res.HandleNonMesos))

	errCh := make(chan error, 2)
	_, e1 := res.Serve("tcp")
	go func() { errCh <- <-e1 }()
	_, e2 := res.Serve("udp")
	go func() { errCh <- <-e2 }()
	return errCh
}
Пример #5
0
func (manager *DnsManager) Setup() error {
	dns.HandleFunc(manager.BaseName, manager.dnsHandler)

	go func() {
		manager.udpServer = &dns.Server{
			Addr:       fmt.Sprintf("%v:%v", manager.ServiceAddr, manager.ServicePort),
			Net:        "udp",
			TsigSecret: nil,
		}
		err := manager.udpServer.ListenAndServe()
		if err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		manager.tcpServer = &dns.Server{
			Addr:       fmt.Sprintf("%v:%v", manager.ServiceAddr, manager.ServicePort),
			Net:        "tcp",
			TsigSecret: nil,
		}
		err := manager.tcpServer.ListenAndServe()
		if err != nil {
			log.Fatal(err)
		}
	}()

	return nil
}
Пример #6
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() * 4)
	flag.Parse()

	configuration := nasello.ReadConfig(*configFile)
	for _, filter := range configuration.Filters {
		// Ensure that each pattern is a FQDN name
		pattern := dns.Fqdn(filter.Pattern)

		log.Printf("Proxing %s on %v\n", pattern, strings.Join(filter.Addresses, ", "))
		dns.HandleFunc(pattern, nasello.ServerHandler(filter.Addresses))
	}

	go serve("tcp", *listenAddr)
	go serve("udp", *listenAddr)

	log.Printf("Started DNS server on: %s\n", *listenAddr)

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case s := <-sig:
			log.Printf("Signal (%s) received, stopping\n", s.String())
			break forever
		}
	}
}
Пример #7
0
func (ts *testSrv) serveTestResolver() {
	dns.HandleFunc(".", ts.dnsHandler)
	dnsServer := &dns.Server{
		Addr:         "0.0.0.0:8053",
		Net:          "tcp",
		ReadTimeout:  time.Millisecond,
		WriteTimeout: time.Millisecond,
	}
	go func() {
		err := dnsServer.ListenAndServe()
		if err != nil {
			fmt.Println(err)
			return
		}
	}()
	webServer := &http.Server{
		Addr:    "0.0.0.0:8055",
		Handler: http.HandlerFunc(ts.setTXT),
	}
	go func() {
		err := webServer.ListenAndServe()
		if err != nil {
			fmt.Println(err)
			return
		}
	}()
}
Пример #8
0
func updateDns(ethereum *eth.Ethereum) {
	stateObject := ethereum.StateManager().CurrentState().GetStateObject(dnsreg)
	if stateObject != nil {
		ethutil.Config.Log.Debugln("Updating DNS")
		stateObject.State().EachStorage(func(name string, value *ethutil.Value) {
			val := value.Bytes()[1:]
			name = sanitizeString(name) + ".eth."
			dns.HandleRemove(name)
			zoneString := fmt.Sprintf("%s 2044 IN A %s", name, val)
			zone := NewRR(zoneString)
			if zone != nil {
				ethutil.Config.Log.Debugln("[DNS] Updated zone:", zone)
				dns.HandleFunc(name, func(w dns.ResponseWriter, r *dns.Msg) {
					switch r.Question[0].Qtype {
					case dns.TypeA:
						m := new(dns.Msg)
						m.SetReply(r)
						m.Answer = []dns.RR{zone}
						m.RecursionAvailable = true
						w.WriteMsg(m)
					default:
						ethutil.Config.Log.Debugln("[DNS] Type not supported yet")
					}

				})
			} else {
				ethutil.Config.Log.Debugln("Invalid zone", zoneString)
			}
		})
	}
}
Пример #9
0
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)
	}
}
Пример #10
0
func (d *DNSResponder) Serve(domains []string) error {
	for _, domain := range domains {
		dns.HandleFunc(domain+".", d.handleDNS)
	}

	addr := d.Address
	if addr == "" {
		addr = DefaultAddress
	}

	var wg sync.WaitGroup

	wg.Add(2)

	go func() {
		defer wg.Done()
		server := &dns.Server{Addr: addr, Net: "udp", TsigSecret: nil}
		server.ListenAndServe()
	}()

	go func() {
		defer wg.Done()
		server := &dns.Server{Addr: addr, Net: "tcp", TsigSecret: nil}
		server.ListenAndServe()
	}()

	wg.Wait()

	return nil
}
Пример #11
0
func main() {
	port := flag.Int("port", 5353, "port to run on")
	flag.Parse()

	dns.HandleFunc(".", handleFirstHost)

	serve := func(net string, port int) {
		server := &dns.Server{Addr: ":" + strconv.Itoa(port), Net: net}
		err := server.ListenAndServe()
		if err != nil {
			glog.Infof("Failed to setup the "+net+" server: %s\n", err.Error())
		}
	}

	go serve("tcp", *port)
	go serve("udp", *port)

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case s := <-sig:
			log.Fatalf("Signal (%d) received, stopping\n", s)
			break forever
		}
	}
}
Пример #12
0
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)
		}
	}
}
Пример #13
0
func TestTransferIn(t *testing.T) {
	soa := soa{250}

	dns.HandleFunc(testZone, soa.Handler)
	defer dns.HandleRemove(testZone)

	s, addrstr, err := test.TCPServer("127.0.0.1:0")
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer s.Shutdown()

	z := new(Zone)
	z.Expired = new(bool)
	z.origin = testZone
	z.TransferFrom = []string{addrstr}

	err = z.TransferIn()
	if err != nil {
		t.Fatalf("unable to run TransferIn: %v", err)
	}
	if z.Apex.SOA.String() != fmt.Sprintf("%s	3600	IN	SOA	bla. bla. 250 0 0 0 0", testZone) {
		t.Fatalf("unknown SOA transferred")
	}
}
Пример #14
0
func addZoneHandles() {
	client := connectToRedis()
	zones := client.Keys("zone:*").Val()
	for i := 0; i < len(zones); i++ {
		dns.HandleFunc(zones[i][5:], handleRequest)
	}
}
Пример #15
0
func main() {
	flag.Parse()
	if *defaultServer == "" {
		log.Fatal("-default is required")
	}
	transferIPs = strings.Split(*allowTransfer, ",")
	routes = make(map[string]string)
	if *routeList != "" {
		for _, s := range strings.Split(*routeList, ",") {
			s := strings.SplitN(s, "=", 2)
			if len(s) != 2 {
				log.Fatal("invalid -routes format")
			}
			if !strings.HasSuffix(s[0], ".") {
				s[0] += "."
			}
			routes[s[0]] = s[1]
		}
	}

	udpServer := &dns.Server{Addr: *address, Net: "udp"}
	tcpServer := &dns.Server{Addr: *address, Net: "tcp"}
	dns.HandleFunc(".", route)
	go func() {
		log.Fatal(udpServer.ListenAndServe())
	}()
	log.Fatal(tcpServer.ListenAndServe())
}
Пример #16
0
func TestShouldTransfer(t *testing.T) {
	soa := soa{250}

	dns.HandleFunc(testZone, soa.Handler)
	defer dns.HandleRemove(testZone)

	s, addrstr, err := test.TCPServer("127.0.0.1:0")
	if err != nil {
		t.Fatalf("unable to run test server: %v", err)
	}
	defer s.Shutdown()

	z := new(Zone)
	z.origin = testZone
	z.TransferFrom = []string{addrstr}

	// Serial smaller
	z.Apex.SOA = test.SOA(fmt.Sprintf("%s IN SOA bla. bla. %d 0 0 0 0 ", testZone, soa.serial-1))
	should, err := z.shouldTransfer()
	if err != nil {
		t.Fatalf("unable to run shouldTransfer: %v", err)
	}
	if !should {
		t.Fatalf("shouldTransfer should return true for serial: %q", soa.serial-1)
	}
	// Serial equal
	z.Apex.SOA = test.SOA(fmt.Sprintf("%s IN SOA bla. bla. %d 0 0 0 0 ", testZone, soa.serial))
	should, err = z.shouldTransfer()
	if err != nil {
		t.Fatalf("unable to run shouldTransfer: %v", err)
	}
	if should {
		t.Fatalf("shouldTransfer should return false for serial: %d", soa.serial)
	}
}
Пример #17
0
func main() {
	parseFlags()

	if *showVersion {
		fmt.Printf("%s\n", VERSION)
		os.Exit(0)
	}

	log.Infof("Starting rancher-dns %s", VERSION)
	err := loadAnswers()
	if err != nil {
		log.Fatal("Cannot startup without a valid Answers file")
	}
	watchSignals()
	watchHttp()

	seed := time.Now().UTC().UnixNano()
	log.Debug("Set random seed to ", seed)
	rand.Seed(seed)

	udpServer := &dns.Server{Addr: *listen, Net: "udp"}
	tcpServer := &dns.Server{Addr: *listen, Net: "tcp"}

	globalCache = cache.New(int(*cacheCapacity), int(*defaultTtl))
	clientSpecificCaches = make(map[string]*cache.Cache)

	dns.HandleFunc(".", route)

	go func() {
		log.Fatal(udpServer.ListenAndServe())
	}()
	log.Info("Listening on ", *listen)
	log.Fatal(tcpServer.ListenAndServe())
}
Пример #18
0
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
}
Пример #19
0
func (srv *Server) setupRootZone() {
	dns.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) {
		m := new(dns.Msg)
		m.SetRcode(r, dns.RcodeRefused)
		w.WriteMsg(m)
	})
}
Пример #20
0
func main() {
	config.Parse()

	if *configCustomDomainNameFile != "" {
		customDNData, err := ioutil.ReadFile(*configCustomDomainNameFile)
		if err != nil {
			fmt.Println(err.Error())
		} else {
			SerfFilterTable = loadCustomDomainName(customDNData)
		}
	}

	serfClient, err := connectSerfAgent(*configSerfRPCAddress, *configSerfRPCAuthKey)
	defer closeSerfConnection(serfClient)
	if err != nil {
		fmt.Println(err.Error())
	}

	dns.HandleFunc(*configDomainName,
		func(writer dns.ResponseWriter, request *dns.Msg) {
			handle(writer, request, serfClient)
		})
	go serve("tcp", *configBind)
	go serve("udp", *configBind)
	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case <-sig:
			break forever
		}
	}
}
Пример #21
0
// Serve starts DNS server
func (dns *DNS) Serve(net string) (err error) {
	log.WithFields(log.Fields{
		"service": "dns",
		"net":     net,
	}).Info("Serve over ", net)

	dns.Server = &mdns.Server{
		Addr: fmt.Sprintf("%s:%d", dns.Config.DNS.IP, dns.Config.DNS.Port),
		Net:  net,
	}

	mdns.HandleFunc(".", dns.HandleRequest)

	err = dns.Server.ListenAndServe()
	if err != nil {
		log.WithFields(log.Fields{
			"service": "dns",
			"addr":    dns.Config.DNS.IP,
			"port":    dns.Config.DNS.Port,
			"net":     net,
			"error":   err,
		}).Error("Can't start server")
	}
	defer dns.Server.Shutdown()

	log.WithFields(log.Fields{
		"service": "dns",
	}).Info("[dns] Shutdown...")

	return
}
Пример #22
0
func main() {
	var (
		name   string // tsig keyname
		secret string // tsig base64
	)

	// Parse flags
	port = flag.Int("port", 53, "server port ")
	tsig = flag.String("tsig", "", "use MD5 hmac tsig: keyname:base64")
	dbPath = flag.String("db_path", "./dyndns.db", "location where db will be stored")
	pidFile = flag.String("pid", "./go-dyndns.pid", "pid file location")
	debug = flag.Bool("debug", false, "log debug to console")

	flag.Parse()

	// Open db
	db, err := bolt.Open(*dbPath, 0600, &bolt.Options{Timeout: 10 * time.Second})

	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	bdb = db

	// Create dns bucket if doesn't exist
	createBucket(rrBucket)

	// Attach request handler func
	dns.HandleFunc(".", handleDNSRequest)

	// Tsig extract
	if *tsig != "" {
		a := strings.SplitN(*tsig, ":", 2)
		name, secret = dns.Fqdn(a[0]), a[1]
	}

	// Pidfile
	file, err := os.OpenFile(*pidFile, os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		Log.Panic("Couldn't create pid file: ", err)
	} else {
		file.Write([]byte(strconv.Itoa(syscall.Getpid())))
		defer file.Close()
	}

	// Start server
	go serve(name, secret, *port)

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
endless:
	for {
		select {
		case s := <-sig:
			Log.Printf("Signal (%v) received, stopping", s)
			break endless
		}
	}
}
Пример #23
0
func main() {
	flag.Parse()
	*memSize *= 1024 * 1024
	if *cacheSize < 2 {
		log.Fatal("Cache size too small")
	}
	parseLocalRRSFile(*localRRSFile)
	cache, _ = lru.NewARC(*cacheSize)
	upstreamServers, _ = parseUpstreamServers(*upstreamServersStr)
	sipHashKey = SipHashKey{k1: randUint64(), k2: randUint64()}
	resolverRing = make(chan QueuedRequest, *maxClients)
	globalTimeout = time.Duration((*maxRTT) * 3.0 * 1E9)
	udpClient = dns.Client{Net: "udp", DialTimeout: globalTimeout, ReadTimeout: globalTimeout, WriteTimeout: globalTimeout, SingleInflight: true}
	tcpClient = dns.Client{Net: "tcp", DialTimeout: globalTimeout, ReadTimeout: globalTimeout, WriteTimeout: globalTimeout, SingleInflight: true}
	probeUpstreamServers(true)
	upstreamServers.lock.Lock()
	log.Printf("Live upstream servers: %v\n", upstreamServers.live)
	upstreamServers.lock.Unlock()
	for i := uint(0); i < *maxClients; i++ {
		go func() {
			resolverThread()
		}()
	}
	dns.HandleFunc(".", route)
	defer dns.HandleRemove(".")
	udpServer := &dns.Server{Addr: *address, Net: "udp"}
	defer udpServer.Shutdown()
	udpAddr, err := net.ResolveUDPAddr(udpServer.Net, udpServer.Addr)
	if err != nil {
		log.Fatal(err)
	}
	udpPacketConn, err := net.ListenUDP(udpServer.Net, udpAddr)
	if err != nil {
		log.Fatal(err)
	}
	udpServer.PacketConn = udpPacketConn
	udpPacketConn.SetReadBuffer(MaxUDPBufferSize)
	udpPacketConn.SetWriteBuffer(MaxUDPBufferSize)

	tcpServer := &dns.Server{Addr: *address, Net: "tcp"}
	defer tcpServer.Shutdown()
	tcpAddr, err := net.ResolveTCPAddr(tcpServer.Net, tcpServer.Addr)
	if err != nil {
		log.Fatal(err)
	}
	tcpListener, err := net.ListenTCP(tcpServer.Net, tcpAddr)
	if err != nil {
		log.Fatal(err)
	}
	tcpServer.Listener = tcpListener
	go func() {
		log.Fatal(udpServer.ActivateAndServe())
	}()
	go func() {
		log.Fatal(tcpServer.ActivateAndServe())
	}()
	fmt.Println("Ready")
	vacuumThread()
}
func main() {
	server := &dns.Server{Addr: ":10015", Net: "udp", Handler: nil, Unsafe: true}
	dns.HandleFunc(".", handlerToAnswer)
	err := server.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
Пример #25
0
func main() {
	dns.HandleFunc(".", handleRequest)
	server := &dns.Server{Addr: ":53", Net: "udp"}

	err := server.ListenAndServe() //Blocking .. forever..
	if err != nil {
		panic(err)
	}
}
Пример #26
0
func ListenAndServeDNS(address string) error {
	dns.HandleFunc("dev.", localhostDNSHandler)

	err := dns.ListenAndServe(address, "udp", nil)
	if err != nil {
		return err
	}
	return nil
}
Пример #27
0
Файл: dns.go Проект: nlf/dlite
func (d *DNS) Start() error {
	dns.HandleFunc(".", d.handleRequest)
	d.server = &dns.Server{
		Addr: ":1053",
		Net:  "udp",
	}

	return d.server.ListenAndServe()
}
// Serve starts a sever for a given net type (udp or tcp)
func (c *CatchAll) Serve(netType string) error {
	dns.HandleFunc(".", c.handleDNS)

	server := &dns.Server{Addr: c.Port, Net: netType, TsigSecret: nil}

	log.Infof("Serve %s", netType)

	return server.ListenAndServe()
}
Пример #29
0
func main() {
	flag.Parse()
	if *flagprof != "" {
		f, err := os.Create(*flagprof)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	*superuser = strings.ToLower(*superuser)
	conf := NewConfig()
	conf.Rights[*superuser] = R_LIST | R_WRITE | R_DROP | R_USER // *all* of them

	go func() {
		conf.ServerUDP = &dns.Server{Addr: ":" + strconv.Itoa(*port), Net: "udp", TsigSecret: map[string]string{dns.Fqdn(*superuser): *superkey}}
		err := conf.ServerUDP.ListenAndServe()
		if err != nil {
			log.Fatal("fksd: could not start udp listener: %s", err.Error())
		}
	}()
	go func() {
		conf.ServerTCP = &dns.Server{Addr: ":" + strconv.Itoa(*port), Net: "tcp", TsigSecret: map[string]string{dns.Fqdn(*superuser): *superkey}}
		err := conf.ServerTCP.ListenAndServe()
		if err != nil {
			log.Fatal("fksd: could not start tcp listener: %s", err.Error())
		}
	}()

	// Hijack these zone names, but only if they use the CLASS 65516
	dns.HandleFunc("zone.", func(w dns.ResponseWriter, req *dns.Msg) { config(w, req, conf) })
	dns.HandleFunc("user.", func(w dns.ResponseWriter, req *dns.Msg) { config(w, req, conf) })

	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt)
forever:
	for {
		select {
		case <-sig:
			logPrintf("signal received, stopping")
			break forever
		}
	}
}
Пример #30
0
func main() {
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
	printf = flag.Bool("print", false, "print replies")
	logflag = flag.Bool("log", false, "log stuff")
	compress = flag.Bool("compress", false, "compress replies")
	tsig = flag.String("tsig", "", "use MD5 hmac tsig: keyname:base64")
	var name, secret string
	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()
	if *tsig != "" {
		a := strings.SplitN(*tsig, ":", 2)
		name, secret = dns.Fqdn(a[0]), a[1] // fqdn the name, which everybody forgets...
	}
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	addZoneHandles()
	dns.HandleFunc("authors.bind.", dns.HandleAuthors)
	dns.HandleFunc("authors.server.", dns.HandleAuthors)
	dns.HandleFunc("version.bind.", dns.HandleVersion)
	dns.HandleFunc("version.server.", dns.HandleVersion)
	go serve("tcp", name, secret)
	go serve("udp", name, secret)
	go handleHTTP()
	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
forever:
	for {
		select {
		case s := <-sig:
			fmt.Printf("Signal (%d) received, stopping\n", s)
			break forever
		}
	}
}