func retrieveFortune(clientConn net.UDPConn, fortuneInfoMsg clientServerUtils.FortuneInfoMessage) clientServerUtils.FortuneMessage { //Send FortuneReqMessage to fserver fortuneReqMsg := clientServerUtils.FortuneReqMessage{fortuneInfoMsg.FortuneNonce} fortuneReq, err := json.Marshal(fortuneReqMsg) if err != nil { fmt.Println("Error marshalling fortuneReqMsg: ", err) os.Exit(-1) } fmt.Println("Retrieving fortune from fserver") fserverUDPAddr := resolveUDPAddr(fortuneInfoMsg.FortuneServer) _, err = clientConn.WriteToUDP(fortuneReq, &fserverUDPAddr) if err != nil { fmt.Println("Error writing to fserver: ", err) os.Exit(-1) } //Receive FortuneMessage reply from fserver var buf [1024]byte msgLen, err := clientConn.Read(buf[:]) if err != nil { fmt.Println("Error on read: ", err) os.Exit(-1) } fortuneReplyStr := string(buf[0:msgLen]) fortuneBytes := []byte(fortuneReplyStr) var fortune clientServerUtils.FortuneMessage json.Unmarshal(fortuneBytes, &fortune) return fortune }
func (s *UdpForwardServer) handleUdpForwardLocal(conn *net.UDPConn, laddr, raddr *net.UDPAddr, data []byte) { lconn, err := net.ListenUDP("udp", nil) if err != nil { glog.V(LWARNING).Infof("[udp] %s -> %s : %s", laddr, raddr, err) return } defer lconn.Close() if _, err := lconn.WriteToUDP(data, raddr); err != nil { glog.V(LWARNING).Infof("[udp] %s -> %s : %s", laddr, raddr, err) return } glog.V(LDEBUG).Infof("[udp] %s >>> %s length %d", laddr, raddr, len(data)) b := make([]byte, MediumBufferSize) lconn.SetReadDeadline(time.Now().Add(ReadTimeout)) n, addr, err := lconn.ReadFromUDP(b) if err != nil { glog.V(LWARNING).Infof("[udp] %s <- %s : %s", laddr, raddr, err) return } glog.V(LDEBUG).Infof("[udp] %s <<< %s length %d", laddr, addr, n) if _, err := conn.WriteToUDP(b[:n], laddr); err != nil { glog.V(LWARNING).Infof("[udp] %s <- %s : %s", laddr, raddr, err) } return }
func (s *UDPServer) handleCall(conn *net.UDPConn) { // Read and buffer UDP datagram b := make([]byte, MaxUdpSize) packetSize, callerAddr, err := conn.ReadFromUDP(b) if err != nil { s.server.log.WithField("err", err).Error("Cannot read UDP datagram") return } reply, err := s.server.handleRecord(b[0:packetSize]) if err != nil { s.server.log.WithField("err", err).Error("handling record") } if _, err := conn.WriteToUDP(reply.Bytes(), callerAddr); err != nil { s.server.log.WithFields(logrus.Fields{ "callerAddr": callerAddr.String(), "err": err, }).Error("Cannot send reply over UDP") return } }
//发出缓存 func fushCache(conn *net.UDPConn, sendAddr *net.UDPAddr) { cacheArray := TempChanMap[sendAddr.IP.String()] /* for item := cacheArray.Front();item != nil ; item = item.Next() { fmt.Print("-"); conn.WriteToUDP(item.Value.([]byte), sendAddr) } */ length := TempChanMapIndex[sendAddr.IP.String()] fmt.Println(length, sendAddr.IP.String()) for i := 0; i < length; i++ { if len(cacheArray[i]) > 0 { fmt.Print("-") position, err := conn.WriteToUDP(cacheArray[i], sendAddr) checkError(err) if err != nil { fmt.Println(position) } } } /* for item := cacheArray.Front();item != nil ; item = item.Next() { cacheArray.Remove(item) fmt.Println("remove"); } */ TempChanMap[sendAddr.IP.String()] = make([][]byte, 1000, 1000000) TempChanMapIndex[sendAddr.IP.String()] = 0 //fmt.Println(TempChanMap,sendAddr.IP.String()); }
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)] }
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) }
/* Constructs and sends an ACK packet over conn. */ func sendAck(conn *net.UDPConn, addr *net.UDPAddr) { ack := make([]byte, 4) copy(ack, ACK) //TODO copy block number _, err := conn.WriteToUDP(ack, addr) checkError(err) }
func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) { ray := handler.vPoint.DispatchToOutbound(packet) close(ray.InboundInput()) responseKey := md5.Sum(request.RequestKey) responseIV := md5.Sum(request.RequestIV) buffer := alloc.NewBuffer().Clear() defer buffer.Release() responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer) if err != nil { log.Error("VMessIn: Failed to create encrypt writer: %v", err) return } responseWriter.Write(request.ResponseHeader) hasData := false if data, ok := <-ray.InboundOutput(); ok { hasData = true responseWriter.Write(data.Value) data.Release() } if hasData { conn.WriteToUDP(buffer.Value, clientAddr) log.Info("VMessIn sending %d bytes to %s", buffer.Len(), clientAddr.String()) } }
func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) { ray := handler.vPoint.DispatchToOutbound(packet) close(ray.InboundInput()) responseKey := md5.Sum(request.RequestKey[:]) responseIV := md5.Sum(request.RequestIV[:]) buffer := bytes.NewBuffer(make([]byte, 0, bufferSize)) response := protocol.NewVMessResponse(request) responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer) if err != nil { log.Error("VMessIn: Failed to create encrypt writer: %v", err) return } responseWriter.Write(response[:]) hasData := false if data, ok := <-ray.InboundOutput(); ok { hasData = true responseWriter.Write(data) } if hasData { conn.WriteToUDP(buffer.Bytes(), clientAddr) log.Info("VMessIn sending %d bytes to %s", len(buffer.Bytes()), clientAddr.String()) } }
/* 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 } } }
// parseAndAck parses the UDP payload and sends anwACK to the client receiver. // TODO(jvesuna): Keep parseAndAck routine live with a connection. Have the ackServer channel data // to this routine for faster processing. func parseAndAck(buf []byte, ServerConn *net.UDPConn, clientUDPAddr *net.UDPAddr) { messageAck := &ptpb.PingtestMessage{} if err := proto.Unmarshal(buf, messageAck); err != nil { //TODO(jvesuna): Fix this error handling. log.Println("error: failed to unmarshal packet in parseAndAck:", err) } if *tinyAck { // Don't include padding. // Here, messageAck should always be about the same size. messageAck = &ptpb.PingtestMessage{ PingtestParams: messageAck.PingtestParams, Type: messageAck.Type, } } wireBytesAck, err := proto.Marshal(messageAck) if err != nil { fmt.Println("error marshalling ACK:", err) } // Send ACK. ServerConn.SetWriteBuffer(proto.Size(messageAck)) _, err = ServerConn.WriteToUDP(wireBytesAck, clientUDPAddr) if err != nil { log.Println("Failed to send ACK:", err) } log.Println("Sent Ack") }
func SendAChunk(conn *net.UDPConn, addr *net.UDPAddr, isServer bool) { var n2 int var err error var datablock []byte //Send the chink that we have in the Block (it is either the previous one being retransmitted or a the next one var opcode = "\x00\x03" //Data packet var blocknumBytes = make([]byte, 2) binary.BigEndian.PutUint16(blocknumBytes, uint16(chunk.blocknum)) datablock = append(datablock, []byte(opcode)...) datablock = append(datablock, blocknumBytes...) fmt.Println("Stage 2: Datablock ", datablock) if chunk.nbytes < 512 { // make a slice of size chunk.nbytes and copy the data into it tempbuf := make([]byte, chunk.nbytes) n1 := copy(tempbuf, chunk.buf[0:chunk.nbytes]) fmt.Println("Copied %d bytes to the last chunk being sent", n1) datablock = append(datablock, tempbuf...) } else { datablock = append(datablock, chunk.buf...) } fmt.Println("sending datablock", datablock) if isServer { n2, err = conn.WriteToUDP(datablock, addr) } else { n2, err = conn.Write(datablock) } fmt.Println("Number of Bytes sent is ", n2) if err != nil { fmt.Printf("Couldn't send datablock %v", err) } }
/** Handles a single UDP connection as a goroutine */ func udpHandler(buf []byte, b int, n int, conn *net.UDPConn, addr *net.UDPAddr) { defer fmt.Printf("Datagram %d sent!\n", n) // Slice buffer depending on read bytes, trim spaces clean := bytes.TrimSpace(buf[:b]) // Decrypt incoming request []byte clean = decrypt(clean) // Parse the received JSON r := Request{} err := json.Unmarshal(clean, &r) if err != nil { fmt.Println(err) return } resp := findRoad(&r) // Convert to JSON, send over the wire s, err := json.Marshal(&resp) if err != nil { panic(err) } // Encrypt response []byte s = encrypt(s) conn.WriteToUDP(s, addr) }
func udp_transmit_server(lconn, bconn *net.UDPConn, send_ch chan Udp_message) { defer func() { if r := recover(); r != nil { fmt.Println("ERROR in udp_transmit_server: %s \n Closing connection.", r) lconn.Close() bconn.Close() } }() var err error var n int for { // fmt.Printf("udp_transmit_server: waiting on new value on Global_Send_ch \n") msg := <-send_ch // fmt.Printf("Writing %s \n", msg.Data) if msg.Raddr == "broadcast" { n, err = lconn.WriteToUDP([]byte(msg.Data), baddr) } else { raddr, err := net.ResolveUDPAddr("udp", msg.Raddr) if err != nil { fmt.Printf("Error: udp_transmit_server: could not resolve raddr\n") panic(err) } n, err = lconn.WriteToUDP([]byte(msg.Data), raddr) } if err != nil || n < 0 { fmt.Printf("Error: udp_transmit_server: writing\n") panic(err) } // fmt.Printf("udp_transmit_server: Sent %s to %s \n", msg.Data, msg.Raddr) } }
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() }
func (r *Router) routePacket(pkt []byte, conn *net.UDPConn) { if len(pkt) < minIP4HdrSize { log.V(1).Infof("Packet too small (%d bytes), unable to route", len(pkt)) return } r.mux.Lock() defer r.mux.Unlock() dstIP := ip.FromBytes(pkt[16:20]) for i, re := range r.routes { if re.sn.Contains(dstIP) { nbytes, err := conn.WriteToUDP(pkt, re.addr) switch { case err != nil: log.V(1).Info("UDP send failed with: ", err) case nbytes != len(pkt): log.V(1).Infof("Was only able to UDP send %d out of %d bytes to %s: ", nbytes, len(pkt), re.addr.IP) } // packets for same dest tend to come in burst. swap to front make it faster for subsequent ones if i != 0 { r.routes[0], r.routes[i] = r.routes[i], r.routes[0] } return } } log.V(1).Info("No route found for ", dstIP) }
func encode(udp *net.UDPConn, ack bool, topic string, payload []byte) { // decode the topic to determine where we're sending this tt := txTopicRE.FindStringSubmatch(topic) if len(tt) != 4 { log.Printf("Cannot parse MQTT message topic for transmission: %s", topic) return } groupId, _ := strconv.Atoi(tt[1]) nodeId, _ := strconv.Atoi(tt[2]) boot := tt[3] == "tb" unicast := nodeId > 0 && nodeId < 31 if !unicast && nodeId != 0 { log.Printf("Invalid nodeId=%d in MQTT message", nodeId) return } // map the group_id to the appropriate UDP destination addr := mapGroupToAddr(byte(groupId)) if addr == nil { log.Printf("No GW known for RF group %d", groupId) return } // Parse message payload as JSON var msg RFMessage err := json.Unmarshal(payload, &msg) if err != nil { log.Printf("Cannot parse JSON payload of MQTT message: %s", err) return } data, _ := base64.StdEncoding.DecodeString(msg.Base64) // Figure out the message type code var code byte switch { //case boot && msg.Kind == "pairing": code = RF_Pairing // not sent out to nodes! case boot && msg.Kind == "boot" && unicast: code = RF_BootReply case !boot && ack && unicast: code = RF_DataReq case !boot && ack && !unicast: code = RF_BcastReq case !boot && !ack && unicast: code = RF_DataPush case !boot && !ack && !unicast: code = RF_BcastPush default: log.Printf("Invalid MQTT message combo: boot=%t kind=%s ack=%t", boot, msg.Kind, ack) } // actually send the packet buf := make([]byte, len(data)+3) buf[0] = code buf[1] = byte(groupId) buf[2] = byte(nodeId) copy(buf[3:], data) udp.WriteToUDP(buf, addr) }
func forward_tap_to_phys(phys_conn *net.UDPConn, tap_conn *TapConn, peer_addr *net.UDPAddr, key []byte, chan_disc_peer chan net.UDPAddr) { /* Raw tap frame received */ frame := make([]byte, TAP_MTU+14) /* Encapsulated frame and error */ var enc_frame []byte var invalid error = nil /* Discovered peer */ var disc_peer_addr net.UDPAddr /* Initialize our HMAC-SHA256 hash context */ hmac_h := hmac.New(sha256.New, key) /* If a peer was specified, fill in our discovered peer information */ if peer_addr != nil { disc_peer_addr.IP = peer_addr.IP disc_peer_addr.Port = peer_addr.Port } else { /* Otherwise, wait for the forward_phys_to_tap() goroutine to discover a peer */ disc_peer_addr = <-chan_disc_peer } log.Printf("Starting tap->phys forwarding with peer %s:%d...\n", disc_peer_addr.IP, disc_peer_addr.Port) for { /* Read a raw frame from our tap device */ n, err := tap_conn.Read(frame) if err != nil { log.Fatalf("Error reading from tap device!: %s\n", err) } if DEBUG == 2 { log.Println("<- tap | Plaintext frame to peer:") log.Println("\n" + hex.Dump(frame[0:n])) } /* Encapsulate the frame */ enc_frame, invalid = encap_frame(frame[0:n], hmac_h) /* Skip it if it's invalid */ if invalid != nil { if DEBUG >= 1 { log.Printf("-> phys | Frame discarded! Size: %d, Reason: %s\n", n, invalid.Error()) log.Println("\n" + hex.Dump(frame[0:n])) } continue } if DEBUG == 2 { log.Println("-> phys | Encapsulated frame to peer:") log.Println("\n" + hex.Dump(enc_frame)) } /* Send the encapsulated frame to our peer through UDP */ _, err = phys_conn.WriteToUDP(enc_frame, &disc_peer_addr) if err != nil { log.Fatalf("Error writing to UDP socket!: %s\n", err) } } }
func (server *SocksServer) handlePacket(conn *net.UDPConn, packet v2net.Packet, clientAddr *net.UDPAddr) { ray := server.vPoint.DispatchToOutbound(packet) close(ray.InboundInput()) if data, ok := <-ray.InboundOutput(); ok { conn.WriteToUDP(data, clientAddr) } }
func doJob(conn *net.UDPConn, address *net.UDPAddr, buf []byte) { _, err := conn.WriteToUDP(buf, address) if err != nil { cntOutErr++ fmt.Fprintf(os.Stderr, "write fail %s \n", err) } cntOut++ }
func myNetwork_serverSend(c *net.UDPConn, packet []byte, cAddr *net.UDPAddr) { if rand.Intn(4) != 10 { //25% failure rate c.WriteToUDP(packet, cAddr) } else { log.Println("Dropped Packet: ", packet) } }
func WriteMessage(c *net.UDPConn, msg *Message, dst net.IP) (err os.Error) { out, err := msg.Marshal() if err != nil { return } _, err = c.WriteToUDP(out, &net.UDPAddr{IP: dst, Port: 67}) return }
func handleClient(conn *net.UDPConn) { var buf [512]byte _, addr, err := conn.ReadFromUDP(buf[0:]) if err != nil { return } daytime := time.Now().String() conn.WriteToUDP([]byte(daytime), addr) }
func sendReply(conn *net.UDPConn) { for { aReply := <-replyCh _, err := conn.WriteToUDP(aReply.data, aReply.addr) if err != nil { fmt.Fprintf(os.Stderr, "Failed to write to client: %v\n", err) //checkTempErr(err) } } }
func send(connection *net.UDPConn, outbound chan Packet, wg *sync.WaitGroup) { defer wg.Done() for packet := range outbound { _, err := connection.WriteToUDP(packet.data, packet.addr) if err != nil { log.Println("Error on write: ", err) continue } } }
// sendMsg bencodes the data in 'query' and sends it to the remote node. func sendMsg(conn *net.UDPConn, raddr *net.UDPAddr, query interface{}) { totalSent.Add(1) var b bytes.Buffer if err := bencode.Marshal(&b, query); err != nil { return } if _, err := conn.WriteToUDP(b.Bytes(), raddr); err != nil { // debug.Println("DHT: node write failed:", err) } return }
func (gatewayimpl *GatewayImpl) SendPullACK(conn *net.UDPConn, addr *net.UDPAddr, protocolversion byte, randomtoken uint16) error { out := make([]byte, 4) out[0] = protocolversion binary.LittleEndian.PutUint16(out[1:3], randomtoken) out[3] = byte(semtech.PullACK) _, err := conn.WriteToUDP(out, addr) if err != nil { return err } return nil }
func sendErrMessage(conn net.UDPConn, sendto *net.UDPAddr, errMsg clientServerUtils.ErrMessage) { req, err := json.Marshal(errMsg) if err != nil { fmt.Println("Error marshalling ErrMessage: ", err) os.Exit(-1) } _, err = conn.WriteToUDP(req, sendto) if err != nil { fmt.Println("Error writing ErrMessage to client: ", err) } }
func SendMsg(conn *net.UDPConn, returnAddress *net.UDPAddr, msg Message) { b, err := msgpack.Marshal(msg) if err != nil { // do something! } bytesWritten, networkErr := conn.WriteToUDP(b, returnAddress) if networkErr != nil { log.Fatalf("FAILED TO WRITE %d BYTES. Reason: %v", bytesWritten, networkErr) } }
func udp_transmit_server(lconn, bconn *net.UDPConn, send_ch <-chan udpMessage) { for { msg := <-send_ch if msg.raddr == "broadcast" { lconn.WriteToUDP(msg.data, baddr) } else { raddr, _ := net.ResolveUDPAddr("udp", msg.raddr) lconn.WriteToUDP(msg.data, raddr) } } }