PageRenderTime 34ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/net/imap.rb

https://github.com/nazy/ruby
Ruby | 3634 lines | 2383 code | 262 blank | 989 comment | 141 complexity | 8b4186f3253a8f975ec886a732607da3 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0, 0BSD, Unlicense
  1. #
  2. # = net/imap.rb
  3. #
  4. # Copyright (C) 2000 Shugo Maeda <shugo@ruby-lang.org>
  5. #
  6. # This library is distributed under the terms of the Ruby license.
  7. # You can freely distribute/modify this library.
  8. #
  9. # Documentation: Shugo Maeda, with RDoc conversion and overview by William
  10. # Webber.
  11. #
  12. # See Net::IMAP for documentation.
  13. #
  14. require "socket"
  15. require "monitor"
  16. require "digest/md5"
  17. require "strscan"
  18. begin
  19. require "openssl"
  20. rescue LoadError
  21. end
  22. module Net
  23. #
  24. # Net::IMAP implements Internet Message Access Protocol (IMAP) client
  25. # functionality. The protocol is described in [IMAP].
  26. #
  27. # == IMAP Overview
  28. #
  29. # An IMAP client connects to a server, and then authenticates
  30. # itself using either #authenticate() or #login(). Having
  31. # authenticated itself, there is a range of commands
  32. # available to it. Most work with mailboxes, which may be
  33. # arranged in an hierarchical namespace, and each of which
  34. # contains zero or more messages. How this is implemented on
  35. # the server is implementation-dependent; on a UNIX server, it
  36. # will frequently be implemented as a files in mailbox format
  37. # within a hierarchy of directories.
  38. #
  39. # To work on the messages within a mailbox, the client must
  40. # first select that mailbox, using either #select() or (for
  41. # read-only access) #examine(). Once the client has successfully
  42. # selected a mailbox, they enter _selected_ state, and that
  43. # mailbox becomes the _current_ mailbox, on which mail-item
  44. # related commands implicitly operate.
  45. #
  46. # Messages have two sorts of identifiers: message sequence
  47. # numbers, and UIDs.
  48. #
  49. # Message sequence numbers number messages within a mail box
  50. # from 1 up to the number of items in the mail box. If new
  51. # message arrives during a session, it receives a sequence
  52. # number equal to the new size of the mail box. If messages
  53. # are expunged from the mailbox, remaining messages have their
  54. # sequence numbers "shuffled down" to fill the gaps.
  55. #
  56. # UIDs, on the other hand, are permanently guaranteed not to
  57. # identify another message within the same mailbox, even if
  58. # the existing message is deleted. UIDs are required to
  59. # be assigned in ascending (but not necessarily sequential)
  60. # order within a mailbox; this means that if a non-IMAP client
  61. # rearranges the order of mailitems within a mailbox, the
  62. # UIDs have to be reassigned. An IMAP client cannot thus
  63. # rearrange message orders.
  64. #
  65. # == Examples of Usage
  66. #
  67. # === List sender and subject of all recent messages in the default mailbox
  68. #
  69. # imap = Net::IMAP.new('mail.example.com')
  70. # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  71. # imap.examine('INBOX')
  72. # imap.search(["RECENT"]).each do |message_id|
  73. # envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  74. # puts "#{envelope.from[0].name}: \t#{envelope.subject}"
  75. # end
  76. #
  77. # === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
  78. #
  79. # imap = Net::IMAP.new('mail.example.com')
  80. # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  81. # imap.select('Mail/sent-mail')
  82. # if not imap.list('Mail/', 'sent-apr03')
  83. # imap.create('Mail/sent-apr03')
  84. # end
  85. # imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
  86. # imap.copy(message_id, "Mail/sent-apr03")
  87. # imap.store(message_id, "+FLAGS", [:Deleted])
  88. # end
  89. # imap.expunge
  90. #
  91. # == Thread Safety
  92. #
  93. # Net::IMAP supports concurrent threads. For example,
  94. #
  95. # imap = Net::IMAP.new("imap.foo.net", "imap2")
  96. # imap.authenticate("cram-md5", "bar", "password")
  97. # imap.select("inbox")
  98. # fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
  99. # search_result = imap.search(["BODY", "hello"])
  100. # fetch_result = fetch_thread.value
  101. # imap.disconnect
  102. #
  103. # This script invokes the FETCH command and the SEARCH command concurrently.
  104. #
  105. # == Errors
  106. #
  107. # An IMAP server can send three different types of responses to indicate
  108. # failure:
  109. #
  110. # NO:: the attempted command could not be successfully completed. For
  111. # instance, the username/password used for logging in are incorrect;
  112. # the selected mailbox does not exists; etc.
  113. #
  114. # BAD:: the request from the client does not follow the server's
  115. # understanding of the IMAP protocol. This includes attempting
  116. # commands from the wrong client state; for instance, attempting
  117. # to perform a SEARCH command without having SELECTed a current
  118. # mailbox. It can also signal an internal server
  119. # failure (such as a disk crash) has occurred.
  120. #
  121. # BYE:: the server is saying goodbye. This can be part of a normal
  122. # logout sequence, and can be used as part of a login sequence
  123. # to indicate that the server is (for some reason) unwilling
  124. # to accept our connection. As a response to any other command,
  125. # it indicates either that the server is shutting down, or that
  126. # the server is timing out the client connection due to inactivity.
  127. #
  128. # These three error response are represented by the errors
  129. # Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
  130. # Net::IMAP::ByeResponseError, all of which are subclasses of
  131. # Net::IMAP::ResponseError. Essentially, all methods that involve
  132. # sending a request to the server can generate one of these errors.
  133. # Only the most pertinent instances have been documented below.
  134. #
  135. # Because the IMAP class uses Sockets for communication, its methods
  136. # are also susceptible to the various errors that can occur when
  137. # working with sockets. These are generally represented as
  138. # Errno errors. For instance, any method that involves sending a
  139. # request to the server and/or receiving a response from it could
  140. # raise an Errno::EPIPE error if the network connection unexpectedly
  141. # goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2),
  142. # and associated man pages.
  143. #
  144. # Finally, a Net::IMAP::DataFormatError is thrown if low-level data
  145. # is found to be in an incorrect format (for instance, when converting
  146. # between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
  147. # thrown if a server response is non-parseable.
  148. #
  149. #
  150. # == References
  151. #
  152. # [[IMAP]]
  153. # M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
  154. # RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
  155. #
  156. # [[LANGUAGE-TAGS]]
  157. # Alvestrand, H., "Tags for the Identification of
  158. # Languages", RFC 1766, March 1995.
  159. #
  160. # [[MD5]]
  161. # Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
  162. # 1864, October 1995.
  163. #
  164. # [[MIME-IMB]]
  165. # Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
  166. # Mail Extensions) Part One: Format of Internet Message Bodies", RFC
  167. # 2045, November 1996.
  168. #
  169. # [[RFC-822]]
  170. # Crocker, D., "Standard for the Format of ARPA Internet Text
  171. # Messages", STD 11, RFC 822, University of Delaware, August 1982.
  172. #
  173. # [[RFC-2087]]
  174. # Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
  175. #
  176. # [[RFC-2086]]
  177. # Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
  178. #
  179. # [[RFC-2195]]
  180. # Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
  181. # for Simple Challenge/Response", RFC 2195, September 1997.
  182. #
  183. # [[SORT-THREAD-EXT]]
  184. # Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
  185. # Extensions", draft-ietf-imapext-sort, May 2003.
  186. #
  187. # [[OSSL]]
  188. # http://www.openssl.org
  189. #
  190. # [[RSSL]]
  191. # http://savannah.gnu.org/projects/rubypki
  192. #
  193. # [[UTF7]]
  194. # Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
  195. # Unicode", RFC 2152, May 1997.
  196. #
  197. class IMAP
  198. include MonitorMixin
  199. if defined?(OpenSSL)
  200. include OpenSSL
  201. include SSL
  202. end
  203. # Returns an initial greeting response from the server.
  204. attr_reader :greeting
  205. # Returns recorded untagged responses. For example:
  206. #
  207. # imap.select("inbox")
  208. # p imap.responses["EXISTS"][-1]
  209. # #=> 2
  210. # p imap.responses["UIDVALIDITY"][-1]
  211. # #=> 968263756
  212. attr_reader :responses
  213. # Returns all response handlers.
  214. attr_reader :response_handlers
  215. # The thread to receive exceptions.
  216. attr_accessor :client_thread
  217. # Flag indicating a message has been seen
  218. SEEN = :Seen
  219. # Flag indicating a message has been answered
  220. ANSWERED = :Answered
  221. # Flag indicating a message has been flagged for special or urgent
  222. # attention
  223. FLAGGED = :Flagged
  224. # Flag indicating a message has been marked for deletion. This
  225. # will occur when the mailbox is closed or expunged.
  226. DELETED = :Deleted
  227. # Flag indicating a message is only a draft or work-in-progress version.
  228. DRAFT = :Draft
  229. # Flag indicating that the message is "recent", meaning that this
  230. # session is the first session in which the client has been notified
  231. # of this message.
  232. RECENT = :Recent
  233. # Flag indicating that a mailbox context name cannot contain
  234. # children.
  235. NOINFERIORS = :Noinferiors
  236. # Flag indicating that a mailbox is not selected.
  237. NOSELECT = :Noselect
  238. # Flag indicating that a mailbox has been marked "interesting" by
  239. # the server; this commonly indicates that the mailbox contains
  240. # new messages.
  241. MARKED = :Marked
  242. # Flag indicating that the mailbox does not contains new messages.
  243. UNMARKED = :Unmarked
  244. # Returns the debug mode.
  245. def self.debug
  246. return @@debug
  247. end
  248. # Sets the debug mode.
  249. def self.debug=(val)
  250. return @@debug = val
  251. end
  252. # Returns the max number of flags interned to symbols.
  253. def self.max_flag_count
  254. return @@max_flag_count
  255. end
  256. # Sets the max number of flags interned to symbols.
  257. def self.max_flag_count=(count)
  258. @@max_flag_count = count
  259. end
  260. # Adds an authenticator for Net::IMAP#authenticate. +auth_type+
  261. # is the type of authentication this authenticator supports
  262. # (for instance, "LOGIN"). The +authenticator+ is an object
  263. # which defines a process() method to handle authentication with
  264. # the server. See Net::IMAP::LoginAuthenticator,
  265. # Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator
  266. # for examples.
  267. #
  268. #
  269. # If +auth_type+ refers to an existing authenticator, it will be
  270. # replaced by the new one.
  271. def self.add_authenticator(auth_type, authenticator)
  272. @@authenticators[auth_type] = authenticator
  273. end
  274. # Disconnects from the server.
  275. def disconnect
  276. begin
  277. begin
  278. # try to call SSL::SSLSocket#io.
  279. @sock.io.shutdown
  280. rescue NoMethodError
  281. # @sock is not an SSL::SSLSocket.
  282. @sock.shutdown
  283. end
  284. rescue Errno::ENOTCONN
  285. # ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
  286. rescue Exception => e
  287. @receiver_thread.raise(e)
  288. end
  289. @receiver_thread.join
  290. synchronize do
  291. unless @sock.closed?
  292. @sock.close
  293. end
  294. end
  295. raise e if e
  296. end
  297. # Returns true if disconnected from the server.
  298. def disconnected?
  299. return @sock.closed?
  300. end
  301. # Sends a CAPABILITY command, and returns an array of
  302. # capabilities that the server supports. Each capability
  303. # is a string. See [IMAP] for a list of possible
  304. # capabilities.
  305. #
  306. # Note that the Net::IMAP class does not modify its
  307. # behaviour according to the capabilities of the server;
  308. # it is up to the user of the class to ensure that
  309. # a certain capability is supported by a server before
  310. # using it.
  311. def capability
  312. synchronize do
  313. send_command("CAPABILITY")
  314. return @responses.delete("CAPABILITY")[-1]
  315. end
  316. end
  317. # Sends a NOOP command to the server. It does nothing.
  318. def noop
  319. send_command("NOOP")
  320. end
  321. # Sends a LOGOUT command to inform the server that the client is
  322. # done with the connection.
  323. def logout
  324. send_command("LOGOUT")
  325. end
  326. # Sends a STARTTLS command to start TLS session.
  327. def starttls(options = {}, verify = true)
  328. send_command("STARTTLS") do |resp|
  329. if resp.kind_of?(TaggedResponse) && resp.name == "OK"
  330. begin
  331. # for backward compatibility
  332. certs = options.to_str
  333. options = create_ssl_params(certs, verify)
  334. rescue NoMethodError
  335. end
  336. start_tls_session(options)
  337. end
  338. end
  339. end
  340. # Sends an AUTHENTICATE command to authenticate the client.
  341. # The +auth_type+ parameter is a string that represents
  342. # the authentication mechanism to be used. Currently Net::IMAP
  343. # supports authentication mechanisms:
  344. #
  345. # LOGIN:: login using cleartext user and password.
  346. # CRAM-MD5:: login with cleartext user and encrypted password
  347. # (see [RFC-2195] for a full description). This
  348. # mechanism requires that the server have the user's
  349. # password stored in clear-text password.
  350. #
  351. # For both these mechanisms, there should be two +args+: username
  352. # and (cleartext) password. A server may not support one or other
  353. # of these mechanisms; check #capability() for a capability of
  354. # the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
  355. #
  356. # Authentication is done using the appropriate authenticator object:
  357. # see @@authenticators for more information on plugging in your own
  358. # authenticator.
  359. #
  360. # For example:
  361. #
  362. # imap.authenticate('LOGIN', user, password)
  363. #
  364. # A Net::IMAP::NoResponseError is raised if authentication fails.
  365. def authenticate(auth_type, *args)
  366. auth_type = auth_type.upcase
  367. unless @@authenticators.has_key?(auth_type)
  368. raise ArgumentError,
  369. format('unknown auth type - "%s"', auth_type)
  370. end
  371. authenticator = @@authenticators[auth_type].new(*args)
  372. send_command("AUTHENTICATE", auth_type) do |resp|
  373. if resp.instance_of?(ContinuationRequest)
  374. data = authenticator.process(resp.data.text.unpack("m")[0])
  375. s = [data].pack("m").gsub(/\n/, "")
  376. send_string_data(s)
  377. put_string(CRLF)
  378. end
  379. end
  380. end
  381. # Sends a LOGIN command to identify the client and carries
  382. # the plaintext +password+ authenticating this +user+. Note
  383. # that, unlike calling #authenticate() with an +auth_type+
  384. # of "LOGIN", #login() does *not* use the login authenticator.
  385. #
  386. # A Net::IMAP::NoResponseError is raised if authentication fails.
  387. def login(user, password)
  388. send_command("LOGIN", user, password)
  389. end
  390. # Sends a SELECT command to select a +mailbox+ so that messages
  391. # in the +mailbox+ can be accessed.
  392. #
  393. # After you have selected a mailbox, you may retrieve the
  394. # number of items in that mailbox from @responses["EXISTS"][-1],
  395. # and the number of recent messages from @responses["RECENT"][-1].
  396. # Note that these values can change if new messages arrive
  397. # during a session; see #add_response_handler() for a way of
  398. # detecting this event.
  399. #
  400. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  401. # exist or is for some reason non-selectable.
  402. def select(mailbox)
  403. synchronize do
  404. @responses.clear
  405. send_command("SELECT", mailbox)
  406. end
  407. end
  408. # Sends a EXAMINE command to select a +mailbox+ so that messages
  409. # in the +mailbox+ can be accessed. Behaves the same as #select(),
  410. # except that the selected +mailbox+ is identified as read-only.
  411. #
  412. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  413. # exist or is for some reason non-examinable.
  414. def examine(mailbox)
  415. synchronize do
  416. @responses.clear
  417. send_command("EXAMINE", mailbox)
  418. end
  419. end
  420. # Sends a CREATE command to create a new +mailbox+.
  421. #
  422. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  423. # cannot be created.
  424. def create(mailbox)
  425. send_command("CREATE", mailbox)
  426. end
  427. # Sends a DELETE command to remove the +mailbox+.
  428. #
  429. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  430. # cannot be deleted, either because it does not exist or because the
  431. # client does not have permission to delete it.
  432. def delete(mailbox)
  433. send_command("DELETE", mailbox)
  434. end
  435. # Sends a RENAME command to change the name of the +mailbox+ to
  436. # +newname+.
  437. #
  438. # A Net::IMAP::NoResponseError is raised if a mailbox with the
  439. # name +mailbox+ cannot be renamed to +newname+ for whatever
  440. # reason; for instance, because +mailbox+ does not exist, or
  441. # because there is already a mailbox with the name +newname+.
  442. def rename(mailbox, newname)
  443. send_command("RENAME", mailbox, newname)
  444. end
  445. # Sends a SUBSCRIBE command to add the specified +mailbox+ name to
  446. # the server's set of "active" or "subscribed" mailboxes as returned
  447. # by #lsub().
  448. #
  449. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  450. # subscribed to, for instance because it does not exist.
  451. def subscribe(mailbox)
  452. send_command("SUBSCRIBE", mailbox)
  453. end
  454. # Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
  455. # from the server's set of "active" or "subscribed" mailboxes.
  456. #
  457. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  458. # unsubscribed from, for instance because the client is not currently
  459. # subscribed to it.
  460. def unsubscribe(mailbox)
  461. send_command("UNSUBSCRIBE", mailbox)
  462. end
  463. # Sends a LIST command, and returns a subset of names from
  464. # the complete set of all names available to the client.
  465. # +refname+ provides a context (for instance, a base directory
  466. # in a directory-based mailbox hierarchy). +mailbox+ specifies
  467. # a mailbox or (via wildcards) mailboxes under that context.
  468. # Two wildcards may be used in +mailbox+: '*', which matches
  469. # all characters *including* the hierarchy delimiter (for instance,
  470. # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
  471. # which matches all characters *except* the hierarchy delimiter.
  472. #
  473. # If +refname+ is empty, +mailbox+ is used directly to determine
  474. # which mailboxes to match. If +mailbox+ is empty, the root
  475. # name of +refname+ and the hierarchy delimiter are returned.
  476. #
  477. # The return value is an array of +Net::IMAP::MailboxList+. For example:
  478. #
  479. # imap.create("foo/bar")
  480. # imap.create("foo/baz")
  481. # p imap.list("", "foo/%")
  482. # #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
  483. # #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
  484. # #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
  485. def list(refname, mailbox)
  486. synchronize do
  487. send_command("LIST", refname, mailbox)
  488. return @responses.delete("LIST")
  489. end
  490. end
  491. # Sends the GETQUOTAROOT command along with specified +mailbox+.
  492. # This command is generally available to both admin and user.
  493. # If mailbox exists, returns an array containing objects of
  494. # Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
  495. def getquotaroot(mailbox)
  496. synchronize do
  497. send_command("GETQUOTAROOT", mailbox)
  498. result = []
  499. result.concat(@responses.delete("QUOTAROOT"))
  500. result.concat(@responses.delete("QUOTA"))
  501. return result
  502. end
  503. end
  504. # Sends the GETQUOTA command along with specified +mailbox+.
  505. # If this mailbox exists, then an array containing a
  506. # Net::IMAP::MailboxQuota object is returned. This
  507. # command generally is only available to server admin.
  508. def getquota(mailbox)
  509. synchronize do
  510. send_command("GETQUOTA", mailbox)
  511. return @responses.delete("QUOTA")
  512. end
  513. end
  514. # Sends a SETQUOTA command along with the specified +mailbox+ and
  515. # +quota+. If +quota+ is nil, then quota will be unset for that
  516. # mailbox. Typically one needs to be logged in as server admin
  517. # for this to work. The IMAP quota commands are described in
  518. # [RFC-2087].
  519. def setquota(mailbox, quota)
  520. if quota.nil?
  521. data = '()'
  522. else
  523. data = '(STORAGE ' + quota.to_s + ')'
  524. end
  525. send_command("SETQUOTA", mailbox, RawData.new(data))
  526. end
  527. # Sends the SETACL command along with +mailbox+, +user+ and the
  528. # +rights+ that user is to have on that mailbox. If +rights+ is nil,
  529. # then that user will be stripped of any rights to that mailbox.
  530. # The IMAP ACL commands are described in [RFC-2086].
  531. def setacl(mailbox, user, rights)
  532. if rights.nil?
  533. send_command("SETACL", mailbox, user, "")
  534. else
  535. send_command("SETACL", mailbox, user, rights)
  536. end
  537. end
  538. # Send the GETACL command along with specified +mailbox+.
  539. # If this mailbox exists, an array containing objects of
  540. # Net::IMAP::MailboxACLItem will be returned.
  541. def getacl(mailbox)
  542. synchronize do
  543. send_command("GETACL", mailbox)
  544. return @responses.delete("ACL")[-1]
  545. end
  546. end
  547. # Sends a LSUB command, and returns a subset of names from the set
  548. # of names that the user has declared as being "active" or
  549. # "subscribed". +refname+ and +mailbox+ are interpreted as
  550. # for #list().
  551. # The return value is an array of +Net::IMAP::MailboxList+.
  552. def lsub(refname, mailbox)
  553. synchronize do
  554. send_command("LSUB", refname, mailbox)
  555. return @responses.delete("LSUB")
  556. end
  557. end
  558. # Sends a STATUS command, and returns the status of the indicated
  559. # +mailbox+. +attr+ is a list of one or more attributes that
  560. # we are request the status of. Supported attributes include:
  561. #
  562. # MESSAGES:: the number of messages in the mailbox.
  563. # RECENT:: the number of recent messages in the mailbox.
  564. # UNSEEN:: the number of unseen messages in the mailbox.
  565. #
  566. # The return value is a hash of attributes. For example:
  567. #
  568. # p imap.status("inbox", ["MESSAGES", "RECENT"])
  569. # #=> {"RECENT"=>0, "MESSAGES"=>44}
  570. #
  571. # A Net::IMAP::NoResponseError is raised if status values
  572. # for +mailbox+ cannot be returned, for instance because it
  573. # does not exist.
  574. def status(mailbox, attr)
  575. synchronize do
  576. send_command("STATUS", mailbox, attr)
  577. return @responses.delete("STATUS")[-1].attr
  578. end
  579. end
  580. # Sends a APPEND command to append the +message+ to the end of
  581. # the +mailbox+. The optional +flags+ argument is an array of
  582. # flags to initially passing to the new message. The optional
  583. # +date_time+ argument specifies the creation time to assign to the
  584. # new message; it defaults to the current time.
  585. # For example:
  586. #
  587. # imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
  588. # Subject: hello
  589. # From: shugo@ruby-lang.org
  590. # To: shugo@ruby-lang.org
  591. #
  592. # hello world
  593. # EOF
  594. #
  595. # A Net::IMAP::NoResponseError is raised if the mailbox does
  596. # not exist (it is not created automatically), or if the flags,
  597. # date_time, or message arguments contain errors.
  598. def append(mailbox, message, flags = nil, date_time = nil)
  599. args = []
  600. if flags
  601. args.push(flags)
  602. end
  603. args.push(date_time) if date_time
  604. args.push(Literal.new(message))
  605. send_command("APPEND", mailbox, *args)
  606. end
  607. # Sends a CHECK command to request a checkpoint of the currently
  608. # selected mailbox. This performs implementation-specific
  609. # housekeeping, for instance, reconciling the mailbox's
  610. # in-memory and on-disk state.
  611. def check
  612. send_command("CHECK")
  613. end
  614. # Sends a CLOSE command to close the currently selected mailbox.
  615. # The CLOSE command permanently removes from the mailbox all
  616. # messages that have the \Deleted flag set.
  617. def close
  618. send_command("CLOSE")
  619. end
  620. # Sends a EXPUNGE command to permanently remove from the currently
  621. # selected mailbox all messages that have the \Deleted flag set.
  622. def expunge
  623. synchronize do
  624. send_command("EXPUNGE")
  625. return @responses.delete("EXPUNGE")
  626. end
  627. end
  628. # Sends a SEARCH command to search the mailbox for messages that
  629. # match the given searching criteria, and returns message sequence
  630. # numbers. +keys+ can either be a string holding the entire
  631. # search string, or a single-dimension array of search keywords and
  632. # arguments. The following are some common search criteria;
  633. # see [IMAP] section 6.4.4 for a full list.
  634. #
  635. # <message set>:: a set of message sequence numbers. ',' indicates
  636. # an interval, ':' indicates a range. For instance,
  637. # '2,10:12,15' means "2,10,11,12,15".
  638. #
  639. # BEFORE <date>:: messages with an internal date strictly before
  640. # <date>. The date argument has a format similar
  641. # to 8-Aug-2002.
  642. #
  643. # BODY <string>:: messages that contain <string> within their body.
  644. #
  645. # CC <string>:: messages containing <string> in their CC field.
  646. #
  647. # FROM <string>:: messages that contain <string> in their FROM field.
  648. #
  649. # NEW:: messages with the \Recent, but not the \Seen, flag set.
  650. #
  651. # NOT <search-key>:: negate the following search key.
  652. #
  653. # OR <search-key> <search-key>:: "or" two search keys together.
  654. #
  655. # ON <date>:: messages with an internal date exactly equal to <date>,
  656. # which has a format similar to 8-Aug-2002.
  657. #
  658. # SINCE <date>:: messages with an internal date on or after <date>.
  659. #
  660. # SUBJECT <string>:: messages with <string> in their subject.
  661. #
  662. # TO <string>:: messages with <string> in their TO field.
  663. #
  664. # For example:
  665. #
  666. # p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
  667. # #=> [1, 6, 7, 8]
  668. def search(keys, charset = nil)
  669. return search_internal("SEARCH", keys, charset)
  670. end
  671. # As for #search(), but returns unique identifiers.
  672. def uid_search(keys, charset = nil)
  673. return search_internal("UID SEARCH", keys, charset)
  674. end
  675. # Sends a FETCH command to retrieve data associated with a message
  676. # in the mailbox. The +set+ parameter is a number or an array of
  677. # numbers or a Range object. The number is a message sequence
  678. # number. +attr+ is a list of attributes to fetch; see the
  679. # documentation for Net::IMAP::FetchData for a list of valid
  680. # attributes.
  681. # The return value is an array of Net::IMAP::FetchData. For example:
  682. #
  683. # p imap.fetch(6..8, "UID")
  684. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
  685. # #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
  686. # #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
  687. # p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
  688. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
  689. # data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
  690. # p data.seqno
  691. # #=> 6
  692. # p data.attr["RFC822.SIZE"]
  693. # #=> 611
  694. # p data.attr["INTERNALDATE"]
  695. # #=> "12-Oct-2000 22:40:59 +0900"
  696. # p data.attr["UID"]
  697. # #=> 98
  698. def fetch(set, attr)
  699. return fetch_internal("FETCH", set, attr)
  700. end
  701. # As for #fetch(), but +set+ contains unique identifiers.
  702. def uid_fetch(set, attr)
  703. return fetch_internal("UID FETCH", set, attr)
  704. end
  705. # Sends a STORE command to alter data associated with messages
  706. # in the mailbox, in particular their flags. The +set+ parameter
  707. # is a number or an array of numbers or a Range object. Each number
  708. # is a message sequence number. +attr+ is the name of a data item
  709. # to store: 'FLAGS' means to replace the message's flag list
  710. # with the provided one; '+FLAGS' means to add the provided flags;
  711. # and '-FLAGS' means to remove them. +flags+ is a list of flags.
  712. #
  713. # The return value is an array of Net::IMAP::FetchData. For example:
  714. #
  715. # p imap.store(6..8, "+FLAGS", [:Deleted])
  716. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  717. # #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  718. # #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
  719. def store(set, attr, flags)
  720. return store_internal("STORE", set, attr, flags)
  721. end
  722. # As for #store(), but +set+ contains unique identifiers.
  723. def uid_store(set, attr, flags)
  724. return store_internal("UID STORE", set, attr, flags)
  725. end
  726. # Sends a COPY command to copy the specified message(s) to the end
  727. # of the specified destination +mailbox+. The +set+ parameter is
  728. # a number or an array of numbers or a Range object. The number is
  729. # a message sequence number.
  730. def copy(set, mailbox)
  731. copy_internal("COPY", set, mailbox)
  732. end
  733. # As for #copy(), but +set+ contains unique identifiers.
  734. def uid_copy(set, mailbox)
  735. copy_internal("UID COPY", set, mailbox)
  736. end
  737. # Sends a SORT command to sort messages in the mailbox.
  738. # Returns an array of message sequence numbers. For example:
  739. #
  740. # p imap.sort(["FROM"], ["ALL"], "US-ASCII")
  741. # #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
  742. # p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
  743. # #=> [6, 7, 8, 1]
  744. #
  745. # See [SORT-THREAD-EXT] for more details.
  746. def sort(sort_keys, search_keys, charset)
  747. return sort_internal("SORT", sort_keys, search_keys, charset)
  748. end
  749. # As for #sort(), but returns an array of unique identifiers.
  750. def uid_sort(sort_keys, search_keys, charset)
  751. return sort_internal("UID SORT", sort_keys, search_keys, charset)
  752. end
  753. # Adds a response handler. For example, to detect when
  754. # the server sends us a new EXISTS response (which normally
  755. # indicates new messages being added to the mail box),
  756. # you could add the following handler after selecting the
  757. # mailbox.
  758. #
  759. # imap.add_response_handler { |resp|
  760. # if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
  761. # puts "Mailbox now has #{resp.data} messages"
  762. # end
  763. # }
  764. #
  765. def add_response_handler(handler = Proc.new)
  766. @response_handlers.push(handler)
  767. end
  768. # Removes the response handler.
  769. def remove_response_handler(handler)
  770. @response_handlers.delete(handler)
  771. end
  772. # As for #search(), but returns message sequence numbers in threaded
  773. # format, as a Net::IMAP::ThreadMember tree. The supported algorithms
  774. # are:
  775. #
  776. # ORDEREDSUBJECT:: split into single-level threads according to subject,
  777. # ordered by date.
  778. # REFERENCES:: split into threads by parent/child relationships determined
  779. # by which message is a reply to which.
  780. #
  781. # Unlike #search(), +charset+ is a required argument. US-ASCII
  782. # and UTF-8 are sample values.
  783. #
  784. # See [SORT-THREAD-EXT] for more details.
  785. def thread(algorithm, search_keys, charset)
  786. return thread_internal("THREAD", algorithm, search_keys, charset)
  787. end
  788. # As for #thread(), but returns unique identifiers instead of
  789. # message sequence numbers.
  790. def uid_thread(algorithm, search_keys, charset)
  791. return thread_internal("UID THREAD", algorithm, search_keys, charset)
  792. end
  793. # Sends an IDLE command that waits for notifications of new or expunged
  794. # messages. Yields responses from the server during the IDLE.
  795. #
  796. # Use #idle_done() to leave IDLE.
  797. def idle(&response_handler)
  798. raise LocalJumpError, "no block given" unless response_handler
  799. response = nil
  800. synchronize do
  801. tag = Thread.current[:net_imap_tag] = generate_tag
  802. put_string("#{tag} IDLE#{CRLF}")
  803. begin
  804. add_response_handler(response_handler)
  805. @idle_done_cond = new_cond
  806. @idle_done_cond.wait
  807. @idle_done_cond = nil
  808. ensure
  809. remove_response_handler(response_handler)
  810. put_string("DONE#{CRLF}")
  811. response = get_tagged_response(tag, "IDLE")
  812. end
  813. end
  814. return response
  815. end
  816. # Leaves IDLE.
  817. def idle_done
  818. synchronize do
  819. if @idle_done_cond.nil?
  820. raise Net::IMAP::Error, "not during IDLE"
  821. end
  822. @idle_done_cond.signal
  823. end
  824. end
  825. # Decode a string from modified UTF-7 format to UTF-8.
  826. #
  827. # UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a
  828. # slightly modified version of this to encode mailbox names
  829. # containing non-ASCII characters; see [IMAP] section 5.1.3.
  830. #
  831. # Net::IMAP does _not_ automatically encode and decode
  832. # mailbox names to and from utf7.
  833. def self.decode_utf7(s)
  834. return s.gsub(/&(.*?)-/n) {
  835. if $1.empty?
  836. "&"
  837. else
  838. base64 = $1.tr(",", "/")
  839. x = base64.length % 4
  840. if x > 0
  841. base64.concat("=" * (4 - x))
  842. end
  843. base64.unpack("m")[0].unpack("n*").pack("U*")
  844. end
  845. }.force_encoding("UTF-8")
  846. end
  847. # Encode a string from UTF-8 format to modified UTF-7.
  848. def self.encode_utf7(s)
  849. return s.gsub(/(&)|([^\x20-\x7e]+)/u) {
  850. if $1
  851. "&-"
  852. else
  853. base64 = [$&.unpack("U*").pack("n*")].pack("m")
  854. "&" + base64.delete("=\n").tr("/", ",") + "-"
  855. end
  856. }.force_encoding("ASCII-8BIT")
  857. end
  858. # Formats +time+ as an IMAP-style date.
  859. def self.format_date(time)
  860. return time.strftime('%d-%b-%Y')
  861. end
  862. # Formats +time+ as an IMAP-style date-time.
  863. def self.format_datetime(time)
  864. return time.strftime('%d-%b-%Y %H:%M %z')
  865. end
  866. private
  867. CRLF = "\r\n" # :nodoc:
  868. PORT = 143 # :nodoc:
  869. SSL_PORT = 993 # :nodoc:
  870. @@debug = false
  871. @@authenticators = {}
  872. @@max_flag_count = 10000
  873. # call-seq:
  874. # Net::IMAP.new(host, options = {})
  875. #
  876. # Creates a new Net::IMAP object and connects it to the specified
  877. # +host+.
  878. #
  879. # +options+ is an option hash, each key of which is a symbol.
  880. #
  881. # The available options are:
  882. #
  883. # port:: port number (default value is 143 for imap, or 993 for imaps)
  884. # ssl:: if options[:ssl] is true, then an attempt will be made
  885. # to use SSL (now TLS) to connect to the server. For this to work
  886. # OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] extensions need to
  887. # be installed.
  888. # if options[:ssl] is a hash, it's passed to
  889. # OpenSSL::SSL::SSLContext#set_params as parameters.
  890. #
  891. # The most common errors are:
  892. #
  893. # Errno::ECONNREFUSED:: connection refused by +host+ or an intervening
  894. # firewall.
  895. # Errno::ETIMEDOUT:: connection timed out (possibly due to packets
  896. # being dropped by an intervening firewall).
  897. # Errno::ENETUNREACH:: there is no route to that network.
  898. # SocketError:: hostname not known or other socket error.
  899. # Net::IMAP::ByeResponseError:: we connected to the host, but they
  900. # immediately said goodbye to us.
  901. def initialize(host, port_or_options = {},
  902. usessl = false, certs = nil, verify = true)
  903. super()
  904. @host = host
  905. begin
  906. options = port_or_options.to_hash
  907. rescue NoMethodError
  908. # for backward compatibility
  909. options = {}
  910. options[:port] = port_or_options
  911. if usessl
  912. options[:ssl] = create_ssl_params(certs, verify)
  913. end
  914. end
  915. @port = options[:port] || (options[:ssl] ? SSL_PORT : PORT)
  916. @tag_prefix = "RUBY"
  917. @tagno = 0
  918. @parser = ResponseParser.new
  919. @sock = TCPSocket.open(@host, @port)
  920. if options[:ssl]
  921. start_tls_session(options[:ssl])
  922. @usessl = true
  923. else
  924. @usessl = false
  925. end
  926. @responses = Hash.new([].freeze)
  927. @tagged_responses = {}
  928. @response_handlers = []
  929. @tagged_response_arrival = new_cond
  930. @continuation_request_arrival = new_cond
  931. @idle_done_cond = nil
  932. @logout_command_tag = nil
  933. @debug_output_bol = true
  934. @exception = nil
  935. @greeting = get_response
  936. if @greeting.name == "BYE"
  937. @sock.close
  938. raise ByeResponseError, @greeting
  939. end
  940. @client_thread = Thread.current
  941. @receiver_thread = Thread.start {
  942. begin
  943. receive_responses
  944. rescue Exception
  945. end
  946. }
  947. end
  948. def receive_responses
  949. connection_closed = false
  950. until connection_closed
  951. synchronize do
  952. @exception = nil
  953. end
  954. begin
  955. resp = get_response
  956. rescue Exception => e
  957. synchronize do
  958. @sock.close
  959. @exception = e
  960. end
  961. break
  962. end
  963. unless resp
  964. synchronize do
  965. @exception = EOFError.new("end of file reached")
  966. end
  967. break
  968. end
  969. begin
  970. synchronize do
  971. case resp
  972. when TaggedResponse
  973. @tagged_responses[resp.tag] = resp
  974. @tagged_response_arrival.broadcast
  975. if resp.tag == @logout_command_tag
  976. return
  977. end
  978. when UntaggedResponse
  979. record_response(resp.name, resp.data)
  980. if resp.data.instance_of?(ResponseText) &&
  981. (code = resp.data.code)
  982. record_response(code.name, code.data)
  983. end
  984. if resp.name == "BYE" && @logout_command_tag.nil?
  985. @sock.close
  986. @exception = ByeResponseError.new(resp)
  987. connection_closed = true
  988. end
  989. when ContinuationRequest
  990. @continuation_request_arrival.signal
  991. end
  992. @response_handlers.each do |handler|
  993. handler.call(resp)
  994. end
  995. end
  996. rescue Exception => e
  997. @exception = e
  998. synchronize do
  999. @tagged_response_arrival.broadcast
  1000. @continuation_request_arrival.broadcast
  1001. end
  1002. end
  1003. end
  1004. synchronize do
  1005. @tagged_response_arrival.broadcast
  1006. @continuation_request_arrival.broadcast
  1007. end
  1008. end
  1009. def get_tagged_response(tag, cmd)
  1010. until @tagged_responses.key?(tag)
  1011. raise @exception if @exception
  1012. @tagged_response_arrival.wait
  1013. end
  1014. resp = @tagged_responses.delete(tag)
  1015. case resp.name
  1016. when /\A(?:NO)\z/ni
  1017. raise NoResponseError, resp
  1018. when /\A(?:BAD)\z/ni
  1019. raise BadResponseError, resp
  1020. else
  1021. return resp
  1022. end
  1023. end
  1024. def get_response
  1025. buff = ""
  1026. while true
  1027. s = @sock.gets(CRLF)
  1028. break unless s
  1029. buff.concat(s)
  1030. if /\{(\d+)\}\r\n/n =~ s
  1031. s = @sock.read($1.to_i)
  1032. buff.concat(s)
  1033. else
  1034. break
  1035. end
  1036. end
  1037. return nil if buff.length == 0
  1038. if @@debug
  1039. $stderr.print(buff.gsub(/^/n, "S: "))
  1040. end
  1041. return @parser.parse(buff)
  1042. end
  1043. def record_response(name, data)
  1044. unless @responses.has_key?(name)
  1045. @responses[name] = []
  1046. end
  1047. @responses[name].push(data)
  1048. end
  1049. def send_command(cmd, *args, &block)
  1050. synchronize do
  1051. args.each do |i|
  1052. validate_data(i)
  1053. end
  1054. tag = generate_tag
  1055. put_string(tag + " " + cmd)
  1056. args.each do |i|
  1057. put_string(" ")
  1058. send_data(i)
  1059. end
  1060. put_string(CRLF)
  1061. if cmd == "LOGOUT"
  1062. @logout_command_tag = tag
  1063. end
  1064. if block
  1065. add_response_handler(block)
  1066. end
  1067. begin
  1068. return get_tagged_response(tag, cmd)
  1069. ensure
  1070. if block
  1071. remove_response_handler(block)
  1072. end
  1073. end
  1074. end
  1075. end
  1076. def generate_tag
  1077. @tagno += 1
  1078. return format("%s%04d", @tag_prefix, @tagno)
  1079. end
  1080. def put_string(str)
  1081. @sock.print(str)
  1082. if @@debug
  1083. if @debug_output_bol
  1084. $stderr.print("C: ")
  1085. end
  1086. $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
  1087. if /\r\n\z/n.match(str)
  1088. @debug_output_bol = true
  1089. else
  1090. @debug_output_bol = false
  1091. end
  1092. end
  1093. end
  1094. def validate_data(data)
  1095. case data
  1096. when nil
  1097. when String
  1098. when Integer
  1099. if data < 0 || data >= 4294967296
  1100. raise DataFormatError, num.to_s
  1101. end
  1102. when Array
  1103. data.each do |i|
  1104. validate_data(i)
  1105. end
  1106. when Time
  1107. when Symbol
  1108. else
  1109. data.validate
  1110. end
  1111. end
  1112. def send_data(data)
  1113. case data
  1114. when nil
  1115. put_string("NIL")
  1116. when String
  1117. send_string_data(data)
  1118. when Integer
  1119. send_number_data(data)
  1120. when Array
  1121. send_list_data(data)
  1122. when Time
  1123. send_time_data(data)
  1124. when Symbol
  1125. send_symbol_data(data)
  1126. else
  1127. data.send_data(self)
  1128. end
  1129. end
  1130. def send_string_data(str)
  1131. case str
  1132. when ""
  1133. put_string('""')
  1134. when /[\x80-\xff\r\n]/n
  1135. # literal
  1136. send_literal(str)
  1137. when /[(){ \x00-\x1f\x7f%*"\\]/n
  1138. # quoted string
  1139. send_quoted_string(str)
  1140. else
  1141. put_string(str)
  1142. end
  1143. end
  1144. def send_quoted_string(str)
  1145. put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
  1146. end
  1147. def send_literal(str)
  1148. put_string("{" + str.length.to_s + "}" + CRLF)
  1149. @continuation_request_arrival.wait
  1150. raise @exception if @exception
  1151. put_string(str)
  1152. end
  1153. def send_number_data(num)
  1154. put_string(num.to_s)
  1155. end
  1156. def send_list_data(list)
  1157. put_string("(")
  1158. first = true
  1159. list.each do |i|
  1160. if first
  1161. first = false
  1162. else
  1163. put_string(" ")
  1164. end
  1165. send_data(i)
  1166. end
  1167. put_string(")")
  1168. end
  1169. DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
  1170. def send_time_data(time)
  1171. t = time.dup.gmtime
  1172. s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
  1173. t.day, DATE_MONTH[t.month - 1], t.year,
  1174. t.hour, t.min, t.sec)
  1175. put_string(s)
  1176. end
  1177. def send_symbol_data(symbol)
  1178. put_string("\\" + symbol.to_s)
  1179. end
  1180. def search_internal(cmd, keys, charset)
  1181. if keys.instance_of?(String)
  1182. keys = [RawData.new(keys)]
  1183. else
  1184. normalize_searching_criteria(keys)
  1185. end
  1186. synchronize do
  1187. if charset
  1188. send_command(cmd, "CHARSET", charset, *keys)
  1189. else
  1190. send_command(cmd, *keys)
  1191. end
  1192. return @responses.delete("SEARCH")[-1]
  1193. end
  1194. end
  1195. def fetch_internal(cmd, set, attr)
  1196. case attr
  1197. when String then
  1198. attr = RawData.new(attr)
  1199. when Array then
  1200. attr = attr.map { |arg|
  1201. arg.is_a?(String) ? RawData.new(arg) : arg
  1202. }
  1203. end
  1204. synchronize do
  1205. @responses.delete("FETCH")
  1206. send_command(cmd, MessageSet.new(set), attr)
  1207. return @responses.delete("FETCH")
  1208. end
  1209. end
  1210. def store_internal(cmd, set, attr, flags)
  1211. if attr.instance_of?(String)
  1212. attr = RawData.new(attr)
  1213. end
  1214. synchronize do
  1215. @responses.delete("FETCH")
  1216. send_command(cmd, MessageSet.new(set), attr, flags)
  1217. return @responses.delete("FETCH")
  1218. end
  1219. end
  1220. def copy_internal(cmd, set, mailbox)
  1221. send_command(cmd, MessageSet.new(set), mailbox)
  1222. end
  1223. def sort_internal(cmd, sort_keys, search_keys, charset)
  1224. if search_keys.instance_of?(String)
  1225. search_keys = [RawData.new(search_keys)]
  1226. else
  1227. normalize_searching_criteria(search_keys)
  1228. end
  1229. normalize_searching_criteria(search_keys)
  1230. synchronize do
  1231. send_command(cmd, sort_keys, charset, *search_keys)
  1232. return @responses.delete("SORT")[-1]
  1233. end
  1234. end
  1235. def thread_internal(cmd, algorithm, search_keys, charset)
  1236. if search_keys.instance_of?(String)
  1237. search_keys = [RawData.new(search_keys)]
  1238. else
  1239. normalize_searching_criteria(search_keys)
  1240. end
  1241. normalize_searching_criteria(search_keys)
  1242. send_command(cmd, algorithm, charset, *search_keys)
  1243. return @responses.delete("THREAD")[-1]
  1244. end
  1245. def normalize_searching_criteria(keys)
  1246. keys.collect! do |i|
  1247. case i
  1248. when -1, Range, Array
  1249. MessageSet.new(i)
  1250. else
  1251. i
  1252. end
  1253. end
  1254. end
  1255. def create_ssl_params(certs = nil, verify = true)
  1256. params = {}
  1257. if certs
  1258. if File.file?(certs)
  1259. params[:ca_file] = certs
  1260. elsif File.directory?(certs)
  1261. params[:ca_path] = certs
  1262. end
  1263. end
  1264. if verify
  1265. params[:verify_mode] = VERIFY_PEER
  1266. else
  1267. params[:verify_mode] = VERIFY_NONE
  1268. end
  1269. return params
  1270. end
  1271. def start_tls_session(params = {})
  1272. unless defined?(OpenSSL)
  1273. raise "SSL extension not installed"
  1274. end
  1275. if @sock.kind_of?(OpenSSL::SSL::SSLSocket)
  1276. raise RuntimeError, "already using SSL"
  1277. end
  1278. begin
  1279. params = params.to_hash
  1280. rescue NoMethodError
  1281. params = {}
  1282. end
  1283. context = SSLContext.new
  1284. context.set_params(params)
  1285. if defined?(VerifyCallbackProc)
  1286. context.verify_callback = VerifyCallbackProc
  1287. end
  1288. @sock = SSLSocket.new(@sock, context)
  1289. @sock.sync_close = true
  1290. @sock.connect
  1291. if context.verify_mode != VERIFY_NONE
  1292. @sock.post_connection_check(@host)
  1293. end
  1294. end
  1295. class RawData # :nodoc:
  1296. def send_data(imap)
  1297. imap.send(:put_string, @data)
  1298. end
  1299. def validate
  1300. end
  1301. private
  1302. def initialize(data)
  1303. @data = data
  1304. end
  1305. end
  1306. class Atom # :nodoc:
  1307. def send_data(imap)
  1308. imap.send(:put_string, @data)
  1309. end
  1310. def validate
  1311. end
  1312. private
  1313. def initialize(data)
  1314. @data = data
  1315. end
  1316. end
  1317. class QuotedString # :nodoc:
  1318. def send_data(imap)
  1319. imap.send(:send_quoted_string, @data)
  1320. end
  1321. def validate
  1322. end
  1323. private
  1324. def initialize(data)
  1325. @data = data
  1326. end
  1327. end
  1328. class Literal # :nodoc:
  1329. def send_data(imap)
  1330. imap.send(:send_literal, @data)
  1331. end
  1332. def validate
  1333. end
  1334. private
  1335. def initialize(data)
  1336. @data = data
  1337. end
  1338. end
  1339. class MessageSet # :nodoc:
  1340. def send_data(imap)
  1341. imap.send(:put_string, format_internal(@data))
  1342. end
  1343. def validate
  1344. validate_internal(@data)
  1345. end
  1346. private
  1347. def initialize(data)
  1348. @data = data
  1349. end
  1350. def format_internal(data)
  1351. case data
  1352. when "*"
  1353. return data
  1354. when Integer
  1355. if data == -1
  1356. return "*"
  1357. else
  1358. return data.to_s
  1359. end
  1360. when Range
  1361. return format_internal(data.first) +
  1362. ":" + format_internal(data.last)
  1363. when Array
  1364. return data.collect {|i| format_internal(i)}.join(",")
  1365. when ThreadMember
  1366. return data.seqno.to_s +
  1367. ":" + data.children.collect {|i| format_internal(i).join(",")}
  1368. end
  1369. end
  1370. def validate_internal(data)
  1371. case data
  1372. when "*"
  1373. when Integer
  1374. ensure_nz_number(data)
  1375. when Range
  1376. when Array
  1377. data.each do |i|
  1378. validate_internal(i)
  1379. end
  1380. when ThreadMember
  1381. data.children.each do |i|
  1382. validate_internal(i)
  1383. end
  1384. else
  1385. raise DataFormatError, data.inspect
  1386. end
  1387. end
  1388. def ensure_nz_number(num)
  1389. if num < -1 || num == 0 || num >= 4294967296
  1390. msg = "nz_number must be non-zero unsigned 32-bit integer: " +
  1391. num.inspect
  1392. raise DataFormatError, msg
  1393. end
  1394. end
  1395. end
  1396. # Net::IMAP::ContinuationRequest represents command continuation requests.
  1397. #
  1398. # The command continuation request response is indicated by a "+" token
  1399. # instead of a tag. This form of response indicates that the server is
  1400. # ready to accept the continuation of a command from the client. The
  1401. # remainder of this response is a line of text.
  1402. #
  1403. # continue_req ::= "+" SPACE (resp_text / base64)
  1404. #
  1405. # ==== Fields:
  1406. #
  1407. # data:: Returns the data (Net::IMAP::ResponseText).
  1408. #
  1409. # raw_data:: Returns the raw data string.
  1410. ContinuationRequest = Struct.new(:data, :raw_data)
  1411. # Net::IMAP::UntaggedResponse represents untagged responses.
  1412. #
  1413. # Data transmitted by the server to the client and status responses
  1414. # that do not indicate command completion are prefixed with the token
  1415. # "*", and are called untagged responses.
  1416. #
  1417. # response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye /
  1418. # mailbox_data / message_data / capability_data)
  1419. #
  1420. # ==== Fields:
  1421. #
  1422. # name:: Returns the name such as "FLAGS", "LIST", "FETCH"....
  1423. #
  1424. # data:: Returns the data such as an array of flag symbols,
  1425. # a ((<Net::IMAP::MailboxList>)) object....
  1426. #
  1427. # raw_data:: Returns the raw data string.
  1428. UntaggedResponse = Struct.new(:name, :data, :raw_data)
  1429. # Net::IMAP::TaggedResponse represents tagged responses.
  1430. #
  1431. # The server completion result response indicates the success or
  1432. # failure of the operation. It is tagged with the same tag as the
  1433. # client command which began the operation.
  1434. #
  1435. # response_tagged ::= tag SPACE resp_cond_state CRLF
  1436. #
  1437. # tag ::= 1*<any ATOM_CHAR except "+">
  1438. #
  1439. # resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
  1440. #
  1441. # ==== Fields:
  1442. #
  1443. # tag:: Returns the tag.
  1444. #
  1445. # name:: Returns the name. the name is one of "OK", "NO", "BAD".
  1446. #
  1447. # data:: Returns the data. See ((<Net::IMAP::ResponseText>)).
  1448. #
  1449. # raw_data:: Returns the raw data string.
  1450. #
  1451. TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)
  1452. # Net::IMAP::ResponseText represents texts of responses.
  1453. # The text may be prefixed by the response code.
  1454. #
  1455. # resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
  1456. # ;; text SHOULD NOT begin with "[" or "="
  1457. #
  1458. # ==== Fields:
  1459. #
  1460. # code:: Returns the response code. See ((<Net::IMAP::ResponseCode>)).
  1461. #
  1462. # text:: Returns the text.
  1463. #
  1464. ResponseText = Struct.new(:code, :text)
  1465. #
  1466. # Net::IMAP::ResponseCode represents response codes.
  1467. #
  1468. # resp_text_code ::= "ALERT" / "PARSE" /
  1469. # "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
  1470. # "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
  1471. # "UIDVALIDITY" SPACE nz_number /
  1472. # "UNSEEN" SPACE nz_number /
  1473. # atom [SPACE 1*<any TEXT_CHAR except "]">]
  1474. #
  1475. # ==== Fields:
  1476. #
  1477. # name:: Returns the name such as "ALERT", "PERMANENTFLAGS", "UIDVALIDITY"....
  1478. #
  1479. # data:: Returns the data if it exists.
  1480. #
  1481. ResponseCode = Struct.new(:name, :data)
  1482. # Net::IMAP::MailboxList represents contents of the LIST response.
  1483. #
  1484. # mailbox_list ::= "(" #("\Marked" / "\Noinferiors" /
  1485. # "\Noselect" / "\Unmarked" / flag_extension) ")"
  1486. # SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
  1487. #
  1488. # ==== Fields:
  1489. #
  1490. # attr:: Returns the name attributes. Each name attribute is a symbol
  1491. # capitalized by String#capitalize, such as :Noselect (not :NoSelect).
  1492. #
  1493. # delim:: Returns the hierarchy delimiter
  1494. #
  1495. # name:: Returns the mailbox name.
  1496. #
  1497. MailboxList = Struct.new(:attr, :delim, :name)
  1498. # Net::IMAP::MailboxQuota represents contents of GETQUOTA response.
  1499. # This object can also be a response to GETQUOTAROOT. In the syntax
  1500. # specification below, the delimiter used with the "#" construct is a
  1501. # single space (SPACE).
  1502. #
  1503. # quota_list ::= "(" #quota_resource ")"
  1504. #
  1505. # quota_resource ::= atom SPACE number SPACE number
  1506. #
  1507. # quota_response ::= "QUOTA" SPACE astring SPACE quota_list
  1508. #
  1509. # ==== Fields:
  1510. #
  1511. # mailbox:: The mailbox with the associated quota.
  1512. #
  1513. # usage:: Current storage usage of mailbox.
  1514. #
  1515. # quota:: Quota limit imposed on mailbox.
  1516. #
  1517. MailboxQuota = Struct.new(:mailbox, :usage, :quota)
  1518. # Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT
  1519. # response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
  1520. #
  1521. # quotaroot_response ::= "QUOTAROOT" SPACE astring *(SPACE astring)
  1522. #
  1523. # ==== Fields:
  1524. #
  1525. # mailbox:: The mailbox with the associated quota.
  1526. #
  1527. # quotaroots:: Zero or more quotaroots that effect the quota on the
  1528. # specified mailbox.
  1529. #
  1530. MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots)
  1531. # Net::IMAP::MailboxACLItem represents response from GETACL.
  1532. #
  1533. # acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE rights)
  1534. #
  1535. # identifier ::= astring
  1536. #
  1537. # rights ::= astring
  1538. #
  1539. # ==== Fields:
  1540. #
  1541. # user:: Login name that has certain rights to the mailbox
  1542. # that was specified with the getacl command.
  1543. #
  1544. # rights:: The access rights the indicated user has to the
  1545. # mailbox.
  1546. #
  1547. MailboxACLItem = Struct.new(:user, :rights)
  1548. # Net::IMAP::StatusData represents contents of the STATUS response.
  1549. #
  1550. # ==== Fields:
  1551. #
  1552. # mailbox:: Returns the mailbox name.
  1553. #
  1554. # attr:: Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT",
  1555. # "UIDVALIDITY", "UNSEEN". Each value is a number.
  1556. #
  1557. StatusData = Struct.new(:mailbox, :attr)
  1558. # Net::IMAP::FetchData represents contents of the FETCH response.
  1559. #
  1560. # ==== Fields:
  1561. #
  1562. # seqno:: Returns the message sequence number.
  1563. # (Note: not the unique identifier, even for the UID command response.)
  1564. #
  1565. # attr:: Returns a hash. Each key is a data item name, and each value is
  1566. # its value.
  1567. #
  1568. # The current data items are:
  1569. #
  1570. # [BODY]
  1571. # A form of BODYSTRUCTURE without extension data.
  1572. # [BODY[<section>]<<origin_octet>>]
  1573. # A string expressing the body contents of the specified section.
  1574. # [BODYSTRUCTURE]
  1575. # An object that describes the [MIME-IMB] body structure of a message.
  1576. # See Net::IMAP::BodyTypeBasic, Net::IMAP::BodyTypeText,
  1577. # Net::IMAP::BodyTypeMessage, Net::IMAP::BodyTypeMultipart.
  1578. # [ENVELOPE]
  1579. # A Net::IMAP::Envelope object that describes the envelope
  1580. # structure of a message.
  1581. # [FLAGS]
  1582. # A array of flag symbols that are set for this message. flag symbols
  1583. # are capitalized by String#capitalize.
  1584. # [INTERNALDATE]
  1585. # A string representing the internal date of the message.
  1586. # [RFC822]
  1587. # Equivalent to BODY[].
  1588. # [RFC822.HEADER]
  1589. # Equivalent to BODY.PEEK[HEADER].
  1590. # [RFC822.SIZE]
  1591. # A number expressing the [RFC-822] size of the message.
  1592. # [RFC822.TEXT]
  1593. # Equivalent to BODY[TEXT].
  1594. # [UID]
  1595. # A number expressing the unique identifier of the message.
  1596. #
  1597. FetchData = Struct.new(:seqno, :attr)
  1598. # Net::IMAP::Envelope represents envelope structures of messages.
  1599. #
  1600. # ==== Fields:
  1601. #
  1602. # date:: Returns a string that represents the date.
  1603. #
  1604. # subject:: Returns a string that represents the subject.
  1605. #
  1606. # from:: Returns an array of Net::IMAP::Address that represents the from.
  1607. #
  1608. # sender:: Returns an array of Net::IMAP::Address that represents the sender.
  1609. #
  1610. # reply_to:: Returns an array of Net::IMAP::Address that represents the reply-to.
  1611. #
  1612. # to:: Returns an array of Net::IMAP::Address that represents the to.
  1613. #
  1614. # cc:: Returns an array of Net::IMAP::Address that represents the cc.
  1615. #
  1616. # bcc:: Returns an array of Net::IMAP::Address that represents the bcc.
  1617. #
  1618. # in_reply_to:: Returns a string that represents the in-reply-to.
  1619. #
  1620. # message_id:: Returns a string that represents the message-id.
  1621. #
  1622. Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to,
  1623. :to, :cc, :bcc, :in_reply_to, :message_id)
  1624. #
  1625. # Net::IMAP::Address represents electronic mail addresses.
  1626. #
  1627. # ==== Fields:
  1628. #
  1629. # name:: Returns the phrase from [RFC-822] mailbox.
  1630. #
  1631. # route:: Returns the route from [RFC-822] route-addr.
  1632. #
  1633. # mailbox:: nil indicates end of [RFC-822] group.
  1634. # If non-nil and host is nil, returns [RFC-822] group name.
  1635. # Otherwise, returns [RFC-822] local-part
  1636. #
  1637. # host:: nil indicates [RFC-822] group syntax.
  1638. # Otherwise, returns [RFC-822] domain name.
  1639. #
  1640. Address = Struct.new(:name, :route, :mailbox, :host)
  1641. #
  1642. # Net::IMAP::ContentDisposition represents Content-Disposition fields.
  1643. #
  1644. # ==== Fields:
  1645. #
  1646. # dsp_type:: Returns the disposition type.
  1647. #
  1648. # param:: Returns a hash that represents parameters of the Content-Disposition
  1649. # field.
  1650. #
  1651. ContentDisposition = Struct.new(:dsp_type, :param)
  1652. # Net::IMAP::ThreadMember represents a thread-node returned
  1653. # by Net::IMAP#thread
  1654. #
  1655. # ==== Fields:
  1656. #
  1657. # seqno:: The sequence number of this message.
  1658. #
  1659. # children:: an array of Net::IMAP::ThreadMember objects for mail
  1660. # items that are children of this in the thread.
  1661. #
  1662. ThreadMember = Struct.new(:seqno, :children)
  1663. # Net::IMAP::BodyTypeBasic represents basic body structures of messages.
  1664. #
  1665. # ==== Fields:
  1666. #
  1667. # media_type:: Returns the content media type name as defined in [MIME-IMB].
  1668. #
  1669. # subtype:: Returns the content subtype name as defined in [MIME-IMB].
  1670. #
  1671. # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
  1672. #
  1673. # content_id:: Returns a string giving the content id as defined in [MIME-IMB].
  1674. #
  1675. # description:: Returns a string giving the content description as defined in
  1676. # [MIME-IMB].
  1677. #
  1678. # encoding:: Returns a string giving the content transfer encoding as defined in
  1679. # [MIME-IMB].
  1680. #
  1681. # size:: Returns a number giving the size of the body in octets.
  1682. #
  1683. # md5:: Returns a string giving the body MD5 value as defined in [MD5].
  1684. #
  1685. # disposition:: Returns a Net::IMAP::ContentDisposition object giving
  1686. # the content disposition.
  1687. #
  1688. # language:: Returns a string or an array of strings giving the body
  1689. # language value as defined in [LANGUAGE-TAGS].
  1690. #
  1691. # extension:: Returns extension data.
  1692. #
  1693. # multipart?:: Returns false.
  1694. #
  1695. class BodyTypeBasic < Struct.new(:media_type, :subtype,
  1696. :param, :content_id,
  1697. :description, :encoding, :size,
  1698. :md5, :disposition, :language,
  1699. :extension)
  1700. def multipart?
  1701. return false
  1702. end
  1703. # Obsolete: use +subtype+ instead. Calling this will
  1704. # generate a warning message to +stderr+, then return
  1705. # the value of +subtype+.
  1706. def media_subtype
  1707. $stderr.printf("warning: media_subtype is obsolete.\n")
  1708. $stderr.printf(" use subtype instead.\n")
  1709. return subtype
  1710. end
  1711. end
  1712. # Net::IMAP::BodyTypeText represents TEXT body structures of messages.
  1713. #
  1714. # ==== Fields:
  1715. #
  1716. # lines:: Returns the size of the body in text lines.
  1717. #
  1718. # And Net::IMAP::BodyTypeText has all fields of Net::IMAP::BodyTypeBasic.
  1719. #
  1720. class BodyTypeText < Struct.new(:media_type, :subtype,
  1721. :param, :content_id,
  1722. :description, :encoding, :size,
  1723. :lines,
  1724. :md5, :disposition, :language,
  1725. :extension)
  1726. def multipart?
  1727. return false
  1728. end
  1729. # Obsolete: use +subtype+ instead. Calling this will
  1730. # generate a warning message to +stderr+, then return
  1731. # the value of +subtype+.
  1732. def media_subtype
  1733. $stderr.printf("warning: media_subtype is obsolete.\n")
  1734. $stderr.printf(" use subtype instead.\n")
  1735. return subtype
  1736. end
  1737. end
  1738. # Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.
  1739. #
  1740. # ==== Fields:
  1741. #
  1742. # envelope:: Returns a Net::IMAP::Envelope giving the envelope structure.
  1743. #
  1744. # body:: Returns an object giving the body structure.
  1745. #
  1746. # And Net::IMAP::BodyTypeMessage has all methods of Net::IMAP::BodyTypeText.
  1747. #
  1748. class BodyTypeMessage < Struct.new(:media_type, :subtype,
  1749. :param, :content_id,
  1750. :description, :encoding, :size,
  1751. :envelope, :body, :lines,
  1752. :md5, :disposition, :language,
  1753. :extension)
  1754. def multipart?
  1755. return false
  1756. end
  1757. # Obsolete: use +subtype+ instead. Calling this will
  1758. # generate a warning message to +stderr+, then return
  1759. # the value of +subtype+.
  1760. def media_subtype
  1761. $stderr.printf("warning: media_subtype is obsolete.\n")
  1762. $stderr.printf(" use subtype instead.\n")
  1763. return subtype
  1764. end
  1765. end
  1766. # Net::IMAP::BodyTypeMultipart represents multipart body structures
  1767. # of messages.
  1768. #
  1769. # ==== Fields:
  1770. #
  1771. # media_type:: Returns the content media type name as defined in [MIME-IMB].
  1772. #
  1773. # subtype:: Returns the content subtype name as defined in [MIME-IMB].
  1774. #
  1775. # parts:: Returns multiple parts.
  1776. #
  1777. # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
  1778. #
  1779. # disposition:: Returns a Net::IMAP::ContentDisposition object giving
  1780. # the content disposition.
  1781. #
  1782. # language:: Returns a string or an array of strings giving the body
  1783. # language value as defined in [LANGUAGE-TAGS].
  1784. #
  1785. # extension:: Returns extension data.
  1786. #
  1787. # multipart?:: Returns true.
  1788. #
  1789. class BodyTypeMultipart < Struct.new(:media_type, :subtype,
  1790. :parts,
  1791. :param, :disposition, :language,
  1792. :extension)
  1793. def multipart?
  1794. return true
  1795. end
  1796. # Obsolete: use +subtype+ instead. Calling this will
  1797. # generate a warning message to +stderr+, then return
  1798. # the value of +subtype+.
  1799. def media_subtype
  1800. $stderr.printf("warning: media_subtype is obsolete.\n")
  1801. $stderr.printf(" use subtype instead.\n")
  1802. return subtype
  1803. end
  1804. end
  1805. class ResponseParser # :nodoc:
  1806. def initialize
  1807. @str = nil
  1808. @pos = nil
  1809. @lex_state = nil
  1810. @token = nil
  1811. @flag_symbols = {}
  1812. end
  1813. def parse(str)
  1814. @str = str
  1815. @pos = 0
  1816. @lex_state = EXPR_BEG
  1817. @token = nil
  1818. return response
  1819. end
  1820. private
  1821. EXPR_BEG = :EXPR_BEG
  1822. EXPR_DATA = :EXPR_DATA
  1823. EXPR_TEXT = :EXPR_TEXT
  1824. EXPR_RTEXT = :EXPR_RTEXT
  1825. EXPR_CTEXT = :EXPR_CTEXT
  1826. T_SPACE = :SPACE
  1827. T_NIL = :NIL
  1828. T_NUMBER = :NUMBER
  1829. T_ATOM = :ATOM
  1830. T_QUOTED = :QUOTED
  1831. T_LPAR = :LPAR
  1832. T_RPAR = :RPAR
  1833. T_BSLASH = :BSLASH
  1834. T_STAR = :STAR
  1835. T_LBRA = :LBRA
  1836. T_RBRA = :RBRA
  1837. T_LITERAL = :LITERAL
  1838. T_PLUS = :PLUS
  1839. T_PERCENT = :PERCENT
  1840. T_CRLF = :CRLF
  1841. T_EOF = :EOF
  1842. T_TEXT = :TEXT
  1843. BEG_REGEXP = /\G(?:\
  1844. (?# 1: SPACE )( +)|\
  1845. (?# 2: NIL )(NIL)(?=[\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+])|\
  1846. (?# 3: NUMBER )(\d+)(?=[\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+])|\
  1847. (?# 4: ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+]+)|\
  1848. (?# 5: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
  1849. (?# 6: LPAR )(\()|\
  1850. (?# 7: RPAR )(\))|\
  1851. (?# 8: BSLASH )(\\)|\
  1852. (?# 9: STAR )(\*)|\
  1853. (?# 10: LBRA )(\[)|\
  1854. (?# 11: RBRA )(\])|\
  1855. (?# 12: LITERAL )\{(\d+)\}\r\n|\
  1856. (?# 13: PLUS )(\+)|\
  1857. (?# 14: PERCENT )(%)|\
  1858. (?# 15: CRLF )(\r\n)|\
  1859. (?# 16: EOF )(\z))/ni
  1860. DATA_REGEXP = /\G(?:\
  1861. (?# 1: SPACE )( )|\
  1862. (?# 2: NIL )(NIL)|\
  1863. (?# 3: NUMBER )(\d+)|\
  1864. (?# 4: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
  1865. (?# 5: LITERAL )\{(\d+)\}\r\n|\
  1866. (?# 6: LPAR )(\()|\
  1867. (?# 7: RPAR )(\)))/ni
  1868. TEXT_REGEXP = /\G(?:\
  1869. (?# 1: TEXT )([^\x00\r\n]*))/ni
  1870. RTEXT_REGEXP = /\G(?:\
  1871. (?# 1: LBRA )(\[)|\
  1872. (?# 2: TEXT )([^\x00\r\n]*))/ni
  1873. CTEXT_REGEXP = /\G(?:\
  1874. (?# 1: TEXT )([^\x00\r\n\]]*))/ni
  1875. Token = Struct.new(:symbol, :value)
  1876. def response
  1877. token = lookahead
  1878. case token.symbol
  1879. when T_PLUS
  1880. result = continue_req
  1881. when T_STAR
  1882. result = response_untagged
  1883. else
  1884. result = response_tagged
  1885. end
  1886. match(T_CRLF)
  1887. match(T_EOF)
  1888. return result
  1889. end
  1890. def continue_req
  1891. match(T_PLUS)
  1892. match(T_SPACE)
  1893. return ContinuationRequest.new(resp_text, @str)
  1894. end
  1895. def response_untagged
  1896. match(T_STAR)
  1897. match(T_SPACE)
  1898. token = lookahead
  1899. if token.symbol == T_NUMBER
  1900. return numeric_response
  1901. elsif token.symbol == T_ATOM
  1902. case token.value
  1903. when /\A(?:OK|NO|BAD|BYE|PREAUTH)\z/ni
  1904. return response_cond
  1905. when /\A(?:FLAGS)\z/ni
  1906. return flags_response
  1907. when /\A(?:LIST|LSUB)\z/ni
  1908. return list_response
  1909. when /\A(?:QUOTA)\z/ni
  1910. return getquota_response
  1911. when /\A(?:QUOTAROOT)\z/ni
  1912. return getquotaroot_response
  1913. when /\A(?:ACL)\z/ni
  1914. return getacl_response
  1915. when /\A(?:SEARCH|SORT)\z/ni
  1916. return search_response
  1917. when /\A(?:THREAD)\z/ni
  1918. return thread_response
  1919. when /\A(?:STATUS)\z/ni
  1920. return status_response
  1921. when /\A(?:CAPABILITY)\z/ni
  1922. return capability_response
  1923. else
  1924. return text_response
  1925. end
  1926. else
  1927. parse_error("unexpected token %s", token.symbol)
  1928. end
  1929. end
  1930. def response_tagged
  1931. tag = atom
  1932. match(T_SPACE)
  1933. token = match(T_ATOM)
  1934. name = token.value.upcase
  1935. match(T_SPACE)
  1936. return TaggedResponse.new(tag, name, resp_text, @str)
  1937. end
  1938. def response_cond
  1939. token = match(T_ATOM)
  1940. name = token.value.upcase
  1941. match(T_SPACE)
  1942. return UntaggedResponse.new(name, resp_text, @str)
  1943. end
  1944. def numeric_response
  1945. n = number
  1946. match(T_SPACE)
  1947. token = match(T_ATOM)
  1948. name = token.value.upcase
  1949. case name
  1950. when "EXISTS", "RECENT", "EXPUNGE"
  1951. return UntaggedResponse.new(name, n, @str)
  1952. when "FETCH"
  1953. shift_token
  1954. match(T_SPACE)
  1955. data = FetchData.new(n, msg_att)
  1956. return UntaggedResponse.new(name, data, @str)
  1957. end
  1958. end
  1959. def msg_att
  1960. match(T_LPAR)
  1961. attr = {}
  1962. while true
  1963. token = lookahead
  1964. case token.symbol
  1965. when T_RPAR
  1966. shift_token
  1967. break
  1968. when T_SPACE
  1969. shift_token
  1970. token = lookahead
  1971. end
  1972. case token.value
  1973. when /\A(?:ENVELOPE)\z/ni
  1974. name, val = envelope_data
  1975. when /\A(?:FLAGS)\z/ni
  1976. name, val = flags_data
  1977. when /\A(?:INTERNALDATE)\z/ni
  1978. name, val = internaldate_data
  1979. when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
  1980. name, val = rfc822_text
  1981. when /\A(?:RFC822\.SIZE)\z/ni
  1982. name, val = rfc822_size
  1983. when /\A(?:BODY(?:STRUCTURE)?)\z/ni
  1984. name, val = body_data
  1985. when /\A(?:UID)\z/ni
  1986. name, val = uid_data
  1987. else
  1988. parse_error("unknown attribute `%s'", token.value)
  1989. end
  1990. attr[name] = val
  1991. end
  1992. return attr
  1993. end
  1994. def envelope_data
  1995. token = match(T_ATOM)
  1996. name = token.value.upcase
  1997. match(T_SPACE)
  1998. return name, envelope
  1999. end
  2000. def envelope
  2001. @lex_state = EXPR_DATA
  2002. token = lookahead
  2003. if token.symbol == T_NIL
  2004. shift_token
  2005. result = nil
  2006. else
  2007. match(T_LPAR)
  2008. date = nstring
  2009. match(T_SPACE)
  2010. subject = nstring
  2011. match(T_SPACE)
  2012. from = address_list
  2013. match(T_SPACE)
  2014. sender = address_list
  2015. match(T_SPACE)
  2016. reply_to = address_list
  2017. match(T_SPACE)
  2018. to = address_list
  2019. match(T_SPACE)
  2020. cc = address_list
  2021. match(T_SPACE)
  2022. bcc = address_list
  2023. match(T_SPACE)
  2024. in_reply_to = nstring
  2025. match(T_SPACE)
  2026. message_id = nstring
  2027. match(T_RPAR)
  2028. result = Envelope.new(date, subject, from, sender, reply_to,
  2029. to, cc, bcc, in_reply_to, message_id)
  2030. end
  2031. @lex_state = EXPR_BEG
  2032. return result
  2033. end
  2034. def flags_data
  2035. token = match(T_ATOM)
  2036. name = token.value.upcase
  2037. match(T_SPACE)
  2038. return name, flag_list
  2039. end
  2040. def internaldate_data
  2041. token = match(T_ATOM)
  2042. name = token.value.upcase
  2043. match(T_SPACE)
  2044. token = match(T_QUOTED)
  2045. return name, token.value
  2046. end
  2047. def rfc822_text
  2048. token = match(T_ATOM)
  2049. name = token.value.upcase
  2050. match(T_SPACE)
  2051. return name, nstring
  2052. end
  2053. def rfc822_size
  2054. token = match(T_ATOM)
  2055. name = token.value.upcase
  2056. match(T_SPACE)
  2057. return name, number
  2058. end
  2059. def body_data
  2060. token = match(T_ATOM)
  2061. name = token.value.upcase
  2062. token = lookahead
  2063. if token.symbol == T_SPACE
  2064. shift_token
  2065. return name, body
  2066. end
  2067. name.concat(section)
  2068. token = lookahead
  2069. if token.symbol == T_ATOM
  2070. name.concat(token.value)
  2071. shift_token
  2072. end
  2073. match(T_SPACE)
  2074. data = nstring
  2075. return name, data
  2076. end
  2077. def body
  2078. @lex_state = EXPR_DATA
  2079. token = lookahead
  2080. if token.symbol == T_NIL
  2081. shift_token
  2082. result = nil
  2083. else
  2084. match(T_LPAR)
  2085. token = lookahead
  2086. if token.symbol == T_LPAR
  2087. result = body_type_mpart
  2088. else
  2089. result = body_type_1part
  2090. end
  2091. match(T_RPAR)
  2092. end
  2093. @lex_state = EXPR_BEG
  2094. return result
  2095. end
  2096. def body_type_1part
  2097. token = lookahead
  2098. case token.value
  2099. when /\A(?:TEXT)\z/ni
  2100. return body_type_text
  2101. when /\A(?:MESSAGE)\z/ni
  2102. return body_type_msg
  2103. else
  2104. return body_type_basic
  2105. end
  2106. end
  2107. def body_type_basic
  2108. mtype, msubtype = media_type
  2109. token = lookahead
  2110. if token.symbol == T_RPAR
  2111. return BodyTypeBasic.new(mtype, msubtype)
  2112. end
  2113. match(T_SPACE)
  2114. param, content_id, desc, enc, size = body_fields
  2115. md5, disposition, language, extension = body_ext_1part
  2116. return BodyTypeBasic.new(mtype, msubtype,
  2117. param, content_id,
  2118. desc, enc, size,
  2119. md5, disposition, language, extension)
  2120. end
  2121. def body_type_text
  2122. mtype, msubtype = media_type
  2123. match(T_SPACE)
  2124. param, content_id, desc, enc, size = body_fields
  2125. match(T_SPACE)
  2126. lines = number
  2127. md5, disposition, language, extension = body_ext_1part
  2128. return BodyTypeText.new(mtype, msubtype,
  2129. param, content_id,
  2130. desc, enc, size,
  2131. lines,
  2132. md5, disposition, language, extension)
  2133. end
  2134. def body_type_msg
  2135. mtype, msubtype = media_type
  2136. match(T_SPACE)
  2137. param, content_id, desc, enc, size = body_fields
  2138. match(T_SPACE)
  2139. env = envelope
  2140. match(T_SPACE)
  2141. b = body
  2142. match(T_SPACE)
  2143. lines = number
  2144. md5, disposition, language, extension = body_ext_1part
  2145. return BodyTypeMessage.new(mtype, msubtype,
  2146. param, content_id,
  2147. desc, enc, size,
  2148. env, b, lines,
  2149. md5, disposition, language, extension)
  2150. end
  2151. def body_type_mpart
  2152. parts = []
  2153. while true
  2154. token = lookahead
  2155. if token.symbol == T_SPACE
  2156. shift_token
  2157. break
  2158. end
  2159. parts.push(body)
  2160. end
  2161. mtype = "MULTIPART"
  2162. msubtype = case_insensitive_string
  2163. param, disposition, language, extension = body_ext_mpart
  2164. return BodyTypeMultipart.new(mtype, msubtype, parts,
  2165. param, disposition, language,
  2166. extension)
  2167. end
  2168. def media_type
  2169. mtype = case_insensitive_string
  2170. match(T_SPACE)
  2171. msubtype = case_insensitive_string
  2172. return mtype, msubtype
  2173. end
  2174. def body_fields
  2175. param = body_fld_param
  2176. match(T_SPACE)
  2177. content_id = nstring
  2178. match(T_SPACE)
  2179. desc = nstring
  2180. match(T_SPACE)
  2181. enc = case_insensitive_string
  2182. match(T_SPACE)
  2183. size = number
  2184. return param, content_id, desc, enc, size
  2185. end
  2186. def body_fld_param
  2187. token = lookahead
  2188. if token.symbol == T_NIL
  2189. shift_token
  2190. return nil
  2191. end
  2192. match(T_LPAR)
  2193. param = {}
  2194. while true
  2195. token = lookahead
  2196. case token.symbol
  2197. when T_RPAR
  2198. shift_token
  2199. break
  2200. when T_SPACE
  2201. shift_token
  2202. end
  2203. name = case_insensitive_string
  2204. match(T_SPACE)
  2205. val = string
  2206. param[name] = val
  2207. end
  2208. return param
  2209. end
  2210. def body_ext_1part
  2211. token = lookahead
  2212. if token.symbol == T_SPACE
  2213. shift_token
  2214. else
  2215. return nil
  2216. end
  2217. md5 = nstring
  2218. token = lookahead
  2219. if token.symbol == T_SPACE
  2220. shift_token
  2221. else
  2222. return md5
  2223. end
  2224. disposition = body_fld_dsp
  2225. token = lookahead
  2226. if token.symbol == T_SPACE
  2227. shift_token
  2228. else
  2229. return md5, disposition
  2230. end
  2231. language = body_fld_lang
  2232. token = lookahead
  2233. if token.symbol == T_SPACE
  2234. shift_token
  2235. else
  2236. return md5, disposition, language
  2237. end
  2238. extension = body_extensions
  2239. return md5, disposition, language, extension
  2240. end
  2241. def body_ext_mpart
  2242. token = lookahead
  2243. if token.symbol == T_SPACE
  2244. shift_token
  2245. else
  2246. return nil
  2247. end
  2248. param = body_fld_param
  2249. token = lookahead
  2250. if token.symbol == T_SPACE
  2251. shift_token
  2252. else
  2253. return param
  2254. end
  2255. disposition = body_fld_dsp
  2256. match(T_SPACE)
  2257. language = body_fld_lang
  2258. token = lookahead
  2259. if token.symbol == T_SPACE
  2260. shift_token
  2261. else
  2262. return param, disposition, language
  2263. end
  2264. extension = body_extensions
  2265. return param, disposition, language, extension
  2266. end
  2267. def body_fld_dsp
  2268. token = lookahead
  2269. if token.symbol == T_NIL
  2270. shift_token
  2271. return nil
  2272. end
  2273. match(T_LPAR)
  2274. dsp_type = case_insensitive_string
  2275. match(T_SPACE)
  2276. param = body_fld_param
  2277. match(T_RPAR)
  2278. return ContentDisposition.new(dsp_type, param)
  2279. end
  2280. def body_fld_lang
  2281. token = lookahead
  2282. if token.symbol == T_LPAR
  2283. shift_token
  2284. result = []
  2285. while true
  2286. token = lookahead
  2287. case token.symbol
  2288. when T_RPAR
  2289. shift_token
  2290. return result
  2291. when T_SPACE
  2292. shift_token
  2293. end
  2294. result.push(case_insensitive_string)
  2295. end
  2296. else
  2297. lang = nstring
  2298. if lang
  2299. return lang.upcase
  2300. else
  2301. return lang
  2302. end
  2303. end
  2304. end
  2305. def body_extensions
  2306. result = []
  2307. while true
  2308. token = lookahead
  2309. case token.symbol
  2310. when T_RPAR
  2311. return result
  2312. when T_SPACE
  2313. shift_token
  2314. end
  2315. result.push(body_extension)
  2316. end
  2317. end
  2318. def body_extension
  2319. token = lookahead
  2320. case token.symbol
  2321. when T_LPAR
  2322. shift_token
  2323. result = body_extensions
  2324. match(T_RPAR)
  2325. return result
  2326. when T_NUMBER
  2327. return number
  2328. else
  2329. return nstring
  2330. end
  2331. end
  2332. def section
  2333. str = ""
  2334. token = match(T_LBRA)
  2335. str.concat(token.value)
  2336. token = match(T_ATOM, T_NUMBER, T_RBRA)
  2337. if token.symbol == T_RBRA
  2338. str.concat(token.value)
  2339. return str
  2340. end
  2341. str.concat(token.value)
  2342. token = lookahead
  2343. if token.symbol == T_SPACE
  2344. shift_token
  2345. str.concat(token.value)
  2346. token = match(T_LPAR)
  2347. str.concat(token.value)
  2348. while true
  2349. token = lookahead
  2350. case token.symbol
  2351. when T_RPAR
  2352. str.concat(token.value)
  2353. shift_token
  2354. break
  2355. when T_SPACE
  2356. shift_token
  2357. str.concat(token.value)
  2358. end
  2359. str.concat(format_string(astring))
  2360. end
  2361. end
  2362. token = match(T_RBRA)
  2363. str.concat(token.value)
  2364. return str
  2365. end
  2366. def format_string(str)
  2367. case str
  2368. when ""
  2369. return '""'
  2370. when /[\x80-\xff\r\n]/n
  2371. # literal
  2372. return "{" + str.length.to_s + "}" + CRLF + str
  2373. when /[(){ \x00-\x1f\x7f%*"\\]/n
  2374. # quoted string
  2375. return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
  2376. else
  2377. # atom
  2378. return str
  2379. end
  2380. end
  2381. def uid_data
  2382. token = match(T_ATOM)
  2383. name = token.value.upcase
  2384. match(T_SPACE)
  2385. return name, number
  2386. end
  2387. def text_response
  2388. token = match(T_ATOM)
  2389. name = token.value.upcase
  2390. match(T_SPACE)
  2391. @lex_state = EXPR_TEXT
  2392. token = match(T_TEXT)
  2393. @lex_state = EXPR_BEG
  2394. return UntaggedResponse.new(name, token.value)
  2395. end
  2396. def flags_response
  2397. token = match(T_ATOM)
  2398. name = token.value.upcase
  2399. match(T_SPACE)
  2400. return UntaggedResponse.new(name, flag_list, @str)
  2401. end
  2402. def list_response
  2403. token = match(T_ATOM)
  2404. name = token.value.upcase
  2405. match(T_SPACE)
  2406. return UntaggedResponse.new(name, mailbox_list, @str)
  2407. end
  2408. def mailbox_list
  2409. attr = flag_list
  2410. match(T_SPACE)
  2411. token = match(T_QUOTED, T_NIL)
  2412. if token.symbol == T_NIL
  2413. delim = nil
  2414. else
  2415. delim = token.value
  2416. end
  2417. match(T_SPACE)
  2418. name = astring
  2419. return MailboxList.new(attr, delim, name)
  2420. end
  2421. def getquota_response
  2422. # If quota never established, get back
  2423. # `NO Quota root does not exist'.
  2424. # If quota removed, get `()' after the
  2425. # folder spec with no mention of `STORAGE'.
  2426. token = match(T_ATOM)
  2427. name = token.value.upcase
  2428. match(T_SPACE)
  2429. mailbox = astring
  2430. match(T_SPACE)
  2431. match(T_LPAR)
  2432. token = lookahead
  2433. case token.symbol
  2434. when T_RPAR
  2435. shift_token
  2436. data = MailboxQuota.new(mailbox, nil, nil)
  2437. return UntaggedResponse.new(name, data, @str)
  2438. when T_ATOM
  2439. shift_token
  2440. match(T_SPACE)
  2441. token = match(T_NUMBER)
  2442. usage = token.value
  2443. match(T_SPACE)
  2444. token = match(T_NUMBER)
  2445. quota = token.value
  2446. match(T_RPAR)
  2447. data = MailboxQuota.new(mailbox, usage, quota)
  2448. return UntaggedResponse.new(name, data, @str)
  2449. else
  2450. parse_error("unexpected token %s", token.symbol)
  2451. end
  2452. end
  2453. def getquotaroot_response
  2454. # Similar to getquota, but only admin can use getquota.
  2455. token = match(T_ATOM)
  2456. name = token.value.upcase
  2457. match(T_SPACE)
  2458. mailbox = astring
  2459. quotaroots = []
  2460. while true
  2461. token = lookahead
  2462. break unless token.symbol == T_SPACE
  2463. shift_token
  2464. quotaroots.push(astring)
  2465. end
  2466. data = MailboxQuotaRoot.new(mailbox, quotaroots)
  2467. return UntaggedResponse.new(name, data, @str)
  2468. end
  2469. def getacl_response
  2470. token = match(T_ATOM)
  2471. name = token.value.upcase
  2472. match(T_SPACE)
  2473. mailbox = astring
  2474. data = []
  2475. token = lookahead
  2476. if token.symbol == T_SPACE
  2477. shift_token
  2478. while true
  2479. token = lookahead
  2480. case token.symbol
  2481. when T_CRLF
  2482. break
  2483. when T_SPACE
  2484. shift_token
  2485. end
  2486. user = astring
  2487. match(T_SPACE)
  2488. rights = astring
  2489. ##XXX data.push([user, rights])
  2490. data.push(MailboxACLItem.new(user, rights))
  2491. end
  2492. end
  2493. return UntaggedResponse.new(name, data, @str)
  2494. end
  2495. def search_response
  2496. token = match(T_ATOM)
  2497. name = token.value.upcase
  2498. token = lookahead
  2499. if token.symbol == T_SPACE
  2500. shift_token
  2501. data = []
  2502. while true
  2503. token = lookahead
  2504. case token.symbol
  2505. when T_CRLF
  2506. break
  2507. when T_SPACE
  2508. shift_token
  2509. end
  2510. data.push(number)
  2511. end
  2512. else
  2513. data = []
  2514. end
  2515. return UntaggedResponse.new(name, data, @str)
  2516. end
  2517. def thread_response
  2518. token = match(T_ATOM)
  2519. name = token.value.upcase
  2520. token = lookahead
  2521. if token.symbol == T_SPACE
  2522. threads = []
  2523. while true
  2524. shift_token
  2525. token = lookahead
  2526. case token.symbol
  2527. when T_LPAR
  2528. threads << thread_branch(token)
  2529. when T_CRLF
  2530. break
  2531. end
  2532. end
  2533. else
  2534. # no member
  2535. threads = []
  2536. end
  2537. return UntaggedResponse.new(name, threads, @str)
  2538. end
  2539. def thread_branch(token)
  2540. rootmember = nil
  2541. lastmember = nil
  2542. while true
  2543. shift_token # ignore first T_LPAR
  2544. token = lookahead
  2545. case token.symbol
  2546. when T_NUMBER
  2547. # new member
  2548. newmember = ThreadMember.new(number, [])
  2549. if rootmember.nil?
  2550. rootmember = newmember
  2551. else
  2552. lastmember.children << newmember
  2553. end
  2554. lastmember = newmember
  2555. when T_SPACE
  2556. # do nothing
  2557. when T_LPAR
  2558. if rootmember.nil?
  2559. # dummy member
  2560. lastmember = rootmember = ThreadMember.new(nil, [])
  2561. end
  2562. lastmember.children << thread_branch(token)
  2563. when T_RPAR
  2564. break
  2565. end
  2566. end
  2567. return rootmember
  2568. end
  2569. def status_response
  2570. token = match(T_ATOM)
  2571. name = token.value.upcase
  2572. match(T_SPACE)
  2573. mailbox = astring
  2574. match(T_SPACE)
  2575. match(T_LPAR)
  2576. attr = {}
  2577. while true
  2578. token = lookahead
  2579. case token.symbol
  2580. when T_RPAR
  2581. shift_token
  2582. break
  2583. when T_SPACE
  2584. shift_token
  2585. end
  2586. token = match(T_ATOM)
  2587. key = token.value.upcase
  2588. match(T_SPACE)
  2589. val = number
  2590. attr[key] = val
  2591. end
  2592. data = StatusData.new(mailbox, attr)
  2593. return UntaggedResponse.new(name, data, @str)
  2594. end
  2595. def capability_response
  2596. token = match(T_ATOM)
  2597. name = token.value.upcase
  2598. match(T_SPACE)
  2599. data = []
  2600. while true
  2601. token = lookahead
  2602. case token.symbol
  2603. when T_CRLF
  2604. break
  2605. when T_SPACE
  2606. shift_token
  2607. end
  2608. data.push(atom.upcase)
  2609. end
  2610. return UntaggedResponse.new(name, data, @str)
  2611. end
  2612. def resp_text
  2613. @lex_state = EXPR_RTEXT
  2614. token = lookahead
  2615. if token.symbol == T_LBRA
  2616. code = resp_text_code
  2617. else
  2618. code = nil
  2619. end
  2620. token = match(T_TEXT)
  2621. @lex_state = EXPR_BEG
  2622. return ResponseText.new(code, token.value)
  2623. end
  2624. def resp_text_code
  2625. @lex_state = EXPR_BEG
  2626. match(T_LBRA)
  2627. token = match(T_ATOM)
  2628. name = token.value.upcase
  2629. case name
  2630. when /\A(?:ALERT|PARSE|READ-ONLY|READ-WRITE|TRYCREATE|NOMODSEQ)\z/n
  2631. result = ResponseCode.new(name, nil)
  2632. when /\A(?:PERMANENTFLAGS)\z/n
  2633. match(T_SPACE)
  2634. result = ResponseCode.new(name, flag_list)
  2635. when /\A(?:UIDVALIDITY|UIDNEXT|UNSEEN)\z/n
  2636. match(T_SPACE)
  2637. result = ResponseCode.new(name, number)
  2638. else
  2639. token = lookahead
  2640. if token.symbol == T_SPACE
  2641. shift_token
  2642. @lex_state = EXPR_CTEXT
  2643. token = match(T_TEXT)
  2644. @lex_state = EXPR_BEG
  2645. result = ResponseCode.new(name, token.value)
  2646. else
  2647. result = ResponseCode.new(name, nil)
  2648. end
  2649. end
  2650. match(T_RBRA)
  2651. @lex_state = EXPR_RTEXT
  2652. return result
  2653. end
  2654. def address_list
  2655. token = lookahead
  2656. if token.symbol == T_NIL
  2657. shift_token
  2658. return nil
  2659. else
  2660. result = []
  2661. match(T_LPAR)
  2662. while true
  2663. token = lookahead
  2664. case token.symbol
  2665. when T_RPAR
  2666. shift_token
  2667. break
  2668. when T_SPACE
  2669. shift_token
  2670. end
  2671. result.push(address)
  2672. end
  2673. return result
  2674. end
  2675. end
  2676. ADDRESS_REGEXP = /\G\
  2677. (?# 1: NAME )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
  2678. (?# 2: ROUTE )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
  2679. (?# 3: MAILBOX )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
  2680. (?# 4: HOST )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)")\
  2681. \)/ni
  2682. def address
  2683. match(T_LPAR)
  2684. if @str.index(ADDRESS_REGEXP, @pos)
  2685. # address does not include literal.
  2686. @pos = $~.end(0)
  2687. name = $1
  2688. route = $2
  2689. mailbox = $3
  2690. host = $4
  2691. for s in [name, route, mailbox, host]
  2692. if s
  2693. s.gsub!(/\\(["\\])/n, "\\1")
  2694. end
  2695. end
  2696. else
  2697. name = nstring
  2698. match(T_SPACE)
  2699. route = nstring
  2700. match(T_SPACE)
  2701. mailbox = nstring
  2702. match(T_SPACE)
  2703. host = nstring
  2704. match(T_RPAR)
  2705. end
  2706. return Address.new(name, route, mailbox, host)
  2707. end
  2708. # def flag_list
  2709. # result = []
  2710. # match(T_LPAR)
  2711. # while true
  2712. # token = lookahead
  2713. # case token.symbol
  2714. # when T_RPAR
  2715. # shift_token
  2716. # break
  2717. # when T_SPACE
  2718. # shift_token
  2719. # end
  2720. # result.push(flag)
  2721. # end
  2722. # return result
  2723. # end
  2724. # def flag
  2725. # token = lookahead
  2726. # if token.symbol == T_BSLASH
  2727. # shift_token
  2728. # token = lookahead
  2729. # if token.symbol == T_STAR
  2730. # shift_token
  2731. # return token.value.intern
  2732. # else
  2733. # return atom.intern
  2734. # end
  2735. # else
  2736. # return atom
  2737. # end
  2738. # end
  2739. FLAG_REGEXP = /\
  2740. (?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
  2741. (?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n
  2742. def flag_list
  2743. if @str.index(/\(([^)]*)\)/ni, @pos)
  2744. @pos = $~.end(0)
  2745. return $1.scan(FLAG_REGEXP).collect { |flag, atom|
  2746. if atom
  2747. atom
  2748. else
  2749. symbol = flag.capitalize.untaint.intern
  2750. @flag_symbols[symbol] = true
  2751. if @flag_symbols.length > IMAP.max_flag_count
  2752. raise FlagCountError, "number of flag symbols exceeded"
  2753. end
  2754. symbol
  2755. end
  2756. }
  2757. else
  2758. parse_error("invalid flag list")
  2759. end
  2760. end
  2761. def nstring
  2762. token = lookahead
  2763. if token.symbol == T_NIL
  2764. shift_token
  2765. return nil
  2766. else
  2767. return string
  2768. end
  2769. end
  2770. def astring
  2771. token = lookahead
  2772. if string_token?(token)
  2773. return string
  2774. else
  2775. return atom
  2776. end
  2777. end
  2778. def string
  2779. token = lookahead
  2780. if token.symbol == T_NIL
  2781. shift_token
  2782. return nil
  2783. end
  2784. token = match(T_QUOTED, T_LITERAL)
  2785. return token.value
  2786. end
  2787. STRING_TOKENS = [T_QUOTED, T_LITERAL, T_NIL]
  2788. def string_token?(token)
  2789. return STRING_TOKENS.include?(token.symbol)
  2790. end
  2791. def case_insensitive_string
  2792. token = lookahead
  2793. if token.symbol == T_NIL
  2794. shift_token
  2795. return nil
  2796. end
  2797. token = match(T_QUOTED, T_LITERAL)
  2798. return token.value.upcase
  2799. end
  2800. def atom
  2801. result = ""
  2802. while true
  2803. token = lookahead
  2804. if atom_token?(token)
  2805. result.concat(token.value)
  2806. shift_token
  2807. else
  2808. if result.empty?
  2809. parse_error("unexpected token %s", token.symbol)
  2810. else
  2811. return result
  2812. end
  2813. end
  2814. end
  2815. end
  2816. ATOM_TOKENS = [
  2817. T_ATOM,
  2818. T_NUMBER,
  2819. T_NIL,
  2820. T_LBRA,
  2821. T_RBRA,
  2822. T_PLUS
  2823. ]
  2824. def atom_token?(token)
  2825. return ATOM_TOKENS.include?(token.symbol)
  2826. end
  2827. def number
  2828. token = lookahead
  2829. if token.symbol == T_NIL
  2830. shift_token
  2831. return nil
  2832. end
  2833. token = match(T_NUMBER)
  2834. return token.value.to_i
  2835. end
  2836. def nil_atom
  2837. match(T_NIL)
  2838. return nil
  2839. end
  2840. def match(*args)
  2841. token = lookahead
  2842. unless args.include?(token.symbol)
  2843. parse_error('unexpected token %s (expected %s)',
  2844. token.symbol.id2name,
  2845. args.collect {|i| i.id2name}.join(" or "))
  2846. end
  2847. shift_token
  2848. return token
  2849. end
  2850. def lookahead
  2851. unless @token
  2852. @token = next_token
  2853. end
  2854. return @token
  2855. end
  2856. def shift_token
  2857. @token = nil
  2858. end
  2859. def next_token
  2860. case @lex_state
  2861. when EXPR_BEG
  2862. if @str.index(BEG_REGEXP, @pos)
  2863. @pos = $~.end(0)
  2864. if $1
  2865. return Token.new(T_SPACE, $+)
  2866. elsif $2
  2867. return Token.new(T_NIL, $+)
  2868. elsif $3
  2869. return Token.new(T_NUMBER, $+)
  2870. elsif $4
  2871. return Token.new(T_ATOM, $+)
  2872. elsif $5
  2873. return Token.new(T_QUOTED,
  2874. $+.gsub(/\\(["\\])/n, "\\1"))
  2875. elsif $6
  2876. return Token.new(T_LPAR, $+)
  2877. elsif $7
  2878. return Token.new(T_RPAR, $+)
  2879. elsif $8
  2880. return Token.new(T_BSLASH, $+)
  2881. elsif $9
  2882. return Token.new(T_STAR, $+)
  2883. elsif $10
  2884. return Token.new(T_LBRA, $+)
  2885. elsif $11
  2886. return Token.new(T_RBRA, $+)
  2887. elsif $12
  2888. len = $+.to_i
  2889. val = @str[@pos, len]
  2890. @pos += len
  2891. return Token.new(T_LITERAL, val)
  2892. elsif $13
  2893. return Token.new(T_PLUS, $+)
  2894. elsif $14
  2895. return Token.new(T_PERCENT, $+)
  2896. elsif $15
  2897. return Token.new(T_CRLF, $+)
  2898. elsif $16
  2899. return Token.new(T_EOF, $+)
  2900. else
  2901. parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
  2902. end
  2903. else
  2904. @str.index(/\S*/n, @pos)
  2905. parse_error("unknown token - %s", $&.dump)
  2906. end
  2907. when EXPR_DATA
  2908. if @str.index(DATA_REGEXP, @pos)
  2909. @pos = $~.end(0)
  2910. if $1
  2911. return Token.new(T_SPACE, $+)
  2912. elsif $2
  2913. return Token.new(T_NIL, $+)
  2914. elsif $3
  2915. return Token.new(T_NUMBER, $+)
  2916. elsif $4
  2917. return Token.new(T_QUOTED,
  2918. $+.gsub(/\\(["\\])/n, "\\1"))
  2919. elsif $5
  2920. len = $+.to_i
  2921. val = @str[@pos, len]
  2922. @pos += len
  2923. return Token.new(T_LITERAL, val)
  2924. elsif $6
  2925. return Token.new(T_LPAR, $+)
  2926. elsif $7
  2927. return Token.new(T_RPAR, $+)
  2928. else
  2929. parse_error("[Net::IMAP BUG] DATA_REGEXP is invalid")
  2930. end
  2931. else
  2932. @str.index(/\S*/n, @pos)
  2933. parse_error("unknown token - %s", $&.dump)
  2934. end
  2935. when EXPR_TEXT
  2936. if @str.index(TEXT_REGEXP, @pos)
  2937. @pos = $~.end(0)
  2938. if $1
  2939. return Token.new(T_TEXT, $+)
  2940. else
  2941. parse_error("[Net::IMAP BUG] TEXT_REGEXP is invalid")
  2942. end
  2943. else
  2944. @str.index(/\S*/n, @pos)
  2945. parse_error("unknown token - %s", $&.dump)
  2946. end
  2947. when EXPR_RTEXT
  2948. if @str.index(RTEXT_REGEXP, @pos)
  2949. @pos = $~.end(0)
  2950. if $1
  2951. return Token.new(T_LBRA, $+)
  2952. elsif $2
  2953. return Token.new(T_TEXT, $+)
  2954. else
  2955. parse_error("[Net::IMAP BUG] RTEXT_REGEXP is invalid")
  2956. end
  2957. else
  2958. @str.index(/\S*/n, @pos)
  2959. parse_error("unknown token - %s", $&.dump)
  2960. end
  2961. when EXPR_CTEXT
  2962. if @str.index(CTEXT_REGEXP, @pos)
  2963. @pos = $~.end(0)
  2964. if $1
  2965. return Token.new(T_TEXT, $+)
  2966. else
  2967. parse_error("[Net::IMAP BUG] CTEXT_REGEXP is invalid")
  2968. end
  2969. else
  2970. @str.index(/\S*/n, @pos) #/
  2971. parse_error("unknown token - %s", $&.dump)
  2972. end
  2973. else
  2974. parse_error("invalid @lex_state - %s", @lex_state.inspect)
  2975. end
  2976. end
  2977. def parse_error(fmt, *args)
  2978. if IMAP.debug
  2979. $stderr.printf("@str: %s\n", @str.dump)
  2980. $stderr.printf("@pos: %d\n", @pos)
  2981. $stderr.printf("@lex_state: %s\n", @lex_state)
  2982. if @token
  2983. $stderr.printf("@token.symbol: %s\n", @token.symbol)
  2984. $stderr.printf("@token.value: %s\n", @token.value.inspect)
  2985. end
  2986. end
  2987. raise ResponseParseError, format(fmt, *args)
  2988. end
  2989. end
  2990. # Authenticator for the "LOGIN" authentication type. See
  2991. # #authenticate().
  2992. class LoginAuthenticator
  2993. def process(data)
  2994. case @state
  2995. when STATE_USER
  2996. @state = STATE_PASSWORD
  2997. return @user
  2998. when STATE_PASSWORD
  2999. return @password
  3000. end
  3001. end
  3002. private
  3003. STATE_USER = :USER
  3004. STATE_PASSWORD = :PASSWORD
  3005. def initialize(user, password)
  3006. @user = user
  3007. @password = password
  3008. @state = STATE_USER
  3009. end
  3010. end
  3011. add_authenticator "LOGIN", LoginAuthenticator
  3012. # Authenticator for the "PLAIN" authentication type. See
  3013. # #authenticate().
  3014. class PlainAuthenticator
  3015. def process(data)
  3016. return "\0#{@user}\0#{@password}"
  3017. end
  3018. private
  3019. def initialize(user, password)
  3020. @user = user
  3021. @password = password
  3022. end
  3023. end
  3024. add_authenticator "PLAIN", PlainAuthenticator
  3025. # Authenticator for the "CRAM-MD5" authentication type. See
  3026. # #authenticate().
  3027. class CramMD5Authenticator
  3028. def process(challenge)
  3029. digest = hmac_md5(challenge, @password)
  3030. return @user + " " + digest
  3031. end
  3032. private
  3033. def initialize(user, password)
  3034. @user = user
  3035. @password = password
  3036. end
  3037. def hmac_md5(text, key)
  3038. if key.length > 64
  3039. key = Digest::MD5.digest(key)
  3040. end
  3041. k_ipad = key + "\0" * (64 - key.length)
  3042. k_opad = key + "\0" * (64 - key.length)
  3043. for i in 0..63
  3044. k_ipad[i] = (k_ipad[i].ord ^ 0x36).chr
  3045. k_opad[i] = (k_opad[i].ord ^ 0x5c).chr
  3046. end
  3047. digest = Digest::MD5.digest(k_ipad + text)
  3048. return Digest::MD5.hexdigest(k_opad + digest)
  3049. end
  3050. end
  3051. add_authenticator "CRAM-MD5", CramMD5Authenticator
  3052. # Authenticator for the "DIGEST-MD5" authentication type. See
  3053. # #authenticate().
  3054. class DigestMD5Authenticator
  3055. def process(challenge)
  3056. case @stage
  3057. when STAGE_ONE
  3058. @stage = STAGE_TWO
  3059. sparams = {}
  3060. c = StringScanner.new(challenge)
  3061. while c.scan(/(?:\s*,)?\s*(\w+)=("(?:[^\\"]+|\\.)*"|[^,]+)\s*/)
  3062. k, v = c[1], c[2]
  3063. if v =~ /^"(.*)"$/
  3064. v = $1
  3065. if v =~ /,/
  3066. v = v.split(',')
  3067. end
  3068. end
  3069. sparams[k] = v
  3070. end
  3071. raise DataFormatError, "Bad Challenge: '#{challenge}'" unless c.rest.size == 0
  3072. raise Error, "Server does not support auth (qop = #{sparams['qop'].join(',')})" unless sparams['qop'].include?("auth")
  3073. response = {
  3074. :nonce => sparams['nonce'],
  3075. :username => @user,
  3076. :realm => sparams['realm'],
  3077. :cnonce => Digest::MD5.hexdigest("%.15f:%.15f:%d" % [Time.now.to_f, rand, Process.pid.to_s]),
  3078. :'digest-uri' => 'imap/' + sparams['realm'],
  3079. :qop => 'auth',
  3080. :maxbuf => 65535,
  3081. :nc => "%08d" % nc(sparams['nonce']),
  3082. :charset => sparams['charset'],
  3083. }
  3084. response[:authzid] = @authname unless @authname.nil?
  3085. # now, the real thing
  3086. a0 = Digest::MD5.digest( [ response.values_at(:username, :realm), @password ].join(':') )
  3087. a1 = [ a0, response.values_at(:nonce,:cnonce) ].join(':')
  3088. a1 << ':' + response[:authzid] unless response[:authzid].nil?
  3089. a2 = "AUTHENTICATE:" + response[:'digest-uri']
  3090. a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/
  3091. response[:response] = Digest::MD5.hexdigest(
  3092. [
  3093. Digest::MD5.hexdigest(a1),
  3094. response.values_at(:nonce, :nc, :cnonce, :qop),
  3095. Digest::MD5.hexdigest(a2)
  3096. ].join(':')
  3097. )
  3098. return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',')
  3099. when STAGE_TWO
  3100. @stage = nil
  3101. # if at the second stage, return an empty string
  3102. if challenge =~ /rspauth=/
  3103. return ''
  3104. else
  3105. raise ResponseParseError, challenge
  3106. end
  3107. else
  3108. raise ResponseParseError, challenge
  3109. end
  3110. end
  3111. def initialize(user, password, authname = nil)
  3112. @user, @password, @authname = user, password, authname
  3113. @nc, @stage = {}, STAGE_ONE
  3114. end
  3115. private
  3116. STAGE_ONE = :stage_one
  3117. STAGE_TWO = :stage_two
  3118. def nc(nonce)
  3119. if @nc.has_key? nonce
  3120. @nc[nonce] = @nc[nonce] + 1
  3121. else
  3122. @nc[nonce] = 1
  3123. end
  3124. return @nc[nonce]
  3125. end
  3126. # some responses need quoting
  3127. def qdval(k, v)
  3128. return if k.nil? or v.nil?
  3129. if %w"username authzid realm nonce cnonce digest-uri qop".include? k
  3130. v.gsub!(/([\\"])/, "\\\1")
  3131. return '%s="%s"' % [k, v]
  3132. else
  3133. return '%s=%s' % [k, v]
  3134. end
  3135. end
  3136. end
  3137. add_authenticator "DIGEST-MD5", DigestMD5Authenticator
  3138. # Superclass of IMAP errors.
  3139. class Error < StandardError
  3140. end
  3141. # Error raised when data is in the incorrect format.
  3142. class DataFormatError < Error
  3143. end
  3144. # Error raised when a response from the server is non-parseable.
  3145. class ResponseParseError < Error
  3146. end
  3147. # Superclass of all errors used to encapsulate "fail" responses
  3148. # from the server.
  3149. class ResponseError < Error
  3150. # The response that caused this error
  3151. attr_accessor :response
  3152. def initialize(response)
  3153. @response = response
  3154. super @response.data.text
  3155. end
  3156. end
  3157. # Error raised upon a "NO" response from the server, indicating
  3158. # that the client command could not be completed successfully.
  3159. class NoResponseError < ResponseError
  3160. end
  3161. # Error raised upon a "BAD" response from the server, indicating
  3162. # that the client command violated the IMAP protocol, or an internal
  3163. # server failure has occurred.
  3164. class BadResponseError < ResponseError
  3165. end
  3166. # Error raised upon a "BYE" response from the server, indicating
  3167. # that the client is not being allowed to login, or has been timed
  3168. # out due to inactivity.
  3169. class ByeResponseError < ResponseError
  3170. end
  3171. # Error raised when too many flags are interned to symbols.
  3172. class FlagCountError < Error
  3173. end
  3174. end
  3175. end
  3176. if __FILE__ == $0
  3177. # :enddoc:
  3178. require "getoptlong"
  3179. $stdout.sync = true
  3180. $port = nil
  3181. $user = ENV["USER"] || ENV["LOGNAME"]
  3182. $auth = "login"
  3183. $ssl = false
  3184. $starttls = false
  3185. def usage
  3186. <<EOF
  3187. usage: #{$0} [options] <host>
  3188. --help print this message
  3189. --port=PORT specifies port
  3190. --user=USER specifies user
  3191. --auth=AUTH specifies auth type
  3192. --starttls use starttls
  3193. --ssl use ssl
  3194. EOF
  3195. end
  3196. begin
  3197. require 'io/console'
  3198. rescue LoadError
  3199. def _noecho(&block)
  3200. system("stty", "-echo")
  3201. begin
  3202. yield STDIN
  3203. ensure
  3204. system("stty", "echo")
  3205. end
  3206. end
  3207. else
  3208. def _noecho(&block)
  3209. STDIN.noecho(&block)
  3210. end
  3211. end
  3212. def get_password
  3213. print "password: "
  3214. begin
  3215. return _noecho(&:gets).chomp
  3216. ensure
  3217. puts
  3218. end
  3219. end
  3220. def get_command
  3221. printf("%s@%s> ", $user, $host)
  3222. if line = gets
  3223. return line.strip.split(/\s+/)
  3224. else
  3225. return nil
  3226. end
  3227. end
  3228. parser = GetoptLong.new
  3229. parser.set_options(['--debug', GetoptLong::NO_ARGUMENT],
  3230. ['--help', GetoptLong::NO_ARGUMENT],
  3231. ['--port', GetoptLong::REQUIRED_ARGUMENT],
  3232. ['--user', GetoptLong::REQUIRED_ARGUMENT],
  3233. ['--auth', GetoptLong::REQUIRED_ARGUMENT],
  3234. ['--starttls', GetoptLong::NO_ARGUMENT],
  3235. ['--ssl', GetoptLong::NO_ARGUMENT])
  3236. begin
  3237. parser.each_option do |name, arg|
  3238. case name
  3239. when "--port"
  3240. $port = arg
  3241. when "--user"
  3242. $user = arg
  3243. when "--auth"
  3244. $auth = arg
  3245. when "--ssl"
  3246. $ssl = true
  3247. when "--starttls"
  3248. $starttls = true
  3249. when "--debug"
  3250. Net::IMAP.debug = true
  3251. when "--help"
  3252. usage
  3253. exit
  3254. end
  3255. end
  3256. rescue
  3257. abort usage
  3258. end
  3259. $host = ARGV.shift
  3260. unless $host
  3261. abort usage
  3262. end
  3263. imap = Net::IMAP.new($host, :port => $port, :ssl => $ssl)
  3264. begin
  3265. imap.starttls if $starttls
  3266. class << password = method(:get_password)
  3267. alias to_str call
  3268. end
  3269. imap.authenticate($auth, $user, password)
  3270. while true
  3271. cmd, *args = get_command
  3272. break unless cmd
  3273. begin
  3274. case cmd
  3275. when "list"
  3276. for mbox in imap.list("", args[0] || "*")
  3277. if mbox.attr.include?(Net::IMAP::NOSELECT)
  3278. prefix = "!"
  3279. elsif mbox.attr.include?(Net::IMAP::MARKED)
  3280. prefix = "*"
  3281. else
  3282. prefix = " "
  3283. end
  3284. print prefix, mbox.name, "\n"
  3285. end
  3286. when "select"
  3287. imap.select(args[0] || "inbox")
  3288. print "ok\n"
  3289. when "close"
  3290. imap.close
  3291. print "ok\n"
  3292. when "summary"
  3293. unless messages = imap.responses["EXISTS"][-1]
  3294. puts "not selected"
  3295. next
  3296. end
  3297. if messages > 0
  3298. for data in imap.fetch(1..-1, ["ENVELOPE"])
  3299. print data.seqno, ": ", data.attr["ENVELOPE"].subject, "\n"
  3300. end
  3301. else
  3302. puts "no message"
  3303. end
  3304. when "fetch"
  3305. if args[0]
  3306. data = imap.fetch(args[0].to_i, ["RFC822.HEADER", "RFC822.TEXT"])[0]
  3307. puts data.attr["RFC822.HEADER"]
  3308. puts data.attr["RFC822.TEXT"]
  3309. else
  3310. puts "missing argument"
  3311. end
  3312. when "logout", "exit", "quit"
  3313. break
  3314. when "help", "?"
  3315. print <<EOF
  3316. list [pattern] list mailboxes
  3317. select [mailbox] select mailbox
  3318. close close mailbox
  3319. summary display summary
  3320. fetch [msgno] display message
  3321. logout logout
  3322. help, ? display help message
  3323. EOF
  3324. else
  3325. print "unknown command: ", cmd, "\n"
  3326. end
  3327. rescue Net::IMAP::Error
  3328. puts $!
  3329. end
  3330. end
  3331. ensure
  3332. imap.logout
  3333. imap.disconnect
  3334. end
  3335. end