PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/jruby-1.1.6RC1/lib/ruby/1.8/net/imap.rb

https://bitbucket.org/nicksieger/advent-jruby
Ruby | 3370 lines | 2193 code | 221 blank | 956 comment | 159 complexity | e862d5070edf0c72645934341e1fde79 MD5 | raw file
Possible License(s): CPL-1.0, AGPL-1.0, LGPL-2.1, JSON

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. begin
  18. require "openssl"
  19. rescue LoadError
  20. end
  21. module Net
  22. #
  23. # Net::IMAP implements Internet Message Access Protocol (IMAP) client
  24. # functionality. The protocol is described in [IMAP].
  25. #
  26. # == IMAP Overview
  27. #
  28. # An IMAP client connects to a server, and then authenticates
  29. # itself using either #authenticate() or #login(). Having
  30. # authenticated itself, there is a range of commands
  31. # available to it. Most work with mailboxes, which may be
  32. # arranged in an hierarchical namespace, and each of which
  33. # contains zero or more messages. How this is implemented on
  34. # the server is implementation-dependent; on a UNIX server, it
  35. # will frequently be implemented as a files in mailbox format
  36. # within a hierarchy of directories.
  37. #
  38. # To work on the messages within a mailbox, the client must
  39. # first select that mailbox, using either #select() or (for
  40. # read-only access) #examine(). Once the client has successfully
  41. # selected a mailbox, they enter _selected_ state, and that
  42. # mailbox becomes the _current_ mailbox, on which mail-item
  43. # related commands implicitly operate.
  44. #
  45. # Messages have two sorts of identifiers: message sequence
  46. # numbers, and UIDs.
  47. #
  48. # Message sequence numbers number messages within a mail box
  49. # from 1 up to the number of items in the mail box. If new
  50. # message arrives during a session, it receives a sequence
  51. # number equal to the new size of the mail box. If messages
  52. # are expunged from the mailbox, remaining messages have their
  53. # sequence numbers "shuffled down" to fill the gaps.
  54. #
  55. # UIDs, on the other hand, are permanently guaranteed not to
  56. # identify another message within the same mailbox, even if
  57. # the existing message is deleted. UIDs are required to
  58. # be assigned in ascending (but not necessarily sequential)
  59. # order within a mailbox; this means that if a non-IMAP client
  60. # rearranges the order of mailitems within a mailbox, the
  61. # UIDs have to be reassigned. An IMAP client cannot thus
  62. # rearrange message orders.
  63. #
  64. # == Examples of Usage
  65. #
  66. # === List sender and subject of all recent messages in the default mailbox
  67. #
  68. # imap = Net::IMAP.new('mail.example.com')
  69. # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  70. # imap.examine('INBOX')
  71. # imap.search(["RECENT"]).each do |message_id|
  72. # envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  73. # puts "#{envelope.from[0].name}: \t#{envelope.subject}"
  74. # end
  75. #
  76. # === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
  77. #
  78. # imap = Net::IMAP.new('mail.example.com')
  79. # imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  80. # imap.select('Mail/sent-mail')
  81. # if not imap.list('Mail/', 'sent-apr03')
  82. # imap.create('Mail/sent-apr03')
  83. # end
  84. # imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
  85. # imap.copy(message_id, "Mail/sent-apr03")
  86. # imap.store(message_id, "+FLAGS", [:Deleted])
  87. # end
  88. # imap.expunge
  89. #
  90. # == Thread Safety
  91. #
  92. # Net::IMAP supports concurrent threads. For example,
  93. #
  94. # imap = Net::IMAP.new("imap.foo.net", "imap2")
  95. # imap.authenticate("cram-md5", "bar", "password")
  96. # imap.select("inbox")
  97. # fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
  98. # search_result = imap.search(["BODY", "hello"])
  99. # fetch_result = fetch_thread.value
  100. # imap.disconnect
  101. #
  102. # This script invokes the FETCH command and the SEARCH command concurrently.
  103. #
  104. # == Errors
  105. #
  106. # An IMAP server can send three different types of responses to indicate
  107. # failure:
  108. #
  109. # NO:: the attempted command could not be successfully completed. For
  110. # instance, the username/password used for logging in are incorrect;
  111. # the selected mailbox does not exists; etc.
  112. #
  113. # BAD:: the request from the client does not follow the server's
  114. # understanding of the IMAP protocol. This includes attempting
  115. # commands from the wrong client state; for instance, attempting
  116. # to perform a SEARCH command without having SELECTed a current
  117. # mailbox. It can also signal an internal server
  118. # failure (such as a disk crash) has occurred.
  119. #
  120. # BYE:: the server is saying goodbye. This can be part of a normal
  121. # logout sequence, and can be used as part of a login sequence
  122. # to indicate that the server is (for some reason) unwilling
  123. # to accept our connection. As a response to any other command,
  124. # it indicates either that the server is shutting down, or that
  125. # the server is timing out the client connection due to inactivity.
  126. #
  127. # These three error response are represented by the errors
  128. # Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
  129. # Net::IMAP::ByeResponseError, all of which are subclasses of
  130. # Net::IMAP::ResponseError. Essentially, all methods that involve
  131. # sending a request to the server can generate one of these errors.
  132. # Only the most pertinent instances have been documented below.
  133. #
  134. # Because the IMAP class uses Sockets for communication, its methods
  135. # are also susceptible to the various errors that can occur when
  136. # working with sockets. These are generally represented as
  137. # Errno errors. For instance, any method that involves sending a
  138. # request to the server and/or receiving a response from it could
  139. # raise an Errno::EPIPE error if the network connection unexpectedly
  140. # goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2),
  141. # and associated man pages.
  142. #
  143. # Finally, a Net::IMAP::DataFormatError is thrown if low-level data
  144. # is found to be in an incorrect format (for instance, when converting
  145. # between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
  146. # thrown if a server response is non-parseable.
  147. #
  148. #
  149. # == References
  150. #
  151. # [[IMAP]]
  152. # M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
  153. # RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
  154. #
  155. # [[LANGUAGE-TAGS]]
  156. # Alvestrand, H., "Tags for the Identification of
  157. # Languages", RFC 1766, March 1995.
  158. #
  159. # [[MD5]]
  160. # Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
  161. # 1864, October 1995.
  162. #
  163. # [[MIME-IMB]]
  164. # Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
  165. # Mail Extensions) Part One: Format of Internet Message Bodies", RFC
  166. # 2045, November 1996.
  167. #
  168. # [[RFC-822]]
  169. # Crocker, D., "Standard for the Format of ARPA Internet Text
  170. # Messages", STD 11, RFC 822, University of Delaware, August 1982.
  171. #
  172. # [[RFC-2087]]
  173. # Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
  174. #
  175. # [[RFC-2086]]
  176. # Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
  177. #
  178. # [[RFC-2195]]
  179. # Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
  180. # for Simple Challenge/Response", RFC 2195, September 1997.
  181. #
  182. # [[SORT-THREAD-EXT]]
  183. # Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
  184. # Extensions", draft-ietf-imapext-sort, May 2003.
  185. #
  186. # [[OSSL]]
  187. # http://www.openssl.org
  188. #
  189. # [[RSSL]]
  190. # http://savannah.gnu.org/projects/rubypki
  191. #
  192. # [[UTF7]]
  193. # Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
  194. # Unicode", RFC 2152, May 1997.
  195. #
  196. class IMAP
  197. include MonitorMixin
  198. if defined?(OpenSSL)
  199. include OpenSSL
  200. include SSL
  201. end
  202. # Returns an initial greeting response from the server.
  203. attr_reader :greeting
  204. # Returns recorded untagged responses. For example:
  205. #
  206. # imap.select("inbox")
  207. # p imap.responses["EXISTS"][-1]
  208. # #=> 2
  209. # p imap.responses["UIDVALIDITY"][-1]
  210. # #=> 968263756
  211. attr_reader :responses
  212. # Returns all response handlers.
  213. attr_reader :response_handlers
  214. # The thread to receive exceptions.
  215. attr_accessor :client_thread
  216. # Flag indicating a message has been seen
  217. SEEN = :Seen
  218. # Flag indicating a message has been answered
  219. ANSWERED = :Answered
  220. # Flag indicating a message has been flagged for special or urgent
  221. # attention
  222. FLAGGED = :Flagged
  223. # Flag indicating a message has been marked for deletion. This
  224. # will occur when the mailbox is closed or expunged.
  225. DELETED = :Deleted
  226. # Flag indicating a message is only a draft or work-in-progress version.
  227. DRAFT = :Draft
  228. # Flag indicating that the message is "recent", meaning that this
  229. # session is the first session in which the client has been notified
  230. # of this message.
  231. RECENT = :Recent
  232. # Flag indicating that a mailbox context name cannot contain
  233. # children.
  234. NOINFERIORS = :Noinferiors
  235. # Flag indicating that a mailbox is not selected.
  236. NOSELECT = :Noselect
  237. # Flag indicating that a mailbox has been marked "interesting" by
  238. # the server; this commonly indicates that the mailbox contains
  239. # new messages.
  240. MARKED = :Marked
  241. # Flag indicating that the mailbox does not contains new messages.
  242. UNMARKED = :Unmarked
  243. # Returns the debug mode.
  244. def self.debug
  245. return @@debug
  246. end
  247. # Sets the debug mode.
  248. def self.debug=(val)
  249. return @@debug = val
  250. end
  251. # Adds an authenticator for Net::IMAP#authenticate. +auth_type+
  252. # is the type of authentication this authenticator supports
  253. # (for instance, "LOGIN"). The +authenticator+ is an object
  254. # which defines a process() method to handle authentication with
  255. # the server. See Net::IMAP::LoginAuthenticator and
  256. # Net::IMAP::CramMD5Authenticator for examples.
  257. #
  258. # If +auth_type+ refers to an existing authenticator, it will be
  259. # replaced by the new one.
  260. def self.add_authenticator(auth_type, authenticator)
  261. @@authenticators[auth_type] = authenticator
  262. end
  263. # Disconnects from the server.
  264. def disconnect
  265. if SSL::SSLSocket === @sock
  266. @sock.io.shutdown
  267. else
  268. @sock.shutdown
  269. end
  270. @receiver_thread.join
  271. @sock.close
  272. end
  273. # Returns true if disconnected from the server.
  274. def disconnected?
  275. return @sock.closed?
  276. end
  277. # Sends a CAPABILITY command, and returns an array of
  278. # capabilities that the server supports. Each capability
  279. # is a string. See [IMAP] for a list of possible
  280. # capabilities.
  281. #
  282. # Note that the Net::IMAP class does not modify its
  283. # behaviour according to the capabilities of the server;
  284. # it is up to the user of the class to ensure that
  285. # a certain capability is supported by a server before
  286. # using it.
  287. def capability
  288. synchronize do
  289. send_command("CAPABILITY")
  290. return @responses.delete("CAPABILITY")[-1]
  291. end
  292. end
  293. # Sends a NOOP command to the server. It does nothing.
  294. def noop
  295. send_command("NOOP")
  296. end
  297. # Sends a LOGOUT command to inform the server that the client is
  298. # done with the connection.
  299. def logout
  300. send_command("LOGOUT")
  301. end
  302. # Sends an AUTHENTICATE command to authenticate the client.
  303. # The +auth_type+ parameter is a string that represents
  304. # the authentication mechanism to be used. Currently Net::IMAP
  305. # supports authentication mechanisms:
  306. #
  307. # LOGIN:: login using cleartext user and password.
  308. # CRAM-MD5:: login with cleartext user and encrypted password
  309. # (see [RFC-2195] for a full description). This
  310. # mechanism requires that the server have the user's
  311. # password stored in clear-text password.
  312. #
  313. # For both these mechanisms, there should be two +args+: username
  314. # and (cleartext) password. A server may not support one or other
  315. # of these mechanisms; check #capability() for a capability of
  316. # the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
  317. #
  318. # Authentication is done using the appropriate authenticator object:
  319. # see @@authenticators for more information on plugging in your own
  320. # authenticator.
  321. #
  322. # For example:
  323. #
  324. # imap.authenticate('LOGIN', user, password)
  325. #
  326. # A Net::IMAP::NoResponseError is raised if authentication fails.
  327. def authenticate(auth_type, *args)
  328. auth_type = auth_type.upcase
  329. unless @@authenticators.has_key?(auth_type)
  330. raise ArgumentError,
  331. format('unknown auth type - "%s"', auth_type)
  332. end
  333. authenticator = @@authenticators[auth_type].new(*args)
  334. send_command("AUTHENTICATE", auth_type) do |resp|
  335. if resp.instance_of?(ContinuationRequest)
  336. data = authenticator.process(resp.data.text.unpack("m")[0])
  337. s = [data].pack("m").gsub(/\n/, "")
  338. send_string_data(s)
  339. put_string(CRLF)
  340. end
  341. end
  342. end
  343. # Sends a LOGIN command to identify the client and carries
  344. # the plaintext +password+ authenticating this +user+. Note
  345. # that, unlike calling #authenticate() with an +auth_type+
  346. # of "LOGIN", #login() does *not* use the login authenticator.
  347. #
  348. # A Net::IMAP::NoResponseError is raised if authentication fails.
  349. def login(user, password)
  350. send_command("LOGIN", user, password)
  351. end
  352. # Sends a SELECT command to select a +mailbox+ so that messages
  353. # in the +mailbox+ can be accessed.
  354. #
  355. # After you have selected a mailbox, you may retrieve the
  356. # number of items in that mailbox from @responses["EXISTS"][-1],
  357. # and the number of recent messages from @responses["RECENT"][-1].
  358. # Note that these values can change if new messages arrive
  359. # during a session; see #add_response_handler() for a way of
  360. # detecting this event.
  361. #
  362. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  363. # exist or is for some reason non-selectable.
  364. def select(mailbox)
  365. synchronize do
  366. @responses.clear
  367. send_command("SELECT", mailbox)
  368. end
  369. end
  370. # Sends a EXAMINE command to select a +mailbox+ so that messages
  371. # in the +mailbox+ can be accessed. Behaves the same as #select(),
  372. # except that the selected +mailbox+ is identified as read-only.
  373. #
  374. # A Net::IMAP::NoResponseError is raised if the mailbox does not
  375. # exist or is for some reason non-examinable.
  376. def examine(mailbox)
  377. synchronize do
  378. @responses.clear
  379. send_command("EXAMINE", mailbox)
  380. end
  381. end
  382. # Sends a CREATE command to create a new +mailbox+.
  383. #
  384. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  385. # cannot be created.
  386. def create(mailbox)
  387. send_command("CREATE", mailbox)
  388. end
  389. # Sends a DELETE command to remove the +mailbox+.
  390. #
  391. # A Net::IMAP::NoResponseError is raised if a mailbox with that name
  392. # cannot be deleted, either because it does not exist or because the
  393. # client does not have permission to delete it.
  394. def delete(mailbox)
  395. send_command("DELETE", mailbox)
  396. end
  397. # Sends a RENAME command to change the name of the +mailbox+ to
  398. # +newname+.
  399. #
  400. # A Net::IMAP::NoResponseError is raised if a mailbox with the
  401. # name +mailbox+ cannot be renamed to +newname+ for whatever
  402. # reason; for instance, because +mailbox+ does not exist, or
  403. # because there is already a mailbox with the name +newname+.
  404. def rename(mailbox, newname)
  405. send_command("RENAME", mailbox, newname)
  406. end
  407. # Sends a SUBSCRIBE command to add the specified +mailbox+ name to
  408. # the server's set of "active" or "subscribed" mailboxes as returned
  409. # by #lsub().
  410. #
  411. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  412. # subscribed to, for instance because it does not exist.
  413. def subscribe(mailbox)
  414. send_command("SUBSCRIBE", mailbox)
  415. end
  416. # Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
  417. # from the server's set of "active" or "subscribed" mailboxes.
  418. #
  419. # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
  420. # unsubscribed from, for instance because the client is not currently
  421. # subscribed to it.
  422. def unsubscribe(mailbox)
  423. send_command("UNSUBSCRIBE", mailbox)
  424. end
  425. # Sends a LIST command, and returns a subset of names from
  426. # the complete set of all names available to the client.
  427. # +refname+ provides a context (for instance, a base directory
  428. # in a directory-based mailbox hierarchy). +mailbox+ specifies
  429. # a mailbox or (via wildcards) mailboxes under that context.
  430. # Two wildcards may be used in +mailbox+: '*', which matches
  431. # all characters *including* the hierarchy delimiter (for instance,
  432. # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
  433. # which matches all characters *except* the hierarchy delimiter.
  434. #
  435. # If +refname+ is empty, +mailbox+ is used directly to determine
  436. # which mailboxes to match. If +mailbox+ is empty, the root
  437. # name of +refname+ and the hierarchy delimiter are returned.
  438. #
  439. # The return value is an array of +Net::IMAP::MailboxList+. For example:
  440. #
  441. # imap.create("foo/bar")
  442. # imap.create("foo/baz")
  443. # p imap.list("", "foo/%")
  444. # #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
  445. # #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
  446. # #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
  447. def list(refname, mailbox)
  448. synchronize do
  449. send_command("LIST", refname, mailbox)
  450. return @responses.delete("LIST")
  451. end
  452. end
  453. # Sends the GETQUOTAROOT command along with specified +mailbox+.
  454. # This command is generally available to both admin and user.
  455. # If mailbox exists, returns an array containing objects of
  456. # Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
  457. def getquotaroot(mailbox)
  458. synchronize do
  459. send_command("GETQUOTAROOT", mailbox)
  460. result = []
  461. result.concat(@responses.delete("QUOTAROOT"))
  462. result.concat(@responses.delete("QUOTA"))
  463. return result
  464. end
  465. end
  466. # Sends the GETQUOTA command along with specified +mailbox+.
  467. # If this mailbox exists, then an array containing a
  468. # Net::IMAP::MailboxQuota object is returned. This
  469. # command generally is only available to server admin.
  470. def getquota(mailbox)
  471. synchronize do
  472. send_command("GETQUOTA", mailbox)
  473. return @responses.delete("QUOTA")
  474. end
  475. end
  476. # Sends a SETQUOTA command along with the specified +mailbox+ and
  477. # +quota+. If +quota+ is nil, then quota will be unset for that
  478. # mailbox. Typically one needs to be logged in as server admin
  479. # for this to work. The IMAP quota commands are described in
  480. # [RFC-2087].
  481. def setquota(mailbox, quota)
  482. if quota.nil?
  483. data = '()'
  484. else
  485. data = '(STORAGE ' + quota.to_s + ')'
  486. end
  487. send_command("SETQUOTA", mailbox, RawData.new(data))
  488. end
  489. # Sends the SETACL command along with +mailbox+, +user+ and the
  490. # +rights+ that user is to have on that mailbox. If +rights+ is nil,
  491. # then that user will be stripped of any rights to that mailbox.
  492. # The IMAP ACL commands are described in [RFC-2086].
  493. def setacl(mailbox, user, rights)
  494. if rights.nil?
  495. send_command("SETACL", mailbox, user, "")
  496. else
  497. send_command("SETACL", mailbox, user, rights)
  498. end
  499. end
  500. # Send the GETACL command along with specified +mailbox+.
  501. # If this mailbox exists, an array containing objects of
  502. # Net::IMAP::MailboxACLItem will be returned.
  503. def getacl(mailbox)
  504. synchronize do
  505. send_command("GETACL", mailbox)
  506. return @responses.delete("ACL")[-1]
  507. end
  508. end
  509. # Sends a LSUB command, and returns a subset of names from the set
  510. # of names that the user has declared as being "active" or
  511. # "subscribed". +refname+ and +mailbox+ are interpreted as
  512. # for #list().
  513. # The return value is an array of +Net::IMAP::MailboxList+.
  514. def lsub(refname, mailbox)
  515. synchronize do
  516. send_command("LSUB", refname, mailbox)
  517. return @responses.delete("LSUB")
  518. end
  519. end
  520. # Sends a STATUS command, and returns the status of the indicated
  521. # +mailbox+. +attr+ is a list of one or more attributes that
  522. # we are request the status of. Supported attributes include:
  523. #
  524. # MESSAGES:: the number of messages in the mailbox.
  525. # RECENT:: the number of recent messages in the mailbox.
  526. # UNSEEN:: the number of unseen messages in the mailbox.
  527. #
  528. # The return value is a hash of attributes. For example:
  529. #
  530. # p imap.status("inbox", ["MESSAGES", "RECENT"])
  531. # #=> {"RECENT"=>0, "MESSAGES"=>44}
  532. #
  533. # A Net::IMAP::NoResponseError is raised if status values
  534. # for +mailbox+ cannot be returned, for instance because it
  535. # does not exist.
  536. def status(mailbox, attr)
  537. synchronize do
  538. send_command("STATUS", mailbox, attr)
  539. return @responses.delete("STATUS")[-1].attr
  540. end
  541. end
  542. # Sends a APPEND command to append the +message+ to the end of
  543. # the +mailbox+. The optional +flags+ argument is an array of
  544. # flags to initially passing to the new message. The optional
  545. # +date_time+ argument specifies the creation time to assign to the
  546. # new message; it defaults to the current time.
  547. # For example:
  548. #
  549. # imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
  550. # Subject: hello
  551. # From: shugo@ruby-lang.org
  552. # To: shugo@ruby-lang.org
  553. #
  554. # hello world
  555. # EOF
  556. #
  557. # A Net::IMAP::NoResponseError is raised if the mailbox does
  558. # not exist (it is not created automatically), or if the flags,
  559. # date_time, or message arguments contain errors.
  560. def append(mailbox, message, flags = nil, date_time = nil)
  561. args = []
  562. if flags
  563. args.push(flags)
  564. end
  565. args.push(date_time) if date_time
  566. args.push(Literal.new(message))
  567. send_command("APPEND", mailbox, *args)
  568. end
  569. # Sends a CHECK command to request a checkpoint of the currently
  570. # selected mailbox. This performs implementation-specific
  571. # housekeeping, for instance, reconciling the mailbox's
  572. # in-memory and on-disk state.
  573. def check
  574. send_command("CHECK")
  575. end
  576. # Sends a CLOSE command to close the currently selected mailbox.
  577. # The CLOSE command permanently removes from the mailbox all
  578. # messages that have the \Deleted flag set.
  579. def close
  580. send_command("CLOSE")
  581. end
  582. # Sends a EXPUNGE command to permanently remove from the currently
  583. # selected mailbox all messages that have the \Deleted flag set.
  584. def expunge
  585. synchronize do
  586. send_command("EXPUNGE")
  587. return @responses.delete("EXPUNGE")
  588. end
  589. end
  590. # Sends a SEARCH command to search the mailbox for messages that
  591. # match the given searching criteria, and returns message sequence
  592. # numbers. +keys+ can either be a string holding the entire
  593. # search string, or a single-dimension array of search keywords and
  594. # arguments. The following are some common search criteria;
  595. # see [IMAP] section 6.4.4 for a full list.
  596. #
  597. # <message set>:: a set of message sequence numbers. ',' indicates
  598. # an interval, ':' indicates a range. For instance,
  599. # '2,10:12,15' means "2,10,11,12,15".
  600. #
  601. # BEFORE <date>:: messages with an internal date strictly before
  602. # <date>. The date argument has a format similar
  603. # to 8-Aug-2002.
  604. #
  605. # BODY <string>:: messages that contain <string> within their body.
  606. #
  607. # CC <string>:: messages containing <string> in their CC field.
  608. #
  609. # FROM <string>:: messages that contain <string> in their FROM field.
  610. #
  611. # NEW:: messages with the \Recent, but not the \Seen, flag set.
  612. #
  613. # NOT <search-key>:: negate the following search key.
  614. #
  615. # OR <search-key> <search-key>:: "or" two search keys together.
  616. #
  617. # ON <date>:: messages with an internal date exactly equal to <date>,
  618. # which has a format similar to 8-Aug-2002.
  619. #
  620. # SINCE <date>:: messages with an internal date on or after <date>.
  621. #
  622. # SUBJECT <string>:: messages with <string> in their subject.
  623. #
  624. # TO <string>:: messages with <string> in their TO field.
  625. #
  626. # For example:
  627. #
  628. # p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
  629. # #=> [1, 6, 7, 8]
  630. def search(keys, charset = nil)
  631. return search_internal("SEARCH", keys, charset)
  632. end
  633. # As for #search(), but returns unique identifiers.
  634. def uid_search(keys, charset = nil)
  635. return search_internal("UID SEARCH", keys, charset)
  636. end
  637. # Sends a FETCH command to retrieve data associated with a message
  638. # in the mailbox. The +set+ parameter is a number or an array of
  639. # numbers or a Range object. The number is a message sequence
  640. # number. +attr+ is a list of attributes to fetch; see the
  641. # documentation for Net::IMAP::FetchData for a list of valid
  642. # attributes.
  643. # The return value is an array of Net::IMAP::FetchData. For example:
  644. #
  645. # p imap.fetch(6..8, "UID")
  646. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
  647. # #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
  648. # #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
  649. # p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
  650. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
  651. # data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
  652. # p data.seqno
  653. # #=> 6
  654. # p data.attr["RFC822.SIZE"]
  655. # #=> 611
  656. # p data.attr["INTERNALDATE"]
  657. # #=> "12-Oct-2000 22:40:59 +0900"
  658. # p data.attr["UID"]
  659. # #=> 98
  660. def fetch(set, attr)
  661. return fetch_internal("FETCH", set, attr)
  662. end
  663. # As for #fetch(), but +set+ contains unique identifiers.
  664. def uid_fetch(set, attr)
  665. return fetch_internal("UID FETCH", set, attr)
  666. end
  667. # Sends a STORE command to alter data associated with messages
  668. # in the mailbox, in particular their flags. The +set+ parameter
  669. # is a number or an array of numbers or a Range object. Each number
  670. # is a message sequence number. +attr+ is the name of a data item
  671. # to store: 'FLAGS' means to replace the message's flag list
  672. # with the provided one; '+FLAGS' means to add the provided flags;
  673. # and '-FLAGS' means to remove them. +flags+ is a list of flags.
  674. #
  675. # The return value is an array of Net::IMAP::FetchData. For example:
  676. #
  677. # p imap.store(6..8, "+FLAGS", [:Deleted])
  678. # #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  679. # #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
  680. # #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
  681. def store(set, attr, flags)
  682. return store_internal("STORE", set, attr, flags)
  683. end
  684. # As for #store(), but +set+ contains unique identifiers.
  685. def uid_store(set, attr, flags)
  686. return store_internal("UID STORE", set, attr, flags)
  687. end
  688. # Sends a COPY command to copy the specified message(s) to the end
  689. # of the specified destination +mailbox+. The +set+ parameter is
  690. # a number or an array of numbers or a Range object. The number is
  691. # a message sequence number.
  692. def copy(set, mailbox)
  693. copy_internal("COPY", set, mailbox)
  694. end
  695. # As for #copy(), but +set+ contains unique identifiers.
  696. def uid_copy(set, mailbox)
  697. copy_internal("UID COPY", set, mailbox)
  698. end
  699. # Sends a SORT command to sort messages in the mailbox.
  700. # Returns an array of message sequence numbers. For example:
  701. #
  702. # p imap.sort(["FROM"], ["ALL"], "US-ASCII")
  703. # #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
  704. # p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
  705. # #=> [6, 7, 8, 1]
  706. #
  707. # See [SORT-THREAD-EXT] for more details.
  708. def sort(sort_keys, search_keys, charset)
  709. return sort_internal("SORT", sort_keys, search_keys, charset)
  710. end
  711. # As for #sort(), but returns an array of unique identifiers.
  712. def uid_sort(sort_keys, search_keys, charset)
  713. return sort_internal("UID SORT", sort_keys, search_keys, charset)
  714. end
  715. # Adds a response handler. For example, to detect when
  716. # the server sends us a new EXISTS response (which normally
  717. # indicates new messages being added to the mail box),
  718. # you could add the following handler after selecting the
  719. # mailbox.
  720. #
  721. # imap.add_response_handler { |resp|
  722. # if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
  723. # puts "Mailbox now has #{resp.data} messages"
  724. # end
  725. # }
  726. #
  727. def add_response_handler(handler = Proc.new)
  728. @response_handlers.push(handler)
  729. end
  730. # Removes the response handler.
  731. def remove_response_handler(handler)
  732. @response_handlers.delete(handler)
  733. end
  734. # As for #search(), but returns message sequence numbers in threaded
  735. # format, as a Net::IMAP::ThreadMember tree. The supported algorithms
  736. # are:
  737. #
  738. # ORDEREDSUBJECT:: split into single-level threads according to subject,
  739. # ordered by date.
  740. # REFERENCES:: split into threads by parent/child relationships determined
  741. # by which message is a reply to which.
  742. #
  743. # Unlike #search(), +charset+ is a required argument. US-ASCII
  744. # and UTF-8 are sample values.
  745. #
  746. # See [SORT-THREAD-EXT] for more details.
  747. def thread(algorithm, search_keys, charset)
  748. return thread_internal("THREAD", algorithm, search_keys, charset)
  749. end
  750. # As for #thread(), but returns unique identifiers instead of
  751. # message sequence numbers.
  752. def uid_thread(algorithm, search_keys, charset)
  753. return thread_internal("UID THREAD", algorithm, search_keys, charset)
  754. end
  755. # Decode a string from modified UTF-7 format to UTF-8.
  756. #
  757. # UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a
  758. # slightly modified version of this to encode mailbox names
  759. # containing non-ASCII characters; see [IMAP] section 5.1.3.
  760. #
  761. # Net::IMAP does _not_ automatically encode and decode
  762. # mailbox names to and from utf7.
  763. def self.decode_utf7(s)
  764. return s.gsub(/&(.*?)-/n) {
  765. if $1.empty?
  766. "&"
  767. else
  768. base64 = $1.tr(",", "/")
  769. x = base64.length % 4
  770. if x > 0
  771. base64.concat("=" * (4 - x))
  772. end
  773. u16tou8(base64.unpack("m")[0])
  774. end
  775. }
  776. end
  777. # Encode a string from UTF-8 format to modified UTF-7.
  778. def self.encode_utf7(s)
  779. return s.gsub(/(&)|([^\x20-\x25\x27-\x7e]+)/n) { |x|
  780. if $1
  781. "&-"
  782. else
  783. base64 = [u8tou16(x)].pack("m")
  784. "&" + base64.delete("=\n").tr("/", ",") + "-"
  785. end
  786. }
  787. end
  788. private
  789. CRLF = "\r\n" # :nodoc:
  790. PORT = 143 # :nodoc:
  791. @@debug = false
  792. @@authenticators = {}
  793. # Creates a new Net::IMAP object and connects it to the specified
  794. # +port+ (143 by default) on the named +host+. If +usessl+ is true,
  795. # then an attempt will
  796. # be made to use SSL (now TLS) to connect to the server. For this
  797. # to work OpenSSL [OSSL] and the Ruby OpenSSL [RSSL]
  798. # extensions need to be installed. The +certs+ parameter indicates
  799. # the path or file containing the CA cert of the server, and the
  800. # +verify+ parameter is for the OpenSSL verification callback.
  801. #
  802. # The most common errors are:
  803. #
  804. # Errno::ECONNREFUSED:: connection refused by +host+ or an intervening
  805. # firewall.
  806. # Errno::ETIMEDOUT:: connection timed out (possibly due to packets
  807. # being dropped by an intervening firewall).
  808. # Errno::ENETUNREACH:: there is no route to that network.
  809. # SocketError:: hostname not known or other socket error.
  810. # Net::IMAP::ByeResponseError:: we connected to the host, but they
  811. # immediately said goodbye to us.
  812. def initialize(host, port = PORT, usessl = false, certs = nil, verify = false)
  813. super()
  814. @host = host
  815. @port = port
  816. @tag_prefix = "RUBY"
  817. @tagno = 0
  818. @parser = ResponseParser.new
  819. @sock = TCPSocket.open(host, port)
  820. if usessl
  821. unless defined?(OpenSSL)
  822. raise "SSL extension not installed"
  823. end
  824. @usessl = true
  825. # verify the server.
  826. context = SSLContext::new()
  827. context.ca_file = certs if certs && FileTest::file?(certs)
  828. context.ca_path = certs if certs && FileTest::directory?(certs)
  829. context.verify_mode = VERIFY_PEER if verify
  830. if defined?(VerifyCallbackProc)
  831. context.verify_callback = VerifyCallbackProc
  832. end
  833. @sock = SSLSocket.new(@sock, context)
  834. @sock.connect # start ssl session.
  835. else
  836. @usessl = false
  837. end
  838. @responses = Hash.new([].freeze)
  839. @tagged_responses = {}
  840. @response_handlers = []
  841. @response_arrival = new_cond
  842. @continuation_request = nil
  843. @logout_command_tag = nil
  844. @debug_output_bol = true
  845. @greeting = get_response
  846. if @greeting.name == "BYE"
  847. @sock.close
  848. raise ByeResponseError, @greeting.raw_data
  849. end
  850. @client_thread = Thread.current
  851. @receiver_thread = Thread.start {
  852. receive_responses
  853. }
  854. end
  855. def receive_responses
  856. while true
  857. begin
  858. resp = get_response
  859. rescue Exception
  860. @sock.close
  861. @client_thread.raise($!)
  862. break
  863. end
  864. break unless resp
  865. begin
  866. synchronize do
  867. case resp
  868. when TaggedResponse
  869. @tagged_responses[resp.tag] = resp
  870. @response_arrival.broadcast
  871. if resp.tag == @logout_command_tag
  872. return
  873. end
  874. when UntaggedResponse
  875. record_response(resp.name, resp.data)
  876. if resp.data.instance_of?(ResponseText) &&
  877. (code = resp.data.code)
  878. record_response(code.name, code.data)
  879. end
  880. if resp.name == "BYE" && @logout_command_tag.nil?
  881. @sock.close
  882. raise ByeResponseError, resp.raw_data
  883. end
  884. when ContinuationRequest
  885. @continuation_request = resp
  886. @response_arrival.broadcast
  887. end
  888. @response_handlers.each do |handler|
  889. handler.call(resp)
  890. end
  891. end
  892. rescue Exception
  893. @client_thread.raise($!)
  894. end
  895. end
  896. end
  897. def get_tagged_response(tag)
  898. until @tagged_responses.key?(tag)
  899. @response_arrival.wait
  900. end
  901. return pick_up_tagged_response(tag)
  902. end
  903. def pick_up_tagged_response(tag)
  904. resp = @tagged_responses.delete(tag)
  905. case resp.name
  906. when /\A(?:NO)\z/ni
  907. raise NoResponseError, resp.data.text
  908. when /\A(?:BAD)\z/ni
  909. raise BadResponseError, resp.data.text
  910. else
  911. return resp
  912. end
  913. end
  914. def get_response
  915. buff = ""
  916. while true
  917. s = @sock.gets(CRLF)
  918. break unless s
  919. buff.concat(s)
  920. if /\{(\d+)\}\r\n/n =~ s
  921. s = @sock.read($1.to_i)
  922. buff.concat(s)
  923. else
  924. break
  925. end
  926. end
  927. return nil if buff.length == 0
  928. if @@debug
  929. $stderr.print(buff.gsub(/^/n, "S: "))
  930. end
  931. return @parser.parse(buff)
  932. end
  933. def record_response(name, data)
  934. unless @responses.has_key?(name)
  935. @responses[name] = []
  936. end
  937. @responses[name].push(data)
  938. end
  939. def send_command(cmd, *args, &block)
  940. synchronize do
  941. tag = Thread.current[:net_imap_tag] = generate_tag
  942. put_string(tag + " " + cmd)
  943. args.each do |i|
  944. put_string(" ")
  945. send_data(i)
  946. end
  947. put_string(CRLF)
  948. if cmd == "LOGOUT"
  949. @logout_command_tag = tag
  950. end
  951. if block
  952. add_response_handler(block)
  953. end
  954. begin
  955. return get_tagged_response(tag)
  956. ensure
  957. if block
  958. remove_response_handler(block)
  959. end
  960. end
  961. end
  962. end
  963. def generate_tag
  964. @tagno += 1
  965. return format("%s%04d", @tag_prefix, @tagno)
  966. end
  967. def put_string(str)
  968. @sock.print(str)
  969. if @@debug
  970. if @debug_output_bol
  971. $stderr.print("C: ")
  972. end
  973. $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
  974. if /\r\n\z/n.match(str)
  975. @debug_output_bol = true
  976. else
  977. @debug_output_bol = false
  978. end
  979. end
  980. end
  981. def send_data(data)
  982. case data
  983. when nil
  984. put_string("NIL")
  985. when String
  986. send_string_data(data)
  987. when Integer
  988. send_number_data(data)
  989. when Array
  990. send_list_data(data)
  991. when Time
  992. send_time_data(data)
  993. when Symbol
  994. send_symbol_data(data)
  995. else
  996. data.send_data(self)
  997. end
  998. end
  999. def send_string_data(str)
  1000. case str
  1001. when ""
  1002. put_string('""')
  1003. when /[\x80-\xff\r\n]/n
  1004. # literal
  1005. send_literal(str)
  1006. when /[(){ \x00-\x1f\x7f%*"\\]/n
  1007. # quoted string
  1008. send_quoted_string(str)
  1009. else
  1010. put_string(str)
  1011. end
  1012. end
  1013. def send_quoted_string(str)
  1014. put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
  1015. end
  1016. def send_literal(str)
  1017. put_string("{" + str.length.to_s + "}" + CRLF)
  1018. while @continuation_request.nil? &&
  1019. !@tagged_responses.key?(Thread.current[:net_imap_tag])
  1020. @response_arrival.wait
  1021. end
  1022. if @continuation_request.nil?
  1023. pick_up_tagged_response(Thread.current[:net_imap_tag])
  1024. raise ResponseError.new("expected continuation request")
  1025. end
  1026. @continuation_request = nil
  1027. put_string(str)
  1028. end
  1029. def send_number_data(num)
  1030. if num < 0 || num >= 4294967296
  1031. raise DataFormatError, num.to_s
  1032. end
  1033. put_string(num.to_s)
  1034. end
  1035. def send_list_data(list)
  1036. put_string("(")
  1037. first = true
  1038. list.each do |i|
  1039. if first
  1040. first = false
  1041. else
  1042. put_string(" ")
  1043. end
  1044. send_data(i)
  1045. end
  1046. put_string(")")
  1047. end
  1048. DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
  1049. def send_time_data(time)
  1050. t = time.dup.gmtime
  1051. s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
  1052. t.day, DATE_MONTH[t.month - 1], t.year,
  1053. t.hour, t.min, t.sec)
  1054. put_string(s)
  1055. end
  1056. def send_symbol_data(symbol)
  1057. put_string("\\" + symbol.to_s)
  1058. end
  1059. def search_internal(cmd, keys, charset)
  1060. if keys.instance_of?(String)
  1061. keys = [RawData.new(keys)]
  1062. else
  1063. normalize_searching_criteria(keys)
  1064. end
  1065. synchronize do
  1066. if charset
  1067. send_command(cmd, "CHARSET", charset, *keys)
  1068. else
  1069. send_command(cmd, *keys)
  1070. end
  1071. return @responses.delete("SEARCH")[-1]
  1072. end
  1073. end
  1074. def fetch_internal(cmd, set, attr)
  1075. if attr.instance_of?(String)
  1076. attr = RawData.new(attr)
  1077. end
  1078. synchronize do
  1079. @responses.delete("FETCH")
  1080. send_command(cmd, MessageSet.new(set), attr)
  1081. return @responses.delete("FETCH")
  1082. end
  1083. end
  1084. def store_internal(cmd, set, attr, flags)
  1085. if attr.instance_of?(String)
  1086. attr = RawData.new(attr)
  1087. end
  1088. synchronize do
  1089. @responses.delete("FETCH")
  1090. send_command(cmd, MessageSet.new(set), attr, flags)
  1091. return @responses.delete("FETCH")
  1092. end
  1093. end
  1094. def copy_internal(cmd, set, mailbox)
  1095. send_command(cmd, MessageSet.new(set), mailbox)
  1096. end
  1097. def sort_internal(cmd, sort_keys, search_keys, charset)
  1098. if search_keys.instance_of?(String)
  1099. search_keys = [RawData.new(search_keys)]
  1100. else
  1101. normalize_searching_criteria(search_keys)
  1102. end
  1103. normalize_searching_criteria(search_keys)
  1104. synchronize do
  1105. send_command(cmd, sort_keys, charset, *search_keys)
  1106. return @responses.delete("SORT")[-1]
  1107. end
  1108. end
  1109. def thread_internal(cmd, algorithm, search_keys, charset)
  1110. if search_keys.instance_of?(String)
  1111. search_keys = [RawData.new(search_keys)]
  1112. else
  1113. normalize_searching_criteria(search_keys)
  1114. end
  1115. normalize_searching_criteria(search_keys)
  1116. send_command(cmd, algorithm, charset, *search_keys)
  1117. return @responses.delete("THREAD")[-1]
  1118. end
  1119. def normalize_searching_criteria(keys)
  1120. keys.collect! do |i|
  1121. case i
  1122. when -1, Range, Array
  1123. MessageSet.new(i)
  1124. else
  1125. i
  1126. end
  1127. end
  1128. end
  1129. def self.u16tou8(s)
  1130. len = s.length
  1131. if len < 2
  1132. return ""
  1133. end
  1134. buf = ""
  1135. i = 0
  1136. while i < len
  1137. c = s[i] << 8 | s[i + 1]
  1138. i += 2
  1139. if c == 0xfeff
  1140. next
  1141. elsif c < 0x0080
  1142. buf.concat(c)
  1143. elsif c < 0x0800
  1144. b2 = c & 0x003f
  1145. b1 = c >> 6
  1146. buf.concat(b1 | 0xc0)
  1147. buf.concat(b2 | 0x80)
  1148. elsif c >= 0xdc00 && c < 0xe000
  1149. raise DataFormatError, "invalid surrogate detected"
  1150. elsif c >= 0xd800 && c < 0xdc00
  1151. if i + 2 > len
  1152. raise DataFormatError, "invalid surrogate detected"
  1153. end
  1154. low = s[i] << 8 | s[i + 1]
  1155. i += 2
  1156. if low < 0xdc00 || low > 0xdfff
  1157. raise DataFormatError, "invalid surrogate detected"
  1158. end
  1159. c = (((c & 0x03ff)) << 10 | (low & 0x03ff)) + 0x10000
  1160. b4 = c & 0x003f
  1161. b3 = (c >> 6) & 0x003f
  1162. b2 = (c >> 12) & 0x003f
  1163. b1 = c >> 18;
  1164. buf.concat(b1 | 0xf0)
  1165. buf.concat(b2 | 0x80)
  1166. buf.concat(b3 | 0x80)
  1167. buf.concat(b4 | 0x80)
  1168. else # 0x0800-0xffff
  1169. b3 = c & 0x003f
  1170. b2 = (c >> 6) & 0x003f
  1171. b1 = c >> 12
  1172. buf.concat(b1 | 0xe0)
  1173. buf.concat(b2 | 0x80)
  1174. buf.concat(b3 | 0x80)
  1175. end
  1176. end
  1177. return buf
  1178. end
  1179. private_class_method :u16tou8
  1180. def self.u8tou16(s)
  1181. len = s.length
  1182. buf = ""
  1183. i = 0
  1184. while i < len
  1185. c = s[i]
  1186. if (c & 0x80) == 0
  1187. buf.concat(0x00)
  1188. buf.concat(c)
  1189. i += 1
  1190. elsif (c & 0xe0) == 0xc0 &&
  1191. len >= 2 &&
  1192. (s[i + 1] & 0xc0) == 0x80
  1193. if c == 0xc0 || c == 0xc1
  1194. raise DataFormatError, format("non-shortest UTF-8 sequence (%02x)", c)
  1195. end
  1196. u = ((c & 0x1f) << 6) | (s[i + 1] & 0x3f)
  1197. buf.concat(u >> 8)
  1198. buf.concat(u & 0x00ff)
  1199. i += 2
  1200. elsif (c & 0xf0) == 0xe0 &&
  1201. i + 2 < len &&
  1202. (s[i + 1] & 0xc0) == 0x80 &&
  1203. (s[i + 2] & 0xc0) == 0x80
  1204. if c == 0xe0 && s[i + 1] < 0xa0
  1205. raise DataFormatError, format("non-shortest UTF-8 sequence (%02x)", c)
  1206. end
  1207. u = ((c & 0x0f) << 12) | ((s[i + 1] & 0x3f) << 6) | (s[i + 2] & 0x3f)
  1208. # surrogate chars
  1209. if u >= 0xd800 && u <= 0xdfff
  1210. raise DataFormatError, format("none-UTF-16 char detected (%04x)", u)
  1211. end
  1212. buf.concat(u >> 8)
  1213. buf.concat(u & 0x00ff)
  1214. i += 3
  1215. elsif (c & 0xf8) == 0xf0 &&
  1216. i + 3 < len &&
  1217. (s[i + 1] & 0xc0) == 0x80 &&
  1218. (s[i + 2] & 0xc0) == 0x80 &&
  1219. (s[i + 3] & 0xc0) == 0x80
  1220. if c == 0xf0 && s[i + 1] < 0x90
  1221. raise DataFormatError, format("non-shortest UTF-8 sequence (%02x)", c)
  1222. end
  1223. u = ((c & 0x07) << 18) | ((s[i + 1] & 0x3f) << 12) |
  1224. ((s[i + 2] & 0x3f) << 6) | (s[i + 3] & 0x3f)
  1225. if u < 0x10000
  1226. buf.concat(u >> 8)
  1227. buf.concat(u & 0x00ff)
  1228. elsif u < 0x110000
  1229. high = ((u - 0x10000) >> 10) | 0xd800
  1230. low = (u & 0x03ff) | 0xdc00
  1231. buf.concat(high >> 8)
  1232. buf.concat(high & 0x00ff)
  1233. buf.concat(low >> 8)
  1234. buf.concat(low & 0x00ff)
  1235. else
  1236. raise DataFormatError, format("none-UTF-16 char detected (%04x)", u)
  1237. end
  1238. i += 4
  1239. else
  1240. raise DataFormatError, format("illegal UTF-8 sequence (%02x)", c)
  1241. end
  1242. end
  1243. return buf
  1244. end
  1245. private_class_method :u8tou16
  1246. class RawData # :nodoc:
  1247. def send_data(imap)
  1248. imap.send(:put_string, @data)
  1249. end
  1250. private
  1251. def initialize(data)
  1252. @data = data
  1253. end
  1254. end
  1255. class Atom # :nodoc:
  1256. def send_data(imap)
  1257. imap.send(:put_string, @data)
  1258. end
  1259. private
  1260. def initialize(data)
  1261. @data = data
  1262. end
  1263. end
  1264. class QuotedString # :nodoc:
  1265. def send_data(imap)
  1266. imap.send(:send_quoted_string, @data)
  1267. end
  1268. private
  1269. def initialize(data)
  1270. @data = data
  1271. end
  1272. end
  1273. class Literal # :nodoc:
  1274. def send_data(imap)
  1275. imap.send(:send_literal, @data)
  1276. end
  1277. private
  1278. def initialize(data)
  1279. @data = data
  1280. end
  1281. end
  1282. class MessageSet # :nodoc:
  1283. def send_data(imap)
  1284. imap.send(:put_string, format_internal(@data))
  1285. end
  1286. private
  1287. def initialize(data)
  1288. @data = data
  1289. end
  1290. def format_internal(data)
  1291. case data
  1292. when "*"
  1293. return data
  1294. when Integer
  1295. ensure_nz_number(data)
  1296. if data == -1
  1297. return "*"
  1298. else
  1299. return data.to_s
  1300. end
  1301. when Range
  1302. return format_internal(data.first) +
  1303. ":" + format_internal(data.last)
  1304. when Array
  1305. return data.collect {|i| format_internal(i)}.join(",")
  1306. when ThreadMember
  1307. return data.seqno.to_s +
  1308. ":" + data.children.collect {|i| format_internal(i).join(",")}
  1309. else
  1310. raise DataFormatError, data.inspect
  1311. end
  1312. end
  1313. def ensure_nz_number(num)
  1314. if num < -1 || num == 0 || num >= 4294967296
  1315. msg = "nz_number must be non-zero unsigned 32-bit integer: " +
  1316. num.inspect
  1317. raise DataFormatError, msg
  1318. end
  1319. end
  1320. end
  1321. # Net::IMAP::ContinuationRequest represents command continuation requests.
  1322. #
  1323. # The command continuation request response is indicated by a "+" token
  1324. # instead of a tag. This form of response indicates that the server is
  1325. # ready to accept the continuation of a command from the client. The
  1326. # remainder of this response is a line of text.
  1327. #
  1328. # continue_req ::= "+" SPACE (resp_text / base64)
  1329. #
  1330. # ==== Fields:
  1331. #
  1332. # data:: Returns the data (Net::IMAP::ResponseText).
  1333. #
  1334. # raw_data:: Returns the raw data string.
  1335. ContinuationRequest = Struct.new(:data, :raw_data)
  1336. # Net::IMAP::UntaggedResponse represents untagged responses.
  1337. #
  1338. # Data transmitted by the server to the client and status responses
  1339. # that do not indicate command completion are prefixed with the token
  1340. # "*", and are called untagged responses.
  1341. #
  1342. # response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye /
  1343. # mailbox_data / message_data / capability_data)
  1344. #
  1345. # ==== Fields:
  1346. #
  1347. # name:: Returns the name such as "FLAGS", "LIST", "FETCH"....
  1348. #
  1349. # data:: Returns the data such as an array of flag symbols,
  1350. # a ((<Net::IMAP::MailboxList>)) object....
  1351. #
  1352. # raw_data:: Returns the raw data string.
  1353. UntaggedResponse = Struct.new(:name, :data, :raw_data)
  1354. # Net::IMAP::TaggedResponse represents tagged responses.
  1355. #
  1356. # The server completion result response indicates the success or
  1357. # failure of the operation. It is tagged with the same tag as the
  1358. # client command which began the operation.
  1359. #
  1360. # response_tagged ::= tag SPACE resp_cond_state CRLF
  1361. #
  1362. # tag ::= 1*<any ATOM_CHAR except "+">
  1363. #
  1364. # resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
  1365. #
  1366. # ==== Fields:
  1367. #
  1368. # tag:: Returns the tag.
  1369. #
  1370. # name:: Returns the name. the name is one of "OK", "NO", "BAD".
  1371. #
  1372. # data:: Returns the data. See ((<Net::IMAP::ResponseText>)).
  1373. #
  1374. # raw_data:: Returns the raw data string.
  1375. #
  1376. TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)
  1377. # Net::IMAP::ResponseText represents texts of responses.
  1378. # The text may be prefixed by the response code.
  1379. #
  1380. # resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
  1381. # ;; text SHOULD NOT begin with "[" or "="
  1382. #
  1383. # ==== Fields:
  1384. #
  1385. # code:: Returns the response code. See ((<Net::IMAP::ResponseCode>)).
  1386. #
  1387. # text:: Returns the text.
  1388. #
  1389. ResponseText = Struct.new(:code, :text)
  1390. #
  1391. # Net::IMAP::ResponseCode represents response codes.
  1392. #
  1393. # resp_text_code ::= "ALERT" / "PARSE" /
  1394. # "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /

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