本文整理汇总了Golang中github.com/miekg/dns.Msg.Len方法的典型用法代码示例。如果您正苦于以下问题:Golang Msg.Len方法的具体用法?Golang Msg.Len怎么用?Golang Msg.Len使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/miekg/dns.Msg
的用法示例。
在下文中一共展示了Msg.Len方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeDNS
func (l Logger) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := middleware.State{W: w, Req: r}
for _, rule := range l.Rules {
if middleware.Name(rule.NameScope).Matches(state.Name()) {
responseRecorder := middleware.NewResponseRecorder(w)
rcode, err := l.Next.ServeDNS(ctx, responseRecorder, r)
if rcode > 0 {
// There was an error up the chain, but no response has been written yet.
// The error must be handled here so the log entry will record the response size.
if l.ErrorFunc != nil {
l.ErrorFunc(responseRecorder, r, rcode)
} else {
rc := middleware.RcodeToString(rcode)
answer := new(dns.Msg)
answer.SetRcode(r, rcode)
state.SizeAndDo(answer)
metrics.Report(state, metrics.Dropped, rc, answer.Len(), time.Now())
w.WriteMsg(answer)
}
rcode = 0
}
rep := middleware.NewReplacer(r, responseRecorder, CommonLogEmptyValue)
rule.Log.Println(rep.Replace(rule.Format))
return rcode, err
}
}
return l.Next.ServeDNS(ctx, w, r)
}
示例2: setReply
// set the reply for the entry
// returns True if the entry has changed the validUntil time
func (e *cacheEntry) setReply(reply *dns.Msg, ttl int, flags uint8, now time.Time) bool {
var prevValidUntil time.Time
if e.Status == stResolved {
if reply != nil {
Debug.Printf("[cache msgid %d] replacing response in cache", reply.MsgHdr.Id)
}
prevValidUntil = e.validUntil
}
e.Status = stResolved
e.Flags = flags
e.putTime = now
if ttl != nullTTL {
e.validUntil = now.Add(time.Second * time.Duration(ttl))
} else if reply != nil {
// calculate the validUntil from the reply TTL
var minTTL uint32 = math.MaxUint32
for _, rr := range reply.Answer {
ttl := rr.Header().Ttl
if ttl < minTTL {
minTTL = ttl // TODO: improve the minTTL calculation (maybe we should skip some RRs)
}
}
e.validUntil = now.Add(time.Second * time.Duration(minTTL))
}
if reply != nil {
e.reply = *reply
e.ReplyLen = reply.Len()
}
return (prevValidUntil != e.validUntil)
}
示例3: ReportErrorCount
func ReportErrorCount(resp *dns.Msg, sys System) {
if resp == nil || errorCount == nil {
return
}
if resp.Truncated {
errorCount.WithLabelValues(string(sys), string(Truncated)).Inc()
return
}
if resp.Len() > dns.MaxMsgSize {
errorCount.WithLabelValues(string(sys), string(Overflow)).Inc()
return
}
switch resp.Rcode {
case dns.RcodeServerFailure:
errorCount.WithLabelValues(string(sys), string(Fail)).Inc()
case dns.RcodeRefused:
errorCount.WithLabelValues(string(sys), string(Refused)).Inc()
case dns.RcodeNameError:
errorCount.WithLabelValues(string(sys), string(Nxdomain)).Inc()
// nodata ??
}
}
示例4: WriteMsg
// WriteMsg records the status code and calls the
// underlying ResponseWriter's WriteMsg method.
func (r *ResponseRecorder) WriteMsg(res *dns.Msg) error {
r.rcode = res.Rcode
// We may get called multiple times (axfr for instance).
// Save the last message, but add the sizes.
r.size += res.Len()
r.msg = res
return r.ResponseWriter.WriteMsg(res)
}
示例5: Sign
// Sign signs a message m, it takes care of negative or nodata responses as
// well by synthesising NSEC3 records. It will also cache the signatures, using
// a hash of the signed data as a key.
// We also fake the origin TTL in the signature, because we don't want to
// throw away signatures when services decide to have longer TTL. So we just
// set the origTTL to 60.
// TODO(miek): revisit origTTL
func (s *server) Sign(m *dns.Msg, bufsize uint16) {
now := time.Now().UTC()
incep := uint32(now.Add(-3 * time.Hour).Unix()) // 2+1 hours, be sure to catch daylight saving time and such
expir := uint32(now.Add(7 * 24 * time.Hour).Unix()) // sign for a week
defer func() {
promCacheSize.WithLabelValues("signature").Set(float64(s.scache.Size()))
}()
for _, r := range rrSets(m.Answer) {
if r[0].Header().Rrtype == dns.TypeRRSIG {
continue
}
if !dns.IsSubDomain(s.config.Domain, r[0].Header().Name) {
continue
}
if sig, err := s.signSet(r, now, incep, expir); err == nil {
m.Answer = append(m.Answer, sig)
}
}
for _, r := range rrSets(m.Ns) {
if r[0].Header().Rrtype == dns.TypeRRSIG {
continue
}
if !dns.IsSubDomain(s.config.Domain, r[0].Header().Name) {
continue
}
if sig, err := s.signSet(r, now, incep, expir); err == nil {
m.Ns = append(m.Ns, sig)
}
}
for _, r := range rrSets(m.Extra) {
if r[0].Header().Rrtype == dns.TypeRRSIG || r[0].Header().Rrtype == dns.TypeOPT {
continue
}
if !dns.IsSubDomain(s.config.Domain, r[0].Header().Name) {
continue
}
if sig, err := s.signSet(r, now, incep, expir); err == nil {
m.Extra = append(m.Extra, sig)
}
}
if bufsize >= 512 || bufsize <= 4096 {
// TCP here?
promErrorCount.WithLabelValues("truncated").Inc()
m.Truncated = m.Len() > int(bufsize)
}
o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
o.SetDo()
o.SetUDPSize(4096) // TODO(miek): echo client
m.Extra = append(m.Extra, o)
return
}
示例6: DefaultErrorFunc
// DefaultErrorFunc responds to an DNS request with an error.
func DefaultErrorFunc(w dns.ResponseWriter, r *dns.Msg, rcode int) {
state := middleware.State{W: w, Req: r}
rc := middleware.RcodeToString(rcode)
answer := new(dns.Msg)
answer.SetRcode(r, rcode)
state.SizeAndDo(answer)
metrics.Report(state, metrics.Dropped, rc, answer.Len(), time.Now())
w.WriteMsg(answer)
}
示例7: truncateResp
func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) {
if !isTCP {
resp.Truncated = true
}
// trim the Answer RRs one by one till the whole message fits
// within the reply size
for resp.Len() > maxSize {
resp.Answer = resp.Answer[:len(resp.Answer)-1]
}
}
示例8: metricSizeAndDuration
// metricSizeAndDuration sets the size and duration metrics.
func metricSizeAndDuration(resp *dns.Msg, start time.Time, tcp bool) {
net := "udp"
rlen := float64(0)
if tcp {
net = "tcp"
}
if resp != nil {
rlen = float64(resp.Len())
}
promRequestDuration.WithLabelValues(net).Observe(float64(time.Since(start)) / float64(time.Second))
promResponseSize.WithLabelValues(net).Observe(rlen)
}
示例9: ReportDuration
func ReportDuration(resp *dns.Msg, start time.Time, sys System) {
if requestDuration == nil || responseSize == nil {
return
}
rlen := float64(0)
if resp != nil {
rlen = float64(resp.Len())
}
requestDuration.WithLabelValues(string(sys)).Observe(float64(time.Since(start)) / float64(time.Second))
responseSize.WithLabelValues(string(sys)).Observe(rlen)
}
示例10: Respond
func Respond(w dns.ResponseWriter, req *dns.Msg, records []dns.RR) {
m := new(dns.Msg)
m.SetReply(req)
m.Authoritative = true
m.RecursionAvailable = true
m.Compress = true
m.Answer = records
// Figure out the max response size
bufsize := uint16(512)
tcp := isTcp(w)
if o := req.IsEdns0(); o != nil {
bufsize = o.UDPSize()
}
if tcp {
bufsize = dns.MaxMsgSize - 1
} else if bufsize < 512 {
bufsize = 512
}
if m.Len() > dns.MaxMsgSize {
fqdn := dns.Fqdn(req.Question[0].Name)
log.WithFields(log.Fields{"fqdn": fqdn}).Debug("Response too big, dropping Extra")
m.Extra = nil
if m.Len() > dns.MaxMsgSize {
log.WithFields(log.Fields{"fqdn": fqdn}).Debug("Response still too big")
m := new(dns.Msg)
m.SetRcode(m, dns.RcodeServerFailure)
}
}
if m.Len() > int(bufsize) && !tcp {
log.Debug("Too big 1")
m.Extra = nil
if m.Len() > int(bufsize) {
log.Debug("Too big 2")
m.Answer = nil
m.Truncated = true
}
}
err := w.WriteMsg(m)
if err != nil {
log.Warn("Failed to return reply: ", err, m.Len())
}
}
示例11: TestFit
func TestFit(t *testing.T) {
m := new(dns.Msg)
m.SetQuestion("miek.nl", dns.TypeA)
rr, _ := dns.NewRR("www.miek.nl. IN SRV 10 10 8080 blaat.miek.nl.")
for i := 0; i < 101; i++ {
m.Answer = append(m.Answer, rr)
}
// Uncompresses length is now 4424. Try trimming this to 1927
Fit(m, 1927, true)
if m.Len() > 1927 {
t.Fatalf("failed to fix message, expected < %d, got %d", 1927, m.Len())
}
}
示例12: trimAnswers
// trimAnswers makes sure a UDP response is not longer than allowed by RFC 1035.
// We first enforce an arbitrary limit, and then make sure the response doesn't
// exceed 512 bytes.
func trimAnswers(resp *dns.Msg) (trimmed bool) {
numAnswers := len(resp.Answer)
// This cuts UDP responses to a useful but limited number of responses.
if numAnswers > maxServiceResponses {
resp.Answer = resp.Answer[:maxServiceResponses]
}
// This enforces the hard limit of 512 bytes per the RFC.
for len(resp.Answer) > 0 && resp.Len() > 512 {
resp.Answer = resp.Answer[:len(resp.Answer)-1]
}
return len(resp.Answer) < numAnswers
}
示例13: trimUDPAnswers
// trimUDPAnswers makes sure a UDP response is not longer than allowed by RFC
// 1035. Enforce an arbitrary limit that can be further ratcheted down by
// config, and then make sure the response doesn't exceed 512 bytes.
func trimUDPAnswers(config *DNSConfig, resp *dns.Msg) (trimmed bool) {
numAnswers := len(resp.Answer)
// This cuts UDP responses to a useful but limited number of responses.
maxAnswers := lib.MinInt(maxUDPAnswerLimit, config.UDPAnswerLimit)
if numAnswers > maxAnswers {
resp.Answer = resp.Answer[:maxAnswers]
}
// This enforces the hard limit of 512 bytes per the RFC.
for len(resp.Answer) > 0 && resp.Len() > 512 {
resp.Answer = resp.Answer[:len(resp.Answer)-1]
}
return len(resp.Answer) < numAnswers
}
示例14: truncateResp
func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) {
if !isTCP {
resp.Truncated = true
}
srv := resp.Question[0].Qtype == dns.TypeSRV
// trim the Answer RRs one by one till the whole message fits
// within the reply size
for resp.Len() > maxSize {
resp.Answer = resp.Answer[:len(resp.Answer)-1]
if srv && len(resp.Extra) > 0 {
resp.Extra = resp.Extra[:len(resp.Extra)-1]
}
}
}
示例15: setReply
// set the reply for the entry
// returns True if the entry has changed the validUntil time
func (e *cacheEntry) setReply(reply *dns.Msg, ttl int, flags uint8, now time.Time) bool {
var prevValidUntil time.Time
if e.Status == stResolved {
if reply != nil {
Log.Debugf("[cache msgid %d] replacing response in cache", reply.MsgHdr.Id)
}
prevValidUntil = e.validUntil
}
// make sure we do not overwrite noLocalReplies entries
if flags&CacheNoLocalReplies != 0 {
if e.Flags&CacheNoLocalReplies != 0 {
return false
}
}
if ttl != nullTTL {
e.validUntil = now.Add(time.Second * time.Duration(ttl))
} else if reply != nil {
// calculate the validUntil from the reply TTL
var minTTL uint32 = math.MaxUint32
for _, rr := range reply.Answer {
ttl := rr.Header().Ttl
if ttl < minTTL {
minTTL = ttl // TODO: improve the minTTL calculation (maybe we should skip some RRs)
}
}
e.validUntil = now.Add(time.Second * time.Duration(minTTL))
} else {
Log.Warningf("[cache] no valid TTL could be calculated")
}
e.Status = stResolved
e.Flags = flags
e.putTime = now
if reply != nil {
e.reply = *reply.Copy()
e.ReplyLen = reply.Len()
}
return (prevValidUntil != e.validUntil)
}