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