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('--set_end_stream',
103                  default=False,
104                  action='store_const',
105                  const=True)
106argp.add_argument('--no_framing',
107                  default=False,
108                  action='store_const',
109                  const=True)
110argp.add_argument('--compression',
111                  choices=sorted(_COMPRESSORS.keys()),
112                  default='never')
113argp.add_argument('--huff', default=False, action='store_const', const=True)
114argp.add_argument('--output', default='c', choices=sorted(_OUTPUTS.keys()))
115args = argp.parse_args()
116
117# parse input, fill in vals
118vals = []
119for line in sys.stdin:
120    line = line.strip()
121    if line == '':
122        continue
123    if line[0] == '#':
124        continue
125    key_tail, value = line[1:].split(':')
126    key = (line[0] + key_tail).strip()
127    value = value.strip().encode('ascii')
128    if args.huff:
129        from hpack.huffman import HuffmanEncoder
130        from hpack.huffman_constants import REQUEST_CODES
131        from hpack.huffman_constants import REQUEST_CODES_LENGTH
132        value = HuffmanEncoder(REQUEST_CODES,
133                               REQUEST_CODES_LENGTH).encode(value)
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](payload_line, n, len(vals), key, value,
145                                   args.huff)
146    n += 1
147    payload_len += len(payload_line)
148    payload_bytes.append(payload_line)
149
150# fill in header
151if not args.no_framing:
152    flags = 0x04  # END_HEADERS
153    if args.set_end_stream:
154        flags |= 0x01  # END_STREAM
155    payload_bytes[0].extend([
156        (payload_len >> 16) & 0xff,
157        (payload_len >> 8) & 0xff,
158        (payload_len) & 0xff,
159        # header frame
160        0x01,
161        # flags
162        flags,
163        # stream id
164        0x00,
165        0x00,
166        0x00,
167        0x01
168    ])
169
170hex_bytes = [ord(c) for c in "abcdefABCDEF0123456789"]
171
172# dump bytes
173_OUTPUTS[args.output](payload_bytes)
174