newDoHReq returns new DNS request parsed from the given HTTP request. In case of invalid request returns nil and the suitable status code for an HTTP error response. l must not be nil.
( ctx context.Context, r *http.Request, l *slog.Logger, )
| 131 | // case of invalid request returns nil and the suitable status code for an HTTP |
| 132 | // error response. l must not be nil. |
| 133 | func newDoHReq( |
| 134 | ctx context.Context, |
| 135 | r *http.Request, |
| 136 | l *slog.Logger, |
| 137 | ) (req *dns.Msg, statusCode int) { |
| 138 | var buf []byte |
| 139 | var err error |
| 140 | |
| 141 | switch r.Method { |
| 142 | case http.MethodGet: |
| 143 | dnsParam := r.URL.Query().Get("dns") |
| 144 | buf, err = base64.RawURLEncoding.DecodeString(dnsParam) |
| 145 | if len(buf) == 0 || err != nil { |
| 146 | l.DebugContext( |
| 147 | ctx, |
| 148 | "parsing dns request from http get param", |
| 149 | "param_name", dnsParam, |
| 150 | slogutil.KeyError, err, |
| 151 | ) |
| 152 | |
| 153 | return nil, http.StatusBadRequest |
| 154 | } |
| 155 | case http.MethodPost: |
| 156 | contentType := r.Header.Get(httphdr.ContentType) |
| 157 | if contentType != "application/dns-message" { |
| 158 | l.DebugContext(ctx, "unsupported media type", "content_type", contentType) |
| 159 | |
| 160 | return nil, http.StatusUnsupportedMediaType |
| 161 | } |
| 162 | |
| 163 | limitBody := ioutil.LimitReader(r.Body, dns.MaxMsgSize) |
| 164 | buf, err = io.ReadAll(limitBody) |
| 165 | if err != nil { |
| 166 | l.DebugContext(ctx, "reading http request body", slogutil.KeyError, err) |
| 167 | |
| 168 | return nil, http.StatusBadRequest |
| 169 | } |
| 170 | |
| 171 | defer slogutil.CloseAndLog(ctx, l, r.Body, slog.LevelDebug) |
| 172 | default: |
| 173 | l.DebugContext(ctx, "bad http method", "method", r.Method) |
| 174 | |
| 175 | return nil, http.StatusMethodNotAllowed |
| 176 | } |
| 177 | |
| 178 | req = &dns.Msg{} |
| 179 | if err = req.Unpack(buf); err != nil { |
| 180 | l.DebugContext(ctx, "unpacking http msg", slogutil.KeyError, err) |
| 181 | |
| 182 | return nil, http.StatusBadRequest |
| 183 | } |
| 184 | |
| 185 | return req, http.StatusOK |
| 186 | } |
| 187 | |
| 188 | // ServeHTTP is the http.Handler implementation that handles DoH queries. |
| 189 | // |
no outgoing calls
no test coverage detected
searching dependent graphs…