]> git.cworth.org Git - sup/blob - lib/sup/imap.rb
split sup-import into sup-add and sup-import; merged poll.rb and sup-import code...
[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 nearly as
29 ## shitty 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   def == o; o.is_a?(IMAP) && o.uri == self.uri && o.username == self.username; end
68
69   def load_header id
70     MBox::read_header StringIO.new(raw_header(id))
71   end
72
73   def load_message id
74     RMail::Parser.read raw_full_message(id)
75   end
76
77   def raw_header id
78     unsynchronized_scan_mailbox
79     header, flags = get_imap_fields id, 'RFC822.HEADER', 'FLAGS'
80     header = header + "Status: RO\n" if flags.include? :Seen # fake an mbox-style read header # TODO: improve source-marked-as-read reporting system
81     header.gsub(/\r\n/, "\n")
82   end
83   synchronized :raw_header
84
85   def raw_full_message id
86     unsynchronized_scan_mailbox
87     get_imap_fields(id, 'RFC822').first.gsub(/\r\n/, "\n")
88   end
89   synchronized :raw_full_message
90
91   def connect
92     return if broken? || @imap
93     safely { } # do nothing!
94   end
95   synchronized :connect
96
97   def scan_mailbox
98     return if @last_scan && (Time.now - @last_scan) < SCAN_INTERVAL
99     last_id = safely do
100       @imap.examine mailbox
101       @imap.responses["EXISTS"].last
102     end
103     @last_scan = Time.now
104
105     return if last_id == @ids.length
106
107     Redwood::log "fetching IMAP headers #{(@ids.length + 1) .. last_id}"
108     values = safely { @imap.fetch((@ids.length + 1) .. last_id, ['RFC822.SIZE', 'INTERNALDATE']) }
109     values.each do |v|
110       id = make_id v
111       @ids << id
112       @imap_ids[id] = v.seqno
113     end
114   end
115   synchronized :scan_mailbox
116
117   def each
118     ids = 
119       @mutex.synchronize do
120         unsynchronized_scan_mailbox
121         @ids
122       end
123
124     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
125
126     start.upto(ids.length - 1) do |i|         
127       id = ids[i]
128       self.cur_offset = id
129       yield id, labels
130     end
131   end
132
133   def start_offset
134     unsynchronized_scan_mailbox
135     @ids.first
136   end
137   synchronized :start_offset
138
139   def end_offset
140     unsynchronized_scan_mailbox
141     @ids.last
142   end
143   synchronized :end_offset
144
145   def pct_done; 100.0 * (@ids.index(cur_offset) || 0).to_f / (@ids.length - 1).to_f; end
146
147 private
148
149   def unsafe_connect
150     say "Connecting to IMAP server #{host}:#{port}..."
151
152     ## apparently imap.rb does a lot of threaded stuff internally and
153     ## if an exception occurs, it will catch it and re-raise it on the
154     ## calling thread. but i can't seem to catch that exception, so
155     ## i've resorted to initializing it in its own thread. surely
156     ## there's a better way.
157     exception = nil
158     ::Thread.new do
159       begin
160         #raise Net::IMAP::ByeResponseError, "simulated imap failure"
161         @imap = Net::IMAP.new host, port, ssl?
162         say "Logging in..."
163
164         ## although RFC1730 claims that "If an AUTHENTICATE command
165         ## fails with a NO response, the client may try another", in
166         ## practice it seems like they can also send a BAD response.
167         begin
168           @imap.authenticate 'CRAM-MD5', @username, @password
169         rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
170           Redwood::log "CRAM-MD5 authentication failed: #{e.class}. Trying LOGIN auth..."
171           begin
172             @imap.authenticate 'LOGIN', @username, @password
173           rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError => e
174             Redwood::log "LOGIN authentication failed: #{e.class}. Trying plain-text LOGIN..."
175             @imap.login @username, @password
176           end
177         end
178         say "Successfully connected to #{@parsed_uri}."
179       rescue Exception => e
180         exception = e
181       ensure
182         shutup
183       end
184     end.join
185
186     raise exception if exception
187   end
188
189   def say s
190     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
191     Redwood::log s
192   end
193
194   def shutup
195     BufferManager.clear @say_id if BufferManager.instantiated?
196     @say_id = nil
197   end
198
199   def die_from e, opts={}
200     @imap = nil
201
202     message =
203       case e
204       when Exception
205         "Error while #{opts[:while]}: #{e.message.chomp} (#{e.class.name})."
206       when String
207         e
208       end
209
210     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]
211
212     self.broken_msg = message
213     Redwood::log message
214     BufferManager.flash "Error communicating with IMAP server. See log for details." if BufferManager.instantiated?
215     raise SourceError, message
216   end
217   
218   ## build a fake unique id
219   def make_id imap_stuff
220     # use 7 digits for the size. why 7? seems nice.
221     msize, mdate = imap_stuff.attr['RFC822.SIZE'] % 10000000, Time.parse(imap_stuff.attr["INTERNALDATE"])
222     sprintf("%d%07d", mdate.to_i, msize).to_i
223   end
224
225   def get_imap_fields id, *fields
226     raise SourceError, broken_msg if broken?
227     imap_id = @imap_ids[id] or die_from "Unknown message id #{id}.", :suggest_rebuild => true
228
229     retried = false
230     results = safely { @imap.fetch imap_id, (fields + ['RFC822.SIZE', 'INTERNALDATE']).uniq }.first
231     got_id = make_id results
232     die_from "IMAP message mismatch: requested #{id}, got #{got_id}.", :suggest_rebuild => true unless got_id == id
233
234     fields.map { |f| results.attr[f] }
235   end
236
237   ## execute a block, connected if unconnected, re-connected up to 3
238   ## times if a recoverable error occurs, and properly dying if an
239   ## unrecoverable error occurs.
240   def safely
241     retries = 0
242     begin
243       begin
244         unsafe_connect unless @imap
245         yield
246       rescue *RECOVERABLE_ERRORS
247         if (retries += 1) <= 3
248           @imap = nil
249           retry
250         end
251         raise
252       end
253     rescue Net, SocketError, Net::IMAP::Error, SystemCallError => e
254       die_from e, :while => "communicating with IMAP server"
255     end
256   end
257
258 end
259
260 Redwood::register_yaml(IMAP, %w(uri username password cur_offset usual archived id))
261
262 end