-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathextract_s1ap_proto_ies.py
288 lines (228 loc) · 8.18 KB
/
extract_s1ap_proto_ies.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
import sys
def main():
asn_file = sys.argv[1]
rs_file = sys.argv[2]
proto_ies = parse_asn_spec(asn_file)
replace_old_rust(rs_file, proto_ies)
def replace_old_rust(rs_file, proto_ies):
new_rust = ''
with open(rs_file, 'r') as infile:
rs_lines = infile.readlines()
for typename, fields in proto_ies:
print(f'replacing {typename}...')
ies_impl = f'impl entropic::Entropic for {typename}ProtocolIEs '
line_idx = 0
found = False
while line_idx < len(rs_lines):
if rs_lines[line_idx].find(ies_impl) >= 0:
while rs_lines[line_idx] != '}\n':
rs_lines.pop(line_idx)
rs_lines.pop(line_idx)
found = True
break
line_idx += 1
if found:
new_rust += gen_new_rust(typename, fields)
else:
print(f'WARNING: entropic impl for "{typename}ProtocolIEs" not found')
print('Writing output...')
with open(rs_file, 'w') as outfile:
outfile.writelines(rs_lines)
outfile.write(new_rust)
print('All done!')
def gen_new_rust(typename, fields):
output = ''
ies_ty = typename + 'ProtocolIEs'
ies_entry_ty = ies_ty + '_Entry'
ies_entryvalue_ty = ies_entry_ty + 'Value'
from_entropy_fields_output = ''
to_entropy_fields_output = ''
for ident,ty,presence in fields:
if ident == 'Id_S1_Message':
continue # NOTE: this field is currently dropped by the compiler, so we blacklist it here
if presence == 'mandatory':
from_entropy_fields_output += \
f'''
let b = source.get_byte()?;
if (b & 0b_0001_1111) != 0b_0001_1111 {{ // 1/32 chance of missing
let ie_value = {ies_entryvalue_ty}::{ident}(source.get_entropic()?);
ie_list.push({ies_entry_ty} {{
id: ProtocolIE_ID(ie_value.choice_key()),
criticality: Criticality(Criticality::IGNORE),
value: ie_value,
}});
}}
'''
to_entropy_fields_output += \
f'''
if let Some({ies_entryvalue_ty}::{ident}(value)) = self.0.get(ie_idx).map(|ie| &ie.value) {{
ie_idx += 1;
length += sink.put_byte(0b_0000_0000)?;
sink.put_entropic(value)?;
}} else {{
length += sink.put_byte(0b_0001_1111)?;
}};
'''
elif presence == 'conditional':
from_entropy_fields_output += \
f'''
let b = source.get_byte()?;
if (b & 0b_0000_0011) == 0b_0000_0011 {{ // 1/4 chance of being present
let ie_value = {ies_entryvalue_ty}::{ident}(source.get_entropic()?);
ie_list.push({ies_entry_ty} {{
id: ProtocolIE_ID(ie_value.choice_key()),
criticality: Criticality(Criticality::IGNORE),
value: ie_value,
}});
}}
'''
to_entropy_fields_output += \
f'''
if let Some({ies_entryvalue_ty}::{ident}(value)) = self.0.get(ie_idx).map(|ie| &ie.value) {{
ie_idx += 1;
length += sink.put_byte(0b_0000_0011)?;
sink.put_entropic(value)?;
}} else {{
length += sink.put_byte(0b_0000_0000)?;
}};
'''
elif presence == 'optional':
from_entropy_fields_output += \
f'''
let b = source.get_byte()?;
if (b & 0b_0000_1111) == 0b_0000_1111 {{ // 1/16 chance of being present
let ie_value = {ies_entryvalue_ty}::{ident}(source.get_entropic()?);
ie_list.push({ies_entry_ty} {{
id: ProtocolIE_ID(ie_value.choice_key()),
criticality: Criticality(Criticality::IGNORE),
value: ie_value,
}});
}}
'''
to_entropy_fields_output += \
f'''
if let Some({ies_entryvalue_ty}::{ident}(value)) = self.0.get(ie_idx).map(|ie| &ie.value) {{
ie_idx += 1;
length += sink.put_byte(0b_0000_1111)?;
sink.put_entropic(value)?;
}} else {{
length += sink.put_byte(0b_0000_0000)?;
}};
'''
else:
sys.exit(f'Unknown presence value {presence}')
output += f'''
impl entropic::Entropic for {ies_ty} {{
#[inline]
fn from_entropy_source<'a, I: Iterator<Item = &'a u8>, E: EntropyScheme>(
source: &mut Source<'a, I, E>,
) -> Result<Self, entropic::EntropicError> {{
let mut ie_list = Vec::new();
// Loop this part for every enum discriminant
{from_entropy_fields_output}
Ok({ies_ty}(ie_list))
}}
#[inline]
fn to_entropy_sink<'a, I: Iterator<Item = &'a mut u8>, E: EntropyScheme>(
&self,
sink: &mut Sink<'a, I, E>,
) -> Result<usize, entropic::EntropicError> {{
let mut ie_idx = 0;
let mut length = 0;
{to_entropy_fields_output}
if ie_idx != self.0.len() {{
return Err(entropic::EntropicError::Internal)
}}
Ok(length)
}}
}}
'''
return output
def parse_asn_spec(asn_file):
with open(asn_file, 'r') as infile:
asn_spec = infile.read()
proto_ies_idx = 0
proto_ies = []
while True:
proto_ies_idx = asn_spec.find(" S1AP-PROTOCOL-IES ::= {", proto_ies_idx)
if proto_ies_idx < 0:
break
# get the name of the type
type_name_idx = proto_ies_idx
while asn_spec[type_name_idx - 1] != '\n':
type_name_idx -= 1
typename = asn_spec[type_name_idx:proto_ies_idx]
typename = typename[:-3].replace('-', '_')
if typename[-1] == '_':
typename = typename[:-1]
proto_ies_idx += len(" S1AP-PROTOCOL-IES ::= {")
# Make sure the type conforms to name requirements (not robust yet)
if not is_valid_typename(typename):
print(f'typename "{typename}" is not valid')
continue
# Parse all IE fields
fields = []
while True:
if asn_spec[proto_ies_idx].isspace() or asn_spec[proto_ies_idx] == '|':
proto_ies_idx += 1
continue
if asn_spec[proto_ies_idx] == ',':
proto_ies_idx += 1
while asn_spec[proto_ies_idx].isspace():
proto_ies_idx += 1
if asn_spec[proto_ies_idx:proto_ies_idx + 3] != '...':
print(f"WARNING: unexpected missing ' ...' from end of Protocol IEs def: {asn_spec[proto_ies_idx:proto_ies_idx+20]}")
proto_ies_idx += 3
break # We don't need to parse the closing '}'; we're just grepping anyways.
while asn_spec[proto_ies_idx].isspace():
proto_ies_idx += 1
if asn_spec[proto_ies_idx:proto_ies_idx+2] == '--':
proto_ies_idx = asn_spec.index('\n', proto_ies_idx) + 1
while asn_spec[proto_ies_idx].isspace():
proto_ies_idx += 1
if asn_spec[proto_ies_idx] != '{':
sys.exit(f"ERROR: missing Protocol IEs field definition at {proto_ies_idx}")
f_start = proto_ies_idx
proto_ies_idx = asn_spec.index('}', proto_ies_idx)
proto_field = asn_spec[f_start:proto_ies_idx]
fields.append(parse_proto_field(proto_field))
proto_ies_idx += 1
proto_ies.append((typename,fields))
return proto_ies
def parse_proto_field(f):
i = 0
while f[i].isspace():
i += 1
assert(f[i] == '{')
i += 1
while f[i].isspace():
i += 1
assert(f[i:i+3] == 'ID ')
i += 3
id_start = i
i = f.index('CRITICALITY', i)
ident = f[id_start:i].strip()
i = f.index('TYPE ', i)
i += 5
ty_start = i
i = f.index('PRESENCE', i)
ty = f[ty_start:i].strip()
i += len('PRESENCE')
while f[i].isspace():
i += 1
presence_end = i
while presence_end < len(f) and f[presence_end].isalpha():
presence_end += 1
presence = f[i:presence_end]
ident = ident.replace('-', '_')
if ord(ident[0]) >= ord('a') and ord(ident[0]) <= ord('z'):
ident = chr(ord('A') + ord(ident[0]) - ord('a')) + ident[1:]
return (ident, ty, presence)
def is_valid_typename(typename):
return True
# for c in typename:
# if c != '-' and (not (ord(c) >= ord('a') and ord(c) <= ord('z'))) and (not (ord(c) >= ord('A') and ord(c) <= ord('Z'))) and (not (ord(c) >= ord('0') and ord(c) <= ord('9'))):
# return False
# return True
if __name__ == '__main__':
main()