<commit_before>// +build pg full

package mithril

import (
	"database/sql"
	"flag"
	"fmt"

	"github.com/lib/pq"
)

var (
	enablePgFlag = flag.Bool("pg", false, "Enable PostgreSQL handler")
	pgUriFlag    = flag.String("pg.uri",
		"postgres://localhost?sslmode=disable", "PostgreSQL Server URI")

	dbIsNil      = fmt.Errorf("PostgreSQL handler database is nil!")
	pgMigrations = map[string][]string{
		"20120505000000": {`
			CREATE TABLE IF NOT EXISTS mithril_requests (
				id serial PRIMARY KEY,
				message_id character varying(128) NOT NULL,
				created_at timestamp without time zone NOT NULL,
				app_id character varying(128) NOT NULL,
				content_type character varying(64) NOT NULL,
				exchange character varying(256) NOT NULL,
				routing_key character varying(256) NOT NULL,
				mandatory boolean NOT NULL,
				immediate boolean NOT NULL,
				body_bytes text NOT NULL
			);
		`,
			`CREATE INDEX mithril_app_ids ON mithril_requests (app_id);`,
			`CREATE INDEX mithril_exchanges ON mithril_requests (exchange);`,
			`CREATE INDEX mithril_routing_keys ON mithril_requests (routing_key);`,
		},
	}
)

func init() {
	pipelineCallbacks["pg"] = func(pipeline Handler) Handler {
		if *enablePgFlag {
			Debugln("  --> pg enabled, so adding postgresql handler")
			pipeline = NewPostgreSQLHandler(*pgUriFlag, pipeline)
		} else {
			Debugln("  --> pg not enabled, so leaving pipeline unaltered")
		}
		return pipeline
	}
}

type PostgreSQLHandler struct {
	connUri     string
	db          *sql.DB
	nextHandler Handler
}

func NewPostgreSQLHandler(connUri string, next Handler) *PostgreSQLHandler {
	pgHandler := &PostgreSQLHandler{connUri: connUri}
	pgHandler.SetNextHandler(next)
	return pgHandler
}

func (me *PostgreSQLHandler) SetNextHandler(handler Handler) {
	me.nextHandler = handler
}

func (me *PostgreSQLHandler) Init() error {
	var err error

	if err = me.ensureConnected(); err != nil {
		return err
	}

	if err = me.ensureSchemaPresent(); err != nil {
		return err
	}

	Debugln("PostgreSQL handler initialized")

	if me.nextHandler != nil {
		return me.nextHandler.Init()
	}

	return nil
}

func (me *PostgreSQLHandler) HandleRequest(req *FancyRequest) error {
	if err := me.insertRequest(req); err != nil {
		return err
	}

	if me.nextHandler != nil {
		return me.nextHandler.HandleRequest(req)
	}

	return nil
}

func (me *PostgreSQLHandler) insertRequest(req *FancyRequest) error {
	if me.db == nil {
		return dbIsNil
	}

	r, err := me.db.Exec(`
		INSERT INTO mithril_requests (
			message_id,
			created_at,
			app_id,
			content_type,
			exchange,
			routing_key,
			mandatory,
			immediate,
			body_bytes
		)
		VALUES (
			$1, $2, $3, $4, $5, $6, $7, $8, $9
		)`,
		req.MessageId,
		req.Timestamp,
		req.AppId,
		req.ContentType,
		req.Exchange,
		req.RoutingKey,
		req.Mandatory,
		req.Immediate,
		req.BodyBytes,
	)

	Debugf("Insert returned result=%+v, err=%+v\n", r, err)
	return err
}

func (me *PostgreSQLHandler) ensureConnected() error {
	if me.isConnected() {
		return nil
	}

	return me.establishConnection()
}

func (me *PostgreSQLHandler) isConnected() bool {
	if me.db == nil {
		return false
	}

	if me.selectNow() != nil {
		return false
	}

	return true
}

func (me *PostgreSQLHandler) selectNow() error {
	_, err := me.db.Exec(`SELECT now() "mithril ping test";`)

	if err != nil {
		Debugln("PostgreSQL failed to execute 'SELECT now()':", err)
		Debugln("Is PostgreSQL running?")
	}

	return err
}

func (me *PostgreSQLHandler) establishConnection() error {
	var (
		connStr string
		err     error
		db      *sql.DB
	)

	if connStr, err = pq.ParseURL(me.connUri); err != nil {
		return err
	}

	if db, err = sql.Open("postgres", connStr); err != nil {
		return err
	}

	me.db = db
	return me.selectNow()
}

func (me *PostgreSQLHandler) ensureSchemaPresent() error {
	if me.db == nil {
		return dbIsNil
	}

	ensurer := newPgSchemaEnsurer(me.db, "mithril_schema_migrations")
	if err := ensurer.Init(); err != nil {
		return err
	}

	return ensurer.Migrate(pgMigrations)
}
<commit_msg>Adding correlation_id to mithril_requests table<commit_after>// +build pg full

package mithril

import (
	"database/sql"
	"flag"
	"fmt"

	"github.com/lib/pq"
)

var (
	enablePgFlag = flag.Bool("pg", false, "Enable PostgreSQL handler")
	pgUriFlag    = flag.String("pg.uri",
		"postgres://localhost?sslmode=disable", "PostgreSQL Server URI")

	dbIsNil      = fmt.Errorf("PostgreSQL handler database is nil!")
	pgMigrations = map[string][]string{
		"20120505000000": {`
			CREATE TABLE IF NOT EXISTS mithril_requests (
				id serial PRIMARY KEY,
				message_id character varying(128) NOT NULL,
				correlation_id character varying(128) NOT NULL,
				created_at timestamp without time zone NOT NULL,
				app_id character varying(128) NOT NULL,
				content_type character varying(64) NOT NULL,
				exchange character varying(256) NOT NULL,
				routing_key character varying(256) NOT NULL,
				mandatory boolean NOT NULL,
				immediate boolean NOT NULL,
				body_bytes text NOT NULL
			);
		`,
			`CREATE INDEX mithril_app_ids ON mithril_requests (app_id);`,
			`CREATE INDEX mithril_exchanges ON mithril_requests (exchange);`,
			`CREATE INDEX mithril_routing_keys ON mithril_requests (routing_key);`,
		},
	}
)

func init() {
	pipelineCallbacks["pg"] = func(pipeline Handler) Handler {
		if *enablePgFlag {
			Debugln("  --> pg enabled, so adding postgresql handler")
			pipeline = NewPostgreSQLHandler(*pgUriFlag, pipeline)
		} else {
			Debugln("  --> pg not enabled, so leaving pipeline unaltered")
		}
		return pipeline
	}
}

type PostgreSQLHandler struct {
	connUri     string
	db          *sql.DB
	nextHandler Handler
}

func NewPostgreSQLHandler(connUri string, next Handler) *PostgreSQLHandler {
	pgHandler := &PostgreSQLHandler{connUri: connUri}
	pgHandler.SetNextHandler(next)
	return pgHandler
}

func (me *PostgreSQLHandler) SetNextHandler(handler Handler) {
	me.nextHandler = handler
}

func (me *PostgreSQLHandler) Init() error {
	var err error

	if err = me.ensureConnected(); err != nil {
		return err
	}

	if err = me.ensureSchemaPresent(); err != nil {
		return err
	}

	Debugln("PostgreSQL handler initialized")

	if me.nextHandler != nil {
		return me.nextHandler.Init()
	}

	return nil
}

func (me *PostgreSQLHandler) HandleRequest(req *FancyRequest) error {
	if err := me.insertRequest(req); err != nil {
		return err
	}

	if me.nextHandler != nil {
		return me.nextHandler.HandleRequest(req)
	}

	return nil
}

func (me *PostgreSQLHandler) insertRequest(req *FancyRequest) error {
	if me.db == nil {
		return dbIsNil
	}

	r, err := me.db.Exec(`
		INSERT INTO mithril_requests (
			message_id,
			correlation_id,
			created_at,
			app_id,
			content_type,
			exchange,
			routing_key,
			mandatory,
			immediate,
			body_bytes
		)
		VALUES (
			$1, $2, $3, $4, $5, $6, $7, $8, $9, $10
		)`,
		req.MessageId,
		req.CorrelationId,
		req.Timestamp,
		req.AppId,
		req.ContentType,
		req.Exchange,
		req.RoutingKey,
		req.Mandatory,
		req.Immediate,
		req.BodyBytes,
	)

	Debugf("Insert returned result=%+v, err=%+v\n", r, err)
	return err
}

func (me *PostgreSQLHandler) ensureConnected() error {
	if me.isConnected() {
		return nil
	}

	return me.establishConnection()
}

func (me *PostgreSQLHandler) isConnected() bool {
	if me.db == nil {
		return false
	}

	if me.selectNow() != nil {
		return false
	}

	return true
}

func (me *PostgreSQLHandler) selectNow() error {
	_, err := me.db.Exec(`SELECT now() "mithril ping test";`)

	if err != nil {
		Debugln("PostgreSQL failed to execute 'SELECT now()':", err)
		Debugln("Is PostgreSQL running?")
	}

	return err
}

func (me *PostgreSQLHandler) establishConnection() error {
	var (
		connStr string
		err     error
		db      *sql.DB
	)

	if connStr, err = pq.ParseURL(me.connUri); err != nil {
		return err
	}

	if db, err = sql.Open("postgres", connStr); err != nil {
		return err
	}

	me.db = db
	return me.selectNow()
}

func (me *PostgreSQLHandler) ensureSchemaPresent() error {
	if me.db == nil {
		return dbIsNil
	}

	ensurer := newPgSchemaEnsurer(me.db, "mithril_schema_migrations")
	if err := ensurer.Init(); err != nil {
		return err
	}

	return ensurer.Migrate(pgMigrations)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"runtime"

	rspecs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/specerror"
	"github.com/opencontainers/runtime-tools/validation/util"
)

func main() {
	if "linux" != runtime.GOOS {
		util.Skip("linux-specific process.capabilities test", map[string]string{"OS": runtime.GOOS})
		os.Exit(0)
	}

	g, err := util.GetDefaultGenerator()
	if err != nil {
		util.Fatal(err)
	}
	g.AddProcessCapabilityBounding("CAP_TEST")
	err = util.RuntimeInsideValidate(g, nil, nil)
	if err == nil {
		util.Fatal(specerror.NewError(specerror.LinuxProcCapError, fmt.Errorf("Any value which cannot be mapped to a relevant kernel interface MUST cause an error"), rspecs.Version))
	}
}
<commit_msg>capabilities: correctly add not existing capability<commit_after>package main

import (
	"fmt"
	"os"
	"runtime"

	rspecs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/specerror"
	"github.com/opencontainers/runtime-tools/validation/util"
)

func main() {
	if "linux" != runtime.GOOS {
		util.Skip("linux-specific process.capabilities test", map[string]string{"OS": runtime.GOOS})
		os.Exit(0)
	}

	g, err := util.GetDefaultGenerator()
	if err != nil {
		util.Fatal(err)
	}
	g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, "CAP_TEST")
	err = util.RuntimeInsideValidate(g, nil, nil)
	if err == nil {
		util.Fatal(specerror.NewError(specerror.LinuxProcCapError, fmt.Errorf("Any value which cannot be mapped to a relevant kernel interface MUST cause an error"), rspecs.Version))
	}
}
<|endoftext|>


<commit_before>// csvsplit: Split a .csv file into multiple files.

package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

var records = flag.Int("r", 0, "The number of records per file")
var input = flag.String("i", "", "Filename of the input file to split")
var output = flag.String("o", "", "filename / path of the file output (optional)")

func main() {
	flag.Parse()
	if *input == "" || *records < 1 {
		flag.Usage()
		log.Fatal()
	}

	csvFile, err := os.Open(*input)
	if err != nil {
		log.Fatal(err)
	}
	defer csvFile.Close()

	reader := csv.NewReader(csvFile)
	recordsToWrite := make([][]string, 0)
	fileCount := 1
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		recordsToWrite = append(recordsToWrite, record)
		if len(recordsToWrite) == *records {
			saveCSVFile(recordsToWrite, fileCount)
			recordsToWrite = make([][]string, 0)
			fileCount += 1
		}
	}
	if len(recordsToWrite) > 0 {
		saveCSVFile(recordsToWrite, fileCount)
	}
}

func saveCSVFile(r [][]string, fileCount int) {
	fileName := fmt.Sprintf("%v%03d%v", *output, fileCount, ".csv")
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		f, err := os.Create(fileName)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		writer := csv.NewWriter(f)
		writer.WriteAll(r)
	} else {
		log.Fatal("File exists: ", fileName)
	}
}
<commit_msg>Use os.Exit()<commit_after>// csvsplit: Split a .csv file into multiple files.

package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

var records = flag.Int("r", 0, "The number of records per file")
var input = flag.String("i", "", "Filename of the input file to split")
var output = flag.String("o", "", "filename / path of the file output (optional)")

func main() {
	flag.Parse()
	if *input == "" || *records < 1 {
		flag.Usage()
		os.Exit(1)
	}

	csvFile, err := os.Open(*input)
	if err != nil {
		log.Fatal(err)
	}
	defer csvFile.Close()

	reader := csv.NewReader(csvFile)
	recordsToWrite := make([][]string, 0)
	fileCount := 1
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		recordsToWrite = append(recordsToWrite, record)
		if len(recordsToWrite) == *records {
			saveCSVFile(recordsToWrite, fileCount)
			recordsToWrite = make([][]string, 0)
			fileCount += 1
		}
	}
	if len(recordsToWrite) > 0 {
		saveCSVFile(recordsToWrite, fileCount)
	}
}

func saveCSVFile(r [][]string, fileCount int) {
	fileName := fmt.Sprintf("%v%03d%v", *output, fileCount, ".csv")
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		f, err := os.Create(fileName)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		writer := csv.NewWriter(f)
		writer.WriteAll(r)
	} else {
		log.Fatal("File exists: ", fileName)
	}
}
<|endoftext|>


<commit_before>// csvsplit: Split a .csv into multiple files.
package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

var (
	flagRecords = flag.Int("records", 0, "The number of records per file")
	flagInput = flag.String("input", "", "Filename of the input file to split (if blank, uses stdin)")
	flagOutput = flag.String("output", "", "filename / path of the file output (optional)")
	flagHeaders = flag.Int("headers", 0, "Number of header lines in the input file (will be repeated in each output file")
)

func main() {
	flag.Parse()
	if *flagRecords < 1 || *flagHeaders < 0 || *flagHeaders >= *flagRecords {
		flag.Usage()
		os.Exit(1)
	}

	var reader *csv.Reader
	if *flagInput != "" {
		inputFile, err := os.Open(*flagInput)
		if err != nil {
			log.Fatal(err)
		}
		defer inputFile.Close()
		reader = csv.NewReader(inputFile)
	} else {
		// Get input from stdin
		reader = csv.NewReader(os.Stdin)
	}

	records := make([][]string, 0)
	fileCount := 1
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		records = append(records, record)
		if len(records) == *flagRecords {
			saveCSVFile(records, fileCount)
			records = records[:*flagHeaders]
			fileCount += 1
		}
	}
	if len(records) > 0 {
		saveCSVFile(records, fileCount)
	}
}

func saveCSVFile(r [][]string, fileCount int) {
	fileName := fmt.Sprintf("%v%03d%v", *flagOutput, fileCount, ".csv")
	if _, err := os.Stat(fileName); err == nil {
		log.Fatal("File exists: ", fileName)
	}
	f, err := os.Create(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	writer := csv.NewWriter(f)
	writer.WriteAll(r)
}
<commit_msg>Helpful comments and whitespace<commit_after>// csvsplit: Split a .csv into multiple files.
package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

var (
	flagRecords = flag.Int("records", 0, "The number of records per file")
	flagInput = flag.String("input", "", "Filename of the input file to split (if blank, uses stdin)")
	flagOutput = flag.String("output", "", "filename / path of the file output (optional)")
	flagHeaders = flag.Int("headers", 0, "Number of header lines in the input file (will be repeated in each output file")
)

func main() {
	flag.Parse()

	// Sanity check flags
	if *flagRecords < 1 || *flagHeaders < 0 || *flagHeaders >= *flagRecords {
		flag.Usage()
		os.Exit(1)
	}

	// Get input from a given file or stdin
	var reader *csv.Reader
	if *flagInput != "" {
		inputFile, err := os.Open(*flagInput)
		if err != nil {
			log.Fatal(err)
		}
		defer inputFile.Close()
		reader = csv.NewReader(inputFile)
	} else {
		reader = csv.NewReader(os.Stdin)
	}

	records := make([][]string, 0)
	fileCount := 1
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}

		records = append(records, record)
		if len(records) == *flagRecords {
			saveCSVFile(records, fileCount)
			// Reset records to include just the header lines (if any)
			records = records[:*flagHeaders]
			fileCount += 1
		}
	}
	if len(records) > 0 {
		saveCSVFile(records, fileCount)
	}
}

func saveCSVFile(r [][]string, fileCount int) {
	fileName := fmt.Sprintf("%v%03d%v", *flagOutput, fileCount, ".csv")

	// Make sure we don't overwrite existing files
	if _, err := os.Stat(fileName); err == nil {
		log.Fatal("File exists: ", fileName)
	}

	f, err := os.Create(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	writer := csv.NewWriter(f)
	writer.WriteAll(r)
}
<|endoftext|>


<commit_before>package main

import (
	"os"
	"bytes"
	"io"
	"io/ioutil"
	"crypto/cipher"
	"crypto/aes"
	"crypto/rand"
	"golang.org/x/crypto/pbkdf2"
	"fmt"
	"crypto/sha1"
)

func main() {

	fmt.Println("Encrypting")
	encrypt()

	fmt.Println("Decrypting")
	decrypt()

}

func encrypt() {
	plaintext, err := ioutil.ReadFile("teste.txt")

	if err != nil {
		panic(err.Error())
	}

	key := []byte("teste123")
	salt := []byte("salt")

	dk := pbkdf2.Key(key, salt, 4096, 32, sha1.New)

	block, err := aes.NewCipher(dk)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	// It's important to remember that ciphertexts must be authenticated
	// (i.e. by using crypto/hmac) as well as being encrypted in order to
	// be secure. @todo

	// create a new file for saving the encrypted data.
	f, err := os.Create("teste.enc")
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(ciphertext))
	if err != nil {
		panic(err.Error())
	}
}

func decrypt() {
	ciphertext, err := ioutil.ReadFile("teste.enc")

	if err != nil {
		panic(err.Error())
	}

	key := []byte("teste123")
	salt := []byte("salt")

	dk := pbkdf2.Key(key, salt, 4096, 32, sha1.New)

	block, err := aes.NewCipher(dk)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	if len(ciphertext) < aes.BlockSize {
		panic("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(ciphertext, ciphertext)

	// create a new file for saving the encrypted data.
	f, err := os.Create("teste.dec")
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(ciphertext))
	if err != nil {
		panic(err.Error())
	}
}<commit_msg>Encrypting and decrypting function<commit_after>package main

import (
	"os"
	"bytes"
	"io"
	"io/ioutil"
	"crypto/cipher"
	"crypto/aes"
	"crypto/rand"
	"golang.org/x/crypto/pbkdf2"
	"fmt"
	"crypto/sha1"
)

func main() {

	fmt.Println("Encrypting")
	encrypt()

	fmt.Println("Decrypting")
	decrypt()

}

func encrypt() {

	if _, err := os.Stat("teste.txt"); os.IsNotExist(err) {
		panic("File not found")
	}

	plaintext, err := ioutil.ReadFile("teste.txt")

	if err != nil {
		panic(err.Error())
	}

	key := []byte("teste123")
	salt := []byte("salt")

	dk := pbkdf2.Key(key, salt, 4096, 32, sha1.New)

	block, err := aes.NewCipher(dk)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	// It's important to remember that ciphertexts must be authenticated
	// (i.e. by using crypto/hmac) as well as being encrypted in order to
	// be secure. @todo

	// create a new file for saving the encrypted data.
	f, err := os.Create("teste.enc")
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(ciphertext))
	if err != nil {
		panic(err.Error())
	}
}

func decrypt() {
	ciphertext, err := ioutil.ReadFile("teste.enc")

	if err != nil {
		panic(err.Error())
	}

	key := []byte("teste123")
	salt := []byte("salt")

	dk := pbkdf2.Key(key, salt, 4096, 32, sha1.New)

	block, err := aes.NewCipher(dk)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	if len(ciphertext) < aes.BlockSize {
		panic("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(ciphertext, ciphertext)

	// create a new file for saving the encrypted data.
	f, err := os.Create("teste.dec")
	if err != nil {
		panic(err.Error())
	}
	_, err = io.Copy(f, bytes.NewReader(ciphertext))
	if err != nil {
		panic(err.Error())
	}
}<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"encoding/json"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/util"
)

type Chaincode struct { }

type ChaincodeFunctions struct {
	stub shim.ChaincodeStubInterface
}

func main() {
	err := shim.Start(new(Chaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

func (t Chaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	_ = stub.PutState("deals", []byte("[]"))
	return nil, nil
}

func (t Chaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "registerDeal" {
		deploymentId := args[0]
		issuer := args[1]
		return fns.RegisterDeal(deploymentId, issuer)
	}
	return nil, errors.New("Received unknown function invocation: " + function)
}

func (t Chaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "ping" {
		return fns.Ping()
	} else if function == "getDeals" {
		return fns.GetDeals()
	}
	return nil, errors.New("Received unknown function query: " + function)
}

type DealConfig struct {
	Issuer 		string 		`json:"issuer"`
	Banks 		[]string 	`json:"banks"`
	BookStatus 	string 		`json:"bookStatus"`
	Price 		float64 	`json:"price"`
}

type Deal struct {
	DeploymentId 	string 	`json:"deploymentId"`
	Issuer			string 	`json:"issuer"`
}

// Public Functions

func (c ChaincodeFunctions) Ping() ([]byte, error) {
    return []byte("pong"), nil
}

func (c ChaincodeFunctions) RegisterDeal(deploymentId string, issuer string) ([]byte, error)  {
	deal := Deal{DeploymentId: deploymentId, Issuer: issuer}
	c.saveDealToBlockChain(deal)
	c.stub.SetEvent("New Deal Registered", []byte("{\"deploymentId\":\"" + deploymentId + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) GetDeals() ([]byte, error) {
	company, _ := c.stub.ReadCertAttribute("company")
	deals := c.getDealsFromBlockchain()
	var ret []Deal // == nil
    for _, deal := range deals {
    	dealConfig := c.getDealConfig(deal.DeploymentId)
        if stringInSlice(string(company), dealConfig.Banks) {
        	ret = append(ret, deal)
        }
    }
    dealsJson, _ := json.Marshal(ret)
    return []byte(dealsJson), nil
}

// Private Functions

func (c ChaincodeFunctions) saveDealToBlockChain(deal Deal) {
	deals := c.getDealsFromBlockchain()
	deals = append(deals, deal)
	dealRegistryJson, _ := json.Marshal(deals)
	_ = c.stub.PutState("deals", []byte(dealRegistryJson))
}

func (c ChaincodeFunctions) getDealsFromBlockchain() []Deal {
	dealsJson, _ := c.stub.GetState("deals")
	var deals []Deal
	_ = json.Unmarshal(dealsJson, &deals)
	return deals
}

func (c ChaincodeFunctions) getDealConfig(address string) DealConfig {
	invokeArgs := util.ToChaincodeArgs("getDealConfig")
	dealConfigJson, _ := c.stub.QueryChaincode(address, invokeArgs)
	var dealConfig DealConfig
	_ = json.Unmarshal(dealConfigJson, &dealConfig)
	return dealConfig
}

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}<commit_msg>batch check-in<commit_after>package main

import (
	"errors"
	"fmt"
	"encoding/json"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/util"
)

type Chaincode struct { }

type ChaincodeFunctions struct {
	stub shim.ChaincodeStubInterface
}

func main() {
	err := shim.Start(new(Chaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

func (t Chaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	_ = stub.PutState("deals", []byte("[]"))
	return nil, nil
}

func (t Chaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "registerDeal" {
		deploymentId := args[0]
		issuer := args[1]
		return fns.RegisterDeal(deploymentId, issuer)
	}
	return nil, errors.New("Received unknown function invocation: " + function)
}

func (t Chaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "ping" {
		return fns.Ping()
	} else if function == "getDeals" {
		return fns.GetDeals()
	}
	return nil, errors.New("Received unknown function query: " + function)
}

type DealConfig struct {
	Issuer 		string 		`json:"issuer"`
	Banks 		[]string 	`json:"banks"`
	BookStatus 	string 		`json:"bookStatus"`
	Price 		float64 	`json:"price"`
}

type Deal struct {
	DeploymentId 	string 	`json:"deploymentId"`
	Issuer			string 	`json:"issuer"`
}

// Public Functions

func (c ChaincodeFunctions) Ping() ([]byte, error) {
    return []byte("pong"), nil
}

func (c ChaincodeFunctions) RegisterDeal(deploymentId string, issuer string) ([]byte, error)  {
	deal := Deal{DeploymentId: deploymentId, Issuer: issuer}
	c.saveDealToBlockChain(deal)
	c.stub.SetEvent("New Deal Registered", []byte("{\"deploymentId\":\"" + deploymentId + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) GetDeals() ([]byte, error) {
	company, _ := c.stub.ReadCertAttribute("company")
	deals := c.getDealsFromBlockchain()
	ret := make([]Deal, 0)
    for _, deal := range deals {
    	dealConfig := c.getDealConfig(deal.DeploymentId)
        if stringInSlice(string(company), dealConfig.Banks) {
        	ret = append(ret, deal)
        }
    }
    dealsJson, _ := json.Marshal(ret)
    return []byte(dealsJson), nil
}

// Private Functions

func (c ChaincodeFunctions) saveDealToBlockChain(deal Deal) {
	deals := c.getDealsFromBlockchain()
	deals = append(deals, deal)
	dealRegistryJson, _ := json.Marshal(deals)
	_ = c.stub.PutState("deals", []byte(dealRegistryJson))
}

func (c ChaincodeFunctions) getDealsFromBlockchain() []Deal {
	dealsJson, _ := c.stub.GetState("deals")
	var deals []Deal
	_ = json.Unmarshal(dealsJson, &deals)
	return deals
}

func (c ChaincodeFunctions) getDealConfig(address string) DealConfig {
	invokeArgs := util.ToChaincodeArgs("getDealConfig")
	dealConfigJson, _ := c.stub.QueryChaincode(address, invokeArgs)
	var dealConfig DealConfig
	_ = json.Unmarshal(dealConfigJson, &dealConfig)
	return dealConfig
}

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}<|endoftext|>


<commit_before>package francis

import (
	"fmt"
	"github.com/bnagy/crashwalk/crash"
	"go/build"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

func (e *Engine) Run(command []string, filename string, memlimit, timeout int) (crash.Info, error) {

	pkg, err := build.Import("github.com/bnagy/francis", ".", build.FindOnly)
	if err != nil {
		return crash.Info{}, fmt.Errorf("Couldn't find import path: %s", err)
	}
	tool := filepath.Join(pkg.Dir, "exploitaben/exploitaben.py")

	// Construct the command array
	cmdSlice := []string{tool, "-e", "MallocScribble=1", "-e", "MallocGuardEdges=1"}
	if e.Timeout > 0 {
		cmdSlice = append(cmdSlice, []string{"-t", strconv.Itoa(e.Timeout)}...)
	}
	cmdSlice = append(cmdSlice, "--")
	cmdSlice = append(cmdSlice, command...)
	cmdStr := strings.Join(cmdSlice, " ")

	cmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return crash.Info{}, fmt.Errorf("Error creating pipe: %s", err)
	}
	if err := cmd.Start(); err != nil {
		return crash.Info{}, fmt.Errorf("Error launching tool: %s", err)
	}

	out, _ := ioutil.ReadAll(stdout)
	cmd.Wait()

	return getCrashInfo(out, cmdStr)

}
<commit_msg>clarify API in comments<commit_after>package francis

import (
	"fmt"
	"github.com/bnagy/crashwalk/crash"
	"go/build"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
)

// Run runs a command under francis. This API matches the interface for
// Debugger for some of my other tools, but the `filename` and `memlimit`
// params are not presently used. The caller should set them to "" and 0
func (e *Engine) Run(command []string, filename string, memlimit, timeout int) (crash.Info, error) {

	pkg, err := build.Import("github.com/bnagy/francis", ".", build.FindOnly)
	if err != nil {
		return crash.Info{}, fmt.Errorf("Couldn't find import path: %s", err)
	}
	tool := filepath.Join(pkg.Dir, "exploitaben/exploitaben.py")

	// Construct the command array
	// XXX: This doesn't do anything, I think I forgot to export an env var or something
	cmdSlice := []string{tool, "-e", "MallocScribble=1", "-e", "MallocGuardEdges=1"}
	if e.Timeout > 0 {
		cmdSlice = append(cmdSlice, []string{"-t", strconv.Itoa(e.Timeout)}...)
	}
	cmdSlice = append(cmdSlice, "--")
	cmdSlice = append(cmdSlice, command...)
	cmdStr := strings.Join(cmdSlice, " ")

	cmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return crash.Info{}, fmt.Errorf("Error creating pipe: %s", err)
	}
	if err := cmd.Start(); err != nil {
		return crash.Info{}, fmt.Errorf("Error launching tool: %s", err)
	}

	out, _ := ioutil.ReadAll(stdout)
	cmd.Wait()

	return getCrashInfo(out, cmdStr)

}
<|endoftext|>


<commit_before>package tmx

import (
	"image"
	"path/filepath"

	"github.com/disintegration/imaging"
)

//Renderer renders a tmx to the given canvas
type Renderer struct {
	canvas Canvas
	m      Map
	loader ResourceLocator
}

//NewRendererWithCanvas lets you draw the map on a custom canvas
func NewRendererWithCanvas(m Map, c Canvas) *Renderer {
	return &Renderer{m: m, canvas: c, loader: FilesystemLocator{}}
}

//Render will generate a preview image of the tmx map provided
func (r Renderer) Render() error {
	canvas := tilemap{subject: r.m, tilesets: map[string]image.Image{}}
	canvas.renderBackground(r)
	err := canvas.renderLayer(r)
	if err != nil {
		return err
	}

	return nil
}

type tilemap struct {
	subject  Map
	tilesets map[string]image.Image
}

func (t tilemap) renderBackground(r Renderer) {
	color := t.subject.BackgroundColor
	r.canvas.FillRect(color, r.canvas.Bounds())
}

func (t *tilemap) renderLayer(r Renderer) error {
	for _, tileset := range t.subject.Tilesets {
		path := tileset.Image.Source

		tileset, err := r.loader.LoadResource(filepath.Clean(t.subject.filename + path))

		if err != nil {
			return err
		}

		t.tilesets[path] = tileset
	}

	for _, l := range t.subject.Layers {
		if !l.IsVisible() {
			continue
		}

		for i, dt := range l.Data.DataTiles {
			tileset, err := t.subject.GetTilesetForGID(dt.GID)
			if err != nil {
				continue
			}

			if tileset == nil {
				continue
			}

			tx := int(dt.GID-tileset.FirstGID) % tileset.GetNumTilesX()
			ty := int(dt.GID-tileset.FirstGID) / tileset.GetNumTilesX()
			tx *= t.subject.TileWidth
			ty *= t.subject.TileHeight

			tilesetgfx, found := t.tilesets[tileset.Image.Source]
			if !found {
				panic("invalid tileset path")
			}

			ptileset, ok := tilesetgfx.(*image.Paletted)
			if !ok {
				panic("invalid image type given")
			}

			tileBounds := image.Rect(tx, ty, tx+t.subject.TileWidth, ty+t.subject.TileHeight)
			tile := ptileset.SubImage(tileBounds)

			if dt.DiagonalFlip {
				tile = imaging.Rotate270(tile)
				tile = imaging.FlipH(tile)
			}

			if dt.HorizontalFlip {
				tile = imaging.FlipH(tile)
			}

			if dt.VerticalFlip {
				tile = imaging.FlipV(tile)
			}

			x := (i % l.Width) * t.subject.TileWidth
			y := (i / l.Height) * t.subject.TileHeight

			bounds := image.Rect(x, y, x+t.subject.TileWidth, y+t.subject.TileWidth)

			r.canvas.Draw(tile, bounds)
		}
	}

	return nil
}
<commit_msg>Refactor constructor functions<commit_after>package tmx

import (
	"image"
	"path/filepath"

	"github.com/disintegration/imaging"
)

//Renderer renders a tmx to the given canvas
type Renderer struct {
	canvas Canvas
	m      Map
	loader ResourceLocator
}

//NewRenderer lets you draw the map on a custom canvas
//with a default FilesystemLocator
func NewRenderer(m Map, c Canvas) *Renderer {
	return NewRendererWithResourceLocator(m, c, FilesystemLocator{})
}

//NewRendererWithResourceLocator return a new renderer
func NewRendererWithResourceLocator(m Map, c Canvas, locator ResourceLocator) *Renderer {
	return &Renderer{m: m, canvas: c, loader: locator}
}

//Render will generate a preview image of the tmx map provided
func (r Renderer) Render() error {
	canvas := tilemap{subject: r.m, tilesets: map[string]image.Image{}}
	canvas.renderBackground(r)
	err := canvas.renderLayer(r)
	if err != nil {
		return err
	}

	return nil
}

type tilemap struct {
	subject  Map
	tilesets map[string]image.Image
}

func (t tilemap) renderBackground(r Renderer) {
	color := t.subject.BackgroundColor
	r.canvas.FillRect(color, r.canvas.Bounds())
}

func (t *tilemap) renderLayer(r Renderer) error {
	for _, tileset := range t.subject.Tilesets {
		path := tileset.Image.Source

		tileset, err := r.loader.LoadResource(filepath.Clean(t.subject.filename + path))

		if err != nil {
			return err
		}

		t.tilesets[path] = tileset
	}

	for _, l := range t.subject.Layers {
		if !l.IsVisible() {
			continue
		}

		for i, dt := range l.Data.DataTiles {
			tileset, err := t.subject.GetTilesetForGID(dt.GID)
			if err != nil {
				continue
			}

			if tileset == nil {
				continue
			}

			tx := int(dt.GID-tileset.FirstGID) % tileset.GetNumTilesX()
			ty := int(dt.GID-tileset.FirstGID) / tileset.GetNumTilesX()
			tx *= t.subject.TileWidth
			ty *= t.subject.TileHeight

			tilesetgfx, found := t.tilesets[tileset.Image.Source]
			if !found {
				panic("invalid tileset path")
			}

			ptileset, ok := tilesetgfx.(*image.Paletted)
			if !ok {
				panic("invalid image type given")
			}

			tileBounds := image.Rect(tx, ty, tx+t.subject.TileWidth, ty+t.subject.TileHeight)
			tile := ptileset.SubImage(tileBounds)

			if dt.DiagonalFlip {
				tile = imaging.Rotate270(tile)
				tile = imaging.FlipH(tile)
			}

			if dt.HorizontalFlip {
				tile = imaging.FlipH(tile)
			}

			if dt.VerticalFlip {
				tile = imaging.FlipV(tile)
			}

			x := (i % l.Width) * t.subject.TileWidth
			y := (i / l.Height) * t.subject.TileHeight

			bounds := image.Rect(x, y, x+t.subject.TileWidth, y+t.subject.TileWidth)

			r.canvas.Draw(tile, bounds)
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package socks_test

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net"
	"testing"

	"golang.org/x/net/proxy"

	"github.com/v2ray/v2ray-core/app"
	v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
	v2proxy "github.com/v2ray/v2ray-core/proxy"
	proxytesting "github.com/v2ray/v2ray-core/proxy/testing"
	proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
	"github.com/v2ray/v2ray-core/shell/point"
	v2testing "github.com/v2ray/v2ray-core/testing"
	"github.com/v2ray/v2ray-core/testing/assert"
)

func TestSocksTcpConnect(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnOutput: connOutput,
		ConnInput:  bytes.NewReader(connInput),
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "noauth"
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "google.com:80"
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	data2Send := "The data to be sent to remote server."
	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
	assert.Bytes(dataReturned).Equals(connInput)
	assert.StringLiteral(targetServer).Equals(och.Destination.NetAddr())
}

func TestSocksTcpConnectWithUserPass(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passy"}, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	data2Send := "The data to be sent to remote server."
	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
	assert.Bytes(dataReturned).Equals(connInput)
	assert.StringLiteral(targetServer).Equals(och.Destination.NetAddr())
}

func TestSocksTcpConnectWithWrongUserPass(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passz"}, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	_, err = socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNotNil()
}

func TestSocksTcpConnectWithWrongAuthMethod(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	_, err = socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNotNil()
}

func TestSocksUdpSend(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och",
		func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
			return och, nil
		})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`{"auth": "noauth", "udp": true}`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: int(port),
		Zone: "",
	})

	assert.Error(err).IsNil()

	data2Send := []byte("Fake DNS request")

	buffer := make([]byte, 0, 1024)
	buffer = append(buffer, 0, 0, 0)
	buffer = append(buffer, 1, 8, 8, 4, 4, 0, 53)
	buffer = append(buffer, data2Send...)

	conn.Write(buffer)

	response := make([]byte, 1024)
	nBytes, err := conn.Read(response)

	assert.Error(err).IsNil()
	assert.Bytes(response[10:nBytes]).Equals(connInput)
	assert.Bytes(data2Send).Equals(connOutput.Bytes())
	assert.StringLiteral(och.Destination.String()).Equals("udp:8.8.4.4:53")
}
<commit_msg>remove out dated test<commit_after>package socks_test

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net"
	"testing"

	"golang.org/x/net/proxy"

	"github.com/v2ray/v2ray-core/app"
	v2nettesting "github.com/v2ray/v2ray-core/common/net/testing"
	v2proxy "github.com/v2ray/v2ray-core/proxy"
	proxytesting "github.com/v2ray/v2ray-core/proxy/testing"
	proxymocks "github.com/v2ray/v2ray-core/proxy/testing/mocks"
	"github.com/v2ray/v2ray-core/shell/point"
	v2testing "github.com/v2ray/v2ray-core/testing"
	"github.com/v2ray/v2ray-core/testing/assert"
)

func TestSocksTcpConnect(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnOutput: connOutput,
		ConnInput:  bytes.NewReader(connInput),
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "noauth"
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "google.com:80"
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	data2Send := "The data to be sent to remote server."
	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
	assert.Bytes(dataReturned).Equals(connInput)
	assert.StringLiteral(targetServer).Equals(och.Destination.NetAddr())
}

func TestSocksTcpConnectWithUserPass(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passy"}, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	conn, err := socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNil()

	data2Send := "The data to be sent to remote server."
	conn.Write([]byte(data2Send))
	if tcpConn, ok := conn.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}

	dataReturned, err := ioutil.ReadAll(conn)
	assert.Error(err).IsNil()
	conn.Close()

	assert.Bytes([]byte(data2Send)).Equals(connOutput.Bytes())
	assert.Bytes(dataReturned).Equals(connInput)
	assert.StringLiteral(targetServer).Equals(och.Destination.NetAddr())
}

func TestSocksTcpConnectWithWrongUserPass(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), &proxy.Auth{"userx", "passz"}, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	_, err = socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNotNil()
}

func TestSocksTcpConnectWithWrongAuthMethod(t *testing.T) {
	v2testing.Current(t)
	port := v2nettesting.PickPort()

	connInput := []byte("The data to be returned to socks server.")
	connOutput := bytes.NewBuffer(make([]byte, 0, 1024))
	och := &proxymocks.OutboundConnectionHandler{
		ConnInput:  bytes.NewReader(connInput),
		ConnOutput: connOutput,
	}

	protocol, err := proxytesting.RegisterOutboundConnectionHandlerCreator("mock_och", func(space app.Space, config interface{}) (v2proxy.OutboundHandler, error) {
		return och, nil
	})
	assert.Error(err).IsNil()

	config := &point.Config{
		Port: port,
		InboundConfig: &point.ConnectionConfig{
			Protocol: "socks",
			Settings: []byte(`
      {
        "auth": "password",
        "accounts": [
          {"user": "userx", "pass": "passy"}
        ]
      }`),
		},
		OutboundConfig: &point.ConnectionConfig{
			Protocol: protocol,
			Settings: nil,
		},
	}

	point, err := point.NewPoint(config)
	assert.Error(err).IsNil()

	err = point.Start()
	assert.Error(err).IsNil()

	socks5Client, err := proxy.SOCKS5("tcp", fmt.Sprintf("127.0.0.1:%d", port), nil, proxy.Direct)
	assert.Error(err).IsNil()

	targetServer := "1.2.3.4:443"
	_, err = socks5Client.Dial("tcp", targetServer)
	assert.Error(err).IsNotNil()
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/gob"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"
)

const ucdFileName = "UnicodeData.txt"
const ucdBaseUrl = "http://www.unicode.org/Public/UCD/latest/ucd/"
const indexFileName = "runefinder.gob"

func progressDisplay(running <-chan bool) {
	for {
		select {
		case <-running:
			fmt.Println()
		case <-time.After(200 * time.Millisecond):
			fmt.Print(".")
		}
	}
}

func getUcdFile(fileName string) {

	url := ucdBaseUrl + ucdFileName
	fmt.Printf("%s not found\nretrieving from %s\n", ucdFileName, url)
	running := make(chan bool)
	go progressDisplay(running)
	defer func() {
		running <- false
	}()
	response, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(file, response.Body)
	if err != nil {
		panic(err)
	}
	file.Close()
}

type RuneSlice []rune

func (rs RuneSlice) Len() int           { return len(rs) }
func (rs RuneSlice) Less(i, j int) bool { return rs[i] < rs[j] }
func (rs RuneSlice) Swap(i, j int)      { rs[i], rs[j] = rs[j], rs[i] }

type RuneSet map[rune]struct{}

func (rs RuneSet) Put(key rune) {
	rs[key] = struct{}{} // zero-byte struct
}

func (rs RuneSet) Contains(key rune) bool {
	_, found := rs[key]
	return found
}

func (rs RuneSet) Intersection(other RuneSet) RuneSet {
	result := RuneSet{}
	for k := range rs {
		if other.Contains(k) {
			result.Put(k)
		}
	}
	return result
}

func (rs RuneSet) ToRuneSlice() RuneSlice {
	result := RuneSlice{}
	for uchar := range rs {
		result = append(result, uchar)
	}
	return result
}

func (rs RuneSet) String() string {
	sl := rs.ToRuneSlice()
	sort.Sort(sl)
	str := "❮"
	for i, uchar := range sl {
		if i > 0 {
			str += " "
		}
		str += fmt.Sprintf("U+%04X", uchar)
	}
	return str + "❯"
}

type RuneIndex struct {
	characters map[string]RuneSet
	names      map[rune]string
}

func buildIndex(indexDir string) RuneIndex {
	ucdPath := path.Join(indexDir, ucdFileName)
	if _, err := os.Stat(ucdPath); os.IsNotExist(err) {
		getUcdFile(ucdPath)
	}
	content, err := ioutil.ReadFile(ucdPath)
	if err != nil {
		panic(err)
	}
	lines := strings.Split(string(content), "\n")

	var index RuneIndex
	index.characters = map[string]RuneSet{}
	index.names = map[rune]string{}

	for _, line := range lines {
		var uchar rune
		fields := strings.Split(line, ";")
		if len(fields) >= 2 {
			code64, _ := strconv.ParseInt(fields[0], 16, 0)
			uchar = rune(code64)
			index.names[uchar] = fields[1]
			for _, word := range strings.Split(fields[1], " ") {
				existing, ok := index.characters[word]
				if !ok {
					existing = RuneSet{}
				}
				existing.Put(uchar)
				index.characters[word] = existing
			}
		}

	}
	indexPath := path.Join(indexDir, indexFileName)
	indexFile, err := os.Create(indexPath)
	if err != nil {
		fmt.Printf("WARNING: Unable to save index file.")
	} else {
		dataEncoder := gob.NewEncoder(indexFile)
		defer indexFile.Close()
		dataEncoder.Encode(index.characters)
		dataEncoder.Encode(index.names)
	}
	return index
}

func getIndex() RuneIndex {
	indexDir, _ := os.Getwd()
	indexPath := path.Join(indexDir, indexFileName)
	if _, err := os.Stat(indexPath); os.IsNotExist(err) {
		return buildIndex(indexDir)
	}
	// load existing index
	indexFile, err := os.Open(indexPath)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer indexFile.Close()

	var index RuneIndex
	index.characters = map[string]RuneSet{}
	index.names = map[rune]string{}

	dataDecoder := gob.NewDecoder(indexFile)
	err = dataDecoder.Decode(&index.characters)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = dataDecoder.Decode(&index.names)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	return index
}

func findRunes(query []string, index RuneIndex) RuneSlice {
	commonRunes := RuneSet{}
	for i, word := range query {
		word = strings.ToUpper(word)
		found := index.characters[word]
		if i == 0 {
			commonRunes = found
		} else {
			commonRunes = commonRunes.Intersection(found)
		}
		if len(commonRunes) == 0 {
			break
		}
	}
	result := commonRunes.ToRuneSlice()
	sort.Sort(result)
	return result
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage:  runefinder <word>\texample: runefinder cat")
		os.Exit(1)
	}
	words := os.Args[1:]

	index := getIndex()

	count := 0
	format := "U+%04X  %c \t%s\n"
	for _, uchar := range findRunes(words, index) {
		if uchar > 0xFFFF {
			format = "U+%5X %c \t%s\n"
		}
		fmt.Printf(format, uchar, uchar, index.names[uchar])
		count++
	}
	fmt.Printf("%d characters found\n", count)

}
<commit_msg>minor name changes<commit_after>package main

import (
	"encoding/gob"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"
)

const ucdFileName = "UnicodeData.txt"
const ucdBaseUrl = "http://www.unicode.org/Public/UCD/latest/ucd/"
const indexFileName = "runefinder.gob"

func progressDisplay(running <-chan bool) {
	for {
		select {
		case <-running:
			fmt.Println()
		case <-time.After(200 * time.Millisecond):
			fmt.Print(".")
		}
	}
}

func getUcdFile(fileName string) {

	url := ucdBaseUrl + ucdFileName
	fmt.Printf("%s not found\nretrieving from %s\n", ucdFileName, url)
	running := make(chan bool)
	go progressDisplay(running)
	defer func() {
		running <- false
	}()
	response, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(file, response.Body)
	if err != nil {
		panic(err)
	}
	file.Close()
}

type RuneSlice []rune

func (rs RuneSlice) Len() int           { return len(rs) }
func (rs RuneSlice) Less(i, j int) bool { return rs[i] < rs[j] }
func (rs RuneSlice) Swap(i, j int)      { rs[i], rs[j] = rs[j], rs[i] }

type RuneSet map[rune]struct{}

func (rs RuneSet) Put(key rune) {
	rs[key] = struct{}{} // zero-byte struct
}

func (rs RuneSet) Contains(key rune) bool {
	_, found := rs[key]
	return found
}

func (rs RuneSet) Intersection(other RuneSet) RuneSet {
	result := RuneSet{}
	for k := range rs {
		if other.Contains(k) {
			result.Put(k)
		}
	}
	return result
}

func (rs RuneSet) ToRuneSlice() RuneSlice {
	result := RuneSlice{}
	for uchar := range rs {
		result = append(result, uchar)
	}
	return result
}

func (rs RuneSet) String() string {
	sl := rs.ToRuneSlice()
	sort.Sort(sl)
	str := "❮"
	for i, uchar := range sl {
		if i > 0 {
			str += " "
		}
		str += fmt.Sprintf("U+%04X", uchar)
	}
	return str + "❯"
}

type RuneIndex struct {
	characters map[string]RuneSet
	names      map[rune]string
}

func buildIndex(indexDir string) RuneIndex {
	ucdPath := path.Join(indexDir, ucdFileName)
	if _, err := os.Stat(ucdPath); os.IsNotExist(err) {
		getUcdFile(ucdPath)
	}
	content, err := ioutil.ReadFile(ucdPath)
	if err != nil {
		panic(err)
	}
	lines := strings.Split(string(content), "\n")

	var index RuneIndex
	index.characters = map[string]RuneSet{}
	index.names = map[rune]string{}

	for _, line := range lines {
		var uchar rune
		fields := strings.Split(line, ";")
		if len(fields) >= 2 {
			code64, _ := strconv.ParseInt(fields[0], 16, 0)
			uchar = rune(code64)
			index.names[uchar] = fields[1]
			for _, word := range strings.Split(fields[1], " ") {
				existing, ok := index.characters[word]
				if !ok {
					existing = RuneSet{}
				}
				existing.Put(uchar)
				index.characters[word] = existing
			}
		}

	}
	indexPath := path.Join(indexDir, indexFileName)
	indexFile, err := os.Create(indexPath)
	if err != nil {
		fmt.Printf("WARNING: Unable to save index file.")
	} else {
		encoder := gob.NewEncoder(indexFile)
		defer indexFile.Close()
		encoder.Encode(index.characters)
		encoder.Encode(index.names)
	}
	return index
}

func getIndex() RuneIndex {
	indexDir, _ := os.Getwd()
	indexPath := path.Join(indexDir, indexFileName)
	if _, err := os.Stat(indexPath); os.IsNotExist(err) {
		return buildIndex(indexDir)
	}
	// load existing index
	indexFile, err := os.Open(indexPath)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer indexFile.Close()

	var index RuneIndex
	index.characters = map[string]RuneSet{}
	index.names = map[rune]string{}

	decoder := gob.NewDecoder(indexFile)
	err = decoder.Decode(&index.characters)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = decoder.Decode(&index.names)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	return index
}

func findRunes(query []string, index RuneIndex) RuneSlice {
	commonRunes := RuneSet{}
	for i, word := range query {
		word = strings.ToUpper(word)
		found := index.characters[word]
		if i == 0 {
			commonRunes = found
		} else {
			commonRunes = commonRunes.Intersection(found)
		}
		if len(commonRunes) == 0 {
			break
		}
	}
	result := commonRunes.ToRuneSlice()
	sort.Sort(result)
	return result
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage:  runefinder <word>\texample: runefinder cat")
		os.Exit(1)
	}
	words := os.Args[1:]

	index := getIndex()

	count := 0
	format := "U+%04X  %c \t%s\n"
	for _, uchar := range findRunes(words, index) {
		if uchar > 0xFFFF {
			format = "U+%5X %c \t%s\n"
		}
		fmt.Printf(format, uchar, uchar, index.names[uchar])
		count++
	}
	fmt.Printf("%d characters found\n", count)

}
<|endoftext|>


<commit_before>/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@debian.org>, 2015
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE. }}} */

package reprepro

import (
	"os/exec"
)

type Repo struct {
	Basedir string
}

func (repo *Repo) Command(args ...string) *exec.Cmd {
	return exec.Command("reprepro", append([]string{
		"--basedir", repo.Basedir,
	}, args...)...)
}

func (repo *Repo) ProcessIncoming() error {
	cmd := repo.Command("processincoming")
	return cmd.Run()
}

func (repo *Repo) Check() error {
	cmd := repo.Command("check")
	return cmd.Run()
}

func (repo *Repo) Check() error {
	cmd := repo.Command("checkpool")
	return cmd.Run()
}

func (repo *Repo) Include(suite string, changes string) error {
	cmd := repo.Command("include", suite, changes)
	return cmd.Run()
}

// Create a new reprepro.Repo object given a filesystem path to the Repo.
func NewRepo(path string) *Repo {
	return &Repo{Basedir: path}
}

// vim: foldmethod=marker
<commit_msg>typo fix<commit_after>/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@debian.org>, 2015
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE. }}} */

package reprepro

import (
	"os/exec"
)

type Repo struct {
	Basedir string
}

func (repo *Repo) Command(args ...string) *exec.Cmd {
	return exec.Command("reprepro", append([]string{
		"--basedir", repo.Basedir,
	}, args...)...)
}

func (repo *Repo) ProcessIncoming() error {
	cmd := repo.Command("processincoming")
	return cmd.Run()
}

func (repo *Repo) Check() error {
	cmd := repo.Command("check")
	return cmd.Run()
}

func (repo *Repo) CheckPool() error {
	cmd := repo.Command("checkpool")
	return cmd.Run()
}

func (repo *Repo) Include(suite string, changes string) error {
	cmd := repo.Command("include", suite, changes)
	return cmd.Run()
}

// Create a new reprepro.Repo object given a filesystem path to the Repo.
func NewRepo(path string) *Repo {
	return &Repo{Basedir: path}
}

// vim: foldmethod=marker
<|endoftext|>


<commit_before>package dnsr

import (
	"fmt"
	"time"

	"github.com/miekg/dns"
)

var (
	Timeout        = 2000 * time.Millisecond
	MaxRecursion   = 10
	MaxNameservers = 2
	MaxIPs         = 2

	NXDOMAIN        = fmt.Errorf("NXDOMAIN")
	ErrMaxRecursion = fmt.Errorf("maximum recursion depth reached: %d", MaxRecursion)
	ErrMaxIPs       = fmt.Errorf("maximum name server IPs queried: %d", MaxIPs)
	ErrNoARecords   = fmt.Errorf("no A records found for name server")
	ErrNoResponse   = fmt.Errorf("no responses received")
)

// Resolver implements a primitive, non-recursive, caching DNS resolver.
type Resolver struct {
	cache  *cache
	client *dns.Client
}

// New initializes a Resolver with the specified cache size.
func New(capacity int) *Resolver {
	r := &Resolver{
		cache: newCache(capacity),
		client: &dns.Client{
			DialTimeout:  Timeout,
			ReadTimeout:  Timeout,
			WriteTimeout: Timeout,
		},
	}
	return r
}

// Resolve finds DNS records of type qtype for the domain qname.
// For nonexistent domains (NXDOMAIN), it will return an empty, non-nil slice.
// Specify an empty string in qtype to receive any DNS records found
// (currently A, AAAA, NS, CNAME, and TXT).
func (r *Resolver) Resolve(qname string, qtype string) []*RR {
	rrs, err := r.resolve(qname, qtype, 0)
	if err == NXDOMAIN {
		return emptyRRs
	}
	if err != nil {
		return nil
	}
	return rrs
}

// ResolveErr finds DNS records of type qtype for the domain qname.
// For nonexistent domains, it will return an NXDOMAIN error.
// Specify an empty string in qtype to receive any DNS records found
// (currently A, AAAA, NS, CNAME, and TXT).
func (r *Resolver) ResolveErr(qname string, qtype string) ([]*RR, error) {
	return r.resolve(qname, qtype, 0)
}

func (r *Resolver) resolve(qname string, qtype string, depth int) ([]*RR, error) {
	if depth++; depth > MaxRecursion {
		logMaxRecursion(qname, qtype, depth)
		return nil, ErrMaxRecursion
	}
	qname = toLowerFQDN(qname)
	rrs, err := r.cacheGet(qname, qtype)
	if err != nil {
		return nil, err
	}
	if len(rrs) > 0 {
		return rrs, nil
	}
	logResolveStart(qname, qtype, depth)
	start := time.Now()
	rrs, err = r.iterateParents(qname, qtype, depth)
	logResolveEnd(qname, qtype, rrs, depth, start, err)
	return rrs, err
}

func (r *Resolver) iterateParents(qname string, qtype string, depth int) ([]*RR, error) {
	errs := make(chan error, MaxNameservers)
	for pname, ok := qname, true; ok; pname, ok = parent(pname) {
		if pname == qname && qtype == "NS" { // If we’re looking for [foo.com,NS], then skip to [com,NS]
			continue
		}

		// Only query TLDs against the root nameservers
		if pname == "." && dns.CountLabel(qname) != 1 {
			// fmt.Fprintf(os.Stderr, "Warning: non-TLD query at root: dig +norecurse %s %s\n", qname, qtype)
			return nil, nil
		}

		// Get nameservers
		nrrs, err := r.resolve(pname, "NS", depth)
		if err == NXDOMAIN {
			return nil, err
		}
		if err != nil {
			continue
		}

		// Early out for specific queries
		if len(nrrs) > 0 && qtype != "" {
			rrs, err := r.cacheGet(qname, qtype)
			if err != nil {
				return nil, err
			}
			if len(rrs) > 0 {
				return rrs, nil
			}
		}

		// Query all nameservers in parallel
		count := 0
		for _, nrr := range nrrs {
			if nrr.Type != "NS" {
				continue
			}

			go func(nrr *RR) {
				errs <- r.exchange(nrr.Value, qname, qtype, depth)
			}(nrr)

			count++
			if count >= MaxNameservers {
				break
			}
		}

		// Wait for first response
		for ; count > 0; count-- {
			select {
			case err = <-errs:
				if err == NXDOMAIN {
					return nil, err
				}
				if err == nil {
					return r.resolveCNAMEs(qname, qtype, depth)
				}
			}
		}

		// NS queries naturally recurse, so stop further iteration
		if qtype == "NS" {
			return nil, err
		}
	}

	return nil, ErrNoResponse
}

func (r *Resolver) exchange(host string, qname string, qtype string, depth int) error {
	dtype := dns.StringToType[qtype]
	if dtype == 0 {
		dtype = dns.TypeA
	}
	qmsg := &dns.Msg{}
	qmsg.SetQuestion(qname, dtype)
	qmsg.MsgHdr.RecursionDesired = false

	// Find each A record for the DNS server
	count := 0
	rrs, err := r.resolve(host, "A", depth)
	if err != nil {
		return err
	}
	for _, rr := range rrs {
		if rr.Type != "A" { // FIXME: support AAAA records?
			continue
		}

		// Never query more than MaxIPs for any nameserver
		if count++; count > MaxIPs {
			return ErrMaxIPs
		}

		// Synchronously query this DNS server
		start := time.Now()
		rmsg, _, err := r.client.Exchange(qmsg, rr.Value+":53")
		logExchange(host, qmsg, rmsg, depth, start, err) // Log hostname instead of IP
		if err != nil {
			continue
		}

		// FIXME: cache NXDOMAIN responses responsibly
		if rmsg.Rcode == dns.RcodeNameError {
			r.cache.add(qname, nil)
			return NXDOMAIN
		}

		// Cache records returned
		r.saveDNSRR(host, qname, append(append(rmsg.Answer, rmsg.Ns...), rmsg.Extra...)...)

		// Return after first successful network request
		return nil
	}

	return ErrNoARecords
}

func (r *Resolver) resolveCNAMEs(qname string, qtype string, depth int) ([]*RR, error) {
	crrs, err := r.cacheGet(qname, "")
	if err != nil {
		return nil, err
	}
	var rrs []*RR
	for _, crr := range crrs {
		rrs = append(rrs, crr)
		if crr.Type != "CNAME" {
			continue
		}
		logCNAME(crr.String(), depth)
		crrs, _ := r.resolve(crr.Value, qtype, depth)
		for _, rr := range crrs {
			r.cache.add(qname, rr)
			rrs = append(rrs, crr)
		}
	}
	return rrs, nil
}

// saveDNSRR saves 1 or more DNS records to the resolver cache.
func (r *Resolver) saveDNSRR(host string, qname string, drrs ...dns.RR) {
	cl := dns.CountLabel(qname)
	for _, drr := range drrs {
		if rr := convertRR(drr); rr != nil {
			if dns.CountLabel(rr.Name) < cl && dns.CompareDomainName(qname, rr.Name) < 2 {
				// fmt.Fprintf(os.Stderr, "Warning: potential poisoning from %s: %s -> %s\n", host, qname, drr.String())
				continue
			}
			r.cache.add(rr.Name, rr)
		}
	}
}

// cacheGet returns a randomly ordered slice of DNS records.
func (r *Resolver) cacheGet(qname string, qtype string) ([]*RR, error) {
	any := r.cache.get(qname)
	if any == nil {
		any = rootCache.get(qname)
	}
	if any == nil {
		return nil, nil
	}
	if len(any) == 0 {
		return nil, NXDOMAIN
	}
	rrs := make([]*RR, 0, len(any))
	for _, rr := range any {
		if qtype == "" || rr.Type == qtype {
			rrs = append(rrs, rr)
		}
	}
	if len(rrs) == 0 && (qtype != "" && qtype != "NS") {
		return nil, nil
	}
	return rrs, nil
}
<commit_msg>Return DNS errors in Resolver.exchange.<commit_after>package dnsr

import (
	"errors"
	"fmt"
	"time"

	"github.com/miekg/dns"
)

var (
	Timeout        = 2000 * time.Millisecond
	MaxRecursion   = 10
	MaxNameservers = 2
	MaxIPs         = 2

	NXDOMAIN        = fmt.Errorf("NXDOMAIN")
	ErrMaxRecursion = fmt.Errorf("maximum recursion depth reached: %d", MaxRecursion)
	ErrMaxIPs       = fmt.Errorf("maximum name server IPs queried: %d", MaxIPs)
	ErrNoARecords   = fmt.Errorf("no A records found for name server")
	ErrNoResponse   = fmt.Errorf("no responses received")
)

// Resolver implements a primitive, non-recursive, caching DNS resolver.
type Resolver struct {
	cache  *cache
	client *dns.Client
}

// New initializes a Resolver with the specified cache size.
func New(capacity int) *Resolver {
	r := &Resolver{
		cache: newCache(capacity),
		client: &dns.Client{
			DialTimeout:  Timeout,
			ReadTimeout:  Timeout,
			WriteTimeout: Timeout,
		},
	}
	return r
}

// Resolve finds DNS records of type qtype for the domain qname.
// For nonexistent domains (NXDOMAIN), it will return an empty, non-nil slice.
// Specify an empty string in qtype to receive any DNS records found
// (currently A, AAAA, NS, CNAME, and TXT).
func (r *Resolver) Resolve(qname string, qtype string) []*RR {
	rrs, err := r.resolve(qname, qtype, 0)
	if err == NXDOMAIN {
		return emptyRRs
	}
	if err != nil {
		return nil
	}
	return rrs
}

// ResolveErr finds DNS records of type qtype for the domain qname.
// For nonexistent domains, it will return an NXDOMAIN error.
// Specify an empty string in qtype to receive any DNS records found
// (currently A, AAAA, NS, CNAME, and TXT).
func (r *Resolver) ResolveErr(qname string, qtype string) ([]*RR, error) {
	return r.resolve(qname, qtype, 0)
}

func (r *Resolver) resolve(qname string, qtype string, depth int) ([]*RR, error) {
	if depth++; depth > MaxRecursion {
		logMaxRecursion(qname, qtype, depth)
		return nil, ErrMaxRecursion
	}
	qname = toLowerFQDN(qname)
	rrs, err := r.cacheGet(qname, qtype)
	if err != nil {
		return nil, err
	}
	if len(rrs) > 0 {
		return rrs, nil
	}
	logResolveStart(qname, qtype, depth)
	start := time.Now()
	rrs, err = r.iterateParents(qname, qtype, depth)
	logResolveEnd(qname, qtype, rrs, depth, start, err)
	return rrs, err
}

func (r *Resolver) iterateParents(qname string, qtype string, depth int) ([]*RR, error) {
	errs := make(chan error, MaxNameservers)
	for pname, ok := qname, true; ok; pname, ok = parent(pname) {
		if pname == qname && qtype == "NS" { // If we’re looking for [foo.com,NS], then skip to [com,NS]
			continue
		}

		// Only query TLDs against the root nameservers
		if pname == "." && dns.CountLabel(qname) != 1 {
			// fmt.Fprintf(os.Stderr, "Warning: non-TLD query at root: dig +norecurse %s %s\n", qname, qtype)
			return nil, nil
		}

		// Get nameservers
		nrrs, err := r.resolve(pname, "NS", depth)
		if err == NXDOMAIN {
			return nil, err
		}
		if err != nil {
			continue
		}

		// Early out for specific queries
		if len(nrrs) > 0 && qtype != "" {
			rrs, err := r.cacheGet(qname, qtype)
			if err != nil {
				return nil, err
			}
			if len(rrs) > 0 {
				return rrs, nil
			}
		}

		// Query all nameservers in parallel
		count := 0
		for _, nrr := range nrrs {
			if nrr.Type != "NS" {
				continue
			}

			go func(nrr *RR) {
				errs <- r.exchange(nrr.Value, qname, qtype, depth)
			}(nrr)

			count++
			if count >= MaxNameservers {
				break
			}
		}

		// Wait for first response
		for ; count > 0; count-- {
			select {
			case err = <-errs:
				if err == NXDOMAIN {
					return nil, err
				}
				if err == nil {
					return r.resolveCNAMEs(qname, qtype, depth)
				}
			}
		}

		// NS queries naturally recurse, so stop further iteration
		if qtype == "NS" {
			return nil, err
		}
	}

	return nil, ErrNoResponse
}

func (r *Resolver) exchange(host string, qname string, qtype string, depth int) error {
	dtype := dns.StringToType[qtype]
	if dtype == 0 {
		dtype = dns.TypeA
	}
	qmsg := &dns.Msg{}
	qmsg.SetQuestion(qname, dtype)
	qmsg.MsgHdr.RecursionDesired = false

	// Find each A record for the DNS server
	count := 0
	rrs, err := r.resolve(host, "A", depth)
	if err != nil {
		return err
	}
	for _, rr := range rrs {
		if rr.Type != "A" { // FIXME: support AAAA records?
			continue
		}

		// Never query more than MaxIPs for any nameserver
		if count++; count > MaxIPs {
			return ErrMaxIPs
		}

		// Synchronously query this DNS server
		start := time.Now()
		rmsg, _, err := r.client.Exchange(qmsg, rr.Value+":53")
		logExchange(host, qmsg, rmsg, depth, start, err) // Log hostname instead of IP
		if err != nil {
			continue
		}

		// FIXME: cache NXDOMAIN responses responsibly
		if rmsg.Rcode == dns.RcodeNameError {
			r.cache.add(qname, nil)
			return NXDOMAIN
		} else if rmsg.Rcode != dns.RcodeSuccess {
			return errors.New(dns.RcodeToString[rmsg.Rcode])
		}

		// Cache records returned
		r.saveDNSRR(host, qname, append(append(rmsg.Answer, rmsg.Ns...), rmsg.Extra...)...)

		// Return after first successful network request
		return nil
	}

	return ErrNoARecords
}

func (r *Resolver) resolveCNAMEs(qname string, qtype string, depth int) ([]*RR, error) {
	crrs, err := r.cacheGet(qname, "")
	if err != nil {
		return nil, err
	}
	var rrs []*RR
	for _, crr := range crrs {
		rrs = append(rrs, crr)
		if crr.Type != "CNAME" {
			continue
		}
		logCNAME(crr.String(), depth)
		crrs, _ := r.resolve(crr.Value, qtype, depth)
		for _, rr := range crrs {
			r.cache.add(qname, rr)
			rrs = append(rrs, crr)
		}
	}
	return rrs, nil
}

// saveDNSRR saves 1 or more DNS records to the resolver cache.
func (r *Resolver) saveDNSRR(host string, qname string, drrs ...dns.RR) {
	cl := dns.CountLabel(qname)
	for _, drr := range drrs {
		if rr := convertRR(drr); rr != nil {
			if dns.CountLabel(rr.Name) < cl && dns.CompareDomainName(qname, rr.Name) < 2 {
				// fmt.Fprintf(os.Stderr, "Warning: potential poisoning from %s: %s -> %s\n", host, qname, drr.String())
				continue
			}
			r.cache.add(rr.Name, rr)
		}
	}
}

// cacheGet returns a randomly ordered slice of DNS records.
func (r *Resolver) cacheGet(qname string, qtype string) ([]*RR, error) {
	any := r.cache.get(qname)
	if any == nil {
		any = rootCache.get(qname)
	}
	if any == nil {
		return nil, nil
	}
	if len(any) == 0 {
		return nil, NXDOMAIN
	}
	rrs := make([]*RR, 0, len(any))
	for _, rr := range any {
		if qtype == "" || rr.Type == qtype {
			rrs = append(rrs, rr)
		}
	}
	if len(rrs) == 0 && (qtype != "" && qtype != "NS") {
		return nil, nil
	}
	return rrs, nil
}
<|endoftext|>


<commit_before>package amazing

import (
	"encoding/xml"
	"fmt"
)

const (
	errorFormat = "ErrorCode: %s\nMessage: %s\nRequest:%s"
)

type AmazonItemLookupResponse struct {
	XMLName          xml.Name `xml:"ItemLookupResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonItemSearchResponse struct {
	XMLName          xml.Name `xml:"ItemSearchResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonSimilarityLookupResponse struct {
	XMLName          xml.Name `xml:"SimilarityLookupResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonOperationRequest struct {
	HTTPHeaders           []AmazonOperationRequestHeader   `xml:"HTTPHeaders>Header"`
	Arguments             []AmazonOperationRequestArgument `xml:"Arguments>Argument"`
	RequestId             string
	RequestProcessingTime float64
}

type AmazonOperationRequestHeader struct {
	Name  string `xml:"Name,attr"`
	Value string `xml:"Value,attr"`
}

type AmazonOperationRequestArgument struct {
	Name  string `xml:"Name,attr"`
	Value string `xml:"Value,attr"`
}

type AmazonItems struct {
	Request AmazonRequest
	Items   []AmazonItem `xml:"Item"`
}

type AmazonItem struct {
	ASIN             string
	ParentASIN       string
	DetailPageURL    string
	SalesRank        string
	ItemLinks        []AmazonItemLink `xml:"ItemLinks>ItemLink"`
	SmallImage       AmazonImage
	MediumImage      AmazonImage
	LargeImage       AmazonImage
	ImageSets        []AmazonImageSet `xml:"ImageSets>ImageSet"`
	ItemAttributes   AmazonItemAtributes
	OfferSummary     AmazonItemOfferSummary
	EditorialReviews []AmazonEditorialReview `xml:"EditorialReviews>EditorialReview"`
}

type AmazonEditorialReview struct {
	Source  string
	Content string
}

type AmazonItemAtributes struct {
	Title     string
	ListPrice AmazonItemPrice
}

type AmazonItemOfferSummary struct {
	LowestUsedPrice        AmazonItemPrice
	LowestNewPrice         AmazonItemPrice
	LowestCollectiblePrice AmazonItemPrice
}

type AmazonItemPrice struct {
	Amount         int64
	CurrencyCode   string
	FormattedPrice string
}

type AmazonItemLink struct {
	Description string
	URL         string
}

type AmazonImageSet struct {
	Category       string `xml:"Category,attr"`
	SwatchImage    AmazonImage
	SmallImage     AmazonImage
	ThumbnailImage AmazonImage
	TinyImage      AmazonImage
	MediumImage    AmazonImage
	LargeImage     AmazonImage
}

type AmazonRequest struct {
	IsValid           bool
	ItemLookupRequest AmazonItemLookupRequest
	Errors            []AmazonError
}

type AmazonItemLookupRequest struct {
	Condition      string
	IdType         string
	ItemId         string
	ResponseGroups []string `xml:"ResponseGroup"`
	VariationPage  string
}

type AmazonItemLookupErrorResponse struct {
	XMLName xml.Name
	AmazonError
}

type AmazonError struct {
	Code      string `xml:"Error>Code"`
	Message   string `xml:"Error>Message"`
	RequestId string
}

type AmazonImage struct {
	URL    string
	Height uint16
	Width  uint16
}

func (a *AmazonError) Error() string {
	return fmt.Sprintf(errorFormat, a.Code, a.Message, a.RequestId)
}
<commit_msg>Add Brand field to AmazonItemAtributes<commit_after>package amazing

import (
	"encoding/xml"
	"fmt"
)

const (
	errorFormat = "ErrorCode: %s\nMessage: %s\nRequest:%s"
)

type AmazonItemLookupResponse struct {
	XMLName          xml.Name `xml:"ItemLookupResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonItemSearchResponse struct {
	XMLName          xml.Name `xml:"ItemSearchResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonSimilarityLookupResponse struct {
	XMLName          xml.Name `xml:"SimilarityLookupResponse"`
	OperationRequest AmazonOperationRequest
	AmazonItems      AmazonItems `xml:"Items"`
}

type AmazonOperationRequest struct {
	HTTPHeaders           []AmazonOperationRequestHeader   `xml:"HTTPHeaders>Header"`
	Arguments             []AmazonOperationRequestArgument `xml:"Arguments>Argument"`
	RequestId             string
	RequestProcessingTime float64
}

type AmazonOperationRequestHeader struct {
	Name  string `xml:"Name,attr"`
	Value string `xml:"Value,attr"`
}

type AmazonOperationRequestArgument struct {
	Name  string `xml:"Name,attr"`
	Value string `xml:"Value,attr"`
}

type AmazonItems struct {
	Request AmazonRequest
	Items   []AmazonItem `xml:"Item"`
}

type AmazonItem struct {
	ASIN             string
	ParentASIN       string
	DetailPageURL    string
	SalesRank        string
	ItemLinks        []AmazonItemLink `xml:"ItemLinks>ItemLink"`
	SmallImage       AmazonImage
	MediumImage      AmazonImage
	LargeImage       AmazonImage
	ImageSets        []AmazonImageSet `xml:"ImageSets>ImageSet"`
	ItemAttributes   AmazonItemAtributes
	OfferSummary     AmazonItemOfferSummary
	EditorialReviews []AmazonEditorialReview `xml:"EditorialReviews>EditorialReview"`
}

type AmazonEditorialReview struct {
	Source  string
	Content string
}

type AmazonItemAtributes struct {
	Title     string
	Brand     string
	ListPrice AmazonItemPrice
}

type AmazonItemOfferSummary struct {
	LowestUsedPrice        AmazonItemPrice
	LowestNewPrice         AmazonItemPrice
	LowestCollectiblePrice AmazonItemPrice
}

type AmazonItemPrice struct {
	Amount         int64
	CurrencyCode   string
	FormattedPrice string
}

type AmazonItemLink struct {
	Description string
	URL         string
}

type AmazonImageSet struct {
	Category       string `xml:"Category,attr"`
	SwatchImage    AmazonImage
	SmallImage     AmazonImage
	ThumbnailImage AmazonImage
	TinyImage      AmazonImage
	MediumImage    AmazonImage
	LargeImage     AmazonImage
}

type AmazonRequest struct {
	IsValid           bool
	ItemLookupRequest AmazonItemLookupRequest
	Errors            []AmazonError
}

type AmazonItemLookupRequest struct {
	Condition      string
	IdType         string
	ItemId         string
	ResponseGroups []string `xml:"ResponseGroup"`
	VariationPage  string
}

type AmazonItemLookupErrorResponse struct {
	XMLName xml.Name
	AmazonError
}

type AmazonError struct {
	Code      string `xml:"Error>Code"`
	Message   string `xml:"Error>Message"`
	RequestId string
}

type AmazonImage struct {
	URL    string
	Height uint16
	Width  uint16
}

func (a *AmazonError) Error() string {
	return fmt.Sprintf(errorFormat, a.Code, a.Message, a.RequestId)
}
<|endoftext|>