Class: Dnsruby::PacketSender

Inherits:
Object
  • Object
show all
Includes:
Socket::Constants
Defined in:
lib/dnsruby/packet_sender.rb

Overview

:nodoc: all

Constant Summary collapse

@@authoritative_cache =
Cache.new
@@recursive_cache =
Cache.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ PacketSender

Can take a hash with the following optional keys :

  • :server
  • :port
  • :use_tcp
  • :tcp_pipelining
  • :tcp_pipelining_max_queries
  • :tcp_idle_timeout
  • :no_tcp
  • :ignore_truncation
  • :src_address
  • :src_address6
  • :src_port
  • :udp_size
  • :tsig
  • :packet_timeout
  • :recurse


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/dnsruby/packet_sender.rb', line 204

def initialize(*args)
  arg=args[0]
  @ipv6 = false
  @packet_timeout = Resolver::DefaultPacketTimeout
  @port = Resolver::DefaultPort
  @udp_size = Resolver::DefaultUDPSize
  @dnssec = Resolver::DefaultDnssec
  @use_tcp = false
  @no_tcp = false
  @tsig = nil
  @ignore_truncation = false
  @src_address = '0.0.0.0'
  @src_address6 = '::'
  @src_port = [0]
  @recurse = true
  @tcp_pipelining = false
  @tcp_pipelining_max_queries = :infinite
  @tcp_idle_timeout = Resolver::DefaultTcpIdleTimeout
  @use_counts = {}
  @process_pid = Process.pid

  ignore_config_resolv_errors = false;
  if arg.nil?
  elsif arg.kind_of? String
    @server = arg
  elsif arg.kind_of? Name
    @server = arg
  elsif arg.kind_of? Hash
    arg.keys.each do |attr|
      begin
        if (attr.to_s == "ignore_config_resolv_errors")
          ignore_config_resolv_errors = arg[attr]
        else
          if ((attr.to_s == "src_address" || attr.to_s == "src_address6") &&
              (arg[attr] == nil || arg[attr] == ""))
          else
            send(attr.to_s + "=", arg[attr])
          end
        end
      rescue Exception => e
        raise if attr.to_s == 'tsig' || ValidationBudget.abort?(e)
        Dnsruby.log.error { "PacketSender : Argument #{attr}, #{arg[attr]} not valid : #{e}\n" }
      end
    end
  end
  # Check server is IP
  # We should allow the call of PacketSender.new to flag just to log an error if this fails
  # and then return null
    if ignore_config_resolv_errors
      begin
        @server=Config.resolve_server(@server)
      rescue ArgumentError
        return
      end
    else
        @server=Config.resolve_server(@server)
    end

  check_ipv6
  #       ResolverRegister::register_single_resolver(self)
end

Instance Attribute Details

#dnssec ⇒ Object

Use DNSSEC for this PacketSender dnssec defaults to false



135
136
137
# File 'lib/dnsruby/packet_sender.rb', line 135

def dnssec
  @dnssec
end

#ignore_truncation ⇒ Object

Don't worry if the response is truncated - return it anyway.

Defaults to false



114
115
116
# File 'lib/dnsruby/packet_sender.rb', line 114

def ignore_truncation
  @ignore_truncation
end

#no_tcp ⇒ Object

Use UDP only - don't use TCP For test/debug purposes only Defaults to false



106
107
108
# File 'lib/dnsruby/packet_sender.rb', line 106

def no_tcp
  @no_tcp
end

#packet_timeout ⇒ Object

Returns the value of attribute packet_timeout.



71
72
73
# File 'lib/dnsruby/packet_sender.rb', line 71

def packet_timeout
  @packet_timeout
end

#port ⇒ Object

The port on the resolver to send queries to.

Defaults to 53



76
77
78
# File 'lib/dnsruby/packet_sender.rb', line 76

def port
  @port
end

#recurse ⇒ Object

should the Recursion Desired bit be set on queries?

Defaults to true



124
125
126
# File 'lib/dnsruby/packet_sender.rb', line 124

def recurse
  @recurse
end

#server ⇒ Object

The address of the resolver to send queries to



131
132
133
# File 'lib/dnsruby/packet_sender.rb', line 131

def server
  @server
end

#src_address ⇒ Object

The source address to send queries from

Defaults to localhost



119
120
121
# File 'lib/dnsruby/packet_sender.rb', line 119

def src_address
  @src_address
end

#tcp_pipelining ⇒ Object

Reuse tcp connection

Defaults to false



86
87
88
# File 'lib/dnsruby/packet_sender.rb', line 86

def tcp_pipelining
  @tcp_pipelining
end

#tcp_pipelining_max_queries ⇒ Object

Limit the number of queries per pipeline



89
90
91
# File 'lib/dnsruby/packet_sender.rb', line 89

def tcp_pipelining_max_queries
  @tcp_pipelining_max_queries
end

#tsig ⇒ Object

The TSIG record to sign/verify messages with



109
110
111
# File 'lib/dnsruby/packet_sender.rb', line 109

def tsig
  @tsig
end

#udp_size ⇒ Object

Maximum UDP DNS payload size. Defaults to 1232 bytes; the minimum is 512. A caller-supplied OPT record sets the receive size for that query.



128
129
130
# File 'lib/dnsruby/packet_sender.rb', line 128

def udp_size
  @udp_size
end

#use_tcp ⇒ Object

Use TCP rather than UDP as the transport.

Defaults to false



81
82
83
# File 'lib/dnsruby/packet_sender.rb', line 81

def use_tcp
  @use_tcp
end

Instance Method Details

#add_opt_rr(packet) ⇒ Object



1187
1188
1189
1190
1191
1192
1193
# File 'lib/dnsruby/packet_sender.rb', line 1187

def add_opt_rr(packet)
  Dnsruby.log.debug { ";; Adding EDNS extension with UDP packetsize  #{udp_packet_size}.\n" }
  # Find OPT by type: its class field stores the payload size. Reuse it and
  # its options, since only one OPT is allowed (RFC 6891 section 6.1.1).
  packet.add_additional(RR::OPT.new(udp_packet_size)) unless packet.get_opt
  packet.get_opt
end

#add_src_port(p) ⇒ Object

Can be a single Integer or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised. "0" means "any valid port" - this is only a viable option if it is the only port in the list. An ArgumentError will be raised if "0" is added to an existing set of source ports.

    res.add_src_port(60000)
    res.add_src_port([60001,60005,60010])
    res.add_src_port(60015..60115)


992
993
994
995
996
997
998
999
1000
# File 'lib/dnsruby/packet_sender.rb', line 992

def add_src_port(p)
  additions = Resolver.get_ports_from(p)
  # Adding a concrete port starts a pool instead of retaining the default
  # random-port sentinel, which would otherwise hide every added port.
  ports = @src_port == [0] && !additions.empty? && !additions.include?(0) ? [] : @src_port
  if Resolver.check_port(additions, ports)
    @src_port = ports + additions
  end
end

#check_ipv6 ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/dnsruby/packet_sender.rb', line 266

def check_ipv6
  begin
    IPv4.create(@server)
    #         @src_address = '0.0.0.0'
    @ipv6=false
  rescue Exception
    begin
      Config.ipv6_server_address(@server)
      #           @src_address6 = '::'
      @ipv6=true
    rescue Exception
      Dnsruby.log.error { "Server is neither IPv4 or IPv6!\n" }
    end
  end
end

#check_response(response, response_bytes, query, client_queue, client_query_id, tcp) ⇒ Object



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/dnsruby/packet_sender.rb', line 1038

def check_response(response, response_bytes, query, client_queue, client_query_id, tcp)
  settings = response_query_settings(client_query_id)
  configuration = settings&.transport_configuration
  dnssec = configuration ? configuration[:dnssec] : @dnssec
  ignore_truncation = settings ? settings.ignore_truncation : @ignore_truncation
  no_tcp = settings ? settings.no_tcp : @no_tcp
  #  @TODO@ Should send_raw avoid this?
  if (!query.send_raw)
    # Reject unrelated packet headers before TSIG verification mutates the
    # response or an error/truncation triggers another transport attempt.
    unless response.header.qr && response.header.opcode == query.header.opcode &&
        response.header.id == query.header.id
      return false
    end
    checking_signature = query.tsig && response.tsig
    sig_value = check_tsig(query, response, response_bytes)
    authenticated_tsig_error = checking_signature && sig_value.kind_of?(TsigError) && response.verified? &&
      response.header.get_header_rcode == RCode.NOTAUTH && [18, 22].include?(response.tsigerror)
    if (sig_value != :okay) && !authenticated_tsig_error
      # Keep waiting for a signed response without extending the deadline
      # (RFC 8945 section 5.4). Save the error in case the query times out.
      settings = response_query_settings(client_query_id)
      settings.authentication_error = sig_value if settings
      return false
    end
    # Match the question when one is present. TCP error replies may omit
    # it (RFC 7766 section 7); UDP replies must match (RFC 5452 section 9.1).
    if (query.class == Update)
      # TODO: Validate the zone section for UPDATE replies.
    elsif !(tcp && response.question.empty? && response.header.get_header_rcode != RCode.NOERROR)
      if ((response.question.size == 0) ||
          (response.question[0].qname.labels != query.question[0].qname.labels) ||
          (response.question[0].qtype != query.question[0].qtype) ||
          (response.question[0].qclass != query.question[0].qclass) ||
          (response.question.length != query.question.length) ||
          (response.header.id != query.header.id))
        TheLog.info("Incorrect packet returned : #{response.to_s}")
        return false
      end
    end
    return sig_value if authenticated_tsig_error
    # Retry a FORMERR without optional EDNS (RFC 6891 section 6.2.2).
    # Queries requiring DNSSEC validation must keep EDNS and DO.
    if ((response.header.get_header_rcode == RCode.FORMERR) &&
        query.get_opt && !(dnssec && query.do_validation))
      # EDNS negotiation belongs to this attempt, not to the caller's raw
      # mode or Message (which may also be in use by another nameserver).
      retry_query = query.dup
      retry_query.header = query.header.dup
      retry_query.remove_additional
      query.additional.each do |rr|
        retry_query.add_additional(rr) unless rr.type == Types.OPT || rr.type == Types.TSIG
      end
      if query.tsig
        return TsigError.new unless query.tsig.key
        retry_query.tsigstate = :Unsigned
        retry_query.set_tsig(query.tsig.dup)
      end
      send_async(retry_query, client_queue, client_query_id, tcp, true)
      return false
    end
    if (response.header.tc && !tcp && !ignore_truncation)
      if (no_tcp)
        Dnsruby.log.debug { "Truncated response - not resending over TCP as no_tcp==true" }
      else
        #  Try to resend over tcp
        Dnsruby.log.debug { "Truncated - resending over TCP" }
        #  @TODO@ Are the query options used correctly here? DNSSEC in particular...
        #         query.send_raw = true # Make sure that the packet is not messed with.
        send_async(query, client_queue, client_query_id, true)
        return false
      end
    end
  end
  settings = response_query_settings(client_query_id)
  if settings && settings.cache_scope && settings.cache_scope == positive_cache_scope(query, settings.query_bytes)
    response.instance_variable_set(:@dnsruby_cache_scope, settings.cache_scope)
  else
    # Configuration changed during this exchange, or this response has no
    # tracked transport. Do not seed a cache with an ambiguous route.
    response.instance_variable_set(:@dnsruby_cache_scope, false)
  end
  return true
end

#check_tsig(query, response, response_bytes) ⇒ Object



1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
# File 'lib/dnsruby/packet_sender.rb', line 1123

def check_tsig(query, response, response_bytes)
  if (query.tsig)
    if (response_signature = response.tsig)
      if !query.tsig.verify(query, response, response_bytes)
        authenticated_error = RR::TSIG.authenticated_error(response, response_signature)
        return authenticated_error if authenticated_error
        #  Discard packet and wait for correctly signed response
        Dnsruby.log.error { "TSIG authentication failed!" }
        return TsigError.new
      end
    else
      # A missing signature is a format error (RFC 8945 section 5.4).
      # Keep a distinct exception so callers can diagnose unsigned peers.
      response.tsigstate = :Failed
      response.tsigerror = RCode.FORMERR
      Dnsruby.log.error { "Expecting TSIG signed response, but got unsigned response - discarding" }
      return TsigNotSignedResponseError.new
    end
  elsif (response.tsig)
    #  Error - signed response to unsigned query
    Dnsruby.log.error { "Signed response to unsigned query" }
    return TsigError.new
  end
  return :okay
end

#close ⇒ Object



306
307
308
309
310
311
# File 'lib/dnsruby/packet_sender.rb', line 306

def close
  ensure_current_process
  # Idle streams close immediately; streams still serving another Resolver
  # drain before closing. Do not wait for a writer blocked in connect.
  @selector.retire_sender(self) if @selector
end

#get_next_src_port ⇒ Object



1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'lib/dnsruby/packet_sender.rb', line 1003

def get_next_src_port
  # Preserve the existing high-port range and configured pools, using
  # unpredictable choices for the source-port contribution to DNS IDs.
  ports = @src_port.dup
  if (ports[0] == 0)
    return 50_000 + SecureRandom.random_number(15_536)
  end
  ports[SecureRandom.random_number(ports.length)]
end

#make_query(name, type = Types::A, klass = Classes::IN, set_cd = @dnssec) ⇒ Object



1149
1150
1151
1152
1153
1154
1155
1156
1157
# File 'lib/dnsruby/packet_sender.rb', line 1149

def make_query(name, type = Types::A, klass = Classes::IN, set_cd=@dnssec)
  msg = Message.new
  msg.header.rd = 1
  msg.add_question(name, type, klass)
  if (@dnssec)
    msg.header.cd = set_cd # We do our own validation by default
  end
  return msg
end

#make_query_packet(packet, use_tcp = @use_tcp, disable_edns = false) ⇒ Object

Prepare the packet for sending



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'lib/dnsruby/packet_sender.rb', line 1160

def make_query_packet(packet, use_tcp = @use_tcp, disable_edns = false) #:nodoc: all
  packet.tsig.warn_if_legacy_algorithm if packet.tsig
  # TSIG signs the header and every section, so leave signed messages intact.
  # Decoded messages may have a TSIG without a signing state.
  prepared = packet.signed? || packet.tsig
  if !packet.send_raw && !prepared
    if (packet.header.opcode == OpCode.QUERY || @recurse)
      packet.header.rd=@recurse
    end

    if @dnssec && !disable_edns
      prepare_for_dnssec(packet)
    elsif !disable_edns && (udp_packet_size > 512) && !use_tcp
      add_opt_rr(packet)
    end
  end

  # Prepare the whole message before encoding, which may sign it.
  # Use the resolver's key if the Message has none.
  encoded = packet.encode
  if @tsig && !packet.signed? && !packet.tsig
    packet.set_tsig(@tsig)
    encoded = packet.encode
  end
  encoded
end

#positive_cache_scope(query, query_bytes = query.encode, configuration = nil) ⇒ Object

Retain the request actually sent, including EDNS options, but not its transaction ID. Never share answers across upstream or source routes.



1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/dnsruby/packet_sender.rb', line 1015

def positive_cache_scope(query, query_bytes = query.encode, configuration = nil) #:nodoc:
  route = if configuration
    configuration.values_at(:server, :port, :src_address, :src_address6, :src_port)
  else
    [@server.to_s.dup.freeze, @port, @src_address.to_s.dup.freeze,
      @src_address6.to_s.dup.freeze, @src_port.dup.freeze]
  end
  (route + [query.send_raw, query_bytes.byteslice(2..-1).b.freeze]).freeze
end

#prepare_for_dnssec(packet) ⇒ Object



1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/dnsruby/packet_sender.rb', line 1195

def prepare_for_dnssec(packet)
  # Request DNSSEC records with DO (RFC 4035 section 4.1).
  Dnsruby.log.debug { ";; Adding EDNS extension with UDP packetsize #{udp_packet_size} and DNS OK bit set\n" }
  optrr = add_opt_rr(packet)
  optrr.dnssec_ok=true

  # We use DO to request DNSSEC records and leave AD clear
  # (RFC 6840 section 5.7).
  packet.header.ad = false

  # Local validation needs the original data, even if the server rejects it.
  if (packet.do_validation)
    packet.header.cd = true
  end
  if (Dnssec.no_keys?)
    packet.header.cd = false
  end

end

#prepare_send_async(message, queue, id, retire_connection = false, control = QueryControl.current, transmission_budget = nil) ⇒ Object

Reserve ownership while Resolver still holds its query lock, then perform the synchronous public send after releasing that lock. close/timeout can cancel this reservation even before send_async has started.



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/dnsruby/packet_sender.rb', line 316

def prepare_send_async(message, queue, id, retire_connection = false, control = QueryControl.current, transmission_budget = nil) #:nodoc:
  ensure_current_process
  selector = @selector = SelectThread.instance
  pending = SelectThread::QuerySettings.new(nil, message, @ignore_truncation,
    queue, id, nil, @server, @port, TransportClock.now + @packet_timeout, udp_packet_size, self)
  pending.send_token = SelectThread::SendToken.new(control, transmission_budget)
  pending.endtime = [pending.endtime, control&.deadline].compact.min
  pending.retire_connection = retire_connection
  return unless selector.reserve_send(pending)
  -> do
    next unless selector.query_settings_for_id(id).equal?(pending)
    previous_context = Thread.current[:dnsruby_response_query]
    begin
      Thread.current[:dnsruby_response_query] = pending
      send_async(message, queue, id)
    rescue StandardError => error
      selector.fail_query_if_current(id, queue, pending, error)
    ensure
      Thread.current[:dnsruby_response_query] = previous_context
    end
  end
end

#response_query_settings(client_query_id) ⇒ Object



727
728
729
730
731
# File 'lib/dnsruby/packet_sender.rb', line 727

def response_query_settings(client_query_id)
  settings = Thread.current[:dnsruby_response_query]
  settings if settings && settings.client_query_id == client_query_id &&
    settings.single_resolver.equal?(self)
end

#send_async(*args) ⇒ Object

Asynchronously send a Message to the server. The send can be done using just Dnsruby. Support for EventMachine has been deprecated.

Dnsruby pure Ruby event loop :

A client_queue is supplied by the client, along with an optional client_query_id to identify the response. The client_query_id is generated, if not supplied, and returned to the client. When the response is known, the tuple (query_id, response_message, response_exception) is put in the queue for the client to process.

The query is sent synchronously in the caller's thread. The select thread is then used to listen for and process the response (up to pushing it to the client_queue). The client thread is then used to retrieve the response and deal with it.

Takes :

  • msg - the message to send
  • client_queue - a Queue to push the response to, when it arrives
  • client_query_id - an optional ID to identify the query to the client
  • use_tcp - whether to use TCP (defaults to PacketSender.use_tcp)

Returns :

  • client_query_id - to identify the query response to the client. This ID is generated if it is not passed in by the client

If the native Dsnruby networking layer is being used, then this method returns the client_query_id

id = res.send_async(msg, queue)
NOT SUPPORTED : id = res.send_async(msg, queue, use_tcp)
id = res.send_async(msg, queue, id)
id = res.send_async(msg, queue, id, use_tcp)

Use Message#send_raw to send the packet with an untouched header. Use Message#do_caching to tell dnsruby whether to check the cache before sending, and update the cache upon receiving a response. Use Message#do_validation to tell dnsruby whether or not to do DNSSEC validation for this particular packet (assuming SingleResolver#dnssec == true) Note that these options should not normally be used!



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/dnsruby/packet_sender.rb', line 379

def send_async(*args) # msg, client_queue, client_query_id, use_tcp=@use_tcp)
  ensure_current_process
  #  @TODO@ Need to select a good Header ID here - see forgery-resilience RFC draft for details
  msg = args[0]
  client_query_id = nil
  client_queue = nil
  use_tcp = @use_tcp
  if (msg.kind_of? String)
    msg = Message.new(msg)
    if (@dnssec)
      msg.header.cd = @dnssec # we'll do our own validation by default
      if (Dnssec.no_keys?)
        msg.header.cd = false
      end
    end
  end
  if (args.length > 1)
    if (args[1].class==Queue)
      client_queue = args[1]
    elsif (args.length == 2)
      use_tcp = args[1]
    end
    if (args.length > 2)
      client_query_id = args[2]
      if (args.length > 3)
        use_tcp = args[3]
      end
    end
  end
  # Keep the request MAC for response verification (RFC 8945 section 4.3.1).
  if (!client_query_id)
    client_query_id = Time.now + rand(10000) # is this safe?!
  end
  response_settings = response_query_settings(client_query_id)
  disable_edns = args[4] || (response_settings && response_settings.disable_edns)

  begin
    query_packet = make_query_packet(msg, use_tcp, disable_edns)
    check_message_size(query_packet)
  rescue EncodeError => err
    Dnsruby.log.error { "#{err}" }
    st = SelectThread.instance
    if response_settings
      st.fail_query_if_current(client_query_id, client_queue, response_settings, err)
    else
      st.push_exception_to_select(client_query_id, client_queue, err, nil)
    end
    return
  end

  if (msg.do_caching && !msg.send_raw && (msg.class != Update) && !@tsig && !msg.tsig && !msg.signed?)
    #  Check the cache!!
    cachedanswer = nil
    if (msg.header.rd)
      cachedanswer = @@recursive_cache.find(msg.question()[0].qname, msg.question()[0].type, msg.question()[0].qclass,
        scope: positive_cache_scope(msg, query_packet))
    else
      cachedanswer = @@authoritative_cache.find(msg.question()[0].qname, msg.question()[0].type, msg.question()[0].qclass,
        scope: positive_cache_scope(msg, query_packet))
    end
    if (cachedanswer)
      TheLog.debug("Sending cached answer to client\n")
      #  @TODO@ Fix up the header - ID and flags
      cachedanswer.header.id = msg.header.id
      #  If we can find the answer, send it to the client straight away
      #  Post the result to the client using SelectThread
      st = SelectThread.instance
      if response_settings
        st.push_response_for_query(response_settings, cachedanswer, msg, self)
      else
        st.push_response_to_select(client_query_id, client_queue, cachedanswer, msg, self)
      end
      return client_query_id
    end
  end
  #  Otherwise, run the query
  if (udp_packet_size < query_packet.length)
    if (@no_tcp)
      #  Can't send the message - abort!
      err=IOError.new("Can't send message - too big for UDP and no_tcp=true")
      Dnsruby.log.error { "#{err}" }
      st = SelectThread.instance
      if response_settings
        st.fail_query_if_current(client_query_id, client_queue, response_settings, err)
      else
        st.push_exception_to_select(client_query_id, client_queue, err, nil)
      end
      return
    end
    Dnsruby.log.debug { "Query packet length exceeds max UDP packet size - using TCP" }
    use_tcp = true
  end
  send_dnsruby(query_packet, msg, client_query_id, client_queue, use_tcp, disable_edns)
  return client_query_id
  #       end
end

#send_dnsruby(query_bytes, query, client_query_id, client_queue, use_tcp, disable_edns = false) ⇒ Object

This method sends the packet using the built-in pure Ruby event loop, with no dependencies.



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/dnsruby/packet_sender.rb', line 553

def send_dnsruby(query_bytes, query, client_query_id, client_queue, use_tcp, disable_edns = false) #:nodoc: all
  ensure_current_process
  st = @selector = SelectThread.instance
  response_settings = response_query_settings(client_query_id)
  # A configuration change applies to the next attempt, never half of this one.
  configuration = transport_configuration
  pipeline_mode = use_tcp && configuration[:tcp_pipelining]
  begin
    check_message_size(query_bytes)
  rescue EncodeError => error
    if response_settings
      st.fail_query_if_current(client_query_id, client_queue, response_settings, error)
    else
      st.push_exception_to_select(client_query_id, client_queue, error, nil)
    end
    return
  end
  # A Resolver reservation already started this attempt's packet deadline.
  # A protocol retry (which has bytes) receives a fresh packet deadline.
  endtime = response_settings && response_settings.query_bytes.nil? ?
    response_settings.endtime : TransportClock.now + configuration[:packet_timeout]
  previous_settings = response_settings ||
    (st.query_settings_for_id(client_query_id) if pipeline_mode)
  pending = SelectThread::QuerySettings.new(query_bytes, query,
    configuration[:ignore_truncation], client_queue, client_query_id, nil,
    configuration[:server], configuration[:port],
    endtime, udp_receive_size(query, configuration), self)
  pending.transport_configuration = configuration
  pending.send_token = previous_settings.send_token if previous_settings
  # Carry the controlling lookup through selector retries and workers, whose
  # thread-local control may differ from the thread which admitted it.
  endtime = pending.endtime = [endtime, pending.send_token.control&.deadline].compact.min
  pending.disable_edns = disable_edns || (previous_settings && previous_settings.disable_edns)
  pending.cache_scope = positive_cache_scope(query, query_bytes, configuration)
  # A protocol retry starts its own packet deadline at dispatch, including
  # time queued for a worker. Retire the old socket membership atomically.
  return unless st.reserve_send(pending, previous_settings)
  previous_settings = pending
  operation = -> do
    send_dnsruby_with_socket(query_bytes, query, client_query_id, client_queue,
      use_tcp, endtime, previous_settings, pipeline_mode)
  end
  send_operation = operation
  if pipeline_mode
    # Configuration-only senders remain Marshal-compatible. Allocate the
    # writer mutex only on first use, including senders loaded from storage.
    pipeline_mutex = PIPELINE_MUTEX_CREATION.synchronize { @pipeline_mutex ||= Mutex.new }
    send_operation = -> do
      locked = false
      begin
        until (locked = pipeline_mutex.try_lock)
          break if previous_settings.send_token.cancelled? || TransportClock.now >= endtime ||
            !st.query_settings_for_id(client_query_id).equal?(previous_settings)
          sleep 0.005
        end
        if locked && !previous_settings.send_token.cancelled? && TransportClock.now < endtime
          operation.call
        else
          st.fail_query_if_current(client_query_id, client_queue, previous_settings,
            ResolvTimeout.new("Query timed out waiting for TCP pipeline"))
        end
      ensure
        pipeline_mutex.unlock if locked
      end
    end
  end
  guarded_operation = -> do
    send_operation.call
  rescue StandardError => error
    # Deferred callers do not read SendTask#value. Failures before socket
    # registration still belong to this exact reserved attempt.
    st.fail_query_if_current(client_query_id, client_queue, pending, error)
  end
  if use_tcp && st.selector_thread?
    begin
      st.defer_send(pipeline_mode ? self : nil, &guarded_operation)
    rescue ThreadError => error
      st.fail_query_if_current(client_query_id, client_queue, previous_settings,
        ResolvTimeout.new("Cannot queue TCP send: #{error.message}"))
    end
  else
    # Only the selector delegates I/O. Public caller sends remain synchronous.
    guarded_operation.call
  end
end

#send_dnsruby_with_socket(query_bytes, query, client_query_id, client_queue, use_tcp, endtime, previous_settings, pipeline_mode = use_tcp && @tcp_pipelining) ⇒ Object



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# File 'lib/dnsruby/packet_sender.rb', line 733

def send_dnsruby_with_socket(query_bytes, query, client_query_id, client_queue,
    use_tcp, endtime, previous_settings, pipeline_mode = use_tcp && @tcp_pipelining)
  #  First send the query (synchronously)
  st = SelectThread.instance
  report_error = ->(error) do
    st.fail_query_if_current(client_query_id, client_queue, previous_settings, error)
  end
  return unless st.query_settings_for_id(client_query_id).equal?(previous_settings)
  return if previous_settings.send_token.cancelled?
  configuration = previous_settings.transport_configuration || transport_configuration
  server, port = configuration.values_at(:server, :port)
  unless previous_settings.send_token.transmission_budget.admit(server, port, use_tcp, query.question.first)
    report_error.call(ResolvTimeout.new("DNS retry limit reached for server and transport"))
    return
  end
  socket = nil
  runnextportloop = true
  numtries = 0
  source_port_configuration = configuration[:src_port]
  source_ports = source_port_configuration.uniq
  random_source_port = source_ports.first == 0
  src_address = configuration[configuration[:ipv6] ? :src_address6 : :src_address]
  while (runnextportloop) do
    # A pre-close reservation gets a one-use socket. Recheck on every
    # admission retry without changing ownership or extending its deadline.
    pipeline = pipeline_mode && !previous_settings.retire_connection
    return unless st.query_settings_for_id(client_query_id).equal?(previous_settings)
    return if previous_settings.send_token.cancelled?
    begin
      if TransportClock.now >= endtime
        report_error.call(ResolvTimeout.new("Query timed out before connect"))
        return
      end
      numtries += 1
      src_port = if random_source_port
        # Keep this attempt's mode even if a caller replaces the pool.
        50_000 + SecureRandom.random_number(15_536)
      else
        source_ports[SecureRandom.random_number(source_ports.length)]
      end
      if (use_tcp)
        begin
          if pipeline
            begin
              # RFC 7766 requires unique outstanding IDs on a connection.
              # Moving a collision to a fresh stream preserves caller IDs,
              # including raw messages and bytes covered by TSIG.
              if @pipeline_socket && st.query_id_in_use?(@pipeline_socket, query.header.id)
                st.retire_socket(@pipeline_socket)
                @use_counts.delete(@pipeline_socket)
                @pipeline_socket = nil
              end
              @pipeline_connect_context = [endtime, previous_settings.send_token, configuration]
              socket, new_socket = tcp_pipeline_socket(src_port)
            ensure
              remove_instance_variable(:@pipeline_connect_context)
            end
            src_port = @tcp_pipeline_local_port
          else
            socket = connect_tcp(server, port, src_address, src_port,
              endtime, previous_settings.send_token)
            new_socket = true
          end
        rescue Errno::EBADF, Errno::ENETUNREACH => e
          #  Can't create a connection
          err=IOError.new("TCP connection error to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception = #{e.class}, #{e}")
          Dnsruby.log.error { "#{err}" }
          report_error.call(err)
          return
        end
      else
        socket = nil
        #  JRuby UDPSocket only takes 0 parameters - no IPv6 support in JRuby...
        if (/java/ =~ RUBY_PLATFORM)
          socket = UDPSocket.new()
        else
          #               ipv6 = @src_address =~ /:/
          socket = UDPSocket.new(configuration[:ipv6] ? Socket::AF_INET6 : Socket::AF_INET)
        end
        st.track_socket(socket)
        new_socket = true
        socket.bind(src_address, src_port)
        socket.connect(server, port)
      end
    rescue SendCancelled
      return
    rescue Exception => e
      if (socket!=nil)
        begin
          #let the select thread close the socket if tcp_pipeli
          socket.close unless pipeline && !new_socket
        rescue Exception
        end
      end
      # Only an occupied bind removes a candidate. A pipeline admission
      # retry has not found the port unusable and must retain the pool.
      source_ports.delete(src_port) if e.is_a?(Errno::EADDRINUSE) && !random_source_port
      # Random ports keep the bounded retry policy; configured pools do
      # not revisit an occupied member during this attempt.
      if !e.is_a?(Errno::EADDRINUSE) || (random_source_port && numtries >= 50) ||
          (!random_source_port && source_ports.empty?)
        err_msg = "dnsruby can't connect to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception = #{e.class}, #{e} #{e.backtrace}"
        err=IOError.new(err_msg)
        Dnsruby.log.error( "#{err}")
        Dnsruby.log.error(e.backtrace)
        if e.kind_of?(Errno::ETIMEDOUT) || e.kind_of?(ResolvTimeout)
          report_error.call(ResolvTimeout.new(err_msg))
        elsif pipeline
          report_error.call(SocketEofResolvError.new(err_msg))
        else
          report_error.call(err)
        end
        return
      end
      next # Retry a random source-port collision before registration.
    end
    if (socket==nil)
      err=IOError.new("dnsruby can't connect to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}")
      Dnsruby.log.error { "#{err}" }
      report_error.call(err)
      return
    end
    Dnsruby.log.debug { "Sending packet to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp} : #{query.question()[0].qname}, #{query.question()[0].qtype}" }
    # A reused pipeline is already readable by the selector. Publish its new
    # query before writing so an immediate answer always has an owner.
    query_settings = SelectThread::QuerySettings.new(query_bytes, query, previous_settings.ignore_truncation,
      client_queue, client_query_id, socket, server, port, endtime, previous_settings.udp_packet_size, self)
    query_settings.transport_configuration = configuration
    query_settings.send_token = previous_settings.send_token
    query_settings.disable_edns = previous_settings.disable_edns
    query_settings.cache_scope = previous_settings.cache_scope
    query_settings.is_persistent_socket = pipeline
    query_settings.tcp_pipelining_max_queries = (@pipeline_socket_max_queries || configuration[:tcp_pipelining_max_queries]) if pipeline
    if use_tcp
      registered = st.register_query_if_current(query_settings, previous_settings)
      if registered == :retry_connection
        # No bytes were written and the original reservation still owns the
        # attempt. Peers on the retiring stream keep their registrations.
        @use_counts.delete(socket)
        @pipeline_socket = nil if @pipeline_socket == socket
        next
      end
      unless registered
        # Completion can win during connect. Release only this unused socket
        # reservation; other queries may still own an existing pipeline.
        @use_counts[socket] -= 1 if pipeline && @use_counts[socket]
        socket.close if new_socket && !socket.closed?
        if pipeline && socket.closed?
          @use_counts.delete(socket)
          @pipeline_socket = nil if @pipeline_socket == socket
        end
        return
      end
      previous_settings = query_settings
    elsif !st.query_settings_for_id(client_query_id).equal?(previous_settings)
      socket.close
      return
    end
    runnextportloop = false
  end
  send_packet = -> do
    begin
      if use_tcp
        completed = write_tcp_frame(socket, query_bytes, endtime, query_settings.send_token)
        # Cancellation of a partially written frame retires its whole stream;
        # otherwise another frame could be appended to a corrupt prefix.
        unless completed == true
          if pipeline && completed > 0
            st.fail_tcp_send(query_settings, SocketEofResolvError.new("TCP send cancelled"))
            @use_counts.delete(socket)
            @pipeline_socket = nil if @pipeline_socket == socket
          elsif !pipeline
            socket.close rescue nil
          end
          return
        end
      else
        unless write_udp_packet(socket, query_bytes, endtime, query_settings.send_token, !st.selector_thread?)
          socket.close
          return
        end
        socket.close unless st.register_query_if_current(query_settings, previous_settings)
      end
    rescue IO::WaitWritable
      # Only a congested UDP send reaches this branch on the selector. Keep
      # ordinary UDP traffic independent of the pool's blocked TCP writers.
      return st.defer_send { send_packet.call }
    rescue Exception => e
      err_msg = "Send failed to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception : #{e}"
      err=IOError.new(err_msg)
      Dnsruby.log.error { "#{err}" }
      Dnsruby.log.error(e.backtrace)
      if pipeline
        error = e.kind_of?(ResolvTimeout) ? e : SocketEofResolvError.new(err_msg)
        st.fail_tcp_send(query_settings, error)
        @use_counts.delete(socket)
        @pipeline_socket = nil if @pipeline_socket == socket
      elsif e.kind_of?(ResolvTimeout)
        report_error.call(e)
      else
        report_error.call(err)
      end
      begin
        #we let the select_thread close the socket when doing tcp
        #pipelining
        socket.close unless pipeline && !new_socket
      rescue Exception
      end
      return
    end

    Dnsruby.log.debug { "Packet sent to #{server}:#{port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp} : #{query.question()[0].qname}, #{query.question()[0].qtype}" }
  end
  send_packet.call
rescue StandardError => error
  # Errors outside the expected connect/write failures must not disappear in
  # a worker's result queue. Do not consume a replacement protocol attempt.
  st.fail_query_if_current(client_query_id, client_queue, previous_settings, error)
  # A failure between connect and registration has no selector-owned socket
  # yet. Release that new descriptor here; reused streams retain their peers.
  socket.close if socket && new_socket && !socket.closed?
end

#src_address6=(arg) ⇒ Object

Set the source address. If the arg is nil, do nothing



138
139
140
141
142
# File 'lib/dnsruby/packet_sender.rb', line 138

def src_address6=(arg)
  if (not arg.nil?)
    @src_address6 = arg
  end
end

#src_port ⇒ Object

The source port to send queries from Returns either a single Integer or an Array e.g. "0", or "[60001, 60002, 60007]"

Defaults to 0 - random port



961
962
963
964
# File 'lib/dnsruby/packet_sender.rb', line 961

def src_port
  ports = @src_port
  ports.length == 1 ? ports[0] : ports
end

#src_port=(p) ⇒ Object

Can be a single Integer or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised.

    res.src_port=0
    res.src_port=[60001,60005,60010]
    res.src_port=60015..60115

Raises:

  • (ArgumentError)


974
975
976
977
978
# File 'lib/dnsruby/packet_sender.rb', line 974

def src_port=(p)
  ports = Resolver.get_ports_from(p)
  raise ArgumentError, 'Source port pool must not be empty' if ports.empty?
  @src_port = ports if Resolver.check_port(ports)
end

#tcp_idle_timeout ⇒ Object

Maximum idle time for a reusable TCP connection, in seconds.



92
93
94
# File 'lib/dnsruby/packet_sender.rb', line 92

def tcp_idle_timeout
  @tcp_idle_timeout || Resolver::DefaultTcpIdleTimeout
end

#tcp_idle_timeout=(seconds) ⇒ Object



96
97
98
99
100
101
# File 'lib/dnsruby/packet_sender.rb', line 96

def tcp_idle_timeout=(seconds)
  unless seconds.is_a?(Numeric) && seconds.finite? && seconds > 0
    raise ArgumentError, 'TCP idle timeout must be a positive finite number'
  end
  @tcp_idle_timeout = seconds
end

#tcp_pipeline_socket(src_port) ⇒ Object

This method returns the current tcp socket for pipelining If this is the first time the method is called then the socket is bound to @src_address:@src_port and connected to the remote dns server @server:@port. If the connection has been closed because of an EOF on recv_nonblock (closed by server) the function will recreate of the socket (since @pipeline_socket.connect will result in a IOError exception) In general, every subsequent call the function will either return the current tcp pipeline socket or a new connected socket if the current one was closed by the server



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/dnsruby/packet_sender.rb', line 484

def tcp_pipeline_socket(src_port)
  ensure_current_process
  Dnsruby.log.debug("Using tcp_pipeline_socket")
  # A live connection retains its endpoint and source binding. Compare the
  # configured source-port pool, not each randomly selected candidate port.
  attempt = @pipeline_connect_context&.[](2) || transport_configuration
  configuration = [attempt[:server], attempt[:port],
    attempt[:ipv6] ? attempt[:src_address6] : attempt[:src_address], attempt[:src_port], attempt[:ipv6]]
  sockaddr = Socket.sockaddr_in(configuration[1], configuration[0])

  reuse_pipeline_socket = -> do
    begin
      max = @pipeline_socket_max_queries
      use_count = @use_counts[@pipeline_socket]
      if !SelectThread.instance.reusable_socket?(@pipeline_socket) ||
          max != attempt[:tcp_pipelining_max_queries] ||
          @pipeline_socket_configuration != configuration ||
          (use_count && max != :infinite && use_count >= max)
        # Capacity and endpoint belong to a connection. Outstanding peers
        # keep their old stream and drain before it closes.
        SelectThread.instance.retire_socket(@pipeline_socket)
        @use_counts.delete(@pipeline_socket)
        @pipeline_socket = nil
        Dnsruby.log.debug("Max queries per connection attained - creating new socket")
      else
        @pipeline_socket.connect(sockaddr)
      end
    rescue Errno::EISCONN
      #already connected, do nothing and reuse!
    rescue IOError, Errno::ECONNRESET #close by remote host, reconnect
      @use_counts.delete(@pipeline_socket)
      @pipeline_socket = nil
      Dnsruby.log.debug("Connection closed - recreating socket")
    end
  end

  create_pipeline_socket = -> do
    @tcp_pipeline_local_port = src_port
    src_address = configuration[2]
    begin
      @pipeline_socket_max_queries = attempt[:tcp_pipelining_max_queries]
      @pipeline_socket_configuration = configuration
      deadline, token = @pipeline_connect_context ||
        [TransportClock.now + attempt[:packet_timeout], SelectThread::SendToken.new]
      @pipeline_socket = connect_tcp(configuration[0], configuration[1], src_address, src_port,
        deadline, token)
      Dnsruby.log.debug("Creating socket #{src_address}:#{src_port}")
      @use_counts[@pipeline_socket] = 0
    rescue Exception => e
      # A failed bind/connect never reaches the select thread, which would
      # otherwise own closing the socket (for example, an unusable zone).
      @pipeline_socket.close rescue nil
      @pipeline_socket = nil
      raise e
    end
  end

  # Don't combine the following 2 statements; the reuse lambda can set the
  # socket to nil and if so we'd want to call the create lambda to recreate it.
  reuse_pipeline_socket.() if @pipeline_socket
  new_socket = @pipeline_socket.nil?
  create_pipeline_socket.() unless @pipeline_socket

  @use_counts[@pipeline_socket] += 1

  [@pipeline_socket, new_socket]
end

#udp_packet_size ⇒ Object

Return the packet size to use for UDP



1216
1217
1218
1219
# File 'lib/dnsruby/packet_sender.rb', line 1216

def udp_packet_size
  # Values below 512 mean 512 in EDNS (RFC 6891 section 6.2.3).
  [@udp_size, 512].max
end

#write_tcp_frame(socket, query_bytes, endtime, send_token) ⇒ Object

Socket#send may write only a prefix of a TCP frame. Nonblocking writes keep a stalled peer from holding the pipeline writer past the packet deadline.



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/dnsruby/packet_sender.rb', line 683

def write_tcp_frame(socket, query_bytes, endtime, send_token)
  check_message_size(query_bytes)
  frame = [query_bytes.bytesize].pack('n') + query_bytes
  offset = 0
  while offset < frame.bytesize
    remaining = endtime - TransportClock.now
    begin
      written = send_token.write do
        raise ResolvTimeout, "Query timed out writing TCP frame" if remaining <= 0
        socket.write_nonblock(frame.byteslice(offset, frame.bytesize - offset))
      end
      return offset if written == false # Cancelled between partial writes.
      raise IOError, "TCP write made no progress" unless written && written > 0
      offset += written
    rescue IO::WaitWritable
      # A canceled pipeline may still have peers and remain open. Bound the
      # wait so cancellation releases the worker even if it never becomes
      # writable; the next iteration retires any incomplete frame.
      IO.select(nil, [socket], nil, [remaining, 0.05].min)
    end
  end
  true
end

#write_udp_packet(socket, query_bytes, endtime, send_token, wait_for_writable) ⇒ Object

A datagram is sent atomically. Order the actual write with cancellation, as for TCP, without holding the token while waiting for a writable socket.



709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/dnsruby/packet_sender.rb', line 709

def write_udp_packet(socket, query_bytes, endtime, send_token, wait_for_writable)
  loop do
    remaining = endtime - TransportClock.now
    begin
      written = send_token.write do
        raise ResolvTimeout, "Query timed out writing UDP packet" if remaining <= 0
        socket.write_nonblock(query_bytes)
      end
      return false if written == false
      raise IOError, "Incomplete UDP datagram write" unless written == query_bytes.bytesize
      return true
    rescue IO::WaitWritable
      raise unless wait_for_writable
      IO.select(nil, [socket], nil, [remaining, 0.05].min)
    end
  end
end