//  This is how we handle a beacon coming into our UDP socket;
//  this may be from other peers or an echo of our own broadcast
//  beacon:
3870
func (agent *agent_t) handle_beacon() (err error) {

	msg, err := agent.udp.RecvMessage(0)
	if len(msg[0]) != 16 {
		return errors.New("Not a uuid")
	}

	//  If we got a UUID and it's not our own beacon, we have a peer
	uuid := uuid.UUID(msg[0])
	if bytes.Compare(uuid, agent.uuid_bytes) != 0 {
		//  Find or create peer via its UUID string
		uuid_string := uuid.String()
		peer, ok := agent.peers[uuid_string]
		if !ok {
			peer = new_peer(uuid)
			agent.peers[uuid_string] = peer

			//  Report peer joined the network
			agent.pipe.SendMessage("JOINED", uuid_string)
		}
		//  Any activity from the peer means it's alive
		peer.is_alive()
	}
	return
}
241464
func NewBusSocket() (*BusSocket, error) {
	s, err := NewSocket(AF_SP, BUS)
	return &BusSocket{s}, err
}
94971
func (self *SocketHandler) sendUDP(bin []byte) error {
	if self.conn == nil {
		err := self.createSocket()
		if err != nil {
			return err
		}
	}
	_, err := self.conn.Write(bin)
	return err
}
46375
func Receive(l *net.UDPConn, buf []byte) (Message, error) {
	l.SetReadDeadline(time.Now().Add(ResponseTimeout))

	nr, _, err := l.ReadFromUDP(buf)
	if err != nil {
		return Message{}, err
	}
	return ParseMessage(buf[:nr])
}
817506
func (s *server) rebroadcastHandler() {
	// Wait 5 min before first tx rebroadcast.
	timer := time.NewTimer(5 * time.Minute)
	pendingInvs := make(map[wire.InvVect]interface{})

out:
	for {
		select {
		case riv := <-s.modifyRebroadcastInv:
			switch msg := riv.(type) {
			// Incoming InvVects are added to our map of RPC txs.
			case broadcastInventoryAdd:
				pendingInvs[*msg.invVect] = msg.data

			// When an InvVect has been added to a block, we can
			// now remove it, if it was present.
			case broadcastInventoryDel:
				if _, ok := pendingInvs[*msg]; ok {
					delete(pendingInvs, *msg)
				}
			}

		case <-timer.C:
			// Any inventory we have has not made it into a block
			// yet. We periodically resubmit them until they have.
			for iv, data := range pendingInvs {
				ivCopy := iv
				s.RelayInventory(&ivCopy, data)
			}

			// Process at a random time up to 30mins (in seconds)
			// in the future.
			timer.Reset(time.Second *
				time.Duration(randomUint16Number(1800)))

		case <-s.quit:
			break out
		}
	}

	timer.Stop()

	// Drain channels before exiting so nothing is left waiting around
	// to send.
cleanup:
	for {
		select {
		case <-s.modifyRebroadcastInv:
		default:
			break cleanup
		}
	}
	s.wg.Done()
}
173573
func (d *Datapath) ProcessApplicationUDPPacket(p *packet.Packet) (conn *connection.UDPConnection, err error) {

	if d.packetLogs {
		zap.L().Debug("Processing application UDP packet ",
			zap.String("flow", p.L4FlowHash()),
		)
		defer zap.L().Debug("Finished Processing UDP application packet ",
			zap.String("flow", p.L4FlowHash()),
			zap.Error(err),
		)
	}
	// First retrieve the connection state.
	conn, err = d.appUDPRetrieveState(p)
	if err != nil {
		zap.L().Debug("Connection not found", zap.Error(err))
		return nil, fmt.Errorf("Received packet from unenforced process: %s", err)
	}

	// We are processing only one packet from a given connection at a time.
	conn.Lock()
	defer conn.Unlock()

	// do some pre processing.
	if d.service != nil {
		// PreProcessServiceInterface
		if !d.service.PreProcessUDPAppPacket(p, conn.Context, conn, packet.UDPSynMask) {
			p.Print(packet.PacketFailureService)
			return nil, fmt.Errorf("pre service processing failed for UDP application packet")
		}
	}

	triggerControlProtocol := false
	switch conn.GetState() {
	case connection.UDPStart:
		// Queue the packet. We will send it after we authorize the session.
		if err = conn.QueuePackets(p); err != nil {
			// unable to queue packets, perhaps queue is full. if start
			// machine is still in start state, we can start authorisation
			// again. A drop counter is incremented.
			zap.L().Debug("udp queue full for connection", zap.String("flow", p.L4FlowHash()))
		}

		// Set the state indicating that we send out a Syn packet
		conn.SetState(connection.UDPClientSendSyn)
		// Drop the packet. We stored it in the queue.
		triggerControlProtocol = true

	case connection.UDPReceiverProcessedAck, connection.UDPClientSendAck, connection.UDPData:
		conn.SetState(connection.UDPData)

	default:
		zap.L().Debug("Packet is added to the queue", zap.String("flow", p.L4FlowHash()))
		if err = conn.QueuePackets(p); err != nil {
			return conn, fmt.Errorf("Unable to queue packets:%s", err)
		}
		return conn, fmt.Errorf("Drop in nfq - buffered")
	}

	if d.service != nil {
		// PostProcessServiceInterface
		if !d.service.PostProcessUDPAppPacket(p, nil, conn.Context, conn) {
			p.Print(packet.PacketFailureService)
			return conn, fmt.Errorf("Encryption failed for application packet")
		}
	}

	if triggerControlProtocol {
		err = d.triggerNegotiation(p, conn.Context, conn)
		if err != nil {
			return conn, err
		}
		return conn, fmt.Errorf("Drop in nfq - buffered")
	}

	return conn, nil
}
1175937
func (n *Node) UDP() int {
	var port enr.UDP
	n.Load(&port)
	return int(port)
}
1057502
func UDPRemoteForwardListener(addr string, chain *Chain, ttl time.Duration) (Listener, error) {
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return nil, err
	}

	ln := &udpRemoteForwardListener{
		addr:     laddr,
		chain:    chain,
		conns:    make(map[string]*udpServerConn),
		connChan: make(chan net.Conn, 1024),
		errChan:  make(chan error, 1),
		ttl:      ttl,
		closed:   make(chan struct{}),
	}

	go ln.listenLoop()

	err = <-ln.errChan

	return ln, err
}
258266
func sendtoCallback(a *C.utp_callback_arguments) (ret C.uint64) {
	s := getSocketForLibContext(a.context)
	b := a.bufBytes()
	if err := structSockaddrToUDPAddr(a.address(), &sendToUdpAddr); err != nil {
		panic(err)
	}
	newSends := atomic.AddInt64(&sends, 1)
	if logCallbacks {
		Logger.Printf("sending %d bytes, %d packets", len(b), newSends)
	}
	expMap.Add("socket PacketConn writes", 1)
	n, err := s.pc.WriteTo(b, &sendToUdpAddr)
	c := s.conns[a.socket]
	if err != nil {
		expMap.Add("socket PacketConn write errors", 1)
		if c != nil && c.userOnError != nil {
			go c.userOnError(err)
		} else if c != nil &&
			(strings.Contains(err.Error(), "can't assign requested address") ||
				strings.Contains(err.Error(), "invalid argument")) {
			// Should be an bad argument or network configuration problem we
			// can't recover from.
			c.onError(err)
		} else if c != nil && strings.Contains(err.Error(), "operation not permitted") {
			// Rate-limited. Probably Linux. The implementation might try
			// again later.
		} else {
			Logger.Printf("error sending packet: %s", err)
		}
		return
	}
	if n != len(b) {
		expMap.Add("socket PacketConn short writes", 1)
		Logger.Printf("expected to send %d bytes but only sent %d", len(b), n)
	}
	return
}
1356012
func (cn *conn) recv1Buf(r *readBuf) byte {
	for {
		t, err := cn.recvMessage(r)
		if err != nil {
			panic(err)
		}

		switch t {
		case 'A', 'N':
			// ignore
		case 'S':
			cn.processParameterStatus(r)
		default:
			return t
		}
	}
}
820317
func (t *ipTransport) Handle(ev interface{}) {
	switch ev.(type) {
	case event.DevicePaired:
		log.Debug.Printf("Event: paired with device")
		t.updateMDNSReachability()
	case event.DeviceUnpaired:
		log.Debug.Printf("Event: unpaired with device")
		t.updateMDNSReachability()
	default:
		break
	}
}
756914
func (p *peer) pingHandler() {
	defer p.wg.Done()

	pingTicker := time.NewTicker(pingInterval)
	defer pingTicker.Stop()

	// TODO(roasbeef): make dynamic in order to create fake cover traffic
	const numPingBytes = 16

out:
	for {
		select {
		case <-pingTicker.C:
			p.queueMsg(lnwire.NewPing(numPingBytes), nil)
		case <-p.quit:
			break out
		}
	}
}
73143
func newSocket(s *Server) *Socket {
	a := &Socket{
		writeChan: make(chan string, global.WriteChanSize),
		readChan:  make(chan string, global.ReadChanSize),
	}

	// Set the closer function.
	a.closer = closer.New(func() {
		// Remove the ajax socket from the map.
		if len(a.uid) > 0 {
			func() {
				s.socketsMutex.Lock()
				defer s.socketsMutex.Unlock()

				delete(s.sockets, a.uid)
			}()
		}
	})

	return a
}
1199099
func (cli *Client) handlePINGRESP() error {
	// Lock for reading and updating pingrespcs.
	cli.conn.muPINGRESPs.Lock()

	// Check the length of pingrespcs.
	if len(cli.conn.pingresps) == 0 {
		// Unlock.
		cli.conn.muPINGRESPs.Unlock()

		// Return an error if there is no channel in pingrespcs.
		return ErrInvalidPINGRESP
	}

	// Get the first channel in pingrespcs.
	pingrespc := cli.conn.pingresps[0]

	// Remove the first channel from pingrespcs.
	cli.conn.pingresps = cli.conn.pingresps[1:]

	// Unlock.
	cli.conn.muPINGRESPs.Unlock()

	// Notify the arrival of the PINGRESP Packet if possible.
	select {
	case pingrespc <- struct{}{}:
	default:
	}

	return nil
}
1157462
func Listen(addr string, c chan collectd.Packet, typesdb string) {
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		log.Fatalln("fatal: failed to resolve address", err)
	}

	conn, err := net.ListenUDP("udp", laddr)
	if err != nil {
		log.Fatalln("fatal: failed to listen", err)
	}

	types, err := collectd.TypesDBFile(typesdb)
	if err != nil {
		log.Fatalln("fatal: failed to parse types.db", err)
	}

	for {
		// 1452 is collectd 5's default buffer size. See:
		// https://collectd.org/wiki/index.php/Binary_protocol
		buf := make([]byte, 1452)

		n, err := conn.Read(buf[:])
		if err != nil {
			log.Println("error: Failed to receive packet", err)
			continue
		}

		packets, err := collectd.Packets(buf[0:n], types)
		if err != nil {
			log.Println("error: Failed to receive packet", err)
			continue
		}

		for _, p := range *packets {
			c <- p
		}
	}
}
1234700
func incoming(c *Client) {
	defer c.workers.Done()
	var err error
	var cp packets.ControlPacket

	DEBUG.Println(NET, "incoming started")

	for {
		if cp, err = packets.ReadPacket(c.conn); err != nil {
			break
		}
		DEBUG.Println(NET, "Received Message")
		c.ibound <- cp
	}
	// We received an error on read.
	// If disconnect is in progress, swallow error and return
	select {
	case <-c.stop:
		DEBUG.Println(NET, "incoming stopped")
		return
		// Not trying to disconnect, send the error to the errors channel
	default:
		ERROR.Println(NET, "incoming stopped with error")
		c.errors <- err
		return
	}
}
57991
func (s *ChainService) peerHandler() {
	state := &peerState{
		persistentPeers: make(map[int32]*ServerPeer),
		outboundPeers:   make(map[int32]*ServerPeer),
		banned:          make(map[string]time.Time),
		outboundGroups:  make(map[string]int),
	}

	if !DisableDNSSeed {
		// Add peers discovered through DNS to the address manager.
		connmgr.SeedFromDNS(&s.chainParams, RequiredServices,
			s.nameResolver, func(addrs []*wire.NetAddress) {
				var validAddrs []*wire.NetAddress
				for _, addr := range addrs {
					if addr.Services&RequiredServices !=
						RequiredServices {
						continue
					}

					validAddrs = append(validAddrs, addr)
				}

				if len(validAddrs) == 0 {
					return
				}

				// Bitcoind uses a lookup of the dns seeder
				// here. This is rather strange since the
				// values looked up by the DNS seed lookups
				// will vary quite a lot.  to replicate this
				// behaviour we put all addresses as having
				// come from the first one.
				s.addrManager.AddAddresses(
					validAddrs, validAddrs[0],
				)
			})
	}

out:
	for {
		select {
		// New peers connected to the server.
		case p := <-s.newPeers:
			s.handleAddPeerMsg(state, p)

		// Disconnected peers.
		case p := <-s.donePeers:
			s.handleDonePeerMsg(state, p)

		// Block accepted in mainchain or orphan, update peer height.
		case umsg := <-s.peerHeightsUpdate:
			s.handleUpdatePeerHeights(state, umsg)

		// Peer to ban.
		case p := <-s.banPeers:
			s.handleBanPeerMsg(state, p)

		case qmsg := <-s.query:
			s.handleQuery(state, qmsg)

		case <-s.quit:
			// Disconnect all peers on server shutdown.
			state.forAllPeers(func(sp *ServerPeer) {
				log.Tracef("Shutdown peer %s", sp)
				sp.Disconnect()
			})
			break out
		}
	}

	// Drain channels before exiting so nothing is left waiting around
	// to send.
cleanup:
	for {
		select {
		case <-s.newPeers:
		case <-s.donePeers:
		case <-s.banPeers:
		case <-s.peerHeightsUpdate:
		case <-s.query:
		default:
			break cleanup
		}
	}
	s.wg.Done()
	log.Tracef("Peer handler done")
}