]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
skip system buffers when rolling
[sup] / lib / sup / imap.rb
1 require 'uri'
2 require 'net/imap'
3 require 'stringio'
4 require 'time'
5 require 'rmail'
6 require 'cgi'
7
8 ## TODO: remove synchronized method protector calls; use a Monitor instead
9 ## (ruby's reentrant mutex)
10
11 ## fucking imap fucking sucks. what the FUCK kind of committee of dunces
12 ## designed this shit.
13 ##
14 ## imap talks about 'unique ids' for messages, to be used for
15 ## cross-session identification. great---just what sup needs! except it
16 ## turns out the uids can be invalidated every time the 'uidvalidity'
17 ## value changes on the server, and 'uidvalidity' can change without
18 ## restriction. it can change any time you log in. it can change EVERY
19 ## time you log in. of course the imap spec "strongly recommends" that it
20 ## never change, but there's nothing to stop people from just setting it
21 ## to the current timestamp, and in fact that's EXACTLY what the one imap
22 ## server i have at my disposal does. thus the so-called uids are
23 ## absolutely useless and imap provides no cross-session way of uniquely
24 ## identifying a message. but thanks for the "strong recommendation",
25 ## guys!
26 ##
27 ## so right now i'm using the 'internal date' and the size of each
28 ## message to uniquely identify it, and i scan over the entire mailbox
29 ## each time i open it to map those things to message ids. that can be
30 ## slow for large mailboxes, and we'll just have to hope that there are
31 ## no collisions. ho ho! a perfectly reasonable solution!
32 ##
33 ## and here's another thing. check out RFC2060 2.2.2 paragraph 5:
34 ##
35 ##   A client MUST be prepared to accept any server response at all
36 ##   times.  This includes server data that was not requested.
37 ##
38 ## yeah. that totally makes a lot of sense. and once again, the idiocy of
39 ## the spec actually happens in practice. you'll request flags for one
40 ## message, and get it interspersed with a random bunch of flags for some
41 ## other messages, including a different set of flags for the same
42 ## message! totally ok by the imap spec. totally retarded by any other
43 ## metric.
44 ##
45 ## fuck you, imap committee. you managed to design something nearly as
46 ## shitty as mbox but goddamn THIRTY YEARS LATER.
47 module Redwood
48
49 class IMAP < Source
50   SCAN_INTERVAL = 60 # seconds
51
52   ## upon these errors we'll try to rereconnect a few times
53   RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError ]
54
55   attr_accessor :username, :password
56   yaml_properties :uri, :username, :password, :cur_offset, :usual,
57                   :archived, :id, :labels
58
59   def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil, labels=[]
60     raise ArgumentError, "username and password must be specified" unless username && password
61     raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
62
63     super uri, last_idate, usual, archived, id
64
65     @parsed_uri = URI(uri)
66     @username = username
67     @password = password
68     @imap = nil
69     @imap_state = {}
70     @ids = []
71     @last_scan = nil
72     @labels = ((labels || []) - LabelManager::RESERVED_LABELS).uniq.freeze
73     @say_id = nil
74     @mutex = Mutex.new
75   end
76
77   def self.suggest_labels_for path
78     path =~ /([^\/]*inbox[^\/]*)/i ? [$1.downcase.intern] : []
79   end
80
81   def host; @parsed_uri.host; end
82   def port; @parsed_uri.port || (ssl? ? 993 : 143); end
83   def mailbox
84     x = @parsed_uri.path[1..-1]
85     (x.nil? || x.empty?) ? 'INBOX' : CGI.unescape(x)
86   end
87   def ssl?; @parsed_uri.scheme == 'imaps' end
88
89   def check; end # do nothing because anything we do will be too slow,
90                  # and we'll catch the errors later.
91
92   ## is this necessary? TODO: remove maybe
93   def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
94
95   def load_header id
96     parse_raw_email_header StringIO.new(raw_header(id))
97   end
98
99   def load_message id
100     RMail::Parser.read raw_message(id)
101   end
102   
103   def each_raw_message_line id
104     StringIO.new(raw_message(id)).each { |l| yield l }
105   end
106
107   def raw_header id
108     unsynchronized_scan_mailbox
109     header, flags = get_imap_fields id, 'RFC822.HEADER'
110     header.gsub(/\r\n/, "\n")
111   end
112   synchronized :raw_header
113
114   def store_message date, from_email, &block
115     message = StringIO.new
116     yield message
117     message.string.gsub! /\n/, "\r\n"
118
119     safely { @imap.append mailbox, message.string, [:Seen], Time.now }
120   end
121
122   def raw_message id
123     unsynchronized_scan_mailbox
124     get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
125   end
126   synchronized :raw_message
127
128   def mark_as_deleted ids
129     ids = [ids].flatten # accept single arguments
130     unsynchronized_scan_mailbox
131     imap_ids = ids.map { |i| @imap_state[i] && @imap_state[i][:id] }.compact
132     return if imap_ids.empty?
133     @imap.store imap_ids, "+FLAGS", [:Deleted]
134   end
135   synchronized :mark_as_deleted
136
137   def expunge
138     @imap.expunge
139     unsynchronized_scan_mailbox true
140     true
141   end
142   synchronized :expunge
143
144   def connect
145     return if @imap
146     safely { } # do nothing!
147   end
148   synchronized :connect
149
150   def scan_mailbox force=false
151     return if !force && @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
152     last_id = safely do
153       @imap.examine mailbox
154       @imap.responses["EXISTS"].last
155     end
156     @last_scan = Time.now
157
158     @ids = [] if force
159     return if last_id == @ids.length
160
161     range = (@ids.length + 1) .. last_id
162     Redwood::log "fetching IMAP headers #{range}"
163     fetch(range, ['RFC822.SIZE', 'INTERNALDATE', 'FLAGS']).each do |v|
164       id = make_id v
165       @ids << id
166       @imap_state[id] = { :id => v.seqno, :flags => v.attr["FLAGS"] }
167     end
168     Redwood::log "done fetching IMAP headers"
169   end
170   synchronized :scan_mailbox
171
172   def each
173     return unless start_offset
174
175     ids = 
176       @mutex.synchronize do
177         unsynchronized_scan_mailbox
178         @ids
179       end
180
181     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
182
183     start.upto(ids.length - 1) do |i|
184       id = ids[i]
185       state = @mutex.synchronize { @imap_state[id] } or next
186       self.cur_offset = id 
187       labels = { :Flagged => :starred,
188                  :Deleted => :deleted
189                }.inject(@labels) do |cur, (imap, sup)|
190         cur + (state[:flags].include?(imap) ? [sup] : [])
191       end
192
193       labels += [:unread] unless state[:flags].include?(:Seen)
194
195       yield id, labels
196     end
197   end
198
199   def start_offset
200     unsynchronized_scan_mailbox
201     @ids.first
202   end
203   synchronized :start_offset
204
205   def end_offset
206     unsynchronized_scan_mailbox
207     @ids.last + 1
208   end
209   synchronized :end_offset
210
211   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
212
213 private
214
215   def fetch ids, fields
216     results = safely { @imap.fetch ids, fields }
217     good_results = 
218       if ids.respond_to? :member?
219         results.find_all { |r| ids.member?(r.seqno) && fields.all? { |f| r.attr.member?(f) } }
220       else
221         results.find_all { |r| ids == r.seqno && fields.all? { |f| r.attr.member?(f) } }
222       end
223
224     if good_results.empty?
225       raise FatalSourceError, "no IMAP response for #{ids} containing all fields #{fields.join(', ')} (got #{results.size} results)"
226     elsif good_results.size < results.size
227       Redwood::log "Your IMAP server sucks. It sent #{results.size} results for a request for #{good_results.size} messages. What are you using, Binc?"
228     end
229
230     good_results
231   end
232
233   def unsafe_connect
234     say "Connecting to IMAP server #{host}:#{port}..."
235
236     ## apparently imap.rb does a lot of threaded stuff internally and if
237     ## an exception occurs, it will catch it and re-raise it on the
238     ## calling thread. but i can't seem to catch that exception, so i've
239     ## resorted to initializing it in its own thread. surely there's a
240     ## better way.
241     exception = nil
242     ::Thread.new do
243       begin
244         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
245         @imap = Net::IMAP.new host, port, ssl?
246         say "Logging in..."
247
248         ## although RFC1730 claims that "If an AUTHENTICATE command fails
249         ## with a NO response, the client may try another", in practice
250         ## it seems like they can also send a BAD response.
251         begin
252           raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=CRAM-MD5"
253           @imap.authenticate 'CRAM-MD5', @username, @password
254         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
255           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
256           begin
257             raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=LOGIN"
258             @imap.authenticate 'LOGIN', @username, @password
259           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
260             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
261             @imap.login @username, @password
262           end
263         end
264         say "Successfully connected to #{@parsed_uri}."
265       rescue Exception => e
266         exception = e
267       ensure
268         shutup
269       end
270     end.join
271
272     raise exception if exception
273   end
274
275   def say s
276     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
277     Redwood::log s
278   end
279
280   def shutup
281     BufferManager.clear @say_id if BufferManager.instantiated?
282     @say_id = nil
283   end
284
285   def make_id imap_stuff
286     # use 7 digits for the size. why 7? seems nice.
287     %w(RFC822.SIZE INTERNALDATE).each do |w|
288       raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
289     end
290
291     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
292     sprintf("%d%07d", mdate.to_i, msize).to_i
293   end
294
295   def get_imap_fields id, *fields
296     raise OutOfSyncSourceError, "Unknown message id #{id}" unless @imap_state[id]
297
298     imap_id = @imap_state[id][:id]
299     result = fetch(imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq).first
300     got_id = make_id result
301
302     ## I've turned off the following sanity check because Microsoft
303     ## Exchange fails it.  Exchange actually reports two different
304     ## INTERNALDATEs for the exact same message when queried at different
305     ## points in time.
306     ##
307     ## RFC2060 defines the semantics of INTERNALDATE for messages that
308     ## arrive via SMTP for via various IMAP commands, but states that
309     ## "All other cases are implementation defined.". Great, thanks guys,
310     ## yet another useless field.
311     ## 
312     ## Of course no OTHER imap server I've encountered returns DIFFERENT
313     ## values for the SAME message. But it's Microsoft; what do you
314     ## expect? If their programmers were any good they'd be working at
315     ## Google.
316
317     # raise OutOfSyncSourceError, "IMAP message mismatch: requested #{id}, got #{got_id}." unless got_id == id
318
319     fields.map { |f| result.attr[f] or raise FatalSourceError, "empty response from IMAP server: #{f}" }
320   end
321
322   ## execute a block, connected if unconnected, re-connected up to 3
323   ## times if a recoverable error occurs, and properly dying if an
324   ## unrecoverable error occurs.
325   def safely
326     retries = 0
327     begin
328       begin
329         unsafe_connect unless @imap
330         yield
331       rescue *RECOVERABLE_ERRORS => e
332         if (retries += 1) <= 3
333           @imap = nil
334           Redwood::log "got #{e.class.name}: #{e.message.inspect}"
335           sleep 2
336           retry
337         end
338         raise
339       end
340     rescue SocketError, Net::IMAP::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError => e
341       raise FatalSourceError, "While communicating with IMAP server (type #{e.class.name}): #{e.message.inspect}"
342     end
343   end
344
345 end
346
347 end