Class: Dnsruby::SelectThread
- Inherits:
-
Object
- Object
- Dnsruby::SelectThread
- Includes:
- Singleton
- Defined in:
- lib/dnsruby/select_thread.rb
Overview
:nodoc: all
Defined Under Namespace
Classes: QuerySettings, SelectWakeup, SendTask, SendToken, TransmissionBudget
Class Method Summary collapse
Instance Method Summary collapse
- #add_observer(client_queue, observer) ⇒ Object
-
#add_query_from_mutex_synchronized_block(settings) ⇒ Object
Called only with @@mutex held.
- #add_to_select(query_settings) ⇒ Object
-
#cancel_queries_for_queue(client_queue) ⇒ Object
Stop packet attempts without removing the logical query's observer.
- #check_select_thread_synchronized ⇒ Object
- #claim_query(settings, response_received = false) ⇒ Object
-
#clean_up_closed_sockets ⇒ Object
Detach closed sockets before notifying clients.
- #decrement_remaining_queries(socket) ⇒ Object
-
#defer_send(sender = nil, &operation) ⇒ Object
A finite pool keeps slow connects/writes off the selector without creating an unbounded number of threads.
- #do_select ⇒ Object
-
#fail_query_if_current(id, queue, previous_settings, error) ⇒ Object
A send waiting for the pipeline writer has no new socket registration yet.
-
#fail_tcp_send(settings, error) ⇒ Object
A partial TCP frame makes the whole connection unusable.
-
#get_active_ids(queries, id) ⇒ Object
Retained for callers of this helper; response delivery now matches only queries registered on the receiving socket instead of scanning every ID.
- #get_client_id_from_answerfrom(socket, answerip, answerport, header_id = nil) ⇒ Object
- #get_incoming_data(socket, packet_size) ⇒ Object
- #get_socket_pair ⇒ Object
- #handle_recvfrom_failure(socket, exception) ⇒ Object
-
#initialize ⇒ SelectThread
constructor
This singleton class runs a continuous select loop which listens for responses on all of the in-use sockets.
- #max_attained?(socket) ⇒ Boolean
- #notify_queue_observers(client_queue, client_query_id) ⇒ Object
- #persistent?(socket) ⇒ Boolean
- #process_error(errors) ⇒ Object
- #process_message(msg, bytes, socket) ⇒ Object
- #process_ready(ready) ⇒ Object
- #process_timeouts ⇒ Object
- #push_exception_to_select(client_id, client_queue, err, msg) ⇒ Object
-
#push_response_for_query(settings, msg, query, resolver) ⇒ Object
Cache lookup can satisfy a protocol retry before it reaches the sender.
- #push_response_to_select(client_id, client_queue, msg, query, res, transmission_budget = nil) ⇒ Object
- #push_to_client(client_id, client_queue, msg, err, query, res, transmission_budget = nil) ⇒ Object
- #push_validation_response_to_select(client_id, client_queue, msg, err, query, res) ⇒ Object
- #query_id_in_use?(socket, header_id) ⇒ Boolean
- #query_settings_for_id(client_query_id) ⇒ Object
-
#register_query_if_current(query_settings, previous_settings) ⇒ Object
Reserve a pipeline query before writing, or replace a protocol retry.
- #register_validation(client_queue, sender, control) ⇒ Object
- #remove_id(id) ⇒ Object
-
#remove_id_from_mutex_synchronized_block(id, preserved_token = nil, response_received = false) ⇒ Object
THIS MUST BE CALLED FROM INSIDE A @@mutex SYNCHRONISED BLOCK!.
- #remove_observer(client_queue, observer) ⇒ Object
-
#reserve_send(settings, previous_settings = nil) ⇒ Object
Register ownership before work leaves the selector, including attempts which have not acquired a socket yet.
-
#retire_sender(sender) ⇒ Object
Explicit close retires streams owned by this sender, including idle and rolled-over pipelines.
- #retire_socket(socket) ⇒ Object
-
#retire_socket_from_mutex_synchronized_block(socket) ⇒ Object
Called only with @@mutex held and after the socket has been closed.
- #reusable_socket?(socket) ⇒ Boolean
- #select_thread_alive? ⇒ Boolean
- #selector_thread? ⇒ Boolean
- #send_exception_to_client(err, socket, client_id, msg = nil) ⇒ Object
- #send_queued_exceptions ⇒ Object
- #send_queued_responses ⇒ Object
- #send_queued_validation_responses ⇒ Object
- #send_response_to_client(msg, bytes, socket) ⇒ Object
- #send_tick_to_observers(due_only = true) ⇒ Object
- #tcp?(socket) ⇒ Boolean
- #tcp_read(socket) ⇒ Object
-
#track_socket(socket) ⇒ Object
Keep weak references from allocation through connect/write, before a socket joins the read set.
- #udp?(socket) ⇒ Boolean
- #unregister_validation(client_queue, sender, control) ⇒ Object
-
#validation_deadline(client_queue, client_query_id) ⇒ Object
Take the observer snapshot before acquiring its Resolver lock: Resolver completion acquires these locks in the opposite direction.
- #validation_transmission_budget(client_queue, client_query_id) ⇒ Object
- #wake_up_select_thread ⇒ Object
Constructor Details
#initialize ⇒ SelectThread
This singleton class runs a continuous select loop which listens for responses on all of the in-use sockets. When a new query is sent, the thread is woken up, and the socket is added to the select loop (and the new timeout calculated). Note that a combination of the socket and the packet ID is sufficient to uniquely identify the query to the select thread.
But how do we find the response queue for a particular query? Hash of client_id->[query, client_queue, socket] and socket->[client_ids], including multiple queries per TCP pipeline.
@@mutex owns the attempt, queue and socket indexes. Cancellation may take a SendToken lock while holding @@mutex; a token-protected write must not acquire @@mutex. The selector never waits for a pipeline writer mutex. Blocking I/O and client callbacks run outside @@mutex.
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/dnsruby/select_thread.rb', line 59 def initialize @process_mutex ||= Mutex.new @send_queue = @send_workers = @send_groups = nil @packet_deadlines = DeadlineQueue.new @idle_deadlines = DeadlineQueue.new @created_sockets = ObjectSpace::WeakMap.new @@mutex = Mutex.new @@mutex.synchronize { @@in_select=false @@sockets = Set.new @@timeouts = Hash.new @@query_hash = Hash.new @@queries_by_queue = {}.compare_by_identity @@queries_by_sender = {}.compare_by_identity @@socket_hash = Hash.new @@socket_is_persistent = Hash.new @@socket_owners = Hash.new @@sockets_by_sender = {}.compare_by_identity @@retiring_sockets = Set.new @@observers = Hash.new @@observer_queue_counts = {}.compare_by_identity @@observed_queues = ObjectSpace::WeakMap.new @@validation_pid = Process.pid @@validations = [] @@tcp_buffers=Hash.new @@socket_remaining_queries = Hash.new @@socket_idle_deadlines = Hash.new @@tick_observers = [] @@queued_exceptions=[] @@queued_responses=[] @@queued_validation_responses=[] @@wakeup_sockets = get_socket_pair @@sockets << @@wakeup_sockets[1] # Suppress reverse lookups BasicSocket.do_not_reverse_lookup = true # Now start the select thread @process_pid = Process.pid @@select_thread = Thread.new { do_select } } end |
Class Method Details
.instance ⇒ Object
38 39 40 |
# File 'lib/dnsruby/select_thread.rb', line 38 def instance instance_without_fork_check.tap { |selector| selector.send(:ensure_current_process) } end |
.instance_without_fork_check ⇒ Object
35 |
# File 'lib/dnsruby/select_thread.rb', line 35 alias_method :instance_without_fork_check, :instance |
Instance Method Details
#add_observer(client_queue, observer) ⇒ Object
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 |
# File 'lib/dnsruby/select_thread.rb', line 1336 def add_observer(client_queue, observer) state_mutex.synchronize { (@@observed_queues ||= ObjectSpace::WeakMap.new)[client_queue] = true previous = @@observers[client_queue] unless previous.equal?(observer) remove_observer_queue_count(previous) if previous @@observers[client_queue] = observer count = (@@observer_queue_counts[observer] || 0) + 1 @@observer_queue_counts[observer] = count @@tick_observers.push(observer) if count == 1 end check_select_thread_synchronized } # An empty resolver still has a logical deadline but no socket to wake us. wake_up_select_thread end |
#add_query_from_mutex_synchronized_block(settings) ⇒ Object
Called only with @@mutex held. Retrying a client ID also retires its old socket membership, so stale EOF/timeout work cannot consume the retry.
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 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/dnsruby/select_thread.rb', line 448 def add_query_from_mutex_synchronized_block(settings) id = settings.client_query_id remove_id_from_mutex_synchronized_block(id, settings.send_token) if @@query_hash[id] if settings.socket.closed? @@queued_exceptions << [id, settings.client_queue, SocketEofResolvError.new("TCP socket closed before all answers received"), nil] return false end @@query_hash[id] = settings (@@queries_by_queue[settings.client_queue] ||= Set.new) << id ((@@queries_by_sender ||= {}.compare_by_identity)[settings.single_resolver] ||= Set.new) << id membership = @@socket_hash[settings.socket] unless membership.is_a?(SocketQueries) indexed = SocketQueries.new (membership || []).each { |member| indexed.add_query(@@query_hash[member]) if @@query_hash[member] } membership = @@socket_hash[settings.socket] = indexed end membership.add_query(settings) (@@socket_idle_deadlines ||= {}).delete(settings.socket) @idle_deadlines&.delete(settings.socket) if settings.tcp_pipelining_max_queries != :infinite @@socket_remaining_queries[settings.socket] ||= settings.tcp_pipelining_max_queries end @@timeouts[id] = settings.endtime (@packet_deadlines ||= DeadlineQueue.new)[id] = settings.endtime @@sockets << settings.socket @@socket_is_persistent[settings.socket] = settings.is_persistent_socket previous_owner = (@@socket_owners ||= {})[settings.socket] if previous_owner && !previous_owner.equal?(settings.single_resolver) && (previous_sockets = (@@sockets_by_sender ||= {}.compare_by_identity)[previous_owner]) previous_sockets.delete(settings.socket) @@sockets_by_sender.delete(previous_owner) if previous_sockets.empty? end (@@socket_owners ||= {})[settings.socket] = settings.single_resolver ((@@sockets_by_sender ||= {}.compare_by_identity)[settings.single_resolver] ||= Set.new) << settings.socket (@@retiring_sockets ||= Set.new) << settings.socket if settings.retire_connection true end |
#add_to_select(query_settings) ⇒ Object
409 410 411 412 413 414 415 416 |
# File 'lib/dnsruby/select_thread.rb', line 409 def add_to_select(query_settings) # Add the query to sockets, and then wake the select thread up state_mutex.synchronize { check_select_thread_synchronized add_query_from_mutex_synchronized_block(query_settings) } wake_up_select_thread end |
#cancel_queries_for_queue(client_queue) ⇒ Object
Stop packet attempts without removing the logical query's observer. A received response can still need validation and its overall deadline.
1418 1419 1420 1421 |
# File 'lib/dnsruby/select_thread.rb', line 1418 def cancel_queries_for_queue(client_queue) state_mutex.synchronize { cancel_queries_for_queue_synchronized(client_queue) } wake_up_select_thread end |
#check_select_thread_synchronized ⇒ Object
606 607 608 609 610 611 612 613 |
# File 'lib/dnsruby/select_thread.rb', line 606 def check_select_thread_synchronized if !@@select_thread || !@@select_thread.alive? Dnsruby.log.debug{"Restarting select thread"} @@select_thread = Thread.new { do_select } end end |
#claim_query(settings, response_received = false) ⇒ Object
589 590 591 592 593 594 595 |
# File 'lib/dnsruby/select_thread.rb', line 589 def claim_query(settings, response_received = false) state_mutex.synchronize do return false unless @@query_hash[settings.client_query_id].equal?(settings) remove_id_from_mutex_synchronized_block(settings.client_query_id, nil, response_received) true end end |
#clean_up_closed_sockets ⇒ Object
Detach closed sockets before notifying clients. Callbacks can register other queries, and must never run while holding the selector mutex.
707 708 709 710 711 712 713 |
# File 'lib/dnsruby/select_thread.rb', line 707 def clean_up_closed_sockets state_mutex.synchronize do @@sockets.select(&:closed?).flat_map do |socket| retire_socket_from_mutex_synchronized_block(socket) end end end |
#decrement_remaining_queries(socket) ⇒ Object
910 911 912 913 914 |
# File 'lib/dnsruby/select_thread.rb', line 910 def decrement_remaining_queries(socket) if @@socket_remaining_queries[socket] @@socket_remaining_queries[socket] -= 1 end end |
#defer_send(sender = nil, &operation) ⇒ Object
A finite pool keeps slow connects/writes off the selector without creating an unbounded number of threads. Already-owned attempts can queue without introducing a new admission limit; each retains its original deadline.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
# File 'lib/dnsruby/select_thread.rb', line 350 def defer_send(sender = nil, &operation) task = SendTask.new(&operation) state_mutex.synchronize do unless @send_queue && @send_workers.any?(&:alive?) queue = Queue.new workers = [] begin 4.times { workers << Thread.new { while (work = queue.pop); work.run; end } } rescue ThreadError workers.length.times { queue << nil } raise end @send_queue = queue @send_workers = workers @send_groups = {} end if sender group = @send_groups[sender] if group group << task else @send_groups[sender] = [task] # One worker owns each sender's FIFO. Other tasks for the same # pipeline do not occupy workers just to wait for its writer lock. @send_queue << SendTask.new { run_send_group(sender) } end else @send_queue << task end end task end |
#do_select ⇒ Object
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 |
# File 'lib/dnsruby/select_thread.rb', line 623 def do_select unused_loop_count = 0 while true do send_tick_to_observers expire_idle_sockets send_queued_exceptions send_queued_responses send_queued_validation_responses observer_deadline = next_observer_deadline sockets, packet_deadline, idle_deadline = state_mutex.synchronize do [@@sockets.to_a, @packet_deadlines&.first_deadline, @idle_deadlines&.first_deadline] end now = TransportClock.now if packet_deadline && packet_deadline <= now process_timeouts next end deadline = [packet_deadline, observer_deadline, idle_deadline].compact.min timeout = deadline ? [deadline - now, 0].max : 0.1 ready=nil begin ready, _write, _errors = IO.select(sockets, nil, nil, timeout) rescue SelectWakeup # If SelectWakeup, then just restart this loop - the select call will be made with the new data next rescue IOError, Errno::EBADF, EncodeError # A pipeline writer can close a socket after this loop snapshots its # read set, or while native select is waiting on its descriptor. exceptions = clean_up_closed_sockets exceptions.each { |exception| send_exception_to_client(*exception) } next end if ready && ready.include?(@@wakeup_sockets[1]) ready.delete(@@wakeup_sockets[1]) begin # Bound draining so continuously arriving notifications cannot starve # responses and timeouts. Any remainder wakes the next select. @@wakeup_sockets[1].recv_nonblock(4096) rescue IO::WaitReadable, IOError, SystemCallError end end if (ready == nil) # process the timeouts process_timeouts unused_loop_count+=1 else process_ready(ready) unused_loop_count=0 # process_error(errors) end state_mutex.synchronize do if (unused_loop_count > 10 && @@query_hash.empty? && @@observers.empty? && @@queued_exceptions.empty? && @@queued_responses.empty? && @@queued_validation_responses.empty?) Dnsruby.log.debug("Try stop select loop") # We leave the @@wakeup_sockets here, but remove everything else non_persistent_sockets = @@sockets.select { |s| ! @@socket_is_persistent[s] } non_persistent_sockets.each do |socket| if socket != @@wakeup_sockets[1] socket.close rescue nil retire_socket_from_mutex_synchronized_block(socket) end end Dnsruby.log.debug("Deleted #{non_persistent_sockets.size - 1} non-persistent sockets," + " #{@@sockets.count - 1} persistent sockets remain.") @@socket_hash.clear if @@sockets.size == 1 Dnsruby.log.debug("Stopping select loop") # A producer acquiring the mutex after this decision must start a # replacement, even while the old Ruby thread is still returning. @@select_thread = nil return end end end end end |
#fail_query_if_current(id, queue, previous_settings, error) ⇒ Object
A send waiting for the pipeline writer has no new socket registration yet. Its original attempt may have expired or been replaced in the meantime.
571 572 573 574 575 576 577 578 579 |
# File 'lib/dnsruby/select_thread.rb', line 571 def fail_query_if_current(id, queue, previous_settings, error) state_mutex.synchronize do return unless @@query_hash[id].equal?(previous_settings) remove_id_from_mutex_synchronized_block(id) if previous_settings @@queued_exceptions << [id, queue, error, nil] check_select_thread_synchronized end wake_up_select_thread end |
#fail_tcp_send(settings, error) ⇒ Object
A partial TCP frame makes the whole connection unusable. Atomically claim its outstanding queries, then let the selector deliver their errors. Sender threads must never invoke resolver callbacks themselves.
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 |
# File 'lib/dnsruby/select_thread.rb', line 553 def fail_tcp_send(settings, error) state_mutex.synchronize do settings.socket.close rescue nil exceptions = retire_socket_from_mutex_synchronized_block(settings.socket) exceptions.each do |eof, socket, id| current = @@query_hash[id] next unless current && current.socket == socket remove_id_from_mutex_synchronized_block(id) @@queued_exceptions << [id, current.client_queue, current.equal?(settings) ? error : eof, nil] end check_select_thread_synchronized unless @@queued_exceptions.empty? end wake_up_select_thread end |
#get_active_ids(queries, id) ⇒ Object
Retained for callers of this helper; response delivery now matches only queries registered on the receiving socket instead of scanning every ID.
742 743 744 |
# File 'lib/dnsruby/select_thread.rb', line 742 def get_active_ids(queries, id) queries.keys.select { |client_query_id| client_query_id[1].header.id == id } end |
#get_client_id_from_answerfrom(socket, answerip, answerport, header_id = nil) ⇒ Object
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 |
# File 'lib/dnsruby/select_thread.rb', line 1186 def get_client_id_from_answerfrom(socket, answerip, answerport, header_id=nil) # A pipelined socket can have several outstanding queries. client_id=nil # Figure out client id from answerfrom state_mutex.synchronize{ ids = (header_id ? socket_ids_for_header(socket, header_id) : (@@socket_hash[socket] || [])).select { |id| @@query_hash[id] } # TCP decoding can fail before the peer address has been assigned. The # socket and partial header identify its query, including pipeline use. if answerip.nil? if header_id matching = ids.select { |id| @@query_hash[id].query.header.id == header_id } return matching.first if matching.length == 1 return nil end return ids.first if ids.length == 1 return nil end ids.each do |id| # Does this id speak to this dest_server? query_settings = @@query_hash[id] next if header_id && query_settings.query.header.id != header_id # recvfrom may spell a numeric zone as an interface name. The socket # is already connected to the scoped peer, so compare address bytes. source = IPAddr.new(answerip.split('%', 2).first) destination = IPAddr.new(query_settings.dest_server.to_s.split('%', 2).first) if (source == destination && answerport == query_settings.dest_port) # We have a match client_id = id break end end } return client_id end |
#get_incoming_data(socket, packet_size) ⇒ Object
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 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 1122 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 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 |
# File 'lib/dnsruby/select_thread.rb', line 1016 def get_incoming_data(socket, packet_size) answerfrom,answerip,answerport,answersize=nil ans,buf = nil begin is_tcp = tcp?(socket) rescue IOError, SystemCallError # A concurrent pipeline writer can retire this socket after IO.select # returned it. It has already queued errors for its outstanding queries. return if socket.closed? raise end begin if is_tcp # Call TCP read here - that will take care of reading the 2 byte length, # and then the full packet - without blocking select. buf = tcp_read(socket) if (!buf) # Wait for the buffer to comletely fill # handle_recvfrom_failure(socket, "") return end else # @TODO@ Can we get recvfrom to stop issuing PTR queries when we already # know both the FQDN and the IP address? if (ret = socket.recvfrom_nonblock(packet_size)) buf = ret[0] answerport=ret[1][1] answerfrom=ret[1][2] answerip=ret[1][3] else # recvfrom failed - why? Dnsruby.log.error{"Error - recvfrom failed from #{socket}"} handle_recvfrom_failure(socket, "") return end end rescue IO::WaitReadable, Errno::EINTR # Readiness is only a hint; keep the query registered for its next event. return rescue Exception => e Dnsruby.log.error{"Error - recvfrom failed from #{socket}, exception : #{e}"} handle_recvfrom_failure(socket, e) return end answersize = buf.bytesize Dnsruby.log.debug{";; answer from #{answerfrom} : #{answersize} bytes\n"} begin ans = Message.decode(buf) rescue Exception => e Dnsruby.log.error("Decode error! #{e.class}, #{e}\nfor msg (length=#{buf.length}) : #{buf}") # A partial Message has a newly allocated, random header if decoding # failed before the complete header. Only the bytes identify its ID. header_id = buf.unpack('n').first if buf.bytesize >= 2 client_id=get_client_id_from_answerfrom(socket, answerip, answerport, header_id) if (client_id == nil) Dnsruby.log.error{"Decode error from #{answerip} but can't determine packet id"} return end unless is_tcp matches_question = state_mutex.synchronize do current = @@query_hash[client_id] partial = e. if e.is_a?(DecodeError) current && current.socket == socket && (current.query.send_raw || (buf.bytesize >= 12 && partial && (current.query.kind_of?(Update) || (!partial.question.empty? && partial.header.qdcount == partial.question.length && matching_questions?(partial, current.query))))) end # A truncated answer can justify TCP fallback only after its question # identifies this query (RFC 5452 section 9.1). Incomplete headers or # questions and unrelated questions cannot end the UDP transaction. return unless matches_question end # Decoding may fail after a complete header. Such a packet must match # the response direction and opcode before it can retry or fail its # owner, just as a successfully decoded response must. Use wire bytes: # an incomplete decoded Message can still contain a default header. if buf.bytesize >= 12 flags = buf.unpack('n2').last matches_header = state_mutex.synchronize do current = @@query_hash[client_id] current && current.socket == socket && (current.query.send_raw || ((flags & 0x8000) != 0 && ((flags >> 11) & 15) == current.query.header.opcode.code)) end return unless matches_header end # No undecodable packet can authenticate its TSIG. Discard it before # either failing the transaction or acting on an untrusted TC bit, just # as check_response discards unsigned or incorrectly signed replies. unauthenticated = state_mutex.synchronize do current = @@query_hash[client_id] if current && current.socket == socket && current.query.tsig && !current.query.send_raw current.authentication_error ||= TsigError.new('Cannot authenticate malformed response') true end end return if unauthenticated # Truncation permits a UDP-to-TCP fallback, never another TCP attempt. # Repeating malformed TCP replies must not renew the packet deadline. settings = nil if !is_tcp && (DecodeError === e) && e. && e..header.tc settings = state_mutex.synchronize do current = @@query_hash[client_id] if current && current.socket == socket && !current.ignore_truncation && !current.no_tcp current end end end if settings Dnsruby.log.error{"Decode error (from #{answerip})! Header shows truncation, so trying again over TCP"} previous_context = Thread.current[:dnsruby_response_query] begin Thread.current[:dnsruby_response_query] = settings settings.single_resolver.send_async(settings.query, settings.client_queue, client_id, true) ensure Thread.current[:dnsruby_response_query] = previous_context end else send_exception_to_client(e, socket, client_id) end return end if is_tcp # This supplies peer metadata only. Normal response checks below still # validate the question and TSIG, including sequential duplicate IDs. settings = state_mutex.synchronize do id = socket_ids_for_header(socket, ans.header.id).first @@query_hash[id] end unless settings Dnsruby.log.debug { "Ignoring TCP response with no matching query on this socket" } return end answerfrom = settings.dest_server answerip = answerfrom answerport = settings.dest_port end if (ans!= nil) Dnsruby.log.debug{"#{ans}"} ans.answerfrom=(answerfrom) ans.answersize=(answersize) ans.answerip =(answerip) end return ans, buf end |
#get_socket_pair ⇒ Object
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
# File 'lib/dnsruby/select_thread.rb', line 136 def get_socket_pair # Emulate socketpair on platforms which don't support it srv = nil begin srv = TCPServer.new('localhost', 0) rescue Errno::EADDRNOTAVAIL, SocketError # OSX Snow Leopard issue - need to use explicit IP begin srv = TCPServer.new('127.0.0.1', 0) rescue Error # Try IPv6 srv = TCPServer.new('::1', 0) end end rsock = TCPSocket.new(srv.addr[3], srv.addr[1]) lsock = srv.accept srv.close return [lsock, rsock] end |
#handle_recvfrom_failure(socket, exception) ⇒ Object
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 |
# File 'lib/dnsruby/select_thread.rb', line 1166 def handle_recvfrom_failure(socket, exception) # No way to notify the client about this error, unless there was only one connection on the socket # Not a problem, as there only will ever be one connection on the socket (Kaminsky attack mitigation) ids_for_socket = [] state_mutex.synchronize{ ids_for_socket = (@@socket_hash[socket] || []).to_a } return if ids_for_socket.empty? if (ids_for_socket.length == 1) answerfrom=nil state_mutex.synchronize{ query_settings = @@query_hash[ids_for_socket[0]] answerfrom=query_settings.dest_server if query_settings } send_exception_to_client(OtherResolvError.new("recvfrom failed from #{answerfrom}; #{exception}"), socket, ids_for_socket[0]) else Dnsruby.log.fatal{"Recvfrom failed from #{socket}, no way to tell query id"} end end |
#max_attained?(socket) ⇒ Boolean
916 917 918 919 920 921 |
# File 'lib/dnsruby/select_thread.rb', line 916 def max_attained?(socket) remaining = @@socket_remaining_queries[socket] attained = persistent?(socket) && remaining && remaining <= 0 Dnsruby.log.debug("Max queries per conn attained") if attained attained end |
#notify_queue_observers(client_queue, client_query_id) ⇒ Object
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 |
# File 'lib/dnsruby/select_thread.rb', line 1456 def notify_queue_observers(client_queue, client_query_id) # If any observers are known for this query queue then notify them observer=nil state_mutex.synchronize { observer = @@observers[client_queue] } if (observer) observer.handle_queue_event(client_queue, client_query_id) end rescue ClosedQueueError Dnsruby.log.debug { 'Observer could not deliver to a closed client queue' } end |
#persistent?(socket) ⇒ Boolean
842 843 844 |
# File 'lib/dnsruby/select_thread.rb', line 842 def persistent?(socket) @@socket_is_persistent[socket] end |
#process_error(errors) ⇒ Object
735 736 737 738 |
# File 'lib/dnsruby/select_thread.rb', line 735 def process_error(errors) Dnsruby.log.debug{"Error! #{errors.inspect}"} # @todo@ Process errors [can we do this in single socket environment?] end |
#process_message(msg, bytes, socket) ⇒ Object
765 766 767 768 769 |
# File 'lib/dnsruby/select_thread.rb', line 765 def (msg, bytes, socket) # Delivery looks up IDs only on this connected socket, then checks the # question and TSIG through PacketSender#check_response. send_response_to_client(msg, bytes, socket) end |
#process_ready(ready) ⇒ Object
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 |
# File 'lib/dnsruby/select_thread.rb', line 746 def process_ready(ready) persistent_sockets, nonpersistent_sockets = state_mutex.synchronize { ready.partition { |socket| persistent?(socket) } } nonpersistent_sockets.each do |socket| query_settings = state_mutex.synchronize { @@query_hash[(@@socket_hash[socket] || []).first] } next if !query_settings udp_packet_size = query_settings.udp_packet_size msg, bytes = get_incoming_data(socket, udp_packet_size) (msg, bytes, socket) if msg end persistent_sockets.each do |socket| msg, bytes = get_incoming_data(socket, 0) (msg, bytes, socket) if msg end end |
#process_timeouts ⇒ Object
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 |
# File 'lib/dnsruby/select_thread.rb', line 923 def process_timeouts # Pop only due owners under the same lock used for registrations. Keep # settings identities so a replacement attempt cannot be expired later. time_now = TransportClock.now settings_due = state_mutex.synchronize do due = [] while (first = @packet_deadlines&.first) && first[1] <= time_now id, = first @packet_deadlines.delete(id) due << @@query_hash[id] if @@query_hash[id] end due end settings_due.each do |settings| if claim_query(settings) deliver_queue_event(settings.client_queue, [settings.client_query_id, Resolver::EventType::ERROR, nil, settings.authentication_error || ResolvTimeout.new("Query timed out")]) end end end |
#push_exception_to_select(client_id, client_queue, err, msg) ⇒ Object
1235 1236 1237 1238 1239 1240 1241 |
# File 'lib/dnsruby/select_thread.rb', line 1235 def push_exception_to_select(client_id, client_queue, err, msg) state_mutex.synchronize{ @@queued_exceptions.push([client_id, client_queue, err, msg]) check_select_thread_synchronized } wake_up_select_thread end |
#push_response_for_query(settings, msg, query, resolver) ⇒ Object
Cache lookup can satisfy a protocol retry before it reaches the sender. Claim that exact attempt before publishing a result, just like a wire reply.
583 584 585 586 587 |
# File 'lib/dnsruby/select_thread.rb', line 583 def push_response_for_query(settings, msg, query, resolver) return unless claim_query(settings) push_response_to_select(settings.client_query_id, settings.client_queue, msg, query, resolver, settings.send_token&.transmission_budget) end |
#push_response_to_select(client_id, client_queue, msg, query, res, transmission_budget = nil) ⇒ Object
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 |
# File 'lib/dnsruby/select_thread.rb', line 1243 def push_response_to_select(client_id, client_queue, msg, query, res, transmission_budget = nil) # This needs to queue the response TO THE SELECT THREAD, which then needs # to send it out from its normal loop. Dnsruby.log.debug{"Pushing response to client queue direct from resolver or validator"} state_mutex.synchronize{ err = nil if (msg.rcode == RCode.NXDOMAIN) err = NXDomain.new end @@queued_responses.push([client_id, client_queue, msg, err, query, res, transmission_budget]) check_select_thread_synchronized } wake_up_select_thread end |
#push_to_client(client_id, client_queue, msg, err, query, res, transmission_budget = nil) ⇒ Object
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 |
# File 'lib/dnsruby/select_thread.rb', line 1324 def push_to_client(client_id, client_queue, msg, err, query, res, transmission_budget = nil) # Notify the resolver before validation so it stops competing attempts # while retaining the logical query's total deadline. return unless deliver_queue_event(client_queue, [client_id, Resolver::EventType::RECEIVED, msg, err]) if (!err || (err.instance_of?(NXDomain))) # The validator owns delivery of the validation result. validator = ValidatorThread.new(client_id, client_queue, msg, err, query, self, res, transmission_budget) validator.run end end |
#push_validation_response_to_select(client_id, client_queue, msg, err, query, res) ⇒ Object
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 |
# File 'lib/dnsruby/select_thread.rb', line 1258 def push_validation_response_to_select(client_id, client_queue, msg, err, query, res) # This needs to queue the response TO THE SELECT THREAD, which then needs # to send it out from its normal loop. Dnsruby.log.debug{"Pushing response to client queue direct from resolver or validator"} state_mutex.synchronize{ @@queued_validation_responses.push([client_id, client_queue, msg, err, query, res]) check_select_thread_synchronized } wake_up_select_thread end |
#query_id_in_use?(socket, header_id) ⇒ Boolean
528 529 530 531 532 |
# File 'lib/dnsruby/select_thread.rb', line 528 def query_id_in_use?(socket, header_id) state_mutex.synchronize do !socket_ids_for_header(socket, header_id).empty? end end |
#query_settings_for_id(client_query_id) ⇒ Object
418 419 420 |
# File 'lib/dnsruby/select_thread.rb', line 418 def query_settings_for_id(client_query_id) state_mutex.synchronize { @@query_hash[client_query_id] } end |
#register_query_if_current(query_settings, previous_settings) ⇒ Object
Reserve a pipeline query before writing, or replace a protocol retry. A deferred retry must not replace an attempt already completed or replaced.
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 |
# File 'lib/dnsruby/select_thread.rb', line 428 def register_query_if_current(query_settings, previous_settings) registered = state_mutex.synchronize do return false unless @@query_hash[query_settings.client_query_id].equal?(previous_settings) # Selection happens outside this mutex. A timeout or close may retire # that stream before admission, so leave the reservation untouched and # let the sender choose a new connection under the original deadline. if query_settings.is_persistent_socket && (query_settings.socket.closed? || (@@retiring_sockets ||= Set.new).include?(query_settings.socket)) return :retry_connection end query_settings.retire_connection = previous_settings.retire_connection if previous_settings check_select_thread_synchronized add_query_from_mutex_synchronized_block(query_settings) end wake_up_select_thread registered end |
#register_validation(client_queue, sender, control) ⇒ Object
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 |
# File 'lib/dnsruby/select_thread.rb', line 1367 def register_validation(client_queue, sender, control) state_mutex.synchronize do refresh_validation_process # A response may have been accepted just before close or its total # deadline. Remember prior observers weakly so rejected registrations # cannot keep completed client queues alive. if client_queue.closed? || ((@@observed_queues ||= ObjectSpace::WeakMap.new)[client_queue] && !@@observers[client_queue]) control.cancel return false end # The validation pool is small and bounded. Keep one registration list # rather than maintaining separate indexes for queues and senders. unless @@validations.any? { |queue, owner, token| queue.equal?(client_queue) && owner.equal?(sender) && token.equal?(control) } @@validations << [client_queue, sender, control] end true end end |
#remove_id(id) ⇒ Object
846 847 848 849 850 |
# File 'lib/dnsruby/select_thread.rb', line 846 def remove_id(id) state_mutex.synchronize do remove_id_from_mutex_synchronized_block(id) end end |
#remove_id_from_mutex_synchronized_block(id, preserved_token = nil, response_received = false) ⇒ Object
THIS MUST BE CALLED FROM INSIDE A @@mutex SYNCHRONISED BLOCK!
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 |
# File 'lib/dnsruby/select_thread.rb', line 853 def remove_id_from_mutex_synchronized_block(id, preserved_token = nil, response_received = false) settings = @@query_hash.delete(id) return unless settings ids = @@queries_by_queue[settings.client_queue] if ids ids.delete(id) @@queries_by_queue.delete(settings.client_queue) if ids.empty? end if (sender_ids = (@@queries_by_sender ||= {}.compare_by_identity)[settings.single_resolver]) sender_ids.delete(id) @@queries_by_sender.delete(settings.single_resolver) if sender_ids.empty? end settings.send_token.cancel unless settings.send_token.equal?(preserved_token) @@timeouts.delete(id) @packet_deadlines&.delete(id) socket = settings.socket return unless socket # A queued send may not have acquired a socket yet. (@@socket_hash[socket] || []).delete(id) if persistent?(socket) decrement_remaining_queries(socket) # An unanswered query can still produce a late reply, or leave an # incomplete frame in the reader. Drain existing peers, but never admit # another query on this stream after its ownership has been cancelled. (@@retiring_sockets ||= Set.new) << socket unless response_received end retiring = (@@retiring_sockets ||= Set.new).include?(socket) && (@@socket_hash[socket] || []).empty? if !persistent?(socket) || retiring || (max_attained?(socket) && (@@socket_hash[socket] || []).empty?) Dnsruby.log.debug("Closing socket #{socket}") socket.close rescue nil retire_socket_from_mutex_synchronized_block(socket) elsif (@@socket_hash[socket] || []).empty? # Idle time starts after the last outstanding response, never while a # query or pipeline writer still owns the socket. (@@socket_idle_deadlines ||= {})[socket] = TransportClock.now + settings.tcp_idle_timeout (@idle_deadlines ||= DeadlineQueue.new)[socket] = @@socket_idle_deadlines[socket] end end |
#remove_observer(client_queue, observer) ⇒ Object
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 |
# File 'lib/dnsruby/select_thread.rb', line 1440 def remove_observer(client_queue, observer) state_mutex.synchronize { if (@@observers[client_queue]==observer) registered_observer = @@observers.delete(client_queue) # Resolver completion/close owns every packet attempt for this queue, # including queued sends which have not opened a socket yet. cancel_queries_for_queue_synchronized(client_queue) cancel_validations_for_queue_synchronized(client_queue) remove_observer_queue_count(registered_observer) else Dnsruby.log.error{"remove_observer called with wrong observer for queue"} raise ArgumentError.new("remove_observer called with wrong observer for queue") end } end |
#reserve_send(settings, previous_settings = nil) ⇒ Object
Register ownership before work leaves the selector, including attempts which have not acquired a socket yet. Nil is never a live attempt token.
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/dnsruby/select_thread.rb', line 310 def reserve_send(settings, previous_settings = nil) state_mutex.synchronize do return false unless @@query_hash[settings.client_query_id].equal?(previous_settings) if previous_settings settings.retire_connection = previous_settings.retire_connection remove_id_from_mutex_synchronized_block(settings.client_query_id, settings.send_token) end @@query_hash[settings.client_query_id] = settings (@@queries_by_queue[settings.client_queue] ||= Set.new) << settings.client_query_id ((@@queries_by_sender ||= {}.compare_by_identity)[settings.single_resolver] ||= Set.new) << settings.client_query_id @@timeouts[settings.client_query_id] = settings.endtime (@packet_deadlines ||= DeadlineQueue.new)[settings.client_query_id] = settings.endtime check_select_thread_synchronized end wake_up_select_thread true end |
#retire_sender(sender) ⇒ Object
Explicit close retires streams owned by this sender, including idle and rolled-over pipelines. Other logical queries sharing a sender may finish, but future sends must choose a fresh connection.
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/dnsruby/select_thread.rb', line 490 def retire_sender(sender) state_mutex.synchronize do refresh_validation_process # A connect can be in progress without a socket in our read set yet. # Carry retirement through reservation replacements so its eventual # registration drains and closes, while later fresh sends can reuse. ((@@queries_by_sender ||= {}.compare_by_identity)[sender] || []).each do |id| settings = @@query_hash[id] settings.retire_connection = true if settings end ((@@sockets_by_sender ||= {}.compare_by_identity)[sender] || []).to_a.each do |socket| mark_socket_for_retirement(socket) end @@validations.each do |queue, owner, control| # A Resolver owns its validation through the queue observer. Removing # that observer cancels its work; retiring a shared or reconfigured # sender must let other accepted responses finish. Direct PacketSender # callers have no observer, so their sender's close still cancels them. control.cancel if owner.equal?(sender) && !@@observers[queue] end end wake_up_select_thread end |
#retire_socket(socket) ⇒ Object
514 515 516 517 |
# File 'lib/dnsruby/select_thread.rb', line 514 def retire_socket(socket) state_mutex.synchronize { mark_socket_for_retirement(socket) } wake_up_select_thread end |
#retire_socket_from_mutex_synchronized_block(socket) ⇒ Object
Called only with @@mutex held and after the socket has been closed.
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 |
# File 'lib/dnsruby/select_thread.rb', line 716 def retire_socket_from_mutex_synchronized_block(socket) ids = @@socket_hash.delete(socket) || [] @@sockets.delete(socket) @@tcp_buffers.delete(socket) @@socket_remaining_queries.delete(socket) (@@socket_idle_deadlines ||= {}).delete(socket) @idle_deadlines&.delete(socket) @@socket_is_persistent.delete(socket) owner = (@@socket_owners ||= {}).delete(socket) if (sockets = (@@sockets_by_sender ||= {}.compare_by_identity)[owner]) sockets.delete(socket) @@sockets_by_sender.delete(owner) if sockets.empty? end (@@retiring_sockets ||= Set.new).delete(socket) ids.map do |client_id| [SocketEofResolvError.new("TCP socket closed before all answers received"), socket, client_id] end end |
#reusable_socket?(socket) ⇒ Boolean
544 545 546 547 548 |
# File 'lib/dnsruby/select_thread.rb', line 544 def reusable_socket?(socket) state_mutex.synchronize do !socket.closed? && !(@@retiring_sockets ||= Set.new).include?(socket) end end |
#select_thread_alive? ⇒ Boolean
615 616 617 618 619 620 621 |
# File 'lib/dnsruby/select_thread.rb', line 615 def select_thread_alive? ret=true state_mutex.synchronize{ ret = !!(@@select_thread && @@select_thread.alive?) } return ret end |
#selector_thread? ⇒ Boolean
422 423 424 |
# File 'lib/dnsruby/select_thread.rb', line 422 def selector_thread? state_mutex.synchronize { @@select_thread.equal?(Thread.current) } end |
#send_exception_to_client(err, socket, client_id, msg = nil) ⇒ Object
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 |
# File 'lib/dnsruby/select_thread.rb', line 1222 def send_exception_to_client(err, socket, client_id, msg=nil) # find the client response queue client_queue = nil state_mutex.synchronize { settings = @@query_hash[client_id] return unless settings && (!socket || settings.socket == socket) client_queue = settings.client_queue remove_id_from_mutex_synchronized_block(client_id) } # push_to_client(client_id, client_queue, msg, err) deliver_queue_event(client_queue, [client_id, Resolver::EventType::ERROR, msg, err]) end |
#send_queued_exceptions ⇒ Object
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
# File 'lib/dnsruby/select_thread.rb', line 1269 def send_queued_exceptions exceptions = [] state_mutex.synchronize{ exceptions = @@queued_exceptions @@queued_exceptions = [] } exceptions.each do |item| client_id, client_queue, err, msg = item # push_to_client(client_id, client_queue, msg, err) deliver_queue_event(client_queue, [client_id, Resolver::EventType::ERROR, msg, err]) end end |
#send_queued_responses ⇒ Object
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 |
# File 'lib/dnsruby/select_thread.rb', line 1283 def send_queued_responses responses = [] state_mutex.synchronize{ responses = @@queued_responses @@queued_responses = [] } responses.each do |item| client_id, client_queue, msg, err, query, res, transmission_budget = item # push_to_client(client_id, client_queue, msg, err) next unless deliver_queue_event(client_queue, [client_id, Resolver::EventType::RECEIVED, msg, err]) # Do we need to validate this? The response has come from the cache - # validate it only if it has not been validated already # So, if we need to validate it, send it to the validation thread # Otherwise, send VALIDATED to the requester. if (((msg.security_level == Message::SecurityLevel.UNCHECKED) || (msg.security_level == Message::SecurityLevel.INDETERMINATE)) && (ValidatorThread.requires_validation?(query, msg, err, res))) validator = ValidatorThread.new(client_id, client_queue, msg, err, query, self, res, transmission_budget) validator.run else PacketSender.cache(query, msg) # The validator won't cache it, so we'd better do it now deliver_queue_event(client_queue, [client_id, Resolver::EventType::VALIDATED, msg, err]) end end end |
#send_queued_validation_responses ⇒ Object
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 |
# File 'lib/dnsruby/select_thread.rb', line 1310 def send_queued_validation_responses responses = [] state_mutex.synchronize{ responses = @@queued_validation_responses @@queued_validation_responses = [] } responses.each do |item| client_id, client_queue, msg, err, _query, _res = item # push_to_client(client_id, client_queue, msg, err) deliver_queue_event(client_queue, [client_id, Resolver::EventType::VALIDATED, msg, err]) end end |
#send_response_to_client(msg, bytes, socket) ⇒ Object
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 |
# File 'lib/dnsruby/select_thread.rb', line 780 def send_response_to_client(msg, bytes, socket) # Match the header ID against queries outstanding on this connection. client_ids=[] state_mutex.synchronize{ client_ids = socket_ids_for_header(socket, msg.header.id) } # get the queries associated with them client_ids.each do |id| settings = state_mutex.synchronize { @@query_hash[id] } next unless settings && settings.socket == socket query_header_id = settings.query.header.id if (query_header_id == msg.header.id) # IDs can collide on a pipeline. Select the matching question before # query-specific TSIG checks or retries, which may consume the attempt. # Preserve raw/update responses and questionless FORMERR handling. query = settings.query unless query.send_raw || query.kind_of?(Update) || msg.question.empty? next unless matching_questions?(msg, query) end # process the response client_queue = settings.client_queue res = settings.single_resolver query = settings.query begin tcp = settings.is_persistent_socket || tcp?(socket) rescue IOError, SystemCallError return if socket.closed? raise end # At this point, we should check if the response is OK previous_context = Thread.current[:dnsruby_response_query] begin # check_response may synchronously retry (FORMERR or truncation). # Carry this attempt's identity through that unchanged public API. Thread.current[:dnsruby_response_query] = settings ret = res.check_response(msg, bytes, query, client_queue, id, tcp) ensure Thread.current[:dnsruby_response_query] = previous_context end if ret # A writer failure or a retry can replace/remove settings while # check_response runs. Only one path may claim this attempt. return unless claim_query(settings, true) exception = msg.get_exception if (ret.kind_of?TsigError) exception = ret end Dnsruby.log.debug{"Pushing response to client queue"} push_to_client(id, client_queue, msg, exception, query, res, settings.send_token&.transmission_budget) # client_queue.push([id, msg, exception]) # notify_queue_observers(client_queue, id) else # Sending query again - don't return response end return end end # If not, then we have an error Dnsruby.log.error{"Stray packet - " + msg.inspect + "\n from " + socket.inspect} end |
#send_tick_to_observers(due_only = true) ⇒ Object
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 |
# File 'lib/dnsruby/select_thread.rb', line 1487 def send_tick_to_observers(due_only = true) # Observer callbacks acquire Resolver locks, so never call them under the # selector lock. Tick only observers with a retry or query deadline due. tick_observers = state_mutex.synchronize { @@tick_observers.dup } tick_observers.each do |observer| begin if observer.respond_to?(:next_tick_at) deadline = observer.next_tick_at observer.tick if !due_only || (deadline && deadline <= TransportClock.now) else observer.tick end rescue ClosedQueueError Dnsruby.log.debug { 'Observer tick could not deliver to a closed client queue' } end end end |
#tcp?(socket) ⇒ Boolean
399 400 401 402 |
# File 'lib/dnsruby/select_thread.rb', line 399 def tcp?(socket) type = socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_TYPE) [Socket::SOCK_STREAM].pack("i") == type.data end |
#tcp_read(socket) ⇒ Object
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
# File 'lib/dnsruby/select_thread.rb', line 944 def tcp_read(socket) # Keep buffer for all TCP sockets, and return # to select after reading available data. Once all data has been received, # then process message. buf = +"" expected_length = 0 reading_length = nil state_mutex.synchronize { return false if socket.closed? buf, expected_length, reading_length = @@tcp_buffers[socket] if (!buf) buf = +"" expected_length = 2 reading_length = true @@tcp_buffers[socket]=[buf, expected_length, reading_length] end } if (buf.length() < expected_length) begin input, = socket.recv_nonblock(expected_length-buf.length) # Depending on the Ruby version, EOF is nil or an empty string. if input.nil? || input.empty? Dnsruby.log.debug("EOF from server - no bytes read - closing socket") exceptions = state_mutex.synchronize do socket.close retire_socket_from_mutex_synchronized_block(socket) end exceptions.each { |exception| send_exception_to_client(*exception) } return false end buf << input if input rescue IO::WaitReadable, Errno::EINTR return false rescue IOError, SystemCallError => error # A reset or fatal read failure cannot become readable again. Retire # every owner once, without invoking resolver callbacks under our lock. exceptions = state_mutex.synchronize do socket.close rescue nil retire_socket_from_mutex_synchronized_block(socket) end exceptions.each { |exception| send_exception_to_client(*exception) } Dnsruby.log.debug { "TCP read failed: #{error.class}: #{error.}" } return false end end # If data is complete, then return it. if (buf.length == expected_length) if reading_length # We just read the data_length field. Now we need to start reading that many bytes. state_mutex.synchronize { return false if socket.closed? answersize = buf.unpack('n')[0] @@tcp_buffers[socket] = [+"", answersize, false] } return tcp_read(socket) else # We just read the data - now return it state_mutex.synchronize { @@tcp_buffers.delete(socket) } return buf end else state_mutex.synchronize { return false if socket.closed? @@tcp_buffers[socket]=[buf, expected_length, reading_length] } return false end end |
#track_socket(socket) ⇒ Object
Keep weak references from allocation through connect/write, before a socket joins the read set. A fork must close those descriptor copies too.
131 132 133 134 |
# File 'lib/dnsruby/select_thread.rb', line 131 def track_socket(socket) state_mutex.synchronize { (@created_sockets ||= ObjectSpace::WeakMap.new)[socket] = true } socket end |
#udp?(socket) ⇒ Boolean
404 405 406 407 |
# File 'lib/dnsruby/select_thread.rb', line 404 def udp?(socket) type = socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_TYPE) [Socket::SOCK_DGRAM].pack("i") == type.data end |
#unregister_validation(client_queue, sender, control) ⇒ Object
1388 1389 1390 1391 1392 1393 1394 1395 |
# File 'lib/dnsruby/select_thread.rb', line 1388 def unregister_validation(client_queue, sender, control) state_mutex.synchronize do refresh_validation_process @@validations.delete_if do |queue, owner, token| queue.equal?(client_queue) && owner.equal?(sender) && token.equal?(control) end end end |
#validation_deadline(client_queue, client_query_id) ⇒ Object
Take the observer snapshot before acquiring its Resolver lock: Resolver completion acquires these locks in the opposite direction.
1355 1356 1357 1358 |
# File 'lib/dnsruby/select_thread.rb', line 1355 def validation_deadline(client_queue, client_query_id) observer = state_mutex.synchronize { @@observers[client_queue] } observer.validation_deadline(client_queue, client_query_id) if observer.respond_to?(:validation_deadline) end |
#validation_transmission_budget(client_queue, client_query_id) ⇒ Object
1360 1361 1362 1363 1364 1365 |
# File 'lib/dnsruby/select_thread.rb', line 1360 def validation_transmission_budget(client_queue, client_query_id) observer = state_mutex.synchronize { @@observers[client_queue] } if observer.respond_to?(:validation_transmission_budget) observer.validation_transmission_budget(client_queue, client_query_id) end end |
#wake_up_select_thread ⇒ Object
597 598 599 600 601 602 603 604 |
# File 'lib/dnsruby/select_thread.rb', line 597 def wake_up_select_thread # One unread byte is sufficient: a full socket already guarantees that # select will wake. Never let notification block a producer or the selector # itself (cache hits and protocol retries also produce notifications). @@wakeup_sockets[0].write_nonblock(".") rescue IO::WaitWritable, IOError, SystemCallError nil end |