PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/net/imap.rb

https://github.com/thepelkus/ruby
Ruby | 3725 lines | 2429 code | 267 blank | 1029 comment | 143 complexity | ead4d398b1b845fc5d54cdd78fb2be88 MD5 | raw file
Possible License(s): 0BSD, Unlicense, GPL-2.0, BSD-3-Clause, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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::SSL)
  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. # The default port for IMAP connections, port 143
  275. def self.default_port
  276. return PORT
  277. end
  278. # The default port for IMAPS connections, port 993
  279. def self.default_tls_port
  280. return SSL_PORT
  281. end
  282. class << self
  283. alias default_imap_port default_port
  284. alias default_imaps_port default_tls_port
  285. alias default_ssl_port default_tls_port
  286. end
  287. # Disconnects from the server.
  288. def disconnect
  289. begin
  290. begin
  291. # try to call SSL::SSLSocket#io.
  292. @sock.io.shutdown
  293. rescue NoMethodError
  294. # @sock is not an SSL::SSLSocket.
  295. @sock.shutdown
  296. end
  297. rescue Errno::ENOTCONN
  298. # ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
  299. rescue Exception => e
  300. @receiver_thread.raise(e)
  301. end
  302. @receiver_thread.join
  303. synchronize do
  304. unless @sock.closed?
  305. @sock.close
  306. end
  307. end
  308. raise e if e
  309. end
  310. # Returns true if disconnected from the server.
  311. def disconnected?
  312. return @sock.closed?
  313. end
  314. # Sends a CAPABILITY command, and returns an array of
  315. # capabilities that the server supports. Each capability
  316. # is a string. See [IMAP] for a list of possible
  317. # capabilities.
  318. #
  319. # Note that the Net::IMAP class does not modify its
  320. # behaviour according to the capabilities of the server;
  321. # it is up to the user of the class to ensure that
  322. # a certain capability is supported by a server before
  323. # using it.
  324. def capability
  325. synchronize do
  326. send_command("CAPABILITY")
  327. return @responses.delete("CAPABILITY")[-1]
  328. end
  329. end
  330. # Sends a NOOP command to the server. It does nothing.
  331. def noop
  332. send_command("NOOP")
  333. end
  334. # Sends a LOGOUT command to inform the server that the client is
  335. # done with the connection.
  336. def logout
  337. send_command("LOGOUT")
  338. end
  339. # Sends a STARTTLS command to start TLS session.
  340. def starttls(options = {}, verify = true)
  341. send_command("STARTTLS") do |resp|
  342. if resp.kind_of?(TaggedResponse) && resp.name == "OK"
  343. begin
  344. # for backward compatibility
  345. certs = options.to_str
  346. options = create_ssl_params(certs, verify)
  347. rescue NoMethodError
  348. end
  349. start_tls_session(options)
  350. end
  351. end
  352. end
  353. # Sends an AUTHENTICATE command to authenticate the client.
  354. # The +auth_type+ parameter is a string that represents
  355. # the authentication mechanism to be used. Currently Net::IMAP
  356. # supports authentication mechanisms:
  357. #
  358. # LOGIN:: login using cleartext user and password.
  359. # CRAM-MD5:: login with cleartext user and encrypted password
  360. # (see [RFC-2195] for a full description). This
  361. # mechanism requires that the server have the user's
  362. # password stored in clear-text password.
  363. #
  364. # For both these mechanisms, there should be two +args+: username
  365. # and (cleartext) password. A server may not support one or other
  366. # of these mechanisms; check #capability() for a capability of
  367. # the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
  368. #
  369. # Authentication is done using the appropriate authenticator object:
  370. # see @@authenticators for more information on plugging in your own
  371. # authenticator.
  372. #
  373. # For example:
  374. #
  375. # imap.authenticate('LOGIN', user, password)
  376. #
  377. # A Net::IMAP::NoResponseError is raised if authentication fails.
  378. def authenticate(auth_type, *args)
  379. auth_type = auth_type.upcase
  380. unless @@authenticators.has_key?(auth_type)
  381. raise ArgumentError,
  382. format('unknown auth type - "%s"', auth_type)
  383. end
  384. authenticator = @@authenticators[auth_type].new(*args)
  385. send_command("AUTHENTICATE", auth_type) do |resp|
  386. if resp.instance_of?(ContinuationRequest)
  387. data = authenticator.process(resp.data.text.unpack("m")[0])
  388. s = [data].pack("m").gsub(/\n/, "")
  389. send_string_data(s)
  390. put_string(CRLF)
  391. end
  392. end
  393. end
  394. # Sends a LOGIN command to identify the client and carries
  395. # the plaintext +password+ authenticating this +user+. Note
  396. # that, unlike calling #authenticate() with an +auth_type+
  397. # of "LOGIN", #login() does *not* use the login authenticator.
  398. #
  399. # A Net::IMAP::NoResponseError is raised if authentication fails.
  400. def login(user, password)
  401. send_command("LOGIN", user, password)
  402. end
  403. # Sends a SELECT command to select a +mailbox+ so that messages
  404. # in the +mailbox+ can be accessed.
  405. #
  406. # After you have selected a mailbox, you may retrieve the
  407. # number of items in that mailbox from @responses["EXISTS"][-1],
  408. # and the number of recent messages from @responses["RECENT"][-1].
  409. # Note that these values can change if new messages arrive
  410. # during a session; see #add_response_handler() for a way of
  411. # detecting this event.
  412. #
  413. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  414. # exist or is for some reason non-selectable.
  415. def select(mailbox)
  416. synchronize do
  417. @responses.clear
  418. send_command("SELECT", mailbox)
  419. end
  420. end
  421. # Sends a EXAMINE command to select a +mailbox+ so that messages
  422. # in the +mailbox+ can be accessed. Behaves the same as #select(),
  423. # except that the selected +mailbox+ is identified as read-only.
  424. #
  425. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  426. # exist or is for some reason non-examinable.
  427. def examine(mailbox)
  428. synchronize do
  429. @responses.clear
  430. send_command("EXAMINE", mailbox)
  431. end
  432. end
  433. # Sends a CREATE command to create a new +mailbox+.
  434. #
  435. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  436. # cannot be created.
  437. def create(mailbox)
  438. send_command("CREATE", mailbox)
  439. end
  440. # Sends a DELETE command to remove the +mailbox+.
  441. #
  442. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  443. # cannot be deleted, either because it does not exist or because the
  444. # client does not have permission to delete it.
  445. def delete(mailbox)
  446. send_command("DELETE", mailbox)
  447. end
  448. # Sends a RENAME command to change the name of the +mailbox+ to
  449. # +newname+.
  450. #
  451. # A Net::IMAP::NoResponseError is raised if a mailbox with the
  452. # name +mailbox+ cannot be renamed to +newname+ for whatever
  453. # reason; for instance, because +mailbox+ does not exist, or
  454. # because there is already a mailbox with the name +newname+.
  455. def rename(mailbox, newname)
  456. send_command("RENAME", mailbox, newname)
  457. end
  458. # Sends a SUBSCRIBE command to add the specified +mailbox+ name to
  459. # the server's set of "active" or "subscribed" mailboxes as returned
  460. # by #lsub().
  461. #
  462. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  463. # subscribed to, for instance because it does not exist.
  464. def subscribe(mailbox)
  465. send_command("SUBSCRIBE", mailbox)
  466. end
  467. # Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
  468. # from the server's set of "active" or "subscribed" mailboxes.
  469. #
  470. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  471. # unsubscribed from, for instance because the client is not currently
  472. # subscribed to it.
  473. def unsubscribe(mailbox)
  474. send_command("UNSUBSCRIBE", mailbox)
  475. end
  476. # Sends a LIST command, and returns a subset of names from
  477. # the complete set of all names available to the client.
  478. # +refname+ provides a context (for instance, a base directory
  479. # in a directory-based mailbox hierarchy). +mailbox+ specifies
  480. # a mailbox or (via wildcards) mailboxes under that context.
  481. # Two wildcards may be used in +mailbox+: '*', which matches
  482. # all characters *including* the hierarchy delimiter (for instance,
  483. # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
  484. # which matches all characters *except* the hierarchy delimiter.
  485. #
  486. # If +refname+ is empty, +mailbox+ is used directly to determine
  487. # which mailboxes to match. If +mailbox+ is empty, the root
  488. # name of +refname+ and the hierarchy delimiter are returned.
  489. #
  490. # The return value is an array of +Net::IMAP::MailboxList+. For example:
  491. #
  492. # imap.create("foo/bar")
  493. # imap.create("foo/baz")
  494. # p imap.list("", "foo/%")
  495. # #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
  496. # #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
  497. # #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
  498. def list(refname, mailbox)
  499. synchronize do
  500. send_command("LIST", refname, mailbox)
  501. return @responses.delete("LIST")
  502. end
  503. end
  504. # Sends a XLIST command, and returns a subset of names from
  505. # the complete set of all names available to the client.
  506. # +refname+ provides a context (for instance, a base directory
  507. # in a directory-based mailbox hierarchy). +mailbox+ specifies
  508. # a mailbox or (via wildcards) mailboxes under that context.
  509. # Two wildcards may be used in +mailbox+: '*', which matches
  510. # all characters *including* the hierarchy delimiter (for instance,
  511. # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
  512. # which matches all characters *except* the hierarchy delimiter.
  513. #
  514. # If +refname+ is empty, +mailbox+ is used directly to determine
  515. # which mailboxes to match. If +mailbox+ is empty, the root
  516. # name of +refname+ and the hierarchy delimiter are returned.
  517. #
  518. # The XLIST command is like the LIST command except that the flags
  519. # returned refer to the function of the folder/mailbox, e.g. :Sent
  520. #
  521. # The return value is an array of +Net::IMAP::MailboxList+. For example:
  522. #
  523. # imap.create("foo/bar")
  524. # imap.create("foo/baz")
  525. # p imap.xlist("", "foo/%")
  526. # #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
  527. # #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
  528. # #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
  529. def xlist(refname, mailbox)
  530. synchronize do
  531. send_command("XLIST", refname, mailbox)
  532. return @responses.delete("XLIST")
  533. end
  534. end
  535. # Sends the GETQUOTAROOT command along with specified +mailbox+.
  536. # This command is generally available to both admin and user.
  537. # If mailbox exists, returns an array containing objects of
  538. # Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
  539. def getquotaroot(mailbox)
  540. synchronize do
  541. send_command("GETQUOTAROOT", mailbox)
  542. result = []
  543. result.concat(@responses.delete("QUOTAROOT"))
  544. result.concat(@responses.delete("QUOTA"))
  545. return result
  546. end
  547. end
  548. # Sends the GETQUOTA command along with specified +mailbox+.
  549. # If this mailbox exists, then an array containing a
  550. # Net::IMAP::MailboxQuota object is returned. This
  551. # command generally is only available to server admin.
  552. def getquota(mailbox)
  553. synchronize do
  554. send_command("GETQUOTA", mailbox)
  555. return @responses.delete("QUOTA")
  556. end
  557. end
  558. # Sends a SETQUOTA command along with the specified +mailbox+ and
  559. # +quota+. If +quota+ is nil, then quota will be unset for that
  560. # mailbox. Typically one needs to be logged in as server admin
  561. # for this to work. The IMAP quota commands are described in
  562. # [RFC-2087].
  563. def setquota(mailbox, quota)
  564. if quota.nil?
  565. data = '()'
  566. else
  567. data = '(STORAGE ' + quota.to_s + ')'
  568. end
  569. send_command("SETQUOTA", mailbox, RawData.new(data))
  570. end
  571. # Sends the SETACL command along with +mailbox+, +user+ and the
  572. # +rights+ that user is to have on that mailbox. If +rights+ is nil,
  573. # then that user will be stripped of any rights to that mailbox.
  574. # The IMAP ACL commands are described in [RFC-2086].
  575. def setacl(mailbox, user, rights)
  576. if rights.nil?
  577. send_command("SETACL", mailbox, user, "")
  578. else
  579. send_command("SETACL", mailbox, user, rights)
  580. end
  581. end
  582. # Send the GETACL command along with specified +mailbox+.
  583. # If this mailbox exists, an array containing objects of
  584. # Net::IMAP::MailboxACLItem will be returned.
  585. def getacl(mailbox)
  586. synchronize do
  587. send_command("GETACL", mailbox)
  588. return @responses.delete("ACL")[-1]
  589. end
  590. end
  591. # Sends a LSUB command, and returns a subset of names from the set
  592. # of names that the user has declared as being "active" or
  593. # "subscribed". +refname+ and +mailbox+ are interpreted as
  594. # for #list().
  595. # The return value is an array of +Net::IMAP::MailboxList+.
  596. def lsub(refname, mailbox)
  597. synchronize do
  598. send_command("LSUB", refname, mailbox)
  599. return @responses.delete("LSUB")
  600. end
  601. end
  602. # Sends a STATUS command, and returns the status of the indicated
  603. # +mailbox+. +attr+ is a list of one or more attributes that
  604. # we are request the status of. Supported attributes include:
  605. #
  606. # MESSAGES:: the number of messages in the mailbox.
  607. # RECENT:: the number of recent messages in the mailbox.
  608. # UNSEEN:: the number of unseen messages in the mailbox.
  609. #
  610. # The return value is a hash of attributes. For example:
  611. #
  612. # p imap.status("inbox", ["MESSAGES", "RECENT"])
  613. # #=> {"RECENT"=>0, "MESSAGES"=>44}
  614. #
  615. # A Net::IMAP::NoResponseError is raised if status values
  616. # for +mailbox+ cannot be returned, for instance because it
  617. # does not exist.
  618. def status(mailbox, attr)
  619. synchronize do
  620. send_command("STATUS", mailbox, attr)
  621. return @responses.delete("STATUS")[-1].attr
  622. end
  623. end
  624. # Sends a APPEND command to append the +message+ to the end of
  625. # the +mailbox+. The optional +flags+ argument is an array of
  626. # flags to initially passing to the new message. The optional
  627. # +date_time+ argument specifies the creation time to assign to the
  628. # new message; it defaults to the current time.
  629. # For example:
  630. #
  631. # imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
  632. # Subject: hello
  633. # From: shugo@ruby-lang.org
  634. # To: shugo@ruby-lang.org
  635. #
  636. # hello world
  637. # EOF
  638. #
  639. # A Net::IMAP::NoResponseError is raised if the mailbox does
  640. # not exist (it is not created automatically), or if the flags,
  641. # date_time, or message arguments contain errors.
  642. def append(mailbox, message, flags = nil, date_time = nil)
  643. args = []
  644. if flags
  645. args.push(flags)
  646. end
  647. args.push(date_time) if date_time
  648. args.push(Literal.new(message))
  649. send_command("APPEND", mailbox, *args)
  650. end
  651. # Sends a CHECK command to request a checkpoint of the currently
  652. # selected mailbox. This performs implementation-specific
  653. # housekeeping, for instance, reconciling the mailbox's
  654. # in-memory and on-disk state.
  655. def check
  656. send_command("CHECK")
  657. end
  658. # Sends a CLOSE command to close the currently selected mailbox.
  659. # The CLOSE command permanently removes from the mailbox all
  660. # messages that have the \Deleted flag set.
  661. def close
  662. send_command("CLOSE")
  663. end
  664. # Sends a EXPUNGE command to permanently remove from the currently
  665. # selected mailbox all messages that have the \Deleted flag set.
  666. def expunge
  667. synchronize do
  668. send_command("EXPUNGE")
  669. return @responses.delete("EXPUNGE")
  670. end
  671. end
  672. # Sends a SEARCH command to search the mailbox for messages that
  673. # match the given searching criteria, and returns message sequence
  674. # numbers. +keys+ can either be a string holding the entire
  675. # search string, or a single-dimension array of search keywords and
  676. # arguments. The following are some common search criteria;
  677. # see [IMAP] section 6.4.4 for a full list.
  678. #
  679. # <message set>:: a set of message sequence numbers. ',' indicates
  680. # an interval, ':' indicates a range. For instance,
  681. # '2,10:12,15' means "2,10,11,12,15".
  682. #
  683. # BEFORE <date>:: messages with an internal date strictly before
  684. # <date>. The date argument has a format similar
  685. # to 8-Aug-2002.
  686. #
  687. # BODY <string>:: messages that contain <string> within their body.
  688. #
  689. # CC <string>:: messages containing <string> in their CC field.
  690. #
  691. # FROM <string>:: messages that contain <string> in their FROM field.
  692. #
  693. # NEW:: messages with the \Recent, but not the \Seen, flag set.
  694. #
  695. # NOT <search-key>:: negate the following search key.
  696. #
  697. # OR <search-key> <search-key>:: "or" two search keys together.
  698. #
  699. # ON <date>:: messages with an internal date exactly equal to <date>,
  700. # which has a format similar to 8-Aug-2002.
  701. #
  702. # SINCE <date>:: messages with an internal date on or after <date>.
  703. #
  704. # SUBJECT <string>:: messages with <string> in their subject.
  705. #
  706. # TO <string>:: messages with <string> in their TO field.
  707. #
  708. # For example:
  709. #
  710. # p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
  711. # #=> [1, 6, 7, 8]
  712. def search(keys, charset = nil)
  713. return search_internal("SEARCH", keys, charset)
  714. end
  715. # As for #search(), but returns unique identifiers.
  716. def uid_search(keys, charset = nil)
  717. return search_internal("UID SEARCH", keys, charset)
  718. end
  719. # Sends a FETCH command to retrieve data associated with a message
  720. # in the mailbox. The +set+ parameter is a number or an array of
  721. # numbers or a Range object. The number is a message sequence
  722. # number. +attr+ is a list of attributes to fetch; see the
  723. # documentation for Net::IMAP::FetchData for a list of valid
  724. # attributes.
  725. # The return value is an array of Net::IMAP::FetchData. For example:
  726. #
  727. # p imap.fetch(6..8, "UID")
  728. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
  729. # #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
  730. # #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
  731. # p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
  732. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
  733. # data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
  734. # p data.seqno
  735. # #=> 6
  736. # p data.attr["RFC822.SIZE"]
  737. # #=> 611
  738. # p data.attr["INTERNALDATE"]
  739. # #=> "12-Oct-2000 22:40:59 +0900"
  740. # p data.attr["UID"]
  741. # #=> 98
  742. def fetch(set, attr)
  743. return fetch_internal("FETCH", set, attr)
  744. end
  745. # As for #fetch(), but +set+ contains unique identifiers.
  746. def uid_fetch(set, attr)
  747. return fetch_internal("UID FETCH", set, attr)
  748. end
  749. # Sends a STORE command to alter data associated with messages
  750. # in the mailbox, in particular their flags. The +set+ parameter
  751. # is a number or an array of numbers or a Range object. Each number
  752. # is a message sequence number. +attr+ is the name of a data item
  753. # to store: 'FLAGS' means to replace the message's flag list
  754. # with the provided one; '+FLAGS' means to add the provided flags;
  755. # and '-FLAGS' means to remove them. +flags+ is a list of flags.
  756. #
  757. # The return value is an array of Net::IMAP::FetchData. For example:
  758. #
  759. # p imap.store(6..8, "+FLAGS", [:Deleted])
  760. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  761. # #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  762. # #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
  763. def store(set, attr, flags)
  764. return store_internal("STORE", set, attr, flags)
  765. end
  766. # As for #store(), but +set+ contains unique identifiers.
  767. def uid_store(set, attr, flags)
  768. return store_internal("UID STORE", set, attr, flags)
  769. end
  770. # Sends a COPY command to copy the specified message(s) to the end
  771. # of the specified destination +mailbox+. The +set+ parameter is
  772. # a number or an array of numbers or a Range object. The number is
  773. # a message sequence number.
  774. def copy(set, mailbox)
  775. copy_internal("COPY", set, mailbox)
  776. end
  777. # As for #copy(), but +set+ contains unique identifiers.
  778. def uid_copy(set, mailbox)
  779. copy_internal("UID COPY", set, mailbox)
  780. end
  781. # Sends a SORT command to sort messages in the mailbox.
  782. # Returns an array of message sequence numbers. For example:
  783. #
  784. # p imap.sort(["FROM"], ["ALL"], "US-ASCII")
  785. # #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
  786. # p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
  787. # #=> [6, 7, 8, 1]
  788. #
  789. # See [SORT-THREAD-EXT] for more details.
  790. def sort(sort_keys, search_keys, charset)
  791. return sort_internal("SORT", sort_keys, search_keys, charset)
  792. end
  793. # As for #sort(), but returns an array of unique identifiers.
  794. def uid_sort(sort_keys, search_keys, charset)
  795. return sort_internal("UID SORT", sort_keys, search_keys, charset)
  796. end
  797. # Adds a response handler. For example, to detect when
  798. # the server sends us a new EXISTS response (which normally
  799. # indicates new messages being added to the mail box),
  800. # you could add the following handler after selecting the
  801. # mailbox.
  802. #
  803. # imap.add_response_handler { |resp|
  804. # if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
  805. # puts "Mailbox now has #{resp.data} messages"
  806. # end
  807. # }
  808. #
  809. def add_response_handler(handler = Proc.new)
  810. @response_handlers.push(handler)
  811. end
  812. # Removes the response handler.
  813. def remove_response_handler(handler)
  814. @response_handlers.delete(handler)
  815. end
  816. # As for #search(), but returns message sequence numbers in threaded
  817. # format, as a Net::IMAP::ThreadMember tree. The supported algorithms
  818. # are:
  819. #
  820. # ORDEREDSUBJECT:: split into single-level threads according to subject,
  821. # ordered by date.
  822. # REFERENCES:: split into threads by parent/child relationships determined
  823. # by which message is a reply to which.
  824. #
  825. # Unlike #search(), +charset+ is a required argument. US-ASCII
  826. # and UTF-8 are sample values.
  827. #
  828. # See [SORT-THREAD-EXT] for more details.
  829. def thread(algorithm, search_keys, charset)
  830. return thread_internal("THREAD", algorithm, search_keys, charset)
  831. end
  832. # As for #thread(), but returns unique identifiers instead of
  833. # message sequence numbers.
  834. def uid_thread(algorithm, search_keys, charset)
  835. return thread_internal("UID THREAD", algorithm, search_keys, charset)
  836. end
  837. # Sends an IDLE command that waits for notifications of new or expunged
  838. # messages. Yields responses from the server during the IDLE.
  839. #
  840. # Use #idle_done() to leave IDLE.
  841. def idle(&response_handler)
  842. raise LocalJumpError, "no block given" unless response_handler
  843. response = nil
  844. synchronize do
  845. tag = Thread.current[:net_imap_tag] = generate_tag
  846. put_string("#{tag} IDLE#{CRLF}")
  847. begin
  848. add_response_handler(response_handler)
  849. @idle_done_cond = new_cond
  850. @idle_done_cond.wait
  851. @idle_done_cond = nil
  852. if @receiver_thread_terminating
  853. raise Net::IMAP::Error, "connection closed"
  854. end
  855. ensure
  856. unless @receiver_thread_terminating
  857. remove_response_handler(response_handler)
  858. put_string("DONE#{CRLF}")
  859. response = get_tagged_response(tag, "IDLE")
  860. end
  861. end
  862. end
  863. return response
  864. end
  865. # Leaves IDLE.
  866. def idle_done
  867. synchronize do
  868. if @idle_done_cond.nil?
  869. raise Net::IMAP::Error, "not during IDLE"
  870. end
  871. @idle_done_cond.signal
  872. end
  873. end
  874. # Decode a string from modified UTF-7 format to UTF-8.
  875. #
  876. # UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a
  877. # slightly modified version of this to encode mailbox names
  878. # containing non-ASCII characters; see [IMAP] section 5.1.3.
  879. #
  880. # Net::IMAP does _not_ automatically encode and decode
  881. # mailbox names to and from utf7.
  882. def self.decode_utf7(s)
  883. return s.gsub(/&([^-]+)?-/n) {
  884. if $1
  885. ($1.tr(",", "/") + "===").unpack("m")[0].encode(Encoding::UTF_8, Encoding::UTF_16BE)
  886. else
  887. "&"
  888. end
  889. }
  890. end
  891. # Encode a string from UTF-8 format to modified UTF-7.
  892. def self.encode_utf7(s)
  893. return s.gsub(/(&)|[^\x20-\x7e]+/) {
  894. if $1
  895. "&-"
  896. else
  897. base64 = [$&.encode(Encoding::UTF_16BE)].pack("m")
  898. "&" + base64.delete("=\n").tr("/", ",") + "-"
  899. end
  900. }.force_encoding("ASCII-8BIT")
  901. end
  902. # Formats +time+ as an IMAP-style date.
  903. def self.format_date(time)
  904. return time.strftime('%d-%b-%Y')
  905. end
  906. # Formats +time+ as an IMAP-style date-time.
  907. def self.format_datetime(time)
  908. return time.strftime('%d-%b-%Y %H:%M %z')
  909. end
  910. private
  911. CRLF = "\r\n" # :nodoc:
  912. PORT = 143 # :nodoc:
  913. SSL_PORT = 993 # :nodoc:
  914. @@debug = false
  915. @@authenticators = {}
  916. @@max_flag_count = 10000
  917. # :call-seq:
  918. # Net::IMAP.new(host, options = {})
  919. #
  920. # Creates a new Net::IMAP object and connects it to the specified
  921. # +host+.
  922. #
  923. # +options+ is an option hash, each key of which is a symbol.
  924. #
  925. # The available options are:
  926. #
  927. # port:: port number (default value is 143 for imap, or 993 for imaps)
  928. # ssl:: if options[:ssl] is true, then an attempt will be made
  929. # to use SSL (now TLS) to connect to the server. For this to work
  930. # OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] extensions need to
  931. # be installed.
  932. # if options[:ssl] is a hash, it's passed to
  933. # OpenSSL::SSL::SSLContext#set_params as parameters.
  934. #
  935. # The most common errors are:
  936. #
  937. # Errno::ECONNREFUSED:: connection refused by +host+ or an intervening
  938. # firewall.
  939. # Errno::ETIMEDOUT:: connection timed out (possibly due to packets
  940. # being dropped by an intervening firewall).
  941. # Errno::ENETUNREACH:: there is no route to that network.
  942. # SocketError:: hostname not known or other socket error.
  943. # Net::IMAP::ByeResponseError:: we connected to the host, but they
  944. # immediately said goodbye to us.
  945. def initialize(host, port_or_options = {},
  946. usessl = false, certs = nil, verify = true)
  947. super()
  948. @host = host
  949. begin
  950. options = port_or_options.to_hash
  951. rescue NoMethodError
  952. # for backward compatibility
  953. options = {}
  954. options[:port] = port_or_options
  955. if usessl
  956. options[:ssl] = create_ssl_params(certs, verify)
  957. end
  958. end
  959. @port = options[:port] || (options[:ssl] ? SSL_PORT : PORT)
  960. @tag_prefix = "RUBY"
  961. @tagno = 0
  962. @parser = ResponseParser.new
  963. @sock = TCPSocket.open(@host, @port)
  964. if options[:ssl]
  965. start_tls_session(options[:ssl])
  966. @usessl = true
  967. else
  968. @usessl = false
  969. end
  970. @responses = Hash.new([].freeze)
  971. @tagged_responses = {}
  972. @response_handlers = []
  973. @tagged_response_arrival = new_cond
  974. @continuation_request_arrival = new_cond
  975. @idle_done_cond = nil
  976. @logout_command_tag = nil
  977. @debug_output_bol = true
  978. @exception = nil
  979. @greeting = get_response
  980. if @greeting.nil?
  981. @sock.close
  982. raise Error, "connection closed"
  983. end
  984. if @greeting.name == "BYE"
  985. @sock.close
  986. raise ByeResponseError, @greeting
  987. end
  988. @client_thread = Thread.current
  989. @receiver_thread = Thread.start {
  990. begin
  991. receive_responses
  992. rescue Exception
  993. end
  994. }
  995. @receiver_thread_terminating = false
  996. end
  997. def receive_responses
  998. connection_closed = false
  999. until connection_closed
  1000. synchronize do
  1001. @exception = nil
  1002. end
  1003. begin
  1004. resp = get_response
  1005. rescue Exception => e
  1006. synchronize do
  1007. @sock.close
  1008. @exception = e
  1009. end
  1010. break
  1011. end
  1012. unless resp
  1013. synchronize do
  1014. @exception = EOFError.new("end of file reached")
  1015. end
  1016. break
  1017. end
  1018. begin
  1019. synchronize do
  1020. case resp
  1021. when TaggedResponse
  1022. @tagged_responses[resp.tag] = resp
  1023. @tagged_response_arrival.broadcast
  1024. if resp.tag == @logout_command_tag
  1025. return
  1026. end
  1027. when UntaggedResponse
  1028. record_response(resp.name, resp.data)
  1029. if resp.data.instance_of?(ResponseText) &&
  1030. (code = resp.data.code)
  1031. record_response(code.name, code.data)
  1032. end
  1033. if resp.name == "BYE" && @logout_command_tag.nil?
  1034. @sock.close
  1035. @exception = ByeResponseError.new(resp)
  1036. connection_closed = true
  1037. end
  1038. when ContinuationRequest
  1039. @continuation_request_arrival.signal
  1040. end
  1041. @response_handlers.each do |handler|
  1042. handler.call(resp)
  1043. end
  1044. end
  1045. rescue Exception => e
  1046. @exception = e
  1047. synchronize do
  1048. @tagged_response_arrival.broadcast
  1049. @continuation_request_arrival.broadcast
  1050. end
  1051. end
  1052. end
  1053. synchronize do
  1054. @receiver_thread_terminating = true
  1055. @tagged_response_arrival.broadcast
  1056. @continuation_request_arrival.broadcast
  1057. if @idle_done_cond
  1058. @idle_done_cond.signal
  1059. end
  1060. end
  1061. end
  1062. def get_tagged_response(tag, cmd)
  1063. until @tagged_responses.key?(tag)
  1064. raise @exception if @exception
  1065. @tagged_response_arrival.wait
  1066. end
  1067. resp = @tagged_responses.delete(tag)
  1068. case resp.name
  1069. when /\A(?:NO)\z/ni
  1070. raise NoResponseError, resp
  1071. when /\A(?:BAD)\z/ni
  1072. raise BadResponseError, resp
  1073. else
  1074. return resp
  1075. end
  1076. end
  1077. def get_response
  1078. buff = ""
  1079. while true
  1080. s = @sock.gets(CRLF)
  1081. break unless s
  1082. buff.concat(s)
  1083. if /\{(\d+)\}\r\n/n =~ s
  1084. s = @sock.read($1.to_i)
  1085. buff.concat(s)
  1086. else
  1087. break
  1088. end
  1089. end
  1090. return nil if buff.length == 0
  1091. if @@debug
  1092. $stderr.print(buff.gsub(/^/n, "S: "))
  1093. end
  1094. return @parser.parse(buff)
  1095. end
  1096. def record_response(name, data)
  1097. unless @responses.has_key?(name)
  1098. @responses[name] = []
  1099. end
  1100. @responses[name].push(data)
  1101. end
  1102. def send_command(cmd, *args, &block)
  1103. synchronize do
  1104. args.each do |i|
  1105. validate_data(i)
  1106. end
  1107. tag = generate_tag
  1108. put_string(tag + " " + cmd)
  1109. args.each do |i|
  1110. put_string(" ")
  1111. send_data(i)
  1112. end
  1113. put_string(CRLF)
  1114. if cmd == "LOGOUT"
  1115. @logout_command_tag = tag
  1116. end
  1117. if block
  1118. add_response_handler(block)
  1119. end
  1120. begin
  1121. return get_tagged_response(tag, cmd)
  1122. ensure
  1123. if block
  1124. remove_response_handler(block)
  1125. end
  1126. end
  1127. end
  1128. end
  1129. def generate_tag
  1130. @tagno += 1
  1131. return format("%s%04d", @tag_prefix, @tagno)
  1132. end
  1133. def put_string(str)
  1134. @sock.print(str)
  1135. if @@debug
  1136. if @debug_output_bol
  1137. $stderr.print("C: ")
  1138. end
  1139. $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
  1140. if /\r\n\z/n.match(str)
  1141. @debug_output_bol = true
  1142. else
  1143. @debug_output_bol = false
  1144. end
  1145. end
  1146. end
  1147. def validate_data(data)
  1148. case data
  1149. when nil
  1150. when String
  1151. when Integer
  1152. if data < 0 || data >= 4294967296
  1153. raise DataFormatError, num.to_s
  1154. end
  1155. when Array
  1156. data.each do |i|
  1157. validate_data(i)
  1158. end
  1159. when Time
  1160. when Symbol
  1161. else
  1162. data.validate
  1163. end
  1164. end
  1165. def send_data(data)
  1166. case data
  1167. when nil
  1168. put_string("NIL")
  1169. when String
  1170. send_string_data(data)
  1171. when Integer
  1172. send_number_data(data)
  1173. when Array
  1174. send_list_data(data)
  1175. when Time
  1176. send_time_data(data)
  1177. when Symbol
  1178. send_symbol_data(data)
  1179. else
  1180. data.send_data(self)
  1181. end
  1182. end
  1183. def send_string_data(str)
  1184. case str
  1185. when ""
  1186. put_string('""')
  1187. when /[\x80-\xff\r\n]/n
  1188. # literal
  1189. send_literal(str)
  1190. when /[(){ \x00-\x1f\x7f%*"\\]/n
  1191. # quoted string
  1192. send_quoted_string(str)
  1193. else
  1194. put_string(str)
  1195. end
  1196. end
  1197. def send_quoted_string(str)
  1198. put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
  1199. end
  1200. def send_literal(str)
  1201. put_string("{" + str.bytesize.to_s + "}" + CRLF)
  1202. @continuation_request_arrival.wait
  1203. raise @exception if @exception
  1204. put_string(str)
  1205. end
  1206. def send_number_data(num)
  1207. put_string(num.to_s)
  1208. end
  1209. def send_list_data(list)
  1210. put_string("(")
  1211. first = true
  1212. list.each do |i|
  1213. if first
  1214. first = false
  1215. else
  1216. put_string(" ")
  1217. end
  1218. send_data(i)
  1219. end
  1220. put_string(")")
  1221. end
  1222. DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
  1223. def send_time_data(time)
  1224. t = time.dup.gmtime
  1225. s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
  1226. t.day, DATE_MONTH[t.month - 1], t.year,
  1227. t.hour, t.min, t.sec)
  1228. put_string(s)
  1229. end
  1230. def send_symbol_data(symbol)
  1231. put_string("\\" + symbol.to_s)
  1232. end
  1233. def search_internal(cmd, keys, charset)
  1234. if keys.instance_of?(String)
  1235. keys = [RawData.new(keys)]
  1236. else
  1237. normalize_searching_criteria(keys)
  1238. end
  1239. synchronize do
  1240. if charset
  1241. send_command(cmd, "CHARSET", charset, *keys)
  1242. else
  1243. send_command(cmd, *keys)
  1244. end
  1245. return @responses.delete("SEARCH")[-1]
  1246. end
  1247. end
  1248. def fetch_internal(cmd, set, attr)
  1249. case attr
  1250. when String then
  1251. attr = RawData.new(attr)
  1252. when Array then
  1253. attr = attr.map { |arg|
  1254. arg.is_a?(String) ? RawData.new(arg) : arg
  1255. }
  1256. end
  1257. synchronize do
  1258. @responses.delete("FETCH")
  1259. send_command(cmd, MessageSet.new(set), attr)
  1260. return @responses.delete("FETCH")
  1261. end
  1262. end
  1263. def store_internal(cmd, set, attr, flags)
  1264. if attr.instance_of?(String)
  1265. attr = RawData.new(attr)
  1266. end
  1267. synchronize do
  1268. @responses.delete("FETCH")
  1269. send_command(cmd, MessageSet.new(set), attr, flags)
  1270. return @responses.delete("FETCH")
  1271. end
  1272. end
  1273. def copy_internal(cmd, set, mailbox)
  1274. send_command(cmd, MessageSet.new(set), mailbox)
  1275. end
  1276. def sort_internal(cmd, sort_keys, search_keys, charset)
  1277. if search_keys.instance_of?(String)
  1278. search_keys = [RawData.new(search_keys)]
  1279. else
  1280. normalize_searching_criteria(search_keys)
  1281. end
  1282. normalize_searching_criteria(search_keys)
  1283. synchronize do
  1284. send_command(cmd, sort_keys, charset, *search_keys)
  1285. return @responses.delete("SORT")[-1]
  1286. end
  1287. end
  1288. def thread_internal(cmd, algorithm, search_keys, charset)
  1289. if search_keys.instance_of?(String)
  1290. search_keys = [RawData.new(search_keys)]
  1291. else
  1292. normalize_searching_criteria(search_keys)
  1293. end
  1294. normalize_searching_criteria(search_keys)
  1295. send_command(cmd, algorithm, charset, *search_keys)
  1296. return @responses.delete("THREAD")[-1]
  1297. end
  1298. def normalize_searching_criteria(keys)
  1299. keys.collect! do |i|
  1300. case i
  1301. when -1, Range, Array
  1302. MessageSet.new(i)
  1303. else
  1304. i
  1305. end
  1306. end
  1307. end
  1308. def create_ssl_params(certs = nil, verify = true)
  1309. params = {}
  1310. if certs
  1311. if File.file?(certs)
  1312. params[:ca_file] = certs
  1313. elsif File.directory?(certs)
  1314. params[:ca_path] = certs
  1315. end
  1316. end
  1317. if verify
  1318. params[:verify_mode] = VERIFY_PEER
  1319. else
  1320. params[:verify_mode] = VERIFY_NONE
  1321. end
  1322. return params
  1323. end
  1324. def start_tls_session(params = {})
  1325. unless defined?(OpenSSL::SSL)
  1326. raise "SSL extension not installed"
  1327. end
  1328. if @sock.kind_of?(OpenSSL::SSL::SSLSocket)
  1329. raise RuntimeError, "already using SSL"
  1330. end
  1331. begin
  1332. params = params.to_hash
  1333. rescue NoMethodError
  1334. params = {}
  1335. end
  1336. context = SSLContext.new
  1337. context.set_params(params)
  1338. if defined?(VerifyCallbackProc)
  1339. context.verify_callback = VerifyCallbackProc
  1340. end
  1341. @sock = SSLSocket.new(@sock, context)
  1342. @sock.sync_close = true
  1343. @sock.connect
  1344. if context.verify_mode != VERIFY_NONE
  1345. @sock.post_connection_check(@host)
  1346. end
  1347. end
  1348. class RawData # :nodoc:
  1349. def send_data(imap)
  1350. imap.send(:put_string, @data)
  1351. end
  1352. def validate
  1353. end
  1354. private
  1355. def initialize(data)
  1356. @data = data
  1357. end
  1358. end
  1359. class Atom # :nodoc:
  1360. def send_data(imap)
  1361. imap.send(:put_string, @data)
  1362. end
  1363. def validate
  1364. end
  1365. private
  1366. def initialize(data)
  1367. @data = data
  1368. end
  1369. end
  1370. class QuotedString # :nodoc:
  1371. def send_data(imap)
  1372. imap.send(:send_quoted_string, @data)
  1373. end
  1374. def validate
  1375. end
  1376. private
  1377. def initialize(data)
  1378. @data = data
  1379. end
  1380. end
  1381. class Literal # :nodoc:
  1382. def send_data(imap)
  1383. imap.send(:send_literal, @data)
  1384. end
  1385. def validate
  1386. end
  1387. private
  1388. def initialize(data)
  1389. @data = data
  1390. end
  1391. end
  1392. class MessageSet # :nodoc:
  1393. def send_data(imap)
  1394. imap.send(:put_string, format_internal(@data))
  1395. end
  1396. def validate
  1397. validate_internal(@data)
  1398. end
  1399. private
  1400. def initialize(data)
  1401. @data = data
  1402. end
  1403. def format_internal(data)
  1404. case data
  1405. when "*"
  1406. return data
  1407. when Integer
  1408. if data == -1
  1409. return "*"
  1410. else
  1411. return data.to_s
  1412. end
  1413. when Range
  1414. return format_internal(data.first) +
  1415. ":" + format_internal(data.last)
  1416. when Array
  1417. return data.collect {|i| format_internal(i)}.join(",")
  1418. when ThreadMember
  1419. return data.seqno.to_s +
  1420. ":" + data.children.collect {|i| format_internal(i).join(",")}
  1421. end
  1422. end
  1423. def valid…

Large files files are truncated, but you can click here to view the full file