wj_eventmachine 1.3.0.dev.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (180) 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 +2238 -0
  37. data/ext/ed.h +460 -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 +285 -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 +1610 -0
  52. data/ext/ssl.cpp +627 -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 +776 -0
  70. data/lib/em/deferrable.rb +210 -0
  71. data/lib/em/deferrable/pool.rb +2 -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.rb +37 -0
  81. data/lib/em/protocols/header_and_content.rb +138 -0
  82. data/lib/em/protocols/httpclient.rb +303 -0
  83. data/lib/em/protocols/httpclient2.rb +602 -0
  84. data/lib/em/protocols/line_and_text.rb +125 -0
  85. data/lib/em/protocols/line_protocol.rb +33 -0
  86. data/lib/em/protocols/linetext2.rb +179 -0
  87. data/lib/em/protocols/memcache.rb +331 -0
  88. data/lib/em/protocols/object_protocol.rb +46 -0
  89. data/lib/em/protocols/postgres3.rb +246 -0
  90. data/lib/em/protocols/saslauth.rb +175 -0
  91. data/lib/em/protocols/smtpclient.rb +394 -0
  92. data/lib/em/protocols/smtpserver.rb +666 -0
  93. data/lib/em/protocols/socks4.rb +66 -0
  94. data/lib/em/protocols/stomp.rb +205 -0
  95. data/lib/em/protocols/tcptest.rb +54 -0
  96. data/lib/em/pure_ruby.rb +1299 -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 +318 -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 +153 -0
  114. data/tests/em_test_helper.rb +198 -0
  115. data/tests/jruby/test_jeventmachine.rb +38 -0
  116. data/tests/test_attach.rb +199 -0
  117. data/tests/test_basic.rb +321 -0
  118. data/tests/test_channel.rb +75 -0
  119. data/tests/test_completion.rb +178 -0
  120. data/tests/test_connection_count.rb +83 -0
  121. data/tests/test_connection_write.rb +35 -0
  122. data/tests/test_defer.rb +35 -0
  123. data/tests/test_deferrable.rb +35 -0
  124. data/tests/test_epoll.rb +141 -0
  125. data/tests/test_error_handler.rb +38 -0
  126. data/tests/test_exc.rb +37 -0
  127. data/tests/test_file_watch.rb +86 -0
  128. data/tests/test_fork.rb +75 -0
  129. data/tests/test_futures.rb +170 -0
  130. data/tests/test_handler_check.rb +35 -0
  131. data/tests/test_hc.rb +155 -0
  132. data/tests/test_httpclient.rb +238 -0
  133. data/tests/test_httpclient2.rb +132 -0
  134. data/tests/test_idle_connection.rb +31 -0
  135. data/tests/test_inactivity_timeout.rb +102 -0
  136. data/tests/test_io_streamer.rb +47 -0
  137. data/tests/test_ipv4.rb +96 -0
  138. data/tests/test_ipv6.rb +107 -0
  139. data/tests/test_iterator.rb +122 -0
  140. data/tests/test_kb.rb +28 -0
  141. data/tests/test_keepalive.rb +113 -0
  142. data/tests/test_line_protocol.rb +33 -0
  143. data/tests/test_ltp.rb +155 -0
  144. data/tests/test_ltp2.rb +332 -0
  145. data/tests/test_many_fds.rb +21 -0
  146. data/tests/test_next_tick.rb +104 -0
  147. data/tests/test_object_protocol.rb +36 -0
  148. data/tests/test_pause.rb +109 -0
  149. data/tests/test_pending_connect_timeout.rb +52 -0
  150. data/tests/test_pool.rb +196 -0
  151. data/tests/test_process_watch.rb +50 -0
  152. data/tests/test_processes.rb +128 -0
  153. data/tests/test_proxy_connection.rb +180 -0
  154. data/tests/test_pure.rb +156 -0
  155. data/tests/test_queue.rb +64 -0
  156. data/tests/test_resolver.rb +129 -0
  157. data/tests/test_running.rb +14 -0
  158. data/tests/test_sasl.rb +46 -0
  159. data/tests/test_send_file.rb +217 -0
  160. data/tests/test_servers.rb +32 -0
  161. data/tests/test_shutdown_hooks.rb +23 -0
  162. data/tests/test_smtpclient.rb +75 -0
  163. data/tests/test_smtpserver.rb +90 -0
  164. data/tests/test_sock_opt.rb +53 -0
  165. data/tests/test_spawn.rb +290 -0
  166. data/tests/test_ssl_args.rb +41 -0
  167. data/tests/test_ssl_dhparam.rb +57 -0
  168. data/tests/test_ssl_ecdh_curve.rb +57 -0
  169. data/tests/test_ssl_extensions.rb +24 -0
  170. data/tests/test_ssl_methods.rb +31 -0
  171. data/tests/test_ssl_protocols.rb +190 -0
  172. data/tests/test_ssl_verify.rb +52 -0
  173. data/tests/test_stomp.rb +38 -0
  174. data/tests/test_system.rb +46 -0
  175. data/tests/test_threaded_resource.rb +68 -0
  176. data/tests/test_tick_loop.rb +58 -0
  177. data/tests/test_timers.rb +150 -0
  178. data/tests/test_ud.rb +8 -0
  179. data/tests/test_unbind_reason.rb +40 -0
  180. metadata +384 -0
@@ -0,0 +1,394 @@
1
+ #--
2
+ #
3
+ # Author:: Francis Cianfrocca (gmail: blackhedd)
4
+ # Homepage:: http://rubyeventmachine.com
5
+ # Date:: 16 July 2006
6
+ #
7
+ # See EventMachine and EventMachine::Connection for documentation and
8
+ # usage examples.
9
+ #
10
+ #----------------------------------------------------------------------------
11
+ #
12
+ # Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
13
+ # Gmail: blackhedd
14
+ #
15
+ # This program is free software; you can redistribute it and/or modify
16
+ # it under the terms of either: 1) the GNU General Public License
17
+ # as published by the Free Software Foundation; either version 2 of the
18
+ # License, or (at your option) any later version; or 2) Ruby's License.
19
+ #
20
+ # See the file COPYING for complete licensing information.
21
+ #
22
+ #---------------------------------------------------------------------------
23
+ #
24
+ #
25
+
26
+ require 'ostruct'
27
+
28
+ module EventMachine
29
+ module Protocols
30
+
31
+ # Simple SMTP client
32
+ #
33
+ # @example
34
+ # email = EM::Protocols::SmtpClient.send(
35
+ # :domain=>"example.com",
36
+ # :host=>'localhost',
37
+ # :port=>25, # optional, defaults 25
38
+ # :starttls=>true, # use ssl
39
+ # :from=>"sender@example.com",
40
+ # :to=> ["to_1@example.com", "to_2@example.com"],
41
+ # :header=> {"Subject" => "This is a subject line"},
42
+ # :body=> "This is the body of the email"
43
+ # )
44
+ # email.callback{
45
+ # puts 'Email sent!'
46
+ # }
47
+ # email.errback{ |e|
48
+ # puts 'Email failed!'
49
+ # }
50
+ #
51
+ # Sending generated emails (using Mail)
52
+ #
53
+ # mail = Mail.new do
54
+ # from 'alice@example.com'
55
+ # to 'bob@example.com'
56
+ # subject 'This is a test email'
57
+ # body 'Hello, world!'
58
+ # end
59
+ #
60
+ # email = EM::P::SmtpClient.send(
61
+ # :domain=>'example.com',
62
+ # :from=>mail.from.first,
63
+ # :to=>mail.to,
64
+ # :message=>mail.to_s
65
+ # )
66
+ #
67
+ class SmtpClient < Connection
68
+ include EventMachine::Deferrable
69
+ include EventMachine::Protocols::LineText2
70
+
71
+ def initialize
72
+ @succeeded = nil
73
+ @responder = nil
74
+ @code = nil
75
+ @msg = nil
76
+ end
77
+
78
+ # :host => required String
79
+ # a string containing the IP address or host name of the SMTP server to connect to.
80
+ # :port => optional
81
+ # defaults to 25.
82
+ # :domain => required String
83
+ # This is passed as the argument to the EHLO command.
84
+ # :starttls => optional Boolean
85
+ # If it evaluates true, then the client will initiate STARTTLS with
86
+ # the server, and abort the connection if the negotiation doesn't succeed.
87
+ # TODO, need to be able to pass certificate parameters with this option.
88
+ # :auth => optional Hash of auth parameters
89
+ # If not given, then no auth will be attempted.
90
+ # (In that case, the connection will be aborted if the server requires auth.)
91
+ # Specify the hash value :type to determine the auth type, along with additional parameters
92
+ # depending on the type.
93
+ # Currently only :type => :plain is supported. Pass additional parameters :username (String),
94
+ # and :password (either a String or a Proc that will be called at auth-time).
95
+ #
96
+ # @example
97
+ # :auth => {:type=>:plain, :username=>"mickey@disney.com", :password=>"mouse"}
98
+ #
99
+ # :from => required String
100
+ # Specifies the sender of the message. Will be passed as the argument
101
+ # to the MAIL FROM. Do NOT enclose the argument in angle-bracket (<>) characters.
102
+ # The connection will abort if the server rejects the value.
103
+ # :to => required String or Array of Strings
104
+ # The recipient(s) of the message. Do NOT enclose
105
+ # any of the values in angle-brackets (<>) characters. It's NOT a fatal error if one or more
106
+ # recipients are rejected by the server. (Of course, if ALL of them are, the server will most
107
+ # likely trigger an error when we try to send data.) An array of codes containing the status
108
+ # of each requested recipient is available after the call completes. TODO, we should define
109
+ # an overridable stub that will be called on rejection of a recipient or a sender, giving
110
+ # user code the chance to try again or abort the connection.
111
+ #
112
+ # One of either :message, :content, or :header and :body is required:
113
+ #
114
+ # :message => String
115
+ # A valid RFC2822 Internet Message.
116
+ # :content => String
117
+ # Raw data which MUST be in correct SMTP body format, with escaped leading dots and a trailing
118
+ # dot line.
119
+ # :header => String or Hash of values to be transmitted in the header of the message.
120
+ # The hash keys are the names of the headers (do NOT append a trailing colon), and the values
121
+ # are strings containing the header values. TODO, support Arrays of header values, which would
122
+ # cause us to send that specific header line more than once.
123
+ #
124
+ # @example
125
+ # :header => {"Subject" => "Bogus", "CC" => "myboss@example.com"}
126
+ #
127
+ # :body => Optional String or Array of Strings, defaults blank.
128
+ # This will be passed as the body of the email message.
129
+ # TODO, this needs to be significantly beefed up. As currently written, this requires the caller
130
+ # to properly format the input into CRLF-delimited lines of 7-bit characters in the standard
131
+ # SMTP transmission format. We need to be able to automatically convert binary data, and add
132
+ # correct line-breaks to text data.
133
+ #
134
+ # :verbose => Optional.
135
+ # If true, will cause a lot of information (including the server-side of the
136
+ # conversation) to be dumped to $>.
137
+ #
138
+ def self.send args={}
139
+ args[:port] ||= 25
140
+ args[:body] ||= ""
141
+
142
+ =begin
143
+ (I don't think it's possible for EM#connect to throw an exception under normal
144
+ circumstances, so this original code is stubbed out. A connect-failure will result
145
+ in the #unbind method being called without calling #connection_completed.)
146
+ begin
147
+ EventMachine.connect( args[:host], args[:port], self) {|c|
148
+ # According to the EM docs, we will get here AFTER post_init is called.
149
+ c.args = args
150
+ c.set_comm_inactivity_timeout 60
151
+ }
152
+ rescue
153
+ # We'll get here on a connect error. This code mimics the effect
154
+ # of a call to invoke_internal_error. Would be great to DRY this up.
155
+ # (Actually, it may be that we never get here, if EM#connect catches
156
+ # its errors internally.)
157
+ d = EM::DefaultDeferrable.new
158
+ d.set_deferred_status(:failed, {:error=>[:connect, 500, "unable to connect to server"]})
159
+ d
160
+ end
161
+ =end
162
+ EventMachine.connect( args[:host], args[:port], self) {|c|
163
+ # According to the EM docs, we will get here AFTER post_init is called.
164
+ c.args = args
165
+ c.set_comm_inactivity_timeout 60
166
+ }
167
+ end
168
+
169
+ attr_writer :args
170
+
171
+ # @private
172
+ def post_init
173
+ @return_values = OpenStruct.new
174
+ @return_values.start_time = Time.now
175
+ end
176
+
177
+ # @private
178
+ def connection_completed
179
+ @responder = :receive_signon
180
+ @msg = []
181
+ end
182
+
183
+ # We can get here in a variety of ways, all of them being failures unless
184
+ # the @succeeded flag is set. If a protocol success was recorded, then don't
185
+ # set a deferred success because the caller will already have done it
186
+ # (no need to wait until the connection closes to invoke the callbacks).
187
+ #
188
+ # @private
189
+ def unbind
190
+ unless @succeeded
191
+ @return_values.elapsed_time = Time.now - @return_values.start_time
192
+ @return_values.responder = @responder
193
+ @return_values.code = @code
194
+ @return_values.message = @msg
195
+ set_deferred_status(:failed, @return_values)
196
+ end
197
+ end
198
+
199
+ # @private
200
+ def receive_line ln
201
+ $>.puts ln if @args[:verbose]
202
+ @range = ln[0...1].to_i
203
+ @code = ln[0...3].to_i
204
+ @msg << ln[4..-1]
205
+ unless ln[3...4] == '-'
206
+ $>.puts @responder if @args[:verbose]
207
+ send @responder
208
+ @msg.clear
209
+ end
210
+ end
211
+
212
+ private
213
+
214
+ # We encountered an error from the server and will close the connection.
215
+ # Use the error and message the server returned.
216
+ #
217
+ def invoke_error
218
+ @return_values.elapsed_time = Time.now - @return_values.start_time
219
+ @return_values.responder = @responder
220
+ @return_values.code = @code
221
+ @return_values.message = @msg
222
+ set_deferred_status :failed, @return_values
223
+ send_data "QUIT\r\n"
224
+ close_connection_after_writing
225
+ end
226
+
227
+ # We encountered an error on our side of the protocol and will close the connection.
228
+ # Use an extra-protocol error code (900) and use the message from the caller.
229
+ #
230
+ def invoke_internal_error msg = "???"
231
+ @return_values.elapsed_time = Time.now - @return_values.start_time
232
+ @return_values.responder = @responder
233
+ @return_values.code = 900
234
+ @return_values.message = msg
235
+ set_deferred_status :failed, @return_values
236
+ send_data "QUIT\r\n"
237
+ close_connection_after_writing
238
+ end
239
+
240
+ def send_ehlo
241
+ send_data "EHLO #{@args[:domain]}\r\n"
242
+ end
243
+
244
+ def receive_signon
245
+ return invoke_error unless @range == 2
246
+ send_ehlo
247
+ @responder = :receive_ehlo_response
248
+ end
249
+ def receive_ehlo_response
250
+ return invoke_error unless @range == 2
251
+ @server_caps = @msg
252
+ invoke_starttls
253
+ end
254
+
255
+ def invoke_starttls
256
+ if @args[:starttls]
257
+ # It would be more sociable to first ask if @server_caps contains
258
+ # the string "STARTTLS" before we invoke it, but hey, life's too short.
259
+ send_data "STARTTLS\r\n"
260
+ @responder = :receive_starttls_response
261
+ else
262
+ invoke_auth
263
+ end
264
+ end
265
+ def receive_starttls_response
266
+ return invoke_error unless @range == 2
267
+ start_tls
268
+ invoke_ehlo_over_tls
269
+ end
270
+
271
+ def invoke_ehlo_over_tls
272
+ send_ehlo
273
+ @responder = :receive_ehlo_over_tls_response
274
+ end
275
+ def receive_ehlo_over_tls_response
276
+ return invoke_error unless @range == 2
277
+ invoke_auth
278
+ end
279
+
280
+ # Perform an authentication. If the caller didn't request one, then fall through
281
+ # to the mail-from state.
282
+ def invoke_auth
283
+ if @args[:auth]
284
+ if @args[:auth][:type] == :plain
285
+ psw = @args[:auth][:password]
286
+ if psw.respond_to?(:call)
287
+ psw = psw.call
288
+ end
289
+ #str = Base64::encode64("\0#{@args[:auth][:username]}\0#{psw}").chomp
290
+ str = ["\0#{@args[:auth][:username]}\0#{psw}"].pack("m").gsub(/\n/, '')
291
+ send_data "AUTH PLAIN #{str}\r\n"
292
+ @responder = :receive_auth_response
293
+ else
294
+ return invoke_internal_error("unsupported auth type")
295
+ end
296
+ else
297
+ invoke_mail_from
298
+ end
299
+ end
300
+ def receive_auth_response
301
+ return invoke_error unless @range == 2
302
+ invoke_mail_from
303
+ end
304
+
305
+ def invoke_mail_from
306
+ send_data "MAIL FROM: <#{@args[:from]}>\r\n"
307
+ @responder = :receive_mail_from_response
308
+ end
309
+ def receive_mail_from_response
310
+ return invoke_error unless @range == 2
311
+ invoke_rcpt_to
312
+ end
313
+
314
+ def invoke_rcpt_to
315
+ @rcpt_responses ||= []
316
+ l = @rcpt_responses.length
317
+ to = @args[:to].is_a?(Array) ? @args[:to] : [@args[:to].to_s]
318
+ if l < to.length
319
+ send_data "RCPT TO: <#{to[l]}>\r\n"
320
+ @responder = :receive_rcpt_to_response
321
+ else
322
+ e = @rcpt_responses.select {|rr| rr.last == 2}
323
+ if e and e.length > 0
324
+ invoke_data
325
+ else
326
+ invoke_error
327
+ end
328
+ end
329
+ end
330
+ def receive_rcpt_to_response
331
+ @rcpt_responses << [@code, @msg, @range]
332
+ invoke_rcpt_to
333
+ end
334
+
335
+ def escape_leading_dots(s)
336
+ s.gsub(/^\./, '..')
337
+ end
338
+
339
+ def invoke_data
340
+ send_data "DATA\r\n"
341
+ @responder = :receive_data_response
342
+ end
343
+ def receive_data_response
344
+ return invoke_error unless @range == 3
345
+
346
+ # The data to send can be given in either @args[:message], @args[:content], or the
347
+ # combination of @args[:header] and @args[:body].
348
+ #
349
+ # - @args[:message] (String) MUST be a valid RFC2822 Internet Message
350
+ #
351
+ # - @args[:content] (String) MUST be in correct SMTP body format, with escaped
352
+ # leading dots and a trailing dot line
353
+ #
354
+ # - @args[:header] (Hash or String)
355
+ # - @args[:body] (Array or String)
356
+ if @args[:message]
357
+ send_data escape_leading_dots(@args[:message].to_s)
358
+ send_data "\r\n.\r\n"
359
+ elsif @args[:content]
360
+ send_data @args[:content].to_s
361
+ else
362
+ # The header can be a hash or an array.
363
+ if @args[:header].is_a?(Hash)
364
+ (@args[:header] || {}).each {|k,v| send_data escape_leading_dots("#{k}: #{v}\r\n") }
365
+ else
366
+ send_data escape_leading_dots(@args[:header].to_s)
367
+ end
368
+ send_data "\r\n"
369
+
370
+ if @args[:body].is_a?(Array)
371
+ @args[:body].each {|e| send_data escape_leading_dots(e)}
372
+ else
373
+ send_data escape_leading_dots(@args[:body].to_s)
374
+ end
375
+
376
+ send_data "\r\n.\r\n"
377
+ end
378
+
379
+ @responder = :receive_message_response
380
+ end
381
+ def receive_message_response
382
+ return invoke_error unless @range == 2
383
+ send_data "QUIT\r\n"
384
+ close_connection_after_writing
385
+ @succeeded = true
386
+ @return_values.elapsed_time = Time.now - @return_values.start_time
387
+ @return_values.responder = @responder
388
+ @return_values.code = @code
389
+ @return_values.message = @msg
390
+ set_deferred_status :succeeded, @return_values
391
+ end
392
+ end
393
+ end
394
+ end
@@ -0,0 +1,666 @@
1
+ #--
2
+ #
3
+ # Author:: Francis Cianfrocca (gmail: blackhedd)
4
+ # Homepage:: http://rubyeventmachine.com
5
+ # Date:: 16 July 2006
6
+ #
7
+ # See EventMachine and EventMachine::Connection for documentation and
8
+ # usage examples.
9
+ #
10
+ #----------------------------------------------------------------------------
11
+ #
12
+ # Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
13
+ # Gmail: blackhedd
14
+ #
15
+ # This program is free software; you can redistribute it and/or modify
16
+ # it under the terms of either: 1) the GNU General Public License
17
+ # as published by the Free Software Foundation; either version 2 of the
18
+ # License, or (at your option) any later version; or 2) Ruby's License.
19
+ #
20
+ # See the file COPYING for complete licensing information.
21
+ #
22
+ #---------------------------------------------------------------------------
23
+ #
24
+ #
25
+
26
+ module EventMachine
27
+ module Protocols
28
+
29
+ # This is a protocol handler for the server side of SMTP.
30
+ # It's NOT a complete SMTP server obeying all the semantics of servers conforming to
31
+ # RFC2821. Rather, it uses overridable method stubs to communicate protocol states
32
+ # and data to user code. User code is responsible for doing the right things with the
33
+ # data in order to get complete and correct SMTP server behavior.
34
+ #
35
+ # Simple SMTP server example:
36
+ #
37
+ # class EmailServer < EM::P::SmtpServer
38
+ # def receive_plain_auth(user, pass)
39
+ # true
40
+ # end
41
+ #
42
+ # def get_server_domain
43
+ # "mock.smtp.server.local"
44
+ # end
45
+ #
46
+ # def get_server_greeting
47
+ # "mock smtp server greets you with impunity"
48
+ # end
49
+ #
50
+ # def receive_sender(sender)
51
+ # current.sender = sender
52
+ # true
53
+ # end
54
+ #
55
+ # def receive_recipient(recipient)
56
+ # current.recipient = recipient
57
+ # true
58
+ # end
59
+ #
60
+ # def receive_message
61
+ # current.received = true
62
+ # current.completed_at = Time.now
63
+ #
64
+ # p [:received_email, current]
65
+ # @current = OpenStruct.new
66
+ # true
67
+ # end
68
+ #
69
+ # def receive_ehlo_domain(domain)
70
+ # @ehlo_domain = domain
71
+ # true
72
+ # end
73
+ #
74
+ # def receive_data_command
75
+ # current.data = ""
76
+ # true
77
+ # end
78
+ #
79
+ # def receive_data_chunk(data)
80
+ # current.data << data.join("\n")
81
+ # true
82
+ # end
83
+ #
84
+ # def receive_transaction
85
+ # if @ehlo_domain
86
+ # current.ehlo_domain = @ehlo_domain
87
+ # @ehlo_domain = nil
88
+ # end
89
+ # true
90
+ # end
91
+ #
92
+ # def current
93
+ # @current ||= OpenStruct.new
94
+ # end
95
+ #
96
+ # def self.start(host = 'localhost', port = 1025)
97
+ # require 'ostruct'
98
+ # @server = EM.start_server host, port, self
99
+ # end
100
+ #
101
+ # def self.stop
102
+ # if @server
103
+ # EM.stop_server @server
104
+ # @server = nil
105
+ # end
106
+ # end
107
+ #
108
+ # def self.running?
109
+ # !!@server
110
+ # end
111
+ # end
112
+ #
113
+ # EM.run{ EmailServer.start }
114
+ #
115
+ #--
116
+ # Useful paragraphs in RFC-2821:
117
+ # 4.3.2: Concise list of command-reply sequences, in essence a text representation
118
+ # of the command state-machine.
119
+ #
120
+ # STARTTLS is defined in RFC2487.
121
+ # Observe that there are important rules governing whether a publicly-referenced server
122
+ # (meaning one whose Internet address appears in public MX records) may require the
123
+ # non-optional use of TLS.
124
+ # Non-optional TLS does not apply to EHLO, NOOP, QUIT or STARTTLS.
125
+ class SmtpServer < EventMachine::Connection
126
+ include Protocols::LineText2
127
+
128
+ HeloRegex = /\AHELO\s*/i
129
+ EhloRegex = /\AEHLO\s*/i
130
+ QuitRegex = /\AQUIT/i
131
+ MailFromRegex = /\AMAIL FROM:\s*/i
132
+ RcptToRegex = /\ARCPT TO:\s*/i
133
+ DataRegex = /\ADATA/i
134
+ NoopRegex = /\ANOOP/i
135
+ RsetRegex = /\ARSET/i
136
+ VrfyRegex = /\AVRFY\s+/i
137
+ ExpnRegex = /\AEXPN\s+/i
138
+ HelpRegex = /\AHELP/i
139
+ StarttlsRegex = /\ASTARTTLS/i
140
+ AuthRegex = /\AAUTH\s+/i
141
+
142
+
143
+ # Class variable containing default parameters that can be overridden
144
+ # in application code.
145
+ # Individual objects of this class will make an instance-local copy of
146
+ # the class variable, so that they can be reconfigured on a per-instance
147
+ # basis.
148
+ #
149
+ # Chunksize is the number of data lines we'll buffer before
150
+ # sending them to the application. TODO, make this user-configurable.
151
+ #
152
+ @@parms = {
153
+ :chunksize => 4000,
154
+ :verbose => false
155
+ }
156
+ def self.parms= parms={}
157
+ @@parms.merge!(parms)
158
+ end
159
+
160
+
161
+
162
+ def initialize *args
163
+ super
164
+ @parms = @@parms
165
+ init_protocol_state
166
+ end
167
+
168
+ def parms= parms={}
169
+ @parms.merge!(parms)
170
+ end
171
+
172
+ # In SMTP, the server talks first. But by a (perhaps flawed) axiom in EM,
173
+ # #post_init will execute BEFORE the block passed to #start_server, for any
174
+ # given accepted connection. Since in this class we'll probably be getting
175
+ # a lot of initialization parameters, we want the guts of post_init to
176
+ # run AFTER the application has initialized the connection object. So we
177
+ # use a spawn to schedule the post_init to run later.
178
+ # It's a little weird, I admit. A reasonable alternative would be to set
179
+ # parameters as a class variable and to do that before accepting any connections.
180
+ #
181
+ # OBSOLETE, now we have @@parms. But the spawn is nice to keep as an illustration.
182
+ #
183
+ def post_init
184
+ #send_data "220 #{get_server_greeting}\r\n" (ORIGINAL)
185
+ #(EM.spawn {|x| x.send_data "220 #{x.get_server_greeting}\r\n"}).notify(self)
186
+ (EM.spawn {|x| x.send_server_greeting}).notify(self)
187
+ end
188
+
189
+ def send_server_greeting
190
+ send_data "220 #{get_server_greeting}\r\n"
191
+ end
192
+
193
+ def receive_line ln
194
+ @@parms[:verbose] and $>.puts ">>> #{ln}"
195
+
196
+ return process_data_line(ln) if @state.include?(:data)
197
+ return process_auth_line(ln) if @state.include?(:auth_incomplete)
198
+
199
+ case ln
200
+ when EhloRegex
201
+ process_ehlo $'.dup
202
+ when HeloRegex
203
+ process_helo $'.dup
204
+ when MailFromRegex
205
+ process_mail_from $'.dup
206
+ when RcptToRegex
207
+ process_rcpt_to $'.dup
208
+ when DataRegex
209
+ process_data
210
+ when RsetRegex
211
+ process_rset
212
+ when VrfyRegex
213
+ process_vrfy
214
+ when ExpnRegex
215
+ process_expn
216
+ when HelpRegex
217
+ process_help
218
+ when NoopRegex
219
+ process_noop
220
+ when QuitRegex
221
+ process_quit
222
+ when StarttlsRegex
223
+ process_starttls
224
+ when AuthRegex
225
+ process_auth $'.dup
226
+ else
227
+ process_unknown
228
+ end
229
+ end
230
+
231
+ # TODO - implement this properly, the implementation is a stub!
232
+ def process_help
233
+ send_data "250 Ok, but unimplemented\r\n"
234
+ end
235
+
236
+ # RFC2821, 3.5.3 Meaning of VRFY or EXPN Success Response:
237
+ # A server MUST NOT return a 250 code in response to a VRFY or EXPN
238
+ # command unless it has actually verified the address. In particular,
239
+ # a server MUST NOT return 250 if all it has done is to verify that the
240
+ # syntax given is valid. In that case, 502 (Command not implemented)
241
+ # or 500 (Syntax error, command unrecognized) SHOULD be returned.
242
+ #
243
+ # TODO - implement this properly, the implementation is a stub!
244
+ def process_vrfy
245
+ send_data "502 Command not implemented\r\n"
246
+ end
247
+ # TODO - implement this properly, the implementation is a stub!
248
+ def process_expn
249
+ send_data "502 Command not implemented\r\n"
250
+ end
251
+
252
+ #--
253
+ # This is called at several points to restore the protocol state
254
+ # to a pre-transaction state. In essence, we "forget" having seen
255
+ # any valid command except EHLO and STARTTLS.
256
+ # We also have to callback user code, in case they're keeping track
257
+ # of senders, recipients, and whatnot.
258
+ #
259
+ # We try to follow the convention of avoiding the verb "receive" for
260
+ # internal method names except receive_line (which we inherit), and
261
+ # using only receive_xxx for user-overridable stubs.
262
+ #
263
+ # init_protocol_state is called when we initialize the connection as
264
+ # well as during reset_protocol_state. It does NOT call the user
265
+ # override method. This enables us to promise the users that they
266
+ # won't see the overridable fire except after EHLO and RSET, and
267
+ # after a message has been received. Although the latter may be wrong.
268
+ # The standard may allow multiple DATA segments with the same set of
269
+ # senders and recipients.
270
+ #
271
+ def reset_protocol_state
272
+ init_protocol_state
273
+ s,@state = @state,[]
274
+ @state << :starttls if s.include?(:starttls)
275
+ @state << :ehlo if s.include?(:ehlo)
276
+ receive_transaction
277
+ end
278
+ def init_protocol_state
279
+ @state ||= []
280
+ end
281
+
282
+
283
+ #--
284
+ # EHLO/HELO is always legal, per the standard. On success
285
+ # it always clears buffers and initiates a mail "transaction."
286
+ # Which means that a MAIL FROM must follow.
287
+ #
288
+ # Per the standard, an EHLO/HELO or a RSET "initiates" an email
289
+ # transaction. Thereafter, MAIL FROM must be received before
290
+ # RCPT TO, before DATA. Not sure what this specific ordering
291
+ # achieves semantically, but it does make it easier to
292
+ # implement. We also support user-specified requirements for
293
+ # STARTTLS and AUTH. We make it impossible to proceed to MAIL FROM
294
+ # without fulfilling tls and/or auth, if the user specified either
295
+ # or both as required. We need to check the extension standard
296
+ # for auth to see if a credential is discarded after a RSET along
297
+ # with all the rest of the state. We'll behave as if it is.
298
+ # Now clearly, we can't discard tls after its been negotiated
299
+ # without dropping the connection, so that flag doesn't get cleared.
300
+ #
301
+ def process_ehlo domain
302
+ if receive_ehlo_domain domain
303
+ send_data "250-#{get_server_domain}\r\n"
304
+ if @@parms[:starttls]
305
+ send_data "250-STARTTLS\r\n"
306
+ end
307
+ if @@parms[:auth]
308
+ send_data "250-AUTH PLAIN\r\n"
309
+ end
310
+ send_data "250-NO-SOLICITING\r\n"
311
+ # TODO, size needs to be configurable.
312
+ send_data "250 SIZE 20000000\r\n"
313
+ reset_protocol_state
314
+ @state << :ehlo
315
+ else
316
+ send_data "550 Requested action not taken\r\n"
317
+ end
318
+ end
319
+
320
+ def process_helo domain
321
+ if receive_ehlo_domain domain.dup
322
+ send_data "250 #{get_server_domain}\r\n"
323
+ reset_protocol_state
324
+ @state << :ehlo
325
+ else
326
+ send_data "550 Requested action not taken\r\n"
327
+ end
328
+ end
329
+
330
+ def process_quit
331
+ send_data "221 Ok\r\n"
332
+ close_connection_after_writing
333
+ end
334
+
335
+ def process_noop
336
+ send_data "250 Ok\r\n"
337
+ end
338
+
339
+ def process_unknown
340
+ send_data "500 Unknown command\r\n"
341
+ end
342
+
343
+ #--
344
+ # So far, only AUTH PLAIN is supported but we should do at least LOGIN as well.
345
+ # TODO, support clients that send AUTH PLAIN with no parameter, expecting a 3xx
346
+ # response and a continuation of the auth conversation.
347
+ #
348
+ def process_auth str
349
+ if @state.include?(:auth)
350
+ send_data "503 auth already issued\r\n"
351
+ elsif str =~ /\APLAIN\s?/i
352
+ if $'.length == 0
353
+ # we got a partial response, so let the client know to send the rest
354
+ @state << :auth_incomplete
355
+ send_data("334 \r\n")
356
+ else
357
+ # we got the initial response, so go ahead & process it
358
+ process_auth_line($')
359
+ end
360
+ #elsif str =~ /\ALOGIN\s+/i
361
+ else
362
+ send_data "504 auth mechanism not available\r\n"
363
+ end
364
+ end
365
+
366
+ def process_auth_line(line)
367
+ plain = line.unpack("m").first
368
+ _,user,psw = plain.split("\000")
369
+
370
+ succeeded = proc {
371
+ send_data "235 authentication ok\r\n"
372
+ @state << :auth
373
+ }
374
+ failed = proc {
375
+ send_data "535 invalid authentication\r\n"
376
+ }
377
+ auth = receive_plain_auth user,psw
378
+
379
+ if auth.respond_to?(:callback)
380
+ auth.callback(&succeeded)
381
+ auth.errback(&failed)
382
+ else
383
+ (auth ? succeeded : failed).call
384
+ end
385
+
386
+ @state.delete :auth_incomplete
387
+ end
388
+
389
+ #--
390
+ # Unusually, we can deal with a Deferrable returned from the user application.
391
+ # This was added to deal with a special case in a particular application, but
392
+ # it would be a nice idea to add it to the other user-code callbacks.
393
+ #
394
+ def process_data
395
+ unless @state.include?(:rcpt)
396
+ send_data "503 Operation sequence error\r\n"
397
+ else
398
+ succeeded = proc {
399
+ send_data "354 Send it\r\n"
400
+ @state << :data
401
+ @databuffer = []
402
+ }
403
+ failed = proc {
404
+ send_data "550 Operation failed\r\n"
405
+ }
406
+
407
+ d = receive_data_command
408
+
409
+ if d.respond_to?(:callback)
410
+ d.callback(&succeeded)
411
+ d.errback(&failed)
412
+ else
413
+ (d ? succeeded : failed).call
414
+ end
415
+ end
416
+ end
417
+
418
+ def process_rset
419
+ reset_protocol_state
420
+ receive_reset
421
+ send_data "250 Ok\r\n"
422
+ end
423
+
424
+ def unbind
425
+ connection_ended
426
+ end
427
+
428
+ #--
429
+ # STARTTLS may not be issued before EHLO, or unless the user has chosen
430
+ # to support it.
431
+ #
432
+ # If :starttls_options is present and :starttls is set in the parms
433
+ # pass the options in :starttls_options to start_tls. Do this if you want to use
434
+ # your own certificate
435
+ # e.g. {:cert_chain_file => "/etc/ssl/cert.pem", :private_key_file => "/etc/ssl/private/cert.key"}
436
+
437
+ def process_starttls
438
+ if @@parms[:starttls]
439
+ if @state.include?(:starttls)
440
+ send_data "503 TLS Already negotiated\r\n"
441
+ elsif ! @state.include?(:ehlo)
442
+ send_data "503 EHLO required before STARTTLS\r\n"
443
+ else
444
+ send_data "220 Start TLS negotiation\r\n"
445
+ start_tls(@@parms[:starttls_options] || {})
446
+ @state << :starttls
447
+ end
448
+ else
449
+ process_unknown
450
+ end
451
+ end
452
+
453
+
454
+ #--
455
+ # Requiring TLS is touchy, cf RFC2784.
456
+ # Requiring AUTH seems to be much more reasonable.
457
+ # We don't currently support any notion of deriving an authentication from the TLS
458
+ # negotiation, although that would certainly be reasonable.
459
+ # We DON'T allow MAIL FROM to be given twice.
460
+ # We DON'T enforce all the various rules for validating the sender or
461
+ # the reverse-path (like whether it should be null), and notifying the reverse
462
+ # path in case of delivery problems. All of that is left to the calling application.
463
+ #
464
+ def process_mail_from sender
465
+ if (@@parms[:starttls]==:required and !@state.include?(:starttls))
466
+ send_data "550 This server requires STARTTLS before MAIL FROM\r\n"
467
+ elsif (@@parms[:auth]==:required and !@state.include?(:auth))
468
+ send_data "550 This server requires authentication before MAIL FROM\r\n"
469
+ elsif @state.include?(:mail_from)
470
+ send_data "503 MAIL already given\r\n"
471
+ else
472
+ unless receive_sender sender
473
+ send_data "550 sender is unacceptable\r\n"
474
+ else
475
+ send_data "250 Ok\r\n"
476
+ @state << :mail_from
477
+ end
478
+ end
479
+ end
480
+
481
+ #--
482
+ # Since we require :mail_from to have been seen before we process RCPT TO,
483
+ # we don't need to repeat the tests for TLS and AUTH.
484
+ # Note that we don't remember or do anything else with the recipients.
485
+ # All of that is on the user code.
486
+ # TODO: we should enforce user-definable limits on the total number of
487
+ # recipients per transaction.
488
+ # We might want to make sure that a given recipient is only seen once, but
489
+ # for now we'll let that be the user's problem.
490
+ #
491
+ # User-written code can return a deferrable from receive_recipient.
492
+ #
493
+ def process_rcpt_to rcpt
494
+ unless @state.include?(:mail_from)
495
+ send_data "503 MAIL is required before RCPT\r\n"
496
+ else
497
+ succeeded = proc {
498
+ send_data "250 Ok\r\n"
499
+ @state << :rcpt unless @state.include?(:rcpt)
500
+ }
501
+ failed = proc {
502
+ send_data "550 recipient is unacceptable\r\n"
503
+ }
504
+
505
+ d = receive_recipient rcpt
506
+
507
+ if d.respond_to?(:set_deferred_status)
508
+ d.callback(&succeeded)
509
+ d.errback(&failed)
510
+ else
511
+ (d ? succeeded : failed).call
512
+ end
513
+
514
+ =begin
515
+ unless receive_recipient rcpt
516
+ send_data "550 recipient is unacceptable\r\n"
517
+ else
518
+ send_data "250 Ok\r\n"
519
+ @state << :rcpt unless @state.include?(:rcpt)
520
+ end
521
+ =end
522
+ end
523
+ end
524
+
525
+
526
+ # Send the incoming data to the application one chunk at a time, rather than
527
+ # one line at a time. That lets the application be a little more flexible about
528
+ # storing to disk, etc.
529
+ # Since we clear the chunk array every time we submit it, the caller needs to be
530
+ # aware to do things like dup it if he wants to keep it around across calls.
531
+ #
532
+ # Resets the transaction upon disposition of the incoming message.
533
+ # RFC5321 says this about the MAIL FROM command:
534
+ # "This command tells the SMTP-receiver that a new mail transaction is
535
+ # starting and to reset all its state tables and buffers, including any
536
+ # recipients or mail data."
537
+ #
538
+ # Equivalent behaviour is implemented by resetting after a completed transaction.
539
+ #
540
+ # User-written code can return a Deferrable as a response from receive_message.
541
+ #
542
+ def process_data_line ln
543
+ if ln == "."
544
+ if @databuffer.length > 0
545
+ receive_data_chunk @databuffer
546
+ @databuffer.clear
547
+ end
548
+
549
+
550
+ succeeded = proc {
551
+ send_data "250 Message accepted\r\n"
552
+ reset_protocol_state
553
+ }
554
+ failed = proc {
555
+ send_data "550 Message rejected\r\n"
556
+ reset_protocol_state
557
+ }
558
+ d = receive_message
559
+
560
+ if d.respond_to?(:set_deferred_status)
561
+ d.callback(&succeeded)
562
+ d.errback(&failed)
563
+ else
564
+ (d ? succeeded : failed).call
565
+ end
566
+
567
+ @state -= [:data, :mail_from, :rcpt]
568
+ else
569
+ # slice off leading . if any
570
+ ln.slice!(0...1) if ln[0] == ?.
571
+ @databuffer << ln
572
+ if @databuffer.length > @@parms[:chunksize]
573
+ receive_data_chunk @databuffer
574
+ @databuffer.clear
575
+ end
576
+ end
577
+ end
578
+
579
+
580
+ #------------------------------------------
581
+ # Everything from here on can be overridden in user code.
582
+
583
+ # The greeting returned in the initial connection message to the client.
584
+ def get_server_greeting
585
+ "EventMachine SMTP Server"
586
+ end
587
+ # The domain name returned in the first line of the response to a
588
+ # successful EHLO or HELO command.
589
+ def get_server_domain
590
+ "Ok EventMachine SMTP Server"
591
+ end
592
+
593
+ # A false response from this user-overridable method will cause a
594
+ # 550 error to be returned to the remote client.
595
+ #
596
+ def receive_ehlo_domain domain
597
+ true
598
+ end
599
+
600
+ # Return true or false to indicate that the authentication is acceptable.
601
+ def receive_plain_auth user, password
602
+ true
603
+ end
604
+
605
+ # Receives the argument of the MAIL FROM command. Return false to
606
+ # indicate to the remote client that the sender is not accepted.
607
+ # This can only be successfully called once per transaction.
608
+ #
609
+ def receive_sender sender
610
+ true
611
+ end
612
+
613
+ # Receives the argument of a RCPT TO command. Can be given multiple
614
+ # times per transaction. Return false to reject the recipient.
615
+ #
616
+ def receive_recipient rcpt
617
+ true
618
+ end
619
+
620
+ # Sent when the remote peer issues the RSET command.
621
+ # Since RSET is not allowed to fail (according to the protocol),
622
+ # we ignore any return value from user overrides of this method.
623
+ #
624
+ def receive_reset
625
+ end
626
+
627
+ # Sent when the remote peer has ended the connection.
628
+ #
629
+ def connection_ended
630
+ end
631
+
632
+ # Called when the remote peer sends the DATA command.
633
+ # Returning false will cause us to send a 550 error to the peer.
634
+ # This can be useful for dealing with problems that arise from processing
635
+ # the whole set of sender and recipients.
636
+ #
637
+ def receive_data_command
638
+ true
639
+ end
640
+
641
+ # Sent when data from the remote peer is available. The size can be controlled
642
+ # by setting the :chunksize parameter. This call can be made multiple times.
643
+ # The goal is to strike a balance between sending the data to the application one
644
+ # line at a time, and holding all of a very large message in memory.
645
+ #
646
+ def receive_data_chunk data
647
+ @smtps_msg_size ||= 0
648
+ @smtps_msg_size += data.join.length
649
+ STDERR.write "<#{@smtps_msg_size}>"
650
+ end
651
+
652
+ # Sent after a message has been completely received. User code
653
+ # must return true or false to indicate whether the message has
654
+ # been accepted for delivery.
655
+ def receive_message
656
+ @@parms[:verbose] and $>.puts "Received complete message"
657
+ true
658
+ end
659
+
660
+ # This is called when the protocol state is reset. It happens
661
+ # when the remote client calls EHLO/HELO or RSET.
662
+ def receive_transaction
663
+ end
664
+ end
665
+ end
666
+ end