Commit b9e5da32 authored by Andreas Jung's avatar Andreas Jung

we *hate* tabs - lets get rid of them

parent 91134442
This diff is collapsed.
......@@ -5,7 +5,7 @@
# All Rights Reserved.
#
RCS_ID = '$Id: auth_handler.py,v 1.2 2001/04/25 19:07:30 andreas Exp $'
RCS_ID = '$Id: auth_handler.py,v 1.3 2001/05/01 11:44:48 andreas Exp $'
# support for 'basic' authenticaion.
......@@ -30,108 +30,108 @@ import producers
# does anyone support digest authentication? (rfc2069)
class auth_handler:
def __init__ (self, dict, handler, realm='default'):
self.authorizer = dictionary_authorizer (dict)
self.handler = handler
self.realm = realm
self.pass_count = counter.counter()
self.fail_count = counter.counter()
def match (self, request):
# by default, use the given handler's matcher
return self.handler.match (request)
def handle_request (self, request):
# authorize a request before handling it...
scheme = get_header (AUTHORIZATION, request.header)
if scheme:
scheme = string.lower (scheme)
if scheme == 'basic':
cookie = AUTHORIZATION.group(2)
try:
decoded = base64.decodestring (cookie)
except:
print 'malformed authorization info <%s>' % cookie
request.error (400)
return
auth_info = string.split (decoded, ':')
if self.authorizer.authorize (auth_info):
self.pass_count.increment()
request.auth_info = auth_info
self.handler.handle_request (request)
else:
self.handle_unauthorized (request)
#elif scheme == 'digest':
# print 'digest: ',AUTHORIZATION.group(2)
else:
print 'unknown/unsupported auth method: %s' % scheme
self.handle_unauthorized()
else:
# list both? prefer one or the other?
# you could also use a 'nonce' here. [see below]
#auth = 'Basic realm="%s" Digest realm="%s"' % (self.realm, self.realm)
#nonce = self.make_nonce (request)
#auth = 'Digest realm="%s" nonce="%s"' % (self.realm, nonce)
#request['WWW-Authenticate'] = auth
#print 'sending header: %s' % request['WWW-Authenticate']
self.handle_unauthorized (request)
def handle_unauthorized (self, request):
# We are now going to receive data that we want to ignore.
# to ignore the file data we're not interested in.
self.fail_count.increment()
request.channel.set_terminator (None)
request['Connection'] = 'close'
request['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm
request.error (401)
def make_nonce (self, request):
"A digest-authentication <nonce>, constructed as suggested in RFC 2069"
ip = request.channel.server.ip
now = str (long (time.time()))[:-1]
private_key = str (id (self))
nonce = string.join ([ip, now, private_key], ':')
return self.apply_hash (nonce)
def apply_hash (self, s):
"Apply MD5 to a string <s>, then wrap it in base64 encoding."
m = md5.new()
m.update (s)
d = m.digest()
# base64.encodestring tacks on an extra linefeed.
return base64.encodestring (d)[:-1]
def status (self):
# Thanks to mwm@contessa.phone.net (Mike Meyer)
r = [
producers.simple_producer (
'<li>Authorization Extension : '
'<b>Unauthorized requests:</b> %s<ul>' % self.fail_count
)
]
if hasattr (self.handler, 'status'):
r.append (self.handler.status())
r.append (
producers.simple_producer ('</ul>')
)
return producers.composite_producer (
http_server.fifo (r)
)
def __init__ (self, dict, handler, realm='default'):
self.authorizer = dictionary_authorizer (dict)
self.handler = handler
self.realm = realm
self.pass_count = counter.counter()
self.fail_count = counter.counter()
def match (self, request):
# by default, use the given handler's matcher
return self.handler.match (request)
def handle_request (self, request):
# authorize a request before handling it...
scheme = get_header (AUTHORIZATION, request.header)
if scheme:
scheme = string.lower (scheme)
if scheme == 'basic':
cookie = AUTHORIZATION.group(2)
try:
decoded = base64.decodestring (cookie)
except:
print 'malformed authorization info <%s>' % cookie
request.error (400)
return
auth_info = string.split (decoded, ':')
if self.authorizer.authorize (auth_info):
self.pass_count.increment()
request.auth_info = auth_info
self.handler.handle_request (request)
else:
self.handle_unauthorized (request)
#elif scheme == 'digest':
# print 'digest: ',AUTHORIZATION.group(2)
else:
print 'unknown/unsupported auth method: %s' % scheme
self.handle_unauthorized()
else:
# list both? prefer one or the other?
# you could also use a 'nonce' here. [see below]
#auth = 'Basic realm="%s" Digest realm="%s"' % (self.realm, self.realm)
#nonce = self.make_nonce (request)
#auth = 'Digest realm="%s" nonce="%s"' % (self.realm, nonce)
#request['WWW-Authenticate'] = auth
#print 'sending header: %s' % request['WWW-Authenticate']
self.handle_unauthorized (request)
def handle_unauthorized (self, request):
# We are now going to receive data that we want to ignore.
# to ignore the file data we're not interested in.
self.fail_count.increment()
request.channel.set_terminator (None)
request['Connection'] = 'close'
request['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm
request.error (401)
def make_nonce (self, request):
"A digest-authentication <nonce>, constructed as suggested in RFC 2069"
ip = request.channel.server.ip
now = str (long (time.time()))[:-1]
private_key = str (id (self))
nonce = string.join ([ip, now, private_key], ':')
return self.apply_hash (nonce)
def apply_hash (self, s):
"Apply MD5 to a string <s>, then wrap it in base64 encoding."
m = md5.new()
m.update (s)
d = m.digest()
# base64.encodestring tacks on an extra linefeed.
return base64.encodestring (d)[:-1]
def status (self):
# Thanks to mwm@contessa.phone.net (Mike Meyer)
r = [
producers.simple_producer (
'<li>Authorization Extension : '
'<b>Unauthorized requests:</b> %s<ul>' % self.fail_count
)
]
if hasattr (self.handler, 'status'):
r.append (self.handler.status())
r.append (
producers.simple_producer ('</ul>')
)
return producers.composite_producer (
http_server.fifo (r)
)
class dictionary_authorizer:
def __init__ (self, dict):
self.dict = dict
def authorize (self, auth_info):
[username, password] = auth_info
if (self.dict.has_key (username)) and (self.dict[username] == password):
return 1
else:
return 0
def __init__ (self, dict):
self.dict = dict
def authorize (self, auth_info):
[username, password] = auth_info
if (self.dict.has_key (username)) and (self.dict[username] == password):
return 1
else:
return 0
AUTHORIZATION = re.compile (
# scheme challenge
'Authorization: ([^ ]+) (.*)',
re.IGNORECASE
)
# scheme challenge
'Authorization: ([^ ]+) (.*)',
re.IGNORECASE
)
......@@ -5,7 +5,7 @@
# All Rights Reserved.
#
RCS_ID = '$Id: chat_server.py,v 1.2 2001/04/25 19:07:30 andreas Exp $'
RCS_ID = '$Id: chat_server.py,v 1.3 2001/05/01 11:44:48 andreas Exp $'
import string
......@@ -18,133 +18,133 @@ import status_handler
class chat_channel (asynchat.async_chat):
def __init__ (self, server, sock, addr):
asynchat.async_chat.__init__ (self, sock)
self.server = server
self.addr = addr
self.set_terminator ('\r\n')
self.data = ''
self.nick = None
self.push ('nickname?: ')
def collect_incoming_data (self, data):
self.data = self.data + data
def found_terminator (self):
line = self.data
self.data = ''
if self.nick is None:
self.nick = string.split (line)[0]
if not self.nick:
self.nick = None
self.push ('huh? gimmee a nickname: ')
else:
self.greet()
else:
if not line:
pass
elif line[0] != '/':
self.server.push_line (self, line)
else:
self.handle_command (line)
def greet (self):
self.push ('Hello, %s\r\n' % self.nick)
num_channels = len(self.server.channels)-1
if num_channels == 0:
self.push ('[Kinda lonely in here... you\'re the only caller!]\r\n')
else:
self.push ('[There are %d other callers]\r\n' % (len(self.server.channels)-1))
nicks = map (lambda x: x.get_nick(), self.server.channels.keys())
self.push (string.join (nicks, '\r\n ') + '\r\n')
self.server.push_line (self, '[joined]')
def handle_command (self, command):
import types
command_line = string.split(command)
name = 'cmd_%s' % command_line[0][1:]
if hasattr (self, name):
# make sure it's a method...
method = getattr (self, name)
if type(method) == type(self.handle_command):
method (command_line[1:])
else:
self.push ('unknown command: %s' % command_line[0])
def cmd_quit (self, args):
self.server.push_line (self, '[left]')
self.push ('Goodbye!\r\n')
self.close_when_done()
# alias for '/quit' - '/q'
cmd_q = cmd_quit
def push_line (self, nick, line):
self.push ('%s: %s\r\n' % (nick, line))
def handle_close (self):
self.close()
def close (self):
del self.server.channels[self]
asynchat.async_chat.close (self)
def get_nick (self):
if self.nick is not None:
return self.nick
else:
return 'Unknown'
def __init__ (self, server, sock, addr):
asynchat.async_chat.__init__ (self, sock)
self.server = server
self.addr = addr
self.set_terminator ('\r\n')
self.data = ''
self.nick = None
self.push ('nickname?: ')
def collect_incoming_data (self, data):
self.data = self.data + data
def found_terminator (self):
line = self.data
self.data = ''
if self.nick is None:
self.nick = string.split (line)[0]
if not self.nick:
self.nick = None
self.push ('huh? gimmee a nickname: ')
else:
self.greet()
else:
if not line:
pass
elif line[0] != '/':
self.server.push_line (self, line)
else:
self.handle_command (line)
def greet (self):
self.push ('Hello, %s\r\n' % self.nick)
num_channels = len(self.server.channels)-1
if num_channels == 0:
self.push ('[Kinda lonely in here... you\'re the only caller!]\r\n')
else:
self.push ('[There are %d other callers]\r\n' % (len(self.server.channels)-1))
nicks = map (lambda x: x.get_nick(), self.server.channels.keys())
self.push (string.join (nicks, '\r\n ') + '\r\n')
self.server.push_line (self, '[joined]')
def handle_command (self, command):
import types
command_line = string.split(command)
name = 'cmd_%s' % command_line[0][1:]
if hasattr (self, name):
# make sure it's a method...
method = getattr (self, name)
if type(method) == type(self.handle_command):
method (command_line[1:])
else:
self.push ('unknown command: %s' % command_line[0])
def cmd_quit (self, args):
self.server.push_line (self, '[left]')
self.push ('Goodbye!\r\n')
self.close_when_done()
# alias for '/quit' - '/q'
cmd_q = cmd_quit
def push_line (self, nick, line):
self.push ('%s: %s\r\n' % (nick, line))
def handle_close (self):
self.close()
def close (self):
del self.server.channels[self]
asynchat.async_chat.close (self)
def get_nick (self):
if self.nick is not None:
return self.nick
else:
return 'Unknown'
class chat_server (asyncore.dispatcher):
SERVER_IDENT = 'Chat Server (V%s)' % VERSION
channel_class = chat_channel
spy = 1
def __init__ (self, ip='', port=8518):
self.port = port
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.bind ((ip, port))
print '%s started on port %d' % (self.SERVER_IDENT, port)
self.listen (5)
self.channels = {}
self.count = 0
def handle_accept (self):
conn, addr = self.accept()
self.count = self.count + 1
print 'client #%d - %s:%d' % (self.count, addr[0], addr[1])
self.channels[self.channel_class (self, conn, addr)] = 1
def push_line (self, from_channel, line):
nick = from_channel.get_nick()
if self.spy:
print '%s: %s' % (nick, line)
for c in self.channels.keys():
if c is not from_channel:
c.push ('%s: %s\r\n' % (nick, line))
def status (self):
lines = [
'<h2>%s</h2>' % self.SERVER_IDENT,
'<br>Listening on Port: %d' % self.port,
'<br><b>Total Sessions:</b> %d' % self.count,
'<br><b>Current Sessions:</b> %d' % (len(self.channels))
]
return status_handler.lines_producer (lines)
def writable (self):
return 0
SERVER_IDENT = 'Chat Server (V%s)' % VERSION
channel_class = chat_channel
spy = 1
def __init__ (self, ip='', port=8518):
self.port = port
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.bind ((ip, port))
print '%s started on port %d' % (self.SERVER_IDENT, port)
self.listen (5)
self.channels = {}
self.count = 0
def handle_accept (self):
conn, addr = self.accept()
self.count = self.count + 1
print 'client #%d - %s:%d' % (self.count, addr[0], addr[1])
self.channels[self.channel_class (self, conn, addr)] = 1
def push_line (self, from_channel, line):
nick = from_channel.get_nick()
if self.spy:
print '%s: %s' % (nick, line)
for c in self.channels.keys():
if c is not from_channel:
c.push ('%s: %s\r\n' % (nick, line))
def status (self):
lines = [
'<h2>%s</h2>' % self.SERVER_IDENT,
'<br>Listening on Port: %d' % self.port,
'<br><b>Total Sessions:</b> %d' % self.count,
'<br><b>Current Sessions:</b> %d' % (len(self.channels))
]
return status_handler.lines_producer (lines)
def writable (self):
return 0
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
port = string.atoi (sys.argv[1])
else:
port = 8518
s = chat_server ('', port)
asyncore.loop()
import sys
if len(sys.argv) > 1:
port = string.atoi (sys.argv[1])
else:
port = 8518
s = chat_server ('', port)
asyncore.loop()
......@@ -4,24 +4,24 @@
class continuation:
'Package up a continuation as an object.'
'Also a convenient place to store state.'
def __init__ (self, fun, *args):
self.funs = [(fun, args)]
def __call__ (self, *args):
fun, init_args = self.funs[0]
self.funs = self.funs[1:]
if self.funs:
apply (fun, (self,)+ init_args + args)
else:
apply (fun, init_args + args)
def chain (self, fun, *args):
self.funs.insert (0, (fun, args))
return self
def abort (self, *args):
fun, init_args = self.funs[-1]
apply (fun, init_args + args)
'Package up a continuation as an object.'
'Also a convenient place to store state.'
def __init__ (self, fun, *args):
self.funs = [(fun, args)]
def __call__ (self, *args):
fun, init_args = self.funs[0]
self.funs = self.funs[1:]
if self.funs:
apply (fun, (self,)+ init_args + args)
else:
apply (fun, init_args + args)
def chain (self, fun, *args):
self.funs.insert (0, (fun, args))
return self
def abort (self, *args):
fun, init_args = self.funs[-1]
apply (fun, init_args + args)
This diff is collapsed.
......@@ -4,17 +4,17 @@ import time
def main (env, stdin, stdout):
# write out the response
stdout.write ("HTTP/1.0 200 OK\r\n")
# write out a header
stdout.write ("Content-Type: text/html\r\n")
stdout.write ("\r\n")
stdout.write ("<html><body>")
for i in range (10,0,-1):
stdout.write ("<br> <b>tick</b> %d\r\n" % i)
stdout.flush()
time.sleep (3)
stdout.write ("</body></html>\r\n")
# write out the response
stdout.write ("HTTP/1.0 200 OK\r\n")
# write out a header
stdout.write ("Content-Type: text/html\r\n")
stdout.write ("\r\n")
stdout.write ("<html><body>")
for i in range (10,0,-1):
stdout.write ("<br> <b>tick</b> %d\r\n" % i)
stdout.flush()
time.sleep (3)
stdout.write ("</body></html>\r\n")
......@@ -13,35 +13,35 @@
# will overflow.
class counter:
"general-purpose counter"
def __init__ (self, initial_value=0):
self.value = initial_value
def increment (self, delta=1):
result = self.value
try:
self.value = self.value + delta
except OverflowError:
self.value = long(self.value) + delta
return result
def decrement (self, delta=1):
result = self.value
try:
self.value = self.value - delta
except OverflowError:
self.value = long(self.value) - delta
return result
def as_long (self):
return long(self.value)
def __nonzero__ (self):
return self.value != 0
def __repr__ (self):
return '<counter value=%s at %x>' % (self.value, id(self))
def __str__ (self):
return str(long(self.value))[:-1]
"general-purpose counter"
def __init__ (self, initial_value=0):
self.value = initial_value
def increment (self, delta=1):
result = self.value
try:
self.value = self.value + delta
except OverflowError:
self.value = long(self.value) + delta
return result
def decrement (self, delta=1):
result = self.value
try:
self.value = self.value - delta
except OverflowError:
self.value = long(self.value) - delta
return result
def as_long (self):
return long(self.value)
def __nonzero__ (self):
return self.value != 0
def __repr__ (self):
return '<counter value=%s at %x>' % (self.value, id(self))
def __str__ (self):
return str(long(self.value))[:-1]
This diff is collapsed.
......@@ -20,74 +20,74 @@ socket_map = asyncore.socket_map
class event_loop:
def __init__ (self):
self.events = []
self.num_channels = 0
self.max_channels = 0
def go (self, timeout=30.0, granularity=15):
global socket_map
last_event_check = 0
while socket_map:
now = int(time.time())
if (now - last_event_check) >= granularity:
last_event_check = now
fired = []
# yuck. i want my lisp.
i = j = 0
while i < len(self.events):
when, what = self.events[i]
if now >= when:
fired.append (what)
j = i + 1
else:
break
i = i + 1
if fired:
self.events = self.events[j:]
for what in fired:
what (self, now)
# sample the number of channels
n = len(asyncore.socket_map)
self.num_channels = n
if n > self.max_channels:
self.max_channels = n
asyncore.poll (timeout)
def schedule (self, delta, callback):
now = int (time.time())
bisect.insort (self.events, (now + delta, callback))
def __len__ (self):
return len(self.events)
def __init__ (self):
self.events = []
self.num_channels = 0
self.max_channels = 0
def go (self, timeout=30.0, granularity=15):
global socket_map
last_event_check = 0
while socket_map:
now = int(time.time())
if (now - last_event_check) >= granularity:
last_event_check = now
fired = []
# yuck. i want my lisp.
i = j = 0
while i < len(self.events):
when, what = self.events[i]
if now >= when:
fired.append (what)
j = i + 1
else:
break
i = i + 1
if fired:
self.events = self.events[j:]
for what in fired:
what (self, now)
# sample the number of channels
n = len(asyncore.socket_map)
self.num_channels = n
if n > self.max_channels:
self.max_channels = n
asyncore.poll (timeout)
def schedule (self, delta, callback):
now = int (time.time())
bisect.insort (self.events, (now + delta, callback))
def __len__ (self):
return len(self.events)
class test (asyncore.dispatcher):
def __init__ (self):
asyncore.dispatcher.__init__ (self)
def handle_connect (self):
print 'Connected!'
def writable (self):
return not self.connected
def connect_timeout_callback (self, event_loop, when):
if not self.connected:
print 'Timeout on connect'
self.close()
def periodic_thing_callback (self, event_loop, when):
print 'A Periodic Event has Occurred!'
# re-schedule it.
event_loop.schedule (15, self.periodic_thing_callback)
def __init__ (self):
asyncore.dispatcher.__init__ (self)
def handle_connect (self):
print 'Connected!'
def writable (self):
return not self.connected
def connect_timeout_callback (self, event_loop, when):
if not self.connected:
print 'Timeout on connect'
self.close()
def periodic_thing_callback (self, event_loop, when):
print 'A Periodic Event has Occurred!'
# re-schedule it.
event_loop.schedule (15, self.periodic_thing_callback)
if __name__ == '__main__':
import socket
el = event_loop()
t = test ()
t.create_socket (socket.AF_INET, socket.SOCK_STREAM)
el.schedule (10, t.connect_timeout_callback)
el.schedule (15, t.periodic_thing_callback)
t.connect (('squirl', 80))
el.go(1.0)
import socket
el = event_loop()
t = test ()
t.create_socket (socket.AF_INET, socket.SOCK_STREAM)
el.schedule (10, t.connect_timeout_callback)
el.schedule (15, t.periodic_thing_callback)
t.connect (('squirl', 80))
el.go(1.0)
......@@ -2,202 +2,202 @@
# fifo, implemented with lisp-style pairs.
# [quick translation of scheme48/big/queue.scm]
class fifo:
def __init__ (self):
self.head, self.tail = None, None
self.length = 0
self.node_cache = None
def __len__ (self):
return self.length
def push (self, v):
self.node_cache = None
self.length = self.length + 1
p = [v, None]
if self.head is None:
self.head = p
else:
self.tail[1] = p
self.tail = p
def pop (self):
self.node_cache = None
pair = self.head
if pair is None:
raise ValueError, "pop() from an empty queue"
else:
self.length = self.length - 1
[value, next] = pair
self.head = next
if next is None:
self.tail = None
return value
def first (self):
if self.head is None:
raise ValueError, "first() of an empty queue"
else:
return self.head[0]
def push_front (self, thing):
self.node_cache = None
self.length = self.length + 1
old_head = self.head
new_head = [thing, old_head]
self.head = new_head
if old_head is None:
self.tail = new_head
def _nth (self, n):
i = n
h = self.head
while i:
h = h[1]
i = i - 1
self.node_cache = n, h[1]
return h[0]
def __getitem__ (self, index):
if (index < 0) or (index >= self.length):
raise IndexError, "index out of range"
else:
if self.node_cache:
j, h = self.node_cache
if j == index - 1:
result = h[0]
self.node_cache = index, h[1]
return result
else:
return self._nth (index)
else:
return self._nth (index)
class fifo:
def __init__ (self):
self.head, self.tail = None, None
self.length = 0
self.node_cache = None
def __len__ (self):
return self.length
def push (self, v):
self.node_cache = None
self.length = self.length + 1
p = [v, None]
if self.head is None:
self.head = p
else:
self.tail[1] = p
self.tail = p
def pop (self):
self.node_cache = None
pair = self.head
if pair is None:
raise ValueError, "pop() from an empty queue"
else:
self.length = self.length - 1
[value, next] = pair
self.head = next
if next is None:
self.tail = None
return value
def first (self):
if self.head is None:
raise ValueError, "first() of an empty queue"
else:
return self.head[0]
def push_front (self, thing):
self.node_cache = None
self.length = self.length + 1
old_head = self.head
new_head = [thing, old_head]
self.head = new_head
if old_head is None:
self.tail = new_head
def _nth (self, n):
i = n
h = self.head
while i:
h = h[1]
i = i - 1
self.node_cache = n, h[1]
return h[0]
def __getitem__ (self, index):
if (index < 0) or (index >= self.length):
raise IndexError, "index out of range"
else:
if self.node_cache:
j, h = self.node_cache
if j == index - 1:
result = h[0]
self.node_cache = index, h[1]
return result
else:
return self._nth (index)
else:
return self._nth (index)
class protected_fifo:
def __init__ (self, lock=None):
if lock is None:
import thread
self.lock = thread.allocate_lock()
else:
self.lock = lock
self.fifo = fifo.fifo()
def push (self, item):
try:
self.lock.acquire()
self.fifo.push (item)
finally:
self.lock.release()
enqueue = push
def pop (self):
try:
self.lock.acquire()
return self.fifo.pop()
finally:
self.lock.release()
dequeue = pop
def __len__ (self):
try:
self.lock.acquire()
return len(self.queue)
finally:
self.lock.release()
def __init__ (self, lock=None):
if lock is None:
import thread
self.lock = thread.allocate_lock()
else:
self.lock = lock
self.fifo = fifo.fifo()
def push (self, item):
try:
self.lock.acquire()
self.fifo.push (item)
finally:
self.lock.release()
enqueue = push
def pop (self):
try:
self.lock.acquire()
return self.fifo.pop()
finally:
self.lock.release()
dequeue = pop
def __len__ (self):
try:
self.lock.acquire()
return len(self.queue)
finally:
self.lock.release()
class output_fifo:
EMBEDDED = 'embedded'
EOF = 'eof'
TRIGGER = 'trigger'
def __init__ (self):
# containment, not inheritance
self.fifo = fifo()
self._embedded = None
def push_embedded (self, fifo):
# push embedded fifo
fifo.parent = self # CYCLE
self.fifo.push ((self.EMBEDDED, fifo))
def push_eof (self):
# push end-of-fifo
self.fifo.push ((self.EOF, None))
def push_trigger (self, thunk):
self.fifo.push ((self.TRIGGER, thunk))
def push (self, item):
# item should be a producer or string
self.fifo.push (item)
# 'length' is an inaccurate term. we should
# probably use an 'empty' method instead.
def __len__ (self):
if self._embedded is None:
return len(self.fifo)
else:
return len(self._embedded)
def empty (self):
return len(self) == 0
def first (self):
if self._embedded is None:
return self.fifo.first()
else:
return self._embedded.first()
def pop (self):
if self._embedded is not None:
return self._embedded.pop()
else:
result = self.fifo.pop()
# unset self._embedded
self._embedded = None
# check for special items in the front
if len(self.fifo):
front = self.fifo.first()
if type(front) is type(()):
# special
kind, value = front
if kind is self.EMBEDDED:
self._embedded = value
elif kind is self.EOF:
# break the cycle
parent = self.parent
self.parent = None
# pop from parent
parent._embedded = None
elif kind is self.TRIGGER:
# call the trigger thunk
value()
# remove the special
self.fifo.pop()
# return the originally popped result
return result
EMBEDDED = 'embedded'
EOF = 'eof'
TRIGGER = 'trigger'
def __init__ (self):
# containment, not inheritance
self.fifo = fifo()
self._embedded = None
def push_embedded (self, fifo):
# push embedded fifo
fifo.parent = self # CYCLE
self.fifo.push ((self.EMBEDDED, fifo))
def push_eof (self):
# push end-of-fifo
self.fifo.push ((self.EOF, None))
def push_trigger (self, thunk):
self.fifo.push ((self.TRIGGER, thunk))
def push (self, item):
# item should be a producer or string
self.fifo.push (item)
# 'length' is an inaccurate term. we should
# probably use an 'empty' method instead.
def __len__ (self):
if self._embedded is None:
return len(self.fifo)
else:
return len(self._embedded)
def empty (self):
return len(self) == 0
def first (self):
if self._embedded is None:
return self.fifo.first()
else:
return self._embedded.first()
def pop (self):
if self._embedded is not None:
return self._embedded.pop()
else:
result = self.fifo.pop()
# unset self._embedded
self._embedded = None
# check for special items in the front
if len(self.fifo):
front = self.fifo.first()
if type(front) is type(()):
# special
kind, value = front
if kind is self.EMBEDDED:
self._embedded = value
elif kind is self.EOF:
# break the cycle
parent = self.parent
self.parent = None
# pop from parent
parent._embedded = None
elif kind is self.TRIGGER:
# call the trigger thunk
value()
# remove the special
self.fifo.pop()
# return the originally popped result
return result
def test_embedded():
of = output_fifo()
f2 = output_fifo()
f3 = output_fifo()
of.push ('one')
of.push_embedded (f2)
f2.push ('two')
f3.push ('three')
f3.push ('four')
f2.push_embedded (f3)
f3.push_eof()
f2.push ('five')
f2.push_eof()
of.push ('six')
of.push ('seven')
while 1:
print of.pop()
of = output_fifo()
f2 = output_fifo()
f3 = output_fifo()
of.push ('one')
of.push_embedded (f2)
f2.push ('two')
f3.push ('three')
f3.push ('four')
f2.push_embedded (f3)
f3.push_eof()
f2.push ('five')
f2.push_eof()
of.push ('six')
of.push ('seven')
while 1:
print of.pop()
This diff is collapsed.
This diff is collapsed.
......@@ -3,73 +3,73 @@
import string
import regex
RCS_ID = '$Id: http_bobo.py,v 1.3 2001/04/26 00:07:52 andreas Exp $'
RCS_ID = '$Id: http_bobo.py,v 1.4 2001/05/01 11:44:48 andreas Exp $'
VERSION_STRING = string.split(RCS_ID)[2]
class bobo_extension:
hits = 0
SERVER_IDENT = 'Bobo Extension (V%s)' % VERSION_STRING
def __init__ (self, regexp):
self.regexp = regex.compile (regexp)
def __repr__ (self):
return '<Bobo Extension <b>(%d hits)</b> at %x>' % (
self.hits,
id (self)
)
def match (self, path_part):
if self.regexp.match (path_part) == len(path_part):
return 1
else:
return 0
def status (self):
return mstatus.lines_producer ([
'<h2>%s</h2>' %self.SERVER_IDENT,
'<br><b>Total Hits:</b> %d' % self.hits,
])
def handle_request (self, channel):
self.hits = self.hits + 1
[path, params, query, fragment] = channel.uri
if query:
# cgi_publisher_module doesn't want the leading '?'
query = query[1:]
env = {}
env['REQUEST_METHOD'] = method
env['SERVER_PORT'] = channel.server.port
env['SERVER_NAME'] = channel.server.server_name
env['SCRIPT_NAME'] = module_name
env['QUERY_STRING'] = query
env['PATH_INFO'] = string.join (path_parts[1:],'/')
# this should really be done with with a real producer. just
# have to make sure it can handle all of the file object api.
sin = StringIO.StringIO('')
sout = StringIO.StringIO()
serr = StringIO.StringIO()
cgi_module_publisher.publish_module (
module_name,
stdin=sin,
stdout=sout,
stderr=serr,
environ=env,
debug=1
)
channel.push (
channel.response (200) + \
channel.generated_content_header (path)
)
self.push (sout.getvalue())
self.push (serr.getvalue())
self.close_when_done()
hits = 0
SERVER_IDENT = 'Bobo Extension (V%s)' % VERSION_STRING
def __init__ (self, regexp):
self.regexp = regex.compile (regexp)
def __repr__ (self):
return '<Bobo Extension <b>(%d hits)</b> at %x>' % (
self.hits,
id (self)
)
def match (self, path_part):
if self.regexp.match (path_part) == len(path_part):
return 1
else:
return 0
def status (self):
return mstatus.lines_producer ([
'<h2>%s</h2>' %self.SERVER_IDENT,
'<br><b>Total Hits:</b> %d' % self.hits,
])
def handle_request (self, channel):
self.hits = self.hits + 1
[path, params, query, fragment] = channel.uri
if query:
# cgi_publisher_module doesn't want the leading '?'
query = query[1:]
env = {}
env['REQUEST_METHOD'] = method
env['SERVER_PORT'] = channel.server.port
env['SERVER_NAME'] = channel.server.server_name
env['SCRIPT_NAME'] = module_name
env['QUERY_STRING'] = query
env['PATH_INFO'] = string.join (path_parts[1:],'/')
# this should really be done with with a real producer. just
# have to make sure it can handle all of the file object api.
sin = StringIO.StringIO('')
sout = StringIO.StringIO()
serr = StringIO.StringIO()
cgi_module_publisher.publish_module (
module_name,
stdin=sin,
stdout=sout,
stderr=serr,
environ=env,
debug=1
)
channel.push (
channel.response (200) + \
channel.generated_content_header (path)
)
self.push (sout.getvalue())
self.push (serr.getvalue())
self.close_when_done()
......@@ -5,14 +5,14 @@ import string
import time
def concat (*args):
return ''.join (args)
return ''.join (args)
def join (seq, field=' '):
return field.join (seq)
return field.join (seq)
def group (s):
return '(' + s + ')'
return '(' + s + ')'
short_days = ['sun','mon','tue','wed','thu','fri','sat']
long_days = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday']
......@@ -21,17 +21,17 @@ long_day_reg = group (join (long_days, '|'))
daymap = {}
for i in range(7):
daymap[short_days[i]] = i
daymap[long_days[i]] = i
daymap[short_days[i]] = i
daymap[long_days[i]] = i
hms_reg = join (3 * [group('[0-9][0-9]')], ':')
months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
monmap = {}
for i in range(12):
monmap[months[i]] = i+1
monmap[months[i]] = i+1
months_reg = group (join (months, '|'))
# From draft-ietf-http-v11-spec-07.txt/3.3.1
......@@ -41,86 +41,86 @@ months_reg = group (join (months, '|'))
# rfc822 format
rfc822_date = join (
[concat (short_day_reg,','), # day
group('[0-9][0-9]?'), # date
months_reg, # month
group('[0-9]+'), # year
hms_reg, # hour minute second
'gmt'
],
' '
)
[concat (short_day_reg,','), # day
group('[0-9][0-9]?'), # date
months_reg, # month
group('[0-9]+'), # year
hms_reg, # hour minute second
'gmt'
],
' '
)
rfc822_reg = re.compile (rfc822_date)
def unpack_rfc822 (m):
g = m.group
a = string.atoi
return (
a(g(4)), # year
monmap[g(3)], # month
a(g(2)), # day
a(g(5)), # hour
a(g(6)), # minute
a(g(7)), # second
0,
0,
0
)
# rfc850 format
g = m.group
a = string.atoi
return (
a(g(4)), # year
monmap[g(3)], # month
a(g(2)), # day
a(g(5)), # hour
a(g(6)), # minute
a(g(7)), # second
0,
0,
0
)
# rfc850 format
rfc850_date = join (
[concat (long_day_reg,','),
join (
[group ('[0-9][0-9]?'),
months_reg,
group ('[0-9]+')
],
'-'
),
hms_reg,
'gmt'
],
' '
)
[concat (long_day_reg,','),
join (
[group ('[0-9][0-9]?'),
months_reg,
group ('[0-9]+')
],
'-'
),
hms_reg,
'gmt'
],
' '
)
rfc850_reg = re.compile (rfc850_date)
# they actually unpack the same way
def unpack_rfc850 (m):
g = m.group
a = string.atoi
return (
a(g(4)), # year
monmap[g(3)], # month
a(g(2)), # day
a(g(5)), # hour
a(g(6)), # minute
a(g(7)), # second
0,
0,
0
)
# parsdate.parsedate - ~700/sec.
# parse_http_date - ~1333/sec.
g = m.group
a = string.atoi
return (
a(g(4)), # year
monmap[g(3)], # month
a(g(2)), # day
a(g(5)), # hour
a(g(6)), # minute
a(g(7)), # second
0,
0,
0
)
# parsdate.parsedate - ~700/sec.
# parse_http_date - ~1333/sec.
def build_http_date (when):
return time.strftime ('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(when))
return time.strftime ('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(when))
def parse_http_date (d):
d = string.lower (d)
tz = time.timezone
m = rfc850_reg.match (d)
if m and m.end() == len(d):
retval = int (time.mktime (unpack_rfc850(m)) - tz)
else:
m = rfc822_reg.match (d)
if m and m.end() == len(d):
retval = int (time.mktime (unpack_rfc822(m)) - tz)
else:
return 0
# Thanks to Craig Silverstein <csilvers@google.com> for pointing
# out the DST discrepancy
if time.daylight and time.localtime(retval)[-1] == 1: # DST correction
retval = retval + (tz - time.altzone)
return retval
d = string.lower (d)
tz = time.timezone
m = rfc850_reg.match (d)
if m and m.end() == len(d):
retval = int (time.mktime (unpack_rfc850(m)) - tz)
else:
m = rfc822_reg.match (d)
if m and m.end() == len(d):
retval = int (time.mktime (unpack_rfc822(m)) - tz)
else:
return 0
# Thanks to Craig Silverstein <csilvers@google.com> for pointing
# out the DST discrepancy
if time.daylight and time.localtime(retval)[-1] == 1: # DST correction
retval = retval + (tz - time.altzone)
return retval
This diff is collapsed.
This diff is collapsed.
......@@ -98,80 +98,80 @@ LOG_LOCAL6 = 22 # reserved for local use
LOG_LOCAL7 = 23 # reserved for local use
priority_names = {
"alert": LOG_ALERT,
"crit": LOG_CRIT,
"debug": LOG_DEBUG,
"emerg": LOG_EMERG,
"err": LOG_ERR,
"error": LOG_ERR, # DEPRECATED
"info": LOG_INFO,
"notice": LOG_NOTICE,
"panic": LOG_EMERG, # DEPRECATED
"warn": LOG_WARNING, # DEPRECATED
"warning": LOG_WARNING,
}
"alert": LOG_ALERT,
"crit": LOG_CRIT,
"debug": LOG_DEBUG,
"emerg": LOG_EMERG,
"err": LOG_ERR,
"error": LOG_ERR, # DEPRECATED
"info": LOG_INFO,
"notice": LOG_NOTICE,
"panic": LOG_EMERG, # DEPRECATED
"warn": LOG_WARNING, # DEPRECATED
"warning": LOG_WARNING,
}
facility_names = {
"auth": LOG_AUTH,
"authpriv": LOG_AUTHPRIV,
"cron": LOG_CRON,
"daemon": LOG_DAEMON,
"kern": LOG_KERN,
"lpr": LOG_LPR,
"mail": LOG_MAIL,
"news": LOG_NEWS,
"security": LOG_AUTH, # DEPRECATED
"syslog": LOG_SYSLOG,
"user": LOG_USER,
"uucp": LOG_UUCP,
"local0": LOG_LOCAL0,
"local1": LOG_LOCAL1,
"local2": LOG_LOCAL2,
"local3": LOG_LOCAL3,
"local4": LOG_LOCAL4,
"local5": LOG_LOCAL5,
"local6": LOG_LOCAL6,
"local7": LOG_LOCAL7,
}
"auth": LOG_AUTH,
"authpriv": LOG_AUTHPRIV,
"cron": LOG_CRON,
"daemon": LOG_DAEMON,
"kern": LOG_KERN,
"lpr": LOG_LPR,
"mail": LOG_MAIL,
"news": LOG_NEWS,
"security": LOG_AUTH, # DEPRECATED
"syslog": LOG_SYSLOG,
"user": LOG_USER,
"uucp": LOG_UUCP,
"local0": LOG_LOCAL0,
"local1": LOG_LOCAL1,
"local2": LOG_LOCAL2,
"local3": LOG_LOCAL3,
"local4": LOG_LOCAL4,
"local5": LOG_LOCAL5,
"local6": LOG_LOCAL6,
"local7": LOG_LOCAL7,
}
import socket
class syslog_client:
def __init__ (self, address='/dev/log'):
self.address = address
if type (address) == type(''):
self.socket = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.connect (address)
self.unix = 1
else:
self.socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
self.unix = 0
# curious: when talking to the unix-domain '/dev/log' socket, a
# zero-terminator seems to be required. this string is placed
# into a class variable so that it can be overridden if
# necessary.
log_format_string = '<%d>%s\000'
def log (self, message, facility=LOG_USER, priority=LOG_INFO):
message = self.log_format_string % (
self.encode_priority (facility, priority),
message
)
if self.unix:
self.socket.send (message)
else:
self.socket.sendto (message, self.address)
def encode_priority (self, facility, priority):
if type(facility) == type(''):
facility = facility_names[facility]
if type(priority) == type(''):
priority = priority_names[priority]
return (facility<<3) | priority
def close (self):
if self.unix:
self.socket.close()
def __init__ (self, address='/dev/log'):
self.address = address
if type (address) == type(''):
self.socket = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.connect (address)
self.unix = 1
else:
self.socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
self.unix = 0
# curious: when talking to the unix-domain '/dev/log' socket, a
# zero-terminator seems to be required. this string is placed
# into a class variable so that it can be overridden if
# necessary.
log_format_string = '<%d>%s\000'
def log (self, message, facility=LOG_USER, priority=LOG_INFO):
message = self.log_format_string % (
self.encode_priority (facility, priority),
message
)
if self.unix:
self.socket.send (message)
else:
self.socket.sendto (message, self.address)
def encode_priority (self, facility, priority):
if type(facility) == type(''):
facility = facility_names[facility]
if type(priority) == type(''):
priority = priority_names[priority]
return (facility<<3) | priority
def close (self):
if self.unix:
self.socket.close()
This diff is collapsed.
......@@ -7,60 +7,60 @@ import asyncore
import asynchat
class recorder_channel (asyncore.dispatcher):
def __init__ (self, sock, addr):
asyncore.dispatcher.__init__ (self, sock)
self.fd = open ('%s:%d' % addr, 'wb')
def handle_read (self):
data = self.recv (1024)
if not data:
self.fd.close()
self.close()
else:
self.fd.write (data)
self.fd.flush()
def __init__ (self, sock, addr):
asyncore.dispatcher.__init__ (self, sock)
self.fd = open ('%s:%d' % addr, 'wb')
def handle_read (self):
data = self.recv (1024)
if not data:
self.fd.close()
self.close()
else:
self.fd.write (data)
self.fd.flush()
class recorder_server (asyncore.dispatcher):
SERVER_IDENT = 'Recorder'
def __init__ (self, port=8989):
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.bind (('', port))
print '%s started on port %d' % (self.SERVER_IDENT, port)
self.listen (5)
def handle_accept (self):
conn, addr = self.accept()
print 'incoming connection',addr
recorder_channel (conn, addr)
# force a clean shutdown
SERVER_IDENT = 'Recorder'
def __init__ (self, port=8989):
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.bind (('', port))
print '%s started on port %d' % (self.SERVER_IDENT, port)
self.listen (5)
def handle_accept (self):
conn, addr = self.accept()
print 'incoming connection',addr
recorder_channel (conn, addr)
# force a clean shutdown
def shutdown():
sm = asyncore.socket_map
asyncore.socket_map = {}
for s in sm.values():
try:
s.close()
except:
pass
print 'Done.'
sm = asyncore.socket_map
asyncore.socket_map = {}
for s in sm.values():
try:
s.close()
except:
pass
print 'Done.'
if __name__ == '__main__':
import string
import sys
if len(sys.argv) > 1:
port = string.atoi (sys.argv[1])
else:
port = 8989
s = recorder_server (port)
try:
asyncore.loop()
except KeyboardInterrupt:
import sys
import tb
print sys.exc_type, sys.exc_value
tb.printtb (sys.exc_traceback)
print 'Shutting down due to unhandled exception...'
shutdown()
import string
import sys
if len(sys.argv) > 1:
port = string.atoi (sys.argv[1])
else:
port = 8989
s = recorder_server (port)
try:
asyncore.loop()
except KeyboardInterrupt:
import sys
import tb
print sys.exc_type, sys.exc_value
tb.printtb (sys.exc_traceback)
print 'Shutting down due to unhandled exception...'
shutdown()
......@@ -26,39 +26,39 @@ SO_SYNCHRONOUS_ALERT = 0x10
SO_SYNCHRONOUS_NONALERT = 0x20
def set_sync_option (on=1):
result = wsock32.getsockopt (
INVALID_SOCKET,
SOCKET_SOL,
SO_OPENTYPE,
option,
option_len
)
if result:
raise SystemError, "getsockopt: (%d)" % (
wsock32.WSAGetLastError()
)
else:
old = struct.unpack ('l', option.read())[0]
if on:
new = old | SO_SYNCHRONOUS_ALERT
else:
new = old & (~SO_SYNCHRONOUS_ALERT)
option.write (struct.pack ('l', new))
result = wsock32.setsockopt (
INVALID_SOCKET,
SOCKET_SOL,
SO_OPENTYPE,
option,
option_len
)
if result:
raise SystemError, "getsockopt: (%d)" % (
wsock32.WSAGetLastError()
)
return old
result = wsock32.getsockopt (
INVALID_SOCKET,
SOCKET_SOL,
SO_OPENTYPE,
option,
option_len
)
if result:
raise SystemError, "getsockopt: (%d)" % (
wsock32.WSAGetLastError()
)
else:
old = struct.unpack ('l', option.read())[0]
if on:
new = old | SO_SYNCHRONOUS_ALERT
else:
new = old & (~SO_SYNCHRONOUS_ALERT)
option.write (struct.pack ('l', new))
result = wsock32.setsockopt (
INVALID_SOCKET,
SOCKET_SOL,
SO_OPENTYPE,
option,
option_len
)
if result:
raise SystemError, "getsockopt: (%d)" % (
wsock32.WSAGetLastError()
)
return old
def sync_on():
return set_sync_option (1)
return set_sync_option (1)
def sync_off():
return set_sync_option (0)
return set_sync_option (0)
This diff is collapsed.
......@@ -14,113 +14,113 @@ import md5
import time
class stdin_channel (asyncore.file_dispatcher):
def handle_read (self):
data = self.recv(512)
if not data:
print '\nclosed.'
self.sock_channel.close()
try:
self.close()
except:
pass
data = regsub.gsub ('\n', '\r\n', data)
self.sock_channel.push (data)
def writable (self):
return 0
def log (self, *ignore):
pass
def handle_read (self):
data = self.recv(512)
if not data:
print '\nclosed.'
self.sock_channel.close()
try:
self.close()
except:
pass
data = regsub.gsub ('\n', '\r\n', data)
self.sock_channel.push (data)
def writable (self):
return 0
def log (self, *ignore):
pass
class monitor_client (asynchat.async_chat):
def __init__ (self, password, addr=('',8023), socket_type=socket.AF_INET):
asynchat.async_chat.__init__ (self)
self.create_socket (socket_type, socket.SOCK_STREAM)
self.terminator = '\r\n'
self.connect (addr)
self.sent_auth = 0
self.timestamp = ''
self.password = password
def collect_incoming_data (self, data):
if not self.sent_auth:
self.timestamp = self.timestamp + data
else:
sys.stdout.write (data)
sys.stdout.flush()
def found_terminator (self):
if not self.sent_auth:
self.push (hex_digest (self.timestamp + self.password) + '\r\n')
self.sent_auth = 1
else:
print
def handle_close (self):
# close all the channels, which will make the standard main
# loop exit.
map (lambda x: x.close(), asyncore.socket_map.values())
def log (self, *ignore):
pass
def __init__ (self, password, addr=('',8023), socket_type=socket.AF_INET):
asynchat.async_chat.__init__ (self)
self.create_socket (socket_type, socket.SOCK_STREAM)
self.terminator = '\r\n'
self.connect (addr)
self.sent_auth = 0
self.timestamp = ''
self.password = password
def collect_incoming_data (self, data):
if not self.sent_auth:
self.timestamp = self.timestamp + data
else:
sys.stdout.write (data)
sys.stdout.flush()
def found_terminator (self):
if not self.sent_auth:
self.push (hex_digest (self.timestamp + self.password) + '\r\n')
self.sent_auth = 1
else:
print
def handle_close (self):
# close all the channels, which will make the standard main
# loop exit.
map (lambda x: x.close(), asyncore.socket_map.values())
def log (self, *ignore):
pass
class encrypted_monitor_client (monitor_client):
"Wrap push() and recv() with a stream cipher"
def init_cipher (self, cipher, key):
self.outgoing = cipher.new (key)
self.incoming = cipher.new (key)
def push (self, data):
# push the encrypted data instead
return monitor_client.push (self, self.outgoing.encrypt (data))
def recv (self, block_size):
data = monitor_client.recv (self, block_size)
if data:
return self.incoming.decrypt (data)
else:
return data
"Wrap push() and recv() with a stream cipher"
def init_cipher (self, cipher, key):
self.outgoing = cipher.new (key)
self.incoming = cipher.new (key)
def push (self, data):
# push the encrypted data instead
return monitor_client.push (self, self.outgoing.encrypt (data))
def recv (self, block_size):
data = monitor_client.recv (self, block_size)
if data:
return self.incoming.decrypt (data)
else:
return data
def hex_digest (s):
m = md5.md5()
m.update (s)
return string.join (
map (lambda x: hex (ord (x))[2:], map (None, m.digest())),
'',
)
m = md5.md5()
m.update (s)
return string.join (
map (lambda x: hex (ord (x))[2:], map (None, m.digest())),
'',
)
if __name__ == '__main__':
if len(sys.argv) == 1:
print 'Usage: %s host port' % sys.argv[0]
sys.exit(0)
if ('-e' in sys.argv):
encrypt = 1
sys.argv.remove ('-e')
else:
encrypt = 0
sys.stderr.write ('Enter Password: ')
sys.stderr.flush()
import os
try:
os.system ('stty -echo')
p = raw_input()
print
finally:
os.system ('stty echo')
stdin = stdin_channel (0)
if len(sys.argv) > 1:
if encrypt:
client = encrypted_monitor_client (p, (sys.argv[1], string.atoi (sys.argv[2])))
import sapphire
client.init_cipher (sapphire, p)
else:
client = monitor_client (p, (sys.argv[1], string.atoi (sys.argv[2])))
else:
# default to local host, 'standard' port
client = monitor_client (p)
stdin.sock_channel = client
asyncore.loop()
if len(sys.argv) == 1:
print 'Usage: %s host port' % sys.argv[0]
sys.exit(0)
if ('-e' in sys.argv):
encrypt = 1
sys.argv.remove ('-e')
else:
encrypt = 0
sys.stderr.write ('Enter Password: ')
sys.stderr.flush()
import os
try:
os.system ('stty -echo')
p = raw_input()
print
finally:
os.system ('stty echo')
stdin = stdin_channel (0)
if len(sys.argv) > 1:
if encrypt:
client = encrypted_monitor_client (p, (sys.argv[1], string.atoi (sys.argv[2])))
import sapphire
client.init_cipher (sapphire, p)
else:
client = monitor_client (p, (sys.argv[1], string.atoi (sys.argv[2])))
else:
# default to local host, 'standard' port
client = monitor_client (p)
stdin.sock_channel = client
asyncore.loop()
......@@ -13,41 +13,41 @@ import thread
import md5
def hex_digest (s):
m = md5.md5()
m.update (s)
return string.join (
map (lambda x: hex (ord (x))[2:], map (None, m.digest())),
'',
)
m = md5.md5()
m.update (s)
return string.join (
map (lambda x: hex (ord (x))[2:], map (None, m.digest())),
'',
)
def reader (lock, sock, password):
# first grab the timestamp
ts = sock.recv (1024)[:-2]
sock.send (hex_digest (ts+password) + '\r\n')
while 1:
d = sock.recv (1024)
if not d:
lock.release()
print 'Connection closed. Hit <return> to exit'
thread.exit()
sys.stdout.write (d)
sys.stdout.flush()
# first grab the timestamp
ts = sock.recv (1024)[:-2]
sock.send (hex_digest (ts+password) + '\r\n')
while 1:
d = sock.recv (1024)
if not d:
lock.release()
print 'Connection closed. Hit <return> to exit'
thread.exit()
sys.stdout.write (d)
sys.stdout.flush()
def writer (lock, sock, barrel="just kidding"):
while lock.locked():
sock.send (
sys.stdin.readline()[:-1] + '\r\n'
)
while lock.locked():
sock.send (
sys.stdin.readline()[:-1] + '\r\n'
)
if __name__ == '__main__':
if len(sys.argv) == 1:
print 'Usage: %s host port'
sys.exit(0)
print 'Enter Password: ',
p = raw_input()
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect ((sys.argv[1], string.atoi(sys.argv[2])))
l = thread.allocate_lock()
l.acquire()
thread.start_new_thread (reader, (l, s, p))
writer (l, s)
if len(sys.argv) == 1:
print 'Usage: %s host port'
sys.exit(0)
print 'Enter Password: ',
p = raw_input()
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect ((sys.argv[1], string.atoi(sys.argv[2])))
l = thread.allocate_lock()
l.acquire()
thread.start_new_thread (reader, (l, s, p))
writer (l, s)
This diff is collapsed.
......@@ -5,7 +5,7 @@
# All Rights Reserved.
#
RCS_ID = '$Id: put_handler.py,v 1.2 2001/04/25 19:07:33 andreas Exp $'
RCS_ID = '$Id: put_handler.py,v 1.3 2001/05/01 11:44:48 andreas Exp $'
import re
import string
......@@ -17,99 +17,99 @@ get_header = default_handler.get_header
last_request = None
class put_handler:
def __init__ (self, filesystem, uri_regex):
self.filesystem = filesystem
if type (uri_regex) == type(''):
self.uri_regex = re.compile (uri_regex)
else:
self.uri_regex = uri_regex
def match (self, request):
uri = request.uri
if request.command == 'put':
m = self.uri_regex.match (uri)
if m and m.end() == len(uri):
return 1
return 0
def handle_request (self, request):
path, params, query, fragment = request.split_uri()
# strip off leading slashes
while path and path[0] == '/':
path = path[1:]
if '%' in path:
path = unquote (path)
# make sure there's a content-length header
cl = get_header (CONTENT_LENGTH, request.header)
if not cl:
request.error (411)
return
else:
cl = string.atoi (cl)
# don't let the try to overwrite a directory
if self.filesystem.isdir (path):
request.error (405)
return
is_update = self.filesystem.isfile (path)
try:
output_file = self.filesystem.open (path, 'wb')
except:
request.error (405)
return
request.collector = put_collector (output_file, cl, request, is_update)
# no terminator while receiving PUT data
request.channel.set_terminator (None)
# don't respond yet, wait until we've received the data...
def __init__ (self, filesystem, uri_regex):
self.filesystem = filesystem
if type (uri_regex) == type(''):
self.uri_regex = re.compile (uri_regex)
else:
self.uri_regex = uri_regex
def match (self, request):
uri = request.uri
if request.command == 'put':
m = self.uri_regex.match (uri)
if m and m.end() == len(uri):
return 1
return 0
def handle_request (self, request):
path, params, query, fragment = request.split_uri()
# strip off leading slashes
while path and path[0] == '/':
path = path[1:]
if '%' in path:
path = unquote (path)
# make sure there's a content-length header
cl = get_header (CONTENT_LENGTH, request.header)
if not cl:
request.error (411)
return
else:
cl = string.atoi (cl)
# don't let the try to overwrite a directory
if self.filesystem.isdir (path):
request.error (405)
return
is_update = self.filesystem.isfile (path)
try:
output_file = self.filesystem.open (path, 'wb')
except:
request.error (405)
return
request.collector = put_collector (output_file, cl, request, is_update)
# no terminator while receiving PUT data
request.channel.set_terminator (None)
# don't respond yet, wait until we've received the data...
class put_collector:
def __init__ (self, file, length, request, is_update):
self.file = file
self.length = length
self.request = request
self.is_update = is_update
self.bytes_in = 0
def collect_incoming_data (self, data):
ld = len(data)
bi = self.bytes_in
if (bi + ld) >= self.length:
# last bit of data
chunk = self.length - bi
self.file.write (data[:chunk])
self.file.close()
if chunk != ld:
print 'orphaned %d bytes: <%s>' % (ld - chunk, repr(data[chunk:]))
# do some housekeeping
r = self.request
ch = r.channel
ch.current_request = None
# set the terminator back to the default
ch.set_terminator ('\r\n\r\n')
if self.is_update:
r.reply_code = 204 # No content
r.done()
else:
r.reply_now (201) # Created
# avoid circular reference
del self.request
else:
self.file.write (data)
self.bytes_in = self.bytes_in + ld
def found_terminator (self):
# shouldn't be called
pass
def __init__ (self, file, length, request, is_update):
self.file = file
self.length = length
self.request = request
self.is_update = is_update
self.bytes_in = 0
def collect_incoming_data (self, data):
ld = len(data)
bi = self.bytes_in
if (bi + ld) >= self.length:
# last bit of data
chunk = self.length - bi
self.file.write (data[:chunk])
self.file.close()
if chunk != ld:
print 'orphaned %d bytes: <%s>' % (ld - chunk, repr(data[chunk:]))
# do some housekeeping
r = self.request
ch = r.channel
ch.current_request = None
# set the terminator back to the default
ch.set_terminator ('\r\n\r\n')
if self.is_update:
r.reply_code = 204 # No content
r.done()
else:
r.reply_now (201) # Created
# avoid circular reference
del self.request
else:
self.file.write (data)
self.bytes_in = self.bytes_in + ld
def found_terminator (self):
# shouldn't be called
pass
CONTENT_LENGTH = re.compile ('Content-Length: ([0-9]+)', re.IGNORECASE)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -14,9 +14,9 @@ form = """<html><form method=POST action="form.mpy">
</form></html>"""
if data:
import cgi
info = '<h2>CGI variables:</h2>%s\r\n' % repr(cgi.parse_qs(data))
import cgi
info = '<h2>CGI variables:</h2>%s\r\n' % repr(cgi.parse_qs(data))
else:
info = ''
info = ''
print form % info
......@@ -27,17 +27,17 @@ count = 0
import string
def html_clean (s):
s = string.replace (s, '<', '&lt;')
s = string.replace (s, '>', '&gt;')
return s
s = string.replace (s, '<', '&lt;')
s = string.replace (s, '>', '&gt;')
return s
def main (request):
global count
count = count + 1
print '<html><h1>Hit Count=%d</h1>' % count
print '<h3>Request Attributes:</h3><ul>'
print '<li>command : %s' % request.command
print '<li>uri: %s' % html_clean (request.uri)
print '<li>channel: %s' % html_clean (repr (request.channel))
print '</ul>'
print '</html>'
global count
count = count + 1
print '<html><h1>Hit Count=%d</h1>' % count
print '<h3>Request Attributes:</h3><ul>'
print '<li>command : %s' % request.command
print '<li>uri: %s' % html_clean (request.uri)
print '<li>channel: %s' % html_clean (repr (request.channel))
print '</ul>'
print '</html>'
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -4,10 +4,10 @@ import pprint
def main (env, stdin, stdout):
stdout.write (
'<html><body><h1>Test CGI Module</h1>\r\n'
'<br>The Environment:<pre>\r\n'
)
pprint.pprint (env, stdout)
stdout.write ('</pre></body></html>\r\n')
stdout.write (
'<html><body><h1>Test CGI Module</h1>\r\n'
'<br>The Environment:<pre>\r\n'
)
pprint.pprint (env, stdout)
stdout.write ('</pre></body></html>\r\n')
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment