3 # Copyright Mark Longair (c) 2002, 2005, 2008 Reuben Thomas (c) 2005-2007.
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # This is a simple script for fetching mail from POP3 accounts.
19 # On a Debian system, you'll need the following packages:
26 # See http://mythic-beasts.com/~mark/software/stand/
27 # for further remarks.
29 $program_name = 'stand'
39 # FIXME: I don't understand the recent changes that have been made to
40 # InternetMessageIO and broke the old version of these two classes, so
41 # while this seems to work at the moment, I expect it to break at any
46 class SSLIO
< InternetMessageIO
48 def SSLIO
.old_open(addr
, port
, open_timeout
= 30, read_timeout
= 30, debug_output
= nil)
50 tcp_socket
= timeout(open_timeout
) { TCPsocket
.new(addr
, port
) }
52 @ssl_context = OpenSSL
::SSL::SSLContext.new()
55 @ssl_context.ca_path
= '/etc/ssl/certs'
56 @ssl_context.verify_mode
= OpenSSL
::SSL::VERIFY_PEER
58 @ssl_context.verify_mode
= OpenSSL
::SSL::VERIFY_NONE
61 socket
= OpenSSL
::SSL::SSLSocket.new(tcp_socket
, @ssl_context)
66 io
.read_timeout
= read_timeout
67 io
.debug_output
= debug_output
76 # ----------------------------------------------------------------------
96 # ----------------------------------------------------------------------
98 # Command line argument parsing...
100 # Some default values...
102 $configuration_file = "#{ENV['HOME']}/.stand.yaml"
103 $configuration_file_pretty = "~/.stand.yaml"
104 $uidl_database_filename = "#{ENV['HOME']}/.stand-uidls"
109 Usage: #{$program_name} [OPTION]...
111 -h, --help Display this message and exit.
112 -d, --delete Delete messages on server after fetching.
113 -n, --no-ssl-verify Don\'t verify the peer\'s certificate when using SSL.
114 -f <FILENAME>, --configuration-file=<FILENAME>
115 Specify the configuration file to use.
116 (default: #{$configuration_file_pretty})
117 -r <SECONDS>, --reconnect-after=<SECONDS>
118 Reconnect to the server if <SECONDS> seconds has
119 elapsed since the last connection.
124 options
= GetoptLong
.new(
125 [ "--help", "-h", GetoptLong
::NO_ARGUMENT ],
126 [ "--delete", "-d", GetoptLong
::NO_ARGUMENT ],
127 [ "--no-ssl-verify", "-n", GetoptLong
::NO_ARGUMENT ],
128 [ "--configuration-file", "-f", GetoptLong
::REQUIRED_ARGUMENT ],
129 [ "--reconnect-after", "-r", GetoptLong
::REQUIRED_ARGUMENT ]
134 $reconnect_after = nil
138 options
.each
do |opt
, arg
|
146 when "--no-ssl-verify"
148 when "--configuration-file"
149 $configuration_file = arg
150 when "--reconnect-after"
151 $reconnect_after = Float(arg
)
158 print
"Bad command line option: " + $
! + "\n"
164 if $keep and $reconnect_after
165 puts
"There should be no reason to specify --reconnect-after with --keep"
169 # ----------------------------------------------------------------------
171 # A fairly idiotic progress class.
175 def initialize(maximum
)
181 set
@current_value + i
185 block_change
= (v
/ 1024) - (@current_value / 1024)
187 (1..block_change
).each
{ print
"." }
190 backspaces
= - block_change
191 (1..backspaces
).each
{ print
"\b" }
199 # ----------------------------------------------------------------------
201 # This class deals with connecting to a POP3 server, and fetching the
206 attr_accessor
:host, :user, :port
210 def initialize(host
, user
, password
, use_ssl
, use_apop
, port
, command
)
221 "#{@user} at #{@host}:#{@port}#{ @use_ssl ? ' (SSL)' : ''}"
224 def account_uidl(uidl
)
225 "#{@user}@#{@host}:#{@port}##{uidl}"
228 # These three methods manipulate the UIDL database.
230 def add_uidl_to_db(db
,u
)
231 db
.execute( "INSERT INTO uidls VALUES (?)", account_uidl(u
) )
234 def delete_uidls_from_db(db
,a
)
236 db
.execute( "DELETE FROM uidls WHERE uidl = ?", account_uidl(u
) )
240 def db_has_uidl
?(db
,u
)
241 rows
= db
.execute( "SELECT uidl FROM uidls WHERE uidl = ?", account_uidl(u
) )
245 # Fetch all the new messages from this POP3 account, deleting
246 # successfully downloaded messages.
250 # Choose correct POP class
253 pop3_class
= Net
::POP3s
255 pop3_class
= Net
::POP3
258 # Process all the messages
267 pop3_class
.start(@host, @port, @user, @password, @use_apop) do |pop
|
269 connected_at
= Time
.now
271 if i
== 0 and not pop
.mails
.empty
?
274 puts
" There " + (plural
? "are" : "is") + " #{total} message" +
275 (plural
? "s" : "") + " available."
289 print
" Retrieving message #{i} of #{total} [#{m.length} bytes]: "
293 if db_has_uidl
? $db, uidl
297 puts
" [Skipping, Deleting]"
299 delete_list
.push uidl
305 progress
= Progress
.new(m
.size
)
307 # Fetch the message...
310 chunk
.gsub
!(/\r\n/, "\n")
312 progress
.increase_by chunk
.length
315 # Deliver the message...
316 Kernel
.open("|-", "w+") do |f
|
323 raise "Couldn't exec \"#{@command}\": #{$!}\n"
329 unless add_uidl_to_db
$db, uidl
331 raise "Adding the UIDL to the database failed."
335 raise "The command \"#{@command}\" failed with exit code #{$?.exitstatus}"
339 # We've successfully dealt with the message now...
343 print
" [Fetched, Deleting]"
345 delete_list
.push uidl
349 if $reconnect_after and Time
.now
- connected_at
>= $reconnect_after
356 $db.transaction
do |db
|
357 delete_uidls_from_db db
, delete_list
365 # ----------------------------------------------------------------------
369 # Make sure that the UIDL database file is present.
371 $db = SQLite3
::Database.new($uidl_database_filename)
373 $db.execute( "CREATE TABLE IF NOT EXISTS uidls ( uidl TEXT PRIMARY KEY )" )
375 # Read in the configuration file...
377 accounts
= open($configuration_file, "r") { |f
| YAML
.load(f
) }
378 raise "No accounts specified in configuration file." if accounts
.length
== 0
380 # This is the main loop. Go through every account, fetching all the
383 accounts
.each_index
do |i
|
387 # Do some quick checks on what we've just parsed...
389 valid_account_properties
= ['Host', 'User', 'Pass', 'Command', 'SSL', 'APOP', 'Port']
391 (a
.keys
- valid_account_properties
).each
do |property
|
392 puts
"Warning: in account #{i + 1}, the unknown account property `#{property}' was ignored."
395 ['Host', 'User', 'Pass'].each
do |required
|
396 raise "Missing `#{required}:' line in account #{i + 1}" unless a
[required
]
397 unless a
[required
].class == String
398 raise "The value in the `#{required}:' property of account #{i + 1} " +
399 "(`#{a[required].to_s}' was not interpreted as a string; you " +
400 "may need to quote it"
404 ['SSL', 'APOP'].each
do |boolean
|
406 unless [ TrueClass
, FalseClass
].include? a
[boolean
].class
407 raise "In account #{i + 1}, `#{boolean}' property must be `yes', `no', `true' or `false'"
413 unless a
['Port'].class == Fixnum
414 raise "In account #{i + 1} the Port property must be an integer (not `#{a['Port']}\')"
417 a
['Port'] = a
['SSL'] ? 995 : 110
421 a
['Command'] = 'procmail -f-'
424 account
= POP3Account
.new(a
['Host'], a
['User'], a
['Pass'], a
['SSL'],
425 a
['APOP'], a
['Port'], a
['Command'])
428 puts
"Checking account: #{account}"
429 puts
" Piping mail to the command: #{account.command}"
432 $db.rollback
if $db.transaction_active
?
433 puts
"Interrupt received: exiting."
436 $db.rollback
if $db.transaction_active
?
437 puts
" Error fetching mail from account `#{account}': " + $
!
443 puts
"Fatal error: " + $
!