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