]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
3daa3d46d149cfb5546894b7a0891b42a8b2c624
[sup] / lib / sup / imap.rb
1 require 'uri'
2 require 'net/imap'
3 require 'stringio'
4 require 'time'
5
6 ## fucking imap fucking sucks. what the FUCK kind of committee of
7 ## dunces designed this shit.
8
9 ## imap talks about 'unique ids' for messages, to be used for
10 ## cross-session identification. great---just what sup needs! except
11 ## it turns out the uids can be invalidated every time the
12 ## 'uidvalidity' value changes on the server, and 'uidvalidity' can
13 ## change without restriction. it can change any time you log in. it
14 ## can change EVERY time you log in. of course the imap spec "strongly
15 ## recommends" that it never change, but there's nothing to stop
16 ## people from just setting it to the current timestamp, and in fact
17 ## that's exactly what the one imap server i have at my disposal
18 ## does. thus the so-called uids are absolutely useless and imap
19 ## provides no cross-session way of uniquely identifying a
20 ## message. but thanks for the "strong recommendation", guys!
21
22 ## so right now i'm using the 'internal date' and the size of each
23 ## message to uniquely identify it, and i scan over the entire mailbox
24 ## each time i open it to map those things to message ids. that can be
25 ## slow for large mailboxes, and we'll just have to hope that there
26 ## are no collisions. ho ho! a perfectly reasonable solution!
27
28 ## fuck you, imap committee. you managed to design something as shitty
29 ## as mbox but goddamn THIRTY YEARS LATER.
30 module Redwood
31
32 class IMAP < Source
33   SCAN_INTERVAL = 60 # seconds
34
35   ## upon these errors we'll try to rereconnect a few times
36   RECOVERABLE_ERRORS = [ Errno::EPIPE, Errno::ETIMEDOUT ]
37
38   attr_reader_cloned :labels
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 << :inbox unless archived?
56     @labels << mailbox.intern unless mailbox =~ /inbox/i
57     @mutex = Mutex.new
58   end
59
60   def host; @parsed_uri.host; end
61   def port; @parsed_uri.port || (ssl? ? 993 : 143); end
62   def mailbox
63     x = @parsed_uri.path[1..-1]
64     x.nil? || x.empty? ? 'INBOX' : x
65   end
66   def ssl?; @parsed_uri.scheme == 'imaps' end
67
68   def load_header id
69     MBox::read_header StringIO.new(raw_header(id))
70   end
71
72   def load_message id
73     RMail::Parser.read raw_full_message(id)
74   end
75
76   def raw_header id
77     unsynchronized_scan_mailbox
78     header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
79     header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
80     header.gsub(/\r\n/, "\n")
81   end
82   synchronized :raw_header
83
84   def raw_full_message id
85     unsynchronized_scan_mailbox
86     get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
87   end
88   synchronized :raw_full_message
89
90   def connect
91     return if broken? || @imap
92     safely { } # do nothing!
93   end
94   synchronized :connect
95
96   def scan_mailbox
97     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
98     last_id = safely do
99       @imap.examine mailbox
100       @imap.responses["EXISTS"].last
101     end
102     @last_scan = Time.now
103
104     return if last_id == @ids.length
105
106     Redwood::log "fetching IMAP headers #{(@ids.length + 1) .. last_id}"
107     values = safely { @imap.fetch((@ids.length + 1) .. last_id, ['RFC822.SIZE', 'INTERNALDATE']) }
108     values.each do |v|
109       id = make_id v
110       @ids << id
111       @imap_ids[id] = v.seqno
112     end
113   end
114   synchronized :scan_mailbox
115
116   def each
117     ids = 
118       @mutex.synchronize do
119         unsynchronized_scan_mailbox
120         @ids
121       end
122
123     start = ids.index(cur_offset || start_offset) or die_from "Unknown message id #{cur_offset || start_offset}.", :suggest_rebuild => true # couldn't find the most recent email
124
125     start.upto(ids.length - 1) do |i|         
126       id = ids[i]
127       self.cur_offset = id
128       yield id, labels
129     end
130   end
131
132   def start_offset
133     unsynchronized_scan_mailbox
134     @ids.first
135   end
136   synchronized :start_offset
137
138   def end_offset
139     unsynchronized_scan_mailbox
140     @ids.last
141   end
142   synchronized :end_offset
143
144   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
145
146 private
147
148   def unsafe_connect
149     say "Connecting to IMAP server #{host}:#{port}..."
150
151     ## apparently imap.rb does a lot of threaded stuff internally and
152     ## if an exception occurs, it will catch it and re-raise it on the
153     ## calling thread. but i can't seem to catch that exception, so
154     ## i've resorted to initializing it in its own thread. surely
155     ## there's a better way.
156     exception = nil
157     ::Thread.new do
158       begin
159         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
160         @imap = Net::IMAP.new host, port, ssl?
161         say "Logging in..."
162
163         ## although RFC1730 claims that "If an AUTHENTICATE command
164         ## fails with a NO response, the client may try another", in
165         ## practice it seems like they can also send a BAD response.
166         begin
167           @imap.authenticate 'CRAM-MD5', @username, @password
168         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
169           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
170           begin
171             @imap.authenticate 'LOGIN', @username, @password
172           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
173             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
174             @imap.login @username, @password
175           end
176         end
177         say "Successfully connected to #{@parsed_uri}."
178       rescue Exception => e
179         exception = e
180       ensure
181         shutup
182       end
183     end.join
184
185     raise exception if exception
186   end
187
188   def say s
189     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
190     Redwood::log s
191   end
192
193   def shutup
194     BufferManager.clear @say_id if BufferManager.instantiated?
195     @say_id = nil
196   end
197
198   def die_from e, opts={}
199     @imap = nil
200
201     message =
202       case e
203       when Exception
204         "Error while #{opts[:while]}: #{e.message.chomp} (#{e.class.name})."
205       when String
206         e
207       end
208
209     message += " It is likely that messages have been deleted from this IMAP mailbox. Please run sup-import --rebuild #{to_s} to correct this problem." if opts[:suggest_rebuild]
210
211     self.broken_msg = message
212     Redwood::log message
213     BufferManager.flash "Error communicating with IMAP server. See log for details." if BufferManager.instantiated?
214     raise SourceError, message
215   end
216   
217   ## build a fake unique id
218   def make_id imap_stuff
219     # use 7 digits for the size. why 7? seems nice.
220     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
221     sprintf("%d%07d", mdate.to_i, msize).to_i
222   end
223
224   def get_imap_fields id, *fields
225     raise SourceError, broken_msg if broken?
226     imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
227
228     retried = false
229     results = safely { @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq }.first
230     got_id = make_id results
231     die_from "IMAP message mismatch: requested #{id}, got #{got_id}.", :suggest_rebuild => true unless got_id == id
232
233     fields.map { |f| results.attr[f] }
234   end
235
236   ## execute a block, connected if unconnected, re-connected up to 3
237   ## times if a recoverable error occurs, and properly dying if an
238   ## unrecoverable error occurs.
239   def safely
240     retries = 0
241     begin
242       begin
243         unsafe_connect unless @imap
244         yield
245       rescue *RECOVERABLE_ERRORS
246         if (retries += 1) <= 3
247           @imap = nil
248           retry
249         end
250         raise
251       end
252     rescue Net, SocketError, Net::IMAP::Error, SystemCallError => e
253       die_from e, :while => "communicating with IMAP server"
254     end
255   end
256
257 end
258
259 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))
260
261 end