// 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 } }
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 }
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 }
// 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) } }
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) } } }() }
// RFC 3489: Clients SHOULD retransmit the request starting with an interval // of 100ms, doubling every retransmit until the interval reaches 1.6s. // Retransmissions continue with intervals of 1.6s until a response is // received, or a total of 9 requests have been sent. func (v *packet) send(conn net.PacketConn, addr net.Addr) (*packet, error) { timeout := 100 for i := 0; i < 9; i++ { length, err := conn.WriteTo(v.bytes(), addr) if err != nil { return nil, err } if length != len(v.bytes()) { return nil, errors.New("Error in sending data.") } conn.SetReadDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond)) if timeout < 1600 { timeout *= 2 } packetBytes := make([]byte, 1024) length, _, err = conn.ReadFrom(packetBytes) if err == nil { return newPacketFromBytes(packetBytes[0:length]) } else { if !err.(net.Error).Timeout() { return nil, err } } } return nil, nil }
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 }
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 } } }
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 }
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) } }
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()) } }
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) } }
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 } } } }
// 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 }
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) } }
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) } }
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) } }
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 }
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) } }
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 }
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 } } }
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 }
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 }
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() }
func handleClient(conn net.PacketConn) { var buf [512]byte _, addr, err := conn.ReadFrom(buf[0:]) if err != nil { return } daytime := time.Now() msg := fmt.Sprint(daytime) conn.WriteTo([]byte(msg), addr) }
func (s *Server) receiver(c net.PacketConn) { // make packet buffer the same size as logspout buf := make([]byte, 1048576) for { n, _, err := c.ReadFrom(buf) if err != nil { if !s.shutdown { s.l.Fatalln("Read error:", err) } return } // pass along the incoming syslog message s.passToHandlers(&Message{string(buf[:n])}) } }
// readFromConnection retrieves OSC packets. func (s *Server) readFromConnection(c net.PacketConn) (packet Packet, err error) { if s.ReadTimeout != 0 { err = c.SetReadDeadline(time.Now().Add(s.ReadTimeout)) if err != nil { return nil, err } } data := make([]byte, 65535) var n, start int n, _, err = c.ReadFrom(data) if err != nil { return nil, err } return s.readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n) }
func readDeaLoggingAgentOutputConn(connection net.PacketConn, m *messageHolder) { readBuffer := make([]byte, 65535) //buffer with size = max theoretical UDP size goRoutineSpawned.Done() for { readCount, _, err := connection.ReadFrom(readBuffer) if err != nil { return } readData := make([]byte, readCount) //pass on buffer in size only of read data copy(readData, readBuffer[:readCount]) envelope := UnmarshalMessage(readData) m.Lock() m.messages = append(m.messages, envelope) m.Unlock() } }
// 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") }
// handleUpdateUDP listens on conn, parses data into Versions and sends them to `updates` chan. func handleUpdateUDP(conn net.PacketConn, updates chan<- version.Version) { for { b := make([]byte, 2048) n, addr, err := conn.ReadFrom(b) if err != nil { l.Print("ERROR: handleUpdateUDP: ReadFrom:\n ", err) continue } ip := addr.(*net.UDPAddr).IP v, err := version.ParsePacket(ip.String(), b[:n]) if err != nil { l.Print("ERROR: handleUpdateUDP: parsePacket:\n ", err, "\n packet:", string(b[:n])) continue } updates <- v } }