Created
April 24, 2017 18:37
-
-
Save timofurrer/498a5f5b670bbfedd351a6f4dd3dd079 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Parse compiled terminfo DB files | |
python terminfo.py /usr/share/terminfo adm3a | |
""" | |
import os | |
import sys | |
import struct | |
def get_db_contents(basepath, termname): | |
""" | |
Get the path to the DB file on the | |
system by concatinating the basepath | |
and the terminal name appropriately. | |
""" | |
path = os.path.join(basepath, termname[0], termname) | |
with open(path, 'rb') as dbfile: | |
return dbfile.read() | |
def parse(db_content): | |
""" | |
Parse the given terminfo DB content | |
""" | |
offset = 0 | |
magic_number, names_section_size, bool_sec_size, number_sec_size, string_sec_size, string_table_size = struct.unpack_from('HHHHHH', db_content, offset) | |
print('magic number:', oct(magic_number)) | |
print('names_section_size,:', names_section_size) | |
print('bool_sec_size:', bool_sec_size) | |
print('number_sec_size,:', number_sec_size) | |
print('string_sec_size,:', string_sec_size) | |
print('string_table_size:', string_table_size) | |
offset = struct.calcsize('H') * 6 | |
# read termial names | |
names = struct.unpack_from('{0}s'.format(names_section_size), db_content, offset)[0] | |
print('terminal names:', names) | |
offset += names_section_size | |
# read boolean flags | |
bool_flags = struct.unpack_from('B' * bool_sec_size, db_content, offset) | |
print('boolean flags:', bool_flags) | |
offset += bool_sec_size | |
# add byte if offset is odd | |
offset += (12 + names_section_size + bool_sec_size) % 2 | |
# parse numbers | |
numbers = struct.unpack_from('<' + 'h' * number_sec_size, db_content, offset) | |
print('numbers:', numbers) | |
offset += struct.calcsize('<h') * number_sec_size | |
# parse string table offsets | |
string_offsets = struct.unpack_from('h' * string_sec_size, db_content, offset) | |
print('string offsets:', string_offsets) | |
offset += struct.calcsize('h') * string_sec_size | |
# parse string table | |
strings = db_content[offset:] | |
print('string table:', strings) | |
db_content = get_db_contents(sys.argv[1], sys.argv[2]) | |
print(db_content) | |
parse(db_content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment