eventmachine 0.12.6-java → 0.12.8-java

Sign up to get free protection for your applications and to get access to all the features.
Files changed (116) hide show
  1. data/{docs/README → README} +21 -13
  2. data/Rakefile +5 -3
  3. data/docs/DEFERRABLES +0 -5
  4. data/docs/INSTALL +2 -4
  5. data/docs/LEGAL +1 -1
  6. data/docs/LIGHTWEIGHT_CONCURRENCY +0 -2
  7. data/docs/PURE_RUBY +0 -2
  8. data/docs/RELEASE_NOTES +0 -2
  9. data/docs/SMTP +0 -7
  10. data/docs/SPAWNED_PROCESSES +0 -4
  11. data/docs/TODO +0 -2
  12. data/eventmachine.gemspec +17 -8
  13. data/examples/ex_channel.rb +43 -0
  14. data/examples/ex_queue.rb +2 -0
  15. data/examples/helper.rb +2 -0
  16. data/ext/cmain.cpp +119 -20
  17. data/ext/cplusplus.cpp +15 -6
  18. data/ext/ed.cpp +303 -93
  19. data/ext/ed.h +49 -22
  20. data/ext/em.cpp +368 -42
  21. data/ext/em.h +43 -6
  22. data/ext/eventmachine.h +21 -8
  23. data/ext/eventmachine_cpp.h +1 -0
  24. data/ext/extconf.rb +4 -0
  25. data/ext/kb.cpp +1 -2
  26. data/ext/pipe.cpp +1 -3
  27. data/ext/project.h +21 -0
  28. data/ext/rubymain.cpp +232 -32
  29. data/ext/ssl.cpp +38 -1
  30. data/ext/ssl.h +5 -1
  31. data/java/src/com/rubyeventmachine/Application.java +7 -3
  32. data/java/src/com/rubyeventmachine/EmReactor.java +16 -1
  33. data/java/src/com/rubyeventmachine/tests/ConnectTest.java +25 -3
  34. data/lib/{protocols → em}/buftok.rb +16 -5
  35. data/lib/em/callback.rb +26 -0
  36. data/lib/em/channel.rb +57 -0
  37. data/lib/em/connection.rb +505 -0
  38. data/lib/em/deferrable.rb +144 -165
  39. data/lib/em/file_watch.rb +54 -0
  40. data/lib/em/future.rb +24 -25
  41. data/lib/em/messages.rb +1 -1
  42. data/lib/em/process_watch.rb +44 -0
  43. data/lib/em/processes.rb +58 -52
  44. data/lib/em/protocols.rb +35 -0
  45. data/lib/em/protocols/header_and_content.rb +138 -0
  46. data/lib/em/protocols/httpclient.rb +263 -0
  47. data/lib/em/protocols/httpclient2.rb +582 -0
  48. data/lib/{protocols → em/protocols}/line_and_text.rb +2 -2
  49. data/lib/em/protocols/linetext2.rb +160 -0
  50. data/lib/{protocols → em/protocols}/memcache.rb +37 -7
  51. data/lib/em/protocols/object_protocol.rb +39 -0
  52. data/lib/em/protocols/postgres3.rb +247 -0
  53. data/lib/em/protocols/saslauth.rb +175 -0
  54. data/lib/em/protocols/smtpclient.rb +331 -0
  55. data/lib/em/protocols/smtpserver.rb +547 -0
  56. data/lib/em/protocols/stomp.rb +200 -0
  57. data/lib/{protocols → em/protocols}/tcptest.rb +21 -25
  58. data/lib/em/queue.rb +61 -0
  59. data/lib/em/spawnable.rb +53 -56
  60. data/lib/em/streamer.rb +92 -74
  61. data/lib/em/timers.rb +55 -0
  62. data/lib/em/version.rb +3 -0
  63. data/lib/eventmachine.rb +1008 -1298
  64. data/lib/evma.rb +1 -1
  65. data/lib/jeventmachine.rb +106 -101
  66. data/lib/pr_eventmachine.rb +47 -36
  67. data/tasks/project.rake +2 -1
  68. data/tests/client.crt +31 -0
  69. data/tests/client.key +51 -0
  70. data/tests/test_attach.rb +18 -0
  71. data/tests/test_basic.rb +108 -54
  72. data/tests/test_channel.rb +63 -0
  73. data/tests/test_connection_count.rb +2 -2
  74. data/tests/test_epoll.rb +109 -110
  75. data/tests/test_errors.rb +36 -36
  76. data/tests/test_exc.rb +22 -25
  77. data/tests/test_file_watch.rb +49 -0
  78. data/tests/test_futures.rb +77 -93
  79. data/tests/test_hc.rb +2 -2
  80. data/tests/test_httpclient.rb +55 -52
  81. data/tests/test_httpclient2.rb +110 -112
  82. data/tests/test_inactivity_timeout.rb +30 -0
  83. data/tests/test_kb.rb +8 -9
  84. data/tests/test_ltp2.rb +274 -277
  85. data/tests/test_next_tick.rb +91 -65
  86. data/tests/test_object_protocol.rb +37 -0
  87. data/tests/test_process_watch.rb +48 -0
  88. data/tests/test_processes.rb +56 -23
  89. data/tests/test_proxy_connection.rb +92 -0
  90. data/tests/test_pure.rb +1 -5
  91. data/tests/test_queue.rb +44 -0
  92. data/tests/test_running.rb +9 -14
  93. data/tests/test_sasl.rb +32 -34
  94. data/tests/test_send_file.rb +175 -176
  95. data/tests/test_servers.rb +37 -41
  96. data/tests/test_smtpserver.rb +47 -55
  97. data/tests/test_spawn.rb +284 -291
  98. data/tests/test_ssl_args.rb +1 -1
  99. data/tests/test_ssl_methods.rb +1 -1
  100. data/tests/test_ssl_verify.rb +82 -0
  101. data/tests/test_timers.rb +81 -88
  102. data/tests/test_ud.rb +0 -7
  103. data/tests/testem.rb +1 -1
  104. metadata +52 -36
  105. data/lib/em/eventable.rb +0 -39
  106. data/lib/eventmachine_version.rb +0 -31
  107. data/lib/protocols/header_and_content.rb +0 -129
  108. data/lib/protocols/httpcli2.rb +0 -803
  109. data/lib/protocols/httpclient.rb +0 -270
  110. data/lib/protocols/linetext2.rb +0 -161
  111. data/lib/protocols/postgres.rb +0 -261
  112. data/lib/protocols/saslauth.rb +0 -179
  113. data/lib/protocols/smtpclient.rb +0 -308
  114. data/lib/protocols/smtpserver.rb +0 -556
  115. data/lib/protocols/stomp.rb +0 -153
  116. data/tests/test_eventables.rb +0 -77
@@ -208,9 +208,10 @@ SslContext_t::~SslContext_t()
208
208
  SslBox_t::SslBox_t
209
209
  ******************/
210
210
 
211
- SslBox_t::SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile):
211
+ SslBox_t::SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile, bool verify_peer, const char *binding):
212
212
  bIsServer (is_server),
213
213
  bHandshakeCompleted (false),
214
+ bVerifyPeer (verify_peer),
214
215
  pSSL (NULL),
215
216
  pbioRead (NULL),
216
217
  pbioWrite (NULL)
@@ -232,6 +233,12 @@ SslBox_t::SslBox_t (bool is_server, const string &privkeyfile, const string &cer
232
233
  assert (pSSL);
233
234
  SSL_set_bio (pSSL, pbioRead, pbioWrite);
234
235
 
236
+ // Store a pointer to the binding signature in the SSL object so we can retrieve it later
237
+ SSL_set_ex_data(pSSL, 0, (void*) binding);
238
+
239
+ if (bVerifyPeer)
240
+ SSL_set_verify(pSSL, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, ssl_verify_wrapper);
241
+
235
242
  if (!bIsServer)
236
243
  SSL_connect (pSSL);
237
244
  }
@@ -419,5 +426,35 @@ X509 *SslBox_t::GetPeerCert()
419
426
  return cert;
420
427
  }
421
428
 
429
+
430
+ /******************
431
+ ssl_verify_wrapper
432
+ *******************/
433
+
434
+ extern "C" int ssl_verify_wrapper(int preverify_ok, X509_STORE_CTX *ctx)
435
+ {
436
+ const char *binding;
437
+ X509 *cert;
438
+ SSL *ssl;
439
+ BUF_MEM *buf;
440
+ BIO *out;
441
+ int result;
442
+
443
+ cert = X509_STORE_CTX_get_current_cert(ctx);
444
+ ssl = (SSL*) X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
445
+ binding = (const char*) SSL_get_ex_data(ssl, 0);
446
+
447
+ out = BIO_new(BIO_s_mem());
448
+ PEM_write_bio_X509(out, cert);
449
+ BIO_write(out, "\0", 1);
450
+ BIO_get_mem_ptr(out, &buf);
451
+
452
+ ConnectionDescriptor *cd = dynamic_cast <ConnectionDescriptor*> (Bindable_t::GetObject(binding));
453
+ result = (cd->VerifySslPeer(buf->data) == true ? 1 : 0);
454
+ BUF_MEM_free(buf);
455
+
456
+ return result;
457
+ }
458
+
422
459
  #endif // WITH_SSL
423
460
 
data/ext/ssl.h CHANGED
@@ -57,7 +57,7 @@ class SslBox_t
57
57
  class SslBox_t
58
58
  {
59
59
  public:
60
- SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile);
60
+ SslBox_t (bool is_server, const string &privkeyfile, const string &certchainfile, bool verify_peer, const char *binding);
61
61
  virtual ~SslBox_t();
62
62
 
63
63
  int PutPlaintext (const char*, int);
@@ -75,6 +75,7 @@ class SslBox_t
75
75
  protected:
76
76
  SslContext_t *Context;
77
77
 
78
+ bool bVerifyPeer;
78
79
  bool bIsServer;
79
80
  bool bHandshakeCompleted;
80
81
  SSL *pSSL;
@@ -83,6 +84,9 @@ class SslBox_t
83
84
 
84
85
  PageList OutboundQ;
85
86
  };
87
+
88
+ extern "C" int ssl_verify_wrapper(int, X509_STORE_CTX*);
89
+
86
90
  #endif // WITH_SSL
87
91
 
88
92
 
@@ -128,16 +128,20 @@ public class Application {
128
128
  reactor.timers.put(s, t);
129
129
 
130
130
  }
131
-
132
- public void connect (String host, int port, Connection c) {
131
+
132
+ public void bindConnect (String bindAddr, int bindPort, String host, int port, Connection c) {
133
133
  try {
134
- String s = reactor.connectTcpServer(host, port);
134
+ String s = reactor.connectTcpServer(bindAddr, bindPort, host, port);
135
135
  c.application = this;
136
136
  c.signature = s;
137
137
  reactor.connections.put(s, c);
138
138
  c.postInit();
139
139
  } catch (ClosedChannelException e) {}
140
140
  }
141
+
142
+ public void connect (String host, int port, Connection c) {
143
+ bindConnect(null, 0, host, port, c);
144
+ }
141
145
 
142
146
  public void startServer (SocketAddress sa, ConnectionFactory f) throws EmReactorException {
143
147
  String s = reactor.startTcpServer(sa);
@@ -340,7 +340,6 @@ public class EmReactor {
340
340
  (Connections.get(sig)).scheduleOutboundDatagram( bb, recipAddress, recipPort);
341
341
  }
342
342
 
343
-
344
343
  /**
345
344
  *
346
345
  * @param address
@@ -349,11 +348,27 @@ public class EmReactor {
349
348
  * @throws ClosedChannelException
350
349
  */
351
350
  public String connectTcpServer (String address, int port) throws ClosedChannelException {
351
+ return connectTcpServer(null, 0, address, port);
352
+ }
353
+
354
+ /**
355
+ *
356
+ * @param bindAddr
357
+ * @param bindPort
358
+ * @param address
359
+ * @param port
360
+ * @return
361
+ * @throws ClosedChannelException
362
+ */
363
+ public String connectTcpServer (String bindAddr, int bindPort, String address, int port) throws ClosedChannelException {
352
364
  String b = createBinding();
353
365
 
354
366
  try {
355
367
  SocketChannel sc = SocketChannel.open();
356
368
  sc.configureBlocking(false);
369
+ if (bindAddr != null)
370
+ sc.socket().bind(new InetSocketAddress (bindAddr, bindPort));
371
+
357
372
  EventableSocketChannel ec = new EventableSocketChannel (sc, b, mySelector);
358
373
 
359
374
  if (sc.connect (new InetSocketAddress (address, port))) {
@@ -97,9 +97,31 @@ public class ConnectTest {
97
97
  });
98
98
  a.run();
99
99
  }
100
-
101
-
102
-
100
+
101
+ public final void testBindConnect() throws IOException {
102
+ class Server extends Connection {
103
+ public void postInit() {
104
+ // TODO: get peername here and check if the port is 33333
105
+ // doesnt seem like peername is impl yet?
106
+ System.out.println("post init!");
107
+ }
108
+ };
109
+
110
+ Application a = new Application();
111
+ a.addTimer(0, new Timer() {
112
+ public void fire() {
113
+ application.startServer(new InetSocketAddress("localhost", 20000), new Server());
114
+ }
115
+ });
116
+ a.addTimer(500, new Timer() {
117
+ public void fire() {
118
+ application.bindConnect("localhost", 33333, "localhost", 20000);
119
+ }
120
+ });
121
+
122
+ a.run();
123
+ }
124
+
103
125
  class C1 extends Connection {
104
126
  Application application;
105
127
  public C1 (Application a) {
@@ -18,6 +18,16 @@
18
18
  # by default. It allows input to be spoon-fed from some outside source which
19
19
  # receives arbitrary length datagrams which may-or-may-not contain the token
20
20
  # by which entities are delimited.
21
+ #
22
+ # Commonly used to parse lines out of incoming data:
23
+ #
24
+ # module LineBufferedConnection
25
+ # def receive_data(data)
26
+ # (@buffer ||= BufferedTokenizer.new).extract(data).each do |line|
27
+ # receive_line(line)
28
+ # end
29
+ # end
30
+ # end
21
31
 
22
32
  class BufferedTokenizer
23
33
  # New BufferedTokenizers will operate on lines delimited by "\n" by default
@@ -76,10 +86,10 @@ class BufferedTokenizer
76
86
  entities.unshift @input.join
77
87
 
78
88
  =begin
79
- # Note added by FC, 10Jul07. This paragraph contains a regression. It breaks
80
- # empty tokens. Think of the empty line that delimits an HTTP header. It will have
81
- # two "\n" delimiters in a row, and this code mishandles the resulting empty token.
82
- # It someone figures out how to fix the problem, we can re-enable this code branch.
89
+ # Note added by FC, 10Jul07. This paragraph contains a regression. It breaks
90
+ # empty tokens. Think of the empty line that delimits an HTTP header. It will have
91
+ # two "\n" delimiters in a row, and this code mishandles the resulting empty token.
92
+ # It someone figures out how to fix the problem, we can re-enable this code branch.
83
93
  # Multi-character token support.
84
94
  # Split any tokens that were incomplete on the last iteration buf complete now.
85
95
  entities.map! do |e|
@@ -121,7 +131,8 @@ class BufferedTokenizer
121
131
  buffer
122
132
  end
123
133
 
134
+ # Is the buffer empty?
124
135
  def empty?
125
136
  @input.empty?
126
137
  end
127
- end
138
+ end
@@ -0,0 +1,26 @@
1
+ module EventMachine
2
+ # Utility method for coercing arguments to an object that responds to #call
3
+ # Accepts an object and a method name to send to, or a block, or an object
4
+ # that responds to call.
5
+ #
6
+ # cb = EM.Callback{ |msg| puts(msg) }
7
+ # cb.call('hello world')
8
+ #
9
+ # cb = EM.Callback(Object, :puts)
10
+ # cb.call('hello world')
11
+ #
12
+ # cb = EM.Callback(proc{ |msg| puts(msg) })
13
+ # cb.call('hello world')
14
+ #
15
+ def self.Callback(object = nil, method = nil, &blk)
16
+ if object && method
17
+ lambda { |*args| object.send method, *args }
18
+ else
19
+ if object.respond_to? :call
20
+ object
21
+ else
22
+ blk || raise(ArgumentError)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,57 @@
1
+ module EventMachine
2
+ # Provides a simple interface to push items to a number of subscribers. The
3
+ # channel will schedule all operations on the main reactor thread for thread
4
+ # safe reactor operations.
5
+ #
6
+ # This provides a convenient way for connections to consume messages from
7
+ # long running code in defer, without threading issues.
8
+ #
9
+ # channel = EM::Channel.new
10
+ # sid = channel.subscribe{ |msg| p [:got, msg] }
11
+ # channel.push('hello world')
12
+ # channel.unsubscribe(sid)
13
+ #
14
+ # See examples/ex_channel.rb for a detailed example.
15
+ class Channel
16
+ # Create a new channel
17
+ def initialize
18
+ @subs = {}
19
+ @uid = 0
20
+ end
21
+
22
+ # Takes any arguments suitable for EM::Callback() and returns a subscriber
23
+ # id for use when unsubscribing.
24
+ def subscribe(*a, &b)
25
+ name = gen_id
26
+ EM.schedule { @subs[name] = EM::Callback(*a, &b) }
27
+ name
28
+ end
29
+
30
+ # Removes this subscriber from the list.
31
+ def unsubscribe(name)
32
+ EM.schedule { @subs.delete name }
33
+ end
34
+
35
+ # Add items to the channel, which are pushed out to all subscribers.
36
+ def push(*items)
37
+ items = items.dup
38
+ EM.schedule { @subs.values.each { |s| items.each { |i| s.call i } } }
39
+ end
40
+ alias << push
41
+
42
+ # Receive exactly one message from the channel.
43
+ def pop(*a, &b)
44
+ EM.schedule {
45
+ name = subscribe do |*args|
46
+ unsubscribe(name)
47
+ EM::Callback(*a, &b).call(*args)
48
+ end
49
+ }
50
+ end
51
+
52
+ private
53
+ def gen_id # :nodoc:
54
+ @uid += 1
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,505 @@
1
+ module EventMachine
2
+ class FileNotFoundException < Exception # :nodoc:
3
+ end
4
+
5
+ # EventMachine::Connection is a class that is instantiated
6
+ # by EventMachine's processing loop whenever a new connection
7
+ # is created. (New connections can be either initiated locally
8
+ # to a remote server or accepted locally from a remote client.)
9
+ # When a Connection object is instantiated, it <i>mixes in</i>
10
+ # the functionality contained in the user-defined module
11
+ # specified in calls to EventMachine#connect or EventMachine#start_server.
12
+ # User-defined handler modules may redefine any or all of the standard
13
+ # methods defined here, as well as add arbitrary additional code
14
+ # that will also be mixed in.
15
+ #
16
+ # EventMachine manages one object inherited from EventMachine::Connection
17
+ # (and containing the mixed-in user code) for every network connection
18
+ # that is active at any given time.
19
+ # The event loop will automatically call methods on EventMachine::Connection
20
+ # objects whenever specific events occur on the corresponding connections,
21
+ # as described below.
22
+ #
23
+ # This class is never instantiated by user code, and does not publish an
24
+ # initialize method. The instance methods of EventMachine::Connection
25
+ # which may be called by the event loop are: post_init, receive_data,
26
+ # and unbind. All of the other instance methods defined here are called
27
+ # only by user code.
28
+ #
29
+ class Connection
30
+ attr_accessor :signature # :nodoc:
31
+
32
+ # Override .new so subclasses don't have to call super and can ignore
33
+ # connection-specific arguments
34
+ #
35
+ def self.new(sig, *args) #:nodoc:
36
+ allocate.instance_eval do
37
+ # Call a superclass's #initialize if it has one
38
+ initialize(*args)
39
+
40
+ # Store signature and run #post_init
41
+ @signature = sig
42
+ associate_callback_target sig
43
+ post_init
44
+
45
+ self
46
+ end
47
+ end
48
+
49
+ # Stubbed initialize so legacy superclasses can safely call super
50
+ #
51
+ def initialize(*args) #:nodoc:
52
+ end
53
+
54
+ def associate_callback_target(sig) #:nodoc:
55
+ # no-op for the time being, to match similar no-op in rubymain.cpp
56
+ end
57
+
58
+ # EventMachine::Connection#post_init is called by the event loop
59
+ # immediately after the network connection has been established,
60
+ # and before resumption of the network loop.
61
+ # This method is generally not called by user code, but is called automatically
62
+ # by the event loop. The base-class implementation is a no-op.
63
+ # This is a very good place to initialize instance variables that will
64
+ # be used throughout the lifetime of the network connection.
65
+ #
66
+ def post_init
67
+ end
68
+
69
+ # EventMachine::Connection#receive_data is called by the event loop
70
+ # whenever data has been received by the network connection.
71
+ # It is never called by user code.
72
+ # receive_data is called with a single parameter, a String containing
73
+ # the network protocol data, which may of course be binary. You will
74
+ # generally redefine this method to perform your own processing of the incoming data.
75
+ #
76
+ # Here's a key point which is essential to understanding the event-driven
77
+ # programming model: <i>EventMachine knows absolutely nothing about the protocol
78
+ # which your code implements.</i> You must not make any assumptions about
79
+ # the size of the incoming data packets, or about their alignment on any
80
+ # particular intra-message or PDU boundaries (such as line breaks).
81
+ # receive_data can and will send you arbitrary chunks of data, with the
82
+ # only guarantee being that the data is presented to your code in the order
83
+ # it was collected from the network. Don't even assume that the chunks of
84
+ # data will correspond to network packets, as EventMachine can and will coalesce
85
+ # several incoming packets into one, to improve performance. The implication for your
86
+ # code is that you generally will need to implement some kind of a state machine
87
+ # in your redefined implementation of receive_data. For a better understanding
88
+ # of this, read through the examples of specific protocol handlers in EventMachine::Protocols
89
+ #
90
+ # The base-class implementation of receive_data (which will be invoked if
91
+ # you don't redefine it) simply prints the size of each incoming data packet
92
+ # to stdout.
93
+ #
94
+ def receive_data data
95
+ puts "............>>>#{data.length}"
96
+ end
97
+
98
+ # #ssl_handshake_completed is called by EventMachine when the SSL/TLS handshake has
99
+ # been completed, as a result of calling #start_tls to initiate SSL/TLS on the connection.
100
+ #
101
+ # This callback exists because #post_init and #connection_completed are <b>not</b> reliable
102
+ # for indicating when an SSL/TLS connection is ready to have it's certificate queried for.
103
+ #
104
+ # See #get_peer_cert for application and example.
105
+ def ssl_handshake_completed
106
+ end
107
+
108
+ # #ssl_verify_peer is called by EventMachine when :verify_peer => true has been passed to #start_tls.
109
+ # It will be called with each certificate in the certificate chain provided by the remote peer.
110
+ # The cert will be passed as a String in PEM format, the same as in #get_peer_cert. It is up to user defined
111
+ # code to perform a check on the certificates. The return value from this callback is used to accept or deny the peer.
112
+ # A return value that is not nil or false triggers acceptance. If the peer is not accepted, the connection
113
+ # will be subsequently closed. See 'tests/test_ssl_verify.rb' for a simple example.
114
+ def ssl_verify_peer(cert)
115
+ end
116
+
117
+ # EventMachine::Connection#unbind is called by the framework whenever a connection
118
+ # (either a server or client connection) is closed. The close can occur because
119
+ # your code intentionally closes it (see close_connection and close_connection_after_writing),
120
+ # because the remote peer closed the connection, or because of a network error.
121
+ # You may not assume that the network connection is still open and able to send or
122
+ # receive data when the callback to unbind is made. This is intended only to give
123
+ # you a chance to clean up associations your code may have made to the connection
124
+ # object while it was open.
125
+ #
126
+ def unbind
127
+ end
128
+
129
+ # EventMachine::Connection#proxy_target_unbound is called by the reactor after attempting
130
+ # to relay incoming data to a descriptor (set as a proxy target descriptor with
131
+ # EventMachine::enable_proxy) that has already been closed.
132
+ def proxy_target_unbound
133
+ end
134
+
135
+ # EventMachine::Connection#proxy_incoming_to is called only by user code. It sets up
136
+ # a low-level proxy relay for all data inbound for this connection, to the connection given
137
+ # as the argument. This is essentially just a helper method for enable_proxy.
138
+ # See EventMachine::enable_proxy documentation for details.
139
+ def proxy_incoming_to(conn)
140
+ EventMachine::enable_proxy(self, conn)
141
+ end
142
+
143
+ # Helper method for EventMachine::disable_proxy(self)
144
+ def stop_proxying
145
+ EventMachine::disable_proxy(self)
146
+ end
147
+
148
+ # EventMachine::Connection#close_connection is called only by user code, and never
149
+ # by the event loop. You may call this method against a connection object in any
150
+ # callback handler, whether or not the callback was made against the connection
151
+ # you want to close. close_connection <i>schedules</i> the connection to be closed
152
+ # at the next available opportunity within the event loop. You may not assume that
153
+ # the connection is closed when close_connection returns. In particular, the framework
154
+ # will callback the unbind method for the particular connection at a point shortly
155
+ # after you call close_connection. You may assume that the unbind callback will
156
+ # take place sometime after your call to close_connection completes. In other words,
157
+ # the unbind callback will not re-enter your code "inside" of your call to close_connection.
158
+ # However, it's not guaranteed that a future version of EventMachine will not change
159
+ # this behavior.
160
+ #
161
+ # close_connection will <i>silently discard</i> any outbound data which you have
162
+ # sent to the connection using EventMachine::Connection#send_data but which has not
163
+ # yet been sent across the network. If you want to avoid this behavior, use
164
+ # EventMachine::Connection#close_connection_after_writing.
165
+ #
166
+ def close_connection after_writing = false
167
+ EventMachine::close_connection @signature, after_writing
168
+ end
169
+
170
+ # EventMachine::Connection#detach will remove the given connection from the event loop.
171
+ # The connection's socket remains open and its file descriptor number is returned
172
+ def detach
173
+ EventMachine::detach_fd @signature
174
+ end
175
+
176
+ # EventMachine::Connection#close_connection_after_writing is a variant of close_connection.
177
+ # All of the descriptive comments given for close_connection also apply to
178
+ # close_connection_after_writing, <i>with one exception:</i> If the connection has
179
+ # outbound data sent using send_dat but which has not yet been sent across the network,
180
+ # close_connection_after_writing will schedule the connection to be closed <i>after</i>
181
+ # all of the outbound data has been safely written to the remote peer.
182
+ #
183
+ # Depending on the amount of outgoing data and the speed of the network,
184
+ # considerable time may elapse between your call to close_connection_after_writing
185
+ # and the actual closing of the socket (at which time the unbind callback will be called
186
+ # by the event loop). During this time, you <i>may not</i> call send_data to transmit
187
+ # additional data (that is, the connection is closed for further writes). In very
188
+ # rare cases, you may experience a receive_data callback after your call to close_connection_after_writing,
189
+ # depending on whether incoming data was in the process of being received on the connection
190
+ # at the moment when you called close_connection_after_writing. Your protocol handler must
191
+ # be prepared to properly deal with such data (probably by ignoring it).
192
+ #
193
+ def close_connection_after_writing
194
+ close_connection true
195
+ end
196
+
197
+ # EventMachine::Connection#send_data is only called by user code, never by
198
+ # the event loop. You call this method to send data to the remote end of the
199
+ # network connection. send_data is called with a single String argument, which
200
+ # may of course contain binary data. You can call send_data any number of times.
201
+ # send_data is an instance method of an object derived from EventMachine::Connection
202
+ # and containing your mixed-in handler code), so if you call it without qualification
203
+ # within a callback function, the data will be sent to the same network connection
204
+ # that generated the callback. Calling self.send_data is exactly equivalent.
205
+ #
206
+ # You can also call send_data to write to a connection <i>other than the one
207
+ # whose callback you are calling send_data from.</i> This is done by recording
208
+ # the value of the connection in any callback function (the value self), in any
209
+ # variable visible to other callback invocations on the same or different
210
+ # connection objects. (Need an example to make that clear.)
211
+ #
212
+ def send_data data
213
+ data = data.to_s
214
+ size = data.bytesize if data.respond_to?(:bytesize)
215
+ size ||= data.size
216
+ EventMachine::send_data @signature, data, size
217
+ end
218
+
219
+ # Returns true if the connection is in an error state, false otherwise.
220
+ # In general, you can detect the occurrence of communication errors or unexpected
221
+ # disconnection by the remote peer by handing the #unbind method. In some cases, however,
222
+ # it's useful to check the status of the connection using #error? before attempting to send data.
223
+ # This function is synchronous: it will return immediately without blocking.
224
+ #
225
+ #
226
+ def error?
227
+ EventMachine::report_connection_error_status(@signature) != 0
228
+ end
229
+
230
+ # #connection_completed is called by the event loop when a remote TCP connection
231
+ # attempt completes successfully. You can expect to get this notification after calls
232
+ # to EventMachine#connect. Remember that EventMachine makes remote connections
233
+ # asynchronously, just as with any other kind of network event. #connection_completed
234
+ # is intended primarily to assist with network diagnostics. For normal protocol
235
+ # handling, use #post_init to perform initial work on a new connection (such as
236
+ # send an initial set of data).
237
+ # #post_init will always be called. #connection_completed will only be called in case
238
+ # of a successful completion. A connection-attempt which fails will receive a call
239
+ # to #unbind after the failure.
240
+ def connection_completed
241
+ end
242
+
243
+ # Call #start_tls at any point to initiate TLS encryption on connected streams.
244
+ # The method is smart enough to know whether it should perform a server-side
245
+ # or a client-side handshake. An appropriate place to call #start_tls is in
246
+ # your redefined #post_init method, or in the #connection_completed handler for
247
+ # an outbound connection.
248
+ #
249
+ # #start_tls takes an optional parameter hash that allows you to specify certificate
250
+ # and other options to be used with this Connection object. Here are the currently-supported
251
+ # options:
252
+ #
253
+ # * :cert_chain_file :
254
+ # takes a String, which is interpreted as the name of a readable file in the
255
+ # local filesystem. The file is expected to contain a chain of X509 certificates in
256
+ # PEM format, with the most-resolved certificate at the top of the file, successive
257
+ # intermediate certs in the middle, and the root (or CA) cert at the bottom.
258
+ #
259
+ # * :private_key_file :
260
+ # takes a String, which is interpreted as the name of a readable file in the
261
+ # local filesystem. The file must contain a private key in PEM format.
262
+ #
263
+ # * :verify_peer :
264
+ # takes either true or false. Default is false. This indicates whether a server should request a
265
+ # certificate from a peer, to be verified by user code. If true, the #ssl_verify_peer callback
266
+ # on the Connection object is called with each certificate in the certificate chain provided by
267
+ # the peer. See documentation on #ssl_verify_peer for how to use this.
268
+ #
269
+ # === Usage example:
270
+ #
271
+ # require 'rubygems'
272
+ # require 'eventmachine'
273
+ #
274
+ # module Handler
275
+ # def post_init
276
+ # start_tls(:private_key_file => '/tmp/server.key', :cert_chain_file => '/tmp/server.crt', :verify_peer => false)
277
+ # end
278
+ # end
279
+ #
280
+ # EM.run {
281
+ # EM.start_server("127.0.0.1", 9999, Handler)
282
+ # }
283
+ #
284
+ #--
285
+ # TODO: support passing an encryption parameter, which can be string or Proc, to get a passphrase
286
+ # for encrypted private keys.
287
+ # TODO: support passing key material via raw strings or Procs that return strings instead of
288
+ # just filenames.
289
+ # What will get nasty is whether we have to define a location for storing this stuff as files.
290
+ # In general, the OpenSSL interfaces for dealing with certs and keys in files are much better
291
+ # behaved than the ones for raw chunks of memory.
292
+ #
293
+ def start_tls args={}
294
+ priv_key, cert_chain, verify_peer = args.values_at(:private_key_file, :cert_chain_file, :verify_peer)
295
+
296
+ [priv_key, cert_chain].each do |file|
297
+ next if file.nil? or file.empty?
298
+ raise FileNotFoundException,
299
+ "Could not find #{file} for start_tls" unless File.exists? file
300
+ end
301
+
302
+ EventMachine::set_tls_parms(@signature, priv_key || '', cert_chain || '', verify_peer)
303
+ EventMachine::start_tls @signature
304
+ end
305
+
306
+ # If SSL/TLS is active on the connection, #get_peer_cert returns the remote X509 certificate
307
+ # as a String, in the popular PEM format. This can then be used for arbitrary validation
308
+ # of a peer's certificate in your code.
309
+ #
310
+ # This should be called in/after the #ssl_handshake_completed callback, which indicates
311
+ # that SSL/TLS is active. Using this callback is important, because the certificate may not
312
+ # be available until the time it is executed. Using #post_init or #connection_completed is
313
+ # not adequate, because the SSL handshake may still be taking place.
314
+ #
315
+ # #get_peer_cert will return <b>nil</b> if:
316
+ #
317
+ # * EventMachine is not built with OpenSSL support
318
+ # * SSL/TLS is not active on the connection
319
+ # * SSL/TLS handshake is not yet complete
320
+ # * Remote peer for any other reason has not presented a certificate
321
+ #
322
+ # === Example:
323
+ #
324
+ # module Handler
325
+ #
326
+ # def post_init
327
+ # puts "Starting TLS"
328
+ # start_tls
329
+ # end
330
+ #
331
+ # def ssl_handshake_completed
332
+ # puts get_peer_cert
333
+ # close_connection
334
+ # end
335
+ #
336
+ # def unbind
337
+ # EventMachine::stop_event_loop
338
+ # end
339
+ #
340
+ # end
341
+ #
342
+ # EM.run {
343
+ # EventMachine::connect "mail.google.com", 443, Handler
344
+ # }
345
+ #
346
+ # Output:
347
+ # -----BEGIN CERTIFICATE-----
348
+ # MIIDIjCCAougAwIBAgIQbldpChBPqv+BdPg4iwgN8TANBgkqhkiG9w0BAQUFADBM
349
+ # MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
350
+ # THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0wODA1MDIxNjMyNTRaFw0w
351
+ # OTA1MDIxNjMyNTRaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
352
+ # MRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUgSW5jMRgw
353
+ # FgYDVQQDEw9tYWlsLmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
354
+ # AoGBALlkxdh2QXegdElukCSOV2+8PKiONIS+8Tu9K7MQsYpqtLNC860zwOPQ2NLI
355
+ # 3Zp4jwuXVTrtzGuiqf5Jioh35Ig3CqDXtLyZoypjZUQcq4mlLzHlhIQ4EhSjDmA7
356
+ # Ffw9y3ckSOQgdBQWNLbquHh9AbEUjmhkrYxIqKXeCnRKhv6nAgMBAAGjgecwgeQw
357
+ # KAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUFBwMCBglghkgBhvhCBAEwNgYDVR0f
358
+ # BC8wLTAroCmgJ4YlaHR0cDovL2NybC50aGF3dGUuY29tL1RoYXd0ZVNHQ0NBLmNy
359
+ # bDByBggrBgEFBQcBAQRmMGQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnRoYXd0
360
+ # ZS5jb20wPgYIKwYBBQUHMAKGMmh0dHA6Ly93d3cudGhhd3RlLmNvbS9yZXBvc2l0
361
+ # b3J5L1RoYXd0ZV9TR0NfQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQEF
362
+ # BQADgYEAsRwpLg1dgCR1gYDK185MFGukXMeQFUvhGqF8eT/CjpdvezyKVuz84gSu
363
+ # 6ccMXgcPQZGQN/F4Xug+Q01eccJjRSVfdvR5qwpqCj+6BFl5oiKDBsveSkrmL5dz
364
+ # s2bn7TdTSYKcLeBkjXxDLHGBqLJ6TNCJ3c4/cbbG5JhGvoema94=
365
+ # -----END CERTIFICATE-----
366
+ #
367
+ # You can do whatever you want with the certificate String, such as load it
368
+ # as a certificate object using the OpenSSL library, and check it's fields.
369
+ def get_peer_cert
370
+ EventMachine::get_peer_cert @signature
371
+ end
372
+
373
+
374
+ # send_datagram is for sending UDP messages.
375
+ # This method may be called from any Connection object that refers
376
+ # to an open datagram socket (see EventMachine#open_datagram_socket).
377
+ # The method sends a UDP (datagram) packet containing the data you specify,
378
+ # to a remote peer specified by the IP address and port that you give
379
+ # as parameters to the method.
380
+ # Observe that you may send a zero-length packet (empty string).
381
+ # However, you may not send an arbitrarily-large data packet because
382
+ # your operating system will enforce a platform-specific limit on
383
+ # the size of the outbound packet. (Your kernel
384
+ # will respond in a platform-specific way if you send an overlarge
385
+ # packet: some will send a truncated packet, some will complain, and
386
+ # some will silently drop your request).
387
+ # On LANs, it's usually OK to send datagrams up to about 4000 bytes in length,
388
+ # but to be really safe, send messages smaller than the Ethernet-packet
389
+ # size (typically about 1400 bytes). Some very restrictive WANs
390
+ # will either drop or truncate packets larger than about 500 bytes.
391
+ #--
392
+ # Added the Integer wrapper around the port parameter per suggestion by
393
+ # Matthieu Riou, after he passed a String and spent hours tearing his hair out.
394
+ #
395
+ def send_datagram data, recipient_address, recipient_port
396
+ data = data.to_s
397
+ EventMachine::send_datagram @signature, data, data.length, recipient_address, Integer(recipient_port)
398
+ end
399
+
400
+
401
+ # #get_peername is used with stream-connections to obtain the identity
402
+ # of the remotely-connected peer. If a peername is available, this method
403
+ # returns a sockaddr structure. The method returns nil if no peername is available.
404
+ # You can use Socket.unpack_sockaddr_in and its variants to obtain the
405
+ # values contained in the peername structure returned from #get_peername.
406
+ #
407
+ # require 'socket'
408
+ # module Handler
409
+ # def receive_data data
410
+ # port, ip = Socket.unpack_sockaddr_in(get_peername)
411
+ # puts "got #{data.inspect} from #{ip}:#{port}"
412
+ # end
413
+ # end
414
+ def get_peername
415
+ EventMachine::get_peername @signature
416
+ end
417
+
418
+ # #get_sockname is used with stream-connections to obtain the identity
419
+ # of the local side of the connection. If a local name is available, this method
420
+ # returns a sockaddr structure. The method returns nil if no local name is available.
421
+ # You can use Socket#unpack_sockaddr_in and its variants to obtain the
422
+ # values contained in the local-name structure returned from #get_sockname.
423
+ def get_sockname
424
+ EventMachine::get_sockname @signature
425
+ end
426
+
427
+ # Returns the PID (kernel process identifier) of a subprocess
428
+ # associated with this Connection object. For use with EventMachine#popen
429
+ # and similar methods. Returns nil when there is no meaningful subprocess.
430
+ #--
431
+ #
432
+ def get_pid
433
+ EventMachine::get_subprocess_pid @signature
434
+ end
435
+
436
+ # Returns a subprocess exit status. Only useful for #popen. Call it in your
437
+ # #unbind handler.
438
+ #
439
+ def get_status
440
+ EventMachine::get_subprocess_status @signature
441
+ end
442
+
443
+ # comm_inactivity_timeout returns the current value (float in seconds) of the inactivity-timeout
444
+ # property of network-connection and datagram-socket objects. A nonzero value
445
+ # indicates that the connection or socket will automatically be closed if no read or write
446
+ # activity takes place for at least that number of seconds.
447
+ # A zero value (the default) specifies that no automatic timeout will take place.
448
+ def comm_inactivity_timeout
449
+ EventMachine::get_comm_inactivity_timeout @signature
450
+ end
451
+
452
+ # Alias for #set_comm_inactivity_timeout.
453
+ def comm_inactivity_timeout= value
454
+ self.send :set_comm_inactivity_timeout, value
455
+ end
456
+
457
+ # comm_inactivity_timeout= allows you to set the inactivity-timeout property for
458
+ # a network connection or datagram socket. Specify a non-negative float value in seconds.
459
+ # If the value is greater than zero, the connection or socket will automatically be closed
460
+ # if no read or write activity takes place for at least that number of seconds.
461
+ # Specify a value of zero to indicate that no automatic timeout should take place.
462
+ # Zero is the default value.
463
+ def set_comm_inactivity_timeout value
464
+ EventMachine::set_comm_inactivity_timeout @signature, value.to_f
465
+ end
466
+
467
+ # Reconnect to a given host/port with the current EventMachine::Connection instance
468
+ #--
469
+ # EXPERIMENTAL. DO NOT RELY ON THIS METHOD TO REMAIN SUPPORTED.
470
+ # (03Nov06)
471
+ def reconnect server, port
472
+ EventMachine::reconnect server, port, self
473
+ end
474
+
475
+
476
+ # Like EventMachine::Connection#send_data, this sends data to the remote end of
477
+ # the network connection. EventMachine::Connection@send_file_data takes a
478
+ # filename as an argument, though, and sends the contents of the file, in one
479
+ # chunk. Contributed by Kirk Haines.
480
+ #
481
+ def send_file_data filename
482
+ EventMachine::send_file_data @signature, filename
483
+ end
484
+
485
+ # Open a file on the filesystem and send it to the remote peer. This returns an
486
+ # object of type EventMachine::Deferrable. The object's callbacks will be executed
487
+ # on the reactor main thread when the file has been completely scheduled for
488
+ # transmission to the remote peer. Its errbacks will be called in case of an error
489
+ # (such as file-not-found). #stream_file_data employs various strategems to achieve
490
+ # the fastest possible performance, balanced against minimum consumption of memory.
491
+ #
492
+ # You can control the behavior of #stream_file_data with the optional arguments parameter.
493
+ # Currently-supported arguments are:
494
+ # :http_chunks, a boolean flag which defaults false. If true, this flag streams the
495
+ # file data in a format compatible with the HTTP chunked-transfer encoding.
496
+ #
497
+ # Warning: this feature has an implicit dependency on an outboard extension,
498
+ # evma_fastfilereader. You must install this extension in order to use #stream_file_data
499
+ # with files larger than a certain size (currently 8192 bytes).
500
+ #
501
+ def stream_file_data filename, args={}
502
+ EventMachine::FileStreamer.new( self, filename, args )
503
+ end
504
+ end
505
+ end