// Request sends an ODR request to the LES network (implementation of LesOdrRequest)
554026
func (r *BlockRequest) Request(reqID uint64, peer *peer) error {
	peer.Log().Debug("Requesting block body", "hash", r.Hash)
	return peer.RequestBodies(reqID, r.GetCost(peer), []common.Hash{r.Hash})
}
970945
func (srv *server) request(jsonData []byte, target string) ([]byte, error) {
	result, err := srv.getResultMap(jsonData, target)
	if err != nil {
		return nil, err
	}
	cert := result["certificate"].(string)
	if cert != "" {
		return []byte(cert), nil
	}

	return nil, errors.Wrap(errors.APIClientError, errors.ClientHTTPError, stderr.New("response doesn't contain certificate."))
}
867073
func (c *Conn) Request(m *protocol.Message) (*protocol.Message, error) {
	m.Id = uint64(rand.Int63())
	m.ResponseRequired = true
	if err := c.Send(m); err != nil {
		return nil, err
	}

	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(10 * time.Second)
		timeout <- true
	}()
	resp := make(chan *protocol.Message, 1)
	c.expectedMessages[m.Id] = resp

	var msg *protocol.Message
	var err error
	select {
	case msg = <-resp:
	case <-timeout:
		err = Timeout
	}
	delete(c.expectedMessages, m.Id)
	return msg, err
}
325219
func (this *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) {

	r, err := this.Do(p, req)
	if err != nil {
		return
	}

	rb := bufio.NewReader(r)
	tp := textproto.NewReader(rb)
	resp = new(http.Response)
	// Parse the first line of the response.
	line, err := tp.ReadLine()
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return nil, err
	}
	if i := strings.IndexByte(line, ' '); i == -1 {
		err = &badStringError{"malformed HTTP response", line}
	} else {
		resp.Proto = line[:i]
		resp.Status = strings.TrimLeft(line[i+1:], " ")
	}
	statusCode := resp.Status
	if i := strings.IndexByte(resp.Status, ' '); i != -1 {
		statusCode = resp.Status[:i]
	}
	if len(statusCode) != 3 {
		err = &badStringError{"malformed HTTP status code", statusCode}
	}
	resp.StatusCode, err = strconv.Atoi(statusCode)
	if err != nil || resp.StatusCode < 0 {
		err = &badStringError{"malformed HTTP status code", statusCode}
	}
	var ok bool
	if resp.ProtoMajor, resp.ProtoMinor, ok = http.ParseHTTPVersion(resp.Proto); !ok {
		err = &badStringError{"malformed HTTP version", resp.Proto}
	}
	// Parse the response headers.
	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return nil, err
	}
	resp.Header = http.Header(mimeHeader)
	// TODO: fixTransferEncoding ?
	resp.TransferEncoding = resp.Header["Transfer-Encoding"]
	resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

	if chunked(resp.TransferEncoding) {
		resp.Body = ioutil.NopCloser(httputil.NewChunkedReader(rb))
	} else {
		resp.Body = ioutil.NopCloser(rb)
	}
	return
}
164212
func (c *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) {
	r, err := c.Do(p, req)
	if err != nil {
		return
	}

	rb := bufio.NewReader(r)
	tp := textproto.NewReader(rb)
	resp = new(http.Response)

	if c.readTimeout != 0 {
		if err = c.conn.SetReadDeadline(time.Now().Add(c.readTimeout)); err != nil {
			return
		}
	}

	// Parse the response headers.
	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil && err != io.EOF {
		return
	}
	resp.Header = http.Header(mimeHeader)

	if resp.Header.Get("Status") != "" {
		statusParts := strings.SplitN(resp.Header.Get("Status"), " ", 2)
		resp.StatusCode, err = strconv.Atoi(statusParts[0])
		if err != nil {
			return
		}
		if len(statusParts) > 1 {
			resp.Status = statusParts[1]
		}

	} else {
		resp.StatusCode = http.StatusOK
	}

	// TODO: fixTransferEncoding ?
	resp.TransferEncoding = resp.Header["Transfer-Encoding"]
	resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

	if chunked(resp.TransferEncoding) {
		resp.Body = clientCloser{c, httputil.NewChunkedReader(rb)}
	} else {
		resp.Body = clientCloser{c, ioutil.NopCloser(rb)}
	}
	return
}
918300
func (m *model) Request(deviceID protocol.DeviceID, folder, name string, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (out protocol.RequestResponse, err error) {
	if size < 0 || offset < 0 {
		return nil, protocol.ErrInvalid
	}

	m.fmut.RLock()
	folderCfg, ok := m.folderCfgs[folder]
	folderIgnores := m.folderIgnores[folder]
	m.fmut.RUnlock()
	if !ok {
		// The folder might be already unpaused in the config, but not yet
		// in the model.
		l.Debugf("Request from %s for file %s in unstarted folder %q", deviceID, name, folder)
		return nil, protocol.ErrGeneric
	}

	if !folderCfg.SharedWith(deviceID) {
		l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
		return nil, protocol.ErrGeneric
	}
	if folderCfg.Paused {
		l.Debugf("Request from %s for file %s in paused folder %q", deviceID, name, folder)
		return nil, protocol.ErrGeneric
	}

	// Make sure the path is valid and in canonical form
	if name, err = fs.Canonicalize(name); err != nil {
		l.Debugf("Request from %s in folder %q for invalid filename %s", deviceID, folder, name)
		return nil, protocol.ErrGeneric
	}

	if deviceID != protocol.LocalDeviceID {
		l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, size, fromTemporary)
	}

	if fs.IsInternal(name) {
		l.Debugf("%v REQ(in) for internal file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
		return nil, protocol.ErrInvalid
	}

	if folderIgnores.Match(name).IsIgnored() {
		l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
		return nil, protocol.ErrInvalid
	}

	folderFs := folderCfg.Filesystem()

	if err := osutil.TraversesSymlink(folderFs, filepath.Dir(name)); err != nil {
		l.Debugf("%v REQ(in) traversal check: %s - %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
		return nil, protocol.ErrNoSuchFile
	}

	// Restrict parallel requests by connection/device

	m.pmut.RLock()
	limiter := m.connRequestLimiters[deviceID]
	m.pmut.RUnlock()

	if limiter != nil {
		limiter.take(int(size))
	}

	// The requestResponse releases the bytes to the limiter when its Close method is called.
	res := newRequestResponse(int(size))
	defer func() {
		// Close it ourselves if it isn't returned due to an error
		if err != nil {
			res.Close()
		}
	}()

	if limiter != nil {
		go func() {
			res.Wait()
			limiter.give(int(size))
		}()
	}

	// Only check temp files if the flag is set, and if we are set to advertise
	// the temp indexes.
	if fromTemporary && !folderCfg.DisableTempIndexes {
		tempFn := fs.TempName(name)

		if info, err := folderFs.Lstat(tempFn); err != nil || !info.IsRegular() {
			// Reject reads for anything that doesn't exist or is something
			// other than a regular file.
			l.Debugf("%v REQ(in) failed stating temp file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
			return nil, protocol.ErrNoSuchFile
		}
		err := readOffsetIntoBuf(folderFs, tempFn, offset, res.data)
		if err == nil && scanner.Validate(res.data, hash, weakHash) {
			return res, nil
		}
		// Fall through to reading from a non-temp file, just incase the temp
		// file has finished downloading.
	}

	if info, err := folderFs.Lstat(name); err != nil || !info.IsRegular() {
		// Reject reads for anything that doesn't exist or is something
		// other than a regular file.
		l.Debugf("%v REQ(in) failed stating file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
		return nil, protocol.ErrNoSuchFile
	}

	if err := readOffsetIntoBuf(folderFs, name, offset, res.data); fs.IsNotExist(err) {
		l.Debugf("%v REQ(in) file doesn't exist: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
		return nil, protocol.ErrNoSuchFile
	} else if err != nil {
		l.Debugf("%v REQ(in) failed reading file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
		return nil, protocol.ErrGeneric
	}

	if !scanner.Validate(res.data, hash, weakHash) {
		m.recheckFile(deviceID, folderFs, folder, name, size, offset, hash)
		l.Debugf("%v REQ(in) failed validating data (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
		return nil, protocol.ErrNoSuchFile
	}

	return res, nil
}
1062970
func (c *Client) Get() *Request {
	req := c.Request()
	req.Method("GET")
	return req
}
1155446
func (cn *connection) request(r request, mw messageWriter) bool {
	if _, ok := cn.requests[r]; ok {
		panic("chunk already requested")
	}
	if !cn.PeerHasPiece(pieceIndex(r.Index)) {
		panic("requesting piece peer doesn't have")
	}
	if _, ok := cn.t.conns[cn]; !ok {
		panic("requesting but not in active conns")
	}
	if cn.closed.IsSet() {
		panic("requesting when connection is closed")
	}
	if cn.PeerChoked {
		if cn.peerAllowedFast.Get(int(r.Index)) {
			torrent.Add("allowed fast requests sent", 1)
		} else {
			panic("requesting while choked and not allowed fast")
		}
	}
	if cn.t.hashingPiece(pieceIndex(r.Index)) {
		panic("piece is being hashed")
	}
	if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
		panic("piece is queued for hash")
	}
	if cn.requests == nil {
		cn.requests = make(map[request]struct{})
	}
	cn.requests[r] = struct{}{}
	if cn.validReceiveChunks == nil {
		cn.validReceiveChunks = make(map[request]struct{})
	}
	cn.validReceiveChunks[r] = struct{}{}
	cn.t.pendingRequests[r]++
	cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() {
		torrent.Add("duplicate request timeouts", 1)
		cn.mu().Lock()
		defer cn.mu().Unlock()
		delete(cn.t.lastRequested, r)
		for cn := range cn.t.conns {
			if cn.PeerHasPiece(pieceIndex(r.Index)) {
				cn.updateRequests()
			}
		}
	})
	cn.updateExpectingChunks()
	return mw(pp.Message{
		Type:   pp.Request,
		Index:  r.Index,
		Begin:  r.Begin,
		Length: r.Length,
	})
}
1014132
func (l *Linode) Request(action string, params Parameters, result interface{}) (*Response, error) {
	// Initialize the request.
	req, err := http.NewRequest("GET", l.apiEndpoint, nil)
	if err != nil {
		return nil, NewError(err)
	}
	params.Set(apiAction, action)
	params.Set(apiKey, l.apiKey)
	req.URL.RawQuery = params.Encode()

	// Make the request.
	resp, err := client.Do(req)
	if err != nil {
		return nil, NewError(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, NewError(fmt.Errorf("Expected status code %d, received %d", http.StatusOK, resp.StatusCode))
	}

	// Decode the response.
	var response *Response
	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&response); err != nil {
		return nil, NewError(err)
	}

	// Decode the raw data into action-specific data.
	if result != nil {
		if err = json.Unmarshal(response.RawData, &result); err != nil {
			return nil, NewError(err)
		}
		response.Data = result
	}

	// If we have errors in the response, return both the response as well
	// as an API error.
	if len(response.Errors) != 0 {
		return response, NewApiError(response.Errors[0].Code, response.Errors[0].Message)
	}
	return response, nil
}
965454
func (s *Adaptor) request(method string, url string, params url.Values) (m map[string]interface{}, err error) {
	var resp *http.Response

	if method == "POST" {
		resp, err = http.PostForm(url, params)
	} else if method == "GET" {
		resp, err = http.Get(url)
	}

	if err != nil {
		return
	}

	buf, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return
	}

	json.Unmarshal(buf, &m)

	if resp.Status != "200 OK" {
		err = fmt.Errorf("%v: error communicating to the Particle cloud", resp.Status)
	} else if _, ok := m["error"]; ok {
		err = errors.New(m["error"].(string))
	}

	return
}
943942
func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) {
	params, err := client.Payload(command)
	if err != nil {
		return nil, err
	}
	signature, err := client.Sign(params)
	if err != nil {
		return nil, err
	}
	params.Add("signature", signature)

	method := "GET"
	query := params.Encode()
	url := fmt.Sprintf("%s?%s", client.Endpoint, query)

	var body io.Reader
	// respect Internet Explorer limit of 2048
	if len(url) > 2048 {
		url = client.Endpoint
		method = "POST"
		body = strings.NewReader(query)
	}

	request, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	request = request.WithContext(ctx)
	request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version))

	if method == "POST" {
		request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		request.Header.Add("Content-Length", strconv.Itoa(len(query)))
	}

	resp, err := client.HTTPClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close() // nolint: errcheck

	contentType := resp.Header.Get("content-type")

	if !strings.Contains(contentType, "application/json") {
		return nil, fmt.Errorf(`body content-type response expected "application/json", got %q`, contentType)
	}

	text, err := client.parseResponse(resp, client.APIName(command))
	if err != nil {
		return nil, err
	}

	return text, nil
}
1111339
func (r *ReceiptsRequest) Request(reqID uint64, peer *peer) error {
	peer.Log().Debug("Requesting block receipts", "hash", r.Hash)
	return peer.RequestReceipts(reqID, r.GetCost(peer), []common.Hash{r.Hash})
}
809846
func (inv *Investigate) Request(req *http.Request) (*http.Response, error) {
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", inv.key))
	resp := new(http.Response)
	var err error
	tries := 0

	for ; resp.Body == nil && tries <= maxTries; tries++ {
		inv.Logf("%s %s\n", req.Method, req.URL.String())
		resp, err = inv.client.Do(req)
		if err != nil || (resp.StatusCode >= 400 && resp.StatusCode < 600) {
			// if it's a 400 error code, just return an error.
			// otherwise, if it's a server error, retry
			if resp.StatusCode >= 400 && resp.StatusCode < 500 {
				errStr := fmt.Sprintf("error: %v", err)
				inv.Log(errStr)
				inv.LogHTTPResponseBody(resp.Body)
				return nil, errors.New(errStr)
			}

			if tries == maxTries {
				errStr := fmt.Sprintf("error: %v\nFailed all attempts. Skipping.", err)
				log.Print(errStr)
				return nil, errors.New(errStr)
			}

			log.Printf("\nerror: %v\nTrying again: Attempt %d/%d\n", err, tries+1, maxTries)
			resp = new(http.Response)
		}
	}

	return resp, err
}
743786
func Request(requests ...mesos.Request) *scheduler.Call {
	return &scheduler.Call{
		Type: scheduler.Call_REQUEST,
		Request: &scheduler.Call_Request{
			Requests: requests,
		},
	}
}
868934
func (requestor *AuroraRequestor) Request(relativeURL string, method string, body []byte) ([]byte, error) {
	req, err := requestor.buildRequest(relativeURL, method, body)

	client := http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		logrus.Errorf("Failed request: %s", err)
		return nil, err
	}

	defer resp.Body.Close()

	rawResponse, err := httputil.DumpResponse(resp, true)
	logrus.Debugf("Received raw response:\n%s", rawResponse)
	if err != nil {
		logrus.Errorf("Failed to dump response: %s", err)
	}

	response, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logrus.Errorf("Failed to read response: %s", response)
		return nil, err
	}

	response, err = requestor.testInvalidResponse(resp, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
358768
func (t traceV2) Request(req *http.Request) (err error) {
	origAuth := req.Header.Get("Authorization")

	if strings.TrimSpace(origAuth) != "" {
		// Authorization (S3 v2 signature) Format:
		// Authorization: AWS AKIAJVA5BMMU2RHO6IO1:Y10YHUZ0DTUterAUI6w3XKX7Iqk=

		// Set a temporary redacted auth
		req.Header.Set("Authorization", "AWS **REDACTED**:**REDACTED**")

		var reqTrace []byte
		reqTrace, err = httputil.DumpRequestOut(req, false) // Only display header
		if err == nil {
			console.Debug(string(reqTrace))
		}

		// Undo
		req.Header.Set("Authorization", origAuth)
	}
	return err
}
1099147
func (r *Resource) Request(method string, body ...interface{}) *http.Request {
	rdr := io.MultiReader() // empty body by default
	if len(body) != 0 {
		rdr = encode(body[0])
	}
	req, err := http.NewRequest(method, r.u.String(), rdr)
	if err != nil {
		panic(err)
	}
	return req
}