Ejemplo n.º 1
0
Archivo: main.go Proyecto: hycxa/gonet
//----------------------------------------------- handle cooldown request
func handleClient(conn *net.UDPConn) {
	// init receive buffer
	config := cfg.Get()
	maxchan, e := strconv.Atoi(config["stats_max_queue_size"])
	if e != nil {
		maxchan = DEFAULT_MAX_QUEUE
		log.Println("cannot parse stats_max_queue_size from config", e)
	}

	ch := make(chan []byte, maxchan)
	defer close(ch)

	go StatsAgent(ch, conn)

	// loop receiving
	for {
		// udp receive buffer, max 512 packet
		data := make([]byte, 512)
		n, addr, err := conn.ReadFromUDP(data)
		if err != nil {
			log.Println("read udp failed", n, addr, err)
			continue
		}

		ch <- data[:n]
	}
}
Ejemplo n.º 2
0
func (router *Router) udpReader(conn *net.UDPConn, po PacketSink) {
	defer conn.Close()
	dec := NewEthernetDecoder()
	handleUDPPacket := router.handleUDPPacketFunc(dec, po)
	buf := make([]byte, MaxUDPPacketSize)
	for {
		n, sender, err := conn.ReadFromUDP(buf)
		if err == io.EOF {
			return
		} else if err != nil {
			log.Println("ignoring UDP read error", err)
			continue
		} else if n < NameSize {
			continue // TODO something different?
		} else {
			name := PeerNameFromBin(buf[:NameSize])
			packet := make([]byte, n-NameSize)
			copy(packet, buf[NameSize:n])
			udpPacket := &UDPPacket{
				Name:   name,
				Packet: packet,
				Sender: sender}
			peerConn, found := router.Ourself.ConnectionTo(name)
			if !found {
				continue
			}
			relayConn, ok := peerConn.(*LocalConnection)
			if !ok {
				continue
			}
			checkWarn(relayConn.Decryptor.IterateFrames(handleUDPPacket, udpPacket))
		}
	}
}
Ejemplo n.º 3
0
Archivo: server.go Proyecto: h2non/dns
// ServeUDP starts a UDP listener for the server.
// Each request is handled in a seperate goroutine,
// with the Handler set in ....
func (srv *Server) ServeUDP(l *net.UDPConn) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	if srv.UDPSize == 0 {
		srv.UDPSize = UDPMsgSize
	}
	for {
		m := make([]byte, srv.UDPSize)
		n, a, e := l.ReadFromUDP(m)
		if e != nil {
			return e
		}
		m = m[:n]

		if srv.ReadTimeout != 0 {
			l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		d, err := newConn(nil, l, a, m, handler, srv.TsigSecret)
		if err != nil {
			continue
		}
		go d.serve()
	}
	panic("not reached")
}
Ejemplo n.º 4
0
// Read from UDP socket, writes slice of byte into channel.
func readFromSocket(socket *net.UDPConn, conChan chan packetType, bytesArena arena, stop chan bool) {
	for {
		b := bytesArena.Pop()
		n, addr, err := socket.ReadFromUDP(b)
		if err != nil {
			log.V(3).Infof("DHT: readResponse error:", err)
		}
		b = b[0:n]
		if n == maxUDPPacketSize {
			log.V(3).Infof("DHT: Warning. Received packet with len >= %d, some data may have been discarded.\n", maxUDPPacketSize)
		}
		totalReadBytes.Add(int64(n))
		if n > 0 && err == nil {
			p := packetType{b, *addr}
			select {
			case conChan <- p:
				continue
			case <-stop:
				return
			}
		}
		// Do a non-blocking read of the stop channel and stop this goroutine if the channel
		// has been closed.
		select {
		case <-stop:
			return
		default:
		}
	}
}
Ejemplo n.º 5
0
func UDPInbox(ctx Context, conn *net.UDPConn, buf int) (chan UDPPacket, error) {
	udpIn := make(chan UDPPacket, buf)
	go func() {
		for {
			payload := make([]byte, MaxUDPPacketSize)

			size, rAddr, err := conn.ReadFromUDP(payload)
			if err != nil {
				// Check if the done channel closed then shutdown goroutine
				select {
				case <-ctx.DoneChan:
					ctx.Log.Debug.Println("UDPInbox shutdown")
					close(udpIn)
					return
				default:
					// Need default case otherwise the select statment would block
				}

				ctx.Log.Error.Println(err.Error())
				continue
			}
			ctx.Log.Debug.Println("Receive UDP Packet")
			udpIn <- UDPPacket{
				RemoteAddr: rAddr,
				Size:       size,
				Payload:    payload,
			}

		}

	}()
	return udpIn, nil
}
func listen(socket *net.UDPConn) {
	data := make([]byte, 4096)
	length, remoteAddr, err := socket.ReadFromUDP(data)
	if err != nil {
		log.Fatal(err)
	}

	//@ToDO: Check, if the user wants the file
	var request transmitFileRequest
	error := json.Unmarshal(data[:length], &request)
	if error != nil {
		log.Fatal(error)
	}

	fmt.Printf("Got connection attempt from %s -> ", remoteAddr)

	//Only accept connections from server when the user specified it
	if *server != nil {
		if remoteAddr.IP.Equal(*server) {
			fmt.Printf("accepting connection\n")
			fmt.Printf("Remote wants to transfer %s (Size: %s)\n", request.FileName, humanize.Bytes(uint64(request.Size)))
			acceptIncomingFileTransfer(remoteAddr.IP, request)
		} else {
			fmt.Printf("DENY (only accepting connections from %s)", *server)
		}
	} else {
		fmt.Printf("accepting connection\n")
		fmt.Printf("Remote wants to transfer %s (Size: %s)\n", request.FileName, humanize.Bytes(uint64(request.Size)))
		acceptIncomingFileTransfer(remoteAddr.IP, request)
	}
}
Ejemplo n.º 7
0
func (handler *VMessInboundHandler) AcceptPackets(conn *net.UDPConn) {
	for {
		buffer := make([]byte, bufferSize)
		nBytes, addr, err := conn.ReadFromUDP(buffer)
		if err != nil {
			log.Error("VMessIn failed to read UDP packets: %v", err)
			continue
		}

		reader := bytes.NewReader(buffer[:nBytes])
		requestReader := protocol.NewVMessRequestReader(handler.clients)

		request, err := requestReader.Read(reader)
		if err != nil {
			log.Warning("VMessIn: Invalid request from (%s): %v", addr.String(), err)
			continue
		}

		cryptReader, err := v2io.NewAesDecryptReader(request.RequestKey, request.RequestIV, reader)
		if err != nil {
			log.Error("VMessIn: Failed to create decrypt reader: %v", err)
			continue
		}

		data := make([]byte, bufferSize)
		nBytes, err = cryptReader.Read(data)
		if err != nil {
			log.Warning("VMessIn: Unable to decrypt data: %v", err)
			continue
		}

		packet := v2net.NewPacket(request.Destination(), data[:nBytes], false)
		go handler.handlePacket(conn, request, packet, addr)
	}
}
Ejemplo n.º 8
0
func detect_precense(connection *net.UDPConn, masterChan chan bool) {
	buffer := make([]byte, 2048)
	for {
		t := time.Now()
		connection.SetReadDeadline(t.Add(3 * time.Second))
		_, _, err := connection.ReadFromUDP(buffer)
		if err != nil {
			fmt.Println("UDP timeout: ", err)
			masterChan <- true
			break
		}
		/*
			fmt.Println("I'm getting into this for")
			select {
			case <-time.After(time.Second * 3):
				fmt.Println("Master dead")
				masterChan <- true
				break L
				/*
					default:
						_, _, err := connection.ReadFromUDP(buffer)
						if err != nil {
							fmt.Println("You messed up in detect_precense.")
							panic(err)
						}
			}(*/
	}
}
Ejemplo n.º 9
0
// sendDataPacket sends the given data packet to the connected client
// and waits for the correct ACK, or times out
func sendDataPacket(s *Server, d *pkt.DataPacket, con *net.UDPConn) error {
	_, err := con.Write(d.Bytes())
	if err != nil {
		return err
	}

	// Now wait for the ACK...
	maxtimeout := time.After(AckTimeout)
	ackch := make(chan error)

	// Move it to its own function
	go func() {
		ack := make([]byte, 256)
		for {
			n, _, err := con.ReadFromUDP(ack)
			if err != nil {
				ackch <- err
				return
			}

			pack, err := pkt.ParsePacket(ack[:n])
			if err != nil {
				ackch <- err
				return
			}

			// Check packet type
			ackpack, ok := pack.(*pkt.AckPacket)
			if !ok {
				ackch <- pkt.ErrPacketType
				return
			}

			if ackpack.GetBlocknum() != d.BlockNum {
				s.Logger.Warning("got ack(%d) but expected ack(%d)\n", d.BlockNum, ackpack.GetBlocknum())
				continue
			}
			ackch <- nil
			return
		}
	}()

	// Loop and retransmit until ack or timeout
	retransmit := time.After(RetransmitTime)
	for {
		select {
		case <-maxtimeout:
			return ErrTimeout
		case <-retransmit:
			s.Logger.Warning("Retransmit")
			_, err := con.Write(d.Bytes())
			if err != nil {
				return err
			}
			retransmit = time.After(RetransmitTime)
		case err := <-ackch:
			return err
		}
	}
}
Ejemplo n.º 10
0
func AcceptUDP(UDP_Listner *net.UDPConn) {
	for {
		var (
			buf      = make([]byte, 1024)
			PlayerID ID
		)

		_, addr, err := UDP_Listner.ReadFromUDP(buf[0:])

		if err != nil {
			log.Printf("AcceptUDP error:" + err.Error())
			continue
		}
		if buf[0] == ID_ResolveUDP {
			PlayerID = ID(buf[3]) | (ID(buf[4]) << 8) | (ID(buf[5])<<16 | ID(buf[6])<<24)
			for _, c := range MainServer.Clients {
				if PlayerID == c.ID { // TODO: must be reply TCP message with approve connection
					log.Printf("%s pid=%d", addr.String(), PlayerID)
					c.UDPCon = UDP_Listner
					c.UDPAddr = addr
				}
			}
			buf = make([]byte, 1024)
			continue
		}
	}
}
Ejemplo n.º 11
0
func main() {
	listen := flag.String("addr", ":2055", "Listen address")
	flag.Parse()

	var addr *net.UDPAddr
	var err error
	if addr, err = net.ResolveUDPAddr("udp", *listen); err != nil {
		log.Fatal(err)
	}

	var server *net.UDPConn
	if server, err = net.ListenUDP("udp", addr); err != nil {
		log.Fatal(err)
	}

	decoders := make(map[string]*netflow.Decoder)
	for {
		buf := make([]byte, 8192)
		var remote *net.UDPAddr
		if _, remote, err = server.ReadFromUDP(buf); err != nil {
			log.Printf("error reading from %s: %v\n", remote, err)
			continue
		}

		log.Printf("received %d bytes from %s\n", len(buf), remote)

		d, found := decoders[remote.String()]
		if !found {
			s := session.New()
			d = netflow.NewDecoder(s)
			decoders[remote.String()] = d
		}

		m, err := d.Read(bytes.NewBuffer(buf))
		if err != nil {
			log.Println("decoder error:", err)
			continue
		}

		switch p := m.(type) {
		case *netflow1.Packet:
			netflow1.Dump(p)

		case *netflow5.Packet:
			netflow5.Dump(p)

		case *netflow6.Packet:
			netflow6.Dump(p)

		case *netflow7.Packet:
			netflow7.Dump(p)

		case *netflow9.Packet:
			netflow9.Dump(p)

		case *ipfix.Message:
			ipfix.Dump(p)
		}
	}
}
Ejemplo n.º 12
0
func listenOutage(conn *net.UDPConn) {
	for {
		b := make([]byte, 256)
		_, _, err := conn.ReadFromUDP(b)
		fmt.Println("read", string(b))
		t, m, err := message.DecodeClientToClientMessage(b)
		if err != nil {
			log.Println("[Client] Can't decode message", string(b))
		}
		switch t {
		case message.VOTE_T:
			// Start voting
			if !inVotingProcess {
				startVotingAlgorithm()
			}
			address := m.VoteMessage.Number
			fmt.Println("Got this address", address)
			if address != myAddress {
				// Add Adress to list of known address
				otherClientsAddress[address] = true
				fmt.Println("Known address", otherClientsAddress)
			}
		case message.COORDINATOR_T:
			Newaddr := m.CoordinatorMessage.Address
			fmt.Println("Coordinator", Newaddr)
			stopVotingProcess()
		}
		log.Println("[Client] Got", m)
	}
}
Ejemplo n.º 13
0
func (s *Server) serve(conn *net.UDPConn) {
	defer s.wg.Done()

	// From https://collectd.org/wiki/index.php/Binary_protocol
	//   1024 bytes (payload only, not including UDP / IP headers)
	//   In versions 4.0 through 4.7, the receive buffer has a fixed size
	//   of 1024 bytes. When longer packets are received, the trailing data
	//   is simply ignored. Since version 4.8, the buffer size can be
	//   configured. Version 5.0 will increase the default buffer size to
	//   1452 bytes (the maximum payload size when using UDP/IPv6 over
	//   Ethernet).
	buffer := make([]byte, 1452)

	for {
		n, _, err := conn.ReadFromUDP(buffer)
		if err != nil && s.conn != nil {
			log.Printf("Collectd ReadFromUDP error: %s", err)
			continue
		}
		log.Printf("received %d bytes", n)
		if n > 0 {
			s.handleMessage(buffer[:n])
		}
		if s.conn == nil {
			// we closed the connection, time to go
			return
		}
	}
}
Ejemplo n.º 14
0
func (s *serv) udphandler(conn *net.UDPConn) {
	u := newUpstream(s.proto)
	u.udpconn = conn

	// add to pool
	s.pool.append(u, 0)
	defer func() {
		u.close()
		s.pool.remove(u)
	}()

	for {
		udpbuf := make([]byte, buffersize)
		n, addr, err := conn.ReadFromUDP(udpbuf)
		if err != nil {
			logrus.WithError(err).Warnln("ReadFromUDP error")
			break
		}
		if u.udpaddr == nil {
			u.udpaddr = addr
		}

		p := packet{}
		if err := decodePacket(udpbuf[:n], &p); err != nil {
			logrus.WithError(err).Warnln("server gop decode from udp error", n)
			continue
		}

		p.udp = true
		if err := s.proc(u, &p); err != nil {
			logrus.WithError(err).Warn("serve send pong err")
			return
		}
	}
}
Ejemplo n.º 15
0
func (c *client) getReplies(so *net.UDPConn) {
	for {
		log.Println("here")
		b := make([]byte, 128)
		i, sa, err := so.ReadFromUDP(b)
		if err != nil {
			log.Println("failed to read from socket, ", err.Error())
			continue
		}

		tns := uint64(time.Now().UnixNano())
		macLen := 256 / 8
		mac := b[:macLen]
		message := b[macLen:i]

		if len(mac) != macLen || !checkMAC(message, mac, []byte(c.key)) {
			//Should count bad hmacs
			continue
		}

		rep := pb.PingReply{}
		proto.Unmarshal(message, &rep)
		go c.processReply(&rep, tns, sa)
	}
}
Ejemplo n.º 16
0
// Serve starts the server using an existing UDPConn.
func (s *Server) Serve(conn *net.UDPConn) error {
	if s.rh == nil && s.wh == nil {
		return ErrNoRegisteredHandlers
	}

	s.connMu.Lock()
	s.conn = conn
	s.connMu.Unlock()

	s.connMu.RLock()
	defer s.connMu.RUnlock()
	buf := make([]byte, 65536) // Largest possible TFTP datagram
	for {
		numBytes, addr, err := conn.ReadFromUDP(buf)
		if err != nil {
			if s.close {
				return nil
			}
			return wrapError(err, "reading from conn")
		}

		// Make a copy of the received data
		b := make([]byte, numBytes)
		copy(b, buf)

		switch buf[1] {
		case 1: //RRQ
			go s.dispatchReadRequest(addr, b)
		case 2: //WRQ
			go s.dispatchWriteRequest(addr, b)
		default:
			go s.demuxToConn(addr, b)
		}
	}
}
Ejemplo n.º 17
0
func run(conn *net.UDPConn) {
	for {
		buf := make([]byte, 256) //这里要给一个合适的大小,不必太大,对于异常数据可以扔掉
		n, address, err := conn.ReadFromUDP(buf)

		if err != nil {
			fmt.Fprintf(os.Stderr, "read fail %s \n", err)
			cntInErr++
			continue
		}
		if address == nil {
			cntInErr++
			fmt.Fprintf(os.Stderr, "address fail %v \n", address)
			continue
		}
		if n == 0 {
			fmt.Fprintf(os.Stderr, "data empty \n")
			cntInErr++
			continue
		}
		buf = buf[:n]
		go func(conn *net.UDPConn, address *net.UDPAddr, buf []byte) {
			doJob(conn, address, buf)
		}(conn, address, buf)
		cntIn++
	}

}
Ejemplo n.º 18
0
func ReadMessage(c *net.UDPConn) (msg *Message, src net.Addr, err os.Error) {
	buff := make([]byte, DHCP_MAX_LEN)
	//log.Printf("Waiting for read")
	n, src, err := c.ReadFromUDP(buff)
	if err != nil {
		return
	}
	if n < DHCP_MIN_LEN {
		err = os.NewError("Invalid DHCP messge received (too small)")
		return
	}
	buff = buff[0:n]
	msg = &Message{
		Operation:    buff[0],
		HardwareType: buff[1],
		HardwareLen:  buff[2],
		Hops:         buff[3],
		Xid:          binary.LittleEndian.Uint32(buff[4:8]),
		Secs:         binary.LittleEndian.Uint16(buff[8:10]),
		Flags:        binary.LittleEndian.Uint16(buff[10:12]),
		ClientIP:     net.IPv4(buff[12], buff[13], buff[14], buff[15]),
		YourIP:       net.IPv4(buff[16], buff[17], buff[18], buff[19]),
		ServerIP:     net.IPv4(buff[20], buff[21], buff[22], buff[23]),
		GatewayIP:    net.IPv4(buff[24], buff[25], buff[26], buff[27]),
	}
	copy(msg.ClientHWAddr[0:16], buff[28:44])
	// We skip the magic bytes and assume for now.
	msg.Options, err = ParseOptions(buff[DHCP_MIN_LEN+4:])
	//log.Printf("Parsed %d options.", len(msg.Options))
	// TODO: Handle Option 52 extensions.
	return
}
Ejemplo n.º 19
0
func udpConnectionReader(conn *net.UDPConn, rcvCh chan UdpMessage, TimeoutCh chan bool) {

	for {
		buf := make([]byte, MSGsize)
		conn.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
		n, rAddr, err := conn.ReadFromUDP(buf)

		buf = buf[:n]

		if err != nil || n < 0 {
			switch err := err.(type) {
			case net.Error:
				if err.Timeout() {
					//fmt.Println("Before rcvCh1")
					TimeoutCh <- true
					//fmt.Println("After rcvCh1")
					continue
				} else {
					fmt.Println("Error in connectionReader")
					panic(err)
				}
			}
		}

		var TempData elevatorOperation.Elevator
		DecodeMessage(&TempData, buf)
		//fmt.Println(TempData)
		rcvCh <- UdpMessage{Raddr: rAddr.String(), Data: TempData, Length: n}
		//fmt.Println("After rcvCh2")
		time.Sleep(10 * time.Millisecond)
	}
}
Ejemplo n.º 20
0
Archivo: tftp.go Proyecto: evanqi/TFTP
/* Sends file data in DATA packets over conn. */
func sendData(conn *net.UDPConn, addr *net.UDPAddr, filename string) {
	input, err := os.Open(filename)
	checkError(err)

	buf := make([]byte, 512)
	for {
		n, err := input.Read(buf)
		checkError(err)

		data := make([]byte, n+4)
		copy(data, DATA)
		copy(data[4:], buf[:n])
		_, err = conn.WriteToUDP(data, addr)
		checkError(err)

		if n < len(buf) {
			finalAck := make([]byte, 4)
			for !bytes.Equal(finalAck[0:2], ACK) {
				_, _, err := conn.ReadFromUDP(finalAck)
				checkError(err)
			}

			break
		}
	}

}
Ejemplo n.º 21
0
func handleClient(conn *net.UDPConn, sb []byte) {
	var buf [256]byte
	size, addr, err := conn.ReadFromUDP(buf[0:])
	//println(size, addr)
	if err != nil {
		return
	}
	if size < 48 {
		return
	}
	sec, microsec := gettimeofday()
	vn := byteArrayToUint64(buf[0:][0:3]) & 0x38000000
	copy(sb[0:3], uint64ToByteArray(0x040106F0|vn)) // flag
	copy(sb[4:7], []byte{0, 0, 0, 0})               //delay
	copy(sb[8:11], uint64ToByteArray(0x00000010))   // dispersion
	copy(sb[12:15], []byte("LOCL"))                 // Ref ID
	copy(sb[16:19], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[20:23], []byte{0, 0, 0, 0})
	copy(sb[24:31], buf[0:][40:47])
	copy(sb[32:35], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[36:39], uint64ToByteArray((microsec/500000)*0x80000000))
	sec, microsec = gettimeofday()
	copy(sb[40:43], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[44:47], uint64ToByteArray((microsec/500000)*0x80000000))

	conn.WriteToUDP([]byte(sb), addr)
}
Ejemplo n.º 22
0
func (s *Server) HandleSocket(socket *net.UDPConn) {
	// From https://collectd.org/wiki/index.php/Binary_protocol
	//   1024 bytes (payload only, not including UDP / IP headers)
	//   In versions 4.0 through 4.7, the receive buffer has a fixed size
	//   of 1024 bytes. When longer packets are received, the trailing data
	//   is simply ignored. Since version 4.8, the buffer size can be
	//   configured. Version 5.0 will increase the default buffer size to
	//   1452 bytes (the maximum payload size when using UDP/IPv6 over
	//   Ethernet).
	buffer := make([]byte, 1452)

	for {
		n, _, err := socket.ReadFromUDP(buffer)
		if err != nil || n == 0 {
			log.Error("Collectd ReadFromUDP error: %s", err)
			continue
		}

		packets, err := collectd.Packets(buffer[:n], s.typesdb)
		if err != nil {
			log.Error("Collectd parse error: %s", err)
			continue
		}

		for _, packet := range *packets {
			series := packetToSeries(&packet)
			err = s.coordinator.WriteSeriesData(s.user, s.database, series)
			if err != nil {
				log.Error("Collectd cannot write data: %s", err)
				continue
			}
		}
	}
}
Ejemplo n.º 23
0
func read(serv_conn *net.UDPConn) {

	buffer := make([]byte, 1024)
	// number of last received packet
	var last_recd int = 0
	for {
		//		fmt.Println("Reading from UDP buffer...")
		n, addr, err := serv_conn.ReadFromUDP(buffer)

		// get the current packet number
		current_packet, err := strconv.Atoi(string(buffer[0:n]))
		CheckError(err)
		// check the packet we have now against the one we received last
		go check_packet(serv_conn, current_packet, last_recd)
		last_recd, err = strconv.Atoi(string(buffer[0:n]))
		// check for duplicates and discard them as necessary, otherwise mark as received
		if last_recd == most_recent {
			fmt.Println("Duplicate packet found, discarding", string(buffer[0:n]))
		} else {
			fmt.Println("Successfully received", string(buffer[0:n]), "from", addr)
			most_recent = last_recd
		}
		CheckError(err)
	}
}
Ejemplo n.º 24
0
func listenUdp(c *net.UDPConn) {
	//m := make(map[string]int, 100)
	for {
		var message string

		buf := make([]byte, MAIN_BUFFER_SIZE)
		n, addr, err := c.ReadFromUDP(buf)

		if err != nil {
			log.Fatalln("error reading UDP: ", err)
			//break
		}
		message = string(buf[0:n])
		log.Println("received message from ", addr, message)

		writeSize, writeErr := c.WriteToUDP(buf, addr)
		if writeErr != nil {
			log.Fatalln("error writing UDP: ", writeErr, writeSize)
			//break
		}

		// IF this is a chat message, broadcast it:
		//h.broadcast <- message
		// TODO: IF this is a movement command, hand it to nav system
		// TODO: IF we don't recognize it, throw an error
	}
	c.Close()
}
Ejemplo n.º 25
0
func (s ServerUdp) udpHandler(conn *net.UDPConn) {
	var buf [512]byte
	_, addr, err := conn.ReadFromUDP(buf[0:])
	if err != nil {
		log.Printf("Error: %s \n", err)
	}
	var hash int = 0
	for _, d := range buf[11:] {
		hash += int(d)
	}
	gethash, _ := strconv.Atoi(string(buf[5:10]))

	if string(buf[0:5]) == "MAGIC" && hash == gethash {
		_, err = conn.WriteToUDP([]byte("200"), addr)
		if err != nil {
			log.Printf("Error: %s \n", err)
		}
	} else {
		_, err = conn.WriteToUDP([]byte("400"), addr)
		if err != nil {
			log.Printf("Error: %s \n", err)
		}
		log.Printf("Inv UDP %s From %v:%v,Ignored\n", string(buf[0:]), addr.IP, addr.Port)
		return
	}
	log.Printf("Recv GPRMC From %v:%v\n%s\n", addr.IP, addr.Port, string(buf[0:]))
	s.Info <- buf[11:len(buf)]
}
Ejemplo n.º 26
0
// serveUDP starts a UDP listener for the server.
// Each request is handled in a seperate goroutine.
func (srv *Server) serveUDP(l *net.UDPConn) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	if srv.UDPSize == 0 {
		srv.UDPSize = udpMsgSize
	}
	for {
		if srv.ReadTimeout != 0 {
			l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		m := make([]byte, srv.UDPSize)
		n, a, e := l.ReadFromUDP(m)
		if e != nil || n == 0 {
			// don't bail out, but wait for a new request
			continue
		}
		m = m[:n]
		go serve(a, handler, m, l, nil, srv.TsigSecret)
	}
	panic("dns: not reached")
}
Ejemplo n.º 27
0
func (srv *Server) ServeUDP(l *net.UDPConn) os.Error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	for {
		m := make([]byte, DefaultMsgSize)
		n, a, e := l.ReadFromUDP(m)
		if e != nil {
			return e
		}
		m = m[:n]

		if srv.ReadTimeout != 0 {
			l.SetReadTimeout(srv.ReadTimeout)
		}
		if srv.WriteTimeout != 0 {
			l.SetWriteTimeout(srv.WriteTimeout)
		}
		d, err := newConn(nil, l, a, m, handler)
		if err != nil {
			continue
		}
		go d.serve()
	}
	panic("not reached")
}
Ejemplo n.º 28
0
func (server *SocksServer) AcceptPackets(conn *net.UDPConn) error {
	for {
		buffer := alloc.NewBuffer()
		nBytes, addr, err := conn.ReadFromUDP(buffer.Value)
		if err != nil {
			log.Error("Socks failed to read UDP packets: %v", err)
			buffer.Release()
			continue
		}
		log.Info("Client UDP connection from %v", addr)
		request, err := protocol.ReadUDPRequest(buffer.Value[:nBytes])
		buffer.Release()
		if err != nil {
			log.Error("Socks failed to parse UDP request: %v", err)
			request.Data.Release()
			continue
		}
		if request.Fragment != 0 {
			log.Warning("Dropping fragmented UDP packets.")
			// TODO handle fragments
			request.Data.Release()
			continue
		}

		udpPacket := v2net.NewPacket(request.Destination(), request.Data, false)
		log.Info("Send packet to %s with %d bytes", udpPacket.Destination().String(), request.Data.Len())
		go server.handlePacket(conn, udpPacket, addr, request.Address)
	}
}
Ejemplo n.º 29
0
// here is where we're constantly monitoring the UDP buffer to wait for those
// precious ACKs we so desperately need to keep the data flowing.
func wait_for_ack(serv_conn *net.UDPConn, expected int, i chan int) {
	for {
		fmt.Println("Waiting for ACK for", expected)
		// our buffer to read into
		buffer := make([]byte, 1024)
		// our wrong value for our ACK result
		ack_val := -1
		n, addr, err := serv_conn.ReadFromUDP(buffer)
		// if we're actually receiving data,
		if addr != nil {
			// do some messy conversions to get the number in the buffer as an int
			curr_packet, err := strconv.Atoi(string(buffer[0:n]))
			CheckError(err)

			fmt.Println("Received", curr_packet, ", looking for", expected)
			// check to see which packet we actually got
			ack_val = check_packet(curr_packet, expected)
			fmt.Println("Received ACK for", curr_packet, "from", addr)
		}
		CheckError(err)
		// if we got an ACK, write it to the channel and get outta there
		if ack_val != -1 {
			i <- ack_val
			break
		}
	}
}
Ejemplo n.º 30
-1
func udpListener(conn *net.UDPConn, sendingFrom net.Addr, start *sync.WaitGroup, end *sync.WaitGroup) {
	fmt.Fprintln(os.Stderr, "Started listener...")
	start.Done()

	buff := make([]byte, 1600) // standard MTU size -- no packet should be bigger
	for i := 0; true; i++ {
		fmt.Fprintln(os.Stderr, "Waiting for packet #"+strconv.Itoa(i))
		len, from, err := conn.ReadFromUDP(buff)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error receiving UDP packet: "+err.Error())
		}
		if from.String() == sendingFrom.String() {
			i--
			continue
		}

		str := string(buff[:len])
		fmt.Println("Received message from " + from.String() + "\n\t" + str)
		if strings.Contains(str, "<<terminate>>") {
			conn.Close()
			fmt.Fprintln(os.Stderr, "Terminated UDP listener")
			end.Done()
			return
		}
	}
}