#!/usr/bin/python

# Unix SMB/CIFS implementation.
# Copyright (C) Kamen Mazdrashki <kamen.mazdrashki@postpath.com> 2009
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

"""binary OID encode/decode in BER format"""

def encode_sub_identifier(v):
    s = ''
    if (v >= (1<<28)): s += "%02X" % (0x80 | ((v>>28)&0x7f))
    if (v >= (1<<21)): s += "%02X" % (0x80 | ((v>>21)&0x7f))
    if (v >= (1<<14)): s += "%02X" % (0x80 | ((v>>14)&0x7f))
    if (v >= (1<<7)): s += "%02X" % (0x80 | ((v>>7)&0x7f))
    s += "%02X" % (v&0x7f)
    return s

def encode(oid):
    s = ''
    ids = [int(x) for x in oid.split('.')]
    # make first byte
    s += "%02X" % (40 * ids.pop(0) + ids.pop(0))
    # encode sub-identifiers
    for subid in ids:
        s += encode_sub_identifier(subid)
    return s

def decode(bin_str):
    # get rid of 0x
    if bin_str[:2].lower() == "0x":
        bin_str = bin_str[2:]

    # decode first 'special' byte
    v = int(bin_str[:2], 16)
    oid = '%d.%d' % (v / 40, v % 40)

    # decode the rest
    v = 0
    for i in range(2, len(bin_str), 2):
        num = bin_str[i:i + 2]
        n = int(num, 16)
        v = (v << 7) | (n & 0x7f)
        if ((n & 0x80) == 0):
            oid += ".%d" % v
            v = 0
    return oid


if __name__ == '__main__':
    # some testing here
    s = "2.5.21"
    assert decode(encode(s)) == s
    s = "0.9.2342.19200300.100.1"
    assert decode(encode(s)) == s
    pass
