# This software carries the following license:
#
# Modified BSD license
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 
# 3. The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Steinar Knutsen

"""Geomyidae 1.4

Minimal gopher server. Not designed for heavy load. Main design goal has
been quick set up and reasonably robust operation. Based on RFC 1436.

Note: No sanity checks are made on served files, therefore all files
served as text or directories should use \\r\\n as newline, have
".\\r\\n" as their last three characters and embed single "." on a
line as "..".
"""
configtemplate = """# Configuration defaults for Gopher daemon.
# This is imported as a Python module.

# Port to bind on server.
port = 70
# Root for document requests.
root = "/usr/local/gopher"
# Number of seconds before killing off a fresh connection that hasn't made
# a request yet.
timeout = 10 
# Number of seconds to let a connection live in total.
ttl = 60
# Default directory page
def_page = "index.idx"
"""

import os, sys, socket, time, select, string

def demonize():
	pid = os.fork()
	if not pid:
		ppid = os.getppid()
		while ppid != 1:
			time.sleep(0.5)
			ppid = os.getppid()
		return
	else:
		os._exit(0)

def legalpath(path):
	path = os.path.abspath(os.path.join(
		geomyidaeconfig.root, path))
	if path[:len(geomyidaeconfig.root)] == geomyidaeconfig.root:
		return path
	else:
		return None

class connection:
	def __init__(self, client, address):
		self.timestamp = time.time()
		self.address = address
		self.client = client
		self.data = ''

	def serve(self):
		# We happily assume we have received a well formed request and let the
		# user pay if we haven't. This is generally a very ugly programmed
		# method.
		try:
			request = self.client.recv(1024)
		except:
			return
		if len(request) < 2:
			return
		elif request == '\r\n':
			request = geomyidaeconfig.def_page + "\r\n"
		path = request[:-2]
		path = legalpath(path)
		if path:
			try:
				file = open(path)
				self.data = file.read(-1)
				file.close()
			except:
				pass

	def pending_write(self):
		try:
			sent = self.client.send(self.data)
			if sent < len(self.data):
				self.data = self.data[sent:]
			else:
				self.data = ''
		except:
			pass

def removeclient(client, dictionary):
	try:
		client.shutdown(2)
		client.close()
	except:
		pass
	del dictionary[client]

def main():
	demonize()
	connections = {}
	transmitting = {}
	listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	listener.bind(('', geomyidaeconfig.port))
	listener.setblocking(0)
	while 1:
		try:
			listener.listen(2)
			client, address = listener.accept()
			client.setblocking(0)
			pending = connection(client, address)
			connections[client] = pending
		except socket.error:
			ready = select.select(connections.keys(), transmitting.keys(), [], 1)
			for client in ready[0]:
				uplink = connections[client]
				uplink.serve()
				if not uplink.data:
					removeclient(client, connections)
				else:
					transmitting[client] = uplink
					del connections[client]
			for client in ready[1]:
				downlink = transmitting[client]
				downlink.pending_write()
				if not downlink.data:
					removeclient(client, transmitting)
			for client, wrapper in connections.items():
				if time.time() - wrapper.timestamp > geomyidaeconfig.timeout:
					removeclient(client, connections)
			for client, wrapper in transmitting.items():
				if time.time() - wrapper.timestamp > geomyidaeconfig.ttl:
					removeclient(client, transmitting)

if __name__ == '__main__':
	if len(sys.argv) == 2 and sys.argv[1] == 'makeconfig':
		configfile = open('geomyidaeconfig.py', 'w')
		configfile.write(configtemplate)
		configfile.close()
	else:
		try:
			import geomyidaeconfig
		except:
			print 'No config file. "geomyidae makeconfig" generates a template.'
			sys.exit(0)
		main()
