// This will automatically add the user agent and encode the http request properly
485495
func (m *MWApi) postForm(query url.Values) ([]byte, error) {
	request, err := http.NewRequest("POST", m.url.String(), strings.NewReader(query.Encode()))
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("user-agent", m.userAgent)
	if m.UseBasicAuth {
		request.SetBasicAuth(m.BasicAuthUser, m.BasicAuthPass)
	}
	resp, err := m.client.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if err = checkError(body); err != nil {
		return nil, err
	}

	return body, nil
}
1262753
func WithUserAgent(agent string) ConfigFunc {
	return func(c *Client) {
		ot := c.client.Transport
		c.client.Transport = rtFunc(func(r *http.Request) (*http.Response, error) {
			nagent := agent
			if agent != "" {
				nagent = fmt.Sprintf(" (%s)", nagent)
			}

			r.Header.Set("User-Agent", fmt.Sprintf("go-manifold-%s%s", manifold.Version, nagent))
			return ot.RoundTrip(r)
		})
	}
}
346014
func (s *AgentService) create(req *restful.Request, resp *restful.Response) {
	// TODO (m0sth8): Check permissions
	raw := &agent.Agent{}

	if err := req.ReadEntity(raw); err != nil {
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusBadRequest, services.WrongEntityErr)
		return
	}

	mgr := s.Manager()
	defer mgr.Close()

	raw.Type = agent.System
	raw.Status = agent.StatusRegistered

	// automatically approve agent if it's created by internal agent user
	u := filters.GetUser(req)
	if u.Email == manager.AgentEmail {
		raw.Status = agent.StatusApproved
	}

	obj, err := mgr.Agents.Create(raw)
	if err != nil {
		if mgr.IsDup(err) {
			resp.WriteServiceError(
				http.StatusConflict,
				services.DuplicateErr)
			return
		}
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}

	resp.WriteHeader(http.StatusCreated)
	resp.WriteEntity(obj)
}
870630
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		// We absolutely need to be sure we stay alive up here,
		// even though, in theory, the errors middleware does this.
		if rec := recover(); rec != nil {
			log.Printf("[PANIC] %v", rec)
			DefaultErrorFunc(w, r, http.StatusInternalServerError)
		}
	}()

	// record the User-Agent string (with a cap on its length to mitigate attacks)
	ua := r.Header.Get("User-Agent")
	if len(ua) > 512 {
		ua = ua[:512]
	}
	uaHash := telemetry.FastHash([]byte(ua)) // this is a normalized field
	go telemetry.SetNested("http_user_agent", uaHash, ua)
	go telemetry.AppendUnique("http_user_agent_count", uaHash)
	go telemetry.Increment("http_request_count")

	// copy the original, unchanged URL into the context
	// so it can be referenced by middlewares
	urlCopy := *r.URL
	if r.URL.User != nil {
		userInfo := new(url.Userinfo)
		*userInfo = *r.URL.User
		urlCopy.User = userInfo
	}
	c := context.WithValue(r.Context(), OriginalURLCtxKey, urlCopy)
	r = r.WithContext(c)

	// Setup a replacer for the request that keeps track of placeholder
	// values across plugins.
	replacer := NewReplacer(r, nil, "")
	c = context.WithValue(r.Context(), ReplacerCtxKey, replacer)
	r = r.WithContext(c)

	w.Header().Set("Server", caddy.AppName)

	status, _ := s.serveHTTP(w, r)

	// Fallback error response in case error handling wasn't chained in
	if status >= 400 {
		DefaultErrorFunc(w, r, status)
	}
}
60119
func insertUpstreamUserAgent(upstreamUA string, dockerUA string) string {
	charsToEscape := `();\`
	upstreamUAEscaped := escapeStr(upstreamUA, charsToEscape)
	return fmt.Sprintf("%s UpstreamClient(%s)", dockerUA, upstreamUAEscaped)
}
522306
func OptionUserAgent(userAgent string) OptionRoundtripperFunc {
	return func(j *dcosRoundtripper) error {
		if userAgent == "" {
			return ErrInvalidUserAgent
		}
		j.userAgent = userAgent
		return nil
	}
}
638263
func (s *HTTPServer) AgentService(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Get the proxy ID. Note that this is the ID of a proxy's service instance.
	id := strings.TrimPrefix(req.URL.Path, "/v1/agent/service/")

	// DEPRECATED(managed-proxies) - remove this whole hack.
	//
	// Support managed proxies until they are removed entirely. Since built-in
	// proxy will now use this endpoint, in order to not break managed proxies in
	// the interim until they are removed, we need to mirror the default-setting
	// behavior they had. Rather than thread that through this whole method as
	// special cases that need to be unwound later (and duplicate logic in the
	// proxy config endpoint) just defer to that and then translate the response.
	if managedProxy := s.agent.State.Proxy(id); managedProxy != nil {
		// This is for a managed proxy, use the old endpoint's behavior
		req.URL.Path = "/v1/agent/connect/proxy/" + id
		obj, err := s.AgentConnectProxyConfig(resp, req)
		if err != nil {
			return obj, err
		}
		proxyCfg, ok := obj.(*api.ConnectProxyConfig)
		if !ok {
			return nil, errors.New("internal error")
		}
		// These are all set by defaults so type checks are just sanity checks that
		// should never fail.
		port, ok := proxyCfg.Config["bind_port"].(int)
		if !ok || port < 1 {
			return nil, errors.New("invalid proxy config")
		}
		addr, ok := proxyCfg.Config["bind_address"].(string)
		if !ok || addr == "" {
			return nil, errors.New("invalid proxy config")
		}
		localAddr, ok := proxyCfg.Config["local_service_address"].(string)
		if !ok || localAddr == "" {
			return nil, errors.New("invalid proxy config")
		}
		// Old local_service_address was a host:port
		localAddress, localPortRaw, err := net.SplitHostPort(localAddr)
		if err != nil {
			return nil, err
		}
		localPort, err := strconv.Atoi(localPortRaw)
		if err != nil {
			return nil, err
		}

		reply := &api.AgentService{
			Kind:        api.ServiceKindConnectProxy,
			ID:          proxyCfg.ProxyServiceID,
			Service:     managedProxy.Proxy.ProxyService.Service,
			Port:        port,
			Address:     addr,
			ContentHash: proxyCfg.ContentHash,
			Proxy: &api.AgentServiceConnectProxyConfig{
				DestinationServiceName: proxyCfg.TargetServiceName,
				DestinationServiceID:   proxyCfg.TargetServiceID,
				LocalServiceAddress:    localAddress,
				LocalServicePort:       localPort,
				Config:                 proxyCfg.Config,
				Upstreams:              proxyCfg.Upstreams,
			},
		}
		return reply, nil
	}

	// Maybe block
	var queryOpts structs.QueryOptions
	if parseWait(resp, req, &queryOpts) {
		// parseWait returns an error itself
		return nil, nil
	}

	// Parse the token
	var token string
	s.parseToken(req, &token)

	// Parse hash specially. Eventually this should happen in parseWait and end up
	// in QueryOptions but I didn't want to make very general changes right away.
	hash := req.URL.Query().Get("hash")

	return s.agentLocalBlockingQuery(resp, hash, &queryOpts,
		func(ws memdb.WatchSet) (string, interface{}, error) {

			svcState := s.agent.State.ServiceState(id)
			if svcState == nil {
				resp.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(resp, "unknown proxy service ID: %s", id)
				return "", nil, nil
			}

			svc := svcState.Service

			// Setup watch on the service
			ws.Add(svcState.WatchCh)

			// Check ACLs.
			rule, err := s.agent.resolveToken(token)
			if err != nil {
				return "", nil, err
			}
			if rule != nil && !rule.ServiceRead(svc.Service) {
				return "", nil, acl.ErrPermissionDenied
			}

			var connect *api.AgentServiceConnect
			var proxy *api.AgentServiceConnectProxyConfig

			if svc.Connect.Native {
				connect = &api.AgentServiceConnect{
					Native: svc.Connect.Native,
				}
			}

			if svc.Kind == structs.ServiceKindConnectProxy {
				proxy = svc.Proxy.ToAPI()
			}

			var weights api.AgentWeights
			if svc.Weights != nil {
				err := mapstructure.Decode(svc.Weights, &weights)
				if err != nil {
					return "", nil, err
				}
			}

			// Calculate the content hash over the response, minus the hash field
			reply := &api.AgentService{
				Kind:              api.ServiceKind(svc.Kind),
				ID:                svc.ID,
				Service:           svc.Service,
				Tags:              svc.Tags,
				Meta:              svc.Meta,
				Port:              svc.Port,
				Address:           svc.Address,
				EnableTagOverride: svc.EnableTagOverride,
				Weights:           weights,
				Proxy:             proxy,
				Connect:           connect,
			}

			rawHash, err := hashstructure.Hash(reply, nil)
			if err != nil {
				return "", nil, err
			}

			// Include the ContentHash in the response body
			reply.ContentHash = fmt.Sprintf("%x", rawHash)

			return reply.ContentHash, reply, nil
		})
}
89857
func UserAgentHandler(name string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if ua := r.Header.Get("User-Agent"); ua != "" {
				l := FromContext(r.Context())
				l.SetField(name, ua)
			}
			next.ServeHTTP(w, r)
		})
	}
}
915062
func (c Client) setUserAgent(req *http.Request) {
	req.Header.Set("User-Agent", libraryUserAgent)
	if c.appInfo.appName != "" && c.appInfo.appVersion != "" {
		req.Header.Set("User-Agent", libraryUserAgent+" "+c.appInfo.appName+"/"+c.appInfo.appVersion)
	}
}
44301
func (i *TeleInstance) AddUser(username string, mappings []string) *User {
	log.Infof("teleInstance.AddUser(%v) mapped to %v", username, mappings)
	if mappings == nil {
		mappings = make([]string, 0)
	}
	user := &User{
		Username:      username,
		AllowedLogins: mappings,
	}
	i.Secrets.Users[username] = user
	return user
}
842100
func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) {
	switch ld.Mode {
	case "block", "challenge", "js_challenge", "whitelist":
		break
	default:
		return nil, errors.New(`the User-Agent Block rule mode must be one of "block", "challenge", "js_challenge", "whitelist"`)
	}

	uri := "/zones/" + zoneID + "/firewall/ua_rules"
	res, err := api.makeRequest("POST", uri, ld)
	if err != nil {
		return nil, errors.Wrap(err, errMakeRequestError)
	}

	response := &UserAgentRuleResponse{}
	err = json.Unmarshal(res, &response)
	if err != nil {
		return nil, errors.Wrap(err, errUnmarshalError)
	}

	return response, nil
}
699316
func (s *HTTPServer) AgentServersRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	switch req.Method {
	case "PUT", "POST":
		return s.updateServers(resp, req)
	case "GET":
		return s.listServers(resp, req)
	default:
		return nil, CodedError(405, ErrInvalidMethod)
	}
}
779155
func OperaUserAgent() string {
	platform := "(" + randomPlatform() + "; en-US) Presto/2." + strconv.Itoa(randIntRange(8, 13)) + "." + strconv.Itoa(randIntRange(160, 355)) + " Version/" + strconv.Itoa(randIntRange(10, 13)) + ".00"

	return "Opera/" + strconv.Itoa(randIntRange(8, 10)) + "." + strconv.Itoa(randIntRange(10, 99)) + " " + platform
}
846581
func (s *Http) SetUserAgent(v string) *Http {
	s.UserAgent = &v
	return s
}
595389
func (v *VoiceTarget) AddUser(user *User) {
	v.users = append(v.users, user)
}
927826
func AddRequestHeader(config Config, req *http.Request) *http.Request {
	if config.Debug {
		log.SetLevel(log.DebugLevel)
	}
	timestamp := makeEdgeTimeStamp()
	nonce := createNonce()

	if req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", "application/json")
	}

	_, AkamaiCliEnvOK := os.LookupEnv("AKAMAI_CLI")
	AkamaiCliVersionEnv, AkamaiCliVersionEnvOK := os.LookupEnv("AKAMAI_CLI_VERSION")
	AkamaiCliCommandEnv, AkamaiCliCommandEnvOK := os.LookupEnv("AKAMAI_CLI_COMMAND")
	AkamaiCliCommandVersionEnv, AkamaiCliCommandVersionEnvOK := os.LookupEnv("AKAMAI_CLI_COMMAND_VERSION")

	if AkamaiCliEnvOK && AkamaiCliVersionEnvOK {
		if req.Header.Get("User-Agent") != "" {
			req.Header.Set("User-Agent", req.Header.Get("User-Agent")+" AkamaiCLI/"+AkamaiCliVersionEnv)
		} else {
			req.Header.Set("User-Agent", "AkamaiCLI/"+AkamaiCliVersionEnv)
		}
	}
	if AkamaiCliCommandEnvOK && AkamaiCliCommandVersionEnvOK {
		if req.Header.Get("User-Agent") != "" {
			req.Header.Set("User-Agent", req.Header.Get("User-Agent")+" AkamaiCLI-"+AkamaiCliCommandEnv+"/"+AkamaiCliCommandVersionEnv)
		} else {
			req.Header.Set("User-Agent", "AkamaiCLI-"+AkamaiCliCommandEnv+"/"+AkamaiCliCommandVersionEnv)
		}
	}

	req.Header.Set("Authorization", createAuthHeader(config, req, timestamp, nonce))
	return req
}
1023481
func (api *API) ModifyUserApi(user_id string, active bool) (*User, error) {
	result := new(User)
	req := struct {
		Active bool `json:"active"`
	}{active}
	url := createUrl(api, userPathSegment, user_id, "api")
	err := api.Client.Put(url, &req, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}