• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
10from __future__ import print_function
11import code, sys, importlib
12from scapy.config import conf
13from scapy.themes import *
14from scapy.error import Scapy_Exception
15from scapy.utils import tex_escape
16import scapy.modules.six as six
17
18
19#########################
20##### Autorun stuff #####
21#########################
22
23class StopAutorun(Scapy_Exception):
24    code_run = ""
25
26class ScapyAutorunInterpreter(code.InteractiveInterpreter):
27    def __init__(self, *args, **kargs):
28        code.InteractiveInterpreter.__init__(self, *args, **kargs)
29        self.error = 0
30    def showsyntaxerror(self, *args, **kargs):
31        self.error = 1
32        return code.InteractiveInterpreter.showsyntaxerror(self, *args, **kargs)
33    def showtraceback(self, *args, **kargs):
34        self.error = 1
35        exc_type, exc_value, exc_tb = sys.exc_info()
36        if isinstance(exc_value, StopAutorun):
37            raise exc_value
38        return code.InteractiveInterpreter.showtraceback(self, *args, **kargs)
39
40
41def autorun_commands(cmds, my_globals=None, ignore_globals=None, verb=0):
42    sv = conf.verb
43    try:
44        try:
45            if my_globals is None:
46                my_globals = importlib.import_module(".all", "scapy").__dict__
47                if ignore_globals:
48                    for ig in ignore_globals:
49                        my_globals.pop(ig, None)
50            conf.verb = verb
51            interp = ScapyAutorunInterpreter(my_globals)
52            cmd = ""
53            cmds = cmds.splitlines()
54            cmds.append("") # ensure we finish multi-line commands
55            cmds.reverse()
56            six.moves.builtins.__dict__["_"] = None
57            while True:
58                if cmd:
59                    sys.stderr.write(sys.__dict__.get("ps2","... "))
60                else:
61                    sys.stderr.write(str(sys.__dict__.get("ps1", sys.ps1)))
62
63                l = cmds.pop()
64                print(l)
65                cmd += "\n"+l
66                if interp.runsource(cmd):
67                    continue
68                if interp.error:
69                    return 0
70                cmd = ""
71                if len(cmds) <= 1:
72                    break
73        except SystemExit:
74            pass
75    finally:
76        conf.verb = sv
77    return _
78
79def autorun_get_interactive_session(cmds, **kargs):
80    class StringWriter:
81        def __init__(self):
82            self.s = ""
83        def write(self, x):
84            self.s += x
85        def flush(self):
86            pass
87
88    sw = StringWriter()
89    sstdout,sstderr = sys.stdout,sys.stderr
90    try:
91        try:
92            sys.stdout = sys.stderr = sw
93            res = autorun_commands(cmds, **kargs)
94        except StopAutorun as e:
95            e.code_run = sw.s
96            raise
97    finally:
98        sys.stdout,sys.stderr = sstdout,sstderr
99    return sw.s,res
100
101def autorun_get_text_interactive_session(cmds, **kargs):
102    ct = conf.color_theme
103    try:
104        conf.color_theme = NoTheme()
105        s,res = autorun_get_interactive_session(cmds, **kargs)
106    finally:
107        conf.color_theme = ct
108    return s,res
109
110def autorun_get_ansi_interactive_session(cmds, **kargs):
111    ct = conf.color_theme
112    try:
113        conf.color_theme = DefaultTheme()
114        s,res = autorun_get_interactive_session(cmds, **kargs)
115    finally:
116        conf.color_theme = ct
117    return s,res
118
119def autorun_get_html_interactive_session(cmds, **kargs):
120    ct = conf.color_theme
121    to_html = lambda s: s.replace("<","&lt;").replace(">","&gt;").replace("#[#","<").replace("#]#",">")
122    try:
123        try:
124            conf.color_theme = HTMLTheme2()
125            s,res = autorun_get_interactive_session(cmds, **kargs)
126        except StopAutorun as e:
127            e.code_run = to_html(e.code_run)
128            raise
129    finally:
130        conf.color_theme = ct
131
132    return to_html(s),res
133
134def autorun_get_latex_interactive_session(cmds, **kargs):
135    ct = conf.color_theme
136    to_latex = lambda s: tex_escape(s).replace("@[@","{").replace("@]@","}").replace("@`@","\\")
137    try:
138        try:
139            conf.color_theme = LatexTheme2()
140            s,res = autorun_get_interactive_session(cmds, **kargs)
141        except StopAutorun as e:
142            e.code_run = to_latex(e.code_run)
143            raise
144    finally:
145        conf.color_theme = ct
146    return to_latex(s),res
147
148
149