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