#!/usr/local/bin/python """gives fake apache dir interface""" base_url = "apache_dir.cgi?" head = """
Name Last modified Size Description
""" tail = """""" def gen_link(str,pn): spacer = '' newstr = str if len(newstr) > 20: newstr = newstr[:20] + '..>' if len(newstr) <= 20: spacer += " " * (23 - len(newstr)) return '' + newstr + ' ' + spacer def gen_time(secs): import time return time.strftime("%d-%b-%Y %R", time.localtime(secs)) def ls(path): import os rv = [] if os.path.isdir(path): for fn in os.listdir(path): filename = os.path.join(path,fn) rv.append((filename,os.path.getmtime(filename),os.path.getsize(filename))) return rv ICNS = {'text':"/icons/text.gif", 'image':"/icons/image2.gif", 'audio':'/icons/sound2.gif', 'video':'/icons/movie.gif'} def icon_path(fn): t = guess_type(fn) t = t[:t.find('/')] if ICNS.has_key(t): return ICNS[t] return '/icons/blank.gif' def index(path): print "Content-type: text/html\n\n", print head % {'path':path} for fn,mt,sz in ls(path): pn = fn[fn.rfind('/')+1:] pn = base_url + pn fn = fn[fn.rfind('/')+1:] icnpath = icon_path(fn) print """%s %s %s""" % (icnpath, gen_link(fn,pn),gen_time(mt),sz) print tail def guess_type(path): import posixpath,mimetypes extensions_map = mimetypes.types_map base, ext = posixpath.splitext(path) ext = ext.lower() if ext in extensions_map: return extensions_map[ext] else: return 'text/html' def get_file(path): import sys,shutil,os,stat ## check if readable by all st = os.stat(path) mode = st[stat.ST_MODE] if int(oct(mode & 0777)[-1]) >= 4: sys.stdout.write("Content-type:" + guess_type(path) + '\n\n') shutil.copyfileobj(open(path), sys.stdout) sys.stdout.flush() else: print "Content-type: text/html\n\n" print "
" print "no permission to read",path print "" if __name__ == '__main__': path = "/csua/tmp" import sys,os urlpath = sys.argv[0] cginame = urlpath[urlpath.rfind('/')+1:] relpath = '' if len(sys.argv) > 1: relpath = sys.argv[1] combined_path = os.path.join(path,relpath) ## remove sneaky parent path .. combined_path = combined_path.replace('..','') # print os.path.abspath(os.curdir) if os.path.isdir(combined_path): index(combined_path) elif os.path.exists(combined_path): get_file(combined_path) else: print "Content-type: text/html\n\n" print "Not found:" print combined_path print urlpath print cginame print relpath print guess_type(combined_path) print ""