Debian Codegraph @

config/confighttp/clientinfohandler.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package confighttp // import "go.opentelemetry.io/collector/config/confighttp"
5
6 import (
7 "context"
8 "net"
9 "net/http"
10
11 "go.opentelemetry.io/collector/client"
12 )
13
14 // clientInfoHandler is an http.Handler that enhances the incoming request context with client.Info.
15 type clientInfoHandler struct {
16 next http.Handler
17
18 // include client metadata or not
19 includeMetadata bool
20 }
21
22 // ServeHTTP intercepts incoming HTTP requests, replacing the request's context with one that contains
23 // a client.Info containing the client's IP address.
24 func (h *clientInfoHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
25 req = req.WithContext(contextWithClient(req, h.includeMetadata)) //nolint:contextcheck //context already handled through contextWithClient
26 h.next.ServeHTTP(w, req)
27 }
28
29 // contextWithClient attempts to add the client IP address to the client.Info from the context. When no
30 // client.Info exists in the context, one is created.
31 func contextWithClient(req *http.Request, includeMetadata bool) context.Context {
32 cl := client.FromContext(req.Context())
33
34 ip := parseIP(req.RemoteAddr)
35 if ip != nil {
36 cl.Addr = ip
37 }
38
39 if includeMetadata {
40 md := req.Header.Clone()
41 if md.Get(client.MetadataHostName) == "" && req.Host != "" {
42 md.Add(client.MetadataHostName, req.Host)
43 }
44
45 cl.Metadata = client.NewMetadata(md)
46 }
47
48 ctx := client.NewContext(req.Context(), cl)
49 return ctx
50 }
51
52 // parseIP parses the given string for an IP address. The input string might contain the port,
53 // but must not contain a protocol or path. Suitable for getting the IP part of a client connection.
54 func parseIP(source string) *net.IPAddr {
55 ipstr, _, err := net.SplitHostPort(source)
56 if err == nil {
57 source = ipstr
58 }
59 ip := net.ParseIP(source)
60 if ip != nil {
61 return &net.IPAddr{
62 IP: ip,
63 }
64 }
65 return nil
66 }