Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python2....
File: mailcap.py
"""Mailcap file handling. See RFC 1524."""
[0] Fix | Delete
[1] Fix | Delete
import os
[2] Fix | Delete
import warnings
[3] Fix | Delete
import re
[4] Fix | Delete
[5] Fix | Delete
__all__ = ["getcaps","findmatch"]
[6] Fix | Delete
[7] Fix | Delete
[8] Fix | Delete
_find_unsafe = re.compile(r'[^\xa1-\xff\w@+=:,./-]').search
[9] Fix | Delete
[10] Fix | Delete
class UnsafeMailcapInput(Warning):
[11] Fix | Delete
"""Warning raised when refusing unsafe input"""
[12] Fix | Delete
[13] Fix | Delete
[14] Fix | Delete
# Part 1: top-level interface.
[15] Fix | Delete
[16] Fix | Delete
def getcaps():
[17] Fix | Delete
"""Return a dictionary containing the mailcap database.
[18] Fix | Delete
[19] Fix | Delete
The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
[20] Fix | Delete
to a list of dictionaries corresponding to mailcap entries. The list
[21] Fix | Delete
collects all the entries for that MIME type from all available mailcap
[22] Fix | Delete
files. Each dictionary contains key-value pairs for that MIME type,
[23] Fix | Delete
where the viewing command is stored with the key "view".
[24] Fix | Delete
[25] Fix | Delete
"""
[26] Fix | Delete
caps = {}
[27] Fix | Delete
for mailcap in listmailcapfiles():
[28] Fix | Delete
try:
[29] Fix | Delete
fp = open(mailcap, 'r')
[30] Fix | Delete
except IOError:
[31] Fix | Delete
continue
[32] Fix | Delete
with fp:
[33] Fix | Delete
morecaps = readmailcapfile(fp)
[34] Fix | Delete
for key, value in morecaps.iteritems():
[35] Fix | Delete
if not key in caps:
[36] Fix | Delete
caps[key] = value
[37] Fix | Delete
else:
[38] Fix | Delete
caps[key] = caps[key] + value
[39] Fix | Delete
return caps
[40] Fix | Delete
[41] Fix | Delete
def listmailcapfiles():
[42] Fix | Delete
"""Return a list of all mailcap files found on the system."""
[43] Fix | Delete
# XXX Actually, this is Unix-specific
[44] Fix | Delete
if 'MAILCAPS' in os.environ:
[45] Fix | Delete
str = os.environ['MAILCAPS']
[46] Fix | Delete
mailcaps = str.split(':')
[47] Fix | Delete
else:
[48] Fix | Delete
if 'HOME' in os.environ:
[49] Fix | Delete
home = os.environ['HOME']
[50] Fix | Delete
else:
[51] Fix | Delete
# Don't bother with getpwuid()
[52] Fix | Delete
home = '.' # Last resort
[53] Fix | Delete
mailcaps = [home + '/.mailcap', '/etc/mailcap',
[54] Fix | Delete
'/usr/etc/mailcap', '/usr/local/etc/mailcap']
[55] Fix | Delete
return mailcaps
[56] Fix | Delete
[57] Fix | Delete
[58] Fix | Delete
# Part 2: the parser.
[59] Fix | Delete
[60] Fix | Delete
def readmailcapfile(fp):
[61] Fix | Delete
"""Read a mailcap file and return a dictionary keyed by MIME type.
[62] Fix | Delete
[63] Fix | Delete
Each MIME type is mapped to an entry consisting of a list of
[64] Fix | Delete
dictionaries; the list will contain more than one such dictionary
[65] Fix | Delete
if a given MIME type appears more than once in the mailcap file.
[66] Fix | Delete
Each dictionary contains key-value pairs for that MIME type, where
[67] Fix | Delete
the viewing command is stored with the key "view".
[68] Fix | Delete
"""
[69] Fix | Delete
caps = {}
[70] Fix | Delete
while 1:
[71] Fix | Delete
line = fp.readline()
[72] Fix | Delete
if not line: break
[73] Fix | Delete
# Ignore comments and blank lines
[74] Fix | Delete
if line[0] == '#' or line.strip() == '':
[75] Fix | Delete
continue
[76] Fix | Delete
nextline = line
[77] Fix | Delete
# Join continuation lines
[78] Fix | Delete
while nextline[-2:] == '\\\n':
[79] Fix | Delete
nextline = fp.readline()
[80] Fix | Delete
if not nextline: nextline = '\n'
[81] Fix | Delete
line = line[:-2] + nextline
[82] Fix | Delete
# Parse the line
[83] Fix | Delete
key, fields = parseline(line)
[84] Fix | Delete
if not (key and fields):
[85] Fix | Delete
continue
[86] Fix | Delete
# Normalize the key
[87] Fix | Delete
types = key.split('/')
[88] Fix | Delete
for j in range(len(types)):
[89] Fix | Delete
types[j] = types[j].strip()
[90] Fix | Delete
key = '/'.join(types).lower()
[91] Fix | Delete
# Update the database
[92] Fix | Delete
if key in caps:
[93] Fix | Delete
caps[key].append(fields)
[94] Fix | Delete
else:
[95] Fix | Delete
caps[key] = [fields]
[96] Fix | Delete
return caps
[97] Fix | Delete
[98] Fix | Delete
def parseline(line):
[99] Fix | Delete
"""Parse one entry in a mailcap file and return a dictionary.
[100] Fix | Delete
[101] Fix | Delete
The viewing command is stored as the value with the key "view",
[102] Fix | Delete
and the rest of the fields produce key-value pairs in the dict.
[103] Fix | Delete
"""
[104] Fix | Delete
fields = []
[105] Fix | Delete
i, n = 0, len(line)
[106] Fix | Delete
while i < n:
[107] Fix | Delete
field, i = parsefield(line, i, n)
[108] Fix | Delete
fields.append(field)
[109] Fix | Delete
i = i+1 # Skip semicolon
[110] Fix | Delete
if len(fields) < 2:
[111] Fix | Delete
return None, None
[112] Fix | Delete
key, view, rest = fields[0], fields[1], fields[2:]
[113] Fix | Delete
fields = {'view': view}
[114] Fix | Delete
for field in rest:
[115] Fix | Delete
i = field.find('=')
[116] Fix | Delete
if i < 0:
[117] Fix | Delete
fkey = field
[118] Fix | Delete
fvalue = ""
[119] Fix | Delete
else:
[120] Fix | Delete
fkey = field[:i].strip()
[121] Fix | Delete
fvalue = field[i+1:].strip()
[122] Fix | Delete
if fkey in fields:
[123] Fix | Delete
# Ignore it
[124] Fix | Delete
pass
[125] Fix | Delete
else:
[126] Fix | Delete
fields[fkey] = fvalue
[127] Fix | Delete
return key, fields
[128] Fix | Delete
[129] Fix | Delete
def parsefield(line, i, n):
[130] Fix | Delete
"""Separate one key-value pair in a mailcap entry."""
[131] Fix | Delete
start = i
[132] Fix | Delete
while i < n:
[133] Fix | Delete
c = line[i]
[134] Fix | Delete
if c == ';':
[135] Fix | Delete
break
[136] Fix | Delete
elif c == '\\':
[137] Fix | Delete
i = i+2
[138] Fix | Delete
else:
[139] Fix | Delete
i = i+1
[140] Fix | Delete
return line[start:i].strip(), i
[141] Fix | Delete
[142] Fix | Delete
[143] Fix | Delete
# Part 3: using the database.
[144] Fix | Delete
[145] Fix | Delete
def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
[146] Fix | Delete
"""Find a match for a mailcap entry.
[147] Fix | Delete
[148] Fix | Delete
Return a tuple containing the command line, and the mailcap entry
[149] Fix | Delete
used; (None, None) if no match is found. This may invoke the
[150] Fix | Delete
'test' command of several matching entries before deciding which
[151] Fix | Delete
entry to use.
[152] Fix | Delete
[153] Fix | Delete
"""
[154] Fix | Delete
if _find_unsafe(filename):
[155] Fix | Delete
msg = "Refusing to use mailcap with filename %r. Use a safe temporary filename." % (filename,)
[156] Fix | Delete
warnings.warn(msg, UnsafeMailcapInput)
[157] Fix | Delete
return None, None
[158] Fix | Delete
entries = lookup(caps, MIMEtype, key)
[159] Fix | Delete
# XXX This code should somehow check for the needsterminal flag.
[160] Fix | Delete
for e in entries:
[161] Fix | Delete
if 'test' in e:
[162] Fix | Delete
test = subst(e['test'], filename, plist)
[163] Fix | Delete
if test is None:
[164] Fix | Delete
continue
[165] Fix | Delete
if test and os.system(test) != 0:
[166] Fix | Delete
continue
[167] Fix | Delete
command = subst(e[key], MIMEtype, filename, plist)
[168] Fix | Delete
if command is not None:
[169] Fix | Delete
return command, e
[170] Fix | Delete
return None, None
[171] Fix | Delete
[172] Fix | Delete
def lookup(caps, MIMEtype, key=None):
[173] Fix | Delete
entries = []
[174] Fix | Delete
if MIMEtype in caps:
[175] Fix | Delete
entries = entries + caps[MIMEtype]
[176] Fix | Delete
MIMEtypes = MIMEtype.split('/')
[177] Fix | Delete
MIMEtype = MIMEtypes[0] + '/*'
[178] Fix | Delete
if MIMEtype in caps:
[179] Fix | Delete
entries = entries + caps[MIMEtype]
[180] Fix | Delete
if key is not None:
[181] Fix | Delete
entries = filter(lambda e, key=key: key in e, entries)
[182] Fix | Delete
return entries
[183] Fix | Delete
[184] Fix | Delete
def subst(field, MIMEtype, filename, plist=[]):
[185] Fix | Delete
# XXX Actually, this is Unix-specific
[186] Fix | Delete
res = ''
[187] Fix | Delete
i, n = 0, len(field)
[188] Fix | Delete
while i < n:
[189] Fix | Delete
c = field[i]; i = i+1
[190] Fix | Delete
if c != '%':
[191] Fix | Delete
if c == '\\':
[192] Fix | Delete
c = field[i:i+1]; i = i+1
[193] Fix | Delete
res = res + c
[194] Fix | Delete
else:
[195] Fix | Delete
c = field[i]; i = i+1
[196] Fix | Delete
if c == '%':
[197] Fix | Delete
res = res + c
[198] Fix | Delete
elif c == 's':
[199] Fix | Delete
res = res + filename
[200] Fix | Delete
elif c == 't':
[201] Fix | Delete
if _find_unsafe(MIMEtype):
[202] Fix | Delete
msg = "Refusing to substitute MIME type %r into a shell command." % (MIMEtype,)
[203] Fix | Delete
warnings.warn(msg, UnsafeMailcapInput)
[204] Fix | Delete
return None
[205] Fix | Delete
res = res + MIMEtype
[206] Fix | Delete
elif c == '{':
[207] Fix | Delete
start = i
[208] Fix | Delete
while i < n and field[i] != '}':
[209] Fix | Delete
i = i+1
[210] Fix | Delete
name = field[start:i]
[211] Fix | Delete
i = i+1
[212] Fix | Delete
param = findparam(name, plist)
[213] Fix | Delete
if _find_unsafe(param):
[214] Fix | Delete
msg = "Refusing to substitute parameter %r (%s) into a shell command" % (param, name)
[215] Fix | Delete
warnings.warn(msg, UnsafeMailcapInput)
[216] Fix | Delete
return None
[217] Fix | Delete
res = res + param
[218] Fix | Delete
# XXX To do:
[219] Fix | Delete
# %n == number of parts if type is multipart/*
[220] Fix | Delete
# %F == list of alternating type and filename for parts
[221] Fix | Delete
else:
[222] Fix | Delete
res = res + '%' + c
[223] Fix | Delete
return res
[224] Fix | Delete
[225] Fix | Delete
def findparam(name, plist):
[226] Fix | Delete
name = name.lower() + '='
[227] Fix | Delete
n = len(name)
[228] Fix | Delete
for p in plist:
[229] Fix | Delete
if p[:n].lower() == name:
[230] Fix | Delete
return p[n:]
[231] Fix | Delete
return ''
[232] Fix | Delete
[233] Fix | Delete
[234] Fix | Delete
# Part 4: test program.
[235] Fix | Delete
[236] Fix | Delete
def test():
[237] Fix | Delete
import sys
[238] Fix | Delete
caps = getcaps()
[239] Fix | Delete
if not sys.argv[1:]:
[240] Fix | Delete
show(caps)
[241] Fix | Delete
return
[242] Fix | Delete
for i in range(1, len(sys.argv), 2):
[243] Fix | Delete
args = sys.argv[i:i+2]
[244] Fix | Delete
if len(args) < 2:
[245] Fix | Delete
print "usage: mailcap [MIMEtype file] ..."
[246] Fix | Delete
return
[247] Fix | Delete
MIMEtype = args[0]
[248] Fix | Delete
file = args[1]
[249] Fix | Delete
command, e = findmatch(caps, MIMEtype, 'view', file)
[250] Fix | Delete
if not command:
[251] Fix | Delete
print "No viewer found for", type
[252] Fix | Delete
else:
[253] Fix | Delete
print "Executing:", command
[254] Fix | Delete
sts = os.system(command)
[255] Fix | Delete
if sts:
[256] Fix | Delete
print "Exit status:", sts
[257] Fix | Delete
[258] Fix | Delete
def show(caps):
[259] Fix | Delete
print "Mailcap files:"
[260] Fix | Delete
for fn in listmailcapfiles(): print "\t" + fn
[261] Fix | Delete
print
[262] Fix | Delete
if not caps: caps = getcaps()
[263] Fix | Delete
print "Mailcap entries:"
[264] Fix | Delete
print
[265] Fix | Delete
ckeys = caps.keys()
[266] Fix | Delete
ckeys.sort()
[267] Fix | Delete
for type in ckeys:
[268] Fix | Delete
print type
[269] Fix | Delete
entries = caps[type]
[270] Fix | Delete
for e in entries:
[271] Fix | Delete
keys = e.keys()
[272] Fix | Delete
keys.sort()
[273] Fix | Delete
for k in keys:
[274] Fix | Delete
print " %-15s" % k, e[k]
[275] Fix | Delete
print
[276] Fix | Delete
[277] Fix | Delete
if __name__ == '__main__':
[278] Fix | Delete
test()
[279] Fix | Delete
[280] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function