コード例 #1
0
func echoServer(Address *string, Message *string) {
	var c net.PacketConn
	var err error

	c, err = net.ListenPacket("sctp", *settings.Address)

	if err != nil {
		log.Printf("Error listening: %v", err)
		os.Exit(-1)
	}
	defer c.Close()

	for {
		msg := make([]byte, 2048)
		log.Printf("Listening on %s", *settings.Address)
		_, addr, err := c.ReadFrom(msg)
		if err != nil {
			log.Printf("Error: %v ", err)
			break
		}
		fmt.Println("Message: " + string(msg))
		c.WriteTo(msg, addr)
	}

}
コード例 #2
0
ファイル: reuse_test.go プロジェクト: uin57/frontd
func packetEcho(c net.PacketConn) {
	defer c.Close()
	buf := make([]byte, 65536)
	for {
		n, addr, err := c.ReadFrom(buf)
		if err != nil {
			return
		}
		if _, err := c.WriteTo(buf[:n], addr); err != nil {
			return
		}
	}
}
コード例 #3
0
ファイル: udp_test.go プロジェクト: dcosson/golog
func runUdpReader(c net.PacketConn, msgChan chan<- string) {
	var buf [4096]byte
	var rcvd string = ""
	for {
		n, _, err := c.ReadFrom(buf[0:])
		if err != nil || n == 0 {
			break
		}
		rcvd += string(buf[0:n])
	}

	msgChan <- rcvd
	c.Close()
}
コード例 #4
0
ファイル: receiver.go プロジェクト: RangelReale/gostatsd
// Receive accepts incoming datagrams on c and calls r.Handler.HandleMetric() for each line in the
// datagram that successfully parses in to a Metric
func (r *MetricReceiver) Receive(c net.PacketConn) error {
	defer c.Close()

	msg := make([]byte, 1024)
	for {
		nbytes, addr, err := c.ReadFrom(msg)
		if err != nil {
			log.Printf("%s", err)
			continue
		}
		buf := make([]byte, nbytes)
		copy(buf, msg[:nbytes])
		go r.handleMessage(addr, buf)
	}
	panic("not reached")
}
コード例 #5
0
ファイル: server.go プロジェクト: Tsingson1988/arp
// Serve accepts incoming connections ARP requests on net.PacketConn p,
// creating a new goroutine for each.
//
// The service goroutine reads requests, generates the appropriate Request and
// ResponseSender values, then calls s.Handler to handle the request.
func (s *Server) Serve(p net.PacketConn) error {
	defer p.Close()

	// Loop and read requests until exit
	buf := make([]byte, 128)
	for {
		n, addr, err := p.ReadFrom(buf)
		if err != nil {
			// Treat EOF as an exit signal
			if err == io.EOF {
				return nil
			}

			return err
		}

		c := s.newConn(p, addr.(*raw.Addr), n, buf)
		go c.serve()
	}
}
コード例 #6
0
func echoServer(Address *string, Message *string) {
	var c net.PacketConn
	var err error

	c, err = net.ListenPacket("sctp", *settings.Address)

	if err != nil {
		log.Printf("Error listening: %v", err)
		os.Exit(-1)
	}
	defer c.Close()
	log.Printf("Listening on %s", *settings.Address)

	msg := make([]byte, 2048)
	for {
		_, _, err := c.ReadFrom(msg)
		if err != nil {
			log.Printf("Error: %v ", err)
			break
		}
	}

}
コード例 #7
0
ファイル: syslog_test.go プロジェクト: pjump/gcc
func runPktSyslog(c net.PacketConn, done chan<- string) {
	var buf [4096]byte
	var rcvd string
	ct := 0
	for {
		var n int
		var err error

		c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
		n, _, err = c.ReadFrom(buf[:])
		rcvd += string(buf[:n])
		if err != nil {
			if oe, ok := err.(*net.OpError); ok {
				if ct < 3 && oe.Temporary() {
					ct++
					continue
				}
			}
			break
		}
	}
	c.Close()
	done <- rcvd
}
コード例 #8
0
		origin := []string{"test-origin"}

		BeforeEach(func() {
			var err error
			udpListener, err = net.ListenPacket("udp4", ":3457")
			Expect(err).ToNot(HaveOccurred())

			go listenForEvents(origin)
			dropsonde.Initialize("localhost:3457", origin...)
			sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter())
			batcher := metricbatcher.New(sender, 100*time.Millisecond)
			metrics.Initialize(sender, batcher)
		})

		AfterEach(func() {
			udpListener.Close()
		})

		It("emits HTTP client/server events", func() {
			httpListener, err := net.Listen("tcp", "localhost:0")
			Expect(err).ToNot(HaveOccurred())
			defer httpListener.Close()
			httpHandler := dropsonde.InstrumentedHandler(FakeHandler{})
			go http.Serve(httpListener, httpHandler)

			_, err = http.Get("http://" + httpListener.Addr().String())
			Expect(err).ToNot(HaveOccurred())

			metrics.SendValue("TestMetric", 0, "")
			metrics.IncrementCounter("TestIncrementCounter")
			metrics.BatchIncrementCounter("TestBatchedCounter")
コード例 #9
0
	BeforeEach(func() {
		testDoppler, _ = net.ListenPacket("udp", "localhost:3457")

		node := storeadapter.StoreNode{
			Key:   "/healthstatus/doppler/z1/0",
			Value: []byte("localhost"),
		}

		adapter := etcdRunner.Adapter()
		adapter.Create(node)
		adapter.Disconnect()
	})

	AfterEach(func() {
		testDoppler.Close()
	})

	It("forwards hmac signed messages to a healthy doppler server", func(done Done) {
		type signedMessage struct {
			signature []byte
			message   []byte
		}

		defer close(done)

		originalMessage := basicValueMessage()
		expectedEnvelope := addDefaultTags(basicValueMessageEnvelope())
		expectedMessage, _ := proto.Marshal(expectedEnvelope)

		mac := hmac.New(sha256.New, []byte("shared_secret"))
コード例 #10
0
	BeforeEach(func() {
		fakeDoppler = eventuallyListensForUDP("localhost:3457")

		node := storeadapter.StoreNode{
			Key:   "/healthstatus/doppler/z1/doppler_z1/0",
			Value: []byte("localhost"),
		}

		adapter := etcdRunner.Adapter()
		adapter.Create(node)
		adapter.Disconnect()
		time.Sleep(200 * time.Millisecond) // FIXME: wait for metron to discover the fake doppler ... better ideas welcome
	})

	AfterEach(func() {
		fakeDoppler.Close()
	})

	Context("with a fake statsd client", func() {
		It("outputs gauges as signed value metric messages", func(done Done) {
			connection, err := net.Dial("udp", "localhost:51162")
			Expect(err).ToNot(HaveOccurred())
			defer connection.Close()

			statsdmsg := []byte("fake-origin.test.gauge:23|g\nfake-origin.sampled.gauge:23|g|@0.2")
			_, err = connection.Write(statsdmsg)
			Expect(err).ToNot(HaveOccurred())

			expected := basicValueMetric("test.gauge", 23, "gauge")
			Eventually(getValueMetric).Should(Equal(expected))
コード例 #11
0
		BeforeEach(func() {
			var err error
			logMessages = nil
			udpConn, err = net.ListenPacket("udp4", ":0")
			Expect(err).ToNot(HaveOccurred())

			go listenForLogs()
			udpAddr := udpConn.LocalAddr().(*net.UDPAddr)
			dropsonde.Initialize(fmt.Sprintf("localhost:%d", udpAddr.Port), origin...)
			sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter())
			batcher := metricbatcher.New(sender, 100*time.Millisecond)
			metrics.Initialize(sender, batcher)
		})

		AfterEach(func() {
			udpConn.Close()
		})

		It("sends dropped error message for messages which are just under 64k and don't fit in UDP packet", func() {
			logSender := log_sender.NewLogSender(dropsonde.AutowiredEmitter(), time.Second, loggertesthelper.Logger())

			const length = 64*1024 - 1
			reader := strings.NewReader(strings.Repeat("s", length) + "\n")
			logSender.ScanErrorLogStream("someId", "app", "0", reader)

			Eventually(func() []*events.LogMessage {
				logLock.RLock()
				defer logLock.RUnlock()
				return logMessages
			}).Should(HaveLen(1))
コード例 #12
0
ファイル: main_suite_test.go プロジェクト: cloudfoundry/bbs
		EncryptionKeys:         []string{"label:key"},
		ActiveKeyLabel:         "label",
		ConvergeRepeatInterval: time.Hour,
	}
	storeClient = etcd.NewStoreClient(etcdClient)
	consulHelper = test_helpers.NewConsulHelper(logger, consulClient)
})

var _ = AfterEach(func() {
	ginkgomon.Kill(bbsProcess)

	// Make sure the healthcheck server is really gone before trying to start up
	// the bbs again in another test.
	Eventually(func() error {
		conn, err := net.Dial("tcp", bbsHealthAddress)
		if err == nil {
			conn.Close()
			return nil
		}

		return err
	}).Should(HaveOccurred())

	auctioneerServer.Close()
	testMetricsListener.Close()
	Eventually(testMetricsChan).Should(BeClosed())

	sqlRunner.Reset()
})
コード例 #13
0
ファイル: listener.go プロジェクト: sunnyboy00/gomnet
// receives packets from the receive loop and dispatches them
// to their corresponding connections
func processLoop(c net.PacketConn, l *listener, rld *receiveLoopData, pld *processLoopData) {

	var (
		quit        bool
		wg          = new(sync.WaitGroup)
		tq          = newTimerQueue()
		connections = struct {
			sync.RWMutex
			M map[uint32]*connection
		}{
			M: make(map[uint32]*connection),
		}
	)

	// keep a refcount to `c` for ourselves
	wg.Add(1)
	defer wg.Done()

	// wait for all pending connections, then close the socket
	go func() {
		wg.Wait()
		c.Close()
		tq.Close()
	}()

	// generate a new key for cookies
	cookieKey := make([]byte, sha1.Size)
	if _, err := crand.Read(cookieKey); err != nil {
		l.L.Lock()
		l.err = fmt.Errorf("Failed to generate cookie secret: %v", err)
		l.L.Unlock()
		l.Broadcast()
		return
	}

	sig := hmac.New(sha1.New, cookieKey)

	// generate addler32(localaddr)
	var localAddrSum [4]byte
	binary.LittleEndian.PutUint32(localAddrSum[:], adler32.Checksum([]byte(c.LocalAddr().String())))

	shouldWait := func() bool {
		waitOnConnections := pld.rejectNewConnections && pld.remainingConnections == 0
		return pld.err == nil && len(pld.Q) == 0 && !waitOnConnections
	}

	var packets []processLoopPacket

	for !quit {
		// wait for a packet to become available
		pld.L.Lock()
		for shouldWait() {
			pld.Wait()
		}
		rejectNewConnections := pld.rejectNewConnections
		pldErr := pld.err
		quit = pldErr != nil
		packets, pld.Q = pld.Q, packets[:0]
		remainingConnections := pld.remainingConnections
		pld.L.Unlock()

		if rejectNewConnections && remainingConnections == 0 {
			quit = true
		}

		// process packets
		for ii := range packets {
			buffer, addr := packets[ii].D, packets[ii].A

			switch PacketType(buffer[0]) {
			case PacketInit:
				// are we accepting new connections?
				if rejectNewConnections {
					continue
				}

				// verify length
				const MinInitPacketLength = 9
				if len(buffer) < MinInitPacketLength {
					continue
				}

				// verify protocol magic
				if !bytes.Equal(buffer[1:5], protocolMagic) {
					continue
				}

				// verify version
				if buffer[5] != version1 {
					sendAbort(c, addr, buffer[6:9])
					continue
				}

				var outgoing [32]byte
				now := time.Now()
				outgoing[0] = byte(PacketCookie)
				if _, err := crand.Read(outgoing[1:4]); err != nil {
					return
				}
				copy(outgoing[4:7], buffer[6:9])
				outgoing[7] = version1
				binary.LittleEndian.PutUint32(outgoing[8:12], uint32(now.Add(5*time.Second).Unix()+1))

				sig.Reset()
				sig.Write(outgoing[1:12])
				sig.Write(localAddrSum[:])
				sig.Sum(outgoing[1:12])
				c.WriteTo(outgoing[:], addr)

			case PacketCookieEcho:

				// are we accepting new connections
				if rejectNewConnections {
					continue
				}

				// verify length
				const CookieEchoPacketLength = 32
				if len(buffer) != CookieEchoPacketLength {
					continue
				}

				// verify signature
				sig.Reset()
				sig.Write(buffer[1:12])
				sig.Write(localAddrSum[:])
				if !hmac.Equal(sig.Sum(nil), buffer[12:]) {
					continue
				}

				// verify version
				if buffer[7] != version1 {
					sendAbort(c, addr, buffer[1:4])
					continue
				}

				// vetify timeout
				now := time.Now()
				if time.Unix(int64(binary.LittleEndian.Uint32(buffer[8:12])), 0).Before(now) {
					sendAbort(c, addr, buffer[1:4])
					continue
				}

				// decode connection tag to uin32
				tagId := binary.LittleEndian.Uint32(buffer[3:7]) >> 8

				connections.RLock()
				_, ok := connections.M[tagId]
				connections.RUnlock()
				// create new connection
				if !ok {

					// create connection
					wg.Add(1)
					connections.Lock()
					conn := newConnection(c, addr, tq, buffer[1:4], func() {
						connections.Lock()
						delete(connections.M, tagId)
						connections.Unlock()

						wg.Done()

						pld.L.Lock()
						pld.remainingConnections--
						remain := pld.remainingConnections
						pld.L.Unlock()

						if remain == 0 {
							pld.Signal()
						}
					})

					connections.M[tagId] = conn
					connections.Unlock()

					pld.L.Lock()
					pld.remainingConnections++
					pld.L.Unlock()

					l.L.Lock()
					l.pending = append(l.pending, conn)
					l.L.Unlock()
					l.Signal()
				}

				// send COOKIE-ACK
				var outgoing [4]byte
				outgoing[0] = byte(PacketCookieAck)
				copy(outgoing[1:4], buffer[1:4])
				c.WriteTo(outgoing[:], addr)

			default:
				// parse connection tag
				tagId := binary.LittleEndian.Uint32(buffer[0:4]) >> 8
				connections.RLock()
				conn, ok := connections.M[tagId]
				connections.RUnlock()

				// discard packets addressed to unknown connections
				if !ok {
					sendAbort(c, addr, buffer[1:4])
					continue
				}

				// copy the packet data so we can reuse the buffer
				p := NewPacket(len(buffer))
				copy(p.D, buffer)

				// queue the packet onto the connection
				conn.L.Lock()
				conn.Incoming = append(conn.Incoming, p)
				conn.L.Unlock()
				conn.Signal()
			}
		}

		// return the packet to the receive loop
		rld.L.Lock()
		for ii := range packets {
			rld.buffers = append(rld.buffers, packets[ii].D)
		}
		rld.L.Unlock()
		rld.Signal()

		// if we were signaled to quit, terminate existing connections
		if pldErr != nil {
			connections.Lock()
			m := connections.M
			connections.M = make(map[uint32]*connection)
			connections.Unlock()

			for _, c := range m {
				c.closeWithError(pldErr)
			}
		}
	}
}
コード例 #14
0
package experiment_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"net"
	"testing"
)

func TestExperiment(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Experiment Suite")
}

var fakeMetron net.PacketConn
var _ = BeforeSuite(func() {
	var err error
	fakeMetron, err = net.ListenPacket("udp4", ":51161")
	if err != nil {
		panic(err)
	}
})

var _ = AfterSuite(func() {
	fakeMetron.Close()
})
コード例 #15
0
ファイル: server.go プロジェクト: lixin9311/simplevpn
func serveUDP(conf *Config, localHWAddr tap.HwAddr) error {
	cipher, err := ss.NewCipher(conf.User.Method, conf.User.Password)
	if err != nil {
		return err
	}
	test := net.ParseIP(conf.Server.Ip)
	v6 := false
	if test.To4() == nil {
		v6 = true
	}
	var addr string
	if v6 {
		addr = fmt.Sprintf("[%s]:%d", conf.Server.Ip, conf.Server.Port)
	} else {
		addr = fmt.Sprintf("%s:%d", conf.Server.Ip, conf.Server.Port)
	}

	ln, err := net.ListenPacket("udp", addr)
	if err != nil {
		return err
	}
	var listener net.PacketConn
	if *enc {
		listener = ln
	} else {
		listener = ss.NewPacketConn(ln, cipher.Copy())
	}
	defer listener.Close()
	log.Printf("Server inited, listen on : %s:%d.\n", conf.Server.Ip, conf.Server.Port)
	for {
		buf := make([]byte, MaxPacketSize)
		n, addr, err := listener.ReadFrom(buf)
		if err != nil {
			log.Println("[server]: Failed to read:", err)
		}
		if v, ok := hub.Packet_clients[addr]; !ok {
			auth := new(Auth)
			var mac tap.HwAddr
			err = auth.Unmarshal(buf[:n])
			if err != nil {
				log.Println("[Read]: Failed to Unmarshal data:", err)
			}
			if auth.Type != Auth_Hello {
				log.Println("[Read]: Unexpected message type.")
			}
			copy(mac[:], auth.MacAddr[:6])
			response := new(Auth)
			response.Type = Auth_Welcome
			response.IP = "192.168.1.101/24"
			response.DNS = "8.8.8.8"
			response.MTU = int32(1500)
			response.GateWay = "192.168.1.1"
			response.MacAddr = localHWAddr[:]
			data, err := response.Marshal()
			if err != nil {
				log.Println("Faield to encode config:", err)
			}
			client := &Client{MacAddr: mac, PacketConn: listener, is_packet: true, input: make(chan []byte, 8), remoteAddr: addr}
			client.Write(data)
			hub.Connect(client)
		} else {
			v.input <- buf[:n]
		}
	}
}
コード例 #16
0
func stopServer(in net.PacketConn) {
	in.Close()
}
コード例 #17
0
		Context("when the agent is listening", func() {

			var agentListener net.PacketConn

			BeforeEach(func() {
				var err error
				agentListener, err = net.ListenPacket("udp4", "")
				Expect(err).ToNot(HaveOccurred())

				udpEmitter, err = emitter.NewUdpEmitter(agentListener.LocalAddr().String())
				Expect(err).ToNot(HaveOccurred())
			})

			AfterEach(func() {
				agentListener.Close()
			})

			It("should send the data", func(done Done) {
				err := udpEmitter.Emit(testData)
				Expect(err).ToNot(HaveOccurred())

				buffer := make([]byte, 4096)
				readCount, _, err := agentListener.ReadFrom(buffer)
				Expect(err).ToNot(HaveOccurred())
				Expect(buffer[:readCount]).To(Equal(testData))

				close(done)
			})
		})
コード例 #18
0
ファイル: gomul.go プロジェクト: 42wim/gomul
func main() {
	var flagGroup, flagIP string
	var flagIndex int
	var c net.PacketConn
	var p6 *ipv6.PacketConn
	var p4 *ipv4.PacketConn

	iMap = make(map[string]int)

	flag.BoolVar(&flagList, "li", false, "show available interfaces")
	flag.IntVar(&flagIndex, "interface", 0, "interface to listen on (number)")
	flag.StringVar(&flagGroup, "group", "ff02::42:1 239.42.42.1", "multicast groups to join (space seperated)")
	flag.StringVar(&flagIP, "ip", "", "use interface where the specified ip is bound on")
	flag.Parse()
	if flag.NFlag() < 1 {
		flag.PrintDefaults()
		os.Exit(1)
	}
	if flagList {
		parseInterfaces()
		os.Exit(1)
	}

	parseInterfaces()
	if flagIndex == 0 {
		fmt.Print("searching interface for ip ", flagIP)
		for k, v := range iMap {
			if strings.HasPrefix(k, flagIP) {
				fmt.Println(" using interface", v, "with ip", k)
				flagIndex = v
				break
			}
		}
	}

	fmt.Println("listening on index", flagIndex)
	iface, err := net.InterfaceByIndex(flagIndex)
	if err != nil {
		log.Fatal(err)
	}

	groups := strings.Fields(flagGroup)

	if strings.Contains(flagGroup, ":") {
		c, err = net.ListenPacket("udp6", "[::]:1024")
		if err != nil {
			log.Fatal(err)
		}
		defer c.Close()
		p6 = ipv6.NewPacketConn(c)
	}
	if strings.Contains(flagGroup, ".") {
		c, err = net.ListenPacket("udp4", ":1024")
		if err != nil {
			log.Fatal(err)
		}
		defer c.Close()
		p4 = ipv4.NewPacketConn(c)
	}

	for _, group := range groups {
		IPgroup := net.ParseIP(group)
		if strings.Contains(group, ":") {
			fmt.Println("joining ipv6 group", group)
			if err := p6.JoinGroup(iface, &net.UDPAddr{IP: IPgroup}); err != nil {
				log.Fatal(err)
			}
		} else {
			fmt.Println("joining ipv4 group", group)
			if err := p4.JoinGroup(iface, &net.UDPAddr{IP: IPgroup}); err != nil {
				log.Fatal(err)
			}
		}
	}
	select {}
}