1 """Mailcap file handling. See RFC 1524."""
7 __all__ = ["getcaps","findmatch"]
10 # _DEPRECATION_MSG = ('The {name} module is deprecated and will be removed in '
11 # 'Python {remove}. See the mimetypes module for an '
13 # warnings._deprecated(__name__, _DEPRECATION_MSG, remove=(3, 13))
16 def lineno_sort_key(entry):
17 # Sort in ascending order, with unspecified entries at the end
19 return 0, entry['lineno']
23 _find_unsafe = re.compile(r'[^\xa1-\U0010FFFF\w@+=:,./-]').search
25 class UnsafeMailcapInput(Warning):
26 """Warning raised when refusing unsafe input"""
29 # Part 1: top-level interface.
32 """Return a dictionary containing the mailcap database.
34 The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain')
35 to a list of dictionaries corresponding to mailcap entries. The list
36 collects all the entries for that MIME type from all available mailcap
37 files. Each dictionary contains key-value pairs for that MIME type,
38 where the viewing command is stored with the key "view".
43 for mailcap in listmailcapfiles():
45 fp = open(mailcap, 'r')
49 morecaps, lineno = _readmailcapfile(fp, lineno)
50 for key, value in morecaps.items():
54 caps[key] = caps[key] + value
57 def listmailcapfiles():
58 """Return a list of all mailcap files found on the system."""
59 # This is mostly a Unix thing, but we use the OS path separator anyway
60 if 'MAILCAPS' in os.environ:
61 pathstr = os.environ['MAILCAPS']
62 mailcaps = pathstr.split(os.pathsep)
64 if 'HOME' in os.environ:
65 home = os.environ['HOME']
67 # Don't bother with getpwuid()
68 home = '.' # Last resort
69 mailcaps = [home + '/.mailcap', '/etc/mailcap',
70 '/usr/etc/mailcap', '/usr/local/etc/mailcap']
75 def readmailcapfile(fp):
76 """Read a mailcap file and return a dictionary keyed by MIME type."""
77 warnings.warn('readmailcapfile is deprecated, use getcaps instead',
78 DeprecationWarning, 2)
79 caps, _ = _readmailcapfile(fp, None)
83 def _readmailcapfile(fp, lineno):
84 """Read a mailcap file and return a dictionary keyed by MIME type.
86 Each MIME type is mapped to an entry consisting of a list of
87 dictionaries; the list will contain more than one such dictionary
88 if a given MIME type appears more than once in the mailcap file.
89 Each dictionary contains key-value pairs for that MIME type, where
90 the viewing command is stored with the key "view".
93 while line := fp.readline():
94 # Ignore comments and blank lines
95 if line[0] == '#' or line.strip() == '':
98 # Join continuation lines
99 while nextline[-2:] == '\\\n':
100 nextline = fp.readline()
101 if not nextline: nextline = '\n'
102 line = line[:-2] + nextline
104 key, fields = parseline(line)
105 if not (key and fields):
107 if lineno is not None:
108 fields['lineno'] = lineno
111 types = key.split('/')
112 for j in range(len(types)):
113 types[j] = types[j].strip()
114 key = '/'.join(types).lower()
115 # Update the database
117 caps[key].append(fields)
123 """Parse one entry in a mailcap file and return a dictionary.
125 The viewing command is stored as the value with the key "view",
126 and the rest of the fields produce key-value pairs in the dict.
131 field, i = parsefield(line, i, n)
133 i = i+1 # Skip semicolon
136 key, view, rest = fields[0], fields[1], fields[2:]
137 fields = {'view': view}
144 fkey = field[:i].strip()
145 fvalue = field[i+1:].strip()
150 fields[fkey] = fvalue
153 def parsefield(line, i, n):
154 """Separate one key-value pair in a mailcap entry."""
164 return line[start:i].strip(), i
167 # Part 3: using the database.
169 def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
170 """Find a match for a mailcap entry.
172 Return a tuple containing the command line, and the mailcap entry
173 used; (None, None) if no match is found. This may invoke the
174 'test' command of several matching entries before deciding which
178 if _find_unsafe(filename):
179 msg = "Refusing to use mailcap with filename %r. Use a safe temporary filename." % (filename,)
180 warnings.warn(msg, UnsafeMailcapInput)
182 entries = lookup(caps, MIMEtype, key)
183 # XXX This code should somehow check for the needsterminal flag.
186 test = subst(e['test'], filename, plist)
189 if test and os.system(test) != 0:
191 command = subst(e[key], MIMEtype, filename, plist)
192 if command is not None:
196 def lookup(caps, MIMEtype, key=None):
199 entries = entries + caps[MIMEtype]
200 MIMEtypes = MIMEtype.split('/')
201 MIMEtype = MIMEtypes[0] + '/*'
203 entries = entries + caps[MIMEtype]
205 entries = [e for e in entries if key in e]
206 entries = sorted(entries, key=lineno_sort_key)
209 def subst(field, MIMEtype, filename, plist=[]):
210 # XXX Actually, this is Unix-specific
214 c = field[i]; i = i+1
217 c = field[i:i+1]; i = i+1
220 c = field[i]; i = i+1
226 if _find_unsafe(MIMEtype):
227 msg = "Refusing to substitute MIME type %r into a shell command." % (MIMEtype,)
228 warnings.warn(msg, UnsafeMailcapInput)
233 while i < n and field[i] != '}':
235 name = field[start:i]
237 param = findparam(name, plist)
238 if _find_unsafe(param):
239 msg = "Refusing to substitute parameter %r (%s) into a shell command" % (param, name)
240 warnings.warn(msg, UnsafeMailcapInput)
244 # %n == number of parts if type is multipart/*
245 # %F == list of alternating type and filename for parts
250 def findparam(name, plist):
251 name = name.lower() + '='
254 if p[:n].lower() == name:
259 # Part 4: test program.
267 for i in range(1, len(sys.argv), 2):
268 args = sys.argv[i:i+2]
270 print("usage: mailcap [MIMEtype file] ...")
274 command, e = findmatch(caps, MIMEtype, 'view', file)
276 print("No viewer found for", type)
278 print("Executing:", command)
279 sts = os.system(command)
280 sts = os.waitstatus_to_exitcode(sts)
282 print("Exit status:", sts)
285 print("Mailcap files:")
286 for fn in listmailcapfiles(): print("\t" + fn)
288 if not caps: caps = getcaps()
289 print("Mailcap entries:")
298 print(" %-15s" % k, e[k])
301 if __name__ == '__main__':