This repository has been archived by the owner on Aug 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzio3.py
executable file
·2328 lines (1955 loc) · 82.2 KB
/
zio3.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
#!/usr/bin/env python3
# Mainly borrowed from pexpect. Thanks very much!
__version__ = "3.0.4"
__project__ = "https://github.com/alset0326/zio3"
import struct
import socket
import os
import sys
import pty
import time
import re
import select
import termios
import resource
import tty
import errno
import signal
import fcntl
import platform
import datetime
import inspect
import atexit
import ast
import binascii
import abc
import stat
import itertools
from io import BytesIO
from functools import wraps
import builtins
__all__ = ['l8', 'b8', 'l16', 'b16', 'l32', 'b32', 'l64', 'b64', 'zio', 'EOF', 'TIMEOUT', 'SOCKET', 'PROCESS', 'REPR',
'EVAL', 'HEX', 'UNHEX', 'BIN', 'UNBIN', 'RAW', 'NONE', 'COLORED', 'PIPE', 'TTY', 'TTY_RAW',
'ensure_str', 'ensure_bytes', 'create_zio']
# OS constants
POSIX = os.name == "posix"
WINDOWS = os.name == "nt"
LINUX = sys.platform.startswith("linux")
OSX = sys.platform.startswith("darwin")
FREEBSD = sys.platform.startswith("freebsd")
OPENBSD = sys.platform.startswith("openbsd")
NETBSD = sys.platform.startswith("netbsd")
BSD = FREEBSD or OPENBSD or NETBSD
SUNOS = sys.platform.startswith("sunos") or sys.platform.startswith("solaris")
AIX = sys.platform.startswith("aix")
if WINDOWS:
raise Exception("zio (version %s) process mode is currently only supported on linux and osx." % __version__)
# Define pack functions
def _lb_wrapper(func):
endian = func.__name__[0] == 'l' and '<' or '>'
bits = int(func.__name__[1:])
pfs = {8: 'B', 16: 'H', 32: 'I', 64: 'Q'}
@wraps(func)
def wrapper(*args):
ret = []
join = False
for i in args:
if isinstance(i, int):
join = True
v = struct.pack(endian + pfs[bits], i % (1 << bits))
ret.append(v)
elif not i:
ret.append(None)
else:
i = ensure_bytes(i)
v = struct.unpack(endian + pfs[bits] * (len(i) * 8 // bits), i)
ret += v
if join:
return b''.join(ret)
elif len(ret) == 1:
return ret[0]
elif len(ret) == 0: # all of the input are empty strings
return None
else:
return ret
return wrapper
@_lb_wrapper
def l8(*args): pass
@_lb_wrapper
def b8(*args): pass
@_lb_wrapper
def l16(*args): pass
@_lb_wrapper
def b16(*args): pass
@_lb_wrapper
def l32(*args): pass
@_lb_wrapper
def b32(*args): pass
@_lb_wrapper
def l64(*args): pass
@_lb_wrapper
def b64(*args): pass
# pwntools style
p32 = l32
u32 = l32
p64 = l64
u64 = l64
# Define trigger exceptions
class EOF(Exception):
"""Raised when EOF is read from child or socket.
This usually means the child has exited or socket shutdown at remote end"""
class TIMEOUT(Exception):
"""Raised when a read timeout exceeds the timeout. """
# Define consts
SOCKET = 'socket' # zio mode socket
PROCESS = 'process' # zio mode process
PIPE = 'pipe' # io mode (process io): send all characters untouched, but use PIPE, so libc cache may apply
TTY = 'tty' # io mode (process io): normal tty behavier, support Ctrl-C to terminate, and auto \r\n to display more readable lines for human
TTY_RAW = 'ttyraw' # io mode (process io): send all characters just untouched
# Define print functions. They dealing with bytes not str
ensure_bytes = lambda s: s and (isinstance(s, bytes) and s or s.encode('latin-1')) or b''
b = ensure_bytes
def ensure_str(s, encoding=sys.getdefaultencoding()):
if s and isinstance(s, str):
return s
if s and isinstance(s, bytes):
try:
return s.decode(encoding)
except UnicodeDecodeError:
return s.decode('latin-1')
return ''
s = ensure_str
# colored needed consts
ATTRIBUTES = dict(
list(zip(['bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed'], list(range(1, 9))))
)
del ATTRIBUTES['']
HIGHLIGHTS = dict(
list(zip(['on_grey', 'on_red', 'on_green', 'on_yellow', 'on_blue', 'on_magenta', 'on_cyan', 'on_white'],
list(range(40, 48))))
)
COLORS = dict(
list(zip(['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ],
list(range(30, 38)))))
RESET = b'\033[0m'
def colored(text: bytes, color: str = None, on_color: str = None, attrs: str = None):
""" colored copied from termcolor v1.1.0 changing to bytes
Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv('ANSI_COLORS_DISABLED') is None:
fmt_str = b'\033[%dm%s'
if color is not None:
text = fmt_str % (COLORS[color], text)
if on_color is not None:
text = fmt_str % (HIGHLIGHTS[on_color], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
def stdout(s: bytes, color=None, on_color=None, attrs=None):
"""Write bytes to stdout"""
if not color:
sys.stdout.buffer.write(s)
else:
sys.stdout.buffer.write(colored(s, color, on_color, attrs))
sys.stdout.flush()
def log(s, color=None, on_color=None, attrs=None, new_line=True, timestamp=False, f=sys.stderr):
s = ensure_bytes(s)
if timestamp is True:
now = ensure_bytes(datetime.datetime.now().strftime('[%Y-%m-%d_%H:%M:%S]'))
elif timestamp is False:
now = None
elif timestamp:
now = timestamp
else:
now = None
if color:
s = colored(s, color, on_color, attrs)
if now:
f.buffer.write(now)
f.buffer.write(b' ')
f.buffer.write(s)
if new_line:
f.buffer.write(b'\n')
f.flush()
def COLORED(f, color='cyan', on_color=None, attrs=None): return lambda s: colored(f(s), color, on_color, attrs)
def REPR(s): return ensure_bytes(repr(s)) + b'\r\n'
def EVAL(s): # now you are not worried about pwning yourself
return ast.literal_eval(s)
def HEX(s): return binascii.b2a_hex(s) + b'\r\n'
# hex-strings with odd length are now acceptable
def UNHEX(s): s = s.strip(); return binascii.a2b_hex(len(s) % 2 and b'0' + s or s)
def BIN(s): return ensure_bytes(''.join((bin(x)[2:] for x in s)) + '\r\n')
def UNBIN(s): s = s.strip(); return b''.join((bytes((int(s[i:i + 8], 2),)) for i in range(0, len(s), 8)))
def RAW(s): return s
def NONE(s): raise Exception("I'm NONE why call me?")
# Define zio base class
class ZioBase(object, metaclass=abc.ABCMeta):
"""
|
| str/bytes <-> user API
|-----------
| bytes -> class buffer
|-----------
| bytes -> syscall read/write, stdout
|
"""
linesep = ensure_bytes(os.linesep)
allowed_string_types = (bytes, str)
string_type = bytes
buffer_type = BytesIO # Expecter used
STDIN_FILENO = pty.STDIN_FILENO
STDOUT_FILENO = pty.STDOUT_FILENO
STDERR_FILENO = pty.STDERR_FILENO
def __init__(self, target, *, print_read=RAW, print_write=RAW, timeout=8, write_delay=0.05, ignorecase=False,
debug=None):
if not target:
raise Exception('cmdline or socket not provided for zio, try zio("ls -l")')
# Store args
self.debug = debug
self.target = target
self.print_read = print_read
self.print_write = print_write
self.ignorecase = ignorecase
if isinstance(timeout, int) and timeout > 0:
self.timeout = timeout
else:
self.timeout = 8
self.write_delay = write_delay # the delay before writing data, pexcept said Linux don't like this to be below 30ms
self.close_delay = 0.1 # like pexcept, will used by close(), to give kernel time to update process status, time in seconds
self.terminate_delay = 0.1 # like close_delay
# Init inside variables
# close and eof flag
self.flag_eof = False
self.closed = True
# fileno
self.readfd = -1
self.writefd = -1
# core buffer
self._buffer = self.buffer_type()
# search result
self.before = self.after = self.match = self.string_type()
self.match_index = None
# max bytes to read at one time into buffer
self.maxread = 2000
# Delay in seconds to sleep after each call to read_nonblocking().
self.delayafterread = None
# Data before searchwindowsize point is preserved, but not searched.
self.searchwindowsize = None
# Define properties
@property
def buffer(self):
return self._buffer.getvalue()
@buffer.setter
def buffer(self, value):
self._buffer = self.buffer_type()
self._buffer.write(value)
@property
def print_read(self):
return self._print_read and (self._print_read is not NONE)
@print_read.setter
def print_read(self, value):
if value is True:
self._print_read = RAW
elif value is False:
self._print_read = NONE
elif callable(value):
self._print_read = value
else:
raise Exception('Bad print_read value')
assert callable(self._print_read) and len(inspect.getfullargspec(self._print_read).args) == 1
@property
def print_write(self):
return self._print_write and (self._print_write is not NONE)
@print_write.setter
def print_write(self, value):
if value is True:
self._print_write = RAW
elif value is False:
self._print_write = NONE
elif callable(value):
self._print_write = value
else:
raise Exception('Bad print_write value')
assert callable(self._print_write) and len(inspect.getfullargspec(self._print_write).args) == 1
# Define flag functions
def eof(self):
"""This returns True if the EOF exception was ever raised.
"""
return self.flag_eof
def flush(self):
"""
just keep to be a file-like object
"""
pass
# Define write functions
def _pattern_type_err(self, pattern):
"""Copy from pexpect"""
raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one of: {goodtypes}, zio3.EOF, zio3.TIMEOUT'
.format(badtype=type(pattern), badobj=pattern,
goodtypes=', '.join([str(ast) for ast in self.allowed_string_types])))
def write(self, s):
"""
:param s: bytes/str
:return: len
"""
if not s: return 0
s = ensure_bytes(s)
if self.print_write:
stdout(self._print_write(s))
return self._write(s)
def writeline(self, s=''):
"""
:param s: str/bytes
:return: len (include linesep)
"""
s = ensure_bytes(s)
return self.write(s + self.linesep)
def writelines(self, sequence):
"""
:param sequence: list/tuple
:return: len (include linesep)
"""
return sum((self.writeline(i) for i in sequence))
# Define read functions
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=None):
"""Expect string list. Copy from pexpect expect_exact. Return match index."""
if timeout == -1:
timeout = self.timeout
if (isinstance(pattern_list, self.allowed_string_types) or
pattern_list in (TIMEOUT, EOF)):
pattern_list = [pattern_list]
def prepare_pattern(pattern):
if pattern in (TIMEOUT, EOF):
return pattern
if isinstance(pattern, self.allowed_string_types):
return ensure_bytes(pattern)
self._pattern_type_err(pattern)
try:
pattern_list = iter(pattern_list)
except TypeError:
self._pattern_type_err(pattern_list)
pattern_list = [prepare_pattern(p) for p in pattern_list]
exp = Expecter(self, searcher_string(pattern_list), searchwindowsize)
return exp.expect_loop(timeout)
def compile_pattern_list(self, patterns):
"""Copy from pexpect compile_pattern_list"""
if patterns is None:
return []
if not isinstance(patterns, list):
patterns = [patterns]
# Allow dot to match \n
compile_flags = re.DOTALL
if self.ignorecase:
compile_flags = compile_flags | re.IGNORECASE
compiled_pattern_list = []
for idx, p in enumerate(patterns):
if isinstance(p, self.allowed_string_types):
p = ensure_bytes(p)
compiled_pattern_list.append(re.compile(p, compile_flags))
elif p is EOF:
compiled_pattern_list.append(EOF)
elif p is TIMEOUT:
compiled_pattern_list.append(TIMEOUT)
elif isinstance(p, type(re.compile(''))):
compiled_pattern_list.append(p)
else:
self._pattern_type_err(p)
return compiled_pattern_list
def expect(self, pattern, timeout=-1, searchwindowsize=-1):
"""Expect re. Copy from pexpect expect. Return match index"""
compiled_pattern_list = self.compile_pattern_list(pattern)
return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
"""Expect re list. Copy from pexpect expect_list. Return match index"""
if timeout == -1:
timeout = self.timeout
exp = Expecter(self, searcher_re(pattern_list), searchwindowsize)
return exp.expect_loop(timeout)
def read_nonblocking(self, size=1, timeout=-1):
"""Copy from pexpect read_nonblocking"""
if self.closed:
raise ValueError('I/O operation on closed file.')
if timeout == -1:
timeout = self.timeout
# Note that some systems such as Solaris do not give an EOF when
# the child dies. In fact, you can still try to read
# from the child_fd -- it will block forever or until TIMEOUT.
# For this case, I test isalive() before doing any reading.
# If isalive() is false, then I pretend that this is the same as EOF.
if not self.isalive():
# timeout of 0 means "poll"
r, w, e = select_ignore_interrupts([self.readfd], [], [], 0)
if not r:
self.flag_eof = True
raise EOF('End Of File (EOF). Braindead platform.')
r, w, e = select_ignore_interrupts([self.readfd], [], [], timeout)
if not r:
if not self.isalive():
# Some platforms, such as Irix, will claim that their
# processes are alive; timeout on the select; and
# then finally admit that they are not alive.
self.flag_eof = True
raise EOF('End of File (EOF). Very slow platform.')
else:
raise TIMEOUT('Timeout exceeded.')
if self.readfd in r:
try:
s = self._read(size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
if self.print_read:
stdout(self._print_read(s))
return s
raise Exception('Reached an unexpected state.') # pragma: no cover
def read(self, size=-1, timeout=None):
"""Copy from pexpect read"""
if size == 0:
return self.string_type()
if size < 0:
# read until EOF
self.expect(EOF)
return self.before
cre = re.compile(ensure_bytes('.{%d}' % size), re.DOTALL)
index = self.expect([cre, EOF], timeout=timeout)
if index == 0:
# assert self.before == self.string_type() # Maybe not assert?
return self.after
return self.before
def read_until_timeout(self, timeout=0.05):
if timeout is not None and timeout > 0:
end_time = time.time() + timeout
else:
end_time = float('inf')
old_data = self.buffer
try:
while True:
now = time.time()
if now > end_time: break
if timeout is not None and timeout > 0:
timeout = end_time - now
old_data += self.read_nonblocking(2048, timeout)
except EOF:
err = sys.exc_info()[1]
self._buffer = self.buffer_type()
self.before = self.string_type()
self.after = EOF
self.match = old_data
self.match_index = None
raise EOF(str(err) + '\n' + str(self))
except TIMEOUT:
self._buffer = self.buffer_type()
self.before = self.string_type()
self.after = TIMEOUT
self.match = old_data
self.match_index = None
return old_data
except:
self.before = self.string_type()
self.after = None
self.match = old_data
self.match_index = None
raise
read_eager = read_until_timeout
# def readable(self):
# return select_ignore_interrupts([self.readfd], [], [], 0) == ([self.readfd], [], [])
def readline(self, size=-1):
"""Copy and modify from pexpect readline"""
if size == 0:
return self.string_type()
lineseps = [b'\r\n', b'\n', EOF]
index = self.expect(lineseps)
if index < 2:
return self.before + lineseps[index]
else:
return self.before
read_line = readline
def readlines(self, sizehint=sys.maxsize):
return [i for i in itertools.islice(iter(self.readline, b''), 0, sizehint)]
read_lines = readlines
def read_until(self, pattern_list, timeout=-1, searchwindowsize=None):
matched = self.expect_exact(pattern_list, timeout, searchwindowsize)
ret = self.before
if isinstance(self.after, self.string_type):
ret += self.after # after is the matched string, before is the string before this match
return ret # be compatible with telnetlib.read_until
readuntil = read_until
def read_until_re(self, pattern, timeout=-1, searchwindowsize=None):
matched = self.expect(pattern, timeout, searchwindowsize)
ret = self.before
if isinstance(self.after, self.string_type):
ret += self.after
return ret
readuntilre = read_until_re
# Combinations, from pwntools
def writeafter(self, pattern, data, timeout=-1, searchwindowsize=None):
try:
return self.read_until(pattern, timeout, searchwindowsize)
finally:
self.write(data)
def writelineafter(self, pattern, data, timeout=-1, searchwindowsize=None):
try:
return self.read_until(pattern, timeout, searchwindowsize)
finally:
self.writeline(data)
def writethen(self, pattern, data, timeout=-1, searchwindowsize=None):
self.write(data)
return self.read_until(pattern, timeout, searchwindowsize)
def writelinethen(self, pattern, data, timeout=-1, searchwindowsize=None):
self.writeline(data)
return self.read_until(pattern, timeout, searchwindowsize)
def gdb_hint(self, breakpoints=None, relative=None, extras=None):
# disable timeout while using gdb_hint
self.timeout = None
pid = self.pid
if not pid:
input('[ WARN ] pid unavailable to attach gdb, please find out the pid by your own. '
'Press enter to continue ...')
return
hints = ['attach %d' % pid]
base = 0
if relative:
vmmap = open('/proc/%d/maps' % pid).read()
for line in vmmap.splitlines():
if line.lower().find(relative.lower()) > -1:
base = int(line.split('-')[0], 16)
break
if breakpoints:
for b in breakpoints:
hints.append('b *' + hex(base + b))
if extras:
for e in extras:
hints.append(str(e))
gdb = 'gdb' + ''.join((' -eval-command "' + i + '"' for i in hints)) + \
'\nuse cmdline above to attach gdb then press enter to continue ...'
input(gdb)
@abc.abstractmethod
def terminate(self, force=False):
pass
@abc.abstractmethod
def wait(self):
pass
@abc.abstractmethod
def isalive(self):
pass
@abc.abstractmethod
def interact(self, escape_character=None, input_filter=None, output_filter=None, raw_rw=True):
pass
@abc.abstractmethod
def end(self, force_close=False):
pass
@abc.abstractmethod
def close(self, force=True):
pass
@abc.abstractmethod
def _read(self, size):
pass
@abc.abstractmethod
def _write(self, s):
pass
@property
@abc.abstractmethod
def pid(self):
pass
# not impl should at last
def _not_impl(self, hint="Not Implemented"):
raise NotImplementedError(hint)
# apis below
read_after = read_before = read_between = read_range = _not_impl
# pwntools style
recv = read
recvuntil = read_until
recvlines = readlines
recvline = readline
recvregex = read_until_re
recvall = read
send = write
sendline = writeline
sendlines = writelines
sendafter = writeafter
sendlineafter = writelineafter
sendthen = writethen
sendlinethen = writelinethen
def interaction(self, escape_character=None, input_filter=None, output_filter=None, raw_rw=True):
self.interact(escape_character, input_filter, output_filter, raw_rw)
class ZioSocket(ZioBase):
def __init__(self, target, *, print_read=RAW, print_write=RAW, timeout=8, write_delay=0.05, ignorecase=False,
debug=None):
super().__init__(target, print_read=print_read, print_write=print_write, timeout=timeout,
write_delay=write_delay, ignorecase=ignorecase, debug=debug)
if isinstance(self.target, socket.socket):
self.sock = self.target
self.name = repr(self.target)
else:
self.sock = socket.create_connection(self.target, self.timeout)
self.name = '<socket ' + self.target[0] + ':' + str(self.target[1]) + '>'
self.readfd = self.writefd = self.sock.fileno()
self.closed = False
def __str__(self):
ret = ['io-mode: SOCKET',
'name: {}'.format(self.name),
'timeout: {}'.format(self.timeout),
'write-fd: {}'.format(self.writefd),
'read-fd: {}'.format(self.readfd),
'buffer(last 100 chars): {}'.format(repr(ensure_str(self.buffer[-100:]))),
'eof: {}'.format(self.flag_eof)]
return '\n'.join(ret)
def terminate(self, force=False):
self.close()
def wait(self):
return self.read_until_timeout()
def isalive(self):
"""This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exit code or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to return the right status. """
return not self.flag_eof
def interact(self, escape_character=None, input_filter=None, output_filter=None, raw_rw=True):
if self.print_read: stdout(self._print_read(self.buffer))
self._buffer = self.buffer_type()
if escape_character is not None:
escape_character = ensure_bytes(escape_character)
while self.isalive():
r, w, e = select_ignore_interrupts([self.readfd, self.STDIN_FILENO], [], [])
if self.readfd in r:
try:
data = self._read(1024)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
break
raise
if data == b'':
# BSD-style EOF
self.flag_eof = True
break
if output_filter:
data = output_filter(data)
stdout(raw_rw and data or self._print_read(data))
if self.STDIN_FILENO in r:
data = os.read(self.STDIN_FILENO, 1024)
if input_filter:
data = input_filter(data)
i = -1
if escape_character is not None:
i = data.rfind(escape_character)
if i != -1:
data = data[:i]
self._write(data)
break
self._write(data)
def end(self, force_close=False):
"""
end of writing stream, but we can still read
"""
self.sock.shutdown(socket.SHUT_WR)
def close(self, force=True):
"""
close and clean up, nothing can and should be done after closing
"""
if self.closed:
return
if self.sock:
self.sock.close()
self.sock = None
self.flag_eof = True
self.closed = True
self.readfd = -1
self.writefd = -1
def _read(self, size):
try:
return self.sock.recv(size)
except socket.error as err:
if err.args[0] == errno.ECONNRESET:
raise EOF('Connection reset by peer')
raise err
def _write(self, s):
self.sock.sendall(s)
return len(s)
@property
def pid(self):
# code borrowed from https://github.com/Gallopsled/pwntools to implement gdb attach of local socket
if OSX:
# osx cannot get pid of a socket yet
return None
def toaddr(arg: tuple):
"""
(host, port)
:return:
"""
return '%08X:%04X' % (l32(socket.inet_aton(arg[0])), arg[1])
def getpid(loc, rem):
loc = toaddr(loc)
rem = toaddr(rem)
inode = 0
with open('/proc/net/tcp') as fd:
for line in fd:
line = line.split()
if line[1] == loc and line[2] == rem:
inode = line[9]
if inode == 0:
return []
for pid in all_pids():
try:
for fd in os.listdir('/proc/%d/fd' % pid):
fd = os.readlink('/proc/%d/fd/%s' % (pid, fd))
m = re.match('socket:\[(\d+)\]', fd)
if m:
this_inode = m.group(1)
if this_inode == inode:
return pid
except:
pass
sock = self.sock.getsockname()
peer = self.sock.getpeername()
pids = [getpid(peer, sock), getpid(sock, peer)]
if pids[0]: return pids[0]
if pids[1]: return pids[1]
return None
class ZioProcess(ZioBase):
CHILD = pty.CHILD
def __init__(self, target, *, stdin=PIPE, stdout=TTY_RAW, print_read=RAW, print_write=RAW, timeout=8, cwd=None,
env=None, sighup=signal.SIG_DFL, write_delay=0.05, ignorecase=False, debug=None):
super().__init__(target, print_read=print_read, print_write=print_write, timeout=timeout,
write_delay=write_delay, ignorecase=ignorecase, debug=debug)
self.stdin = stdin
self.stdout = stdout
self.cwd = cwd
self.env = env
self.sighup = sighup
# Set exit code
self.exit_code = None
# spawn process below
self.child_pid = None
self.closed = False
if isinstance(target, bytes):
target = ensure_str(target)
elif isinstance(target, tuple):
target = list(target)
if isinstance(target, str):
self.args = split_command_line(target)
self.command = self.args[0]
elif isinstance(target, list):
self.args = target
self.command = self.args[0]
else:
raise Exception('Unknown target type')
command_with_path = which(self.command)
if command_with_path is None:
raise Exception('zio (process mode) Command not found in path: %s' % self.command)
self.command = command_with_path
self.args[0] = self.command
self.name = '<' + ' '.join(self.args) + '>'
# Delay in seconds to sleep after each call to read_nonblocking().
# Set this to None to skip the time.sleep() call completely: that
# would restore the behavior from pexpect-2.0 (for performance
# reasons or because you don't want to release Python's global
# interpreter lock).
self.delayafterread = 0.0001
self._spawn()
def _spawn(self):
exec_err_pipe_read, exec_err_pipe_write = os.pipe()
if self.stdout == PIPE:
stdout_slave_fd, stdout_master_fd = self.pipe_cloexec()
else:
stdout_master_fd, stdout_slave_fd = pty.openpty()
if stdout_master_fd < 0 or stdout_slave_fd < 0: raise Exception(
'Could not create pipe or openpty for stdout/stderr')
# use another pty for stdin because we don't want our input to be echoed back in stdout
# set echo off does not help because in application like ssh, when you input the password
# echo will be switched on again
# and dont use os.pipe either, because many thing weired will happen, such as baskspace not working, ssh lftp command hang
stdin_master_fd, stdin_slave_fd = self.stdin == PIPE and self.pipe_cloexec() or pty.openpty()
if stdin_master_fd < 0 or stdin_slave_fd < 0: raise Exception('Could not openpty for stdin')
pid = os.fork()
if pid < 0:
raise Exception('failed to fork')
elif pid == self.CHILD: # Child
os.close(stdout_master_fd)
if os.isatty(stdin_slave_fd):
self._pty_make_controlling_tty(stdin_slave_fd)
# Dup fds for child
def _dup2(a, b):
# dup2() removes the CLOEXEC flag but
# we must do it ourselves if dup2()
# would be a no-op (python issue #10806).
if a == b:
self._set_cloexec_flag(a, False)
elif a is not None:
os.dup2(a, b)
# redirect stdout and stderr to pty
os.dup2(stdout_slave_fd, self.STDOUT_FILENO)