Example #1
0
// receive packets from conn, print them to stdout, and send the address
// of each packet upstream to our master.
// The data packets are assumed to have embedded newlines, which may be
// false.
func packetRecv(conn net.PacketConn, master chan net.Addr) {
	buf := make([]byte, bufsize)
	for {
		var bufStr string

		n, addr, err := conn.ReadFrom(buf[0:])
		if err != nil {
			warnln("error on ReadFrom:", err)
			return
		}

		// TODO: can n ever be 0?
		if dgramhex {
			bufStr = fmt.Sprintf("0x % x\n", buf[:n])
		} else {
			bufStr = fmt.Sprintf("%s", string(buf[:n]))
		}

		if quiet {
			fmt.Printf("%s", bufStr)
		} else {
			fmt.Printf("%s > %s", addr, bufStr)
		}

		// We print packet details before sending the address
		// upstream in case this send blocks.
		master <- addr
	}
}
Example #2
0
func (s *Server) Serve(l net.PacketConn, replyPort int) error {
	var srcAddr *net.UDPAddr
	if s.ServerIP != nil {
		srcAddr = &net.UDPAddr{IP: s.ServerIP}
	}
	buffer := make([]byte, 1500)
	r, err := net.DialUDP("udp", srcAddr, &net.UDPAddr{IP: net.IPv4(255, 255, 255, 255), Port: replyPort})
	if err != nil {
		return err
	}
	defer r.Close()
	for {
		n, _, err := l.ReadFrom(buffer)
		if err != nil {
			return err
		}
		if n < 240 {
			continue
		}
		p := Packet(buffer[:n])
		options := p.ParseOptions()
		msgType := options[OptionDHCPMessageType]
		if len(msgType) != 1 {
			return nil
		}
		// TODO consider more packet validity checks
		if res := s.Handler.ServeDHCP(p, MessageType(msgType[0]), options); res != nil {
			if _, e := r.Write(res); e != nil {
				fmt.Println("Write Error:", e.Error())
			}
		}
	}
	return nil
}
Example #3
0
// Serve messages received on the given packet listener to the srv.Handler.
func (srv *Server) Serve(l net.PacketConn) error {
	maxMessageBytes := DefaultMaxMessageBytes
	if srv.MaxMessageBytes != 0 {
		maxMessageBytes = srv.MaxMessageBytes
	}
	for {
		buf := make([]byte, maxMessageBytes)
		n, peerAddr, err := l.ReadFrom(buf)
		if err != nil {
			return err
		}
		buf = buf[:n]

		go func(buf []byte, peerAddr net.Addr) {
			// At least one router's UPnP implementation has added a trailing space
			// after "HTTP/1.1" - trim it.
			buf = trailingWhitespaceRx.ReplaceAllLiteral(buf, crlf)

			req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(buf)))
			if err != nil {
				log.Printf("httpu: Failed to parse request: %v", err)
				return
			}
			req.RemoteAddr = peerAddr.String()
			srv.Handler.ServeMessage(req)
			// No need to call req.Body.Close - underlying reader is bytes.Buffer.
		}(buf, peerAddr)
	}
}
Example #4
0
File: osc.go Project: kward/go-osc
// ReceivePacket listens for incoming OSC packets and returns the packet and
// client address if one is received.
func (s *Server) ReceivePacket(ctx context.Context, c net.PacketConn) (Packet, net.Addr, error) {
	if deadline, ok := ctx.Deadline(); ok {
		if err := c.SetReadDeadline(deadline); err != nil {
			return nil, nil, err
		}
	}

	go func() {
		select {
		// case <-time.After(200 * time.Millisecond):
		// 	log.Println("Overslept.")
		case <-ctx.Done():
			log.Println(ctx.Err())
		}
	}()

	data := make([]byte, 65535)
	var n, start int
	n, addr, err := c.ReadFrom(data)
	if err != nil {
		return nil, nil, err
	}
	pkt, err := readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n)
	return pkt, addr, err
}
Example #5
0
func WriteFile(w io.Writer, conn net.PacketConn, remoteAddress net.Addr, packet []byte, tid uint16) (int, net.Addr, error) {
	// Read data packet
	n, replyAddr, err := conn.ReadFrom(packet)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error reading packet: %v", err)
	}

	opcode, err := GetOpCode(packet)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error getting opcode: %v", err)
	}
	if opcode != OpDATA {
		return n, replyAddr, fmt.Errorf("Expected DATA packet, got %v\n", opcode)
	}

	packetTID := binary.BigEndian.Uint16(packet[2:4])
	if packetTID != tid {
		SendError(5, "Unknown transfer id", conn, remoteAddress)
		return n, replyAddr, fmt.Errorf("Expected TID %d, got %d\n", tid, packetTID)
	}

	// Write data to disk
	_, err = w.Write(packet[4:n])
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error writing: %v", err)
	}

	ack := CreateAckPacket(tid)
	_, err = conn.WriteTo(ack, replyAddr)
	if err != nil {
		return n, replyAddr, fmt.Errorf("Error writing ACK packet: %v", err)
	}

	return n, replyAddr, nil
}
Example #6
0
// sends an ABORT packet to the specified peer
func sendAbort(c net.PacketConn, addr net.Addr, tag []byte) {
	p := NewPacket(4)
	p.D[0] = byte(PacketAbort)
	copy(p.D[1:4], tag)
	c.WriteTo(p.D, addr)
	p.Free()
}
Example #7
0
func (s *Server) goReceiveDatagrams(packetconn net.PacketConn) {
	s.wait.Add(1)
	go func() {
		defer s.wait.Done()
		for {
			buf := s.datagramPool.Get().([]byte)
			n, addr, err := packetconn.ReadFrom(buf)
			if err == nil {
				// Ignore trailing control characters and NULs
				for ; (n > 0) && (buf[n-1] < 32); n-- {
				}
				if n > 0 {
					var address string
					if addr != nil {
						address = addr.String()
					}
					s.datagramChannel <- DatagramMessage{buf[:n], address}
				}
			} else {
				// there has been an error. Either the server has been killed
				// or may be getting a transitory error due to (e.g.) the
				// interface being shutdown in which case sleep() to avoid busy wait.
				opError, ok := err.(*net.OpError)
				if (ok) && !opError.Temporary() && !opError.Timeout() {
					return
				}
				time.Sleep(10 * time.Millisecond)
			}
		}
	}()
}
Example #8
0
func UDPReader(conn net.PacketConn) {
	obytes := make([]byte, 64*1024)
	start := time.Now()
	var bcount, count time.Duration

	fmt.Printf("UDP:%s -> REDIS:%s@%s.\n", *listen, key, *redis)

	for {
		bytes := obytes
		n, _, err := conn.ReadFrom(bytes)

		if err != nil {
			fmt.Println(err)
			continue
		}

		count += 1
		bcount += time.Duration(n)

		now := time.Now()
		diff := now.Sub(start)

		if diff > 1e9 {
			fmt.Printf(
				"bps = %s, pps = %d.\n", gutils.FormatBytes(float64(bcount)),
				count,
			)
			start = now
			bcount, count = 0, 0
		}
	}
}
Example #9
0
func test1(conn net.PacketConn, addr net.Addr, softwareName string) (*packet, net.Addr, bool, *Host, error) {
	packet, err := sendBindingReq(conn, addr, softwareName)
	if err != nil {
		return nil, nil, false, nil, err
	}
	if packet == nil {
		return nil, nil, false, nil, nil
	}

	// RFC 3489 doesn't require the server return XOR mapped address.
	hostMappedAddr := packet.xorMappedAddr()
	if hostMappedAddr == nil {
		hostMappedAddr = packet.mappedAddr()
		if hostMappedAddr == nil {
			return nil, nil, false, nil, errors.New("No mapped address.")
		}
	}

	identical := isLocalAddress(conn.LocalAddr().String(), hostMappedAddr.TransportAddr())

	hostChangedAddr := packet.changedAddr()
	if hostChangedAddr == nil {
		return packet, nil, identical, hostMappedAddr, nil
	}
	changedAddrStr := hostChangedAddr.TransportAddr()
	changedAddr, err := net.ResolveUDPAddr("udp", changedAddrStr)
	if err != nil {
		return nil, nil, false, nil, errors.New("Failed to resolve changed address.")
	}
	return packet, changedAddr, identical, hostMappedAddr, nil
}
Example #10
0
func getack(conn net.PacketConn, srcport layers.TCPPort, dstip string) (ack uint32, err error) {
	for {
		b := make([]byte, 4096)
		log.Println("reading from conn")
		var n int
		var addr net.Addr
		n, addr, err = conn.ReadFrom(b)
		if err != nil {
			log.Println("reading..", err)
			return
		} else if addr.String() == dstip {
			// Decode a packet
			packet := gopacket.NewPacket(b[:n], layers.LayerTypeTCP, gopacket.Default)
			// Get the TCP layer from this packet
			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				if tcp.DstPort == srcport {
					if tcp.SYN && tcp.ACK {
						ack = tcp.Seq
					} else {
						err = errors.New("Port is CLOSED")
					}
					return
				}
			}
		} else {
			err = errors.New("Got packet not matching addr")
		}
	}
	return
}
Example #11
0
func udpServer(conn net.PacketConn) {
	for {
		bytes := make([]byte, 512)
		n, _, err := conn.ReadFrom(bytes)

		if err != nil {
			fmt.Println(err)
			continue
		}

		bytes = bytes[:n]

		fmt.Println(bytes)

		var job Work
		err = json.Unmarshal(bytes, &job)

		if err != nil {
			fmt.Println(err)
		}

		if job.IP == "" {
			fmt.Println("UDP: got bad json, no IP supplied.", job.String())
			continue
		}

		workers <- job

		fmt.Printf("UDP: %s.\n", job.String())
	}
}
Example #12
0
func handleHandshake(conn net.PacketConn) error {
	packet := make([]byte, common.MaxPacketSize)

	n, remoteAddr, err := conn.ReadFrom(packet)
	if err != nil {
		return fmt.Errorf("Error reading from connection: %v", err)
	}
	if n == common.MaxPacketSize {
		return fmt.Errorf("Packet too big: %d bytes", n)
	}

	log.Printf("Request from %v", remoteAddr)
	req, err := common.ParseRequestPacket(packet)
	if err != nil {
		return fmt.Errorf("Error parsing request packet: %v", err)
	}

	if !acceptedMode(req.Mode) {
		return fmt.Errorf("Unknown mode: %s", req.Mode)
	}

	handler, ok := handlerMapping[req.OpCode]
	if !ok {
		return fmt.Errorf("No handler for OpCode: %d\n", req.OpCode)
	}
	go handler.serve(remoteAddr, req.Filename)

	return nil
}
Example #13
0
func serveTestUdp(in net.PacketConn, pdu_txt string, waiter *sync.WaitGroup) {

	defer func() {
		waiter.Done()
	}()

	var byteArray [10000]byte

	for {
		_, addr, err := in.ReadFrom(byteArray[:])
		if nil != err {
			fmt.Println("[test] read failed", err.Error())
			break
		}

		fmt.Println("[test] recv ok, send at next step")

		bin, err := hex.DecodeString(pdu_txt)
		if nil != err {
			fmt.Println("[test]", err.Error())
		} else {
			if _, err = in.WriteTo(bin, addr); nil != err {
				fmt.Println("[test] write failed", err.Error())
				break
			}
		}
	}
}
func sendPacket(conn net.PacketConn, destination *net.IPAddr, payload []byte, seq int) {
	packet := make([]byte, len(payload)+8)
	packet[0] = 8
	packet[1] = 0
	packet[4] = uint8(os.Getpid() >> 8)
	packet[5] = uint8(os.Getpid() & 0xff)
	packet[6] = uint8(seq >> 8)
	packet[7] = uint8(seq & 0xff)
	copy(packet[8:], payload)

	cklen := len(packet)
	cksum := uint32(0)
	for i := 0; i < cklen-1; i += 2 {
		cksum += uint32(packet[i+1])<<8 | uint32(packet[i])
	}
	if cklen&1 == 1 {
		cksum += uint32(packet[cklen-1])
	}
	cksum = (cksum >> 16) + (cksum & 0xffff)
	cksum = cksum + (cksum >> 16)

	packet[2] ^= uint8(^cksum & 0xff)
	packet[3] ^= uint8(^cksum >> 8)

	_, err := conn.WriteTo(packet, destination)
	if err != nil {
		panic(err)
	}
}
Example #15
0
File: server.go Project: inz/deis
func (s *Server) receiver(c net.PacketConn) {
	//q := (chan<- Message)(s.q)
	buf := make([]byte, 1024)
	for {
		n, _, err := c.ReadFrom(buf)
		if err != nil {
			if !s.shutdown {
				s.l.Fatalln("Read error:", err)
			}
			return
		}
		pkt := buf[:n]

		p := rfc3164.NewParser(pkt)
		if err := p.Parse(); err != nil {
			log.Println(err)
		}
		log := p.Dump()

		m := &Message{
			Time:      time.Now(),
			Priority:  log["priority"].(syslog.Priority),
			Timestamp: log["timestamp"].(time.Time),
			Hostname:  log["hostname"].(string),
			Tag:       log["tag"].(string),
			Content:   log["content"].(string),
		}

		s.passToHandlers(m)
	}
}
Example #16
0
func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) {
	if _, err := c.WriteTo(wb, dst); err != nil {
		b.Fatal(err)
	}
	if _, _, err := c.ReadFrom(rb); err != nil {
		b.Fatal(err)
	}
}
Example #17
0
func MGCPCommandRespondEcho(msg MGCPCommand, conn net.PacketConn, addr net.Addr) {
	str_reply := fmt.Sprintf("%s", msg)

	if _, err := conn.WriteTo([]byte(str_reply), addr); err != nil {
		fmt.Println(err)
	}

}
Example #18
0
func SendError(code uint16, message string, conn net.PacketConn, remoteAddress net.Addr) error {
	errPacket := CreateErrorPacket(0, message)
	_, err := conn.WriteTo(errPacket, remoteAddress)
	if err != nil {
		return fmt.Errorf("Error writing error packet: %v", err)
	}
	return nil
}
Example #19
0
func (p *Packet) Send(c net.PacketConn, addr net.Addr) error {
	buf, err := p.Encode()
	if err != nil {
		return err
	}

	_, err = c.WriteTo(buf, addr)
	return err
}
Example #20
0
func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, dst net.Addr) {
	if _, err := c.WriteTo([]byte("HELLO-R-U-THERE"), dst); err != nil {
		b.Fatalf("net.PacketConn.WriteTo failed: %v", err)
	}
	rb := make([]byte, 128)
	if _, _, err := c.ReadFrom(rb); err != nil {
		b.Fatalf("net.PacketConn.ReadFrom failed: %v", err)
	}
}
Example #21
0
func (p *Packet) Send(c net.PacketConn, addr net.Addr) error {
	var buf [4096]byte
	n, _, err := p.Encode(buf[:])
	if err != nil {
		return err
	}

	n, err = c.WriteTo(buf[:n], addr)
	return err
}
Example #22
0
func receiver(c net.PacketConn) {
	b := make([]byte, 1500)
	for {
		n, peer, err := c.ReadFrom(b)
		if err != nil {
			log.Println(err)
			continue
		}
		log.Printf("%v bytes received from %v\n", n, peer)
	}
}
Example #23
0
func runSyslog(c net.PacketConn, done chan<- string) {
	var buf [4096]byte
	var rcvd string = ""
	for {
		n, _, err := c.ReadFrom(&buf)
		if err != nil || n == 0 {
			break
		}
		rcvd += string(buf[0:n])
	}
	done <- rcvd
}
Example #24
0
File: rtp.go Project: hinike/rtsp
func (s *Session) HandleRtcpConn(conn net.PacketConn) {
	buf := make([]byte, 4096)
	for {
		n, _, err := conn.ReadFrom(buf)
		if err != nil {
			panic(err)
		}
		cpy := make([]byte, n)
		copy(cpy, buf)
		go s.handleRtcp(cpy)
	}
}
Example #25
0
func newConnection(c net.PacketConn, addr net.Addr, tq *timerQueue, tag []byte, closed func()) *connection {
	conn := &connection{
		Cond:      sync.Cond{L: new(sync.Mutex)},
		addr:      addr,
		localAddr: c.LocalAddr(),
		closeWait: make(chan struct{}),
	}

	var tag3 [3]byte
	copy(tag3[:], tag)
	go conn.proc(c, tq, tag3, closed)
	return conn
}
Example #26
0
func MGCPCommandRespondErr(msg MGCPCommand, conn net.PacketConn, addr net.Addr) {
	var reply MGCPResponse
	reply.ResponseCode = "504"
	reply.TransID = msg.TransID
	reply.ResponseStr = "ERR"

	str_reply := fmt.Sprintf("%s", reply)

	if _, err := conn.WriteTo([]byte(str_reply), addr); err != nil {
		fmt.Println(err)
	}

}
Example #27
0
func runSyslog(c net.PacketConn, done chan<- string) {
	var buf [4096]byte
	var rcvd string
	for {
		c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
		n, _, err := c.ReadFrom(buf[:])
		rcvd += string(buf[:n])
		if err != nil {
			break
		}
	}
	done <- rcvd
}
Example #28
0
func (s *Server) readUDP(data net.PacketConn) ([]byte, net.Addr, error) {
	if s.BufferSize < 1 {
		s.BufferSize = DefaultBufferSize
	}

	buf := make([]byte, s.BufferSize)
	count, addr, err := data.ReadFrom(buf)

	if err != nil {
		return nil, nil, err
	}

	return buf[0:count], addr, nil
}
Example #29
0
func (p *Packet) SendAndWait(c net.PacketConn, addr net.Addr) (pac *Packet, err error) {
	var buf [4096]byte
	err = p.Send(c, addr)
	if err != nil {
		return nil, err
	}
	n, addr, err := c.ReadFrom(buf[:])
	b := buf[:n]
	pac = new(Packet)
	pac.Code = PacketCode(b[0])
	pac.Identifier = b[1]
	copy(pac.Authenticator[:], b[4:20])
	return pac, nil
}
Example #30
0
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()
}