Debian Codegraph @

lib/gtp/support/gtp_tlv.py

raw
1 #
2 # Copyright (c) 2017, NextEPC Group
3 # All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are met:
7 #
8 # 1. Redistributions of source code must retain the above copyright notice, this
9 # list of conditions and the following disclaimer.
10 # 2. Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation
12 # and/or other materials provided with the distribution.
13 #
14 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
18 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 #
25 from docx import Document
26 import re, os, sys, string
27 import datetime
28 import getopt
29 import getpass
30
31 version = "0.1.0"
32
33 msg_list = {}
34 type_list = {}
35 group_list = {}
36
37 verbosity = 0
38 filename = ""
39 outdir = './'
40 cachedir = './cache/'
41
42 FAIL = '\033[91m'
43 INFO = '\033[93m'
44 ENDC = '\033[0m'
45
46 def d_print(string):
47 if verbosity > 0:
48 sys.stdout.write(string)
49
50 def d_info(string):
51 sys.stdout.write(INFO + string + ENDC + "\n")
52
53 def d_error(string):
54 sys.stderr.write(FAIL + string + ENDC + "\n")
55 sys.exit(0)
56
57 def write_file(f, string):
58 f.write(string)
59 d_print(string)
60
61 def output_header_to_file(f):
62 now = datetime.datetime.now()
63 f.write("""/*
64 * Copyright (c) 2017, NextEPC Group
65 * All rights reserved.
66 *
67 * Redistribution and use in source and binary forms, with or without
68 * modification, are permitted provided that the following conditions are met:
69 *
70 * 1. Redistributions of source code must retain the above copyright notice, this
71 * list of conditions and the following disclaimer.
72 * 2. Redistributions in binary form must reproduce the above copyright notice,
73 * this list of conditions and the following disclaimer in the documentation
74 * and/or other materials provided with the distribution.
75
76 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
77 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
78 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
79 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
80 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
81 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
82 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
83 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
84 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
85 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
86 */
87
88 """)
89 f.write("/*******************************************************************************\n")
90 f.write(" * This file had been created by gtp_tlv.py script v%s\n" % (version))
91 f.write(" * Please do not modify this file but regenerate it via script.\n")
92 f.write(" * Created on: %s by %s\n * from %s\n" % (str(now), getpass.getuser(), filename))
93 f.write(" ******************************************************************************/\n\n")
94
95 def usage():
96 print "Python generating TLV build/parser for GTPv2-C v%s" % (version)
97 print "Usage: python gtp_tlv.py [options]"
98 print "Available options:"
99 print "-d Enable script debug"
100 print "-f [file] Input file to parse"
101 print "-o [dir] Output files to given directory"
102 print "-c [dir] Cache files to given directory"
103 print "-h Print this help and return"
104
105 def v_upper(v):
106 return re.sub('3GPP', '', re.sub('\'', '_', re.sub('/', '_', re.sub('-', '_', re.sub(' ', '_', v)))).upper())
107
108 def v_lower(v):
109 return re.sub('3gpp', '', re.sub('\'', '_', re.sub('/', '_', re.sub('-', '_', re.sub(' ', '_', v)))).lower())
110
111 def get_cells(cells):
112 instance = cells[4].text.encode('ascii', 'ignore')
113 if instance.isdigit() is not True:
114 return None
115 ie_type = re.sub('\s*$', '', re.sub('\s*\n*\s*\(NOTE.*\)*', '', cells[3].text.encode('ascii', 'ignore')))
116 if ie_type.find('LDN') != -1:
117 ie_type = 'LDN'
118 elif ie_type.find('APCO') != -1:
119 ie_type = 'APCO'
120 elif ie_type.find('Charging Id') != -1:
121 ie_type = 'Charging ID'
122 elif ie_type.find('H(e)NB Information Reporting') != -1:
123 ie_type = 'eNB Information Reporting'
124 elif ie_type.find('IPv4 Configuration Parameters (IP4CP)') != -1:
125 ie_type = 'IP4CP'
126 if ie_type not in type_list.keys():
127 assert False, "Unknown IE type : [" \
128 + cells[3].text + "]" + "(" + ie_type + ")"
129 presence = cells[1].text.encode('ascii', 'ignore')
130 ie_value = re.sub('\s*\n*\s*\([^\)]*\)*', '', cells[0].text).encode('ascii', 'ignore')
131 comment = cells[2].text.encode('ascii', 'ignore')
132 comment = re.sub('\n|\"|\'|\\\\', '', comment);
133
134 if int(instance) > int(type_list[ie_type]["max_instance"]):
135 type_list[ie_type]["max_instance"] = instance
136 write_file(f, "type_list[\"" + ie_type + "\"][\"max_instance\"] = \"" + instance + "\"\n")
137
138 return { "ie_type" : ie_type, "ie_value" : ie_value, "presence" : presence, "instance" : instance, "comment" : comment }
139
140 def write_cells_to_file(name, cells):
141 write_file(f, name + ".append({ \"ie_type\" : \"" + cells["ie_type"] + \
142 "\", \"ie_value\" : \"" + cells["ie_value"] + \
143 "\", \"presence\" : \"" + cells["presence"] + \
144 "\", \"instance\" : \"" + cells["instance"] + \
145 "\", \"comment\" : \"" + cells["comment"] + "\"})\n")
146
147 try:
148 opts, args = getopt.getopt(sys.argv[1:], "df:ho:c:", ["debug", "file", "help", "output", "cache"])
149 except getopt.GetoptError as err:
150 # print help information and exit:
151 usage()
152 sys.exit(2)
153
154 for o, a in opts:
155 if o in ("-d", "--debug"):
156 verbosity = 1
157 if o in ("-f", "--file"):
158 filename = a
159 if o in ("-o", "--output"):
160 outdir = a
161 if outdir.rfind('/') != len(outdir):
162 outdir += '/'
163 if o in ("-c", "--cache"):
164 cache = a
165 if cachedir.rfind('/') != len(cachedir):
166 cachedir += '/'
167 if o in ("-h", "--help"):
168 usage()
169 sys.exit(2)
170
171 if os.path.isfile(filename) and os.access(filename, os.R_OK):
172 file = open(filename, 'r')
173 else:
174 d_error("Cannot find file : " + filename)
175
176 d_info("[Message List]")
177 cachefile = cachedir + 'tlv_msg_list.py'
178 if os.path.isfile(cachefile) and os.access(cachefile, os.R_OK):
179 execfile(cachefile)
180 print "Read from " + cachefile
181 else:
182 document = Document(filename)
183 f = open(cachefile, 'w')
184
185 msg_table = ""
186 for i, table in enumerate(document.tables):
187 cell = table.rows[0].cells[0]
188 if cell.text.find('Message Type value') != -1:
189 msg_table = table
190 d_print("Table Index = %d\n" % i)
191
192 for row in msg_table.rows[2:-4]:
193 key = row.cells[1].text.encode('ascii', 'ignore')
194 type = row.cells[0].text.encode('ascii', 'ignore')
195 if type.isdigit() is False:
196 continue
197 if int(type) in range(128, 160):
198 continue
199 if int(type) in range(231, 240):
200 continue
201 if key.find('Reserved') != -1:
202 continue
203 key = re.sub('\s*\n*\s*\([^\)]*\)*', '', key)
204 msg_list[key] = { "type": type }
205 write_file(f, "msg_list[\"" + key + "\"] = { \"type\" : \"" + type + "\" }\n")
206 f.close()
207
208 d_info("[IE Type List]")
209 cachefile = cachedir + 'tlv_type_list.py'
210 if os.path.isfile(cachefile) and os.access(cachefile, os.R_OK):
211 execfile(cachefile)
212 print "Read from " + cachefile
213 else:
214 document = Document(filename)
215 f = open(cachefile, 'w')
216
217 ie_table = ""
218 for i, table in enumerate(document.tables):
219 cell = table.rows[0].cells[0]
220 if cell.text.find('IE Type value') != -1:
221 ie_table = table
222 d_print("Table Index = %d\n" % i)
223
224 for row in ie_table.rows[1:-5]:
225 key = row.cells[1].text.encode('ascii', 'ignore')
226 if key.find('Reserved') != -1:
227 continue
228 if key.find('MM Context') != -1:
229 continue
230 elif key.find('Recovery') != -1:
231 key = 'Recovery'
232 elif key.find('Trusted WLAN Mode Indication') != -1:
233 key = 'TWMI'
234 elif key.find('LDN') != -1:
235 key = 'LDN'
236 elif key.find('APCO') != -1:
237 key = 'APCO'
238 elif key.find('Remote UE IP information') != -1:
239 key = 'Remote UE IP Information'
240 elif key.find('Procedure Transaction ID') != -1:
241 key = 'PTI'
242 else:
243 key = re.sub('.*\(', '', row.cells[1].text.encode('ascii', 'ignore'))
244 key = re.sub('\)', '', key)
245 key = re.sub('\s*$', '', key)
246 type = row.cells[0].text.encode('ascii', 'ignore')
247 type_list[key] = { "type": type , "max_instance" : "0" }
248 write_file(f, "type_list[\"" + key + "\"] = { \"type\" : \"" + type)
249 write_file(f, "\", \"max_instance\" : \"0\" }\n")
250 f.close()
251 type_list['MM Context'] = { "type": "107", "max_instance" : "0" }
252
253 d_info("[Group IE List]")
254 cachefile = cachedir + 'tlv_group_list.py'
255 if os.path.isfile(cachefile) and os.access(cachefile, os.R_OK):
256 execfile(cachefile)
257 print "Read from " + cachefile
258 else:
259 document = Document(filename)
260 f = open(cachefile, 'w')
261
262 for i, table in enumerate(document.tables):
263 if table.rows[0].cells[0].text.find('Octet') != -1 and \
264 table.rows[0].cells[2].text.find('IE Type') != -1:
265 d_print("Table Index = %d\n" % i)
266
267 row = table.rows[0];
268
269 if len(re.findall('\d+', row.cells[2].text)) == 0:
270 continue;
271 ie_type = re.findall('\d+', row.cells[2].text)[0].encode('ascii', 'ignore')
272 ie_name = re.sub('\s*IE Type.*', '', row.cells[2].text.encode('ascii', 'ignore'))
273
274 if ie_name not in group_list.keys():
275 ies = []
276 write_file(f, "ies = []\n")
277 for row in table.rows[4:]:
278 cells = get_cells(row.cells)
279 if cells is None:
280 continue
281
282 ies_is_added = True
283 for ie in ies:
284 if (cells["ie_type"], cells["instance"]) == (ie["ie_type"], ie["instance"]):
285 ies_is_added = False
286 if ies_is_added is True:
287 ies.append(cells)
288 write_cells_to_file("ies", cells)
289
290 group_list[ie_name] = { "type" : ie_type, "ies" : ies }
291 write_file(f, "group_list[\"" + ie_name + "\"] = { \"type\" : \"" + ie_type + "\", \"ies\" : ies }\n")
292 else:
293 group_list_is_added = False
294 added_ies = group_list[ie_name]["ies"]
295 write_file(f, "added_ies = group_list[\"" + ie_name + "\"][\"ies\"]\n")
296 for row in table.rows[4:]:
297 cells = get_cells(row.cells)
298 if cells is None:
299 continue
300
301 ies_is_added = True
302 for ie in group_list[ie_name]["ies"]:
303 if (cells["ie_type"], cells["instance"]) == (ie["ie_type"], ie["instance"]):
304 ies_is_added = False
305 for ie in ies:
306 if (cells["ie_type"], cells["instance"]) == (ie["ie_type"], ie["instance"]):
307 ies_is_added = False
308 if ies_is_added is True:
309 added_ies.append(cells)
310 write_cells_to_file("added_ies", cells)
311 group_list_is_added = True
312 if group_list_is_added is True:
313 group_list[ie_name] = { "type" : ie_type, "ies" : added_ies }
314 write_file(f, "group_list[\"" + ie_name + "\"] = { \"type\" : \"" + ie_type + "\", \"ies\" : added_ies }\n")
315 f.close()
316
317 msg_list["Echo Request"]["table"] = 6
318 msg_list["Echo Response"]["table"] = 7
319 msg_list["Create Session Request"]["table"] = 8
320 msg_list["Create Session Response"]["table"] = 13
321 msg_list["Create Bearer Request"]["table"] = 18
322 msg_list["Create Bearer Response"]["table"] = 22
323 msg_list["Modify Bearer Request"]["table"] = 29
324 msg_list["Modify Bearer Response"]["table"] = 33
325 msg_list["Delete Session Request"]["table"] = 38
326 msg_list["Delete Bearer Request"]["table"] = 40
327 msg_list["Delete Session Response"]["table"] = 44
328 msg_list["Delete Bearer Response"]["table"] = 47
329 msg_list["Downlink Data Notification"]["table"] = 50
330 msg_list["Downlink Data Notification Acknowledge"]["table"] = 53
331 msg_list["Downlink Data Notification Failure Indication"]["table"] = 54
332 msg_list["Delete Indirect Data Forwarding Tunnel Request"]["table"] = 55
333 msg_list["Delete Indirect Data Forwarding Tunnel Response"]["table"] = 56
334 msg_list["Modify Bearer Command"]["table"] = 57
335 msg_list["Modify Bearer Failure Indication"]["table"] = 60
336 msg_list["Update Bearer Request"]["table"] = 62
337 msg_list["Update Bearer Response"]["table"] = 66
338 msg_list["Delete Bearer Command"]["table"] = 69
339 msg_list["Delete Bearer Failure Indication"]["table"] = 72
340 msg_list["Create Indirect Data Forwarding Tunnel Request"]["table"] = 75
341 msg_list["Create Indirect Data Forwarding Tunnel Response"]["table"] = 77
342 msg_list["Release Access Bearers Request"]["table"] = 79
343 msg_list["Release Access Bearers Response"]["table"] = 80
344 msg_list["Modify Access Bearers Request"]["table"] = 84
345 msg_list["Modify Access Bearers Response"]["table"] = 87
346
347 for key in msg_list.keys():
348 if "table" in msg_list[key].keys():
349 d_info("[" + key + "]")
350 cachefile = cachedir + "tlv_msg_" + msg_list[key]["type"] + ".py"
351 if os.path.isfile(cachefile) and os.access(cachefile, os.R_OK):
352 execfile(cachefile)
353 print "Read from " + cachefile
354 else:
355 document = Document(filename)
356 f = open(cachefile, 'w')
357
358 ies = []
359 write_file(f, "ies = []\n")
360 table = document.tables[msg_list[key]["table"]]
361 for row in table.rows[1:]:
362 cells = get_cells(row.cells)
363 if cells is None:
364 continue
365
366 ies_is_added = True
367 for ie in ies:
368 if (cells["ie_type"], cells["instance"]) == (ie["ie_type"], ie["instance"]):
369 ies_is_added = False
370 if ies_is_added is True:
371 ies.append(cells)
372 write_cells_to_file("ies", cells)
373 msg_list[key]["ies"] = ies
374 write_file(f, "msg_list[key][\"ies\"] = ies\n")
375 f.close()
376
377 type_list["Recovery"]["size"] = 1 # Type : 3
378 type_list["EBI"]["size"] = 1 # Type : 73
379 type_list["RAT Type"]["size"] = 1 # Type : 82
380 type_list["PDN Type"]["size"] = 1 # Type : 99
381 type_list["Port Number"]["size"] = 2 # Type : 126
382 type_list["APN Restriction"]["size"] = 1 # Type : 127
383 type_list["Selection Mode"]["size"] = 1 # Type : 128
384 type_list["Node Type"]["size"] = 1 # Type : 128
385
386 f = open(outdir + 'gtp_message.h', 'w')
387 output_header_to_file(f)
388 f.write("""#ifndef __GTP_TLV_H__
389 #define __GTP_TLV_H__
390
391 #include "core_tlv_msg.h"
392
393 #ifdef __cplusplus
394 extern "C" {
395 #endif /* __cplusplus */
396
397 /* 5.1 General format */
398 #define GTPV1U_HEADER_LEN 8
399 #define GTPV2C_HEADER_LEN 12
400 #define GTP_TEID_LEN 4
401 typedef struct _gtp_header_t {
402 union {
403 struct {
404 ED4(c_uint8_t version:3;,
405 c_uint8_t piggybacked:1;,
406 c_uint8_t teid_presence:1;,
407 c_uint8_t spare1:3;)
408 };
409 /* GTU-U flags */
410 #define GTPU_FLAGS_PN 0x1
411 #define GTPU_FLAGS_S 0x2
412 c_uint8_t flags;
413 };
414 c_uint8_t type;
415 c_uint16_t length;
416 union {
417 struct {
418 c_uint32_t teid;
419 /* sqn : 31bit ~ 8bit, spare : 7bit ~ 0bit */
420 #define GTP_XID_TO_SQN(__xid) htonl(((__xid) << 8))
421 #define GTP_SQN_TO_XID(__sqn) (ntohl(__sqn) >> 8)
422 c_uint32_t sqn;
423 };
424 /* sqn : 31bit ~ 8bit, spare : 7bit ~ 0bit */
425 c_uint32_t sqn_only;
426 };
427 } __attribute__ ((packed)) gtp_header_t;
428
429 /* GTP-U message type, defined in 3GPP TS 29.281 Release 11 */
430 #define GTPU_MSGTYPE_ECHO_REQ 1
431 #define GTPU_MSGTYPE_ECHO_RSP 2
432 #define GTPU_MSGTYPE_ERR_IND 26
433 #define GTPU_MSGTYPE_SUPP_EXTHDR_NOTI 31
434 #define GTPU_MSGTYPE_END_MARKER 254
435 #define GTPU_MSGTYPE_GPDU 255
436
437 /* GTPv2-C message type */
438 """)
439
440 tmp = [(k, v["type"]) for k, v in msg_list.items()]
441 sorted_msg_list = sorted(tmp, key=lambda tup: int(tup[1]))
442 for (k, v) in sorted_msg_list:
443 f.write("#define GTP_" + v_upper(k) + "_TYPE " + v + "\n")
444 f.write("\n")
445
446 tmp = [(k, v["type"]) for k, v in type_list.items()]
447 sorted_type_list = sorted(tmp, key=lambda tup: int(tup[1]))
448 for (k, v) in sorted_type_list:
449 f.write("#define TLV_" + v_upper(k) + "_TYPE " + v + "\n")
450 f.write("\n")
451
452 f.write("/* Infomration Element TLV Descriptor */\n")
453 for (k, v) in sorted_type_list:
454 if k in group_list.keys():
455 continue
456 for instance in range(0, int(type_list[k]["max_instance"])+1):
457 f.write("extern tlv_desc_t tlv_desc_" + v_lower(k))
458 f.write("_" + str(instance) + ";\n")
459 f.write("\n")
460
461 tmp = [(k, v["type"]) for k, v in group_list.items()]
462 sorted_group_list = sorted(tmp, key=lambda tup: int(tup[1]))
463
464 f.write("/* Group Infomration Element TLV Descriptor */\n")
465 for (k, v) in sorted_group_list:
466 for instance in range(0, int(type_list[k]["max_instance"])+1):
467 f.write("extern tlv_desc_t tlv_desc_" + v_lower(k))
468 f.write("_" + str(instance) + ";\n")
469 f.write("\n")
470
471 f.write("/* Message Descriptor */\n")
472 for (k, v) in sorted_msg_list:
473 f.write("extern tlv_desc_t tlv_desc_" + v_lower(k) + ";\n")
474 f.write("\n")
475
476 f.write("/* Structure for Infomration Element */\n")
477 for (k, v) in sorted_type_list:
478 if k in group_list.keys():
479 continue
480 if "size" in type_list[k]:
481 if type_list[k]["size"] == 1:
482 f.write("typedef tlv_uint8_t tlv_" + v_lower(k) + "_t;\n")
483 elif type_list[k]["size"] == 2:
484 f.write("typedef tlv_uint16_t tlv_" + v_lower(k) + "_t;\n")
485 elif type_list[k]["size"] == 3:
486 f.write("typedef tlv_uint24_t tlv_" + v_lower(k) + "_t;\n")
487 elif type_list[k]["size"] == 4:
488 f.write("typedef tlv_uint32_t tlv_" + v_lower(k) + "_t;\n")
489 else:
490 assert False, "Unknown size = %d for key = %s" % (type_list[k]["size"], k)
491 else:
492 f.write("typedef tlv_octet_t tlv_" + v_lower(k) + "_t;\n")
493 f.write("\n")
494
495 f.write("/* Structure for Group Infomration Element */\n")
496 for (k, v) in sorted_group_list:
497 f.write("typedef struct _tlv_" + v_lower(k) + "_t {\n")
498 f.write(" tlv_presence_t presence;\n")
499 for ies in group_list[k]["ies"]:
500 f.write(" tlv_" + v_lower(ies["ie_type"]) + "_t " + \
501 v_lower(ies["ie_value"]))
502 if ies["ie_type"] == "F-TEID":
503 if ies["ie_value"] == "S2b-U ePDG F-TEID":
504 f.write("_" + ies["instance"] + ";")
505 elif ies["ie_value"] == "S2a-U TWAN F-TEID":
506 f.write("_" + ies["instance"] + ";")
507 else:
508 f.write(";")
509 f.write(" /* Instance : " + ies["instance"] + " */\n")
510 else:
511 f.write(";\n")
512 f.write("} tlv_" + v_lower(k) + "_t;\n")
513 f.write("\n")
514
515 f.write("/* Structure for Message */\n")
516 for (k, v) in sorted_msg_list:
517 if "ies" in msg_list[k]:
518 f.write("typedef struct _gtp_" + v_lower(k) + "_t {\n")
519 for ies in msg_list[k]["ies"]:
520 f.write(" tlv_" + v_lower(ies["ie_type"]) + "_t " + \
521 v_lower(ies["ie_value"]) + ";\n")
522 f.write("} gtp_" + v_lower(k) + "_t;\n")
523 f.write("\n")
524
525 f.write("typedef struct _gtp_message_t {\n")
526 f.write(" gtp_header_t h;\n")
527 f.write(" union {\n")
528 for (k, v) in sorted_msg_list:
529 if "ies" in msg_list[k]:
530 f.write(" gtp_" + v_lower(k) + "_t " + v_lower(k) + ";\n");
531 f.write(" };\n");
532 f.write("} gtp_message_t;\n\n")
533
534 f.write("""CORE_DECLARE(status_t) gtp_parse_msg(
535 gtp_message_t *gtp_message, pkbuf_t *pkbuf);
536 CORE_DECLARE(status_t) gtp_build_msg(
537 pkbuf_t **pkbuf, gtp_message_t *gtp_message);
538
539 #ifdef __cplusplus
540 }
541 #endif /* __cplusplus */
542
543 #endif /* __GTP_TLV_H__ */
544 """)
545 f.close()
546
547 f = open(outdir + 'gtp_message.c', 'w')
548 output_header_to_file(f)
549 f.write("""#define TRACE_MODULE _gtp_message
550 #include "core_debug.h"
551 #include "gtp_message.h"
552
553 """)
554
555 for (k, v) in sorted_type_list:
556 if k in group_list.keys():
557 continue
558 for instance in range(0, int(type_list[k]["max_instance"])+1):
559 f.write("tlv_desc_t tlv_desc_%s_%d =\n" % (v_lower(k), instance))
560 f.write("{\n")
561 if "size" in type_list[k]:
562 if type_list[k]["size"] == 1:
563 f.write(" TLV_UINT8,\n")
564 elif type_list[k]["size"] == 2:
565 f.write(" TLV_UINT16,\n")
566 elif type_list[k]["size"] == 3:
567 f.write(" TLV_UINT24,\n")
568 elif type_list[k]["size"] == 4:
569 f.write(" TLV_UINT32,\n")
570 else:
571 assert False, "Unknown size = %d for key = %s" % (type_list[k]["size"], k)
572 else:
573 f.write(" TLV_VAR_STR,\n")
574 f.write(" \"%s\",\n" % k)
575 f.write(" TLV_%s_TYPE,\n" % v_upper(k))
576 if "size" in type_list[k]:
577 f.write(" %d,\n" % type_list[k]["size"])
578 else:
579 f.write(" 0,\n")
580 f.write(" %d,\n" % instance)
581 f.write(" sizeof(tlv_%s_t),\n" % v_lower(k))
582 f.write(" { NULL }\n")
583 f.write("};\n\n")
584
585 for (k, v) in sorted_group_list:
586 for instance in range(0, int(type_list[k]["max_instance"])+1):
587 f.write("tlv_desc_t tlv_desc_%s_%d =\n" % (v_lower(k), instance))
588 f.write("{\n")
589 f.write(" TLV_COMPOUND,\n")
590 f.write(" \"%s\",\n" % k)
591 f.write(" TLV_%s_TYPE,\n" % v_upper(k))
592 f.write(" 0,\n")
593 f.write(" %d,\n" % instance)
594 f.write(" sizeof(tlv_%s_t),\n" % v_lower(k))
595 f.write(" {\n")
596 for ies in group_list[k]["ies"]:
597 f.write(" &tlv_desc_%s_%s,\n" % (v_lower(ies["ie_type"]), v_lower(ies["instance"])))
598 f.write(" NULL,\n")
599 f.write(" }\n")
600 f.write("};\n\n")
601
602 for (k, v) in sorted_msg_list:
603 if "ies" in msg_list[k]:
604 f.write("tlv_desc_t tlv_desc_%s =\n" % v_lower(k))
605 f.write("{\n")
606 f.write(" TLV_MESSAGE,\n")
607 f.write(" \"%s\",\n" % k)
608 f.write(" 0, 0, 0, 0, {\n")
609 for ies in msg_list[k]["ies"]:
610 f.write(" &tlv_desc_%s_%s,\n" % (v_lower(ies["ie_type"]), v_lower(ies["instance"])))
611 f.write(" NULL,\n")
612 f.write("}};\n\n")
613 f.write("\n")
614
615 f.write("""status_t gtp_parse_msg(gtp_message_t *gtp_message, pkbuf_t *pkbuf)
616 {
617 status_t rv = CORE_ERROR;
618 gtp_header_t *h = NULL;
619 c_uint16_t size = 0;
620
621 d_assert(gtp_message, return CORE_ERROR, "Null param");
622 d_assert(pkbuf, return CORE_ERROR, "Null param");
623 d_assert(pkbuf->payload, return CORE_ERROR, "Null param");
624
625 d_trace(50, "[GTPv2] RECV : ");
626 d_trace_hex(50, pkbuf->payload, pkbuf->len);
627
628 h = pkbuf->payload;
629 d_assert(h, return CORE_ERROR, "Null param");
630
631 memset(gtp_message, 0, sizeof(gtp_message_t));
632
633 if (h->teid_presence)
634 size = GTPV2C_HEADER_LEN;
635 else
636 size = GTPV2C_HEADER_LEN-GTP_TEID_LEN;
637
638 d_assert(pkbuf_header(pkbuf, -size) == CORE_OK,
639 return CORE_ERROR, "pkbuf_header error");
640 memcpy(&gtp_message->h, pkbuf->payload - size, size);
641
642 if (h->teid_presence)
643 gtp_message->h.teid = ntohl(gtp_message->h.teid);
644
645 if (pkbuf->len == 0)
646 return CORE_OK;
647
648 switch(gtp_message->h.type)
649 {
650 """)
651 for (k, v) in sorted_msg_list:
652 if "ies" in msg_list[k]:
653 f.write(" case GTP_%s_TYPE:\n" % v_upper(k))
654 f.write(" rv = tlv_parse_msg(&gtp_message->%s,\n" % v_lower(k))
655 f.write(" &tlv_desc_%s, pkbuf, TLV_MODE_T1_L2_I1);\n" % v_lower(k))
656 f.write(" break;\n")
657 f.write(""" default:
658 d_warn("Not implmeneted(type:%d)", gtp_message->h.type);
659 break;
660 }
661
662 return rv;
663 }
664
665 """)
666
667 f.write("""status_t gtp_build_msg(pkbuf_t **pkbuf, gtp_message_t *gtp_message)
668 {
669 status_t rv = CORE_ERROR;
670
671 d_assert(gtp_message, return rv, "Null param");
672 switch(gtp_message->h.type)
673 {
674 """)
675 for (k, v) in sorted_msg_list:
676 if "ies" in msg_list[k]:
677 f.write(" case GTP_%s_TYPE:\n" % v_upper(k))
678 f.write(" rv = tlv_build_msg(pkbuf, &tlv_desc_%s,\n" % v_lower(k))
679 f.write(" &gtp_message->%s, TLV_MODE_T1_L2_I1);\n" % v_lower(k))
680 f.write(" break;\n")
681 f.write(""" default:
682 d_warn("Not implmeneted(type:%d)", gtp_message->h.type);
683 break;
684 }
685
686 if ((*pkbuf) && (*pkbuf)->payload)
687 {
688 d_trace(50, "[GTPv2] SEND : ");
689 d_trace_hex(50, (*pkbuf)->payload, (*pkbuf)->len);
690 }
691
692 return rv;
693 }
694 """)
695
696 f.write("\n")
697
698 f.close()