1 | n/a | # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. |
---|
2 | n/a | # Licensed to PSF under a Contributor Agreement. |
---|
3 | n/a | |
---|
4 | n/a | """Safely evaluate Python string literals without using eval().""" |
---|
5 | n/a | |
---|
6 | n/a | import re |
---|
7 | n/a | |
---|
8 | n/a | simple_escapes = {"a": "\a", |
---|
9 | n/a | "b": "\b", |
---|
10 | n/a | "f": "\f", |
---|
11 | n/a | "n": "\n", |
---|
12 | n/a | "r": "\r", |
---|
13 | n/a | "t": "\t", |
---|
14 | n/a | "v": "\v", |
---|
15 | n/a | "'": "'", |
---|
16 | n/a | '"': '"', |
---|
17 | n/a | "\\": "\\"} |
---|
18 | n/a | |
---|
19 | n/a | def escape(m): |
---|
20 | n/a | all, tail = m.group(0, 1) |
---|
21 | n/a | assert all.startswith("\\") |
---|
22 | n/a | esc = simple_escapes.get(tail) |
---|
23 | n/a | if esc is not None: |
---|
24 | n/a | return esc |
---|
25 | n/a | if tail.startswith("x"): |
---|
26 | n/a | hexes = tail[1:] |
---|
27 | n/a | if len(hexes) < 2: |
---|
28 | n/a | raise ValueError("invalid hex string escape ('\\%s')" % tail) |
---|
29 | n/a | try: |
---|
30 | n/a | i = int(hexes, 16) |
---|
31 | n/a | except ValueError: |
---|
32 | n/a | raise ValueError("invalid hex string escape ('\\%s')" % tail) |
---|
33 | n/a | else: |
---|
34 | n/a | try: |
---|
35 | n/a | i = int(tail, 8) |
---|
36 | n/a | except ValueError: |
---|
37 | n/a | raise ValueError("invalid octal string escape ('\\%s')" % tail) |
---|
38 | n/a | return chr(i) |
---|
39 | n/a | |
---|
40 | n/a | def evalString(s): |
---|
41 | n/a | assert s.startswith("'") or s.startswith('"'), repr(s[:1]) |
---|
42 | n/a | q = s[0] |
---|
43 | n/a | if s[:3] == q*3: |
---|
44 | n/a | q = q*3 |
---|
45 | n/a | assert s.endswith(q), repr(s[-len(q):]) |
---|
46 | n/a | assert len(s) >= 2*len(q) |
---|
47 | n/a | s = s[len(q):-len(q)] |
---|
48 | n/a | return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s) |
---|
49 | n/a | |
---|
50 | n/a | def test(): |
---|
51 | n/a | for i in range(256): |
---|
52 | n/a | c = chr(i) |
---|
53 | n/a | s = repr(c) |
---|
54 | n/a | e = evalString(s) |
---|
55 | n/a | if e != c: |
---|
56 | n/a | print(i, c, s, e) |
---|
57 | n/a | |
---|
58 | n/a | |
---|
59 | n/a | if __name__ == "__main__": |
---|
60 | n/a | test() |
---|