]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
b789d8b50512605cb50d572ff89f588439330564
[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 ## fuck you, imap committee. you managed to design something nearly as
30 ## shitty as mbox but goddamn THIRTY YEARS LATER.
31 module Redwood
32
33 class IMAP < Source
34   SCAN_INTERVAL = 60 # seconds
35
36   ## upon these errors we'll try to rereconnect a few times
37   RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT, OpenSSL::SSL::SSLError ]
38
39   attr_accessor :username, :password
40
41   def initialize uri, username, password, last_idate=nil, usual=true, archived=false, id=nil
42     raise ArgumentError, "username and password must be specified" unless username && password
43     raise ArgumentError, "not an imap uri" unless uri =~ %r!imaps?://!
44
45     super uri, last_idate, usual, archived, id
46
47     @parsed_uri = URI(uri)
48     @username = username
49     @password = password
50     @imap = nil
51     @imap_ids = {}
52     @ids = []
53     @last_scan = nil
54     @labels = [:unread]
55     @labels << mailbox.intern unless mailbox =~ /inbox/i
56     @mutex = Mutex.new
57   end
58
59   def host; @parsed_uri.host; end
60   def port; @parsed_uri.port || (ssl? ? 993 : 143); end
61   def mailbox
62     x = @parsed_uri.path[1..-1]
63     x.nil? || x.empty? ? 'INBOX' : x
64   end
65   def ssl?; @parsed_uri.scheme == 'imaps' end
66
67   def check
68     ids = 
69       @mutex.synchronize do
70         unsynchronized_scan_mailbox
71         @ids
72       end
73
74     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
75   end
76
77   ## is this necessary? TODO: remove maybe
78   def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
79
80   def load_header id
81     MBox::read_header StringIO.new(raw_header(id))
82   end
83
84   def load_message id
85     RMail::Parser.read raw_full_message(id)
86   end
87
88   def raw_header id
89     unsynchronized_scan_mailbox
90     header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
91     header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
92     header.gsub(/\r\n/, "\n")
93   end
94   synchronized :raw_header
95
96   def raw_full_message id
97     unsynchronized_scan_mailbox
98     get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
99   end
100   synchronized :raw_full_message
101
102   def connect
103     return if @imap
104     safely { } # do nothing!
105   end
106   synchronized :connect
107
108   def scan_mailbox
109     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
110     last_id = safely do
111       @imap.examine mailbox
112       @imap.responses["EXISTS"].last
113     end
114     @last_scan = Time.now
115
116     return if last_id == @ids.length
117
118     range = (@ids.length + 1) .. last_id
119     Redwood::log "fetching IMAP headers #{range}"
120     values = safely { @imap.fetch range, ['RFC822.SIZE', 'INTERNALDATE'] }
121     relevant_values = values.find_all { |v| range.include? v.seqno }
122
123     if relevant_values.size != values.size
124       Redwood::log "You IMAP server is buggy: it returned #{values.size} headers for a request for #{range.size}. What are you using, Binc?"
125     end
126
127     relevant_values.each do |v|
128       id = make_id v
129       @ids << id
130       @imap_ids[id] = v.seqno
131     end
132   end
133   synchronized :scan_mailbox
134
135   def each
136     ids = 
137       @mutex.synchronize do
138         unsynchronized_scan_mailbox
139         @ids
140       end
141
142     start = ids.index(cur_offset || start_offset) or raise OutOfSyncSourceError, "Unknown message id #{cur_offset || start_offset}."
143
144     start.upto(ids.length - 1) do |i|         
145       id = ids[i]
146       self.cur_offset = id
147       yield id, @labels.clone
148     end
149   end
150
151   def start_offset
152     unsynchronized_scan_mailbox
153     @ids.first
154   end
155   synchronized :start_offset
156
157   def end_offset
158     unsynchronized_scan_mailbox
159     @ids.last
160   end
161   synchronized :end_offset
162
163   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
164
165 private
166
167   def unsafe_connect
168     say "Connecting to IMAP server #{host}:#{port}..."
169
170     ## apparently imap.rb does a lot of threaded stuff internally and
171     ## if an exception occurs, it will catch it and re-raise it on the
172     ## calling thread. but i can't seem to catch that exception, so
173     ## i've resorted to initializing it in its own thread. surely
174     ## there's a better way.
175     exception = nil
176     ::Thread.new do
177       begin
178         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
179         @imap = Net::IMAP.new host, port, ssl?
180         say "Logging in..."
181
182         ## although RFC1730 claims that "If an AUTHENTICATE command
183         ## fails with a NO response, the client may try another", in
184         ## practice it seems like they can also send a BAD response.
185         begin
186           @imap.authenticate 'CRAM-MD5', @username, @password
187         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
188           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
189           begin
190             @imap.authenticate 'LOGIN', @username, @password
191           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
192             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
193             @imap.login @username, @password
194           end
195         end
196         say "Successfully connected to #{@parsed_uri}."
197       rescue Exception => e
198         exception = e
199       ensure
200         shutup
201       end
202     end.join
203
204     raise exception if exception
205   end
206
207   def say s
208     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
209     Redwood::log s
210   end
211
212   def shutup
213     BufferManager.clear @say_id if BufferManager.instantiated?
214     @say_id = nil
215   end
216
217   def make_id imap_stuff
218     # use 7 digits for the size. why 7? seems nice.
219     %w(RFC822.SIZE INTERNALDATE).each do |w|
220       raise FatalSourceError, "requested data not in IMAP response: #{w}" unless imap_stuff.attr[w]
221     end
222     
223     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
224     sprintf("%d%07d", mdate.to_i, msize).to_i
225   end
226
227   def get_imap_fields id, *fields
228     imap_id = @imap_ids[id] or raise OutOfSyncSourceError, "Unknown message id #{id}"
229
230     retried = false
231     results = safely { @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq }.first
232     got_id = make_id results
233     raise OutOfSyncSourceError, "IMAP message mismatch: requested #{id}, got #{got_id}." unless got_id == id
234
235     fields.map { |f| results.attr[f] or raise FatalSourceError, "empty response from IMAP server: #{f}" }
236   end
237
238   ## execute a block, connected if unconnected, re-connected up to 3
239   ## times if a recoverable error occurs, and properly dying if an
240   ## unrecoverable error occurs.
241   def safely
242     retries = 0
243     begin
244       begin
245         unsafe_connect unless @imap
246         yield
247       rescue *RECOVERABLE_ERRORS => e
248         if (retries += 1) <= 3
249           @imap = nil
250           Redwood::log "got #{e.class.name}: #{e.message.inspect}"
251           sleep 2
252           retry
253         end
254         raise
255       end
256     rescue SocketError, Net::IMAP::Error, SystemCallError, IOError, OpenSSL::SSL::SSLError => e
257       raise FatalSourceError, "While communicating with IMAP server (type #{e.class.name}): #{e.message.inspect}"
258     end
259   end
260
261 end
262
263 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))
264
265 end