[Zope-Checkins] CVS: Zope3/lib/python/Zope/Server/POP3 - IPOP3CommandHandler.py:1.1.2.1 POP3Server.py:1.1.2.1 POP3ServerChannel.py:1.1.2.1 POP3StatusMessages.py:1.1.2.1 __init__.py:1.1.2.1
Stephan Richter
srichter@cbu.edu
Fri, 5 Apr 2002 12:16:39 -0500
Update of /cvs-repository/Zope3/lib/python/Zope/Server/POP3
In directory cvs.zope.org:/tmp/cvs-serv18114/POP3
Added Files:
Tag: Zope3-Server-Branch
IPOP3CommandHandler.py POP3Server.py POP3ServerChannel.py
POP3StatusMessages.py __init__.py
Log Message:
Transcribed the shiks! POP3 code to our server model. Nothing is working
yet, I merely copied and adapted code.
=== Added File Zope3/lib/python/Zope/Server/POP3/IPOP3CommandHandler.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id: IPOP3CommandHandler.py,v 1.1.2.1 2002/04/05 17:16:38 srichter Exp $
"""
from Interface import Interface
class IPOP3CommandHandler(Interface):
"""
"""
def cmd_apop(args):
"""APOP name digest
Arguments:
a string identifying a mailbox and a MD5 digest string
(both required)
Restrictions:
may only be given in the AUTHORIZATION state after the POP3
greeting
Discussion:
Normally, each POP3 session starts with a USER/PASS
exchange. This results in a server/user-id specific
password being sent in the clear on the network. For
intermittent use of POP3, this may not introduce a sizable
risk. However, many POP3 client implementations connect to
the POP3 server on a regular basis -- to check for new
mail. Further the interval of session initiation may be on
the order of five minutes. Hence, the risk of password
capture is greatly enhanced.
An alternate method of authentication is required which
provides for both origin authentication and replay
protection, but which does not involve sending a password
in the clear over the network. The APOP command provides
this functionality.
A POP3 server which implements the APOP command will
include a timestamp in its banner greeting. The syntax of
the timestamp corresponds to the `msg-id' in [RFC822], and
MUST be different each time the POP3 server issues a banner
greeting. For example, on a UNIX implementation in which a
separate UNIX process is used for each instance of a POP3
server, the syntax of the timestamp might be:
<process-ID.clock@hostname>
where `process-ID' is the decimal value of the process's
PID, clock is the decimal value of the system clock, and
hostname is the fully-qualified domain-name corresponding
to the host where the POP3 server is running.
The POP3 client makes note of this timestamp, and then
issues the APOP command. The `name' parameter has
identical semantics to the `name' parameter of the USER
command. The `digest' parameter is calculated by applying
the MD5 algorithm [RFC1321] to a string consisting of the
timestamp (including angle-brackets) followed by a shared
secret. This shared secret is a string known only to the
POP3 client and server. Great care should be taken to
prevent unauthorized disclosure of the secret, as knowledge
of the secret will allow any entity to successfully
masquerade as the named user. The `digest' parameter
itself is a 16-octet value which is sent in hexadecimal
format, using lower-case ASCII characters.
When the POP3 server receives the APOP command, it verifies
the digest provided. If the digest is correct, the POP3
server issues a positive response, and the POP3 session
enters the TRANSACTION state. Otherwise, a negative
response is issued and the POP3 session remains in the
AUTHORIZATION state.
Note that as the length of the shared secret increases, so
does the difficulty of deriving it. As such, shared
secrets should be long strings (considerably longer than
the 8-character example shown below).
Possible Responses:
+OK maildrop locked and ready
-ERR permission denied
Examples:
S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us>
C: APOP mrose c4c9334bac560ecc979e58001b3e22fb
S: +OK maildrop has 1 message (369 octets)
In this example, the shared secret is the string `tan-
staaf'. Hence, the MD5 algorithm is applied to the string
<1896.697170952@dbc.mtview.ca.us>tanstaaf
which produces a digest value of
c4c9334bac560ecc979e58001b3e22fb
"""
def cmd_dele(args):
"""DELE msg
Arguments:
a message-number (required) which may not refer to a
message marked as deleted
Restrictions:
may only be given in the TRANSACTION state
Discussion:
The POP3 server marks the message as deleted. Any future
reference to the message-number associated with the message
in a POP3 command generates an error. The POP3 server does
not actually delete the message until the POP3 session enters
the UPDATE state.
Possible Responses:
+OK message deleted
-ERR no such message
Examples:
C: DELE 1
S: +OK message 1 deleted
...
C: DELE 2
S: -ERR message 2 already deleted
"""
def cmd_list(args):
"""LIST [msg]
Arguments:
a message-number (optional), which, if present, may NOT
refer to a message marked as deleted
Restrictions:
may only be given in the TRANSACTION state
Discussion:
If an argument was given and the POP3 server issues a
positive response with a line containing information for
that message. This line is called a "scan listing" for
that message.
If no argument was given and the POP3 server issues a
positive response, then the response given is multi-line.
After the initial +OK, for each message in the maildrop,
the POP3 server responds with a line containing information
for that message. This line is also called a "scan
listing" for that message.
In order to simplify parsing, all POP3 servers are required
to use a certain format for scan listings. A scan listing
consists of the message-number of the message, followed by
a single space and the exact size of the message in octets.
This memo makes no requirement on what follows the message
size in the scan listing. Minimal implementations should
just end that line of the response with a CRLF pair.
Note that messages marked as deleted are not listed.
Possible Responses:
+OK scan listing follows
-ERR no such message
Examples:
C: LIST
S: +OK 2 messages (320 octets)
S: 1 120
S: 2 200
S: .
...
C: LIST 2
S: +OK 2 200
...
C: LIST 3
S: -ERR no such message, only 2 messages in maildrop
"""
def cmd_pass(args):
"""PASS string
Arguments:
a server/mailbox-specific password (required)
Restrictions:
may only be given in the AUTHORIZATION state after a
successful USER command
Discussion:
Since the PASS command has exactly one argument, a POP3
server may treat spaces in the argument as part of the
password, instead of as argument separators.
Possible Responses:
+OK maildrop locked and ready
-ERR invalid password
-ERR unable to lock maildrop
Examples:
C: USER mrose
S: +OK mrose is a real hoopy frood
C: PASS secret
S: +OK mrose's maildrop has 2 messages (320 octets)
...
C: USER mrose
S: +OK mrose is a real hoopy frood
C: PASS secret
S: -ERR maildrop already locked"""
def cmd_quit(args):
"""QUIT
Arguments: none
Restrictions: none
Discussion:
The POP3 server removes all messages marked as deleted from
the maildrop. It then releases any exclusive-access lock
on the maildrop and replies as to the status of these
operations. The TCP connection is then closed.
Possible Responses:
+OK
Examples:
C: QUIT
S: +OK dewey POP3 server signing off (maildrop empty)
...
C: QUIT
S: +OK dewey POP3 server signing off (2 messages left)
...
"""
def cmd_retr(args):
"""RETR msg
Arguments:
a message-number (required) which may not refer to a
message marked as deleted
Restrictions:
may only be given in the TRANSACTION state
Discussion:
If the POP3 server issues a positive response, then the
response given is multi-line. After the initial +OK, the
POP3 server sends the message corresponding to the given
message-number, being careful to byte-stuff the termination
character (as with all multi-line responses).
Possible Responses:
+OK message follows
-ERR no such message
Examples:
C: RETR 1
S: +OK 120 octets
S: <the POP3 server sends the entire message here>
S: .
"""
def cmd_rset(args):
"""RSET
Arguments: none
Restrictions:
may only be given in the TRANSACTION state
Discussion:
If any messages have been marked as deleted by the POP3
server, they are unmarked. The POP3 server then replies
with a positive response.
Possible Responses:
+OK
Examples:
C: RSET
S: +OK maildrop has 2 messages (320 octets)
"""
def cmd_stat(args):
"""STAT
Arguments: none
Restrictions:
may only be given in the TRANSACTION state
Discussion:
The POP3 server issues a positive response with a line
containing information for the maildrop. This line is
called a "drop listing" for that maildrop.
In order to simplify parsing, all POP3 servers required to
use a certain format for drop listings. The positive
response consists of "+OK" followed by a single space, the
number of messages in the maildrop, a single space, and the
size of the maildrop in octets. This memo makes no
requirement on what follows the maildrop size. Minimal
implementations should just end that line of the response
with a CRLF pair. More advanced implementations may
include other information.
Note that messages marked as deleted are not counted in
either total.
Possible Responses:
+OK nn mm
Examples:
C: STAT
S: +OK 2 320
"""
def cmd_top(args):
"""TOP msg n
Arguments:
a message-number (required) which may NOT refer to a
message marked as deleted, and a non-negative number
(required)
Restrictions:
may only be given in the TRANSACTION state
Discussion:
If the POP3 server issues a positive response, then the
response given is multi-line. After the initial +OK, the
POP3 server sends the headers of the message, the blank
line separating the headers from the body, and then the
number of lines indicated message's body, being careful to
byte-stuff the termination character (as with all multi-
line responses).
Note that if the number of lines requested by the POP3
client is greater than than the number of lines in the
body, then the POP3 server sends the entire message.
Possible Responses:
+OK top of message follows
-ERR no such message
Examples:
C: TOP 1 10
S: +OK
S: <the POP3 server sends the headers of the
message, a blank line, and the first 10 lines
of the body of the message>
S: .
...
C: TOP 100 3
S: -ERR no such message
"""
def cmd_uidl(args):
"""UIDL [msg]
Arguments:
a message-number (optionally) If a message-number is given,
it may NOT refer to a message marked as deleted.
Restrictions:
may only be given in the TRANSACTION state.
Discussion:
If an argument was given and the POP3 server issues a positive
response with a line containing information for that message.
This line is called a "unique-id listing" for that message.
If no argument was given and the POP3 server issues a positive
response, then the response given is multi-line. After the
initial +OK, for each message in the maildrop, the POP3 server
responds with a line containing information for that message.
This line is called a "unique-id listing" for that message.
In order to simplify parsing, all POP3 servers are required to
use a certain format for unique-id listings. A unique-id
listing consists of the message-number of the message,
followed by a single space and the unique-id of the message.
No information follows the unique-id in the unique-id listing.
The unique-id of a message is an arbitrary server-determined
string, consisting of characters in the range 0x21 to 0x7E,
which uniquely identifies a message within a maildrop and
which persists across sessions. The server should never reuse
an unique-id in a given maildrop, for as long as the entity
using the unique-id exists.
Note that messages marked as deleted are not listed.
Possible Responses:
+OK unique-id listing follows
-ERR no such message
Examples:
C: UIDL
S: +OK
S: 1 whqtswO00WBw418f9t5JxYwZ
S: 2 QhdPYR:00WBw1Ph7x7
S: .
...
C: UIDL 2
S: +OK 2 QhdPYR:00WBw1Ph7x7
...
C: UIDL 3
S: -ERR no such message, only 2 messages in maildrop
"""
def cmd_user(args):
"""USER name
Arguments:
a string identifying a mailbox (required), which is of
significance ONLY to the server
Restrictions:
may only be given in the AUTHORIZATION state after the POP3
greeting or after an unsuccessful USER or PASS command
Possible Responses:
+OK name is a valid mailbox
-ERR never heard of mailbox name
Examples:
C: USER mrose
S: +OK mrose is a real hoopy frood
...
C: USER frated
S: -ERR sorry, no mailbox for frated here
"""
=== Added File Zope3/lib/python/Zope/Server/POP3/POP3Server.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id: POP3Server.py,v 1.1.2.1 2002/04/05 17:16:38 srichter Exp $
"""
from POP3ServerChannel import POP3ServerChannel
from Zope.Server.ServerBase import ServerBase
class POP3Server(ServerBase):
"""Generic FTP Server"""
channel_class = POP3ServerChannel
SERVER_IDENT = 'Zope.Server.POP3Server'
def __init__(self, ip, port, task_dispatcher=None, adj=None, start=1,
hit_log=None, verbose=0, socket_map=None):
super(FTPServer, self).__init__(ip, port, task_dispatcher,
adj, start, hit_log,
verbose, socket_map)
if __name__ == '__main__':
import asyncore
from Zope.Server.TaskThreads import ThreadedTaskDispatcher
td = ThreadedTaskDispatcher()
td.setThreadCount(4)
POP3Server('', 8110, task_dispatcher=td)
try:
while 1:
asyncore.poll(5)
print 'active channels:', POP3ServerChannel.active_channels
except KeyboardInterrupt:
print 'shutting down...'
td.shutdown()
=== Added File Zope3/lib/python/Zope/Server/POP3/POP3ServerChannel.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id: POP3ServerChannel.py,v 1.1.2.1 2002/04/05 17:16:38 srichter Exp $
"""
import os
import stat
import socket
import time
from Zope.Server.LineReceiver.LineServerChannel import LineServerChannel
from POP3StatusMessages import status_msgs
from FileProducer import FileProducer
from IPOP3CommandHandler import IPOP3CommandHandler
from PassiveAcceptor import PassiveAcceptor
from RecvChannel import RecvChannel
from XmitChannel import XmitChannel
class POP3ServerChannel(LineServerChannel):
"""The POP3 Server Channel represents a connection to a particular
client. We can therefore store information here."""
__implements__ = LineServerChannel.__implements__, IPOP3CommandHandler
# These are the commands that are allowed without the channel being in
# "Transaction State", as the POP3 RFC calls it.
special_commands = ('cmd_quit', 'cmd_user', 'cmd_pass')
# These are the commands that are accessing the filesystem.
# Since this could be also potentially a longer process, these commands
# are also the ones that are executed in a different thread.
thread_commands = ('cmd_apop', 'cmd_dele', 'cmd_list', 'cmd_pass',
'cmd_retr', 'cmd_rset', 'cmd_stat', 'cmd_top',
'cmd_uidl')
# Define the status messages
status_messages = status_msgs
def __init__(self, server, conn, addr, adj=None, socket_map=None):
super(POP3ServerChannel, self).__init__(server, conn, addr,
adj, socket_map)
self.username = ''
self.password = ''
self.messagelist = []
############################################################
# Implementation methods for interface
# Zope.Server.POP3.IPOP3CommandHandler
def cmd_apop(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
pass
def cmd_dele(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
try:
msg_index = int(args)-1
except:
return self.reply('ERR_MSG_UNKNOWN')
msg_list = self.messagelist
if msg_index >= 0 and msg_index < len(msg_list):
# mark message as deleted
self.msg_list[msg_index].deleted = 1
return self.reply('OK_DELETE')
return self.reply('ERR_MSG_UNKNOWN')
def cmd_list(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
msg_list = self.messagelist
if args:
# A message id was passed, so let's work with it.
try:
msg_index = int(args)-1
except:
return self.reply('ERR_MSG_UNKNOWN')
if msg_index >= 0 and msg_index < len(msg_list):
return self.reply('ERR_MSG_UNKNOWN')
message = msg_list[msg_index]
self.reply('OK_SINGLE_LIST', (msg_index+1, message.size)
else:
usedbytes = self.getTotalSize(msg_list)
total_msgs = len(map(lambda msg: not msg.deleted, msg_list))
self.reply('OK_MSG_LIST', (len(msg_list), usedbytes))
for msg in msg_list:
if msg.deleted: continue
self.write("%d %d\r\n" % (msg_list.index(msg)+1, msg.size))
self.write('.\r\n')
self.flush()
def cmd_pass(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
self.password = args
if self.authenticated:
return self.reply('ERR_INV_STATE')
if not self.username:
return self.reply('ERR_NO_USER')
auth = self.server.auth_source
self.authenticated, message = auth.authenticate(self.username,
self.password)
if self.authenticated:
self.reply('OK_LOGIN')
else:
self.reply('ERR_LOGIN_MISMATCH')
self.close_when_done()
def cmd_quit(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
self.reply('OK_QUIT')
# XXX Should de;ete messages
self.close_when_done()
def cmd_retr(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
try:
msg_index = int(args)-1
except:
return self.reply('ERR_MSG_UNKNOWN')
msg_list = self.messagelist
if msg_index >= 0 and msg_index < len(msg_list):
# mark message as deleted
self.write(msg.body)
return self.reply('OK_RETR')
return self.reply('ERR_MSG_UNKNOWN')
def cmd_rset(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
for msg in self.messagelist):
# mark all messages as not-deleted
msg.deleted = 0
self.reply('OK_RSET')
def cmd_stat(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
usedbytes = self.getTotalSize(msg_list)
total_msgs = len(map(lambda msg: not msg.deleted, msg_list))
self.reply('OK_STAT', (total_msgs, usedbytes))
def cmd_top(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
try:
msg_index, nroflines = args.split()
msg_index = int(args)-1
nroflines = int(nroflines)
except:
return self.reply('ERR_MSG_UNKNOWN')
msg_list = self.messagelist
if msg_index >= 0 and msg_index < len(msg_list):
# Split message body into lines/
lines = self.messagelist[msg_index].body.split("\r\n")
found, isHeader, line = -1, 1, 0
# XXX: This is too complicated. It can be done easier.
while line < len(nroflines):
if isHeader:
# skip header lines. Header lines have a :
if lines[line].find(':') == 0:
isHeader = 0
else:
found += 1
if found == nroflines:
break
self.reply('OK_TOP', line)
lines = lines[:line]
self.write("\r\n".join(lines))
self.write('.\r\n')
self.flush()
else:
return self.reply('ERR_MSG_UNKNOWN')
def cmd_uidl(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
pass
def cmd_user(self, args):
'See Zope.Server.POP3.IPOP3CommandHandler.IPOP3CommandHandler'
if self.authenticated:
return self.reply('ERR_INV_STATE')
if self.auth.hasUser(args):
self.reply('OK_USER', args)
else:
self.reply('ERR_NOT_USER')
#
############################################################
=== Added File Zope3/lib/python/Zope/Server/POP3/POP3StatusMessages.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id: POP3StatusMessages.py,v 1.1.2.1 2002/04/05 17:16:38 srichter Exp $
"""
status_msgs = {
'OK_GENERAL' : '+OK',
'OK_LOGIN' : '+OK login successful',
'OK_USER' : '+OK %s is a valid name box',
'OK_QUIT' : '+OK',
'OK_SINGLE_LIST' : '+OK %i %i',
'OK_MSG_LIST' : '+OK %i message (%i octets)',
'OK_DELETE' : '+OK The message was successfully deleted'
'OK_RETR' : '+OK message follows',
'OK_RSET' : '+OK Resetting all messages done',
'OKTOP' : '+OK top %i lines of message follows',
'OK_APOP' : '+OK maildrop locked and ready',
'OK_UIDL' : '+OK unique-id listing follows',
'ERR_CMD_UNKNOWN' : '-ERR unknown command',
'ERR_MSG_UNKNOWN' : '-ERR unknown or invalid message id',
'ERR_INV_STATE' : '-ERR Invalid State',
'ERR_NO_USER' : '-ERR No user was yet specified'
'ERR_NOT_USER' : '-ERR never heard of mailbox name',
'ERR_LOGIN_MISMATH' : '-ERR username and password did not match',
}
=== Added File Zope3/lib/python/Zope/Server/POP3/__init__.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id: __init__.py,v 1.1.2.1 2002/04/05 17:16:38 srichter Exp $
"""