crusher-eventmachine 0.12.11

Sign up to get free protection for your applications and to get access to all the features.
Files changed (162) hide show
  1. data/README +81 -0
  2. data/Rakefile +370 -0
  3. data/docs/COPYING +60 -0
  4. data/docs/ChangeLog +211 -0
  5. data/docs/DEFERRABLES +246 -0
  6. data/docs/EPOLL +141 -0
  7. data/docs/GNU +281 -0
  8. data/docs/INSTALL +13 -0
  9. data/docs/KEYBOARD +42 -0
  10. data/docs/LEGAL +25 -0
  11. data/docs/LIGHTWEIGHT_CONCURRENCY +130 -0
  12. data/docs/PURE_RUBY +75 -0
  13. data/docs/RELEASE_NOTES +94 -0
  14. data/docs/SMTP +4 -0
  15. data/docs/SPAWNED_PROCESSES +148 -0
  16. data/docs/TODO +8 -0
  17. data/eventmachine.gemspec +40 -0
  18. data/examples/ex_channel.rb +43 -0
  19. data/examples/ex_queue.rb +2 -0
  20. data/examples/ex_tick_loop_array.rb +15 -0
  21. data/examples/ex_tick_loop_counter.rb +32 -0
  22. data/examples/helper.rb +2 -0
  23. data/ext/binder.cpp +124 -0
  24. data/ext/binder.h +46 -0
  25. data/ext/cmain.cpp +852 -0
  26. data/ext/cplusplus.cpp +202 -0
  27. data/ext/ed.cpp +1884 -0
  28. data/ext/ed.h +418 -0
  29. data/ext/em.cpp +2377 -0
  30. data/ext/em.h +239 -0
  31. data/ext/emwin.cpp +300 -0
  32. data/ext/emwin.h +94 -0
  33. data/ext/epoll.cpp +26 -0
  34. data/ext/epoll.h +25 -0
  35. data/ext/eventmachine.h +124 -0
  36. data/ext/eventmachine_cpp.h +96 -0
  37. data/ext/extconf.rb +150 -0
  38. data/ext/fastfilereader/extconf.rb +85 -0
  39. data/ext/fastfilereader/mapper.cpp +214 -0
  40. data/ext/fastfilereader/mapper.h +59 -0
  41. data/ext/fastfilereader/rubymain.cpp +127 -0
  42. data/ext/files.cpp +94 -0
  43. data/ext/files.h +65 -0
  44. data/ext/kb.cpp +79 -0
  45. data/ext/page.cpp +107 -0
  46. data/ext/page.h +51 -0
  47. data/ext/pipe.cpp +347 -0
  48. data/ext/project.h +157 -0
  49. data/ext/rubymain.cpp +1215 -0
  50. data/ext/sigs.cpp +89 -0
  51. data/ext/sigs.h +32 -0
  52. data/ext/ssl.cpp +460 -0
  53. data/ext/ssl.h +94 -0
  54. data/java/.classpath +8 -0
  55. data/java/.project +17 -0
  56. data/java/src/com/rubyeventmachine/EmReactor.java +571 -0
  57. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  58. data/java/src/com/rubyeventmachine/EventableChannel.java +69 -0
  59. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +189 -0
  60. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
  61. data/java/src/com/rubyeventmachine/application/Application.java +194 -0
  62. data/java/src/com/rubyeventmachine/application/Connection.java +74 -0
  63. data/java/src/com/rubyeventmachine/application/ConnectionFactory.java +37 -0
  64. data/java/src/com/rubyeventmachine/application/DefaultConnectionFactory.java +46 -0
  65. data/java/src/com/rubyeventmachine/application/PeriodicTimer.java +38 -0
  66. data/java/src/com/rubyeventmachine/application/Timer.java +54 -0
  67. data/java/src/com/rubyeventmachine/tests/ApplicationTest.java +109 -0
  68. data/java/src/com/rubyeventmachine/tests/ConnectTest.java +148 -0
  69. data/java/src/com/rubyeventmachine/tests/EMTest.java +80 -0
  70. data/java/src/com/rubyeventmachine/tests/TestDatagrams.java +53 -0
  71. data/java/src/com/rubyeventmachine/tests/TestServers.java +75 -0
  72. data/java/src/com/rubyeventmachine/tests/TestTimers.java +90 -0
  73. data/lib/em/buftok.rb +138 -0
  74. data/lib/em/callback.rb +26 -0
  75. data/lib/em/channel.rb +57 -0
  76. data/lib/em/connection.rb +569 -0
  77. data/lib/em/deferrable.rb +206 -0
  78. data/lib/em/file_watch.rb +54 -0
  79. data/lib/em/future.rb +61 -0
  80. data/lib/em/iterator.rb +270 -0
  81. data/lib/em/messages.rb +66 -0
  82. data/lib/em/process_watch.rb +44 -0
  83. data/lib/em/processes.rb +119 -0
  84. data/lib/em/protocols.rb +36 -0
  85. data/lib/em/protocols/header_and_content.rb +138 -0
  86. data/lib/em/protocols/httpclient.rb +276 -0
  87. data/lib/em/protocols/httpclient2.rb +590 -0
  88. data/lib/em/protocols/line_and_text.rb +125 -0
  89. data/lib/em/protocols/linetext2.rb +161 -0
  90. data/lib/em/protocols/memcache.rb +323 -0
  91. data/lib/em/protocols/object_protocol.rb +45 -0
  92. data/lib/em/protocols/postgres3.rb +247 -0
  93. data/lib/em/protocols/saslauth.rb +175 -0
  94. data/lib/em/protocols/smtpclient.rb +357 -0
  95. data/lib/em/protocols/smtpserver.rb +640 -0
  96. data/lib/em/protocols/socks4.rb +66 -0
  97. data/lib/em/protocols/stomp.rb +200 -0
  98. data/lib/em/protocols/tcptest.rb +53 -0
  99. data/lib/em/pure_ruby.rb +1019 -0
  100. data/lib/em/queue.rb +62 -0
  101. data/lib/em/spawnable.rb +85 -0
  102. data/lib/em/streamer.rb +130 -0
  103. data/lib/em/tick_loop.rb +85 -0
  104. data/lib/em/timers.rb +57 -0
  105. data/lib/em/version.rb +3 -0
  106. data/lib/eventmachine.rb +1540 -0
  107. data/lib/evma.rb +32 -0
  108. data/lib/evma/callback.rb +32 -0
  109. data/lib/evma/container.rb +75 -0
  110. data/lib/evma/factory.rb +77 -0
  111. data/lib/evma/protocol.rb +87 -0
  112. data/lib/evma/reactor.rb +48 -0
  113. data/lib/jeventmachine.rb +257 -0
  114. data/setup.rb +1585 -0
  115. data/tasks/cpp.rake_example +77 -0
  116. data/tests/client.crt +31 -0
  117. data/tests/client.key +51 -0
  118. data/tests/test_attach.rb +136 -0
  119. data/tests/test_basic.rb +249 -0
  120. data/tests/test_channel.rb +63 -0
  121. data/tests/test_connection_count.rb +35 -0
  122. data/tests/test_defer.rb +49 -0
  123. data/tests/test_deferrable.rb +35 -0
  124. data/tests/test_epoll.rb +160 -0
  125. data/tests/test_error_handler.rb +35 -0
  126. data/tests/test_errors.rb +82 -0
  127. data/tests/test_exc.rb +55 -0
  128. data/tests/test_file_watch.rb +49 -0
  129. data/tests/test_futures.rb +198 -0
  130. data/tests/test_get_sock_opt.rb +30 -0
  131. data/tests/test_handler_check.rb +37 -0
  132. data/tests/test_hc.rb +190 -0
  133. data/tests/test_httpclient.rb +227 -0
  134. data/tests/test_httpclient2.rb +154 -0
  135. data/tests/test_inactivity_timeout.rb +50 -0
  136. data/tests/test_kb.rb +60 -0
  137. data/tests/test_ltp.rb +190 -0
  138. data/tests/test_ltp2.rb +317 -0
  139. data/tests/test_next_tick.rb +133 -0
  140. data/tests/test_object_protocol.rb +37 -0
  141. data/tests/test_pause.rb +70 -0
  142. data/tests/test_pending_connect_timeout.rb +48 -0
  143. data/tests/test_process_watch.rb +50 -0
  144. data/tests/test_processes.rb +128 -0
  145. data/tests/test_proxy_connection.rb +144 -0
  146. data/tests/test_pure.rb +134 -0
  147. data/tests/test_queue.rb +44 -0
  148. data/tests/test_running.rb +42 -0
  149. data/tests/test_sasl.rb +72 -0
  150. data/tests/test_send_file.rb +251 -0
  151. data/tests/test_servers.rb +76 -0
  152. data/tests/test_smtpclient.rb +83 -0
  153. data/tests/test_smtpserver.rb +85 -0
  154. data/tests/test_spawn.rb +322 -0
  155. data/tests/test_ssl_args.rb +79 -0
  156. data/tests/test_ssl_methods.rb +50 -0
  157. data/tests/test_ssl_verify.rb +82 -0
  158. data/tests/test_tick_loop.rb +59 -0
  159. data/tests/test_timers.rb +160 -0
  160. data/tests/test_ud.rb +36 -0
  161. data/tests/testem.rb +31 -0
  162. metadata +251 -0
@@ -0,0 +1,90 @@
1
+ /**
2
+ * $Id$
3
+ *
4
+ * Author:: Francis Cianfrocca (gmail: blackhedd)
5
+ * Homepage:: http://rubyeventmachine.com
6
+ * Date:: 15 Jul 2007
7
+ *
8
+ * See EventMachine and EventMachine::Connection for documentation and
9
+ * usage examples.
10
+ *
11
+ *
12
+ *----------------------------------------------------------------------------
13
+ *
14
+ * Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
15
+ * Gmail: blackhedd
16
+ *
17
+ * This program is free software; you can redistribute it and/or modify
18
+ * it under the terms of either: 1) the GNU General Public License
19
+ * as published by the Free Software Foundation; either version 2 of the
20
+ * License, or (at your option) any later version; or 2) Ruby's License.
21
+ *
22
+ * See the file COPYING for complete licensing information.
23
+ *
24
+ *---------------------------------------------------------------------------
25
+ *
26
+ *
27
+ */
28
+
29
+
30
+ package com.rubyeventmachine.tests;
31
+
32
+ import com.rubyeventmachine.*;
33
+ import com.rubyeventmachine.application.*;
34
+ import java.io.*;
35
+
36
+ import org.junit.Assert;
37
+ import org.junit.After;
38
+ import org.junit.AfterClass;
39
+ import org.junit.Before;
40
+ import org.junit.BeforeClass;
41
+ import org.junit.Test;
42
+
43
+
44
+ public class TestTimers {
45
+
46
+ @BeforeClass
47
+ public static void setUpBeforeClass() throws Exception {
48
+ }
49
+
50
+ @AfterClass
51
+ public static void tearDownAfterClass() throws Exception {
52
+ }
53
+
54
+ @Before
55
+ public void setUp() throws Exception {
56
+ }
57
+
58
+ @After
59
+ public void tearDown() throws Exception {
60
+ }
61
+
62
+
63
+
64
+ @Test
65
+ public final void test2() throws IOException {
66
+ Application a = new Application();
67
+ a.addTimer(0, new Timer() {
68
+ public void fire() {
69
+ application.stop();
70
+ }
71
+ });
72
+ a.run();
73
+ Assert.assertEquals (1, 1); // just to make sure the reactor halts.
74
+ }
75
+
76
+ @Test
77
+ public final void test3() throws IOException {
78
+ Application a = new Application();
79
+ a.addTimer (0.1, new PeriodicTimer() {
80
+ int n = 0;
81
+ public void fire() {
82
+ n++;
83
+ if (n == 5)
84
+ application.stop();
85
+ }
86
+ });
87
+ a.run();
88
+ Assert.assertEquals(1, 1);
89
+ }
90
+ }
data/lib/em/buftok.rb ADDED
@@ -0,0 +1,138 @@
1
+ # BufferedTokenizer - Statefully split input data by a specifiable token
2
+ #
3
+ # Authors:: Tony Arcieri, Martin Emde
4
+ #
5
+ #----------------------------------------------------------------------------
6
+ #
7
+ # Copyright (C) 2006-07 by Tony Arcieri and Martin Emde
8
+ #
9
+ # Distributed under the Ruby license (http://www.ruby-lang.org/en/LICENSE.txt)
10
+ #
11
+ #---------------------------------------------------------------------------
12
+ #
13
+
14
+ # (C)2006 Tony Arcieri, Martin Emde
15
+ # Distributed under the Ruby license (http://www.ruby-lang.org/en/LICENSE.txt)
16
+
17
+ # BufferedTokenizer takes a delimiter upon instantiation, or acts line-based
18
+ # by default. It allows input to be spoon-fed from some outside source which
19
+ # receives arbitrary length datagrams which may-or-may-not contain the token
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
31
+
32
+ class BufferedTokenizer
33
+ # New BufferedTokenizers will operate on lines delimited by "\n" by default
34
+ # or allow you to specify any delimiter token you so choose, which will then
35
+ # be used by String#split to tokenize the input data
36
+ def initialize(delimiter = "\n", size_limit = nil)
37
+ # Store the specified delimiter
38
+ @delimiter = delimiter
39
+
40
+ # Store the specified size limitation
41
+ @size_limit = size_limit
42
+
43
+ # The input buffer is stored as an array. This is by far the most efficient
44
+ # approach given language constraints (in C a linked list would be a more
45
+ # appropriate data structure). Segments of input data are stored in a list
46
+ # which is only joined when a token is reached, substantially reducing the
47
+ # number of objects required for the operation.
48
+ @input = []
49
+
50
+ # Size of the input buffer
51
+ @input_size = 0
52
+ end
53
+
54
+ # Extract takes an arbitrary string of input data and returns an array of
55
+ # tokenized entities, provided there were any available to extract. This
56
+ # makes for easy processing of datagrams using a pattern like:
57
+ #
58
+ # tokenizer.extract(data).map { |entity| Decode(entity) }.each do ...
59
+ def extract(data)
60
+ # Extract token-delimited entities from the input string with the split command.
61
+ # There's a bit of craftiness here with the -1 parameter. Normally split would
62
+ # behave no differently regardless of if the token lies at the very end of the
63
+ # input buffer or not (i.e. a literal edge case) Specifying -1 forces split to
64
+ # return "" in this case, meaning that the last entry in the list represents a
65
+ # new segment of data where the token has not been encountered
66
+ entities = data.split @delimiter, -1
67
+
68
+ # Check to see if the buffer has exceeded capacity, if we're imposing a limit
69
+ if @size_limit
70
+ raise 'input buffer full' if @input_size + entities.first.size > @size_limit
71
+ @input_size += entities.first.size
72
+ end
73
+
74
+ # Move the first entry in the resulting array into the input buffer. It represents
75
+ # the last segment of a token-delimited entity unless it's the only entry in the list.
76
+ @input << entities.shift
77
+
78
+ # If the resulting array from the split is empty, the token was not encountered
79
+ # (not even at the end of the buffer). Since we've encountered no token-delimited
80
+ # entities this go-around, return an empty array.
81
+ return [] if entities.empty?
82
+
83
+ # At this point, we've hit a token, or potentially multiple tokens. Now we can bring
84
+ # together all the data we've buffered from earlier calls without hitting a token,
85
+ # and add it to our list of discovered entities.
86
+ entities.unshift @input.join
87
+
88
+ =begin
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.
93
+ # Multi-character token support.
94
+ # Split any tokens that were incomplete on the last iteration buf complete now.
95
+ entities.map! do |e|
96
+ e.split @delimiter, -1
97
+ end
98
+ # Flatten the resulting array. This has the side effect of removing the empty
99
+ # entry at the end that was produced by passing -1 to split. Add it again if
100
+ # necessary.
101
+ if (entities[-1] == [])
102
+ entities.flatten! << []
103
+ else
104
+ entities.flatten!
105
+ end
106
+ =end
107
+
108
+ # Now that we've hit a token, joined the input buffer and added it to the entities
109
+ # list, we can go ahead and clear the input buffer. All of the segments that were
110
+ # stored before the join can now be garbage collected.
111
+ @input.clear
112
+
113
+ # The last entity in the list is not token delimited, however, thanks to the -1
114
+ # passed to split. It represents the beginning of a new list of as-yet-untokenized
115
+ # data, so we add it to the start of the list.
116
+ @input << entities.pop
117
+
118
+ # Set the new input buffer size, provided we're keeping track
119
+ @input_size = @input.first.size if @size_limit
120
+
121
+ # Now we're left with the list of extracted token-delimited entities we wanted
122
+ # in the first place. Hooray!
123
+ entities
124
+ end
125
+
126
+ # Flush the contents of the input buffer, i.e. return the input buffer even though
127
+ # a token has not yet been encountered
128
+ def flush
129
+ buffer = @input.join
130
+ @input.clear
131
+ buffer
132
+ end
133
+
134
+ # Is the buffer empty?
135
+ def empty?
136
+ @input.empty?
137
+ 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
data/lib/em/channel.rb ADDED
@@ -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,569 @@
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
+ # Store signature
38
+ @signature = sig
39
+ # associate_callback_target sig
40
+
41
+ # Call a superclass's #initialize if it has one
42
+ initialize(*args)
43
+
44
+ # post initialize callback
45
+ post_init
46
+
47
+ self
48
+ end
49
+ end
50
+
51
+ # Stubbed initialize so legacy superclasses can safely call super
52
+ #
53
+ def initialize(*args) #:nodoc:
54
+ end
55
+
56
+ # def associate_callback_target(sig) #:nodoc:
57
+ # # no-op for the time being, to match similar no-op in rubymain.cpp
58
+ # end
59
+
60
+ # EventMachine::Connection#post_init is called by the event loop
61
+ # immediately after the network connection has been established,
62
+ # and before resumption of the network loop.
63
+ # This method is generally not called by user code, but is called automatically
64
+ # by the event loop. The base-class implementation is a no-op.
65
+ # This is a very good place to initialize instance variables that will
66
+ # be used throughout the lifetime of the network connection.
67
+ #
68
+ def post_init
69
+ end
70
+
71
+ # EventMachine::Connection#receive_data is called by the event loop
72
+ # whenever data has been received by the network connection.
73
+ # It is never called by user code.
74
+ # receive_data is called with a single parameter, a String containing
75
+ # the network protocol data, which may of course be binary. You will
76
+ # generally redefine this method to perform your own processing of the incoming data.
77
+ #
78
+ # Here's a key point which is essential to understanding the event-driven
79
+ # programming model: <i>EventMachine knows absolutely nothing about the protocol
80
+ # which your code implements.</i> You must not make any assumptions about
81
+ # the size of the incoming data packets, or about their alignment on any
82
+ # particular intra-message or PDU boundaries (such as line breaks).
83
+ # receive_data can and will send you arbitrary chunks of data, with the
84
+ # only guarantee being that the data is presented to your code in the order
85
+ # it was collected from the network. Don't even assume that the chunks of
86
+ # data will correspond to network packets, as EventMachine can and will coalesce
87
+ # several incoming packets into one, to improve performance. The implication for your
88
+ # code is that you generally will need to implement some kind of a state machine
89
+ # in your redefined implementation of receive_data. For a better understanding
90
+ # of this, read through the examples of specific protocol handlers in EventMachine::Protocols
91
+ #
92
+ # The base-class implementation of receive_data (which will be invoked if
93
+ # you don't redefine it) simply prints the size of each incoming data packet
94
+ # to stdout.
95
+ #
96
+ def receive_data data
97
+ puts "............>>>#{data.length}"
98
+ end
99
+
100
+ # #ssl_handshake_completed is called by EventMachine when the SSL/TLS handshake has
101
+ # been completed, as a result of calling #start_tls to initiate SSL/TLS on the connection.
102
+ #
103
+ # This callback exists because #post_init and #connection_completed are <b>not</b> reliable
104
+ # for indicating when an SSL/TLS connection is ready to have it's certificate queried for.
105
+ #
106
+ # See #get_peer_cert for application and example.
107
+ def ssl_handshake_completed
108
+ end
109
+
110
+ # #ssl_verify_peer is called by EventMachine when :verify_peer => true has been passed to #start_tls.
111
+ # It will be called with each certificate in the certificate chain provided by the remote peer.
112
+ # The cert will be passed as a String in PEM format, the same as in #get_peer_cert. It is up to user defined
113
+ # code to perform a check on the certificates. The return value from this callback is used to accept or deny the peer.
114
+ # A return value that is not nil or false triggers acceptance. If the peer is not accepted, the connection
115
+ # will be subsequently closed. See 'tests/test_ssl_verify.rb' for a simple example.
116
+ def ssl_verify_peer(cert)
117
+ end
118
+
119
+ # EventMachine::Connection#unbind is called by the framework whenever a connection
120
+ # (either a server or client connection) is closed. The close can occur because
121
+ # your code intentionally closes it (see close_connection and close_connection_after_writing),
122
+ # because the remote peer closed the connection, or because of a network error.
123
+ # You may not assume that the network connection is still open and able to send or
124
+ # receive data when the callback to unbind is made. This is intended only to give
125
+ # you a chance to clean up associations your code may have made to the connection
126
+ # object while it was open.
127
+ #
128
+ def unbind
129
+ end
130
+
131
+ # EventMachine::Connection#proxy_target_unbound is called by the reactor after attempting
132
+ # to relay incoming data to a descriptor (set as a proxy target descriptor with
133
+ # EventMachine::enable_proxy) that has already been closed.
134
+ def proxy_target_unbound
135
+ end
136
+
137
+ # EventMachine::Connection#proxy_completed is called when the reactor finished proxying all
138
+ # of the requested bytes.
139
+ def proxy_completed
140
+ end
141
+
142
+ # EventMachine::Connection#proxy_incoming_to is called only by user code. It sets up
143
+ # a low-level proxy relay for all data inbound for this connection, to the connection given
144
+ # as the argument. This is essentially just a helper method for enable_proxy.
145
+ # See EventMachine::enable_proxy documentation for details.
146
+ def proxy_incoming_to(conn,bufsize=0)
147
+ EventMachine::enable_proxy(self, conn, bufsize)
148
+ end
149
+
150
+ # Helper method for EventMachine::disable_proxy(self)
151
+ def stop_proxying
152
+ EventMachine::disable_proxy(self)
153
+ end
154
+
155
+ # EventMachine::Connection#close_connection is called only by user code, and never
156
+ # by the event loop. You may call this method against a connection object in any
157
+ # callback handler, whether or not the callback was made against the connection
158
+ # you want to close. close_connection <i>schedules</i> the connection to be closed
159
+ # at the next available opportunity within the event loop. You may not assume that
160
+ # the connection is closed when close_connection returns. In particular, the framework
161
+ # will callback the unbind method for the particular connection at a point shortly
162
+ # after you call close_connection. You may assume that the unbind callback will
163
+ # take place sometime after your call to close_connection completes. In other words,
164
+ # the unbind callback will not re-enter your code "inside" of your call to close_connection.
165
+ # However, it's not guaranteed that a future version of EventMachine will not change
166
+ # this behavior.
167
+ #
168
+ # close_connection will <i>silently discard</i> any outbound data which you have
169
+ # sent to the connection using EventMachine::Connection#send_data but which has not
170
+ # yet been sent across the network. If you want to avoid this behavior, use
171
+ # EventMachine::Connection#close_connection_after_writing.
172
+ #
173
+ def close_connection after_writing = false
174
+ EventMachine::close_connection @signature, after_writing
175
+ end
176
+
177
+ # EventMachine::Connection#detach will remove the given connection from the event loop.
178
+ # The connection's socket remains open and its file descriptor number is returned
179
+ def detach
180
+ EventMachine::detach_fd @signature
181
+ end
182
+
183
+ def get_sock_opt level, option
184
+ EventMachine::get_sock_opt @signature, level, option
185
+ end
186
+
187
+ # EventMachine::Connection#close_connection_after_writing is a variant of close_connection.
188
+ # All of the descriptive comments given for close_connection also apply to
189
+ # close_connection_after_writing, <i>with one exception:</i> If the connection has
190
+ # outbound data sent using send_dat but which has not yet been sent across the network,
191
+ # close_connection_after_writing will schedule the connection to be closed <i>after</i>
192
+ # all of the outbound data has been safely written to the remote peer.
193
+ #
194
+ # Depending on the amount of outgoing data and the speed of the network,
195
+ # considerable time may elapse between your call to close_connection_after_writing
196
+ # and the actual closing of the socket (at which time the unbind callback will be called
197
+ # by the event loop). During this time, you <i>may not</i> call send_data to transmit
198
+ # additional data (that is, the connection is closed for further writes). In very
199
+ # rare cases, you may experience a receive_data callback after your call to close_connection_after_writing,
200
+ # depending on whether incoming data was in the process of being received on the connection
201
+ # at the moment when you called close_connection_after_writing. Your protocol handler must
202
+ # be prepared to properly deal with such data (probably by ignoring it).
203
+ #
204
+ def close_connection_after_writing
205
+ close_connection true
206
+ end
207
+
208
+ # EventMachine::Connection#send_data is only called by user code, never by
209
+ # the event loop. You call this method to send data to the remote end of the
210
+ # network connection. send_data is called with a single String argument, which
211
+ # may of course contain binary data. You can call send_data any number of times.
212
+ # send_data is an instance method of an object derived from EventMachine::Connection
213
+ # and containing your mixed-in handler code), so if you call it without qualification
214
+ # within a callback function, the data will be sent to the same network connection
215
+ # that generated the callback. Calling self.send_data is exactly equivalent.
216
+ #
217
+ # You can also call send_data to write to a connection <i>other than the one
218
+ # whose callback you are calling send_data from.</i> This is done by recording
219
+ # the value of the connection in any callback function (the value self), in any
220
+ # variable visible to other callback invocations on the same or different
221
+ # connection objects. (Need an example to make that clear.)
222
+ #
223
+ def send_data data
224
+ data = data.to_s
225
+ size = data.bytesize if data.respond_to?(:bytesize)
226
+ size ||= data.size
227
+ EventMachine::send_data @signature, data, size
228
+ end
229
+
230
+ # Returns true if the connection is in an error state, false otherwise.
231
+ # In general, you can detect the occurrence of communication errors or unexpected
232
+ # disconnection by the remote peer by handing the #unbind method. In some cases, however,
233
+ # it's useful to check the status of the connection using #error? before attempting to send data.
234
+ # This function is synchronous: it will return immediately without blocking.
235
+ #
236
+ #
237
+ def error?
238
+ EventMachine::report_connection_error_status(@signature) != 0
239
+ end
240
+
241
+ # #connection_completed is called by the event loop when a remote TCP connection
242
+ # attempt completes successfully. You can expect to get this notification after calls
243
+ # to EventMachine#connect. Remember that EventMachine makes remote connections
244
+ # asynchronously, just as with any other kind of network event. #connection_completed
245
+ # is intended primarily to assist with network diagnostics. For normal protocol
246
+ # handling, use #post_init to perform initial work on a new connection (such as
247
+ # send an initial set of data).
248
+ # #post_init will always be called. #connection_completed will only be called in case
249
+ # of a successful completion. A connection-attempt which fails will receive a call
250
+ # to #unbind after the failure.
251
+ def connection_completed
252
+ end
253
+
254
+ # Call #start_tls at any point to initiate TLS encryption on connected streams.
255
+ # The method is smart enough to know whether it should perform a server-side
256
+ # or a client-side handshake. An appropriate place to call #start_tls is in
257
+ # your redefined #post_init method, or in the #connection_completed handler for
258
+ # an outbound connection.
259
+ #
260
+ # #start_tls takes an optional parameter hash that allows you to specify certificate
261
+ # and other options to be used with this Connection object. Here are the currently-supported
262
+ # options:
263
+ #
264
+ # * :cert_chain_file :
265
+ # takes a String, which is interpreted as the name of a readable file in the
266
+ # local filesystem. The file is expected to contain a chain of X509 certificates in
267
+ # PEM format, with the most-resolved certificate at the top of the file, successive
268
+ # intermediate certs in the middle, and the root (or CA) cert at the bottom.
269
+ #
270
+ # * :private_key_file :
271
+ # takes a String, which is interpreted as the name of a readable file in the
272
+ # local filesystem. The file must contain a private key in PEM format.
273
+ #
274
+ # * :verify_peer :
275
+ # takes either true or false. Default is false. This indicates whether a server should request a
276
+ # certificate from a peer, to be verified by user code. If true, the #ssl_verify_peer callback
277
+ # on the Connection object is called with each certificate in the certificate chain provided by
278
+ # the peer. See documentation on #ssl_verify_peer for how to use this.
279
+ #
280
+ # === Usage example:
281
+ #
282
+ # require 'rubygems'
283
+ # require 'eventmachine'
284
+ #
285
+ # module Handler
286
+ # def post_init
287
+ # start_tls(:private_key_file => '/tmp/server.key', :cert_chain_file => '/tmp/server.crt', :verify_peer => false)
288
+ # end
289
+ # end
290
+ #
291
+ # EM.run {
292
+ # EM.start_server("127.0.0.1", 9999, Handler)
293
+ # }
294
+ #
295
+ #--
296
+ # TODO: support passing an encryption parameter, which can be string or Proc, to get a passphrase
297
+ # for encrypted private keys.
298
+ # TODO: support passing key material via raw strings or Procs that return strings instead of
299
+ # just filenames.
300
+ # What will get nasty is whether we have to define a location for storing this stuff as files.
301
+ # In general, the OpenSSL interfaces for dealing with certs and keys in files are much better
302
+ # behaved than the ones for raw chunks of memory.
303
+ #
304
+ def start_tls args={}
305
+ priv_key, cert_chain, verify_peer = args.values_at(:private_key_file, :cert_chain_file, :verify_peer)
306
+
307
+ [priv_key, cert_chain].each do |file|
308
+ next if file.nil? or file.empty?
309
+ raise FileNotFoundException,
310
+ "Could not find #{file} for start_tls" unless File.exists? file
311
+ end
312
+
313
+ EventMachine::set_tls_parms(@signature, priv_key || '', cert_chain || '', verify_peer)
314
+ EventMachine::start_tls @signature
315
+ end
316
+
317
+ # If SSL/TLS is active on the connection, #get_peer_cert returns the remote X509 certificate
318
+ # as a String, in the popular PEM format. This can then be used for arbitrary validation
319
+ # of a peer's certificate in your code.
320
+ #
321
+ # This should be called in/after the #ssl_handshake_completed callback, which indicates
322
+ # that SSL/TLS is active. Using this callback is important, because the certificate may not
323
+ # be available until the time it is executed. Using #post_init or #connection_completed is
324
+ # not adequate, because the SSL handshake may still be taking place.
325
+ #
326
+ # #get_peer_cert will return <b>nil</b> if:
327
+ #
328
+ # * EventMachine is not built with OpenSSL support
329
+ # * SSL/TLS is not active on the connection
330
+ # * SSL/TLS handshake is not yet complete
331
+ # * Remote peer for any other reason has not presented a certificate
332
+ #
333
+ # === Example:
334
+ #
335
+ # module Handler
336
+ #
337
+ # def post_init
338
+ # puts "Starting TLS"
339
+ # start_tls
340
+ # end
341
+ #
342
+ # def ssl_handshake_completed
343
+ # puts get_peer_cert
344
+ # close_connection
345
+ # end
346
+ #
347
+ # def unbind
348
+ # EventMachine::stop_event_loop
349
+ # end
350
+ #
351
+ # end
352
+ #
353
+ # EM.run {
354
+ # EventMachine::connect "mail.google.com", 443, Handler
355
+ # }
356
+ #
357
+ # Output:
358
+ # -----BEGIN CERTIFICATE-----
359
+ # MIIDIjCCAougAwIBAgIQbldpChBPqv+BdPg4iwgN8TANBgkqhkiG9w0BAQUFADBM
360
+ # MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
361
+ # THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0wODA1MDIxNjMyNTRaFw0w
362
+ # OTA1MDIxNjMyNTRaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
363
+ # MRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUgSW5jMRgw
364
+ # FgYDVQQDEw9tYWlsLmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
365
+ # AoGBALlkxdh2QXegdElukCSOV2+8PKiONIS+8Tu9K7MQsYpqtLNC860zwOPQ2NLI
366
+ # 3Zp4jwuXVTrtzGuiqf5Jioh35Ig3CqDXtLyZoypjZUQcq4mlLzHlhIQ4EhSjDmA7
367
+ # Ffw9y3ckSOQgdBQWNLbquHh9AbEUjmhkrYxIqKXeCnRKhv6nAgMBAAGjgecwgeQw
368
+ # KAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUFBwMCBglghkgBhvhCBAEwNgYDVR0f
369
+ # BC8wLTAroCmgJ4YlaHR0cDovL2NybC50aGF3dGUuY29tL1RoYXd0ZVNHQ0NBLmNy
370
+ # bDByBggrBgEFBQcBAQRmMGQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnRoYXd0
371
+ # ZS5jb20wPgYIKwYBBQUHMAKGMmh0dHA6Ly93d3cudGhhd3RlLmNvbS9yZXBvc2l0
372
+ # b3J5L1RoYXd0ZV9TR0NfQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQEF
373
+ # BQADgYEAsRwpLg1dgCR1gYDK185MFGukXMeQFUvhGqF8eT/CjpdvezyKVuz84gSu
374
+ # 6ccMXgcPQZGQN/F4Xug+Q01eccJjRSVfdvR5qwpqCj+6BFl5oiKDBsveSkrmL5dz
375
+ # s2bn7TdTSYKcLeBkjXxDLHGBqLJ6TNCJ3c4/cbbG5JhGvoema94=
376
+ # -----END CERTIFICATE-----
377
+ #
378
+ # You can do whatever you want with the certificate String, such as load it
379
+ # as a certificate object using the OpenSSL library, and check it's fields.
380
+ def get_peer_cert
381
+ EventMachine::get_peer_cert @signature
382
+ end
383
+
384
+
385
+ # send_datagram is for sending UDP messages.
386
+ # This method may be called from any Connection object that refers
387
+ # to an open datagram socket (see EventMachine#open_datagram_socket).
388
+ # The method sends a UDP (datagram) packet containing the data you specify,
389
+ # to a remote peer specified by the IP address and port that you give
390
+ # as parameters to the method.
391
+ # Observe that you may send a zero-length packet (empty string).
392
+ # However, you may not send an arbitrarily-large data packet because
393
+ # your operating system will enforce a platform-specific limit on
394
+ # the size of the outbound packet. (Your kernel
395
+ # will respond in a platform-specific way if you send an overlarge
396
+ # packet: some will send a truncated packet, some will complain, and
397
+ # some will silently drop your request).
398
+ # On LANs, it's usually OK to send datagrams up to about 4000 bytes in length,
399
+ # but to be really safe, send messages smaller than the Ethernet-packet
400
+ # size (typically about 1400 bytes). Some very restrictive WANs
401
+ # will either drop or truncate packets larger than about 500 bytes.
402
+ #--
403
+ # Added the Integer wrapper around the port parameter per suggestion by
404
+ # Matthieu Riou, after he passed a String and spent hours tearing his hair out.
405
+ #
406
+ def send_datagram data, recipient_address, recipient_port
407
+ data = data.to_s
408
+ EventMachine::send_datagram @signature, data, data.length, recipient_address, Integer(recipient_port)
409
+ end
410
+
411
+
412
+ # #get_peername is used with stream-connections to obtain the identity
413
+ # of the remotely-connected peer. If a peername is available, this method
414
+ # returns a sockaddr structure. The method returns nil if no peername is available.
415
+ # You can use Socket.unpack_sockaddr_in and its variants to obtain the
416
+ # values contained in the peername structure returned from #get_peername.
417
+ #
418
+ # require 'socket'
419
+ # module Handler
420
+ # def receive_data data
421
+ # port, ip = Socket.unpack_sockaddr_in(get_peername)
422
+ # puts "got #{data.inspect} from #{ip}:#{port}"
423
+ # end
424
+ # end
425
+ def get_peername
426
+ EventMachine::get_peername @signature
427
+ end
428
+
429
+ # #get_sockname is used with stream-connections to obtain the identity
430
+ # of the local side of the connection. If a local name is available, this method
431
+ # returns a sockaddr structure. The method returns nil if no local name is available.
432
+ # You can use Socket#unpack_sockaddr_in and its variants to obtain the
433
+ # values contained in the local-name structure returned from #get_sockname.
434
+ def get_sockname
435
+ EventMachine::get_sockname @signature
436
+ end
437
+
438
+ # Returns the PID (kernel process identifier) of a subprocess
439
+ # associated with this Connection object. For use with EventMachine#popen
440
+ # and similar methods. Returns nil when there is no meaningful subprocess.
441
+ #--
442
+ #
443
+ def get_pid
444
+ EventMachine::get_subprocess_pid @signature
445
+ end
446
+
447
+ # Returns a subprocess exit status. Only useful for #popen. Call it in your
448
+ # #unbind handler.
449
+ #
450
+ def get_status
451
+ EventMachine::get_subprocess_status @signature
452
+ end
453
+
454
+ # comm_inactivity_timeout returns the current value (float in seconds) of the inactivity-timeout
455
+ # property of network-connection and datagram-socket objects. A nonzero value
456
+ # indicates that the connection or socket will automatically be closed if no read or write
457
+ # activity takes place for at least that number of seconds.
458
+ # A zero value (the default) specifies that no automatic timeout will take place.
459
+ def comm_inactivity_timeout
460
+ EventMachine::get_comm_inactivity_timeout @signature
461
+ end
462
+
463
+ # Alias for #set_comm_inactivity_timeout.
464
+ def comm_inactivity_timeout= value
465
+ self.set_comm_inactivity_timeout value
466
+ end
467
+
468
+ # comm_inactivity_timeout= allows you to set the inactivity-timeout property for
469
+ # a network connection or datagram socket. Specify a non-negative float value in seconds.
470
+ # If the value is greater than zero, the connection or socket will automatically be closed
471
+ # if no read or write activity takes place for at least that number of seconds.
472
+ # Specify a value of zero to indicate that no automatic timeout should take place.
473
+ # Zero is the default value.
474
+ def set_comm_inactivity_timeout value
475
+ EventMachine::set_comm_inactivity_timeout @signature, value.to_f
476
+ end
477
+
478
+ # pending_connect_timeout is the duration after which a TCP connection in the connecting
479
+ # state will fail. It is important to distinguish this value from comm_inactivity_timeout,
480
+ # which looks at how long since data was passed on an already established connection.
481
+ # The value is a float in seconds.
482
+ def pending_connect_timeout
483
+ EventMachine::get_pending_connect_timeout @signature
484
+ end
485
+
486
+ # Alias for #set_pending_connect_timeout.
487
+ def pending_connect_timeout= value
488
+ self.set_pending_connect_timeout value
489
+ end
490
+
491
+ # set_pending_connect_timeout sets the duration after which a TCP connection in a
492
+ # connecting state will fail. Takes a float in seconds.
493
+ def set_pending_connect_timeout value
494
+ EventMachine::set_pending_connect_timeout @signature, value.to_f
495
+ end
496
+
497
+ # Reconnect to a given host/port with the current EventMachine::Connection instance
498
+ def reconnect server, port
499
+ EventMachine::reconnect server, port, self
500
+ end
501
+
502
+
503
+ # Like EventMachine::Connection#send_data, this sends data to the remote end of
504
+ # the network connection. EventMachine::Connection@send_file_data takes a
505
+ # filename as an argument, though, and sends the contents of the file, in one
506
+ # chunk. Contributed by Kirk Haines.
507
+ #
508
+ def send_file_data filename
509
+ EventMachine::send_file_data @signature, filename
510
+ end
511
+
512
+ # Open a file on the filesystem and send it to the remote peer. This returns an
513
+ # object of type EventMachine::Deferrable. The object's callbacks will be executed
514
+ # on the reactor main thread when the file has been completely scheduled for
515
+ # transmission to the remote peer. Its errbacks will be called in case of an error
516
+ # (such as file-not-found). #stream_file_data employs various strategems to achieve
517
+ # the fastest possible performance, balanced against minimum consumption of memory.
518
+ #
519
+ # You can control the behavior of #stream_file_data with the optional arguments parameter.
520
+ # Currently-supported arguments are:
521
+ # :http_chunks, a boolean flag which defaults false. If true, this flag streams the
522
+ # file data in a format compatible with the HTTP chunked-transfer encoding.
523
+ #
524
+ # Warning: this feature has an implicit dependency on an outboard extension,
525
+ # evma_fastfilereader. You must install this extension in order to use #stream_file_data
526
+ # with files larger than a certain size (currently 8192 bytes).
527
+ #
528
+ def stream_file_data filename, args={}
529
+ EventMachine::FileStreamer.new( self, filename, args )
530
+ end
531
+
532
+ # Enable notify_readable callbacks on this connection. Only possible if the connection was created
533
+ # using EM.attach and had notify_readable/notify_writable defined on the handler.
534
+ def notify_readable= mode
535
+ EventMachine::set_notify_readable @signature, mode
536
+ end
537
+
538
+ # Returns true if the connection is being watched for readability.
539
+ def notify_readable?
540
+ EventMachine::is_notify_readable @signature
541
+ end
542
+
543
+ # Enable notify_writable callbacks on this connection. Only possible if the connection was created
544
+ # using EM.attach and had notify_readable/notify_writable defined on the handler.
545
+ def notify_writable= mode
546
+ EventMachine::set_notify_writable @signature, mode
547
+ end
548
+
549
+ # Returns true if the connection is being watched for writability.
550
+ def notify_writable?
551
+ EventMachine::is_notify_writable @signature
552
+ end
553
+
554
+ # Pause a connection so that #send_data and #receive_data events are not fired until #resume is called.
555
+ def pause
556
+ EventMachine::pause_connection @signature
557
+ end
558
+
559
+ # Resume a connection's #send_data and #receive_data events.
560
+ def resume
561
+ EventMachine::resume_connection @signature
562
+ end
563
+
564
+ # True if the connect was paused using #pause.
565
+ def paused?
566
+ EventMachine::connection_paused? @signature
567
+ end
568
+ end
569
+ end