1## This file is part of Scapy
2## See http://www.secdev.org/projects/scapy for more informations
3## Copyright (C) Philippe Biondi <phil@secdev.org>
4## This program is published under a GPLv2 license
5
6"""
7Run commands when the Scapy interpreter starts.
8"""
9
10import code,sys
11from config import conf
12from themes import *
13from error import Scapy_Exception
14from utils import tex_escape
15
16
17#########################
18##### Autorun stuff #####
19#########################
20
21class StopAutorun(Scapy_Exception):
22    code_run = ""
23
24class ScapyAutorunInterpreter(code.InteractiveInterpreter):
25    def __init__(self, *args, **kargs):
26        code.InteractiveInterpreter.__init__(self, *args, **kargs)
27        self.error = 0
28    def showsyntaxerror(self, *args, **kargs):
29        self.error = 1
30        return code.InteractiveInterpreter.showsyntaxerror(self, *args, **kargs)
31    def showtraceback(self, *args, **kargs):
32        self.error = 1
33        exc_type, exc_value, exc_tb = sys.exc_info()
34        if isinstance(exc_value, StopAutorun):
35            raise exc_value
36        return code.InteractiveInterpreter.showtraceback(self, *args, **kargs)
37
38
39def autorun_commands(cmds,my_globals=None,verb=0):
40    sv = conf.verb
41    import __builtin__
42    try:
43        try:
44            if my_globals is None:
45                my_globals = __import__("scapy.all").all.__dict__
46            conf.verb = verb
47            interp = ScapyAutorunInterpreter(my_globals)
48            cmd = ""
49            cmds = cmds.splitlines()
50            cmds.append("") # ensure we finish multiline commands
51            cmds.reverse()
52            __builtin__.__dict__["_"] = None
53            while 1:
54                if cmd:
55                    sys.stderr.write(sys.__dict__.get("ps2","... "))
56                else:
57                    sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
58
59                l = cmds.pop()
60                print l
61                cmd += "\n"+l
62                if interp.runsource(cmd):
63                    continue
64                if interp.error:
65                    return 0
66                cmd = ""
67                if len(cmds) <= 1:
68                    break
69        except SystemExit:
70            pass
71    finally:
72        conf.verb = sv
73    return _
74
75def autorun_get_interactive_session(cmds, **kargs):
76    class StringWriter:
77        def __init__(self):
78            self.s = ""
79        def write(self, x):
80            self.s += x
81
82    sw = StringWriter()
83    sstdout,sstderr = sys.stdout,sys.stderr
84    try:
85        try:
86            sys.stdout = sys.stderr = sw
87            res = autorun_commands(cmds, **kargs)
88        except StopAutorun,e:
89            e.code_run = sw.s
90            raise
91    finally:
92        sys.stdout,sys.stderr = sstdout,sstderr
93    return sw.s,res
94
95def autorun_get_text_interactive_session(cmds, **kargs):
96    ct = conf.color_theme
97    try:
98        conf.color_theme = NoTheme()
99        s,res = autorun_get_interactive_session(cmds, **kargs)
100    finally:
101        conf.color_theme = ct
102    return s,res
103
104def autorun_get_ansi_interactive_session(cmds, **kargs):
105    ct = conf.color_theme
106    try:
107        conf.color_theme = DefaultTheme()
108        s,res = autorun_get_interactive_session(cmds, **kargs)
109    finally:
110        conf.color_theme = ct
111    return s,res
112
113def autorun_get_html_interactive_session(cmds, **kargs):
114    ct = conf.color_theme
115    to_html = lambda s: s.replace("<","&lt;").replace(">","&gt;").replace("#[#","<").replace("#]#",">")
116    try:
117        try:
118            conf.color_theme = HTMLTheme2()
119            s,res = autorun_get_interactive_session(cmds, **kargs)
120        except StopAutorun,e:
121            e.code_run = to_html(e.code_run)
122            raise
123    finally:
124        conf.color_theme = ct
125
126    return to_html(s),res
127
128def autorun_get_latex_interactive_session(cmds, **kargs):
129    ct = conf.color_theme
130    to_latex = lambda s: tex_escape(s).replace("@[@","{").replace("@]@","}").replace("@`@","\\")
131    try:
132        try:
133            conf.color_theme = LatexTheme2()
134            s,res = autorun_get_interactive_session(cmds, **kargs)
135        except StopAutorun,e:
136            e.code_run = to_latex(e.code_run)
137            raise
138    finally:
139        conf.color_theme = ct
140    return to_latex(s),res
141
142
143