Handle incoming Telnet commands that are two bytes long.
543209
def _two_byte_cmd(self, cmd):
        
        #print "got two byte cmd %d" % ord(cmd)

        if cmd == SB:
            ## Begin capturing a sub-negotiation string
            self.telnet_got_sb = True
            self.telnet_sb_buffer = ''

        elif cmd == SE:
            ## Stop capturing a sub-negotiation string
            self.telnet_got_sb = False
            self._sb_decoder()

        elif cmd == NOP:
            pass

        elif cmd == DATMK:
            pass

        elif cmd == IP:
            pass

        elif cmd == AO:
            pass

        elif cmd == AYT:
            pass

        elif cmd == EC:
            pass

        elif cmd == EL:
            pass

        elif cmd == GA:
            pass

        else:
            print "2BC: Should not be here."

        self.telnet_got_iac = False
        self.telnet_got_cmd = None
553550
def get(self, command=None):
        

        try:
            assert self.telnet
            with self.lock:
                if command:
                    if not command.endswith('\r\n'):
                        command += '\r\n'
                    LOGGER.debug('%s: sending %r', self.host, command)
                    self.telnet.write(command.encode())

                res = self.telnet.read_until('\r\n'.encode()).decode()
                LOGGER.debug('%s: received %r', self.host, res)
                if res.split()[0] not in ('100', '250'):
                    LOGGER.warn('command error: %r', res)
                    return None
                return res.split()[1]

        except (AssertionError):
            self.connect()

        except (EOFError, socket.gaierror, BrokenPipeError):
            LOGGER.error("Cannot get answer from %s (%d)",
                         self.host, self.retries)
            if self.retries > 0:
                self.retries -= 1
                self.connect()
                return self.get(command)
            else:
                self.retries = Netio.MAX_RETRIES
                return None
1051920
def handle_read(self):
        """"""
        while True:
            try:
                c = self.recv(1)
            except socket.error as e:
                if e.errno == errno.EWOULDBLOCK:
                    return
                else:
                    raise
            else:
                self._do(c)
                self.socket.setblocking(True)
                self.send(b'A')
                self.socket.setblocking(False)
1170123
def handle(self, conn):
        """"""
        keyring.sendline(conn, b'OK')
        for line in keyring.iterlines(conn):
            parts = line.split(b' ')
            command = parts[0]
            args = tuple(parts[1:])

            if command == b'BYE':
                return
            elif command == b'KILLAGENT':
                keyring.sendline(conn, b'OK')
                raise AgentStop()

            if command not in self.handlers:
                log.error('unknown request: %r', line)
                continue

            handler = self.handlers[command]
            if handler:
                try:
                    handler(conn, args)
                except AgentError as e:
                    msg, = e.args
                    keyring.sendline(conn, msg)
                    continue
            keyring.sendline(conn, b'OK')
38962
def handle(conn, addr, gateway, *args, **kwargs):
    
    conn.sendall(b'OK pubsub 1.0\n')
    while True:
        try:
            s = conn.recv(1024).decode('utf-8').strip()
            if not s:
                conn.close()
                break
        except ConnectionResetError:
            logger.debug('Client close the connection.')
            break

        parts = s.split(' ')
        if len(parts) != 2:
            conn.send(b"Invalid command\n")
            continue
        cmd, topic = parts
        if cmd.lower() != 'sub':
            conn.send(bytes("Unknown command '{}'\n".format(cmd.lower()), 'utf-8'))
            continue
        if topic not in gateway.topics:
            conn.send(bytes("Unknown topic '{}'\n".format(topic), 'utf-8'))
            continue
        conn.sendall(bytes('ACK {} {}\n'.format(cmd, topic), 'utf-8'))
        subscriber = Subscriber(addr, conn)
        gateway.link(topic, subscriber)
        break
616884
def direct_command(self, device_id, command, command2, extended_payload=None):
        """"""
        extended_payload = extended_payload or ''
        if not extended_payload:
            msg_type = '0'
            msg_type_desc = 'Standard'
        else:
            msg_type = '1'
            msg_type_desc = 'Extended'

            extended_payload = extended_payload.ljust(26, '0')

            ### Determine checksum to add onto the payload for I2CS support
            checksum_payload_hex = [int("0x" + extended_payload[i:i+2],16) for i in range(0,len(extended_payload)-1,2)]
            checksum_payload_hex.insert(0, int("0x" + command2, 16))
            checksum_payload_hex.insert(0, int("0x" + command, 16))

            # Get sum of all hex bytes
            bytessum = 0
            for ch in checksum_payload_hex:
                bytessum += ch
            bytessumStr = hex(bytessum)

            # Get last byte of the bytessum
            lastByte = bytessumStr[-2:]
            lastByte = '0x' + lastByte.zfill(2)
            # Determine compliment of last byte
            lastByteHex = int(lastByte, 16)
            lastCompliment = lastByteHex ^ 0xFF
            # Add one to create checksum
            checksum = hex(lastCompliment + 0x01)
            # Remove 0x prefix
            checksum_final = (format(int(checksum, 16), 'x'))
            checksum_final = checksum_final.upper()
            #print("final checksum")
            #pprint.pprint(checksum_final)
            extended_payload = extended_payload + checksum_final

        self.logger.info("direct_command: Device: %s Command: %s Command 2: %s Extended: %s MsgType: %s", device_id, command, command2, extended_payload, msg_type_desc)
        device_id = device_id.upper()
        command_url = (self.hub_url + '/3?' + "0262"
                       + device_id + msg_type + "F"
                       + command + command2 + extended_payload + "=I=3")
        return self.post_direct_command(command_url)
551359
def str2long(s):
    """"""
    if type(s) not in (types.StringType, types.UnicodeType):
        raise ValueError('the input must be a string')

    l = 0
    for i in s:
        l <<= 8
        l |= ord(i)

    return l
1149925
def command_packet(cmd):
    
    return message('Command',
                   Container(string_length=len(cmd),
                             string=bytes(cmd, ENCODING)),
                   len(cmd) + 2)
1201207
def _echo_byte(self, byte):
        
        if byte == '\n':
            self.send_buffer += '\r'
        if self.telnet_echo_password:
            self.send_buffer += '*'
        else:
            self.send_buffer += byte
936309
def handle_ctrlchan(handler, msg, nick, send):
    """"""
    with handler.db.session_scope() as db:
        parser = init_parser(send, handler, nick, db)
        try:
            cmdargs = parser.parse_args(msg)
        except arguments.ArgumentException as e:
            # FIXME: figure out a better way to allow non-commands without spamming the channel.
            err_str = r"invalid choice: .* \(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\)"
            if not re.match(err_str, str(e)):
                send(str(e))
            return
        cmdargs.func(cmdargs)
742101
def respond(self):
        """"""
        mrbs = self.server.max_request_body_size
        if self.chunked_read:
            self.rfile = ChunkedRFile(self.conn.rfile, mrbs)
        else:
            cl = int(self.inheaders.get(b'Content-Length', 0))
            if mrbs and mrbs < cl:
                if not self.sent_headers:
                    self.simple_response(
                        '413 Request Entity Too Large',
                        'The entity sent with the request exceeds the '
                        'maximum allowed bytes.',
                    )
                return
            self.rfile = KnownLengthRFile(self.conn.rfile, cl)

        self.server.gateway(self).respond()
        self.ready and self.ensure_headers_sent()

        if self.chunked_write:
            self.conn.wfile.write(b'0\r\n\r\n')
1012353
def decodebytes(input):
    """"""
    py_version = sys.version_info[0]
    if py_version >= 3:
        return _decodebytes_py3(input)
    return _decodebytes_py2(input)
191762
def _handle_decoded_payload(self, data):
        '''
        
        '''
        # TODO: even do this??
        data['to'] = int(data.get('to', self.opts['timeout'])) - 1
        # Only forward the command if it didn't originate from ourselves
        if data.get('master_id', 0) != self.opts.get('master_id', 1):
            self.syndic_cmd(data)
440281
def handle_raw_packet(self, raw_packet):
        """"""
        log.debug('got packet: %s', raw_packet)
        if rflink_log:
            print(raw_packet, file=rflink_log)
            rflink_log.flush()
        packet = None
        try:
            packet = decode_packet(raw_packet)
        except:
            log.exception('failed to parse packet: %s', packet)

        log.debug('decoded packet: %s', packet)

        if packet:
            if 'ok' in packet:
                # handle response packets internally
                log.debug('command response: %s', packet)
                self._last_ack = packet
                self._command_ack.set()
            else:
                self.handle_packet(packet)
        else:
            log.warning('no valid packet')
1271103
def handle_lines(self):
        """"""
        while "\r\n" in self.buffer:
            line, self.buffer = self.buffer.split("\r\n", 1)
            if valid_packet(line):
                self.handle_raw_packet(line)
            else:
                log.warning('dropping invalid data: %s', line)
1076325
def write_longlong(self, n):
        
        if (n < 0) or (n >= (2**64)):
            raise ValueError('Octet out of range 0..2**64-1')
        self._flushbits()
        self.out.write(pack('>Q', n))
178926
def _command(self, sock_info, command, slave_ok=False, value=1, check=True,
                 allowable_errors=None, read_preference=ReadPreference.PRIMARY,
                 codec_options=DEFAULT_CODEC_OPTIONS,
                 write_concern=None,
                 parse_write_concern_error=False, **kwargs):
        """"""
        if isinstance(command, string_type):
            command = SON([(command, value)])

        if sock_info.max_wire_version >= 5 and write_concern:
            command['writeConcern'] = write_concern.document

        command.update(kwargs)

        return sock_info.command(
            self.__name,
            command,
            slave_ok,
            read_preference,
            codec_options,
            check,
            allowable_errors,
            parse_write_concern_error=parse_write_concern_error)