<commit_before>package cmd

import (
	"github.com/go-errors/errors"
	irma "github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/internal/keysharecore"
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/keyshare/keyshareserver"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var keyshareServerCmd = &cobra.Command{
	Use:   "server",
	Short: "IRMA keyshare server",
	Run: func(command *cobra.Command, args []string) {
		conf, err := configureKeyshareServer(command)
		if err != nil {
			die("failed to read configuration", err)
		}

		// Create main server
		keyshareServer, err := keyshareserver.New(conf)
		if err != nil {
			die("", err)
		}

		runServer(keyshareServer, conf.Logger)
	},
}

func init() {
	keyshareRootCmd.AddCommand(keyshareServerCmd)

	keyshareServerCmd.SetUsageTemplate(headerFlagsTemplate)
	headers := map[string]string{}
	flagHeaders["irma keyshare server"] = headers

	flags := keyshareServerCmd.Flags()
	flags.SortFlags = false
	flags.StringP("config", "c", "", "path to configuration file")
	flags.StringP("schemes-path", "s", irma.DefaultSchemesPath(), "path to irma_configuration")
	flags.String("schemes-assets-path", "", "if specified, copy schemes from here into --schemes-path")
	flags.Int("schemes-update", 60, "update IRMA schemes every x minutes (0 to disable)")
	flags.StringP("privkeys", "k", "", "path to IRMA private keys")
	flags.StringP("url", "u", "", "external URL to server to which the IRMA client connects, \":port\" being replaced by --port value")

	headers["port"] = "Server address and port to listen on"
	flags.IntP("port", "p", 8080, "port at which to listen")
	flags.StringP("listen-addr", "l", "", "address at which to listen (default 0.0.0.0)")

	headers["db-type"] = "Database configuration"
	flags.String("db-type", string(keyshareserver.DBTypePostgres), "Type of database to connect keyshare server to")
	flags.String("db", "", "Database server connection string")

	headers["jwt-privkey"] = "Cryptographic keys"
	flags.String("jwt-privkey", "", "Private jwt key of keyshare server")
	flags.String("jwt-privkey-file", "", "Path to file containing private jwt key of keyshare server")
	flags.Int("jwt-privkey-id", 0, "Key identifier of keyshare server public key matching used private key")
	flags.String("jwt-issuer", keysharecore.JWTIssuerDefault, "JWT issuer used in \"iss\" field")
	flags.Int("jwt-pin-expiry", keysharecore.JWTPinExpiryDefault, "Expiry of PIN JWT in seconds")
	flags.String("storage-primary-keyfile", "", "Primary key used for encrypting and decrypting secure containers")
	flags.StringSlice("storage-fallback-keyfile", nil, "Fallback key(s) used to decrypt older secure containers")

	headers["keyshare-attribute"] = "Keyshare server attribute issued during registration"
	flags.String("keyshare-attribute", "", "Attribute identifier that contains username")

	headers["email-server"] = "Email configuration (leave empty to disable sending emails)"
	flags.String("email-server", "", "Email server to use for sending email address confirmation emails")
	flags.String("email-hostname", "", "Hostname used in email server tls certificate (leave empty when mail server does not use tls)")
	flags.String("email-username", "", "Username to use when authenticating with email server")
	flags.String("email-password", "", "Password to use when authenticating with email server")
	flags.String("email-from", "", "Email address to use as sender address")
	flags.String("default-language", "en", "Default language, used as fallback when users preferred language is not available")
	flags.StringToString("registration-email-subjects", nil, "Translated subject lines for the registration email")
	flags.StringToString("registration-email-files", nil, "Translated emails for the registration email")
	flags.StringToString("verification-url", nil, "Base URL for the email verification link (localized)")

	headers["tls-cert"] = "TLS configuration (leave empty to disable TLS)"
	flags.String("tls-cert", "", "TLS certificate (chain)")
	flags.String("tls-cert-file", "", "path to TLS certificate (chain)")
	flags.String("tls-privkey", "", "TLS private key")
	flags.String("tls-privkey-file", "", "path to TLS private key")
	flags.Bool("no-tls", false, "Disable TLS")

	headers["verbose"] = "Other options"
	flags.CountP("verbose", "v", "verbose (repeatable)")
	flags.BoolP("quiet", "q", false, "quiet")
	flags.Bool("log-json", false, "Log in JSON format")
	flags.Bool("production", false, "Production mode")
}

func configureKeyshareServer(cmd *cobra.Command) (*keyshareserver.Configuration, error) {
	readConfig(cmd, "keyshareserver", "keyshareserver", []string{".", "/etc/keyshareserver"}, nil)

	// And build the configuration
	conf := &keyshareserver.Configuration{
		Configuration:      configureIRMAServer(),
		EmailConfiguration: configureEmail(),

		DBType:    keyshareserver.DBType(viper.GetString("db_type")),
		DBConnStr: viper.GetString("db_str"),

		JwtKeyID:                viper.GetUint32("jwt_privkey_id"),
		JwtPrivateKey:           viper.GetString("jwt_privkey"),
		JwtPrivateKeyFile:       viper.GetString("jwt_privkey_file"),
		JwtIssuer:               viper.GetString("jwt_issuer"),
		JwtPinExpiry:            viper.GetInt("jwt_pin_expiry"),
		StoragePrimaryKeyFile:   viper.GetString("storage_primary_keyfile"),
		StorageFallbackKeyFiles: viper.GetStringSlice("storage_fallback_keyfile"),

		KeyshareAttribute: irma.NewAttributeTypeIdentifier(viper.GetString("keyshare_attribute")),

		RegistrationEmailSubjects: viper.GetStringMapString("registration_email_subjects"),
		RegistrationEmailFiles:    viper.GetStringMapString("registration_email_files"),
		VerificationURL:           viper.GetStringMapString("verification_url"),
	}

	if conf.Production && conf.DBType != keyshareserver.DBTypePostgres {
		return nil, errors.New("in production mode, db-type must be postgres")
	}

	conf.URL = server.ReplacePortString(viper.GetString("url"), viper.GetInt("port"))

	return conf, nil
}
<commit_msg>fix: incorrect conf keys in keyshare server configuration<commit_after>package cmd

import (
	"github.com/go-errors/errors"
	irma "github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/internal/keysharecore"
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/keyshare/keyshareserver"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var keyshareServerCmd = &cobra.Command{
	Use:   "server",
	Short: "IRMA keyshare server",
	Run: func(command *cobra.Command, args []string) {
		conf, err := configureKeyshareServer(command)
		if err != nil {
			die("failed to read configuration", err)
		}

		// Create main server
		keyshareServer, err := keyshareserver.New(conf)
		if err != nil {
			die("", err)
		}

		runServer(keyshareServer, conf.Logger)
	},
}

func init() {
	keyshareRootCmd.AddCommand(keyshareServerCmd)

	keyshareServerCmd.SetUsageTemplate(headerFlagsTemplate)
	headers := map[string]string{}
	flagHeaders["irma keyshare server"] = headers

	flags := keyshareServerCmd.Flags()
	flags.SortFlags = false
	flags.StringP("config", "c", "", "path to configuration file")
	flags.StringP("schemes-path", "s", irma.DefaultSchemesPath(), "path to irma_configuration")
	flags.String("schemes-assets-path", "", "if specified, copy schemes from here into --schemes-path")
	flags.Int("schemes-update", 60, "update IRMA schemes every x minutes (0 to disable)")
	flags.StringP("privkeys", "k", "", "path to IRMA private keys")
	flags.StringP("url", "u", "", "external URL to server to which the IRMA client connects, \":port\" being replaced by --port value")

	headers["port"] = "Server address and port to listen on"
	flags.IntP("port", "p", 8080, "port at which to listen")
	flags.StringP("listen-addr", "l", "", "address at which to listen (default 0.0.0.0)")

	headers["db-type"] = "Database configuration"
	flags.String("db-type", string(keyshareserver.DBTypePostgres), "Type of database to connect keyshare server to")
	flags.String("db", "", "Database server connection string")

	headers["jwt-privkey"] = "Cryptographic keys"
	flags.String("jwt-privkey", "", "Private jwt key of keyshare server")
	flags.String("jwt-privkey-file", "", "Path to file containing private jwt key of keyshare server")
	flags.Int("jwt-privkey-id", 0, "Key identifier of keyshare server public key matching used private key")
	flags.String("jwt-issuer", keysharecore.JWTIssuerDefault, "JWT issuer used in \"iss\" field")
	flags.Int("jwt-pin-expiry", keysharecore.JWTPinExpiryDefault, "Expiry of PIN JWT in seconds")
	flags.String("storage-primary-keyfile", "", "Primary key used for encrypting and decrypting secure containers")
	flags.StringSlice("storage-fallback-keyfile", nil, "Fallback key(s) used to decrypt older secure containers")

	headers["keyshare-attribute"] = "Keyshare server attribute issued during registration"
	flags.String("keyshare-attribute", "", "Attribute identifier that contains username")

	headers["email-server"] = "Email configuration (leave empty to disable sending emails)"
	flags.String("email-server", "", "Email server to use for sending email address confirmation emails")
	flags.String("email-hostname", "", "Hostname used in email server tls certificate (leave empty when mail server does not use tls)")
	flags.String("email-username", "", "Username to use when authenticating with email server")
	flags.String("email-password", "", "Password to use when authenticating with email server")
	flags.String("email-from", "", "Email address to use as sender address")
	flags.String("default-language", "en", "Default language, used as fallback when users preferred language is not available")
	flags.StringToString("registration-email-subjects", nil, "Translated subject lines for the registration email")
	flags.StringToString("registration-email-files", nil, "Translated emails for the registration email")
	flags.StringToString("verification-url", nil, "Base URL for the email verification link (localized)")

	headers["tls-cert"] = "TLS configuration (leave empty to disable TLS)"
	flags.String("tls-cert", "", "TLS certificate (chain)")
	flags.String("tls-cert-file", "", "path to TLS certificate (chain)")
	flags.String("tls-privkey", "", "TLS private key")
	flags.String("tls-privkey-file", "", "path to TLS private key")
	flags.Bool("no-tls", false, "Disable TLS")

	headers["verbose"] = "Other options"
	flags.CountP("verbose", "v", "verbose (repeatable)")
	flags.BoolP("quiet", "q", false, "quiet")
	flags.Bool("log-json", false, "Log in JSON format")
	flags.Bool("production", false, "Production mode")
}

func configureKeyshareServer(cmd *cobra.Command) (*keyshareserver.Configuration, error) {
	readConfig(cmd, "keyshareserver", "keyshareserver", []string{".", "/etc/keyshareserver"}, nil)

	// And build the configuration
	conf := &keyshareserver.Configuration{
		Configuration:      configureIRMAServer(),
		EmailConfiguration: configureEmail(),

		DBType:    keyshareserver.DBType(viper.GetString("db_type")),
		DBConnStr: viper.GetString("db_str"),

		JwtKeyID:                viper.GetUint32("jwt_privkey_id"),
		JwtPrivateKey:           viper.GetString("jwt_privkey"),
		JwtPrivateKeyFile:       viper.GetString("jwt_privkey_file"),
		JwtIssuer:               viper.GetString("jwt_issuer"),
		JwtPinExpiry:            viper.GetInt("jwt_pin_expiry"),
		StoragePrimaryKeyFile:   viper.GetString("storage_primary_key_file"),
		StorageFallbackKeyFiles: viper.GetStringSlice("storage_fallback_key_file"),

		KeyshareAttribute: irma.NewAttributeTypeIdentifier(viper.GetString("keyshare_attribute")),

		RegistrationEmailSubjects: viper.GetStringMapString("registration_email_subjects"),
		RegistrationEmailFiles:    viper.GetStringMapString("registration_email_files"),
		VerificationURL:           viper.GetStringMapString("verification_url"),
	}

	if conf.Production && conf.DBType != keyshareserver.DBTypePostgres {
		return nil, errors.New("in production mode, db-type must be postgres")
	}

	conf.URL = server.ReplacePortString(viper.GetString("url"), viper.GetInt("port"))

	return conf, nil
}
<|endoftext|>


<commit_before>// Package ping tries to ping a HTTP server through different ways
// Connection, Session (Head), Get and Post
package ping

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"regexp"
	"strings"
	"time"

	"github.com/mehrdadrad/mylg/cli"
)

// Ping represents HTTP ping request
type Ping struct {
	url     string
	host    string
	timeout time.Duration
	count   int
	method  string
	buf     string
	rAddr   net.Addr
	nsTime  time.Duration
	conn    net.Conn
}

// Result holds Ping result
type Result struct {
	StatusCode int
	ConnTime   float64
	TotalTime  float64
	Size       int
	Proto      string
	Server     string
	Status     string
}

// NewPing validate and constructs request object
func NewPing(args string, cfg cli.Config) (*Ping, error) {
	URL, flag := cli.Flag(args)
	// help
	if _, ok := flag["help"]; ok || URL == "" {
		help(cfg)
		return nil, fmt.Errorf("")
	}
	URL = Normalize(URL)
	u, err := url.Parse(URL)
	if err != nil {
		return &Ping{}, fmt.Errorf("cannot parse url")
	}
	sTime := time.Now()
	ipAddr, err := net.ResolveIPAddr("ip", u.Host)
	if err != nil {
		return &Ping{}, fmt.Errorf("cannot resolve %s: Unknown host", u.Host)
	}

	p := &Ping{
		url:    URL,
		host:   u.Host,
		rAddr:  ipAddr,
		nsTime: time.Since(sTime),
	}

	// set count
	p.count = cli.SetFlag(flag, "c", cfg.Hping.Count).(int)
	// set timeout
	timeout := cli.SetFlag(flag, "t", cfg.Hping.Timeout).(string)
	p.timeout, err = time.ParseDuration(timeout)
	if err != nil {
		return p, err
	}
	// set method
	p.method = cli.SetFlag(flag, "m", cfg.Hping.Method).(string)
	p.method = strings.ToUpper(p.method)
	// set buff (post)
	buf := cli.SetFlag(flag, "d", "mylg").(string)
	p.buf = buf
	return p, nil
}

// Normalize fixes scheme
func Normalize(URL string) string {
	re := regexp.MustCompile(`(?i)https{0,1}://`)
	if !re.MatchString(URL) {
		URL = fmt.Sprintf("http://%s", URL)
	}
	return URL
}

// Run tries to ping w/ pretty print
func (p *Ping) Run() {
	if p.method != "GET" && p.method != "POST" && p.method != "HEAD" {
		fmt.Printf("Error: Method '%s' not recognized.\n", p.method)
		return
	}
	var (
		sigCh = make(chan os.Signal, 1)
		c     = make(map[int]float64, 10)
		s     []float64
	)
	// capture interrupt w/ s channel
	signal.Notify(sigCh, os.Interrupt)
	defer signal.Stop(sigCh)

	pStrPrefix := "HTTP Response seq=%d, "
	pStrSuffix := "proto=%s, status=%d, size=%d Bytes, time=%.3f ms\n"
	pStrSuffixHead := "proto=%s, status=%d, time=%.3f ms\n"
	fmt.Printf("HPING %s (%s), Method: %s, DNSLookup: %.4f ms\n", p.host, p.rAddr, p.method, p.nsTime.Seconds()*1000)

LOOP:
	for i := 0; i < p.count; i++ {
		if r, err := p.Ping(); err == nil {
			if p.method != "HEAD" {
				fmt.Printf(pStrPrefix+pStrSuffix, i, r.Proto, r.StatusCode, r.Size, r.TotalTime*1000)
			} else {
				fmt.Printf(pStrPrefix+pStrSuffixHead, i, r.Proto, r.StatusCode, r.TotalTime*1000)
			}
			c[r.StatusCode]++
			s = append(s, r.TotalTime*1000)
		} else {
			c[-1]++
			errmsg := strings.Split(err.Error(), ": ")
			fmt.Printf(pStrPrefix+"%s\n", i, errmsg[len(errmsg)-1])
		}
		select {
		case <-sigCh:
			break LOOP
		default:
		}
	}
	// print statistics
	printStats(c, s, p.host)
}

// printStats prints out the footer
func printStats(c map[int]float64, s []float64, host string) {
	var r = make(map[string]float64, 5)

	// total replied requests
	for k, v := range c {
		if k < 0 {
			continue
		}
		r["sum"] += v
	}

	for _, v := range s {
		// maximum
		if r["max"] < v {
			r["max"] = v
		}
		// minimum
		if r["min"] > v || r["min"] == 0 {
			r["min"] = v
		}
		// average
		if r["avg"] == 0 {
			r["avg"] = v
		} else {
			r["avg"] = (r["avg"] + v) / 2
		}
	}

	totalReq := r["sum"] + c[-1]
	failPct := 100 - (100*r["sum"])/totalReq

	fmt.Printf("\n--- %s HTTP ping statistics --- \n", host)
	fmt.Printf("%.0f requests transmitted, %.0f replies received, %.0f%% requests failed\n", totalReq, r["sum"], failPct)
	fmt.Printf("HTTP Round-trip min/avg/max = %.2f/%.2f/%.2f ms\n", r["min"], r["avg"], r["max"])
	for k, v := range c {
		if k < 0 {
			continue
		}
		progress := fmt.Sprintf("%10s", strings.Repeat("\u2588", int(v*100/(r["sum"])/5)))
		fmt.Printf("HTTP Code [%d] responses : [%s] %.2f%% \n", k, progress, v*100/(r["sum"]))
	}
}

// Ping tries to ping a web server through http
func (p *Ping) Ping() (Result, error) {
	var (
		r     Result
		sTime time.Time
		resp  *http.Response
		req   *http.Request
		err   error
	)

	client := &http.Client{Timeout: p.timeout * time.Second}
	sTime = time.Now()

	if p.method == "POST" {
		r.Size = len(p.buf)
		reader := strings.NewReader(p.buf)
		req, err = http.NewRequest(p.method, p.url, reader)
	} else {
		req, err = http.NewRequest(p.method, p.url, nil)
	}

	if err != nil {
		return r, err
	}

	req.Header.Add("User-Agent", "myLG (http://mylg.io)")

	resp, err = client.Do(req)

	if err != nil {
		return r, err
	}

	r.TotalTime = time.Since(sTime).Seconds()

	if p.method == "GET" {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return r, err
		}
		r.Size = len(body)
	}

	r.StatusCode = resp.StatusCode
	r.Proto = resp.Proto
	return r, nil
}

// help shows ping help
func help(cfg cli.Config) {
	fmt.Printf(`
    usage:
          hping url [options]

    options:
          -c count       Send 'count' requests (default: %d)
          -t timeout     Specifies a time limit for requests in ms/s (default is %s)
          -m method      HTTP methods: GET/POST/HEAD (default: %s)
          -d data        Sending the given data (text/json) (default: "%s")
	`,
		cfg.Hping.Count,
		cfg.Hping.Timeout,
		cfg.Hping.Method,
		cfg.Hping.Data)
}
<commit_msg>Fixes timeout in hping so it actually times out if timeout is exceeded. Also improves error-message if syntax of hping.timeout can't be parsed<commit_after>// Package ping tries to ping a HTTP server through different ways
// Connection, Session (Head), Get and Post
package ping

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"regexp"
	"strings"
	"time"

	"github.com/mehrdadrad/mylg/cli"
)

// Ping represents HTTP ping request
type Ping struct {
	url     string
	host    string
	timeout time.Duration
	count   int
	method  string
	buf     string
	rAddr   net.Addr
	nsTime  time.Duration
	conn    net.Conn
}

// Result holds Ping result
type Result struct {
	StatusCode int
	ConnTime   float64
	TotalTime  float64
	Size       int
	Proto      string
	Server     string
	Status     string
}

// NewPing validate and constructs request object
func NewPing(args string, cfg cli.Config) (*Ping, error) {
	URL, flag := cli.Flag(args)
	// help
	if _, ok := flag["help"]; ok || URL == "" {
		help(cfg)
		return nil, fmt.Errorf("")
	}
	URL = Normalize(URL)
	u, err := url.Parse(URL)
	if err != nil {
		return &Ping{}, fmt.Errorf("cannot parse url")
	}
	sTime := time.Now()
	ipAddr, err := net.ResolveIPAddr("ip", u.Host)
	if err != nil {
		return &Ping{}, fmt.Errorf("cannot resolve %s: Unknown host", u.Host)
	}

	p := &Ping{
		url:    URL,
		host:   u.Host,
		rAddr:  ipAddr,
		nsTime: time.Since(sTime),
	}

	// set count
	p.count = cli.SetFlag(flag, "c", cfg.Hping.Count).(int)
	// set timeout
	timeout := cli.SetFlag(flag, "t", cfg.Hping.Timeout).(string)
	p.timeout, err = time.ParseDuration(timeout)
	if err != nil {
		return p, fmt.Errorf("Failed to parse config.hping.timeout: %s. Correct syntax is <number>s/ms", err)
	}
	// set method
	p.method = cli.SetFlag(flag, "m", cfg.Hping.Method).(string)
	p.method = strings.ToUpper(p.method)
	// set buff (post)
	buf := cli.SetFlag(flag, "d", "mylg").(string)
	p.buf = buf
	return p, nil
}

// Normalize fixes scheme
func Normalize(URL string) string {
	re := regexp.MustCompile(`(?i)https{0,1}://`)
	if !re.MatchString(URL) {
		URL = fmt.Sprintf("http://%s", URL)
	}
	return URL
}

// Run tries to ping w/ pretty print
func (p *Ping) Run() {
	if p.method != "GET" && p.method != "POST" && p.method != "HEAD" {
		fmt.Printf("Error: Method '%s' not recognized.\n", p.method)
		return
	}
	var (
		sigCh = make(chan os.Signal, 1)
		c     = make(map[int]float64, 10)
		s     []float64
	)
	// capture interrupt w/ s channel
	signal.Notify(sigCh, os.Interrupt)
	defer signal.Stop(sigCh)

	pStrPrefix := "HTTP Response seq=%d, "
	pStrSuffix := "proto=%s, status=%d, size=%d Bytes, time=%.3f ms\n"
	pStrSuffixHead := "proto=%s, status=%d, time=%.3f ms\n"
	fmt.Printf("HPING %s (%s), Method: %s, DNSLookup: %.4f ms\n", p.host, p.rAddr, p.method, p.nsTime.Seconds()*1000)

LOOP:
	for i := 0; i < p.count; i++ {
		if r, err := p.Ping(); err == nil {
			if p.method != "HEAD" {
				fmt.Printf(pStrPrefix+pStrSuffix, i, r.Proto, r.StatusCode, r.Size, r.TotalTime*1000)
			} else {
				fmt.Printf(pStrPrefix+pStrSuffixHead, i, r.Proto, r.StatusCode, r.TotalTime*1000)
			}
			c[r.StatusCode]++
			s = append(s, r.TotalTime*1000)
		} else {
			c[-1]++
			errmsg := strings.Split(err.Error(), ": ")
			fmt.Printf(pStrPrefix+"%s\n", i, errmsg[len(errmsg)-1])
		}
		select {
		case <-sigCh:
			break LOOP
		default:
		}
	}
	// print statistics
	printStats(c, s, p.host)
}

// printStats prints out the footer
func printStats(c map[int]float64, s []float64, host string) {
	var r = make(map[string]float64, 5)

	// total replied requests
	for k, v := range c {
		if k < 0 {
			continue
		}
		r["sum"] += v
	}

	for _, v := range s {
		// maximum
		if r["max"] < v {
			r["max"] = v
		}
		// minimum
		if r["min"] > v || r["min"] == 0 {
			r["min"] = v
		}
		// average
		if r["avg"] == 0 {
			r["avg"] = v
		} else {
			r["avg"] = (r["avg"] + v) / 2
		}
	}

	totalReq := r["sum"] + c[-1]
	failPct := 100 - (100*r["sum"])/totalReq

	fmt.Printf("\n--- %s HTTP ping statistics --- \n", host)
	fmt.Printf("%.0f requests transmitted, %.0f replies received, %.0f%% requests failed\n", totalReq, r["sum"], failPct)
	fmt.Printf("HTTP Round-trip min/avg/max = %.2f/%.2f/%.2f ms\n", r["min"], r["avg"], r["max"])
	for k, v := range c {
		if k < 0 {
			continue
		}
		progress := fmt.Sprintf("%10s", strings.Repeat("\u2588", int(v*100/(r["sum"])/5)))
		fmt.Printf("HTTP Code [%d] responses : [%s] %.2f%% \n", k, progress, v*100/(r["sum"]))
	}
}

// Ping tries to ping a web server through http
func (p *Ping) Ping() (Result, error) {
	var (
		r     Result
		sTime time.Time
		resp  *http.Response
		req   *http.Request
		err   error
	)

	client := &http.Client{Timeout: p.timeout}
	sTime = time.Now()

	if p.method == "POST" {
		r.Size = len(p.buf)
		reader := strings.NewReader(p.buf)
		req, err = http.NewRequest(p.method, p.url, reader)
	} else {
		req, err = http.NewRequest(p.method, p.url, nil)
	}

	if err != nil {
		return r, err
	}

	req.Header.Add("User-Agent", "myLG (http://mylg.io)")

	resp, err = client.Do(req)

	if err != nil {
		return r, err
	}

	r.TotalTime = time.Since(sTime).Seconds()

	if p.method == "GET" {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return r, err
		}
		r.Size = len(body)
	}

	r.StatusCode = resp.StatusCode
	r.Proto = resp.Proto
	return r, nil
}

// help shows ping help
func help(cfg cli.Config) {
	fmt.Printf(`
    usage:
          hping url [options]

    options:
          -c count       Send 'count' requests (default: %d)
          -t timeout     Specifies a time limit for requests in ms/s (default is %s)
          -m method      HTTP methods: GET/POST/HEAD (default: %s)
          -d data        Sending the given data (text/json) (default: "%s")
	`,
		cfg.Hping.Count,
		cfg.Hping.Timeout,
		cfg.Hping.Method,
		cfg.Hping.Data)
}
<|endoftext|>


<commit_before>package goarmorapi

import (
	"context"
	"encoding/json"
	"errors"
	"strings"
	"time"

	"github.com/armor5games/goarmor/goarmorconfigs"
)

type JSONRequest struct {
	Payload interface{} `json:",omitempty"`
	Time    uint64      `json:",omitempty"`
}

type JSONResponse struct {
	Success bool
	Errors  []*ErrorJSON `json:",omitempty"`
	Payload interface{}  `json:",omitempty"`
	Time    uint64       `json:",omitempty"`
}

type ErrorJSON struct {
	Code uint64
	// TODO: Rename "Error" to "Err"
	Error    error             `json:"Message,omitempty"`
	Public   bool              `json:"-"`
	Severity ErrorJSONSeverity `json:"-"`
}

type ErrorJSONSeverity uint64

const (
	ErrSeverityDebug ErrorJSONSeverity = iota
	ErrSeverityInfo
	ErrSeverityWarn
	ErrSeverityError
	ErrSeverityFatal
	ErrSeverityPanic
)

type ResponseErrorer interface {
	ResponseErrors() []*ErrorJSON
}

func (e *ErrorJSON) MarshalJSON() ([]byte, error) {
	var m string

	if e.Error != nil {
		m = e.Error.Error()
	}

	return json.Marshal(&struct {
		Code    uint64
		Message string `json:",omitempty"`
	}{
		Code:    e.Code,
		Message: m})
}

func (e *ErrorJSON) UnmarshalJSON(b []byte) error {
	s := &struct {
		Code    uint64
		Message string
	}{}

	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	e.Code = s.Code

	if s.Message != "" {
		e.Error = errors.New(s.Message)
	}

	return nil
}

func (j *JSONResponse) KV() (KV, error) {
	if j == nil {
		return nil, errors.New("empty api response")
	}

	if len(j.Errors) == 0 {
		return nil, errors.New("empty key values")
	}

	kv := NewKV()

	for _, e := range j.Errors {
		if e.Code != KVAPIErrorCode {
			continue
		}

		if e.Error.Error() == "" {
			return nil, errors.New("empty kv")
		}

		x := strings.SplitN(e.Error.Error(), ":", 2)
		if len(x) != 2 {
			return nil, errors.New("bad kv format")
		}

		kv[x[0]] = x[1]
	}

	if len(kv) == 0 {
		return nil, errors.New("empty kv")
	}

	return kv, nil
}

func NewJSONRequest(
	ctx context.Context,
	responsePayload interface{}) (*JSONRequest, error) {
	return &JSONRequest{
		Payload: responsePayload,
		Time:    uint64(time.Now().Unix())}, nil
}

func NewJSONResponse(
	ctx context.Context,
	isSuccess bool,
	responsePayload interface{},
	responseErrorer ResponseErrorer,
	errs ...*ErrorJSON) (*JSONResponse, error) {
	publicErrors, err := NewJSONResponseErrors(ctx, responseErrorer, errs...)
	if err != nil {
		return nil, err
	}

	return &JSONResponse{
		Success: isSuccess,
		Errors:  publicErrors,
		Payload: responsePayload,
		Time:    uint64(time.Now().Unix())}, nil
}

func NewJSONResponseErrors(
	ctx context.Context,
	responseErrorer ResponseErrorer,
	errs ...*ErrorJSON) ([]*ErrorJSON, error) {
	config, ok := ctx.Value(CtxKeyConfig).(goarmorconfigs.Configer)
	if !ok {
		return nil, errors.New("context.Value fn error")
	}

	errs = append(errs, responseErrorer.ResponseErrors()...)

	var publicErrors []*ErrorJSON

	if config.ServerDebuggingLevel() > 0 {
		for _, x := range errs {
			publicErrors = append(publicErrors,
				&ErrorJSON{
					Code:     x.Code,
					Error:    errors.New(x.Error.Error()),
					Public:   x.Public,
					Severity: x.Severity})
		}

	} else {
		isKVRemoved := false

		for _, x := range errs {
			if x.Public {
				publicErrors = append(publicErrors,
					&ErrorJSON{
						Code:     x.Code,
						Error:    errors.New(x.Error.Error()),
						Public:   x.Public,
						Severity: x.Severity})

				continue
			}

			if x.Code == KVAPIErrorCode {
				isKVRemoved = true

				continue
			}

			publicErrors = append(publicErrors,
				&ErrorJSON{Code: x.Code, Severity: x.Severity})
		}

		if isKVRemoved {
			// Add empty (only with "code") "ErrorJSON" structure in order to be able to
			// determine was an key-values in hadler's response.
			publicErrors = append(publicErrors, &ErrorJSON{Code: KVAPIErrorCode})
		}
	}

	return publicErrors, nil
}
<commit_msg>minor<commit_after>package goarmorapi

import (
	"context"
	"encoding/json"
	"errors"
	"strings"
	"time"

	"github.com/armor5games/goarmor/goarmorconfigs"
)

type JSONRequest struct {
	Payload interface{} `json:",omitempty"`
	Time    uint64      `json:",omitempty"`
}

type JSONResponse struct {
	Success bool
	Errors  []*ErrorJSON `json:",omitempty"`
	Payload interface{}  `json:",omitempty"`
	Time    uint64       `json:",omitempty"`
}

type ErrorJSON struct {
	Code uint64
	// TODO: Rename "Error" to "Err"
	Error    error             `json:"Message,omitempty"`
	Public   bool              `json:"-"`
	Severity ErrorJSONSeverity `json:"-"`
}

type ErrorJSONSeverity uint64

const (
	ErrSeverityDebug ErrorJSONSeverity = iota
	ErrSeverityInfo
	ErrSeverityWarn
	ErrSeverityError
	ErrSeverityFatal
	ErrSeverityPanic
)

type ResponseErrorer interface {
	ResponseErrors() []*ErrorJSON
}

func (e *ErrorJSON) MarshalJSON() ([]byte, error) {
	var m string

	if e.Error != nil {
		m = e.Error.Error()
	}

	return json.Marshal(&struct {
		Code    uint64
		Message string `json:",omitempty"`
	}{
		Code:    e.Code,
		Message: m})
}

func (e *ErrorJSON) UnmarshalJSON(b []byte) error {
	s := &struct {
		Code    uint64
		Message string
	}{}

	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	e.Code = s.Code

	if s.Message != "" {
		e.Error = errors.New(s.Message)
	}

	return nil
}

func (j *JSONResponse) KV() (KV, error) {
	if j == nil {
		return nil, errors.New("empty api response")
	}

	if len(j.Errors) == 0 {
		return nil, errors.New("empty key values")
	}

	kv := NewKV()

	for _, e := range j.Errors {
		if e.Code != KVAPIErrorCode {
			continue
		}

		if e.Error.Error() == "" {
			return nil, errors.New("empty kv")
		}

		x := strings.SplitN(e.Error.Error(), ":", 2)
		if len(x) != 2 {
			return nil, errors.New("bad kv format")
		}

		kv[x[0]] = x[1]
	}

	if len(kv) == 0 {
		return nil, errors.New("empty kv")
	}

	return kv, nil
}

func NewJSONRequest(
	ctx context.Context,
	responsePayload interface{}) (*JSONRequest, error) {
	return &JSONRequest{
		Payload: responsePayload,
		Time:    uint64(time.Now().Unix())}, nil
}

func NewJSONResponse(
	ctx context.Context,
	isSuccess bool,
	responsePayload interface{},
	responseErrorer ResponseErrorer,
	errs ...*ErrorJSON) (*JSONResponse, error) {
	publicErrors, err := newJSONResponseErrors(ctx, responseErrorer, errs...)
	if err != nil {
		return nil, err
	}

	return &JSONResponse{
		Success: isSuccess,
		Errors:  publicErrors,
		Payload: responsePayload,
		Time:    uint64(time.Now().Unix())}, nil
}

func newJSONResponseErrors(
	ctx context.Context,
	responseErrorer ResponseErrorer,
	errs ...*ErrorJSON) ([]*ErrorJSON, error) {
	config, ok := ctx.Value(CtxKeyConfig).(goarmorconfigs.Configer)
	if !ok {
		return nil, errors.New("context.Value fn error")
	}

	errs = append(errs, responseErrorer.ResponseErrors()...)

	var publicErrors []*ErrorJSON

	if config.ServerDebuggingLevel() > 0 {
		for _, x := range errs {
			publicErrors = append(publicErrors,
				&ErrorJSON{
					Code:     x.Code,
					Error:    errors.New(x.Error.Error()),
					Public:   x.Public,
					Severity: x.Severity})
		}

	} else {
		isKVRemoved := false

		for _, x := range errs {
			if x.Public {
				publicErrors = append(publicErrors,
					&ErrorJSON{
						Code:     x.Code,
						Error:    errors.New(x.Error.Error()),
						Public:   x.Public,
						Severity: x.Severity})

				continue
			}

			if x.Code == KVAPIErrorCode {
				isKVRemoved = true

				continue
			}

			publicErrors = append(publicErrors,
				&ErrorJSON{Code: x.Code, Severity: x.Severity})
		}

		if isKVRemoved {
			// Add empty (only with "code") "ErrorJSON" structure in order to be able to
			// determine was an key-values in hadler's response.
			publicErrors = append(publicErrors, &ErrorJSON{Code: KVAPIErrorCode})
		}
	}

	return publicErrors, nil
}
<|endoftext|>


<commit_before>package dnssec

import (
	"hash/fnv"

	"github.com/miekg/dns"
)

// hash serializes the RRset and returns a signature cache key.
func hash(rrs []dns.RR) uint64 {
	h := fnv.New64()
	buf := make([]byte, 256)
	for _, r := range rrs {
		off, err := dns.PackRR(r, buf, 0, nil, false)
		if err == nil {
			h.Write(buf[:off])
		}
	}

	i := h.Sum64()
	return i
}
<commit_msg>plugin/dnssec: Change hash key input (#4372)<commit_after>package dnssec

import (
	"hash/fnv"
	"io"
	"strconv"
	"strings"

	"github.com/miekg/dns"
)

// hash serializes the RRset and returns a signature cache key.
func hash(rrs []dns.RR) uint64 {
	h := fnv.New64()
	// Only need this to be unique for ownername + qtype (+class), but we
	// only care about IN. Its already an RRSet, so the ownername is the
	// same as is the qtype. Take the first one and construct the hash
	// string that creates the key
	io.WriteString(h, strings.ToLower(rrs[0].Header().Name))
	typ, ok := dns.TypeToString[rrs[0].Header().Rrtype]
	if !ok {
		typ = "TYPE" + strconv.FormatUint(uint64(rrs[0].Header().Rrtype), 10)
	}
	io.WriteString(h, typ)
	i := h.Sum64()
	return i
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"sort"
	"strings"
	"syscall"

	"github.com/mitchellh/osext"
)

const envPrefix = "VAGRANT_OLD_ENV"

func main() {
	debug := os.Getenv("VAGRANT_DEBUG_LAUNCHER") != ""

	// Get the path to the executable. This path doesn't resolve symlinks
	// so we have to do that afterwards to find the real binary.
	path, err := osext.Executable()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to load Vagrant: %s\n", err)
		os.Exit(1)
	}
	if debug {
		log.Printf("launcher: path = %s", path)
	}
	// Retain this path in case we need to re-launch
	launcher_path := path

	for {
		fi, err := os.Lstat(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to stat executable: %s\n", err)
			os.Exit(1)
		}
		if fi.Mode()&os.ModeSymlink == 0 {
			break
		}

		// The executable is a symlink, so resolve it
		path, err = os.Readlink(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to load Vagrant: %s\n", err)
			os.Exit(1)
		}
		if debug {
			log.Printf("launcher: resolved symlink = %s", path)
		}
	}

	// Determine some basic directories that we use throughout
	path = filepath.Dir(filepath.Clean(path))
	installerDir := filepath.Dir(path)
	embeddedDir := filepath.Join(installerDir, "embedded")
	if debug {
		log.Printf("launcher: installerDir = %s", installerDir)
		log.Printf("launcher: embeddedDir = %s", embeddedDir)
	}

	// Find the Vagrant gem
	gemPaths, err := filepath.Glob(
		filepath.Join(embeddedDir, "gems", "gems", "vagrant-*"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to find Vagrant: %s\n", err)
		os.Exit(1)
	}
	if debug {
		log.Printf("launcher: gemPaths (initial) = %#v", gemPaths)
	}
	for i := 0; i < len(gemPaths); i++ {
		fullPath := filepath.Join(gemPaths[i], "lib", "vagrant", "version.rb")
		if _, err := os.Stat(fullPath); err != nil {
			if debug {
				log.Printf("launcher: bad gemPath += %s", fullPath)
			}

			gemPaths = append(gemPaths[:i], gemPaths[i+1:]...)
			i--
		}
	}
	if len(gemPaths) == 0 {
		fmt.Fprintf(os.Stderr, "Failed to find Vagrant!\n")
		os.Exit(1)
	}
	gemPath := gemPaths[len(gemPaths)-1]
	vagrantExecutable := filepath.Join(gemPath, "bin", "vagrant")
	if debug {
		log.Printf("launcher: gemPaths (final) = %#v", gemPaths)
		log.Printf("launcher: gemPath = %s", gemPath)
	}

	// Setup the CPP/LDFLAGS so that native extensions can be
	// properly compiled into the Vagrant environment.
	cppflags := ""
	cflags := ""
	ldflags := ""
	mingwArchDir := "x86_64-w64-mingw32"
	mingwDir := "mingw64"
	if runtime.GOOS == "windows" {
		// Check if we are in a 32bit or 64bit install
		mingwTestPath := filepath.Join(embeddedDir, "mingw64")
		if _, err := os.Stat(mingwTestPath); err != nil {
			log.Printf("launcher: detected 32bit Windows installation")
			mingwDir = "mingw32"
			mingwArchDir = "i686-w64-mingw32"
		}
		cflags := "-I" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "include") +
			" -I" + filepath.Join(embeddedDir, mingwDir, "include") +
			" -I" + filepath.Join(embeddedDir, "usr", "include")
		cppflags := "-I" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "include") +
			" -I" + filepath.Join(embeddedDir, mingwDir, "include") +
			" -I" + filepath.Join(embeddedDir, "usr", "include")
		ldflags := "-L" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "lib") +
			" -L" + filepath.Join(embeddedDir, mingwDir, "lib") +
			" -L" + filepath.Join(embeddedDir, "usr", "lib")
		if original := os.Getenv("CFLAGS"); original != "" {
			cflags = original + " " + cflags
		}
		if original := os.Getenv("CPPFLAGS"); original != "" {
			cppflags = original + " " + cppflags
		}
		if original := os.Getenv("LDFLAGS"); original != "" {
			ldflags = original + " " + ldflags
		}
	} else {
		cppflags := "-I" + filepath.Join(embeddedDir, "include") +
			" -I" + filepath.Join(embeddedDir, "include", "libxml2")
		ldflags := "-L" + filepath.Join(embeddedDir, "lib")
		if original := os.Getenv("CPPFLAGS"); original != "" {
			cppflags = original + " " + cppflags
		}
		if original := os.Getenv("LDFLAGS"); original != "" {
			ldflags = original + " " + ldflags
		}
		cflags := "-I" + filepath.Join(embeddedDir, "include") +
			" -I" + filepath.Join(embeddedDir, "include", "libxml2")
		if original := os.Getenv("CFLAGS"); original != "" {
			cflags = original + " " + cflags
		}
	}

	// Set the PATH to include the proper paths into our embedded dir
	path = os.Getenv("PATH")
	if runtime.GOOS == "windows" {
		path = fmt.Sprintf(
			"%s;%s;%s",
			filepath.Join(embeddedDir, mingwDir, "bin"),
			filepath.Join(embeddedDir, "usr", "bin"),
			path)
	} else {
		path = fmt.Sprintf("%s:%s",
			filepath.Join(embeddedDir, "bin"), path)
	}

	// Allow users to specify a custom SSL cert
	sslCertFile := os.Getenv("SSL_CERT_FILE")
	if sslCertFile == "" {
		sslCertFile = filepath.Join(embeddedDir, "cacert.pem")
	}

	newEnv := map[string]string{
		// Setup the environment to prefer our embedded dir over
		// anything the user might have setup on his/her system.
		"CPPFLAGS":      cppflags,
		"CFLAGS":        cflags,
		"GEM_HOME":      filepath.Join(embeddedDir, "gems"),
		"GEM_PATH":      filepath.Join(embeddedDir, "gems"),
		"GEMRC":         filepath.Join(embeddedDir, "etc", "gemrc"),
		"LDFLAGS":       ldflags,
		"PATH":          path,
		"SSL_CERT_FILE": sslCertFile,

		// Instruct nokogiri installations to use libraries provided
		// by the installer
		"NOKOGIRI_USE_SYSTEM_LIBRARIES": "true",

		// Environmental variables used by Vagrant itself
		"VAGRANT_EXECUTABLE":             vagrantExecutable,
		"VAGRANT_INSTALLER_ENV":          "1",
		"VAGRANT_INSTALLER_EMBEDDED_DIR": embeddedDir,
		"VAGRANT_INSTALLER_VERSION":      "2",
	}

	// Unset any RUBYOPT, we don't want this bleeding into our runtime
	newEnv["RUBYOPT"] = ""
	// Unset any RUBYLIB, we don't want this bleeding into our runtime
	newEnv["RUBYLIB"] = ""

	if runtime.GOOS == "darwin" {
		configure_args := "-Wl,rpath," + filepath.Join(embeddedDir, "lib")
		if original_configure_args := os.Getenv("CONFIGURE_ARGS"); original_configure_args != "" {
			configure_args = original_configure_args + " " + configure_args
		}
		newEnv["CONFIGURE_ARGS"] = configure_args
	}

	// Set pkg-config paths
	if runtime.GOOS == "windows" {
		newEnv["PKG_CONFIG_PATH"] = filepath.Join(embeddedDir, mingwDir, "lib", "pkgconfig") +
			":" + filepath.Join(embeddedDir, "usr", "lib", "pkgconfig")
	} else {
		newEnv["PKG_CONFIG_PATH"] = filepath.Join(embeddedDir, "lib", "pkgconfig")
	}

	// Detect custom windows environment (cygwin/msys/etc)
	if runtime.GOOS == "windows" {
		// If VAGRANT_DETECTED_OS is provided by the user let that value
		// take precedence over any discovery.
		if os.Getenv("VAGRANT_DETECTED_OS") != "" {
			newEnv["VAGRANT_DETECTED_OS"] = os.Getenv("VAGRANT_DETECTED_OS")
		} else if os.Getenv("OSTYPE") != "" {
			newEnv["VAGRANT_DETECTED_OS"] = os.Getenv("OSTYPE")
		} else {
			uname, err := exec.Command("uname", "-o").Output()
			if err == nil {
				newEnv["VAGRANT_DETECTED_OS"] = strings.ToLower(strings.Replace(fmt.Sprintf("%s", uname), "\n", "", -1))
			}
		}
		if debug && newEnv["VAGRANT_DETECTED_OS"] != "" {
			log.Printf("launcher: windows detected OS - %s", newEnv["VAGRANT_DETECTED_OS"])
		}
	}

	// Store the "current" environment so Vagrant can restore it when shelling
	// out.
	for _, value := range os.Environ() {
		idx := strings.IndexRune(value, '=')
		key := fmt.Sprintf("%s_%s", envPrefix, value[:idx])
		newEnv[key] = value[idx+1:]
	}
	if debug {
		keys := make([]string, 0, len(newEnv))
		for k, _ := range newEnv {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		for _, k := range keys {
			log.Printf("launcher: env %q = %q", k, newEnv[k])
		}
	}

	// Determine the path to Ruby and then start the Vagrant process
	rubyPath := filepath.Join(embeddedDir, "bin", "ruby")
	if runtime.GOOS == "windows" {
		rubyPath = filepath.Join(embeddedDir, mingwDir, "bin", "ruby") + ".exe"
	}

	// Prior to starting the command, we ignore interrupts. Vagrant itself
	// handles these, so the launcher should just wait until that exits.
	signal.Ignore(os.Interrupt)

	// Check if running within a cygwin or msys type environment on Windows. If
	// we are, then wrap the execution with winpty to properly provide terminal
	// support to Vagrant. Without this we get the ever loved "stdin is not a tty"
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" && os.Getenv("VAGRANT_WINPTY_WRAPPED") != "1" &&
		(newEnv["VAGRANT_DETECTED_OS"] == "msys" || newEnv["VAGRANT_DETECTED_OS"] == "cygwin") {
		os.Setenv("VAGRANT_WINPTY_WRAPPED", "1")
		winptyPath := filepath.Join(embeddedDir, "bin", newEnv["VAGRANT_DETECTED_OS"], "winpty.exe")
		cmd = exec.Command(winptyPath)
		cmd.Args = make([]string, len(os.Args)+1)
		cmd.Args[0] = "winpty"
		cmd.Args[1] = launcher_path
		copy(cmd.Args[2:], os.Args[1:])
		if debug {
			log.Printf("launcher: winpty re-launch (stdin will be a tty!)")
			log.Printf("launcher: winptyPath = %s", winptyPath)
		}
	} else {
		// Set all the environmental variables
		for k, v := range newEnv {
			if err := os.Setenv(k, v); err != nil {
				fmt.Fprintf(os.Stderr, "Error setting env var %s: %s\n", k, err)
				os.Exit(1)
			}
		}

		cmd = exec.Command(rubyPath)
		cmd.Args = make([]string, len(os.Args)+1)
		cmd.Args[0] = "ruby"
		cmd.Args[1] = vagrantExecutable
		copy(cmd.Args[2:], os.Args[1:])
		if debug {
			log.Printf("launcher: rubyPath = %s", rubyPath)
		}
	}

	if debug {
		log.Printf("launcher: args = %#v", cmd.Args)
	}

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Start(); err != nil {
		fmt.Fprintf(os.Stderr, "Exec error: %s\n", err)
		os.Exit(1)
	}

	exitCode := 0
	if err := cmd.Wait(); err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			// The program has exited with an exit code != 0

			// This works on both Unix and Windows. Although package
			// syscall is generally platform dependent, WaitStatus is
			// defined for both Unix and Windows and in both cases has
			// an ExitStatus() method with the same signature.
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				exitCode = status.ExitStatus()
			}
		}
	}

	os.Exit(exitCode)
}
<commit_msg>Only print debug output when debug is enabled<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"sort"
	"strings"
	"syscall"

	"github.com/mitchellh/osext"
)

const envPrefix = "VAGRANT_OLD_ENV"

func main() {
	debug := os.Getenv("VAGRANT_DEBUG_LAUNCHER") != ""

	// Get the path to the executable. This path doesn't resolve symlinks
	// so we have to do that afterwards to find the real binary.
	path, err := osext.Executable()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to load Vagrant: %s\n", err)
		os.Exit(1)
	}
	if debug {
		log.Printf("launcher: path = %s", path)
	}
	// Retain this path in case we need to re-launch
	launcher_path := path

	for {
		fi, err := os.Lstat(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to stat executable: %s\n", err)
			os.Exit(1)
		}
		if fi.Mode()&os.ModeSymlink == 0 {
			break
		}

		// The executable is a symlink, so resolve it
		path, err = os.Readlink(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to load Vagrant: %s\n", err)
			os.Exit(1)
		}
		if debug {
			log.Printf("launcher: resolved symlink = %s", path)
		}
	}

	// Determine some basic directories that we use throughout
	path = filepath.Dir(filepath.Clean(path))
	installerDir := filepath.Dir(path)
	embeddedDir := filepath.Join(installerDir, "embedded")
	if debug {
		log.Printf("launcher: installerDir = %s", installerDir)
		log.Printf("launcher: embeddedDir = %s", embeddedDir)
	}

	// Find the Vagrant gem
	gemPaths, err := filepath.Glob(
		filepath.Join(embeddedDir, "gems", "gems", "vagrant-*"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to find Vagrant: %s\n", err)
		os.Exit(1)
	}
	if debug {
		log.Printf("launcher: gemPaths (initial) = %#v", gemPaths)
	}
	for i := 0; i < len(gemPaths); i++ {
		fullPath := filepath.Join(gemPaths[i], "lib", "vagrant", "version.rb")
		if _, err := os.Stat(fullPath); err != nil {
			if debug {
				log.Printf("launcher: bad gemPath += %s", fullPath)
			}

			gemPaths = append(gemPaths[:i], gemPaths[i+1:]...)
			i--
		}
	}
	if len(gemPaths) == 0 {
		fmt.Fprintf(os.Stderr, "Failed to find Vagrant!\n")
		os.Exit(1)
	}
	gemPath := gemPaths[len(gemPaths)-1]
	vagrantExecutable := filepath.Join(gemPath, "bin", "vagrant")
	if debug {
		log.Printf("launcher: gemPaths (final) = %#v", gemPaths)
		log.Printf("launcher: gemPath = %s", gemPath)
	}

	// Setup the CPP/LDFLAGS so that native extensions can be
	// properly compiled into the Vagrant environment.
	cppflags := ""
	cflags := ""
	ldflags := ""
	mingwArchDir := "x86_64-w64-mingw32"
	mingwDir := "mingw64"
	if runtime.GOOS == "windows" {
		// Check if we are in a 32bit or 64bit install
		mingwTestPath := filepath.Join(embeddedDir, "mingw64")
		if _, err := os.Stat(mingwTestPath); err != nil {
			if debug {
				log.Printf("launcher: detected 32bit Windows installation")
			}
			mingwDir = "mingw32"
			mingwArchDir = "i686-w64-mingw32"
		}
		cflags := "-I" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "include") +
			" -I" + filepath.Join(embeddedDir, mingwDir, "include") +
			" -I" + filepath.Join(embeddedDir, "usr", "include")
		cppflags := "-I" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "include") +
			" -I" + filepath.Join(embeddedDir, mingwDir, "include") +
			" -I" + filepath.Join(embeddedDir, "usr", "include")
		ldflags := "-L" + filepath.Join(embeddedDir, mingwDir, mingwArchDir, "lib") +
			" -L" + filepath.Join(embeddedDir, mingwDir, "lib") +
			" -L" + filepath.Join(embeddedDir, "usr", "lib")
		if original := os.Getenv("CFLAGS"); original != "" {
			cflags = original + " " + cflags
		}
		if original := os.Getenv("CPPFLAGS"); original != "" {
			cppflags = original + " " + cppflags
		}
		if original := os.Getenv("LDFLAGS"); original != "" {
			ldflags = original + " " + ldflags
		}
	} else {
		cppflags := "-I" + filepath.Join(embeddedDir, "include") +
			" -I" + filepath.Join(embeddedDir, "include", "libxml2")
		ldflags := "-L" + filepath.Join(embeddedDir, "lib")
		if original := os.Getenv("CPPFLAGS"); original != "" {
			cppflags = original + " " + cppflags
		}
		if original := os.Getenv("LDFLAGS"); original != "" {
			ldflags = original + " " + ldflags
		}
		cflags := "-I" + filepath.Join(embeddedDir, "include") +
			" -I" + filepath.Join(embeddedDir, "include", "libxml2")
		if original := os.Getenv("CFLAGS"); original != "" {
			cflags = original + " " + cflags
		}
	}

	// Set the PATH to include the proper paths into our embedded dir
	path = os.Getenv("PATH")
	if runtime.GOOS == "windows" {
		path = fmt.Sprintf(
			"%s;%s;%s",
			filepath.Join(embeddedDir, mingwDir, "bin"),
			filepath.Join(embeddedDir, "usr", "bin"),
			path)
	} else {
		path = fmt.Sprintf("%s:%s",
			filepath.Join(embeddedDir, "bin"), path)
	}

	// Allow users to specify a custom SSL cert
	sslCertFile := os.Getenv("SSL_CERT_FILE")
	if sslCertFile == "" {
		sslCertFile = filepath.Join(embeddedDir, "cacert.pem")
	}

	newEnv := map[string]string{
		// Setup the environment to prefer our embedded dir over
		// anything the user might have setup on his/her system.
		"CPPFLAGS":      cppflags,
		"CFLAGS":        cflags,
		"GEM_HOME":      filepath.Join(embeddedDir, "gems"),
		"GEM_PATH":      filepath.Join(embeddedDir, "gems"),
		"GEMRC":         filepath.Join(embeddedDir, "etc", "gemrc"),
		"LDFLAGS":       ldflags,
		"PATH":          path,
		"SSL_CERT_FILE": sslCertFile,

		// Instruct nokogiri installations to use libraries provided
		// by the installer
		"NOKOGIRI_USE_SYSTEM_LIBRARIES": "true",

		// Environmental variables used by Vagrant itself
		"VAGRANT_EXECUTABLE":             vagrantExecutable,
		"VAGRANT_INSTALLER_ENV":          "1",
		"VAGRANT_INSTALLER_EMBEDDED_DIR": embeddedDir,
		"VAGRANT_INSTALLER_VERSION":      "2",
	}

	// Unset any RUBYOPT, we don't want this bleeding into our runtime
	newEnv["RUBYOPT"] = ""
	// Unset any RUBYLIB, we don't want this bleeding into our runtime
	newEnv["RUBYLIB"] = ""

	if runtime.GOOS == "darwin" {
		configure_args := "-Wl,rpath," + filepath.Join(embeddedDir, "lib")
		if original_configure_args := os.Getenv("CONFIGURE_ARGS"); original_configure_args != "" {
			configure_args = original_configure_args + " " + configure_args
		}
		newEnv["CONFIGURE_ARGS"] = configure_args
	}

	// Set pkg-config paths
	if runtime.GOOS == "windows" {
		newEnv["PKG_CONFIG_PATH"] = filepath.Join(embeddedDir, mingwDir, "lib", "pkgconfig") +
			":" + filepath.Join(embeddedDir, "usr", "lib", "pkgconfig")
	} else {
		newEnv["PKG_CONFIG_PATH"] = filepath.Join(embeddedDir, "lib", "pkgconfig")
	}

	// Detect custom windows environment (cygwin/msys/etc)
	if runtime.GOOS == "windows" {
		// If VAGRANT_DETECTED_OS is provided by the user let that value
		// take precedence over any discovery.
		if os.Getenv("VAGRANT_DETECTED_OS") != "" {
			newEnv["VAGRANT_DETECTED_OS"] = os.Getenv("VAGRANT_DETECTED_OS")
		} else if os.Getenv("OSTYPE") != "" {
			newEnv["VAGRANT_DETECTED_OS"] = os.Getenv("OSTYPE")
		} else {
			uname, err := exec.Command("uname", "-o").Output()
			if err == nil {
				newEnv["VAGRANT_DETECTED_OS"] = strings.ToLower(strings.Replace(fmt.Sprintf("%s", uname), "\n", "", -1))
			}
		}
		if debug && newEnv["VAGRANT_DETECTED_OS"] != "" {
			log.Printf("launcher: windows detected OS - %s", newEnv["VAGRANT_DETECTED_OS"])
		}
	}

	// Store the "current" environment so Vagrant can restore it when shelling
	// out.
	for _, value := range os.Environ() {
		idx := strings.IndexRune(value, '=')
		key := fmt.Sprintf("%s_%s", envPrefix, value[:idx])
		newEnv[key] = value[idx+1:]
	}
	if debug {
		keys := make([]string, 0, len(newEnv))
		for k, _ := range newEnv {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		for _, k := range keys {
			log.Printf("launcher: env %q = %q", k, newEnv[k])
		}
	}

	// Determine the path to Ruby and then start the Vagrant process
	rubyPath := filepath.Join(embeddedDir, "bin", "ruby")
	if runtime.GOOS == "windows" {
		rubyPath = filepath.Join(embeddedDir, mingwDir, "bin", "ruby") + ".exe"
	}

	// Prior to starting the command, we ignore interrupts. Vagrant itself
	// handles these, so the launcher should just wait until that exits.
	signal.Ignore(os.Interrupt)

	// Check if running within a cygwin or msys type environment on Windows. If
	// we are, then wrap the execution with winpty to properly provide terminal
	// support to Vagrant. Without this we get the ever loved "stdin is not a tty"
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" && os.Getenv("VAGRANT_WINPTY_WRAPPED") != "1" &&
		(newEnv["VAGRANT_DETECTED_OS"] == "msys" || newEnv["VAGRANT_DETECTED_OS"] == "cygwin") {
		os.Setenv("VAGRANT_WINPTY_WRAPPED", "1")
		winptyPath := filepath.Join(embeddedDir, "bin", newEnv["VAGRANT_DETECTED_OS"], "winpty.exe")
		cmd = exec.Command(winptyPath)
		cmd.Args = make([]string, len(os.Args)+1)
		cmd.Args[0] = "winpty"
		cmd.Args[1] = launcher_path
		copy(cmd.Args[2:], os.Args[1:])
		if debug {
			log.Printf("launcher: winpty re-launch (stdin will be a tty!)")
			log.Printf("launcher: winptyPath = %s", winptyPath)
		}
	} else {
		// Set all the environmental variables
		for k, v := range newEnv {
			if err := os.Setenv(k, v); err != nil {
				fmt.Fprintf(os.Stderr, "Error setting env var %s: %s\n", k, err)
				os.Exit(1)
			}
		}

		cmd = exec.Command(rubyPath)
		cmd.Args = make([]string, len(os.Args)+1)
		cmd.Args[0] = "ruby"
		cmd.Args[1] = vagrantExecutable
		copy(cmd.Args[2:], os.Args[1:])
		if debug {
			log.Printf("launcher: rubyPath = %s", rubyPath)
		}
	}

	if debug {
		log.Printf("launcher: args = %#v", cmd.Args)
	}

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Start(); err != nil {
		fmt.Fprintf(os.Stderr, "Exec error: %s\n", err)
		os.Exit(1)
	}

	exitCode := 0
	if err := cmd.Wait(); err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			// The program has exited with an exit code != 0

			// This works on both Unix and Windows. Although package
			// syscall is generally platform dependent, WaitStatus is
			// defined for both Unix and Windows and in both cases has
			// an ExitStatus() method with the same signature.
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				exitCode = status.ExitStatus()
			}
		}
	}

	os.Exit(exitCode)
}
<|endoftext|>


<commit_before>package paillier

import (
	"crypto/rand"
	"errors"
	"io"
	"math/big"
	"time"
)

// Generates a threshold Paillier key with an algorithm based on [DJN 10],
// section 5.1, "Key generation".
//
// Bear in mind that the algorithm assumes an existence of a trusted dealer
// to generate and distribute the keys.
//
//
//     [DJN 10]: Ivan Damgard, Mads Jurik, Jesper Buus Nielsen, (2010)
//               A Generalization of Paillier’s Public-Key System
//               with Applications to Electronic Voting
//               Aarhus University, Dept. of Computer Science, BRICS
type ThresholdKeyGenerator struct {
	publicKeyBitLength             int
	TotalNumberOfDecryptionServers int
	Threshold                      int
	Random                         io.Reader

	// Both p1 and q1 are primes of length nbits - 1
	p1 *big.Int
	q1 *big.Int

	p       *big.Int // p is prime and p=2*p1+1
	q       *big.Int // q is prime and q=2*q1+1
	n       *big.Int // n=p*q
	m       *big.Int // m = p1*q1
	nSquare *big.Int // nSquare = n*n
	nm      *big.Int // nm = n*m

	// As specified in the paper, d must satify d=1 mod n and d=0 mod m
	d *big.Int

	// A generator of QR in Z_{n^2}
	v *big.Int

	// The polynomial coefficients to hide a secret. See Shamir.
	polynomialCoefficients []*big.Int
}

// GetThresholdKeyGenerator is a preferable way to construct the
// ThresholdKeyGenerator.
// Due to the various properties that must be met for the threshold key to be
// considered valid, the minimum public key `N` bit length is 18 bits and the
// public key bit length should be an even number.
// The plaintext space for the key will be `Z_N`.
func GetThresholdKeyGenerator(
	publicKeyBitLength int,
	totalNumberOfDecryptionServers int,
	threshold int,
	random io.Reader,
) (*ThresholdKeyGenerator, error) {
	if publicKeyBitLength%2 == 1 {
		// For an odd n-bit number, we can't find two n-1-bit numbers which
		// multiplied gives an n-bit number.
		return nil, errors.New("Public key bit length must be an even number")
	}
	if publicKeyBitLength < 18 {
		// We need to find two n-1-bit safe primes, P and Q which are not equal.
		// This is not possible for n<18.
		return nil, errors.New("Public key bit length must be at least 18 bits")
	}

	generator := new(ThresholdKeyGenerator)
	generator.publicKeyBitLength = publicKeyBitLength
	generator.TotalNumberOfDecryptionServers = totalNumberOfDecryptionServers
	generator.Threshold = threshold
	generator.Random = random
	return generator, nil
}

func (tkg *ThresholdKeyGenerator) generateSafePrimes() (*big.Int, *big.Int, error) {
	concurrencyLevel := 4
	timeout := 120 * time.Second
	safePrimeBitLength := tkg.publicKeyBitLength / 2

	return GenerateSafePrime(safePrimeBitLength, concurrencyLevel, timeout, tkg.Random)
}

func (tkg *ThresholdKeyGenerator) initPandP1() error {
	var err error
	tkg.p, tkg.p1, err = tkg.generateSafePrimes()
	return err
}

func (tkg *ThresholdKeyGenerator) initQandQ1() error {
	var err error
	tkg.q, tkg.q1, err = tkg.generateSafePrimes()
	return err
}

func (tkg *ThresholdKeyGenerator) initShortcuts() {
	tkg.n = new(big.Int).Mul(tkg.p, tkg.q)
	tkg.m = new(big.Int).Mul(tkg.p1, tkg.q1)
	tkg.nSquare = new(big.Int).Mul(tkg.n, tkg.n)
	tkg.nm = new(big.Int).Mul(tkg.n, tkg.m)
}

func (tkg *ThresholdKeyGenerator) arePsAndQsGood() bool {
	if tkg.p.Cmp(tkg.q) == 0 {
		return false
	}
	if tkg.p.Cmp(tkg.q1) == 0 {
		return false
	}
	if tkg.p1.Cmp(tkg.q) == 0 {
		return false
	}
	return true
}

func (tkg *ThresholdKeyGenerator) initPsAndQs() error {
	if err := tkg.initPandP1(); err != nil {
		return err
	}
	if err := tkg.initQandQ1(); err != nil {
		return err
	}
	if !tkg.arePsAndQsGood() {
		return tkg.initPsAndQs()
	}
	return nil
}

// v generates a cyclic group of squares in Zn^2.
func (tkg *ThresholdKeyGenerator) computeV() error {
	var err error
	tkg.v, err = GetRandomGeneratorOfTheQuadraticResidue(tkg.nSquare, tkg.Random)
	return err
}

// Choose d such that d=0 (mod m) and d=1 (mod n).
//
// From Chinese Remainder Theorem:
// x = a1 (mod n1)
// x = a2 (mod n2)
//
// N = n1*n2
// y1 = N/n1
// y2 = N/n2
// z1 = y1^-1 mod n1
// z2 = y2^-1 mod n2
// Solution is x = a1*y1*z1 + a2*y2*z2
//
// In our case:
// x = 0 (mod m)
// x = 1 (mod n)
//
// Since a1 = 0, it's enough to compute a2*y2*z2 to get x.
//
// a2 = 1
// y2 = mn/n = m
// z2 = m^-1 mod n
//
// x = a2*y2*z2 = 1 * m * [m^-1 mod n]
func (tkg *ThresholdKeyGenerator) initD() {
	mInverse := new(big.Int).ModInverse(tkg.m, tkg.n)
	tkg.d = new(big.Int).Mul(mInverse, tkg.m)
}

func (tkg *ThresholdKeyGenerator) initNumerialValues() error {
	if err := tkg.initPsAndQs(); err != nil {
		return err
	}
	tkg.initShortcuts()
	tkg.initD()
	return tkg.computeV()
}

// f(X) = a_0 X^0 + a_1 X^1 + ... + a_(w-1) X^(w-1)
//
// where:
// `w` - threshold
// `a_i` - random value from {0, ... nm - 1} for 0<i<w
// `a_0` is always equal `d`
func (tkg *ThresholdKeyGenerator) generateHidingPolynomial() error {
	tkg.polynomialCoefficients = make([]*big.Int, tkg.Threshold)
	tkg.polynomialCoefficients[0] = tkg.d
	var err error
	for i := 1; i < tkg.Threshold; i++ {
		tkg.polynomialCoefficients[i], err = rand.Int(tkg.Random, tkg.nm)
		if err != nil {
			return err
		}
	}
	return nil
}

// The secred share of the i'th authority is `f(i) mod nm`, where `f` is
// the polynomial we generated in `GenerateHidingPolynomial` function.
func (tkg *ThresholdKeyGenerator) computeShare(index int) *big.Int {
	share := big.NewInt(0)
	for i := 0; i < tkg.Threshold; i++ {
		a := tkg.polynomialCoefficients[i]
		// we index authorities from 1, that's why we do index+1 here
		b := new(big.Int).Exp(big.NewInt(int64(index+1)), big.NewInt(int64(i)), nil)
		tmp := new(big.Int).Mul(a, b)
		share = new(big.Int).Add(share, tmp)
	}
	return new(big.Int).Mod(share, tkg.nm)
}

func (tkg *ThresholdKeyGenerator) createShares() []*big.Int {
	shares := make([]*big.Int, tkg.TotalNumberOfDecryptionServers)
	for i := 0; i < tkg.TotalNumberOfDecryptionServers; i++ {
		shares[i] = tkg.computeShare(i)
	}
	return shares
}

func (tkg *ThresholdKeyGenerator) delta() *big.Int {
	return Factorial(tkg.TotalNumberOfDecryptionServers)
}

// Generates verification keys for actions of decryption servers.
//
// For each decryption server `i`, we generate
// v_i = v^(l! s_i) mod n^2
//
// where:
// `l` is the number of decryption servers
// `s_i` is a secret share for server `i`.
// Secret shares were previously generated in the `CrateShares` function.
func (tkg *ThresholdKeyGenerator) createViArray(shares []*big.Int) (viArray []*big.Int) {
	viArray = make([]*big.Int, len(shares))
	delta := tkg.delta()
	for i, share := range shares {
		tmp := new(big.Int).Mul(share, delta)
		viArray[i] = new(big.Int).Exp(tkg.v, tmp, tkg.nSquare)
	}
	return viArray
}

func (tkg *ThresholdKeyGenerator) createPrivateKey(i int, share *big.Int, viArray []*big.Int) *ThresholdPrivateKey {
	ret := new(ThresholdPrivateKey)
	ret.N = tkg.n
	ret.V = tkg.v

	ret.TotalNumberOfDecryptionServers = tkg.TotalNumberOfDecryptionServers
	ret.Threshold = tkg.Threshold
	ret.Share = share
	ret.Id = i + 1
	ret.Vi = viArray
	return ret
}

func (tkg *ThresholdKeyGenerator) createPrivateKeys() []*ThresholdPrivateKey {
	shares := tkg.createShares()
	viArray := tkg.createViArray(shares)
	ret := make([]*ThresholdPrivateKey, tkg.TotalNumberOfDecryptionServers)
	for i := 0; i < tkg.TotalNumberOfDecryptionServers; i++ {
		ret[i] = tkg.createPrivateKey(i, shares[i], viArray)
	}
	return ret
}

func (tkg *ThresholdKeyGenerator) Generate() ([]*ThresholdPrivateKey, error) {
	if err := tkg.initNumerialValues(); err != nil {
		return nil, err
	}
	if err := tkg.generateHidingPolynomial(); err != nil {
		return nil, err
	}
	return tkg.createPrivateKeys(), nil
}
<commit_msg>Create and return ThresholdKeyGenerator in one shot.<commit_after>package paillier

import (
	"crypto/rand"
	"errors"
	"io"
	"math/big"
	"time"
)

// Generates a threshold Paillier key with an algorithm based on [DJN 10],
// section 5.1, "Key generation".
//
// Bear in mind that the algorithm assumes an existence of a trusted dealer
// to generate and distribute the keys.
//
//
//     [DJN 10]: Ivan Damgard, Mads Jurik, Jesper Buus Nielsen, (2010)
//               A Generalization of Paillier’s Public-Key System
//               with Applications to Electronic Voting
//               Aarhus University, Dept. of Computer Science, BRICS
type ThresholdKeyGenerator struct {
	publicKeyBitLength             int
	TotalNumberOfDecryptionServers int
	Threshold                      int
	Random                         io.Reader

	// Both p1 and q1 are primes of length nbits - 1
	p1 *big.Int
	q1 *big.Int

	p       *big.Int // p is prime and p=2*p1+1
	q       *big.Int // q is prime and q=2*q1+1
	n       *big.Int // n=p*q
	m       *big.Int // m = p1*q1
	nSquare *big.Int // nSquare = n*n
	nm      *big.Int // nm = n*m

	// As specified in the paper, d must satify d=1 mod n and d=0 mod m
	d *big.Int

	// A generator of QR in Z_{n^2}
	v *big.Int

	// The polynomial coefficients to hide a secret. See Shamir.
	polynomialCoefficients []*big.Int
}

// GetThresholdKeyGenerator is a preferable way to construct the
// ThresholdKeyGenerator.
// Due to the various properties that must be met for the threshold key to be
// considered valid, the minimum public key `N` bit length is 18 bits and the
// public key bit length should be an even number.
// The plaintext space for the key will be `Z_N`.
func GetThresholdKeyGenerator(
	publicKeyBitLength int,
	totalNumberOfDecryptionServers int,
	threshold int,
	random io.Reader,
) (*ThresholdKeyGenerator, error) {
	if publicKeyBitLength%2 == 1 {
		// For an odd n-bit number, we can't find two n-1-bit numbers which
		// multiplied gives an n-bit number.
		return nil, errors.New("Public key bit length must be an even number")
	}
	if publicKeyBitLength < 18 {
		// We need to find two n-1-bit safe primes, P and Q which are not equal.
		// This is not possible for n<18.
		return nil, errors.New("Public key bit length must be at least 18 bits")
	}

	return &ThresholdKeyGenerator{
		publicKeyBitLength:             publicKeyBitLength,
		TotalNumberOfDecryptionServers: totalNumberOfDecryptionServers,
		Threshold:                      threshold,
		Random:                         random,
	}, nil
}

func (tkg *ThresholdKeyGenerator) generateSafePrimes() (*big.Int, *big.Int, error) {
	concurrencyLevel := 4
	timeout := 120 * time.Second
	safePrimeBitLength := tkg.publicKeyBitLength / 2

	return GenerateSafePrime(safePrimeBitLength, concurrencyLevel, timeout, tkg.Random)
}

func (tkg *ThresholdKeyGenerator) initPandP1() error {
	var err error
	tkg.p, tkg.p1, err = tkg.generateSafePrimes()
	return err
}

func (tkg *ThresholdKeyGenerator) initQandQ1() error {
	var err error
	tkg.q, tkg.q1, err = tkg.generateSafePrimes()
	return err
}

func (tkg *ThresholdKeyGenerator) initShortcuts() {
	tkg.n = new(big.Int).Mul(tkg.p, tkg.q)
	tkg.m = new(big.Int).Mul(tkg.p1, tkg.q1)
	tkg.nSquare = new(big.Int).Mul(tkg.n, tkg.n)
	tkg.nm = new(big.Int).Mul(tkg.n, tkg.m)
}

func (tkg *ThresholdKeyGenerator) arePsAndQsGood() bool {
	if tkg.p.Cmp(tkg.q) == 0 {
		return false
	}
	if tkg.p.Cmp(tkg.q1) == 0 {
		return false
	}
	if tkg.p1.Cmp(tkg.q) == 0 {
		return false
	}
	return true
}

func (tkg *ThresholdKeyGenerator) initPsAndQs() error {
	if err := tkg.initPandP1(); err != nil {
		return err
	}
	if err := tkg.initQandQ1(); err != nil {
		return err
	}
	if !tkg.arePsAndQsGood() {
		return tkg.initPsAndQs()
	}
	return nil
}

// v generates a cyclic group of squares in Zn^2.
func (tkg *ThresholdKeyGenerator) computeV() error {
	var err error
	tkg.v, err = GetRandomGeneratorOfTheQuadraticResidue(tkg.nSquare, tkg.Random)
	return err
}

// Choose d such that d=0 (mod m) and d=1 (mod n).
//
// From Chinese Remainder Theorem:
// x = a1 (mod n1)
// x = a2 (mod n2)
//
// N = n1*n2
// y1 = N/n1
// y2 = N/n2
// z1 = y1^-1 mod n1
// z2 = y2^-1 mod n2
// Solution is x = a1*y1*z1 + a2*y2*z2
//
// In our case:
// x = 0 (mod m)
// x = 1 (mod n)
//
// Since a1 = 0, it's enough to compute a2*y2*z2 to get x.
//
// a2 = 1
// y2 = mn/n = m
// z2 = m^-1 mod n
//
// x = a2*y2*z2 = 1 * m * [m^-1 mod n]
func (tkg *ThresholdKeyGenerator) initD() {
	mInverse := new(big.Int).ModInverse(tkg.m, tkg.n)
	tkg.d = new(big.Int).Mul(mInverse, tkg.m)
}

func (tkg *ThresholdKeyGenerator) initNumerialValues() error {
	if err := tkg.initPsAndQs(); err != nil {
		return err
	}
	tkg.initShortcuts()
	tkg.initD()
	return tkg.computeV()
}

// f(X) = a_0 X^0 + a_1 X^1 + ... + a_(w-1) X^(w-1)
//
// where:
// `w` - threshold
// `a_i` - random value from {0, ... nm - 1} for 0<i<w
// `a_0` is always equal `d`
func (tkg *ThresholdKeyGenerator) generateHidingPolynomial() error {
	tkg.polynomialCoefficients = make([]*big.Int, tkg.Threshold)
	tkg.polynomialCoefficients[0] = tkg.d
	var err error
	for i := 1; i < tkg.Threshold; i++ {
		tkg.polynomialCoefficients[i], err = rand.Int(tkg.Random, tkg.nm)
		if err != nil {
			return err
		}
	}
	return nil
}

// The secred share of the i'th authority is `f(i) mod nm`, where `f` is
// the polynomial we generated in `GenerateHidingPolynomial` function.
func (tkg *ThresholdKeyGenerator) computeShare(index int) *big.Int {
	share := big.NewInt(0)
	for i := 0; i < tkg.Threshold; i++ {
		a := tkg.polynomialCoefficients[i]
		// we index authorities from 1, that's why we do index+1 here
		b := new(big.Int).Exp(big.NewInt(int64(index+1)), big.NewInt(int64(i)), nil)
		tmp := new(big.Int).Mul(a, b)
		share = new(big.Int).Add(share, tmp)
	}
	return new(big.Int).Mod(share, tkg.nm)
}

func (tkg *ThresholdKeyGenerator) createShares() []*big.Int {
	shares := make([]*big.Int, tkg.TotalNumberOfDecryptionServers)
	for i := 0; i < tkg.TotalNumberOfDecryptionServers; i++ {
		shares[i] = tkg.computeShare(i)
	}
	return shares
}

func (tkg *ThresholdKeyGenerator) delta() *big.Int {
	return Factorial(tkg.TotalNumberOfDecryptionServers)
}

// Generates verification keys for actions of decryption servers.
//
// For each decryption server `i`, we generate
// v_i = v^(l! s_i) mod n^2
//
// where:
// `l` is the number of decryption servers
// `s_i` is a secret share for server `i`.
// Secret shares were previously generated in the `CrateShares` function.
func (tkg *ThresholdKeyGenerator) createViArray(shares []*big.Int) (viArray []*big.Int) {
	viArray = make([]*big.Int, len(shares))
	delta := tkg.delta()
	for i, share := range shares {
		tmp := new(big.Int).Mul(share, delta)
		viArray[i] = new(big.Int).Exp(tkg.v, tmp, tkg.nSquare)
	}
	return viArray
}

func (tkg *ThresholdKeyGenerator) createPrivateKey(i int, share *big.Int, viArray []*big.Int) *ThresholdPrivateKey {
	ret := new(ThresholdPrivateKey)
	ret.N = tkg.n
	ret.V = tkg.v

	ret.TotalNumberOfDecryptionServers = tkg.TotalNumberOfDecryptionServers
	ret.Threshold = tkg.Threshold
	ret.Share = share
	ret.Id = i + 1
	ret.Vi = viArray
	return ret
}

func (tkg *ThresholdKeyGenerator) createPrivateKeys() []*ThresholdPrivateKey {
	shares := tkg.createShares()
	viArray := tkg.createViArray(shares)
	ret := make([]*ThresholdPrivateKey, tkg.TotalNumberOfDecryptionServers)
	for i := 0; i < tkg.TotalNumberOfDecryptionServers; i++ {
		ret[i] = tkg.createPrivateKey(i, shares[i], viArray)
	}
	return ret
}

func (tkg *ThresholdKeyGenerator) Generate() ([]*ThresholdPrivateKey, error) {
	if err := tkg.initNumerialValues(); err != nil {
		return nil, err
	}
	if err := tkg.generateHidingPolynomial(); err != nil {
		return nil, err
	}
	return tkg.createPrivateKeys(), nil
}
<|endoftext|>


<commit_before>package pollers

import (
	"bufio"
	"github.com/freeformz/shh/mm"
	"github.com/freeformz/shh/utils"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

type CpuValues struct {
	User    float64
	Nice    float64
	System  float64
	Idle    float64
	Iowait  float64
	Irq     float64
	Softirq float64
	Steal   float64
	Guest   float64
}

func (cv CpuValues) Total() float64 {
	return cv.User + cv.Nice + cv.System + cv.Idle + cv.Iowait + cv.Irq + cv.Softirq + cv.Steal + cv.Guest
}

type Cpu struct {
	measurements chan<- *mm.Measurement
	last         map[string]CpuValues
}

func NewCpuPoller(measurements chan<- *mm.Measurement) Cpu {
	return Cpu{measurements: measurements, last: make(map[string]CpuValues)}
}

func calcPercent(val, total float64) string {
	if total == 0 {
		return "0"
	}
	return strconv.FormatFloat(val/total*100, 'f', 2, 64)
}

func (poller Cpu) Poll(tick time.Time) {
	file, err := os.Open("/proc/stat")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}

		if strings.HasPrefix(line, "cpu") {
			fields := strings.Fields(line)
			cpu := fields[0]

			var current = CpuValues{}

			current.User = utils.Atofloat64(fields[1])
			current.Nice = utils.Atofloat64(fields[2])
			current.System = utils.Atofloat64(fields[3])
			current.Idle = utils.Atofloat64(fields[4])
			current.Iowait = utils.Atofloat64(fields[5])
			current.Irq = utils.Atofloat64(fields[6])
			current.Softirq = utils.Atofloat64(fields[7])
			current.Steal = utils.Atofloat64(fields[8])
			current.Guest = utils.Atofloat64(fields[9])

			var last = poller.last[cpu]

			if last.Total() != 0 {
				cTotal := current.Total() - last.Total()
				cUser := current.User - last.User
				cNice := current.Nice - last.Nice
				cSystem := current.System - last.System
				cIdle := current.Idle - last.Idle
				cIowait := current.Iowait - last.Iowait
				cIrq := current.Irq - last.Irq
				cSoftirq := current.Softirq - last.Softirq
				cSteal := current.Steal - last.Steal
				cGuest := current.Guest - last.Guest

				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "user"}, calcPercent(cUser, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "nice"}, calcPercent(cNice, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "system"}, calcPercent(cSystem, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "idle"}, calcPercent(cIdle, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "iowait"}, calcPercent(cIowait, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "irq"}, calcPercent(cIrq, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "softirq"}, calcPercent(cSoftirq, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "steal"}, calcPercent(cSteal, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "guest"}, calcPercent(cGuest, cTotal), mm.GAUGE}
			}

			poller.last[cpu] = current

		}
	}
}

func (poller Cpu) Name() string {
	return "cpu"
}
<commit_msg>declare at top<commit_after>package pollers

import (
	"bufio"
	"github.com/freeformz/shh/mm"
	"github.com/freeformz/shh/utils"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

type CpuValues struct {
	User    float64
	Nice    float64
	System  float64
	Idle    float64
	Iowait  float64
	Irq     float64
	Softirq float64
	Steal   float64
	Guest   float64
}

func (cv CpuValues) Total() float64 {
	return cv.User + cv.Nice + cv.System + cv.Idle + cv.Iowait + cv.Irq + cv.Softirq + cv.Steal + cv.Guest
}

type Cpu struct {
	measurements chan<- *mm.Measurement
	last         map[string]CpuValues
}

func NewCpuPoller(measurements chan<- *mm.Measurement) Cpu {
	return Cpu{measurements: measurements, last: make(map[string]CpuValues)}
}

func calcPercent(val, total float64) string {
	if total == 0 {
		return "0"
	}
	return strconv.FormatFloat(val/total*100, 'f', 2, 64)
}

func (poller Cpu) Poll(tick time.Time) {
  var current, last CpuValues

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

	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}

		if strings.HasPrefix(line, "cpu") {
			fields := strings.Fields(line)
			cpu := fields[0]

			current = CpuValues{}

			current.User = utils.Atofloat64(fields[1])
			current.Nice = utils.Atofloat64(fields[2])
			current.System = utils.Atofloat64(fields[3])
			current.Idle = utils.Atofloat64(fields[4])
			current.Iowait = utils.Atofloat64(fields[5])
			current.Irq = utils.Atofloat64(fields[6])
			current.Softirq = utils.Atofloat64(fields[7])
			current.Steal = utils.Atofloat64(fields[8])
			current.Guest = utils.Atofloat64(fields[9])

			last = poller.last[cpu]

			if last.Total() != 0 {
				cTotal := current.Total() - last.Total()
				cUser := current.User - last.User
				cNice := current.Nice - last.Nice
				cSystem := current.System - last.System
				cIdle := current.Idle - last.Idle
				cIowait := current.Iowait - last.Iowait
				cIrq := current.Irq - last.Irq
				cSoftirq := current.Softirq - last.Softirq
				cSteal := current.Steal - last.Steal
				cGuest := current.Guest - last.Guest

				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "user"}, calcPercent(cUser, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "nice"}, calcPercent(cNice, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "system"}, calcPercent(cSystem, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "idle"}, calcPercent(cIdle, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "iowait"}, calcPercent(cIowait, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "irq"}, calcPercent(cIrq, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "softirq"}, calcPercent(cSoftirq, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "steal"}, calcPercent(cSteal, cTotal), mm.GAUGE}
				poller.measurements <- &mm.Measurement{tick, poller.Name(), []string{cpu, "guest"}, calcPercent(cGuest, cTotal), mm.GAUGE}
			}

			poller.last[cpu] = current

		}
	}
}

func (poller Cpu) Name() string {
	return "cpu"
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"net/http"
)

type pongoRender struct {
	cache map[string]*pongo2.Template
}

func newPongoRender() *pongoRender {
	return &pongoRender{map[string]*pongo2.Template{}}
}

func writeHeader(w http.ResponseWriter, code int, contentType string) {
	if code >= 0 {
		w.Header().Set("Content-Type", contentType)
		w.WriteHeader(code)
	}
}

func (p *pongoRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		tmpl, err := pongo2.FromFile(file)
		if err != nil {
			return err
		}
		p.cache[file] = tmpl
		t = tmpl
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteRW(w, ctx)
}

func main() {
	r := gin.Default()
	r.HTMLRender = newPongoRender()

	r.GET("/index", func(c *gin.Context) {
		name := c.Request.FormValue("name")
		ctx := pongo2.Context{
			"title": "Gin meets pongo2 !",
			"name":  name,
		}
		c.HTML(200, "index.html", ctx)
	})

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
<commit_msg>Fix PR #71<commit_after>package main

import (
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"net/http"
)

type pongoRender struct {
	cache map[string]*pongo2.Template
}

func newPongoRender() *pongoRender {
	return &pongoRender{map[string]*pongo2.Template{}}
}

func writeHeader(w http.ResponseWriter, code int, contentType string) {
	if code >= 0 {
		w.Header().Set("Content-Type", contentType)
		w.WriteHeader(code)
	}
}

func (p *pongoRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		tmpl, err := pongo2.FromFile(file)
		if err != nil {
			return err
		}
		p.cache[file] = tmpl
		t = tmpl
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteWriter(ctx, w)
}

func main() {
	r := gin.Default()
	r.HTMLRender = newPongoRender()

	r.GET("/index", func(c *gin.Context) {
		name := c.Request.FormValue("name")
		ctx := pongo2.Context{
			"title": "Gin meets pongo2 !",
			"name":  name,
		}
		c.HTML(200, "index.html", ctx)
	})

	// Listen and server on 0.0.0.0:8080
	r.Run(":8080")
}
<|endoftext|>


<commit_before>package main

import (
	"context"
	"fmt"

	"gitlab.com/tesgo/kit/proto/ses/pb"
	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:6000", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	client := pb.NewSESClient(conn)

	reply, err := client.Send(context.Background(),
		&pb.SendRequest{
			From:    "gunsluo@gmail.com",
			To:      []string{"gunsluo@gmail.com"},
			Subject: "Amazon SES Test (AWS SDK for Go)",
			Html:    "this is a test",
		})
	if err != nil {
		fmt.Println("unable to send ", err)
	} else {
		fmt.Println("reply:", reply.Id, reply.Status)
	}
}
<commit_msg>status<commit_after>package main

import (
	"context"
	"fmt"

	"gitlab.com/tesgo/kit/proto/ses/pb"
	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:6000", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	client := pb.NewSESClient(conn)

	reply, err := client.Send(context.Background(),
		&pb.SendRequest{
			From:    "gunsluo@gmail.com",
			To:      []string{"gunsluo@gmail.com"},
			Subject: "Amazon SES Test (AWS SDK for Go)",
			Html:    "this is a test",
		})
	if err != nil {
		fmt.Println("unable to send ", err)
	} else {
		fmt.Println("reply:", reply.Id, reply.Status)
	}

	reply2, err := client.Status(context.Background(),
		&pb.StatusRequest{
			Id: "3edcc83a-c764-4878-9fda-2013233dfb29",
		})
	if err != nil {
		fmt.Println("unable to query status ", err)
	} else {
		fmt.Println("reply:", reply2.Status, reply2.Reason)
	}

}
<|endoftext|>


<commit_before>package main

import (
	"github.com/mmcquillan/jane/listeners"
	"github.com/mmcquillan/jane/models"
	"sync"
)

var wg sync.WaitGroup

func main() {
	config := models.Load()
	models.Flags(&config)
	models.Logging(&config)
	wg.Add(len(config.Listeners))
	go runListener(&config)
	wg.Wait()
}

func runListener(config *models.Config) {
	for _, listener := range config.Listeners {
		if listener.Active {
			defer wg.Done()
			switch listener.Type {
			case "slack":
				go listeners.Slack(config, listener)
			case "cli":
				go listeners.Cli(config, listener)
			case "rss":
				go listeners.Rss(config, listener)
			}
		}
	}
}
<commit_msg>initial monitor listener<commit_after>package main

import (
	"github.com/mmcquillan/jane/listeners"
	"github.com/mmcquillan/jane/models"
	"sync"
)

var wg sync.WaitGroup

func main() {
	config := models.Load()
	models.Flags(&config)
	models.Logging(&config)
	wg.Add(len(config.Listeners))
	go runListener(&config)
	wg.Wait()
}

func runListener(config *models.Config) {
	for _, listener := range config.Listeners {
		if listener.Active {
			defer wg.Done()
			switch listener.Type {
			case "slack":
				go listeners.Slack(config, listener)
			case "cli":
				go listeners.Cli(config, listener)
			case "rss":
				go listeners.Rss(config, listener)
			case "monitor":
				go listeners.Monitor(config, listener)
			}
		}
	}
}
<|endoftext|>


<commit_before>package decision

import (
	"sync"
	"time"

	wantlist "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	pq "github.com/ipfs/go-ipfs/thirdparty/pq"
	u "github.com/ipfs/go-ipfs/util"
)

type peerRequestQueue interface {
	// Pop returns the next peerRequestTask. Returns nil if the peerRequestQueue is empty.
	Pop() *peerRequestTask
	Push(entry wantlist.Entry, to peer.ID)
	Remove(k u.Key, p peer.ID)
	// NB: cannot expose simply expose taskQueue.Len because trashed elements
	// may exist. These trashed elements should not contribute to the count.
}

func newPRQ() peerRequestQueue {
	return &prq{
		taskMap:  make(map[string]*peerRequestTask),
		partners: make(map[peer.ID]*activePartner),
		pQueue:   pq.New(partnerCompare),
	}
}

// verify interface implementation
var _ peerRequestQueue = &prq{}

// TODO: at some point, the strategy needs to plug in here
// to help decide how to sort tasks (on add) and how to select
// tasks (on getnext). For now, we are assuming a dumb/nice strategy.
type prq struct {
	lock     sync.Mutex
	pQueue   pq.PQ
	taskMap  map[string]*peerRequestTask
	partners map[peer.ID]*activePartner
}

// Push currently adds a new peerRequestTask to the end of the list
func (tl *prq) Push(entry wantlist.Entry, to peer.ID) {
	tl.lock.Lock()
	defer tl.lock.Unlock()
	partner, ok := tl.partners[to]
	if !ok {
		partner = &activePartner{taskQueue: pq.New(wrapCmp(V1))}
		tl.pQueue.Push(partner)
		tl.partners[to] = partner
	}

	if task, ok := tl.taskMap[taskKey(to, entry.Key)]; ok {
		task.Entry.Priority = entry.Priority
		partner.taskQueue.Update(task.index)
		return
	}

	task := &peerRequestTask{
		Entry:   entry,
		Target:  to,
		created: time.Now(),
		Done: func() {
			partner.TaskDone()
			tl.lock.Lock()
			tl.pQueue.Update(partner.Index())
			tl.lock.Unlock()
		},
	}

	partner.taskQueue.Push(task)
	tl.taskMap[task.Key()] = task
	partner.requests++
	tl.pQueue.Update(partner.Index())
}

// Pop 'pops' the next task to be performed. Returns nil if no task exists.
func (tl *prq) Pop() *peerRequestTask {
	tl.lock.Lock()
	defer tl.lock.Unlock()
	if tl.pQueue.Len() == 0 {
		return nil
	}
	partner := tl.pQueue.Pop().(*activePartner)

	var out *peerRequestTask
	for partner.taskQueue.Len() > 0 {
		out = partner.taskQueue.Pop().(*peerRequestTask)
		delete(tl.taskMap, out.Key())
		if out.trash {
			continue // discarding tasks that have been removed
		}
		break // and return |out|
	}

	// start the new task, and push the partner back onto the queue
	partner.StartTask()
	partner.requests--
	tl.pQueue.Push(partner)
	return out
}

// Remove removes a task from the queue
func (tl *prq) Remove(k u.Key, p peer.ID) {
	tl.lock.Lock()
	t, ok := tl.taskMap[taskKey(p, k)]
	if ok {
		// remove the task "lazily"
		// simply mark it as trash, so it'll be dropped when popped off the
		// queue.
		t.trash = true

		// having canceled a block, we now account for that in the given partner
		tl.partners[p].requests--
	}
	tl.lock.Unlock()
}

type peerRequestTask struct {
	Entry  wantlist.Entry
	Target peer.ID

	// A callback to signal that this task has been completed
	Done func()

	// trash in a book-keeping field
	trash bool
	// created marks the time that the task was added to the queue
	created time.Time
	index   int // book-keeping field used by the pq container
}

// Key uniquely identifies a task.
func (t *peerRequestTask) Key() string {
	return taskKey(t.Target, t.Entry.Key)
}

// Index implements pq.Elem
func (t *peerRequestTask) Index() int {
	return t.index
}

// SetIndex implements pq.Elem
func (t *peerRequestTask) SetIndex(i int) {
	t.index = i
}

// taskKey returns a key that uniquely identifies a task.
func taskKey(p peer.ID, k u.Key) string {
	return string(p.String() + k.String())
}

// FIFO is a basic task comparator that returns tasks in the order created.
var FIFO = func(a, b *peerRequestTask) bool {
	return a.created.Before(b.created)
}

// V1 respects the target peer's wantlist priority. For tasks involving
// different peers, the oldest task is prioritized.
var V1 = func(a, b *peerRequestTask) bool {
	if a.Target == b.Target {
		return a.Entry.Priority > b.Entry.Priority
	}
	return FIFO(a, b)
}

func wrapCmp(f func(a, b *peerRequestTask) bool) func(a, b pq.Elem) bool {
	return func(a, b pq.Elem) bool {
		return f(a.(*peerRequestTask), b.(*peerRequestTask))
	}
}

type activePartner struct {
	lk sync.Mutex

	// Active is the number of blocks this peer is currently being sent
	// active must be locked around as it will be updated externally
	active int

	// requests is the number of blocks this peer is currently requesting
	// request need not be locked around as it will only be modified under
	// the peerRequestQueue's locks
	requests int

	// for the PQ interface
	index int

	// priority queue of tasks belonging to this peer
	taskQueue pq.PQ
}

// partnerCompare implements pq.ElemComparator
func partnerCompare(a, b pq.Elem) bool {
	pa := a.(*activePartner)
	pb := b.(*activePartner)

	// having no blocks in their wantlist means lowest priority
	if pa.requests == 0 {
		return false
	}
	if pb.requests == 0 {
		return true
	}
	return pa.active < pb.active
}

// StartTask signals that a task was started for this partner
func (p *activePartner) StartTask() {
	p.lk.Lock()
	p.active++
	p.lk.Unlock()
}

// TaskDone signals that a task was completed for this partner
func (p *activePartner) TaskDone() {
	p.lk.Lock()
	p.active--
	if p.active < 0 {
		panic("more tasks finished than started!")
	}
	p.lk.Unlock()
}

// Index implements pq.Elem
func (p *activePartner) Index() int {
	return p.index
}

// SetIndex implements pq.Elem
func (p *activePartner) SetIndex(i int) {
	p.index = i
}
<commit_msg>fix some logic<commit_after>package decision

import (
	"sync"
	"time"

	wantlist "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	pq "github.com/ipfs/go-ipfs/thirdparty/pq"
	u "github.com/ipfs/go-ipfs/util"
)

type peerRequestQueue interface {
	// Pop returns the next peerRequestTask. Returns nil if the peerRequestQueue is empty.
	Pop() *peerRequestTask
	Push(entry wantlist.Entry, to peer.ID)
	Remove(k u.Key, p peer.ID)
	// NB: cannot expose simply expose taskQueue.Len because trashed elements
	// may exist. These trashed elements should not contribute to the count.
}

func newPRQ() peerRequestQueue {
	return &prq{
		taskMap:  make(map[string]*peerRequestTask),
		partners: make(map[peer.ID]*activePartner),
		pQueue:   pq.New(partnerCompare),
	}
}

// verify interface implementation
var _ peerRequestQueue = &prq{}

// TODO: at some point, the strategy needs to plug in here
// to help decide how to sort tasks (on add) and how to select
// tasks (on getnext). For now, we are assuming a dumb/nice strategy.
type prq struct {
	lock     sync.Mutex
	pQueue   pq.PQ
	taskMap  map[string]*peerRequestTask
	partners map[peer.ID]*activePartner
}

// Push currently adds a new peerRequestTask to the end of the list
func (tl *prq) Push(entry wantlist.Entry, to peer.ID) {
	tl.lock.Lock()
	defer tl.lock.Unlock()
	partner, ok := tl.partners[to]
	if !ok {
		partner = &activePartner{taskQueue: pq.New(wrapCmp(V1))}
		tl.pQueue.Push(partner)
		tl.partners[to] = partner
	}

	if task, ok := tl.taskMap[taskKey(to, entry.Key)]; ok {
		task.Entry.Priority = entry.Priority
		partner.taskQueue.Update(task.index)
		return
	}

	task := &peerRequestTask{
		Entry:   entry,
		Target:  to,
		created: time.Now(),
		Done: func() {
			partner.TaskDone()
			tl.lock.Lock()
			tl.pQueue.Update(partner.Index())
			tl.lock.Unlock()
		},
	}

	partner.taskQueue.Push(task)
	tl.taskMap[task.Key()] = task
	partner.requests++
	tl.pQueue.Update(partner.Index())
}

// Pop 'pops' the next task to be performed. Returns nil if no task exists.
func (tl *prq) Pop() *peerRequestTask {
	tl.lock.Lock()
	defer tl.lock.Unlock()
	if tl.pQueue.Len() == 0 {
		return nil
	}
	partner := tl.pQueue.Pop().(*activePartner)

	var out *peerRequestTask
	for partner.taskQueue.Len() > 0 {
		out = partner.taskQueue.Pop().(*peerRequestTask)
		delete(tl.taskMap, out.Key())
		if out.trash {
			out = nil
			continue // discarding tasks that have been removed
		}

		partner.StartTask()
		partner.requests--
		break // and return |out|
	}

	tl.pQueue.Push(partner)
	return out
}

// Remove removes a task from the queue
func (tl *prq) Remove(k u.Key, p peer.ID) {
	tl.lock.Lock()
	t, ok := tl.taskMap[taskKey(p, k)]
	if ok {
		// remove the task "lazily"
		// simply mark it as trash, so it'll be dropped when popped off the
		// queue.
		t.trash = true

		// having canceled a block, we now account for that in the given partner
		tl.partners[p].requests--
	}
	tl.lock.Unlock()
}

type peerRequestTask struct {
	Entry  wantlist.Entry
	Target peer.ID

	// A callback to signal that this task has been completed
	Done func()

	// trash in a book-keeping field
	trash bool
	// created marks the time that the task was added to the queue
	created time.Time
	index   int // book-keeping field used by the pq container
}

// Key uniquely identifies a task.
func (t *peerRequestTask) Key() string {
	return taskKey(t.Target, t.Entry.Key)
}

// Index implements pq.Elem
func (t *peerRequestTask) Index() int {
	return t.index
}

// SetIndex implements pq.Elem
func (t *peerRequestTask) SetIndex(i int) {
	t.index = i
}

// taskKey returns a key that uniquely identifies a task.
func taskKey(p peer.ID, k u.Key) string {
	return string(p.String() + k.String())
}

// FIFO is a basic task comparator that returns tasks in the order created.
var FIFO = func(a, b *peerRequestTask) bool {
	return a.created.Before(b.created)
}

// V1 respects the target peer's wantlist priority. For tasks involving
// different peers, the oldest task is prioritized.
var V1 = func(a, b *peerRequestTask) bool {
	if a.Target == b.Target {
		return a.Entry.Priority > b.Entry.Priority
	}
	return FIFO(a, b)
}

func wrapCmp(f func(a, b *peerRequestTask) bool) func(a, b pq.Elem) bool {
	return func(a, b pq.Elem) bool {
		return f(a.(*peerRequestTask), b.(*peerRequestTask))
	}
}

type activePartner struct {
	lk sync.Mutex

	// Active is the number of blocks this peer is currently being sent
	// active must be locked around as it will be updated externally
	active int

	// requests is the number of blocks this peer is currently requesting
	// request need not be locked around as it will only be modified under
	// the peerRequestQueue's locks
	requests int

	// for the PQ interface
	index int

	// priority queue of tasks belonging to this peer
	taskQueue pq.PQ
}

// partnerCompare implements pq.ElemComparator
func partnerCompare(a, b pq.Elem) bool {
	pa := a.(*activePartner)
	pb := b.(*activePartner)

	// having no blocks in their wantlist means lowest priority
	if pa.requests == 0 {
		return false
	}
	if pb.requests == 0 {
		return true
	}
	return pa.active < pb.active
}

// StartTask signals that a task was started for this partner
func (p *activePartner) StartTask() {
	p.lk.Lock()
	p.active++
	p.lk.Unlock()
}

// TaskDone signals that a task was completed for this partner
func (p *activePartner) TaskDone() {
	p.lk.Lock()
	p.active--
	if p.active < 0 {
		panic("more tasks finished than started!")
	}
	p.lk.Unlock()
}

// Index implements pq.Elem
func (p *activePartner) Index() int {
	return p.index
}

// SetIndex implements pq.Elem
func (p *activePartner) SetIndex(i int) {
	p.index = i
}
<|endoftext|>


<commit_before>package reinet

import (
	"regexp"
	"net/http"
)

const (
	// DELETE HTTP method
	DELETE = "DELETE"
	// GET HTTP method
	GET = "GET"
	// HEAD HTTP method
	HEAD = "HEAD"
	// OPTIONS HTTP method
	OPTIONS = "OPTIONS"
	// PATCH HTTP method
	PATCH = "PATCH"
	// POST HTTP method
	POST = "POST"
	// PUT HTTP method
	PUT = "PUT"
	// TRACE HTTP method
	TRACE = "TRACE"
)

type Context struct {
	req *http.Request
	res http.ResponseWriter
	formParams map[string]string
	urlQueryParams map[string]string
}

type handler interface{}

type route struct {
	regex *regexp.Regexp
	params map[int]string
	handler handler
	method string
}

var mainServer *ReiServer
var Sessions *Manager

func init() {
	mainServer = NewServer()
	Sessions = nil
	initSession()
	Sessions, _ = NewManager("default", "reinetSessionID", 3600)
}

func wrap(handleFunc handler) handler {
	return handleFunc
}

func Get(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), GET)
}

func Post(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), POST)
}

func Delete(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), DELETE)
}

func Put(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), PUT)
}

func Patch(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), PATCH)
}

func GivenMethod(pattern string, handleFunc handler, method string) {
	mainServer.addRoute(pattern, wrap(handleFunc), method)
}

func SetStatic(url string, path string) {
	(*(mainServer.staticDir))[url] = path
}

func Run(addr string) {
	go Sessions.GC()
	http.ListenAndServe(addr, mainServer)
}

func UseProvider(providerName string, provider Provider) {
	AddProvider(providerName, provider)
	Sessions.provider = provides[providerName]
}

func SetExpires(expires int64) {
	Sessions.maxLifeTime = expires
}<commit_msg>Mod: add some features<commit_after>package reinet

import (
	"reflect"
	"html/template"
	"regexp"
	"net/http"
)

const (
	// DELETE HTTP method
	DELETE = "DELETE"
	// GET HTTP method
	GET = "GET"
	// HEAD HTTP method
	HEAD = "HEAD"
	// OPTIONS HTTP method
	OPTIONS = "OPTIONS"
	// PATCH HTTP method
	PATCH = "PATCH"
	// POST HTTP method
	POST = "POST"
	// PUT HTTP method
	PUT = "PUT"
	// TRACE HTTP method
	TRACE = "TRACE"
)

type Context struct {
	req *http.Request
	res http.ResponseWriter
	formParams map[string]string
	urlQueryParams map[string]string
}

type handler interface{}

type route struct {
	regex *regexp.Regexp
	params map[int]string
	handler handler
	method string
}

var mainServer *ReiServer
var Sessions *Manager

func init() {
	mainServer = NewServer()
	Sessions = nil
	initSession()
	Sessions, _ = NewManager("default", "reinetSessionID", 3600)
}

func wrap(handleFunc handler) handler {
	return handleFunc
}

func Get(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), GET)
}

func Post(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), POST)
}

func Delete(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), DELETE)
}

func Put(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), PUT)
}

func Patch(pattern string, handleFunc handler) {
	mainServer.addRoute(pattern, wrap(handleFunc), PATCH)
}

func GivenMethod(pattern string, handleFunc handler, method string) {
	mainServer.addRoute(pattern, wrap(handleFunc), method)
}

func SetStatic(url string, path string) {
	(*(mainServer.staticDir))[url] = path
}

func Run(addr string) {
	go Sessions.GC()
	http.ListenAndServe(addr, mainServer)
}

func UseProvider(providerName string, provider Provider) {
	AddProvider(providerName, provider)
	Sessions.provider = provides[providerName]
}

func SetExpires(expires int64) {
	Sessions.maxLifeTime = expires
}

func RenderTemplate(ctx Context, tmpl string, params interface{}) {
	t, err := template.ParseFiles(tmpl)
	if err != nil {
		http.Error(ctx.res, err.Error(), http.StatusInternalServerError)
		return
	}
	err := t.Execute(ctx.res, params)
	if err != nil {
		http.Error(ctx.res, err.Error(), http.StatusInternalServerError)
		return
	}
}

func Redirect(ctx Context, redirectUrl string) {
	http.Redirect(ctx.res, ctx.req, redirectUrl, http.StatusFound)
}<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strings"
)

func ReverseWords(stringR string) []string {
	//indexSpace = make([]int, 0)
	var wordsList []string
	/**
	for i, s := range stringR {
		if s == " " {
			indexSpace = append(indexSpace, i)
		}
	}
	for i, _ := range indexSpace {
		if i < len(indexSpace)-1; indexSpace[i+1]-indexSpace[i] >= 2 {
			wordsList = append(wordsList, stringR[indexSpace[i]:indexSpace[i+1]])
		}
	}*/

	wordsList = strings.Split(stringR, " ")
	return wordsList
}

func main() {
	fmt.Print(ReverseWords("ccQ nihao"))
}
<commit_msg>finish go version<commit_after>package main

import (
	"fmt"
	"os"
	"strings"
)

var args []string = os.Args[1:]

func ReverseWords(stringR string) []string {

	wordsList := strings.Split(stringR, " ")
	var newWordsList []string
	//fmt.Println(wordsList)

	for i := len(wordsList) - 1; i >= 0; i = i - 1 {
		newWordsList = append(newWordsList, wordsList[i])
		//fmt.Println(wordsList[i])
	}
	return newWordsList
}

func main() {
	var result string
	for _, i := range args {
		result = result + i + " "
	}
	result = strings.TrimSuffix(result, " ")
	fmt.Print(ReverseWords(result))
}
<|endoftext|>