# -*- Mode: Python; tab-width: 4 -*-

import filesys
import ftp_server
import string

# create a 'dummy' authorizer (one that lets everyone in) that returns
# a read-only filesystem rooted at '/homes/ftp'

class email_authorizer:
	def __init__ (self, root='/'):
		self.root = root
	def authorize (self, channel, username, password):
		channel.persona = -1, -1
		# writes will be caught by the channel 'open' method.
		channel.read_only = 0
		return 1, 'Ok.', filesys.os_filesystem (self.root)

authorizer = email_authorizer ('/homes/ftp')

# Create an ftp server using this authorizer, running on port 8021
# [the standard port is 21, but you are probably already running
#  a server there]

import StringIO
import os
import socket

class email_file:

	def __init__ (self, from_whom):
		self.buffer = []
		self.from_whom = from_whom

	def write (self, data):
		self.buffer.append (data)
		return len(data)

	def close (self):
		import nnfmp
		self.buffer.insert (0, 'From: <%s>\n\n' % self.from_whom)
		nnfmp.send_message (
			#['carlp@eGroups.net'],
			['rushing@seattle.nightmare.com'],
			string.join (self.buffer, ''),
			self.from_whom
			)

class email_ftp_channel (ftp_server.ftp_channel):

	read_only = 0

	def open (self, path, mode):
		print 'open: %s %s' % (path, mode)
		if not 'r' in mode:
			# XXX: DoS with huge input?
			return email_file (self.user)
		else:
			return ftp_server.ftp_channel.open (self, path, mode)

class email_ftp_server (ftp_server.ftp_server):

	ftp_channel_class = email_ftp_channel

fs = email_ftp_server (authorizer, port=9021)

import asyncore
asyncore.loop()

# to test this server, try
# $ ftp myhost 8021
# when using the standard bsd ftp client,
# $ ncftp -p 8021 myhost
# when using ncftp, and
# ftp://myhost:8021/
# from a web browser.
