예제 #1
0
func main() {
	defer envpprof.Stop()
	listen := flag.Bool("l", false, "listen")
	port := flag.Int("p", 0, "port to listen on")
	flag.Parse()
	var (
		conn net.Conn
		err  error
	)
	if *listen {
		s, err := utp.NewSocket("udp", fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer s.Close()
		conn, err = s.Accept()
		if err != nil {
			log.Fatal(err)
		}
	} else {
		conn, err = utp.Dial(net.JoinHostPort(flag.Arg(0), flag.Arg(1)))
		if err != nil {
			log.Fatal(err)
		}
	}
	defer conn.Close()
	go func() {
		sig := make(chan os.Signal, 1)
		signal.Notify(sig, os.Interrupt)
		<-sig
		conn.Close()
	}()
	writerDone := make(chan struct{})
	readerDone := make(chan struct{})
	go func() {
		defer close(writerDone)
		written, err := io.Copy(conn, os.Stdin)
		if err != nil {
			conn.Close()
			log.Fatalf("error after writing %d bytes: %s", written, err)
		}
		log.Printf("wrote %d bytes", written)
		conn.Close()
	}()
	go func() {
		defer close(readerDone)
		n, err := io.Copy(os.Stdout, conn)
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("received %d bytes", n)
	}()
	// Technically we should wait until both reading and writing are done. But
	// ucat-style binaries terminate abrubtly when read or write is completed,
	// and no state remains to clean-up the peer neatly.
	select {
	case <-writerDone:
	case <-readerDone:
	}
}
예제 #2
0
func main() {
	list := flag.Bool("l", false, "listen on the given address")
	spew := flag.Bool("spew", false, "spew random data on the connection")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [-l] <host> <port>\n", os.Args[0])
	}

	flag.Parse()

	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt)

	if len(flag.Args()) < 2 {
		flag.Usage()
		os.Exit(1)
	}

	addr := fmt.Sprintf("%s:%s", flag.Arg(0), flag.Arg(1))

	var con io.ReadWriteCloser
	if *list {
		sock, err := utp.NewSocket("udp", addr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "create socket failed: %s\n", err)
			os.Exit(1)
		}

		defer sock.Close()

		utpcon, err := sock.Accept()
		if err != nil {
			fmt.Fprintf(os.Stderr, "accept failed: %s\n", err)
			os.Exit(1)
		}

		con = utpcon
	} else {
		utpcon, err := utp.Dial(addr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "dial failed: %s\n", err)
			os.Exit(1)
		}

		con = utpcon
	}

	var in io.Reader = os.Stdin
	if *spew {
		in = rand.New()
	}

	go func() {
		<-c
		con.Close()
	}()
	beNetcat(con, in)
}
예제 #3
0
func TryConnect(h string, networkSecret *secure.NetworkSecret, ln *LocalNode) (*RemoteNode, error) {
	host, portStr, errSplit := net.SplitHostPort(h)
	if errSplit != nil {
		return nil, errSplit
	}

	port, errConvert := strconv.Atoi(portStr)
	if errConvert != nil {
		return nil, errConvert
	}

	rn := new(RemoteNode)
	rn.lastHeartbeat = time.Now()
	rn.publicAddress = fmt.Sprintf("%s:%d", host, port+1)

	rn.logger = log.L(fmt.Sprintf("public %s", rn.publicAddress))
	rn.logger.Debug("trying to connect...")

	s, errSocket := utp.NewSocket("udp4", ":0")
	if errSocket != nil {
		rn.logger.Error("unable to crete a socket, %v", errSocket)
		return nil, errSocket
	}

	conn, errDial := s.DialTimeout(rn.publicAddress, 10*time.Second)
	if errDial != nil {
		rn.logger.Error("unable to dial, %s", errDial)
		return nil, errDial
	}

	rn.conn = conn
	rn.sessionKey = RandomBytes(16)

	if err := protocol.WriteEncodeHandshake(rn.conn, rn.sessionKey, networkSecret); err != nil {
		return nil, err
	}
	if _, okError := protocol.ReadDecodeOk(rn.conn); okError != nil {
		return nil, okError
	}

	peerInfo, errPeerInfo := protocol.ReadDecodePeerInfo(rn.conn)
	if errPeerInfo != nil {
		return nil, errPeerInfo
	}

	rn.privateIP = peerInfo.PrivateIP()

	// create new logger
	log.RemoveLogger(rn.logger.Name())
	rn.logger = log.L(fmt.Sprintf(rnLoggerFormat, rn.privateIP.String()))

	if err := protocol.WriteEncodePeerInfo(rn.conn, ln.State().PrivateIP); err != nil {
		return nil, err
	}

	rn.logger.Info("connected, with public address %q", rn.publicAddress)
	return rn, nil
}
예제 #4
0
파일: listener.go 프로젝트: intfrr/meshbird
func (l *ListenerService) Init(ln *LocalNode) error {
	l.logger = log.New(os.Stderr, "[listener] ", log.LstdFlags)

	l.logger.Printf("Listening on port: %d", ln.State().ListenPort+1)
	socket, err := utp.NewSocket("udp4", fmt.Sprintf("0.0.0.0:%d", ln.State().ListenPort+1))
	if err != nil {
		return err
	}

	l.localNode = ln
	l.socket = socket
	return nil
}
예제 #5
0
func (d *Dialer) Dial(rnet string, raddr string) (net.Conn, error) {
	if d.LocalAddr != nil {
		s, err := utp.NewSocket(d.LocalAddr.Network(), d.LocalAddr.String())
		if err != nil {
			return nil, err
		}

		// zero timeout is the same as calling s.Dial()
		return s.DialTimeout(raddr, d.Timeout)
	}

	return utp.DialTimeout(raddr, d.Timeout)
}
예제 #6
0
func (l *ListenerService) Init(ln *LocalNode) error {
	l.logger = log.L(l.Name())

	port := ln.State().ListenPort + 1
	l.logger.Info("listening on %d port", port)
	socket, err := utp.NewSocket("udp4", fmt.Sprintf("0.0.0.0:%d", port))
	if err != nil {
		return err
	}

	l.localNode = ln
	l.socket = socket
	return nil
}
예제 #7
0
파일: ucat.go 프로젝트: petar/utp
func main() {
	defer envpprof.Stop()
	listen := flag.Bool("l", false, "listen")
	port := flag.Int("p", 0, "port to listen on")
	flag.Parse()
	var (
		conn net.Conn
		err  error
	)
	if *listen {
		s, err := utp.NewSocket("udp", fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer s.Close()
		conn, err = s.Accept()
		if err != nil {
			log.Fatal(err)
		}
	} else {
		conn, err = utp.Dial(net.JoinHostPort(flag.Arg(0), flag.Arg(1)))
		if err != nil {
			log.Fatal(err)
		}
	}
	defer conn.Close()
	go func() {
		sig := make(chan os.Signal, 1)
		signal.Notify(sig, os.Interrupt)
		<-sig
		conn.Close()
	}()
	writerDone := make(chan struct{})
	go func() {
		defer close(writerDone)
		written, err := io.Copy(conn, os.Stdin)
		if err != nil {
			conn.Close()
			log.Fatalf("error after writing %d bytes: %s", written, err)
		}
		log.Printf("wrote %d bytes", written)
		conn.Close()
	}()
	n, err := io.Copy(os.Stdout, conn)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("received %d bytes", n)
	// <-writerDone
}
예제 #8
0
func Listen(network string, laddr string) (net.Listener, error) {
	switch network {
	case "utp", "utp4", "utp6":
		s, err := utp.NewSocket("udp"+network[3:], laddr)
		if err != nil {
			return nil, err
		}

		return &Listener{s}, nil

	default:
		return nil, errors.New("unrecognized network: " + network)
	}
}
예제 #9
0
func server(wg *sync.WaitGroup, host string, port int) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("error: %s", r)
		}
		wg.Done()
	}()
	log.Printf("server listen %s:%d", host, port)
	s, err := utp.NewSocket("udp", fmt.Sprintf("%s:%d", host, port))
	if err != nil {
		panic(err)
	}
	defer s.Close()
	for {
		conn, err := s.Accept()
		if err != nil {
			panic(err)
		}
		wg.Add(1)
		go readConn(conn)
	}
}
예제 #10
0
func TestUTPRawConn(t *testing.T) {
	l, err := utp.NewSocket("udp", "")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	go func() {
		for {
			_, err := l.Accept()
			if err != nil {
				break
			}
		}
	}()
	// Connect a UTP peer to see if the RawConn will still work.
	s, _ := utp.NewSocket("udp", "")
	defer s.Close()
	utpPeer, err := s.Dial(fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
	if err != nil {
		t.Fatalf("error dialing utp listener: %s", err)
	}
	defer utpPeer.Close()
	peer, err := net.ListenPacket("udp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	defer peer.Close()

	msgsReceived := 0
	// How many messages to send. I've set this to double the channel buffer
	// size in the raw packetConn.
	const N = 200
	readerStopped := make(chan struct{})
	// The reader goroutine.
	go func() {
		defer close(readerStopped)
		b := make([]byte, 500)
		for i := 0; i < N; i++ {
			n, _, err := l.ReadFrom(b)
			if err != nil {
				t.Fatalf("error reading from raw conn: %s", err)
			}
			msgsReceived++
			var d int
			fmt.Sscan(string(b[:n]), &d)
			if d != i {
				log.Printf("got wrong number: expected %d, got %d", i, d)
			}
		}
	}()
	udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
	if err != nil {
		t.Fatal(err)
	}
	for i := 0; i < N; i++ {
		_, err := peer.WriteTo([]byte(fmt.Sprintf("%d", i)), udpAddr)
		if err != nil {
			t.Fatal(err)
		}
		time.Sleep(time.Microsecond)
	}
	select {
	case <-readerStopped:
	case <-time.After(time.Second):
		t.Fatal("reader timed out")
	}
	if msgsReceived != N {
		t.Fatalf("messages received: %d", msgsReceived)
	}
}
예제 #11
0
파일: client.go 프로젝트: jakop345/torrent
func listenUTP(networkSuffix, addr string) (*utp.Socket, error) {
	return utp.NewSocket("udp"+networkSuffix, addr)
}