Skip to content

Commit

Permalink
Merge pull request #45 from subutai-io/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
crioto committed Feb 15, 2016
2 parents 5d658fb + 2aeadfe commit d6c7998
Show file tree
Hide file tree
Showing 11 changed files with 462 additions and 229 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ p2p-cp/p2p-cp
tests/*
cp-v*
p2p-v*
cp-*-v*
p2p-*-v*

# Logs
*.log
8 changes: 6 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ CP_APP=cp
CC=go
PACK=goupx
VERSION=$(shell git describe)
OS=$(shell uname -s)
ARCH=$(shell uname -m)

all: pack

Expand All @@ -19,6 +21,8 @@ pack: $(APP) $(CP_APP)
clean:
-rm -f $(APP)
-rm -f $(CP_APP)
-rm -f $(APP)-*-v*
-rm -f $(CP_APP)-*-v*
-rm -f $(APP)-v*
-rm -f $(CP_APP)-v*

Expand All @@ -28,5 +32,5 @@ test: $(APP) $(CP_APP)
release: $(APP) $(CP_APP)
release: pack
release:
-cp $(APP) $(APP)-$(VERSION)
-cp $(CP_APP) $(CP_APP)-$(VERSION)
-cp $(APP) $(APP)-$(OS)-$(ARCH)-$(VERSION)
-cp $(CP_APP) $(CP_APP)-$(OS)-$(ARCH)-$(VERSION)
17 changes: 5 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ Dev: [![Build Status - dev](https://api.travis-ci.org/subutai-io/p2p.png?branch=

P2P Cloud project allows users to build their private networks.

Running on Linux
Running
-------------------

> **MacOS** users should install [TUN/TAP driver](http://tuntaposx.sourceforge.net) and create a config.yaml file with the following line: ``` iptool: /sbin/ifconfig ```
> **Windows** users should install [TAP-windows NDIS6](https://openvpn.net/index.php/open-source/downloads.html) driver from OpenVPN suite
p2p is managed by a daemon that controls every instance of your private networks (if you're participating in a different networks at the same time). To start a daemon simply run p2p with -daemon flag. Note, that application will run in a foreground mode.

```
Expand All @@ -32,17 +36,6 @@ Instance of P2P network can be stopped with use of -stop flag
p2p -stop -hash UNIQUE_STRING_IDENTIFIER
```

Running on Mac OS
-------------------

Running p2p on Mac OS requires you to perform two additional steps:

* First you should install [TUN/TAP driver](http://tuntaposx.sourceforge.net) first.
* Create new file named **config.yaml** and write the following line inside it:
```
iptool: /sbin/ifconfig
```

Development & Branching Model
-------------------

Expand Down
20 changes: 19 additions & 1 deletion lib/dht.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type DHTClient struct {
Mode OperatingMode
Shutdown bool
IPList []net.IP
FailedProxyList []*net.UDPAddr
}

type Forwarder struct {
Expand Down Expand Up @@ -352,6 +353,9 @@ func (dht *DHTClient) HandleCp(data DHTResponse, conn *net.UDPConn) {
// We've received information about proxy
Log(INFO, "Received control peer %s. Saving", data.Dest)
var found bool = false
if data.Dest == "0" {
return
}
for _, fwd := range dht.Forwarders {
if fwd.Addr.String() == data.Dest && fwd.DestinationID == data.Id {
found = true
Expand Down Expand Up @@ -474,7 +478,11 @@ func (dht *DHTClient) RequestControlPeer(id string) {
var req DHTRequest
var err error
req.Id = dht.ID
req.Query = dht.NetworkHash
req.Query = ""
// Collect list of failed forwarders
for _, fwd := range dht.FailedProxyList {
req.Query += fwd.String() + "|"
}
req.Command = CMD_CP
req.Arguments = id
var b bytes.Buffer
Expand Down Expand Up @@ -538,3 +546,13 @@ func (dht *DHTClient) Stop() {
conn.Write([]byte(msg))
}
}

func (dht *DHTClient) MakeForwarderFailed(addr *net.UDPAddr) {
for _, fwd := range dht.FailedProxyList {
if fwd.String() == addr.String() {
Log(DEBUG, "Can't mark proxy as failed: Already in list")
return
}
}
dht.FailedProxyList = append(dht.FailedProxyList, addr)
}
20 changes: 18 additions & 2 deletions lib/tuntap_other.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// +build !linux,!darwin
// +build !linux,!darwin,!windows

package ptp

Expand All @@ -9,5 +9,21 @@ import (
var flagTruncated = 0

func createInterface(f *os.File, ifPattern string, kind DevKind) (string, error) {
panic("Not implemented on this platform")
panic("TUN/TAP functionality is not supported on this platform")
}

func ConfigureInterface(ip, mac, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func LinkUp(device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func SetIp(ip, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func SetMac(mac, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}
187 changes: 187 additions & 0 deletions lib/tuntap_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// +build windows
package ptp

import (
"fmt"
"os"
"syscall"
"unicode/utf16"
"os/exec"
)

type TAPDevice struct {
Handle syscall.Handle
Name string
Interface string
IP string
Mask string
}

const (
NETWORK_KEY string = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
ADAPTER_KEY string = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
NO_MORE_ITEMS syscall.Errno = 259
USERMODE_DEVICE_DIR string = "\\\\.\\Global\\"
SYS_DEVICE_DIR string = "\\Device\\"
USER_DEVICE_DIR string = "\\DosDevices\\Global\\"
TAP_SUFFIX string = ".tap"
)

var (
TAP_IOCTL_GET_MAC = TAP_CONTROL_CODE(1, 0)
TAP_IOCTL_GET_VERSION = TAP_CONTROL_CODE(2, 0)
TAP_IOCTL_GET_MTU = TAP_CONTROL_CODE(3, 0)
TAP_IOCTL_GET_INFO = TAP_CONTROL_CODE(4, 0)
TAP_IOCTL_CONFIG_POINT_TO_POINT = TAP_CONTROL_CODE(5, 0)
TAP_IOCTL_SET_MEDIA_STATUS = TAP_CONTROL_CODE(6, 0)
TAP_IOCTL_CONFIG_DHCP_MASQ = TAP_CONTROL_CODE(7, 0)
TAP_IOCTL_GET_LOG_LINE = TAP_CONTROL_CODE(8, 0)
TAP_IOCTL_CONFIG_DHCP_SET_OPT = TAP_CONTROL_CODE(9, 0)
TAP_IOCTL_CONFIG_TUN = TAP_CONTROL_CODE(10, 0)
)

func TAP_CONTROL_CODE(request, method uint32) uint32 {
return CTL_CODE(34, request, method, 0)
}

func CTL_CODE(device_type, function, method, access uint32) uint32 {
return (device_type << 16) | (access << 14) | (function << 2) | method
}

func removeZeroes(s string) string {
bytes := []byte(s)
var (
res []byte
prev bool
size int = 0
)
for _, b := range bytes {
if b == 0 && prev {
break
} else if b == 0 && !prev {
prev = true
} else {
prev = false
res = append(res, b)
size++
}
}
return string(res[:size])
}

func queryNetworkKey() (syscall.Handle, error) {
var handle syscall.Handle
err := syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, syscall.StringToUTF16Ptr(NETWORK_KEY), 0, syscall.KEY_READ, &handle)
if err != nil {
return 0, err
}
return handle, nil
}

func queryAdapters(handle syscall.Handle) (TAPDevice, error) {
var dev TAPDevice
var index uint32 = 0
for {
var length uint32 = 72
adapter := make([]uint16, length)
err := syscall.RegEnumKeyEx(handle, index, &adapter[0], &length, nil, nil, nil, nil)
if err == NO_MORE_ITEMS {
break
}
index++
adapterId := string(utf16.Decode(adapter[0:72]))
adapterId = removeZeroes(adapterId)
path := fmt.Sprintf("%s\\%s\\Connection", NETWORK_KEY, adapterId)
var iHandle syscall.Handle
err = syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, syscall.StringToUTF16Ptr(path), 0, syscall.KEY_READ, &iHandle)
if err != nil {
continue
}
length = 1024
aName := make([]byte, length)
err = syscall.RegQueryValueEx(iHandle, syscall.StringToUTF16Ptr("Name"), nil, nil, &aName[0], &length)
if err != nil {
continue
}
syscall.RegCloseKey(iHandle)
adapterName := removeZeroes(string(aName))
tapname := fmt.Sprintf("%s%s%s", USERMODE_DEVICE_DIR, adapterId, TAP_SUFFIX)
dev.Handle, err = syscall.CreateFile(syscall.StringToUTF16Ptr(tapname),
syscall.GENERIC_WRITE|syscall.GENERIC_READ,
0,
nil,
syscall.OPEN_EXISTING,
syscall.FILE_ATTRIBUTE_SYSTEM|syscall.FILE_FLAG_OVERLAPPED,
0)
if err != nil {
syscall.CloseHandle(dev.Handle)
continue
}
dev.Name = adapterId
dev.Interface = adapterName
return dev, nil
}
return dev, nil
}

func openDevice(ifPattern string) (*os.File, error) {
handle, err := queryNetworkKey()
if err != nil {
Log(ERROR, "Failed to query Windows registry: %v", err)
return nil, err
}
dev, err := queryAdapters(handle)
if err != nil {
Log(ERROR, "Failed to query network adapters: %v", err)
return nil, err
}
if dev.Name == "" {
Log(ERROR, "Failed to query network adapters: %v", err)
return nil, nil
}
setip := exec.Command("netsh")
setip.SysProcAttr = &syscall.SysProcAttr{}
setip.SysProcAttr.CmdLine = fmt.Sprintf(`netsh interface ip set address "%s" static %s %s`, dev.Interface, dev.IP, dev.Mask)
err = setip.Run()
if err != nil {
Log(ERROR, "Failed to properly configure TAP device with netsh: %v", err)
return nil, err
}

in := []byte("\x01\x00\x00\x00")
var length uint32
err = syscall.DeviceIoControl(dev.Handle, TAP_IOCTL_SET_MEDIA_STATUS,
&in[0],
uint32(len(in)),
&in[0],
uint32(len(in)),
&length,
nil)
if err != nil {
Log(ERROR, "Failed to change device status to 'connected': %v", err)
return nil, err
}

file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
return file, err
}

func createInterface(file *os.File, ifPattern string, kind DevKind, meta bool) (string, error) {
panic("TUN/TAP functionality is not supported on this platform")
}

func ConfigureInterface(ip, mac, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func LinkUp(device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func SetIp(ip, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}

func SetMac(mac, device, tool string) error {
panic("TUN/TAP functionality is not supported on this platform")
}
13 changes: 13 additions & 0 deletions lib/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,16 @@ const (
CMD_STOP string = "stop"
CMD_UNKNOWN string = "unk"
)

type PeerState int

// Peer state
const (
P_INIT PeerState = 0 + iota
P_CONNECTED = 1
P_HANDSHAKING = 2
P_HANDSHAKING_FAILED = 3
P_WAITING_FORWARDER = 4
P_HANDSHAKING_FORWARDER = 5
P_DISCONNECT = 6
)
14 changes: 14 additions & 0 deletions lib/windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// +build windows

package ptp

import (
"testing"
)

func TestInitTuntap(t *testing.T) {
ret := InitTuntap()
if ret != 0 {
t.Errorf("Failed to initialize tuntap: %d", ret)
}
}
Loading

0 comments on commit d6c7998

Please sign in to comment.