| 1 |
//go:build unix |
| 2 |
|
| 3 |
package dns |
| 4 |
|
| 5 |
import ( |
| 6 |
"net" |
| 7 |
"sync" |
| 8 |
|
| 9 |
"golang.org/x/net/ipv4" |
| 10 |
) |
| 11 |
|
| 12 |
// listenUDP starts a UDP listener for the server. |
| 13 |
func (srv *Server) listenUDP(pc net.PacketConn) { |
| 14 |
if f := srv.NotifyStartedFunc; f != nil { |
| 15 |
f(srv.ctx) |
| 16 |
} |
| 17 |
|
| 18 |
var wg sync.WaitGroup |
| 19 |
xpc := ipv4.NewPacketConn(pc) // suspect this somehow works on Linux, but not other OSes. |
| 20 |
|
| 21 |
slab := make([]byte, BatchSize*srv.UDPSize) |
| 22 |
|
| 23 |
bufs := make([][]byte, BatchSize) |
| 24 |
msgs := make([]ipv4.Message, BatchSize) |
| 25 |
|
| 26 |
for i := range BatchSize { |
| 27 |
start := i * srv.UDPSize |
| 28 |
|
| 29 |
bufs[i] = slab[start : start+srv.UDPSize] |
| 30 |
msgs[i].Buffers = [][]byte{bufs[i]} |
| 31 |
|
| 32 |
msgs[i].OOB = make([]byte, oobSize) |
| 33 |
} |
| 34 |
|
| 35 |
udpConn := pc.(*net.UDPConn) |
| 36 |
Read: |
| 37 |
for { |
| 38 |
select { |
| 39 |
default: |
| 40 |
// If we set the read deadline is will timeout every ReadTimeout and reallocate the msgs, we are |
| 41 |
// also a server, so just wait for incoming messages. |
| 42 |
|
| 43 |
n, err := xpc.ReadBatch(msgs, 0) |
| 44 |
if err != nil { |
| 45 |
continue Read |
| 46 |
} |
| 47 |
_ = msgs[:n] // eliminate further bounds checking |
| 48 |
|
| 49 |
for i := range msgs[:n] { |
| 50 |
r := &Msg{Data: srv.MsgPool.Get()} |
| 51 |
copy(r.Data, msgs[i].Buffers[0][:msgs[i].N]) |
| 52 |
r.Data = r.Data[:msgs[i].N] |
| 53 |
|
| 54 |
oob := make([]byte, oobSize) |
| 55 |
copy(oob, msgs[i].OOB[:msgs[i].NN]) |
| 56 |
|
| 57 |
w := &response{conn: udpConn, session: &Session{msgs[i].Addr.(*net.UDPAddr), oob}} |
| 58 |
wg.Add(1) // no wg.Go to prevent defer usage |
| 59 |
go func() { |
| 60 |
srv.serveDNS(w, r) |
| 61 |
wg.Done() |
| 62 |
}() |
| 63 |
|
| 64 |
bufs[i] = bufs[i][:0] |
| 65 |
} |
| 66 |
case <-srv.shutdown: |
| 67 |
pc.Close() |
| 68 |
wg.Wait() |
| 69 |
close(srv.exited) |
| 70 |
return |
| 71 |
} |
| 72 |
} |
| 73 |
} |