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