-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
httpcat.py
executable file
·116 lines (93 loc) · 2.4 KB
/
httpcat.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
#!/usr/bin/env python3
"""
Create raw HTTP requests on the command line.
"""
import sys
import argparse
from signal import signal, SIGPIPE, SIG_DFL
__author__ = 'Jakub Roztocil'
__version__ = '0.0.2'
__licence__ = 'BSD'
signal(SIGPIPE, SIG_DFL)
EOF = ''
CRLF = '\r\n'
def httpcat(initial_lines=sys.argv[1:],
infile=sys.stdin,
outfile=sys.stdout,
logfile=sys.stderr,
verbose=False):
class sent:
request_line = False
headers = False
def log(msg, prefix='> '):
if verbose:
logfile.write(prefix + msg.rstrip() + '\n')
logfile.flush()
def write_line(line):
if not sent.request_line:
sent.request_line = True
line = line.strip()
if line.startswith('/'):
line = 'GET ' + line
if 'HTTP/' not in line:
line += ' HTTP/1.1'
return write_line(line)
elif not sent.headers:
if not line.endswith(CRLF):
line = line.rstrip() + CRLF
elif line == EOF:
return False
outfile.write(line)
outfile.flush()
if sent.headers:
log(line)
else:
log(repr(line).strip("'"))
if line == CRLF:
sent.headers = True
return True
try:
for line in initial_lines:
write_line(line)
if infile:
while write_line(infile.readline()):
pass
except KeyboardInterrupt:
pass
parser = argparse.ArgumentParser(
description=__doc__.strip(),
epilog='project homepage: https://github.com/jakubroztocil/httpcat',
)
parser.add_argument(
'-V, --version',
action='version',
version=__version__,
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='print info about output lines to stderr',
)
parser.add_argument(
'lines',
metavar='line',
nargs=argparse.ZERO_OR_MORE,
help='input lines read before lines from stdin',
)
parser.add_argument(
'-n',
'--no-stdin',
dest='read_stdin',
action='store_false',
default=True,
help='disable reading of lines from stdin',
)
def main():
args = parser.parse_args()
httpcat(
initial_lines=args.lines,
infile=sys.stdin if args.read_stdin else None,
verbose=args.verbose
)
if __name__ == '__main__':
main()