]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
Merge branch 'master' into next
[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 dunces
9 ## 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 it
13 ## turns out the uids can be invalidated every time the 'uidvalidity'
14 ## value changes on the server, and 'uidvalidity' can change without
15 ## restriction. it can change any time you log in. it can change EVERY
16 ## time you log in. of course the imap spec "strongly recommends" that it
17 ## never change, but there's nothing to stop people from just setting it
18 ## to the current timestamp, and in fact that's exactly what the one imap
19 ## server i have at my disposal does. thus the so-called uids are
20 ## absolutely useless and imap provides no cross-session way of uniquely
21 ## identifying a message. but thanks for the "strong recommendation",
22 ## 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 are
28 ## 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
33 ##   times.  This includes server data that was not requested.
34 ##
35 ## yeah. that totally makes a lot of sense. and once again, the idiocy of
36 ## the spec actually happens in practice. you'll request flags for one
37 ## message, and get it interspersed with a random bunch of flags for some
38 ## other messages, including a different set of flags for the same
39 ## message! totally ok by the imap spec. totally retarded by any other
40 ## 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 mark_as_deleted ids
118     ids = [ids].flatten # accept single arguments
119     unsynchronized_scan_mailbox
120     imap_ids = ids.map { |i| @imap_state[i] && @imap_state[i][:id] }.compact
121     return if imap_ids.empty?
122     @imap.store imap_ids, "+FLAGS", [:Deleted]
123   end
124   synchronized :mark_as_deleted
125
126   def expunge
127     @imap.expunge
128     unsynchronized_scan_mailbox true
129     true
130   end
131   synchronized :expunge
132
133   def connect
134     return if @imap
135     safely { } # do nothing!
136   end
137   synchronized :connect
138
139   def scan_mailbox force=false
140     return if !force && @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
141     last_id = safely do
142       @imap.examine mailbox
143       @imap.responses["EXISTS"].last
144     end
145     @last_scan = Time.now
146
147     @ids = [] if force
148     return if last_id == @ids.length
149
150     range = (@ids.length + 1) .. last_id
151     Redwood::log "fetching IMAP headers #{range}"
152     fetch(range, ['RFC822.SIZE', 'INTERNALDATE', 'FLAGS']).each do |v|
153       id = make_id v
154       @ids << id
155       @imap_state[id] = { :id => v.seqno, :flags => v.attr["FLAGS"] }
156     end
157     Redwood::log "done fetching IMAP headers"
158   end
159   synchronized :scan_mailbox
160
161   def each
162     return unless start_offset
163
164     ids = 
165       @mutex.synchronize do
166         unsynchronized_scan_mailbox
167         @ids
168       end
169
170     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
171
172     start.upto(ids.length - 1) do |i|
173       id = ids[i]
174       state = @mutex.synchronize { @imap_state[id] } or next
175       self.cur_offset = id 
176       labels = { :Flagged => :starred,
177                  :Deleted => :deleted
178                }.inject(@labels) do |cur, (imap, sup)|
179         cur + (state[:flags].include?(imap) ? [sup] : [])
180       end
181
182       labels += [:unread] unless state[:flags].include?(:Seen)
183
184       yield id, labels
185     end
186   end
187
188   def start_offset
189     unsynchronized_scan_mailbox
190     @ids.first
191   end
192   synchronized :start_offset
193
194   def end_offset
195     unsynchronized_scan_mailbox
196     @ids.last + 1
197   end
198   synchronized :end_offset
199
200   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
201
202 private
203
204   def fetch ids, fields
205     results = safely { @imap.fetch ids, fields }
206     good_results = 
207       if ids.respond_to? :member?
208         results.find_all { |r| ids.member?(r.seqno) && fields.all? { |f| r.attr.member?(f) } }
209       else
210         results.find_all { |r| ids == r.seqno && fields.all? { |f| r.attr.member?(f) } }
211       end
212
213     if good_results.empty?
214       raise FatalSourceError, "no IMAP response for #{ids} containing all fields #{fields.join(', ')} (got #{results.size} results)"
215     elsif good_results.size < results.size
216       Redwood::log "Your IMAP server sucks. It sent #{results.size} results for a request for #{good_results.size} messages. What are you using, Binc?"
217     end
218
219     good_results
220   end
221
222   def unsafe_connect
223     say "Connecting to IMAP server #{host}:#{port}..."
224
225     ## apparently imap.rb does a lot of threaded stuff internally and if
226     ## an exception occurs, it will catch it and re-raise it on the
227     ## calling thread. but i can't seem to catch that exception, so i've
228     ## resorted to initializing it in its own thread. surely there's a
229     ## better way.
230     exception = nil
231     ::Thread.new do
232       begin
233         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
234         @imap = Net::IMAP.new host, port, ssl?
235         say "Logging in..."
236
237         ## although RFC1730 claims that "If an AUTHENTICATE command fails
238         ## with a NO response, the client may try another", in practice
239         ## it seems like they can also send a BAD response.
240         begin
241           raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=CRAM-MD5"
242           @imap.authenticate 'CRAM-MD5', @username, @password
243         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
244           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
245           begin
246             raise Net::IMAP::NoResponseError unless @imap.capability().member? "AUTH=LOGIN"
247             @imap.authenticate 'LOGIN', @username, @password
248           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
249             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
250             @imap.login @username, @password
251           end
252         end
253         say "Successfully connected to #{@parsed_uri}."
254       rescue Exception => e
255         exception = e
256       ensure
257         shutup
258       end
259     end.join
260
261     raise exception if exception
262   end
263
264   def say s
265     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
266     Redwood::log s
267   end
268
269   def shutup
270     BufferManager.clear @say_id if BufferManager.instantiated?
271     @say_id = nil
272   end
273
274   def make_id imap_stuff
275     # use 7 digits for the size. why 7? seems nice.
276     %w(RFC822.SIZE INTERNALDATE).each do |w|
277       raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
278     end
279
280     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
281     sprintf("%d%07d", mdate.to_i, msize).to_i
282   end
283
284   def get_imap_fields id, *fields
285     raise OutOfSyncSourceError, "Unknown message id #{id}" unless @imap_state[id]
286
287     imap_id = @imap_state[id][:id]
288     result = fetch(imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq).first
289     got_id = make_id result
290
291     ## I've turned off the following sanity check because Microsoft
292     ## Exchange fails it.  Exchange actually reports two different
293     ## INTERNALDATEs for the exact same message when queried at different
294     ## points in time.
295     ##
296     ## RFC2060 defines the semantics of INTERNALDATE for messages that
297     ## arrive via SMTP for via various IMAP commands, but states that
298     ## "All other cases are implementation defined.". Great, thanks guys,
299     ## yet another useless field.
300     ## 
301     ## Of course no OTHER imap server I've encountered returns DIFFERENT
302     ## values for the SAME message. But it's Microsoft; what do you
303     ## expect? If their programmers were any good they'd be working at
304     ## Google.
305
306     # raise OutOfSyncSourceError, "IMAP message mismatch: requested #{id}, got #{got_id}." unless got_id == id
307
308     fields.map { |f| result.attr[f] or raise FatalSourceError, "empty response from IMAP server: #{f}" }
309   end
310
311   ## execute a block, connected if unconnected, re-connected up to 3
312   ## times if a recoverable error occurs, and properly dying if an
313   ## unrecoverable error occurs.
314   def safely
315     retries = 0
316     begin
317       begin
318         unsafe_connect unless @imap
319         yield
320       rescue *RECOVERABLE_ERRORS => e
321         if (retries += 1) <= 3
322           @imap = nil
323           Redwood::log "got #{e.class.name}: #{e.message.inspect}"
324           sleep 2
325           retry
326         end
327         raise
328       end
329     rescue SocketError, Net::IMAP::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError => e
330       raise FatalSourceError, "While communicating with IMAP server (type #{e.class.name}): #{e.message.inspect}"
331     end
332   end
333
334 end
335
336 end