ptp

package
v6.3.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2018 License: GPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Package ptp is a generated protocol buffer package.

It is generated from these files:

dht.proto

It has these top-level messages:

DHTPacket

Index

Constants

View Source
const (
	MagicCookie uint16 = 0xabcd
	HeaderSize  int    = 10
)

Constants

View Source
const (
	EthPacketSize        int        = 512
	PacketPARCUniversal  PacketType = 512
	PacketIPv4           PacketType = 2048
	PacketARP            PacketType = 2054
	PacketRARP           PacketType = 32821
	Packet8021Q          PacketType = 33024
	PacketIPv6           PacketType = 34525
	PacketPPPoEDiscovery PacketType = 34915
	PacketPPPoESession   PacketType = 34916
	PacketLLDP           PacketType = 35020
)

Packet Types

View Source
const (
	ConfigDir  string = "/usr/local/etc"
	DefaultMTU int    = 1376
)

Constants

View Source
const (
	MsgTypeString    MsgType = 0  // String
	MsgTypeIntro             = 1  // Introduction packet
	MsgTypeIntroReq          = 2  // Request for introduction packet
	MsgTypeNenc              = 3  // Not encrypted message
	MsgTypeEnc               = 4  // Encrypted message
	MsgTypePing              = 5  // Internal ping message for Proxies
	MsgTypeXpeerPing         = 6  // Crosspeer ping message
	MsgTypeTest              = 7  // Packet tests established connection
	MsgTypeProxy             = 8  // Information about proxy (forwarder)
	MsgTypeBadTun            = 9  // Notifies about dead tunnel
	MsgTypeConf              = 10 // Confirmation
)

Internal network packet type

View Source
const (
	DhtCmdConn        string = "conn"
	DhtCmdFrwd        string = "frwd"
	DhtCmdFind        string = "find"
	DhtCmdNode        string = "node"
	DhtCmdPing        string = "ping"
	DhtCmdRegProxy    string = "regcp"
	DhtCmdBadProxy    string = "badcp"
	DhtCmdProxy       string = "cp"
	DhtCmdNotify      string = "notify"
	DhtCmdLoad        string = "load"
	DhtCmdStop        string = "stop"
	DhtCmdUnknown     string = "unk"
	DhtCmdDhcp        string = "dhcp"
	DhtCmdError       string = "error"
	DhtCmdUnsupported string = "unsupported"
	DhtCmdState       string = "state"
)

List of commands used in DHT

View Source
const (
	PeerStateInit             PeerState = 1  // Peer has been added recently.
	PeerStateRequestedIP                = 2  // We know ID of a peer, but don't know it's IPs
	PeerStateRequestingProxy            = 3  // Requesting proxies for this peer
	PeerStateWaitingForProxy            = 4  // Waiting for proxies
	PeerStateWaitingToConnect           = 5  // Waiting for other peer to start establishing connection
	PeerStateConnecting                 = 6  // Trying to establish connection
	PeerStateConnected                  = 7  // Connected, handshaked and operating normally
	PeerStateDisconnect                 = 8  // We're disconnecting
	PeerStateStop                       = 9  // Peer has been stopped and now can be removed from list of peers
	PeerStateCooldown                   = 10 // Peer is in cooldown mode
)

Peer state

View Source
const (
	DHTMaxRetries         int           = 10
	DHCPMaxRetries        int           = 10
	PeerPingTimeout       time.Duration = time.Second * 1
	WaitProxyTimeout      time.Duration = time.Second * 5
	HandshakeProxyTimeout time.Duration = time.Second * 3
)

Timeouts and retries

View Source
const DHTBufferSize = 1024

DHTBufferSize is a size of DHT buffer

View Source
const (
	// DhtErrorUnsupported - Unsupported version
	DhtErrorUnsupported string = "unsupported"
)
View Source
const (
	MaximumInterfaceNameLength int = 12
)
View Source
const PacketVersion int32 = 20005

PacketVersion is a version of packet used in DHT communication

Variables

View Source
var (
	// ErrInvalidHardwareAddr is returned when one or more invalid hardware
	// addresses are passed to NewPacket.
	ErrInvalidHardwareAddr = errors.New("invalid hardware address")

	// ErrInvalidIP is returned when one or more invalid IPv4 addresses are
	// passed to NewPacket.
	ErrInvalidIP = errors.New("invalid IPv4 address")

	// PacketID is a ID of the received packet
	PacketID uint16
)
View Source
var ActiveInterfaces []net.IP

ActiveInterfaces is a global (daemon-wise) list of reserved IP addresses

View Source
var DHTPacketType_name = map[int32]string{
	0:  "Undefined",
	1:  "Connect",
	2:  "Forward",
	3:  "Find",
	4:  "Node",
	5:  "Ping",
	6:  "RegisterProxy",
	7:  "RequestProxy",
	8:  "ReportProxy",
	9:  "BadProxy",
	10: "Proxy",
	11: "Notify",
	12: "ReportLoad",
	13: "Stop",
	14: "Unknown",
	15: "DHCP",
	16: "Error",
	17: "Unsupported",
	18: "State",
}
View Source
var DHTPacketType_value = map[string]int32{
	"Undefined":     0,
	"Connect":       1,
	"Forward":       2,
	"Find":          3,
	"Node":          4,
	"Ping":          5,
	"RegisterProxy": 6,
	"RequestProxy":  7,
	"ReportProxy":   8,
	"BadProxy":      9,
	"Proxy":         10,
	"Notify":        11,
	"ReportLoad":    12,
	"Stop":          13,
	"Unknown":       14,
	"DHCP":          15,
	"Error":         16,
	"Unsupported":   17,
	"State":         18,
}
View Source
var (
	// ErrorList stores known errors
	ErrorList map[ErrorType]error
)
View Source
var SupportedVersion = [...]int32{20005, 200006}

SupportedVersion is a list of versions supported by DHT server

Functions

func CheckPermissions

func CheckPermissions() bool

CheckPermissions validates platform specific permissions to run TUNTAP utilities

func FilterInterface

func FilterInterface(infName, infIP string) bool

FilterInterface will return true if this interface needs to be filtered out

func GenerateMAC

func GenerateMAC() (string, net.HardwareAddr)

GenerateMAC generates a MAC address for a new interface

func GenerateToken

func GenerateToken() string

GenerateToken produces UUID string that will be used during handshake with DHT server. Since we don't have an ID on start - we will use token and wait from DHT server to respond with ID and our Token, so later we will replace Token with received ID

func GetConfigurationTool

func GetConfigurationTool() string

GetConfigurationTool function will return path to configuration tool on specific platform

func GetDeviceBase

func GetDeviceBase() string

GetDeviceBase returns a default interface name

func InitErrors

func InitErrors()

InitErrors populates ErrorList with error types

func InitPlatform

func InitPlatform()

InitPlatform does a platform specific preparation

func IsInterfaceLocal

func IsInterfaceLocal(ip net.IP) bool

IsInterfaceLocal will return true if specified IP is in list of local network interfaces

func Log

func Log(level LogLevel, format string, v ...interface{})

Log writes a log message

func SetMinLogLevel

func SetMinLogLevel(level LogLevel)

SetMinLogLevel sets a minimal logging level

func SetSyslogSocket

func SetSyslogSocket(socket string)

SetSyslogSocket sets an adders of the syslog server

func SetupPlatform

func SetupPlatform(remove bool)

SetupPlatform runs platform specific preparations during p2p daemon creation

func StringifyState

func StringifyState(state PeerState) string

StringifyState extracts human-readable word that represents a peer status

func Syslog

func Syslog(level LogLevel, format string, v ...interface{})

Syslog provides additional logging to the syslog server

Types

type ARPPacket

type ARPPacket struct {
	// HardwareType specifies an IANA-assigned hardware type, as described
	// in RFC 826.
	HardwareType uint16

	// ProtocolType specifies the internetwork protocol for which the ARP
	// request is intended.  Typically, this is the IPv4 EtherType.
	ProtocolType uint16

	// HardwareAddrLength specifies the length of the sender and target
	// hardware addresses included in a Packet.
	HardwareAddrLength uint8

	// IPLength specifies the length of the sender and target IPv4 addresses
	// included in a Packet.
	IPLength uint8

	// Operation specifies the ARP operation being performed, such as request
	// or reply.
	Operation Operation

	// SenderHardwareAddr specifies the hardware address of the sender of this
	// Packet.
	SenderHardwareAddr net.HardwareAddr

	// SenderIP specifies the IPv4 address of the sender of this Packet.
	SenderIP net.IP

	// TargetHardwareAddr specifies the hardware address of the target of this
	// Packet.
	TargetHardwareAddr net.HardwareAddr

	// TargetIP specifies the IPv4 address of the target of this Packet.
	TargetIP net.IP
}

ARPPacket represents an ARP packet

func (*ARPPacket) MarshalBinary

func (p *ARPPacket) MarshalBinary() ([]byte, error)

MarshalBinary allocates a byte slice containing the data from a Packet.

MarshalBinary never returns an error.

func (*ARPPacket) NewPacket

func (p *ARPPacket) NewPacket(op Operation, srcHW net.HardwareAddr, srcIP net.IP, dstHW net.HardwareAddr, dstIP net.IP) (*ARPPacket, error)

NewPacket creates new ARP packet

func (*ARPPacket) String

func (p *ARPPacket) String() string

func (*ARPPacket) UnmarshalARP

func (p *ARPPacket) UnmarshalARP(b []byte) error

UnmarshalARP unmarshals ARP header

type Configuration

type Configuration struct {
	IPTool  string `yaml:"iptool"`  // Network interface configuration tool
	AddTap  string `yaml:"addtap"`  // Path to addtap.bat
	InfFile string `yaml:"inffile"` // Path to deltap.bat
}

func (*Configuration) GetAddTap

func (y *Configuration) GetAddTap() string

func (*Configuration) GetIPTool

func (y *Configuration) GetIPTool() string

func (*Configuration) GetInfFile

func (y *Configuration) GetInfFile() string

func (*Configuration) Read

func (y *Configuration) Read() error

type Crypto

type Crypto struct {
	Keys      []CryptoKey
	ActiveKey CryptoKey
	Active    bool
}

Crypto is a object used by crypto subsystem

func (Crypto) EnrichKeyValues

func (c Crypto) EnrichKeyValues(ckey CryptoKey, key, datetime string) CryptoKey

EnrichKeyValues update information about current and feature keys

func (Crypto) ReadKeysFromFile

func (c Crypto) ReadKeysFromFile(filepath string)

ReadKeysFromFile read a file stored in a file system and extracts keys to be used

type CryptoKey

type CryptoKey struct {
	TTLConfig string `yaml:"ttl"`
	KeyConfig string `yaml:"key"`
	Until     time.Time
	Key       []byte
}

CryptoKey represents a key and it's expiration date

type DHTClient

type DHTClient struct {
	Routers       string                        // Comma-separated list of bootstrap nodes
	NetworkHash   string                        // Saved network hash
	ID            string                        // Current instance ID
	FailedRouters []string                      // List of routes that we failed to connect to
	Connections   []*net.TCPConn                // TCP connections to bootstrap nodes
	LocalPort     int                           // UDP port number used by this instance
	RemotePort    int                           // UDP port number reported by echo server
	Forwarders    []Forwarder                   // List of worwarders
	TCPCallbacks  map[DHTPacketType]dhtCallback // Callbacks for incoming packets
	Mode          OperatingMode                 // DHT Client mode ???
	IPList        []net.IP                      // List of network active interfaces
	IP            net.IP                        // IP of local interface received from DHCP or specified manually
	Network       *net.IPNet                    // Network information about current network. Used to inform p2p about mask for interface
	Connected     bool                          // Whether connection with bootstrap nodes established or not
	//isShutdown        bool                          // Whether DHT shutting down or not
	LastUpdate        time.Time // When last `find` packet was sent
	OutboundIP        net.IP    // Outbound IP
	ListenerIsRunning bool      // True if listener is runnning
	IncomingData      chan *DHTPacket
	OutgoingData      chan *DHTPacket
}

DHTClient is a main structure of a DHT client

func (*DHTClient) Close

func (dht *DHTClient) Close() error

Close will close all connections and switch DHT object to shutdown mode, which will terminate every loop/goroutine

func (*DHTClient) Connect

func (dht *DHTClient) Connect(ipList []net.IP, proxyList []*proxyServer) error

Connect sends `conn` packet to a DHT

func (*DHTClient) Init

func (dht *DHTClient) Init(hash string) error

Init bootstrap for this instance

func (*DHTClient) RegisterProxy

func (dht *DHTClient) RegisterProxy(ip net.IP, port int) error

RegisterProxy will register current node as a proxy on bootstrap node

func (*DHTClient) ReportLoad

func (dht *DHTClient) ReportLoad(clientsNum int) error

ReportLoad will send amount of tunnels created on particular proxy

func (*DHTClient) WaitID

func (dht *DHTClient) WaitID() error

WaitID will block DHT until valid instance ID is received from Bootstrap node or specified timeout passes.

type DHTPacket

type DHTPacket struct {
	Type      DHTPacketType `protobuf:"varint,1,opt,name=type,enum=main.DHTPacketType" json:"type,omitempty"`
	Id        string        `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
	Infohash  string        `protobuf:"bytes,3,opt,name=infohash" json:"infohash,omitempty"`
	Data      string        `protobuf:"bytes,4,opt,name=data" json:"data,omitempty"`
	Query     string        `protobuf:"bytes,5,opt,name=query" json:"query,omitempty"`
	Arguments []string      `protobuf:"bytes,6,rep,name=arguments" json:"arguments,omitempty"`
	Proxies   []string      `protobuf:"bytes,7,rep,name=proxies" json:"proxies,omitempty"`
	Extra     string        `protobuf:"bytes,8,opt,name=extra" json:"extra,omitempty"`
	Payload   []byte        `protobuf:"bytes,9,opt,name=payload,proto3" json:"payload,omitempty"`
	Version   int32         `protobuf:"varint,10,opt,name=version" json:"version,omitempty"`
}

func (*DHTPacket) Descriptor

func (*DHTPacket) Descriptor() ([]byte, []int)

func (*DHTPacket) GetArguments

func (m *DHTPacket) GetArguments() []string

func (*DHTPacket) GetData

func (m *DHTPacket) GetData() string

func (*DHTPacket) GetExtra

func (m *DHTPacket) GetExtra() string

func (*DHTPacket) GetId

func (m *DHTPacket) GetId() string

func (*DHTPacket) GetInfohash

func (m *DHTPacket) GetInfohash() string

func (*DHTPacket) GetPayload

func (m *DHTPacket) GetPayload() []byte

func (*DHTPacket) GetProxies

func (m *DHTPacket) GetProxies() []string

func (*DHTPacket) GetQuery

func (m *DHTPacket) GetQuery() string

func (*DHTPacket) GetType

func (m *DHTPacket) GetType() DHTPacketType

func (*DHTPacket) GetVersion

func (m *DHTPacket) GetVersion() int32

func (*DHTPacket) ProtoMessage

func (*DHTPacket) ProtoMessage()

func (*DHTPacket) Reset

func (m *DHTPacket) Reset()

func (*DHTPacket) String

func (m *DHTPacket) String() string

type DHTPacketType

type DHTPacketType int32
const (
	DHTPacketType_Undefined     DHTPacketType = 0
	DHTPacketType_Connect       DHTPacketType = 1
	DHTPacketType_Forward       DHTPacketType = 2
	DHTPacketType_Find          DHTPacketType = 3
	DHTPacketType_Node          DHTPacketType = 4
	DHTPacketType_Ping          DHTPacketType = 5
	DHTPacketType_RegisterProxy DHTPacketType = 6
	DHTPacketType_RequestProxy  DHTPacketType = 7
	DHTPacketType_ReportProxy   DHTPacketType = 8
	DHTPacketType_BadProxy      DHTPacketType = 9
	DHTPacketType_Proxy         DHTPacketType = 10
	DHTPacketType_Notify        DHTPacketType = 11
	DHTPacketType_ReportLoad    DHTPacketType = 12
	DHTPacketType_Stop          DHTPacketType = 13
	DHTPacketType_Unknown       DHTPacketType = 14
	DHTPacketType_DHCP          DHTPacketType = 15
	DHTPacketType_Error         DHTPacketType = 16
	DHTPacketType_Unsupported   DHTPacketType = 17
	DHTPacketType_State         DHTPacketType = 18
)

func (DHTPacketType) EnumDescriptor

func (DHTPacketType) EnumDescriptor() ([]byte, []int)

func (DHTPacketType) String

func (x DHTPacketType) String() string

type ErrorType

type ErrorType string

ErrorType is a type of an error

const (
	ErrUnknownError       ErrorType = "unknownerror"
	ErrIncopatibleVersion ErrorType = "unsupported"
	ErrMalformedHandshake ErrorType = "badhandshake"
	ErrPortParseFailed    ErrorType = "badport"
	ErrBadUDPAddr         ErrorType = "badudpaddr"
	ErrBadIDReceived      ErrorType = "badid"
	ErrBadDHCPData        ErrorType = "baddhcp"
)

Types of errors

type Forwarder

type Forwarder struct {
	Addr          *net.UDPAddr
	DestinationID string
}

Forwarder structure represents a Proxy received from DHT server

type ListOperation

type ListOperation int

ListOperation will specify which operation is performed on peer list

const (
	OperateDelete ListOperation = 0 // Delete entry from map
	OperateUpdate ListOperation = 1 // Add/Update entry in map
)

List operations

type LogLevel

type LogLevel int32

LogLevel is a level of the log message

const (
	Trace LogLevel = iota
	Debug
	Info
	Warning
	Error
)

Log Levels

func MinLogLevel

func MinLogLevel() LogLevel

MinLogLevel returns minimal log level

type MessageHandler

type MessageHandler func(message *P2PMessage, srcAddr *net.UDPAddr)

MessageHandler is a messages callback

type MsgType

type MsgType uint16

MsgType is a type of the message

type Network

type Network struct {
	// contains filtered or unexported fields
}

Network is a network subsystem

func (*Network) Addr

func (uc *Network) Addr() *net.UDPAddr

Addr returns assigned address

func (*Network) Disposed

func (uc *Network) Disposed() bool

Disposed returns whether service is willing to stop or not

func (*Network) GetPort

func (uc *Network) GetPort() int

GetPort return a port assigned

func (*Network) Init

func (uc *Network) Init(host string, port int) error

Init creates a UDP connection

func (*Network) KeepAlive

func (uc *Network) KeepAlive(addr *net.UDPAddr)

KeepAlive will send keep alive packet periodically to keep UDP port bind

func (*Network) Listen

func (uc *Network) Listen(receivedCallback UDPReceivedCallback)

Listen is a main listener of a network traffic

func (*Network) SendMessage

func (uc *Network) SendMessage(msg *P2PMessage, dstAddr *net.UDPAddr) (int, error)

SendMessage sends message over network

func (*Network) SendRawBytes

func (uc *Network) SendRawBytes(bytes []byte, dstAddr *net.UDPAddr) (int, error)

SendRawBytes sends bytes over network

func (*Network) Stop

func (uc *Network) Stop()

Stop will terminate packet reader

type NetworkPeer

type NetworkPeer struct {
	ID                 string           // ID of a peer
	Endpoint           *net.UDPAddr     // Endpoint address of a peer. TODO: Make this net.UDPAddr
	KnownIPs           []*net.UDPAddr   // List of IP addresses that accepts connection on peer
	Proxies            []*net.UDPAddr   // List of proxies of this peer
	PeerLocalIP        net.IP           // IP of peers interface. TODO: Rename to IP
	PeerHW             net.HardwareAddr // Hardware address of peer interface. TODO: Rename to Mac
	State              PeerState        // State of a peer on our end
	RemoteState        PeerState        // State of remote peer
	LastContact        time.Time        // Last ping with this peer
	PingCount          uint8            // Number of pings messages sent without response
	LastError          string           // Test of last error occured during state execution
	ConnectionAttempts uint8            // How many times we tried to connect

	Running       bool            // Whether peer is running or not
	EndpointsHeap []*PeerEndpoint // List of all endpoints
	// EndpointsActive    []PeerEndpoint                     // List of active endpoints
	EndpointsLock sync.RWMutex // Mutex for endpoints operations

	LastFind  time.Time // Moment when we got this peer from DHT
	LastPunch time.Time // Last time we run hole punch
	Stat      PeerStats // Peer statistics
	// contains filtered or unexported fields
}

NetworkPeer represents a peer

func (*NetworkPeer) BumpEndpoint

func (np *NetworkPeer) BumpEndpoint(epAddr string)

func (*NetworkPeer) RequestForwarder

func (np *NetworkPeer) RequestForwarder(ptpc *PeerToPeer)

RequestForwarder sends a request for a proxy with DHT client

func (*NetworkPeer) Run

func (np *NetworkPeer) Run(ptpc *PeerToPeer)

Run is main loop for a peer

func (*NetworkPeer) SetState

func (np *NetworkPeer) SetState(state PeerState, ptpc *PeerToPeer)

SetState modify local state of peer

type NetworkPeerState

type NetworkPeerState struct {
	ID    string // Peer's ID
	State string // State of peer
}

NetworkPeerState represents a state for remote peers

type OperatingMode

type OperatingMode int

OperatingMode - Mode in which DHT client is operating

const (
	DHTModeClient OperatingMode = 1
	DHTModeProxy  OperatingMode = 2
)

Possible operating modes

type Operation

type Operation uint16

Operation determines whether operation is a request or a reply

const (
	OperationRequest Operation = 1
	OperationReply   Operation = 2
)

Types of Operation

type P2PMessage

type P2PMessage struct {
	Header *P2PMessageHeader
	Data   []byte
}

P2PMessage is a cross-peer message packet

func CreateMessageStatic

func CreateMessageStatic(msgType MsgType, payload []byte) (*P2PMessage, error)

CreateMessageStatic is a static method for a P2P Message

func P2PMessageFromBytes

func P2PMessageFromBytes(bytes []byte) (*P2PMessage, error)

P2PMessageFromBytes extract a payload from received packet

func (*P2PMessage) Serialize

func (v *P2PMessage) Serialize() []byte

Serialize constructs a P2P message

type P2PMessageHeader

type P2PMessageHeader struct {
	Magic         uint16
	Type          uint16
	Length        uint16
	SerializedLen uint16
	NetProto      uint16
}

P2PMessageHeader is header used in cross-peer packets

func P2PMessageHeaderFromBytes

func P2PMessageHeaderFromBytes(bytes []byte) (*P2PMessageHeader, error)

P2PMessageHeaderFromBytes extracts message header from received packet

func (*P2PMessageHeader) Serialize

func (v *P2PMessageHeader) Serialize() []byte

Serialize does a header serialization

type Packet

type Packet struct {
	Protocol int
	Packet   []byte
}

Packet represents a packet received on TUN/TAP interface

type PacketHandlerCallback

type PacketHandlerCallback func(data []byte, proto int)

PacketHandlerCallback represents a callback function for each packet type

type PacketType

type PacketType int

PacketType is a type of the IPv4 packet

type PeerEndpoint

type PeerEndpoint struct {
	Addr        *net.UDPAddr
	LastContact time.Time
	LastPing    time.Time
}

PeerEndpoint reprsents a UDP address endpoint that instance may use for connection with a peer

type PeerHandshake

type PeerHandshake struct {
	ID           string
	IP           net.IP
	HardwareAddr net.HardwareAddr
	Endpoint     *net.UDPAddr
}

PeerHandshake holds handshake information received from peer

type PeerIP

type PeerIP struct {
	ID  string
	Ips []*net.UDPAddr
}

PeerIP structure represents a pair of peer ID and associated list of IP addresses

type PeerList

type PeerList struct {
	// contains filtered or unexported fields
}

PeerList is for handling list of peers with all mappings

func (*PeerList) Delete

func (l *PeerList) Delete(id string)

Delete will remove entry with specified ID from peer list

func (*PeerList) Get

func (l *PeerList) Get() map[string]*NetworkPeer

Get returns copy of map with all peers

func (*PeerList) GetEndpointAndProxy

func (l *PeerList) GetEndpointAndProxy(mac string) (*net.UDPAddr, uint16, error)

GetEndpointAndProxy returns endpoint address and proxy id

func (*PeerList) GetID

func (l *PeerList) GetID(ip string) (string, error)

GetID returns ID by specified IP

func (*PeerList) GetPeer

func (l *PeerList) GetPeer(id string) *NetworkPeer

GetPeer returns single peer by id

func (*PeerList) Init

func (l *PeerList) Init()

Init will initialize PeerList's maps

func (*PeerList) Length

func (l *PeerList) Length() int

Length returns size of peer list map

func (*PeerList) RunPeer

func (l *PeerList) RunPeer(id string, p *PeerToPeer)

RunPeer should be called once on each peer when added to list

func (*PeerList) Update

func (l *PeerList) Update(id string, peer *NetworkPeer)

Update will append/edit peer in list

type PeerState

type PeerState int

PeerState - current state of the peer

type PeerStats

type PeerStats struct {
	// contains filtered or unexported fields
}

PeerStats represents different peer statistics

type PeerToPeer

type PeerToPeer struct {
	Config          Configuration                        // Network interface configuration tool
	UDPSocket       *Network                             // Peer-to-peer interconnection socket
	LocalIPs        []net.IP                             // List of IPs available in the system
	Dht             *DHTClient                           // DHT Client
	Crypter         Crypto                               // Cryptography subsystem
	Shutdown        bool                                 // Set to true when instance in shutdown mode
	ForwardMode     bool                                 // Skip local peer discovery
	ReadyToStop     bool                                 // Set to true when instance is ready to stop
	MessageHandlers map[uint16]MessageHandler            // Callbacks for network packets
	PacketHandlers  map[PacketType]PacketHandlerCallback // Callbacks for packets received by TAP interface
	PeersLock       sync.Mutex                           // Lock for peers map
	Hash            string                               // Infohash for this instance
	Routers         string                               // Comma-separated list of Bootstrap nodes
	Interface       TAP                                  // TAP Interface
	Peers           *PeerList                            // Known peers
	HolePunching    sync.Mutex                           // Mutex for hole punching sync
	ProxyManager    *ProxyManager                        // Proxy manager
	// contains filtered or unexported fields
}

PeerToPeer - Main structure

func New

func New(argIP, argMac, argDev, argDirect, argHash, argDht, argKeyfile, argKey, argTTL, argLog string, fwd bool, port int, ignoreIPs []string, outboundIP net.IP) *PeerToPeer

New is an entry point of a P2P library.

func (*PeerToPeer) AssignInterface

func (p *PeerToPeer) AssignInterface(interfaceName string) error

AssignInterface - Creates TUN/TAP Interface and configures it with provided IP tool

func (*PeerToPeer) Close

func (p *PeerToPeer) Close() error

Close stops current instance

func (*PeerToPeer) CreateMessage

func (p *PeerToPeer) CreateMessage(msgType MsgType, payload []byte, proto uint16, encrypt bool) (*P2PMessage, error)

CreateMessage create internal P2P Message

func (*PeerToPeer) FindNetworkAddresses

func (p *PeerToPeer) FindNetworkAddresses()

FindNetworkAddresses method lists interfaces available in the system and retrieves their IP addresses

func (*PeerToPeer) GenerateDeviceName

func (p *PeerToPeer) GenerateDeviceName(i int) string

GenerateDeviceName method will generate device name if none were specified at startup

func (*PeerToPeer) HandleBadTun

func (p *PeerToPeer) HandleBadTun(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleBadTun notified peer about proxy being malfunction This method is not used in currenct scheme TODO: Consider to remove

func (*PeerToPeer) HandleIntroMessage

func (p *PeerToPeer) HandleIntroMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleIntroMessage receives an introduction string from another peer during handshake

func (*PeerToPeer) HandleIntroRequestMessage

func (p *PeerToPeer) HandleIntroRequestMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleIntroRequestMessage is a handshake request from another peer First 36 bytes is an ID of original sender, data after byte 36 is an endpoint on which sender was trying to communicate with this peer. We need to send this data back to him, so he knows which endpoint replied

func (*PeerToPeer) HandleNotEncryptedMessage

func (p *PeerToPeer) HandleNotEncryptedMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleNotEncryptedMessage is a normal message sent over p2p network

func (*PeerToPeer) HandleP2PMessage

func (p *PeerToPeer) HandleP2PMessage(count int, srcAddr *net.UDPAddr, err error, rcvBytes []byte)

HandleP2PMessage is a handler for new messages received from P2P network

func (*PeerToPeer) HandlePingMessage

func (p *PeerToPeer) HandlePingMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandlePingMessage is a PING message from a proxy handler

func (*PeerToPeer) HandleProxyMessage

func (p *PeerToPeer) HandleProxyMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleProxyMessage receives a control packet from proxy Proxy packets comes in format of UDP connection address

func (*PeerToPeer) HandleXpeerPingMessage

func (p *PeerToPeer) HandleXpeerPingMessage(msg *P2PMessage, srcAddr *net.UDPAddr)

HandleXpeerPingMessage receives a cross-peer ping message

func (*PeerToPeer) Init

func (p *PeerToPeer) Init()

Init will initialize PeerToPeer

func (*PeerToPeer) IsDeviceExists

func (p *PeerToPeer) IsDeviceExists(name string) bool

IsDeviceExists - checks whether interface with the given name exists in the system or not

func (*PeerToPeer) IsIPv4

func (p *PeerToPeer) IsIPv4(ip string) bool

IsIPv4 checks whether interface is IPv4 or IPv6

func (*PeerToPeer) ListenInterface

func (p *PeerToPeer) ListenInterface()

ListenInterface - Listens TAP interface for incoming packets Read packets received by TAP interface and send them to a handlePacket goroutine This goroutine will execute a callback method based on packet type

func (*PeerToPeer) ParseIntroString

func (p *PeerToPeer) ParseIntroString(intro string) (*PeerHandshake, error)

ParseIntroString receives a comma-separated string with ID, MAC and IP of a peer and returns this data

func (*PeerToPeer) PrepareInterfaces

func (p *PeerToPeer) PrepareInterfaces(ip, interfaceName string) error

PrepareInterfaces will assign IPs to interfaces

func (*PeerToPeer) PrepareIntroductionMessage

func (p *PeerToPeer) PrepareIntroductionMessage(id, endpoint string) *P2PMessage

PrepareIntroductionMessage collects client ID, mac and IP address and create a comma-separated line endpoint is an address that received this introduction message

func (*PeerToPeer) ReadDHT

func (p *PeerToPeer) ReadDHT()

ReadDHT will read packets from bootstrap node

func (*PeerToPeer) ReportIP

func (p *PeerToPeer) ReportIP(ipAddress, mac, device string) (net.IP, net.IPMask, error)

ReportIP will send IP specified at service start to DHCP-like service

func (*PeerToPeer) RequestIP

func (p *PeerToPeer) RequestIP(mac, device string) (net.IP, net.IPMask, error)

RequestIP asks DHT to get IP from DHCP-like service

func (*PeerToPeer) Run

func (p *PeerToPeer) Run()

Run is a main loop

func (*PeerToPeer) SendTo

func (p *PeerToPeer) SendTo(dst net.HardwareAddr, msg *P2PMessage) (int, error)

SendTo sends a p2p packet by MAC address

func (*PeerToPeer) WriteToDevice

func (p *PeerToPeer) WriteToDevice(b []byte, proto uint16, truncated bool)

WriteToDevice writes data to created TAP interface

type ProxyManager

type ProxyManager struct {
	// contains filtered or unexported fields
}

ProxyManager manages TURN servers

func (*ProxyManager) GetList

func (p *ProxyManager) GetList() []*proxyServer

GetList will return a slice of proxyServers

type RemotePeerState

type RemotePeerState struct {
	ID    string
	State PeerState
}

RemotePeerState is a state information of another peer received from DHT

type StateHandlerCallback

type StateHandlerCallback func(ptpc *PeerToPeer) error

StateHandlerCallback is a peer method callback executed by peer state

type TAP

type TAP interface {
	GetName() string
	GetHardwareAddress() net.HardwareAddr
	GetIP() net.IP
	GetMask() net.IPMask
	GetBasename() string
	SetName(string)
	SetHardwareAddress(net.HardwareAddr)
	SetIP(net.IP)
	SetMask(net.IPMask)
	Init(string) error
	Open() error
	Close() error
	Configure() error
	ReadPacket() (*Packet, error)
	WritePacket(*Packet) error
	Run()
	IsConfigured() bool
	MarkConfigured()
}

TAP interface

type TAPLinux

type TAPLinux struct {
	IP   net.IP           // IP
	Mask net.IPMask       // Mask
	Mac  net.HardwareAddr // Hardware Address
	Name string           // Network interface name
	Tool string           // Path to `ip`
	MTU  int              // MTU value

	Configured bool
	// contains filtered or unexported fields
}

TAPLinux is an interface for TAP device on Linux platform

func (*TAPLinux) Close

func (t *TAPLinux) Close() error

Close will close TAP interface by closing it's file descriptor

func (*TAPLinux) Configure

func (t *TAPLinux) Configure() error

Configure will configure interface using system calls to commands

func (*TAPLinux) GetBasename

func (t *TAPLinux) GetBasename() string

GetBasename returns a prefix for automatically generated interface names

func (*TAPLinux) GetHardwareAddress

func (t *TAPLinux) GetHardwareAddress() net.HardwareAddr

GetHardwareAddress returns a MAC address of the interface

func (*TAPLinux) GetIP

func (t *TAPLinux) GetIP() net.IP

GetIP returns IP addres of the interface

func (*TAPLinux) GetMask

func (t *TAPLinux) GetMask() net.IPMask

GetMask returns an IP mask of the interface

func (*TAPLinux) GetName

func (t *TAPLinux) GetName() string

GetName returns a name of interface

func (*TAPLinux) Init

func (t *TAPLinux) Init(name string) error

Init will initialize TAP interface creation process

func (*TAPLinux) IsConfigured

func (t *TAPLinux) IsConfigured() bool

func (*TAPLinux) MarkConfigured

func (t *TAPLinux) MarkConfigured()

func (*TAPLinux) Open

func (t *TAPLinux) Open() error

Open will open a file descriptor for a new interface

func (*TAPLinux) ReadPacket

func (t *TAPLinux) ReadPacket() (*Packet, error)

ReadPacket will read single packet from network interface

func (*TAPLinux) Run

func (t *TAPLinux) Run()

Run will start TAP processes

func (*TAPLinux) SetHardwareAddress

func (t *TAPLinux) SetHardwareAddress(mac net.HardwareAddr)

SetHardwareAddress will set MAC

func (*TAPLinux) SetIP

func (t *TAPLinux) SetIP(ip net.IP)

SetIP will set IP

func (*TAPLinux) SetMask

func (t *TAPLinux) SetMask(mask net.IPMask)

SetMask will set mask

func (*TAPLinux) SetName

func (t *TAPLinux) SetName(name string)

SetName will set interface name

func (*TAPLinux) WritePacket

func (t *TAPLinux) WritePacket(packet *Packet) error

WritePacket will write a single packet to interface

type TError

type TError struct {
	Type ErrorType
}

TError -Struct for errors

type UDPReceivedCallback

type UDPReceivedCallback func(count int, src_addr *net.UDPAddr, err error, buff []byte)

UDPReceivedCallback is executed when message is received

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL