eventmachine-mkroman 1.3.0.dev.1

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 (182) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +179 -0
  3. data/GNU +281 -0
  4. data/LICENSE +60 -0
  5. data/README.md +110 -0
  6. data/docs/DocumentationGuidesIndex.md +27 -0
  7. data/docs/GettingStarted.md +520 -0
  8. data/docs/old/ChangeLog +211 -0
  9. data/docs/old/DEFERRABLES +246 -0
  10. data/docs/old/EPOLL +141 -0
  11. data/docs/old/INSTALL +13 -0
  12. data/docs/old/KEYBOARD +42 -0
  13. data/docs/old/LEGAL +25 -0
  14. data/docs/old/LIGHTWEIGHT_CONCURRENCY +130 -0
  15. data/docs/old/PURE_RUBY +75 -0
  16. data/docs/old/RELEASE_NOTES +94 -0
  17. data/docs/old/SMTP +4 -0
  18. data/docs/old/SPAWNED_PROCESSES +148 -0
  19. data/docs/old/TODO +8 -0
  20. data/examples/guides/getting_started/01_eventmachine_echo_server.rb +18 -0
  21. data/examples/guides/getting_started/02_eventmachine_echo_server_that_recognizes_exit_command.rb +22 -0
  22. data/examples/guides/getting_started/03_simple_chat_server.rb +149 -0
  23. data/examples/guides/getting_started/04_simple_chat_server_step_one.rb +27 -0
  24. data/examples/guides/getting_started/05_simple_chat_server_step_two.rb +43 -0
  25. data/examples/guides/getting_started/06_simple_chat_server_step_three.rb +98 -0
  26. data/examples/guides/getting_started/07_simple_chat_server_step_four.rb +121 -0
  27. data/examples/guides/getting_started/08_simple_chat_server_step_five.rb +141 -0
  28. data/examples/old/ex_channel.rb +43 -0
  29. data/examples/old/ex_queue.rb +2 -0
  30. data/examples/old/ex_tick_loop_array.rb +15 -0
  31. data/examples/old/ex_tick_loop_counter.rb +32 -0
  32. data/examples/old/helper.rb +2 -0
  33. data/ext/binder.cpp +124 -0
  34. data/ext/binder.h +52 -0
  35. data/ext/cmain.cpp +1046 -0
  36. data/ext/ed.cpp +2243 -0
  37. data/ext/ed.h +463 -0
  38. data/ext/em.cpp +2378 -0
  39. data/ext/em.h +266 -0
  40. data/ext/eventmachine.h +152 -0
  41. data/ext/extconf.rb +291 -0
  42. data/ext/fastfilereader/extconf.rb +120 -0
  43. data/ext/fastfilereader/mapper.cpp +214 -0
  44. data/ext/fastfilereader/mapper.h +59 -0
  45. data/ext/fastfilereader/rubymain.cpp +126 -0
  46. data/ext/kb.cpp +79 -0
  47. data/ext/page.cpp +107 -0
  48. data/ext/page.h +51 -0
  49. data/ext/pipe.cpp +354 -0
  50. data/ext/project.h +174 -0
  51. data/ext/rubymain.cpp +1643 -0
  52. data/ext/ssl.cpp +701 -0
  53. data/ext/ssl.h +103 -0
  54. data/ext/wait_for_single_fd.h +36 -0
  55. data/java/.classpath +8 -0
  56. data/java/.project +17 -0
  57. data/java/src/com/rubyeventmachine/EmReactor.java +625 -0
  58. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  59. data/java/src/com/rubyeventmachine/EmReactorInterface.java +70 -0
  60. data/java/src/com/rubyeventmachine/EventableChannel.java +72 -0
  61. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +201 -0
  62. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +415 -0
  63. data/java/src/com/rubyeventmachine/NullEmReactor.java +157 -0
  64. data/java/src/com/rubyeventmachine/NullEventableChannel.java +81 -0
  65. data/lib/em/buftok.rb +59 -0
  66. data/lib/em/callback.rb +58 -0
  67. data/lib/em/channel.rb +69 -0
  68. data/lib/em/completion.rb +307 -0
  69. data/lib/em/connection.rb +802 -0
  70. data/lib/em/deferrable/pool.rb +2 -0
  71. data/lib/em/deferrable.rb +210 -0
  72. data/lib/em/file_watch.rb +73 -0
  73. data/lib/em/future.rb +61 -0
  74. data/lib/em/io_streamer.rb +68 -0
  75. data/lib/em/iterator.rb +252 -0
  76. data/lib/em/messages.rb +66 -0
  77. data/lib/em/pool.rb +151 -0
  78. data/lib/em/process_watch.rb +45 -0
  79. data/lib/em/processes.rb +123 -0
  80. data/lib/em/protocols/header_and_content.rb +138 -0
  81. data/lib/em/protocols/httpclient.rb +303 -0
  82. data/lib/em/protocols/httpclient2.rb +602 -0
  83. data/lib/em/protocols/line_and_text.rb +125 -0
  84. data/lib/em/protocols/line_protocol.rb +33 -0
  85. data/lib/em/protocols/linetext2.rb +179 -0
  86. data/lib/em/protocols/memcache.rb +331 -0
  87. data/lib/em/protocols/object_protocol.rb +46 -0
  88. data/lib/em/protocols/postgres3.rb +246 -0
  89. data/lib/em/protocols/saslauth.rb +175 -0
  90. data/lib/em/protocols/smtpclient.rb +394 -0
  91. data/lib/em/protocols/smtpserver.rb +666 -0
  92. data/lib/em/protocols/socks4.rb +66 -0
  93. data/lib/em/protocols/stomp.rb +205 -0
  94. data/lib/em/protocols/tcptest.rb +54 -0
  95. data/lib/em/protocols.rb +37 -0
  96. data/lib/em/pure_ruby.rb +1300 -0
  97. data/lib/em/queue.rb +80 -0
  98. data/lib/em/resolver.rb +232 -0
  99. data/lib/em/spawnable.rb +84 -0
  100. data/lib/em/streamer.rb +118 -0
  101. data/lib/em/threaded_resource.rb +90 -0
  102. data/lib/em/tick_loop.rb +85 -0
  103. data/lib/em/timers.rb +61 -0
  104. data/lib/em/version.rb +3 -0
  105. data/lib/eventmachine.rb +1602 -0
  106. data/lib/jeventmachine.rb +319 -0
  107. data/rakelib/package.rake +120 -0
  108. data/rakelib/test.rake +6 -0
  109. data/rakelib/test_pure.rake +11 -0
  110. data/tests/client.crt +31 -0
  111. data/tests/client.key +51 -0
  112. data/tests/dhparam.pem +13 -0
  113. data/tests/em_ssl_handlers.rb +165 -0
  114. data/tests/em_test_helper.rb +198 -0
  115. data/tests/encoded_client.key +54 -0
  116. data/tests/jruby/test_jeventmachine.rb +38 -0
  117. data/tests/test_attach.rb +199 -0
  118. data/tests/test_basic.rb +321 -0
  119. data/tests/test_channel.rb +75 -0
  120. data/tests/test_completion.rb +178 -0
  121. data/tests/test_connection_count.rb +83 -0
  122. data/tests/test_connection_write.rb +35 -0
  123. data/tests/test_defer.rb +35 -0
  124. data/tests/test_deferrable.rb +35 -0
  125. data/tests/test_epoll.rb +141 -0
  126. data/tests/test_error_handler.rb +38 -0
  127. data/tests/test_exc.rb +37 -0
  128. data/tests/test_file_watch.rb +86 -0
  129. data/tests/test_fork.rb +75 -0
  130. data/tests/test_futures.rb +170 -0
  131. data/tests/test_handler_check.rb +35 -0
  132. data/tests/test_hc.rb +155 -0
  133. data/tests/test_httpclient.rb +238 -0
  134. data/tests/test_httpclient2.rb +132 -0
  135. data/tests/test_idle_connection.rb +31 -0
  136. data/tests/test_inactivity_timeout.rb +102 -0
  137. data/tests/test_io_streamer.rb +48 -0
  138. data/tests/test_ipv4.rb +96 -0
  139. data/tests/test_ipv6.rb +107 -0
  140. data/tests/test_iterator.rb +122 -0
  141. data/tests/test_kb.rb +28 -0
  142. data/tests/test_keepalive.rb +113 -0
  143. data/tests/test_line_protocol.rb +33 -0
  144. data/tests/test_ltp.rb +155 -0
  145. data/tests/test_ltp2.rb +332 -0
  146. data/tests/test_many_fds.rb +21 -0
  147. data/tests/test_next_tick.rb +104 -0
  148. data/tests/test_object_protocol.rb +36 -0
  149. data/tests/test_pause.rb +109 -0
  150. data/tests/test_pending_connect_timeout.rb +52 -0
  151. data/tests/test_pool.rb +196 -0
  152. data/tests/test_process_watch.rb +50 -0
  153. data/tests/test_processes.rb +147 -0
  154. data/tests/test_proxy_connection.rb +180 -0
  155. data/tests/test_pure.rb +156 -0
  156. data/tests/test_queue.rb +64 -0
  157. data/tests/test_resolver.rb +129 -0
  158. data/tests/test_running.rb +14 -0
  159. data/tests/test_sasl.rb +46 -0
  160. data/tests/test_send_file.rb +217 -0
  161. data/tests/test_servers.rb +32 -0
  162. data/tests/test_shutdown_hooks.rb +23 -0
  163. data/tests/test_smtpclient.rb +75 -0
  164. data/tests/test_smtpserver.rb +90 -0
  165. data/tests/test_sock_opt.rb +53 -0
  166. data/tests/test_spawn.rb +290 -0
  167. data/tests/test_ssl_args.rb +70 -0
  168. data/tests/test_ssl_dhparam.rb +57 -0
  169. data/tests/test_ssl_ecdh_curve.rb +57 -0
  170. data/tests/test_ssl_extensions.rb +24 -0
  171. data/tests/test_ssl_inline_cert.rb +222 -0
  172. data/tests/test_ssl_methods.rb +31 -0
  173. data/tests/test_ssl_protocols.rb +190 -0
  174. data/tests/test_ssl_verify.rb +108 -0
  175. data/tests/test_stomp.rb +38 -0
  176. data/tests/test_system.rb +46 -0
  177. data/tests/test_threaded_resource.rb +68 -0
  178. data/tests/test_tick_loop.rb +58 -0
  179. data/tests/test_timers.rb +150 -0
  180. data/tests/test_ud.rb +8 -0
  181. data/tests/test_unbind_reason.rb +40 -0
  182. metadata +389 -0
@@ -0,0 +1,802 @@
1
+ module EventMachine
2
+ class FileNotFoundException < Exception ; end
3
+ class BadParams < Exception ; end
4
+ class BadCertParams < BadParams ; end
5
+ class BadPrivateKeyParams < BadParams ;end
6
+
7
+ # EventMachine::Connection is a class that is instantiated
8
+ # by EventMachine's processing loop whenever a new connection
9
+ # is created. (New connections can be either initiated locally
10
+ # to a remote server or accepted locally from a remote client.)
11
+ # When a Connection object is instantiated, it <i>mixes in</i>
12
+ # the functionality contained in the user-defined module
13
+ # specified in calls to {EventMachine.connect} or {EventMachine.start_server}.
14
+ # User-defined handler modules may redefine any or all of the standard
15
+ # methods defined here, as well as add arbitrary additional code
16
+ # that will also be mixed in.
17
+ #
18
+ # EventMachine manages one object inherited from EventMachine::Connection
19
+ # (and containing the mixed-in user code) for every network connection
20
+ # that is active at any given time.
21
+ # The event loop will automatically call methods on EventMachine::Connection
22
+ # objects whenever specific events occur on the corresponding connections,
23
+ # as described below.
24
+ #
25
+ # This class is never instantiated by user code, and does not publish an
26
+ # initialize method. The instance methods of EventMachine::Connection
27
+ # which may be called by the event loop are:
28
+ #
29
+ # * {#post_init}
30
+ # * {#connection_completed}
31
+ # * {#receive_data}
32
+ # * {#unbind}
33
+ # * {#ssl_verify_peer} (if TLS is used)
34
+ # * {#ssl_handshake_completed}
35
+ #
36
+ # All of the other instance methods defined here are called only by user code.
37
+ #
38
+ # @see file:docs/GettingStarted.md EventMachine tutorial
39
+ class Connection
40
+ # @private
41
+ attr_accessor :signature
42
+
43
+ # @private
44
+ alias original_method method
45
+
46
+ # Override .new so subclasses don't have to call super and can ignore
47
+ # connection-specific arguments
48
+ #
49
+ # @private
50
+ def self.new(sig, *args)
51
+ allocate.instance_eval do
52
+ # Store signature
53
+ @signature = sig
54
+ # associate_callback_target sig
55
+
56
+ # Call a superclass's #initialize if it has one
57
+ initialize(*args)
58
+
59
+ # post initialize callback
60
+ post_init
61
+
62
+ self
63
+ end
64
+ end
65
+
66
+ # Stubbed initialize so legacy superclasses can safely call super
67
+ #
68
+ # @private
69
+ def initialize(*args)
70
+ end
71
+
72
+ # Called by the event loop immediately after the network connection has been established,
73
+ # and before resumption of the network loop.
74
+ # This method is generally not called by user code, but is called automatically
75
+ # by the event loop. The base-class implementation is a no-op.
76
+ # This is a very good place to initialize instance variables that will
77
+ # be used throughout the lifetime of the network connection.
78
+ #
79
+ # @see #connection_completed
80
+ # @see #unbind
81
+ # @see #send_data
82
+ # @see #receive_data
83
+ def post_init
84
+ end
85
+
86
+ # Called by the event loop whenever data has been received by the network connection.
87
+ # It is never called by user code. {#receive_data} is called with a single parameter, a String containing
88
+ # the network protocol data, which may of course be binary. You will
89
+ # generally redefine this method to perform your own processing of the incoming data.
90
+ #
91
+ # Here's a key point which is essential to understanding the event-driven
92
+ # programming model: <i>EventMachine knows absolutely nothing about the protocol
93
+ # which your code implements.</i> You must not make any assumptions about
94
+ # the size of the incoming data packets, or about their alignment on any
95
+ # particular intra-message or PDU boundaries (such as line breaks).
96
+ # receive_data can and will send you arbitrary chunks of data, with the
97
+ # only guarantee being that the data is presented to your code in the order
98
+ # it was collected from the network. Don't even assume that the chunks of
99
+ # data will correspond to network packets, as EventMachine can and will coalesce
100
+ # several incoming packets into one, to improve performance. The implication for your
101
+ # code is that you generally will need to implement some kind of a state machine
102
+ # in your redefined implementation of receive_data. For a better understanding
103
+ # of this, read through the examples of specific protocol handlers in EventMachine::Protocols
104
+ #
105
+ # @param [String] data Opaque incoming data.
106
+ # @note Depending on the protocol, buffer sizes and OS networking stack configuration, incoming data may or may not be "a complete message".
107
+ # It is up to this handler to detect content boundaries to determine whether all the content (for example, full HTTP request)
108
+ # has been received and can be processed.
109
+ #
110
+ # @see #post_init
111
+ # @see #connection_completed
112
+ # @see #unbind
113
+ # @see #send_data
114
+ # @see file:docs/GettingStarted.md EventMachine tutorial
115
+ def receive_data data
116
+ end
117
+
118
+ # Called by EventMachine when the SSL/TLS handshake has
119
+ # been completed, as a result of calling #start_tls to initiate SSL/TLS on the connection.
120
+ #
121
+ # This callback exists because {#post_init} and {#connection_completed} are **not** reliable
122
+ # for indicating when an SSL/TLS connection is ready to have its certificate queried for.
123
+ #
124
+ # @see #get_peer_cert
125
+ def ssl_handshake_completed
126
+ end
127
+
128
+ # Called by EventMachine when :verify_peer => true has been passed to {#start_tls}.
129
+ # It will be called with each certificate in the certificate chain provided by the remote peer.
130
+ #
131
+ # The cert will be passed as a String in PEM format, the same as in {#get_peer_cert}. It is up to user defined
132
+ # code to perform a check on the certificates. The return value from this callback is used to accept or deny the peer.
133
+ # A return value that is not nil or false triggers acceptance. If the peer is not accepted, the connection
134
+ # will be subsequently closed.
135
+ #
136
+ # @example This server always accepts all peers
137
+ #
138
+ # module AcceptServer
139
+ # def post_init
140
+ # start_tls(:verify_peer => true)
141
+ # end
142
+ #
143
+ # def ssl_verify_peer(cert)
144
+ # true
145
+ # end
146
+ #
147
+ # def ssl_handshake_completed
148
+ # $server_handshake_completed = true
149
+ # end
150
+ # end
151
+ #
152
+ #
153
+ # @example This server never accepts any peers
154
+ #
155
+ # module DenyServer
156
+ # def post_init
157
+ # start_tls(:verify_peer => true)
158
+ # end
159
+ #
160
+ # def ssl_verify_peer(cert)
161
+ # # Do not accept the peer. This should now cause the connection to shut down
162
+ # # without the SSL handshake being completed.
163
+ # false
164
+ # end
165
+ #
166
+ # def ssl_handshake_completed
167
+ # $server_handshake_completed = true
168
+ # end
169
+ # end
170
+ #
171
+ # @see #start_tls
172
+ def ssl_verify_peer(cert)
173
+ end
174
+
175
+ # called by the framework whenever a connection (either a server or client connection) is closed.
176
+ # The close can occur because your code intentionally closes it (using {#close_connection} and {#close_connection_after_writing}),
177
+ # because the remote peer closed the connection, or because of a network error.
178
+ # You may not assume that the network connection is still open and able to send or
179
+ # receive data when the callback to unbind is made. This is intended only to give
180
+ # you a chance to clean up associations your code may have made to the connection
181
+ # object while it was open.
182
+ #
183
+ # If you want to detect which peer has closed the connection, you can override {#close_connection} in your protocol handler
184
+ # and set an @ivar.
185
+ #
186
+ # @example Overriding Connection#close_connection to distinguish connections closed on our side
187
+ #
188
+ # class MyProtocolHandler < EventMachine::Connection
189
+ #
190
+ # # ...
191
+ #
192
+ # def close_connection(*args)
193
+ # @intentionally_closed_connection = true
194
+ # super(*args)
195
+ # end
196
+ #
197
+ # def unbind
198
+ # if @intentionally_closed_connection
199
+ # # ...
200
+ # end
201
+ # end
202
+ #
203
+ # # ...
204
+ #
205
+ # end
206
+ #
207
+ # @see #post_init
208
+ # @see #connection_completed
209
+ # @see file:docs/GettingStarted.md EventMachine tutorial
210
+ def unbind
211
+ end
212
+
213
+ # Called by the reactor after attempting to relay incoming data to a descriptor (set as a proxy target descriptor with
214
+ # {EventMachine.enable_proxy}) that has already been closed.
215
+ #
216
+ # @see EventMachine.enable_proxy
217
+ def proxy_target_unbound
218
+ end
219
+
220
+ # called when the reactor finished proxying all
221
+ # of the requested bytes.
222
+ def proxy_completed
223
+ end
224
+
225
+ # EventMachine::Connection#proxy_incoming_to is called only by user code. It sets up
226
+ # a low-level proxy relay for all data inbound for this connection, to the connection given
227
+ # as the argument. This is essentially just a helper method for enable_proxy.
228
+ #
229
+ # @see EventMachine.enable_proxy
230
+ def proxy_incoming_to(conn,bufsize=0)
231
+ EventMachine::enable_proxy(self, conn, bufsize)
232
+ end
233
+
234
+ # A helper method for {EventMachine.disable_proxy}
235
+ def stop_proxying
236
+ EventMachine::disable_proxy(self)
237
+ end
238
+
239
+ # The number of bytes proxied to another connection. Reset to zero when
240
+ # EventMachine::Connection#proxy_incoming_to is called, and incremented whenever data is proxied.
241
+ def get_proxied_bytes
242
+ EventMachine::get_proxied_bytes(@signature)
243
+ end
244
+
245
+ # EventMachine::Connection#close_connection is called only by user code, and never
246
+ # by the event loop. You may call this method against a connection object in any
247
+ # callback handler, whether or not the callback was made against the connection
248
+ # you want to close. close_connection <i>schedules</i> the connection to be closed
249
+ # at the next available opportunity within the event loop. You may not assume that
250
+ # the connection is closed when close_connection returns. In particular, the framework
251
+ # will callback the unbind method for the particular connection at a point shortly
252
+ # after you call close_connection. You may assume that the unbind callback will
253
+ # take place sometime after your call to close_connection completes. In other words,
254
+ # the unbind callback will not re-enter your code "inside" of your call to close_connection.
255
+ # However, it's not guaranteed that a future version of EventMachine will not change
256
+ # this behavior.
257
+ #
258
+ # {#close_connection} will *silently discard* any outbound data which you have
259
+ # sent to the connection using {EventMachine::Connection#send_data} but which has not
260
+ # yet been sent across the network. If you want to avoid this behavior, use
261
+ # {EventMachine::Connection#close_connection_after_writing}.
262
+ #
263
+ def close_connection after_writing = false
264
+ EventMachine::close_connection @signature, after_writing
265
+ end
266
+
267
+ # Removes given connection from the event loop.
268
+ # The connection's socket remains open and its file descriptor number is returned.
269
+ def detach
270
+ EventMachine::detach_fd @signature
271
+ end
272
+
273
+ def get_sock_opt level, option
274
+ EventMachine::get_sock_opt @signature, level, option
275
+ end
276
+
277
+ def set_sock_opt level, optname, optval
278
+ EventMachine::set_sock_opt @signature, level, optname, optval
279
+ end
280
+
281
+ # A variant of {#close_connection}.
282
+ # All of the descriptive comments given for close_connection also apply to
283
+ # close_connection_after_writing, *with one exception*: if the connection has
284
+ # outbound data sent using send_dat but which has not yet been sent across the network,
285
+ # close_connection_after_writing will schedule the connection to be closed *after*
286
+ # all of the outbound data has been safely written to the remote peer.
287
+ #
288
+ # Depending on the amount of outgoing data and the speed of the network,
289
+ # considerable time may elapse between your call to close_connection_after_writing
290
+ # and the actual closing of the socket (at which time the unbind callback will be called
291
+ # by the event loop). During this time, you *may not* call send_data to transmit
292
+ # additional data (that is, the connection is closed for further writes). In very
293
+ # rare cases, you may experience a receive_data callback after your call to {#close_connection_after_writing},
294
+ # depending on whether incoming data was in the process of being received on the connection
295
+ # at the moment when you called {#close_connection_after_writing}. Your protocol handler must
296
+ # be prepared to properly deal with such data (probably by ignoring it).
297
+ #
298
+ # @see #close_connection
299
+ # @see #send_data
300
+ def close_connection_after_writing
301
+ close_connection true
302
+ end
303
+
304
+ # Call this method to send data to the remote end of the network connection. It takes a single String argument,
305
+ # which may contain binary data. Data is buffered to be sent at the end of this event loop tick (cycle).
306
+ #
307
+ # When used in a method that is event handler (for example, {#post_init} or {#connection_completed}, it will send
308
+ # data to the other end of the connection that generated the event.
309
+ # You can also call {#send_data} to write to other connections. For more information see The Chat Server Example in the
310
+ # {file:docs/GettingStarted.md EventMachine tutorial}.
311
+ #
312
+ # If you want to send some data and then immediately close the connection, make sure to use {#close_connection_after_writing}
313
+ # instead of {#close_connection}.
314
+ #
315
+ #
316
+ # @param [String] data Data to send asynchronously
317
+ #
318
+ # @see file:docs/GettingStarted.md EventMachine tutorial
319
+ # @see Connection#receive_data
320
+ # @see Connection#post_init
321
+ # @see Connection#unbind
322
+ def send_data data
323
+ data = data.to_s
324
+ size = data.bytesize if data.respond_to?(:bytesize)
325
+ size ||= data.size
326
+ EventMachine::send_data @signature, data, size
327
+ end
328
+
329
+ # Returns true if the connection is in an error state, false otherwise.
330
+ #
331
+ # In general, you can detect the occurrence of communication errors or unexpected
332
+ # disconnection by the remote peer by handing the {#unbind} method. In some cases, however,
333
+ # it's useful to check the status of the connection using {#error?} before attempting to send data.
334
+ # This function is synchronous but it will return immediately without blocking.
335
+ #
336
+ # @return [Boolean] true if the connection is in an error state, false otherwise
337
+ def error?
338
+ errno = EventMachine::report_connection_error_status(@signature)
339
+ case errno
340
+ when 0
341
+ false
342
+ when -1
343
+ true
344
+ else
345
+ EventMachine::ERRNOS[errno]
346
+ end
347
+ end
348
+
349
+ # Called by the event loop when a remote TCP connection attempt completes successfully.
350
+ # You can expect to get this notification after calls to {EventMachine.connect}. Remember that EventMachine makes remote connections
351
+ # asynchronously, just as with any other kind of network event. This method
352
+ # is intended primarily to assist with network diagnostics. For normal protocol
353
+ # handling, use #post_init to perform initial work on a new connection (such as sending initial set of data).
354
+ # {Connection#post_init} will always be called. This method will only be called in case of a successful completion.
355
+ # A connection attempt which fails will result a call to {Connection#unbind} after the failure.
356
+ #
357
+ # @see Connection#post_init
358
+ # @see Connection#unbind
359
+ # @see file:docs/GettingStarted.md EventMachine tutorial
360
+ def connection_completed
361
+ end
362
+
363
+ # Call {#start_tls} at any point to initiate TLS encryption on connected streams.
364
+ # The method is smart enough to know whether it should perform a server-side
365
+ # or a client-side handshake. An appropriate place to call {#start_tls} is in
366
+ # your redefined {#post_init} method, or in the {#connection_completed} handler for
367
+ # an outbound connection.
368
+ #
369
+ #
370
+ # @option args [String] :cert_chain_file (nil) local path of a readable file that contants a chain of X509 certificates in
371
+ # the [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail),
372
+ # with the most-resolved certificate at the top of the file, successive intermediate
373
+ # certs in the middle, and the root (or CA) cert at the bottom. If both
374
+ # :cert_chain_file and :cert are used, BadCertParams will be raised.
375
+ #
376
+ # @option args [String] :cert (nil) a string with the client certificate to use, complete with header and footer. If a cert chain is required, you will have to use the :cert_chain_file option. If both :cert_chain_file and :cert are used, BadCertParams will be raised.
377
+ #
378
+ # @option args [String] :private_key_file (nil) local path of a readable file that must contain a private key in the [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail). If both :private_key_file and :private_key are used, BadPrivateKeyParams will be raised. If the Private Key does not match the certificate, InvalidPrivateKey will be raised.
379
+ #
380
+ # @option args [String] :private_key (nil) a string, complete with header and footer, that must contain a private key in the [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail). If both :private_key_file and :private_key are used, BadPrivateKeyParams will be raised. If the Private Key does not match the certificate, InvalidPrivateKey will be raised.
381
+ #
382
+ # @option args [String] :private_key_pass (nil) a string to use as password to decode :private_key or :private_key_file
383
+ #
384
+ # @option args [Boolean] :verify_peer (false) indicates whether a server should request a certificate from a peer, to be verified by user code.
385
+ # If true, the {#ssl_verify_peer} callback on the {EventMachine::Connection} object is called with each certificate
386
+ # in the certificate chain provided by the peer. See documentation on {#ssl_verify_peer} for how to use this.
387
+ #
388
+ # @option args [Boolean] :fail_if_no_peer_cert (false) Used in conjunction with verify_peer. If set the SSL handshake will be terminated if the peer does not provide a certificate.
389
+ #
390
+ #
391
+ # @option args [String] :cipher_list ("ALL:!ADH:!LOW:!EXP:!DES-CBC3-SHA:@STRENGTH") indicates the available SSL cipher values. Default value is "ALL:!ADH:!LOW:!EXP:!DES-CBC3-SHA:@STRENGTH". Check the format of the OpenSSL cipher string at http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT.
392
+ #
393
+ # @option args [String] :ecdh_curve (nil) The curve for ECDHE ciphers. See available ciphers with 'openssl ecparam -list_curves'
394
+ #
395
+ # @option args [String] :dhparam (nil) The local path of a file containing DH parameters for EDH ciphers in [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail) See: 'openssl dhparam'
396
+ #
397
+ # @option args [Array] :ssl_version (TLSv1 TLSv1_1 TLSv1_2) indicates the allowed SSL/TLS versions. Possible values are: {SSLv2}, {SSLv3}, {TLSv1}, {TLSv1_1}, {TLSv1_2}.
398
+ #
399
+ # @example Using TLS with EventMachine
400
+ #
401
+ # require 'rubygems'
402
+ # require 'eventmachine'
403
+ #
404
+ # module Handler
405
+ # def post_init
406
+ # start_tls(:private_key_file => '/tmp/server.key', :cert_chain_file => '/tmp/server.crt', :verify_peer => false)
407
+ # end
408
+ # end
409
+ #
410
+ # EventMachine.run do
411
+ # EventMachine.start_server("127.0.0.1", 9999, Handler)
412
+ # end
413
+ #
414
+ # @param [Hash] args
415
+ #
416
+ # @todo support passing an encryption parameter, which can be string or Proc, to get a passphrase
417
+ # for encrypted private keys.
418
+ # @todo support passing key material via raw strings or Procs that return strings instead of
419
+ # just filenames.
420
+ #
421
+ # @see #ssl_verify_peer
422
+ def start_tls args={}
423
+ priv_key_path = args[:private_key_file]
424
+ priv_key = args[:private_key]
425
+ priv_key_pass = args[:private_key_pass]
426
+ cert_chain_path = args[:cert_chain_file]
427
+ cert = args[:cert]
428
+ verify_peer = args[:verify_peer]
429
+ sni_hostname = args[:sni_hostname]
430
+ cipher_list = args[:cipher_list]
431
+ ssl_version = args[:ssl_version]
432
+ ecdh_curve = args[:ecdh_curve]
433
+ dhparam = args[:dhparam]
434
+ fail_if_no_peer_cert = args[:fail_if_no_peer_cert]
435
+
436
+ [priv_key_path, cert_chain_path].each do |file|
437
+ next if file.nil? or file.empty?
438
+ raise FileNotFoundException,
439
+ "Could not find #{file} for start_tls" unless File.exist? file
440
+ end
441
+
442
+ if !priv_key_path.nil? && !priv_key_path.empty? && !priv_key.nil? && !priv_key.empty?
443
+ raise BadPrivateKeyParams, "Specifying both private_key and private_key_file not allowed"
444
+ end
445
+
446
+ if !cert_chain_path.nil? && !cert_chain_path.empty? && !cert.nil? && !cert.empty?
447
+ raise BadCertParams, "Specifying both cert and cert_chain_file not allowed"
448
+ end
449
+
450
+ if (!priv_key_path.nil? && !priv_key_path.empty?) || (!priv_key.nil? && !priv_key.empty?)
451
+ if (cert_chain_path.nil? || cert_chain_path.empty?) && (cert.nil? || cert.empty?)
452
+ raise BadParams, "You have specified a private key to use, but not the related cert"
453
+ end
454
+ end
455
+
456
+ protocols_bitmask = 0
457
+ if ssl_version.nil?
458
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1
459
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_1
460
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_2
461
+ if EventMachine.const_defined? :EM_PROTO_TLSv1_3
462
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_3
463
+ end
464
+ else
465
+ [ssl_version].flatten.each do |p|
466
+ case p.to_s.downcase
467
+ when 'sslv2'
468
+ protocols_bitmask |= EventMachine::EM_PROTO_SSLv2
469
+ when 'sslv3'
470
+ protocols_bitmask |= EventMachine::EM_PROTO_SSLv3
471
+ when 'tlsv1'
472
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1
473
+ when 'tlsv1_1'
474
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_1
475
+ when 'tlsv1_2'
476
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_2
477
+ when 'tlsv1_3'
478
+ protocols_bitmask |= EventMachine::EM_PROTO_TLSv1_3
479
+ else
480
+ raise("Unrecognized SSL/TLS Protocol: #{p}")
481
+ end
482
+ end
483
+ end
484
+
485
+ EventMachine::set_tls_parms(@signature, priv_key_path || '', priv_key || '', priv_key_pass || '', cert_chain_path || '', cert || '', verify_peer, fail_if_no_peer_cert, sni_hostname || '', cipher_list || '', ecdh_curve || '', dhparam || '', protocols_bitmask)
486
+ EventMachine::start_tls @signature
487
+ end
488
+
489
+ # If [TLS](http://en.wikipedia.org/wiki/Transport_Layer_Security) is active on the connection, returns the remote [X509 certificate](http://en.wikipedia.org/wiki/X.509)
490
+ # as a string, in the popular [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail). This can then be used for arbitrary validation
491
+ # of a peer's certificate in your code.
492
+ #
493
+ # This should be called in/after the {#ssl_handshake_completed} callback, which indicates
494
+ # that SSL/TLS is active. Using this callback is important, because the certificate may not
495
+ # be available until the time it is executed. Using #post_init or #connection_completed is
496
+ # not adequate, because the SSL handshake may still be taking place.
497
+ #
498
+ # This method will return `nil` if:
499
+ #
500
+ # * EventMachine is not built with [OpenSSL](http://www.openssl.org) support
501
+ # * [TLS](http://en.wikipedia.org/wiki/Transport_Layer_Security) is not active on the connection
502
+ # * TLS handshake is not yet complete
503
+ # * Remote peer for any other reason has not presented a certificate
504
+ #
505
+ #
506
+ # @example Getting peer TLS certificate information in EventMachine
507
+ #
508
+ # module Handler
509
+ # def post_init
510
+ # puts "Starting TLS"
511
+ # start_tls
512
+ # end
513
+ #
514
+ # def ssl_handshake_completed
515
+ # puts get_peer_cert
516
+ # close_connection
517
+ # end
518
+ #
519
+ # def unbind
520
+ # EventMachine::stop_event_loop
521
+ # end
522
+ # end
523
+ #
524
+ # EventMachine.run do
525
+ # EventMachine.connect "mail.google.com", 443, Handler
526
+ # end
527
+ #
528
+ # # Will output:
529
+ # # -----BEGIN CERTIFICATE-----
530
+ # # MIIDIjCCAougAwIBAgIQbldpChBPqv+BdPg4iwgN8TANBgkqhkiG9w0BAQUFADBM
531
+ # # MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
532
+ # # THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0wODA1MDIxNjMyNTRaFw0w
533
+ # # OTA1MDIxNjMyNTRaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
534
+ # # MRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUgSW5jMRgw
535
+ # # FgYDVQQDEw9tYWlsLmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
536
+ # # AoGBALlkxdh2QXegdElukCSOV2+8PKiONIS+8Tu9K7MQsYpqtLNC860zwOPQ2NLI
537
+ # # 3Zp4jwuXVTrtzGuiqf5Jioh35Ig3CqDXtLyZoypjZUQcq4mlLzHlhIQ4EhSjDmA7
538
+ # # Ffw9y3ckSOQgdBQWNLbquHh9AbEUjmhkrYxIqKXeCnRKhv6nAgMBAAGjgecwgeQw
539
+ # # KAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUFBwMCBglghkgBhvhCBAEwNgYDVR0f
540
+ # # BC8wLTAroCmgJ4YlaHR0cDovL2NybC50aGF3dGUuY29tL1RoYXd0ZVNHQ0NBLmNy
541
+ # # bDByBggrBgEFBQcBAQRmMGQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnRoYXd0
542
+ # # ZS5jb20wPgYIKwYBBQUHMAKGMmh0dHA6Ly93d3cudGhhd3RlLmNvbS9yZXBvc2l0
543
+ # # b3J5L1RoYXd0ZV9TR0NfQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQEF
544
+ # # BQADgYEAsRwpLg1dgCR1gYDK185MFGukXMeQFUvhGqF8eT/CjpdvezyKVuz84gSu
545
+ # # 6ccMXgcPQZGQN/F4Xug+Q01eccJjRSVfdvR5qwpqCj+6BFl5oiKDBsveSkrmL5dz
546
+ # # s2bn7TdTSYKcLeBkjXxDLHGBqLJ6TNCJ3c4/cbbG5JhGvoema94=
547
+ # # -----END CERTIFICATE-----
548
+ #
549
+ # You can do whatever you want with the certificate String, such as load it
550
+ # as a certificate object using the OpenSSL library, and check its fields.
551
+ #
552
+ # @return [String] the remote [X509 certificate](http://en.wikipedia.org/wiki/X.509), in the popular [PEM format](http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail),
553
+ # if TLS is active on the connection
554
+ #
555
+ # @see Connection#start_tls
556
+ # @see Connection#ssl_handshake_completed
557
+ def get_peer_cert
558
+ EventMachine::get_peer_cert @signature
559
+ end
560
+
561
+ def get_cipher_bits
562
+ EventMachine::get_cipher_bits @signature
563
+ end
564
+
565
+ def get_cipher_name
566
+ EventMachine::get_cipher_name @signature
567
+ end
568
+
569
+ def get_cipher_protocol
570
+ EventMachine::get_cipher_protocol @signature
571
+ end
572
+
573
+ def get_sni_hostname
574
+ EventMachine::get_sni_hostname @signature
575
+ end
576
+
577
+ # Sends UDP messages.
578
+ #
579
+ # This method may be called from any Connection object that refers
580
+ # to an open datagram socket (see EventMachine#open_datagram_socket).
581
+ # The method sends a UDP (datagram) packet containing the data you specify,
582
+ # to a remote peer specified by the IP address and port that you give
583
+ # as parameters to the method.
584
+ # Observe that you may send a zero-length packet (empty string).
585
+ # However, you may not send an arbitrarily-large data packet because
586
+ # your operating system will enforce a platform-specific limit on
587
+ # the size of the outbound packet. (Your kernel
588
+ # will respond in a platform-specific way if you send an overlarge
589
+ # packet: some will send a truncated packet, some will complain, and
590
+ # some will silently drop your request).
591
+ # On LANs, it's usually OK to send datagrams up to about 4000 bytes in length,
592
+ # but to be really safe, send messages smaller than the Ethernet-packet
593
+ # size (typically about 1400 bytes). Some very restrictive WANs
594
+ # will either drop or truncate packets larger than about 500 bytes.
595
+ #
596
+ # @param [String] data Data to send asynchronously
597
+ # @param [String] recipient_address IP address of the recipient
598
+ # @param [String] recipient_port Port of the recipient
599
+ def send_datagram data, recipient_address, recipient_port
600
+ data = data.to_s
601
+ size = data.bytesize if data.respond_to?(:bytesize)
602
+ size ||= data.size
603
+ EventMachine::send_datagram @signature, data, size, recipient_address, Integer(recipient_port)
604
+ end
605
+
606
+
607
+ # This method is used with stream-connections to obtain the identity
608
+ # of the remotely-connected peer. If a peername is available, this method
609
+ # returns a sockaddr structure. The method returns nil if no peername is available.
610
+ # You can use Socket.unpack_sockaddr_in and its variants to obtain the
611
+ # values contained in the peername structure returned from #get_peername.
612
+ #
613
+ # @example How to get peer IP address and port with EventMachine
614
+ #
615
+ # require 'socket'
616
+ #
617
+ # module Handler
618
+ # def receive_data data
619
+ # port, ip = Socket.unpack_sockaddr_in(get_peername)
620
+ # puts "got #{data.inspect} from #{ip}:#{port}"
621
+ # end
622
+ # end
623
+ def get_peername
624
+ EventMachine::get_peername @signature
625
+ end
626
+
627
+ # Used with stream-connections to obtain the identity
628
+ # of the local side of the connection. If a local name is available, this method
629
+ # returns a sockaddr structure. The method returns nil if no local name is available.
630
+ # You can use {Socket.unpack_sockaddr_in} and its variants to obtain the
631
+ # values contained in the local-name structure returned from this method.
632
+ #
633
+ # @example
634
+ #
635
+ # require 'socket'
636
+ #
637
+ # module Handler
638
+ # def receive_data data
639
+ # port, ip = Socket.unpack_sockaddr_in(get_sockname)
640
+ # puts "got #{data.inspect}"
641
+ # end
642
+ # end
643
+ def get_sockname
644
+ EventMachine::get_sockname @signature
645
+ end
646
+
647
+ # Returns the PID (kernel process identifier) of a subprocess
648
+ # associated with this Connection object. For use with {EventMachine.popen}
649
+ # and similar methods. Returns nil when there is no meaningful subprocess.
650
+ #
651
+ # @return [Integer]
652
+ def get_pid
653
+ EventMachine::get_subprocess_pid @signature
654
+ end
655
+
656
+ # Returns a subprocess exit status. Only useful for {EventMachine.popen}. Call it in your
657
+ # {#unbind} handler.
658
+ #
659
+ # @return [Integer]
660
+ def get_status
661
+ EventMachine::get_subprocess_status @signature
662
+ end
663
+
664
+ # The number of seconds since the last send/receive activity on this connection.
665
+ def get_idle_time
666
+ EventMachine::get_idle_time @signature
667
+ end
668
+
669
+ # comm_inactivity_timeout returns the current value (float in seconds) of the inactivity-timeout
670
+ # property of network-connection and datagram-socket objects. A nonzero value
671
+ # indicates that the connection or socket will automatically be closed if no read or write
672
+ # activity takes place for at least that number of seconds.
673
+ # A zero value (the default) specifies that no automatic timeout will take place.
674
+ def comm_inactivity_timeout
675
+ EventMachine::get_comm_inactivity_timeout @signature
676
+ end
677
+
678
+ # Allows you to set the inactivity-timeout property for
679
+ # a network connection or datagram socket. Specify a non-negative float value in seconds.
680
+ # If the value is greater than zero, the connection or socket will automatically be closed
681
+ # if no read or write activity takes place for at least that number of seconds.
682
+ # Specify a value of zero to indicate that no automatic timeout should take place.
683
+ # Zero is the default value.
684
+ def comm_inactivity_timeout= value
685
+ EventMachine::set_comm_inactivity_timeout @signature, value.to_f
686
+ end
687
+ alias set_comm_inactivity_timeout comm_inactivity_timeout=
688
+
689
+ # The duration after which a TCP connection in the connecting state will fail.
690
+ # It is important to distinguish this value from {EventMachine::Connection#comm_inactivity_timeout},
691
+ # which looks at how long since data was passed on an already established connection.
692
+ # The value is a float in seconds.
693
+ #
694
+ # @return [Float] The duration after which a TCP connection in the connecting state will fail, in seconds.
695
+ def pending_connect_timeout
696
+ EventMachine::get_pending_connect_timeout @signature
697
+ end
698
+
699
+ # Sets the duration after which a TCP connection in a
700
+ # connecting state will fail.
701
+ #
702
+ # @param [Float, #to_f] value Connection timeout in seconds
703
+ def pending_connect_timeout= value
704
+ EventMachine::set_pending_connect_timeout @signature, value.to_f
705
+ end
706
+ alias set_pending_connect_timeout pending_connect_timeout=
707
+
708
+ # Reconnect to a given host/port with the current instance
709
+ #
710
+ # @param [String] server Hostname or IP address
711
+ # @param [Integer] port Port to reconnect to
712
+ def reconnect server, port
713
+ EventMachine::reconnect server, port, self
714
+ end
715
+
716
+
717
+ # Like {EventMachine::Connection#send_data}, this sends data to the remote end of
718
+ # the network connection. {EventMachine::Connection#send_file_data} takes a
719
+ # filename as an argument, though, and sends the contents of the file, in one
720
+ # chunk.
721
+ #
722
+ # @param [String] filename Local path of the file to send
723
+ #
724
+ # @see #send_data
725
+ # @author Kirk Haines
726
+ def send_file_data filename
727
+ EventMachine::send_file_data @signature, filename
728
+ end
729
+
730
+ # Open a file on the filesystem and send it to the remote peer. This returns an
731
+ # object of type {EventMachine::Deferrable}. The object's callbacks will be executed
732
+ # on the reactor main thread when the file has been completely scheduled for
733
+ # transmission to the remote peer. Its errbacks will be called in case of an error (such as file-not-found).
734
+ # This method employs various strategies to achieve the fastest possible performance,
735
+ # balanced against minimum consumption of memory.
736
+ #
737
+ # Warning: this feature has an implicit dependency on an outboard extension,
738
+ # evma_fastfilereader. You must install this extension in order to use {#stream_file_data}
739
+ # with files larger than a certain size (currently 8192 bytes).
740
+ #
741
+ # @option args [Boolean] :http_chunks (false) If true, this method will stream the file data in a format
742
+ # compatible with the HTTP chunked-transfer encoding
743
+ #
744
+ # @param [String] filename Local path of the file to stream
745
+ # @param [Hash] args Options
746
+ #
747
+ # @return [EventMachine::Deferrable]
748
+ def stream_file_data filename, args={}
749
+ EventMachine::FileStreamer.new( self, filename, args )
750
+ end
751
+
752
+ # Watches connection for readability. Only possible if the connection was created
753
+ # using {EventMachine.attach} and had {EventMachine.notify_readable}/{EventMachine.notify_writable} defined on the handler.
754
+ #
755
+ # @see #notify_readable?
756
+ def notify_readable= mode
757
+ EventMachine::set_notify_readable @signature, mode
758
+ end
759
+
760
+ # @return [Boolean] true if the connection is being watched for readability.
761
+ def notify_readable?
762
+ EventMachine::is_notify_readable @signature
763
+ end
764
+
765
+ # Watches connection for writeability. Only possible if the connection was created
766
+ # using {EventMachine.attach} and had {EventMachine.notify_readable}/{EventMachine.notify_writable} defined on the handler.
767
+ #
768
+ # @see #notify_writable?
769
+ def notify_writable= mode
770
+ EventMachine::set_notify_writable @signature, mode
771
+ end
772
+
773
+ # Returns true if the connection is being watched for writability.
774
+ def notify_writable?
775
+ EventMachine::is_notify_writable @signature
776
+ end
777
+
778
+ # Pause a connection so that {#send_data} and {#receive_data} events are not fired until {#resume} is called.
779
+ # @see #resume
780
+ def pause
781
+ EventMachine::pause_connection @signature
782
+ end
783
+
784
+ # Resume a connection's {#send_data} and {#receive_data} events.
785
+ # @see #pause
786
+ def resume
787
+ EventMachine::resume_connection @signature
788
+ end
789
+
790
+ # @return [Boolean] true if the connect was paused using {EventMachine::Connection#pause}.
791
+ # @see #pause
792
+ # @see #resume
793
+ def paused?
794
+ EventMachine::connection_paused? @signature
795
+ end
796
+
797
+ # @return [Boolean] true if the connect was watch only
798
+ def watch_only?
799
+ EventMachine::watch_only? @signature
800
+ end
801
+ end
802
+ end