]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
remove spurious variable
[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     if path =~ /inbox/i
76       [path.intern]
77     else
78       []
79     end
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
91     return unless start_offset
92
93     ids = 
94       @mutex.synchronize do
95         unsynchronized_scan_mailbox
96         @ids
97       end
98
99     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
100   end
101
102   ## is this necessary? TODO: remove maybe
103   def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
104
105   def load_header id
106     MBox::read_header StringIO.new(raw_header(id))
107   end
108
109   def load_message id
110     RMail::Parser.read raw_message(id)
111   end
112
113   def raw_header id
114     unsynchronized_scan_mailbox
115     header, flags = get_imap_fields id, 'RFC822.HEADER'
116     header.gsub(/\r\n/, "\n")
117   end
118   synchronized :raw_header
119
120   def raw_message id
121     unsynchronized_scan_mailbox
122     get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
123   end
124   synchronized :raw_message
125
126   def connect
127     return if @imap
128     safely { } # do nothing!
129   end
130   synchronized :connect
131
132   def scan_mailbox
133     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
134     last_id = safely do
135       @imap.examine mailbox
136       @imap.responses["EXISTS"].last
137     end
138     @last_scan = Time.now
139
140     return if last_id == @ids.length
141
142     range = (@ids.length + 1) .. last_id
143     Redwood::log "fetching IMAP headers #{range}"
144     fetch(range, ['RFC822.SIZE', 'INTERNALDATE', 'FLAGS']).each do |v|
145       id = make_id v
146       @ids << id
147       @imap_state[id] = { :id => v.seqno, :flags => v.attr["FLAGS"] }
148     end
149   end
150   synchronized :scan_mailbox
151
152   def each
153     return unless start_offset
154
155     ids = 
156       @mutex.synchronize do
157         unsynchronized_scan_mailbox
158         @ids
159       end
160
161     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
162
163     start.upto(ids.length - 1) do |i|
164       id = ids[i]
165       state = @mutex.synchronize { @imap_state[id] } or next
166       self.cur_offset = id 
167       labels = { :Seen => :unread, 
168                  :Flagged => :starred,
169                  :Deleted => :deleted
170                }.inject(@labels) do |cur, (imap, sup)|
171         cur + (state[:flags].include?(imap) ? [sup] : [])
172       end
173
174       yield id, labels
175     end
176   end
177
178   def start_offset
179     unsynchronized_scan_mailbox
180     @ids.first
181   end
182   synchronized :start_offset
183
184   def end_offset
185     unsynchronized_scan_mailbox
186     @ids.last
187   end
188   synchronized :end_offset
189
190   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
191
192 private
193
194   def fetch ids, fields
195     results = safely { @imap.fetch ids, fields }
196     good_results = 
197       if ids.respond_to? :member?
198         results.find_all { |r| ids.member?(r.seqno) && fields.all? { |f| r.attr.member?(f) } }
199       else
200         results.find_all { |r| ids == r.seqno && fields.all? { |f| r.attr.member?(f) } }
201       end
202
203     if good_results.empty?
204       raise FatalSourceError, "no IMAP response for #{ids} containing all fields #{fields.join(', ')} (got #{results.size} results)"
205     elsif good_results.size < results.size
206       Redwood::log "Your IMAP server sucks. It sent #{results.size} results for a request for #{good_results.size} messages. What are you using, Binc?"
207     end
208
209     good_results
210   end
211
212   def unsafe_connect
213     say "Connecting to IMAP server #{host}:#{port}..."
214
215     ## apparently imap.rb does a lot of threaded stuff internally and
216     ## if an exception occurs, it will catch it and re-raise it on the
217     ## calling thread. but i can't seem to catch that exception, so
218     ## i've resorted to initializing it in its own thread. surely
219     ## there's a better way.
220     exception = nil
221     ::Thread.new do
222       begin
223         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
224         @imap = Net::IMAP.new host, port, ssl?
225         say "Logging in..."
226
227         ## although RFC1730 claims that "If an AUTHENTICATE command
228         ## fails with a NO response, the client may try another", in
229         ## practice it seems like they can also send a BAD response.
230         begin
231           @imap.authenticate 'CRAM-MD5', @username, @password
232         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
233           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
234           begin
235             @imap.authenticate 'LOGIN', @username, @password
236           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
237             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
238             @imap.login @username, @password
239           end
240         end
241         say "Successfully connected to #{@parsed_uri}."
242       rescue Exception => e
243         exception = e
244       ensure
245         shutup
246       end
247     end.join
248
249     raise exception if exception
250   end
251
252   def say s
253     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
254     Redwood::log s
255   end
256
257   def shutup
258     BufferManager.clear @say_id if BufferManager.instantiated?
259     @say_id = nil
260   end
261
262   def make_id imap_stuff
263     # use 7 digits for the size. why 7? seems nice.
264     %w(RFC822.SIZE INTERNALDATE).each do |w|
265       raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
266     end
267     
268     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
269     sprintf("%d%07d", mdate.to_i, msize).to_i
270   end
271
272   def get_imap_fields id, *fields
273     imap_id = @imap_state[id][:id] or raise OutOfSyncSourceError, "Unknown message id #{id}"
274
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