Exemplo n.º 1
0
// GetOriginalDst returns original destination of Conn
func GetOriginalDst(c net.Conn) (string, error) {
	tcp, ok := c.(*net.TCPConn)
	if !ok {
		return "", errors.New("socket is not tcp")
	}
	file, err := tcp.File()
	if err != nil {
		return "", err
	}
	defer file.Close()
	sa, err := syscall.Getsockname(int(file.Fd()))
	if err != nil {
		return "", err
	}

	var addr net.TCPAddr
	if v, ok := sa.(*syscall.SockaddrInet4); ok {
		addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port}
	} else if v, ok := sa.(*syscall.SockaddrInet6); ok {
		addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port, Zone: zoneToString(int(v.ZoneId))}
	} else {
		return "", errors.New("socket is not ipv4")
	}
	return addr.String(), nil
}
Exemplo n.º 2
0
func (thisNode *node) removeDeadFinger(deadAddress *net.TCPAddr) {
	// If a connected node disappears, remove it from the finger table.
	var closestFinger *net.TCPAddr
	for _, entry := range thisNode.fingerTable {
		if entry.fingerAddress != nil && entry.fingerAddress.String() == deadAddress.String() {
			entry.fingerAddress = nil
		} else if entry.fingerAddress != nil && closestFinger == nil {
			closestFinger = entry.fingerAddress
		}
	}
	// If it's the predecessor, remove it.
	if thisNode.predecessorAddress.String() == deadAddress.String() {
		thisNode.predecessorAddress = nil
	}
	// If there was some other finger, replace it.
	if closestFinger != nil {
		thisNode.SetSuccessor(closestFinger)
	} else if thisNode.predecessorAddress != nil {
		// There was no other finger in the table, but maybe as a predecessor?
		thisNode.SetSuccessor(thisNode.predecessorAddress)
	} else {
		// If not, become a singular node ring.
		thisNode.MakeIntoRing()
	}
}
Exemplo n.º 3
0
// Generate all publishable URLs for a given HTTP port.
func interfaceURLs(port int) (types.URLs, error) {
	allAddrs, err := net.InterfaceAddrs()
	if err != nil {
		return []url.URL{}, err
	}

	var allURLs types.URLs
	for _, a := range allAddrs {
		ip, ok := a.(*net.IPNet)
		if !ok || !ip.IP.IsGlobalUnicast() {
			continue
		}

		tcp := net.TCPAddr{
			IP:   ip.IP,
			Port: port,
		}

		u := url.URL{
			Scheme: "http",
			Host:   tcp.String(),
		}
		allURLs = append(allURLs, u)
	}

	if len(allAddrs) == 0 {
		return []url.URL{}, fmt.Errorf("no publishable addresses")
	}

	return allURLs, nil
}
Exemplo n.º 4
0
// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: int(port)}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
	metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)

	// Send our state
	if err := m.sendLocalState(conn, join); err != nil {
		return nil, nil, err
	}

	// Read remote state
	_, remote, userState, err := m.readRemoteState(conn)
	if err != nil {
		err := fmt.Errorf("Reading remote state failed: %v", err)
		return nil, nil, err
	}

	// Return the remote state
	return remote, userState, nil
}
Exemplo n.º 5
0
// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: m.config.TCPPort}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[INFO] Initiating push/pull sync with: %s", conn.RemoteAddr())

	// Send our state
	if err := m.sendLocalState(conn); err != nil {
		return nil, nil, err
	}

	// Read remote state
	remote, userState, err := m.readRemoteState(conn)
	if err != nil {
		err := fmt.Errorf("Reading remote state failed: %v", err)
		return nil, nil, err
	}

	// Return the remote state
	return remote, userState, nil
}
Exemplo n.º 6
0
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s message", os.Args[0])
		os.Exit(1)
	}
	message := os.Args[1]

	serverIP := "127.0.0.1" //サーバ側のIP
	serverPort := "55555"   //サーバ側のポート番号
	myIP := "127.0.0.1"     //クライアント側のIP
	myPort := 55556         //クライアント側のポート番号

	tcpAddr, err := net.ResolveTCPAddr("tcp", serverIP+":"+serverPort)
	checkError(err)
	myAddr := new(net.TCPAddr)
	myAddr.IP = net.ParseIP(myIP)
	myAddr.Port = myPort
	conn, err := net.DialTCP("tcp", myAddr, tcpAddr)
	checkError(err)
	defer conn.Close()

	conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
	conn.Write([]byte(message))

	readBuf := make([]byte, 1024)
	conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	readlen, err := conn.Read(readBuf)
	checkError(err)

	fmt.Println("server: " + string(readBuf[:readlen]))
}
Exemplo n.º 7
0
func ts6_main(msg chan string, exit chan int) {

	// No configuration, so this is fixed.
	var addr net.TCPAddr
	addr.IP = net.IPv4(127, 0, 0, 1)
	addr.Port = 3725

	// Start our listener.
	l, err := net.ListenTCP("tcp4", &addr)
	if err != nil {
		fmt.Printf("No bind: %s\n", err)
		exit <- 0
	} else {
		go listen(l)

		// Again, no configuration.
		addr.Port = 13725
		c, err := net.DialTCP("tcp4", nil, &addr)
		if err != nil {
			fmt.Printf("No connection: %s\n", err)
		} else {
			go link(c, true)
		}
	}

	// Handle messages.
	for message := range msg {
		if message == "exit" {
			exit <- 0
		}
	}
}
Exemplo n.º 8
0
// detailedOutput is used to dump all known information about nodes in
// their raw format
func (c *MembersCommand) detailedOutput(members []agent.Member) []string {
	result := make([]string, 0, len(members))
	header := "Node|Address|Status|Tags"
	result = append(result, header)
	for _, member := range members {
		// Get the tags sorted by key
		tagKeys := make([]string, 0, len(member.Tags))
		for key := range member.Tags {
			tagKeys = append(tagKeys, key)
		}
		sort.Strings(tagKeys)

		// Format the tags as tag1=v1,tag2=v2,...
		var tagPairs []string
		for _, key := range tagKeys {
			tagPairs = append(tagPairs, fmt.Sprintf("%s=%s", key, member.Tags[key]))
		}

		tags := strings.Join(tagPairs, ",")

		addr := net.TCPAddr{IP: member.Addr, Port: int(member.Port)}
		line := fmt.Sprintf("%s|%s|%s|%s",
			member.Name, addr.String(), member.Status, tags)
		result = append(result, line)
	}
	return result
}
Exemplo n.º 9
0
func (p *httpProxyClient) DialTCP(network string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
	if laddr != nil || laddr.Port != 0 {
		return nil, errors.New("代理协议不支持指定本地地址。")
	}

	return p.DialTCPSAddr(network, raddr.String())
}
Exemplo n.º 10
0
// sendAndReceiveState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: int(port)}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
	metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)

	// Send our state
	if err := m.sendLocalState(conn, join); err != nil {
		return nil, nil, err
	}

	conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
	msgType, bufConn, dec, err := m.readTCP(conn)
	if err != nil {
		return nil, nil, err
	}

	// Quit if not push/pull
	if msgType != pushPullMsg {
		err := fmt.Errorf("received invalid msgType (%d), expected pushPullMsg (%d) %s", msgType, pushPullMsg, LogConn(conn))
		return nil, nil, err
	}

	// Read remote state
	_, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
	return remoteNodes, userState, err
}
Exemplo n.º 11
0
func (d *DHT) replyAnnouncePeer(addr net.UDPAddr, node *remoteNode, r responseType) {
	ih := InfoHash(r.A.InfoHash)
	if log.V(3) {
		log.Infof("DHT: announce_peer. Host %v, nodeID: %x, infoHash: %x, peerPort %d, distance to me %x",
			addr, r.A.Id, ih, r.A.Port, hashDistance(ih, InfoHash(d.nodeId)),
		)
	}
	// node can be nil if, for example, the server just restarted and received an announce_peer
	// from a node it doesn't yet know about.
	if node != nil && d.checkToken(addr, r.A.Token) {
		peerAddr := net.TCPAddr{IP: addr.IP, Port: r.A.Port}
		d.peerStore.addContact(ih, nettools.DottedPortToBinary(peerAddr.String()))
		// Allow searching this node immediately, since it's telling us
		// it has an infohash. Enables faster upgrade of other nodes to
		// "peer" of an infohash, if the announcement is valid.
		node.lastResponseTime = time.Now().Add(-searchRetryPeriod)
		if d.peerStore.hasLocalDownload(ih) {
			d.PeersRequestResults <- map[InfoHash][]string{ih: []string{nettools.DottedPortToBinary(peerAddr.String())}}
		}
	}
	// Always reply positively. jech says this is to avoid "back-tracking", not sure what that means.
	reply := replyMessage{
		T: r.T,
		Y: "r",
		R: map[string]interface{}{"id": d.nodeId},
	}
	sendMsg(d.conn, addr, reply)
}
Exemplo n.º 12
0
Arquivo: main.go Projeto: dilfish/dist
func MakeConn(ip string) (*net.TCPConn, error) {
	var addr net.TCPAddr
	addr.IP = net.ParseIP(ip)
	addr.Port = Port
	c, err := net.DialTCP("tcp4", nil, &addr)
	return c, err
}
Exemplo n.º 13
0
Arquivo: socket.go Projeto: htee/hteed
func CreateTCPSocket(proto, addr string) (net.Listener, error) {
	var err error
	var laddr *net.TCPAddr

	laddr, err = net.ResolveTCPAddr(proto, addr)
	if err != nil {
		return nil, err
	}

	family, ipv6only := favoriteTCPAddrFamily(proto, laddr, "listen")

	var socketAddr syscall.Sockaddr
	if socketAddr, err = ipToSockaddr(family, laddr.IP, laddr.Port, laddr.Zone); err != nil {
		panic(err)
		return nil, err
	}

	var s int
	if s, err = sysSocket(family, syscall.SOCK_STREAM, 0); err != nil {
		return nil, err
	}

	if err = setDefaultSockopts(s, family, syscall.SOCK_STREAM, ipv6only); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = setDefaultListenerSockopts(s); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = syscall.SetsockoptInt(s, syscall.SOL_SOCKET, SO_REUSEPORT, 1); err != nil {
		closesocket(s)
		panic(err)
		return nil, err
	}

	if err = syscall.Bind(s, socketAddr); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = syscall.Listen(s, maxListenerBacklog()); err != nil {
		closesocket(s)
		return nil, err
	}

	file := os.NewFile(uintptr(s), "listener-"+laddr.String())
	defer file.Close()

	var socketListener net.Listener
	if socketListener, err = net.FileListener(file); err != nil {
		return nil, err
	}

	return socketListener, nil

}
Exemplo n.º 14
0
func mustConnectLookupd(t *testing.T, tcpAddr *net.TCPAddr) net.Conn {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		t.Fatal("failed to connect to lookupd")
	}
	conn.Write(nsq.MagicV1)
	return conn
}
Exemplo n.º 15
0
func mustConnectNSQD(tcpAddr *net.TCPAddr) (net.Conn, error) {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		return nil, err
	}
	conn.Write(nsq.MagicV2)
	return conn, nil
}
Exemplo n.º 16
0
func ServeHTTPBooter(listenAddr net.TCPAddr, ds datasource.DataSource, webPort int) error {
	logging.Log("HTTPBOOTER", "Listening on %s", listenAddr.String())
	mux, err := HTTPBooterMux(listenAddr, ds, webPort)
	if err != nil {
		return err
	}
	return http.ListenAndServe(listenAddr.String(), mux)
}
Exemplo n.º 17
0
func mustConnectGFW(tcpAddr *net.TCPAddr) (net.Conn, error) {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		return nil, err
	}
	conn.Write([]byte("  V1"))
	return conn, nil
}
Exemplo n.º 18
0
func ServeHTTPBooter(listenAddr net.TCPAddr, runtimeConfig *datasource.RuntimeConfiguration, bootParamsRepo *cloudconfig.Repo) error {
	logging.Log("HTTPBOOTER", "Listening on %s", listenAddr.String())
	mux, err := HTTPBooterMux(listenAddr, runtimeConfig, bootParamsRepo)
	if err != nil {
		return err
	}
	return http.ListenAndServe(listenAddr.String(), mux)
}
Exemplo n.º 19
0
// No routine in package net to test if an address is v4 or v6?
func isTCPIPv6(address *net.TCPAddr) bool {
	if strings.HasPrefix(address.String(), "<nil>") {
		return false
	} else {
		return (address.String()[0] == '[')
	}
	return false // Should never arrive here
}
Exemplo n.º 20
0
func (c *MembersCommand) Run(args []string) int {
	var detailed bool
	var roleFilter, statusFilter string
	cmdFlags := flag.NewFlagSet("members", flag.ContinueOnError)
	cmdFlags.Usage = func() { c.Ui.Output(c.Help()) }
	cmdFlags.BoolVar(&detailed, "detailed", false, "detailed output")
	cmdFlags.StringVar(&roleFilter, "role", ".*", "role filter")
	cmdFlags.StringVar(&statusFilter, "status", ".*", "status filter")
	rpcAddr := RPCAddrFlag(cmdFlags)
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	// Compile the regexp
	roleRe, err := regexp.Compile(roleFilter)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to compile role regexp: %v", err))
		return 1
	}
	statusRe, err := regexp.Compile(statusFilter)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to compile status regexp: %v", err))
		return 1
	}

	client, err := RPCClient(*rpcAddr)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error connecting to Serf agent: %s", err))
		return 1
	}
	defer client.Close()

	members, err := client.Members()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error retrieving members: %s", err))
		return 1
	}

	for _, member := range members {
		// Skip the non-matching members
		if !roleRe.MatchString(member.Role) || !statusRe.MatchString(member.Status) {
			continue
		}

		addr := net.TCPAddr{IP: member.Addr, Port: int(member.Port)}
		c.Ui.Output(fmt.Sprintf("%s    %s    %s    %s",
			member.Name, addr.String(), member.Status, member.Role))

		if detailed {
			c.Ui.Output(fmt.Sprintf("    Protocol Version: %d",
				member.DelegateCur))
			c.Ui.Output(fmt.Sprintf("    Available Protocol Range: [%d, %d]",
				member.DelegateMin, member.DelegateMax))
		}
	}

	return 0
}
Exemplo n.º 21
0
// Send DataItems to Zabbix server and wait for response.
// Returns encountered fatal error like I/O and marshalling/unmarshalling.
// Caller should inspect response (and in some situations also Zabbix server log)
// to check if all items are accepted.
func Send(addr *net.TCPAddr, di DataItems) (res *Response, err error) {
	b, err := di.Marshal()
	if err != nil {
		return
	}

	// Zabbix doesn't support persistent connections, so open/close it every time.
	conn, err := net.DialTCP(addr.Network(), nil, addr)
	if err != nil {
		return
	}
	defer conn.Close()

	_, err = conn.Write(b)
	if err != nil {
		return
	}

	buf := make([]byte, 8)
	_, err = io.ReadFull(conn, buf[:5])
	if err != nil {
		return
	}
	if !bytes.Equal(buf[:5], header) {
		err = ErrBadHeader
		return
	}

	_, err = io.ReadFull(conn, buf)
	if err != nil {
		return
	}
	var datalen uint64
	err = binary.Read(bytes.NewBuffer(buf), binary.LittleEndian, &datalen)
	if err != nil {
		err = ErrBadHeader
		return
	}

	buf = make([]byte, datalen)
	_, err = io.ReadFull(conn, buf)
	if err != nil {
		return
	}

	res = new(Response)
	err = json.Unmarshal(buf, res)
	if err == nil {
		m := infoRE.FindStringSubmatch(res.Info)
		if len(m) == 3 {
			p, _ := strconv.Atoi(m[1])
			f, _ := strconv.Atoi(m[2])
			res.Processed = p
			res.Failed = f
		}
	}
	return
}
Exemplo n.º 22
0
func CheckStatusOld(addr *net.TCPAddr, host string, port uint16) (*MinecraftStatus, time.Duration, error) {
	conn, err := net.DialTCP(addr.Network(), nil, addr)
	if err != nil {
		return nil, 0, fmt.Errorf("CheckStatusOld error dialing: %s", err)
	}
	defer conn.Close()
	status, ping, err := CheckStatusOldConn(conn, host, port)
	return status, ping, err
}
Exemplo n.º 23
0
func Serve(listenAddr net.TCPAddr, datasource *datasource.DataSource) error {
	logging.Log(debugTag, "Serving Rest API on %s", listenAddr)
	restApi := newRestServerAPI(datasource)
	handler, err := restApi.MakeHandler()
	if err != nil {
		return err
	}
	return http.ListenAndServe(listenAddr.String(), handler)
}
Exemplo n.º 24
0
func (cluster *mongoCluster) server(addr string, tcpaddr *net.TCPAddr) *mongoServer {
	cluster.RLock()
	server := cluster.servers.Search(tcpaddr.String())
	cluster.RUnlock()
	if server != nil {
		return server
	}
	return newServer(addr, tcpaddr, cluster.sync, cluster.dial)
}
Exemplo n.º 25
0
func sendAliasBackupToPredecessor(sourceAddress, receiver *net.TCPAddr, alias string) error {
	var (
		fail = fmt.Errorf("failed: sendAliasBackupToPredecessor(%s, %s)", receiver.String(), alias)
		err  error
	)
	if _, err = sendArgument(sourceAddress, receiver, "AliasBackupToPredecessor", alias); err != nil {
		return fmt.Errorf("%s:\n%s", fail.Error(), err.Error())
	}
	return nil
}
Exemplo n.º 26
0
// Helper function to decode a *net.TCPAddr into a tuple of network and
// address. Must use this since kavu/so_reuseport does not currently
// support passing "tcp" to support for IPv4 and IPv6. We must pass "tcp4"
// or "tcp6" explicitly.
func decodeAddress(tuple *net.TCPAddr) (network, address string) {
	if tuple.IP.To4() != nil {
		network = "tcp4"
	} else {
		network = "tcp6"
	}

	address = tuple.String()
	return
}
Exemplo n.º 27
0
func deleteAliasAtPredecessor(sourceAddress, receiver *net.TCPAddr, hashOfName string) error {
	var (
		fail = fmt.Errorf("failed: deleteAliasAtPredecessor(%s, %s)", receiver.String(), hashOfName)
		err  error
	)
	if _, err = sendArgument(sourceAddress, receiver, "DeleteAliasAtPredecessor", hashOfName); err != nil {
		return fmt.Errorf("%s:\n%s", fail.Error(), err.Error())
	}
	return nil
}
Exemplo n.º 28
0
func TCPAddr(buf []byte) (net.TCPAddr, int) {

	var value net.TCPAddr
	value.IP = make([]byte, 16)
	copy(value.IP, buf[:16])
	value.Port = int(binary.BigEndian.Uint16(buf[16:18]))

	return value, Size

}
Exemplo n.º 29
-1
func ProxyRelay(port string, relays map[string]Relay) error {
	tcpAddr := net.TCPAddr{}
	tcpAddr.IP = net.ParseIP("127.0.0.1")
	tcpAddr.Port, _ = strconv.Atoi(port)
	ln, err := net.ListenTCP("tcp", &tcpAddr)
	if err != nil {
		msg := fmt.Sprintf("Proxy listener error on port %s: %s",
			port, err)
		LogWriter.Err(msg)
		return fmt.Errorf(msg)
	}
	msg := fmt.Sprintf("Started proxy listener on port: %s",
		port)
	LogWriter.Info(msg)
	defer ln.Close()
	for {
		conn, err := ln.AcceptTCP()
		if err != nil {
			msg := fmt.Sprintf("Error accepting TCP connection on port %s: %s",
				port, err)
			LogWriter.Err(msg)
			continue
		}
		conn.SetKeepAlive(true)
		if err != nil {
			msg := fmt.Sprintf("Error setting keep-alive on connection: %s",
				err)
			LogWriter.Err(msg)
		}
		go acceptClient(conn, relays)
	}
	return nil
}
Exemplo n.º 30
-2
func makeNewNode(host string, port int) (*node, error) {
	var (
		resolvedAddress *net.TCPAddr
		err             error
	)
	if resolvedAddress, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(host, strconv.Itoa(port))); err != nil {
		return nil, err
	}
	newNode := new(node)
	newNode.SetAddress(resolvedAddress)
	if host == "" {
		return nil, ErrNotYetImplemented
	} else {
		newNode.baseKey = hashString(resolvedAddress.String())
	}
	entries := M()
	newNode.fingerTable = make([]*tableEntry, entries, entries)
	for row := 0; row < entries; row++ {
		newNode.SetTableEntry(row, nil)
	}
	newNode.dataStorage = make(map[string][]byte)
	newNode.backupStorageOfPredecessorsData = make(map[string][]byte)
	newNode.backupStorageOfSuccessorsData = make(map[string][]byte)
	newNode.aliasStorage = make(map[string]string)
	newNode.backupStorageOfPredecessorsAliases = make(map[string]string)
	newNode.backupStorageOfSuccessorsAliases = make(map[string]string)
	newNode.wgs = new(waitGroups)
	return newNode, nil
}