<commit_before>package main

import (
	"encoding/binary"
	"fmt"
	"strings"
)

type regionFlag byte

const (
	pal  regionFlag = 1 << iota
	dual            // if both are off, it is a NTSC file
)

type extraChipFlag byte

const (
	vrc6 extraChipFlag = 1 << iota
	vrc7
	fds
	mmc5
	namco163
	sunsoft5b
	futureChip1 // must never be set
	futureChip2 // must never be set
)

// nesWord is a little endian uint16
type nesWord [2]byte

func (w nesWord) toUInt16() uint16 {
	return binary.LittleEndian.Uint16(w[:])
}

// nsfHeader exposes the nsf header fields (more info at http://wiki.nesdev.com/w/index.php/NSF)
type nsfHeader struct {
	Prelude          [5]byte
	Version          int8
	TotalSongs       int8
	StartingSong     int8
	LoadAddress      nesWord
	InitAddress      nesWord
	PlayAddress      nesWord
	SongName         [32]byte
	Artist           [32]byte
	CopyrightHolder  [32]byte
	NTSCPlaySpeed    nesWord
	BankswitchInit   int64 // we do not care about the specific banks assignment
	PalPlaySpeed     nesWord
	RegionFlags      regionFlag
	ExtraChipFlags   extraChipFlag
	ExpansionPadding int32 // always 0
}

func (h nsfHeader) String() string {
	return fmt.Sprintf("%-23s: %s\n%-23s: %s\n%-23s: %s\n%-23s: %d\n%-23s: %d\n%-23s: %s\n%-23s: %d\n----------------\n%-23s: %d\n%-23s: %v\n%-23s: %s\n%-23s: %#x\n%-23s: %#x\n%-23s: %#x",
		"name", trimNull(h.SongName[:]),
		"artist", trimNull(h.Artist[:]),
		"copyright holder", trimNull(h.CopyrightHolder[:]),
		"total # of songs", h.TotalSongs,
		"first song", h.StartingSong,
		"region", h.region(),
		"play speed (μs)", h.playSpeed().toUInt16(),
		"nsf version", h.Version,
		"uses bankswitching", h.BankswitchInit != 0,
		"expansion chips in use", h.extraChips(),
		"load address", h.LoadAddress.toUInt16(),
		"init address", h.InitAddress.toUInt16(),
		"play address", h.PlayAddress.toUInt16(),
	)
}

func (h nsfHeader) playSpeed() nesWord {
	if h.RegionFlags&pal != 0 {
		return h.PalPlaySpeed
	}
	return h.NTSCPlaySpeed
}

func (h nsfHeader) region() string {
	if h.RegionFlags&dual != 0 {
		return "dual PAL/NTSC"
	} else if h.RegionFlags&pal != 0 {
		return "PAL"
	}
	return "NTSC"
}

func (h nsfHeader) extraChips() string {
	// todo: replace those ugly if/else with a const [extraChipFlag, string]map
	var chipsInUse []string
	if h.ExtraChipFlags&vrc6 != 0 {
		chipsInUse = append(chipsInUse, "VRC6")
	} else if h.ExtraChipFlags&vrc7 != 0 {
		chipsInUse = append(chipsInUse, "VRC7")
	} else if h.ExtraChipFlags&fds != 0 {
		chipsInUse = append(chipsInUse, "Famicom Disk System")
	} else if h.ExtraChipFlags&mmc5 != 0 {
		chipsInUse = append(chipsInUse, "mmc5")
	} else if h.ExtraChipFlags&namco163 != 0 {
		chipsInUse = append(chipsInUse, "Namco 163")
	} else if h.ExtraChipFlags&sunsoft5b != 0 {
		chipsInUse = append(chipsInUse, "Sunsoft 5B")
	}
	if len(chipsInUse) == 0 {
		chipsInUse = append(chipsInUse, "none")
	}
	return fmt.Sprintf("%v", chipsInUse) // do a better comma-delimited formatting here
}

func trimNull(s []byte) string {
	return string(s[:strings.Index(string(s), "\x00")])
}
<commit_msg>made use of strings.join to comma-delimit the list of extra chips<commit_after>package main

import (
	"encoding/binary"
	"fmt"
	"strings"
)

type regionFlag byte

const (
	pal  regionFlag = 1 << iota
	dual            // if both are off, it is a NTSC file
)

type extraChipFlag byte

const (
	vrc6 extraChipFlag = 1 << iota
	vrc7
	fds
	mmc5
	namco163
	sunsoft5b
	futureChip1 // must never be set
	futureChip2 // must never be set
)

// nesWord is a little endian uint16
type nesWord [2]byte

func (w nesWord) toUInt16() uint16 {
	return binary.LittleEndian.Uint16(w[:])
}

// nsfHeader exposes the nsf header fields (more info at http://wiki.nesdev.com/w/index.php/NSF)
type nsfHeader struct {
	Prelude          [5]byte
	Version          int8
	TotalSongs       int8
	StartingSong     int8
	LoadAddress      nesWord
	InitAddress      nesWord
	PlayAddress      nesWord
	SongName         [32]byte
	Artist           [32]byte
	CopyrightHolder  [32]byte
	NTSCPlaySpeed    nesWord
	BankswitchInit   int64 // we do not care about the specific banks assignment
	PalPlaySpeed     nesWord
	RegionFlags      regionFlag
	ExtraChipFlags   extraChipFlag
	ExpansionPadding int32 // always 0
}

func (h nsfHeader) String() string {
	return fmt.Sprintf("%-23s: %s\n%-23s: %s\n%-23s: %s\n%-23s: %d\n%-23s: %d\n%-23s: %s\n%-23s: %d\n----------------\n%-23s: %d\n%-23s: %v\n%-23s: %s\n%-23s: %#x\n%-23s: %#x\n%-23s: %#x",
		"name", trimNull(h.SongName[:]),
		"artist", trimNull(h.Artist[:]),
		"copyright holder", trimNull(h.CopyrightHolder[:]),
		"total # of songs", h.TotalSongs,
		"first song", h.StartingSong,
		"region", h.region(),
		"play speed (μs)", h.playSpeed().toUInt16(),
		"nsf version", h.Version,
		"uses bankswitching", h.BankswitchInit != 0,
		"expansion chips in use", h.extraChips(),
		"load address", h.LoadAddress.toUInt16(),
		"init address", h.InitAddress.toUInt16(),
		"play address", h.PlayAddress.toUInt16(),
	)
}

func (h nsfHeader) playSpeed() nesWord {
	if h.RegionFlags&pal != 0 {
		return h.PalPlaySpeed
	}
	return h.NTSCPlaySpeed
}

func (h nsfHeader) region() string {
	if h.RegionFlags&dual != 0 {
		return "dual PAL/NTSC"
	} else if h.RegionFlags&pal != 0 {
		return "PAL"
	}
	return "NTSC"
}

func (h nsfHeader) extraChips() string {
	// todo: replace those ugly if/else with a const [extraChipFlag, string]map
	var chipsInUse []string
	if h.ExtraChipFlags&vrc6 != 0 {
		chipsInUse = append(chipsInUse, "VRC6")
	} else if h.ExtraChipFlags&vrc7 != 0 {
		chipsInUse = append(chipsInUse, "VRC7")
	} else if h.ExtraChipFlags&fds != 0 {
		chipsInUse = append(chipsInUse, "Famicom Disk System")
	} else if h.ExtraChipFlags&mmc5 != 0 {
		chipsInUse = append(chipsInUse, "mmc5")
	} else if h.ExtraChipFlags&namco163 != 0 {
		chipsInUse = append(chipsInUse, "Namco 163")
	} else if h.ExtraChipFlags&sunsoft5b != 0 {
		chipsInUse = append(chipsInUse, "Sunsoft 5B")
	}
	if len(chipsInUse) == 0 {
		chipsInUse = append(chipsInUse, "none")
	}
	return strings.Join(chipsInUse, ", ")
}

func trimNull(s []byte) string {
	return string(s[:strings.Index(string(s), "\x00")])
}
<|endoftext|>


<commit_before>// +build linux

package nsinit

import (
	"fmt"
	"os"
	"runtime"
	"syscall"

	"github.com/dotcloud/docker/pkg/apparmor"
	"github.com/dotcloud/docker/pkg/label"
	"github.com/dotcloud/docker/pkg/libcontainer"
	"github.com/dotcloud/docker/pkg/libcontainer/console"
	"github.com/dotcloud/docker/pkg/libcontainer/mount"
	"github.com/dotcloud/docker/pkg/libcontainer/network"
	"github.com/dotcloud/docker/pkg/libcontainer/security/apparmor"
	"github.com/dotcloud/docker/pkg/libcontainer/security/capabilities"
	"github.com/dotcloud/docker/pkg/libcontainer/utils"
	"github.com/dotcloud/docker/pkg/system"
	"github.com/dotcloud/docker/pkg/user"
)

// Init is the init process that first runs inside a new namespace to setup mounts, users, networking,
// and other options required for the new container.
func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consolePath string, syncPipe *SyncPipe, args []string) error {
	rootfs, err := utils.ResolveRootfs(uncleanRootfs)
	if err != nil {
		return err
	}

	// We always read this as it is a way to sync with the parent as well
	ns.logger.Printf("reading from sync pipe fd %d\n", syncPipe.child.Fd())
	context, err := syncPipe.ReadFromParent()
	if err != nil {
		syncPipe.Close()
		return err
	}
	ns.logger.Println("received context from parent")
	syncPipe.Close()

	if consolePath != "" {
		ns.logger.Printf("setting up %s as console\n", consolePath)
		if err := console.OpenAndDup(consolePath); err != nil {
			return err
		}
	}
	if _, err := system.Setsid(); err != nil {
		return fmt.Errorf("setsid %s", err)
	}
	if consolePath != "" {
		if err := system.Setctty(); err != nil {
			return fmt.Errorf("setctty %s", err)
		}
	}
	if err := setupNetwork(container, context); err != nil {
		return fmt.Errorf("setup networking %s", err)
	}

	label.Init()
	ns.logger.Println("setup mount namespace")
	if err := mount.InitializeMountNamespace(rootfs, consolePath, container); err != nil {
		return fmt.Errorf("setup mount namespace %s", err)
	}
	if err := system.Sethostname(container.Hostname); err != nil {
		return fmt.Errorf("sethostname %s", err)
	}
	if err := finalizeNamespace(container); err != nil {
		return fmt.Errorf("finalize namespace %s", err)
	}

	if profile := container.Context["apparmor_profile"]; profile != "" {
		ns.logger.Printf("setting apparmor profile %s\n", profile)
		if err := apparmor.ApplyProfile(os.Getpid(), profile); err != nil {
			return err
		}
	}
	runtime.LockOSThread()
	if err := label.SetProcessLabel(container.Context["process_label"]); err != nil {
		return fmt.Errorf("SetProcessLabel label %s", err)
	}
	ns.logger.Printf("execing %s\n", args[0])
	return system.Execv(args[0], args[0:], container.Env)
}

func setupUser(container *libcontainer.Container) error {
	switch container.User {
	case "root", "":
		if err := system.Setgroups(nil); err != nil {
			return err
		}
		if err := system.Setresgid(0, 0, 0); err != nil {
			return err
		}
		if err := system.Setresuid(0, 0, 0); err != nil {
			return err
		}
	default:
		uid, gid, suppGids, err := user.GetUserGroupSupplementary(container.User, syscall.Getuid(), syscall.Getgid())
		if err != nil {
			return err
		}
		if err := system.Setgroups(suppGids); err != nil {
			return err
		}
		if err := system.Setgid(gid); err != nil {
			return err
		}
		if err := system.Setuid(uid); err != nil {
			return err
		}
	}
	return nil
}

// setupVethNetwork uses the Network config if it is not nil to initialize
// the new veth interface inside the container for use by changing the name to eth0
// setting the MTU and IP address along with the default gateway
func setupNetwork(container *libcontainer.Container, context libcontainer.Context) error {
	for _, config := range container.Networks {
		strategy, err := network.GetStrategy(config.Type)
		if err != nil {
			return err
		}

		err1 := strategy.Initialize(config, context)
		if err1 != nil {
			return err1
		}
	}
	return nil
}

// finalizeNamespace drops the caps and sets the correct user
// and working dir before execing the command inside the namespace
func finalizeNamespace(container *libcontainer.Container) error {
	if err := capabilities.DropCapabilities(container); err != nil {
		return fmt.Errorf("drop capabilities %s", err)
	}
	if err := setupUser(container); err != nil {
		return fmt.Errorf("setup user %s", err)
	}
	if container.WorkingDir != "" {
		if err := system.Chdir(container.WorkingDir); err != nil {
			return fmt.Errorf("chdir to %s %s", container.WorkingDir, err)
		}
	}
	return nil
}
<commit_msg>Update init for new apparmor import path Docker-DCO-1.1-Signed-off-by: Michael Crosby <michael@crosbymichael.com> (github: crosbymichael)<commit_after>// +build linux

package nsinit

import (
	"fmt"
	"os"
	"runtime"
	"syscall"

	"github.com/dotcloud/docker/pkg/apparmor"
	"github.com/dotcloud/docker/pkg/label"
	"github.com/dotcloud/docker/pkg/libcontainer"
	"github.com/dotcloud/docker/pkg/libcontainer/console"
	"github.com/dotcloud/docker/pkg/libcontainer/mount"
	"github.com/dotcloud/docker/pkg/libcontainer/network"
	"github.com/dotcloud/docker/pkg/libcontainer/security/capabilities"
	"github.com/dotcloud/docker/pkg/libcontainer/utils"
	"github.com/dotcloud/docker/pkg/system"
	"github.com/dotcloud/docker/pkg/user"
)

// Init is the init process that first runs inside a new namespace to setup mounts, users, networking,
// and other options required for the new container.
func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, consolePath string, syncPipe *SyncPipe, args []string) error {
	rootfs, err := utils.ResolveRootfs(uncleanRootfs)
	if err != nil {
		return err
	}

	// We always read this as it is a way to sync with the parent as well
	ns.logger.Printf("reading from sync pipe fd %d\n", syncPipe.child.Fd())
	context, err := syncPipe.ReadFromParent()
	if err != nil {
		syncPipe.Close()
		return err
	}
	ns.logger.Println("received context from parent")
	syncPipe.Close()

	if consolePath != "" {
		ns.logger.Printf("setting up %s as console\n", consolePath)
		if err := console.OpenAndDup(consolePath); err != nil {
			return err
		}
	}
	if _, err := system.Setsid(); err != nil {
		return fmt.Errorf("setsid %s", err)
	}
	if consolePath != "" {
		if err := system.Setctty(); err != nil {
			return fmt.Errorf("setctty %s", err)
		}
	}
	if err := setupNetwork(container, context); err != nil {
		return fmt.Errorf("setup networking %s", err)
	}

	label.Init()
	ns.logger.Println("setup mount namespace")
	if err := mount.InitializeMountNamespace(rootfs, consolePath, container); err != nil {
		return fmt.Errorf("setup mount namespace %s", err)
	}
	if err := system.Sethostname(container.Hostname); err != nil {
		return fmt.Errorf("sethostname %s", err)
	}
	if err := finalizeNamespace(container); err != nil {
		return fmt.Errorf("finalize namespace %s", err)
	}

	if profile := container.Context["apparmor_profile"]; profile != "" {
		ns.logger.Printf("setting apparmor profile %s\n", profile)
		if err := apparmor.ApplyProfile(os.Getpid(), profile); err != nil {
			return err
		}
	}
	runtime.LockOSThread()
	if err := label.SetProcessLabel(container.Context["process_label"]); err != nil {
		return fmt.Errorf("SetProcessLabel label %s", err)
	}
	ns.logger.Printf("execing %s\n", args[0])
	return system.Execv(args[0], args[0:], container.Env)
}

func setupUser(container *libcontainer.Container) error {
	switch container.User {
	case "root", "":
		if err := system.Setgroups(nil); err != nil {
			return err
		}
		if err := system.Setresgid(0, 0, 0); err != nil {
			return err
		}
		if err := system.Setresuid(0, 0, 0); err != nil {
			return err
		}
	default:
		uid, gid, suppGids, err := user.GetUserGroupSupplementary(container.User, syscall.Getuid(), syscall.Getgid())
		if err != nil {
			return err
		}
		if err := system.Setgroups(suppGids); err != nil {
			return err
		}
		if err := system.Setgid(gid); err != nil {
			return err
		}
		if err := system.Setuid(uid); err != nil {
			return err
		}
	}
	return nil
}

// setupVethNetwork uses the Network config if it is not nil to initialize
// the new veth interface inside the container for use by changing the name to eth0
// setting the MTU and IP address along with the default gateway
func setupNetwork(container *libcontainer.Container, context libcontainer.Context) error {
	for _, config := range container.Networks {
		strategy, err := network.GetStrategy(config.Type)
		if err != nil {
			return err
		}

		err1 := strategy.Initialize(config, context)
		if err1 != nil {
			return err1
		}
	}
	return nil
}

// finalizeNamespace drops the caps and sets the correct user
// and working dir before execing the command inside the namespace
func finalizeNamespace(container *libcontainer.Container) error {
	if err := capabilities.DropCapabilities(container); err != nil {
		return fmt.Errorf("drop capabilities %s", err)
	}
	if err := setupUser(container); err != nil {
		return fmt.Errorf("setup user %s", err)
	}
	if container.WorkingDir != "" {
		if err := system.Chdir(container.WorkingDir); err != nil {
			return fmt.Errorf("chdir to %s %s", container.WorkingDir, err)
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package crypto_test

import (
	"bytes"
	"crypto/rand"
	"testing"

	. "github.com/libp2p/go-libp2p-core/crypto"
	pb "github.com/libp2p/go-libp2p-core/crypto/pb"
	"github.com/libp2p/go-libp2p-core/test"
)

func TestKeys(t *testing.T) {
	for _, typ := range KeyTypes {
		testKeyType(typ, t)
	}
}

func testKeyType(typ int, t *testing.T) {
	sk, pk, err := test.RandTestKeyPair(typ, 512)
	if err != nil {
		t.Fatal(err)
	}

	testKeySignature(t, sk)
	testKeyEncoding(t, sk)
	testKeyEquals(t, sk)
	testKeyEquals(t, pk)
}

func testKeySignature(t *testing.T, sk PrivKey) {
	pk := sk.GetPublic()

	text := make([]byte, 16)
	if _, err := rand.Read(text); err != nil {
		t.Fatal(err)
	}

	sig, err := sk.Sign(text)
	if err != nil {
		t.Fatal(err)
	}

	valid, err := pk.Verify(text, sig)
	if err != nil {
		t.Fatal(err)
	}

	if !valid {
		t.Fatal("Invalid signature.")
	}
}

func testKeyEncoding(t *testing.T, sk PrivKey) {
	skbm, err := MarshalPrivateKey(sk)
	if err != nil {
		t.Fatal(err)
	}

	sk2, err := UnmarshalPrivateKey(skbm)
	if err != nil {
		t.Fatal(err)
	}

	if !sk.Equals(sk2) {
		t.Error("Unmarshaled private key didn't match original.\n")
	}

	skbm2, err := MarshalPrivateKey(sk2)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(skbm, skbm2) {
		t.Error("skb -> marshal -> unmarshal -> skb failed.\n", skbm, "\n", skbm2)
	}

	pk := sk.GetPublic()
	pkbm, err := MarshalPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}

	pk2, err := UnmarshalPublicKey(pkbm)
	if err != nil {
		t.Fatal(err)
	}

	if !pk.Equals(pk2) {
		t.Error("Unmarshaled public key didn't match original.\n")
	}

	pkbm2, err := MarshalPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(pkbm, pkbm2) {
		t.Error("skb -> marshal -> unmarshal -> skb failed.\n", pkbm, "\n", pkbm2)
	}
}

func testKeyEquals(t *testing.T, k Key) {
	kb, err := k.Bytes()
	if err != nil {
		t.Fatal(err)
	}

	if !KeyEqual(k, k) {
		t.Fatal("Key not equal to itself.")
	}

	if !KeyEqual(k, testkey(kb)) {
		t.Fatal("Key not equal to key with same bytes.")
	}

	sk, pk, err := test.RandTestKeyPair(RSA, 512)
	if err != nil {
		t.Fatal(err)
	}

	if KeyEqual(k, sk) {
		t.Fatal("Keys should not equal.")
	}

	if KeyEqual(k, pk) {
		t.Fatal("Keys should not equal.")
	}
}

type testkey []byte

func (pk testkey) Bytes() ([]byte, error) {
	return pk, nil
}

func (pk testkey) Type() pb.KeyType {
	return pb.KeyType_RSA
}

func (pk testkey) Raw() ([]byte, error) {
	return pk, nil
}

func (pk testkey) Equals(k Key) bool {
	return KeyEqual(pk, k)
}
<commit_msg>Add test for unknown elliptic curves<commit_after>package crypto_test

import (
	"bytes"
	"crypto/rand"
	"testing"

	. "github.com/libp2p/go-libp2p-core/crypto"
	pb "github.com/libp2p/go-libp2p-core/crypto/pb"
	"github.com/libp2p/go-libp2p-core/test"
)

func TestKeys(t *testing.T) {
	for _, typ := range KeyTypes {
		testKeyType(typ, t)
	}
}

func testKeyType(typ int, t *testing.T) {
	sk, pk, err := test.RandTestKeyPair(typ, 512)
	if err != nil {
		t.Fatal(err)
	}

	testKeySignature(t, sk)
	testKeyEncoding(t, sk)
	testKeyEquals(t, sk)
	testKeyEquals(t, pk)
}

func testKeySignature(t *testing.T, sk PrivKey) {
	pk := sk.GetPublic()

	text := make([]byte, 16)
	if _, err := rand.Read(text); err != nil {
		t.Fatal(err)
	}

	sig, err := sk.Sign(text)
	if err != nil {
		t.Fatal(err)
	}

	valid, err := pk.Verify(text, sig)
	if err != nil {
		t.Fatal(err)
	}

	if !valid {
		t.Fatal("Invalid signature.")
	}
}

func testKeyEncoding(t *testing.T, sk PrivKey) {
	skbm, err := MarshalPrivateKey(sk)
	if err != nil {
		t.Fatal(err)
	}

	sk2, err := UnmarshalPrivateKey(skbm)
	if err != nil {
		t.Fatal(err)
	}

	if !sk.Equals(sk2) {
		t.Error("Unmarshaled private key didn't match original.\n")
	}

	skbm2, err := MarshalPrivateKey(sk2)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(skbm, skbm2) {
		t.Error("skb -> marshal -> unmarshal -> skb failed.\n", skbm, "\n", skbm2)
	}

	pk := sk.GetPublic()
	pkbm, err := MarshalPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}

	pk2, err := UnmarshalPublicKey(pkbm)
	if err != nil {
		t.Fatal(err)
	}

	if !pk.Equals(pk2) {
		t.Error("Unmarshaled public key didn't match original.\n")
	}

	pkbm2, err := MarshalPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(pkbm, pkbm2) {
		t.Error("skb -> marshal -> unmarshal -> skb failed.\n", pkbm, "\n", pkbm2)
	}
}

func testKeyEquals(t *testing.T, k Key) {
	kb, err := k.Bytes()
	if err != nil {
		t.Fatal(err)
	}

	if !KeyEqual(k, k) {
		t.Fatal("Key not equal to itself.")
	}

	if !KeyEqual(k, testkey(kb)) {
		t.Fatal("Key not equal to key with same bytes.")
	}

	sk, pk, err := test.RandTestKeyPair(RSA, 512)
	if err != nil {
		t.Fatal(err)
	}

	if KeyEqual(k, sk) {
		t.Fatal("Keys should not equal.")
	}

	if KeyEqual(k, pk) {
		t.Fatal("Keys should not equal.")
	}
}

type testkey []byte

func (pk testkey) Bytes() ([]byte, error) {
	return pk, nil
}

func (pk testkey) Type() pb.KeyType {
	return pb.KeyType_RSA
}

func (pk testkey) Raw() ([]byte, error) {
	return pk, nil
}

func (pk testkey) Equals(k Key) bool {
	return KeyEqual(pk, k)
}

func TestUnknownCurveErrors(t *testing.T) {
	_, _, err := GenerateEKeyPair("P-256")
	if err != nil {
		t.Fatal(err)
	}

	_, _, err = GenerateEKeyPair("error-please")
	if err == nil {
		t.Fatal("expected invalid key type to error")
	}
}
<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All Rights Reserved.
//
// 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 oauth2

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-martini/martini"
	"github.com/martini-contrib/sessions"
)

func Test_LoginRedirect(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&Options{
		ClientId:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	r, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "https://accounts.google.com/o/oauth2/auth?access_type=&approval_prompt=&client_id=client_id&redirect_uri=refresh_url&response_type=code&scope=x+y&state=%2F" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}

func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&Options{
		ClientId:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
		return 200, tokens.Access()
	})

	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	m.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}

func Test_Logout(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&Options{
	// no need to configure
	}))

	m.Get("/", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/get", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User credentials are still kept in the session.")
		}
	})

	logout, _ := http.NewRequest("GET", "/logout", nil)
	index, _ := http.NewRequest("GET", "/", nil)

	m.ServeHTTP(httptest.NewRecorder(), index)
	m.ServeHTTP(recorder, logout)

	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the next page.")
	}
}

func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&Options{
	// no need to configure
	}))

	m.Get("/addtoken", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User not logged out although access token is expired.")
		}
	})

	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, addtoken)
	m.ServeHTTP(recorder, index)
}

func Test_InjectedTokens(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&Options{
	// no need to configure
	}))
	m.Get("/", func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
}

func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&Options{
	// no need to configure
	}))
	m.Get("/", LoginRequired, func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page although user is not logged in.")
	}
}
<commit_msg>fix tests<commit_after>// Copyright 2014 Google Inc. All Rights Reserved.
//
// 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 oauth2

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-martini/martini"
	"github.com/golang/oauth2"
	"github.com/martini-contrib/sessions"
)

func Test_LoginRedirect(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.New()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&oauth2.Options{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	r, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "https://accounts.google.com/o/oauth2/auth?access_type=&approval_prompt=&client_id=client_id&redirect_uri=refresh_url&response_type=code&scope=x+y&state=%2F" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}

func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&oauth2.Options{
		ClientID:     "client_id",
		ClientSecret: "client_secret",
		RedirectURL:  "refresh_url",
		Scopes:       []string{"x", "y"},
	}))

	m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
		return 200, tokens.Access()
	})

	r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
	m.ServeHTTP(recorder, r)

	location := recorder.HeaderMap["Location"][0]
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page.")
	}
	if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
		t.Errorf("Not being redirected to the right page, %v found", location)
	}
}

func Test_Logout(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&oauth2.Options{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	m.Get("/", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/get", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User credentials are still kept in the session.")
		}
	})

	logout, _ := http.NewRequest("GET", "/logout", nil)
	index, _ := http.NewRequest("GET", "/", nil)

	m.ServeHTTP(httptest.NewRecorder(), index)
	m.ServeHTTP(recorder, logout)

	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the next page.")
	}
}

func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
	recorder := httptest.NewRecorder()
	s := sessions.NewCookieStore([]byte("secret123"))

	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", s))
	m.Use(Google(&oauth2.Options{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))

	m.Get("/addtoken", func(s sessions.Session) {
		s.Set(keyToken, "dummy token")
	})

	m.Get("/", func(s sessions.Session) {
		if s.Get(keyToken) != nil {
			t.Errorf("User not logged out although access token is expired.")
		}
	})

	addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
	index, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, addtoken)
	m.ServeHTTP(recorder, index)
}

func Test_InjectedTokens(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&oauth2.Options{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))
	m.Get("/", func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
}

func Test_LoginRequired(t *testing.T) {
	recorder := httptest.NewRecorder()
	m := martini.Classic()
	m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
	m.Use(Google(&oauth2.Options{
		ClientID:     "foo",
		ClientSecret: "foo",
		RedirectURL:  "foo",
	}))
	m.Get("/", LoginRequired, func(tokens Tokens) string {
		return "Hello world!"
	})
	r, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(recorder, r)
	if recorder.Code != 302 {
		t.Errorf("Not being redirected to the auth page although user is not logged in.")
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.

package oci

import (
	"log"
)

const Version = "3.54.0"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}
<commit_msg>Finalize changelog and release for version v3.55.0<commit_after>// Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.

package oci

import (
	"log"
)

const Version = "3.55.0"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}
<|endoftext|>


<commit_before>/*
   Implements the Google omaha protocol.

   Omaha is a request/response protocol using XML. Requests are made by
   clients and responses are given by the Omaha server.
   http://code.google.com/p/omaha/wiki/ServerProtocol
*/
package omaha

import (
	"encoding/xml"
)

type Request struct {
	XMLName        xml.Name `xml:"request" datastore:"-"`
	Os             Os       `xml:"os"`
	Apps           []*App   `xml:"app"`
	Protocol       string   `xml:"protocol,attr"`
	Version        string   `xml:"version,attr,omitempty"`
	IsMachine      string   `xml:"ismachine,attr,omitempty"`
	SessionId      string   `xml:"sessionid,attr,omitempty"`
	UserId         string   `xml:"userid,attr,omitempty"`
	InstallSource  string   `xml:"installsource,attr,omitempty"`
	TestSource     string   `xml:"testsource,attr,omitempty"`
	RequestId      string   `xml:"requestid,attr,omitempty"`
	UpdaterVersion string   `xml:"updaterversion,attr,omitempty"`
}

func NewRequest(version string, platform string, sp string, arch string) *Request {
	r := new(Request)
	r.Protocol = "3.0"
	r.Os = Os{Version: version, Platform: platform, Sp: sp, Arch: arch}
	return r
}

func (r *Request) AddApp(id string, version string) *App {
	a := NewApp(id)
	a.Version = version
	r.Apps = append(r.Apps, a)
	return a
}

/* Response
 */
type Response struct {
	XMLName  xml.Name `xml:"response" datastore:"-"`
	DayStart DayStart `xml:"daystart"`
	Apps     []*App   `xml:"app"`
	Protocol string   `xml:"protocol,attr"`
	Server   string   `xml:"server,attr"`
}

func NewResponse(server string) *Response {
	r := &Response{Server: server, Protocol: "3.0"}
	r.DayStart.ElapsedSeconds = "0"
	return r
}

type DayStart struct {
	ElapsedSeconds string `xml:"elapsed_seconds,attr"`
}

func (r *Response) AddApp(id string) *App {
	a := NewApp(id)
	r.Apps = append(r.Apps, a)
	return a
}

type App struct {
	XMLName     xml.Name     `xml:"app" datastore"-"`
	Ping        *Ping        `xml:"ping"`
	UpdateCheck *UpdateCheck `xml:"updatecheck"`
	Events      []*Event     `xml:"event"`
	Id          string       `xml:"appid,attr,omitempty"`
	Version     string       `xml:"version,attr,omitempty"`
	NextVersion string       `xml:"nextversion,attr,omitempty"`
	Lang        string       `xml:"lang,attr,omitempty"`
	Client      string       `xml:"client,attr,omitempty"`
	InstallAge  string       `xml:"installage,attr,omitempty"`
	FromTrack   string       `xml:"from_track,attr,omitempty"`
	Status      string       `xml:"status,attr,omitempty"`
}

func NewApp(id string) *App {
	a := &App{Id: id}
	return a
}

func (a *App) AddUpdateCheck() *UpdateCheck {
	a.UpdateCheck = new(UpdateCheck)
	return a.UpdateCheck
}

func (a *App) AddPing() *Ping {
	a.Ping = new(Ping)
	return a.Ping
}

func (a *App) AddEvent() *Event {
	event := new(Event)
	a.Events = append(a.Events, event)
	return event
}

type UpdateCheck struct {
	XMLName             xml.Name  `xml:"updatecheck" datastore:"-"`
	Urls                *Urls     `xml:"urls"`
	Manifest            *Manifest `xml:"manifest"`
	TargetVersionPrefix string    `xml:"targetversionprefix,attr,omitempty"`
	Status              string    `xml:"status,attr,omitempty"`
}

func (u *UpdateCheck) AddUrl(codebase string) *Url {
	if u.Urls == nil {
		u.Urls = new(Urls)
	}
	url := new(Url)
	url.CodeBase = codebase
	u.Urls.Urls = append(u.Urls.Urls, *url)
	return url
}

func (u *UpdateCheck) AddManifest(version string) *Manifest {
	u.Manifest = &Manifest{Version: version}
	return u.Manifest
}

type Ping struct {
	XMLName        xml.Name `xml:"ping" datastore:"-"`
	LastReportDays string   `xml:"r,attr,omitempty"`
	Status         string   `xml:"status,attr,omitempty"`
}

type Os struct {
	XMLName  xml.Name `xml:"os" datastore:"-"`
	Platform string   `xml:"platform,attr,omitempty"`
	Version  string   `xml:"version,attr,omitempty"`
	Sp       string   `xml:"sp,attr,omitempty"`
	Arch     string   `xml:"arch,attr,omitempty"`
}

func NewOs(platform string, version string, sp string, arch string) *Os {
	o := &Os{Version: version, Platform: platform, Sp: sp, Arch: arch}
	return o
}

type Event struct {
	XMLName         xml.Name `xml:"event" datastore:"-"`
	Type            string   `xml:"eventtype,attr,omitempty"`
	Result          string   `xml:"eventresult,attr,omitempty"`
	PreviousVersion string   `xml:"previousversion,attr,omitempty"`
}

type Urls struct {
	XMLName xml.Name `xml:"urls" datastore:"-"`
	Urls    []Url    `xml:"url"`
}

type Url struct {
	XMLName  xml.Name `xml:"url" datastore:"-"`
	CodeBase string   `xml:"codebase,attr"`
}

type Manifest struct {
	XMLName  xml.Name `xml:"manifest" datastore:"-"`
	Packages Packages `xml:"packages"`
	Actions  Actions  `xml:"actions"`
	Version  string   `xml:"version,attr"`
}

type Packages struct {
	XMLName  xml.Name  `xml:"packages" datastore:"-"`
	Packages []Package `xml:"package"`
}

type Package struct {
	XMLName  xml.Name `xml:"package" datastore:"-"`
	Hash     string   `xml:"hash,attr"`
	Name     string   `xml:"name,attr"`
	Size     string   `xml:"size,attr"`
	Required bool     `xml:"required,attr"`
}

func (m *Manifest) AddPackage(hash string, name string, size string, required bool) *Package {
	p := &Package{Hash: hash, Name: name, Size: size, Required: required}
	m.Packages.Packages = append(m.Packages.Packages, *p)
	return p
}

type Actions struct {
	XMLName xml.Name  `xml:"actions" datastore:"-"`
	Actions []*Action `xml:"action"`
}

type Action struct {
	XMLName         xml.Name `xml:"action" datastore:"-"`
	Event           string   `xml:"event,attr"`
	ChromeOSVersion string   `xml:"ChromeOSVersion,attr"`
	Sha256          string   `xml:"sha256,attr"`
	NeedsAdmin      bool     `xml:"needsadmin,attr"`
	IsDelta         bool     `xml:"IsDelta,attr"`
	DisablePayloadBackoff bool `xml:"DisablePayloadBackoff,attr,omitempty"`
}

func (m *Manifest) AddAction(event string) *Action {
	a := &Action{Event: event}
	m.Actions.Actions = append(m.Actions.Actions, a)
	return a
}

var EventTypes = map[int]string{
	0:   "unknown",
	1:   "download complete",
	2:   "install complete",
	3:   "update complete",
	4:   "uninstall",
	5:   "download started",
	6:   "install started",
	9:   "new application install started",
	10:  "setup started",
	11:  "setup finished",
	12:  "update application started",
	13:  "update download started",
	14:  "update download finished",
	15:  "update installer started",
	16:  "setup update begin",
	17:  "setup update complete",
	20:  "register product complete",
	30:  "OEM install first check",
	40:  "app-specific command started",
	41:  "app-specific command ended",
	100: "setup failure",
	102: "COM server failure",
	103: "setup update failure",
}

var EventResults = map[int]string{
	0:  "error",
	1:  "success",
	2:  "success reboot",
	3:  "success restart browser",
	4:  "cancelled",
	5:  "error installer MSI",
	6:  "error installer other",
	7:  "noupdate",
	8:  "error installer system",
	9:  "update deferred",
	10: "handoff error",
}
<commit_msg>fix(omaha): create section for update_engine extensions<commit_after>/*
   Implements the Google omaha protocol.

   Omaha is a request/response protocol using XML. Requests are made by
   clients and responses are given by the Omaha server.
   http://code.google.com/p/omaha/wiki/ServerProtocol
*/
package omaha

import (
	"encoding/xml"
)

type Request struct {
	XMLName        xml.Name `xml:"request" datastore:"-"`
	Os             Os       `xml:"os"`
	Apps           []*App   `xml:"app"`
	Protocol       string   `xml:"protocol,attr"`
	Version        string   `xml:"version,attr,omitempty"`
	IsMachine      string   `xml:"ismachine,attr,omitempty"`
	SessionId      string   `xml:"sessionid,attr,omitempty"`
	UserId         string   `xml:"userid,attr,omitempty"`
	InstallSource  string   `xml:"installsource,attr,omitempty"`
	TestSource     string   `xml:"testsource,attr,omitempty"`
	RequestId      string   `xml:"requestid,attr,omitempty"`
	UpdaterVersion string   `xml:"updaterversion,attr,omitempty"`
}

func NewRequest(version string, platform string, sp string, arch string) *Request {
	r := new(Request)
	r.Protocol = "3.0"
	r.Os = Os{Version: version, Platform: platform, Sp: sp, Arch: arch}
	return r
}

func (r *Request) AddApp(id string, version string) *App {
	a := NewApp(id)
	a.Version = version
	r.Apps = append(r.Apps, a)
	return a
}

/* Response
 */
type Response struct {
	XMLName  xml.Name `xml:"response" datastore:"-"`
	DayStart DayStart `xml:"daystart"`
	Apps     []*App   `xml:"app"`
	Protocol string   `xml:"protocol,attr"`
	Server   string   `xml:"server,attr"`
}

func NewResponse(server string) *Response {
	r := &Response{Server: server, Protocol: "3.0"}
	r.DayStart.ElapsedSeconds = "0"
	return r
}

type DayStart struct {
	ElapsedSeconds string `xml:"elapsed_seconds,attr"`
}

func (r *Response) AddApp(id string) *App {
	a := NewApp(id)
	r.Apps = append(r.Apps, a)
	return a
}

type App struct {
	XMLName     xml.Name     `xml:"app" datastore"-"`
	Ping        *Ping        `xml:"ping"`
	UpdateCheck *UpdateCheck `xml:"updatecheck"`
	Events      []*Event     `xml:"event"`
	Id          string       `xml:"appid,attr,omitempty"`
	Version     string       `xml:"version,attr,omitempty"`
	NextVersion string       `xml:"nextversion,attr,omitempty"`
	Lang        string       `xml:"lang,attr,omitempty"`
	Client      string       `xml:"client,attr,omitempty"`
	InstallAge  string       `xml:"installage,attr,omitempty"`
	FromTrack   string       `xml:"from_track,attr,omitempty"`
	Status      string       `xml:"status,attr,omitempty"`
}

func NewApp(id string) *App {
	a := &App{Id: id}
	return a
}

func (a *App) AddUpdateCheck() *UpdateCheck {
	a.UpdateCheck = new(UpdateCheck)
	return a.UpdateCheck
}

func (a *App) AddPing() *Ping {
	a.Ping = new(Ping)
	return a.Ping
}

func (a *App) AddEvent() *Event {
	event := new(Event)
	a.Events = append(a.Events, event)
	return event
}

type UpdateCheck struct {
	XMLName             xml.Name  `xml:"updatecheck" datastore:"-"`
	Urls                *Urls     `xml:"urls"`
	Manifest            *Manifest `xml:"manifest"`
	TargetVersionPrefix string    `xml:"targetversionprefix,attr,omitempty"`
	Status              string    `xml:"status,attr,omitempty"`
}

func (u *UpdateCheck) AddUrl(codebase string) *Url {
	if u.Urls == nil {
		u.Urls = new(Urls)
	}
	url := new(Url)
	url.CodeBase = codebase
	u.Urls.Urls = append(u.Urls.Urls, *url)
	return url
}

func (u *UpdateCheck) AddManifest(version string) *Manifest {
	u.Manifest = &Manifest{Version: version}
	return u.Manifest
}

type Ping struct {
	XMLName        xml.Name `xml:"ping" datastore:"-"`
	LastReportDays string   `xml:"r,attr,omitempty"`
	Status         string   `xml:"status,attr,omitempty"`
}

type Os struct {
	XMLName  xml.Name `xml:"os" datastore:"-"`
	Platform string   `xml:"platform,attr,omitempty"`
	Version  string   `xml:"version,attr,omitempty"`
	Sp       string   `xml:"sp,attr,omitempty"`
	Arch     string   `xml:"arch,attr,omitempty"`
}

func NewOs(platform string, version string, sp string, arch string) *Os {
	o := &Os{Version: version, Platform: platform, Sp: sp, Arch: arch}
	return o
}

type Event struct {
	XMLName         xml.Name `xml:"event" datastore:"-"`
	Type            string   `xml:"eventtype,attr,omitempty"`
	Result          string   `xml:"eventresult,attr,omitempty"`
	PreviousVersion string   `xml:"previousversion,attr,omitempty"`
}

type Urls struct {
	XMLName xml.Name `xml:"urls" datastore:"-"`
	Urls    []Url    `xml:"url"`
}

type Url struct {
	XMLName  xml.Name `xml:"url" datastore:"-"`
	CodeBase string   `xml:"codebase,attr"`
}

type Manifest struct {
	XMLName  xml.Name `xml:"manifest" datastore:"-"`
	Packages Packages `xml:"packages"`
	Actions  Actions  `xml:"actions"`
	Version  string   `xml:"version,attr"`
}

type Packages struct {
	XMLName  xml.Name  `xml:"packages" datastore:"-"`
	Packages []Package `xml:"package"`
}

type Package struct {
	XMLName  xml.Name `xml:"package" datastore:"-"`
	Hash     string   `xml:"hash,attr"`
	Name     string   `xml:"name,attr"`
	Size     string   `xml:"size,attr"`
	Required bool     `xml:"required,attr"`
}

func (m *Manifest) AddPackage(hash string, name string, size string, required bool) *Package {
	p := &Package{Hash: hash, Name: name, Size: size, Required: required}
	m.Packages.Packages = append(m.Packages.Packages, *p)
	return p
}

type Actions struct {
	XMLName xml.Name  `xml:"actions" datastore:"-"`
	Actions []*Action `xml:"action"`
}

type Action struct {
	XMLName         xml.Name `xml:"action" datastore:"-"`
	Event           string   `xml:"event,attr"`

	// Extensions added by update_engine
	ChromeOSVersion string   `xml:"ChromeOSVersion,attr"`
	Sha256          string   `xml:"sha256,attr"`
	NeedsAdmin      bool     `xml:"needsadmin,attr"`
	IsDelta         bool     `xml:"IsDelta,attr"`
	DisablePayloadBackoff bool `xml:"DisablePayloadBackoff,attr,omitempty"`
}

func (m *Manifest) AddAction(event string) *Action {
	a := &Action{Event: event}
	m.Actions.Actions = append(m.Actions.Actions, a)
	return a
}

var EventTypes = map[int]string{
	0:   "unknown",
	1:   "download complete",
	2:   "install complete",
	3:   "update complete",
	4:   "uninstall",
	5:   "download started",
	6:   "install started",
	9:   "new application install started",
	10:  "setup started",
	11:  "setup finished",
	12:  "update application started",
	13:  "update download started",
	14:  "update download finished",
	15:  "update installer started",
	16:  "setup update begin",
	17:  "setup update complete",
	20:  "register product complete",
	30:  "OEM install first check",
	40:  "app-specific command started",
	41:  "app-specific command ended",
	100: "setup failure",
	102: "COM server failure",
	103: "setup update failure",
}

var EventResults = map[int]string{
	0:  "error",
	1:  "success",
	2:  "success reboot",
	3:  "success restart browser",
	4:  "cancelled",
	5:  "error installer MSI",
	6:  "error installer other",
	7:  "noupdate",
	8:  "error installer system",
	9:  "update deferred",
	10: "handoff error",
}
<|endoftext|>


<commit_before>package main

import (
	// "github.com/davecgh/go-spew/spew"
	"github.com/elastic/libbeat/common"
	"github.com/elastic/libbeat/logp"
	"github.com/tatsushid/go-fastping"
	"net"
	"os"
	"time"
)

type Pingbeat struct {
	isAlive  bool
	useIPv4  bool
	useIPv6  bool
	period   time.Duration
	pingType string
	targets  []Target
	events   chan common.MapStr
}

func (p *Pingbeat) Init(config PingConfig, events chan common.MapStr) error {

	if config.Period != nil {
		p.period = time.Duration(*config.Period) * time.Second
	} else {
		p.period = 1 * time.Second
	}
	logp.Debug("pingbeat", "Period %v\n", p.period)

	if *config.Privileged {
		p.pingType = "ip"
	} else {
		p.pingType = "udp"
	}
	logp.Debug("pingbeat", "Using %v for pings\n", p.pingType)

	p.useIPv4 = true
	p.useIPv6 = false
	if config.UseIPv4 != nil && *config.UseIPv4 == false {
		p.useIPv4 = false
	}
	if config.UseIPv6 != nil && *config.UseIPv6 == true {
		p.useIPv6 = true
	}
	logp.Debug("pingbeat", "IPv4: %v, IPv6: %v\n", p.useIPv4, p.useIPv6)

	if config.Targets != nil {
		for tag, targets := range *config.Targets {
			for i := 0; i < len(targets); i++ {
				thisTarget := &Target{}
				thisTarget.Init(targets[i], tag)
				p.targets = append(p.targets, *thisTarget)
			}
		}
	}

	p.events = events
	return nil
}

func (p *Pingbeat) Run() error {

	p.isAlive = true

	fp := fastping.NewPinger()

	errInput, err := fp.Network(p.pingType)
	if err != nil {
		logp.Critical("Error: %v (input %v)", err, errInput)
		os.Exit(1)
	}

	details := make(map[string][2]string)

	for _, target := range p.targets {
		if p.useIPv4 {
			logp.Debug("pingbeat", "In IPv4 Loop\n")
			for i := 0; i < len(target.ipv4Addrs); i++ {
				fp.AddIP(target.ipv4Addrs[i].String())
				details[target.ipv4Addrs[i].String()] = [2]string{target.name, target.tag}
			}
		}
		if p.useIPv6 {
			logp.Debug("pingbeat", "In IPv6 Loop\n")
			for i := 0; i < len(target.ipv6Addrs); i++ {
				fp.AddIP(target.ipv6Addrs[i].String())
				details[target.ipv6Addrs[i].String()] = [2]string{target.name, target.tag}
			}
		}
	}
	fp.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
		name := details[addr.String()][0]
		tag := details[addr.String()][1]
		event := common.MapStr{
			"timestamp":   common.Time(time.Now()),
			"type":        "pingbeat",
			"target_name": name,
			"target_addr": addr.String(),
			"tag":         tag,
			"rtt":         milliSeconds(rtt),
		}
		p.events <- event
	}
	// fp.OnIdle = func() {
	// 	fmt.Println("loop done")
	// }
	for p.isAlive {
		time.Sleep(p.period)
		err := fp.Run()
		if err != nil {
			logp.Warn("Warning: %v", err)
		}
	}

	return nil
}

func (p *Pingbeat) Stop() {
	p.isAlive = false
}
<commit_msg>Slightly better debug messages for targets.<commit_after>package main

import (
	// "github.com/davecgh/go-spew/spew"
	"github.com/elastic/libbeat/common"
	"github.com/elastic/libbeat/logp"
	"github.com/tatsushid/go-fastping"
	"net"
	"os"
	"time"
)

type Pingbeat struct {
	isAlive  bool
	useIPv4  bool
	useIPv6  bool
	period   time.Duration
	pingType string
	targets  []Target
	events   chan common.MapStr
}

func (p *Pingbeat) Init(config PingConfig, events chan common.MapStr) error {

	if config.Period != nil {
		p.period = time.Duration(*config.Period) * time.Second
	} else {
		p.period = 1 * time.Second
	}
	logp.Debug("pingbeat", "Period %v\n", p.period)

	if *config.Privileged {
		p.pingType = "ip"
	} else {
		p.pingType = "udp"
	}
	logp.Debug("pingbeat", "Using %v for pings\n", p.pingType)

	p.useIPv4 = true
	p.useIPv6 = false
	if config.UseIPv4 != nil && *config.UseIPv4 == false {
		p.useIPv4 = false
	}
	if config.UseIPv6 != nil && *config.UseIPv6 == true {
		p.useIPv6 = true
	}
	logp.Debug("pingbeat", "IPv4: %v, IPv6: %v\n", p.useIPv4, p.useIPv6)

	if config.Targets != nil {
		for tag, targets := range *config.Targets {
			for i := 0; i < len(targets); i++ {
				thisTarget := &Target{}
				thisTarget.Init(targets[i], tag)
				p.targets = append(p.targets, *thisTarget)
			}
		}
	}

	p.events = events
	return nil
}

func (p *Pingbeat) Run() error {

	p.isAlive = true

	fp := fastping.NewPinger()

	errInput, err := fp.Network(p.pingType)
	if err != nil {
		logp.Critical("Error: %v (input %v)", err, errInput)
		os.Exit(1)
	}

	details := make(map[string][2]string)

	for _, target := range p.targets {
		if p.useIPv4 {
			for i := 0; i < len(target.ipv4Addrs); i++ {
				logp.Debug("pingbeat", "Adding target IP: %s, Name: %s, Tag: %s\n", target.ipv4Addrs[i].String(), target.name, target.tag)
				fp.AddIP(target.ipv4Addrs[i].String())
				details[target.ipv4Addrs[i].String()] = [2]string{target.name, target.tag}
			}
		}
		if p.useIPv6 {
			for i := 0; i < len(target.ipv6Addrs); i++ {
				logp.Debug("pingbeat", "Adding target IP: %s, Name: %s, Tag: %s\n", target.ipv4Addrs[i].String(), target.name, target.tag)
				fp.AddIP(target.ipv6Addrs[i].String())
				details[target.ipv6Addrs[i].String()] = [2]string{target.name, target.tag}
			}
		}
	}
	fp.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
		name := details[addr.String()][0]
		tag := details[addr.String()][1]
		event := common.MapStr{
			"timestamp":   common.Time(time.Now()),
			"type":        "pingbeat",
			"target_name": name,
			"target_addr": addr.String(),
			"tag":         tag,
			"rtt":         milliSeconds(rtt),
		}
		p.events <- event
	}
	// fp.OnIdle = func() {
	// 	fmt.Println("loop done")
	// }
	for p.isAlive {
		time.Sleep(p.period)
		err := fp.Run()
		if err != nil {
			logp.Warn("Warning: %v", err)
		}
	}

	return nil
}

func (p *Pingbeat) Stop() {
	p.isAlive = false
}
<|endoftext|>


<commit_before>package structlog_test

import (
	"bytes"
	"fmt"
	stdlog "log"
	"os"
	"strconv"
	"testing"

	"github.com/powerman/check"
	"github.com/powerman/structlog"
)

type bufPrinter struct{ bytes.Buffer }

func (bp *bufPrinter) Print(v ...interface{}) { fmt.Fprint(&bp.Buffer, append(v, "\n")...) }

func TestDefaultPrinter(tt *testing.T) {
	t := check.T(tt)
	var buf bytes.Buffer
	stdlog.SetOutput(&buf)
	defer stdlog.SetOutput(os.Stderr)
	log := structlog.New()
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestDefaultPrinter(output_test.go:25)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestDefaultPrinter(output_test.go:26)\n")
}

func TestPrinter(tt *testing.T) {
	t := check.T(tt)
	var buf bufPrinter
	log := structlog.New().SetPrinter(&buf)
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestPrinter(output_test.go:37)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestPrinter(output_test.go:38)\n")
}

func TestOutput(tt *testing.T) {
	t := check.T(tt)
	var buf bytes.Buffer
	log := structlog.New().SetOutput(&buf)
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestOutput(output_test.go:49)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestOutput(output_test.go:50)\n")
}
<commit_msg>ci: fix KeyUnit in tests<commit_after>package structlog_test

import (
	"bytes"
	"fmt"
	stdlog "log"
	"os"
	"strconv"
	"testing"

	"github.com/powerman/check"
	"github.com/powerman/structlog"
)

type bufPrinter struct{ bytes.Buffer }

func (bp *bufPrinter) Print(v ...interface{}) { fmt.Fprint(&bp.Buffer, append(v, "\n")...) }

func TestDefaultPrinter(tt *testing.T) {
	t := check.T(tt)
	var buf bytes.Buffer
	stdlog.SetOutput(&buf)
	defer stdlog.SetOutput(os.Stderr)
	log := structlog.New(structlog.KeyUnit, "structlog")
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestDefaultPrinter(output_test.go:25)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestDefaultPrinter(output_test.go:26)\n")
}

func TestPrinter(tt *testing.T) {
	t := check.T(tt)
	var buf bufPrinter
	log := structlog.New(structlog.KeyUnit, "structlog").SetPrinter(&buf)
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestPrinter(output_test.go:37)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestPrinter(output_test.go:38)\n")
}

func TestOutput(tt *testing.T) {
	t := check.T(tt)
	var buf bytes.Buffer
	log := structlog.New(structlog.KeyUnit, "structlog").SetOutput(&buf)
	log.Info("something happens", "k1", "v1", "k2", "v2")
	log.Warn("oops")
	pid := strconv.Itoa(os.Getpid())
	t.Equal(buf.String(), ""+
		"structlog.test["+pid+"] inf structlog: `something happens` k1=v1 k2=v2 \t@ structlog_test.TestOutput(output_test.go:49)\n"+
		"structlog.test["+pid+"] WRN structlog: `oops` \t@ structlog_test.TestOutput(output_test.go:50)\n")
}
<|endoftext|>


<commit_before>package outputs

import (
	"fmt"
	"strings"

	"github.com/fatih/color"
	"github.com/hexbotio/hex/models"
)

type Cli struct {
}

func (x Cli) Write(outputMsgs <-chan models.Message, service models.Service) {
	for {
		message := <-outputMsgs
		fmt.Print("\n")
		if message.Success {
			color.Set(color.FgGreen)
		} else {
			color.Set(color.FgRed)
		}
		fmt.Println(strings.Join(message.Response[:], "\n"))
		color.Unset()
		fmt.Print("\n", service.BotName, "> ")
	}
}
<commit_msg>only applying color to alert messages<commit_after>package outputs

import (
	"fmt"
	"strings"

	"github.com/fatih/color"
	"github.com/hexbotio/hex/models"
)

type Cli struct {
}

func (x Cli) Write(outputMsgs <-chan models.Message, service models.Service) {
	for {
		message := <-outputMsgs
		fmt.Print("\n")
		if message.Inputs["hex.pipeline.alert"] == "true" {
			if message.Success {
				color.Set(color.FgGreen)
			} else {
				color.Set(color.FgRed)
			}
		}
		fmt.Println(strings.Join(message.Response[:], "\n"))
		color.Unset()
		fmt.Print("\n", service.BotName, "> ")
	}
}
<|endoftext|>


<commit_before>package lib

const (
	Version = "2.2.1"
)
<commit_msg>Put the Version comment back<commit_after>package lib

const (
	// Version is the version number the client believes it is
	Version = "2.2.1"
)
<|endoftext|>


<commit_before>// A `pass` based credential helper. Passwords are stored as arguments to pass
// of the form: "$PASS_FOLDER/base64-url(serverURL)/username". We base64-url
// encode the serverURL, because under the hood pass uses files and folders, so
// /s will get translated into additional folders.
package pass

import (
	"encoding/base64"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"

	"github.com/docker/docker-credential-helpers/credentials"
)

const PASS_FOLDER = "docker-credential-helpers"

var (
	PassInitialized bool
)

func init() {
	// In principle, we could just run `pass init`. However, pass has a bug
	// where if gpg fails, it doesn't always exit 1. Additionally, pass
	// uses gpg2, but gpg is the default, which may be confusing. So let's
	// just explictily check that pass actually can store and retreive a
	// password.
	password := "pass is initialized"
	name := path.Join(PASS_FOLDER, "docker-pass-initialized-check")

	_, err := runPass(password, "insert", "-f", "-m", name)
	if err != nil {
		return
	}

	stored, err := runPass("", "show", name)
	PassInitialized = err == nil && stored == password

	if PassInitialized {
		runPass("", "rm", "-rf", name)
	}
}

func runPass(stdinContent string, args ...string) (string, error) {
	cmd := exec.Command("pass", args...)

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return "", err
	}
	defer stdin.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		return "", err
	}
	defer stderr.Close()

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return "", err
	}
	defer stdout.Close()

	err = cmd.Start()
	if err != nil {
		return "", err
	}

	_, err = stdin.Write([]byte(stdinContent))
	if err != nil {
		return "", err
	}
	stdin.Close()

	errContent, err := ioutil.ReadAll(stderr)
	if err != nil {
		return "", fmt.Errorf("error reading stderr: %s", err)
	}

	result, err := ioutil.ReadAll(stdout)
	if err != nil {
		return "", fmt.Errorf("Error reading stdout: %s", err)
	}

	cmdErr := cmd.Wait()
	if cmdErr != nil {
		return "", fmt.Errorf("%s: %s", cmdErr, errContent)
	}

	return string(result), nil
}

// Pass handles secrets using Linux secret-service as a store.
type Pass struct{}

// Add adds new credentials to the keychain.
func (h Pass) Add(creds *credentials.Credentials) error {
	if !PassInitialized {
		return errors.New("pass store is uninitialized")
	}

	if creds == nil {
		return errors.New("missing credentials")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(creds.ServerURL))

	_, err := runPass(creds.Secret, "insert", "-f", "-m", path.Join(PASS_FOLDER, encoded, creds.Username))
	return err
}

// Delete removes credentials from the store.
func (h Pass) Delete(serverURL string) error {
	if !PassInitialized {
		return errors.New("pass store is uninitialized")
	}

	if serverURL == "" {
		return errors.New("missing server url")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(serverURL))
	_, err := runPass("", "rm", "-rf", path.Join(PASS_FOLDER, encoded))
	return err
}

func getPassDir() string {
	passDir := os.ExpandEnv("$HOME/.password-store")
	for _, e := range os.Environ() {
		parts := strings.SplitN(e, "=", 2)
		if len(parts) < 2 {
			continue
		}

		if parts[0] != "PASSWORD_STORE_DIR" {
			continue
		}

		passDir = parts[1]
		break
	}

	return passDir
}

// listPassDir lists all the contents of a directory in the password store.
// Pass uses fancy unicode to emit stuff to stdout, so rather than try
// and parse this, let's just look at the directory structure instead.
func listPassDir(args ...string) ([]os.FileInfo, error) {
	passDir := getPassDir()
	p := path.Join(append([]string{passDir, PASS_FOLDER}, args...)...)
	contents, err := ioutil.ReadDir(p)
	if err != nil {
		if os.IsNotExist(err) {
			return []os.FileInfo{}, nil
		}

		return nil, err
	}

	return contents, nil
}

// Get returns the username and secret to use for a given registry server URL.
func (h Pass) Get(serverURL string) (string, string, error) {
	if !PassInitialized {
		return "", "", errors.New("pass store is uninitialized")
	}

	if serverURL == "" {
		return "", "", errors.New("missing server url")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(serverURL))

	if _, err := os.Stat(path.Join(getPassDir(), PASS_FOLDER, encoded)); err != nil {
		if os.IsNotExist(err) {
			return "", "", nil;
		}

		return "", "", err
	}

	usernames, err := listPassDir(encoded)
	if err != nil {
		return "", "", err
	}

	if len(usernames) < 1 {
		return "", "", fmt.Errorf("no usernames for %s", serverURL)
	}

	actual := strings.TrimSuffix(usernames[0].Name(), ".gpg")
	secret, err := runPass("", "show", path.Join(PASS_FOLDER, encoded, actual))
	return actual, secret, err
}

// List returns the stored URLs and corresponding usernames for a given credentials label
func (h Pass) List() (map[string]string, error) {
	if !PassInitialized {
		return nil, errors.New("pass store is uninitialized")
	}

	servers, err := listPassDir()
	if err != nil {
		return nil, err
	}

	resp := map[string]string{}

	for _, server := range servers {
		if !server.IsDir() {
			continue
		}

		serverURL, err := base64.URLEncoding.DecodeString(server.Name())
		if err != nil {
			return nil, err
		}

		usernames, err := listPassDir(server.Name())
		if err != nil {
			return nil, err
		}

		if len(usernames) < 1 {
			return nil, fmt.Errorf("no usernames for %s", serverURL)
		}

		resp[string(serverURL)] = strings.TrimSuffix(usernames[0].Name(), ".gpg")
	}

	return resp, nil
}
<commit_msg>pass: simplify some code<commit_after>// A `pass` based credential helper. Passwords are stored as arguments to pass
// of the form: "$PASS_FOLDER/base64-url(serverURL)/username". We base64-url
// encode the serverURL, because under the hood pass uses files and folders, so
// /s will get translated into additional folders.
package pass

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"

	"github.com/docker/docker-credential-helpers/credentials"
)

const PASS_FOLDER = "docker-credential-helpers"

var (
	PassInitialized bool
)

func init() {
	// In principle, we could just run `pass init`. However, pass has a bug
	// where if gpg fails, it doesn't always exit 1. Additionally, pass
	// uses gpg2, but gpg is the default, which may be confusing. So let's
	// just explictily check that pass actually can store and retreive a
	// password.
	password := "pass is initialized"
	name := path.Join(PASS_FOLDER, "docker-pass-initialized-check")

	_, err := runPass(password, "insert", "-f", "-m", name)
	if err != nil {
		return
	}

	stored, err := runPass("", "show", name)
	PassInitialized = err == nil && stored == password

	if PassInitialized {
		runPass("", "rm", "-rf", name)
	}
}

func runPass(stdin string, args ...string) (string, error) {
	var stdout, stderr bytes.Buffer
	cmd := exec.Command("pass", args...)
	cmd.Stdin = strings.NewReader(stdin)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		return "", fmt.Errorf("%s: %s", err, stderr.String())
	}

	return stdout.String(), nil
}

// Pass handles secrets using Linux secret-service as a store.
type Pass struct{}

// Add adds new credentials to the keychain.
func (h Pass) Add(creds *credentials.Credentials) error {
	if !PassInitialized {
		return errors.New("pass store is uninitialized")
	}

	if creds == nil {
		return errors.New("missing credentials")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(creds.ServerURL))

	_, err := runPass(creds.Secret, "insert", "-f", "-m", path.Join(PASS_FOLDER, encoded, creds.Username))
	return err
}

// Delete removes credentials from the store.
func (h Pass) Delete(serverURL string) error {
	if !PassInitialized {
		return errors.New("pass store is uninitialized")
	}

	if serverURL == "" {
		return errors.New("missing server url")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(serverURL))
	_, err := runPass("", "rm", "-rf", path.Join(PASS_FOLDER, encoded))
	return err
}

func getPassDir() string {
	passDir := "$HOME/.password-store"
	if envDir := os.Getenv("PASSWORD_STORE_DIR"); envDir != "" {
		passDir = envDir
	}
	return os.ExpandEnv(passDir)
}

// listPassDir lists all the contents of a directory in the password store.
// Pass uses fancy unicode to emit stuff to stdout, so rather than try
// and parse this, let's just look at the directory structure instead.
func listPassDir(args ...string) ([]os.FileInfo, error) {
	passDir := getPassDir()
	p := path.Join(append([]string{passDir, PASS_FOLDER}, args...)...)
	contents, err := ioutil.ReadDir(p)
	if err != nil {
		if os.IsNotExist(err) {
			return []os.FileInfo{}, nil
		}

		return nil, err
	}

	return contents, nil
}

// Get returns the username and secret to use for a given registry server URL.
func (h Pass) Get(serverURL string) (string, string, error) {
	if !PassInitialized {
		return "", "", errors.New("pass store is uninitialized")
	}

	if serverURL == "" {
		return "", "", errors.New("missing server url")
	}

	encoded := base64.URLEncoding.EncodeToString([]byte(serverURL))

	if _, err := os.Stat(path.Join(getPassDir(), PASS_FOLDER, encoded)); err != nil {
		if os.IsNotExist(err) {
			return "", "", nil
		}

		return "", "", err
	}

	usernames, err := listPassDir(encoded)
	if err != nil {
		return "", "", err
	}

	if len(usernames) < 1 {
		return "", "", fmt.Errorf("no usernames for %s", serverURL)
	}

	actual := strings.TrimSuffix(usernames[0].Name(), ".gpg")
	secret, err := runPass("", "show", path.Join(PASS_FOLDER, encoded, actual))
	return actual, secret, err
}

// List returns the stored URLs and corresponding usernames for a given credentials label
func (h Pass) List() (map[string]string, error) {
	if !PassInitialized {
		return nil, errors.New("pass store is uninitialized")
	}

	servers, err := listPassDir()
	if err != nil {
		return nil, err
	}

	resp := map[string]string{}

	for _, server := range servers {
		if !server.IsDir() {
			continue
		}

		serverURL, err := base64.URLEncoding.DecodeString(server.Name())
		if err != nil {
			return nil, err
		}

		usernames, err := listPassDir(server.Name())
		if err != nil {
			return nil, err
		}

		if len(usernames) < 1 {
			return nil, fmt.Errorf("no usernames for %s", serverURL)
		}

		resp[string(serverURL)] = strings.TrimSuffix(usernames[0].Name(), ".gpg")
	}

	return resp, nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/omarqazi/broadcast/datastore"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var allChannels map[string]*datastore.Channel = make(map[string]*datastore.Channel)

type PlaylistGenerator struct {
}

func (pl PlaylistGenerator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	checkCORSHeader(w, r)
	var err error
	channelId := strings.TrimSuffix(r.URL.Path, ".m3u8")
	channel, ok := allChannels[channelId]
	if !ok { // If this is the first time the channel is requested
		channel, err = datastore.GetChannel(channelId)
		if err != nil {
			http.Error(w, "internal server error", 500)
			return
		}

		go channel.AdvanceEvery(5*time.Second, nil)
		allChannels[channelId] = channel
	}

	fmt.Fprintln(w, channel.PlaylistData())
}

func checkCORSHeader(w http.ResponseWriter, r *http.Request) {
	origin := r.Header.Get("Origin")
	url, err := url.Parse(origin)
	if err != nil {
		http.Error(w, "Invalid origin header", 400)
	}
	host := url.Host
	w.Header().Add("Access-Control-Allow-Origin", host)
}
<commit_msg>somehow managed to screw up a copy paste operation<commit_after>package main

import (
	"fmt"
	"github.com/omarqazi/broadcast/datastore"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var allChannels map[string]*datastore.Channel = make(map[string]*datastore.Channel)

type PlaylistGenerator struct {
}

func (pl PlaylistGenerator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	checkCORSHeader(w, r)
	var err error
	channelId := strings.TrimSuffix(r.URL.Path, ".m3u8")
	channel, ok := allChannels[channelId]
	if !ok { // If this is the first time the channel is requested
		channel, err = datastore.GetChannel(channelId)
		if err != nil {
			http.Error(w, "internal server error", 500)
			return
		}

		go channel.AdvanceEvery(5*time.Second, nil)
		allChannels[channelId] = channel
	}

	fmt.Fprintln(w, channel.PlaylistData())
}

func checkCORSHeader(w http.ResponseWriter, r *http.Request) {
	origin := r.Header.Get("Origin")
	url, err := url.Parse(origin)
	if err != nil {
		http.Error(w, "Invalid origin header", 400)
	}
	w.Header().Add("Access-Control-Allow-Origin", origin)
}
<|endoftext|>


<commit_before>package spectrum

type MemoryAccessor interface {
	readByte(address uint16) byte
	readByteInternal(address uint16) byte

	writeByte(address uint16, value byte)
	writeByteInternal(address uint16, value byte)

	contendRead(addr uint16, time uint)
	contendReadNoMreq(addr uint16, time uint)

	contendWriteNoMreq(addr uint16, time uint)

	set(addr uint16, value byte)

	getBorder() byte
	setBorder(borderColor byte)

	frame_begin()
	sendScreenToDisplay(display DisplayChannel, borderEvents *BorderEvent)

	At(addr uint) byte
	Data() []byte
}

// The lower 4 bits define the paper, the higher 4 bits define the ink.
// Note that the paper is in the *lower* half.
// There is no flash bit.
type attr_4bit byte

type Screen struct {
	bitmap       [BytesPerLine*ScreenHeight] byte			// Linear y-coordinate
	attr         [BytesPerLine*ScreenHeight] attr_4bit		// Linear y-coordinate
	dirty        [ScreenWidth_Attr*ScreenHeight_Attr] bool	// The 8x8 rectangular region was modified, either the bitmap or the attr
	border       byte
	borderEvents *BorderEvent	// Might be nil
}

type ula_byte_t struct {
	valid bool
	value uint8
}

type ula_attr_t struct {
	valid bool
	value uint8
	tstate uint
}

type Memory struct {
	data         [0x10000]byte

	// Frame number
	frame        uint

	borderColor  byte

	// Screen bitmap data read by ULA, if they differ from data in memory at the end of a frame.
	// Spectrum y-coordinate.
	ula_bitmap   [BytesPerLine*ScreenHeight] ula_byte_t

	// Screen attributes read by ULA, if they differ from data in memory at the end of a frame.
	// Linear y-coordinate.
	ula_attr     [BytesPerLine*ScreenHeight] ula_attr_t

	// Whether the 8x8 rectangular screen area was modified during the current frame
	dirtyScreen  [ScreenWidth_Attr*ScreenHeight_Attr] bool

	z80          *Z80
}

func NewMemory() *Memory {
	return &Memory{}
}

func (memory *Memory) readByteInternal(addr uint16) byte {
	return memory.data[addr]
}

func (memory *Memory) readByte(addr uint16) byte {
	memory.contend(addr, 3)
	return memory.readByteInternal(addr)
}

func (memory *Memory) writeByte(addr uint16, b byte) {
	memory.contend(addr, 3)
	memory.writeByteInternal(addr, b)
}

func (memory *Memory) writeByteInternal(address uint16, b byte) {
	if (address >= SCREEN_BASE_ADDR) && (address < ATTR_BASE_ADDR) {
		if memory.data[address] != b {
			memory.screenBitmapWrite(address)

			rel_addr := address-SCREEN_BASE_ADDR
			screenline_start_tstate := screenline_start_tstates[rel_addr >> BytesPerLine_log2]
			x, _ := screenAddr_to_xy(address)
			screen_tstate := screenline_start_tstate + uint(x >> PIXELS_PER_TSTATE_LOG2)
			if memory.z80.tstates > screen_tstate {
				// Remember the value read by ULA
				memory.ula_bitmap[rel_addr] = ula_byte_t{true, memory.data[address]}
			}
		}
	} else if (address >= ATTR_BASE_ADDR) && (address < 0x5b00) {
		memory.screenAttrWrite(address)

		attr_x := (address & 0x001f)
		attr_y := (address - ATTR_BASE_ADDR) / ScreenWidth_Attr

		x := uint(8*attr_x)
		y := uint(8*attr_y)
		for i:=0; i<8; i++ {
			screenline_start_tstate := FIRST_SCREEN_BYTE + y*TSTATES_PER_LINE
			screen_tstate := screenline_start_tstate + (x>>PIXELS_PER_TSTATE_LOG2)
			if memory.z80.tstates > screen_tstate {
				ofs := (y << BytesPerLine_log2) + uint(attr_x)
				ula_attr := &memory.ula_attr[ofs]
				if !ula_attr.valid || (screen_tstate > ula_attr.tstate) {
					*ula_attr = ula_attr_t{true, memory.data[address], memory.z80.tstates}
				}
			}
			y++
		}
	}

	memory.data[address] = b
}

func (memory *Memory) screenBitmapWrite(address uint16) {
	// address: [0 1 0 y7 y6 y2 y1 y0 / y5 y4 y3 x4 x3 x2 x1 x0]
	var attr_x = (address & 0x001f)
	var attr_y = ( ((address & 0x0700) >> 8) | ((address & 0x00e0) >> 2) | ((address & 0x1800) >> 5) ) / 8

	memory.dirtyScreen[attr_y*ScreenWidth_Attr + attr_x] = true
}

func (memory *Memory) screenAttrWrite(address uint16) {
	memory.dirtyScreen[address-ATTR_BASE_ADDR] = true
}

func (memory *Memory) getBorder() byte {
	return memory.borderColor
}

func (memory *Memory) setBorder(borderColor byte) {
	memory.borderColor = borderColor
}

// This function is called at the beginning of each frame
func (memory *Memory) frame_begin() {
	memory.frame++
	if memory.frame == 1 {
		// The very first frame --> repaint the whole screen
		for i:=0 ; i < ScreenWidth_Attr*ScreenHeight_Attr ; i++ {
			memory.dirtyScreen[i] = true
		}
	} else {
		for i:=0 ; i < ScreenWidth_Attr*ScreenHeight_Attr ; i++ {
			memory.dirtyScreen[i] = false
		}
	}

	ula_bitmap := &memory.ula_bitmap
	for ofs:=uint16(0) ; ofs < BytesPerLine*ScreenHeight ; ofs++ {
		if ula_bitmap[ofs].valid {
			memory.screenBitmapWrite(SCREEN_BASE_ADDR + ofs)
		}

		ula_bitmap[ofs].valid = false
	}

	ula_attr := &memory.ula_attr
	for ofs:=uint16(0) ; ofs < BytesPerLine*ScreenHeight ; ofs++ {
		if ula_attr[ofs].valid {
			linearY := (ofs >> BytesPerLine_log2)
			attr_y := (linearY >> 3)
			attr_x := (ofs & 0x001f)
			memory.screenAttrWrite(ATTR_BASE_ADDR + (attr_y << BytesPerLine_log2) + attr_x)
		}

		ula_attr[ofs].valid = false
	}
}

func (memory *Memory) sendScreenToDisplay(display DisplayChannel, borderEvents *BorderEvent) {
	var screen Screen
	{
		flash := (memory.frame & 0x10) != 0
		flash_previous := (memory.frame-1) & 0x10 != 0
		flash_diff := (flash != flash_previous)

		// Fill screen.bitmap & screen.attr, but only the dirty regions.
		memory_data := &memory.data
		memory_ulaBitmap := &memory.ula_bitmap
		memory_ulaAttr := &memory.ula_attr
		memory_dirtyScreen := memory.dirtyScreen
		screen_bitmap := &screen.bitmap
		screen_attr := &screen.attr
		for attr_y := uint(0); attr_y < ScreenHeight_Attr; attr_y++ {
			attr_y8 := 8*attr_y

			for attr_x := uint(0); attr_x < ScreenWidth_Attr; attr_x++ {
				attr_ofs := attr_y*ScreenWidth_Attr + attr_x

				// Make sure to send all changed flashing bytes to the DisplayChannel
				if flash_diff {
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						var attr byte
						if !memory_ulaAttr[linearY_ofs].valid {
							attr = memory_data[ATTR_BASE_ADDR + attr_ofs]
						} else {
							attr = memory_ulaAttr[linearY_ofs].value
						}

						if (attr & 0x80) != 0 {
							memory_dirtyScreen[attr_ofs] = true
							break;
						}

						linearY_ofs += BytesPerLine
					}
				}

				if !memory_dirtyScreen[attr_ofs] {
					continue
				}

				// screen.bitmap
				{
					screen_addr := xy_to_screenAddr(uint8(8*attr_x), uint8(attr_y8))
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						if !memory_ulaBitmap[screen_addr-SCREEN_BASE_ADDR].valid {
							screen_bitmap[linearY_ofs] = memory_data[screen_addr]
						} else {
							screen_bitmap[linearY_ofs] = memory_ulaBitmap[screen_addr-SCREEN_BASE_ADDR].value
						}

						screen_addr += 8*BytesPerLine
						linearY_ofs += BytesPerLine
					}
				}

				// screen.attr
				{
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						var attr byte
						if !memory_ulaAttr[linearY_ofs].valid {
							attr = memory_data[ATTR_BASE_ADDR + attr_ofs]
						} else {
							attr = memory_ulaAttr[linearY_ofs].value
						}

						ink := ((attr&0x40)>>3)|(attr&0x07)
						paper := (attr&0x78)>>3

						if flash && ((attr & 0x80) != 0) {
							/* invert flashing attributes */
							ink,paper = paper,ink
						}

						screen_attr[linearY_ofs] = attr_4bit((ink << 4) | paper)

						linearY_ofs += BytesPerLine
					}
				}
			}
		}

		// screen.dirty
		screen.dirty = memory.dirtyScreen

		// screen.border
		screen.border = memory.borderColor

		// screen.borderEvents
		if (borderEvents != nil) && (borderEvents.previous_orNil==nil) {
			// Only the one event which was added there at the start of the frame - ignore it
			screen.borderEvents = nil
		} else {
			screen.borderEvents = borderEvents
		}
	}

	display.getScreenChannel() <- &screen
}

func (memory *Memory) contend(address uint16, time uint) {
	tstates_p := &memory.z80.tstates

	if (address >= 0x4000) && (address <= 0x7fff) {
		*tstates_p += uint(delay_table[*tstates_p])
	}

	*tstates_p += time
}

func (memory *Memory) contendRead(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) contendReadNoMreq(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) contendWriteNoMreq(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) set(address uint16, value byte) {
	memory.data[address] = value
}

func (memory *Memory) At(address uint) byte {
	return memory.data[address]
}

func (memory *Memory) Data() []byte {
	return []byte(memory.Data())
}

// Number of T-states to delay, for each possible T-state within a frame.
// The array is extended at the end - this covers the case when the emulator
// begins to execute an instruction at Tstate=(TStatesPerFrame-1). Such an
// instruction will finish at (TStatesPerFrame-1+4) or later.
var delay_table [TStatesPerFrame+100]byte;

// Initialize 'delay_table' at program startup
func init() {
	// Note: The language automatically initialized all values
	//       of the 'delay_table' array to zeroes. So, we only
	//       have to modify the non-zero elements.

	tstate := FIRST_SCREEN_BYTE-1
	for y:=0; y<ScreenHeight; y++ {
		for x:=0; x<ScreenWidth; x+=16 {
			tstate_x := x/PIXELS_PER_TSTATE
			delay_table[tstate+tstate_x+0] = 6
			delay_table[tstate+tstate_x+1] = 5
			delay_table[tstate+tstate_x+2] = 4
			delay_table[tstate+tstate_x+3] = 3
			delay_table[tstate+tstate_x+4] = 2
			delay_table[tstate+tstate_x+5] = 1
		}
		tstate += TSTATES_PER_LINE
	}
}

<commit_msg>Fix flashing attributes.<commit_after>package spectrum

type MemoryAccessor interface {
	readByte(address uint16) byte
	readByteInternal(address uint16) byte

	writeByte(address uint16, value byte)
	writeByteInternal(address uint16, value byte)

	contendRead(addr uint16, time uint)
	contendReadNoMreq(addr uint16, time uint)

	contendWriteNoMreq(addr uint16, time uint)

	set(addr uint16, value byte)

	getBorder() byte
	setBorder(borderColor byte)

	frame_begin()
	sendScreenToDisplay(display DisplayChannel, borderEvents *BorderEvent)

	At(addr uint) byte
	Data() []byte
}

// The lower 4 bits define the paper, the higher 4 bits define the ink.
// Note that the paper is in the *lower* half.
// There is no flash bit.
type attr_4bit byte

type Screen struct {
	bitmap       [BytesPerLine*ScreenHeight] byte			// Linear y-coordinate
	attr         [BytesPerLine*ScreenHeight] attr_4bit		// Linear y-coordinate
	dirty        [ScreenWidth_Attr*ScreenHeight_Attr] bool	// The 8x8 rectangular region was modified, either the bitmap or the attr
	border       byte
	borderEvents *BorderEvent	// Might be nil
}

type ula_byte_t struct {
	valid bool
	value uint8
}

type ula_attr_t struct {
	valid bool
	value uint8
	tstate uint
}

type Memory struct {
	data         [0x10000]byte

	// Frame number
	frame        uint

	borderColor  byte

	// Screen bitmap data read by ULA, if they differ from data in memory at the end of a frame.
	// Spectrum y-coordinate.
	ula_bitmap   [BytesPerLine*ScreenHeight] ula_byte_t

	// Screen attributes read by ULA, if they differ from data in memory at the end of a frame.
	// Linear y-coordinate.
	ula_attr     [BytesPerLine*ScreenHeight] ula_attr_t

	// Whether the 8x8 rectangular screen area was modified during the current frame
	dirtyScreen  [ScreenWidth_Attr*ScreenHeight_Attr] bool

	z80          *Z80
}

func NewMemory() *Memory {
	return &Memory{}
}

func (memory *Memory) readByteInternal(addr uint16) byte {
	return memory.data[addr]
}

func (memory *Memory) readByte(addr uint16) byte {
	memory.contend(addr, 3)
	return memory.readByteInternal(addr)
}

func (memory *Memory) writeByte(addr uint16, b byte) {
	memory.contend(addr, 3)
	memory.writeByteInternal(addr, b)
}

func (memory *Memory) writeByteInternal(address uint16, b byte) {
	if (address >= SCREEN_BASE_ADDR) && (address < ATTR_BASE_ADDR) {
		if memory.data[address] != b {
			memory.screenBitmapWrite(address)

			rel_addr := address-SCREEN_BASE_ADDR
			screenline_start_tstate := screenline_start_tstates[rel_addr >> BytesPerLine_log2]
			x, _ := screenAddr_to_xy(address)
			screen_tstate := screenline_start_tstate + uint(x >> PIXELS_PER_TSTATE_LOG2)
			if memory.z80.tstates > screen_tstate {
				// Remember the value read by ULA
				memory.ula_bitmap[rel_addr] = ula_byte_t{true, memory.data[address]}
			}
		}
	} else if (address >= ATTR_BASE_ADDR) && (address < 0x5b00) {
		memory.screenAttrWrite(address)

		attr_x := (address & 0x001f)
		attr_y := (address - ATTR_BASE_ADDR) / ScreenWidth_Attr

		x := uint(8*attr_x)
		y := uint(8*attr_y)
		for i:=0; i<8; i++ {
			screenline_start_tstate := FIRST_SCREEN_BYTE + y*TSTATES_PER_LINE
			screen_tstate := screenline_start_tstate + (x>>PIXELS_PER_TSTATE_LOG2)
			if memory.z80.tstates > screen_tstate {
				ofs := (y << BytesPerLine_log2) + uint(attr_x)
				ula_attr := &memory.ula_attr[ofs]
				if !ula_attr.valid || (screen_tstate > ula_attr.tstate) {
					*ula_attr = ula_attr_t{true, memory.data[address], memory.z80.tstates}
				}
			}
			y++
		}
	}

	memory.data[address] = b
}

func (memory *Memory) screenBitmapWrite(address uint16) {
	// address: [0 1 0 y7 y6 y2 y1 y0 / y5 y4 y3 x4 x3 x2 x1 x0]
	var attr_x = (address & 0x001f)
	var attr_y = ( ((address & 0x0700) >> 8) | ((address & 0x00e0) >> 2) | ((address & 0x1800) >> 5) ) / 8

	memory.dirtyScreen[attr_y*ScreenWidth_Attr + attr_x] = true
}

func (memory *Memory) screenAttrWrite(address uint16) {
	memory.dirtyScreen[address-ATTR_BASE_ADDR] = true
}

func (memory *Memory) getBorder() byte {
	return memory.borderColor
}

func (memory *Memory) setBorder(borderColor byte) {
	memory.borderColor = borderColor
}

// This function is called at the beginning of each frame
func (memory *Memory) frame_begin() {
	memory.frame++
	if memory.frame == 1 {
		// The very first frame --> repaint the whole screen
		for i:=0 ; i < ScreenWidth_Attr*ScreenHeight_Attr ; i++ {
			memory.dirtyScreen[i] = true
		}
	} else {
		for i:=0 ; i < ScreenWidth_Attr*ScreenHeight_Attr ; i++ {
			memory.dirtyScreen[i] = false
		}
	}

	ula_bitmap := &memory.ula_bitmap
	for ofs:=uint16(0) ; ofs < BytesPerLine*ScreenHeight ; ofs++ {
		if ula_bitmap[ofs].valid {
			memory.screenBitmapWrite(SCREEN_BASE_ADDR + ofs)
		}

		ula_bitmap[ofs].valid = false
	}

	ula_attr := &memory.ula_attr
	for ofs:=uint16(0) ; ofs < BytesPerLine*ScreenHeight ; ofs++ {
		if ula_attr[ofs].valid {
			linearY := (ofs >> BytesPerLine_log2)
			attr_y := (linearY >> 3)
			attr_x := (ofs & 0x001f)
			memory.screenAttrWrite(ATTR_BASE_ADDR + (attr_y << BytesPerLine_log2) + attr_x)
		}

		ula_attr[ofs].valid = false
	}
}

func (memory *Memory) sendScreenToDisplay(display DisplayChannel, borderEvents *BorderEvent) {
	var screen Screen
	{
		flash := (memory.frame & 0x10) != 0
		flash_previous := ((memory.frame-1) & 0x10) != 0
		flash_diff := (flash != flash_previous)

		// Fill screen.bitmap & screen.attr, but only the dirty regions.
		memory_data := &memory.data
		memory_ulaBitmap := &memory.ula_bitmap
		memory_ulaAttr := &memory.ula_attr
		memory_dirtyScreen := &memory.dirtyScreen
		screen_bitmap := &screen.bitmap
		screen_attr := &screen.attr
		for attr_y := uint(0); attr_y < ScreenHeight_Attr; attr_y++ {
			attr_y8 := 8*attr_y

			for attr_x := uint(0); attr_x < ScreenWidth_Attr; attr_x++ {
				attr_ofs := attr_y*ScreenWidth_Attr + attr_x

				// Make sure to send all changed flashing bytes to the DisplayChannel
				if flash_diff {
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						var attr byte
						if !memory_ulaAttr[linearY_ofs].valid {
							attr = memory_data[ATTR_BASE_ADDR + attr_ofs]
						} else {
							attr = memory_ulaAttr[linearY_ofs].value
						}

						if (attr & 0x80) != 0 {
							memory_dirtyScreen[attr_ofs] = true
							break
						}

						linearY_ofs += BytesPerLine
					}
				}

				if !memory_dirtyScreen[attr_ofs] {
					continue
				}

				// screen.bitmap
				{
					screen_addr := xy_to_screenAddr(uint8(8*attr_x), uint8(attr_y8))
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						if !memory_ulaBitmap[screen_addr-SCREEN_BASE_ADDR].valid {
							screen_bitmap[linearY_ofs] = memory_data[screen_addr]
						} else {
							screen_bitmap[linearY_ofs] = memory_ulaBitmap[screen_addr-SCREEN_BASE_ADDR].value
						}

						screen_addr += 8*BytesPerLine
						linearY_ofs += BytesPerLine
					}
				}

				// screen.attr
				{
					linearY_ofs := (attr_y8 << BytesPerLine_log2) + attr_x

					for y := 0; y < 8; y++ {
						var attr byte
						if !memory_ulaAttr[linearY_ofs].valid {
							attr = memory_data[ATTR_BASE_ADDR + attr_ofs]
						} else {
							attr = memory_ulaAttr[linearY_ofs].value
						}

						ink := ((attr&0x40)>>3)|(attr&0x07)
						paper := (attr&0x78)>>3

						if flash && ((attr & 0x80) != 0) {
							/* invert flashing attributes */
							ink,paper = paper,ink
						}

						screen_attr[linearY_ofs] = attr_4bit((ink << 4) | paper)

						linearY_ofs += BytesPerLine
					}
				}
			}
		}

		// screen.dirty
		screen.dirty = memory.dirtyScreen

		// screen.border
		screen.border = memory.borderColor

		// screen.borderEvents
		if (borderEvents != nil) && (borderEvents.previous_orNil==nil) {
			// Only the one event which was added there at the start of the frame - ignore it
			screen.borderEvents = nil
		} else {
			screen.borderEvents = borderEvents
		}
	}

	display.getScreenChannel() <- &screen
}

func (memory *Memory) contend(address uint16, time uint) {
	tstates_p := &memory.z80.tstates

	if (address >= 0x4000) && (address <= 0x7fff) {
		*tstates_p += uint(delay_table[*tstates_p])
	}

	*tstates_p += time
}

func (memory *Memory) contendRead(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) contendReadNoMreq(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) contendWriteNoMreq(address uint16, time uint) {
	memory.contend(address, time)
}

func (memory *Memory) set(address uint16, value byte) {
	memory.data[address] = value
}

func (memory *Memory) At(address uint) byte {
	return memory.data[address]
}

func (memory *Memory) Data() []byte {
	return []byte(memory.Data())
}

// Number of T-states to delay, for each possible T-state within a frame.
// The array is extended at the end - this covers the case when the emulator
// begins to execute an instruction at Tstate=(TStatesPerFrame-1). Such an
// instruction will finish at (TStatesPerFrame-1+4) or later.
var delay_table [TStatesPerFrame+100]byte;

// Initialize 'delay_table' at program startup
func init() {
	// Note: The language automatically initialized all values
	//       of the 'delay_table' array to zeroes. So, we only
	//       have to modify the non-zero elements.

	tstate := FIRST_SCREEN_BYTE-1
	for y:=0; y<ScreenHeight; y++ {
		for x:=0; x<ScreenWidth; x+=16 {
			tstate_x := x/PIXELS_PER_TSTATE
			delay_table[tstate+tstate_x+0] = 6
			delay_table[tstate+tstate_x+1] = 5
			delay_table[tstate+tstate_x+2] = 4
			delay_table[tstate+tstate_x+3] = 3
			delay_table[tstate+tstate_x+4] = 2
			delay_table[tstate+tstate_x+5] = 1
		}
		tstate += TSTATES_PER_LINE
	}
}

<|endoftext|>


<commit_before>/*
 * A name server which sends back the IP address of its client, the
 * recursive resolver. When queried for type TXT, it sends back the text
 * form of the address.  When queried for type A (resp. AAAA), it sends
 * back the IPv4 (resp. v6) address.
 *
 * Similar services: whoami.ultradns.net, whoami.akamai.net. Also (but it
 * is not their normal goal): rs.dns-oarc.net, porttest.dns-oarc.net,
 * amiopen.openresolvers.org.
 *
 * Stephane Bortzmeyer <stephane+grong@bortzmeyer.org>
 *
 * Adapted to Go DNS (i.e. completely rewritten)
 * Miek Gieben <miek@miek.nl>
 */

package main

import (
	"os"
	"net"
	"dns"
	"fmt"
	"os/signal"
	"strconv"
)

func reply(c *dns.Conn, in *dns.Msg) []byte {
	m := new(dns.Msg)
	m.SetReply(in.MsgHdr.Id)

	m.Question = make([]dns.Question, 1)
	m.Answer = make([]dns.RR, 1)
	m.Extra = make([]dns.RR, 1)

	m.Question[0] = in.Question[0]

        var ad net.IP
        if c.UDP != nil {
                ad = c.Addr.(*net.UDPAddr).IP
        } else {
                ad = c.Addr.(*net.TCPAddr).IP
        }
        if ad.To4() != nil {
                r := new(dns.RR_A)
                r.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
                if c.UDP != nil {
                        r.A = c.Addr.(*net.UDPAddr).IP
                } else {
                        r.A = c.Addr.(*net.TCPAddr).IP
                }
                m.Answer[0] = r
        } else {
                r := new(dns.RR_AAAA)
                r.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
                if c.UDP != nil {
                        r.AAAA = c.Addr.(*net.UDPAddr).IP
                } else {
                        r.AAAA = c.Addr.(*net.TCPAddr).IP
                }
                m.Answer[0] = r
        }

	t := new(dns.RR_TXT)
	t.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0}
	if c.TCP != nil {
		t.Txt = "Port: " + strconv.Itoa(c.Port) + " (tcp)"
	} else {
		t.Txt = "Port: " + strconv.Itoa(c.Port) + " (udp)"
	}
	m.Extra[0] = t

	b, _ := m.Pack()
        return b
}

func handle(c *dns.Conn, in *dns.Msg) {
	if in.MsgHdr.Response == true {
		return      // We don't do responses
	}
	answer := reply(c, in)
	c.Write(answer)
}

func tcp(addr string, e chan os.Error) {
	err := dns.ListenAndServeTCP(addr, handle)
	e <- err
	return
}

func udp(addr string, e chan os.Error) {
        err := dns.ListenAndServeUDP(addr, handle)
	e <- err
	return
}

func main() {
	e := make(chan os.Error)
	go udp("127.0.0.1:8053", e)
	go udp("[::1]:8053", e)
	go tcp("127.0.0.1:8053", e)
	go tcp("[::1]:8053", e)

forever:
	for {
		// Wait for a signal to stop
		select {
		case err := <-e:
			fmt.Printf("Error received, stopping: %s\n", err.String())
			break forever
		case <-signal.Incoming:
			fmt.Printf("Signal received, stopping\n")
			break forever
		}
	}
	close(e)
}
<commit_msg>Fix reflect<commit_after>/*
 * A name server which sends back the IP address of its client, the
 * recursive resolver. When queried for type TXT, it sends back the text
 * form of the address.  When queried for type A (resp. AAAA), it sends
 * back the IPv4 (resp. v6) address.
 *
 * Similar services: whoami.ultradns.net, whoami.akamai.net. Also (but it
 * is not their normal goal): rs.dns-oarc.net, porttest.dns-oarc.net,
 * amiopen.openresolvers.org.
 *
 * Stephane Bortzmeyer <stephane+grong@bortzmeyer.org>
 *
 * Adapted to Go DNS (i.e. completely rewritten)
 * Miek Gieben <miek@miek.nl>
 */

package main

import (
	"os"
	"net"
	"dns"
	"fmt"
	"os/signal"
	"strconv"
)

func reply(c *dns.Conn, in *dns.Msg) []byte {
	m := new(dns.Msg)
	m.SetReply(in.MsgHdr.Id)

	m.Question = make([]dns.Question, 1)
	m.Answer = make([]dns.RR, 1)
	m.Extra = make([]dns.RR, 1)

        // Copy the question.
	m.Question[0] = in.Question[0]

        // Some foo to check if we are called trough ip6 or ip4.
        // We add the correct reply RR.
        var ad net.IP
        if c.UDP != nil {
                ad = c.Addr.(*net.UDPAddr).IP
        } else {
                ad = c.Addr.(*net.TCPAddr).IP
        }

        if ad.To4() != nil {
                r := new(dns.RR_A)
                r.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
                r.A = ad
                m.Answer[0] = r
        } else {
                r := new(dns.RR_AAAA)
                r.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: 0}
                r.AAAA = ad
                m.Answer[0] = r
        }

	t := new(dns.RR_TXT)
	t.Hdr = dns.RR_Header{Name: "whoami.miek.nl.", Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0}
	if c.TCP != nil {
		t.Txt = "Port: " + strconv.Itoa(c.Port) + " (tcp)"
	} else {
		t.Txt = "Port: " + strconv.Itoa(c.Port) + " (udp)"
	}
	m.Extra[0] = t

	b, _ := m.Pack()
        return b
}

func handle(c *dns.Conn, in *dns.Msg) {
	if in.MsgHdr.Response == true {
		return      // We don't do responses
	}
	answer := reply(c, in)
	c.Write(answer)
}

func tcp(addr string, e chan os.Error) {
	err := dns.ListenAndServeTCP(addr, handle)
	e <- err
	return
}

func udp(addr string, e chan os.Error) {
        err := dns.ListenAndServeUDP(addr, handle)
	e <- err
	return
}

func main() {
	e := make(chan os.Error)
	go udp("127.0.0.1:8053", e)
	go udp("[::1]:8053", e)
	go tcp("127.0.0.1:8053", e)
	go tcp("[::1]:8053", e)

forever:
	for {
		// Wait for a signal to stop
		select {
		case err := <-e:
			fmt.Printf("Error received, stopping: %s\n", err.String())
			break forever
		case <-signal.Incoming:
			fmt.Printf("Signal received, stopping\n")
			break forever
		}
	}
	close(e)
}
<|endoftext|>