<commit_before>/*
Copyright 2015 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

package web

import (
	"archive/zip"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
	"github.com/kardianos/osext"
)

// relative path to static assets. this is useful during development.
var debugAssetsPath string

// NewStaticFileSystem returns the initialized implementation of http.FileSystem
// interface which can be used to serve Teleport Proxy Web UI
//
// If 'debugMode' is true, it will load the web assets from the same git repo
// directory where the executable is, otherwise it will load them from the embedded
// zip archive.
//
func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) {
	if debugMode {
		assetsToCheck := []string{"index.html", "/app"}

		if debugAssetsPath == "" {
			exePath, err := osext.ExecutableFolder()
			if err != nil {
				return nil, trace.Wrap(err)
			}
			debugAssetsPath = path.Join(exePath, "../web/dist")
		}

		for _, af := range assetsToCheck {
			_, err := os.Stat(filepath.Join(debugAssetsPath, af))
			if err != nil {
				return nil, trace.Wrap(err)
			}
		}
		log.Infof("[Web] Using filesystem for serving web assets: %s", debugAssetsPath)
		return http.Dir(debugAssetsPath), nil
	}

	// otherwise, lets use the zip archive attached to the executable:
	return loadZippedExeAssets()
}

// isDebugMode determines if teleport is running in a "debug" mode.
// It looks at DEBUG environment variable
func isDebugMode() bool {
	v, err := strconv.ParseBool(os.Getenv("DEBUG"))
	return v && err == nil
}

// LoadWebResources returns a filesystem implementation compatible
// with http.Serve.
//
// The "filesystem" is served from a zip file attached at the end of
// the executable
//
func loadZippedExeAssets() (ResourceMap, error) {
	// open ourselves (teleport binary) for reading:
	// NOTE: the file stays open to serve future Read() requests
	myExe, err := osext.Executable()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return readZipArchive(myExe)
}

func readZipArchive(archivePath string) (ResourceMap, error) {
	file, err := os.Open(archivePath)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// feed the binary into the zip reader and enumerate all files
	// found in the attached zip file:
	info, err := file.Stat()
	if err != nil {
		log.Fatal(err)
	}
	zreader, err := zip.NewReader(file, info.Size())
	if err != nil {
		log.Fatal(err)
	}
	entries := make(ResourceMap)
	for _, file := range zreader.File {
		if file.FileInfo().IsDir() {
			continue
		}
		entries[file.Name] = file
	}
	// no entries found?
	if len(entries) == 0 {
		return nil, trace.Wrap(os.ErrInvalid)
	}
	return entries, nil
}

// resource struct implements http.File interface on top of zip.File object
type resource struct {
	reader io.ReadCloser
	file   *zip.File
}

func (rsc *resource) Read(p []byte) (n int, err error) {
	return rsc.reader.Read(p)
}

func (rsc *resource) Seek(offset int64, whence int) (int64, error) {
	return offset, nil
}

func (rsc *resource) Readdir(count int) ([]os.FileInfo, error) {
	return nil, trace.Wrap(os.ErrPermission)
}

func (rsc *resource) Stat() (os.FileInfo, error) {
	return rsc.file.FileInfo(), nil
}

func (rsc *resource) Close() (err error) {
	log.Debugf("[web] zip::Close(%s)", rsc.file.FileInfo().Name())
	return rsc.reader.Close()
}

type ResourceMap map[string]*zip.File

func (rm ResourceMap) Open(name string) (http.File, error) {
	log.Debugf("[web] GET zip:%s", name)
	f, ok := rm[strings.Trim(name, "/")]
	if !ok {
		return nil, trace.Wrap(os.ErrNotExist)
	}
	reader, err := f.Open()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &resource{reader, f}, nil
}
<commit_msg>Nicer error message on missing ZIP assets.<commit_after>/*
Copyright 2015 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

package web

import (
	"archive/zip"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
	"github.com/kardianos/osext"
)

// relative path to static assets. this is useful during development.
var debugAssetsPath string

// NewStaticFileSystem returns the initialized implementation of http.FileSystem
// interface which can be used to serve Teleport Proxy Web UI
//
// If 'debugMode' is true, it will load the web assets from the same git repo
// directory where the executable is, otherwise it will load them from the embedded
// zip archive.
//
func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) {
	if debugMode {
		assetsToCheck := []string{"index.html", "/app"}

		if debugAssetsPath == "" {
			exePath, err := osext.ExecutableFolder()
			if err != nil {
				return nil, trace.Wrap(err)
			}
			debugAssetsPath = path.Join(exePath, "../web/dist")
		}

		for _, af := range assetsToCheck {
			_, err := os.Stat(filepath.Join(debugAssetsPath, af))
			if err != nil {
				return nil, trace.Wrap(err)
			}
		}
		log.Infof("[Web] Using filesystem for serving web assets: %s", debugAssetsPath)
		return http.Dir(debugAssetsPath), nil
	}

	// otherwise, lets use the zip archive attached to the executable:
	return loadZippedExeAssets()
}

// isDebugMode determines if teleport is running in a "debug" mode.
// It looks at DEBUG environment variable
func isDebugMode() bool {
	v, err := strconv.ParseBool(os.Getenv("DEBUG"))
	return v && err == nil
}

// LoadWebResources returns a filesystem implementation compatible
// with http.Serve.
//
// The "filesystem" is served from a zip file attached at the end of
// the executable
//
func loadZippedExeAssets() (ResourceMap, error) {
	// open ourselves (teleport binary) for reading:
	// NOTE: the file stays open to serve future Read() requests
	myExe, err := osext.Executable()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return readZipArchive(myExe)
}

func readZipArchive(archivePath string) (ResourceMap, error) {
	file, err := os.Open(archivePath)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// feed the binary into the zip reader and enumerate all files
	// found in the attached zip file:
	info, err := file.Stat()
	if err != nil {
		log.Fatal(err)
	}
	zreader, err := zip.NewReader(file, info.Size())
	if err != nil {
		// this often happens when teleport is launched without the web assets
		// zip file attached to the binary. for launching it in such mode
		// set DEBUG environment variable to 1
		log.Fatalf("Failed reading web assets from the binary. %v", err)
	}
	entries := make(ResourceMap)
	for _, file := range zreader.File {
		if file.FileInfo().IsDir() {
			continue
		}
		entries[file.Name] = file
	}
	// no entries found?
	if len(entries) == 0 {
		return nil, trace.Wrap(os.ErrInvalid)
	}
	return entries, nil
}

// resource struct implements http.File interface on top of zip.File object
type resource struct {
	reader io.ReadCloser
	file   *zip.File
}

func (rsc *resource) Read(p []byte) (n int, err error) {
	return rsc.reader.Read(p)
}

func (rsc *resource) Seek(offset int64, whence int) (int64, error) {
	return offset, nil
}

func (rsc *resource) Readdir(count int) ([]os.FileInfo, error) {
	return nil, trace.Wrap(os.ErrPermission)
}

func (rsc *resource) Stat() (os.FileInfo, error) {
	return rsc.file.FileInfo(), nil
}

func (rsc *resource) Close() (err error) {
	log.Debugf("[web] zip::Close(%s)", rsc.file.FileInfo().Name())
	return rsc.reader.Close()
}

type ResourceMap map[string]*zip.File

func (rm ResourceMap) Open(name string) (http.File, error) {
	log.Debugf("[web] GET zip:%s", name)
	f, ok := rm[strings.Trim(name, "/")]
	if !ok {
		return nil, trace.Wrap(os.ErrNotExist)
	}
	reader, err := f.Open()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &resource{reader, f}, nil
}
<|endoftext|>


<commit_before>package convox

import (
	"errors"
	"fmt"
	"time"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func ResourceConvoxResourceLink(clientUnpacker ClientUnpacker) *schema.Resource {
	return &schema.Resource{
		Schema: map[string]*schema.Schema{
			"rack": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"app_name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"resource_name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
		Read:   ResourceConvoxResourceLinkReadFactory(clientUnpacker),
		Create: ResourceConvoxResourceLinkCreateFactory(clientUnpacker),
		Delete: ResourceConvoxResourceLinkDeleteFactory(clientUnpacker),
	}
}

func ResourceConvoxResourceLinkCreateFactory(clientUnpacker ClientUnpacker) schema.CreateFunc {

	return func(d *schema.ResourceData, meta interface{}) error {
		if clientUnpacker == nil {
			return errors.New("clientUnpacker is required")
		}

		c, err := clientUnpacker(d, meta)
		if err != nil {
			return fmt.Errorf("Error unpacking client in CreateFunc: %s", err.Error())
		}

		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		_, err = c.CreateLink(app, resourceName)
		if err != nil {
			return fmt.Errorf("Error calling CreateLink(%s, %s): %s", app, resourceName, err.Error())
		}

		stateConf := &resource.StateChangeConf{
			Pending: []string{"updating"},
			Target:  []string{"running"},
			Refresh: readResourceStateFunc(c, resourceName),
			Timeout: 10 * time.Minute,
			Delay:   5 * time.Second,
		}

		if _, err = stateConf.WaitForState(); err != nil {
			return fmt.Errorf(
				"Error waiting for resource link to be created: %s", err)
		}

		d.SetId(fmt.Sprintf("%s-%s", resourceName, app))

		return nil
	}
}

func ResourceConvoxResourceLinkDeleteFactory(clientUnpacker ClientUnpacker) schema.DeleteFunc {
	return func(d *schema.ResourceData, meta interface{}) error {
		if clientUnpacker == nil {
			return errors.New("clientUnpacker is required")
		}

		c, err := clientUnpacker(d, meta)
		if err != nil {
			return fmt.Errorf("Error unpacking client in DeleteFunc: %s", err.Error())
		}

		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		_, err = c.DeleteLink(app, resourceName)
		if err != nil {
			return fmt.Errorf("Error calling DeleteLink(%s, %s): %s", app, resourceName, err.Error())
		}

		stateConf := &resource.StateChangeConf{
			Pending: []string{"updating"},
			Target:  []string{"running"},
			Refresh: readResourceStateFunc(c, resourceName),
			Timeout: 10 * time.Minute,
			Delay:   5 * time.Second,
		}

		if _, err = stateConf.WaitForState(); err != nil {
			return fmt.Errorf(
				"Error waiting for resource link to be deleted: %s", err)
		}

		return nil
	}
}

func ResourceConvoxResourceLinkReadFactory(clientUnpacker ClientUnpacker) schema.ReadFunc {
	return func(d *schema.ResourceData, meta interface{}) error {
		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		d.SetId(fmt.Sprintf("%s-%s", resourceName, app))

		return nil
	}
}
<commit_msg>coordinate creates a bit<commit_after>package convox

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func ResourceConvoxResourceLink(clientUnpacker ClientUnpacker) *schema.Resource {
	return &schema.Resource{
		Schema: map[string]*schema.Schema{
			"rack": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"app_name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"resource_name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
		Read:   ResourceConvoxResourceLinkReadFactory(clientUnpacker),
		Create: ResourceConvoxResourceLinkCreateFactory(clientUnpacker),
		Delete: ResourceConvoxResourceLinkDeleteFactory(clientUnpacker),
	}
}

func ResourceConvoxResourceLinkCreateFactory(clientUnpacker ClientUnpacker) schema.CreateFunc {
	var createFunc schema.CreateFunc
	createFunc = func(d *schema.ResourceData, meta interface{}) error {
		if clientUnpacker == nil {
			return errors.New("clientUnpacker is required")
		}

		c, err := clientUnpacker(d, meta)
		if err != nil {
			return fmt.Errorf("Error unpacking client in CreateFunc: %s", err.Error())
		}

		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		_, err = c.CreateLink(app, resourceName)
		if err != nil {
			if strings.Contains(err.Error(), "UPDATE_IN_PROGRESS") {
				if err := waitForRunning(c, resourceName); err != nil {
					return fmt.Errorf(
						"Error waiting for resource link API to become available: %s", err)
				}
				return createFunc(d, meta)
			}
			return fmt.Errorf("Error calling CreateLink(%s, %s): %s", app, resourceName, err.Error())
		}

		if err := waitForRunning(c, resourceName); err != nil {
			return fmt.Errorf(
				"Error waiting for resource link to be created: %s", err)
		}

		d.SetId(fmt.Sprintf("%s-%s", resourceName, app))

		return nil
	}

	return createFunc
}

func ResourceConvoxResourceLinkDeleteFactory(clientUnpacker ClientUnpacker) schema.DeleteFunc {
	return func(d *schema.ResourceData, meta interface{}) error {
		if clientUnpacker == nil {
			return errors.New("clientUnpacker is required")
		}

		c, err := clientUnpacker(d, meta)
		if err != nil {
			return fmt.Errorf("Error unpacking client in DeleteFunc: %s", err.Error())
		}

		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		_, err = c.DeleteLink(app, resourceName)
		if err != nil {
			return fmt.Errorf("Error calling DeleteLink(%s, %s): %s", app, resourceName, err.Error())
		}

		if err := waitForRunning(c, resourceName); err != nil {
			return fmt.Errorf(
				"Error waiting for resource link to be deleted: %s", err)
		}

		return nil
	}
}

func waitForRunning(c Client, resourceName string) error {
	stateConf := &resource.StateChangeConf{
		Pending: []string{"updating"},
		Target:  []string{"running"},
		Refresh: readResourceStateFunc(c, resourceName),
		Timeout: 10 * time.Minute,
		Delay:   5 * time.Second,
	}

	if _, err := stateConf.WaitForState(); err != nil {
		return err
	}

	return nil
}

func ResourceConvoxResourceLinkReadFactory(clientUnpacker ClientUnpacker) schema.ReadFunc {
	return func(d *schema.ResourceData, meta interface{}) error {
		resourceName := d.Get("resource_name").(string)
		app := d.Get("app_name").(string)

		d.SetId(fmt.Sprintf("%s-%s", resourceName, app))

		return nil
	}
}
<|endoftext|>


<commit_before>package machineprovision

import (
	name2 "github.com/rancher/wrangler/pkg/name"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

const (
	InfraMachineGroup   = "rke.cattle.io/infra-machine-group"
	InfraMachineVersion = "rke.cattle.io/infra-machine-version"
	InfraMachineKind    = "rke.cattle.io/infra-machine-kind"
	InfraMachineName    = "rke.cattle.io/infra-machine-name"
)

func getJobName(name string) string {
	return name2.SafeConcatName(name, "machine", "provision")
}

func (h *handler) objects(ready bool, typeMeta metav1.Type, meta metav1.Object, args driverArgs) ([]runtime.Object, error) {
	machineGVK := schema.FromAPIVersionAndKind(typeMeta.GetAPIVersion(), typeMeta.GetKind())
	saName := getJobName(meta.GetName())
	secret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      args.StateSecretName,
			Namespace: meta.GetNamespace(),
		},
		Type: "rke.cattle.io/machine-state",
	}

	if ready {
		return []runtime.Object{secret}, nil
	}

	if args.BootstrapOptional && args.BootstrapSecretName == "" {
		args.BootstrapSecretName = "not-found"
	}

	sa := &corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
	}
	role := &rbacv1.Role{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Rules: []rbacv1.PolicyRule{
			{
				Verbs:         []string{"get", "update"},
				APIGroups:     []string{""},
				Resources:     []string{"secrets"},
				ResourceNames: []string{secret.Name},
			},
		},
	}
	rb := &rbacv1.RoleBinding{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Subjects: []rbacv1.Subject{
			{
				Kind:      "ServiceAccount",
				Name:      saName,
				Namespace: meta.GetNamespace(),
			},
		},
		RoleRef: rbacv1.RoleRef{
			APIGroup: rbacv1.GroupName,
			Kind:     "Role",
			Name:     saName,
		},
	}
	job := &batchv1.Job{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Spec: batchv1.JobSpec{
			BackoffLimit: &[]int32{0}[0],
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						InfraMachineGroup:   machineGVK.Group,
						InfraMachineVersion: machineGVK.Version,
						InfraMachineKind:    machineGVK.Kind,
						InfraMachineName:    meta.GetName(),
					},
				},
				Spec: corev1.PodSpec{
					Volumes: []corev1.Volume{
						{
							Name: "bootstrap",
							VolumeSource: corev1.VolumeSource{
								Secret: &corev1.SecretVolumeSource{
									SecretName:  args.BootstrapSecretName,
									DefaultMode: &[]int32{0700}[0],
									Optional:    &args.BootstrapOptional,
								},
							},
						},
					},
					RestartPolicy: corev1.RestartPolicyNever,
					Containers: []corev1.Container{
						{
							Name:            "machine",
							Image:           args.ImageName,
							ImagePullPolicy: args.ImagePullPolicy,
							Args:            args.Args,
							EnvFrom: []corev1.EnvFromSource{
								{
									SecretRef: &corev1.SecretEnvSource{
										LocalObjectReference: corev1.LocalObjectReference{
											Name: args.EnvSecret.Name,
										},
									},
								},
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "bootstrap",
									ReadOnly:  false,
									MountPath: "/run/secrets/machine",
								},
							},
						},
					},
					ServiceAccountName: saName,
				},
			},
		},
	}

	return []runtime.Object{
		args.EnvSecret,
		secret,
		sa,
		role,
		rb,
		job,
	}, nil
}
<commit_msg>Allow additional CAs to be inserted into the machine provisioning pods<commit_after>package machineprovision

import (
	name2 "github.com/rancher/wrangler/pkg/name"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

const (
	InfraMachineGroup   = "rke.cattle.io/infra-machine-group"
	InfraMachineVersion = "rke.cattle.io/infra-machine-version"
	InfraMachineKind    = "rke.cattle.io/infra-machine-kind"
	InfraMachineName    = "rke.cattle.io/infra-machine-name"
)

func getJobName(name string) string {
	return name2.SafeConcatName(name, "machine", "provision")
}

func (h *handler) objects(ready bool, typeMeta metav1.Type, meta metav1.Object, args driverArgs) ([]runtime.Object, error) {
	machineGVK := schema.FromAPIVersionAndKind(typeMeta.GetAPIVersion(), typeMeta.GetKind())
	saName := getJobName(meta.GetName())
	secret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      args.StateSecretName,
			Namespace: meta.GetNamespace(),
		},
		Type: "rke.cattle.io/machine-state",
	}

	if ready {
		return []runtime.Object{secret}, nil
	}

	if args.BootstrapOptional && args.BootstrapSecretName == "" {
		args.BootstrapSecretName = "not-found"
	}

	sa := &corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
	}
	role := &rbacv1.Role{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Rules: []rbacv1.PolicyRule{
			{
				Verbs:         []string{"get", "update"},
				APIGroups:     []string{""},
				Resources:     []string{"secrets"},
				ResourceNames: []string{secret.Name},
			},
		},
	}
	rb := &rbacv1.RoleBinding{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Subjects: []rbacv1.Subject{
			{
				Kind:      "ServiceAccount",
				Name:      saName,
				Namespace: meta.GetNamespace(),
			},
		},
		RoleRef: rbacv1.RoleRef{
			APIGroup: rbacv1.GroupName,
			Kind:     "Role",
			Name:     saName,
		},
	}
	job := &batchv1.Job{
		ObjectMeta: metav1.ObjectMeta{
			Name:      saName,
			Namespace: meta.GetNamespace(),
		},
		Spec: batchv1.JobSpec{
			BackoffLimit: &[]int32{0}[0],
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						InfraMachineGroup:   machineGVK.Group,
						InfraMachineVersion: machineGVK.Version,
						InfraMachineKind:    machineGVK.Kind,
						InfraMachineName:    meta.GetName(),
					},
				},
				Spec: corev1.PodSpec{
					Volumes: []corev1.Volume{
						{
							Name: "bootstrap",
							VolumeSource: corev1.VolumeSource{
								Secret: &corev1.SecretVolumeSource{
									SecretName:  args.BootstrapSecretName,
									DefaultMode: &[]int32{0700}[0],
									Optional:    &args.BootstrapOptional,
								},
							},
						},
						{
							Name: "tls-ca-additional-volume",
							VolumeSource: corev1.VolumeSource{
								Secret: &corev1.SecretVolumeSource{
									SecretName:  "tls-ca-additional-volume",
									DefaultMode: &[]int32{0400}[0],
									Optional:    &[]bool{true}[0],
								},
							},
						},
					},
					RestartPolicy: corev1.RestartPolicyNever,
					Containers: []corev1.Container{
						{
							Name:            "machine",
							Image:           args.ImageName,
							ImagePullPolicy: args.ImagePullPolicy,
							Args:            args.Args,
							EnvFrom: []corev1.EnvFromSource{
								{
									SecretRef: &corev1.SecretEnvSource{
										LocalObjectReference: corev1.LocalObjectReference{
											Name: args.EnvSecret.Name,
										},
									},
								},
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "bootstrap",
									ReadOnly:  false,
									MountPath: "/run/secrets/machine",
								},
								{
									Name:      "tls-ca-additional-volume",
									ReadOnly:  true,
									MountPath: "/etc/ssl/certs/ca-additional.pem",
									SubPath:   "ca-additional.pem",
								},
							},
						},
					},
					ServiceAccountName: saName,
				},
			},
		},
	}

	return []runtime.Object{
		args.EnvSecret,
		secret,
		sa,
		role,
		rb,
		job,
	}, nil
}
<|endoftext|>


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

package commands

import (
	"go/build"
	"os"
	"os/exec"
	"strings"
	"syscall"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"

	"nvim-go/gb"
	"nvim-go/nvim"
)

func init() {
	plugin.HandleCommand("Gobuild", &plugin.CommandOptions{Eval: "expand('%:p:h')"}, Build)
}

func cmdBuild(v *vim.Vim, dir string) {
	go Build(v, dir)
}

// Build building the current buffer's package use compile tool that determined from the directory structure.
func Build(v *vim.Vim, dir string) error {
	defer gb.WithGoBuildForPath(dir)()
	var (
		b vim.Buffer
		w vim.Window
	)

	p := v.NewPipeline()
	p.CurrentBuffer(&b)
	p.CurrentWindow(&w)
	if err := p.Wait(); err != nil {
		return nvim.Echoerr(v, err)
	}

	var compiler string
	buildDir := strings.Split(build.Default.GOPATH, ":")[0]
	if buildDir == os.Getenv("GOPATH") {
		compiler = "go"
	} else {
		compiler = "gb"
	}

	cmd := exec.Command(compiler, "build")
	cmd.Dir = buildDir
	out, _ := cmd.CombinedOutput()
	cmd.Run()

	s, _ := cmd.ProcessState.Sys().(syscall.WaitStatus)
	if s.ExitStatus() > 0 {
		loclist := nvim.ParseError(v, string(out), dir)
		if err := nvim.SetLoclist(p, loclist); err != nil {
			return nvim.Echoerr(v, err)
		}
		return nvim.OpenLoclist(p, w, loclist, true)
	}

	return nvim.Echohl(v, "GoBuild: ", "Function", "SUCCESS")
}
<commit_msg>Fix cmd.Dir to current vim working directory for error list<commit_after>// Copyright 2016 Koichi Shiraishi. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package commands

import (
	"go/build"
	"os"
	"os/exec"
	"strings"
	"syscall"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"

	"nvim-go/gb"
	"nvim-go/nvim"
	"nvim-go/pkgs"
)

func init() {
	plugin.HandleCommand("Gobuild", &plugin.CommandOptions{Eval: "expand('%:p:h')"}, Build)
}

func cmdBuild(v *vim.Vim, dir string) {
	go Build(v, dir)
}

// Build building the current buffer's package use compile tool that determined from the directory structure.
func Build(v *vim.Vim, dir string) error {
	defer gb.WithGoBuildForPath(dir)()
	var (
		b vim.Buffer
		w vim.Window
	)

	p := v.NewPipeline()
	p.CurrentBuffer(&b)
	p.CurrentWindow(&w)
	if err := p.Wait(); err != nil {
		return nvim.Echoerr(v, err)
	}

	var compiler string
	buildDir := strings.Split(build.Default.GOPATH, ":")[0]
	if buildDir == os.Getenv("GOPATH") {
		compiler = "go"
	} else {
		compiler = "gb"
	}

	rootDir := pkgs.FindVcsDir(dir)

	cmd := exec.Command(compiler, "build")
	cmd.Dir = rootDir
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nvim.Echoerr(v, err)
	}

	cmd.Run()

	s, _ := cmd.ProcessState.Sys().(syscall.WaitStatus)
	if s.ExitStatus() > 0 {
		loclist := nvim.ParseError(v, string(out), dir)
		if err := nvim.SetLoclist(p, loclist); err != nil {
			return nvim.Echoerr(v, err)
		}
		return nvim.OpenLoclist(p, w, loclist, true)
	}

	return nvim.Echohl(v, "GoBuild: ", "Function", "SUCCESS")
}
<|endoftext|>


<commit_before>package scp

import (
	"github.com/viant/toolbox"
	"github.com/viant/toolbox/storage"
	"strings"
	"time"
)

type object struct {
	*storage.AbstractObject
	source           interface{}
	url              string
	name             string
	owner            string
	group            string
	size             string
	modificationTime time.Time
	day              string
	month            string
	year             string
	hour             string
	isDirectory      bool
	permission       string
}

//URL return storage URL
func (i *object) URL() string {
	if strings.Contains(i.url, i.name) {
		return i.url
	}
	return toolbox.URLPathJoin(i.url, i.name)
}

//Type returns storage type  StorageObjectFolderType or StorageObjectContentType
func (i *object) Type() int {
	if strings.Contains(i.permission, "d") {
		return storage.StorageObjectFolderType
	}
	return storage.StorageObjectContentType
}

//IsFolder returns true if object is a folder
func (i *object) IsFolder() bool {
	return i.Type() == storage.StorageObjectFolderType
}

//IsContent returns true if object is a file
func (i *object) IsContent() bool {
	return i.Type() == storage.StorageObjectContentType
}

//LastModified returns last modification time
func (i *object) LastModified() *time.Time {
	dateTime := i.year + " " + i.month + " " + i.day + " " + i.hour
	layout := toolbox.DateFormatToLayout("yyyy MMM ddd HH:mm:s")
	result, err := time.Parse(layout, dateTime)
	if err != nil {
		return nil
	}
	return &result

}

//Size returns content size
func (i *object) Size() int64 {
	return int64(toolbox.AsInt(i.size))
}

//Wrap wraps source storage object
func (i *object) Wrap(source interface{}) {
	i.source = source
}

//Unwrap unwraps source storage object into provided target.
func (i *object) Unwrap(target interface{}) error {
	if result, ok := target.(**object); ok {
		*result = i
	}
	return nil
}

//newObject creates a new gc storage object
func newStorageObject(url string, objectType int, source interface{}, lastModified *time.Time, size int64) storage.Object {
	abstract := storage.NewAbstractStorageObject(url, source, objectType, lastModified, size)
	result := &object{
		AbstractObject: abstract,
	}
	result.AbstractObject.Object = result
	return result
}
<commit_msg>patched file info on linux<commit_after>package scp

import (
	"github.com/viant/toolbox"
	"github.com/viant/toolbox/storage"
	"strings"
	"time"
)

type object struct {
	*storage.AbstractObject
	source           interface{}
	url              string
	name             string
	owner            string
	group            string
	size             string
	modificationTime *time.Time
	date 			 string
	time 			 string
	timezone		 string
	day              string
	month            string
	year             string
	hour             string
	isDirectory      bool
	permission       string
}

//URL return storage URL
func (i *object) URL() string {
	if strings.Contains(i.url, i.name) {
		return i.url
	}
	return toolbox.URLPathJoin(i.url, i.name)
}

//Type returns storage type  StorageObjectFolderType or StorageObjectContentType
func (i *object) Type() int {
	if strings.Contains(i.permission, "d") {
		return storage.StorageObjectFolderType
	}
	return storage.StorageObjectContentType
}

//IsFolder returns true if object is a folder
func (i *object) IsFolder() bool {
	return i.Type() == storage.StorageObjectFolderType
}

//IsContent returns true if object is a file
func (i *object) IsContent() bool {
	return i.Type() == storage.StorageObjectContentType
}

//LastModified returns last modification time
func (i *object) LastModified() *time.Time {
	if i.modificationTime != nil {
		return i.modificationTime
	}
	var dateTime, layout string
	if i.date != "" {
		timeLen := len(i.time)
		if timeLen > 12 {
			i.time = string(i.time[:12])
		}
		dateTime = i.date + " " + i.time + " " + i.timezone
		layout = toolbox.DateFormatToLayout("yyyy-MM-dd HH:mm:ss.SSS ZZ")

	} else {

		dateTime = i.year + " " + i.month + " " + i.day + " " + i.hour
		layout = toolbox.DateFormatToLayout("yyyy MMM ddd HH:mm:s")
	}

	result, err := time.Parse(layout, dateTime)
	if err != nil {
		return nil
	}
	i.modificationTime = &result
	return i.modificationTime

}

//Size returns content size
func (i *object) Size() int64 {
	return int64(toolbox.AsInt(i.size))
}

//Wrap wraps source storage object
func (i *object) Wrap(source interface{}) {
	i.source = source
}

//Unwrap unwraps source storage object into provided target.
func (i *object) Unwrap(target interface{}) error {
	if result, ok := target.(**object); ok {
		*result = i
	}
	return nil
}

//newObject creates a new gc storage object
func newStorageObject(url string, objectType int, source interface{}, lastModified *time.Time, size int64) storage.Object {
	abstract := storage.NewAbstractStorageObject(url, source, objectType, lastModified, size)
	result := &object{
		AbstractObject: abstract,
	}
	result.AbstractObject.Object = result
	return result
}
<|endoftext|>


<commit_before>package libcoap

/*
#cgo LDFLAGS: -lcoap-3-openssl
#include <coap3/coap.h>
#include "callback.h"
*/
import "C"
import "errors"
import "unsafe"
import "strings"
import log "github.com/sirupsen/logrus"
import cache "github.com/patrickmn/go-cache"

// across invocations, sessions are not 'eq'
type MethodHandler func(*Context, *Resource, *Session, *Pdu, *[]byte, *string, *Pdu)

type EventHandler func(*Session, Event)

type EndPoint struct {
    ptr *C.coap_endpoint_t
}

type Event int
const (
    EventSessionDisconnected Event = C.COAP_EVENT_DTLS_CLOSED
    EventSessionConnected    Event = C.COAP_EVENT_DTLS_CONNECTED
    EventSessionRenegotiate  Event = C.COAP_EVENT_DTLS_RENEGOTIATE
    EventSessionError        Event = C.COAP_EVENT_DTLS_ERROR
)

func (context *Context) ContextSetPSK(identity string, key []byte) {
    cid := C.CString(identity)
    defer C.free(unsafe.Pointer(cid))

    C.coap_context_set_psk(context.ptr,
                           cid,
                           (*C.uint8_t)(&key[0]),
                           C.size_t(len(key)))
}

//export export_method_handler
func export_method_handler(rsrc  *C.coap_resource_t,
                           sess  *C.coap_session_t,
                           req   *C.coap_pdu_t,
                           query *C.coap_string_t,
                           resp  *C.coap_pdu_t) {
    ctx := C.coap_session_get_context(sess)
    if ctx == nil {
        return
    }
    context, ok := contexts[ctx]
    if !ok {
        return
    }
    resource, ok := resources[rsrc]
    if !ok {
        return
    }
    blockSize := resource.GetBlockSize()
    isQBlock2 := resource.IsQBlock2()

    // Handle observe :
    // In case of observation response (or notification), original 'request' from libcoap is NULL
    // In order to handle request with handleGet(), it is necessary to re-create equest
    // First, initialize request from response to re-use some data.
    is_observe := false
    if resource.IsNotification() {
        is_observe = true
        resource.SetIsNotification(false)
    }
    tok := C.coap_get_token_from_request_pdu(req)

    session, ok := sessions[sess]
    if !ok {
		return
    }

    request, err := req.toGo()
    if err != nil {
        return
    }

    // Handle observe:
    // Set request.uri-path from resource.uri-path (so that it can by-pass uri-path check inside PrefixFilter)
    var uri []string
    uri_path := resource.UriPath()
    hb_uri_path := request.PathString()
    if strings.Contains(hb_uri_path, "/hb") {
        uri_path = hb_uri_path
    }
    if is_observe {
        uriFilterList := GetUriFilterByKey(uri_path)
        for _, uriFilter := range uriFilterList {
            uriQuery := uriFilter
            uriFilterSplit := strings.Split(uriFilter, "?")
            if len(uriFilterSplit) > 1 {
                uriQuery = uriFilterSplit[0]
            }
            resourceTmp := context.GetResourceByQuery(&uriQuery)
            if resourceTmp != nil && resource.IsObserved() {
                if !strings.Contains(uri_path, "/mid") && !strings.Contains(uri_path, "/tmid") {
                    resourceTmp.SetIsObserved(false)
                }
                resource = resourceTmp
                uri_path = uriFilter
                break
            }
        }
        request.Code = RequestGet
        request.Options = make([]Option, 0)
        tmpUri := strings.Split(uri_path, "?")
        // Set uri-query and uri-path for handle observe
        if len(tmpUri) > 1 {
            uri = strings.Split(tmpUri[0], "/")
            queries := strings.Split(tmpUri[1], "&")
            uri = append(uri, queries...)
        } else {
            uri = strings.Split(uri_path, "/")
        }
        request.SetPath(uri)
        // If request is observe and resource contains block 2 option, set block 2 for request
        if blockSize != nil {
            block := &Block{}
            block.NUM = 0
            block.M   = 0
            block.SZX = *blockSize
            if isQBlock2 {
                request.SetOption(OptionQBlock2, uint32(block.ToInt()))
            } else {
                request.SetOption(OptionBlock2, uint32(block.ToInt()))
            }
            request.fillC(req)
        }
        session.SetIsNotification(true)
        log.WithField("Request:", request).Debug("Re-create request for handling obervation\n")
    }

    id := ""
    resourceOneUriPaths := strings.Split(uri_path, "/mid=")
    if len (resourceOneUriPaths) <= 1 {
        resourceOneUriPaths = strings.Split(uri_path, "/tmid=")
    }
    if len(resourceOneUriPaths) > 1 {
        id = resourceOneUriPaths[1]
    }
    token := tok.toBytes()
    queryString := query.toString()
    if !is_observe && queryString != nil {
        queryStr := "?" + *queryString
        id += queryStr
    }

    handler, ok := resource.handlers[request.Code]
    if ok {
        itemKey := *tok.toString() + id
        response := Pdu{}
        res, isFound := caches.Get(itemKey)

        // If data does not exist in cache, add data to cache. Else get data from cache for response body
        if !isFound {
            SetBlockOptionFirstRequest(request)
            handler(context, resource, session, request, token, queryString, &response)
        } else {
            response = res.(Pdu)
            response.MessageID = request.MessageID
            response.Token = request.Token
        }
        if is_observe {
            response.SetPath(uri)
            resource.IncreaseObserveNumber()
            response.SetOption(OptionObserve, uint32(resource.GetObserveNumber()))
        } else {
            response.SetPath(strings.Split(uri_path, "/"))
        }
        response.fillC(resp)
        if request.Code == RequestGet && response.Code == ResponseContent {
            // handle max-age option
            maxAge, err := response.GetOptionIntegerValue(OptionMaxage)
            if err != nil || maxAge < 0 {
                maxAge = -1
            }
            response.RemoveOption(OptionMaxage)
            qBlock2, _ := request.GetOptionIntegerValue(OptionQBlock2)
            if qBlock2 >= 0 {
                C.coap_add_data_large_response(resource.ptr, session.ptr, req, resp, query, C.COAP_MEDIATYPE_APPLICATION_DOTS_CBOR, C.int(0),
                                            C.uint64_t(0), C.size_t(len(response.Data)), (*C.uint8_t)(unsafe.Pointer(&response.Data[0])), nil, nil)
            } else {
                C.coap_add_data_blocked_response(req, resp, C.uint16_t(C.COAP_MEDIATYPE_APPLICATION_DOTS_CBOR), C.int(maxAge),
                                            C.size_t(len(response.Data)), (*C.uint8_t)(unsafe.Pointer(&response.Data[0])))
            }
            resPdu,_ := resp.toGo()
            HandleCache(resPdu, response, resource, context, itemKey)
        }
    }
}

// Create Event type from coap_event_t
func newEvent (ev C.coap_event_t) Event {
    switch ev {
    case C.COAP_EVENT_DTLS_CLOSED:      return EventSessionDisconnected
    case C.COAP_EVENT_DTLS_CONNECTED:   return EventSessionConnected
    case C.COAP_EVENT_DTLS_RENEGOTIATE: return EventSessionRenegotiate
    case C.COAP_EVENT_DTLS_ERROR:       return EventSessionError
    default: return -1
    }
}

//export export_event_handler
func export_event_handler(sess *C.coap_session_t, event C.coap_event_t) {
    ctx := C.coap_session_get_context(sess)
    if ctx == nil {
        return
    }
    context, ok := contexts[ctx]
	if !ok {
		return
    }

    session, ok := sessions[sess]
    if !ok {
        session = &Session{ sess, &SessionConfig{false, false, false, false, false, false, false, 0, 0 } }
    }

    // Run event handler when session is connected or disconnected
	if context.eventHandler != nil {
		context.eventHandler(session, newEvent(event))
	}
}

func (resource *Resource) RegisterHandler(method Code, handler MethodHandler) {
    resource.handlers[method] = handler
    C.coap_register_handler(resource.ptr, C.coap_request_t(method), C.coap_method_handler_t(C.method_handler))
}

// Register event handler to libcoap
func (context *Context) RegisterEventHandler(handler EventHandler) {
	context.eventHandler = handler
	C.coap_register_event_handler(context.ptr, C.coap_event_handler_t(C.event_handler))
}

func (context *Context) NewEndpoint(address Address, proto Proto) *EndPoint {
    ptr := C.coap_new_endpoint(context.ptr, &address.value, C.coap_proto_t(proto))
    if ptr == nil {
        return nil
    } else {
        return &EndPoint{ ptr }
    }
}

func (session *Session) DtlsGetPeerCommonName() (_ string, err error) {
    buf := make([]byte, 1024)
    n := C.coap_dtls_get_peer_common_name(session.ptr, (*C.char)(unsafe.Pointer(&buf[0])), 1024)
    if n < 0 {
        err = errors.New("could not get peer common name")
        return
    }
    return string(buf[:n]), nil
}

/*
 * Set block option with Num = 0 for first request
 */
func SetBlockOptionFirstRequest(request *Pdu) {
    blockValue,_ := request.GetOptionIntegerValue(OptionBlock2)
    block := IntToBlock(blockValue)
    if block != nil {
        block.NUM = 0
        request.SetOption(OptionBlock2, uint32(block.ToInt()))
    }
}

/*
 * Handle delete item if block is last block
 * Handle add item if item does not exist in cache
 */
func HandleCache(resp *Pdu, response Pdu, resource *Resource, context *Context, keyItem string) error {
    blockValue,_ := resp.GetOptionIntegerValue(OptionBlock2)
    block := IntToBlock(int(blockValue))
    // Delete block in cache when block is last block
    // Set isBlockwiseInProgress = false as one of conditions to remove resource if it expired
    if block != nil && block.NUM > 0 && block.M == LAST_BLOCK {
        log.Debugf("Delete item cache with key = %+v", keyItem)
        caches.Delete(keyItem)
        resource.isBlockwiseInProgress = false
    }

    // Add item with key if it does not exists
    // Set isBlockwiseInProgress = true to not remove resource in case it expired because block-wise transfer is in progress
    if block != nil && block.NUM == 0 && block.M == MORE_BLOCK {
        log.Debug("Create item cache with key = ", keyItem)
        caches.Set(keyItem, response, cache.DefaultExpiration)
        resource.isBlockwiseInProgress = true
    }
    return nil
}<commit_msg>Update key of cache for Block2<commit_after>package libcoap

/*
#cgo LDFLAGS: -lcoap-3-openssl
#include <coap3/coap.h>
#include "callback.h"
*/
import "C"
import "errors"
import "unsafe"
import "strings"
import log "github.com/sirupsen/logrus"
import cache "github.com/patrickmn/go-cache"

// across invocations, sessions are not 'eq'
type MethodHandler func(*Context, *Resource, *Session, *Pdu, *[]byte, *string, *Pdu)

type EventHandler func(*Session, Event)

type EndPoint struct {
    ptr *C.coap_endpoint_t
}

type Event int
const (
    EventSessionDisconnected Event = C.COAP_EVENT_DTLS_CLOSED
    EventSessionConnected    Event = C.COAP_EVENT_DTLS_CONNECTED
    EventSessionRenegotiate  Event = C.COAP_EVENT_DTLS_RENEGOTIATE
    EventSessionError        Event = C.COAP_EVENT_DTLS_ERROR
)

func (context *Context) ContextSetPSK(identity string, key []byte) {
    cid := C.CString(identity)
    defer C.free(unsafe.Pointer(cid))

    C.coap_context_set_psk(context.ptr,
                           cid,
                           (*C.uint8_t)(&key[0]),
                           C.size_t(len(key)))
}

//export export_method_handler
func export_method_handler(rsrc  *C.coap_resource_t,
                           sess  *C.coap_session_t,
                           req   *C.coap_pdu_t,
                           query *C.coap_string_t,
                           resp  *C.coap_pdu_t) {
    ctx := C.coap_session_get_context(sess)
    if ctx == nil {
        return
    }
    context, ok := contexts[ctx]
    if !ok {
        return
    }
    resource, ok := resources[rsrc]
    if !ok {
        return
    }
    blockSize := resource.GetBlockSize()
    isQBlock2 := resource.IsQBlock2()

    // Handle observe :
    // In case of observation response (or notification), original 'request' from libcoap is NULL
    // In order to handle request with handleGet(), it is necessary to re-create equest
    // First, initialize request from response to re-use some data.
    is_observe := false
    if resource.IsNotification() {
        is_observe = true
        resource.SetIsNotification(false)
    }
    tok := C.coap_get_token_from_request_pdu(req)

    session, ok := sessions[sess]
    if !ok {
		return
    }

    request, err := req.toGo()
    if err != nil {
        return
    }

    // Handle observe:
    // Set request.uri-path from resource.uri-path (so that it can by-pass uri-path check inside PrefixFilter)
    var uri []string
    uri_path := resource.UriPath()
    hb_uri_path := request.PathString()
    if strings.Contains(hb_uri_path, "/hb") {
        uri_path = hb_uri_path
    }
    if is_observe {
        uriFilterList := GetUriFilterByKey(uri_path)
        for _, uriFilter := range uriFilterList {
            uriQuery := uriFilter
            uriFilterSplit := strings.Split(uriFilter, "?")
            if len(uriFilterSplit) > 1 {
                uriQuery = uriFilterSplit[0]
            }
            resourceTmp := context.GetResourceByQuery(&uriQuery)
            if resourceTmp != nil && resource.IsObserved() {
                if !strings.Contains(uri_path, "/mid") && !strings.Contains(uri_path, "/tmid") {
                    resourceTmp.SetIsObserved(false)
                }
                resource = resourceTmp
                uri_path = uriFilter
                break
            }
        }
        request.Code = RequestGet
        request.Options = make([]Option, 0)
        tmpUri := strings.Split(uri_path, "?")
        // Set uri-query and uri-path for handle observe
        if len(tmpUri) > 1 {
            uri = strings.Split(tmpUri[0], "/")
            queries := strings.Split(tmpUri[1], "&")
            uri = append(uri, queries...)
        } else {
            uri = strings.Split(uri_path, "/")
        }
        request.SetPath(uri)
        // If request is observe and resource contains block 2 option, set block 2 for request
        if blockSize != nil {
            block := &Block{}
            block.NUM = 0
            block.M   = 0
            block.SZX = *blockSize
            if isQBlock2 {
                request.SetOption(OptionQBlock2, uint32(block.ToInt()))
            } else {
                request.SetOption(OptionBlock2, uint32(block.ToInt()))
            }
            request.fillC(req)
        }
        session.SetIsNotification(true)
        log.WithField("Request:", request).Debug("Re-create request for handling obervation\n")
    }

    id := ""
    resourceOneUriPaths := strings.Split(uri_path, "/mid=")
    if len (resourceOneUriPaths) <= 1 {
        resourceOneUriPaths = strings.Split(uri_path, "/tmid=")
    }
    if len(resourceOneUriPaths) > 1 {
        id = resourceOneUriPaths[1]
    }
    token := tok.toBytes()
    queryString := query.toString()
    if !is_observe && queryString != nil {
        queryStr := "?" + *queryString
        id += queryStr
    }

    handler, ok := resource.handlers[request.Code]
    if ok {
        itemKey := uri_path
        response := Pdu{}
        res, isFound := caches.Get(itemKey)

        // If data does not exist in cache, add data to cache. Else get data from cache for response body
        if !isFound {
            SetBlockOptionFirstRequest(request)
            handler(context, resource, session, request, token, queryString, &response)
        } else {
            response = res.(Pdu)
            response.MessageID = request.MessageID
            response.Token = request.Token
        }
        if is_observe {
            response.SetPath(uri)
            resource.IncreaseObserveNumber()
            response.SetOption(OptionObserve, uint32(resource.GetObserveNumber()))
        } else {
            response.SetPath(strings.Split(uri_path, "/"))
        }
        response.fillC(resp)
        if request.Code == RequestGet && response.Code == ResponseContent {
            // handle max-age option
            maxAge, err := response.GetOptionIntegerValue(OptionMaxage)
            if err != nil || maxAge < 0 {
                maxAge = -1
            }
            response.RemoveOption(OptionMaxage)
            qBlock2, _ := request.GetOptionIntegerValue(OptionQBlock2)
            if qBlock2 >= 0 {
                C.coap_add_data_large_response(resource.ptr, session.ptr, req, resp, query, C.COAP_MEDIATYPE_APPLICATION_DOTS_CBOR, C.int(0),
                                            C.uint64_t(0), C.size_t(len(response.Data)), (*C.uint8_t)(unsafe.Pointer(&response.Data[0])), nil, nil)
            } else {
                C.coap_add_data_blocked_response(req, resp, C.uint16_t(C.COAP_MEDIATYPE_APPLICATION_DOTS_CBOR), C.int(maxAge),
                                            C.size_t(len(response.Data)), (*C.uint8_t)(unsafe.Pointer(&response.Data[0])))
            }
            resPdu,_ := resp.toGo()
            HandleCache(resPdu, response, resource, context, itemKey)
        }
    }
}

// Create Event type from coap_event_t
func newEvent (ev C.coap_event_t) Event {
    switch ev {
    case C.COAP_EVENT_DTLS_CLOSED:      return EventSessionDisconnected
    case C.COAP_EVENT_DTLS_CONNECTED:   return EventSessionConnected
    case C.COAP_EVENT_DTLS_RENEGOTIATE: return EventSessionRenegotiate
    case C.COAP_EVENT_DTLS_ERROR:       return EventSessionError
    default: return -1
    }
}

//export export_event_handler
func export_event_handler(sess *C.coap_session_t, event C.coap_event_t) {
    ctx := C.coap_session_get_context(sess)
    if ctx == nil {
        return
    }
    context, ok := contexts[ctx]
	if !ok {
		return
    }

    session, ok := sessions[sess]
    if !ok {
        session = &Session{ sess, &SessionConfig{false, false, false, false, false, false, false, 0, 0 } }
    }

    // Run event handler when session is connected or disconnected
	if context.eventHandler != nil {
		context.eventHandler(session, newEvent(event))
	}
}

func (resource *Resource) RegisterHandler(method Code, handler MethodHandler) {
    resource.handlers[method] = handler
    C.coap_register_handler(resource.ptr, C.coap_request_t(method), C.coap_method_handler_t(C.method_handler))
}

// Register event handler to libcoap
func (context *Context) RegisterEventHandler(handler EventHandler) {
	context.eventHandler = handler
	C.coap_register_event_handler(context.ptr, C.coap_event_handler_t(C.event_handler))
}

func (context *Context) NewEndpoint(address Address, proto Proto) *EndPoint {
    ptr := C.coap_new_endpoint(context.ptr, &address.value, C.coap_proto_t(proto))
    if ptr == nil {
        return nil
    } else {
        return &EndPoint{ ptr }
    }
}

func (session *Session) DtlsGetPeerCommonName() (_ string, err error) {
    buf := make([]byte, 1024)
    n := C.coap_dtls_get_peer_common_name(session.ptr, (*C.char)(unsafe.Pointer(&buf[0])), 1024)
    if n < 0 {
        err = errors.New("could not get peer common name")
        return
    }
    return string(buf[:n]), nil
}

/*
 * Set block option with Num = 0 for first request
 */
func SetBlockOptionFirstRequest(request *Pdu) {
    blockValue,_ := request.GetOptionIntegerValue(OptionBlock2)
    block := IntToBlock(blockValue)
    if block != nil {
        block.NUM = 0
        request.SetOption(OptionBlock2, uint32(block.ToInt()))
    }
}

/*
 * Handle delete item if block is last block
 * Handle add item if item does not exist in cache
 */
func HandleCache(resp *Pdu, response Pdu, resource *Resource, context *Context, keyItem string) error {
    blockValue,_ := resp.GetOptionIntegerValue(OptionBlock2)
    block := IntToBlock(int(blockValue))
    // Delete block in cache when block is last block
    // Set isBlockwiseInProgress = false as one of conditions to remove resource if it expired
    if block != nil && block.NUM > 0 && block.M == LAST_BLOCK {
        log.Debugf("Delete item cache with key = %+v", keyItem)
        caches.Delete(keyItem)
        resource.isBlockwiseInProgress = false
    }

    // Add item with key if it does not exists
    // Set isBlockwiseInProgress = true to not remove resource in case it expired because block-wise transfer is in progress
    if block != nil && block.NUM == 0 && block.M == MORE_BLOCK {
        log.Debug("Create item cache with key = ", keyItem)
        caches.Set(keyItem, response, cache.DefaultExpiration)
        resource.isBlockwiseInProgress = true
    }
    return nil
}<|endoftext|>


<commit_before><commit_msg>transforms/mutate/mapreplace: fix wrong stage status<commit_after><|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 internal

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
)

// Token represents the credentials used to authorize
// the requests to access protected resources on the OAuth 2.0
// provider's backend.
//
// This type is a mirror of oauth2.Token and exists to break
// an otherwise-circular dependency. Other internal packages
// should convert this Token into an oauth2.Token before use.
type Token struct {
	// AccessToken is the token that authorizes and authenticates
	// the requests.
	AccessToken string

	// TokenType is the type of token.
	// The Type method returns either this or "Bearer", the default.
	TokenType string

	// RefreshToken is a token that's used by the application
	// (as opposed to the user) to refresh the access token
	// if it expires.
	RefreshToken string

	// Expiry is the optional expiration time of the access token.
	//
	// If zero, TokenSource implementations will reuse the same
	// token forever and RefreshToken or equivalent
	// mechanisms for that TokenSource will not be used.
	Expiry time.Time

	// Raw optionally contains extra metadata from the server
	// when updating a token.
	Raw interface{}
}

// tokenJSON is the struct representing the HTTP response from OAuth2
// providers returning a token in JSON form.
type tokenJSON struct {
	AccessToken  string         `json:"access_token"`
	TokenType    string         `json:"token_type"`
	RefreshToken string         `json:"refresh_token"`
	ExpiresIn    expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
	Expires      expirationTime `json:"expires"`    // broken Facebook spelling of expires_in
}

func (e *tokenJSON) expiry() (t time.Time) {
	if v := e.ExpiresIn; v != 0 {
		return time.Now().Add(time.Duration(v) * time.Second)
	}
	if v := e.Expires; v != 0 {
		return time.Now().Add(time.Duration(v) * time.Second)
	}
	return
}

type expirationTime int32

func (e *expirationTime) UnmarshalJSON(b []byte) error {
	var n json.Number
	err := json.Unmarshal(b, &n)
	if err != nil {
		return err
	}
	i, err := n.Int64()
	if err != nil {
		return err
	}
	*e = expirationTime(i)
	return nil
}

var brokenAuthHeaderProviders = []string{
	"https://accounts.google.com/",
	"https://api.codeswholesale.com/oauth/token",
	"https://api.dropbox.com/",
	"https://api.dropboxapi.com/",
	"https://api.instagram.com/",
	"https://api.netatmo.net/",
	"https://api.odnoklassniki.ru/",
	"https://api.pushbullet.com/",
	"https://api.soundcloud.com/",
	"https://api.twitch.tv/",
	"https://app.box.com/",
	"https://connect.stripe.com/",
	"https://login.mailchimp.com/",
	"https://login.microsoftonline.com/",
	"https://login.salesforce.com/",
	"https://login.windows.net",
	"https://login.live.com/",
	"https://oauth.sandbox.trainingpeaks.com/",
	"https://oauth.trainingpeaks.com/",
	"https://oauth.vk.com/",
	"https://openapi.baidu.com/",
	"https://slack.com/",
	"https://test-sandbox.auth.corp.google.com",
	"https://test.salesforce.com/",
	"https://user.gini.net/",
	"https://www.douban.com/",
	"https://www.googleapis.com/",
	"https://www.linkedin.com/",
	"https://www.strava.com/oauth/",
	"https://www.wunderlist.com/oauth/",
	"https://api.patreon.com/",
	"https://sandbox.codeswholesale.com/oauth/token",
	"https://api.sipgate.com/v1/authorization/oauth",
	"https://api.medium.com/v1/tokens",
	"https://log.finalsurge.com/oauth/token",
	"https://multisport.todaysplan.com.au/rest/oauth/access_token",
	"https://whats.todaysplan.com.au/rest/oauth/access_token",
}

// brokenAuthHeaderDomains lists broken providers that issue dynamic endpoints.
var brokenAuthHeaderDomains = []string{
	".auth0.com",
	".force.com",
	".myshopify.com",
	".okta.com",
	".oktapreview.com",
}

func RegisterBrokenAuthHeaderProvider(tokenURL string) {
	brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
}

// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
// implements the OAuth2 spec correctly
// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
// In summary:
// - Reddit only accepts client secret in the Authorization header
// - Dropbox accepts either it in URL param or Auth header, but not both.
// - Google only accepts URL param (not spec compliant?), not Auth header
// - Stripe only accepts client secret in Auth header with Bearer method, not Basic
func providerAuthHeaderWorks(tokenURL string) bool {
	for _, s := range brokenAuthHeaderProviders {
		if strings.HasPrefix(tokenURL, s) {
			// Some sites fail to implement the OAuth2 spec fully.
			return false
		}
	}

	if u, err := url.Parse(tokenURL); err == nil {
		for _, s := range brokenAuthHeaderDomains {
			if strings.HasSuffix(u.Host, s) {
				return false
			}
		}
	}

	// Assume the provider implements the spec properly
	// otherwise. We can add more exceptions as they're
	// discovered. We will _not_ be adding configurable hooks
	// to this package to let users select server bugs.
	return true
}

func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
	bustedAuth := !providerAuthHeaderWorks(tokenURL)
	if bustedAuth {
		if clientID != "" {
			v.Set("client_id", clientID)
		}
		if clientSecret != "" {
			v.Set("client_secret", clientSecret)
		}
	}
	req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if !bustedAuth {
		req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
	}
	r, err := ctxhttp.Do(ctx, ContextClient(ctx), req)
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
	}
	if code := r.StatusCode; code < 200 || code > 299 {
		return nil, &RetrieveError{
			Response: r,
			Body:     body,
		}
	}

	var token *Token
	content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
	switch content {
	case "application/x-www-form-urlencoded", "text/plain":
		vals, err := url.ParseQuery(string(body))
		if err != nil {
			return nil, err
		}
		token = &Token{
			AccessToken:  vals.Get("access_token"),
			TokenType:    vals.Get("token_type"),
			RefreshToken: vals.Get("refresh_token"),
			Raw:          vals,
		}
		e := vals.Get("expires_in")
		if e == "" {
			// TODO(jbd): Facebook's OAuth2 implementation is broken and
			// returns expires_in field in expires. Remove the fallback to expires,
			// when Facebook fixes their implementation.
			e = vals.Get("expires")
		}
		expires, _ := strconv.Atoi(e)
		if expires != 0 {
			token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
		}
	default:
		var tj tokenJSON
		if err = json.Unmarshal(body, &tj); err != nil {
			return nil, err
		}
		token = &Token{
			AccessToken:  tj.AccessToken,
			TokenType:    tj.TokenType,
			RefreshToken: tj.RefreshToken,
			Expiry:       tj.expiry(),
			Raw:          make(map[string]interface{}),
		}
		json.Unmarshal(body, &token.Raw) // no error checks for optional fields
	}
	// Don't overwrite `RefreshToken` with an empty value
	// if this was a token refreshing request.
	if token.RefreshToken == "" {
		token.RefreshToken = v.Get("refresh_token")
	}
	if token.AccessToken == "" {
		return token, errors.New("oauth2: server response missing access_token")
	}
	return token, nil
}

type RetrieveError struct {
	Response *http.Response
	Body     []byte
}

func (r *RetrieveError) Error() string {
	return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
}
<commit_msg>internal: add Twitch's other endpoint to blacklist<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 internal

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
)

// Token represents the credentials used to authorize
// the requests to access protected resources on the OAuth 2.0
// provider's backend.
//
// This type is a mirror of oauth2.Token and exists to break
// an otherwise-circular dependency. Other internal packages
// should convert this Token into an oauth2.Token before use.
type Token struct {
	// AccessToken is the token that authorizes and authenticates
	// the requests.
	AccessToken string

	// TokenType is the type of token.
	// The Type method returns either this or "Bearer", the default.
	TokenType string

	// RefreshToken is a token that's used by the application
	// (as opposed to the user) to refresh the access token
	// if it expires.
	RefreshToken string

	// Expiry is the optional expiration time of the access token.
	//
	// If zero, TokenSource implementations will reuse the same
	// token forever and RefreshToken or equivalent
	// mechanisms for that TokenSource will not be used.
	Expiry time.Time

	// Raw optionally contains extra metadata from the server
	// when updating a token.
	Raw interface{}
}

// tokenJSON is the struct representing the HTTP response from OAuth2
// providers returning a token in JSON form.
type tokenJSON struct {
	AccessToken  string         `json:"access_token"`
	TokenType    string         `json:"token_type"`
	RefreshToken string         `json:"refresh_token"`
	ExpiresIn    expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
	Expires      expirationTime `json:"expires"`    // broken Facebook spelling of expires_in
}

func (e *tokenJSON) expiry() (t time.Time) {
	if v := e.ExpiresIn; v != 0 {
		return time.Now().Add(time.Duration(v) * time.Second)
	}
	if v := e.Expires; v != 0 {
		return time.Now().Add(time.Duration(v) * time.Second)
	}
	return
}

type expirationTime int32

func (e *expirationTime) UnmarshalJSON(b []byte) error {
	var n json.Number
	err := json.Unmarshal(b, &n)
	if err != nil {
		return err
	}
	i, err := n.Int64()
	if err != nil {
		return err
	}
	*e = expirationTime(i)
	return nil
}

var brokenAuthHeaderProviders = []string{
	"https://accounts.google.com/",
	"https://api.codeswholesale.com/oauth/token",
	"https://api.dropbox.com/",
	"https://api.dropboxapi.com/",
	"https://api.instagram.com/",
	"https://api.netatmo.net/",
	"https://api.odnoklassniki.ru/",
	"https://api.pushbullet.com/",
	"https://api.soundcloud.com/",
	"https://api.twitch.tv/",
	"https://id.twitch.tv/",
	"https://app.box.com/",
	"https://connect.stripe.com/",
	"https://login.mailchimp.com/",
	"https://login.microsoftonline.com/",
	"https://login.salesforce.com/",
	"https://login.windows.net",
	"https://login.live.com/",
	"https://oauth.sandbox.trainingpeaks.com/",
	"https://oauth.trainingpeaks.com/",
	"https://oauth.vk.com/",
	"https://openapi.baidu.com/",
	"https://slack.com/",
	"https://test-sandbox.auth.corp.google.com",
	"https://test.salesforce.com/",
	"https://user.gini.net/",
	"https://www.douban.com/",
	"https://www.googleapis.com/",
	"https://www.linkedin.com/",
	"https://www.strava.com/oauth/",
	"https://www.wunderlist.com/oauth/",
	"https://api.patreon.com/",
	"https://sandbox.codeswholesale.com/oauth/token",
	"https://api.sipgate.com/v1/authorization/oauth",
	"https://api.medium.com/v1/tokens",
	"https://log.finalsurge.com/oauth/token",
	"https://multisport.todaysplan.com.au/rest/oauth/access_token",
	"https://whats.todaysplan.com.au/rest/oauth/access_token",
}

// brokenAuthHeaderDomains lists broken providers that issue dynamic endpoints.
var brokenAuthHeaderDomains = []string{
	".auth0.com",
	".force.com",
	".myshopify.com",
	".okta.com",
	".oktapreview.com",
}

func RegisterBrokenAuthHeaderProvider(tokenURL string) {
	brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
}

// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
// implements the OAuth2 spec correctly
// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
// In summary:
// - Reddit only accepts client secret in the Authorization header
// - Dropbox accepts either it in URL param or Auth header, but not both.
// - Google only accepts URL param (not spec compliant?), not Auth header
// - Stripe only accepts client secret in Auth header with Bearer method, not Basic
func providerAuthHeaderWorks(tokenURL string) bool {
	for _, s := range brokenAuthHeaderProviders {
		if strings.HasPrefix(tokenURL, s) {
			// Some sites fail to implement the OAuth2 spec fully.
			return false
		}
	}

	if u, err := url.Parse(tokenURL); err == nil {
		for _, s := range brokenAuthHeaderDomains {
			if strings.HasSuffix(u.Host, s) {
				return false
			}
		}
	}

	// Assume the provider implements the spec properly
	// otherwise. We can add more exceptions as they're
	// discovered. We will _not_ be adding configurable hooks
	// to this package to let users select server bugs.
	return true
}

func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
	bustedAuth := !providerAuthHeaderWorks(tokenURL)
	if bustedAuth {
		if clientID != "" {
			v.Set("client_id", clientID)
		}
		if clientSecret != "" {
			v.Set("client_secret", clientSecret)
		}
	}
	req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if !bustedAuth {
		req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
	}
	r, err := ctxhttp.Do(ctx, ContextClient(ctx), req)
	if err != nil {
		return nil, err
	}
	defer r.Body.Close()
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
	}
	if code := r.StatusCode; code < 200 || code > 299 {
		return nil, &RetrieveError{
			Response: r,
			Body:     body,
		}
	}

	var token *Token
	content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
	switch content {
	case "application/x-www-form-urlencoded", "text/plain":
		vals, err := url.ParseQuery(string(body))
		if err != nil {
			return nil, err
		}
		token = &Token{
			AccessToken:  vals.Get("access_token"),
			TokenType:    vals.Get("token_type"),
			RefreshToken: vals.Get("refresh_token"),
			Raw:          vals,
		}
		e := vals.Get("expires_in")
		if e == "" {
			// TODO(jbd): Facebook's OAuth2 implementation is broken and
			// returns expires_in field in expires. Remove the fallback to expires,
			// when Facebook fixes their implementation.
			e = vals.Get("expires")
		}
		expires, _ := strconv.Atoi(e)
		if expires != 0 {
			token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
		}
	default:
		var tj tokenJSON
		if err = json.Unmarshal(body, &tj); err != nil {
			return nil, err
		}
		token = &Token{
			AccessToken:  tj.AccessToken,
			TokenType:    tj.TokenType,
			RefreshToken: tj.RefreshToken,
			Expiry:       tj.expiry(),
			Raw:          make(map[string]interface{}),
		}
		json.Unmarshal(body, &token.Raw) // no error checks for optional fields
	}
	// Don't overwrite `RefreshToken` with an empty value
	// if this was a token refreshing request.
	if token.RefreshToken == "" {
		token.RefreshToken = v.Get("refresh_token")
	}
	if token.AccessToken == "" {
		return token, errors.New("oauth2: server response missing access_token")
	}
	return token, nil
}

type RetrieveError struct {
	Response *http.Response
	Body     []byte
}

func (r *RetrieveError) Error() string {
	return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
}
<|endoftext|>


<commit_before>// Copyright 2015 Guntas Grewal

package main

import (
	"fmt"
	"periwinkle/listeners/twilio"
)

func main() {
	testNumber, err := twilio.NewPhoneNum()

	if err != nil {
		fmt.Printf("ERROR CHECK!\n")
	}

	fmt.Printf("%s\n", testNumber)
}
<commit_msg>remove magic<commit_after><|endoftext|>


<commit_before>// Copyright 2011 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 net

import (
	"errors"
	"os"
	"runtime"
	"syscall"
	"testing"
)

var multicastListenerTests = []struct {
	net   string
	gaddr *UDPAddr
	flags Flags
	ipv6  bool // test with underlying AF_INET6 socket
}{
	// cf. RFC 4727: Experimental Values in IPv4, IPv6, ICMPv4, ICMPv6, UDP, and TCP Headers

	{"udp", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},
	{"udp", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, 0, false},
	{"udp", &UDPAddr{ParseIP("ff0e::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp", &UDPAddr{ParseIP("ff0e::114"), 12345}, 0, true},

	{"udp4", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},
	{"udp4", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, 0, false},

	{"udp6", &UDPAddr{ParseIP("ff01::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff01::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff02::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff02::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff04::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff04::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff05::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff05::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff08::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff08::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff0e::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff0e::114"), 12345}, 0, true},
}

// TestMulticastListener tests both single and double listen to a test
// listener with same address family, same group address and same port.
func TestMulticastListener(t *testing.T) {
	switch runtime.GOOS {
	case "netbsd", "openbsd", "plan9", "windows":
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	case "linux":
		if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" {
			t.Logf("skipping test on %q/%q", runtime.GOOS, runtime.GOARCH)
			return
		}
	}

	for _, tt := range multicastListenerTests {
		if tt.ipv6 && (!supportsIPv6 || os.Getuid() != 0) {
			continue
		}
		ifi, err := availMulticastInterface(t, tt.flags)
		if err != nil {
			continue
		}
		c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("First ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c1, tt.gaddr)
		c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("Second ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c2, tt.gaddr)
		c2.Close()
		switch c1.fd.family {
		case syscall.AF_INET:
			testIPv4MulticastSocketOptions(t, c1.fd, ifi)
		case syscall.AF_INET6:
			testIPv6MulticastSocketOptions(t, c1.fd, ifi)
		}
		c1.Close()
	}
}

func TestSimpleMulticastListener(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	}

	for _, tt := range multicastListenerTests {
		if tt.ipv6 {
			continue
		}
		tt.flags = FlagUp | FlagMulticast // for windows testing
		ifi, err := availMulticastInterface(t, tt.flags)
		if err != nil {
			continue
		}
		c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("First ListenMulticastUDP failed: %v", err)
		}
		checkSimpleMulticastListener(t, err, c1, tt.gaddr)
		c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("Second ListenMulticastUDP failed: %v", err)
		}
		checkSimpleMulticastListener(t, err, c2, tt.gaddr)
		c2.Close()
		c1.Close()
	}
}

func checkMulticastListener(t *testing.T, err error, c *UDPConn, gaddr *UDPAddr) {
	if !multicastRIBContains(t, gaddr.IP) {
		t.Fatalf("%q not found in RIB", gaddr.String())
	}
	if c.LocalAddr().String() != gaddr.String() {
		t.Fatalf("LocalAddr returns %q, expected %q", c.LocalAddr().String(), gaddr.String())
	}
}

func checkSimpleMulticastListener(t *testing.T, err error, c *UDPConn, gaddr *UDPAddr) {
	if c.LocalAddr().String() != gaddr.String() {
		t.Fatalf("LocalAddr returns %q, expected %q", c.LocalAddr().String(), gaddr.String())
	}
}

func availMulticastInterface(t *testing.T, flags Flags) (*Interface, error) {
	var ifi *Interface
	if flags != Flags(0) {
		ift, err := Interfaces()
		if err != nil {
			t.Fatalf("Interfaces failed: %v", err)
		}
		for _, x := range ift {
			if x.Flags&flags == flags {
				ifi = &x
				break
			}
		}
		if ifi == nil {
			return nil, errors.New("an appropriate multicast interface not found")
		}
	}
	return ifi, nil
}

func multicastRIBContains(t *testing.T, ip IP) bool {
	ift, err := Interfaces()
	if err != nil {
		t.Fatalf("Interfaces failed: %v", err)
	}
	for _, ifi := range ift {
		ifmat, err := ifi.MulticastAddrs()
		if err != nil {
			t.Fatalf("MulticastAddrs failed: %v", err)
		}
		for _, ifma := range ifmat {
			if ifma.(*IPAddr).IP.Equal(ip) {
				return true
			}
		}
	}
	return false
}

func testIPv4MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {
	_, err := ipv4MulticastInterface(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastInterface failed: %v", err)
	}
	if ifi != nil {
		err = setIPv4MulticastInterface(fd, ifi)
		if err != nil {
			t.Fatalf("setIPv4MulticastInterface failed: %v", err)
		}
	}
	_, err = ipv4MulticastTTL(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastTTL failed: %v", err)
	}
	err = setIPv4MulticastTTL(fd, 1)
	if err != nil {
		t.Fatalf("setIPv4MulticastTTL failed: %v", err)
	}
	_, err = ipv4MulticastLoopback(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastLoopback failed: %v", err)
	}
	err = setIPv4MulticastLoopback(fd, false)
	if err != nil {
		t.Fatalf("setIPv4MulticastLoopback failed: %v", err)
	}
}

func testIPv6MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {
	_, err := ipv6MulticastInterface(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastInterface failed: %v", err)
	}
	if ifi != nil {
		err = setIPv6MulticastInterface(fd, ifi)
		if err != nil {
			t.Fatalf("setIPv6MulticastInterface failed: %v", err)
		}
	}
	_, err = ipv6MulticastHopLimit(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastHopLimit failed: %v", err)
	}
	err = setIPv6MulticastHopLimit(fd, 1)
	if err != nil {
		t.Fatalf("setIPv6MulticastHopLimit failed: %v", err)
	}
	_, err = ipv6MulticastLoopback(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastLoopback failed: %v", err)
	}
	err = setIPv6MulticastLoopback(fd, false)
	if err != nil {
		t.Fatalf("setIPv6MulticastLoopback failed: %v", err)
	}
}
<commit_msg>net: disable another external network test<commit_after>// Copyright 2011 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 net

import (
	"errors"
	"os"
	"runtime"
	"syscall"
	"testing"
)

var multicastListenerTests = []struct {
	net   string
	gaddr *UDPAddr
	flags Flags
	ipv6  bool // test with underlying AF_INET6 socket
}{
	// cf. RFC 4727: Experimental Values in IPv4, IPv6, ICMPv4, ICMPv6, UDP, and TCP Headers

	{"udp", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},
	{"udp", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, 0, false},
	{"udp", &UDPAddr{ParseIP("ff0e::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp", &UDPAddr{ParseIP("ff0e::114"), 12345}, 0, true},

	{"udp4", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},
	{"udp4", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, 0, false},

	{"udp6", &UDPAddr{ParseIP("ff01::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff01::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff02::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff02::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff04::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff04::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff05::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff05::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff08::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff08::114"), 12345}, 0, true},
	{"udp6", &UDPAddr{ParseIP("ff0e::114"), 12345}, FlagUp | FlagLoopback, true},
	{"udp6", &UDPAddr{ParseIP("ff0e::114"), 12345}, 0, true},
}

// TestMulticastListener tests both single and double listen to a test
// listener with same address family, same group address and same port.
func TestMulticastListener(t *testing.T) {
	switch runtime.GOOS {
	case "netbsd", "openbsd", "plan9", "windows":
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	case "linux":
		if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" {
			t.Logf("skipping test on %q/%q", runtime.GOOS, runtime.GOARCH)
			return
		}
	}

	for _, tt := range multicastListenerTests {
		if tt.ipv6 && (!supportsIPv6 || os.Getuid() != 0) {
			continue
		}
		ifi, err := availMulticastInterface(t, tt.flags)
		if err != nil {
			continue
		}
		c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("First ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c1, tt.gaddr)
		c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("Second ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c2, tt.gaddr)
		c2.Close()
		switch c1.fd.family {
		case syscall.AF_INET:
			testIPv4MulticastSocketOptions(t, c1.fd, ifi)
		case syscall.AF_INET6:
			testIPv6MulticastSocketOptions(t, c1.fd, ifi)
		}
		c1.Close()
	}
}

func TestSimpleMulticastListener(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	case "windows":
		if testing.Short() || !*testExternal {
			t.Logf("skipping test on windows to avoid firewall")
			return
		}
	}

	for _, tt := range multicastListenerTests {
		if tt.ipv6 {
			continue
		}
		tt.flags = FlagUp | FlagMulticast // for windows testing
		ifi, err := availMulticastInterface(t, tt.flags)
		if err != nil {
			continue
		}
		c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("First ListenMulticastUDP failed: %v", err)
		}
		checkSimpleMulticastListener(t, err, c1, tt.gaddr)
		c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("Second ListenMulticastUDP failed: %v", err)
		}
		checkSimpleMulticastListener(t, err, c2, tt.gaddr)
		c2.Close()
		c1.Close()
	}
}

func checkMulticastListener(t *testing.T, err error, c *UDPConn, gaddr *UDPAddr) {
	if !multicastRIBContains(t, gaddr.IP) {
		t.Fatalf("%q not found in RIB", gaddr.String())
	}
	if c.LocalAddr().String() != gaddr.String() {
		t.Fatalf("LocalAddr returns %q, expected %q", c.LocalAddr().String(), gaddr.String())
	}
}

func checkSimpleMulticastListener(t *testing.T, err error, c *UDPConn, gaddr *UDPAddr) {
	if c.LocalAddr().String() != gaddr.String() {
		t.Fatalf("LocalAddr returns %q, expected %q", c.LocalAddr().String(), gaddr.String())
	}
}

func availMulticastInterface(t *testing.T, flags Flags) (*Interface, error) {
	var ifi *Interface
	if flags != Flags(0) {
		ift, err := Interfaces()
		if err != nil {
			t.Fatalf("Interfaces failed: %v", err)
		}
		for _, x := range ift {
			if x.Flags&flags == flags {
				ifi = &x
				break
			}
		}
		if ifi == nil {
			return nil, errors.New("an appropriate multicast interface not found")
		}
	}
	return ifi, nil
}

func multicastRIBContains(t *testing.T, ip IP) bool {
	ift, err := Interfaces()
	if err != nil {
		t.Fatalf("Interfaces failed: %v", err)
	}
	for _, ifi := range ift {
		ifmat, err := ifi.MulticastAddrs()
		if err != nil {
			t.Fatalf("MulticastAddrs failed: %v", err)
		}
		for _, ifma := range ifmat {
			if ifma.(*IPAddr).IP.Equal(ip) {
				return true
			}
		}
	}
	return false
}

func testIPv4MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {
	_, err := ipv4MulticastInterface(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastInterface failed: %v", err)
	}
	if ifi != nil {
		err = setIPv4MulticastInterface(fd, ifi)
		if err != nil {
			t.Fatalf("setIPv4MulticastInterface failed: %v", err)
		}
	}
	_, err = ipv4MulticastTTL(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastTTL failed: %v", err)
	}
	err = setIPv4MulticastTTL(fd, 1)
	if err != nil {
		t.Fatalf("setIPv4MulticastTTL failed: %v", err)
	}
	_, err = ipv4MulticastLoopback(fd)
	if err != nil {
		t.Fatalf("ipv4MulticastLoopback failed: %v", err)
	}
	err = setIPv4MulticastLoopback(fd, false)
	if err != nil {
		t.Fatalf("setIPv4MulticastLoopback failed: %v", err)
	}
}

func testIPv6MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {
	_, err := ipv6MulticastInterface(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastInterface failed: %v", err)
	}
	if ifi != nil {
		err = setIPv6MulticastInterface(fd, ifi)
		if err != nil {
			t.Fatalf("setIPv6MulticastInterface failed: %v", err)
		}
	}
	_, err = ipv6MulticastHopLimit(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastHopLimit failed: %v", err)
	}
	err = setIPv6MulticastHopLimit(fd, 1)
	if err != nil {
		t.Fatalf("setIPv6MulticastHopLimit failed: %v", err)
	}
	_, err = ipv6MulticastLoopback(fd)
	if err != nil {
		t.Fatalf("ipv6MulticastLoopback failed: %v", err)
	}
	err = setIPv6MulticastLoopback(fd, false)
	if err != nil {
		t.Fatalf("setIPv6MulticastLoopback failed: %v", err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2012 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 runtime_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"testing"
	"text/template"
)

type crashTest struct {
	Cgo bool
}

// This test is a separate program, because it is testing
// both main (m0) and non-main threads (m).

func testCrashHandler(t *testing.T, ct *crashTest) {
	if runtime.GOOS == "freebsd" {
		// TODO(brainman): do not know why this test fails on freebsd
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	}

	st := template.Must(template.New("crashSource").Parse(crashSource))

	dir, err := ioutil.TempDir("", "go-build")
	if err != nil {
		t.Fatalf("failed to create temp directory: %v", err)
	}
	defer os.RemoveAll(dir)

	src := filepath.Join(dir, "main.go")
	f, err := os.Create(src)
	if err != nil {
		t.Fatalf("failed to create %v: %v", src, err)
	}
	err = st.Execute(f, ct)
	if err != nil {
		f.Close()
		t.Fatalf("failed to execute template: %v", err)
	}
	f.Close()

	got, err := exec.Command("go", "run", src).CombinedOutput()
	if err != nil {
		t.Fatalf("program exited with error: %v\n%v", err, string(got))
	}
	want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
	if string(got) != string(want) {
		t.Fatalf("expected %q, but got %q", string(want), string(got))
	}
}

func TestCrashHandler(t *testing.T) {
	testCrashHandler(t, &crashTest{Cgo: false})
}

const crashSource = `
package main

import (
	"fmt"
	"runtime"
)

{{if .Cgo}}
import "C"
{{end}}

func test(name string) {
	defer func() {
		if x := recover(); x != nil {
			fmt.Printf(" recovered")
		}
		fmt.Printf(" done\n")
	}()
	fmt.Printf("%s:", name)
	var s *string
	_ = *s
	fmt.Print("SHOULD NOT BE HERE")
}

func testInNewThread(name string) {
	c := make(chan bool)
	go func() {
		runtime.LockOSThread()
		test(name)
		c <- true
	}()
	<-c
}

func main() {
	runtime.LockOSThread()
	test("main")
	testInNewThread("new-thread")
	testInNewThread("second-new-thread")
	test("main-again")
}
`
<commit_msg>runtime: re-enable crash test on FreeBSD<commit_after>// Copyright 2012 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 runtime_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
	"text/template"
)

type crashTest struct {
	Cgo bool
}

// This test is a separate program, because it is testing
// both main (m0) and non-main threads (m).

func testCrashHandler(t *testing.T, ct *crashTest) {
	st := template.Must(template.New("crashSource").Parse(crashSource))

	dir, err := ioutil.TempDir("", "go-build")
	if err != nil {
		t.Fatalf("failed to create temp directory: %v", err)
	}
	defer os.RemoveAll(dir)

	src := filepath.Join(dir, "main.go")
	f, err := os.Create(src)
	if err != nil {
		t.Fatalf("failed to create %v: %v", src, err)
	}
	err = st.Execute(f, ct)
	if err != nil {
		f.Close()
		t.Fatalf("failed to execute template: %v", err)
	}
	f.Close()

	got, err := exec.Command("go", "run", src).CombinedOutput()
	if err != nil {
		t.Fatalf("program exited with error: %v\n%v", err, string(got))
	}
	want := "main: recovered done\nnew-thread: recovered done\nsecond-new-thread: recovered done\nmain-again: recovered done\n"
	if string(got) != string(want) {
		t.Fatalf("expected %q, but got %q", string(want), string(got))
	}
}

func TestCrashHandler(t *testing.T) {
	testCrashHandler(t, &crashTest{Cgo: false})
}

const crashSource = `
package main

import (
	"fmt"
	"runtime"
)

{{if .Cgo}}
import "C"
{{end}}

func test(name string) {
	defer func() {
		if x := recover(); x != nil {
			fmt.Printf(" recovered")
		}
		fmt.Printf(" done\n")
	}()
	fmt.Printf("%s:", name)
	var s *string
	_ = *s
	fmt.Print("SHOULD NOT BE HERE")
}

func testInNewThread(name string) {
	c := make(chan bool)
	go func() {
		runtime.LockOSThread()
		test(name)
		c <- true
	}()
	<-c
}

func main() {
	runtime.LockOSThread()
	test("main")
	testInNewThread("new-thread")
	testInNewThread("second-new-thread")
	test("main-again")
}
`
<|endoftext|>


<commit_before>// Copyright (c) 2017 Daniel Oaks
// released under the MIT license

package irc

import (
	"reflect"
	"testing"

	"github.com/oragono/oragono/irc/modes"
)

func TestParseDefaultChannelModes(t *testing.T) {
	nt := "+nt"
	n := "+n"
	empty := ""
	tminusi := "+t -i"

	var parseTests = []struct {
		raw      *string
		expected modes.Modes
	}{
		{&nt, modes.Modes{modes.NoOutside, modes.OpOnlyTopic}},
		{&n, modes.Modes{modes.NoOutside}},
		{&empty, modes.Modes{}},
		{&tminusi, modes.Modes{modes.OpOnlyTopic}},
		{nil, modes.Modes{modes.NoOutside, modes.OpOnlyTopic}},
	}

	for _, testcase := range parseTests {
		result := ParseDefaultChannelModes(testcase.raw)
		if !reflect.DeepEqual(result, testcase.expected) {
			t.Errorf("expected modes %s, got %s", testcase.expected, result)
		}
	}
}

func TestUmodeGreaterThan(t *testing.T) {
	if !umodeGreaterThan(modes.Halfop, modes.Voice) {
		t.Errorf("expected Halfop > Voice")
	}

	if !umodeGreaterThan(modes.Voice, modes.Mode(0)) {
		t.Errorf("expected Voice > 0 (the zero value of modes.Mode)")
	}

	if umodeGreaterThan(modes.ChannelAdmin, modes.ChannelAdmin) {
		t.Errorf("modes should not be greater than themselves")
	}
}

func assertEqual(supplied, expected interface{}, t *testing.T) {
	if !reflect.DeepEqual(supplied, expected) {
		t.Errorf("expected %v but got %v", expected, supplied)
	}
}

func TestChannelUserModeHasPrivsOver(t *testing.T) {
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Mode(0), modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Mode(0)), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelAdmin, modes.ChannelAdmin), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Halfop, modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Voice), false, t)

	assertEqual(channelUserModeHasPrivsOver(modes.Halfop, modes.Voice), true, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelFounder, modes.ChannelAdmin), true, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelOperator, modes.ChannelOperator), true, t)
}
<commit_msg>Add test for ParseDefaultUserModes.<commit_after>// Copyright (c) 2017 Daniel Oaks
// released under the MIT license

package irc

import (
	"reflect"
	"testing"

	"github.com/oragono/oragono/irc/modes"
)

func TestParseDefaultChannelModes(t *testing.T) {
	nt := "+nt"
	n := "+n"
	empty := ""
	tminusi := "+t -i"

	var parseTests = []struct {
		raw      *string
		expected modes.Modes
	}{
		{&nt, modes.Modes{modes.NoOutside, modes.OpOnlyTopic}},
		{&n, modes.Modes{modes.NoOutside}},
		{&empty, modes.Modes{}},
		{&tminusi, modes.Modes{modes.OpOnlyTopic}},
		{nil, modes.Modes{modes.NoOutside, modes.OpOnlyTopic}},
	}

	for _, testcase := range parseTests {
		result := ParseDefaultChannelModes(testcase.raw)
		if !reflect.DeepEqual(result, testcase.expected) {
			t.Errorf("expected modes %s, got %s", testcase.expected, result)
		}
	}
}

func TestParseDefaultUserModes(t *testing.T) {
	iR := "+iR"
	i := "+i"
	empty := ""
	rminusi := "+R -i"

	var parseTests = []struct {
		raw      *string
		expected modes.Modes
	}{
		{&iR, modes.Modes{modes.Invisible, modes.RegisteredOnly}},
		{&i, modes.Modes{modes.Invisible}},
		{&empty, modes.Modes{}},
		{&rminusi, modes.Modes{modes.RegisteredOnly}},
		{nil, modes.Modes{}},
	}

	for _, testcase := range parseTests {
		result := ParseDefaultUserModes(testcase.raw)
		if !reflect.DeepEqual(result, testcase.expected) {
			t.Errorf("expected modes %s, got %s", testcase.expected, result)
		}
	}
}

func TestUmodeGreaterThan(t *testing.T) {
	if !umodeGreaterThan(modes.Halfop, modes.Voice) {
		t.Errorf("expected Halfop > Voice")
	}

	if !umodeGreaterThan(modes.Voice, modes.Mode(0)) {
		t.Errorf("expected Voice > 0 (the zero value of modes.Mode)")
	}

	if umodeGreaterThan(modes.ChannelAdmin, modes.ChannelAdmin) {
		t.Errorf("modes should not be greater than themselves")
	}
}

func assertEqual(supplied, expected interface{}, t *testing.T) {
	if !reflect.DeepEqual(supplied, expected) {
		t.Errorf("expected %v but got %v", expected, supplied)
	}
}

func TestChannelUserModeHasPrivsOver(t *testing.T) {
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Mode(0), modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Mode(0)), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelAdmin, modes.ChannelAdmin), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Halfop, modes.Halfop), false, t)
	assertEqual(channelUserModeHasPrivsOver(modes.Voice, modes.Voice), false, t)

	assertEqual(channelUserModeHasPrivsOver(modes.Halfop, modes.Voice), true, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelFounder, modes.ChannelAdmin), true, t)
	assertEqual(channelUserModeHasPrivsOver(modes.ChannelOperator, modes.ChannelOperator), true, t)
}
<|endoftext|>


<commit_before>// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license

package utils

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

const (
	IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
)

var (
	ErrInvalidParams = errors.New("Invalid parameters")
)

// ArgsToStrings takes the arguments and splits them into a series of strings,
// each argument separated by delim and each string bounded by maxLength.
func ArgsToStrings(maxLength int, arguments []string, delim string) []string {
	var messages []string

	var buffer string
	for {
		if len(arguments) < 1 {
			break
		}

		if len(buffer) > 0 && maxLength < len(buffer)+len(delim)+len(arguments[0]) {
			messages = append(messages, buffer)
			buffer = ""
			continue
		}

		if len(buffer) > 1 {
			buffer += delim
		}
		buffer += arguments[0]
		arguments = arguments[1:]
	}

	if len(buffer) > 0 {
		messages = append(messages, buffer)
	}

	return messages
}

func StringToBool(str string) (result bool, err error) {
	switch strings.ToLower(str) {
	case "on", "true", "t", "yes", "y", "disabled":
		result = true
	case "off", "false", "f", "no", "n", "enabled":
		result = false
	default:
		err = ErrInvalidParams
	}
	return
}

// Checks that a parameter can be passed as a non-trailing, and returns "*"
// if it can't. See #697.
func SafeErrorParam(param string) string {
	if param == "" || param[0] == ':' || strings.IndexByte(param, ' ') != -1 {
		return "*"
	}
	return param
}

type IncompatibleSchemaError struct {
	CurrentVersion  string
	RequiredVersion string
}

func (err *IncompatibleSchemaError) Error() string {
	return fmt.Sprintf("Database requires update. Expected schema v%s, got v%s", err.RequiredVersion, err.CurrentVersion)
}

func NanoToTimestamp(nanotime int64) string {
	return time.Unix(0, nanotime).Format(IRCv3TimestampFormat)
}
<commit_msg>fix StringToBool (thanks @wrmsr)<commit_after>// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license

package utils

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

const (
	IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
)

var (
	ErrInvalidParams = errors.New("Invalid parameters")
)

// ArgsToStrings takes the arguments and splits them into a series of strings,
// each argument separated by delim and each string bounded by maxLength.
func ArgsToStrings(maxLength int, arguments []string, delim string) []string {
	var messages []string

	var buffer string
	for {
		if len(arguments) < 1 {
			break
		}

		if len(buffer) > 0 && maxLength < len(buffer)+len(delim)+len(arguments[0]) {
			messages = append(messages, buffer)
			buffer = ""
			continue
		}

		if len(buffer) > 1 {
			buffer += delim
		}
		buffer += arguments[0]
		arguments = arguments[1:]
	}

	if len(buffer) > 0 {
		messages = append(messages, buffer)
	}

	return messages
}

func StringToBool(str string) (result bool, err error) {
	switch strings.ToLower(str) {
	case "on", "true", "t", "yes", "y", "enabled":
		result = true
	case "off", "false", "f", "no", "n", "disabled":
		result = false
	default:
		err = ErrInvalidParams
	}
	return
}

// Checks that a parameter can be passed as a non-trailing, and returns "*"
// if it can't. See #697.
func SafeErrorParam(param string) string {
	if param == "" || param[0] == ':' || strings.IndexByte(param, ' ') != -1 {
		return "*"
	}
	return param
}

type IncompatibleSchemaError struct {
	CurrentVersion  string
	RequiredVersion string
}

func (err *IncompatibleSchemaError) Error() string {
	return fmt.Sprintf("Database requires update. Expected schema v%s, got v%s", err.RequiredVersion, err.CurrentVersion)
}

func NanoToTimestamp(nanotime int64) string {
	return time.Unix(0, nanotime).Format(IRCv3TimestampFormat)
}
<|endoftext|>