/usr/lib/ezmlm-browse/main.py is in ezmlm-browse 0.10-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | import cgitb
cgitb.enable()
import cgi
import email
import imp
import os
import re
import sys
import time
import types
import Cookie
import ezmlm
from globals import *
from globalfns import *
import context
import config
ctxt = None
form = None
###############################################################################
# Fixup configuration values
def fixup_config():
for name in config.archives.keys():
l = config.archives[name]
if l.has_key(LISTDIR):
l[LISTDIR] = os.path.join(config.basedir, l[LISTDIR])
else:
l[LISTDIR] = os.path.join(config.basedir, name)
if not l.has_key(LISTEMAIL):
l[LISTEMAIL] = '%s@%s' % (name, config.basehost)
if not l.has_key(LISTSUB):
l[LISTSUB] = '%s-subscribe@%s' % (name, config.basehost)
###############################################################################
# Context functions
def iif(cond, truestr, falsestr=''):
global ctxt
if cond:
return truestr % ctxt
return falsestr % ctxt
def defined(name):
global ctxt
return ctxt.has_key(name)
def escape(str, escapes):
for (needle, replacement) in escapes:
str = str.replace(needle, replacement)
return str
_html_escapes = ( ('&', '&'),
('<', '<'),
('>', '>'),
('"', '"') )
def escape_html(str): return escape(str, _html_escapes)
_url_escapes = ( ('%', '%25'),
(' ', '%20'),
('&', '%26'),
('?', '%3f'),
(':', '%3a'),
(';', '%3b'),
('+', '%2b') )
def escape_url(str): return escape(str, _url_escapes)
def nl2br(str): return str.replace('\n', '<br />')
rx_url = re.compile(r'([^\s\"]+://[^\s\"]+)')
def markup_urls(str): return rx_url.sub(r'<a href="\1">\1</a>', str)
#rx_addr = re.compile(r'<[^>@]+@[^>]+>')
rx_addr = re.compile(r'\S+@\S+\.\S+')
def mask_email(str):
return rx_addr.sub('####@####.####', str)
def wordwrap(str):
try:
width = int(ctxt.get(WRAPWIDTH, 0))
except:
return str
if not width:
return str
out = []
for line in str.split('\n'):
while len(line) > width:
# Try to break the line on the first space before the width.
space = line.rfind(' ', 0, width)
if space == -1:
# None found, now fall back to the first space on the line.
space = line.find(' ')
if space == -1:
# No spaces found, no word-wrapping can be done.
break
# If the remainder of the line is empty, don't do anything.
nextline = line[space+1:].lstrip()
if not nextline:
break
out.append(line[:space])
line = nextline
out.append(line)
return '\n'.join(out)
def relurl(**kw):
# Put certain keywords in a fixed order
pre = []
for key in (LIST, COMMAND):
try:
pre.append((key,kw[key]))
del kw[key]
except KeyError:
pass
kw = kw.items()
kw.sort()
kw = pre + kw
kw = map(lambda val:"%s=%s"%(val[0],escape_url(str(val[1]))), kw)
return '?%s' % ('&'.join(kw))
def absurl(**kw):
global ctxt
return ''.join(('http://',
ctxt['SERVER_NAME'],
ctxt['SCRIPT_NAME'],
apply(relurl, (), kw)))
def relink(text, classname, **kw):
return '<a class="%s" href="%s">%s</a>' % (
classname, apply(relurl, (), kw), text)
def cmdlink(text, classname, command, **kw):
global ctxt
kw[COMMAND] = command
kw[LIST] = ctxt[LIST]
return apply(relink, (text, classname), kw)
def optlink(text, classname, dolink, command, **kw):
if dolink:
return apply(cmdlink, (text, classname, command), kw)
else:
return '<span class="%s">%s</span>' % (classname, text)
def pagelink(text, classname, index):
global ctxt
index = max(1, min(ctxt[PAGES], index))
if index == ctxt[PAGE]:
return '<span class="%s">%s</span>' % (classname, text)
kw = form.copy()
kw[PAGE] = index
return apply(relink, (text, classname), kw)
def msgsubjlink(msg, **kw):
global ctxt
if type(msg) is types.IntType:
kw[MSGNUM] = msg
msg = ctxt[EZMLM].index[msg]
else:
kw[MSGNUM] = msg[MSGNUM]
return apply(cmdlink, (msg[SUBJECT], 'subject', 'showmsg'), kw)
def msgauthlink(msg, **kw):
global ctxt
if type(msg) is types.IntType:
msg = ctxt[EZMLM].index[msg]
kw[AUTHORID] = msg[AUTHORID]
return apply(cmdlink, (msg[AUTHOR], 'author', 'author'), kw)
def threadlink(text, classname, index):
global ctxt
index = max(1, min(ctxt['threadlen'], index))
if index == ctxt[PAGE]:
return '<span class="%s">%s</span>' % (classname, text)
kw = form.copy()
kw[MSGNUM] = ctxt[MESSAGES][index-1][MSGNUM]
return apply(relink, (text, classname), kw)
def selectlist(name, list, value=None, options=''):
s = ['<select name=%s %s>' % (name, options)]
for option in list:
selected = ''
try:
(ovalue,oname) = option
if ovalue == value:
selected = ' selected'
s.append('<option value="%s"%s>%s' % (
escape_html(ovalue), selected, escape_html(oname) ))
except:
if option == value:
selected = ' selected'
s.append('<option%s>%s' % ( selected, escape_html(option) ))
s.append('</select>')
return '\n'.join(s)
def monthname(number):
if number >= 100000:
number %= 100
return ezmlm.month_names[number]
def isogmtime(ts):
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(float(ts)))
def rfc822gmtime(ts):
return time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(float(ts)))
def update_global_context():
context.global_context.update({
'absurl': absurl,
'cmdlink': cmdlink,
'config': config,
'defined': defined,
'format_timestamp': lambda msg:format_timestamp(ctxt, msg),
'iif': iif,
'isogmtime': isogmtime,
'html': escape_html,
'markup_urls': markup_urls,
'mask_email': mask_email,
'wordwrap': wordwrap,
'msgauthlink': msgauthlink,
'msgsubjlink': msgsubjlink,
'monthname': monthname,
'nl2br': nl2br,
'optlink': optlink,
'pagelink': pagelink,
'relink': relink,
'relurl': relurl,
'rfc822gmtime': rfc822gmtime,
'selectlist': selectlist,
'threadlink': threadlink,
'url': escape_url,
})
###############################################################################
# Main routine
###############################################################################
def load_form():
#if not os.environ['QUERY_STRING']:
# return { }
cgi.maxlen = 64*1024
cgiform = cgi.FieldStorage()
form = { }
for key in cgiform.keys():
item = cgiform[key]
if type(item) is not type([]) and \
not item.file:
form[key] = item.value
return form
def setup_list():
global ctxt
list = ctxt[LIST]
if list:
try:
base = config.archives[list]
except KeyError:
die(ctxt, 'Unknown list: ' + list)
ctxt.update(base)
eza = ctxt[EZMLM] = ezmlm.EzmlmArchive(ctxt[LISTDIR])
if ctxt.has_key(MSGNUM):
ctxt.update(eza.index[ctxt[MSGNUM]])
if ctxt.has_key(THREADID):
ctxt.update(eza.thread(ctxt[THREADID]))
eza.set_months(ctxt)
if ctxt[TZ] and ctxt[TZ] <> 'None':
os.environ['TZ'] = ctxt[TZ]
def main_path(pathstr):
# FIXME: handle ?part=#.#.#&filename=string
# and then convert sub_showmsg et al to use the same notation
global ctxt
if not config.allowraw:
die(ctxt, "Downloading raw messages is administratively prohibited.")
while pathstr[0] == '/':
pathstr = pathstr[1:]
path = pathstr.split('/')
ctxt[LIST] = path[0]
setup_list()
try:
msgnum = int(path[1])
except:
die(ctxt, "Invalid path: " + pathstr)
msg = ctxt[EZMLM].open(msgnum)
if ctxt.has_key(PART):
parts = map(int, ctxt[PART].split('.'))
part = email.message_from_file(msg)
# FIXME: What the heck am I supposed to be doing with these numbers?!?
if parts[0] != 1:
raise ValueError
parts = parts[1:]
while parts:
part = part.get_payload()[parts[0]]
parts = parts[1:]
write('Content-Type: %s\r\n\r\n' % part.get_content_type())
write(part.get_payload(decode=1))
else:
try:
partnum = int(path[2])
msg = email.message_from_file(msg)
for part in msg.walk():
if partnum <= 0:
break
partnum -= 1
write('Content-Type: %s\r\n\r\n' % part.get_content_type())
write(part.get_payload(decode=1))
except:
write('Content-Type: message/rfc822\r\n\r\n')
buf = msg.read(8192)
while buf:
write(buf)
buf = msg.read(8192)
sys.exit(0)
def import_command(command):
name = 'commands.' + command
for base in sys.path[:2]:
filename = base + '/commands/' + command + '.py'
if os.path.exists(filename):
return imp.load_module(name, open(filename, 'r'), filename,
('', '', imp.PY_SOURCE))
raise ImportError, "Could not locate command: " + command
def main_form():
global ctxt
setup_list()
if ctxt.has_key('command'): ctxt[COMMAND] = ctxt['command']
if '/' in ctxt[COMMAND]:
die(ctxt, "Invalid command")
if not ctxt[LIST]:
ctxt[COMMAND] = 'lists'
try:
module = import_command(ctxt[COMMAND])
except ImportError:
die(ctxt, "Invalid command")
module.do(ctxt)
def main():
update_global_context()
global ctxt
ctxt = context.Context()
# Insert the environment (CGI) variables
ctxt.update(os.environ)
# Set up hard-coded defaults
ctxt[ALTPART] = 'text/plain'
ctxt[COMMAND] = 'months'
ctxt[CSSPREFIX] = ''
ctxt[DATESORT] = 'ascending'
ctxt[FEEDMSGS] = 10
ctxt[FEEDTYPE] = 'atom'
ctxt[FORMATTIME] = ''
ctxt[LIST] = ''
ctxt[MSGSPERPAGE] = 10
ctxt[PERPAGE] = 20
ctxt[STYLE] = ''
ctxt[WRAPWIDTH] = 0
ctxt[TERMS] = ''
ctxt[TZ] = ''
# Update with defaults from the config
ctxt.update(config.defaults)
ctxt[ALLOWRAW] = config.allowraw
# Update with all cookies
for c in Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE', '')).values():
ctxt[c.key] = c.value
fixup_config()
global form
form = load_form()
ctxt.update(form)
try:
path = os.environ['PATH_INFO']
main_path(path)
except KeyError:
pass
main_form()
|