/
utils.py
3199 lines (2721 loc) · 102 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: GPL-2.0-only
# This file is part of Scapy
# See https://scapy.net/ for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
"""
General utility functions.
"""
from __future__ import absolute_import
from __future__ import print_function
from decimal import Decimal
import array
import collections
import decimal
import difflib
import gzip
import os
import random
import re
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import warnings
import scapy.libs.six as six
from scapy.libs.six.moves import range, input, zip_longest
from scapy.config import conf
from scapy.consts import DARWIN, OPENBSD, WINDOWS
from scapy.data import MTU, DLT_EN10MB
from scapy.compat import orb, plain_str, chb, bytes_base64,\
base64_bytes, hex_bytes, lambda_tuple_converter, bytes_encode
from scapy.error import log_runtime, Scapy_Exception, warning
from scapy.pton_ntop import inet_pton
# Typing imports
from scapy.compat import (
cast,
Any,
AnyStr,
Callable,
Dict,
IO,
Iterator,
List,
Literal,
Optional,
TYPE_CHECKING,
Tuple,
Type,
Union,
overload,
)
if TYPE_CHECKING:
from scapy.packet import Packet
from scapy.plist import _PacketIterable, PacketList
from scapy.supersocket import SuperSocket
_SuperSocket = SuperSocket
else:
_SuperSocket = object
_ByteStream = Union[IO[bytes], gzip.GzipFile]
###########
# Tools #
###########
def issubtype(x, # type: Any
t, # type: Union[type, str]
):
# type: (...) -> bool
"""issubtype(C, B) -> bool
Return whether C is a class and if it is a subclass of class B.
When using a tuple as the second argument issubtype(X, (A, B, ...)),
is a shortcut for issubtype(X, A) or issubtype(X, B) or ... (etc.).
"""
if isinstance(t, str):
return t in (z.__name__ for z in x.__bases__)
if isinstance(x, type) and issubclass(x, t):
return True
return False
_Decimal = Union[Decimal, int]
class EDecimal(Decimal):
"""Extended Decimal
This implements arithmetic and comparison with float for
backward compatibility
"""
def __add__(self, other, context=None):
# type: (_Decimal, Any) -> EDecimal
return EDecimal(Decimal.__add__(self, Decimal(other)))
def __radd__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__add__(self, Decimal(other)))
def __sub__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__sub__(self, Decimal(other)))
def __rsub__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__rsub__(self, Decimal(other)))
def __mul__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mul__(self, Decimal(other)))
def __rmul__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mul__(self, Decimal(other)))
def __truediv__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__truediv__(self, Decimal(other)))
def __floordiv__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__floordiv__(self, Decimal(other)))
if sys.version_info >= (3,):
def __divmod__(self, other):
# type: (_Decimal) -> Tuple[EDecimal, EDecimal]
r = Decimal.__divmod__(self, Decimal(other))
return EDecimal(r[0]), EDecimal(r[1])
else:
def __div__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__div__(self, Decimal(other)))
def __rdiv__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__rdiv__(self, Decimal(other)))
def __mod__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__mod__(self, Decimal(other)))
def __rmod__(self, other):
# type: (_Decimal) -> EDecimal
return EDecimal(Decimal.__rmod__(self, Decimal(other)))
def __pow__(self, other, modulo=None):
# type: (_Decimal, Optional[_Decimal]) -> EDecimal
return EDecimal(Decimal.__pow__(self, Decimal(other), modulo))
def __eq__(self, other):
# type: (Any) -> bool
return super(EDecimal, self).__eq__(other) or float(self) == other
def normalize(self, precision): # type: ignore
# type: (int) -> EDecimal
with decimal.localcontext() as ctx:
ctx.prec = precision
return EDecimal(super(EDecimal, self).normalize(ctx))
@overload
def get_temp_file(keep, autoext, fd):
# type: (bool, str, Literal[True]) -> IO[bytes]
pass
@overload
def get_temp_file(keep=False, autoext="", fd=False): # noqa: F811
# type: (bool, str, Literal[False]) -> str
pass
def get_temp_file(keep=False, autoext="", fd=False): # noqa: F811
# type: (bool, str, bool) -> Union[IO[bytes], str]
"""Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
file opened. If False (default), this returns a file path.
"""
f = tempfile.NamedTemporaryFile(prefix="scapy", suffix=autoext,
delete=False)
if not keep:
conf.temp_files.append(f.name)
if fd:
return f
else:
# Close the file so something else can take it.
f.close()
return f.name
def get_temp_dir(keep=False):
# type: (bool) -> str
"""Creates a temporary file, and returns its name.
:param keep: If False (default), the directory will be recursively
deleted when Scapy exits.
:return: A full path to a temporary directory.
"""
dname = tempfile.mkdtemp(prefix="scapy")
if not keep:
conf.temp_files.append(dname)
return dname
def sane(x, color=False):
# type: (AnyStr, bool) -> str
r = ""
for i in x:
j = orb(i)
if (j < 32) or (j >= 127):
if color:
r += conf.color_theme.not_printable(".")
else:
r += "."
else:
r += chr(j)
return r
@conf.commands.register
def restart():
# type: () -> None
"""Restarts scapy"""
if not conf.interactive or not os.path.isfile(sys.argv[0]):
raise OSError("Scapy was not started from console")
if WINDOWS:
try:
res_code = subprocess.call([sys.executable] + sys.argv)
except KeyboardInterrupt:
res_code = 1
finally:
os._exit(res_code)
os.execv(sys.executable, [sys.executable] + sys.argv)
def lhex(x):
# type: (Any) -> str
from scapy.volatile import VolatileValue
if isinstance(x, VolatileValue):
return repr(x)
if isinstance(x, six.integer_types):
return hex(x)
if isinstance(x, tuple):
return "(%s)" % ", ".join(lhex(v) for v in x)
if isinstance(x, list):
return "[%s]" % ", ".join(lhex(v) for v in x)
return str(x)
@conf.commands.register
def hexdump(p, dump=False):
# type: (Union[Packet, AnyStr], bool) -> Optional[str]
"""Build a tcpdump like hexadecimal view
:param p: a Packet
:param dump: define if the result must be printed or returned in a variable
:return: a String only when dump=True
"""
s = ""
x = bytes_encode(p)
x_len = len(x)
i = 0
while i < x_len:
s += "%04x " % i
for j in range(16):
if i + j < x_len:
s += "%02X " % orb(x[i + j])
else:
s += " "
s += " %s\n" % sane(x[i:i + 16], color=True)
i += 16
# remove trailing \n
s = s[:-1] if s.endswith("\n") else s
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def linehexdump(p, onlyasc=0, onlyhex=0, dump=False):
# type: (Union[Packet, AnyStr], int, int, bool) -> Optional[str]
"""Build an equivalent view of hexdump() on a single line
Note that setting both onlyasc and onlyhex to 1 results in a empty output
:param p: a Packet
:param onlyasc: 1 to display only the ascii view
:param onlyhex: 1 to display only the hexadecimal view
:param dump: print the view if False
:return: a String only when dump=True
"""
s = ""
s = hexstr(p, onlyasc=onlyasc, onlyhex=onlyhex, color=not dump)
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def chexdump(p, dump=False):
# type: (Union[Packet, AnyStr], bool) -> Optional[str]
"""Build a per byte hexadecimal representation
Example:
>>> chexdump(IP())
0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501
:param p: a Packet
:param dump: print the view if False
:return: a String only if dump=True
"""
x = bytes_encode(p)
s = ", ".join("%#04x" % orb(x) for x in x)
if dump:
return s
else:
print(s)
return None
@conf.commands.register
def hexstr(p, onlyasc=0, onlyhex=0, color=False):
# type: (Union[Packet, AnyStr], int, int, bool) -> str
"""Build a fancy tcpdump like hex from bytes."""
x = bytes_encode(p)
s = []
if not onlyasc:
s.append(" ".join("%02X" % orb(b) for b in x))
if not onlyhex:
s.append(sane(x, color=color))
return " ".join(s)
def repr_hex(s):
# type: (bytes) -> str
""" Convert provided bitstring to a simple string of hex digits """
return "".join("%02x" % orb(x) for x in s)
@conf.commands.register
def hexdiff(a, b, autojunk=False):
# type: (Union[Packet, AnyStr], Union[Packet, AnyStr], bool) -> None
"""
Show differences between 2 binary strings, Packets...
For the autojunk parameter, see
https://docs.python.org/3.8/library/difflib.html#difflib.SequenceMatcher
:param a:
:param b: The binary strings, packets... to compare
:param autojunk: Setting it to True will likely increase the comparison
speed a lot on big byte strings, but will reduce accuracy (will tend
to miss insertion and see replacements instead for instance).
"""
# Compare the strings using difflib
xb = bytes_encode(a)
yb = bytes_encode(b)
sm = difflib.SequenceMatcher(a=xb, b=yb, autojunk=autojunk)
xarr = [xb[i:i + 1] for i in range(len(xb))]
yarr = [yb[i:i + 1] for i in range(len(yb))]
backtrackx = []
backtracky = []
for opcode in sm.get_opcodes():
typ, x0, x1, y0, y1 = opcode
if typ == 'delete':
backtrackx += xarr[x0:x1]
backtracky += [b''] * (x1 - x0)
elif typ == 'insert':
backtrackx += [b''] * (y1 - y0)
backtracky += yarr[y0:y1]
elif typ in ['equal', 'replace']:
backtrackx += xarr[x0:x1]
backtracky += yarr[y0:y1]
if autojunk:
# Some lines may have been considered as junk. Check the sizes
lbx = len(backtrackx)
lby = len(backtracky)
backtrackx += [b''] * (max(lbx, lby) - lbx)
backtracky += [b''] * (max(lbx, lby) - lby)
# Print the diff
x = y = i = 0
colorize = {0: lambda x: x,
-1: conf.color_theme.left,
1: conf.color_theme.right}
dox = 1
doy = 0
btx_len = len(backtrackx)
while i < btx_len:
linex = backtrackx[i:i + 16]
liney = backtracky[i:i + 16]
xx = sum(len(k) for k in linex)
yy = sum(len(k) for k in liney)
if dox and not xx:
dox = 0
doy = 1
if dox and linex == liney:
doy = 1
if dox:
xd = y
j = 0
while not linex[j]:
j += 1
xd -= 1
print(colorize[doy - dox]("%04x" % xd), end=' ')
x += xx
line = linex
else:
print(" ", end=' ')
if doy:
yd = y
j = 0
while not liney[j]:
j += 1
yd -= 1
print(colorize[doy - dox]("%04x" % yd), end=' ')
y += yy
line = liney
else:
print(" ", end=' ')
print(" ", end=' ')
cl = ""
for j in range(16):
if i + j < btx_len:
if line[j]:
col = colorize[(linex[j] != liney[j]) * (doy - dox)]
print(col("%02X" % orb(line[j])), end=' ')
if linex[j] == liney[j]:
cl += sane(line[j], color=True)
else:
cl += col(sane(line[j]))
else:
print(" ", end=' ')
cl += " "
else:
print(" ", end=' ')
if j == 7:
print("", end=' ')
print(" ", cl)
if doy or not yy:
doy = 0
dox = 1
i += 16
else:
if yy:
dox = 0
doy = 1
else:
i += 16
if struct.pack("H", 1) == b"\x00\x01": # big endian
checksum_endian_transform = lambda chk: chk # type: Callable[[int], int]
else:
checksum_endian_transform = lambda chk: ((chk >> 8) & 0xff) | chk << 8
def checksum(pkt):
# type: (bytes) -> int
if len(pkt) % 2 == 1:
pkt += b"\0"
s = sum(array.array("H", pkt))
s = (s >> 16) + (s & 0xffff)
s += s >> 16
s = ~s
return checksum_endian_transform(s) & 0xffff
def _fletcher16(charbuf):
# type: (bytes) -> Tuple[int, int]
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501
c0 = c1 = 0
for char in charbuf:
c0 += orb(char)
c1 += c0
c0 %= 255
c1 %= 255
return (c0, c1)
@conf.commands.register
def fletcher16_checksum(binbuf):
# type: (bytes) -> int
"""Calculates Fletcher-16 checksum of the given buffer.
Note:
If the buffer contains the two checkbytes derived from the Fletcher-16 checksum # noqa: E501
the result of this function has to be 0. Otherwise the buffer has been corrupted. # noqa: E501
"""
(c0, c1) = _fletcher16(binbuf)
return (c1 << 8) | c0
@conf.commands.register
def fletcher16_checkbytes(binbuf, offset):
# type: (bytes, int) -> bytes
"""Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
Including the bytes into the buffer (at the position marked by offset) the # noqa: E501
global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501
the integrity of the buffer on the receiver side.
For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501
"""
# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501
if len(binbuf) < offset:
raise Exception("Packet too short for checkbytes %d" % len(binbuf))
binbuf = binbuf[:offset] + b"\x00\x00" + binbuf[offset + 2:]
(c0, c1) = _fletcher16(binbuf)
x = ((len(binbuf) - offset - 1) * c0 - c1) % 255
if (x <= 0):
x += 255
y = 510 - c0 - x
if (y > 255):
y -= 255
return chb(x) + chb(y)
def mac2str(mac):
# type: (str) -> bytes
return b"".join(chb(int(x, 16)) for x in plain_str(mac).split(':'))
def valid_mac(mac):
# type: (str) -> bool
try:
return len(mac2str(mac)) == 6
except ValueError:
pass
return False
def str2mac(s):
# type: (bytes) -> str
if isinstance(s, str):
return ("%02x:" * len(s))[:-1] % tuple(map(ord, s))
return ("%02x:" * len(s))[:-1] % tuple(s)
def randstring(length):
# type: (int) -> bytes
"""
Returns a random string of length (length >= 0)
"""
return b"".join(struct.pack('B', random.randint(0, 255))
for _ in range(length))
def zerofree_randstring(length):
# type: (int) -> bytes
"""
Returns a random string of length (length >= 0) without zero in it.
"""
return b"".join(struct.pack('B', random.randint(1, 255))
for _ in range(length))
def strxor(s1, s2):
# type: (bytes, bytes) -> bytes
"""
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: chb(orb(x) ^ orb(y)), s1, s2))
def strand(s1, s2):
# type: (bytes, bytes) -> bytes
"""
Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2
must be of same length.
"""
return b"".join(map(lambda x, y: chb(orb(x) & orb(y)), s1, s2))
# Workaround bug 643005 : https://sourceforge.net/tracker/?func=detail&atid=105470&aid=643005&group_id=5470 # noqa: E501
try:
socket.inet_aton("255.255.255.255")
except socket.error:
def inet_aton(ip_string):
# type: (str) -> bytes
if ip_string == "255.255.255.255":
return b"\xff" * 4
else:
return socket.inet_aton(ip_string)
else:
inet_aton = socket.inet_aton # type: ignore
inet_ntoa = socket.inet_ntoa
def atol(x):
# type: (str) -> int
try:
ip = inet_aton(x)
except socket.error:
ip = inet_aton(socket.gethostbyname(x))
return cast(int, struct.unpack("!I", ip)[0])
def valid_ip(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
try:
atol(addr)
except (OSError, ValueError, socket.error):
return False
return True
def valid_net(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
if '/' in addr:
ip, mask = addr.split('/', 1)
return valid_ip(ip) and mask.isdigit() and 0 <= int(mask) <= 32
return valid_ip(addr)
def valid_ip6(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
try:
inet_pton(socket.AF_INET6, addr)
except socket.error:
try:
socket.getaddrinfo(addr, None, socket.AF_INET6)[0][4][0]
except socket.error:
return False
return True
def valid_net6(addr):
# type: (str) -> bool
try:
addr = plain_str(addr)
except UnicodeDecodeError:
return False
if '/' in addr:
ip, mask = addr.split('/', 1)
return valid_ip6(ip) and mask.isdigit() and 0 <= int(mask) <= 128
return valid_ip6(addr)
def ltoa(x):
# type: (int) -> str
return inet_ntoa(struct.pack("!I", x & 0xffffffff))
def itom(x):
# type: (int) -> int
return (0xffffffff00000000 >> x) & 0xffffffff
class ContextManagerSubprocess(object):
"""
Context manager that eases checking for unknown command, without
crashing.
Example:
>>> with ContextManagerSubprocess("tcpdump"):
>>> subprocess.Popen(["tcpdump", "--version"])
ERROR: Could not execute tcpdump, is it installed?
"""
def __init__(self, prog, suppress=True):
# type: (str, bool) -> None
self.prog = prog
self.suppress = suppress
def __enter__(self):
# type: () -> None
pass
def __exit__(self,
exc_type, # type: Optional[type]
exc_value, # type: Optional[Exception]
traceback, # type: Optional[Any]
):
# type: (...) -> Optional[bool]
if exc_value is None or exc_type is None:
return None
# Errored
if isinstance(exc_value, EnvironmentError):
msg = "Could not execute %s, is it installed?" % self.prog
else:
msg = "%s: execution failed (%s)" % (
self.prog,
exc_type.__class__.__name__
)
if not self.suppress:
raise exc_type(msg)
log_runtime.error(msg, exc_info=True)
return True # Suppress the exception
class ContextManagerCaptureOutput(object):
"""
Context manager that intercept the console's output.
Example:
>>> with ContextManagerCaptureOutput() as cmco:
... print("hey")
... assert cmco.get_output() == "hey"
"""
def __init__(self):
# type: () -> None
self.result_export_object = ""
try:
import mock # noqa: F401
except Exception:
raise ImportError("The mock module needs to be installed !")
def __enter__(self):
# type: () -> ContextManagerCaptureOutput
import mock
def write(s, decorator=self):
# type: (str, ContextManagerCaptureOutput) -> None
decorator.result_export_object += s
mock_stdout = mock.Mock()
mock_stdout.write = write
self.bck_stdout = sys.stdout
sys.stdout = mock_stdout
return self
def __exit__(self, *exc):
# type: (*Any) -> Literal[False]
sys.stdout = self.bck_stdout
return False
def get_output(self, eval_bytes=False):
# type: (bool) -> str
if self.result_export_object.startswith("b'") and eval_bytes:
return plain_str(eval(self.result_export_object))
return self.result_export_object
def do_graph(
graph, # type: str
prog=None, # type: Optional[str]
format=None, # type: Optional[str]
target=None, # type: Optional[Union[IO[bytes], str]]
type=None, # type: Optional[str]
string=None, # type: Optional[bool]
options=None # type: Optional[List[str]]
):
# type: (...) -> Optional[str]
"""Processes graph description using an external software.
This method is used to convert a graphviz format to an image.
:param graph: GraphViz graph description
:param prog: which graphviz program to use
:param format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T"
option
:param string: if not None, simply return the graph string
:param target: filename or redirect. Defaults pipe to Imagemagick's
display program
:param options: options to be passed to prog
"""
if format is None:
format = "svg"
if string:
return graph
if type is not None:
warnings.warn(
"type is deprecated, and was renamed format",
DeprecationWarning
)
format = type
if prog is None:
prog = conf.prog.dot
start_viewer = False
if target is None:
if WINDOWS:
target = get_temp_file(autoext="." + format)
start_viewer = True
else:
with ContextManagerSubprocess(conf.prog.display):
target = subprocess.Popen([conf.prog.display],
stdin=subprocess.PIPE).stdin
if format is not None:
format = "-T%s" % format
if isinstance(target, str):
if target.startswith('|'):
target = subprocess.Popen(target[1:].lstrip(), shell=True,
stdin=subprocess.PIPE).stdin
elif target.startswith('>'):
target = open(target[1:].lstrip(), "wb")
else:
target = open(os.path.abspath(target), "wb")
target = cast(IO[bytes], target)
proc = subprocess.Popen(
"\"%s\" %s %s" % (prog, options or "", format or ""),
shell=True, stdin=subprocess.PIPE, stdout=target,
stderr=subprocess.PIPE
)
_, stderr = proc.communicate(bytes_encode(graph))
if proc.returncode != 0:
raise OSError(
"GraphViz call failed (is it installed?):\n" +
plain_str(stderr)
)
try:
target.close()
except Exception:
pass
if start_viewer:
# Workaround for file not found error: We wait until tempfile is written. # noqa: E501
waiting_start = time.time()
while not os.path.exists(target.name):
time.sleep(0.1)
if time.time() - waiting_start > 3:
warning("Temporary file '%s' could not be written. Graphic will not be displayed.", tempfile) # noqa: E501
break
else:
if WINDOWS and conf.prog.display == conf.prog._default:
os.startfile(target.name)
else:
with ContextManagerSubprocess(conf.prog.display):
subprocess.Popen([conf.prog.display, target.name])
return None
_TEX_TR = {
"{": "{\\tt\\char123}",
"}": "{\\tt\\char125}",
"\\": "{\\tt\\char92}",
"^": "\\^{}",
"$": "\\$",
"#": "\\#",
"_": "\\_",
"&": "\\&",
"%": "\\%",
"|": "{\\tt\\char124}",
"~": "{\\tt\\char126}",
"<": "{\\tt\\char60}",
">": "{\\tt\\char62}",
}
def tex_escape(x):
# type: (str) -> str
s = ""
for c in x:
s += _TEX_TR.get(c, c)
return s
def colgen(*lstcol, # type: Any
**kargs # type: Any
):
# type: (...) -> Iterator[Any]
"""Returns a generator that mixes provided quantities forever
trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default""" # noqa: E501
if len(lstcol) < 2:
lstcol *= 2
trans = kargs.get("trans", lambda x, y, z: (x, y, z))
while True:
for i in range(len(lstcol)):
for j in range(len(lstcol)):
for k in range(len(lstcol)):
if i != j or j != k or k != i:
yield trans(lstcol[(i + j) % len(lstcol)], lstcol[(j + k) % len(lstcol)], lstcol[(k + i) % len(lstcol)]) # noqa: E501
def incremental_label(label="tag%05i", start=0):
# type: (str, int) -> Iterator[str]
while True:
yield label % start
start += 1
def binrepr(val):
# type: (int) -> str
return bin(val)[2:]
def long_converter(s):
# type: (str) -> int
return int(s.replace('\n', '').replace(' ', ''), 16)
#########################
# Enum management #
#########################
class EnumElement:
def __init__(self, key, value):
# type: (str, int) -> None
self._key = key
self._value = value
def __repr__(self):
# type: () -> str
return "<%s %s[%r]>" % (self.__dict__.get("_name", self.__class__.__name__), self._key, self._value) # noqa: E501
def __getattr__(self, attr):
# type: (str) -> Any
return getattr(self._value, attr)
def __str__(self):
# type: () -> str
return self._key
def __bytes__(self):
# type: () -> bytes
return bytes_encode(self.__str__())
def __hash__(self):
# type: () -> int
return self._value
def __int__(self):
# type: () -> int
return int(self._value)
def __eq__(self, other):
# type: (Any) -> bool
return self._value == int(other)
def __neq__(self, other):
# type: (Any) -> bool
return not self.__eq__(other)
class Enum_metaclass(type):
element_class = EnumElement
def __new__(cls, name, bases, dct):
# type: (Any, str, Any, Dict[str, Any]) -> Any
rdict = {}
for k, v in six.iteritems(dct):
if isinstance(v, int):
v = cls.element_class(k, v)
dct[k] = v
rdict[v] = k
dct["__rdict__"] = rdict
return super(Enum_metaclass, cls).__new__(cls, name, bases, dct)
def __getitem__(self, attr):
# type: (int) -> Any
return self.__rdict__[attr] # type: ignore
def __contains__(self, val):
# type: (int) -> bool