<commit_before>package nodesyncer

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"

	"github.com/rancher/norman/types/convert"
	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/kubectl"
	nodehelper "github.com/rancher/rancher/pkg/node"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

const (
	drainTokenPrefix = "drain-node-"
	description      = "token for drain"
)

var nodeMapLock = sync.Mutex{}
var toIgnoreErrs = []string{"--ignore-daemonsets", "--delete-local-data", "--force", "did not complete within", "global timeout reached"}

func (m *nodesSyncer) syncCordonFields(key string, obj *v3.Node) (runtime.Object, error) {
	if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable != "true" && obj.Spec.DesiredNodeUnschedulable != "false" {
		return nil, nil
	}

	node, err := nodehelper.GetNodeForMachine(obj, m.nodeLister)
	if err != nil || node == nil || node.DeletionTimestamp != nil {
		return nil, err
	}
	desiredValue := convert.ToBool(obj.Spec.DesiredNodeUnschedulable)
	if node.Spec.Unschedulable != desiredValue {
		toUpdate := node.DeepCopy()
		toUpdate.Spec.Unschedulable = desiredValue
		if _, err = m.nodeClient.Update(toUpdate); err != nil {
			return nil, err
		}
	}

	logrus.Debugf("cordonNode: [%v] desired %v current %v", obj.Name, desiredValue, obj.Spec.InternalNodeSpec.Unschedulable)
	// reset only after Unschedulable reflects correctly
	if obj.Spec.InternalNodeSpec.Unschedulable == desiredValue {
		nodeCopy := obj.DeepCopy()
		nodeCopy.Spec.DesiredNodeUnschedulable = ""

		if !obj.Spec.InternalNodeSpec.Unschedulable {
			removeDrainCondition(nodeCopy)
		}

		obj, err = m.machines.Update(nodeCopy)
	}

	return obj, err
}

func (d *nodeDrain) drainNode(key string, obj *v3.Node) (runtime.Object, error) {
	if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable != "drain" && obj.Spec.DesiredNodeUnschedulable != "stopDrain" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable == "drain" {
		nodeMapLock.Lock()
		if _, ok := d.nodesToContext[obj.Name]; ok {
			nodeMapLock.Unlock()
			return nil, nil
		}
		nodeMapLock.Unlock()

		node, err := nodehelper.GetNodeForMachine(obj, d.nodeLister)
		if err != nil {
			return nil, err
		}
		if node == nil {
			return nil, fmt.Errorf("nodeDrain: error finding node [%s]", obj.Spec.RequestedHostname)
		}
		ctx, cancel := context.WithCancel(d.ctx)

		nodeMapLock.Lock()
		d.nodesToContext[obj.Name] = cancel
		nodeMapLock.Unlock()

		go d.drain(ctx, obj, node.Name, cancel)

	} else if obj.Spec.DesiredNodeUnschedulable == "stopDrain" {
		nodeMapLock.Lock()
		cancelFunc, ok := d.nodesToContext[obj.Name]
		nodeMapLock.Unlock()

		if ok {
			cancelFunc()
		}
		return nil, d.resetDesiredNodeUnschedulable(obj)
	}
	return nil, nil
}

func (d *nodeDrain) updateNode(node *v3.Node, updateFunc func(node *v3.Node, originalErr error, kubeErr error), originalErr error, kubeErr error) (*v3.Node, error) {
	updatedObj, err := d.machines.Update(node)
	if err != nil && errors.IsConflict(err) {
		// retrying twelve times, if conflict error still exists, give up
		for i := 0; i < 12; i++ {
			latestObj, err := d.machines.Get(node.Name, metav1.GetOptions{})
			if err != nil {
				logrus.Warnf("nodeDrain: error fetching node %s", node.Spec.RequestedHostname)
				return nil, err
			}
			updateFunc(latestObj, originalErr, kubeErr)
			updatedObj, err = d.machines.Update(latestObj)
			if err != nil && errors.IsConflict(err) {
				logrus.Debugf("nodeDrain: conflict error, will retry again %s", node.Spec.RequestedHostname)
				time.Sleep(5 * time.Millisecond)
				continue
			}
			return updatedObj, err
		}
	}
	return updatedObj, err
}

func (d *nodeDrain) drain(ctx context.Context, obj *v3.Node, nodeName string, cancel context.CancelFunc) {
	defer deleteFromContextMap(d.nodesToContext, obj.Name)

	for {
		select {
		case <-ctx.Done():
			return
		default:
		}

		stopped := false
		updatedObj, err := v32.NodeConditionDrained.DoUntilTrue(obj, func() (runtime.Object, error) {
			kubeConfig, err := d.getKubeConfig()
			if err != nil {
				logrus.Errorf("nodeDrain: error getting kubeConfig for node %s", obj.Name)
				return obj, fmt.Errorf("error getting kubeConfig for node %s", obj.Name)
			}
			nodeCopy := obj.DeepCopy()
			setConditionDraining(nodeCopy, nil, nil)
			nodeObj, err := d.updateNode(nodeCopy, setConditionDraining, nil, nil)
			if err != nil {
				return obj, err
			}
			logrus.Infof("Draining node %s in %s with flags %v", nodeName, obj.Namespace,
				strings.Join(getFlags(nodeObj.Spec.NodeDrainInput), " "))
			_, msg, err := kubectl.Drain(ctx, kubeConfig, nodeName, getFlags(nodeObj.Spec.NodeDrainInput))
			if err != nil {
				if ctx.Err() == context.Canceled {
					stopped = true
					logrus.Infof(fmt.Sprintf("Stopped draining %s in %s", nodeName, obj.Namespace))
					return nodeObj, nil
				}
				errMsg := filterErrorMsg(msg, nodeName)
				return nodeObj, fmt.Errorf("%s", errMsg)
			}
			return nodeObj, nil
		})
		kubeErr := err
		if err != nil {
			ignore, timeoutErr := ignoreErr(err.Error())
			if ignore {
				if timeoutErr {
					err = fmt.Errorf(fmt.Sprintf("Drain failed: drain did not complete within %vs",
						obj.Spec.NodeDrainInput.Timeout))
				} else {
					// log before ignoring
					logrus.Errorf("nodeDrain: kubectl error ignore draining node [%s] in cluster [%s]: %v", nodeName,
						d.clusterName, kubeErr)
				}
				kubeErr = nil
			}
		}
		if !stopped {
			nodeCopy := updatedObj.(*v3.Node).DeepCopy()
			setConditionComplete(nodeCopy, err, kubeErr)
			_, updateErr := d.updateNode(nodeCopy, setConditionComplete, err, kubeErr)
			if kubeErr != nil || updateErr != nil {
				if kubeErr != nil {
					logrus.Errorf("nodeDrain: kubectl error draining node [%s] in cluster [%s]: %v", nodeName,
						d.clusterName, kubeErr)
				} else {
					logrus.Errorf("nodeDrain: condition update failure for node [%s] in cluster [%s]: %v",
						nodeName, d.clusterName, updateErr)
				}
				d.machines.Controller().Enqueue("", fmt.Sprintf("%s/%s", d.clusterName, obj.Name))
			}
			cancel()
		}
	}
}

func (d *nodeDrain) resetDesiredNodeUnschedulable(obj *v3.Node) error {
	nodeCopy := obj.DeepCopy()
	removeDrainCondition(nodeCopy)
	nodeCopy.Spec.DesiredNodeUnschedulable = ""
	if _, err := d.machines.Update(nodeCopy); err != nil {
		return err
	}
	return nil
}

func (d *nodeDrain) getKubeConfig() (*clientcmdapi.Config, error) {
	cluster, err := d.clusterLister.Get("", d.clusterName)
	if err != nil {
		return nil, err
	}
	user, err := d.systemAccountManager.GetSystemUser(cluster.Name)
	if err != nil {
		return nil, err
	}
	token, err := d.userManager.EnsureToken(drainTokenPrefix+user.Name, description, "drain-node", user.Name)
	if err != nil {
		return nil, err
	}
	kubeConfig := d.kubeConfigGetter.KubeConfig(d.clusterName, token)
	for k := range kubeConfig.Clusters {
		kubeConfig.Clusters[k].InsecureSkipTLSVerify = true
	}
	return kubeConfig, nil
}

func getFlags(input *v32.NodeDrainInput) []string {
	return []string{
		fmt.Sprintf("--delete-local-data=%v", input.DeleteLocalData),
		fmt.Sprintf("--force=%v", input.Force),
		fmt.Sprintf("--grace-period=%v", input.GracePeriod),
		fmt.Sprintf("--ignore-daemonsets=%v", *input.IgnoreDaemonSets),
		fmt.Sprintf("--timeout=%s", convert.ToString(input.Timeout)+"s")}
}

func filterErrorMsg(msg string, nodeName string) string {
	var upd []string
	lines := strings.Split(msg, "\n")
	for _, line := range lines[1:] {
		if strings.HasPrefix(line, "WARNING") || strings.HasPrefix(line, nodeName) {
			continue
		}
		if strings.Contains(line, "aborting") {
			continue
		}
		if strings.HasPrefix(line, "There are pending nodes ") {
			// for only one node in our case
			continue
		}
		if strings.HasPrefix(line, "There are pending pods ") {
			// already considered error
			continue
		}
		if strings.HasPrefix(line, "error") && strings.Contains(line, "unable to drain node") {
			// actual reason at end
			continue
		}
		if strings.HasPrefix(line, "pod") && strings.Contains(line, "evicted") {
			// evicted successfully
			continue
		}
		upd = append(upd, line)
	}
	return strings.Join(upd, "\n")
}

func removeDrainCondition(obj *v3.Node) {
	exists := false
	for _, condition := range obj.Status.Conditions {
		if condition.Type == "Drained" {
			exists = true
			break
		}
	}
	if exists {
		var conditions []v32.NodeCondition
		for _, condition := range obj.Status.Conditions {
			if condition.Type == "Drained" {
				continue
			}
			conditions = append(conditions, condition)
		}
		obj.Status.Conditions = conditions
	}
}

func deleteFromContextMap(data map[string]context.CancelFunc, id string) {
	nodeMapLock.Lock()
	delete(data, id)
	nodeMapLock.Unlock()
}

func ignoreErr(msg string) (bool, bool) {
	for _, val := range toIgnoreErrs {
		if strings.Contains(msg, val) {
			// check if timeout error
			if !strings.HasPrefix(val, "--") {
				return true, true
			}
			return true, false
		}
	}
	return false, false
}

func setConditionDraining(node *v3.Node, err error, kubeErr error) {
	v32.NodeConditionDrained.Unknown(node)
	v32.NodeConditionDrained.Reason(node, "")
	v32.NodeConditionDrained.Message(node, "")
}

func setConditionComplete(node *v3.Node, err error, kubeErr error) {
	if err == nil {
		v32.NodeConditionDrained.True(node)
	} else {
		v32.NodeConditionDrained.False(node)
		v32.NodeConditionDrained.ReasonAndMessageFromError(node, err)
	}
	if kubeErr == nil {
		node.Spec.DesiredNodeUnschedulable = ""
	}
}
<commit_msg>set default value for ignoreDaemonSets<commit_after>package nodesyncer

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"

	"github.com/rancher/norman/types/convert"
	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/kubectl"
	nodehelper "github.com/rancher/rancher/pkg/node"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

const (
	drainTokenPrefix = "drain-node-"
	description      = "token for drain"
)

var nodeMapLock = sync.Mutex{}
var toIgnoreErrs = []string{"--ignore-daemonsets", "--delete-local-data", "--force", "did not complete within", "global timeout reached"}

func (m *nodesSyncer) syncCordonFields(key string, obj *v3.Node) (runtime.Object, error) {
	if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable != "true" && obj.Spec.DesiredNodeUnschedulable != "false" {
		return nil, nil
	}

	node, err := nodehelper.GetNodeForMachine(obj, m.nodeLister)
	if err != nil || node == nil || node.DeletionTimestamp != nil {
		return nil, err
	}
	desiredValue := convert.ToBool(obj.Spec.DesiredNodeUnschedulable)
	if node.Spec.Unschedulable != desiredValue {
		toUpdate := node.DeepCopy()
		toUpdate.Spec.Unschedulable = desiredValue
		if _, err = m.nodeClient.Update(toUpdate); err != nil {
			return nil, err
		}
	}

	logrus.Debugf("cordonNode: [%v] desired %v current %v", obj.Name, desiredValue, obj.Spec.InternalNodeSpec.Unschedulable)
	// reset only after Unschedulable reflects correctly
	if obj.Spec.InternalNodeSpec.Unschedulable == desiredValue {
		nodeCopy := obj.DeepCopy()
		nodeCopy.Spec.DesiredNodeUnschedulable = ""

		if !obj.Spec.InternalNodeSpec.Unschedulable {
			removeDrainCondition(nodeCopy)
		}

		obj, err = m.machines.Update(nodeCopy)
	}

	return obj, err
}

func (d *nodeDrain) drainNode(key string, obj *v3.Node) (runtime.Object, error) {
	if obj == nil || obj.DeletionTimestamp != nil || obj.Spec.DesiredNodeUnschedulable == "" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable != "drain" && obj.Spec.DesiredNodeUnschedulable != "stopDrain" {
		return nil, nil
	}

	if obj.Spec.DesiredNodeUnschedulable == "drain" {
		nodeMapLock.Lock()
		if _, ok := d.nodesToContext[obj.Name]; ok {
			nodeMapLock.Unlock()
			return nil, nil
		}
		nodeMapLock.Unlock()

		node, err := nodehelper.GetNodeForMachine(obj, d.nodeLister)
		if err != nil {
			return nil, err
		}
		if node == nil {
			return nil, fmt.Errorf("nodeDrain: error finding node [%s]", obj.Spec.RequestedHostname)
		}
		ctx, cancel := context.WithCancel(d.ctx)

		nodeMapLock.Lock()
		d.nodesToContext[obj.Name] = cancel
		nodeMapLock.Unlock()

		go d.drain(ctx, obj, node.Name, cancel)

	} else if obj.Spec.DesiredNodeUnschedulable == "stopDrain" {
		nodeMapLock.Lock()
		cancelFunc, ok := d.nodesToContext[obj.Name]
		nodeMapLock.Unlock()

		if ok {
			cancelFunc()
		}
		return nil, d.resetDesiredNodeUnschedulable(obj)
	}
	return nil, nil
}

func (d *nodeDrain) updateNode(node *v3.Node, updateFunc func(node *v3.Node, originalErr error, kubeErr error), originalErr error, kubeErr error) (*v3.Node, error) {
	updatedObj, err := d.machines.Update(node)
	if err != nil && errors.IsConflict(err) {
		// retrying twelve times, if conflict error still exists, give up
		for i := 0; i < 12; i++ {
			latestObj, err := d.machines.Get(node.Name, metav1.GetOptions{})
			if err != nil {
				logrus.Warnf("nodeDrain: error fetching node %s", node.Spec.RequestedHostname)
				return nil, err
			}
			updateFunc(latestObj, originalErr, kubeErr)
			updatedObj, err = d.machines.Update(latestObj)
			if err != nil && errors.IsConflict(err) {
				logrus.Debugf("nodeDrain: conflict error, will retry again %s", node.Spec.RequestedHostname)
				time.Sleep(5 * time.Millisecond)
				continue
			}
			return updatedObj, err
		}
	}
	return updatedObj, err
}

func (d *nodeDrain) drain(ctx context.Context, obj *v3.Node, nodeName string, cancel context.CancelFunc) {
	defer deleteFromContextMap(d.nodesToContext, obj.Name)

	for {
		select {
		case <-ctx.Done():
			return
		default:
		}

		stopped := false
		updatedObj, err := v32.NodeConditionDrained.DoUntilTrue(obj, func() (runtime.Object, error) {
			kubeConfig, err := d.getKubeConfig()
			if err != nil {
				logrus.Errorf("nodeDrain: error getting kubeConfig for node %s", obj.Name)
				return obj, fmt.Errorf("error getting kubeConfig for node %s", obj.Name)
			}
			nodeCopy := obj.DeepCopy()
			setConditionDraining(nodeCopy, nil, nil)
			nodeObj, err := d.updateNode(nodeCopy, setConditionDraining, nil, nil)
			if err != nil {
				return obj, err
			}
			logrus.Infof("Draining node %s in %s with flags %v", nodeName, obj.Namespace,
				strings.Join(getFlags(nodeObj.Spec.NodeDrainInput), " "))
			_, msg, err := kubectl.Drain(ctx, kubeConfig, nodeName, getFlags(nodeObj.Spec.NodeDrainInput))
			if err != nil {
				if ctx.Err() == context.Canceled {
					stopped = true
					logrus.Infof(fmt.Sprintf("Stopped draining %s in %s", nodeName, obj.Namespace))
					return nodeObj, nil
				}
				errMsg := filterErrorMsg(msg, nodeName)
				return nodeObj, fmt.Errorf("%s", errMsg)
			}
			return nodeObj, nil
		})
		kubeErr := err
		if err != nil {
			ignore, timeoutErr := ignoreErr(err.Error())
			if ignore {
				if timeoutErr {
					err = fmt.Errorf(fmt.Sprintf("Drain failed: drain did not complete within %vs",
						obj.Spec.NodeDrainInput.Timeout))
				} else {
					// log before ignoring
					logrus.Errorf("nodeDrain: kubectl error ignore draining node [%s] in cluster [%s]: %v", nodeName,
						d.clusterName, kubeErr)
				}
				kubeErr = nil
			}
		}
		if !stopped {
			nodeCopy := updatedObj.(*v3.Node).DeepCopy()
			setConditionComplete(nodeCopy, err, kubeErr)
			_, updateErr := d.updateNode(nodeCopy, setConditionComplete, err, kubeErr)
			if kubeErr != nil || updateErr != nil {
				if kubeErr != nil {
					logrus.Errorf("nodeDrain: kubectl error draining node [%s] in cluster [%s]: %v", nodeName,
						d.clusterName, kubeErr)
				} else {
					logrus.Errorf("nodeDrain: condition update failure for node [%s] in cluster [%s]: %v",
						nodeName, d.clusterName, updateErr)
				}
				d.machines.Controller().Enqueue("", fmt.Sprintf("%s/%s", d.clusterName, obj.Name))
			}
			cancel()
		}
	}
}

func (d *nodeDrain) resetDesiredNodeUnschedulable(obj *v3.Node) error {
	nodeCopy := obj.DeepCopy()
	removeDrainCondition(nodeCopy)
	nodeCopy.Spec.DesiredNodeUnschedulable = ""
	if _, err := d.machines.Update(nodeCopy); err != nil {
		return err
	}
	return nil
}

func (d *nodeDrain) getKubeConfig() (*clientcmdapi.Config, error) {
	cluster, err := d.clusterLister.Get("", d.clusterName)
	if err != nil {
		return nil, err
	}
	user, err := d.systemAccountManager.GetSystemUser(cluster.Name)
	if err != nil {
		return nil, err
	}
	token, err := d.userManager.EnsureToken(drainTokenPrefix+user.Name, description, "drain-node", user.Name)
	if err != nil {
		return nil, err
	}
	kubeConfig := d.kubeConfigGetter.KubeConfig(d.clusterName, token)
	for k := range kubeConfig.Clusters {
		kubeConfig.Clusters[k].InsecureSkipTLSVerify = true
	}
	return kubeConfig, nil
}

func getFlags(input *v32.NodeDrainInput) []string {
	var ignoreDaemonSets bool
	if input.IgnoreDaemonSets == nil {
		ignoreDaemonSets = true
	} else {
		ignoreDaemonSets = *input.IgnoreDaemonSets
	}
	return []string{
		fmt.Sprintf("--delete-local-data=%v", input.DeleteLocalData),
		fmt.Sprintf("--force=%v", input.Force),
		fmt.Sprintf("--grace-period=%v", input.GracePeriod),
		fmt.Sprintf("--ignore-daemonsets=%v", ignoreDaemonSets),
		fmt.Sprintf("--timeout=%s", convert.ToString(input.Timeout)+"s")}
}

func filterErrorMsg(msg string, nodeName string) string {
	var upd []string
	lines := strings.Split(msg, "\n")
	for _, line := range lines[1:] {
		if strings.HasPrefix(line, "WARNING") || strings.HasPrefix(line, nodeName) {
			continue
		}
		if strings.Contains(line, "aborting") {
			continue
		}
		if strings.HasPrefix(line, "There are pending nodes ") {
			// for only one node in our case
			continue
		}
		if strings.HasPrefix(line, "There are pending pods ") {
			// already considered error
			continue
		}
		if strings.HasPrefix(line, "error") && strings.Contains(line, "unable to drain node") {
			// actual reason at end
			continue
		}
		if strings.HasPrefix(line, "pod") && strings.Contains(line, "evicted") {
			// evicted successfully
			continue
		}
		upd = append(upd, line)
	}
	return strings.Join(upd, "\n")
}

func removeDrainCondition(obj *v3.Node) {
	exists := false
	for _, condition := range obj.Status.Conditions {
		if condition.Type == "Drained" {
			exists = true
			break
		}
	}
	if exists {
		var conditions []v32.NodeCondition
		for _, condition := range obj.Status.Conditions {
			if condition.Type == "Drained" {
				continue
			}
			conditions = append(conditions, condition)
		}
		obj.Status.Conditions = conditions
	}
}

func deleteFromContextMap(data map[string]context.CancelFunc, id string) {
	nodeMapLock.Lock()
	delete(data, id)
	nodeMapLock.Unlock()
}

func ignoreErr(msg string) (bool, bool) {
	for _, val := range toIgnoreErrs {
		if strings.Contains(msg, val) {
			// check if timeout error
			if !strings.HasPrefix(val, "--") {
				return true, true
			}
			return true, false
		}
	}
	return false, false
}

func setConditionDraining(node *v3.Node, err error, kubeErr error) {
	v32.NodeConditionDrained.Unknown(node)
	v32.NodeConditionDrained.Reason(node, "")
	v32.NodeConditionDrained.Message(node, "")
}

func setConditionComplete(node *v3.Node, err error, kubeErr error) {
	if err == nil {
		v32.NodeConditionDrained.True(node)
	} else {
		v32.NodeConditionDrained.False(node)
		v32.NodeConditionDrained.ReasonAndMessageFromError(node, err)
	}
	if kubeErr == nil {
		node.Spec.DesiredNodeUnschedulable = ""
	}
}
<|endoftext|>


<commit_before>// Copyright 2009 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.

// IP sockets

package net

import (
	"os"
	"syscall"
)

// Should we try to use the IPv4 socket interface if we're
// only dealing with IPv4 sockets?  As long as the host system
// understands IPv6, it's okay to pass IPv4 addresses to the IPv6
// interface.  That simplifies our code and is most general.
// Unfortunately, we need to run on kernels built without IPv6 support too.
// So probe the kernel to figure it out.
func kernelSupportsIPv6() bool {
	// FreeBSD does not support this sort of interface.
	if syscall.OS == "freebsd" {
		return false
	}
	fd, e := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
	if fd >= 0 {
		syscall.Close(fd)
	}
	return e == 0
}

var preferIPv4 = !kernelSupportsIPv6()

// TODO(rsc): if syscall.OS == "linux", we're supposd to read
// /proc/sys/net/core/somaxconn,
// to take advantage of kernels that have raised the limit.
func listenBacklog() int { return syscall.SOMAXCONN }

// Internet sockets (TCP, UDP)

// A sockaddr represents a TCP or UDP network address that can
// be converted into a syscall.Sockaddr.
type sockaddr interface {
	Addr
	sockaddr(family int) (syscall.Sockaddr, os.Error)
	family() int
}

func internetSocket(net string, laddr, raddr sockaddr, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) {
	// Figure out IP version.
	// If network has a suffix like "tcp4", obey it.
	var oserr os.Error
	family := syscall.AF_INET6
	switch net[len(net)-1] {
	case '4':
		family = syscall.AF_INET
	case '6':
		// nothing to do
	default:
		// Otherwise, guess.
		// If the addresses are IPv4 and we prefer IPv4, use 4; else 6.
		if preferIPv4 &&
			(laddr == nil || laddr.family() == syscall.AF_INET) &&
			(raddr == nil || raddr.family() == syscall.AF_INET) {
			family = syscall.AF_INET
		}
	}

	var la, ra syscall.Sockaddr
	if laddr != nil {
		if la, oserr = laddr.sockaddr(family); err != nil {
			goto Error
		}
	}
	if raddr != nil {
		if ra, oserr = raddr.sockaddr(family); err != nil {
			goto Error
		}
	}
	fd, oserr = socket(net, family, proto, 0, la, ra, toAddr)
	if err != nil {
		goto Error
	}
	return fd, nil

Error:
	addr := raddr
	if mode == "listen" {
		addr = laddr
	}
	return nil, &OpError{mode, net, addr, oserr}
}

func getip(fd int, remote bool) (ip []byte, port int, ok bool) {
	// No attempt at error reporting because
	// there are no possible errors, and the
	// caller won't report them anyway.
	var sa syscall.Sockaddr
	if remote {
		sa, _ = syscall.Getpeername(fd)
	} else {
		sa, _ = syscall.Getsockname(fd)
	}
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return &sa.Addr, sa.Port, true
	case *syscall.SockaddrInet6:
		return &sa.Addr, sa.Port, true
	}
	return
}

type InvalidAddrError string

func (e InvalidAddrError) String() string  { return string(e) }
func (e InvalidAddrError) Timeout() bool   { return false }
func (e InvalidAddrError) Temporary() bool { return false }

func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) {
	switch family {
	case syscall.AF_INET:
		if len(ip) == 0 {
			ip = IPv4zero
		}
		if ip = ip.To4(); ip == nil {
			return nil, InvalidAddrError("non-IPv4 address")
		}
		s := new(syscall.SockaddrInet4)
		for i := 0; i < IPv4len; i++ {
			s.Addr[i] = ip[i]
		}
		s.Port = port
		return s, nil
	case syscall.AF_INET6:
		if len(ip) == 0 {
			ip = IPzero
		}
		// IPv4 callers use 0.0.0.0 to mean "announce on any available address".
		// In IPv6 mode, Linux treats that as meaning "announce on 0.0.0.0",
		// which it refuses to do.  Rewrite to the IPv6 all zeros.
		if p4 := ip.To4(); p4 != nil && p4[0] == 0 && p4[1] == 0 && p4[2] == 0 && p4[3] == 0 {
			ip = IPzero
		}
		if ip = ip.To16(); ip == nil {
			return nil, InvalidAddrError("non-IPv6 address")
		}
		s := new(syscall.SockaddrInet6)
		for i := 0; i < IPv6len; i++ {
			s.Addr[i] = ip[i]
		}
		s.Port = port
		return s, nil
	}
	return nil, InvalidAddrError("unexpected socket family")
}

// Split "host:port" into "host" and "port".
// Host cannot contain colons unless it is bracketed.
func splitHostPort(hostport string) (host, port string, err os.Error) {
	// The port starts after the last colon.
	i := last(hostport, ':')
	if i < 0 {
		err = &AddrError{"missing port in address", hostport}
		return
	}

	host, port = hostport[0:i], hostport[i+1:]

	// Can put brackets around host ...
	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
		host = host[1 : len(host)-1]
	} else {
		// ... but if there are no brackets, no colons.
		if byteIndex(host, ':') >= 0 {
			err = &AddrError{"too many colons in address", hostport}
			return
		}
	}
	return
}

// Join "host" and "port" into "host:port".
// If host contains colons, will join into "[host]:port".
func joinHostPort(host, port string) string {
	// If host has colons, have to bracket it.
	if byteIndex(host, ':') >= 0 {
		return "[" + host + "]:" + port
	}
	return host + ":" + port
}

// Convert "host:port" into IP address and port.
func hostPortToIP(net, hostport string) (ip IP, iport int, err os.Error) {
	host, port, err := splitHostPort(hostport)
	if err != nil {
		goto Error
	}

	var addr IP
	if host != "" {
		// Try as an IP address.
		addr = ParseIP(host)
		if addr == nil {
			// Not an IP address.  Try as a DNS name.
			_, addrs, err1 := LookupHost(host)
			if err1 != nil {
				err = err1
				goto Error
			}
			addr = ParseIP(addrs[0])
			if addr == nil {
				// should not happen
				err = &AddrError{"LookupHost returned invalid address", addrs[0]}
				goto Error
			}
		}
	}

	p, i, ok := dtoi(port, 0)
	if !ok || i != len(port) {
		p, err = LookupPort(net, port)
		if err != nil {
			goto Error
		}
	}
	if p < 0 || p > 0xFFFF {
		err = &AddrError{"invalid port", port}
		goto Error
	}

	return addr, p, nil

Error:
	return nil, 0, err
}
<commit_msg>net: fix bug in internetSocket introduced by error cleanup.<commit_after>// Copyright 2009 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.

// IP sockets

package net

import (
	"os"
	"syscall"
)

// Should we try to use the IPv4 socket interface if we're
// only dealing with IPv4 sockets?  As long as the host system
// understands IPv6, it's okay to pass IPv4 addresses to the IPv6
// interface.  That simplifies our code and is most general.
// Unfortunately, we need to run on kernels built without IPv6 support too.
// So probe the kernel to figure it out.
func kernelSupportsIPv6() bool {
	// FreeBSD does not support this sort of interface.
	if syscall.OS == "freebsd" {
		return false
	}
	fd, e := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
	if fd >= 0 {
		syscall.Close(fd)
	}
	return e == 0
}

var preferIPv4 = !kernelSupportsIPv6()

// TODO(rsc): if syscall.OS == "linux", we're supposd to read
// /proc/sys/net/core/somaxconn,
// to take advantage of kernels that have raised the limit.
func listenBacklog() int { return syscall.SOMAXCONN }

// Internet sockets (TCP, UDP)

// A sockaddr represents a TCP or UDP network address that can
// be converted into a syscall.Sockaddr.
type sockaddr interface {
	Addr
	sockaddr(family int) (syscall.Sockaddr, os.Error)
	family() int
}

func internetSocket(net string, laddr, raddr sockaddr, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) {
	// Figure out IP version.
	// If network has a suffix like "tcp4", obey it.
	var oserr os.Error
	family := syscall.AF_INET6
	switch net[len(net)-1] {
	case '4':
		family = syscall.AF_INET
	case '6':
		// nothing to do
	default:
		// Otherwise, guess.
		// If the addresses are IPv4 and we prefer IPv4, use 4; else 6.
		if preferIPv4 &&
			(laddr == nil || laddr.family() == syscall.AF_INET) &&
			(raddr == nil || raddr.family() == syscall.AF_INET) {
			family = syscall.AF_INET
		}
	}

	var la, ra syscall.Sockaddr
	if laddr != nil {
		if la, oserr = laddr.sockaddr(family); err != nil {
			goto Error
		}
	}
	if raddr != nil {
		if ra, oserr = raddr.sockaddr(family); err != nil {
			goto Error
		}
	}
	fd, oserr = socket(net, family, proto, 0, la, ra, toAddr)
	if oserr != nil {
		goto Error
	}
	return fd, nil

Error:
	addr := raddr
	if mode == "listen" {
		addr = laddr
	}
	return nil, &OpError{mode, net, addr, oserr}
}

func getip(fd int, remote bool) (ip []byte, port int, ok bool) {
	// No attempt at error reporting because
	// there are no possible errors, and the
	// caller won't report them anyway.
	var sa syscall.Sockaddr
	if remote {
		sa, _ = syscall.Getpeername(fd)
	} else {
		sa, _ = syscall.Getsockname(fd)
	}
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return &sa.Addr, sa.Port, true
	case *syscall.SockaddrInet6:
		return &sa.Addr, sa.Port, true
	}
	return
}

type InvalidAddrError string

func (e InvalidAddrError) String() string  { return string(e) }
func (e InvalidAddrError) Timeout() bool   { return false }
func (e InvalidAddrError) Temporary() bool { return false }

func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) {
	switch family {
	case syscall.AF_INET:
		if len(ip) == 0 {
			ip = IPv4zero
		}
		if ip = ip.To4(); ip == nil {
			return nil, InvalidAddrError("non-IPv4 address")
		}
		s := new(syscall.SockaddrInet4)
		for i := 0; i < IPv4len; i++ {
			s.Addr[i] = ip[i]
		}
		s.Port = port
		return s, nil
	case syscall.AF_INET6:
		if len(ip) == 0 {
			ip = IPzero
		}
		// IPv4 callers use 0.0.0.0 to mean "announce on any available address".
		// In IPv6 mode, Linux treats that as meaning "announce on 0.0.0.0",
		// which it refuses to do.  Rewrite to the IPv6 all zeros.
		if p4 := ip.To4(); p4 != nil && p4[0] == 0 && p4[1] == 0 && p4[2] == 0 && p4[3] == 0 {
			ip = IPzero
		}
		if ip = ip.To16(); ip == nil {
			return nil, InvalidAddrError("non-IPv6 address")
		}
		s := new(syscall.SockaddrInet6)
		for i := 0; i < IPv6len; i++ {
			s.Addr[i] = ip[i]
		}
		s.Port = port
		return s, nil
	}
	return nil, InvalidAddrError("unexpected socket family")
}

// Split "host:port" into "host" and "port".
// Host cannot contain colons unless it is bracketed.
func splitHostPort(hostport string) (host, port string, err os.Error) {
	// The port starts after the last colon.
	i := last(hostport, ':')
	if i < 0 {
		err = &AddrError{"missing port in address", hostport}
		return
	}

	host, port = hostport[0:i], hostport[i+1:]

	// Can put brackets around host ...
	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
		host = host[1 : len(host)-1]
	} else {
		// ... but if there are no brackets, no colons.
		if byteIndex(host, ':') >= 0 {
			err = &AddrError{"too many colons in address", hostport}
			return
		}
	}
	return
}

// Join "host" and "port" into "host:port".
// If host contains colons, will join into "[host]:port".
func joinHostPort(host, port string) string {
	// If host has colons, have to bracket it.
	if byteIndex(host, ':') >= 0 {
		return "[" + host + "]:" + port
	}
	return host + ":" + port
}

// Convert "host:port" into IP address and port.
func hostPortToIP(net, hostport string) (ip IP, iport int, err os.Error) {
	host, port, err := splitHostPort(hostport)
	if err != nil {
		goto Error
	}

	var addr IP
	if host != "" {
		// Try as an IP address.
		addr = ParseIP(host)
		if addr == nil {
			// Not an IP address.  Try as a DNS name.
			_, addrs, err1 := LookupHost(host)
			if err1 != nil {
				err = err1
				goto Error
			}
			addr = ParseIP(addrs[0])
			if addr == nil {
				// should not happen
				err = &AddrError{"LookupHost returned invalid address", addrs[0]}
				goto Error
			}
		}
	}

	p, i, ok := dtoi(port, 0)
	if !ok || i != len(port) {
		p, err = LookupPort(net, port)
		if err != nil {
			goto Error
		}
	}
	if p < 0 || p > 0xFFFF {
		err = &AddrError{"invalid port", port}
		goto Error
	}

	return addr, p, nil

Error:
	return nil, 0, err
}
<|endoftext|>


<commit_before>package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "encoding/json"
)

struct JsonData {
  Name string `json:"name"`
  Struct struct {
    Integer int `json:"integer"`
  } `json:"struce"`
}

func main() {
  http.HandleFunc("/", hello)
  http.ListenAndServe(":8001", nil)
}

func hello(writer http.ResponseWriter, reader *http.Request) {
  file, err := ioutil.ReadFile("simple-http.json")
  if err != nil {
    file = []byte("")
    fmt.Println(err)
  }

  var data JsonData

  decoder := json.NewDecoder(file)

  decoder.Decode(&data)

  writer.Write(file)
}
<commit_msg>Fix struct syntax<commit_after>package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "encoding/json"
)

type JsonData struct {
  Name string `json:"name"`
  Struct struct {
    Integer int `json:"integer"`
  } `json:"struce"`
}

func main() {
  http.HandleFunc("/", hello)
  http.ListenAndServe(":8001", nil)
}

func hello(writer http.ResponseWriter, reader *http.Request) {
  file, err := ioutil.ReadFile("simple-http.json")
  if err != nil {
    fmt.Println(err)
  }

  var data JsonData

  decoder := json.NewDecoder(file)

  decoded := decoder.Decode(&data)

  writer.Write(decoded)
}
<|endoftext|>


<commit_before>// Copyright 2009 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.

/*
	The rpc package provides access to the public methods of an object across a
	network or other I/O connection.  A server registers an object, making it visible
	as a service with the name of the type of the object.  After registration, public
	methods of the object will be accessible remotely.  A server may register multiple
	objects (services) of different types but it is an error to register multiple
	objects of the same type.

	Only methods that satisfy these criteria will be made available for remote access;
	other methods will be ignored:

		- the method name is publicly visible, that is, begins with an upper case letter.
		- the method has two arguments, both pointers to publicly visible structs.
		- the method has return type os.Error.

	The method's first argument represents the arguments provided by the caller; the
	second argument represents the result parameters to be returned to the caller.
	The method's return value, if non-nil, is passed back as a string that the client
	sees as an os.ErrorString.

	The server may handle requests on a single connection by calling ServeConn.  More
	typically it will create a network listener and call Accept or, for an HTTP
	listener, HandleHTTP and http.Serve.

	A client wishing to use the service establishes a connection and then invokes
	NewClient on the connection.  The convenience function Dial (DialHTTP) performs
	both steps for a raw network connection (an HTTP connection).  The resulting
	Client object has two methods, Call and Go, that specify the service and method to
	call, a structure containing the arguments, and a structure to receive the result
	parameters.

	Call waits for the remote call to complete; Go launches the call asynchronously
	and returns a channel that will signal completion.

	Package "gob" is used to transport the data.

	Here is a simple example.  A server wishes to export an object of type Arith:

		package server

		type Args struct {
			A, B int
		}

		type Reply struct {
			C int
		}

		type Arith int

		func (t *Arith) Multiply(args *Args, reply *Reply) os.Error {
			reply.C = args.A * args.B;
			return nil
		}

		func (t *Arith) Divide(args *Args, reply *Reply) os.Error {
			if args.B == 0 {
				return os.ErrorString("divide by zero");
			}
			reply.C = args.A / args.B;
			return nil
		}

	The server calls (for HTTP service):

		arith := new(Arith);
		rpc.Register(arith);
		rrpc.HandleHTTP();
		l, e := net.Listen("tcp", ":1234");
		if e != nil {
			log.Exit("listen error:", e);
		}
		go http.Serve(l, nil);

	At this point, clients can see a service "Arith" with methods "Arith.Multiply" and
	"Arith.Divide".  To invoke one, a client first dials the server:

		client, err := rpc.DialHTTP("tcp", serverAddress + ":1234");
		if err != nil {
			log.Exit("dialing:", err);
		}

	Then it can make a remote call:

		// Synchronous call
		args := &server.Args{7,8};
		reply := new(server.Reply);
		err = client.Call("Arith.Multiply", args, reply);
		if err != nil {
			log.Exit("arith error:", err);
		}
		fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply.C);

	or

		// Asynchronous call
		divCall := client.Go("Arith.Divide", args, reply, nil);
		replyCall := <-divCall.Done;	// will be equal to divCall
		// check errors, print, etc.

	A server implementation will often provide a simple, type-safe wrapper for the
	client.
*/
package rpc

import (
	"gob";
	"http";
	"log";
	"io";
	"net";
	"os";
	"reflect";
	"strings";
	"sync";
	"unicode";
	"utf8";
)

// Precompute the reflect type for os.Error.  Can't use os.Error directly
// because Typeof takes an empty interface value.  This is annoying.
var unusedError *os.Error;
var typeOfOsError = reflect.Typeof(unusedError).(*reflect.PtrType).Elem()

type methodType struct {
	sync.Mutex;	// protects counters
	method	reflect.Method;
	argType	*reflect.PtrType;
	replyType	*reflect.PtrType;
	numCalls	uint;
}

type service struct {
	name	string;	// name of service
	rcvr	reflect.Value;	// receiver of methods for the service
	typ	reflect.Type;	// type of the receiver
	method	map[string] *methodType;	// registered methods
}

// Request is a header written before every RPC call.  It is used internally
// but documented here as an aid to debugging, such as when analyzing
// network traffic.
type Request struct {
	ServiceMethod	string;	// format: "Service.Method"
	Seq	uint64;	// sequence number chosen by client
}

// Response is a header written before every RPC return.  It is used internally
// but documented here as an aid to debugging, such as when analyzing
// network traffic.
type Response struct {
	ServiceMethod	string;	// echoes that of the Request
	Seq	uint64;	// echoes that of the request
	Error	string;	// error, if any.
}

type serverType struct {
	sync.Mutex;	// protects the serviceMap
	serviceMap	map[string] *service;
}

// This variable is a global whose "public" methods are really private methods
// called from the global functions of this package: rpc.Register, rpc.ServeConn, etc.
// For example, rpc.Register() calls server.add().
var server = &serverType{ serviceMap: make(map[string] *service) }

// Is this a publicly vislble - upper case - name?
func isPublic(name string) bool {
	rune, wid_ := utf8.DecodeRuneInString(name);
	return unicode.IsUpper(rune)
}

func (server *serverType) register(rcvr interface{}) os.Error {
	server.Lock();
	defer server.Unlock();
	if server.serviceMap == nil {
		server.serviceMap = make(map[string] *service);
	}
	s := new(service);
	s.typ = reflect.Typeof(rcvr);
	s.rcvr = reflect.NewValue(rcvr);
	sname := reflect.Indirect(s.rcvr).Type().Name();
	if sname == "" {
		log.Exit("rpc: no service name for type", s.typ.String())
	}
	if !isPublic(sname) {
		s := "rpc Register: type " + sname + " is not public";
		log.Stderr(s);
		return os.ErrorString(s);
	}
	if _, present := server.serviceMap[sname]; present {
		return os.ErrorString("rpc: service already defined: " + sname);
	}
	s.name = sname;
	s.method = make(map[string] *methodType);

	// Install the methods
	for m := 0; m < s.typ.NumMethod(); m++ {
		method := s.typ.Method(m);
		mtype := method.Type;
		mname := method.Name;
		if !isPublic(mname) {
			continue
		}
		// Method needs three ins: receiver, *args, *reply.
		// The args and reply must be structs until gobs are more general.
		if mtype.NumIn() != 3 {
			log.Stderr("method", mname, "has wrong number of ins:", mtype.NumIn());
			continue;
		}
		argType, ok := mtype.In(1).(*reflect.PtrType);
		if !ok {
			log.Stderr(mname, "arg type not a pointer:", argType.String());
			continue;
		}
		if _, ok := argType.Elem().(*reflect.StructType); !ok {
			log.Stderr(mname, "arg type not a pointer to a struct:", argType.String());
			continue;
		}
		replyType, ok := mtype.In(2).(*reflect.PtrType);
		if !ok {
			log.Stderr(mname, "reply type not a pointer:", replyType.String());
			continue;
		}
		if _, ok := replyType.Elem().(*reflect.StructType); !ok {
			log.Stderr(mname, "reply type not a pointer to a struct:", replyType.String());
			continue;
		}
		if !isPublic(argType.Elem().Name()) {
			log.Stderr(mname, "argument type not public:", argType.String());
			continue;
		}
		if !isPublic(replyType.Elem().Name()) {
			log.Stderr(mname, "reply type not public:", replyType.String());
			continue;
		}
		// Method needs one out: os.Error.
		if mtype.NumOut() != 1 {
			log.Stderr("method", mname, "has wrong number of outs:", mtype.NumOut());
			continue;
		}
		if returnType := mtype.Out(0); returnType != typeOfOsError {
			log.Stderr("method", mname, "returns", returnType.String(), "not os.Error");
			continue;
		}
		s.method[mname] = &methodType{method: method, argType: argType, replyType: replyType};
	}

	if len(s.method) == 0 {
		s := "rpc Register: type " + sname + " has no public methods of suitable type";
		log.Stderr(s);
		return os.ErrorString(s);
	}
	server.serviceMap[s.name] = s;
	return nil;
}

// A value sent as a placeholder for the response when the server receives an invalid request.
type InvalidRequest struct {
	marker int
}
var invalidRequest = InvalidRequest{1}

func _new(t *reflect.PtrType) *reflect.PtrValue {
	v := reflect.MakeZero(t).(*reflect.PtrValue);
	v.PointTo(reflect.MakeZero(t.Elem()));
	return v;
}

func sendResponse(sending *sync.Mutex, req *Request, reply interface{}, enc *gob.Encoder, errmsg string) {
	resp := new(Response);
	// Encode the response header
	resp.ServiceMethod = req.ServiceMethod;
	resp.Error = errmsg;
	resp.Seq = req.Seq;
	sending.Lock();
	enc.Encode(resp);
	// Encode the reply value.
	enc.Encode(reply);
	sending.Unlock();
}

func (s *service) call(sending *sync.Mutex, mtype *methodType, req *Request, argv, replyv reflect.Value, enc *gob.Encoder) {
	mtype.Lock();
	mtype.numCalls++;
	mtype.Unlock();
	function := mtype.method.Func;
	// Invoke the method, providing a new value for the reply.
	returnValues := function.Call([]reflect.Value{s.rcvr, argv, replyv});
	// The return value for the method is an os.Error.
	errInter := returnValues[0].Interface();
	errmsg := "";
	if errInter != nil {
		errmsg = errInter.(os.Error).String();
	}
	sendResponse(sending, req, replyv.Interface(), enc, errmsg);
}

func (server *serverType) input(conn io.ReadWriteCloser) {
	dec := gob.NewDecoder(conn);
	enc := gob.NewEncoder(conn);
	sending := new(sync.Mutex);
	for {
		// Grab the request header.
		req := new(Request);
		err := dec.Decode(req);
		if err != nil {
			if err == os.EOF || err == io.ErrUnexpectedEOF {
				log.Stderr("rpc: ", err);
				break;
			}
			s := "rpc: server cannot decode request: " + err.String();
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		serviceMethod := strings.Split(req.ServiceMethod, ".", 0);
		if len(serviceMethod) != 2 {
			s := "rpc: service/method request ill:formed: " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		// Look up the request.
		server.Lock();
		service, ok := server.serviceMap[serviceMethod[0]];
		server.Unlock();
		if !ok {
			s := "rpc: can't find service " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		mtype, ok := service.method[serviceMethod[1]];
		if !ok {
			s := "rpc: can't find method " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		method := mtype.method;
		// Decode the argument value.
		argv := _new(mtype.argType);
		replyv := _new(mtype.replyType);
		err = dec.Decode(argv.Interface());
		if err != nil {
			log.Stderr("rpc: tearing down", serviceMethod[0], "connection:", err);
			sendResponse(sending, req, replyv.Interface(), enc, err.String());
			continue;
		}
		go service.call(sending, mtype, req, argv, replyv, enc);
	}
	conn.Close();
}

func (server *serverType) accept(lis net.Listener) {
	for {
		conn, addr, err := lis.Accept();
		if err != nil {
			log.Exit("rpc.Serve: accept:", err.String());	// TODO(r): exit?
		}
		go server.input(conn);
	}
}

// Register publishes in the server the set of methods of the
// receiver value that satisfy the following conditions:
//	- public method
//	- two arguments, both pointers to public structs
//	- one return value of type os.Error
// It returns an error if the receiver is not public or has no
// suitable methods.
func Register(rcvr interface{}) os.Error {
	return server.register(rcvr)
}

// ServeConn runs the server on a single connection.  When the connection
// completes, service terminates.  ServeConn blocks; the caller typically
// invokes it in a go statement.
func ServeConn(conn io.ReadWriteCloser) {
	go server.input(conn)
}

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func Accept(lis net.Listener) {
	server.accept(lis)
}

// Can connect to RPC service using HTTP CONNECT to rpcPath.
var rpcPath string = "/_goRPC_"
var debugPath string = "/debug/rpc"
var connected = "200 Connected to Go RPC"

func serveHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "CONNECT" {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8");
		c.WriteHeader(http.StatusMethodNotAllowed);
		io.WriteString(c, "405 must CONNECT to " + rpcPath + "\n");
		return;
	}
	conn, buf, err := c.Hijack();
	if err != nil {
		log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String());
		return;
	}
	io.WriteString(conn, "HTTP/1.0 " + connected + "\n\n");
	server.input(conn);
}

func debugHTTP(c *http.Conn, req *http.Request)

// HandleHTTP registers an HTTP handler for RPC messages.
// It is still necessary to invoke http.Serve(), typically in a go statement.
func HandleHTTP() {
	http.Handle(rpcPath, http.HandlerFunc(serveHTTP));
	http.Handle(debugPath, http.HandlerFunc(debugHTTP));
}
<commit_msg>fix typo<commit_after>// Copyright 2009 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.

/*
	The rpc package provides access to the public methods of an object across a
	network or other I/O connection.  A server registers an object, making it visible
	as a service with the name of the type of the object.  After registration, public
	methods of the object will be accessible remotely.  A server may register multiple
	objects (services) of different types but it is an error to register multiple
	objects of the same type.

	Only methods that satisfy these criteria will be made available for remote access;
	other methods will be ignored:

		- the method name is publicly visible, that is, begins with an upper case letter.
		- the method has two arguments, both pointers to publicly visible structs.
		- the method has return type os.Error.

	The method's first argument represents the arguments provided by the caller; the
	second argument represents the result parameters to be returned to the caller.
	The method's return value, if non-nil, is passed back as a string that the client
	sees as an os.ErrorString.

	The server may handle requests on a single connection by calling ServeConn.  More
	typically it will create a network listener and call Accept or, for an HTTP
	listener, HandleHTTP and http.Serve.

	A client wishing to use the service establishes a connection and then invokes
	NewClient on the connection.  The convenience function Dial (DialHTTP) performs
	both steps for a raw network connection (an HTTP connection).  The resulting
	Client object has two methods, Call and Go, that specify the service and method to
	call, a structure containing the arguments, and a structure to receive the result
	parameters.

	Call waits for the remote call to complete; Go launches the call asynchronously
	and returns a channel that will signal completion.

	Package "gob" is used to transport the data.

	Here is a simple example.  A server wishes to export an object of type Arith:

		package server

		type Args struct {
			A, B int
		}

		type Reply struct {
			C int
		}

		type Arith int

		func (t *Arith) Multiply(args *Args, reply *Reply) os.Error {
			reply.C = args.A * args.B;
			return nil
		}

		func (t *Arith) Divide(args *Args, reply *Reply) os.Error {
			if args.B == 0 {
				return os.ErrorString("divide by zero");
			}
			reply.C = args.A / args.B;
			return nil
		}

	The server calls (for HTTP service):

		arith := new(Arith);
		rpc.Register(arith);
		rpc.HandleHTTP();
		l, e := net.Listen("tcp", ":1234");
		if e != nil {
			log.Exit("listen error:", e);
		}
		go http.Serve(l, nil);

	At this point, clients can see a service "Arith" with methods "Arith.Multiply" and
	"Arith.Divide".  To invoke one, a client first dials the server:

		client, err := rpc.DialHTTP("tcp", serverAddress + ":1234");
		if err != nil {
			log.Exit("dialing:", err);
		}

	Then it can make a remote call:

		// Synchronous call
		args := &server.Args{7,8};
		reply := new(server.Reply);
		err = client.Call("Arith.Multiply", args, reply);
		if err != nil {
			log.Exit("arith error:", err);
		}
		fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply.C);

	or

		// Asynchronous call
		divCall := client.Go("Arith.Divide", args, reply, nil);
		replyCall := <-divCall.Done;	// will be equal to divCall
		// check errors, print, etc.

	A server implementation will often provide a simple, type-safe wrapper for the
	client.
*/
package rpc

import (
	"gob";
	"http";
	"log";
	"io";
	"net";
	"os";
	"reflect";
	"strings";
	"sync";
	"unicode";
	"utf8";
)

// Precompute the reflect type for os.Error.  Can't use os.Error directly
// because Typeof takes an empty interface value.  This is annoying.
var unusedError *os.Error;
var typeOfOsError = reflect.Typeof(unusedError).(*reflect.PtrType).Elem()

type methodType struct {
	sync.Mutex;	// protects counters
	method	reflect.Method;
	argType	*reflect.PtrType;
	replyType	*reflect.PtrType;
	numCalls	uint;
}

type service struct {
	name	string;	// name of service
	rcvr	reflect.Value;	// receiver of methods for the service
	typ	reflect.Type;	// type of the receiver
	method	map[string] *methodType;	// registered methods
}

// Request is a header written before every RPC call.  It is used internally
// but documented here as an aid to debugging, such as when analyzing
// network traffic.
type Request struct {
	ServiceMethod	string;	// format: "Service.Method"
	Seq	uint64;	// sequence number chosen by client
}

// Response is a header written before every RPC return.  It is used internally
// but documented here as an aid to debugging, such as when analyzing
// network traffic.
type Response struct {
	ServiceMethod	string;	// echoes that of the Request
	Seq	uint64;	// echoes that of the request
	Error	string;	// error, if any.
}

type serverType struct {
	sync.Mutex;	// protects the serviceMap
	serviceMap	map[string] *service;
}

// This variable is a global whose "public" methods are really private methods
// called from the global functions of this package: rpc.Register, rpc.ServeConn, etc.
// For example, rpc.Register() calls server.add().
var server = &serverType{ serviceMap: make(map[string] *service) }

// Is this a publicly vislble - upper case - name?
func isPublic(name string) bool {
	rune, wid_ := utf8.DecodeRuneInString(name);
	return unicode.IsUpper(rune)
}

func (server *serverType) register(rcvr interface{}) os.Error {
	server.Lock();
	defer server.Unlock();
	if server.serviceMap == nil {
		server.serviceMap = make(map[string] *service);
	}
	s := new(service);
	s.typ = reflect.Typeof(rcvr);
	s.rcvr = reflect.NewValue(rcvr);
	sname := reflect.Indirect(s.rcvr).Type().Name();
	if sname == "" {
		log.Exit("rpc: no service name for type", s.typ.String())
	}
	if !isPublic(sname) {
		s := "rpc Register: type " + sname + " is not public";
		log.Stderr(s);
		return os.ErrorString(s);
	}
	if _, present := server.serviceMap[sname]; present {
		return os.ErrorString("rpc: service already defined: " + sname);
	}
	s.name = sname;
	s.method = make(map[string] *methodType);

	// Install the methods
	for m := 0; m < s.typ.NumMethod(); m++ {
		method := s.typ.Method(m);
		mtype := method.Type;
		mname := method.Name;
		if !isPublic(mname) {
			continue
		}
		// Method needs three ins: receiver, *args, *reply.
		// The args and reply must be structs until gobs are more general.
		if mtype.NumIn() != 3 {
			log.Stderr("method", mname, "has wrong number of ins:", mtype.NumIn());
			continue;
		}
		argType, ok := mtype.In(1).(*reflect.PtrType);
		if !ok {
			log.Stderr(mname, "arg type not a pointer:", argType.String());
			continue;
		}
		if _, ok := argType.Elem().(*reflect.StructType); !ok {
			log.Stderr(mname, "arg type not a pointer to a struct:", argType.String());
			continue;
		}
		replyType, ok := mtype.In(2).(*reflect.PtrType);
		if !ok {
			log.Stderr(mname, "reply type not a pointer:", replyType.String());
			continue;
		}
		if _, ok := replyType.Elem().(*reflect.StructType); !ok {
			log.Stderr(mname, "reply type not a pointer to a struct:", replyType.String());
			continue;
		}
		if !isPublic(argType.Elem().Name()) {
			log.Stderr(mname, "argument type not public:", argType.String());
			continue;
		}
		if !isPublic(replyType.Elem().Name()) {
			log.Stderr(mname, "reply type not public:", replyType.String());
			continue;
		}
		// Method needs one out: os.Error.
		if mtype.NumOut() != 1 {
			log.Stderr("method", mname, "has wrong number of outs:", mtype.NumOut());
			continue;
		}
		if returnType := mtype.Out(0); returnType != typeOfOsError {
			log.Stderr("method", mname, "returns", returnType.String(), "not os.Error");
			continue;
		}
		s.method[mname] = &methodType{method: method, argType: argType, replyType: replyType};
	}

	if len(s.method) == 0 {
		s := "rpc Register: type " + sname + " has no public methods of suitable type";
		log.Stderr(s);
		return os.ErrorString(s);
	}
	server.serviceMap[s.name] = s;
	return nil;
}

// A value sent as a placeholder for the response when the server receives an invalid request.
type InvalidRequest struct {
	marker int
}
var invalidRequest = InvalidRequest{1}

func _new(t *reflect.PtrType) *reflect.PtrValue {
	v := reflect.MakeZero(t).(*reflect.PtrValue);
	v.PointTo(reflect.MakeZero(t.Elem()));
	return v;
}

func sendResponse(sending *sync.Mutex, req *Request, reply interface{}, enc *gob.Encoder, errmsg string) {
	resp := new(Response);
	// Encode the response header
	resp.ServiceMethod = req.ServiceMethod;
	resp.Error = errmsg;
	resp.Seq = req.Seq;
	sending.Lock();
	enc.Encode(resp);
	// Encode the reply value.
	enc.Encode(reply);
	sending.Unlock();
}

func (s *service) call(sending *sync.Mutex, mtype *methodType, req *Request, argv, replyv reflect.Value, enc *gob.Encoder) {
	mtype.Lock();
	mtype.numCalls++;
	mtype.Unlock();
	function := mtype.method.Func;
	// Invoke the method, providing a new value for the reply.
	returnValues := function.Call([]reflect.Value{s.rcvr, argv, replyv});
	// The return value for the method is an os.Error.
	errInter := returnValues[0].Interface();
	errmsg := "";
	if errInter != nil {
		errmsg = errInter.(os.Error).String();
	}
	sendResponse(sending, req, replyv.Interface(), enc, errmsg);
}

func (server *serverType) input(conn io.ReadWriteCloser) {
	dec := gob.NewDecoder(conn);
	enc := gob.NewEncoder(conn);
	sending := new(sync.Mutex);
	for {
		// Grab the request header.
		req := new(Request);
		err := dec.Decode(req);
		if err != nil {
			if err == os.EOF || err == io.ErrUnexpectedEOF {
				log.Stderr("rpc: ", err);
				break;
			}
			s := "rpc: server cannot decode request: " + err.String();
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		serviceMethod := strings.Split(req.ServiceMethod, ".", 0);
		if len(serviceMethod) != 2 {
			s := "rpc: service/method request ill:formed: " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		// Look up the request.
		server.Lock();
		service, ok := server.serviceMap[serviceMethod[0]];
		server.Unlock();
		if !ok {
			s := "rpc: can't find service " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		mtype, ok := service.method[serviceMethod[1]];
		if !ok {
			s := "rpc: can't find method " + req.ServiceMethod;
			sendResponse(sending, req, invalidRequest, enc, s);
			continue;
		}
		method := mtype.method;
		// Decode the argument value.
		argv := _new(mtype.argType);
		replyv := _new(mtype.replyType);
		err = dec.Decode(argv.Interface());
		if err != nil {
			log.Stderr("rpc: tearing down", serviceMethod[0], "connection:", err);
			sendResponse(sending, req, replyv.Interface(), enc, err.String());
			continue;
		}
		go service.call(sending, mtype, req, argv, replyv, enc);
	}
	conn.Close();
}

func (server *serverType) accept(lis net.Listener) {
	for {
		conn, addr, err := lis.Accept();
		if err != nil {
			log.Exit("rpc.Serve: accept:", err.String());	// TODO(r): exit?
		}
		go server.input(conn);
	}
}

// Register publishes in the server the set of methods of the
// receiver value that satisfy the following conditions:
//	- public method
//	- two arguments, both pointers to public structs
//	- one return value of type os.Error
// It returns an error if the receiver is not public or has no
// suitable methods.
func Register(rcvr interface{}) os.Error {
	return server.register(rcvr)
}

// ServeConn runs the server on a single connection.  When the connection
// completes, service terminates.  ServeConn blocks; the caller typically
// invokes it in a go statement.
func ServeConn(conn io.ReadWriteCloser) {
	go server.input(conn)
}

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func Accept(lis net.Listener) {
	server.accept(lis)
}

// Can connect to RPC service using HTTP CONNECT to rpcPath.
var rpcPath string = "/_goRPC_"
var debugPath string = "/debug/rpc"
var connected = "200 Connected to Go RPC"

func serveHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "CONNECT" {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8");
		c.WriteHeader(http.StatusMethodNotAllowed);
		io.WriteString(c, "405 must CONNECT to " + rpcPath + "\n");
		return;
	}
	conn, buf, err := c.Hijack();
	if err != nil {
		log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String());
		return;
	}
	io.WriteString(conn, "HTTP/1.0 " + connected + "\n\n");
	server.input(conn);
}

func debugHTTP(c *http.Conn, req *http.Request)

// HandleHTTP registers an HTTP handler for RPC messages.
// It is still necessary to invoke http.Serve(), typically in a go statement.
func HandleHTTP() {
	http.Handle(rpcPath, http.HandlerFunc(serveHTTP));
	http.Handle(debugPath, http.HandlerFunc(debugHTTP));
}
<|endoftext|>


<commit_before>package sysfs

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

// ListDevices prints a list of all storage devices attached to a linux machine
func ListDevicesCmd() {
	fmt.Printf("Current storage devices:\n\n")
	for _, dev := range findDevices() {
		fmt.Printf("%s\n", dev)
	}
	if !isSudoerUser() {
		fmt.Printf("\nPlease, rerun this command with sudo if you want to learn more information about these devices")
	}
	fmt.Printf("\n")
}

func findDevices() []string {
	var devices []string

	file, err := os.Open("/proc/partitions")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		device, err := getDeviceName(scanner.Text())
		if err == nil {
			devDesc := recognizeTypeDevice(device)
			devices = append(devices, devDesc)
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

	return devices
}

func getDeviceName(line string) (string, error) {
	parts := strings.Fields(line)
	if len(parts) >= 4 && isStorageDevice(parts[3]) {
		return parts[3], nil
	}
	return "", errors.New("Line does not contain any storage device")
}

func isStorageDevice(devName string) bool {
	return strings.HasPrefix(devName, "hd") || strings.HasPrefix(devName, "sd")
}

func recognizeTypeDevice(devName string) string {
	if isSudoerUser() {
		output, err := exec.Command("file", "-s", filepath.Join("/dev", devName)).CombinedOutput()
		if err != nil {
			log.Fatal(err)
		}
		return strings.TrimRight(string(output), "\n")
	}
	return "/dev/" + devName
}

func isSudoerUser() bool {
	user, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	// If not superuser
	if user.Uid != "0" {
		err := exec.Command("sudo", "-n", "btrfs", "help").Run()
		return err == nil
	}

	return true
}
<commit_msg>small change<commit_after>package sysfs

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

// ListDevices prints a list of all storage devices attached to a linux machine
func ListDevicesCmd() {
	fmt.Printf("Current storage devices:\n\n")
	for _, dev := range findDevices() {
		fmt.Printf("%s\n", dev)
	}
	if !isSudoerUser() {
		fmt.Printf("\nPlease, rerun this command with sudo if you want to learn more information about these devices")
	}
	fmt.Printf("\n")
}

func findDevices() []string {
	var devices []string

	file, err := os.Open("/proc/partitions")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		device, err := getDeviceName(scanner.Text())
		if err == nil {
			devDesc := recognizeTypeDevice(device)
			devices = append(devices, devDesc)
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

	return devices
}

func getDeviceName(line string) (string, error) {
	parts := strings.Fields(line)
	if len(parts) >= 4 && isStorageDevice(parts[3]) {
		return parts[3], nil
	}
	return "", errors.New("Line does not contain any storage device")
}

func isStorageDevice(devName string) bool {
	return strings.HasPrefix(devName, "hd") || strings.HasPrefix(devName, "sd")
}

func recognizeTypeDevice(devName string) string {
	if isSudoerUser() {
		output, err := exec.Command("file", "-s", filepath.Join("/dev", devName)).CombinedOutput()
		if err != nil {
			log.Fatal(err)
		}
		return strings.TrimRight(string(output), "\n")
	}
	return filepath.Join("/dev/", devName)
}

func isSudoerUser() bool {
	user, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	// If not superuser
	if user.Uid != "0" {
		err := exec.Command("sudo", "-n", "btrfs", "help").Run()
		return err == nil
	}

	return true
}
<|endoftext|>


<commit_before>package plugins

import (
	"database/sql"
	"errors"
	"strings"
	"unicode"

	"github.com/belak/irc"
	"github.com/belak/seabird/bot"
	"github.com/jmoiron/sqlx"
)

func init() {
	bot.RegisterPlugin("phrases", NewPhrasesPlugin)
}

type PhrasesPlugin struct {
	db *sqlx.DB
}

type phrase struct {
	ID        int
	Key       string
	Value     string
	Submitter string
	Deleted   bool
}

func NewPhrasesPlugin(b *bot.Bot) (bot.Plugin, error) {
	b.LoadPlugin("db")
	p := &PhrasesPlugin{b.Plugins["db"].(*sqlx.DB)}

	b.CommandMux.Event("forget", p.forgetCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up a phrase",
	})

	b.CommandMux.Event("get", p.getCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up a phrase",
	})

	b.CommandMux.Event("give", p.giveCallback, &bot.HelpInfo{
		Usage:       "<key> <user>",
		Description: "Mentions a user with a given phrase",
	})

	b.CommandMux.Event("history", p.historyCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up history for a key",
	})

	b.CommandMux.Event("set", p.setCallback, &bot.HelpInfo{
		Usage:       "<key> <phrase>",
		Description: "Remembers a phrase",
	})

	return nil, nil
}

func (p *PhrasesPlugin) cleanedName(name string) string {
	return strings.TrimFunc(strings.ToLower(name), unicode.IsSpace)
}

func (p *PhrasesPlugin) getKey(key string) (*phrase, error) {
	row := &phrase{}
	if len(key) == 0 {
		return row, errors.New("No key provided")
	}

	err := p.db.Get(row, "SELECT * FROM phrases WHERE key=? ORDER BY id DESC LIMIT 1", key)
	if err == sql.ErrNoRows {
		return row, errors.New("No results for given key")
	} else if err != nil {
		return row, err
	} else if row.Deleted {
		return row, errors.New("Phrase was previously deleted")
	}

	return row, nil
}

func (p *PhrasesPlugin) forgetCallback(b *bot.Bot, m *irc.Message) {
	// Ensure there is already a key for this. Note that this
	// introduces a potential race condition, but it's not super
	// important.
	name := p.cleanedName(m.Trailing())
	_, err := p.getKey(name)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	row := phrase{
		Key:       name,
		Submitter: m.Prefix.Name,
		Deleted:   true,
	}

	if len(row.Key) == 0 {
		b.MentionReply(m, "No key supplied")
		return
	}

	_, err = p.db.Exec("INSERT INTO phrases (key, submitter, deleted) VALUES ($1, $2, $3)", row.Key, row.Submitter, row.Deleted)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "Forgot %s", name)
}

func (p *PhrasesPlugin) getCallback(b *bot.Bot, m *irc.Message) {
	row, err := p.getKey(m.Trailing())
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "%s", row.Value)
}

func (p *PhrasesPlugin) giveCallback(b *bot.Bot, m *irc.Message) {
	split := strings.SplitN(m.Trailing(), " ", 2)
	if len(split) < 2 {
		b.MentionReply(m, "Not enough args")
		return
	}

	row, err := p.getKey(split[1])
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.Reply(m, "%s: %s", split[0], row.Value)
}

func (p *PhrasesPlugin) historyCallback(b *bot.Bot, m *irc.Message) {
	rows := []phrase{}
	err := p.db.Select(&rows, "SELECT * FROM phrases WHERE key=? ORDER BY id DESC LIMIT 5", p.cleanedName(m.Trailing()))
	if err == sql.ErrNoRows {
		b.MentionReply(m, "No results for given key")
		return
	} else if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	for _, row := range rows {
		if row.Deleted {
			b.MentionReply(m, "%s deleted by %s", row.Key, row.Submitter)
		} else {
			b.MentionReply(m, "%s set by %s to %s", row.Key, row.Submitter, row.Value)
		}
	}
}

func (p *PhrasesPlugin) setCallback(b *bot.Bot, m *irc.Message) {
	split := strings.SplitN(m.Trailing(), " ", 2)
	if len(split) < 2 {
		b.MentionReply(m, "Not enough args")
		return
	}

	row := phrase{
		Key:       p.cleanedName(split[0]),
		Submitter: m.Prefix.Name,
		Value:     split[1],
	}

	if len(row.Key) == 0 {
		b.MentionReply(m, "No key supplied")
		return
	}

	_, err := p.db.Exec("INSERT INTO phrases (key, submitter, value) VALUES ($1, $2, $3)", row.Key, row.Submitter, row.Value)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "%s set to %s", row.Key, row.Value)
}
<commit_msg>phrases: fix some postgres issues<commit_after>package plugins

import (
	"database/sql"
	"errors"
	"strings"
	"unicode"

	"github.com/belak/irc"
	"github.com/belak/seabird/bot"
	"github.com/jmoiron/sqlx"
)

func init() {
	bot.RegisterPlugin("phrases", NewPhrasesPlugin)
}

type PhrasesPlugin struct {
	db *sqlx.DB
}

type phrase struct {
	ID        int
	Key       string
	Value     string
	Submitter string
	Deleted   bool
}

func NewPhrasesPlugin(b *bot.Bot) (bot.Plugin, error) {
	b.LoadPlugin("db")
	p := &PhrasesPlugin{b.Plugins["db"].(*sqlx.DB)}

	b.CommandMux.Event("forget", p.forgetCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up a phrase",
	})

	b.CommandMux.Event("get", p.getCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up a phrase",
	})

	b.CommandMux.Event("give", p.giveCallback, &bot.HelpInfo{
		Usage:       "<key> <user>",
		Description: "Mentions a user with a given phrase",
	})

	b.CommandMux.Event("history", p.historyCallback, &bot.HelpInfo{
		Usage:       "<key>",
		Description: "Look up history for a key",
	})

	b.CommandMux.Event("set", p.setCallback, &bot.HelpInfo{
		Usage:       "<key> <phrase>",
		Description: "Remembers a phrase",
	})

	return nil, nil
}

func (p *PhrasesPlugin) cleanedName(name string) string {
	return strings.TrimFunc(strings.ToLower(name), unicode.IsSpace)
}

func (p *PhrasesPlugin) getKey(key string) (*phrase, error) {
	row := &phrase{}
	if len(key) == 0 {
		return row, errors.New("No key provided")
	}

	err := p.db.Get(row, "SELECT * FROM phrases WHERE key=$1 ORDER BY id DESC LIMIT 1", key)
	if err == sql.ErrNoRows {
		return row, errors.New("No results for given key")
	} else if err != nil {
		return row, err
	} else if row.Deleted {
		return row, errors.New("Phrase was previously deleted")
	}

	return row, nil
}

func (p *PhrasesPlugin) forgetCallback(b *bot.Bot, m *irc.Message) {
	// Ensure there is already a key for this. Note that this
	// introduces a potential race condition, but it's not super
	// important.
	name := p.cleanedName(m.Trailing())
	_, err := p.getKey(name)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	row := phrase{
		Key:       name,
		Submitter: m.Prefix.Name,
		Deleted:   true,
	}

	if len(row.Key) == 0 {
		b.MentionReply(m, "No key supplied")
		return
	}

	_, err = p.db.Exec("INSERT INTO phrases (key, submitter, deleted) VALUES ($1, $2, $3)", row.Key, row.Submitter, row.Deleted)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "Forgot %s", name)
}

func (p *PhrasesPlugin) getCallback(b *bot.Bot, m *irc.Message) {
	row, err := p.getKey(m.Trailing())
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "%s", row.Value)
}

func (p *PhrasesPlugin) giveCallback(b *bot.Bot, m *irc.Message) {
	split := strings.SplitN(m.Trailing(), " ", 2)
	if len(split) < 2 {
		b.MentionReply(m, "Not enough args")
		return
	}

	row, err := p.getKey(split[1])
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.Reply(m, "%s: %s", split[0], row.Value)
}

func (p *PhrasesPlugin) historyCallback(b *bot.Bot, m *irc.Message) {
	rows := []phrase{}
	err := p.db.Select(&rows, "SELECT * FROM phrases WHERE key=$1 ORDER BY id DESC LIMIT 5", p.cleanedName(m.Trailing()))
	if err == sql.ErrNoRows {
		b.MentionReply(m, "No results for given key")
		return
	} else if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	for _, row := range rows {
		if row.Deleted {
			b.MentionReply(m, "%s deleted by %s", row.Key, row.Submitter)
		} else {
			b.MentionReply(m, "%s set by %s to %s", row.Key, row.Submitter, row.Value)
		}
	}
}

func (p *PhrasesPlugin) setCallback(b *bot.Bot, m *irc.Message) {
	split := strings.SplitN(m.Trailing(), " ", 2)
	if len(split) < 2 {
		b.MentionReply(m, "Not enough args")
		return
	}

	row := phrase{
		Key:       p.cleanedName(split[0]),
		Submitter: m.Prefix.Name,
		Value:     split[1],
	}

	if len(row.Key) == 0 {
		b.MentionReply(m, "No key supplied")
		return
	}

	_, err := p.db.Exec("INSERT INTO phrases (key, submitter, value) VALUES ($1, $2, $3)", row.Key, row.Submitter, row.Value)
	if err != nil {
		b.MentionReply(m, "%s", err.Error())
		return
	}

	b.MentionReply(m, "%s set to %s", row.Key, row.Value)
}
<|endoftext|>


<commit_before>/*
	Attar package provide simple way to get http user auth (via sessions and cookie).

	It use part of great Gorilla web toolkit, 'gorilla/sessions' package
	(http://github.com/gorilla/sessions).

	Usable example:
		package main

		import (
			"html/template"
			"net/http"

			"github.com/SpiritOfStallman/attar"
			"github.com/gorilla/mux"
		)

		// main page
		var mainPage = template.Must(template.New("").Parse(`

HELLO!

			</form>
			`))

		func mainPageHandler(res http.ResponseWriter, req *http.Request) {
			mainPage.Execute(res, nil)
		}

		// login page
		var loginPage = template.Must(template.New("").Parse(`

			<form id="login_form" action="/login" method="POST" style="padding-top:15%;">

user::qwerty

			<input type="text" name="login" placeholder="Login" autofocus>

			<input type="password" placeholder="Password" name="password">

			<input type="submit" value="LOGIN">
			</form>
			`))

		func loginPageHandler(res http.ResponseWriter, req *http.Request) {
			loginPage.Execute(res, nil)
		}

		// auth provider function
		func checkAuth(u, p string) bool {
			if u == "user" && p == "qwerty" {
				return true
			}
			return false
		}

		func main() {

			a := attar.New()

			a.SetAuthProvider(checkAuth)
			a.SetLoginRoute("/login")

			// set options, with session & cookie lifetime == 30 sec
			options := &attar.AttarOptions{
				Path:                       "/",
				MaxAge:                     30,
				HttpOnly:                   true,
				SessionName:                "test-session",
				SessionLifeTime:            30,
				SessionBindUseragent:       true,
				SessionBindUserHost:        true,
				LoginFormUserFieldName:     "login",
				LoginFormPasswordFieldName: "password",
			}
			a.SetAttarOptions(options)

			// create mux router
			router := mux.NewRouter()
			router.HandleFunc("/", mainPageHandler)
			router.HandleFunc("/login", loginPageHandler).Methods("GET")
			// set attar.AuthHandler as handler func
			// for check login POST data
			router.HandleFunc("/login", a.AuthHandler).Methods("POST")

			// set auth proxy function
			http.Handle("/", a.GlobalAuthProxy(router))

			// start net/httm server at 8080 port
			if err := http.ListenAndServe("127.0.0.1:8082", nil); err != nil {
				panic(err)
			}
		}

	For more information - look at the pkg doc.
*/
package attar

import (
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/sessions"
)

type Attar struct {
	authProviderFunc authProvider
	loginRoute       string
	cookieOptions    *AttarOptions
	cookieStore      *sessions.CookieStore
}

/*
	Primary attar options (except for basic settings also accommodates a
	'gorilla/sessions' options (http://www.gorillatoolkit.org/pkg/sessions#Options)).
*/
type AttarOptions struct {
	// 'gorilla/sessions' section:
	// description see on http://www.gorillatoolkit.org/pkg/sessions#Options
	// or source on github
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool

	// attar section:
	// name of cookie browser session
	SessionName     string // default: "attar-session"
	SessionLifeTime int    // default: 86400; in sec

	// bind browser useragent to cookie
	SessionBindUseragent bool

	// bind user IP addr to cookie
	SessionBindUserHost bool

	// html field names, to retrieve
	// user name and password from
	// login form
	LoginFormUserFieldName     string // default: "login"
	LoginFormPasswordFieldName string // default: "password"
}

/*
	Set attar options (*AttarOptions).
*/
func (a *Attar) SetAttarOptions(o *AttarOptions) {
	a.cookieOptions = o
}

/*
	Function for check auth session.
*/
func (a *Attar) GlobalAuthProxy(next http.Handler) http.HandlerFunc {
	return func(res http.ResponseWriter, req *http.Request) {
		if req.URL.Path == a.loginRoute {
			next.ServeHTTP(res, req)
			return
		}

		var cookieStore = a.cookieStore

		cookieStore.Options = &sessions.Options{
			Path:     a.cookieOptions.Path,
			Domain:   a.cookieOptions.Domain,
			MaxAge:   a.cookieOptions.MaxAge,
			Secure:   a.cookieOptions.Secure,
			HttpOnly: a.cookieOptions.HttpOnly,
		}

		session, err := cookieStore.Get(req, a.cookieOptions.SessionName)
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}

		currentTime := time.Now().Local()

		val, ok := session.Values["loginTime"]
		if !ok {
			http.Redirect(res, req, a.loginRoute, http.StatusFound)
			return
		}

		userLoginTime, err := time.Parse(time.RFC3339, val.(string))
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}

		if int(currentTime.Sub(userLoginTime).Seconds()) > a.cookieOptions.SessionLifeTime {
			http.Redirect(res, req, a.loginRoute, http.StatusFound)
			return
		}

		if a.cookieOptions.SessionBindUseragent {
			val, ok = session.Values["useragent"]
			if !ok {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}

			if req.UserAgent() != val.(string) {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}
		}

		if a.cookieOptions.SessionBindUserHost {
			val, ok = session.Values["userHost"]
			if !ok {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}

			if strings.Split(req.RemoteAddr, ":")[0] != val.(string) {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}
		}

		next.ServeHTTP(res, req)
	}
}

/*
	Auth handler, for grub login form data, and init cookie session.
*/
func (a *Attar) AuthHandler(res http.ResponseWriter, req *http.Request) {
	user := req.FormValue(a.cookieOptions.LoginFormUserFieldName)
	password := req.FormValue(a.cookieOptions.LoginFormPasswordFieldName)

	auth := a.authProviderFunc(user, password)
	if auth == true {
		var cookieStore = a.cookieStore

		session, err := cookieStore.Get(req, a.cookieOptions.SessionName)
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		currentTime := time.Now().Local()

		session.Values["user"] = req.FormValue(a.cookieOptions.LoginFormUserFieldName)
		session.Values["loginTime"] = currentTime.Format(time.RFC3339)

		// even if SessionBindUseragent or SessionBindUserHost is false -
		// this data save to cookie, for option change without
		// having to user relogin (and cookie re-get)
		session.Values["userHost"] = strings.Split(req.RemoteAddr, ":")[0]
		session.Values["useragent"] = req.UserAgent()

		session.Save(req, res)

		http.Redirect(res, req, "/", http.StatusFound)
	} else {
		http.Redirect(res, req, a.loginRoute, http.StatusFound)
		return
	}
}

/*
	Get path for login redirect.
*/
func (a *Attar) SetLoginRoute(r string) {
	a.loginRoute = r
}

/*
	Set 'gorilla/sessions' session cookie keys.

	For more information about NewCookieStore() refer
	to http://www.gorillatoolkit.org/pkg/sessions#NewCookieStore.
*/
func (a *Attar) CookieSessionKeys(authKey, encryptionKey []byte) {
	a.cookieStore = sessions.NewCookieStore(
		authKey,
		encryptionKey,
	)
}

// type for auth provider function
type authProvider (func(u, p string) bool)

/*
	Method for set "auth provider" function, and user verification.

	User functon must take 'user' and 'password' arguments, and return
	true (if user auth successfully) or false (if auth data false).

	Example of auth provider function:
		// user code
		func checkAuth(u, p string) bool {
			if u == "user" && p == "qwerty" {
				return true
			}
			return false
		}

	And define it:
		// user code
		a := attar.New()
		a.SetAuthProvider(checkAuth)
*/
func (a *Attar) SetAuthProvider(f authProvider) {
	a.authProviderFunc = f
}

/*
	Return Attar struct with default options.

	By default contain pre-set keys to 'gorilla/sessions' NewCookieStore
	func (provide in *Attar.CookieSessionKeys).
	It is not secure.
	Keys must be changed!

	For more information about NewCookieStore() refer
	to http://www.gorillatoolkit.org/pkg/sessions#NewCookieStore.

*/
func New() *Attar {
	return &Attar{
		// default options
		cookieOptions: &AttarOptions{
			SessionName:                "attar-session",
			SessionLifeTime:            86400,
			SessionBindUseragent:       true,
			SessionBindUserHost:        true,
			LoginFormUserFieldName:     "login",
			LoginFormPasswordFieldName: "password",
		},
		// use default keys is not secure! :)
		cookieStore: sessions.NewCookieStore(
			[]byte("261AD9502C583BD7D8AA03083598653B"),
			[]byte("E9F6FDFAC2772D33FC5C7B3D6E4DDAFF"),
		),
	}
}
<commit_msg>add SimpleAuthProvider<commit_after>/*
	Attar package provide simple way to get http user auth (via sessions and cookie).

	It use part of great Gorilla web toolkit, 'gorilla/sessions' package
	(http://github.com/gorilla/sessions).

	Usable example:
		package main

		import (
			"html/template"
			"net/http"

			"github.com/SpiritOfStallman/attar"
			"github.com/gorilla/mux"
		)

		// main page
		var mainPage = template.Must(template.New("").Parse(`

HELLO!

			</form>
			`))

		func mainPageHandler(res http.ResponseWriter, req *http.Request) {
			mainPage.Execute(res, nil)
		}

		// login page
		var loginPage = template.Must(template.New("").Parse(`

			<form id="login_form" action="/login" method="POST" style="padding-top:15%;">

user::qwerty

			<input type="text" name="login" placeholder="Login" autofocus>

			<input type="password" placeholder="Password" name="password">

			<input type="submit" value="LOGIN">
			</form>
			`))

		func loginPageHandler(res http.ResponseWriter, req *http.Request) {
			loginPage.Execute(res, nil)
		}

		// auth provider function
		func checkAuth(u, p string) bool {
			if u == "user" && p == "qwerty" {
				return true
			}
			return false
		}

		func main() {

			a := attar.New()

			a.SetAuthProvider(checkAuth)
			a.SetLoginRoute("/login")

			// set options, with session & cookie lifetime == 30 sec
			options := &attar.AttarOptions{
				Path:                       "/",
				MaxAge:                     30,
				HttpOnly:                   true,
				SessionName:                "test-session",
				SessionLifeTime:            30,
				SessionBindUseragent:       true,
				SessionBindUserHost:        true,
				LoginFormUserFieldName:     "login",
				LoginFormPasswordFieldName: "password",
			}
			a.SetAttarOptions(options)

			// create mux router
			router := mux.NewRouter()
			router.HandleFunc("/", mainPageHandler)
			router.HandleFunc("/login", loginPageHandler).Methods("GET")
			// set attar.AuthHandler as handler func
			// for check login POST data
			router.HandleFunc("/login", a.AuthHandler).Methods("POST")

			// set auth proxy function
			http.Handle("/", a.GlobalAuthProxy(router))

			// start net/httm server at 8080 port
			if err := http.ListenAndServe("127.0.0.1:8082", nil); err != nil {
				panic(err)
			}
		}

	For more information - look at the pkg doc.
*/
package attar

import (
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/sessions"
)

type Attar struct {
	authProviderFunc authProvider
	loginRoute       string
	cookieOptions    *AttarOptions
	cookieStore      *sessions.CookieStore
}

/*
	Primary attar options (except for basic settings also accommodates a
	'gorilla/sessions' options (http://www.gorillatoolkit.org/pkg/sessions#Options)).
*/
type AttarOptions struct {
	// 'gorilla/sessions' section:
	// description see on http://www.gorillatoolkit.org/pkg/sessions#Options
	// or source on github
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool

	// attar section:
	// name of cookie browser session
	SessionName     string // default: "attar-session"
	SessionLifeTime int    // default: 86400; in sec

	// bind browser useragent to cookie
	SessionBindUseragent bool

	// bind user IP addr to cookie
	SessionBindUserHost bool

	// html field names, to retrieve
	// user name and password from
	// login form
	LoginFormUserFieldName     string // default: "login"
	LoginFormPasswordFieldName string // default: "password"
}

/*
	Set attar options (*AttarOptions).
*/
func (a *Attar) SetAttarOptions(o *AttarOptions) {
	a.cookieOptions = o
}

/*
	Function for check auth session.
*/
func (a *Attar) GlobalAuthProxy(next http.Handler) http.HandlerFunc {
	return func(res http.ResponseWriter, req *http.Request) {
		if req.URL.Path == a.loginRoute {
			next.ServeHTTP(res, req)
			return
		}

		var cookieStore = a.cookieStore

		cookieStore.Options = &sessions.Options{
			Path:     a.cookieOptions.Path,
			Domain:   a.cookieOptions.Domain,
			MaxAge:   a.cookieOptions.MaxAge,
			Secure:   a.cookieOptions.Secure,
			HttpOnly: a.cookieOptions.HttpOnly,
		}

		session, err := cookieStore.Get(req, a.cookieOptions.SessionName)
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}

		currentTime := time.Now().Local()

		val, ok := session.Values["loginTime"]
		if !ok {
			http.Redirect(res, req, a.loginRoute, http.StatusFound)
			return
		}

		userLoginTime, err := time.Parse(time.RFC3339, val.(string))
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}

		if int(currentTime.Sub(userLoginTime).Seconds()) > a.cookieOptions.SessionLifeTime {
			http.Redirect(res, req, a.loginRoute, http.StatusFound)
			return
		}

		if a.cookieOptions.SessionBindUseragent {
			val, ok = session.Values["useragent"]
			if !ok {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}

			if req.UserAgent() != val.(string) {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}
		}

		if a.cookieOptions.SessionBindUserHost {
			val, ok = session.Values["userHost"]
			if !ok {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}

			if strings.Split(req.RemoteAddr, ":")[0] != val.(string) {
				http.Redirect(res, req, a.loginRoute, http.StatusFound)
				return
			}
		}

		next.ServeHTTP(res, req)
	}
}

/*
	Auth handler, for grub login form data, and init cookie session.
*/
func (a *Attar) AuthHandler(res http.ResponseWriter, req *http.Request) {
	user := req.FormValue(a.cookieOptions.LoginFormUserFieldName)
	password := req.FormValue(a.cookieOptions.LoginFormPasswordFieldName)

	auth := a.authProviderFunc(user, password)
	if auth == true {
		var cookieStore = a.cookieStore

		session, err := cookieStore.Get(req, a.cookieOptions.SessionName)
		if err != nil {
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		currentTime := time.Now().Local()

		session.Values["user"] = req.FormValue(a.cookieOptions.LoginFormUserFieldName)
		session.Values["loginTime"] = currentTime.Format(time.RFC3339)

		// even if SessionBindUseragent or SessionBindUserHost is false -
		// this data save to cookie, for option change without
		// having to user relogin (and cookie re-get)
		session.Values["userHost"] = strings.Split(req.RemoteAddr, ":")[0]
		session.Values["useragent"] = req.UserAgent()

		session.Save(req, res)

		http.Redirect(res, req, "/", http.StatusFound)
	} else {
		http.Redirect(res, req, a.loginRoute, http.StatusFound)
		return
	}
}

/*
	Get path for login redirect.
*/
func (a *Attar) SetLoginRoute(r string) {
	a.loginRoute = r
}

/*
	Set 'gorilla/sessions' session cookie keys.

	For more information about NewCookieStore() refer
	to http://www.gorillatoolkit.org/pkg/sessions#NewCookieStore.
*/
func (a *Attar) CookieSessionKeys(authKey, encryptionKey []byte) {
	a.cookieStore = sessions.NewCookieStore(
		authKey,
		encryptionKey,
	)
}

// type for auth provider function
type authProvider (func(u, p string) bool)

/*
	Method for set "auth provider" function, and user verification.

	User functon must take 'user' and 'password' arguments, and return
	true (if user auth successfully) or false (if auth data false).

	As alternative use preset attar auth provider functions (like
	attar.SimpleAuthProvider)

	Example of auth provider function:
		// user code
		func checkAuth(u, p string) bool {
			if u == "user" && p == "qwerty" {
				return true
			}
			return false
		}

	And define it:
		// user code
		a := attar.New()
		a.SetAuthProvider(checkAuth)
*/
func (a *Attar) SetAuthProvider(f authProvider) {
	a.authProviderFunc = f
}

/*
	User auth provider function, for simple user/password check.

	Example of usage:
		// users list based on map[user]password
		userList := map[string]string{
			"user":  "qwerty",
			"admin": "asdfgh",
		}

		a := attar.New()
		a.SetAuthProvider(a.SimpleAuthProvider(userList))
*/
func (a *Attar) SimpleAuthProvider(userlist map[string]string) authProvider {
	return func(u, p string) bool {
		pass, ok := userlist[u]
		if !ok {
			return false
		}
		if p != pass {
			return false
		}
		return true
	}
}

/*
	Return Attar struct with default options.

	By default contain pre-set keys to 'gorilla/sessions' NewCookieStore
	func (provide in *Attar.CookieSessionKeys).
	It is not secure.
	Keys must be changed!

	For more information about NewCookieStore() refer
	to http://www.gorillatoolkit.org/pkg/sessions#NewCookieStore.

*/
func New() *Attar {
	return &Attar{
		// default options
		cookieOptions: &AttarOptions{
			SessionName:                "attar-session",
			SessionLifeTime:            86400,
			SessionBindUseragent:       true,
			SessionBindUserHost:        true,
			LoginFormUserFieldName:     "login",
			LoginFormPasswordFieldName: "password",
		},
		// use default keys is not secure! :)
		cookieStore: sessions.NewCookieStore(
			[]byte("261AD9502C583BD7D8AA03083598653B"),
			[]byte("E9F6FDFAC2772D33FC5C7B3D6E4DDAFF"),
		),
	}
}
<|endoftext|>