1#!/usr/bin/env python2.7
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 json
23import sys
24import argparse
25
26
27def append_never_indexed(payload_line, n, count, key, value):
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))
34    payload_line.extend(ord(c) for c in value)
35
36
37def append_inc_indexed(payload_line, n, count, key, value):
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))
44    payload_line.extend(ord(c) for c in value)
45
46
47def append_pre_indexed(payload_line, n, count, key, value):
48    payload_line.append(0x80 + 61 + count - n)
49
50
51_COMPRESSORS = {
52    'never': append_never_indexed,
53    'inc': append_inc_indexed,
54    'pre': append_pre_indexed,
55}
56
57argp = argparse.ArgumentParser('Generate header frames')
58argp.add_argument(
59    '--set_end_stream', default=False, action='store_const', const=True)
60argp.add_argument(
61    '--no_framing', default=False, action='store_const', const=True)
62argp.add_argument(
63    '--compression', choices=sorted(_COMPRESSORS.keys()), default='never')
64argp.add_argument('--hex', default=False, action='store_const', const=True)
65args = argp.parse_args()
66
67# parse input, fill in vals
68vals = []
69for line in sys.stdin:
70    line = line.strip()
71    if line == '': continue
72    if line[0] == '#': continue
73    key_tail, value = line[1:].split(':')
74    key = (line[0] + key_tail).strip()
75    value = value.strip()
76    vals.append((key, value))
77
78# generate frame payload binary data
79payload_bytes = []
80if not args.no_framing:
81    payload_bytes.append([])  # reserve space for header
82payload_len = 0
83n = 0
84for key, value in vals:
85    payload_line = []
86    _COMPRESSORS[args.compression](payload_line, n, len(vals), key, value)
87    n += 1
88    payload_len += len(payload_line)
89    payload_bytes.append(payload_line)
90
91# fill in header
92if not args.no_framing:
93    flags = 0x04  # END_HEADERS
94    if args.set_end_stream:
95        flags |= 0x01  # END_STREAM
96    payload_bytes[0].extend([
97        (payload_len >> 16) & 0xff,
98        (payload_len >> 8) & 0xff,
99        (payload_len) & 0xff,
100        # header frame
101        0x01,
102        # flags
103        flags,
104        # stream id
105        0x00,
106        0x00,
107        0x00,
108        0x01
109    ])
110
111hex_bytes = [ord(c) for c in "abcdefABCDEF0123456789"]
112
113
114def esc_c(line):
115    out = "\""
116    last_was_hex = False
117    for c in line:
118        if 32 <= c < 127:
119            if c in hex_bytes and last_was_hex:
120                out += "\"\""
121            if c != ord('"'):
122                out += chr(c)
123            else:
124                out += "\\\""
125            last_was_hex = False
126        else:
127            out += "\\x%02x" % c
128            last_was_hex = True
129    return out + "\""
130
131
132# dump bytes
133if args.hex:
134    all_bytes = []
135    for line in payload_bytes:
136        all_bytes.extend(line)
137    print '{%s}' % ', '.join('0x%02x' % c for c in all_bytes)
138else:
139    for line in payload_bytes:
140        print esc_c(line)
141