eventmachine-le 1.1.0.beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. data/.gitignore +21 -0
  2. data/.yardopts +7 -0
  3. data/GNU +281 -0
  4. data/LICENSE +60 -0
  5. data/README.md +80 -0
  6. data/Rakefile +19 -0
  7. data/eventmachine-le.gemspec +42 -0
  8. data/ext/binder.cpp +124 -0
  9. data/ext/binder.h +46 -0
  10. data/ext/cmain.cpp +841 -0
  11. data/ext/ed.cpp +1995 -0
  12. data/ext/ed.h +424 -0
  13. data/ext/em.cpp +2377 -0
  14. data/ext/em.h +243 -0
  15. data/ext/eventmachine.h +126 -0
  16. data/ext/extconf.rb +166 -0
  17. data/ext/fastfilereader/extconf.rb +94 -0
  18. data/ext/fastfilereader/mapper.cpp +214 -0
  19. data/ext/fastfilereader/mapper.h +59 -0
  20. data/ext/fastfilereader/rubymain.cpp +127 -0
  21. data/ext/kb.cpp +79 -0
  22. data/ext/page.cpp +107 -0
  23. data/ext/page.h +51 -0
  24. data/ext/pipe.cpp +347 -0
  25. data/ext/project.h +155 -0
  26. data/ext/rubymain.cpp +1269 -0
  27. data/ext/ssl.cpp +468 -0
  28. data/ext/ssl.h +94 -0
  29. data/lib/em/buftok.rb +110 -0
  30. data/lib/em/callback.rb +58 -0
  31. data/lib/em/channel.rb +64 -0
  32. data/lib/em/completion.rb +304 -0
  33. data/lib/em/connection.rb +728 -0
  34. data/lib/em/deferrable.rb +210 -0
  35. data/lib/em/deferrable/pool.rb +2 -0
  36. data/lib/em/file_watch.rb +73 -0
  37. data/lib/em/future.rb +61 -0
  38. data/lib/em/iterator.rb +313 -0
  39. data/lib/em/messages.rb +66 -0
  40. data/lib/em/pool.rb +151 -0
  41. data/lib/em/process_watch.rb +45 -0
  42. data/lib/em/processes.rb +123 -0
  43. data/lib/em/protocols.rb +37 -0
  44. data/lib/em/protocols/header_and_content.rb +138 -0
  45. data/lib/em/protocols/httpclient.rb +279 -0
  46. data/lib/em/protocols/httpclient2.rb +600 -0
  47. data/lib/em/protocols/line_and_text.rb +125 -0
  48. data/lib/em/protocols/line_protocol.rb +29 -0
  49. data/lib/em/protocols/linetext2.rb +161 -0
  50. data/lib/em/protocols/memcache.rb +331 -0
  51. data/lib/em/protocols/object_protocol.rb +46 -0
  52. data/lib/em/protocols/postgres3.rb +246 -0
  53. data/lib/em/protocols/saslauth.rb +175 -0
  54. data/lib/em/protocols/smtpclient.rb +365 -0
  55. data/lib/em/protocols/smtpserver.rb +663 -0
  56. data/lib/em/protocols/socks4.rb +66 -0
  57. data/lib/em/protocols/stomp.rb +202 -0
  58. data/lib/em/protocols/tcptest.rb +54 -0
  59. data/lib/em/queue.rb +71 -0
  60. data/lib/em/resolver.rb +195 -0
  61. data/lib/em/spawnable.rb +84 -0
  62. data/lib/em/streamer.rb +118 -0
  63. data/lib/em/threaded_resource.rb +90 -0
  64. data/lib/em/tick_loop.rb +85 -0
  65. data/lib/em/timers.rb +106 -0
  66. data/lib/em/version.rb +3 -0
  67. data/lib/eventmachine-le.rb +10 -0
  68. data/lib/eventmachine.rb +1548 -0
  69. data/rakelib/cpp.rake_example +77 -0
  70. data/rakelib/package.rake +98 -0
  71. data/rakelib/test.rake +8 -0
  72. data/tests/client.crt +31 -0
  73. data/tests/client.key +51 -0
  74. data/tests/em_test_helper.rb +143 -0
  75. data/tests/test_attach.rb +148 -0
  76. data/tests/test_basic.rb +294 -0
  77. data/tests/test_channel.rb +62 -0
  78. data/tests/test_completion.rb +177 -0
  79. data/tests/test_connection_count.rb +33 -0
  80. data/tests/test_defer.rb +18 -0
  81. data/tests/test_deferrable.rb +35 -0
  82. data/tests/test_epoll.rb +134 -0
  83. data/tests/test_error_handler.rb +38 -0
  84. data/tests/test_exc.rb +28 -0
  85. data/tests/test_file_watch.rb +65 -0
  86. data/tests/test_futures.rb +170 -0
  87. data/tests/test_get_sock_opt.rb +37 -0
  88. data/tests/test_handler_check.rb +35 -0
  89. data/tests/test_hc.rb +155 -0
  90. data/tests/test_httpclient.rb +190 -0
  91. data/tests/test_httpclient2.rb +128 -0
  92. data/tests/test_inactivity_timeout.rb +54 -0
  93. data/tests/test_ipv4.rb +125 -0
  94. data/tests/test_ipv6.rb +131 -0
  95. data/tests/test_iterator.rb +110 -0
  96. data/tests/test_kb.rb +34 -0
  97. data/tests/test_line_protocol.rb +33 -0
  98. data/tests/test_ltp.rb +138 -0
  99. data/tests/test_ltp2.rb +288 -0
  100. data/tests/test_next_tick.rb +104 -0
  101. data/tests/test_object_protocol.rb +36 -0
  102. data/tests/test_pause.rb +78 -0
  103. data/tests/test_pending_connect_timeout.rb +52 -0
  104. data/tests/test_pool.rb +196 -0
  105. data/tests/test_process_watch.rb +48 -0
  106. data/tests/test_processes.rb +133 -0
  107. data/tests/test_proxy_connection.rb +168 -0
  108. data/tests/test_pure.rb +88 -0
  109. data/tests/test_queue.rb +50 -0
  110. data/tests/test_resolver.rb +55 -0
  111. data/tests/test_running.rb +14 -0
  112. data/tests/test_sasl.rb +47 -0
  113. data/tests/test_send_file.rb +217 -0
  114. data/tests/test_servers.rb +33 -0
  115. data/tests/test_set_sock_opt.rb +41 -0
  116. data/tests/test_shutdown_hooks.rb +23 -0
  117. data/tests/test_smtpclient.rb +55 -0
  118. data/tests/test_smtpserver.rb +120 -0
  119. data/tests/test_spawn.rb +293 -0
  120. data/tests/test_ssl_args.rb +78 -0
  121. data/tests/test_ssl_methods.rb +48 -0
  122. data/tests/test_ssl_verify.rb +82 -0
  123. data/tests/test_threaded_resource.rb +55 -0
  124. data/tests/test_tick_loop.rb +59 -0
  125. data/tests/test_timers.rb +180 -0
  126. data/tests/test_ud.rb +8 -0
  127. data/tests/test_udp46.rb +53 -0
  128. data/tests/test_unbind_reason.rb +48 -0
  129. metadata +390 -0
@@ -0,0 +1,365 @@
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 mailfactory)
52
+ #
53
+ # mail = MailFactory.new
54
+ # mail.to = 'someone@site.co'
55
+ # mail.from = 'me@site.com'
56
+ # mail.subject = 'hi!'
57
+ # mail.text = 'hello world'
58
+ # mail.html = '<h1>hello world</h1>'
59
+ #
60
+ # email = EM::P::SmtpClient.send(
61
+ # :domain=>'site.com',
62
+ # :from=>mail.from,
63
+ # :to=>mail.to,
64
+ # :content=>"#{mail.to_s}\r\n.\r\n"
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
+ # :header => Required hash of values to be transmitted in the header of the message.
112
+ # The hash keys are the names of the headers (do NOT append a trailing colon), and the values are strings
113
+ # containing the header values. TODO, support Arrays of header values, which would cause us to
114
+ # send that specific header line more than once.
115
+ #
116
+ # @example
117
+ # :header => {"Subject" => "Bogus", "CC" => "myboss@example.com"}
118
+ #
119
+ # :body => Optional string, defaults blank.
120
+ # This will be passed as the body of the email message.
121
+ # TODO, this needs to be significantly beefed up. As currently written, this requires the caller
122
+ # to properly format the input into CRLF-delimited lines of 7-bit characters in the standard
123
+ # SMTP transmission format. We need to be able to automatically convert binary data, and add
124
+ # correct line-breaks to text data. I think the :body parameter should remain as it is, and we
125
+ # should add a :content parameter that contains autoconversions and/or conversion parameters.
126
+ # Then we can check if either :body or :content is present and do the right thing.
127
+ # :content => Optional array or string
128
+ # Alternative to providing header and body, an array or string of raw data which MUST be in
129
+ # correct SMTP body format, including a trailing dot line
130
+ # :verbose => Optional.
131
+ # If true, will cause a lot of information (including the server-side of the
132
+ # conversation) to be dumped to $>.
133
+ #
134
+ def self.send args={}
135
+ args[:port] ||= 25
136
+ args[:body] ||= ""
137
+
138
+ =begin
139
+ (I don't think it's possible for EM#connect to throw an exception under normal
140
+ circumstances, so this original code is stubbed out. A connect-failure will result
141
+ in the #unbind method being called without calling #connection_completed.)
142
+ begin
143
+ EventMachine.connect( args[:host], args[:port], self) {|c|
144
+ # According to the EM docs, we will get here AFTER post_init is called.
145
+ c.args = args
146
+ c.set_comm_inactivity_timeout 60
147
+ }
148
+ rescue
149
+ # We'll get here on a connect error. This code mimics the effect
150
+ # of a call to invoke_internal_error. Would be great to DRY this up.
151
+ # (Actually, it may be that we never get here, if EM#connect catches
152
+ # its errors internally.)
153
+ d = EM::DefaultDeferrable.new
154
+ d.set_deferred_status(:failed, {:error=>[:connect, 500, "unable to connect to server"]})
155
+ d
156
+ end
157
+ =end
158
+ EventMachine.connect( args[:host], args[:port], self) {|c|
159
+ # According to the EM docs, we will get here AFTER post_init is called.
160
+ c.args = args
161
+ c.set_comm_inactivity_timeout 60
162
+ }
163
+ end
164
+
165
+ attr_writer :args
166
+
167
+ # @private
168
+ def post_init
169
+ @return_values = OpenStruct.new
170
+ @return_values.start_time = Time.now
171
+ end
172
+
173
+ # @private
174
+ def connection_completed
175
+ @responder = :receive_signon
176
+ @msg = []
177
+ end
178
+
179
+ # We can get here in a variety of ways, all of them being failures unless
180
+ # the @succeeded flag is set. If a protocol success was recorded, then don't
181
+ # set a deferred success because the caller will already have done it
182
+ # (no need to wait until the connection closes to invoke the callbacks).
183
+ #
184
+ # @private
185
+ def unbind
186
+ unless @succeeded
187
+ @return_values.elapsed_time = Time.now - @return_values.start_time
188
+ @return_values.responder = @responder
189
+ @return_values.code = @code
190
+ @return_values.message = @msg
191
+ set_deferred_status(:failed, @return_values)
192
+ end
193
+ end
194
+
195
+ # @private
196
+ def receive_line ln
197
+ $>.puts ln if @args[:verbose]
198
+ @range = ln[0...1].to_i
199
+ @code = ln[0...3].to_i
200
+ @msg << ln[4..-1]
201
+ unless ln[3...4] == '-'
202
+ $>.puts @responder if @args[:verbose]
203
+ send @responder
204
+ @msg.clear
205
+ end
206
+ end
207
+
208
+ private
209
+
210
+ # We encountered an error from the server and will close the connection.
211
+ # Use the error and message the server returned.
212
+ #
213
+ def invoke_error
214
+ @return_values.elapsed_time = Time.now - @return_values.start_time
215
+ @return_values.responder = @responder
216
+ @return_values.code = @code
217
+ @return_values.message = @msg
218
+ set_deferred_status :failed, @return_values
219
+ send_data "QUIT\r\n"
220
+ close_connection_after_writing
221
+ end
222
+
223
+ # We encountered an error on our side of the protocol and will close the connection.
224
+ # Use an extra-protocol error code (900) and use the message from the caller.
225
+ #
226
+ def invoke_internal_error msg = "???"
227
+ @return_values.elapsed_time = Time.now - @return_values.start_time
228
+ @return_values.responder = @responder
229
+ @return_values.code = 900
230
+ @return_values.message = msg
231
+ set_deferred_status :failed, @return_values
232
+ send_data "QUIT\r\n"
233
+ close_connection_after_writing
234
+ end
235
+
236
+ def receive_signon
237
+ return invoke_error unless @range == 2
238
+ send_data "EHLO #{@args[:domain]}\r\n"
239
+ @responder = :receive_ehlo_response
240
+ end
241
+
242
+ def receive_ehlo_response
243
+ return invoke_error unless @range == 2
244
+ @server_caps = @msg
245
+ invoke_starttls
246
+ end
247
+
248
+ def invoke_starttls
249
+ if @args[:starttls]
250
+ # It would be more sociable to first ask if @server_caps contains
251
+ # the string "STARTTLS" before we invoke it, but hey, life's too short.
252
+ send_data "STARTTLS\r\n"
253
+ @responder = :receive_starttls_response
254
+ else
255
+ invoke_auth
256
+ end
257
+ end
258
+ def receive_starttls_response
259
+ return invoke_error unless @range == 2
260
+ start_tls
261
+ invoke_auth
262
+ end
263
+
264
+ # Perform an authentication. If the caller didn't request one, then fall through
265
+ # to the mail-from state.
266
+ def invoke_auth
267
+ if @args[:auth]
268
+ if @args[:auth][:type] == :plain
269
+ psw = @args[:auth][:password]
270
+ if psw.respond_to?(:call)
271
+ psw = psw.call
272
+ end
273
+ #str = Base64::encode64("\0#{@args[:auth][:username]}\0#{psw}").chomp
274
+ str = ["\0#{@args[:auth][:username]}\0#{psw}"].pack("m").chomp
275
+ send_data "AUTH PLAIN #{str}\r\n"
276
+ @responder = :receive_auth_response
277
+ else
278
+ return invoke_internal_error("unsupported auth type")
279
+ end
280
+ else
281
+ invoke_mail_from
282
+ end
283
+ end
284
+ def receive_auth_response
285
+ return invoke_error unless @range == 2
286
+ invoke_mail_from
287
+ end
288
+
289
+ def invoke_mail_from
290
+ send_data "MAIL FROM: <#{@args[:from]}>\r\n"
291
+ @responder = :receive_mail_from_response
292
+ end
293
+ def receive_mail_from_response
294
+ return invoke_error unless @range == 2
295
+ invoke_rcpt_to
296
+ end
297
+
298
+ def invoke_rcpt_to
299
+ @rcpt_responses ||= []
300
+ l = @rcpt_responses.length
301
+ to = @args[:to].is_a?(Array) ? @args[:to] : [@args[:to].to_s]
302
+ if l < to.length
303
+ send_data "RCPT TO: <#{to[l]}>\r\n"
304
+ @responder = :receive_rcpt_to_response
305
+ else
306
+ e = @rcpt_responses.select {|rr| rr.last == 2}
307
+ if e and e.length > 0
308
+ invoke_data
309
+ else
310
+ invoke_error
311
+ end
312
+ end
313
+ end
314
+ def receive_rcpt_to_response
315
+ @rcpt_responses << [@code, @msg, @range]
316
+ invoke_rcpt_to
317
+ end
318
+
319
+ def invoke_data
320
+ send_data "DATA\r\n"
321
+ @responder = :receive_data_response
322
+ end
323
+ def receive_data_response
324
+ return invoke_error unless @range == 3
325
+
326
+ # The data to send can be given either in @args[:content] (an array or string of raw data
327
+ # which MUST be in correct SMTP body format, including a trailing dot line), or a header and
328
+ # body given in @args[:header] and @args[:body].
329
+ #
330
+ if @args[:content]
331
+ send_data @args[:content].to_s
332
+ else
333
+ # The header can be a hash or an array.
334
+ if @args[:header].is_a?(Hash)
335
+ (@args[:header] || {}).each {|k,v| send_data "#{k}: #{v}\r\n" }
336
+ else
337
+ send_data @args[:header].to_s
338
+ end
339
+ send_data "\r\n"
340
+
341
+ if @args[:body].is_a?(Array)
342
+ @args[:body].each {|e| send_data e}
343
+ else
344
+ send_data @args[:body].to_s
345
+ end
346
+
347
+ send_data "\r\n.\r\n"
348
+ end
349
+
350
+ @responder = :receive_message_response
351
+ end
352
+ def receive_message_response
353
+ return invoke_error unless @range == 2
354
+ send_data "QUIT\r\n"
355
+ close_connection_after_writing
356
+ @succeeded = true
357
+ @return_values.elapsed_time = Time.now - @return_values.start_time
358
+ @return_values.responder = @responder
359
+ @return_values.code = @code
360
+ @return_values.message = @msg
361
+ set_deferred_status :succeeded, @return_values
362
+ end
363
+ end
364
+ end
365
+ end
@@ -0,0 +1,663 @@
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_plain_line(ln) if @state.include?(:auth_plain_incomplete)
198
+ return process_auth_login_line(ln) if @state.include?(:auth_login_incomplete)
199
+
200
+ case ln
201
+ when EhloRegex
202
+ process_ehlo $'.dup
203
+ when HeloRegex
204
+ process_helo $'.dup
205
+ when MailFromRegex
206
+ process_mail_from $'.dup
207
+ when RcptToRegex
208
+ process_rcpt_to $'.dup
209
+ when DataRegex
210
+ process_data
211
+ when RsetRegex
212
+ process_rset
213
+ when VrfyRegex
214
+ process_vrfy
215
+ when ExpnRegex
216
+ process_expn
217
+ when HelpRegex
218
+ process_help
219
+ when NoopRegex
220
+ process_noop
221
+ when QuitRegex
222
+ process_quit
223
+ when StarttlsRegex
224
+ process_starttls
225
+ when AuthRegex
226
+ process_auth $'.dup
227
+ else
228
+ process_unknown
229
+ end
230
+ end
231
+
232
+ # TODO - implement this properly, the implementation is a stub!
233
+ def process_vrfy
234
+ send_data "250 Ok, but unimplemented\r\n"
235
+ end
236
+ # TODO - implement this properly, the implementation is a stub!
237
+ def process_help
238
+ send_data "250 Ok, but unimplemented\r\n"
239
+ end
240
+ # TODO - implement this properly, the implementation is a stub!
241
+ def process_expn
242
+ send_data "250 Ok, but unimplemented\r\n"
243
+ end
244
+
245
+ #--
246
+ # This is called at several points to restore the protocol state
247
+ # to a pre-transaction state. In essence, we "forget" having seen
248
+ # any valid command except EHLO and STARTTLS.
249
+ # We also have to callback user code, in case they're keeping track
250
+ # of senders, recipients, and whatnot.
251
+ #
252
+ # We try to follow the convention of avoiding the verb "receive" for
253
+ # internal method names except receive_line (which we inherit), and
254
+ # using only receive_xxx for user-overridable stubs.
255
+ #
256
+ # init_protocol_state is called when we initialize the connection as
257
+ # well as during reset_protocol_state. It does NOT call the user
258
+ # override method. This enables us to promise the users that they
259
+ # won't see the overridable fire except after EHLO and RSET, and
260
+ # after a message has been received. Although the latter may be wrong.
261
+ # The standard may allow multiple DATA segments with the same set of
262
+ # senders and recipients.
263
+ #
264
+ def reset_protocol_state
265
+ init_protocol_state
266
+ s,@state = @state,[]
267
+ @state << :starttls if s.include?(:starttls)
268
+ @state << :ehlo if s.include?(:ehlo)
269
+ receive_transaction
270
+ end
271
+ def init_protocol_state
272
+ @state ||= []
273
+ end
274
+
275
+
276
+ #--
277
+ # EHLO/HELO is always legal, per the standard. On success
278
+ # it always clears buffers and initiates a mail "transaction."
279
+ # Which means that a MAIL FROM must follow.
280
+ #
281
+ # Per the standard, an EHLO/HELO or a RSET "initiates" an email
282
+ # transaction. Thereafter, MAIL FROM must be received before
283
+ # RCPT TO, before DATA. Not sure what this specific ordering
284
+ # achieves semantically, but it does make it easier to
285
+ # implement. We also support user-specified requirements for
286
+ # STARTTLS and AUTH. We make it impossible to proceed to MAIL FROM
287
+ # without fulfilling tls and/or auth, if the user specified either
288
+ # or both as required. We need to check the extension standard
289
+ # for auth to see if a credential is discarded after a RSET along
290
+ # with all the rest of the state. We'll behave as if it is.
291
+ # Now clearly, we can't discard tls after its been negotiated
292
+ # without dropping the connection, so that flag doesn't get cleared.
293
+ #
294
+ def process_ehlo domain
295
+ if receive_ehlo_domain domain
296
+ send_data "250-#{get_server_domain}\r\n"
297
+ if @@parms[:starttls]
298
+ send_data "250-STARTTLS\r\n"
299
+ end
300
+ if @@parms[:auth]
301
+ send_data "250-AUTH PLAIN\r\n"
302
+ end
303
+ send_data "250-NO-SOLICITING\r\n"
304
+ # TODO, size needs to be configurable.
305
+ send_data "250 SIZE 20000000\r\n"
306
+ reset_protocol_state
307
+ @state << :ehlo
308
+ else
309
+ send_data "550 Requested action not taken\r\n"
310
+ end
311
+ end
312
+
313
+ def process_helo domain
314
+ if receive_ehlo_domain domain.dup
315
+ send_data "250 #{get_server_domain}\r\n"
316
+ reset_protocol_state
317
+ @state << :ehlo
318
+ else
319
+ send_data "550 Requested action not taken\r\n"
320
+ end
321
+ end
322
+
323
+ def process_quit
324
+ send_data "221 Ok\r\n"
325
+ close_connection_after_writing
326
+ end
327
+
328
+ def process_noop
329
+ send_data "250 Ok\r\n"
330
+ end
331
+
332
+ def process_unknown
333
+ send_data "500 Unknown command\r\n"
334
+ end
335
+
336
+ #--
337
+ # So far, only AUTH PLAIN is supported but we should do at least LOGIN as well.
338
+ # TODO, support clients that send AUTH PLAIN with no parameter, expecting a 3xx
339
+ # response and a continuation of the auth conversation.
340
+ #
341
+ def process_auth str
342
+ if @state.include?(:auth)
343
+ send_data "503 auth already issued\r\n"
344
+ elsif str =~ /\APLAIN\s?/i
345
+ if $'.length == 0
346
+ # we got a partial response, so let the client know to send the rest
347
+ @state << :auth_plain_incomplete
348
+ send_data("334 \r\n")
349
+ else
350
+ # we got the initial response, so go ahead & process it
351
+ process_auth_plain_line($')
352
+ end
353
+ elsif str =~ /\ALOGIN\s?/i
354
+ if $'.length == 0
355
+ @state << :auth_login_incomplete
356
+ send_data("334 \r\n")
357
+ else
358
+ process_auth_login_line($')
359
+ end
360
+
361
+ else
362
+ send_data "504 auth mechanism not available\r\n"
363
+ end
364
+ end
365
+
366
+ def process_auth_login_line(line)
367
+ @login_auth ||= []
368
+ @login_auth << line.unpack("m").first
369
+ if @login_auth.size == 2
370
+ process_plain_auth(@login_auth.shift, @login_auth.shift)
371
+ @state.delete :auth_login_incomplete
372
+ else
373
+ send_data("334 \r\n")
374
+ end
375
+ end
376
+
377
+ def process_auth_plain_line(line)
378
+ plain = line.unpack("m").first
379
+ _,user,psw = plain.split("\000")
380
+ process_plain_auth user,psw
381
+ @state.delete :auth_plain_incomplete
382
+ end
383
+
384
+ def process_plain_auth(user, password)
385
+ if receive_plain_auth(user, password)
386
+ send_data "235 authentication ok\r\n"
387
+ @state << :auth
388
+ else
389
+ send_data "535 invalid authentication\r\n"
390
+ end
391
+ end
392
+
393
+ #--
394
+ # Unusually, we can deal with a Deferrable returned from the user application.
395
+ # This was added to deal with a special case in a particular application, but
396
+ # it would be a nice idea to add it to the other user-code callbacks.
397
+ #
398
+ def process_data
399
+ unless @state.include?(:rcpt)
400
+ send_data "503 Operation sequence error\r\n"
401
+ else
402
+ succeeded = proc {
403
+ send_data "354 Send it\r\n"
404
+ @state << :data
405
+ @databuffer = []
406
+ }
407
+ failed = proc {
408
+ send_data "550 Operation failed\r\n"
409
+ }
410
+
411
+ d = receive_data_command
412
+
413
+ if d.respond_to?(:callback)
414
+ d.callback(&succeeded)
415
+ d.errback(&failed)
416
+ else
417
+ (d ? succeeded : failed).call
418
+ end
419
+ end
420
+ end
421
+
422
+ def process_rset
423
+ reset_protocol_state
424
+ receive_reset
425
+ send_data "250 Ok\r\n"
426
+ end
427
+
428
+ def unbind
429
+ connection_ended
430
+ end
431
+
432
+ #--
433
+ # STARTTLS may not be issued before EHLO, or unless the user has chosen
434
+ # to support it.
435
+ # TODO, must support user-supplied certificates.
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
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
+ # DON'T reset the transaction upon disposition of the incoming message.
533
+ # This means another DATA command can be accepted with the same sender and recipients.
534
+ # If the client wants to reset, he can call RSET.
535
+ # Not sure whether the standard requires a transaction-reset at this point, but it
536
+ # appears not to.
537
+ #
538
+ # User-written code can return a Deferrable as a response from receive_message.
539
+ #
540
+ def process_data_line ln
541
+ if ln == "."
542
+ if @databuffer.length > 0
543
+ receive_data_chunk @databuffer
544
+ @databuffer.clear
545
+ end
546
+
547
+
548
+ succeeded = proc {
549
+ send_data "250 Message accepted\r\n"
550
+ }
551
+ failed = proc {
552
+ send_data "550 Message rejected\r\n"
553
+ }
554
+
555
+ d = receive_message
556
+
557
+ if d.respond_to?(:set_deferred_status)
558
+ d.callback(&succeeded)
559
+ d.errback(&failed)
560
+ else
561
+ (d ? succeeded : failed).call
562
+ end
563
+
564
+ @state -= [:data, :mail_from, :rcpt]
565
+ else
566
+ # slice off leading . if any
567
+ ln.slice!(0...1) if ln[0] == 46
568
+ @databuffer << ln
569
+ if @databuffer.length > @@parms[:chunksize]
570
+ receive_data_chunk @databuffer
571
+ @databuffer.clear
572
+ end
573
+ end
574
+ end
575
+
576
+
577
+ #------------------------------------------
578
+ # Everything from here on can be overridden in user code.
579
+
580
+ # The greeting returned in the initial connection message to the client.
581
+ def get_server_greeting
582
+ "EventMachine SMTP Server"
583
+ end
584
+ # The domain name returned in the first line of the response to a
585
+ # successful EHLO or HELO command.
586
+ def get_server_domain
587
+ "Ok EventMachine SMTP Server"
588
+ end
589
+
590
+ # A false response from this user-overridable method will cause a
591
+ # 550 error to be returned to the remote client.
592
+ #
593
+ def receive_ehlo_domain domain
594
+ true
595
+ end
596
+
597
+ # Return true or false to indicate that the authentication is acceptable.
598
+ def receive_plain_auth user, password
599
+ true
600
+ end
601
+
602
+ # Receives the argument of the MAIL FROM command. Return false to
603
+ # indicate to the remote client that the sender is not accepted.
604
+ # This can only be successfully called once per transaction.
605
+ #
606
+ def receive_sender sender
607
+ true
608
+ end
609
+
610
+ # Receives the argument of a RCPT TO command. Can be given multiple
611
+ # times per transaction. Return false to reject the recipient.
612
+ #
613
+ def receive_recipient rcpt
614
+ true
615
+ end
616
+
617
+ # Sent when the remote peer issues the RSET command.
618
+ # Since RSET is not allowed to fail (according to the protocol),
619
+ # we ignore any return value from user overrides of this method.
620
+ #
621
+ def receive_reset
622
+ end
623
+
624
+ # Sent when the remote peer has ended the connection.
625
+ #
626
+ def connection_ended
627
+ end
628
+
629
+ # Called when the remote peer sends the DATA command.
630
+ # Returning false will cause us to send a 550 error to the peer.
631
+ # This can be useful for dealing with problems that arise from processing
632
+ # the whole set of sender and recipients.
633
+ #
634
+ def receive_data_command
635
+ true
636
+ end
637
+
638
+ # Sent when data from the remote peer is available. The size can be controlled
639
+ # by setting the :chunksize parameter. This call can be made multiple times.
640
+ # The goal is to strike a balance between sending the data to the application one
641
+ # line at a time, and holding all of a very large message in memory.
642
+ #
643
+ def receive_data_chunk data
644
+ @smtps_msg_size ||= 0
645
+ @smtps_msg_size += data.join.length
646
+ STDERR.write "<#{@smtps_msg_size}>"
647
+ end
648
+
649
+ # Sent after a message has been completely received. User code
650
+ # must return true or false to indicate whether the message has
651
+ # been accepted for delivery.
652
+ def receive_message
653
+ @@parms[:verbose] and $>.puts "Received complete message"
654
+ true
655
+ end
656
+
657
+ # This is called when the protocol state is reset. It happens
658
+ # when the remote client calls EHLO/HELO or RSET.
659
+ def receive_transaction
660
+ end
661
+ end
662
+ end
663
+ end