• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3# Copyright 2015 gRPC authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""Read from stdin a set of colon separated http headers:
17   :path: /foo/bar
18   content-type: application/grpc
19   Write a set of strings containing a hpack encoded http2 frame that
20   represents said headers."""
21
22import argparse
23import json
24import sys
25
26
27def append_never_indexed(payload_line, n, count, key, value, value_is_huff):
28    payload_line.append(0x10)
29    assert len(key) <= 126
30    payload_line.append(len(key))
31    payload_line.extend(ord(c) for c in key)
32    assert len(value) <= 126
33    payload_line.append(len(value) + (0x80 if value_is_huff else 0))
34    payload_line.extend(value)
35
36
37def append_inc_indexed(payload_line, n, count, key, value, value_is_huff):
38    payload_line.append(0x40)
39    assert len(key) <= 126
40    payload_line.append(len(key))
41    payload_line.extend(ord(c) for c in key)
42    assert len(value) <= 126
43    payload_line.append(len(value) + (0x80 if value_is_huff else 0))
44    payload_line.extend(value)
45
46
47def append_pre_indexed(payload_line, n, count, key, value, value_is_huff):
48    assert not value_is_huff
49    payload_line.append(0x80 + 61 + count - n)
50
51
52def esc_c(line):
53    out = '"'
54    last_was_hex = False
55    for c in line:
56        if 32 <= c < 127:
57            if c in hex_bytes and last_was_hex:
58                out += '""'
59            if c != ord('"'):
60                out += chr(c)
61            else:
62                out += '\\"'
63            last_was_hex = False
64        else:
65            out += "\\x%02x" % c
66            last_was_hex = True
67    return out + '"'
68
69
70def output_c(payload_bytes):
71    for line in payload_bytes:
72        print((esc_c(line)))
73
74
75def output_hex(payload_bytes):
76    all_bytes = []
77    for line in payload_bytes:
78        all_bytes.extend(line)
79    print(("{%s}" % ", ".join("0x%02x" % c for c in all_bytes)))
80
81
82def output_hexstr(payload_bytes):
83    all_bytes = []
84    for line in payload_bytes:
85        all_bytes.extend(line)
86    print(("%s" % "".join("%02x" % c for c in all_bytes)))
87
88
89_COMPRESSORS = {
90    "never": append_never_indexed,
91    "inc": append_inc_indexed,
92    "pre": append_pre_indexed,
93}
94
95_OUTPUTS = {
96    "c": output_c,
97    "hex": output_hex,
98    "hexstr": output_hexstr,
99}
100
101argp = argparse.ArgumentParser("Generate header frames")
102argp.add_argument(
103    "--set_end_stream", default=False, action="store_const", const=True
104)
105argp.add_argument(
106    "--no_framing", default=False, action="store_const", const=True
107)
108argp.add_argument(
109    "--compression", choices=sorted(_COMPRESSORS.keys()), default="never"
110)
111argp.add_argument("--huff", default=False, action="store_const", const=True)
112argp.add_argument("--output", default="c", choices=sorted(_OUTPUTS.keys()))
113args = argp.parse_args()
114
115# parse input, fill in vals
116vals = []
117for line in sys.stdin:
118    line = line.strip()
119    if line == "":
120        continue
121    if line[0] == "#":
122        continue
123    key_tail, value = line[1:].split(":")
124    key = (line[0] + key_tail).strip()
125    value = value.strip().encode("ascii")
126    if args.huff:
127        from hpack.huffman import HuffmanEncoder
128        from hpack.huffman_constants import REQUEST_CODES
129        from hpack.huffman_constants import REQUEST_CODES_LENGTH
130
131        value = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH).encode(
132            value
133        )
134    vals.append((key, value))
135
136# generate frame payload binary data
137payload_bytes = []
138if not args.no_framing:
139    payload_bytes.append([])  # reserve space for header
140payload_len = 0
141n = 0
142for key, value in vals:
143    payload_line = []
144    _COMPRESSORS[args.compression](
145        payload_line, n, len(vals), key, value, args.huff
146    )
147    n += 1
148    payload_len += len(payload_line)
149    payload_bytes.append(payload_line)
150
151# fill in header
152if not args.no_framing:
153    flags = 0x04  # END_HEADERS
154    if args.set_end_stream:
155        flags |= 0x01  # END_STREAM
156    payload_bytes[0].extend(
157        [
158            (payload_len >> 16) & 0xFF,
159            (payload_len >> 8) & 0xFF,
160            (payload_len) & 0xFF,
161            # header frame
162            0x01,
163            # flags
164            flags,
165            # stream id
166            0x00,
167            0x00,
168            0x00,
169            0x01,
170        ]
171    )
172
173hex_bytes = [ord(c) for c in "abcdefABCDEF0123456789"]
174
175# dump bytes
176_OUTPUTS[args.output](payload_bytes)
177