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