<commit_before>package log

import (
	"time"

	"gopkg.in/stack.v1"
)

// Value is the return type of the Value method of the Valuer interface.
type Value interface{}

// A Valuer generates a log value. When passed to With, it represents a
// dynamic value which is re-evaluated with each log event.
// It returns a log Value instead of an interface{} to avoid
// inadvertently matching types from packages not intended for use with
// gokit/log.
type Valuer func() Value

// BindValues returns a slice with all value elements (odd indexes) that
// implement Valuer replaced with the result of calling their Value method. If
// no value elements implement Valuer, the original slice is returned.
func BindValues(keyvals ...interface{}) []interface{} {
	if !containsValuer(keyvals) {
		return keyvals
	}

	bound := make([]interface{}, len(keyvals))
	copy(bound, keyvals)
	for i := 1; i < len(bound); i += 2 {
		if v, ok := bound[i].(Valuer); ok {
			bound[i] = v()
		}
	}

	return bound
}

func containsValuer(keyvals []interface{}) bool {
	for i := 1; i < len(keyvals); i += 2 {
		if _, ok := keyvals[i].(Valuer); ok {
			return true
		}
	}
	return false
}

var (
	// Timestamp returns a Valuer that invokes the underlying function when bound,
	// returning a time.Time. Users will probably want to use DefaultTimestamp or
	// DefaultTimestampUTC.
	Timestamp = func(t func() time.Time) Valuer {
		return func() Value { return t() }
	}
	// DefaultTimestamp is a Timestamp Valuer that returns the current wallclock
	// time, respecting time zones, when bound.
	DefaultTimestamp = Timestamp(time.Now)
	// DefaultTimestampUTC wraps DefaultTimestamp but ensures the returned
	// time is always in UTC. Note that it invokes DefaultTimestamp, and so
	// reflects any changes to the DefaultTimestamp package global.
	DefaultTimestampUTC = Timestamp(func() time.Time {
		return DefaultTimestamp().(time.Time).UTC()
	})
	// Caller is a Valuer that returns a file and line from a specified depth in
	// the callstack. Users will probably want to use DefaultCaller.
	Caller = func(depth int) Valuer {
		return func() Value { return stack.Caller(depth) }
	}
	// DefaultCaller is a Valuer that returns the file and line where the Log
	// method was invoked.
	DefaultCaller = Caller(3)
)
<commit_msg>Eliminate the obsolete Value type.<commit_after>package log

import (
	"time"

	"gopkg.in/stack.v1"
)

// A Valuer generates a log value. When passed to With, it represents a
// dynamic value which is re-evaluated with each log event.
type Valuer func() interface{}

// BindValues returns a slice with all value elements (odd indexes) that
// implement Valuer replaced with the result of calling their Value method. If
// no value elements implement Valuer, the original slice is returned.
func BindValues(keyvals ...interface{}) []interface{} {
	if !containsValuer(keyvals) {
		return keyvals
	}

	bound := make([]interface{}, len(keyvals))
	copy(bound, keyvals)
	for i := 1; i < len(bound); i += 2 {
		if v, ok := bound[i].(Valuer); ok {
			bound[i] = v()
		}
	}

	return bound
}

func containsValuer(keyvals []interface{}) bool {
	for i := 1; i < len(keyvals); i += 2 {
		if _, ok := keyvals[i].(Valuer); ok {
			return true
		}
	}
	return false
}

var (
	// Timestamp returns a Valuer that invokes the underlying function when bound,
	// returning a time.Time. Users will probably want to use DefaultTimestamp or
	// DefaultTimestampUTC.
	Timestamp = func(t func() time.Time) Valuer {
		return func() interface{} { return t() }
	}
	// DefaultTimestamp is a Timestamp Valuer that returns the current wallclock
	// time, respecting time zones, when bound.
	DefaultTimestamp = Timestamp(time.Now)
	// DefaultTimestampUTC wraps DefaultTimestamp but ensures the returned
	// time is always in UTC. Note that it invokes DefaultTimestamp, and so
	// reflects any changes to the DefaultTimestamp package global.
	DefaultTimestampUTC = Timestamp(func() time.Time {
		return DefaultTimestamp().(time.Time).UTC()
	})
	// Caller is a Valuer that returns a file and line from a specified depth in
	// the callstack. Users will probably want to use DefaultCaller.
	Caller = func(depth int) Valuer {
		return func() interface{} { return stack.Caller(depth) }
	}
	// DefaultCaller is a Valuer that returns the file and line where the Log
	// method was invoked.
	DefaultCaller = Caller(3)
)
<|endoftext|>


<commit_before>package lint_test

import (
	"testing"

	"log"

	"fmt"
	"reflect"
	"runtime/debug"

	"strings"

	"github.com/surullabs/lint"
	"github.com/surullabs/lint/checkers"
	"github.com/surullabs/lint/dupl"
)

func TestLint(t *testing.T) {
	err := lint.Default.With(dupl.Check{Threshold: 25}).Check("./...")
	err = lint.Skip(err,
		// Ignore all errors from unused.go
		lint.RegexpMatch(`unused\.go`),
		// Ignore duplicates we're okay with.
		dupl.SkipTwo, dupl.Skip("golint.go:1,12"))

	if err != nil {
		t.Fatal(err)
	}
}

type checkFn func(pkgs ...string) error

func (c checkFn) Check(pkgs ...string) error { return c(pkgs...) }

func assert(t *testing.T, cond bool, msg string) {
	if cond {
		return
	}
	t.Fatal(msg, string(debug.Stack()))
}

var (
	expectRecursive = checkFn(func(args ...string) error {
		if !reflect.DeepEqual(args, []string{"./..."}) {
			return fmt.Errorf("expected [./...], got %v", args)
		}
		return nil
	})

	twoErrors = checkFn(func(...string) error {
		return checkers.Error("err1", "err2")
	})

	ungroupedError = checkFn(func(...string) error {
		return fmt.Errorf("ungrouped: %d", 1)
	})
)

func TestGroup(t *testing.T) {
	gcheck := func(fn ...lint.Checker) error {
		return lint.Group(fn).Check("./...")
	}

	// All checks pass
	err := gcheck(expectRecursive)
	assert(t, err == nil, fmt.Sprintf("%v", err))

	err = gcheck(twoErrors)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err1\nlint_test.checkFn: err2",
		fmt.Sprintf("%v", err))

	err = gcheck(ungroupedError)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))

	// Grouped
	err = gcheck(twoErrors, ungroupedError)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err1\nlint_test.checkFn: err2\nlint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))
}

type skipFunc func(err string) bool

func (s skipFunc) Skip(err string) bool { return s(err) }

func errorIs(str string) skipFunc {
	return skipFunc(func(err string) bool { return str == err })
}

func scheck(c lint.Checker, skippers ...lint.Skipper) error {
	return lint.Skip(c.Check("./..."), skippers...)
}

func TestSkip(t *testing.T) {
	// All checks pass
	err := scheck(expectRecursive, errorIs("err1"))
	assert(t, err == nil, fmt.Sprintf("%v", err))

	err = scheck(twoErrors, errorIs("err1"))
	assert(t,
		err != nil && err.Error() == "err2",
		fmt.Sprintf("%v", err))

	// Skip ungrouped error
	err = scheck(ungroupedError, errorIs("ungrouped: 1"))
	assert(t, err == nil, fmt.Sprintf("%v", err))

	// Skip don't skip ungrouped error
	err = scheck(ungroupedError, errorIs("err1"))
	assert(t, err != nil && err.Error() == "ungrouped: 1", fmt.Sprintf("%v", err))

	// Grouped
	err = scheck(lint.Group{twoErrors, ungroupedError}, errorIs("lint_test.checkFn: err1"))
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err2\nlint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))

}

func TestRegexpMatch(t *testing.T) {
	// regexp match
	skipRE := lint.RegexpMatch(`err1`, `ungrouped`)
	err := scheck(lint.Group{twoErrors, ungroupedError}, skipRE)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err2",
		fmt.Sprintf("%v", err))

	// panic on bad RE

	func() {
		defer func() {
			r := recover()
			if r != nil {
				err = fmt.Errorf("%v", r)
			}
		}()
		_ = scheck(twoErrors, lint.RegexpMatch(`(unmatched paren`))
	}()
	assert(t,
		err != nil && strings.HasPrefix(err.Error(), "error parsing regexp"),
		fmt.Sprintf("%v", err))
}

func Example() {
	// Run the default set of linters
	err := lint.Default.Check("./...")

	// Ignore all errors from the file unused.go.
	//
	// This is intended as an example of how to skip errors and not a
	// recommendation that you skip these kinds of errors.
	err = lint.Skip(err, lint.RegexpMatch(
		`unused\.go:4:2: a blank import`,
		`unused\.go:7:7: don't use underscores in Go names`,
	))

	if err != nil {
		// Record lint failures.
		// Use t.Fatal(err) when running in a test
		log.Fatal(err)
	}
	// Output:
}

<commit_msg>More examples<commit_after>package lint_test

import (
	"testing"

	"log"

	"fmt"
	"reflect"
	"runtime/debug"

	"strings"

	"github.com/surullabs/lint"
	"github.com/surullabs/lint/checkers"
	"github.com/surullabs/lint/dupl"
	"github.com/surullabs/lint/gofmt"
	"github.com/surullabs/lint/govet"
)

func TestLint(t *testing.T) {
	err := lint.Default.With(dupl.Check{Threshold: 25}).Check("./...")
	err = lint.Skip(err,
		// Ignore all errors from unused.go
		lint.RegexpMatch(`unused\.go`),
		// Ignore duplicates we're okay with.
		dupl.SkipTwo, dupl.Skip("golint.go:1,12"))

	if err != nil {
		t.Fatal(err)
	}
}

type checkFn func(pkgs ...string) error

func (c checkFn) Check(pkgs ...string) error { return c(pkgs...) }

func assert(t *testing.T, cond bool, msg string) {
	if cond {
		return
	}
	t.Fatal(msg, string(debug.Stack()))
}

var (
	expectRecursive = checkFn(func(args ...string) error {
		if !reflect.DeepEqual(args, []string{"./..."}) {
			return fmt.Errorf("expected [./...], got %v", args)
		}
		return nil
	})

	twoErrors = checkFn(func(...string) error {
		return checkers.Error("err1", "err2")
	})

	ungroupedError = checkFn(func(...string) error {
		return fmt.Errorf("ungrouped: %d", 1)
	})
)

func TestGroup(t *testing.T) {
	gcheck := func(fn ...lint.Checker) error {
		return lint.Group(fn).Check("./...")
	}

	// All checks pass
	err := gcheck(expectRecursive)
	assert(t, err == nil, fmt.Sprintf("%v", err))

	err = gcheck(twoErrors)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err1\nlint_test.checkFn: err2",
		fmt.Sprintf("%v", err))

	err = gcheck(ungroupedError)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))

	// Grouped
	err = gcheck(twoErrors, ungroupedError)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err1\nlint_test.checkFn: err2\nlint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))
}

type skipFunc func(err string) bool

func (s skipFunc) Skip(err string) bool { return s(err) }

func errorIs(str string) skipFunc {
	return skipFunc(func(err string) bool { return str == err })
}

func scheck(c lint.Checker, skippers ...lint.Skipper) error {
	return lint.Skip(c.Check("./..."), skippers...)
}

func TestSkip(t *testing.T) {
	// All checks pass
	err := scheck(expectRecursive, errorIs("err1"))
	assert(t, err == nil, fmt.Sprintf("%v", err))

	err = scheck(twoErrors, errorIs("err1"))
	assert(t,
		err != nil && err.Error() == "err2",
		fmt.Sprintf("%v", err))

	// Skip ungrouped error
	err = scheck(ungroupedError, errorIs("ungrouped: 1"))
	assert(t, err == nil, fmt.Sprintf("%v", err))

	// Skip don't skip ungrouped error
	err = scheck(ungroupedError, errorIs("err1"))
	assert(t, err != nil && err.Error() == "ungrouped: 1", fmt.Sprintf("%v", err))

	// Grouped
	err = scheck(lint.Group{twoErrors, ungroupedError}, errorIs("lint_test.checkFn: err1"))
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err2\nlint_test.checkFn: ungrouped: 1",
		fmt.Sprintf("%v", err))

}

func TestRegexpMatch(t *testing.T) {
	// regexp match
	skipRE := lint.RegexpMatch(`err1`, `ungrouped`)
	err := scheck(lint.Group{twoErrors, ungroupedError}, skipRE)
	assert(t,
		err != nil && err.Error() == "lint_test.checkFn: err2",
		fmt.Sprintf("%v", err))

	// panic on bad RE

	func() {
		defer func() {
			r := recover()
			if r != nil {
				err = fmt.Errorf("%v", r)
			}
		}()
		_ = scheck(twoErrors, lint.RegexpMatch(`(unmatched paren`))
	}()
	assert(t,
		err != nil && strings.HasPrefix(err.Error(), "error parsing regexp"),
		fmt.Sprintf("%v", err))
}

func Example() {
	// Run the default set of linters
	err := lint.Default.Check("./...")

	// Ignore all errors from the file unused.go.
	//
	// This is intended as an example of how to skip errors and not a
	// recommendation that you skip these kinds of errors.
	err = lint.Skip(err, lint.RegexpMatch(
		`unused\.go:4:2: a blank import`,
		`unused\.go:7:7: don't use underscores in Go names`,
	))

	if err != nil {
		// Record lint failures.
		// Use t.Fatal(err) when running in a test
		log.Fatal(err)
	}
	// Output:
}

func Example_custom() {
	// Run a custom set of linters
	custom := lint.Group{
		gofmt.Check{}, govet.Check{},
	}
	if err := custom.Check("./..."); err != nil {
		// Record lint failures.
		// Use t.Fatal(err) when running in a test
		log.Fatal(err)
	}
	// Output:
}

func Example_packages() {
	custom := lint.Group{gofmt.Check{}, govet.Check{}}

	// Specify a list of packages instead of the wildcard
	if err := custom.Check(".", "./checkers"); err != nil {
		// Record lint failures.
		// Use t.Fatal(err) when running in a test
		log.Fatal(err)
	}
	// Output:
}
<|endoftext|>


<commit_before>package ebpf

import (
	"io/ioutil"
	"os"
	"path/filepath"
)

// CollectionSpec describes a collection.
type CollectionSpec struct {
	Maps     map[string]*MapSpec
	Programs map[string]*ProgramSpec
}

// Collection is a collection of Programs and Maps associated
// with their symbols
type Collection struct {
	programs map[string]*Program
	maps     map[string]*Map
}

// NewCollection creates a Collection from a specification
func NewCollection(spec *CollectionSpec) (*Collection, error) {
	maps := make(map[string]*Map)
	for k, spec := range spec.Maps {
		m, err := NewMap(spec)
		if err != nil {
			return nil, err
		}
		maps[k] = m
	}
	progs := make(map[string]*Program)
	for k, spec := range spec.Programs {
		// Rewrite any Symbol which is a valid Map.
		for name := range spec.Refs {
			m, ok := maps[name]
			if !ok {
				continue
			}
			if err := spec.RewriteMap(name, m); err != nil {
				return nil, err
			}
		}
		prog, err := NewProgram(spec)
		if err != nil {
			return nil, err
		}
		progs[k] = prog
	}
	return &Collection{
		progs,
		maps,
	}, nil
}

// ForEachMap iterates over all the Maps in a Collection
func (coll *Collection) ForEachMap(fx func(string, *Map)) {
	for k, v := range coll.maps {
		fx(k, v)
	}
}

// ForEachProgram iterates over all the Programs in a Collection
func (coll *Collection) ForEachProgram(fx func(string, *Program)) {
	for k, v := range coll.programs {
		fx(k, v)
	}
}

// GetMapByName get a Map by its symbolic name
func (coll *Collection) GetMapByName(key string) (*Map, bool) {
	v, ok := coll.maps[key]
	return v, ok
}

// GetProgramByName get a Program by its symbolic name
func (coll *Collection) GetProgramByName(key string) (*Program, bool) {
	v, ok := coll.programs[key]
	return v, ok
}

// Pin persits a Collection beyond the lifetime of the process that created it
func (coll *Collection) Pin(dirName string, fileMode os.FileMode) error {
	err := mkdirIfNotExists(dirName, fileMode)
	if err != nil {
		return err
	}
	if len(coll.maps) > 0 {
		mapPath := filepath.Join(dirName, "maps")
		err = mkdirIfNotExists(mapPath, fileMode)
		if err != nil {
			return err
		}
		for k, v := range coll.maps {
			err := v.Pin(filepath.Join(mapPath, k))
			if err != nil {
				return err
			}
		}
	}
	if len(coll.programs) > 0 {
		progPath := filepath.Join(dirName, "programs")
		err = mkdirIfNotExists(progPath, fileMode)
		if err != nil {
			return err
		}
		for k, v := range coll.programs {
			err = v.Pin(filepath.Join(progPath, k))
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func mkdirIfNotExists(dirName string, fileMode os.FileMode) error {
	_, err := os.Stat(dirName)
	if err != nil && os.IsNotExist(err) {
		err = os.Mkdir(dirName, fileMode)
	}
	if err != nil {
		return err
	}
	return nil
}

// LoadCollection loads a Collection from the pinned directory.
//
// Requires at least Linux 4.13, use LoadCollectionExplicit on
// earlier versions.
func LoadCollection(dirName string) (*Collection, error) {
	return loadCollection(
		dirName,
		func(_ string, path string) (*Map, error) {
			return LoadMap(path)
		},
		func(_ string, path string) (*Program, error) {
			return LoadProgram(path)
		},
	)
}

// LoadCollection loads a Collection from the pinned directory with explicit parameters.
func LoadCollectionExplicit(dirName string, maps map[string]*MapSpec, progs map[string]ProgType) (*Collection, error) {
	return loadCollection(
		dirName,
		func(name string, path string) (*Map, error) {
			return LoadMapExplicit(path, maps[name])
		},
		func(name string, path string) (*Program, error) {
			return LoadProgramExplicit(path, progs[name])
		},
	)
}

func loadCollection(dirName string, loadMap func(string, string) (*Map, error), loadProgram func(string, string) (*Program, error)) (*Collection, error) {
	maps, err := readFileNames(filepath.Join(dirName, "maps"))
	if err != nil {
		return nil, err
	}
	progs, err := readFileNames(filepath.Join(dirName, "programs"))
	if err != nil {
		return nil, err
	}
	bpfColl := &Collection{
		maps:     make(map[string]*Map),
		programs: make(map[string]*Program),
	}
	for _, mf := range maps {
		name := filepath.Base(mf)
		m, err := loadMap(name, mf)
		if err != nil {
			return nil, err
		}
		bpfColl.maps[name] = m
	}
	for _, pf := range progs {
		name := filepath.Base(pf)
		prog, err := loadProgram(name, pf)
		if err != nil {
			return nil, err
		}
		bpfColl.programs[name] = prog
	}
	return bpfColl, nil
}

func readFileNames(dirName string) ([]string, error) {
	var fileNames []string
	files, err := ioutil.ReadDir(dirName)
	if err != nil && err != os.ErrNotExist {
		return nil, err
	}
	for _, fi := range files {
		fileNames = append(fileNames, fi.Name())
	}
	return fileNames, nil
}

// NewCollectionFromFile parse an object file and convert it to a collection
func NewCollectionFromFile(file string) (*Collection, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	spec, err := NewCollectionSpecFromELF(f)
	if err != nil {
		return nil, err
	}
	return NewCollection(spec)
}
<commit_msg>add Collection.Close() method<commit_after>package ebpf

import (
	"io/ioutil"
	"os"
	"path/filepath"
)

// CollectionSpec describes a collection.
type CollectionSpec struct {
	Maps     map[string]*MapSpec
	Programs map[string]*ProgramSpec
}

// Collection is a collection of Programs and Maps associated
// with their symbols
type Collection struct {
	programs map[string]*Program
	maps     map[string]*Map
}

// NewCollection creates a Collection from a specification
func NewCollection(spec *CollectionSpec) (*Collection, error) {
	maps := make(map[string]*Map)
	for k, spec := range spec.Maps {
		m, err := NewMap(spec)
		if err != nil {
			return nil, err
		}
		maps[k] = m
	}
	progs := make(map[string]*Program)
	for k, spec := range spec.Programs {
		// Rewrite any Symbol which is a valid Map.
		for name := range spec.Refs {
			m, ok := maps[name]
			if !ok {
				continue
			}
			if err := spec.RewriteMap(name, m); err != nil {
				return nil, err
			}
		}
		prog, err := NewProgram(spec)
		if err != nil {
			return nil, err
		}
		progs[k] = prog
	}
	return &Collection{
		progs,
		maps,
	}, nil
}

// Close frees all maps and programs associated with the collection.
//
// The collection mustn't be used afterwards.
func (coll *Collection) Close() {
	for _, prog := range coll.programs {
		prog.Close()
	}
	for _, m := range coll.maps {
		m.Close()
	}
}

// ForEachMap iterates over all the Maps in a Collection
func (coll *Collection) ForEachMap(fx func(string, *Map)) {
	for k, v := range coll.maps {
		fx(k, v)
	}
}

// ForEachProgram iterates over all the Programs in a Collection
func (coll *Collection) ForEachProgram(fx func(string, *Program)) {
	for k, v := range coll.programs {
		fx(k, v)
	}
}

// GetMapByName get a Map by its symbolic name
func (coll *Collection) GetMapByName(key string) (*Map, bool) {
	v, ok := coll.maps[key]
	return v, ok
}

// GetProgramByName get a Program by its symbolic name
func (coll *Collection) GetProgramByName(key string) (*Program, bool) {
	v, ok := coll.programs[key]
	return v, ok
}

// Pin persits a Collection beyond the lifetime of the process that created it
func (coll *Collection) Pin(dirName string, fileMode os.FileMode) error {
	err := mkdirIfNotExists(dirName, fileMode)
	if err != nil {
		return err
	}
	if len(coll.maps) > 0 {
		mapPath := filepath.Join(dirName, "maps")
		err = mkdirIfNotExists(mapPath, fileMode)
		if err != nil {
			return err
		}
		for k, v := range coll.maps {
			err := v.Pin(filepath.Join(mapPath, k))
			if err != nil {
				return err
			}
		}
	}
	if len(coll.programs) > 0 {
		progPath := filepath.Join(dirName, "programs")
		err = mkdirIfNotExists(progPath, fileMode)
		if err != nil {
			return err
		}
		for k, v := range coll.programs {
			err = v.Pin(filepath.Join(progPath, k))
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func mkdirIfNotExists(dirName string, fileMode os.FileMode) error {
	_, err := os.Stat(dirName)
	if err != nil && os.IsNotExist(err) {
		err = os.Mkdir(dirName, fileMode)
	}
	if err != nil {
		return err
	}
	return nil
}

// LoadCollection loads a Collection from the pinned directory.
//
// Requires at least Linux 4.13, use LoadCollectionExplicit on
// earlier versions.
func LoadCollection(dirName string) (*Collection, error) {
	return loadCollection(
		dirName,
		func(_ string, path string) (*Map, error) {
			return LoadMap(path)
		},
		func(_ string, path string) (*Program, error) {
			return LoadProgram(path)
		},
	)
}

// LoadCollectionExplicit loads a Collection from the pinned directory with explicit parameters.
func LoadCollectionExplicit(dirName string, maps map[string]*MapSpec, progs map[string]ProgType) (*Collection, error) {
	return loadCollection(
		dirName,
		func(name string, path string) (*Map, error) {
			return LoadMapExplicit(path, maps[name])
		},
		func(name string, path string) (*Program, error) {
			return LoadProgramExplicit(path, progs[name])
		},
	)
}

func loadCollection(dirName string, loadMap func(string, string) (*Map, error), loadProgram func(string, string) (*Program, error)) (*Collection, error) {
	maps, err := readFileNames(filepath.Join(dirName, "maps"))
	if err != nil {
		return nil, err
	}
	progs, err := readFileNames(filepath.Join(dirName, "programs"))
	if err != nil {
		return nil, err
	}
	bpfColl := &Collection{
		maps:     make(map[string]*Map),
		programs: make(map[string]*Program),
	}
	for _, mf := range maps {
		name := filepath.Base(mf)
		m, err := loadMap(name, mf)
		if err != nil {
			return nil, err
		}
		bpfColl.maps[name] = m
	}
	for _, pf := range progs {
		name := filepath.Base(pf)
		prog, err := loadProgram(name, pf)
		if err != nil {
			return nil, err
		}
		bpfColl.programs[name] = prog
	}
	return bpfColl, nil
}

func readFileNames(dirName string) ([]string, error) {
	var fileNames []string
	files, err := ioutil.ReadDir(dirName)
	if err != nil && err != os.ErrNotExist {
		return nil, err
	}
	for _, fi := range files {
		fileNames = append(fileNames, fi.Name())
	}
	return fileNames, nil
}

// NewCollectionFromFile parse an object file and convert it to a collection
func NewCollectionFromFile(file string) (*Collection, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	spec, err := NewCollectionSpecFromELF(f)
	if err != nil {
		return nil, err
	}
	return NewCollection(spec)
}
<|endoftext|>


<commit_before>package cm15

import "time"

// Wrapper around time.Time that adds the ability to unmarshal ruby json date time values
type RubyTime struct {
	time.Time
}

// Implement unmarshaller interface
func (r *RubyTime) Unmarshal(data []byte, v interface{}) error {
	t, err := time.Parse("2006/01/02 15:04:05 -0700", string(data))
	if err != nil {
		return err
	}
	r.Time = t
	return nil
}
<commit_msg>Fix ruby time parsing.<commit_after>package cm15

import "time"

// Wrapper around time.Time that adds the ability to unmarshal ruby json date time values
type RubyTime struct {
	time.Time
}

// Implement unmarshaller interface
func (r *RubyTime) UnmarshalJSON(b []byte) (err error) {
	s := string(b)
	t, err := time.Parse("2006/01/02 15:04:05 -0700", s[1:len(s)-1])
	if err != nil {
		return err
	}
	r.Time = t
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 cmac_test

import (
	"encoding/hex"
	"github.com/jacobsa/aes/cmac"
	aes_testing "github.com/jacobsa/aes/testing"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestHash(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func runCmac(key []byte, msg []byte) []byte {
	h, err := cmac.New(key)
	AssertEq(nil, err)

	_, err = h.Write(msg)
	AssertEq(nil, err)

	return h.Sum([]byte{})
}

type HashTest struct{}

func init() { RegisterTestSuite(&HashTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *HashTest) NilKey() {
	ExpectEq("TODO", "")
}

func (t *HashTest) ShortKey() {
	ExpectEq("TODO", "")
}

func (t *HashTest) LongKey() {
	ExpectEq("TODO", "")
}

func (t *HashTest) SumAppendsToSlice() {
	ExpectEq("TODO", "")
}

func (t *HashTest) Reset() {
	ExpectEq("TODO", "")
}

func (t *HashTest) Size() {
	ExpectEq("TODO", "")
}

func (t *HashTest) BlockSize() {
	ExpectEq("TODO", "")
}

func (t *HashTest) NilMessage() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	var msg []byte = nil

	expectedMac, err := hex.DecodeString("bb1d6929e95937287fa37d129b756746")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase1() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString("")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("bb1d6929e95937287fa37d129b756746")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase2() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString("6bc1bee22e409f96e93d7e117393172a")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("070a16b46b4d4144f79bdd9dd04a287c")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase3() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString(
		"6bc1bee22e409f96e93d7e117393172a" +
			"ae2d8a571e03ac9c9eb76fac45af8e51" +
			"30c81c46a35ce411")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("dfa66747de9ae63030ca32611497c827")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase4() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString(
		"6bc1bee22e409f96e93d7e117393172a" +
			"ae2d8a571e03ac9c9eb76fac45af8e51" +
			"30c81c46a35ce411e5fbc1191a0a52ef" +
			"f69f2445df4f9b17ad2b417be66c3710")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("51f0bebf7e3b9d92fc49741779363cfe")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) GeneratedTestCases() {
	cases := aes_testing.GenerateCmacCases()
	AssertGe(len(cases), 100)

	for i, c := range cases {
		mac := runCmac(c.Key, c.Msg)
		ExpectThat(mac, DeepEquals(c.Mac), "Test case %d: %v", i, c)
	}
}
<commit_msg>HashTest.LongKey<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 cmac_test

import (
	"encoding/hex"
	"github.com/jacobsa/aes/cmac"
	aes_testing "github.com/jacobsa/aes/testing"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestHash(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func runCmac(key []byte, msg []byte) []byte {
	h, err := cmac.New(key)
	AssertEq(nil, err)

	_, err = h.Write(msg)
	AssertEq(nil, err)

	return h.Sum([]byte{})
}

type HashTest struct{}

func init() { RegisterTestSuite(&HashTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *HashTest) NilKey() {
	_, err := cmac.New(nil)
	ExpectThat(err, Error(HasSubstr("16-byte")))
}

func (t *HashTest) ShortKey() {
	_, err := cmac.New(make([]byte, 15))
	ExpectThat(err, Error(HasSubstr("16-byte")))
}

func (t *HashTest) LongKey() {
	_, err := cmac.New(make([]byte, 17))
	ExpectThat(err, Error(HasSubstr("16-byte")))
}

func (t *HashTest) SumAppendsToSlice() {
	ExpectEq("TODO", "")
}

func (t *HashTest) Reset() {
	ExpectEq("TODO", "")
}

func (t *HashTest) Size() {
	ExpectEq("TODO", "")
}

func (t *HashTest) BlockSize() {
	ExpectEq("TODO", "")
}

func (t *HashTest) NilMessage() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	var msg []byte = nil

	expectedMac, err := hex.DecodeString("bb1d6929e95937287fa37d129b756746")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase1() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString("")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("bb1d6929e95937287fa37d129b756746")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase2() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString("6bc1bee22e409f96e93d7e117393172a")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("070a16b46b4d4144f79bdd9dd04a287c")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase3() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString(
		"6bc1bee22e409f96e93d7e117393172a" +
			"ae2d8a571e03ac9c9eb76fac45af8e51" +
			"30c81c46a35ce411")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("dfa66747de9ae63030ca32611497c827")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) Rfc4493GoldenTestCase4() {
	key, err := hex.DecodeString("2b7e151628aed2a6abf7158809cf4f3c")
	AssertEq(nil, err)

	msg, err := hex.DecodeString(
		"6bc1bee22e409f96e93d7e117393172a" +
			"ae2d8a571e03ac9c9eb76fac45af8e51" +
			"30c81c46a35ce411e5fbc1191a0a52ef" +
			"f69f2445df4f9b17ad2b417be66c3710")
	AssertEq(nil, err)

	expectedMac, err := hex.DecodeString("51f0bebf7e3b9d92fc49741779363cfe")
	AssertEq(nil, err)

	mac := runCmac(key, msg)
	ExpectThat(mac, DeepEquals(expectedMac))
}

func (t *HashTest) GeneratedTestCases() {
	cases := aes_testing.GenerateCmacCases()
	AssertGe(len(cases), 100)

	for i, c := range cases {
		mac := runCmac(c.Key, c.Msg)
		ExpectThat(mac, DeepEquals(c.Mac), "Test case %d: %v", i, c)
	}
}
<|endoftext|>


<commit_before>/*
This package is just a collection of test cases
*/
package main

import (
	"fmt"
	"github.com/codegangsta/cli"
	"os"
	"ripe-atlas"
	"strconv"
)

// main is the starting point (and everything)
func main() {
	app := cli.NewApp()
	app.Name = "atlas"
	app.Commands = []cli.Command{
		{
			Name:        "probes",
			Aliases:     []string{"p"},
			Usage:       "use it to see a description",
			Description: "This is how we describe hello the function",
			Subcommands: []cli.Command{
				{
					Name:        "list",
					Aliases:     []string{"ls"},
					Usage:       "lists all probes",
					Description: "greets someone in english",
					Action: func(c *cli.Context) error {
						q, err := atlas.GetProbes()
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("q: %#v\n", q)

						return nil
					},
				},
				{
					Name:        "info",
					Usage:       "info for one probe",
					Description: "gives info for one probe",
					Flags: []cli.Flag{
						cli.IntFlag{
							Name:  "id",
							Value: 0,
							Usage: "id of the probe",
						},
					},
					Action: func(c *cli.Context) error {
						args := c.Args()
						id, _ := strconv.ParseInt(args[0], 10, 32)

						p, err := atlas.GetProbe(int(id))
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("p: %#v\n", p)

						return nil
					},
				},
			},
		},
	}
	app.Run(os.Args)

}
<commit_msg>Add aliases ro the probe command.<commit_after>/*
This package is just a collection of test cases
*/
package main

import (
	"fmt"
	"github.com/codegangsta/cli"
	"os"
	"ripe-atlas"
	"strconv"
)

// main is the starting point (and everything)
func main() {
	app := cli.NewApp()
	app.Name = "atlas"
	app.Commands = []cli.Command{
		{
			Name: "probes",
			Aliases: []string{
				"p",
				"pb",
			},
			Usage:       "use it to see a description",
			Description: "This is how we describe hello the function",
			Subcommands: []cli.Command{
				{
					Name:        "list",
					Aliases:     []string{"ls"},
					Usage:       "lists all probes",
					Description: "greets someone in english",
					Action: func(c *cli.Context) error {
						q, err := atlas.GetProbes()
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("q: %#v\n", q)

						return nil
					},
				},
				{
					Name:        "info",
					Usage:       "info for one probe",
					Description: "gives info for one probe",
					Flags: []cli.Flag{
						cli.IntFlag{
							Name:  "id",
							Value: 0,
							Usage: "id of the probe",
						},
					},
					Action: func(c *cli.Context) error {
						args := c.Args()
						id, _ := strconv.ParseInt(args[0], 10, 32)

						p, err := atlas.GetProbe(int(id))
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("p: %#v\n", p)

						return nil
					},
				},
			},
		},
	}
	app.Run(os.Args)

}
<|endoftext|>


<commit_before>// Copyright 2021 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 main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"text/template"
)

// TODO(prattmic): refactor bent to export Todo so we can directly build this
// in Go.
var configurationTmpl = template.Must(template.New("configuration").Parse(`
{{- range . -}}
[[Configurations]]
  Name = "{{.Name}}"
  Root = "{{.GOROOT}}"

{{end -}}
`))

func writeBentConfiguration(filename string, tcs []*toolchain) error {
	var buf bytes.Buffer
	if err := configurationTmpl.Execute(&buf, tcs); err != nil {
		return fmt.Errorf("error generating configuration: %w", err)
	}

	log.Printf("bent configuration:\n%s", buf.String())

	if err := os.WriteFile(filename, buf.Bytes(), 0644); err != nil {
		return fmt.Errorf("error creating configurations.toml: %w", err)
	}
	return nil
}

// removeAllIncludingReadonly is like os.RemoveAll except that it'll
// also try to change permissions to work around permission errors
// when deleting.
func removeAllIncludingReadonly(dir string) error {
	err := os.RemoveAll(dir)
	if err == nil || !os.IsPermission(err) || runtime.GOOS == "windows" /* different fs permission model */ {
		return err
	}
	// Make a best effort (ignoring errors) attempt to make all
	// files and directories writable before we try to delete them
	// all again.
	filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
		const ownerWritable = 0200
		if err != nil || fi.Mode().Perm()&ownerWritable != 0 {
			return nil
		}
		os.Chmod(path, fi.Mode().Perm()|ownerWritable)
		return nil
	})
	return os.RemoveAll(dir)
}

func bent(tcs []*toolchain) (err error) {
	dir, err := os.MkdirTemp("", "bent")
	if err != nil {
		return fmt.Errorf("error creating temporary directory: %w", err)
	}
	defer func() {
		r := removeAllIncludingReadonly(dir)
		if r != nil && err == nil {
			err = fmt.Errorf("error removing temporary directory: %w", err)
		} else if r != nil {
			log.Printf("error removing temporary directory: %v", err)
		}
	}()
	log.Printf("Bent temporary directory: %s", dir)

	log.Printf("Building bent...")

	// Build bent itself. Just pick any toolchain we have; it doesn't matter which.
	// We're not benchmarking bent itself, it's just a driver.
	bentPath := filepath.Join(dir, "bent")
	if err := tcs[0].BuildPackage("golang.org/x/benchmarks/cmd/bent", bentPath); err != nil {
		return fmt.Errorf("building bent: %w", err)
	}

	log.Printf("Initializing bent...")

	// Initialize scratch dir for bent.
	cmd := exec.Command(bentPath, "-I")
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running bent -I: %w", err)
	}

	confFile := filepath.Join(dir, "configurations.toml")
	if err := writeBentConfiguration(confFile, tcs); err != nil {
		return fmt.Errorf("error writing configuration: %w", err)
	}

	log.Printf("Running bent...")

	// Finally we can actually run the benchmarks.
	// N.B. bent prints the "toolchain" tag to indicate which toolchain is being used.
	// It's passed to bent via the TOML configuration.
	cmd = exec.Command(bentPath, "-C", confFile, "-B", filepath.Join(dir, "benchmarks-50.toml"))
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running bent -I: %w", err)
	}
	return nil
}
<commit_msg>cmd/bench: run 10 iterations for each bent benchmark<commit_after>// Copyright 2021 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 main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"text/template"
)

// TODO(prattmic): refactor bent to export Todo so we can directly build this
// in Go.
var configurationTmpl = template.Must(template.New("configuration").Parse(`
{{- range . -}}
[[Configurations]]
  Name = "{{.Name}}"
  Root = "{{.GOROOT}}"

{{end -}}
`))

func writeBentConfiguration(filename string, tcs []*toolchain) error {
	var buf bytes.Buffer
	if err := configurationTmpl.Execute(&buf, tcs); err != nil {
		return fmt.Errorf("error generating configuration: %w", err)
	}

	log.Printf("bent configuration:\n%s", buf.String())

	if err := os.WriteFile(filename, buf.Bytes(), 0644); err != nil {
		return fmt.Errorf("error creating configurations.toml: %w", err)
	}
	return nil
}

// removeAllIncludingReadonly is like os.RemoveAll except that it'll
// also try to change permissions to work around permission errors
// when deleting.
func removeAllIncludingReadonly(dir string) error {
	err := os.RemoveAll(dir)
	if err == nil || !os.IsPermission(err) || runtime.GOOS == "windows" /* different fs permission model */ {
		return err
	}
	// Make a best effort (ignoring errors) attempt to make all
	// files and directories writable before we try to delete them
	// all again.
	filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
		const ownerWritable = 0200
		if err != nil || fi.Mode().Perm()&ownerWritable != 0 {
			return nil
		}
		os.Chmod(path, fi.Mode().Perm()|ownerWritable)
		return nil
	})
	return os.RemoveAll(dir)
}

func bent(tcs []*toolchain) (err error) {
	dir, err := os.MkdirTemp("", "bent")
	if err != nil {
		return fmt.Errorf("error creating temporary directory: %w", err)
	}
	defer func() {
		r := removeAllIncludingReadonly(dir)
		if r != nil && err == nil {
			err = fmt.Errorf("error removing temporary directory: %w", err)
		} else if r != nil {
			log.Printf("error removing temporary directory: %v", err)
		}
	}()
	log.Printf("Bent temporary directory: %s", dir)

	log.Printf("Building bent...")

	// Build bent itself. Just pick any toolchain we have; it doesn't matter which.
	// We're not benchmarking bent itself, it's just a driver.
	bentPath := filepath.Join(dir, "bent")
	if err := tcs[0].BuildPackage("golang.org/x/benchmarks/cmd/bent", bentPath); err != nil {
		return fmt.Errorf("building bent: %w", err)
	}

	log.Printf("Initializing bent...")

	// Initialize scratch dir for bent.
	cmd := exec.Command(bentPath, "-I")
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running bent -I: %w", err)
	}

	confFile := filepath.Join(dir, "configurations.toml")
	if err := writeBentConfiguration(confFile, tcs); err != nil {
		return fmt.Errorf("error writing configuration: %w", err)
	}

	log.Printf("Running bent...")

	// Finally we can actually run the benchmarks.
	// N.B. bent prints the "toolchain" tag to indicate which toolchain is being used.
	// It's passed to bent via the TOML configuration.
	cmd = exec.Command(bentPath,
		"-N", "10",
		"-C", confFile,
		"-B", filepath.Join(dir, "benchmarks-50.toml"),
	)
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running bent: %w", err)
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/gonuts/flag"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/commander"
	"github.com/jbenet/go-ipfs/daemon"
	h "github.com/jbenet/go-ipfs/server/http"
)

var cmdIpfsServe = &commander.Command{
	UsageLine: "serve",
	Short:     "Serve an interface to ipfs",
	Subcommands: []*commander.Command{
		cmdIpfsServeHttp,
	},
	Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError),
}

var cmdIpfsServeHttp = &commander.Command{
	UsageLine: "http",
	Short:     "Serve an HTTP API",
	Long:      `ipfs serve http - Serve an http gateway into ipfs.`,
	Run:       serveHttpCmd,
	Flag:      *flag.NewFlagSet("ipfs-serve-http", flag.ExitOnError),
}

func init() {
	cmdIpfsServeHttp.Flag.Uint("port", 8080, "Port number")
	cmdIpfsServeHttp.Flag.String("hostname", "localhost", "Hostname")
}

func serveHttpCmd(c *commander.Command, _ []string) error {
	port := c.Flag.Lookup("port").Value.Get().(uint)
	if port < 1 || port > 65535 {
		return errors.New("invalid port number")
	}

	n, err := localNode(true)
	if err != nil {
		return err
	}

	fmt.Println("starting new daemon listener...")
	dl, err := daemon.NewDaemonListener(n, "localhost:12345")
	if err != nil {
		return err
	}
	go dl.Listen()
	defer dl.Close()

	hostname := c.Flag.Lookup("hostname").Value.Get().(string)
	address := fmt.Sprintf("%s:%d", hostname, port)
	fmt.Printf("Serving on %s\n", address)

	return h.Serve(address, n)
}
<commit_msg>fix localNode call<commit_after>package main

import (
	"errors"
	"fmt"

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/gonuts/flag"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/commander"
	"github.com/jbenet/go-ipfs/daemon"
	h "github.com/jbenet/go-ipfs/server/http"
)

var cmdIpfsServe = &commander.Command{
	UsageLine: "serve",
	Short:     "Serve an interface to ipfs",
	Subcommands: []*commander.Command{
		cmdIpfsServeHttp,
	},
	Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError),
}

var cmdIpfsServeHttp = &commander.Command{
	UsageLine: "http",
	Short:     "Serve an HTTP API",
	Long:      `ipfs serve http - Serve an http gateway into ipfs.`,
	Run:       serveHttpCmd,
	Flag:      *flag.NewFlagSet("ipfs-serve-http", flag.ExitOnError),
}

func init() {
	cmdIpfsServeHttp.Flag.Uint("port", 8080, "Port number")
	cmdIpfsServeHttp.Flag.String("hostname", "localhost", "Hostname")
}

func serveHttpCmd(c *commander.Command, _ []string) error {
	port := c.Flag.Lookup("port").Value.Get().(uint)
	if port < 1 || port > 65535 {
		return errors.New("invalid port number")
	}

	conf, err := getConfigDir(c.Parent.Parent)
	if err != nil {
		return err
	}

	n, err := localNode(conf, true)
	if err != nil {
		return err
	}

	fmt.Println("starting new daemon listener...")
	dl, err := daemon.NewDaemonListener(n, "localhost:12345")
	if err != nil {
		return err
	}
	go dl.Listen()
	defer dl.Close()

	hostname := c.Flag.Lookup("hostname").Value.Get().(string)
	address := fmt.Sprintf("%s:%d", hostname, port)
	fmt.Printf("Serving on %s\n", address)

	return h.Serve(address, n)
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"log"
	"os"

	"github.com/bytom/api"
	"github.com/bytom/consensus/difficulty"
	"github.com/bytom/protocol/bc"
	"github.com/bytom/protocol/bc/types"
	"github.com/bytom/util"
)

const (
	maxNonce = ^uint64(0) // 2^64 - 1
	isCrazy = false
)

// do proof of work
func doWork(bh *types.BlockHeader, seed *bc.Hash) bool {
	for i := uint64(0); i <= maxNonce; i++ {
		bh.Nonce = i
		headerHash := bh.Hash()
		if difficulty.CheckProofOfWork(&headerHash, seed, bh.Bits) {
			log.Printf("Mining succeed! Proof hash: %v\n", headerHash.String())
			return true
		}
	}
	return false
}

func getBlockHeaderByHeight(height uint64) {
	type Req struct {
		BlockHeight uint64 `json:"block_height"`
	}

	type Resp struct {
		BlockHeader *types.BlockHeader `json:"block_header"`
		Reward      uint64             `json:"reward"`
	}

	data, _ := util.ClientCall("/get-block-header-by-height", Req{BlockHeight: height})
	rawData, err := json.Marshal(data)
	if err != nil {
		log.Fatalln(err)
	}

	resp := &Resp{}
	if err = json.Unmarshal(rawData, resp); err != nil {
		log.Fatalln(err)
	}
	log.Println("Reward:", resp.Reward)
}

func main() {
	for true {
		data, _ := util.ClientCall("/get-work", nil)
		if data == nil {
			os.Exit(1)
		}
		rawData, err := json.Marshal(data)
		if err != nil {
			log.Fatalln(err)
		}
		resp := &api.GetWorkResp{}
		if err = json.Unmarshal(rawData, resp); err != nil {
			log.Fatalln(err)
		}

		log.Println("Mining at height:", resp.BlockHeader.Height)
		if doWork(resp.BlockHeader, resp.Seed) {
			util.ClientCall("/submit-work", &api.SubmitWorkReq{BlockHeader: resp.BlockHeader})
		}

		getBlockHeaderByHeight(resp.BlockHeader.Height)

		if !isCrazy {
			return
		}
	}
}
<commit_msg>update miner<commit_after>package main

import (
	"encoding/json"
	"log"
	"os"

	"github.com/bytom/api"
	"github.com/bytom/consensus"
	"github.com/bytom/consensus/difficulty"
	"github.com/bytom/protocol/bc"
	"github.com/bytom/protocol/bc/types"
	"github.com/bytom/util"
)

const (
	maxNonce = ^uint64(0) // 2^64 - 1
	isCrazy  = true
	esHR     = 1 //estimated Hashrate
)

var (
	lastNonce  = ^uint64(0)
	lastHeight = uint64(0)
)

// do proof of work
func doWork(bh *types.BlockHeader, seed *bc.Hash) bool {
	for i := uint64(lastNonce + 1); i <= uint64(lastNonce+consensus.TargetSecondsPerBlock*esHR) && i <= maxNonce; i++ {
		bh.Nonce = i
		log.Printf("nonce = %v\n", i)
		headerHash := bh.Hash()
		if difficulty.CheckProofOfWork(&headerHash, seed, bh.Bits) {
			log.Printf("Mining succeed! Proof hash: %v\n", headerHash.String())
			return true
		}
	}
	lastNonce = bh.Nonce
	return false
}

func getBlockHeaderByHeight(height uint64) {
	type Req struct {
		BlockHeight uint64 `json:"block_height"`
	}

	type Resp struct {
		BlockHeader *types.BlockHeader `json:"block_header"`
		Reward      uint64             `json:"reward"`
	}

	data, _ := util.ClientCall("/get-block-header-by-height", Req{BlockHeight: height})
	rawData, err := json.Marshal(data)
	if err != nil {
		log.Fatalln(err)
	}

	resp := &Resp{}
	if err = json.Unmarshal(rawData, resp); err != nil {
		log.Fatalln(err)
	}
	log.Println("Reward:", resp.Reward)
}

func main() {
	for true {
		data, _ := util.ClientCall("/get-work", nil)
		if data == nil {
			os.Exit(1)
		}
		rawData, err := json.Marshal(data)
		if err != nil {
			log.Fatalln(err)
		}
		resp := &api.GetWorkResp{}
		if err = json.Unmarshal(rawData, resp); err != nil {
			log.Fatalln(err)
		}

		log.Println("Mining at height:", resp.BlockHeader.Height)
		if lastHeight != resp.BlockHeader.Height {
			lastNonce = ^uint64(0)
		}
		if doWork(resp.BlockHeader, resp.Seed) {
			util.ClientCall("/submit-work", &api.SubmitWorkReq{BlockHeader: resp.BlockHeader})
			getBlockHeaderByHeight(resp.BlockHeader.Height)
		}

		lastHeight = resp.BlockHeader.Height
		if !isCrazy {
			return
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"

	"github.com/ponzu-cms/ponzu/system/admin"
	"github.com/ponzu-cms/ponzu/system/api"
	"github.com/ponzu-cms/ponzu/system/api/analytics"
	"github.com/ponzu-cms/ponzu/system/db"
	"github.com/ponzu-cms/ponzu/system/tls"

	_ "github.com/ponzu-cms/ponzu/content"
)

var (
	usage = usageHeader + usageNew + usageGenerate +
		usageBuild + usageRun + usageUpgrade + usageVersion
	port      int
	httpsport int
	https     bool
	devhttps  bool
	cli       bool

	// for ponzu internal / core development
	dev   bool
	fork  string
	gocmd string
)

func main() {
	flag.Usage = func() {
		fmt.Println(usage)
	}

	flag.IntVar(&port, "port", 8080, "port for ponzu to bind its HTTP listener")
	flag.IntVar(&httpsport, "httpsport", 443, "port for ponzu to bind its HTTPS listener")
	flag.BoolVar(&https, "https", false, "enable automatic TLS/SSL certificate management")
	flag.BoolVar(&devhttps, "devhttps", false, "[dev environment] enable automatic TLS/SSL certificate management")
	flag.BoolVar(&dev, "dev", false, "modify environment for Ponzu core development")
	flag.BoolVar(&cli, "cli", false, "specify that information should be returned about the CLI, not project")
	flag.StringVar(&fork, "fork", "", "modify repo source for Ponzu core development")
	flag.StringVar(&gocmd, "gocmd", "go", "custom go command if using beta or new release of Go")
	flag.Parse()

	args := flag.Args()

	if len(args) < 1 {
		fmt.Println(usage)
		os.Exit(0)
	}

	switch args[0] {
	case "help", "h":
		if len(args) < 2 {
			fmt.Println(usageHelp)
			fmt.Println(usage)
			os.Exit(0)
		}

		switch args[1] {
		case "new":
			fmt.Println(usageNew)
			os.Exit(0)

		case "generate", "gen", "g":
			fmt.Println(usageGenerate)
			os.Exit(0)

		case "build":
			fmt.Println(usageBuild)
			os.Exit(0)

		case "run":
			fmt.Println(usageRun)
			os.Exit(0)

		case "upgrade":
			fmt.Println(usageUpgrade)
			os.Exit(0)

		case "version", "v":
			fmt.Println(usageVersion)
			os.Exit(0)
		}

	case "new":
		if len(args) < 2 {
			fmt.Println(usageNew)
			os.Exit(0)
		}

		err := newProjectInDir(args[1])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "generate", "gen", "g":
		if len(args) < 3 {
			fmt.Println(usageGenerate)
			os.Exit(0)
		}

		// check what we are asked to generate
		switch args[1] {
		case "content", "c":
			err := generateContentType(args[2:])
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		default:
			msg := fmt.Sprintf("Generator '%s' is not implemented.", args[1])
			fmt.Println(msg)
		}

	case "build":
		err := buildPonzuServer(args)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "run":
		var addTLS string
		if https {
			addTLS = "--https"
		} else {
			addTLS = "--https=false"
		}

		if devhttps {
			addTLS = "--devhttps"
		}

		var services string
		if len(args) > 1 {
			services = args[1]
		} else {
			services = "admin,api"
		}

		serve := exec.Command(GetPonzuServerBuildOutputFileName(),
			fmt.Sprintf("--port=%d", port),
			fmt.Sprintf("--httpsport=%d", httpsport),
			addTLS,
			"serve",
			services,
		)
		serve.Stderr = os.Stderr
		serve.Stdout = os.Stdout

		err := serve.Run()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "serve", "s":
		db.Init()
		defer db.Close()

		analytics.Init()
		defer analytics.Close()

		if len(args) > 1 {
			services := strings.Split(args[1], ",")

			for _, service := range services {
				if service == "api" {
					api.Run()
				} else if service == "admin" {
					admin.Run()
				} else {
					fmt.Println("To execute 'ponzu serve', you must specify which service to run.")
					fmt.Println("$ ponzu --help")
					os.Exit(1)
				}
			}
		}

		// save the https port the system is listening on
		err := db.PutConfig("https_port", fmt.Sprintf("%d", httpsport))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		// cannot run production HTTPS and development HTTPS together
		if devhttps {
			fmt.Println("Enabling self-signed HTTPS... [DEV]")

			go tls.EnableDev()
			fmt.Println("Server listening on https://localhost:10443 for requests... [DEV]")
			fmt.Println("----")
			fmt.Println("If your browser rejects HTTPS requests, try allowing insecure connections on localhost.")
			fmt.Println("on Chrome, visit chrome://flags/#allow-insecure-localhost")

		} else if https {
			fmt.Println("Enabling HTTPS...")

			go tls.Enable()
			fmt.Printf("Server listening on :%s for HTTPS requests...\n", db.ConfigCache("https_port").(string))
		}

		// save the https port the system is listening on so internal system can make
		// HTTP api calls while in dev or production w/o adding more cli flags
		err = db.PutConfig("http_port", fmt.Sprintf("%d", port))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		fmt.Printf("Server listening on :%d for HTTP requests...\n", port)
		fmt.Println("\nvisit `/admin` to get started.")
		log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))

	case "version", "v":
		// read ponzu.json value to Stdout

		p, err := ponzu(cli)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		fmt.Fprintf(os.Stdout, "Ponzu v%s\n", p["version"])

	case "upgrade":
		// confirm since upgrade will replace Ponzu core files
		path, err := os.Getwd()
		if err != nil {
			fmt.Println("Failed to find current directory.", err)
			os.Exit(1)
		}

		fmt.Println("Only files you added to this directory, 'addons' and 'content' will be preserved.")
		fmt.Println("Upgrade this project? (y/N):")

		answer, err := getAnswer()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		switch answer {
		case "n", "no", "\r\n", "\n", "":
			fmt.Println("")

		case "y", "yes":
			err := upgradePonzuProjectDir(path)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

		default:
			fmt.Println("Input not recognized. No upgrade made. Answer as 'y' or 'n' only.")
		}

	case "":
		fmt.Println(usage)
		fmt.Println(usageHelp)

	default:
		fmt.Println(usage)
		fmt.Println(usageHelp)
	}
}
<commit_msg>reduce length of function name and unexport<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"

	"github.com/ponzu-cms/ponzu/system/admin"
	"github.com/ponzu-cms/ponzu/system/api"
	"github.com/ponzu-cms/ponzu/system/api/analytics"
	"github.com/ponzu-cms/ponzu/system/db"
	"github.com/ponzu-cms/ponzu/system/tls"

	_ "github.com/ponzu-cms/ponzu/content"
)

var (
	usage = usageHeader + usageNew + usageGenerate +
		usageBuild + usageRun + usageUpgrade + usageVersion
	port      int
	httpsport int
	https     bool
	devhttps  bool
	cli       bool

	// for ponzu internal / core development
	dev   bool
	fork  string
	gocmd string
)

func main() {
	flag.Usage = func() {
		fmt.Println(usage)
	}

	flag.IntVar(&port, "port", 8080, "port for ponzu to bind its HTTP listener")
	flag.IntVar(&httpsport, "httpsport", 443, "port for ponzu to bind its HTTPS listener")
	flag.BoolVar(&https, "https", false, "enable automatic TLS/SSL certificate management")
	flag.BoolVar(&devhttps, "devhttps", false, "[dev environment] enable automatic TLS/SSL certificate management")
	flag.BoolVar(&dev, "dev", false, "modify environment for Ponzu core development")
	flag.BoolVar(&cli, "cli", false, "specify that information should be returned about the CLI, not project")
	flag.StringVar(&fork, "fork", "", "modify repo source for Ponzu core development")
	flag.StringVar(&gocmd, "gocmd", "go", "custom go command if using beta or new release of Go")
	flag.Parse()

	args := flag.Args()

	if len(args) < 1 {
		fmt.Println(usage)
		os.Exit(0)
	}

	switch args[0] {
	case "help", "h":
		if len(args) < 2 {
			fmt.Println(usageHelp)
			fmt.Println(usage)
			os.Exit(0)
		}

		switch args[1] {
		case "new":
			fmt.Println(usageNew)
			os.Exit(0)

		case "generate", "gen", "g":
			fmt.Println(usageGenerate)
			os.Exit(0)

		case "build":
			fmt.Println(usageBuild)
			os.Exit(0)

		case "run":
			fmt.Println(usageRun)
			os.Exit(0)

		case "upgrade":
			fmt.Println(usageUpgrade)
			os.Exit(0)

		case "version", "v":
			fmt.Println(usageVersion)
			os.Exit(0)
		}

	case "new":
		if len(args) < 2 {
			fmt.Println(usageNew)
			os.Exit(0)
		}

		err := newProjectInDir(args[1])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "generate", "gen", "g":
		if len(args) < 3 {
			fmt.Println(usageGenerate)
			os.Exit(0)
		}

		// check what we are asked to generate
		switch args[1] {
		case "content", "c":
			err := generateContentType(args[2:])
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		default:
			msg := fmt.Sprintf("Generator '%s' is not implemented.", args[1])
			fmt.Println(msg)
		}

	case "build":
		err := buildPonzuServer(args)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "run":
		var addTLS string
		if https {
			addTLS = "--https"
		} else {
			addTLS = "--https=false"
		}

		if devhttps {
			addTLS = "--devhttps"
		}

		var services string
		if len(args) > 1 {
			services = args[1]
		} else {
			services = "admin,api"
		}

		serve := exec.Command(buildOutputName(),
			fmt.Sprintf("--port=%d", port),
			fmt.Sprintf("--httpsport=%d", httpsport),
			addTLS,
			"serve",
			services,
		)
		serve.Stderr = os.Stderr
		serve.Stdout = os.Stdout

		err := serve.Run()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

	case "serve", "s":
		db.Init()
		defer db.Close()

		analytics.Init()
		defer analytics.Close()

		if len(args) > 1 {
			services := strings.Split(args[1], ",")

			for _, service := range services {
				if service == "api" {
					api.Run()
				} else if service == "admin" {
					admin.Run()
				} else {
					fmt.Println("To execute 'ponzu serve', you must specify which service to run.")
					fmt.Println("$ ponzu --help")
					os.Exit(1)
				}
			}
		}

		// save the https port the system is listening on
		err := db.PutConfig("https_port", fmt.Sprintf("%d", httpsport))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		// cannot run production HTTPS and development HTTPS together
		if devhttps {
			fmt.Println("Enabling self-signed HTTPS... [DEV]")

			go tls.EnableDev()
			fmt.Println("Server listening on https://localhost:10443 for requests... [DEV]")
			fmt.Println("----")
			fmt.Println("If your browser rejects HTTPS requests, try allowing insecure connections on localhost.")
			fmt.Println("on Chrome, visit chrome://flags/#allow-insecure-localhost")

		} else if https {
			fmt.Println("Enabling HTTPS...")

			go tls.Enable()
			fmt.Printf("Server listening on :%s for HTTPS requests...\n", db.ConfigCache("https_port").(string))
		}

		// save the https port the system is listening on so internal system can make
		// HTTP api calls while in dev or production w/o adding more cli flags
		err = db.PutConfig("http_port", fmt.Sprintf("%d", port))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		fmt.Printf("Server listening on :%d for HTTP requests...\n", port)
		fmt.Println("\nvisit `/admin` to get started.")
		log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))

	case "version", "v":
		// read ponzu.json value to Stdout

		p, err := ponzu(cli)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		fmt.Fprintf(os.Stdout, "Ponzu v%s\n", p["version"])

	case "upgrade":
		// confirm since upgrade will replace Ponzu core files
		path, err := os.Getwd()
		if err != nil {
			fmt.Println("Failed to find current directory.", err)
			os.Exit(1)
		}

		fmt.Println("Only files you added to this directory, 'addons' and 'content' will be preserved.")
		fmt.Println("Upgrade this project? (y/N):")

		answer, err := getAnswer()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		switch answer {
		case "n", "no", "\r\n", "\n", "":
			fmt.Println("")

		case "y", "yes":
			err := upgradePonzuProjectDir(path)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

		default:
			fmt.Println("Input not recognized. No upgrade made. Answer as 'y' or 'n' only.")
		}

	case "":
		fmt.Println(usage)
		fmt.Println(usageHelp)

	default:
		fmt.Println(usage)
		fmt.Println(usageHelp)
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 *
 * 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.
 *
 * @author		Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @copyright 	2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @license 	Apache-2.0
 */

package cmd

import (
	"context"
	"crypto/tls"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/julienschmidt/httprouter"
	"github.com/ory/go-convenience/urlx"
	"github.com/ory/hydra/pkg"
	"github.com/ory/hydra/rand/sequence"
	"github.com/spf13/cobra"
	"github.com/toqueteos/webbrowser"
	"golang.org/x/oauth2"
)

// tokenUserCmd represents the token command
var tokenUserCmd = &cobra.Command{
	Use:   "user",
	Short: "Starts a web server that initiates and handles OAuth 2.0 requests",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()
		if ok, _ := cmd.Flags().GetBool("skip-tls-verify"); ok {
			// fmt.Println("Warning: Skipping TLS Certificate Verification.")
			ctx = context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}})
		}

		port, _ := cmd.Flags().GetInt("port")
		scopes, _ := cmd.Flags().GetStringSlice("scope")
		redirectUrl, _ := cmd.Flags().GetString("redirect")
		backend, _ := cmd.Flags().GetString("token-url")
		frontend, _ := cmd.Flags().GetString("auth-url")

		clientID, _ := cmd.Flags().GetString("client-id")
		clientSecret, _ := cmd.Flags().GetString("client-secret")
		if clientID == "" || clientSecret == "" {
			fmt.Print(cmd.UsageString())
			fmt.Println("Please provide a Client ID and Client Secret using flags --client-id and --client-secret, or environment variables OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET.")
			return
		}

		serverLocation := fmt.Sprintf("http://127.0.0.1:%d/", port)
		if redirectUrl == "" {
			redirectUrl = serverLocation + "callback"
		}

		if backend == "" {
			bu, err := url.Parse(c.GetClusterURLWithoutTailingSlash(cmd))
			pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.GetClusterURLWithoutTailingSlash(cmd), err)
			backend = urlx.AppendPaths(bu, "/oauth2/token").String()
		}
		if frontend == "" {
			fu, err := url.Parse(c.GetClusterURLWithoutTailingSlash(cmd))
			pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.GetClusterURLWithoutTailingSlash(cmd), err)
			frontend = urlx.AppendPaths(fu, "/oauth2/auth").String()
		}

		conf := oauth2.Config{
			ClientID:     clientID,
			ClientSecret: clientSecret,
			Endpoint: oauth2.Endpoint{
				TokenURL: backend,
				AuthURL:  frontend,
			},
			RedirectURL: redirectUrl,
			Scopes:      scopes,
		}

		state, err := sequence.RuneSequence(24, sequence.AlphaLower)
		pkg.Must(err, "Could not generate random state: %s", err)

		nonce, err := sequence.RuneSequence(24, sequence.AlphaLower)
		pkg.Must(err, "Could not generate random state: %s", err)

		authCodeURL := conf.AuthCodeURL(string(state)) + "&nonce=" + string(nonce)

		if ok, _ := cmd.Flags().GetBool("no-open"); !ok {
			webbrowser.Open(serverLocation)
		}

		fmt.Println("Setting up home route on " + serverLocation)
		fmt.Println("Setting up callback listener on " + serverLocation + "callback")
		fmt.Println("Press ctrl + c on Linux / Windows or cmd + c on OSX to end the process.")
		fmt.Printf("If your browser does not open automatically, navigate to:\n\n\t%s\n\n", serverLocation)

		r := httprouter.New()
		server := &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: r}
		var shutdown = func() {
			time.Sleep(time.Second * 1)
			ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
			server.Shutdown(ctx)
		}

		r.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			w.Write([]byte(fmt.Sprintf(`

Welcome to the example OAuth 2.0 Consumer

This example requests an OAuth 2.0 Access, Refresh, and OpenID Connect ID Token from the OAuth 2.0 Server (ORY Hydra). To initiate the flow, click the "Authorize Application" button.

Authorize application

`, authCodeURL)))
		})

		r.GET("/callback", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			if len(r.URL.Query().Get("error")) > 0 {
				fmt.Printf("Got error: %s\n", r.URL.Query().Get("error_description"))

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s

%s
", r.URL.Query().Get("error"), r.URL.Query().Get("error_description"))
				go shutdown()
				return
			}

			if r.URL.Query().Get("state") != string(state) {
				fmt.Printf("States do not match. Expected %s, got %s\n", string(state), r.URL.Query().Get("state"))

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s

%s
", "States do not match", "Expected state "+string(state)+" but got "+r.URL.Query().Get("state"))
				go shutdown()
				return
			}

			code := r.URL.Query().Get("code")
			token, err := conf.Exchange(ctx, code)
			if err != nil {
				fmt.Printf("Unable to exchange code for token: %s\n", err)

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s
", err)
				go shutdown()
				return
			}

			fmt.Printf("Access Token:\n\t%s\n", token.AccessToken)
			fmt.Printf("Refresh Token:\n\t%s\n\n", token.RefreshToken)
			fmt.Printf("Expires in:\n\t%s\n\n", token.Expiry)

			w.Write([]byte(fmt.Sprintf(`

Access Token: %s

Refresh Token: %s

Expires in: %s

`, token.AccessToken, token.RefreshToken, token.Expiry)))

			idt := token.Extra("id_token")
			if idt != nil {
				w.Write([]byte(fmt.Sprintf(`<li>ID Token: <code>%s</code></li>`, idt)))
				fmt.Printf("ID Token:\n\t%s\n\n", idt)
			}
			w.Write([]byte("
"))

			go shutdown()
		})
		server.ListenAndServe()
	},
}

func init() {
	tokenCmd.AddCommand(tokenUserCmd)
	tokenUserCmd.Flags().Bool("no-open", false, "Do not open the browser window automatically")
	tokenUserCmd.Flags().IntP("port", "p", 4445, "The port on which the server should run")
	tokenUserCmd.Flags().StringSlice("scope", []string{"offline", "openid"}, "Request OAuth2 scope")

	tokenUserCmd.Flags().String("client-id", os.Getenv("OAUTH2_CLIENT_ID"), "Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID")
	tokenUserCmd.Flags().String("client-secret", os.Getenv("OAUTH2_CLIENT_SECRET"), "Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET")

	tokenUserCmd.Flags().String("redirect", "", "Force a redirect url")
	tokenUserCmd.Flags().String("auth-url", os.Getenv("HYDRA_URL"), "Usually it is enough to specify the `endpoint` flag, but if you want to force the authorization url, use this flag")
	tokenUserCmd.Flags().String("token-url", os.Getenv("HYDRA_URL"), "Usually it is enough to specify the `endpoint` flag, but if you want to force the token url, use this flag")
	tokenUserCmd.PersistentFlags().String("endpoint", os.Getenv("HYDRA_URL"), "Set the URL where ORY Hydra is hosted, defaults to environment variable HYDRA_URL")
}
<commit_msg>cmd: Includes error debug message in token user command<commit_after>/*
 * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 *
 * 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.
 *
 * @author		Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @copyright 	2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
 * @license 	Apache-2.0
 */

package cmd

import (
	"context"
	"crypto/tls"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/julienschmidt/httprouter"
	"github.com/ory/go-convenience/urlx"
	"github.com/ory/hydra/pkg"
	"github.com/ory/hydra/rand/sequence"
	"github.com/spf13/cobra"
	"github.com/toqueteos/webbrowser"
	"golang.org/x/oauth2"
)

// tokenUserCmd represents the token command
var tokenUserCmd = &cobra.Command{
	Use:   "user",
	Short: "Starts a web server that initiates and handles OAuth 2.0 requests",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()
		if ok, _ := cmd.Flags().GetBool("skip-tls-verify"); ok {
			// fmt.Println("Warning: Skipping TLS Certificate Verification.")
			ctx = context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}})
		}

		port, _ := cmd.Flags().GetInt("port")
		scopes, _ := cmd.Flags().GetStringSlice("scope")
		redirectUrl, _ := cmd.Flags().GetString("redirect")
		backend, _ := cmd.Flags().GetString("token-url")
		frontend, _ := cmd.Flags().GetString("auth-url")

		clientID, _ := cmd.Flags().GetString("client-id")
		clientSecret, _ := cmd.Flags().GetString("client-secret")
		if clientID == "" || clientSecret == "" {
			fmt.Print(cmd.UsageString())
			fmt.Println("Please provide a Client ID and Client Secret using flags --client-id and --client-secret, or environment variables OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET.")
			return
		}

		serverLocation := fmt.Sprintf("http://127.0.0.1:%d/", port)
		if redirectUrl == "" {
			redirectUrl = serverLocation + "callback"
		}

		if backend == "" {
			bu, err := url.Parse(c.GetClusterURLWithoutTailingSlash(cmd))
			pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.GetClusterURLWithoutTailingSlash(cmd), err)
			backend = urlx.AppendPaths(bu, "/oauth2/token").String()
		}
		if frontend == "" {
			fu, err := url.Parse(c.GetClusterURLWithoutTailingSlash(cmd))
			pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.GetClusterURLWithoutTailingSlash(cmd), err)
			frontend = urlx.AppendPaths(fu, "/oauth2/auth").String()
		}

		conf := oauth2.Config{
			ClientID:     clientID,
			ClientSecret: clientSecret,
			Endpoint: oauth2.Endpoint{
				TokenURL: backend,
				AuthURL:  frontend,
			},
			RedirectURL: redirectUrl,
			Scopes:      scopes,
		}

		state, err := sequence.RuneSequence(24, sequence.AlphaLower)
		pkg.Must(err, "Could not generate random state: %s", err)

		nonce, err := sequence.RuneSequence(24, sequence.AlphaLower)
		pkg.Must(err, "Could not generate random state: %s", err)

		authCodeURL := conf.AuthCodeURL(string(state)) + "&nonce=" + string(nonce)

		if ok, _ := cmd.Flags().GetBool("no-open"); !ok {
			webbrowser.Open(serverLocation)
		}

		fmt.Println("Setting up home route on " + serverLocation)
		fmt.Println("Setting up callback listener on " + serverLocation + "callback")
		fmt.Println("Press ctrl + c on Linux / Windows or cmd + c on OSX to end the process.")
		fmt.Printf("If your browser does not open automatically, navigate to:\n\n\t%s\n\n", serverLocation)

		r := httprouter.New()
		server := &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: r}
		var shutdown = func() {
			time.Sleep(time.Second * 1)
			ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
			server.Shutdown(ctx)
		}

		r.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			w.Write([]byte(fmt.Sprintf(`

Welcome to the example OAuth 2.0 Consumer

This example requests an OAuth 2.0 Access, Refresh, and OpenID Connect ID Token from the OAuth 2.0 Server (ORY Hydra). To initiate the flow, click the "Authorize Application" button.

Authorize application

`, authCodeURL)))
		})

		r.GET("/callback", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			if len(r.URL.Query().Get("error")) > 0 {
				fmt.Printf("Got error: %s\n", r.URL.Query().Get("error_description"))

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s

%s

%s
", r.URL.Query().Get("error"), r.URL.Query().Get("error_description"), r.URL.Query().Get("error_debug"))
				go shutdown()
				return
			}

			if r.URL.Query().Get("state") != string(state) {
				fmt.Printf("States do not match. Expected %s, got %s\n", string(state), r.URL.Query().Get("state"))

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s

%s
", "States do not match", "Expected state "+string(state)+" but got "+r.URL.Query().Get("state"))
				go shutdown()
				return
			}

			code := r.URL.Query().Get("code")
			token, err := conf.Exchange(ctx, code)
			if err != nil {
				fmt.Printf("Unable to exchange code for token: %s\n", err)

				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, "
An error occurred

%s
", err)
				go shutdown()
				return
			}

			fmt.Printf("Access Token:\n\t%s\n", token.AccessToken)
			fmt.Printf("Refresh Token:\n\t%s\n\n", token.RefreshToken)
			fmt.Printf("Expires in:\n\t%s\n\n", token.Expiry)

			w.Write([]byte(fmt.Sprintf(`

Access Token: %s

Refresh Token: %s

Expires in: %s

`, token.AccessToken, token.RefreshToken, token.Expiry)))

			idt := token.Extra("id_token")
			if idt != nil {
				w.Write([]byte(fmt.Sprintf(`<li>ID Token: <code>%s</code></li>`, idt)))
				fmt.Printf("ID Token:\n\t%s\n\n", idt)
			}
			w.Write([]byte("
"))

			go shutdown()
		})
		server.ListenAndServe()
	},
}

func init() {
	tokenCmd.AddCommand(tokenUserCmd)
	tokenUserCmd.Flags().Bool("no-open", false, "Do not open the browser window automatically")
	tokenUserCmd.Flags().IntP("port", "p", 4445, "The port on which the server should run")
	tokenUserCmd.Flags().StringSlice("scope", []string{"offline", "openid"}, "Request OAuth2 scope")

	tokenUserCmd.Flags().String("client-id", os.Getenv("OAUTH2_CLIENT_ID"), "Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID")
	tokenUserCmd.Flags().String("client-secret", os.Getenv("OAUTH2_CLIENT_SECRET"), "Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET")

	tokenUserCmd.Flags().String("redirect", "", "Force a redirect url")
	tokenUserCmd.Flags().String("auth-url", os.Getenv("HYDRA_URL"), "Usually it is enough to specify the `endpoint` flag, but if you want to force the authorization url, use this flag")
	tokenUserCmd.Flags().String("token-url", os.Getenv("HYDRA_URL"), "Usually it is enough to specify the `endpoint` flag, but if you want to force the token url, use this flag")
	tokenUserCmd.PersistentFlags().String("endpoint", os.Getenv("HYDRA_URL"), "Set the URL where ORY Hydra is hosted, defaults to environment variable HYDRA_URL")
}
<|endoftext|>