net-imap 0.6.4.1 → 0.6.8

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 032600f694434b77edab2496c4bff9a7adc5c912301c0a7b386706dfccdc2345
4
- data.tar.gz: 69dd23250cda6c1eb7a9bbeabe10969389c10047f12610d6bec3407d23e16854
3
+ metadata.gz: 9405d034ddfa540378feffe20b4818437ca73913b1d82663cdd56d341ca71553
4
+ data.tar.gz: 2df46e36cdb6fc77aa6c88838ae684f7c800b5a643b985880e95d802e912a2fd
5
5
  SHA512:
6
- metadata.gz: 98ede1ee28c608ceea04bd5a00a114029da96eae454dc222cb046308c625241df423ceac7811322e6f641f3899ba1ca7a7d3f1bbfbf839632d2cf1a01c963c59
7
- data.tar.gz: 810b3514de99b738216d7d49c917a05ee0c73211530bd81fe55540d158736dd7ba84f841d13f6d959b3dca01c3e32d792e500e7ee8f8eb5a2ab6899a53bf095e
6
+ metadata.gz: 554739baaaaa8b0406f729d56447a13d4ced84f33feba90a350851424624483a36765c40f00e34737fe602bd0bd43555a2f480d4f7d9a0af034f791c0c9e0b8a
7
+ data.tar.gz: '06596b9d2da38bbd53dcc0fd990b66b1af5ffbd52af52370b8366188899043f129e63aae7090054090f8a1b29b8e89e7c96402ffc0aa48101d7f95bf09419a96'
data/.simplecov ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ SimpleCov.configure do
4
+ enable_coverage :branch
5
+ enable_coverage :method
6
+ enable_coverage :eval
7
+
8
+ skip "/test/"
9
+ skip "/rakelib/"
10
+ cover "lib/**/*.rb"
11
+
12
+ group "Parser", %w[lib/net/imap/response_parser.rb
13
+ lib/net/imap/response_parser]
14
+
15
+ group "Client", %w[lib/net/imap.rb
16
+ lib/net/imap/connection_state.rb
17
+ lib/net/imap/deprecated_client_options.rb
18
+ lib/net/imap/errors.rb
19
+ lib/net/imap/response_reader.rb]
20
+
21
+ group "Config", %w[lib/net/imap/config.rb
22
+ lib/net/imap/config]
23
+
24
+ group "Data Types", %w[lib/net/imap/flags.rb
25
+ lib/net/imap/sequence_set.rb] +
26
+ [%r{lib/net/imap/\w*_data\.rb},
27
+ %r{lib/net/imap/\w*_result.rb},
28
+ %r{lib/net/imap/data_\w+\.rb}]
29
+
30
+ group "SASL", %w[lib/net/imap/sasl.rb
31
+ lib/net/imap/sasl
32
+ lib/net/imap/sasl_adapter.rb
33
+ lib/net/imap/authenticators.rb]
34
+
35
+ group "StringPrep", %w[lib/net/imap/stringprep.rb
36
+ lib/net/imap/stringprep]
37
+ end
data/Gemfile CHANGED
@@ -13,14 +13,12 @@ gem "irb"
13
13
  gem "rake"
14
14
  gem "rdoc", ">= 7.2.0"
15
15
  gem "test-unit"
16
- gem "test-unit-ruby-core", git: "https://github.com/ruby/test-unit-ruby-core"
16
+ gem "test-unit-ruby-core"
17
17
 
18
18
  gem "benchmark", require: false
19
- gem "benchmark-driver", require: false
19
+ gem "benchmark_driver", require: false
20
20
  gem "vernier", require: false, platform: :mri
21
21
 
22
22
  group :test do
23
- gem "simplecov", require: false, platforms: %i[mri windows]
24
- gem "simplecov-html", require: false, platforms: %i[mri windows]
25
- gem "simplecov-json", require: false, platforms: %i[mri windows]
23
+ gem "simplecov", ">= 1.2.0", require: false, platforms: %i[mri windows]
26
24
  end
data/README.md CHANGED
@@ -26,41 +26,61 @@ Or install it yourself as:
26
26
  ### Connect with TLS to port 993
27
27
 
28
28
  ```ruby
29
- imap = Net::IMAP.new('mail.example.com', ssl: true)
30
- imap.port => 993
31
- imap.tls_verified? => true
32
- case imap.greeting.name
33
- in /OK/i
34
- # The client is connected in the "Not Authenticated" state.
35
- imap.authenticate("PLAIN", "joe_user", "joes_password")
36
- in /PREAUTH/i
37
- # The client is connected in the "Authenticated" state.
29
+ hostname = "mail.example.com"
30
+ username = "user@example.com"
31
+ password = "correct-horse-battery-staple"
32
+
33
+ imap = Net::IMAP.new(hostname, ssl: true)
34
+ imap.authenticate(:plain, username, password)
35
+ ```
36
+
37
+ To authenticate with an OAuth2 access token:
38
+ ```ruby
39
+ if imap.auth_capable?(:OAUTHBEARER)
40
+ imap.authenticate(:OAUTHBEARER, username, oauth2_token)
41
+ elsif imap.auth_capable?(:XOAUTH2)
42
+ imap.authenticate(:XOAUTH2, username, oauth2_token)
43
+ else
44
+ raise "OAuth2 not supported?"
38
45
  end
39
46
  ```
40
47
 
41
- ### List sender and subject of all recent messages in the default mailbox
48
+ ### List sender and subject of recent messages
42
49
 
43
50
  ```ruby
44
51
  imap.examine('INBOX')
45
- imap.search(["RECENT"]).each do |message_id|
46
- envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
47
- puts "#{envelope.from[0].name}: \t#{envelope.subject}"
52
+ search_result = imap.uid_search(["SINCE", Date.today - 7])
53
+ imap.uid_fetch(search_result, "ENVELOPE").each do |fetch_data|
54
+ envelope = fetch_data.envelope
55
+ puts "#{envelope.from.first.name}: \t#{envelope.subject}"
48
56
  end
49
57
  ```
50
58
 
51
- ### Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
59
+ ### Move messages between two dates to another mailbox
52
60
 
53
61
  ```ruby
54
- imap.select('Mail/sent-mail')
55
- if imap.list('Mail/', 'sent-apr03').empty?
56
- imap.create('Mail/sent-apr03')
62
+ source = "Mail/sent-mail"
63
+ destination = "Mail/sent-apr03"
64
+
65
+ # The "BEFORE" and "AFTER" search criteria are not inclusive.
66
+ since = Date.parse("2003-04-01").prev_day
67
+ before = Date.parse("2003-05-01")
68
+
69
+ if imap.list("", destination).empty?
70
+ imap.create(destination)
57
71
  end
58
- imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
59
- if imap.capable?(:move) || imap.capable?(:IMAP4rev2)
60
- imap.move(message_id, "Mail/sent-apr03")
72
+ imap.select(source)
73
+ search_result = imap.uid_search(["SINCE", since, "BEFORE", before])
74
+ if imap.capable?(:MOVE) || imap.capable?(:IMAP4rev2)
75
+ imap.uid_move(search_result, destination)
76
+ else
77
+ # Atomic MOVE is not supported. Copy, delete, and expunge.
78
+ imap.uid_copy(search_result, destination)
79
+ imap.uid_store(search_result, "+FLAGS", [:Deleted])
80
+ if imap.capable?(:UIDPLUS) || imap.capable?(:IMAP4rev2)
81
+ imap.uid_expunge(search_result)
61
82
  else
62
- imap.copy(message_id, "Mail/sent-apr03")
63
- imap.store(message_id, "+FLAGS", [:Deleted])
83
+ # NOTE: This may expunge _other_ deleted messages, too.
64
84
  imap.expunge
65
85
  end
66
86
  end
@@ -68,9 +88,15 @@ end
68
88
 
69
89
  ## Development
70
90
 
71
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
91
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
92
+ `bin/test` to run the tests. You can also run `bin/console` for an interactive
93
+ prompt that will allow you to experiment.
72
94
 
73
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
95
+ To install this gem onto your local machine, run `bundle exec rake install`. To
96
+ release a new version, update the version number in `version.rb`, and then run
97
+ `bundle exec rake release`, which will create a git tag for the version, push
98
+ git commits and tags, and push the `.gem` file to
99
+ [rubygems.org](https://rubygems.org).
74
100
 
75
101
  ## Contributing
76
102
 
data/Rakefile CHANGED
@@ -11,3 +11,64 @@ Rake::TestTask.new(:test) do |t|
11
11
  end
12
12
 
13
13
  task :default => :test
14
+
15
+ desc "Output HTML coverage data report, and error when threshholds aren't met"
16
+ task "test:coverage:report" do
17
+ require "simplecov"
18
+
19
+ SimpleCov.collate "coverage/.resultset.json" do
20
+ formatter SimpleCov::Formatter::HTMLFormatter
21
+
22
+ coverage(:line) do
23
+ minimum 95
24
+
25
+ minimum 98, per: group("Config")
26
+ minimum 97, per: group("StringPrep")
27
+ minimum 97, per: group("SASL")
28
+ minimum 95, per: group("Data Types")
29
+ minimum 94, per: group("Parser")
30
+ minimum 92, per: group("Client")
31
+
32
+ minimum 80, per: :file
33
+ minimum 55, per: "lib/net/imap/search_result.rb"
34
+ end
35
+
36
+ # NOTE: branch coverage varies more widely between ruby versions
37
+ coverage(:branch) do
38
+ # eval branch coverage varies too much between runtime environments
39
+ ignore :eval_generated
40
+
41
+ minimum 80
42
+
43
+ minimum 90, per: group("Data Types")
44
+ minimum 85, per: group("Config")
45
+ minimum 80, per: group("Client")
46
+ minimum 80, per: group("Parser")
47
+ minimum 70, per: group("SASL")
48
+ minimum 70, per: group("StringPrep")
49
+
50
+ minimum 60, per: :file
51
+ minimum 50, per: "lib/net/imap/sasl/authenticators.rb"
52
+ minimum 50, per: "lib/net/imap/config/attr_accessors.rb"
53
+ end
54
+
55
+ coverage(:method) do
56
+ minimum 88
57
+
58
+ minimum 100, per: group("Config")
59
+ minimum 90, per: group("Data Types")
60
+ minimum 90, per: group("StringPrep")
61
+ minimum 85, per: group("Client")
62
+ minimum 80, per: group("Parser")
63
+ minimum 80, per: group("SASL")
64
+
65
+ minimum 65, per: :file
66
+ minimum 60, per: "lib/net/imap/response_parser/parser_utils.rb"
67
+ minimum 55, per: "lib/net/imap/sasl/authenticators.rb"
68
+ minimum 50, per: "lib/net/imap/authenticators.rb"
69
+ minimum 50, per: "lib/net/imap/sasl/anonymous_authenticator.rb"
70
+ minimum 35, per: "lib/net/imap/sasl/protocol_adapters.rb"
71
+ minimum 20, per: "lib/net/imap/response_data.rb"
72
+ end
73
+ end
74
+ end
@@ -15,6 +15,9 @@ module Net
15
15
  case data
16
16
  when nil
17
17
  when String
18
+ if data.include?("\0")
19
+ raise DataFormatError, "String argument contains NULL byte"
20
+ end
18
21
  when Integer
19
22
  # Covers modseq-valzer, which is the largest valid IMAP integer
20
23
  if data.negative?
@@ -55,28 +58,39 @@ module Net
55
58
  end
56
59
  end
57
60
 
61
+ UNQUOTABLE_CHARS = /[\0\r\n]/
62
+ ASTRING_SPECIALS = /[(){ \x00-\x1f\x7f%*"\\]/
63
+ private_constant :UNQUOTABLE_CHARS, :ASTRING_SPECIALS
64
+
65
+ # Sends generic strings formatted as +astring+:
66
+ # * as an atom (note: this is based on +ASTRING-CHAR+, not +ATOM-CHAR+)
67
+ # * as a quoted string
68
+ # * as a literal (may send non-synchronizing)
69
+ #
70
+ # NOTE: This does not validate that +str+ contains no +NULL+ bytes.
58
71
  def send_string_data(str, tag = nil)
59
72
  if str.empty?
73
+ # same as send_quoted_string(str), but incompatible encoding is allowed
60
74
  put_string('""')
61
- elsif str.match?(/[\r\n]/n)
62
- # literal, because multiline
63
- send_literal(str, tag)
64
- elsif !str.ascii_only?
65
- if @utf8_strings
66
- # quoted string
67
- send_quoted_string(str)
68
- else
69
- # literal, because of non-ASCII bytes
70
- send_literal(str, tag)
71
- end
72
- elsif str.match?(/[(){ \x00-\x1f\x7f%*"\\]/n)
73
- # quoted string
75
+ elsif str.ascii_only? && !str.match?(ASTRING_SPECIALS)
76
+ # valid +astring+ atom: non-empty, ASCII only, no ASTRING_SPECIALS
77
+ put_string(str)
78
+ elsif text_encodable?(str) && !str.match?(UNQUOTABLE_CHARS)
74
79
  send_quoted_string(str)
75
80
  else
76
- put_string(str)
81
+ send_literal(str, tag)
77
82
  end
78
83
  end
79
84
 
85
+ # Encodable as +text+ (which is a superset of +quoted+):
86
+ # * ASCII only (for any ASCII compatible encoding)
87
+ # * or valid UTF-8 (when the connection supports it)
88
+ def text_encodable?(str)
89
+ str.ascii_only? || (utf8_enabled? &&
90
+ str.encoding == Encoding::UTF_8 &&
91
+ str.valid_encoding?)
92
+ end
93
+
80
94
  def send_quoted_string(str) = QuotedString.new(data: str).send_data(self)
81
95
 
82
96
  def send_binary_literal(*, **) = send_literal(*, **, binary: true)
@@ -108,8 +122,7 @@ module Net
108
122
  @continuation_request_exception = nil
109
123
  begin
110
124
  @continuation_request_arrival.wait
111
- e = @continuation_request_exception || @exception
112
- raise e if e
125
+ reraise @continuation_request_exception || @exception
113
126
  put_string(str)
114
127
  ensure
115
128
  @continued_command_tag = nil
@@ -154,6 +167,9 @@ module Net
154
167
  def send_date_data(date) put_string Net::IMAP.encode_date(date) end
155
168
  def send_time_data(time) put_string Net::IMAP.encode_time(time) end
156
169
 
170
+ # NOTE: Currently for internal use only. The API is expected to change.
171
+ Command = Data.define(:tag, :name) # :nodoc:
172
+
157
173
  CommandData = Data.define(:data) do # :nodoc:
158
174
  def self.validate(...)
159
175
  data = new(...)
@@ -249,28 +265,42 @@ module Net
249
265
  def self.split(data)
250
266
  data = data.b # dups and ensures BINARY encoding
251
267
  parts = []
252
- while data.match(/(~)?\{(0|[1-9]\d*)(\+)?\}\r\n/n)
253
- text, binary, bytesize, non_sync, data = $`, !!$1, $2, !!$3, $'
268
+ text_start = 0
269
+ while data.match(/(~)?\{(0|[1-9]\d*)(\+)?\}\r\n/n, text_start)
270
+ text, binary, bytesize, non_sync, literal_start =
271
+ data.byteslice(text_start...$~.begin(0)), !!$1, $2, !!$3, $~.end(0)
254
272
  bytesize = NumValidator.coerce_number64 bytesize
273
+ text_start = literal_start + bytesize
255
274
  parts << RawText[text] unless text.empty?
256
- parts << extract_literal(data, binary:, bytesize:, non_sync:)
257
- data.bytesplice(0, bytesize, "")
275
+ parts << extract_literal(data, literal_start, bytesize, binary:, non_sync:)
258
276
  end
259
- parts << RawText[data] unless data.empty?
277
+ parts << RawText[data.byteslice(text_start..)] if text_start < data.bytesize
260
278
  parts
261
279
  end
262
280
 
263
- def self.extract_literal(data, binary:, bytesize:, non_sync:)
264
- if data.bytesize < bytesize
281
+ def self.extract_literal(data, offset, bytesize, binary:, non_sync:)
282
+ remaining = data.bytesize - offset
283
+ if remaining < bytesize
265
284
  raise DataFormatError, "Too few bytes in string for literal, " \
266
- "expected: %s, remaining: %s" % [bytesize, data.bytesize]
285
+ "expected: %s, remaining: %s" % [bytesize, remaining]
267
286
  end
268
- literal = data.byteslice(0, bytesize)
287
+ literal = data.byteslice(offset, bytesize)
269
288
  (binary ? Literal8 : Literal).new(data: literal, non_sync:)
270
289
  end
271
290
  private_class_method :extract_literal
272
291
  end
273
292
 
293
+ # Please note that +ATOM-CHAR+ and +atom+ are not the same as +ASTRING-char+
294
+ # and the atom form of +astring+. +astring+ allows <tt>]</tt>, but +atom+
295
+ # does not.
296
+ #
297
+ # Generic string arguments in Net::IMAP use +astring+, so they will send as
298
+ # atoms even if they contain <tt>]</tt>.
299
+ #
300
+ # This class is used by:
301
+ # * to validate generic symbol arguments, as the superclass of Flag
302
+ # * to validate #enable +capabilities+
303
+ # * to validate #store (and #uid_store) +attr+
274
304
  class Atom < CommandData # :nodoc:
275
305
  def initialize(**)
276
306
  super
@@ -432,7 +462,7 @@ module Net
432
462
  # coerces using +to_s+
433
463
  def string(str)
434
464
  str = str.to_s
435
- if str =~ LITERAL_REGEX
465
+ if str.b.match?(LITERAL_REGEX)
436
466
  Literal.new(str)
437
467
  else
438
468
  QuotedString.new(str)
@@ -58,9 +58,9 @@ module Net
58
58
 
59
59
  private
60
60
 
61
- def initialize_clone(other)
61
+ def initialize_clone(other, **kwargs)
62
62
  super
63
- @data = other.data.clone
63
+ @data = other.data.clone(**kwargs)
64
64
  end
65
65
 
66
66
  def initialize_dup(other)
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../utils"
4
+
3
5
  module Net
4
6
  class IMAP
5
7
  class Config
@@ -28,28 +30,14 @@ module Net
28
30
  end
29
31
  private_class_method :included
30
32
 
31
- if defined?(Ractor.shareable_proc)
32
- def self.safe(&b)
33
- case obj = b.call
34
- when Proc
35
- Ractor.shareable_proc(&obj)
36
- else
37
- Ractor.make_shareable obj
38
- end
39
- end
40
- elsif defined?(Ractor.make_shareable)
41
- def self.safe(&b)
42
- obj = nil.instance_eval(&b).freeze
43
- Ractor.make_shareable obj
44
- end
45
- else
46
- def self.safe(&b) nil.instance_eval(&b).freeze end
47
- end
48
- private_class_method :safe
33
+ extend Utils
49
34
 
50
- Types = Hash.new do |h, type| type => Proc | nil; safe{type} end
51
- Types[:boolean] = Boolean = safe{-> {!!_1}}
52
- Types[Integer] = safe{->{Integer(_1)}}
35
+ Types = Hash.new do |h, type|
36
+ type => Proc | nil
37
+ Utils.shareable{type}
38
+ end
39
+ Types[:boolean] = Boolean = shareable{-> {!!_1}}
40
+ Types[Integer] = shareable{->{Integer(_1)}}
53
41
 
54
42
  def self.attr_accessor(attr, type: nil)
55
43
  type = Types[type] or return
@@ -57,16 +45,16 @@ module Net
57
45
  define_method :"#{attr}?" do send attr end if type == Boolean
58
46
  end
59
47
 
60
- NilOrInteger = safe{->val { Integer val unless val.nil? }}
48
+ NilOrInteger = shareable{->val { Integer val unless val.nil? }}
61
49
 
62
- Enum = ->(*enum) {
63
- safe_enum = safe{enum}
50
+ Enum = shareable{->(*enum) {
51
+ safe_enum = Utils.shareable{enum}
64
52
  expected = -"one of #{safe_enum.map(&:inspect).join(", ")}"
65
- safe{->val {
53
+ Utils.shareable{->val {
66
54
  return val if safe_enum.include?(val)
67
55
  raise ArgumentError, "expected %s, got %p" % [expected, val]
68
56
  }}
69
- }
57
+ }}
70
58
 
71
59
  end
72
60
  end
@@ -120,6 +120,66 @@ module Net
120
120
  #
121
121
  # *NOTE:* Updates to config objects are not synchronized for thread-safety.
122
122
  #
123
+ # == What's here?
124
+ #
125
+ # === \Config attributes
126
+ #
127
+ # ==== Timeouts and other limits
128
+ #
129
+ # * #open_timeout: seconds to wait for connection to open or start TLS
130
+ # * #idle_response_timeout: seconds to wait for +IDLE+ command to complete
131
+ # * max_response_size: Maximum allowed server response size.
132
+ #
133
+ # ==== Server capabilities
134
+ #
135
+ # * #sasl_ir: Controls +SASL-IR+ behavior for Net::IMAP#authenticate.
136
+ # * #enforce_logindisabled: Controls +LOGINDISABLED+ behavior in
137
+ # Net::IMAP#login.
138
+ # * max_non_synchronizing_literal: maximum bytesize for <tt>LITERAL+</tt> /
139
+ # <tt>LITERAL-</tt> non-synchronizing literals.
140
+ #
141
+ # ==== Inherited defaults
142
+ # {Versioned defaults}[rdoc-ref:Net::IMAP@Versioned+defaults] inherit these
143
+ # from ::global and #load_defaults doesn't update them.
144
+ #
145
+ # * #debug (aliased as #debug?): whether debug mode is enabled
146
+ #
147
+ # ==== Backward compatibility
148
+ # These attributes will be removed by some future release.
149
+ #
150
+ # * #responses_without_block: Controls the behavior of Net::IMAP#responses
151
+ # when called without any arguments (+type+ or +block+).
152
+ # * #parser_use_deprecated_uidplus_data: <em>Ignored since +v0.6.0+.</em>
153
+ # * #parser_max_deprecated_uidplus_data_size: <em>Ignored since +v0.6.0+.</em>
154
+ #
155
+ # === Getting a new or existing config
156
+ # * ::global: The global config, used as the default #parent.
157
+ # * ::default: The hardcoded frozen default config, and parent of ::global.
158
+ # * ::version_defaults: Hard-coded frozen default configurations, indexed
159
+ # by version.
160
+ # * ::[]: Returns a config from ::version_defaults or created by ::new.
161
+ # * ::new: Return a new Config which inherits from a given +parent+.
162
+ # * #new: Return a new Config which inherits from +self+.
163
+ #
164
+ # === Updating multiple attributes
165
+ # * #load_defaults: Sets attributes to a given +version+'s default values.
166
+ # * #update: Assigns multiple attribute values to +self+.
167
+ # * #reset: Resets attributes to inherit from #parent.
168
+ #
169
+ # === Exporting multiple attributes
170
+ # * #to_h: Return a hash with all attributes.
171
+ # * #inspect (aliased as #to_s): Returns a string representation of
172
+ # overriden config attributes and the config inheritance chain.
173
+ # * #pretty_print: Used by PP[https://docs.ruby-lang.org/en/master/PP.html]
174
+ # to create a string representation of all config attributes and the
175
+ # inheritance chain.
176
+ #
177
+ # === Inheritance inspection
178
+ # * #parent: Returns the parent config object.
179
+ # * #inherited?: Returns whether all attributes inherit from #parent.
180
+ # * #inherits_defaults?: Returns whether all attributes inherit from a default config.
181
+ # * #overrides?: Returns whether any attributes override the #parent value.
182
+ #
123
183
  class Config
124
184
  # Array of attribute names that are _not_ loaded by #load_defaults.
125
185
  DEFAULT_TO_INHERIT = %i[debug].freeze
@@ -196,7 +256,7 @@ module Net
196
256
  # #load_defaults will not override #debug.
197
257
  attr_accessor :debug, type: :boolean, default: false
198
258
 
199
- # method: debug?
259
+ # :method: debug?
200
260
  # :call-seq: debug? -> boolean
201
261
  #
202
262
  # Alias for #debug
@@ -312,7 +372,7 @@ module Net
312
372
  # * +0.6+: 16 KiB
313
373
  attr_accessor :max_non_synchronizing_literal, type: Integer, defaults: {
314
374
  0.0r => -1,
315
- 0.6r => 16 << 16, # 16 KiB
375
+ 0.6r => 16 << 10, # 16 KiB
316
376
  }
317
377
 
318
378
  # The maximum allowed server response size. When +nil+, there is no limit
@@ -365,7 +425,7 @@ module Net
365
425
  # Prints a warning and returns the mutable responses hash.
366
426
  # <em>This is not thread-safe.</em>
367
427
  #
368
- # [+:frozen_dup+ <em>(planned default for +v0.6+)</em>]
428
+ # [+:frozen_dup+ <em>(default since +v0.6+)</em>]
369
429
  # Returns a frozen copy of the unhandled responses hash, with frozen
370
430
  # array values.
371
431
  #
@@ -279,7 +279,11 @@ module Net
279
279
  #
280
280
  # This is different from UnknownResponseError: the response has been
281
281
  # rejected. Although it may be parsable, the server is forbidden from
282
- # sending it in the current context. The client should automatically
282
+ # sending it in the current context.
283
+ #
284
+ # This could be caused by a bug in the server or in Net::IMAP. Or it
285
+ # might indicate a malicious server, a man-in-the-middle attack, or
286
+ # client-side command injection. So the client should automatically
283
287
  # disconnect, abruptly (without logout).
284
288
  #
285
289
  # Note that InvalidResponseError does not inherit from ResponseError: it
@@ -288,6 +292,67 @@ module Net
288
292
  class InvalidResponseError < Error
289
293
  end
290
294
 
295
+ # Error raised when the server sends a tagged #response that is invalid for
296
+ # the #command #state.
297
+ #
298
+ # This could be caused by a bug in the server or in Net::IMAP. Or it
299
+ # might indicate a malicious server, a man-in-the-middle attack, or
300
+ # client-side command injection, so the client should disconnect
301
+ # automatically and abruptly (without logout).
302
+ class InvalidTaggedResponseError < InvalidResponseError
303
+ # A symbol representing the state of the matching tagged command.
304
+ #
305
+ # +:unknown+::
306
+ # #response does not match any known command (#command will be +nil+).
307
+ # +:unstarted+::
308
+ # Any tagged #response is invalid before #command starts sending.
309
+ # +:incomplete+::
310
+ # A tagged +OK+ #response is invalid before #command is fully sent.
311
+ # +:completed+::
312
+ # Multiple tagged responses were received for the same command.
313
+ #
314
+ # NOTE: Command state is neither anticipated nor remembered indefinitely.
315
+ # +:unknown+ is used before the matching command is called and after the
316
+ # it is forgotten.
317
+ #
318
+ # NOTE: This version of Net::IMAP does not detect or raise an exception
319
+ # for all of these states.
320
+ attr_reader :state
321
+
322
+ # Metadata about the matching IMAP command.
323
+ #
324
+ # Returns +nil+ when #state is +:unknown+.
325
+ #
326
+ # NOTE: The non-nil return type is an unstable API, for debug only. It
327
+ # may be changed by any release, without warning or deprecation.
328
+ attr_reader :command
329
+
330
+ # The TaggedResponse which triggered this error
331
+ attr_reader :response
332
+
333
+ def initialize(state, response:, command: nil)
334
+ response => TaggedResponse[tag:, name: status]
335
+ case [state, status, command]
336
+ in :unknown, _, nil
337
+ in :incomplete, "OK", {tag: ^tag, name:}
338
+ in :unstarted | :completed, _, {tag: ^tag, name:}
339
+ end
340
+ @state, @command, @response = state, command, response
341
+ cmd_desc = name ? "#{state} #{name}" : state
342
+ super "Received tagged #{status} to #{cmd_desc} command (tag=#{tag})"
343
+ rescue NoMatchingPatternError => err
344
+ raise ArgumentError, err.message
345
+ end
346
+
347
+ def detailed_message(**)
348
+ "#{message}.\n" \
349
+ "Disconnecting: This could indicate a malicious server, a " \
350
+ "man-in-the-middle attack, a client-side command injection, or " \
351
+ "a bug in net-imap.\n" \
352
+ "response.data=#{response.data.inspect}"
353
+ end
354
+ end
355
+
291
356
  # Error raised upon an unknown response from the server.
292
357
  #
293
358
  # This is different from InvalidResponseError: the response may be a
@@ -193,11 +193,11 @@ module Net
193
193
  end
194
194
 
195
195
  ##
196
- # method: range
196
+ # :method: range
197
197
  # :call-seq: range -> range
198
198
 
199
199
  ##
200
- # method: results
200
+ # :method: results
201
201
  # :call-seq: results -> sequence set or nil
202
202
 
203
203
  # Converts #results to an array of integers.