net-tns 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +202 -0
  3. data/bin/tns_oradb_version.rb +15 -0
  4. data/bin/tns_sid_enumeration.rb +52 -0
  5. data/bin/tns_sid_list.rb +43 -0
  6. data/lib/net/tns/client.rb +94 -0
  7. data/lib/net/tns/connection.rb +201 -0
  8. data/lib/net/tns/exceptions.rb +34 -0
  9. data/lib/net/tns/gem_version.rb +5 -0
  10. data/lib/net/tns/helpers/string_helpers.rb +49 -0
  11. data/lib/net/tns/packet.rb +82 -0
  12. data/lib/net/tns/packets/abort_packet.rb +12 -0
  13. data/lib/net/tns/packets/accept_packet.rb +19 -0
  14. data/lib/net/tns/packets/ack_packet.rb +7 -0
  15. data/lib/net/tns/packets/attention_packet.rb +9 -0
  16. data/lib/net/tns/packets/connect_packet.rb +55 -0
  17. data/lib/net/tns/packets/control_packet.rb +7 -0
  18. data/lib/net/tns/packets/data_packet.rb +20 -0
  19. data/lib/net/tns/packets/marker_packet.rb +18 -0
  20. data/lib/net/tns/packets/null_packet.rb +7 -0
  21. data/lib/net/tns/packets/redirect_packet.rb +10 -0
  22. data/lib/net/tns/packets/refuse_packet.rb +12 -0
  23. data/lib/net/tns/packets/resend_packet.rb +7 -0
  24. data/lib/net/tns/version.rb +15 -0
  25. data/lib/net/tns.rb +20 -0
  26. data/lib/net/tti/client.rb +90 -0
  27. data/lib/net/tti/connection.rb +142 -0
  28. data/lib/net/tti/crypto.rb +189 -0
  29. data/lib/net/tti/data_types/chunked_string.rb +63 -0
  30. data/lib/net/tti/data_types/key_value_pair.rb +25 -0
  31. data/lib/net/tti/data_types.rb +2 -0
  32. data/lib/net/tti/exceptions.rb +62 -0
  33. data/lib/net/tti/message.rb +50 -0
  34. data/lib/net/tti/messages/data_type_negotiation_request.rb +133 -0
  35. data/lib/net/tti/messages/data_type_negotiation_response.rb +9 -0
  36. data/lib/net/tti/messages/error_message.rb +14 -0
  37. data/lib/net/tti/messages/function_call.rb +46 -0
  38. data/lib/net/tti/messages/function_calls/authentication.rb +45 -0
  39. data/lib/net/tti/messages/function_calls/authentication_x64.rb +42 -0
  40. data/lib/net/tti/messages/function_calls/authentication_x86.rb +53 -0
  41. data/lib/net/tti/messages/function_calls/pre_authentication_response.rb +32 -0
  42. data/lib/net/tti/messages/protocol_negotiation_request.rb +29 -0
  43. data/lib/net/tti/messages/protocol_negotiation_response.rb +44 -0
  44. data/lib/net/tti.rb +18 -0
  45. metadata +128 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: d03a8d027339c11e4a2a9352aa3f48db222a9bc1
4
+ data.tar.gz: 782786a91cedfd3b3cafd7faba2fefa099baa65c
5
+ SHA512:
6
+ metadata.gz: 4bdfd445c3f87d49112fc5c41fc64c3d10d5a5b49331a44a1869a8551265086574cb608bc4d1115c372df8e454c887a17c6dd075a314adda99851300ff01e4d8
7
+ data.tar.gz: ca09a8ce51d48f51afe4ea19fe71f27d0ed27bdd85662871f1c0e3239a09f7add3bc64a1c1f08f6c7d891ee7817b12d40667f14af1c21d8b2c57dd19e10c0ea0
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "net/tns"
4
+
5
+ if (ARGV.size < 1 or ARGV[0] == '-h')
6
+ STDERR.puts("Usage: #{File.basename $0} host [port]")
7
+ exit 1
8
+ end
9
+
10
+ opts = {}
11
+ opts[:host] = ARGV.shift
12
+ port = ARGV.shift
13
+ opts[:port] = port.to_i unless port.nil?
14
+
15
+ puts Net::TNS::Client.get_version(opts)
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "net/tns"
4
+ require "set"
5
+
6
+ if (ARGV.size < 1 or ARGV[0] == '-h')
7
+ STDERR.puts("Usage: #{File.basename $0} host [port]")
8
+ exit 1
9
+ end
10
+
11
+ @conn_opts = {}
12
+ @conn_opts[:host] = ARGV.shift
13
+ port = ARGV.shift
14
+ @conn_opts[:port] = port.to_i unless port.nil?
15
+
16
+ def valid_sid?(name)
17
+ begin
18
+ conn = Net::TNS::Connection.new(@conn_opts)
19
+ conn.connect(:sid=>name)
20
+ return true
21
+ rescue Net::TNS::Exceptions::RefuseMessageReceived
22
+ ensure
23
+ conn.disconnect() if conn
24
+ end
25
+ return false
26
+ end
27
+
28
+
29
+ dictionary = [
30
+ "ORCL",
31
+ "ORACLE",
32
+ "ORADB",
33
+ "XE",
34
+ "TEST",
35
+ "PLSExtProc",
36
+ ]
37
+
38
+ sids = Set.new
39
+ begin
40
+ dictionary.each do |name|
41
+ sids << name if valid_sid?(name)
42
+ end
43
+
44
+ ensure
45
+ unless sids.empty?
46
+ puts "SIDs:\n " + sids.to_a.join("\n ")
47
+ end
48
+
49
+ if sids.empty?
50
+ puts "No valid SIDs found"
51
+ end
52
+ end
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "net/tns"
4
+ require "set"
5
+
6
+ if (ARGV.size < 1 or ARGV[0] == '-h')
7
+ STDERR.puts("Usage: #{File.basename $0} host [port]")
8
+ exit 1
9
+ end
10
+
11
+ opts = {}
12
+ opts[:host] = ARGV.shift
13
+ port = ARGV.shift
14
+ opts[:port] = port.to_i unless port.nil?
15
+
16
+ begin
17
+ sids = Set.new
18
+ service_names = Set.new
19
+
20
+ status_raw = Net::TNS::Client.get_status(opts)
21
+ status_raw.scan(/(INSTANCE|SERVICE)_NAME=([^\)]+)/).each do |type, name|
22
+ case type
23
+ when "INSTANCE"
24
+ sids << name
25
+ when "SERVICE"
26
+ service_names << name
27
+ end
28
+ end
29
+
30
+ unless sids.empty?
31
+ puts "SIDs:\n " + sids.to_a.join("\n ")
32
+ end
33
+
34
+ unless service_names.empty?
35
+ puts "Service Names:\n " + service_names.to_a.join("\n ")
36
+ end
37
+
38
+ if sids.empty? && service_names.empty?
39
+ puts "No SIDs or service names received."
40
+ end
41
+ rescue Net::TNS::Exceptions::RefuseMessageReceived
42
+ warn "Server refused the request"
43
+ end
@@ -0,0 +1,94 @@
1
+ module Net
2
+ module TNS
3
+ class Client
4
+ def self.ping?(opts={})
5
+ begin
6
+ conn = Connection.new(opts)
7
+ conn.open_socket()
8
+ request = ConnectPacket.new(:data => "(CONNECT_DATA=(COMMAND=ping))")
9
+ conn.send_and_receive( request )
10
+ return true
11
+ rescue Exceptions::ConnectionClosed
12
+ return false
13
+ rescue Exceptions::TnsException
14
+ return true
15
+ ensure
16
+ conn.close_socket() unless conn.nil?
17
+ end
18
+ end
19
+
20
+ def self.get_version(opts={})
21
+ begin
22
+ conn = Connection.new(opts)
23
+ conn.open_socket()
24
+ request = ConnectPacket.new(:data => "(CONNECT_DATA=(COMMAND=VERSION))")
25
+
26
+ response = conn.send_and_receive( request )
27
+ raise "Expected AcceptPacket in response" unless response.is_a?(AcceptPacket)
28
+
29
+ version_data = response.data
30
+ rescue Exceptions::RefuseMessageReceived => refuse_err
31
+ version_data = refuse_err.message
32
+ ensure
33
+ conn.close_socket() unless conn.nil?
34
+ end
35
+
36
+ return nil if version_data.nil?
37
+
38
+ if ( version_match = version_data.match( /Version ((?:\d+.)+\d+)/ ) ) then
39
+ return version_match[1]
40
+ # If that didn't work, see if we got an encoded version number
41
+ elsif ( version_match = version_data.match( /\(VSNNUM=(\d+)\)/ ) ) then
42
+ return parse_vsnnum(version_match[1])
43
+ end
44
+ end
45
+
46
+ def self.get_status(opts={})
47
+ begin
48
+ conn = Connection.new(opts)
49
+ conn.open_socket()
50
+ request = ConnectPacket.new(:data => "(CONNECT_DATA=(COMMAND=STATUS))")
51
+
52
+ status_response_raw = ""
53
+ begin
54
+ response = conn.send_and_receive( request )
55
+ rescue EOFError
56
+ # The first packet sent is an Accept with an unknown structure.
57
+ # Attempting to parse it as an Accept results in an EOFError, due to
58
+ # a data length that is greater than the available data.
59
+ end
60
+
61
+ # Successful responses are typically spread across multiple Data packets.
62
+ while ( response = conn.receive_tns_packet() )
63
+ break unless response.is_a?(DataPacket)
64
+ break if response.flags == 0x0040
65
+ status_response_raw += response.data
66
+ end
67
+ return status_response_raw
68
+ ensure
69
+ conn.close_socket() unless conn.nil?
70
+ end
71
+ end
72
+
73
+ # Parse the "VSNNUM" component of certain TNS listener responses, which
74
+ # contains an encoded form of the version number.
75
+ def self.parse_vsnnum(vsnnum_string)
76
+ # The VSNNUM is a really insane way of encoding the version number. It
77
+ # is a decimal number (e.g. 169869568) that, in hex (e.g. A200100),
78
+ # is a weird representation of the dotted version
79
+ # (e.g. 169869568 -> A200100 -> A.2.0.01.00 -> A.2.0.1.0 -> 10.2.0.1.0).
80
+ raise ArgumentError unless vsnnum_string.is_a?(String)
81
+ vsnnum_decimal = vsnnum_string.to_i
82
+
83
+ version_components = []
84
+ version_components << (( vsnnum_decimal >> 24 ) & 0xF)
85
+ version_components << (( vsnnum_decimal >> 20 ) & 0xF)
86
+ version_components << (( vsnnum_decimal >> 16 ) & 0xF)
87
+ version_components << (( vsnnum_decimal >> 8 ) & 0xFF)
88
+ version_components << (( vsnnum_decimal >> 0 ) & 0xFF)
89
+
90
+ return version_components.join('.')
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,201 @@
1
+ require "net/tns/packet"
2
+ require "net/tns/exceptions"
3
+
4
+ module Net
5
+ module TNS
6
+ class Connection
7
+ attr_reader :tns_protocol_version
8
+
9
+ def initialize(opts={})
10
+ opts = {
11
+ :port => 1521,
12
+ }.merge(opts)
13
+
14
+ @socket = nil
15
+ @socket_opts = {}
16
+ socket_opts_keys = [:host, :port, :get_socket_callback, :close_socket_callback]
17
+ socket_opts_keys.each {|key| @socket_opts[key] = opts.delete(key) if opts.has_key?(key)}
18
+
19
+ raise ArgumentError.new("Unrecognized options: #{opts.keys}") unless opts.empty?
20
+ end
21
+
22
+ # This is a low-level function to directly open a socket for this connection.
23
+ # Most callers should use #connect instead, which will open a socket and
24
+ # negotiate a TNS connection.
25
+ def open_socket
26
+ Net::TNS.logger.debug("Connection#open_socket called")
27
+ close_socket()
28
+
29
+ if (host = @socket_opts[:host]) && (port = @socket_opts[:port])
30
+ if @socket_opts.has_key?(:get_socket_callback) || @socket_opts.has_key?(:close_socket_callback)
31
+ raise ArgumentError.new("Cannot specify :host/:port with :get_socket_callback/:close_socket_callback")
32
+ end
33
+
34
+ require "socket"
35
+ Net::TNS.logger.info("Creating new TCPSocket for #{host}:#{port}")
36
+ @socket = TCPSocket.new(host, port)
37
+ elsif socket_cb = @socket_opts[:get_socket_callback]
38
+ Net::TNS.logger.info("Calling get-socket callback for new socket")
39
+ @socket = socket_cb.call()
40
+ else
41
+ raise ArgumentError.new("No valid options for socket creation. Need :host and :port, or :get_socket_callback (:close_socket_callback optional)")
42
+ end
43
+
44
+ return
45
+ end
46
+
47
+ # This is a low-level function to directly close the socket for this connection.
48
+ # Most callers should use #disconnect instead, which will disconnect the
49
+ # TNS connection before closing the socket.
50
+ def close_socket
51
+ Net::TNS.logger.debug("Connection#close_socket called")
52
+ begin
53
+ unless @socket.nil?
54
+ if close_cb = @socket_opts[:close_socket_callback]
55
+ Net::TNS.logger.info("Calling close-socket callback to close socket")
56
+ close_cb.call(@socket)
57
+ else
58
+ unless @socket.closed?
59
+ Net::TNS.logger.info("Closing socket")
60
+ @socket.close
61
+ end
62
+ end
63
+ end
64
+ ensure
65
+ @socket = nil
66
+ end
67
+ end
68
+
69
+ def connect(opts={})
70
+ sid = opts.delete(:sid) if opts.has_key?(:sid)
71
+ service_name = opts.delete(:service_name) if opts.has_key?(:service_name)
72
+ raise ArgumentError.new("Unrecognized opts: #{opts.keys}") unless opts.empty?
73
+ raise ArgumentError.new("Must specify :sid or :service_name") unless sid.nil? != service_name.nil?
74
+
75
+ open_socket() if @socket.nil?
76
+ dst_host = @socket.peeraddr[3]
77
+ dst_port = @socket.peeraddr[1]
78
+
79
+ if sid
80
+ Net::TNS.logger.debug("Connecting to target by SID (""#{sid}"")")
81
+ connect_packet = ConnectPacket.make_connection_by_sid( dst_host, dst_port, sid )
82
+ elsif service_name
83
+ Net::TNS.logger.debug("Connecting to target by service name (""#{service_name}"")")
84
+ connect_packet = ConnectPacket.make_connection_by_service_name( dst_host, dst_port, service_name )
85
+ end
86
+
87
+ response = send_and_receive(connect_packet)
88
+ unless response.is_a?(AcceptPacket)
89
+ raise Exceptions::ProtocolException.new("Unexpected response to Connect packet: #{response.class}")
90
+ end
91
+
92
+ @tns_protocol_version = response.version.to_i
93
+ negotiate_ano()
94
+ end
95
+
96
+ def disconnect
97
+ begin
98
+ packet = DataPacket.make_disconnect_request
99
+ send_tns_packet( packet )
100
+ ensure
101
+ close_socket()
102
+ end
103
+ end
104
+
105
+ # Perform negotiation of Additional Network Options ("SNS" in Wireshark).
106
+ # This is actually a different layer from TNS, but we're basically
107
+ # ignoring it anyway, so there's no sense factoring it out of Net::TNS (yet).
108
+ def negotiate_ano
109
+ # create request for no ANO
110
+ request = DataPacket.new()
111
+ request.data = ("deadbeef00920a2001000004000004000300000000000400050a200100000800" +
112
+ "0100000b58884d7db000120001deadbeef000300000004000400010001000200" +
113
+ "01000300000000000400050a20010000020003e0e100020006fcff0002000200" +
114
+ "000000000400050a200100000c0001001106100c0f0a0b080201030003000200" +
115
+ "000000000400050a20010000030001000301").tns_unhexify
116
+
117
+ Net::TNS.logger.debug("Sending ANO negotiation request")
118
+ response = send_and_receive(request)
119
+ unless response.is_a?(DataPacket) && response.data.start_with?("deadbeef".tns_unhexify)
120
+ raise Exceptions::ProtocolException.new("Unexpected response to ANO request")
121
+ end
122
+ return response.data
123
+ end
124
+ private :negotiate_ano
125
+
126
+
127
+
128
+ def send_and_receive( packet )
129
+ send_tns_packet( packet )
130
+ receive_tns_packet()
131
+ end
132
+
133
+ # @param packet [Net::TNS::Packet]
134
+ def send_tns_packet( packet )
135
+ # Store this in case we get a Resend
136
+ @tns_last_sent_packet = packet
137
+ Net::TNS.logger.debug( "Sending packet #{packet.class} (#{packet.num_bytes} bytes)" )
138
+ @socket.write( packet.to_binary_s )
139
+ end
140
+
141
+ def resend_last_tns_packet
142
+ if @tns_last_sent_packet.nil?
143
+ raise Exceptions::TnsException.new( "Resend received without a packet to resend" )
144
+ end
145
+ send_tns_packet( @tns_last_sent_packet )
146
+ end
147
+ private :resend_last_tns_packet
148
+
149
+ # Attempts to receive a TNS message.
150
+ #
151
+ # @param [Boolean] (Optional) Indicates a special state in which an error
152
+ # notification has been received, and we expect to be receiving a response
153
+ # to a request for the error message.
154
+ # @return [Net::TNS::Packet]
155
+ # @raise [Net::TNS::Exceptions::RefuseMessageReceived] If the other side
156
+ # sent TNS refuse message.
157
+ # @raise [Net::TNS::Exceptions::TnsException] If another unexpected
158
+ # state or action occurs.
159
+ def receive_tns_packet( waiting_for_error_message = false )
160
+ # This is structured as a loop in order to handle messages (e.g. Resends)
161
+ # that need to be handled without returning to the caller. To keep a malicious
162
+ # server from making us loop continuously, we set an arbitrary limit of
163
+ # 10 loops without a "real" message before we throw an exception.
164
+ receive_count = 0
165
+ while ( true )
166
+ raise Exceptions::ConnectionClosed if @socket.closed?
167
+
168
+ receive_count += 1
169
+ if ( receive_count >= 3 )
170
+ raise Exceptions::TnsException.new( "Maximum receive attempts exceeded - too many Resends received." )
171
+ end
172
+
173
+ # Try to receive a TNS packet
174
+ Net::TNS.logger.debug("Attempting to receive packet (try ##{receive_count})")
175
+ packet = Net::TNS::Packet.from_socket(@socket)
176
+
177
+ case packet
178
+ when Net::TNS::RefusePacket
179
+ Net::TNS.logger.warn("Received RefusePacket")
180
+ raise Exceptions::RefuseMessageReceived.new( packet.data )
181
+
182
+ # # We received a redirect request (typical of Oracle 9 and possibly previous versions)
183
+ # when Net::TNS::RedirectPacket
184
+ # raise Exceptions::RedirectMessageReceived.new( packet.data )
185
+
186
+ # We received a request to resend the last packet
187
+ when Net::TNS::ResendPacket
188
+ Net::TNS.logger.debug("Received ResendPacket")
189
+ # Re-send the last packet and then loop again
190
+ resend_last_tns_packet()
191
+
192
+ # We received a normal response
193
+ else
194
+ Net::TNS.logger.debug("Received #{packet.class} (#{packet.num_bytes} bytes)")
195
+ return packet
196
+ end
197
+ end
198
+ end
199
+ end
200
+ end
201
+ end
@@ -0,0 +1,34 @@
1
+ module Net::TNS
2
+ module Exceptions
3
+ class TnsException < StandardError
4
+ end
5
+
6
+ class ProtocolException < TnsException
7
+ end
8
+
9
+
10
+ class ReceiveTimeoutExceeded < TnsException
11
+ end
12
+
13
+ class ConnectionClosed < TnsException
14
+ end
15
+
16
+ class RefuseMessageReceived < TnsException
17
+ end
18
+
19
+ class RedirectMessageReceived < TnsException
20
+ attr_reader :new_port
21
+ attr_reader :new_host
22
+
23
+ def initialize( message )
24
+ super( message )
25
+
26
+ host_matches = /\(HOST=([^\)]+)\)/.match( self.message )
27
+ @new_host = host_matches[1] unless host_matches.nil?
28
+
29
+ port_matches = /\(PORT=(\d{1,5})\)/.match( self.message )
30
+ @new_port = port_matches[1] unless port_matches.nil?
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,5 @@
1
+ module Net
2
+ module TNS
3
+ VERSION = "1.0.0"
4
+ end
5
+ end