<commit_before>package casper

import (
	"fmt"
	"time"

	log "github.com/golang/glog"
	zmq "github.com/pebbe/zmq4"

	"github.com/gogap/logs"
)

type EntranceZMQ struct {
	address   string
	app       *App
	socket    *zmq.Socket
	messenger Messenger
}

func init() {
	entrancefactory.RegisterEntrance(new(EntranceZMQ))
}

func (p *EntranceZMQ) Type() string {
	return "zmq"
}

func (p *EntranceZMQ) Init(messenger Messenger, configs EntranceConfig) (err error) {
	if addr, ok := configs.GetConfigString("address"); !ok {
		err = fmt.Errorf("[entrance-%s] get config section of %s failed", p.Type(), "address")
	} else {
		p.address = addr
	}

	if messenger == nil {
		err = fmt.Errorf("[entrance-%s] Messenger is nil", p.Type())
		logs.Info(err)
		return
	} else {
		p.messenger = messenger
	}

	return
}

func (p *EntranceZMQ) Run() error {
	var err error

	if p.socket, err = zmq.NewSocket(zmq.REP); err != nil {
		return err
	}

	if err = p.socket.Bind(p.address); err != nil {
		return err
	}

	logs.Info("entrance", p.Type(), "start:", p.address)
	p.EntranceZMQHandler()

	return nil
}

func (p *EntranceZMQ) EntranceZMQHandler() {
	for {
		msg, err := p.socket.RecvMessageBytes(0)
		if err != nil {
			log.Errorln("recvMessage err:", err.Error())
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		if !isValidPacket(msg) {
			log.Errorln("RecvMessage invalid message.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		log.Infoln("recvMessage:", string(msg[1]))

		comMsg, _ := NewComponentMessage(nil, nil)
		err = comMsg.FromJson(msg[1])
		if err != nil {
			log.Errorln("RecvMessage message fmt error.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		log.Infoln("recvComsg:", comMsg)

		apiName, err := comMsg.Payload.GetContextString(REQ_X_API)
		if err != nil {
			log.Errorln("Get message's X-API error.", err.Error())
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}
		if apiName == "" {
			log.Errorln("Get message's X-API NULL.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		go func(api string, msg *ComponentMessage) {
			// send msg to next
			id, ch, err := p.messenger.SendMessage(api, msg)
			if err != nil {
				log.Errorln("sendMsg err:", msg.Id, err.Error())
				p.socket.SendMessage(newPacket([]byte("ERR")))
				return
			}
			if ch == nil {
				log.Errorln("sendMsg return nil:", msg.Id)
				p.socket.SendMessage(newPacket([]byte("ERR")))
				return
			}

			defer close(ch)
			defer p.messenger.OnMessageEvent(id, MSG_EVENT_PROCESSED)

			// Wait for response from IN port
			log.Infoln("Waiting for response: ", api)
			var load *Payload
			select {
			case load = <-ch:
				break
			case <-time.Tick(REQ_TIMEOUT):
				p.socket.SendMessage(newPacket([]byte("TIMEOUT")))
				return
			}

			comMsg.Payload = load
			rst, _ := comMsg.Serialize()
			p.socket.SendMessage(newPacket(rst))
		}(apiName, comMsg)
	}
}

func zmqSyncCall(endpoint string, request *ComponentMessage) (reply *ComponentMessage, err error) {
	if endpoint == "" {
		return nil, fmt.Errorf("endpoint is nil")
	}
	if request == nil {
		return nil, fmt.Errorf("request is nil")
	}

	client, err := zmq.NewSocket(zmq.REQ)
	if err != nil {
		return nil, err
	}
	if err := client.Connect(endpoint); err != nil {
		return nil, err
	}
	log.Infoln("zmq connect ok:", endpoint)

	msg, _ := request.Serialize()
	packet := newPacket(msg)
	total, err := client.SendMessage(packet)
	if err != nil {
		return nil, err
	}
	log.Infoln("sendok: ", total, endpoint, string(msg))

	poller := zmq.NewPoller()
	poller.Add(client, zmq.POLLIN)
	polled, err := poller.Poll(REQ_TIMEOUT)
	if err != nil {
		return nil, err
	}

	if len(polled) == 1 {
		ip, err := client.RecvMessageBytes(0)
		if err != nil {
			log.Errorln("recvmsg err:", err.Error())
			return nil, err
		}

		if !isValidPacket(ip) {
			return nil, fmt.Errorf("recv not valid message")
		}

		rst := new(ComponentMessage)
		rst.FromJson(ip[1])
		return rst, nil
	}

	return nil, fmt.Errorf("Time out")
}
<commit_msg>update<commit_after>package casper

import (
	"fmt"
	"time"

	log "github.com/golang/glog"
	zmq "github.com/pebbe/zmq4"

	"github.com/gogap/logs"
)

type EntranceZMQ struct {
	address   string
	app       *App
	socket    *zmq.Socket
	messenger Messenger
}

func init() {
	entrancefactory.RegisterEntrance(new(EntranceZMQ))
}

func (p *EntranceZMQ) Type() string {
	return "zmq"
}

func (p *EntranceZMQ) Init(messenger Messenger, configs EntranceConfig) (err error) {
	if addr, ok := configs.GetConfigString("address"); !ok {
		err = fmt.Errorf("[entrance-%s] get config section of %s failed", p.Type(), "address")
	} else {
		p.address = addr
	}

	if messenger == nil {
		err = fmt.Errorf("[entrance-%s] Messenger is nil", p.Type())
		logs.Info(err)
		return
	} else {
		p.messenger = messenger
	}

	return
}

func (p *EntranceZMQ) Run() error {
	var err error

	if p.socket, err = zmq.NewSocket(zmq.REP); err != nil {
		return err
	}

	if err = p.socket.Bind(p.address); err != nil {
		return err
	}

	logs.Info("entrance", p.Type(), "start:", p.address)
	p.EntranceZMQHandler()

	return nil
}

func (p *EntranceZMQ) EntranceZMQHandler() {
	for {
		msg, err := p.socket.RecvMessageBytes(0)
		if err != nil {
			log.Errorln("recvMessage err:", err.Error())
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		if !isValidPacket(msg) {
			log.Errorln("RecvMessage invalid message.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		log.Infoln("recvMessage:", string(msg[1]))

		comMsg, _ := NewComponentMessage(nil, nil)
		err = comMsg.FromJson(msg[1])
		if err != nil {
			log.Errorln("RecvMessage message fmt error.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		log.Infoln("recvComsg:", comMsg)

		apiName, err := comMsg.Payload.GetContextString(REQ_X_API)
		if err != nil {
			log.Errorln("Get message's X-API error.", err.Error())
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}
		if apiName == "" {
			log.Errorln("Get message's X-API NULL.")
			p.socket.SendMessage(newPacket([]byte("ERR")))
			continue
		}

		go func(api string, coMsg1 *ComponentMessage) {
			// send msg to next
			id, ch, err := p.messenger.SendMessage(api, coMsg1)
			if err != nil {
				log.Errorln("sendMsg err:", coMsg1.Id, err.Error())
				p.socket.SendMessage(newPacket([]byte("ERR")))
				return
			}
			if ch == nil {
				log.Errorln("sendMsg return nil:", coMsg1.Id)
				p.socket.SendMessage(newPacket([]byte("ERR")))
				return
			}

			defer close(ch)
			defer p.messenger.OnMessageEvent(id, MSG_EVENT_PROCESSED)

			// Wait for response from IN port
			log.Infoln("Waiting for response: ", api)
			var load *Payload
			select {
			case load = <-ch:
				break
			case <-time.Tick(REQ_TIMEOUT):
				p.socket.SendMessage(newPacket([]byte("TIMEOUT")))
				return
			}

			comMsg.Payload = load
			rst, _ := comMsg.Serialize()
			p.socket.SendMessage(newPacket(rst))
		}(apiName, comMsg)
	}
}

func zmqSyncCall(endpoint string, request *ComponentMessage) (reply *ComponentMessage, err error) {
	if endpoint == "" {
		return nil, fmt.Errorf("endpoint is nil")
	}
	if request == nil {
		return nil, fmt.Errorf("request is nil")
	}

	client, err := zmq.NewSocket(zmq.REQ)
	if err != nil {
		return nil, err
	}
	if err := client.Connect(endpoint); err != nil {
		return nil, err
	}
	log.Infoln("zmq connect ok:", endpoint)

	msg, _ := request.Serialize()
	packet := newPacket(msg)
	total, err := client.SendMessage(packet)
	if err != nil {
		return nil, err
	}
	log.Infoln("sendok: ", total, endpoint, string(msg))

	poller := zmq.NewPoller()
	poller.Add(client, zmq.POLLIN)
	polled, err := poller.Poll(REQ_TIMEOUT)
	if err != nil {
		return nil, err
	}

	if len(polled) == 1 {
		ip, err := client.RecvMessageBytes(0)
		if err != nil {
			log.Errorln("recvmsg err:", err.Error())
			return nil, err
		}

		if !isValidPacket(ip) {
			return nil, fmt.Errorf("recv not valid message")
		}

		rst := new(ComponentMessage)
		rst.FromJson(ip[1])
		return rst, nil
	}

	return nil, fmt.Errorf("Time out")
}
<|endoftext|>


<commit_before>package space

import (
	"testing"
)

func TestAge(t *testing.T) {
	for _, tc := range testCases {
		if actual := Age(tc.seconds, tc.planet); actual != tc.expected {
			t.Fatalf("FAIL: %s\nExpected: %#v\nActual: %#v", tc.description, tc.expected, actual)
		}
		t.Logf("PASS: %s", tc.description)
	}
}

func BenchmarkAge(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, tc := range testCases {
			Age(tc.seconds, tc.planet)
		}
	}
}
<commit_msg>space-age: do not force rounding of solutions (#960)<commit_after>package space

import (
	"math"
	"testing"
)

func TestAge(t *testing.T) {
	const precision = 0.01
	for _, tc := range testCases {
		if actual := Age(tc.seconds, tc.planet); math.Abs(actual-tc.expected) > precision {
			t.Fatalf("FAIL: %s\nExpected: %#v\nActual: %#v", tc.description, tc.expected, actual)
		}
		t.Logf("PASS: %s", tc.description)
	}
}

func BenchmarkAge(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, tc := range testCases {
			Age(tc.seconds, tc.planet)
		}
	}
}
<|endoftext|>


<commit_before>package bot

const (
	rankCommand = "rank"
)

func rank(c *Cmd, channel, senderNick string, conn connection) {
	conn.Privmsg(channel, "League of Legends - Gold V")
	conn.Privmsg(channel, "CS:GO - Legendary Eagle")
}
<commit_msg>updating rank to LEM<commit_after>package bot

const (
	rankCommand = "rank"
)

func rank(c *Cmd, channel, senderNick string, conn connection) {
	conn.Privmsg(channel, "League of Legends - Gold V")
	conn.Privmsg(channel, "CS:GO - Legendary Eagle Master")
}
<|endoftext|>


<commit_before>//upnp functions to open ports on router
package upnp

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"
)

const (
	BroadcastRetryCount      = 3
	BroadcastWaitTimeSeconds = 3
	ServiceType              = "urn:schemas-upnp-org:service:WANIPConnection:1"
)

// Device Description xml elements
type Service struct {
	ServiceType string `xml:"serviceType"`
	//ServiceId   string `xml:"serviceId"`
	//SCPDURL     string `xml:"SCPDURL"`
	ControlURL string `xml:"controlURL"`
	//EventSubURL string `xml:"eventSubURL"`
}

type UPNP struct {
	gw *Gateway
}

type Gateway struct {
	GatewayName   string
	Host          string
	DeviceDescUrl string
	Cache         string
	ST            string
	ControlURL    string
	OutsideIP     net.IP
}

// NewUPNP returns a new UPNP object with a populated Gateway object.
func NewUPNP() (*UPNP, error) {
	u := &UPNP{}

	// Populate te the Gateway fields
	err := u.findGateway()
	if err != nil {
		return nil, err
	}

	err = u.DeviceDesc()
	if err != nil {
		return nil, err
	}

	if len(u.gw.ControlURL) == 0 || len(u.gw.Host) == 0 {
		return nil, errors.New("upnp: could not get gateway control url or host")
	}

	return u, nil
}

// perform the requested upnp action
func (u *UPNP) perform(action, body string) (*http.Response, error) {
	// Add soap envelope
	envelope := `<?xml version="1.0"?>
<SOAP-ENV:Envelope
	xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
	SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
 <SOAP-ENV:Body>
 ` + body + "</SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n\r\n"

	header := http.Header{}
	header.Set("SOAPAction", action)
	header.Set("Content-Type", "text/xml")
	header.Set("Connection", "Close")
	header.Set("Content-Length", string(len(envelope)))

	url := "http://" + u.gw.Host + u.gw.ControlURL
	req, _ := http.NewRequest("POST", url, strings.NewReader(envelope))
	req.Header = header

	//dumpreq, _ := httputil.DumpRequestOut(req, true)
	//log.Println(string(dumpreq))

	resp, err := http.DefaultClient.Do(req)

	//dumpresp, _ := httputil.DumpResponse(resp, true)
	//log.Println(string(dumpresp))

	return resp, err
}

// AddPortMapping to the WAN/Internet
func (u *UPNP) AddPortMapping(localPort, remotePort int, protocol string) error {

	protocol = strings.ToUpper(protocol)
	if protocol != "UDP" && protocol != "TCP" {
		return errors.New("upnp: bad protocol supplied: " + protocol)
	}

	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"`

	body := fmt.Sprintf(`<m:AddPortMapping xmlns:m="%v">
    <NewRemoteHost></NewRemoteHost>
    <NewExternalPort>%v</NewExternalPort>
	<NewProtocol>%v</NewProtocol>
	<NewInternalPort>%v</NewInternalPort>
	<NewInternalClient>%v</NewInternalClient>
	<NewEnabled>1</NewEnabled>
	<NewPortMappingDescription>USATVA</NewPortMappingDescription>
	<NewLeaseDuration>0</NewLeaseDuration>
  </m:AddPortMapping>`, ServiceType, remotePort, protocol, localPort, GetLocalAddress())

	r, err := u.perform(action, body)
	if err != nil {
		return fmt.Errorf("upnp: bad response from gateway for add port mapping (%v)", err)
	}

	if r.StatusCode == 200 {
		fmt.Printf("upnp: added mapping wan:%v => %v %v\n", remotePort, localPort, protocol)
		return nil
	}

	return errors.New("upnp: bad response for add port")
}

func (u *UPNP) DelPortMapping(remotePort int, protocol string) error {

	protocol = strings.ToUpper(protocol)
	if protocol != "UDP" && protocol != "TCP" {
		return errors.New("upnp: bad protocol supplied: " + protocol)
	}

	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping"`

	body := fmt.Sprintf(`<m:DeletePortMapping xmlns:m="urn:schemas-upnp-org:service:WANIPConnection:1">
	<NewRemoteHost></NewRemoteHost>
	<NewExternalPort>%v</NewExternalPort>
	<NewProtocol>%v</NewProtocol>
  </m:DeletePortMapping>`, remotePort, protocol)

	r, err := u.perform(action, body)
	if err != nil {
		return fmt.Errorf("upnp: bad response from gateway for del port mapping (%v)", err)
	}

	if r.StatusCode == 200 {
		fmt.Printf("upnp: removed mapping wan:%v %v\n", remotePort, protocol)
		return nil
	}

	return errors.New("upnp: bad response for del port mapping")
}

func (u *UPNP) ExternalIPAddress() (net.IP, error) {
	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress"`
	body := `<m:GetExternalIPAddress xmlns:m="urn:schemas-upnp-org:service:WANIPConnection:1"/>`

	r, err := u.perform(action, body)
	if r.StatusCode != 200 {
		return nil, fmt.Errorf("upnp: bad response from gateway for get external ip address (%v:%v)", r.StatusCode, err)
	}

	decoder := xml.NewDecoder(r.Body)
	found := false
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch se := t.(type) {
		case xml.StartElement:
			found = (se.Name.Local == "NewExternalIPAddress")
		case xml.CharData:
			if found {
				ip := net.ParseIP(string(se))
				u.gw.OutsideIP = ip
				return ip, nil
			}
		}
	}

	return nil, errors.New("upnp: could not get public ip from gateway")
}

func (u *UPNP) DeviceDesc() error {
	header := http.Header{}
	header.Set("Host", u.gw.Host)
	header.Set("Connection", "keep-alive")

	request, _ := http.NewRequest("GET", "http://"+u.gw.Host+u.gw.DeviceDescUrl, nil)
	request.Header = header

	response, err := http.DefaultClient.Do(request)

	if response.StatusCode != 200 {
		return err
	}

	decoder := xml.NewDecoder(response.Body)
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch se := t.(type) {
		case xml.StartElement:
			if se.Name.Local == "service" {
				var s Service
				if err := decoder.DecodeElement(&s, &se); err != nil {
					continue
				}
				if s.ServiceType == ServiceType {
					u.gw.ControlURL = s.ControlURL
					return nil
				}
			}
		}
	}
	return errors.New("upnp: Can't get control url for gateway")
}

func (u *UPNP) findGateway() error {

	search := "M-SEARCH * HTTP/1.1\r\n" +
		"HOST: 239.255.255.250:1900\r\n" +
		"ST: urn:schemas-upnp-org:service:WANIPConnection:1\r\n" +
		"MAN: \"ssdp:discover\"\r\n" +
		"MX: 3\r\n\r\n"

	// Listening port for response
	localAddr, err := net.ResolveUDPAddr("udp", ":0")
	if err != nil {
		return err
	}
	conn, err := net.ListenUDP("udp", localAddr)
	if err != nil {
		return err
	}
	defer conn.Close()

	buf := make([]byte, 1024)
	var result string
	// Broadcast message
	for i := 0; i < BroadcastRetryCount; i++ {
		remotAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
		_, err = conn.WriteToUDP([]byte(search), remotAddr)
		if err != nil {
			return err
		}

		conn.SetReadDeadline(time.Now().Add(BroadcastWaitTimeSeconds * time.Second))
		n, _, err := conn.ReadFromUDP(buf)
		if err != nil {
			if e, ok := err.(net.Error); ok && e.Timeout() {
				continue
			}
			return err
		}
		result = string(buf[:n])
		break
	}

	// Populate Gateway Info
	u.gw = &Gateway{}

	lines := strings.Split(result, "\r\n")
	for _, line := range lines {
		nameValues := strings.SplitAfterN(line, ":", 2)
		if len(nameValues) < 2 {
			continue
		}
		switch strings.ToUpper(strings.Trim(strings.Split(nameValues[0], ":")[0], " ")) {
		case "ST":
			u.gw.ST = nameValues[1]
		case "CACHE-CONTROL":
			u.gw.Cache = nameValues[1]
		case "LOCATION":
			urls := strings.Split(strings.Split(nameValues[1], "//")[1], "/")
			u.gw.Host = urls[0]
			u.gw.DeviceDescUrl = "/" + urls[1]
		case "SERVER":
			u.gw.GatewayName = nameValues[1]
		}
	}

	return nil
}

func GetLocalAddress() net.IP {
	addrs, _ := net.InterfaceAddrs()
	for _, addr := range addrs {
		ip, _, err := net.ParseCIDR(addr.String())

		if err != nil {
			continue
		}

		if isPrivateUnicast(ip) {
			return ip
		}
	}

	return nil
}

func isPrivateUnicast(ip net.IP) bool {
	for _, v := range []string{"10.0.0.0/8", "192.168.0.0/16", "172.16.0.0/12"} {
		_, block, _ := net.ParseCIDR(v)
		if block.Contains(ip) {
			return true
		}
	}

	return false
}
<commit_msg>Make Gateway info accessible<commit_after>//upnp functions to open ports on router
package upnp

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"
)

const (
	BroadcastRetryCount      = 3
	BroadcastWaitTimeSeconds = 3
	ServiceType              = "urn:schemas-upnp-org:service:WANIPConnection:1"
)

// Device Description xml elements
type Service struct {
	ServiceType string `xml:"serviceType"`
	//ServiceId   string `xml:"serviceId"`
	//SCPDURL     string `xml:"SCPDURL"`
	ControlURL string `xml:"controlURL"`
	//EventSubURL string `xml:"eventSubURL"`
}

type UPNP struct {
	Gateway *Gateway
}

type Gateway struct {
	GatewayName   string
	Host          string
	DeviceDescUrl string
	Cache         string
	ST            string
	ControlURL    string
	OutsideIP     net.IP
}

// NewUPNP returns a new UPNP object with a populated Gateway object.
func NewUPNP() (*UPNP, error) {
	u := &UPNP{}

	// Populate te the Gateway fields
	err := u.findGateway()
	if err != nil {
		return nil, err
	}

	err = u.DeviceDesc()
	if err != nil {
		return nil, err
	}

	if len(u.Gateway.ControlURL) == 0 || len(u.Gateway.Host) == 0 {
		return nil, errors.New("upnp: could not get gateway control url or host")
	}

	return u, nil
}

// perform the requested upnp action
func (u *UPNP) perform(action, body string) (*http.Response, error) {
	// Add soap envelope
	envelope := `<?xml version="1.0"?>
<SOAP-ENV:Envelope
	xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
	SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
 <SOAP-ENV:Body>
 ` + body + "</SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n\r\n"

	header := http.Header{}
	header.Set("SOAPAction", action)
	header.Set("Content-Type", "text/xml")
	header.Set("Connection", "Close")
	header.Set("Content-Length", string(len(envelope)))

	url := "http://" + u.Gateway.Host + u.Gateway.ControlURL
	req, _ := http.NewRequest("POST", url, strings.NewReader(envelope))
	req.Header = header

	//dumpreq, _ := httputil.DumpRequestOut(req, true)
	//log.Println(string(dumpreq))

	resp, err := http.DefaultClient.Do(req)

	//dumpresp, _ := httputil.DumpResponse(resp, true)
	//log.Println(string(dumpresp))

	return resp, err
}

// AddPortMapping to the WAN/Internet
func (u *UPNP) AddPortMapping(localPort, remotePort int, protocol string) error {

	protocol = strings.ToUpper(protocol)
	if protocol != "UDP" && protocol != "TCP" {
		return errors.New("upnp: bad protocol supplied: " + protocol)
	}

	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"`

	body := fmt.Sprintf(`<m:AddPortMapping xmlns:m="%v">
    <NewRemoteHost></NewRemoteHost>
    <NewExternalPort>%v</NewExternalPort>
	<NewProtocol>%v</NewProtocol>
	<NewInternalPort>%v</NewInternalPort>
	<NewInternalClient>%v</NewInternalClient>
	<NewEnabled>1</NewEnabled>
	<NewPortMappingDescription>USATVA</NewPortMappingDescription>
	<NewLeaseDuration>0</NewLeaseDuration>
  </m:AddPortMapping>`, ServiceType, remotePort, protocol, localPort, GetLocalAddress())

	r, err := u.perform(action, body)
	if err != nil {
		return fmt.Errorf("upnp: bad response from gateway for add port mapping (%v)", err)
	}

	if r.StatusCode == 200 {
		fmt.Printf("upnp: added mapping wan:%v => %v %v\n", remotePort, localPort, protocol)
		return nil
	}

	return errors.New("upnp: bad response for add port")
}

func (u *UPNP) DelPortMapping(remotePort int, protocol string) error {

	protocol = strings.ToUpper(protocol)
	if protocol != "UDP" && protocol != "TCP" {
		return errors.New("upnp: bad protocol supplied: " + protocol)
	}

	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping"`

	body := fmt.Sprintf(`<m:DeletePortMapping xmlns:m="urn:schemas-upnp-org:service:WANIPConnection:1">
	<NewRemoteHost></NewRemoteHost>
	<NewExternalPort>%v</NewExternalPort>
	<NewProtocol>%v</NewProtocol>
  </m:DeletePortMapping>`, remotePort, protocol)

	r, err := u.perform(action, body)
	if err != nil {
		return fmt.Errorf("upnp: bad response from gateway for del port mapping (%v)", err)
	}

	if r.StatusCode == 200 {
		fmt.Printf("upnp: removed mapping wan:%v %v\n", remotePort, protocol)
		return nil
	}

	return errors.New("upnp: bad response for del port mapping")
}

func (u *UPNP) ExternalIPAddress() (net.IP, error) {
	action := `"urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress"`
	body := `<m:GetExternalIPAddress xmlns:m="urn:schemas-upnp-org:service:WANIPConnection:1"/>`

	r, err := u.perform(action, body)
	if r.StatusCode != 200 {
		return nil, fmt.Errorf("upnp: bad response from gateway for get external ip address (%v:%v)", r.StatusCode, err)
	}

	decoder := xml.NewDecoder(r.Body)
	found := false
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch se := t.(type) {
		case xml.StartElement:
			found = (se.Name.Local == "NewExternalIPAddress")
		case xml.CharData:
			if found {
				ip := net.ParseIP(string(se))
				u.Gateway.OutsideIP = ip
				return ip, nil
			}
		}
	}

	return nil, errors.New("upnp: could not get public ip from gateway")
}

func (u *UPNP) DeviceDesc() error {
	header := http.Header{}
	header.Set("Host", u.Gateway.Host)
	header.Set("Connection", "keep-alive")

	request, _ := http.NewRequest("GET", "http://"+u.Gateway.Host+u.Gateway.DeviceDescUrl, nil)
	request.Header = header

	response, err := http.DefaultClient.Do(request)

	if response.StatusCode != 200 {
		return err
	}

	decoder := xml.NewDecoder(response.Body)
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch se := t.(type) {
		case xml.StartElement:
			if se.Name.Local == "service" {
				var s Service
				if err := decoder.DecodeElement(&s, &se); err != nil {
					continue
				}
				if s.ServiceType == ServiceType {
					u.Gateway.ControlURL = s.ControlURL
					return nil
				}
			}
		}
	}
	return errors.New("upnp: Can't get control url for gateway")
}

func (u *UPNP) findGateway() error {

	search := "M-SEARCH * HTTP/1.1\r\n" +
		"HOST: 239.255.255.250:1900\r\n" +
		"ST: urn:schemas-upnp-org:service:WANIPConnection:1\r\n" +
		"MAN: \"ssdp:discover\"\r\n" +
		"MX: 3\r\n\r\n"

	// Listening port for response
	localAddr, err := net.ResolveUDPAddr("udp", ":0")
	if err != nil {
		return err
	}
	conn, err := net.ListenUDP("udp", localAddr)
	if err != nil {
		return err
	}
	defer conn.Close()

	buf := make([]byte, 1024)
	var result string
	// Broadcast message
	for i := 0; i < BroadcastRetryCount; i++ {
		remotAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
		_, err = conn.WriteToUDP([]byte(search), remotAddr)
		if err != nil {
			return err
		}

		conn.SetReadDeadline(time.Now().Add(BroadcastWaitTimeSeconds * time.Second))
		n, _, err := conn.ReadFromUDP(buf)
		if err != nil {
			if e, ok := err.(net.Error); ok && e.Timeout() {
				continue
			}
			return err
		}
		result = string(buf[:n])
		break
	}

	// Populate Gateway Info
	u.Gateway = &Gateway{}

	lines := strings.Split(result, "\r\n")
	for _, line := range lines {
		nameValues := strings.SplitAfterN(line, ":", 2)
		if len(nameValues) < 2 {
			continue
		}
		switch strings.ToUpper(strings.Trim(strings.Split(nameValues[0], ":")[0], " ")) {
		case "ST":
			u.Gateway.ST = nameValues[1]
		case "CACHE-CONTROL":
			u.Gateway.Cache = nameValues[1]
		case "LOCATION":
			urls := strings.Split(strings.Split(nameValues[1], "//")[1], "/")
			u.Gateway.Host = urls[0]
			u.Gateway.DeviceDescUrl = "/" + urls[1]
		case "SERVER":
			u.Gateway.GatewayName = nameValues[1]
		}
	}

	return nil
}

func GetLocalAddress() net.IP {
	addrs, _ := net.InterfaceAddrs()
	for _, addr := range addrs {
		ip, _, err := net.ParseCIDR(addr.String())

		if err != nil {
			continue
		}

		if isPrivateUnicast(ip) {
			return ip
		}
	}

	return nil
}

func isPrivateUnicast(ip net.IP) bool {
	for _, v := range []string{"10.0.0.0/8", "192.168.0.0/16", "172.16.0.0/12"} {
		_, block, _ := net.ParseCIDR(v)
		if block.Contains(ip) {
			return true
		}
	}

	return false
}
<|endoftext|>


<commit_before>package main

// Just enough UPnP to be able to forward ports
//

import (
	"bytes"
	"encoding/xml"
	"errors"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
	"io/ioutil"
)

type upnpNAT struct {
	serviceURL string
	ourIP      string
	urnDomain string
}

func Discover() (nat NAT, err error) {
	ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900")
	if err != nil {
		return
	}
	conn, err := net.ListenPacket("udp4", ":0")
	if err != nil {
		return
	}
	socket := conn.(*net.UDPConn)
	defer socket.Close()

	err = socket.SetDeadline(time.Now().Add(3 * time.Second))
	if err != nil {
		return
	}

	st := "InternetGatewayDevice:1"

	buf := bytes.NewBufferString(
		"M-SEARCH * HTTP/1.1\r\n" +
			"HOST: 239.255.255.250:1900\r\n" +
			"ST: ssdp:all\r\n" +
			"MAN: \"ssdp:discover\"\r\n" +
			"MX: 2\r\n\r\n")
	message := buf.Bytes()
	answerBytes := make([]byte, 1024)
	for i := 0; i < 3; i++ {
		_, err = socket.WriteToUDP(message, ssdp)
		if err != nil {
			return
		}
		var n int
		n, _, err = socket.ReadFromUDP(answerBytes)
		for {
			n, _, err = socket.ReadFromUDP(answerBytes)
			if err != nil {
				break
			}
			answer := string(answerBytes[0:n])
			if strings.Index(answer, st) < 0 {
				continue
			}
			// HTTP header field names are case-insensitive.
			// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
			locString := "\r\nlocation:"
			answer = strings.ToLower(answer)
			locIndex := strings.Index(answer, locString)
			if locIndex < 0 {
				continue
			}
			loc := answer[locIndex+len(locString):]
			endIndex := strings.Index(loc, "\r\n")
			if endIndex < 0 {
				continue
			}

			locURL := loc[0:endIndex]
			var serviceURL, urnDomain string
			serviceURL, urnDomain, err = getServiceURL(locURL)
			if err != nil {
				return
			}
			var ourIP string
			ourIP, err = getOurIP()
			if err != nil {
				return
			}
			nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP, urnDomain: urnDomain}
			return
		}
	}
	err = errors.New("UPnP port discovery failed.")
	return
}

type Envelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
	Soap    *SoapBody
}
type SoapBody struct {
	XMLName   xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
	ExternalIP *ExternalIPAddressResponse
}

type ExternalIPAddressResponse struct {
	XMLName xml.Name `xml:"GetExternalIPAddressResponse"`
	IPAddress string `xml:"NewExternalIPAddress"`
}

type ExternalIPAddress struct {
	XMLName xml.Name `xml:"NewExternalIPAddress"`
	IP string
}

type Service struct {
	ServiceType string `xml:"serviceType"`
	ControlURL  string `xml:"controlURL"`
}

type DeviceList struct {
	Device []Device `xml:"device"`
}

type ServiceList struct {
	Service []Service `xml:"service"`
}

type Device struct {
	XMLName xml.Name `xml:"device"`
	DeviceType  string `xml:"deviceType"`
	DeviceList  DeviceList `xml:"deviceList"`
	ServiceList ServiceList `xml:"serviceList"`
}

type Root struct {
	Device Device
}

func getChildDevice(d *Device, deviceType string) *Device {
	dl := d.DeviceList.Device
	for i := 0; i < len(dl); i++ {
		if strings.Index(dl[i].DeviceType, deviceType) >= 0 {
			return &dl[i]
		}
	}
	return nil
}

func getChildService(d *Device, serviceType string) *Service {
	sl := d.ServiceList.Service
	for i := 0; i < len(sl); i++ {
		if strings.Index(sl[i].ServiceType, serviceType) >= 0 {
			return &sl[i]
		}
	}
	return nil
}

func getOurIP() (ip string, err error) {
	hostname, err := os.Hostname()
	if err != nil {
		return
	}
	return net.LookupCNAME(hostname)
}

func getServiceURL(rootURL string) (url, urnDomain string, err error) {
	r, err := http.Get(rootURL)
	if err != nil {
		return
	}
	defer r.Body.Close()
	if r.StatusCode >= 400 {
		err = errors.New(string(r.StatusCode))
		return
	}
	var root Root
	err = xml.NewDecoder(r.Body).Decode(&root)
	if err != nil {
		return
	}
	a := &root.Device
	if strings.Index(a.DeviceType, "InternetGatewayDevice:1") < 0 {
		err = errors.New("No InternetGatewayDevice")
		return
	}
	b := getChildDevice(a, "WANDevice:1")
	if b == nil {
		err = errors.New("No WANDevice")
		return
	}
	c := getChildDevice(b, "WANConnectionDevice:1")
	if c == nil {
		err = errors.New("No WANConnectionDevice")
		return
	}
	d := getChildService(c, "WANIPConnection:1")
	if d == nil {
		// Some routers don't follow the UPnP spec, and put WanIPConnection under WanDevice,
		// instead of under WanConnectionDevice
		d = getChildService(b, "WANIPConnection:1")

		if d == nil {
			err = errors.New("No WANIPConnection")
			return
		}
	}
	// Extract the domain name, which isn't always 'schemas-upnp-org'
	urnDomain = strings.Split(d.ServiceType, ":")[1]
	url = combineURL(rootURL, d.ControlURL)
	return
}

func combineURL(rootURL, subURL string) string {
	protocolEnd := "://"
	protoEndIndex := strings.Index(rootURL, protocolEnd)
	a := rootURL[protoEndIndex+len(protocolEnd):]
	rootIndex := strings.Index(a, "/")
	return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL
}

func soapRequest(url, function, message, domain string) (r *http.Response, err error) {
	fullMessage := "<?xml version=\"1.0\" ?>" +
		"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" +
		"<s:Body>" + message + "</s:Body></s:Envelope>"

	req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"")
	req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3")
	//req.Header.Set("Transfer-Encoding", "chunked")
	req.Header.Set("SOAPAction", "\"urn:" + domain + ":service:WANIPConnection:1#"+function+"\"")
	req.Header.Set("Connection", "Close")
	req.Header.Set("Cache-Control", "no-cache")
	req.Header.Set("Pragma", "no-cache")

	// log.Stderr("soapRequest ", req)

	r, err = http.DefaultClient.Do(req)
	/*if r.Body != nil {
		defer r.Body.Close()
	}*/

	if r.StatusCode >= 400 {
		// log.Stderr(function, r.StatusCode)
		err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function)
		r = nil
		return
	}
	return
}

type statusInfo struct {
	externalIpAddress string
}

func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) {

	message := "<u:GetExternalIPAddress xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"</u:GetExternalIPAddress>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "GetExternalIPAddress", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}
	var envelope Envelope
	data, err := ioutil.ReadAll(response.Body)
	reader := bytes.NewReader(data)
	xml.NewDecoder(reader).Decode(&envelope)

	info = statusInfo{envelope.Soap.ExternalIP.IPAddress}

	if err != nil {
		return
	}

	return
}

func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) {
	info, err := n.getExternalIPAddress()
	if err != nil {
		return
	}
	addr = net.ParseIP(info.externalIpAddress)
	return
}

func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) {
	// A single concatenation would break ARM compilation.
	message := "<u:AddPortMapping xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort)
	message += "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>"
	message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" +
		"<NewInternalClient>" + n.ourIP + "</NewInternalClient>" +
		"<NewEnabled>1</NewEnabled><NewPortMappingDescription>"
	message += description +
		"</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) +
		"</NewLeaseDuration></u:AddPortMapping>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "AddPortMapping", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}

	// TODO: check response to see if the port was forwarded
	// log.Println(message, response)
	mappedExternalPort = externalPort
	_ = response
	return
}

func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) {

	message := "<u:DeletePortMapping xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) +
		"</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>" +
		"</u:DeletePortMapping>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "DeletePortMapping", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}

	// TODO: check response to see if the port was deleted
	// log.Println(message, response)
	_ = response
	return
}
<commit_msg>Run go fmt<commit_after>package main

// Just enough UPnP to be able to forward ports
//

import (
	"bytes"
	"encoding/xml"
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

type upnpNAT struct {
	serviceURL string
	ourIP      string
	urnDomain  string
}

func Discover() (nat NAT, err error) {
	ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900")
	if err != nil {
		return
	}
	conn, err := net.ListenPacket("udp4", ":0")
	if err != nil {
		return
	}
	socket := conn.(*net.UDPConn)
	defer socket.Close()

	err = socket.SetDeadline(time.Now().Add(3 * time.Second))
	if err != nil {
		return
	}

	st := "InternetGatewayDevice:1"

	buf := bytes.NewBufferString(
		"M-SEARCH * HTTP/1.1\r\n" +
			"HOST: 239.255.255.250:1900\r\n" +
			"ST: ssdp:all\r\n" +
			"MAN: \"ssdp:discover\"\r\n" +
			"MX: 2\r\n\r\n")
	message := buf.Bytes()
	answerBytes := make([]byte, 1024)
	for i := 0; i < 3; i++ {
		_, err = socket.WriteToUDP(message, ssdp)
		if err != nil {
			return
		}
		var n int
		n, _, err = socket.ReadFromUDP(answerBytes)
		for {
			n, _, err = socket.ReadFromUDP(answerBytes)
			if err != nil {
				break
			}
			answer := string(answerBytes[0:n])
			if strings.Index(answer, st) < 0 {
				continue
			}
			// HTTP header field names are case-insensitive.
			// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
			locString := "\r\nlocation:"
			answer = strings.ToLower(answer)
			locIndex := strings.Index(answer, locString)
			if locIndex < 0 {
				continue
			}
			loc := answer[locIndex+len(locString):]
			endIndex := strings.Index(loc, "\r\n")
			if endIndex < 0 {
				continue
			}

			locURL := loc[0:endIndex]
			var serviceURL, urnDomain string
			serviceURL, urnDomain, err = getServiceURL(locURL)
			if err != nil {
				return
			}
			var ourIP string
			ourIP, err = getOurIP()
			if err != nil {
				return
			}
			nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP, urnDomain: urnDomain}
			return
		}
	}
	err = errors.New("UPnP port discovery failed.")
	return
}

type Envelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
	Soap    *SoapBody
}
type SoapBody struct {
	XMLName    xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
	ExternalIP *ExternalIPAddressResponse
}

type ExternalIPAddressResponse struct {
	XMLName   xml.Name `xml:"GetExternalIPAddressResponse"`
	IPAddress string   `xml:"NewExternalIPAddress"`
}

type ExternalIPAddress struct {
	XMLName xml.Name `xml:"NewExternalIPAddress"`
	IP      string
}

type Service struct {
	ServiceType string `xml:"serviceType"`
	ControlURL  string `xml:"controlURL"`
}

type DeviceList struct {
	Device []Device `xml:"device"`
}

type ServiceList struct {
	Service []Service `xml:"service"`
}

type Device struct {
	XMLName     xml.Name    `xml:"device"`
	DeviceType  string      `xml:"deviceType"`
	DeviceList  DeviceList  `xml:"deviceList"`
	ServiceList ServiceList `xml:"serviceList"`
}

type Root struct {
	Device Device
}

func getChildDevice(d *Device, deviceType string) *Device {
	dl := d.DeviceList.Device
	for i := 0; i < len(dl); i++ {
		if strings.Index(dl[i].DeviceType, deviceType) >= 0 {
			return &dl[i]
		}
	}
	return nil
}

func getChildService(d *Device, serviceType string) *Service {
	sl := d.ServiceList.Service
	for i := 0; i < len(sl); i++ {
		if strings.Index(sl[i].ServiceType, serviceType) >= 0 {
			return &sl[i]
		}
	}
	return nil
}

func getOurIP() (ip string, err error) {
	hostname, err := os.Hostname()
	if err != nil {
		return
	}
	return net.LookupCNAME(hostname)
}

func getServiceURL(rootURL string) (url, urnDomain string, err error) {
	r, err := http.Get(rootURL)
	if err != nil {
		return
	}
	defer r.Body.Close()
	if r.StatusCode >= 400 {
		err = errors.New(string(r.StatusCode))
		return
	}
	var root Root
	err = xml.NewDecoder(r.Body).Decode(&root)
	if err != nil {
		return
	}
	a := &root.Device
	if strings.Index(a.DeviceType, "InternetGatewayDevice:1") < 0 {
		err = errors.New("No InternetGatewayDevice")
		return
	}
	b := getChildDevice(a, "WANDevice:1")
	if b == nil {
		err = errors.New("No WANDevice")
		return
	}
	c := getChildDevice(b, "WANConnectionDevice:1")
	if c == nil {
		err = errors.New("No WANConnectionDevice")
		return
	}
	d := getChildService(c, "WANIPConnection:1")
	if d == nil {
		// Some routers don't follow the UPnP spec, and put WanIPConnection under WanDevice,
		// instead of under WanConnectionDevice
		d = getChildService(b, "WANIPConnection:1")

		if d == nil {
			err = errors.New("No WANIPConnection")
			return
		}
	}
	// Extract the domain name, which isn't always 'schemas-upnp-org'
	urnDomain = strings.Split(d.ServiceType, ":")[1]
	url = combineURL(rootURL, d.ControlURL)
	return
}

func combineURL(rootURL, subURL string) string {
	protocolEnd := "://"
	protoEndIndex := strings.Index(rootURL, protocolEnd)
	a := rootURL[protoEndIndex+len(protocolEnd):]
	rootIndex := strings.Index(a, "/")
	return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL
}

func soapRequest(url, function, message, domain string) (r *http.Response, err error) {
	fullMessage := "<?xml version=\"1.0\" ?>" +
		"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" +
		"<s:Body>" + message + "</s:Body></s:Envelope>"

	req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"")
	req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3")
	//req.Header.Set("Transfer-Encoding", "chunked")
	req.Header.Set("SOAPAction", "\"urn:"+domain+":service:WANIPConnection:1#"+function+"\"")
	req.Header.Set("Connection", "Close")
	req.Header.Set("Cache-Control", "no-cache")
	req.Header.Set("Pragma", "no-cache")

	// log.Stderr("soapRequest ", req)

	r, err = http.DefaultClient.Do(req)
	/*if r.Body != nil {
		defer r.Body.Close()
	}*/

	if r.StatusCode >= 400 {
		// log.Stderr(function, r.StatusCode)
		err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function)
		r = nil
		return
	}
	return
}

type statusInfo struct {
	externalIpAddress string
}

func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) {

	message := "<u:GetExternalIPAddress xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"</u:GetExternalIPAddress>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "GetExternalIPAddress", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}
	var envelope Envelope
	data, err := ioutil.ReadAll(response.Body)
	reader := bytes.NewReader(data)
	xml.NewDecoder(reader).Decode(&envelope)

	info = statusInfo{envelope.Soap.ExternalIP.IPAddress}

	if err != nil {
		return
	}

	return
}

func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) {
	info, err := n.getExternalIPAddress()
	if err != nil {
		return
	}
	addr = net.ParseIP(info.externalIpAddress)
	return
}

func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) {
	// A single concatenation would break ARM compilation.
	message := "<u:AddPortMapping xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort)
	message += "</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>"
	message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" +
		"<NewInternalClient>" + n.ourIP + "</NewInternalClient>" +
		"<NewEnabled>1</NewEnabled><NewPortMappingDescription>"
	message += description +
		"</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) +
		"</NewLeaseDuration></u:AddPortMapping>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "AddPortMapping", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}

	// TODO: check response to see if the port was forwarded
	// log.Println(message, response)
	mappedExternalPort = externalPort
	_ = response
	return
}

func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) {

	message := "<u:DeletePortMapping xmlns:u=\"urn:" + n.urnDomain + ":service:WANIPConnection:1\">\r\n" +
		"<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort) +
		"</NewExternalPort><NewProtocol>" + protocol + "</NewProtocol>" +
		"</u:DeletePortMapping>"

	var response *http.Response
	response, err = soapRequest(n.serviceURL, "DeletePortMapping", message, n.urnDomain)
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}

	// TODO: check response to see if the port was deleted
	// log.Println(message, response)
	_ = response
	return
}
<|endoftext|>


<commit_before>package model

import (
	"fmt"

	"github.com/Konstantin8105/GoFea/input/element"
	"github.com/Konstantin8105/GoFea/utils"
)

func (m *Dim2) checkInputData() error {
	errorText := "Not enought data for calculate. %s"
	if len(m.points) < 2 {
		return fmt.Errorf(errorText, "Please add points in model")
	}
	if len(m.elements) < 1 {
		return fmt.Errorf(errorText, "Please add finite elements in model")
	}
	if len(m.supports) < 1 {
		return fmt.Errorf(errorText, "Please add supports in model")
	}
	if len(m.materials) < 1 {
		return fmt.Errorf(errorText, "Please add material in model")
	}
	if len(m.forceCases) < 1 {
		return fmt.Errorf(errorText, "Please add load case in model")
	}

	// only 2 points in beam
	for _, e := range m.elements {
		switch e.(type) {
		case element.Beam:
			beam := e.(element.Beam)
			if len(beam.GetPointIndex()) != 2 {
				return fmt.Errorf("Not correct amount of node for beam %#v", beam)
			}
		default:
			panic("Add finite element")
		}
	}

	// checking length of finite element beam
	// for avoid divide by zero
	var zeroElements []element.Index
	for _, e := range m.elements {
		coord, err := m.getCoordinate(e.GetIndex())
		if err != nil {
			return err
		}
		for i := 0; i < len(coord); i++ {
			for j := 0; j < len(coord); j++ {
				if i <= j {
					continue
				}
				if utils.LengthDim2(coord[i], coord[j]) <= 0.0 {
					zeroElements = append(zeroElements, e.GetIndex())
					goto next
				}
			}
		}
	next:
	}
	if len(zeroElements) > 0 {
		var list string
		for i := range zeroElements {
			list += fmt.Sprintf("%v,", zeroElements[i])
		}
		return fmt.Errorf("Finite element %s have length equal zero", list)
	}

	// compress node loads
	for _, f := range m.forceCases {
	begin:
		size := len(f.nodeForces)
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if f.nodeForces[i].pointIndex == f.nodeForces[j].pointIndex {
					f.nodeForces[i].nodeForce.Plus(f.nodeForces[j].nodeForce)
					for k := j; k < size-1; k++ {
						f.nodeForces[k] = f.nodeForces[k+1]
					}
					f.nodeForces = f.nodeForces[0 : len(f.nodeForces)-1]
					goto begin
				}
			}
		}
	}

	// compress material
	{
		size := len(m.materials)
		var errorIndexes []int
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.materials[i].elementIndex == m.materials[j].elementIndex {
					errorIndexes = append(errorIndexes, i)
					errorIndexes = append(errorIndexes, j)
				}
			}
		}
		if len(errorIndexes) > 0 {
			s := "Please clarify material, because material is same for next elements:\n"
			for i := 0; i < len(errorIndexes); i += 2 {
				s += fmt.Sprintf("%v and %v\n", errorIndexes[i], errorIndexes[i+1])
			}
			return fmt.Errorf("Error. %v", s)
		}
	}

	//TODO compress support

	// compress shape
	{
		size := len(m.shapes)
		var errorIndexes []int
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.shapes[i].elementIndex == m.shapes[j].elementIndex {
					errorIndexes = append(errorIndexes, i)
					errorIndexes = append(errorIndexes, j)
				}
			}
		}
		if len(errorIndexes) > 0 {
			s := "Please clarify shape, because shapes is same for next elements:\n"
			for i := 0; i < len(errorIndexes); i += 2 {
				s += fmt.Sprintf("%v and %v\n", errorIndexes[i], errorIndexes[i+1])
			}
			return fmt.Errorf("Error. %v", s)
		}
	}

	// compress truss
	{
	beginTruss:
		size := len(m.truss)
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.truss[i].elementIndex == m.truss[j].elementIndex {
					for k := j; k < size-1; k++ {
						m.truss[k] = m.truss[k+1]
					}
					m.truss = m.truss[0 : len(m.truss)-1]
					goto beginTruss
				}
			}
		}
	}

	//TODO sorting for quick search

	return nil
}
<commit_msg>add checking<commit_after>package model

import (
	"fmt"

	"github.com/Konstantin8105/GoFea/input/element"
	"github.com/Konstantin8105/GoFea/utils"
)

func (m *Dim2) checkInputData() error {
	errorText := "Not enought data for calculate. %s"
	if len(m.points) < 2 {
		return fmt.Errorf(errorText, "Please add points in model")
	}
	if len(m.elements) < 1 {
		return fmt.Errorf(errorText, "Please add finite elements in model")
	}
	if len(m.supports) < 1 {
		return fmt.Errorf(errorText, "Please add supports in model")
	}
	if len(m.materials) < 1 {
		return fmt.Errorf(errorText, "Please add material in model")
	}
	if len(m.forceCases) < 1 {
		return fmt.Errorf(errorText, "Please add load case in model")
	}

	// only 2 points in beam
	for _, e := range m.elements {
		switch e.(type) {
		case element.Beam:
			beam := e.(element.Beam)
			if len(beam.GetPointIndex()) != 2 {
				return fmt.Errorf("Not correct amount of node for beam %#v", beam)
			}
		default:
			panic("Add finite element")
		}
	}

	// checking length of finite element beam
	// for avoid divide by zero
	var zeroElements []element.Index
	for _, e := range m.elements {
		coord, err := m.getCoordinate(e.GetIndex())
		if err != nil {
			return err
		}
		for i := 0; i < len(coord); i++ {
			for j := 0; j < len(coord); j++ {
				if i <= j {
					continue
				}
				if utils.LengthDim2(coord[i], coord[j]) <= 0.0 {
					zeroElements = append(zeroElements, e.GetIndex())
					goto next
				}
			}
		}
	next:
	}
	if len(zeroElements) > 0 {
		var list string
		for i := range zeroElements {
			list += fmt.Sprintf("%v,", zeroElements[i])
		}
		return fmt.Errorf("Finite element %s have length equal zero", list)
	}

	// compress node loads
	for _, f := range m.forceCases {
	begin:
		size := len(f.nodeForces)
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if f.nodeForces[i].pointIndex == f.nodeForces[j].pointIndex {
					f.nodeForces[i].nodeForce.Plus(f.nodeForces[j].nodeForce)
					for k := j; k < size-1; k++ {
						f.nodeForces[k] = f.nodeForces[k+1]
					}
					f.nodeForces = f.nodeForces[0 : len(f.nodeForces)-1]
					goto begin
				}
			}
		}
	}

	// compress material
	{
		size := len(m.materials)
		var errorIndexes []int
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.materials[i].elementIndex == m.materials[j].elementIndex {
					errorIndexes = append(errorIndexes, i)
					errorIndexes = append(errorIndexes, j)
				}
			}
		}
		if len(errorIndexes) > 0 {
			s := "Please clarify material, because material is same for next elements:\n"
			for i := 0; i < len(errorIndexes); i += 2 {
				s += fmt.Sprintf("%v and %v\n", errorIndexes[i], errorIndexes[i+1])
			}
			return fmt.Errorf("Error. %v", s)
		}
	}

	// compress support
	{
	beginSupport:
		size := len(m.supports)
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.supports[i].pointIndex == m.supports[j].pointIndex {
					for k := j; k < size-1; k++ {
						m.supports[k] = m.supports[k+1]
					}
					m.supports = m.supports[0 : len(m.supports)-1]
					goto beginSupport
				}
			}
		}
	}

	// compress shape
	{
		size := len(m.shapes)
		var errorIndexes []int
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.shapes[i].elementIndex == m.shapes[j].elementIndex {
					errorIndexes = append(errorIndexes, i)
					errorIndexes = append(errorIndexes, j)
				}
			}
		}
		if len(errorIndexes) > 0 {
			s := "Please clarify shape, because shapes is same for next elements:\n"
			for i := 0; i < len(errorIndexes); i += 2 {
				s += fmt.Sprintf("%v and %v\n", errorIndexes[i], errorIndexes[i+1])
			}
			return fmt.Errorf("Error. %v", s)
		}
	}

	// compress truss
	{
	beginTruss:
		size := len(m.truss)
		for i := 0; i < size; i++ {
			for j := i + 1; j < size; j++ {
				if m.truss[i].elementIndex == m.truss[j].elementIndex {
					for k := j; k < size-1; k++ {
						m.truss[k] = m.truss[k+1]
					}
					m.truss = m.truss[0 : len(m.truss)-1]
					goto beginTruss
				}
			}
		}
	}

	//TODO sorting for quick search

	return nil
}
<|endoftext|>


<commit_before>package self_test

import (
	"context"
	"fmt"
	"io/ioutil"
	"net"

	quic "github.com/lucas-clemente/quic-go"
	"github.com/lucas-clemente/quic-go/internal/handshake"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Key Update tests", func() {
	var server quic.Listener

	runServer := func() {
		var err error
		// start the server
		server, err = quic.ListenAddr("localhost:0", getTLSConfig(), nil)
		Expect(err).ToNot(HaveOccurred())

		go func() {
			defer GinkgoRecover()
			sess, err := server.Accept(context.Background())
			Expect(err).ToNot(HaveOccurred())
			str, err := sess.OpenUniStream()
			Expect(err).ToNot(HaveOccurred())
			defer str.Close()
			_, err = str.Write(PRDataLong)
			Expect(err).ToNot(HaveOccurred())
		}()
	}

	BeforeEach(func() {
		// update keys as frequently as possible
		handshake.KeyUpdateInterval = 1
		runServer()
	})

	It("downloads a large file", func() {
		sess, err := quic.DialAddr(
			fmt.Sprintf("localhost:%d", server.Addr().(*net.UDPAddr).Port),
			getTLSClientConfig(),
			nil,
		)
		Expect(err).ToNot(HaveOccurred())
		defer sess.CloseWithError(0, "")
		str, err := sess.AcceptUniStream(context.Background())
		Expect(err).ToNot(HaveOccurred())
		data, err := ioutil.ReadAll(str)
		Expect(err).ToNot(HaveOccurred())
		Expect(data).To(Equal(PRDataLong))
	})
})
<commit_msg>check that keys are actually updated in the key update integration test<commit_after>package self_test

import (
	"context"
	"fmt"
	"io/ioutil"
	"net"
	"time"

	quic "github.com/lucas-clemente/quic-go"
	"github.com/lucas-clemente/quic-go/internal/handshake"
	"github.com/lucas-clemente/quic-go/internal/protocol"
	"github.com/lucas-clemente/quic-go/logging"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var sentHeaders []*logging.ExtendedHeader
var receivedHeaders []*logging.ExtendedHeader

func countKeyPhases() (sent, received int) {
	lastKeyPhase := protocol.KeyPhaseOne
	for _, hdr := range sentHeaders {
		if hdr.IsLongHeader {
			continue
		}
		if hdr.KeyPhase != lastKeyPhase {
			sent++
			lastKeyPhase = hdr.KeyPhase
		}
	}
	lastKeyPhase = protocol.KeyPhaseOne
	for _, hdr := range receivedHeaders {
		if hdr.IsLongHeader {
			continue
		}
		if hdr.KeyPhase != lastKeyPhase {
			received++
			lastKeyPhase = hdr.KeyPhase
		}
	}
	return
}

type simpleTracer struct{}

var _ logging.Tracer = &simpleTracer{}

func (t *simpleTracer) TracerForConnection(p logging.Perspective, odcid logging.ConnectionID) logging.ConnectionTracer {
	return &connTracer{}
}
func (t *simpleTracer) SentPacket(net.Addr, *logging.Header, logging.ByteCount, []logging.Frame) {}
func (t *simpleTracer) DroppedPacket(net.Addr, logging.PacketType, logging.ByteCount, logging.PacketDropReason) {
}

type connTracer struct{}

var _ logging.ConnectionTracer = &connTracer{}

func (t *connTracer) StartedConnection(local, remote net.Addr, version logging.VersionNumber, srcConnID, destConnID logging.ConnectionID) {
}
func (t *connTracer) ClosedConnection(logging.CloseReason)                     {}
func (t *connTracer) SentTransportParameters(*logging.TransportParameters)     {}
func (t *connTracer) ReceivedTransportParameters(*logging.TransportParameters) {}
func (t *connTracer) SentPacket(hdr *logging.ExtendedHeader, size logging.ByteCount, ack *logging.AckFrame, frames []logging.Frame) {
	sentHeaders = append(sentHeaders, hdr)
}
func (t *connTracer) ReceivedVersionNegotiationPacket(*logging.Header, []logging.VersionNumber) {}
func (t *connTracer) ReceivedRetry(*logging.Header)                                             {}
func (t *connTracer) ReceivedPacket(hdr *logging.ExtendedHeader, size logging.ByteCount, frames []logging.Frame) {
	receivedHeaders = append(receivedHeaders, hdr)
}
func (t *connTracer) BufferedPacket(logging.PacketType)                                             {}
func (t *connTracer) DroppedPacket(logging.PacketType, logging.ByteCount, logging.PacketDropReason) {}
func (t *connTracer) UpdatedMetrics(rttStats *logging.RTTStats, cwnd, bytesInFlight logging.ByteCount, packetsInFlight int) {
}
func (t *connTracer) LostPacket(logging.EncryptionLevel, logging.PacketNumber, logging.PacketLossReason) {
}
func (t *connTracer) UpdatedCongestionState(logging.CongestionState)                     {}
func (t *connTracer) UpdatedPTOCount(value uint32)                                       {}
func (t *connTracer) UpdatedKeyFromTLS(logging.EncryptionLevel, logging.Perspective)     {}
func (t *connTracer) UpdatedKey(generation logging.KeyPhase, remote bool)                {}
func (t *connTracer) DroppedEncryptionLevel(logging.EncryptionLevel)                     {}
func (t *connTracer) DroppedKey(logging.KeyPhase)                                        {}
func (t *connTracer) SetLossTimer(logging.TimerType, logging.EncryptionLevel, time.Time) {}
func (t *connTracer) LossTimerExpired(logging.TimerType, logging.EncryptionLevel)        {}
func (t *connTracer) LossTimerCanceled()                                                 {}
func (t *connTracer) Close()                                                             {}

var _ = Describe("Key Update tests", func() {
	var server quic.Listener

	runServer := func() {
		var err error
		server, err = quic.ListenAddr("localhost:0", getTLSConfig(), nil)
		Expect(err).ToNot(HaveOccurred())

		go func() {
			defer GinkgoRecover()
			sess, err := server.Accept(context.Background())
			Expect(err).ToNot(HaveOccurred())
			str, err := sess.OpenUniStream()
			Expect(err).ToNot(HaveOccurred())
			defer str.Close()
			_, err = str.Write(PRDataLong)
			Expect(err).ToNot(HaveOccurred())
		}()
	}

	It("downloads a large file", func() {
		origKeyUpdateInterval := handshake.KeyUpdateInterval
		defer func() { handshake.KeyUpdateInterval = origKeyUpdateInterval }()
		handshake.KeyUpdateInterval = 1 // update keys as frequently as possible

		runServer()
		sess, err := quic.DialAddr(
			fmt.Sprintf("localhost:%d", server.Addr().(*net.UDPAddr).Port),
			getTLSClientConfig(),
			&quic.Config{Tracer: &simpleTracer{}},
		)
		Expect(err).ToNot(HaveOccurred())
		str, err := sess.AcceptUniStream(context.Background())
		Expect(err).ToNot(HaveOccurred())
		data, err := ioutil.ReadAll(str)
		Expect(err).ToNot(HaveOccurred())
		Expect(data).To(Equal(PRDataLong))
		Expect(sess.CloseWithError(0, "")).To(Succeed())

		keyPhasesSent, keyPhasesReceived := countKeyPhases()
		fmt.Fprintf(GinkgoWriter, "Used %d key phases on outgoing and %d key phases on incoming packets.\n", keyPhasesSent, keyPhasesReceived)
		Expect(keyPhasesReceived).To(BeNumerically(">", 10))
		Expect(keyPhasesReceived).To(BeNumerically("~", keyPhasesSent, 1))
	})
})
<|endoftext|>


<commit_before>// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ipv6_test

import (
	"fmt"
	"log"
	"net"
	"os"
	"time"

	"golang.org/x/net/icmp"
	"golang.org/x/net/internal/iana"
	"golang.org/x/net/ipv6"
)

func ExampleConn_markingTCP() {
	ln, err := net.Listen("tcp6", "[::]:1024")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	for {
		c, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go func(c net.Conn) {
			defer c.Close()
			p := ipv6.NewConn(c)
			if err := p.SetTrafficClass(iana.DiffServAF11); err != nil {
				log.Fatal(err)
			}
			if err := p.SetHopLimit(128); err != nil {
				log.Fatal(err)
			}
			if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil {
				log.Fatal(err)
			}
		}(c)
	}
}

func ExamplePacketConn_servingOneShotMulticastDNS() {
	c, err := net.ListenPacket("udp6", "[::]:5353") // mDNS over UDP
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	en0, err := net.InterfaceByName("en0")
	if err != nil {
		log.Fatal(err)
	}
	mDNSLinkLocal := net.UDPAddr{IP: net.ParseIP("ff02::fb")}
	if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil {
		log.Fatal(err)
	}
	defer p.LeaveGroup(en0, &mDNSLinkLocal)
	if err := p.SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
		log.Fatal(err)
	}

	var wcm ipv6.ControlMessage
	b := make([]byte, 1500)
	for {
		_, rcm, peer, err := p.ReadFrom(b)
		if err != nil {
			log.Fatal(err)
		}
		if !rcm.Dst.IsMulticast() || !rcm.Dst.Equal(mDNSLinkLocal.IP) {
			continue
		}
		wcm.IfIndex = rcm.IfIndex
		answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this
		if _, err := p.WriteTo(answers, &wcm, peer); err != nil {
			log.Fatal(err)
		}
	}
}

func ExamplePacketConn_tracingIPPacketRoute() {
	// Tracing an IP packet route to www.google.com.

	const host = "www.google.com"
	ips, err := net.LookupIP(host)
	if err != nil {
		log.Fatal(err)
	}
	var dst net.IPAddr
	for _, ip := range ips {
		if ip.To16() != nil && ip.To4() == nil {
			dst.IP = ip
			fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host)
			break
		}
	}
	if dst.IP == nil {
		log.Fatal("no AAAA record found")
	}

	c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolIPv6ICMP), "::") // ICMP for IPv6
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	if err := p.SetControlMessage(ipv6.FlagHopLimit|ipv6.FlagSrc|ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
		log.Fatal(err)
	}
	wm := icmp.Message{
		Type: ipv6.ICMPTypeEchoRequest, Code: 0,
		Body: &icmp.Echo{
			ID:   os.Getpid() & 0xffff,
			Data: []byte("HELLO-R-U-THERE"),
		},
	}
	var f ipv6.ICMPFilter
	f.SetAll(true)
	f.Accept(ipv6.ICMPTypeTimeExceeded)
	f.Accept(ipv6.ICMPTypeEchoReply)
	if err := p.SetICMPFilter(&f); err != nil {
		log.Fatal(err)
	}

	var wcm ipv6.ControlMessage
	rb := make([]byte, 1500)
	for i := 1; i <= 64; i++ { // up to 64 hops
		wm.Body.(*icmp.Echo).Seq = i
		wb, err := wm.Marshal(nil)
		if err != nil {
			log.Fatal(err)
		}

		// In the real world usually there are several
		// multiple traffic-engineered paths for each hop.
		// You may need to probe a few times to each hop.
		begin := time.Now()
		wcm.HopLimit = i
		if _, err := p.WriteTo(wb, &wcm, &dst); err != nil {
			log.Fatal(err)
		}
		if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
			log.Fatal(err)
		}
		n, rcm, peer, err := p.ReadFrom(rb)
		if err != nil {
			if err, ok := err.(net.Error); ok && err.Timeout() {
				fmt.Printf("%v\t*\n", i)
				continue
			}
			log.Fatal(err)
		}
		rm, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n])
		if err != nil {
			log.Fatal(err)
		}
		rtt := time.Since(begin)

		// In the real world you need to determine whether the
		// received message is yours using ControlMessage.Src,
		// ControlMesage.Dst, icmp.Echo.ID and icmp.Echo.Seq.
		switch rm.Type {
		case ipv6.ICMPTypeTimeExceeded:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
		case ipv6.ICMPTypeEchoReply:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
			return
		}
	}
}

func ExamplePacketConn_advertisingOSPFHello() {
	c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolOSPFIGP), "::") // OSPF for IPv6
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	en0, err := net.InterfaceByName("en0")
	if err != nil {
		log.Fatal(err)
	}
	allSPFRouters := net.IPAddr{IP: net.ParseIP("ff02::5")}
	if err := p.JoinGroup(en0, &allSPFRouters); err != nil {
		log.Fatal(err)
	}
	defer p.LeaveGroup(en0, &allSPFRouters)

	hello := make([]byte, 24) // fake hello data, you need to implement this
	ospf := make([]byte, 16)  // fake ospf header, you need to implement this
	ospf[0] = 3               // version 3
	ospf[1] = 1               // hello packet
	ospf = append(ospf, hello...)
	if err := p.SetChecksum(true, 12); err != nil {
		log.Fatal(err)
	}

	cm := ipv6.ControlMessage{
		TrafficClass: iana.DiffServCS6,
		HopLimit:     1,
		IfIndex:      en0.Index,
	}
	if _, err := p.WriteTo(ospf, &cm, &allSPFRouters); err != nil {
		log.Fatal(err)
	}
}
<commit_msg>ipv6: don't refer internal packages in examples<commit_after>// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ipv6_test

import (
	"fmt"
	"log"
	"net"
	"os"
	"time"

	"golang.org/x/net/icmp"
	"golang.org/x/net/ipv6"
)

func ExampleConn_markingTCP() {
	ln, err := net.Listen("tcp6", "[::]:1024")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	for {
		c, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go func(c net.Conn) {
			defer c.Close()
			p := ipv6.NewConn(c)
			if err := p.SetTrafficClass(0x28); err != nil { // DSCP AF11
				log.Fatal(err)
			}
			if err := p.SetHopLimit(128); err != nil {
				log.Fatal(err)
			}
			if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil {
				log.Fatal(err)
			}
		}(c)
	}
}

func ExamplePacketConn_servingOneShotMulticastDNS() {
	c, err := net.ListenPacket("udp6", "[::]:5353") // mDNS over UDP
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	en0, err := net.InterfaceByName("en0")
	if err != nil {
		log.Fatal(err)
	}
	mDNSLinkLocal := net.UDPAddr{IP: net.ParseIP("ff02::fb")}
	if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil {
		log.Fatal(err)
	}
	defer p.LeaveGroup(en0, &mDNSLinkLocal)
	if err := p.SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
		log.Fatal(err)
	}

	var wcm ipv6.ControlMessage
	b := make([]byte, 1500)
	for {
		_, rcm, peer, err := p.ReadFrom(b)
		if err != nil {
			log.Fatal(err)
		}
		if !rcm.Dst.IsMulticast() || !rcm.Dst.Equal(mDNSLinkLocal.IP) {
			continue
		}
		wcm.IfIndex = rcm.IfIndex
		answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this
		if _, err := p.WriteTo(answers, &wcm, peer); err != nil {
			log.Fatal(err)
		}
	}
}

func ExamplePacketConn_tracingIPPacketRoute() {
	// Tracing an IP packet route to www.google.com.

	const host = "www.google.com"
	ips, err := net.LookupIP(host)
	if err != nil {
		log.Fatal(err)
	}
	var dst net.IPAddr
	for _, ip := range ips {
		if ip.To16() != nil && ip.To4() == nil {
			dst.IP = ip
			fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host)
			break
		}
	}
	if dst.IP == nil {
		log.Fatal("no AAAA record found")
	}

	c, err := net.ListenPacket("ip6:58", "::") // ICMP for IPv6
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	if err := p.SetControlMessage(ipv6.FlagHopLimit|ipv6.FlagSrc|ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
		log.Fatal(err)
	}
	wm := icmp.Message{
		Type: ipv6.ICMPTypeEchoRequest, Code: 0,
		Body: &icmp.Echo{
			ID:   os.Getpid() & 0xffff,
			Data: []byte("HELLO-R-U-THERE"),
		},
	}
	var f ipv6.ICMPFilter
	f.SetAll(true)
	f.Accept(ipv6.ICMPTypeTimeExceeded)
	f.Accept(ipv6.ICMPTypeEchoReply)
	if err := p.SetICMPFilter(&f); err != nil {
		log.Fatal(err)
	}

	var wcm ipv6.ControlMessage
	rb := make([]byte, 1500)
	for i := 1; i <= 64; i++ { // up to 64 hops
		wm.Body.(*icmp.Echo).Seq = i
		wb, err := wm.Marshal(nil)
		if err != nil {
			log.Fatal(err)
		}

		// In the real world usually there are several
		// multiple traffic-engineered paths for each hop.
		// You may need to probe a few times to each hop.
		begin := time.Now()
		wcm.HopLimit = i
		if _, err := p.WriteTo(wb, &wcm, &dst); err != nil {
			log.Fatal(err)
		}
		if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
			log.Fatal(err)
		}
		n, rcm, peer, err := p.ReadFrom(rb)
		if err != nil {
			if err, ok := err.(net.Error); ok && err.Timeout() {
				fmt.Printf("%v\t*\n", i)
				continue
			}
			log.Fatal(err)
		}
		rm, err := icmp.ParseMessage(58, rb[:n])
		if err != nil {
			log.Fatal(err)
		}
		rtt := time.Since(begin)

		// In the real world you need to determine whether the
		// received message is yours using ControlMessage.Src,
		// ControlMesage.Dst, icmp.Echo.ID and icmp.Echo.Seq.
		switch rm.Type {
		case ipv6.ICMPTypeTimeExceeded:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
		case ipv6.ICMPTypeEchoReply:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
			return
		}
	}
}

func ExamplePacketConn_advertisingOSPFHello() {
	c, err := net.ListenPacket("ip6:89", "::") // OSPF for IPv6
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv6.NewPacketConn(c)

	en0, err := net.InterfaceByName("en0")
	if err != nil {
		log.Fatal(err)
	}
	allSPFRouters := net.IPAddr{IP: net.ParseIP("ff02::5")}
	if err := p.JoinGroup(en0, &allSPFRouters); err != nil {
		log.Fatal(err)
	}
	defer p.LeaveGroup(en0, &allSPFRouters)

	hello := make([]byte, 24) // fake hello data, you need to implement this
	ospf := make([]byte, 16)  // fake ospf header, you need to implement this
	ospf[0] = 3               // version 3
	ospf[1] = 1               // hello packet
	ospf = append(ospf, hello...)
	if err := p.SetChecksum(true, 12); err != nil {
		log.Fatal(err)
	}

	cm := ipv6.ControlMessage{
		TrafficClass: 0xc0, // DSCP CS6
		HopLimit:     1,
		IfIndex:      en0.Index,
	}
	if _, err := p.WriteTo(ospf, &cm, &allSPFRouters); err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"

	"github.com/spf13/viper"
)

func init() {
	config.New("./")
}

func SendEmail(to string, subject string, text string, html string) {
	mg := mailgun.NewMailgun(
		"something.com",
		viper.GetString("MAILGUN_API_KEY"),
		viper.GetString("MAILGUN_PUBLIC_API_KEY"),
	)

	mg := mailgun.NewMailgun(mydomain, mailgunApiKey, mailgungpublicApiKey)

	message := mg.NewMessage("Pex <no-reply@something.com>", subject, text, to)
	message.SetHtml(html)
	if _, _, err := mg.Send(message); err != nil {
		log.SentryError(err)
	}
}

func main() {
	fmt.Println("RESTful")
}

/* package main - edit this at some point
import "gopkg.in/mailgun/mailgun-go.v1"

message := mailgun.NewMessage(
    "sender@example.com",
    "Fancy subject!",
    "Hello from Mailgun Go!",
    "recipient@example.com")
resp, id, err := mg.Send(message)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("ID: %s Resp: %s\n", id, resp)

*/
<commit_msg>updated codeclimate<commit_after>package main

import (
	"fmt"
)

// Looping forever - For the testing Marathon and Mesos
func main() {

	fmt.Println("Hello everyone")

}

/*
func init() {
	config.New("./")
}

func SendEmail(to string, subject string, text string, html string) {
	mg := mailgun.NewMailgun(
		"something.com",
		viper.GetString("MAILGUN_API_KEY"),
		viper.GetString("MAILGUN_PUBLIC_API_KEY"),
	)

	mg := mailgun.NewMailgun(mydomain, mailgunApiKey, mailgungpublicApiKey)

	message := mg.NewMessage("Pex <no-reply@something.com>", subject, text, to)
	message.SetHtml(html)
	if _, _, err := mg.Send(message); err != nil {
		log.SentryError(err)
	}
}

func main() {
	fmt.Println("RESTful")
}
*/
/* package main - edit this at some point
import "gopkg.in/mailgun/mailgun-go.v1"

message := mailgun.NewMessage(
    "sender@example.com",
    "Fancy subject!",
    "Hello from Mailgun Go!",
    "recipient@example.com")
resp, id, err := mg.Send(message)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("ID: %s Resp: %s\n", id, resp)

*/
<|endoftext|>


<commit_before>// Package errors provides errors that have stack-traces.
package errors

import (
	"bytes"
	"fmt"
	"reflect"
	"runtime"
)

// The maximum number of stackframes on any error.
var MaxStackDepth = 50

// Error is an error with an attached stacktrace. It can be used
// wherever the builtin error interface is expected.
type Error struct {
	Err    error
	stack  []uintptr
	frames []StackFrame
}

// ErrorWithCallers allows passing in error objects that
// also have caller information attached.
type ErrorWithCallers interface {
	Error() string
	Callers() []uintptr
}

// New makes an Error from the given value. If that value is already an
// error then it will be used directly, if not, it will be passed to
// fmt.Errorf("%v"). The skip parameter indicates how far up the stack
// to start the stacktrace. 0 is from the current call, 1 from its caller, etc.
func New(e interface{}, skip int) *Error {
	var err error

	switch e := e.(type) {
	case *Error:
		return e
	case ErrorWithCallers:
		return &Error{
			Err:   e,
			stack: e.Callers(),
		}
	case error:
		err = e
	default:
		err = fmt.Errorf("%v", e)
	}

	stack := make([]uintptr, MaxStackDepth)
	length := runtime.Callers(2+skip, stack[:])
	return &Error{
		Err:   err,
		stack: stack[:length],
	}
}

// Errorf creates a new error with the given message. You can use it
// as a drop-in replacement for fmt.Errorf() to provide descriptive
// errors in return values.
func Errorf(format string, a ...interface{}) *Error {
	return New(fmt.Errorf(format, a...), 1)
}

// Error returns the underlying error's message.
func (err *Error) Error() string {
	return err.Err.Error()
}

// Callers returns the raw stack frames as returned by runtime.Callers()
func (err *Error) Callers() []uintptr {
	return err.stack[:]
}

// Stack returns the callstack formatted the same way that go does
// in runtime/debug.Stack()
func (err *Error) Stack() []byte {
	buf := bytes.Buffer{}

	for _, frame := range err.StackFrames() {
		buf.WriteString(frame.String())
	}

	return buf.Bytes()
}

// StackFrames returns an array of frames containing information about the
// stack.
func (err *Error) StackFrames() []StackFrame {
	if err.frames == nil {
		err.frames = make([]StackFrame, len(err.stack))

		for i, pc := range err.stack {
			err.frames[i] = NewStackFrame(pc)
		}
	}

	return err.frames
}

// TypeName returns the type this error. e.g. *errors.stringError.
func (err *Error) TypeName() string {
	if _, ok := err.Err.(uncaughtPanic); ok {
		return "panic"
	}
	name := reflect.TypeOf(err.Err).String()
	if len(name) > 0 {
		return name
	}
	return "error"
}
<commit_msg>Return default name if empty<commit_after>// Package errors provides errors that have stack-traces.
package errors

import (
	"bytes"
	"fmt"
	"reflect"
	"runtime"
)

// The maximum number of stackframes on any error.
var MaxStackDepth = 50

// Error is an error with an attached stacktrace. It can be used
// wherever the builtin error interface is expected.
type Error struct {
	Err    error
	stack  []uintptr
	frames []StackFrame
}

// ErrorWithCallers allows passing in error objects that
// also have caller information attached.
type ErrorWithCallers interface {
	Error() string
	Callers() []uintptr
}

// New makes an Error from the given value. If that value is already an
// error then it will be used directly, if not, it will be passed to
// fmt.Errorf("%v"). The skip parameter indicates how far up the stack
// to start the stacktrace. 0 is from the current call, 1 from its caller, etc.
func New(e interface{}, skip int) *Error {
	var err error

	switch e := e.(type) {
	case *Error:
		return e
	case ErrorWithCallers:
		return &Error{
			Err:   e,
			stack: e.Callers(),
		}
	case error:
		err = e
	default:
		err = fmt.Errorf("%v", e)
	}

	stack := make([]uintptr, MaxStackDepth)
	length := runtime.Callers(2+skip, stack[:])
	return &Error{
		Err:   err,
		stack: stack[:length],
	}
}

// Errorf creates a new error with the given message. You can use it
// as a drop-in replacement for fmt.Errorf() to provide descriptive
// errors in return values.
func Errorf(format string, a ...interface{}) *Error {
	return New(fmt.Errorf(format, a...), 1)
}

// Error returns the underlying error's message.
func (err *Error) Error() string {
	return err.Err.Error()
}

// Callers returns the raw stack frames as returned by runtime.Callers()
func (err *Error) Callers() []uintptr {
	return err.stack[:]
}

// Stack returns the callstack formatted the same way that go does
// in runtime/debug.Stack()
func (err *Error) Stack() []byte {
	buf := bytes.Buffer{}

	for _, frame := range err.StackFrames() {
		buf.WriteString(frame.String())
	}

	return buf.Bytes()
}

// StackFrames returns an array of frames containing information about the
// stack.
func (err *Error) StackFrames() []StackFrame {
	if err.frames == nil {
		err.frames = make([]StackFrame, len(err.stack))

		for i, pc := range err.stack {
			err.frames[i] = NewStackFrame(pc)
		}
	}

	return err.frames
}

// TypeName returns the type this error. e.g. *errors.stringError.
func (err *Error) TypeName() string {
	if _, ok := err.Err.(uncaughtPanic); ok {
		return "panic"
	}
	if name := reflect.TypeOf(err.Err).String(); len(name) > 0 {
		return name
	}
	return "error"
}
<|endoftext|>


<commit_before>package application

import (
	"cf/api"
	"cf/command_metadata"
	"cf/configuration"
	"cf/requirements"
	"cf/terminal"
	"errors"
	"github.com/codegangsta/cli"
)

type Events struct {
	ui         terminal.UI
	config     configuration.Reader
	appReq     requirements.ApplicationRequirement
	eventsRepo api.AppEventsRepository
}

func NewEvents(ui terminal.UI, config configuration.Reader, eventsRepo api.AppEventsRepository) (cmd *Events) {
	cmd = new(Events)
	cmd.ui = ui
	cmd.config = config
	cmd.eventsRepo = eventsRepo
	return
}

func (command *Events) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "events",
		Description: "Show recent app events",
		Usage:       "CF_NAME events APP",
	}
}

func (cmd *Events) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		err = errors.New("Incorrect Usage")
		cmd.ui.FailWithUsage(c, "events")
		return
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(c.Args()[0])

	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
		cmd.appReq,
	}
	return
}

func (cmd *Events) Run(c *cli.Context) {
	app := cmd.appReq.GetApplication()

	cmd.ui.Say("Getting events for app %s in org %s / space %s as %s...\n",
		terminal.EntityNameColor(app.Name),
		terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
		terminal.EntityNameColor(cmd.config.SpaceFields().Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	table := cmd.ui.Table([]string{"time", "event", "actor", "description"})

	events, apiErr := cmd.eventsRepo.RecentEvents(app.Guid, 50)
	if apiErr != nil {
		cmd.ui.Failed("Failed fetching events.\n%s", apiErr.Error())
		return
	}

	for _, event := range events {
		table.Print([][]string{{
			event.Timestamp.Local().Format("2006-01-02T15:04:05.00-0700"),
			event.Name,
			event.ActorName,
			event.Description,
		}})
	}

	if len(events) == 0 {
		cmd.ui.Say("No events for app %s", terminal.EntityNameColor(app.Name))
		return
	}
}
<commit_msg>Use table interface correctly<commit_after>package application

import (
	"cf/api"
	"cf/command_metadata"
	"cf/configuration"
	"cf/requirements"
	"cf/terminal"
	"errors"
	"github.com/codegangsta/cli"
)

type Events struct {
	ui         terminal.UI
	config     configuration.Reader
	appReq     requirements.ApplicationRequirement
	eventsRepo api.AppEventsRepository
}

func NewEvents(ui terminal.UI, config configuration.Reader, eventsRepo api.AppEventsRepository) (cmd *Events) {
	cmd = new(Events)
	cmd.ui = ui
	cmd.config = config
	cmd.eventsRepo = eventsRepo
	return
}

func (command *Events) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "events",
		Description: "Show recent app events",
		Usage:       "CF_NAME events APP",
	}
}

func (cmd *Events) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		err = errors.New("Incorrect Usage")
		cmd.ui.FailWithUsage(c, "events")
		return
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(c.Args()[0])

	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedSpaceRequirement(),
		cmd.appReq,
	}
	return
}

func (cmd *Events) Run(c *cli.Context) {
	app := cmd.appReq.GetApplication()

	cmd.ui.Say("Getting events for app %s in org %s / space %s as %s...\n",
		terminal.EntityNameColor(app.Name),
		terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
		terminal.EntityNameColor(cmd.config.SpaceFields().Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	table := cmd.ui.Table([]string{"time", "event", "actor", "description"})

	events, apiErr := cmd.eventsRepo.RecentEvents(app.Guid, 50)
	if apiErr != nil {
		cmd.ui.Failed("Failed fetching events.\n%s", apiErr.Error())
		return
	}

	for _, event := range events {
		table.Add([]string{
			event.Timestamp.Local().Format("2006-01-02T15:04:05.00-0700"),
			event.Name,
			event.ActorName,
			event.Description,
		})
	}

	table.Print([][]string{})

	if len(events) == 0 {
		cmd.ui.Say("No events for app %s", terminal.EntityNameColor(app.Name))
		return
	}
}
<|endoftext|>


<commit_before>package generation

import (
	"math"
)

type Source interface {
	At2d(x, y float64) float64
	MeanMagnitude() float64
}

type Const float64

func (gen Const) At2d(x, y float64) float64 {
	return float64(gen)
}

func (gen Const) MeanMagnitude() float64 {
	return float64(gen)
}

type Offset struct {
	Dx, Dy float64
	Source Source
}

func (gen *Offset) At2d(x, y float64) float64 {
	return gen.Source.At2d(x+gen.Dx, y+gen.Dy)
}

func (gen *Offset) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude()
}

type Turbulence struct {
	Dx, Dy Source
	Factor float64
	Source Source
}

func (gen *Turbulence) At2d(x, y float64) float64 {
	dx := gen.Dx.At2d(x, y) * gen.Factor
	dy := gen.Dy.At2d(x, y) * gen.Factor
	return gen.Source.At2d(x+dx, y+dy)
}

func (gen *Turbulence) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude()
}

type Scale struct {
	Wavelength float64
	Amplitude  float64
	Source     Source
}

func (gen *Scale) At2d(x, y float64) float64 {
	return gen.Source.At2d(x/gen.Wavelength, y/gen.Wavelength) * gen.Amplitude
}

func (gen *Scale) MeanMagnitude() float64 {
	return gen.Amplitude * gen.Source.MeanMagnitude()
}

type Pow struct {
	Source Source
	Power  Source
}

func (gen *Pow) At2d(x, y float64) float64 {
	v := gen.Source.At2d(x, y)
	power := gen.Power.At2d(x, y)
	if v < 0 {
		// Retain sign, and don't break on negatives raised to fractional powers.
		// Not strictly a power function, but serves the purpose.
		return -math.Pow(-v, power)
	}
	return math.Pow(v, power)
}

func (gen *Pow) MeanMagnitude() float64 {
	// TODO Remove all MeanMagnitude.
	return 0.5
}

type Mult struct {
	A, B Source
}

func (gen *Mult) At2d(x, y float64) float64 {
	return gen.A.At2d(x, y) * gen.B.At2d(x, y)
}

func (gen *Mult) MeanMagnitude() float64 {
	return gen.A.MeanMagnitude() * gen.B.MeanMagnitude()
}

type Add struct {
	Source Source
	Value  float64
}

func (gen *Add) At2d(x, y float64) float64 {
	return gen.Source.At2d(x, y) + gen.Value
}

func (gen *Add) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude() + gen.Value
}

type SumStack struct {
	Inputs []Source
}

func NewSumStack(inputs []Source) *SumStack {
	return &SumStack{
		Inputs: inputs,
	}
}

func (gen *SumStack) At2d(x, y float64) float64 {
	var accum float64
	for _, input := range gen.Inputs {
		accum += input.At2d(x, y)
	}
	return accum
}

func (gen *SumStack) MeanMagnitude() float64 {
	var meanAccum float64
	for _, input := range gen.Inputs {
		meanAccum += input.MeanMagnitude()
	}
	return meanAccum
}
<commit_msg>Fixing the name of an interface in chunkymonkey/generation.<commit_after>package generation

import (
	"math"
)

type ISource interface {
	At2d(x, y float64) float64
	MeanMagnitude() float64
}

type Const float64

func (gen Const) At2d(x, y float64) float64 {
	return float64(gen)
}

func (gen Const) MeanMagnitude() float64 {
	return float64(gen)
}

type Offset struct {
	Dx, Dy float64
	Source Source
}

func (gen *Offset) At2d(x, y float64) float64 {
	return gen.Source.At2d(x+gen.Dx, y+gen.Dy)
}

func (gen *Offset) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude()
}

type Turbulence struct {
	Dx, Dy Source
	Factor float64
	Source Source
}

func (gen *Turbulence) At2d(x, y float64) float64 {
	dx := gen.Dx.At2d(x, y) * gen.Factor
	dy := gen.Dy.At2d(x, y) * gen.Factor
	return gen.Source.At2d(x+dx, y+dy)
}

func (gen *Turbulence) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude()
}

type Scale struct {
	Wavelength float64
	Amplitude  float64
	Source     Source
}

func (gen *Scale) At2d(x, y float64) float64 {
	return gen.Source.At2d(x/gen.Wavelength, y/gen.Wavelength) * gen.Amplitude
}

func (gen *Scale) MeanMagnitude() float64 {
	return gen.Amplitude * gen.Source.MeanMagnitude()
}

type Pow struct {
	Source Source
	Power  Source
}

func (gen *Pow) At2d(x, y float64) float64 {
	v := gen.Source.At2d(x, y)
	power := gen.Power.At2d(x, y)
	if v < 0 {
		// Retain sign, and don't break on negatives raised to fractional powers.
		// Not strictly a power function, but serves the purpose.
		return -math.Pow(-v, power)
	}
	return math.Pow(v, power)
}

func (gen *Pow) MeanMagnitude() float64 {
	// TODO Remove all MeanMagnitude.
	return 0.5
}

type Mult struct {
	A, B Source
}

func (gen *Mult) At2d(x, y float64) float64 {
	return gen.A.At2d(x, y) * gen.B.At2d(x, y)
}

func (gen *Mult) MeanMagnitude() float64 {
	return gen.A.MeanMagnitude() * gen.B.MeanMagnitude()
}

type Add struct {
	Source Source
	Value  float64
}

func (gen *Add) At2d(x, y float64) float64 {
	return gen.Source.At2d(x, y) + gen.Value
}

func (gen *Add) MeanMagnitude() float64 {
	return gen.Source.MeanMagnitude() + gen.Value
}

type SumStack struct {
	Inputs []Source
}

func NewSumStack(inputs []Source) *SumStack {
	return &SumStack{
		Inputs: inputs,
	}
}

func (gen *SumStack) At2d(x, y float64) float64 {
	var accum float64
	for _, input := range gen.Inputs {
		accum += input.At2d(x, y)
	}
	return accum
}

func (gen *SumStack) MeanMagnitude() float64 {
	var meanAccum float64
	for _, input := range gen.Inputs {
		meanAccum += input.MeanMagnitude()
	}
	return meanAccum
}
<|endoftext|>


<commit_before>// Copyright ©2015 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gen

import (
	"fmt"
	"math"
	"math/rand"
	"sort"

	"gonum.org/v1/gonum/graph"
	"gonum.org/v1/gonum/graph/internal/ordered"
	"gonum.org/v1/gonum/graph/simple"
)

// UndirectedMutator is an undirected graph builder that can remove edges.
type UndirectedMutator interface {
	graph.UndirectedBuilder
	graph.EdgeRemover
}

// Duplication constructs a graph in the destination, dst, of order n. New nodes
// are created by duplicating an existing node and all its edges. Each new edge is
// deleted with probability delta. Additional edges are added between the new node
// and existing nodes with probability alpha/|V|. An exception to this addition
// rule is made for the parent node when sigma is not NaN; in this case an edge is
// created with probability sigma. With the exception of the sigma parameter, this
// corresponds to the completely correlated case in doi:10.1016/S0022-5193(03)00028-6.
// If src is not nil it is used as the random source, otherwise rand.Float64 is used.
func Duplication(dst UndirectedMutator, n int, delta, alpha, sigma float64, src *rand.Rand) error {
	// As described in doi:10.1016/S0022-5193(03)00028-6 but
	// also clarified in doi:10.1186/gb-2007-8-4-r51.

	if delta < 0 || delta > 1 {
		return fmt.Errorf("gen: bad delta: delta=%v", delta)
	}
	if alpha <= 0 || alpha > 1 {
		return fmt.Errorf("gen: bad alpha: alpha=%v", alpha)
	}
	if sigma < 0 || sigma > 1 {
		return fmt.Errorf("gen: bad sigma: sigma=%v", sigma)
	}

	var (
		rnd  func() float64
		rndN func(int) int
	)
	if src == nil {
		rnd = rand.Float64
		rndN = rand.Intn
	} else {
		rnd = src.Float64
		rndN = src.Intn
	}

	nodes := dst.Nodes()
	sort.Sort(ordered.ByID(nodes))
	if len(nodes) == 0 {
		n--
		dst.AddNode(simple.Node(0))
		nodes = append(nodes, simple.Node(0))
	}
	for i := 0; i < n; i++ {
		u := nodes[rndN(len(nodes))]
		d := simple.Node(dst.NewNodeID())

		// Add the duplicate node.
		dst.AddNode(d)

		// Loop until we have connectivity
		// into the rest of the graph.
		for {
			// Add edges to parent's neigbours.
			to := dst.From(u)
			sort.Sort(ordered.ByID(to))
			for _, v := range to {
				if rnd() < delta || dst.HasEdgeBetween(v, d) {
					continue
				}
				if v.ID() < d.ID() {
					dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
				} else {
					dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
				}
			}

			// Add edges to old nodes.
			scaledAlpha := alpha / float64(len(nodes))
			for _, v := range nodes {
				switch v.ID() {
				case u.ID():
					if !math.IsNaN(sigma) {
						if i == 0 || rnd() < sigma {
							if v.ID() < d.ID() {
								dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
							} else {
								dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
							}
						}
						continue
					}
					fallthrough
				default:
					if rnd() < scaledAlpha && !dst.HasEdgeBetween(v, d) {
						if v.ID() < d.ID() {
							dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
						} else {
							dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
						}
					}
				}
			}

			if len(dst.From(d)) != 0 {
				break
			}
		}

		nodes = append(nodes, d)
	}

	return nil
}
<commit_msg>graph/graphs/gen: allow dst to determine first ID number<commit_after>// Copyright ©2015 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gen

import (
	"fmt"
	"math"
	"math/rand"
	"sort"

	"gonum.org/v1/gonum/graph"
	"gonum.org/v1/gonum/graph/internal/ordered"
	"gonum.org/v1/gonum/graph/simple"
)

// UndirectedMutator is an undirected graph builder that can remove edges.
type UndirectedMutator interface {
	graph.UndirectedBuilder
	graph.EdgeRemover
}

// Duplication constructs a graph in the destination, dst, of order n. New nodes
// are created by duplicating an existing node and all its edges. Each new edge is
// deleted with probability delta. Additional edges are added between the new node
// and existing nodes with probability alpha/|V|. An exception to this addition
// rule is made for the parent node when sigma is not NaN; in this case an edge is
// created with probability sigma. With the exception of the sigma parameter, this
// corresponds to the completely correlated case in doi:10.1016/S0022-5193(03)00028-6.
// If src is not nil it is used as the random source, otherwise rand.Float64 is used.
func Duplication(dst UndirectedMutator, n int, delta, alpha, sigma float64, src *rand.Rand) error {
	// As described in doi:10.1016/S0022-5193(03)00028-6 but
	// also clarified in doi:10.1186/gb-2007-8-4-r51.

	if delta < 0 || delta > 1 {
		return fmt.Errorf("gen: bad delta: delta=%v", delta)
	}
	if alpha <= 0 || alpha > 1 {
		return fmt.Errorf("gen: bad alpha: alpha=%v", alpha)
	}
	if sigma < 0 || sigma > 1 {
		return fmt.Errorf("gen: bad sigma: sigma=%v", sigma)
	}

	var (
		rnd  func() float64
		rndN func(int) int
	)
	if src == nil {
		rnd = rand.Float64
		rndN = rand.Intn
	} else {
		rnd = src.Float64
		rndN = src.Intn
	}

	nodes := dst.Nodes()
	sort.Sort(ordered.ByID(nodes))
	if len(nodes) == 0 {
		n--
		u := simple.Node(dst.NewNodeID())
		dst.AddNode(u)
		nodes = append(nodes, u)
	}
	for i := 0; i < n; i++ {
		u := nodes[rndN(len(nodes))]
		d := simple.Node(dst.NewNodeID())

		// Add the duplicate node.
		dst.AddNode(d)

		// Loop until we have connectivity
		// into the rest of the graph.
		for {
			// Add edges to parent's neigbours.
			to := dst.From(u)
			sort.Sort(ordered.ByID(to))
			for _, v := range to {
				if rnd() < delta || dst.HasEdgeBetween(v, d) {
					continue
				}
				if v.ID() < d.ID() {
					dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
				} else {
					dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
				}
			}

			// Add edges to old nodes.
			scaledAlpha := alpha / float64(len(nodes))
			for _, v := range nodes {
				switch v.ID() {
				case u.ID():
					if !math.IsNaN(sigma) {
						if i == 0 || rnd() < sigma {
							if v.ID() < d.ID() {
								dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
							} else {
								dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
							}
						}
						continue
					}
					fallthrough
				default:
					if rnd() < scaledAlpha && !dst.HasEdgeBetween(v, d) {
						if v.ID() < d.ID() {
							dst.SetEdge(simple.Edge{F: v, T: d, W: 1})
						} else {
							dst.SetEdge(simple.Edge{F: d, T: v, W: 1})
						}
					}
				}
			}

			if len(dst.From(d)) != 0 {
				break
			}
		}

		nodes = append(nodes, d)
	}

	return nil
}
<|endoftext|>