# Path: xclib/utf8.py
# def unutf8(u, opts='strict'):
#     if opts == 'illegal':
#         try:
#             return u.decode('utf-8', 'strict')
#         except UnicodeError:
#             dec = u.decode('utf-8', 'ignore')
#             logging.error('Illegal UTF-8 sequence: %r' % dec)
#             sys.stderr.write('Illegal UTF-8 sequence: %r\n' % dec)
#             traceback.print_exc()
#             return 'illegal-utf8-sequence-' + dec
#     else:
#         return u.decode('utf-8', opts)


import sys
import logging
from struct import pack, unpack
from xclib.utf8 import unutf8

# Message formats described in `../doc/Protocol.md`

class ejabberd_io:
    @classmethod
    def read_request(cls, infd, outfd):
        try:
            infd = infd.buffer
        except AttributeError:
            pass
        length_field = infd.read(2)
        while len(length_field) == 2:
            (size,) = unpack('>H', length_field)
            if size == 0:
               logging.info('command length 0, treating as logical EOF')
               return
            cmd = infd.read(size)
            if len(cmd) != size:
               logging.warn('premature EOF while reading cmd: %d != %d' % (len(cmd), size))
               return

# Path: xclib/utf8.py
# def unutf8(u, opts='strict'):
#     if opts == 'illegal':
#         try:
#             return u.decode('utf-8', 'strict')
#         except UnicodeError:
#             dec = u.decode('utf-8', 'ignore')
#             logging.error('Illegal UTF-8 sequence: %r' % dec)
#             sys.stderr.write('Illegal UTF-8 sequence: %r\n' % dec)
#             traceback.print_exc()
#             return 'illegal-utf8-sequence-' + dec
#     else:
#         return u.decode('utf-8', opts)


# Path: xclib/ejabberd_io.py
import sys
import logging
from struct import pack, unpack
from xclib.utf8 import unutf8


# Message formats described in `../doc/Protocol.md`

class ejabberd_io:
    @classmethod
    def read_request(cls, infd, outfd):
        try:
            infd = infd.buffer
        except AttributeError:
            pass
        length_field = infd.read(2)
        while len(length_field) == 2:
            (size,) = unpack('>H', length_field)
            if size == 0:
               logging.info('command length 0, treating as logical EOF')
               return
            cmd = infd.read(size)
            if len(cmd) != size:
               logging.warn('premature EOF while reading cmd: %d != %d' % (len(cmd), size))
               return

            x = unutf8(cmd).split(':', 3)