// Configure a default check for a service. The default is to return an HTTP
// check on the first TCP port on the endpoint set in DEFAULT_STATUS_ENDPOINT.
492667
func (m *Monitor) defaultCheckForService(svc *service.Service) *Check {
	port := findFirstTCPPort(svc)
	if port == nil {
		return &Check{ID: svc.ID, Command: &AlwaysSuccessfulCmd{}}
	}

	// Use the const default unless we've been provided something else
	defaultCheckEndpoint := DEFAULT_STATUS_ENDPOINT
	if len(m.DefaultCheckEndpoint) != 0 {
		defaultCheckEndpoint = m.DefaultCheckEndpoint
	}

	url := fmt.Sprintf("http://%v:%v%v", m.DefaultCheckHost, port.Port, defaultCheckEndpoint)
	return &Check{
		ID:      svc.ID,
		Type:    "HttpGet",
		Args:    url,
		Status:  FAILED,
		Command: &HttpGetCmd{},
	}
}
1076913
func SetTransportDefaults(t *http.Transport) *http.Transport {
	t = SetOldTransportDefaults(t)
	// Allow clients to disable http2 if needed.
	if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 {
		klog.Infof("HTTP2 has been explicitly disabled")
	} else {
		if err := http2.ConfigureTransport(t); err != nil {
			klog.Warningf("Transport failed http2 configuration: %v", err)
		}
	}
	return t
}
828255
func (commonOpts *CommonOptions) SetDefaultOptions(flags *pflag.FlagSet) {
	// Regardless of whether the user sets it to true or false, if they
	// specify --tlsverify at all then we need to turn on TLS
	// TLSVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need
	// to check that here as well
	if flags.Changed(FlagTLSVerify) || commonOpts.TLSVerify {
		commonOpts.TLS = true
	}

	if !commonOpts.TLS {
		commonOpts.TLSOptions = nil
	} else {
		tlsOptions := commonOpts.TLSOptions
		tlsOptions.InsecureSkipVerify = !commonOpts.TLSVerify

		// Reset CertFile and KeyFile to empty string if the user did not specify
		// the respective flags and the respective default files were not found.
		if !flags.Changed("tlscert") {
			if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) {
				tlsOptions.CertFile = ""
			}
		}
		if !flags.Changed("tlskey") {
			if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) {
				tlsOptions.KeyFile = ""
			}
		}
	}
}
1022253
func DefaultConfig() *Config {
	config := &Config{
		Address:    "http://127.0.0.1:4646",
		httpClient: cleanhttp.DefaultClient(),
		TLSConfig:  &TLSConfig{},
	}
	transport := config.httpClient.Transport.(*http.Transport)
	transport.TLSHandshakeTimeout = 10 * time.Second
	transport.TLSClientConfig = &tls.Config{
		MinVersion: tls.VersionTLS12,
	}

	if addr := os.Getenv("NOMAD_ADDR"); addr != "" {
		config.Address = addr
	}
	if v := os.Getenv("NOMAD_REGION"); v != "" {
		config.Region = v
	}
	if v := os.Getenv("NOMAD_NAMESPACE"); v != "" {
		config.Namespace = v
	}
	if auth := os.Getenv("NOMAD_HTTP_AUTH"); auth != "" {
		var username, password string
		if strings.Contains(auth, ":") {
			split := strings.SplitN(auth, ":", 2)
			username = split[0]
			password = split[1]
		} else {
			username = auth
		}

		config.HttpAuth = &HttpBasicAuth{
			Username: username,
			Password: password,
		}
	}

	// Read TLS specific env vars
	if v := os.Getenv("NOMAD_CACERT"); v != "" {
		config.TLSConfig.CACert = v
	}
	if v := os.Getenv("NOMAD_CAPATH"); v != "" {
		config.TLSConfig.CAPath = v
	}
	if v := os.Getenv("NOMAD_CLIENT_CERT"); v != "" {
		config.TLSConfig.ClientCert = v
	}
	if v := os.Getenv("NOMAD_CLIENT_KEY"); v != "" {
		config.TLSConfig.ClientKey = v
	}
	if v := os.Getenv("NOMAD_SKIP_VERIFY"); v != "" {
		if insecure, err := strconv.ParseBool(v); err == nil {
			config.TLSConfig.Insecure = insecure
		}
	}
	if v := os.Getenv("NOMAD_TOKEN"); v != "" {
		config.SecretID = v
	}
	return config
}
724170
func Default() map[pb.NetMode]Provider {
	return map[pb.NetMode]Provider{
		// FIXME: still uses host if no provider configured
		pb.NetMode_UNSET: NewHostProvider(),
		pb.NetMode_HOST:  NewHostProvider(),
		pb.NetMode_NONE:  NewNoneProvider(),
	}
}
814636
func (c *Connection) setDefaults() {
	if c.UserAgent == "" {
		c.UserAgent = DefaultUserAgent
	}
	if c.Retries == 0 {
		c.Retries = DefaultRetries
	}
	if c.ConnectTimeout == 0 {
		c.ConnectTimeout = 10 * time.Second
	}
	if c.Timeout == 0 {
		c.Timeout = 60 * time.Second
	}
	if c.Transport == nil {
		t := &http.Transport{
			//		TLSClientConfig:    &tls.Config{RootCAs: pool},
			//		DisableCompression: true,
			Proxy: http.ProxyFromEnvironment,
			// Half of linux's default open files limit (1024).
			MaxIdleConnsPerHost: 512,
		}
		SetExpectContinueTimeout(t, 5*time.Second)
		c.Transport = t
	}
	if c.client == nil {
		c.client = &http.Client{
			//		CheckRedirect: redirectPolicyFunc,
			Transport: c.Transport,
		}
	}
}
690051
func DefaultHTTPEndpoint() string {
	config := &Config{HTTPHost: DefaultHTTPHost, HTTPPort: DefaultHTTPPort}
	return config.HTTPEndpoint()
}
809557
func (cons *HTTP) Configure(conf core.PluginConfigReader) {
	if cons.htpasswd != "" {
		if _, fileErr := os.Stat(cons.htpasswd); os.IsNotExist(fileErr) {
			conf.Errors.Pushf("htpasswd file does not exist: %s", cons.htpasswd)
			cons.htpasswd = ""
		}
		cons.secrets = auth.HtpasswdFileProvider(cons.htpasswd)
	}

	certificateFile := conf.GetString("Certificate", "")
	keyFile := conf.GetString("PrivateKey", "")

	if certificateFile != "" || keyFile != "" {
		if certificateFile == "" || keyFile == "" {
			conf.Errors.Pushf("There must always be a certificate and a private key or none of both")
		} else {

			cons.certificate = new(tls.Config)
			cons.certificate.NextProtos = []string{"http/1.1"}

			keypair, err := tls.LoadX509KeyPair(certificateFile, keyFile)
			if !conf.Errors.Push(err) {
				cons.certificate.Certificates = []tls.Certificate{keypair}
			}
		}
	}
}
322391
func DefaultConfig(host bool, ssh bool) *Config {

	return &Config{
		EventMetadataExtractor: extractors.DefaultHostMetadataExtractor,
		ReleasePath:            "/var/lib/aporeto/cleaner",
		StoredPath:             common.TriremeCgroupPath,
		Host:                   host,
		SSH:                    ssh,
	}
}
668874
func (client *AwsMultiClient) Configure(conf core.PluginConfigReader) {
	client.config = aws.NewConfig()

	client.config.WithRegion(client.region)
	client.config.WithEndpoint(client.endpoint)

	credentials, err := client.Credentials.CreateAwsCredentials()
	if err != nil {
		conf.Errors.Push(err)
	}

	client.config.WithCredentials(credentials)
	client.config.CredentialsChainVerboseErrors = aws.Bool(true)
}
1221300
func SetDefaults_APIServer(obj *APIServer) {
	if obj.TimeoutForControlPlane == nil {
		obj.TimeoutForControlPlane = &metav1.Duration{
			Duration: constants.DefaultControlPlaneTimeout,
		}
	}
}
913551
func (a *Agent) agentHTTPCheck(server bool) *structs.ServiceCheck {
	// Resolve the http check address
	httpCheckAddr := a.config.normalizedAddrs.HTTP
	if *a.config.Consul.ChecksUseAdvertise {
		httpCheckAddr = a.config.AdvertiseAddrs.HTTP
	}
	check := structs.ServiceCheck{
		Name:      a.config.Consul.ClientHTTPCheckName,
		Type:      "http",
		Path:      "/v1/agent/health?type=client",
		Protocol:  "http",
		Interval:  agentHttpCheckInterval,
		Timeout:   agentHttpCheckTimeout,
		PortLabel: httpCheckAddr,
	}
	// Switch to endpoint that doesn't require a leader for servers
	if server {
		check.Name = a.config.Consul.ServerHTTPCheckName
		check.Path = "/v1/agent/health?type=server"
	}
	if !a.config.TLSConfig.EnableHTTP {
		// No HTTPS, return a plain http check
		return &check
	}
	if a.config.TLSConfig.VerifyHTTPSClient {
		a.logger.Warn("not registering Nomad HTTPS Health Check because verify_https_client enabled")
		return nil
	}

	// HTTPS enabled; skip verification
	check.Protocol = "https"
	check.TLSSkipVerify = true
	return &check
}
1079891
func main() {
	bind := flag.String("bind", ":8000", "The host:port to bind this service")
	config := flag.String("config", "config.json", "The configuration for this service")

	flag.Parse()

	// load from config
	var cfgs []proxy.Config
	raw, err := ioutil.ReadFile(*config)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(raw, &cfgs)
	if err != nil {
		panic(err)
	}

	prefix := "/proxy/rets"
	ops := map[string]string{
		"Login":       fmt.Sprintf("%s/login/", prefix),
		"GetMetadata": fmt.Sprintf("%s/metadata/", prefix),
		"Search":      fmt.Sprintf("%s/search/", prefix),
		"GetObject":   fmt.Sprintf("%s/getobject/", prefix),
	}
	srcs := proxy.NewSources(cfgs)
	// the base /rets/ proxy handler
	http.HandleFunc(ops["Login"], proxy.Login(ops, srcs))
	http.HandleFunc(ops["GetMetadata"], proxy.Metadata(ops, srcs))
	http.HandleFunc(ops["Search"], proxy.Search(ops, srcs))
	http.HandleFunc(ops["GetObject"], proxy.GetObject(ops, srcs))
	// web server
	err = http.ListenAndServe(*bind, nil)
	if err != nil {
		panic(err)
	}
}
802690
func DefaultConfig() *Config {
	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	conf := &Config{
		Build:                       version.Version,
		Datacenter:                  DefaultDC,
		NodeName:                    hostname,
		RPCAddr:                     DefaultRPCAddr,
		RaftConfig:                  raft.DefaultConfig(),
		SerfLANConfig:               lib.SerfDefaultConfig(),
		SerfWANConfig:               lib.SerfDefaultConfig(),
		SerfFloodInterval:           60 * time.Second,
		ReconcileInterval:           60 * time.Second,
		ProtocolVersion:             ProtocolVersion2Compatible,
		ACLRoleTTL:                  30 * time.Second,
		ACLPolicyTTL:                30 * time.Second,
		ACLTokenTTL:                 30 * time.Second,
		ACLDefaultPolicy:            "allow",
		ACLDownPolicy:               "extend-cache",
		ACLReplicationRate:          1,
		ACLReplicationBurst:         5,
		ACLReplicationApplyLimit:    100, // ops / sec
		ConfigReplicationRate:       1,
		ConfigReplicationBurst:      5,
		ConfigReplicationApplyLimit: 100, // ops / sec
		TombstoneTTL:                15 * time.Minute,
		TombstoneTTLGranularity:     30 * time.Second,
		SessionTTLMin:               10 * time.Second,
		ACLTokenMinExpirationTTL:    1 * time.Minute,
		ACLTokenMaxExpirationTTL:    24 * time.Hour,

		// These are tuned to provide a total throughput of 128 updates
		// per second. If you update these, you should update the client-
		// side SyncCoordinateRateTarget parameter accordingly.
		CoordinateUpdatePeriod:     5 * time.Second,
		CoordinateUpdateBatchSize:  128,
		CoordinateUpdateMaxBatches: 5,

		RPCRate:     rate.Inf,
		RPCMaxBurst: 1000,

		TLSMinVersion: "tls10",

		// TODO (slackpad) - Until #3744 is done, we need to keep these
		// in sync with agent/config/default.go.
		AutopilotConfig: &autopilot.Config{
			CleanupDeadServers:      true,
			LastContactThreshold:    200 * time.Millisecond,
			MaxTrailingLogs:         250,
			ServerStabilizationTime: 10 * time.Second,
		},

		CAConfig: &structs.CAConfiguration{
			Provider: "consul",
			Config: map[string]interface{}{
				"RotationPeriod": "2160h",
				"LeafCertTTL":    "72h",
			},
		},

		ServerHealthInterval: 2 * time.Second,
		AutopilotInterval:    10 * time.Second,
	}

	// Increase our reap interval to 3 days instead of 24h.
	conf.SerfLANConfig.ReconnectTimeout = 3 * 24 * time.Hour
	conf.SerfWANConfig.ReconnectTimeout = 3 * 24 * time.Hour

	// WAN Serf should use the WAN timing, since we are using it
	// to communicate between DC's
	conf.SerfWANConfig.MemberlistConfig = memberlist.DefaultWANConfig()

	// Ensure we don't have port conflicts
	conf.SerfLANConfig.MemberlistConfig.BindPort = DefaultLANSerfPort
	conf.SerfWANConfig.MemberlistConfig.BindPort = DefaultWANSerfPort

	// Raft protocol version 3 only works with other Consul servers running
	// 0.8.0 or later.
	conf.RaftConfig.ProtocolVersion = 3

	// Disable shutdown on removal
	conf.RaftConfig.ShutdownOnRemove = false

	// Check every 5 seconds to see if there are enough new entries for a snapshot, can be overridden
	conf.RaftConfig.SnapshotInterval = 30 * time.Second

	// Snapshots are created every 16384 entries by default, can be overridden
	conf.RaftConfig.SnapshotThreshold = 16384

	return conf
}
1090196
func (o *Options) SetDefaults() {
	// Set the socket type.
	if o.HTTPSocketType != HTTPSocketTypeNone &&
		o.HTTPSocketType != HTTPSocketTypeTCP &&
		o.HTTPSocketType != HTTPSocketTypeUnix {
		o.HTTPSocketType = HTTPSocketTypeTCP
	}

	// Set the listen address.
	if len(o.HTTPListenAddress) == 0 {
		o.HTTPListenAddress = ":80"
	}

	// Set the handle URL.
	if len(o.HTTPHandleURL) == 0 {
		o.HTTPHandleURL = "/glue/"
	}

	// Be sure that the handle URL ends with a slash.
	if !strings.HasSuffix(o.HTTPHandleURL, "/") {
		o.HTTPHandleURL += "/"
	}

	// Set the default check origin function if not set.
	if o.CheckOrigin == nil {
		o.CheckOrigin = checkSameOrigin
	}
}
868222
func DefaultConfig() *Config {
	return &Config{
		ApiAddress:        "http://api.bosh-lite.com",
		Username:          "admin",
		Password:          "admin",
		Token:             "",
		SkipSslValidation: false,
		HttpClient:        http.DefaultClient,
		UserAgent:         "Go-CF-client/1.1",
	}
}
426146
func (this *HttpClient) Defaults(defaults Map) *HttpClient {
	options, headers := parseMap(defaults)

	// merge options
	if this.options == nil {
		this.options = options
	} else {
		for k, v := range options {
			this.options[k] = v
		}
	}

	// merge headers
	if this.Headers == nil {
		this.Headers = headers
	} else {
		for k, v := range headers {
			this.Headers[k] = v
		}
	}

	return this
}