Debian Codegraph @

response.go

raw
1 package dns
2
3 import (
4 "io"
5 "net"
6 "sync/atomic"
7 "time"
8 )
9
10 // A ResponseWriter interface is used by an DNS handler to construct an DNS response. Note that a response
11 // writer may be used concurrently with TCP pipelining, so be aware that writes need to be atomic. If a write
12 // is attmpted an the Data buffer in the message is empty the write methods will call m.Pack().
13 //
14 // If a ResponseWriter also implements [ResponseController] a write deadline can be set, there is no default.
15 // The default ResponseWriter used a timeout 2s.
16 type ResponseWriter interface {
17 // LocalAddr returns the net.Addr of the server.
18 LocalAddr() net.Addr
19 // RemoteAddr returns the net.Addr of the client that sent the current request.
20 RemoteAddr() net.Addr
21 // Conn returns the underlaying connection. You can get the connection's TLS state via
22 // Conn().(*tls.Conn).ConnectionState().
23 Conn() net.Conn
24 // ResponseWriter must also implement the io.Writer interface.
25 Write([]byte) (int, error)
26 // And the io.Closer interface.
27 Close() error
28 // Session returns the UDP oob session data to correctly route UDP packets.
29 Session() *Session
30 // Hijack lets the caller take over the TCP connection. For UDP this has no effect. The handler is then
31 // responsible for the connection. Packets will still be read and given to the handler, MaxTCPQueries will
32 // be ignored, and the client needs to call Close. Use Conn to check the connection's state.
33 Hijack()
34 }
35
36 // A ResponseController is used by an DNS handler to control the DNS response.
37 type ResponseController interface {
38 // SetWriteDeadline sets the deadline for writing the response.
39 SetWriteDeadline() error
40 }
41
42 // response implements response.Writer. This struct is read-only execpt for hijacked.
43 type response struct {
44 session *Session // used for UDP reply routing.
45 conn net.Conn
46 hijacked atomic.Bool
47 }
48
49 // SetWriteDeadline implements the ResponseController interface.
50 func (w *response) SetWriteDeadline() error {
51 return w.conn.SetWriteDeadline(time.Now().Add(2 * time.Second))
52 }
53 func (w *response) Conn() net.Conn { return w.conn }
54 func (w *response) Session() *Session { return w.session }
55 func (w *response) Write(p []byte) (n int, err error) { return w.conn.Write(p) }
56 func (w *response) Read(p []byte) (n int, err error) { return w.conn.Read(p) }
57 func (w *response) LocalAddr() net.Addr { return w.conn.LocalAddr() }
58 func (w *response) Hijack() { w.hijacked.Store(true) }
59
60 // RemoteAddr implements the ResponseWriter.RemoteAddr method.
61 func (w *response) RemoteAddr() net.Addr {
62 if _, ok := w.conn.(*net.UDPConn); ok {
63 return w.Session().Addr
64 }
65 return w.conn.RemoteAddr()
66 }
67
68 func (w *response) Close() error {
69 if sock, ok := w.conn.(io.Closer); ok {
70 return sock.Close()
71 }
72 return nil
73 }