id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
161,791
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX IP_ADDRESS_WITH_PORT_REGEX = r"\b(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]{2,5}\b" def is_ip_address_with_port_format(value): if value and re.match(IP_ADDRESS_WITH_PORT_REGEX, value): return True else: return False
null
161,792
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX IPV6_ADDRESS_REGEX = r"^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$" def is_ipv6_address_format(value): if value and re.match(IPV6_ADDRESS_REGEX, value): return True else: return False
null
161,793
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX IPV6_URL_REGEX = r"(https?:\/\/)?\[((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\](:\d+)?(\/)?" def is_ipv6_url_format(value): if value and re.match(IPV6_URL_REGEX, value): return True else: return False
null
161,794
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX OLD_VERSION_CHARACTER = ("from comm import cmdline", "from comm import generic") def is_old_version_poc(poc_string): for _ in OLD_VERSION_CHARACTER: if _ in poc_string: return True return False
null
161,795
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX POCSUITE_VERSION_CHARACTER = ("from pocsuite.poc import", "from pocsuite.net import") def is_pocsuite_poc(poc_string): for _ in POCSUITE_VERSION_CHARACTER: if _ in poc_string: return True return False
null
161,796
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def is_pocsuite3_poc(poc_string): return True if "pocsuite3" in poc_string else False
null
161,797
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def multiple_replace(text, adict): rx = re.compile("|".join(map(re.escape, adict))) def get_replace(match): return adict[match.group(0)] return rx.sub(get_replace, text)
null
161,798
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def single_time_log_message(message, level=logging.INFO, flag=None): if flag is None: flag = hash(message) if flag not in kb.single_log_flags: kb.single_log_flags.add(flag) logger.log(level, message) def single_time_debug_message(message): single_time_log_message(message, logging.DEBUG)
null
161,799
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX LOCAL_IP_ADDRESS_REGEX = ( r"(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)" ) def is_local_ip(ip_string): ret = False if ip_string and isinstance(ip_string, str) and re.match(LOCAL_IP_ADDRESS_REGEX, ip_string): ret = True return ret
null
161,800
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def extract_regex_result(regex, content, flags=0): """ Returns 'result' group value from a possible match with regex on a given content >>> extract_regex_result(r'a(?P<result>[^g]+)g', 'abcdefg') 'bcdef' """ ret = None if regex and content and "?P<result>" in regex: match = re.search(regex, content, flags) if match: ret = match.group("result") return ret POC_REQUIRES_REGEX = r"install_requires\s*=\s*\[(?P<result>.*?)\]" def get_poc_requires(code): return extract_regex_result(POC_REQUIRES_REGEX, code)
null
161,801
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def is_os_64bit(): def write_file(data, file_ext='', file_name=''): def get_objective_code(asm_file, target_arch, debug=0): def objdump(obj_file, os_target_arch, debug=0): def generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug): def make_binary_from_obj(o_file, os_target, os_target_arch, debug=0, is_dll=False): class OS: class OS_ARCH: def create_shellcode(asm_code, os_target, os_target_arch, make_exe=0, debug=0, filename="", dll_inj_funcs=[]): if os_target == OS.LINUX: dll_inj_funcs = [] if not is_os_64bit() and os_target_arch == OS_ARCH.X64: print("ERR: can not create shellcode for this os_target_arch ({0}) on os_arch ({1})".format(os_target_arch, OS_ARCH.X64)) return None asm_file = write_file(asm_code, '.asm', filename) obj_file = get_objective_code(asm_file, os_target_arch, debug) # stage_2: if obj_file: shellcode = objdump(obj_file, os_target_arch, debug) shellcode = shellcode.replace('\\x', '').decode('hex') # shellcode = extract_shell_from_obj(obj_file) else: return None if make_exe: make_binary_from_obj(obj_file, os_target, os_target_arch, debug) if dll_inj_funcs: generate_dll(os_target, os_target_arch, asm_code, filename, dll_inj_funcs, debug) return shellcode, asm_file.split(".")[0]
null
161,802
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def extract_shell_from_obj(file): with open(file, 'rb') as f: contents = f.read() flag = contents[4] if flag == '\x01': length = struct.unpack('<H', contents[124:126])[0] contents = contents[272:272 + length] elif flag == '\x02': length = struct.unpack('<H', contents[160:162])[0] contents = contents[384:384 + length] else: raise Exception("Unknown architecture. Can't extract shellcode") print(', '.join('0x%02x' % ord(c) for c in contents)) return contents
null
161,803
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def replace_by_real_values(shellcode, kwargs): for key, value in kwargs.items(): shellcode = shellcode.replace(key, value) return shellcode
null
161,804
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def ip_to_hex(ip, is_big=True): parts = [int(part) for part in ip.split('.')] if is_big: return ''.join(chr(part) for part in parts).encode() return ''.join(chr(part) for part in reversed(parts)).encode()
null
161,805
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def port_to_hex(port, is_big=True): if is_big: return struct.pack('>H', port) return struct.pack('<H', port)
null
161,806
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def validate_ip_addr(addr): import socket try: socket.inet_aton(addr) return True except socket.error: return False
null
161,807
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def ip_to_dd(addr): return ''.join('%02x' % int(x) for x in reversed(addr.split('.'))).encode()
null
161,808
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def port_to_dd(port): return ''.join('%02x' % x for x in struct.pack('<H', port)).encode()
null
161,809
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX The provided code snippet includes necessary dependencies for implementing the `rtrim` function. Write a Python function `def rtrim(text, char)` to solve the following problem: Delete the specified character on the right :param text: str :param char: character :return: Here is the function: def rtrim(text, char): """ Delete the specified character on the right :param text: str :param char: character :return: """ length = len(char) if length > len(text): return text if char == text[-length:]: text = text[:-length] return text
Delete the specified character on the right :param text: str :param char: character :return:
161,810
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX The provided code snippet includes necessary dependencies for implementing the `humanize_path` function. Write a Python function `def humanize_path(path: str) -> str` to solve the following problem: Replace python dotted path to directory-like one. ex. foo.bar.baz -> foo/bar/baz :param str path: path to humanize :return str: humanized path Here is the function: def humanize_path(path: str) -> str: """ Replace python dotted path to directory-like one. ex. foo.bar.baz -> foo/bar/baz :param str path: path to humanize :return str: humanized path """ return path.replace(".", os.sep)
Replace python dotted path to directory-like one. ex. foo.bar.baz -> foo/bar/baz :param str path: path to humanize :return str: humanized path
161,811
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX The provided code snippet includes necessary dependencies for implementing the `pythonize_path` function. Write a Python function `def pythonize_path(path: str) -> str` to solve the following problem: Replaces argument to valid python dotted notation. ex. foo/bar/baz -> foo.bar.baz :param str path: path to pythonize :return str: pythonized path Here is the function: def pythonize_path(path: str) -> str: """ Replaces argument to valid python dotted notation. ex. foo/bar/baz -> foo.bar.baz :param str path: path to pythonize :return str: pythonized path """ return path.replace(os.sep, ".")
Replaces argument to valid python dotted notation. ex. foo/bar/baz -> foo.bar.baz :param str path: path to pythonize :return str: pythonized path
161,812
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX logger = LOGGER The provided code snippet includes necessary dependencies for implementing the `module_required` function. Write a Python function `def module_required(fn)` to solve the following problem: Checks if module is loaded. Decorator that checks if any module is activated before executing command specific to modules (ex. 'run'). Here is the function: def module_required(fn): """ Checks if module is loaded. Decorator that checks if any module is activated before executing command specific to modules (ex. 'run'). """ @wraps(fn) def wrapper(self, *args, **kwargs): if not self.current_module: logger.error("You have to activate any module with 'use' command.") return return fn(self, *args, **kwargs) try: name = "module_required" wrapper.__decorators__.append(name) except AttributeError: wrapper.__decorators__ = [name] return wrapper
Checks if module is loaded. Decorator that checks if any module is activated before executing command specific to modules (ex. 'run').
161,813
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX logger = LOGGER The provided code snippet includes necessary dependencies for implementing the `stop_after` function. Write a Python function `def stop_after(space_number)` to solve the following problem: Decorator that determines when to stop tab-completion Decorator that tells command specific complete function (ex. "complete_use") when to stop tab-completion. Decorator counts number of spaces (' ') in line in order to determine when to stop. ex. "use exploits/dlink/specific_module " -> stop complete after 2 spaces "set rhost " -> stop completing after 2 spaces "run " -> stop after 1 space :param space_number: number of spaces (' ') after which tab-completion should stop :return: Here is the function: def stop_after(space_number): """ Decorator that determines when to stop tab-completion Decorator that tells command specific complete function (ex. "complete_use") when to stop tab-completion. Decorator counts number of spaces (' ') in line in order to determine when to stop. ex. "use exploits/dlink/specific_module " -> stop complete after 2 spaces "set rhost " -> stop completing after 2 spaces "run " -> stop after 1 space :param space_number: number of spaces (' ') after which tab-completion should stop :return: """ def _outer_wrapper(wrapped_function): @wraps(wrapped_function) def _wrapper(self, *args, **kwargs): try: if args[1].count(" ") == space_number: return [] except Exception as err: logger.error(err) return wrapped_function(self, *args, **kwargs) return _wrapper return _outer_wrapper
Decorator that determines when to stop tab-completion Decorator that tells command specific complete function (ex. "complete_use") when to stop tab-completion. Decorator counts number of spaces (' ') in line in order to determine when to stop. ex. "use exploits/dlink/specific_module " -> stop complete after 2 spaces "set rhost " -> stop completing after 2 spaces "run " -> stop after 1 space :param space_number: number of spaces (' ') after which tab-completion should stop :return:
161,814
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX logger = LOGGER IS_WIN = True if (sys.platform in ["win32", "cygwin"] or os.name == "nt") else False def exec_cmd(cmd, raw_data=True): cmd = shlex.split(cmd) out_data = b'' try: p = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while p.poll() is None: line = p.stdout.read() out_data += line except Exception as ex: logger.error("Execute cmd error {}".format(str(ex))) encoding = chardet.detect(out_data).get('encoding') encoding = encoding if encoding else 'utf-8' if IS_WIN: out_data = out_data.split(b'\r\n\r\n') else: out_data = out_data.split(b'\n\n') if not raw_data: for i, data in enumerate(out_data): out_data[i] = data.decode(encoding, errors='ignore') return out_data
null
161,815
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def encoder_bash_payload(cmd: str) -> str: ret = "bash -c '{echo,%s}|{base64,-d}|{bash,-i}'" % base64.b64encode(cmd.encode()).decode() return ret
null
161,816
import base64 import hashlib import inspect import logging import os import re import select import shlex import socket import struct import subprocess import sys import time import collections import chardet import requests import urllib from collections import OrderedDict from functools import wraps from ipaddress import ip_address, ip_network from platform import machine from subprocess import call, Popen, PIPE from colorama.initialise import init as coloramainit from termcolor import colored from pocsuite3.lib.core.convert import stdout_encode from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.data import kb from pocsuite3.lib.core.data import logger from pocsuite3.lib.core.data import paths from pocsuite3.lib.core.decorators import cachedmethod from pocsuite3.lib.core.enums import OS_ARCH, OS from pocsuite3.lib.core.exception import PocsuiteSystemException from pocsuite3.lib.core.log import LOGGER_HANDLER from pocsuite3.lib.core.settings import ( BANNER, BOLD_PATTERNS, IS_WIN, URL_DOMAIN_REGEX, LOCAL_IP_ADDRESS_REGEX, IP_ADDRESS_WITH_PORT_REGEX, IPV6_URL_REGEX, TIMESTAMP, OS_SYSTEM) from pocsuite3.lib.core.settings import IPV6_ADDRESS_REGEX from pocsuite3.lib.core.settings import IP_ADDRESS_REGEX from pocsuite3.lib.core.settings import OLD_VERSION_CHARACTER from pocsuite3.lib.core.settings import POCSUITE_VERSION_CHARACTER from pocsuite3.lib.core.settings import POC_REQUIRES_REGEX from pocsuite3.lib.core.settings import UNICODE_ENCODING from pocsuite3.lib.core.settings import URL_ADDRESS_REGEX def encoder_powershell_payload(powershell: str): command = "powershell -NonI -W Hidden -NoP -Exec Bypass -Enc " + base64.b64encode( '\x00'.join(list(powershell)).encode() + b'\x00').decode() return command
null
161,817
import os import re import subprocess def stdout_encode(data): """ Cross-linked function """ if isinstance(data, bytes): data = data.decode('utf-8') else: data = str(data) return data The provided code snippet includes necessary dependencies for implementing the `get_revision_number` function. Write a Python function `def get_revision_number()` to solve the following problem: Returns abbreviated commit hash number as retrieved with "git rev-parse --short HEAD" Here is the function: def get_revision_number(): """ Returns abbreviated commit hash number as retrieved with "git rev-parse --short HEAD" """ ret = None file_path = None _ = os.path.dirname(__file__) while True: file_path = os.path.join(_, ".git", "HEAD") if os.path.exists(file_path): break else: file_path = None if _ == os.path.dirname(_): break else: _ = os.path.dirname(_) while True: if file_path and os.path.isfile(file_path): with open(file_path, "r") as f: content = f.read() file_path = None if content.startswith("ref: "): file_path = os.path.join(_, ".git", content.replace("ref: ", "")).strip() else: match = re.match(r"(?i)[0-9a-f]{32}", content) ret = match.group(0) if match else None break else: break if not ret: process = subprocess.Popen("git rev-parse --verify HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() stdout = stdout_encode(stdout) match = re.search(r"(?i)[0-9a-f]{32}", stdout or "") ret = match.group(0) if match else None return ret[:7] if ret else None
Returns abbreviated commit hash number as retrieved with "git rev-parse --short HEAD"
161,818
import struct class Constants: STREAM_MAGIC = 0xaced STREAM_VERSION = 5 TC_NULL = 0x70 TC_REFERENCE = 0x71 TC_CLASSDESC = 0x72 TC_OBJECT = 0x73 TC_STRING = 0x74 TC_ARRAY = 0x75 TC_CLASS = 0x76 TC_BLOCKDATA = 0x77 TC_ENDBLOCKDATA = 0x78 TC_RESET = 0x79 TC_BLOCKDATALONG = 0x7A TC_EXCEPTION = 0x7B TC_LONGSTRING = 0x7C TC_PROXYCLASSDESC = 0x7D TC_ENUM = 0x7E BASE_WIRE_HANDLE = 0x7E0000 PRIMITIVE_TYPE_CODES = { 'B': 'byte', 'C': 'char', 'D': 'double', 'F': 'float', 'I': 'int', 'J': 'long', 'S': 'short', 'Z': 'boolean' } OBJECT_TYPE_CODES = { '[': 'array', 'L': 'object' } TYPE_CODES = {} TYPE_CODES.update(PRIMITIVE_TYPE_CODES) TYPE_CODES.update(OBJECT_TYPE_CODES) SC_WRITE_METHOD = 0x01 # if SC_SERIALIZABLE SC_BLOCK_DATA = 0x08 # if SC_EXTERNALIZABLE SC_SERIALIZABLE = 0x02 SC_EXTERNALIZABLE = 0x04 SC_ENUM = 0x10 class BlockData(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(1) if not raw_length: raise Exception('Failed to unserialize BlockData') self.length = struct.unpack('>B', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockData') return self def encode(self): encoded = struct.pack(">B", self.length) encoded += self.contents return encoded def __str__(self): ret = '[' ret += ', '.join("0x%s" % byte.encode('hex') for byte in self.contents) ret += ']' return ret class BlockDataLong(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(4) if not raw_length or len(raw_length) != 4: raise Exception('Failed to unserialize BlockDataLong') self.length = struct.unpack('>i', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockDataLong') return self def encode(self): encoded = struct.pack(">I", [self.length]) encoded += self.contents return encoded def __str__(self): return self.contents.__str__() class EndBlockData(Element): pass class NewArray(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.array_description = None self.type = '' self.values = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.array_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.type = self.array_type() values_length = self.decode_values_length(io) for i in range(values_length): value = self.decode_value(io) self.values.append(value) return self def encode(self): if self.array_description.__class__ is not ClassDesc: raise Exception('Failed to serialize NewArray') encoded = '' encoded += self.array_description.encode() encoded += struct.pack(">I", len(self.values)) for value in self.values: encoded += self.encode_value(value) return encoded def decode_values_length(self, io): values_length = io.read(4) if not values_length or len(values_length) != 4: raise Exception('Failed to unserialize NewArray') return struct.unpack('>I', values_length)[0] def array_type(self): if not self.array_description: raise Exception('Empty NewArray description') if self.array_description.__class__ is not ClassDesc: raise Exception('Unsupported NewArray description class') desc = self.array_description.description if desc.__class__ is Reference: ref = desc.handle - Constants.BASE_WIRE_HANDLE desc = self.stream.references[ref] if desc.class_name.contents[0] != '[': # array raise Exception('Unsupported NewArray description') decoded_type = desc.class_name.contents[1] if decoded_type in Constants.PRIMITIVE_TYPE_CODES.keys(): return Constants.PRIMITIVE_TYPE_CODES[decoded_type] elif decoded_type == 'L': # object return desc.class_name.contents[2:desc.class_name.contents.index(';')] else: raise Exception('Unsupported NewArray Type') def decode_value(self, io): if self.type == 'byte': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'char': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>ss', value)[0] elif self.type == 'boolean': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'short': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>H', value)[0] elif self.type == 'int': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>I', value)[0] elif self.type == 'long': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>Q', value)[0] elif self.type == 'float': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>F', value)[0] elif self.type == 'double': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>D', value)[0] else: value = decode_content(io, self.stream) return value def encode_value(self, value): if self.type == 'byte': res = struct.pack('>B', value) elif self.type == 'char': res = struct.pack('>ss', value) elif self.type == 'double': res = struct.pack('>D', value) elif self.type == 'float': res = struct.pack('>F', value) elif self.type == 'int': res = struct.pack('>I', value) elif self.type == 'long': res = struct.pack('>Q', value) elif self.type == 'short': res = struct.pack('>H', value) elif self.type == 'boolean': res = struct.pack('>B', value) elif self.type.__class__ is Element: res = value.encode() else: res = encode_content(value) return res def __str__(self): ret = self.type.__str__() + ', ' ret += '\n'.join(value.__str__() for value in self.values) return ret class NewClass(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_description = None def decode(self, io): class_desc = ClassDesc(self.stream) self.class_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) return self def encode(self): if self.class_description.__class__ != ClassDesc: raise Exception('Failed to serialize NewClass') encoded = '' encoded += self.class_description.encode() return encoded def __str__(self): return self.class_description.__str__() class NewClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_name = "" self.serial_version = 0 self.flags = 0 self.fields = [] self.class_annotation = None self.super_class = None def decode(self, io): utf = Utf(self.stream) self.class_name = utf.decode(io) self.serial_version = self.decode_serial_version(io) if self.stream: self.stream.add_reference(self) self.flags = self.decode_flags(io) field_length = self.decode_fields_length(io) for i in range(0, field_length): temp_field = Field(self.stream) field = temp_field.decode(io) self.fields.append(field) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_name.__class__ is not Utf \ and self.class_annotation.__class__ is not Annotation \ and self.super_class.__class__ is not ClassDesc: raise Exception('Filed to serialize NewClassDesc') encoded = '' encoded += self.class_name.encode() encoded += struct.pack('>Q', self.serial_version) encoded += struct.pack('>B', self.flags) encoded += struct.pack('>H', len(self.fields)) for field in self.fields: encoded += field.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_serial_version(self, io): raw_serial = io.read(8) if not raw_serial or len(raw_serial) != 8: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>Q', raw_serial)[0] def decode_flags(self, io): raw_flags = io.read(1) if not raw_flags: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>b', raw_flags)[0] def decode_fields_length(self, io): fields_length = io.read(2) if not fields_length or len(fields_length) != 2: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>h', fields_length)[0] def __str__(self): ret = self.class_name.__str__() + ", [" ret += ', '.join(field.__str__() for field in self.fields) ret += ']' # if self.super_class.description.__class__ is NewClassDesc: # ret += ", super_class: " + self.super_class.description.class_name.__str__() # elif self.super_class.description.__class__ is Reference: # ret += ", super_class: " + self.super_class.description.__str__() return ret class NewEnum(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.enum_description = None self.constant_name = None def decode(self, io): class_desc = ClassDesc(self.stream) self.enum_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.constant_name = self.decode_constant_name(io) return self def encode(self): if self.enum_description.__class__ is not ClassDesc or self.constant_name.__class__ is not Utf: raise Exception('Failed to serialize EnumDescription') encoded = '' encoded += self.enum_description.encode() encoded += encode_content(self.constant_name) return encoded def decode_constant_name(self, io): content = decode_content(io, self.stream) if content.__class__ is not Utf: raise Exception('Failed to unserialize NewEnum') return content class NewObject(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.class_desc = None self.class_data = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.class_desc = class_desc.decode(io) if self.stream: self.stream.add_reference(self) if self.class_desc.description.__class__ is NewClassDesc: self.class_data = self.decode_class_data(io, self.class_desc.description) elif self.class_desc.description.__class__ is Reference: ref = self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE self.class_data = self.decode_class_data(io, self.stream.references[ref]) return self def encode(self): if self.class_desc.__class__ is not ClassDesc: raise Exception('Failed to serialize NewObject') encoded = '' encoded += self.class_desc.encode() for value in self.class_data: if type(value) is list: encoded += self.encode_value(value) else: encoded += encode_content(value) return encoded def decode_class_data(self, io, my_class_desc): values = [] if my_class_desc.super_class.description.__class__ is not NullReference: if my_class_desc.super_class.description.__class__ is Reference: ref = my_class_desc.super_class.description.handle - Constants.BASE_WIRE_HANDLE values.extend(self.decode_class_data(io, self.stream.references[ref])) else: values.extend(self.decode_class_data(io, my_class_desc.super_class.description)) values.extend(self.decode_class_fields(io, my_class_desc)) return values def decode_class_fields(self, io, my_class_desc): values = [] for field in my_class_desc.fields: if field.is_primitive(): values.append(self.decode_value(io, field.type)) else: content = decode_content(io, self.stream) values.append(content) return values def decode_value(self, io, type): if type == 'byte': value_raw = io.read(1) val = struct.unpack(">b", value_raw)[0] value = ['byte', val] elif type == 'char': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['char', val] elif type == 'boolean': value_raw = io.read(1) val = struct.unpack(">B", value_raw)[0] value = ['boolean', val] elif type == 'short': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['short', val] elif type == 'int': value_raw = io.read(4) val = struct.unpack(">i", value_raw)[0] value = ['int', val] elif type == 'long': value_raw = io.read(8) val = struct.unpack(">q", value_raw)[0] value = ['long', val] elif type == 'float': value_raw = io.read(4) val = struct.unpack(">f", value_raw)[0] value = ['float', val] elif type == 'double': value_raw = io.read(8) val = struct.unpack(">d", value_raw)[0] value = ['double', val] else: raise Exception("Unknown typecode: %s" % type) return value def encode_value(self, value): res = '' if value[0] == 'byte': res = struct.pack('>b', value[1]) elif value[0] == 'char': res = struct.pack('>h', value[1]) elif value[0] == 'double': res = struct.pack('>d', value[1]) elif value[0] == 'float': res = struct.pack('>f', value[1]) elif value[0] == 'int': res = struct.pack('>i', value[1]) elif value[0] == 'long': res = struct.pack('>Q', value[1]) elif value[0] == 'short': res = struct.pack('>h', value[1]) elif value[0] == 'boolean': res = struct.pack('>B', value[1]) else: raise Exception('Unsupported NewArray type') return res def __str__(self): ret = '' if self.class_desc.description.__class__ is NewClassDesc: ret += self.class_desc.description.class_name.__str__() elif self.class_desc.description.__class__ is ProxyClassDesc: ret += ','.join(iface.contents.__str__() for iface in self.class_desc.description.interfaces) elif self.class_desc.description.__class__ is Reference: ret += hex(self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE) ret += ' => {' data_str = ', '.join(data.__str__() for data in self.class_data) ret += data_str ret += '}' return ret class NullReference(Element): pass class ProxyClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.interfaces = [] self.class_annotation = None self.super_class = None def decode(self, io): if self.stream: self.stream.add_reference(self) interfaces_length = self.decode_interfaces_length(io) for i in range(0, interfaces_length): utf = Utf(self.stream) interface = utf.decode(io) self.interfaces.append(interface) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc: raise Exception('Failed to serialize ProxyClassDesc') encoded = '' encoded += struct.pack('>I', len(self.interfaces)) for interface in self.interfaces: encoded += interface.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_interfaces_length(self, io): field_length = io.read(4) if not field_length or len(field_length) != 4: raise Exception('Failed to unserialize ProxyClassDesc') return struct.unpack('>I', field_length)[0] def __str__(self): ret = '[' interfaces_str = ', '.join(interface.__str__() for interface in self.interfaces) ret += interfaces_str + ']' if self.super_class.description.__class__ is NewClassDesc: ret += ", super_class: " + self.super_class.description.class_name.__str__() elif self.super_class.description.__class__ is Reference: ret += ", super_class: " + self.super_class.description.__str__() return ret class Reference(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.handle = 0 def decode(self, io): handle_raw = io.read(4) if not handle_raw or len(handle_raw) != 4: raise Exception('Failed to unserialize Reference') self.handle = struct.unpack('>I', handle_raw)[0] return self def encode(self): if self.handle < Constants.BASE_WIRE_HANDLE: raise Exception('Failed to serialize Reference') encoded = "" encoded += struct.pack('>I', self.handle) return encoded def __str__(self): return hex(self.handle) class Reset(Element): pass class Utf(Element): def __init__(self, stream='', contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(2) if not raw_length or len(raw_length) != 2: raise Exception('Failed to unserialize Utf') self.length = struct.unpack('>H', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize Utf') return self def encode(self): encoded = struct.pack('>H', self.length) encoded += self.contents return encoded def __str__(self): return self.contents class LongUtf(Utf): def decode(self, io): raw_length = io.read(8) if not raw_length or len(raw_length) != 8: raise Exception('Failed to unserialize LongUtf') self.length = struct.unpack('>Q', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize LongUtf') return self def encode(self): encoded = struct.pack('>Q', [self.length]) encoded += self.contents return encoded def decode_content(io, stream): opcode = io.read(1) if not opcode: raise EOFError() opcode = struct.unpack('>B', opcode)[0] if opcode == Constants.TC_BLOCKDATA: block_data = BlockData(stream) content = block_data.decode(io) elif opcode == Constants.TC_BLOCKDATALONG: block_data_long = BlockDataLong(stream) content = block_data_long.decode(io) elif opcode == Constants.TC_ENDBLOCKDATA: end_bd = EndBlockData(stream) content = end_bd.decode(io) elif opcode == Constants.TC_OBJECT: new_object = NewObject(stream) content = new_object.decode(io) elif opcode == Constants.TC_CLASS: new_class = NewClass(stream) content = new_class.decode(io) elif opcode == Constants.TC_ARRAY: new_array = NewArray(stream) content = new_array.decode(io) elif opcode == Constants.TC_STRING: utf = Utf(stream) content = utf.decode(io) if stream: stream.add_reference(content) elif opcode == Constants.TC_LONGSTRING: long_utf = LongUtf(stream) content = long_utf.decode(io) if stream: stream.add_reference(content) elif opcode == Constants.TC_ENUM: new_enum = NewEnum(stream) content = new_enum.decode(io) elif opcode == Constants.TC_CLASSDESC: new_class_desc = NewClassDesc(stream) content = new_class_desc.decode(io) elif opcode == Constants.TC_PROXYCLASSDESC: proxy = ProxyClassDesc(stream) content = proxy.decode(io) elif opcode == Constants.TC_REFERENCE: ref = Reference(stream) content = ref.decode(io) elif opcode == Constants.TC_NULL: ref = NullReference(stream) content = ref.decode(io) elif opcode == Constants.TC_EXCEPTION: raise Exception("Failed to unserialize unsupported TC_EXCEPTION content") elif opcode == Constants.TC_RESET: reset = Reset(stream) content = reset.decode(io) else: raise Exception('Failed to unserialize content') return content
null
161,819
import struct class Constants: STREAM_MAGIC = 0xaced STREAM_VERSION = 5 TC_NULL = 0x70 TC_REFERENCE = 0x71 TC_CLASSDESC = 0x72 TC_OBJECT = 0x73 TC_STRING = 0x74 TC_ARRAY = 0x75 TC_CLASS = 0x76 TC_BLOCKDATA = 0x77 TC_ENDBLOCKDATA = 0x78 TC_RESET = 0x79 TC_BLOCKDATALONG = 0x7A TC_EXCEPTION = 0x7B TC_LONGSTRING = 0x7C TC_PROXYCLASSDESC = 0x7D TC_ENUM = 0x7E BASE_WIRE_HANDLE = 0x7E0000 PRIMITIVE_TYPE_CODES = { 'B': 'byte', 'C': 'char', 'D': 'double', 'F': 'float', 'I': 'int', 'J': 'long', 'S': 'short', 'Z': 'boolean' } OBJECT_TYPE_CODES = { '[': 'array', 'L': 'object' } TYPE_CODES = {} TYPE_CODES.update(PRIMITIVE_TYPE_CODES) TYPE_CODES.update(OBJECT_TYPE_CODES) SC_WRITE_METHOD = 0x01 # if SC_SERIALIZABLE SC_BLOCK_DATA = 0x08 # if SC_EXTERNALIZABLE SC_SERIALIZABLE = 0x02 SC_EXTERNALIZABLE = 0x04 SC_ENUM = 0x10 class BlockData(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(1) if not raw_length: raise Exception('Failed to unserialize BlockData') self.length = struct.unpack('>B', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockData') return self def encode(self): encoded = struct.pack(">B", self.length) encoded += self.contents return encoded def __str__(self): ret = '[' ret += ', '.join("0x%s" % byte.encode('hex') for byte in self.contents) ret += ']' return ret class BlockDataLong(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(4) if not raw_length or len(raw_length) != 4: raise Exception('Failed to unserialize BlockDataLong') self.length = struct.unpack('>i', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockDataLong') return self def encode(self): encoded = struct.pack(">I", [self.length]) encoded += self.contents return encoded def __str__(self): return self.contents.__str__() class EndBlockData(Element): pass class NewArray(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.array_description = None self.type = '' self.values = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.array_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.type = self.array_type() values_length = self.decode_values_length(io) for i in range(values_length): value = self.decode_value(io) self.values.append(value) return self def encode(self): if self.array_description.__class__ is not ClassDesc: raise Exception('Failed to serialize NewArray') encoded = '' encoded += self.array_description.encode() encoded += struct.pack(">I", len(self.values)) for value in self.values: encoded += self.encode_value(value) return encoded def decode_values_length(self, io): values_length = io.read(4) if not values_length or len(values_length) != 4: raise Exception('Failed to unserialize NewArray') return struct.unpack('>I', values_length)[0] def array_type(self): if not self.array_description: raise Exception('Empty NewArray description') if self.array_description.__class__ is not ClassDesc: raise Exception('Unsupported NewArray description class') desc = self.array_description.description if desc.__class__ is Reference: ref = desc.handle - Constants.BASE_WIRE_HANDLE desc = self.stream.references[ref] if desc.class_name.contents[0] != '[': # array raise Exception('Unsupported NewArray description') decoded_type = desc.class_name.contents[1] if decoded_type in Constants.PRIMITIVE_TYPE_CODES.keys(): return Constants.PRIMITIVE_TYPE_CODES[decoded_type] elif decoded_type == 'L': # object return desc.class_name.contents[2:desc.class_name.contents.index(';')] else: raise Exception('Unsupported NewArray Type') def decode_value(self, io): if self.type == 'byte': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'char': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>ss', value)[0] elif self.type == 'boolean': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'short': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>H', value)[0] elif self.type == 'int': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>I', value)[0] elif self.type == 'long': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>Q', value)[0] elif self.type == 'float': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>F', value)[0] elif self.type == 'double': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>D', value)[0] else: value = decode_content(io, self.stream) return value def encode_value(self, value): if self.type == 'byte': res = struct.pack('>B', value) elif self.type == 'char': res = struct.pack('>ss', value) elif self.type == 'double': res = struct.pack('>D', value) elif self.type == 'float': res = struct.pack('>F', value) elif self.type == 'int': res = struct.pack('>I', value) elif self.type == 'long': res = struct.pack('>Q', value) elif self.type == 'short': res = struct.pack('>H', value) elif self.type == 'boolean': res = struct.pack('>B', value) elif self.type.__class__ is Element: res = value.encode() else: res = encode_content(value) return res def __str__(self): ret = self.type.__str__() + ', ' ret += '\n'.join(value.__str__() for value in self.values) return ret class NewClass(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_description = None def decode(self, io): class_desc = ClassDesc(self.stream) self.class_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) return self def encode(self): if self.class_description.__class__ != ClassDesc: raise Exception('Failed to serialize NewClass') encoded = '' encoded += self.class_description.encode() return encoded def __str__(self): return self.class_description.__str__() class NewClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_name = "" self.serial_version = 0 self.flags = 0 self.fields = [] self.class_annotation = None self.super_class = None def decode(self, io): utf = Utf(self.stream) self.class_name = utf.decode(io) self.serial_version = self.decode_serial_version(io) if self.stream: self.stream.add_reference(self) self.flags = self.decode_flags(io) field_length = self.decode_fields_length(io) for i in range(0, field_length): temp_field = Field(self.stream) field = temp_field.decode(io) self.fields.append(field) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_name.__class__ is not Utf \ and self.class_annotation.__class__ is not Annotation \ and self.super_class.__class__ is not ClassDesc: raise Exception('Filed to serialize NewClassDesc') encoded = '' encoded += self.class_name.encode() encoded += struct.pack('>Q', self.serial_version) encoded += struct.pack('>B', self.flags) encoded += struct.pack('>H', len(self.fields)) for field in self.fields: encoded += field.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_serial_version(self, io): raw_serial = io.read(8) if not raw_serial or len(raw_serial) != 8: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>Q', raw_serial)[0] def decode_flags(self, io): raw_flags = io.read(1) if not raw_flags: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>b', raw_flags)[0] def decode_fields_length(self, io): fields_length = io.read(2) if not fields_length or len(fields_length) != 2: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>h', fields_length)[0] def __str__(self): ret = self.class_name.__str__() + ", [" ret += ', '.join(field.__str__() for field in self.fields) ret += ']' # if self.super_class.description.__class__ is NewClassDesc: # ret += ", super_class: " + self.super_class.description.class_name.__str__() # elif self.super_class.description.__class__ is Reference: # ret += ", super_class: " + self.super_class.description.__str__() return ret class NewEnum(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.enum_description = None self.constant_name = None def decode(self, io): class_desc = ClassDesc(self.stream) self.enum_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.constant_name = self.decode_constant_name(io) return self def encode(self): if self.enum_description.__class__ is not ClassDesc or self.constant_name.__class__ is not Utf: raise Exception('Failed to serialize EnumDescription') encoded = '' encoded += self.enum_description.encode() encoded += encode_content(self.constant_name) return encoded def decode_constant_name(self, io): content = decode_content(io, self.stream) if content.__class__ is not Utf: raise Exception('Failed to unserialize NewEnum') return content class NewObject(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.class_desc = None self.class_data = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.class_desc = class_desc.decode(io) if self.stream: self.stream.add_reference(self) if self.class_desc.description.__class__ is NewClassDesc: self.class_data = self.decode_class_data(io, self.class_desc.description) elif self.class_desc.description.__class__ is Reference: ref = self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE self.class_data = self.decode_class_data(io, self.stream.references[ref]) return self def encode(self): if self.class_desc.__class__ is not ClassDesc: raise Exception('Failed to serialize NewObject') encoded = '' encoded += self.class_desc.encode() for value in self.class_data: if type(value) is list: encoded += self.encode_value(value) else: encoded += encode_content(value) return encoded def decode_class_data(self, io, my_class_desc): values = [] if my_class_desc.super_class.description.__class__ is not NullReference: if my_class_desc.super_class.description.__class__ is Reference: ref = my_class_desc.super_class.description.handle - Constants.BASE_WIRE_HANDLE values.extend(self.decode_class_data(io, self.stream.references[ref])) else: values.extend(self.decode_class_data(io, my_class_desc.super_class.description)) values.extend(self.decode_class_fields(io, my_class_desc)) return values def decode_class_fields(self, io, my_class_desc): values = [] for field in my_class_desc.fields: if field.is_primitive(): values.append(self.decode_value(io, field.type)) else: content = decode_content(io, self.stream) values.append(content) return values def decode_value(self, io, type): if type == 'byte': value_raw = io.read(1) val = struct.unpack(">b", value_raw)[0] value = ['byte', val] elif type == 'char': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['char', val] elif type == 'boolean': value_raw = io.read(1) val = struct.unpack(">B", value_raw)[0] value = ['boolean', val] elif type == 'short': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['short', val] elif type == 'int': value_raw = io.read(4) val = struct.unpack(">i", value_raw)[0] value = ['int', val] elif type == 'long': value_raw = io.read(8) val = struct.unpack(">q", value_raw)[0] value = ['long', val] elif type == 'float': value_raw = io.read(4) val = struct.unpack(">f", value_raw)[0] value = ['float', val] elif type == 'double': value_raw = io.read(8) val = struct.unpack(">d", value_raw)[0] value = ['double', val] else: raise Exception("Unknown typecode: %s" % type) return value def encode_value(self, value): res = '' if value[0] == 'byte': res = struct.pack('>b', value[1]) elif value[0] == 'char': res = struct.pack('>h', value[1]) elif value[0] == 'double': res = struct.pack('>d', value[1]) elif value[0] == 'float': res = struct.pack('>f', value[1]) elif value[0] == 'int': res = struct.pack('>i', value[1]) elif value[0] == 'long': res = struct.pack('>Q', value[1]) elif value[0] == 'short': res = struct.pack('>h', value[1]) elif value[0] == 'boolean': res = struct.pack('>B', value[1]) else: raise Exception('Unsupported NewArray type') return res def __str__(self): ret = '' if self.class_desc.description.__class__ is NewClassDesc: ret += self.class_desc.description.class_name.__str__() elif self.class_desc.description.__class__ is ProxyClassDesc: ret += ','.join(iface.contents.__str__() for iface in self.class_desc.description.interfaces) elif self.class_desc.description.__class__ is Reference: ret += hex(self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE) ret += ' => {' data_str = ', '.join(data.__str__() for data in self.class_data) ret += data_str ret += '}' return ret class NullReference(Element): pass class ProxyClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.interfaces = [] self.class_annotation = None self.super_class = None def decode(self, io): if self.stream: self.stream.add_reference(self) interfaces_length = self.decode_interfaces_length(io) for i in range(0, interfaces_length): utf = Utf(self.stream) interface = utf.decode(io) self.interfaces.append(interface) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc: raise Exception('Failed to serialize ProxyClassDesc') encoded = '' encoded += struct.pack('>I', len(self.interfaces)) for interface in self.interfaces: encoded += interface.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_interfaces_length(self, io): field_length = io.read(4) if not field_length or len(field_length) != 4: raise Exception('Failed to unserialize ProxyClassDesc') return struct.unpack('>I', field_length)[0] def __str__(self): ret = '[' interfaces_str = ', '.join(interface.__str__() for interface in self.interfaces) ret += interfaces_str + ']' if self.super_class.description.__class__ is NewClassDesc: ret += ", super_class: " + self.super_class.description.class_name.__str__() elif self.super_class.description.__class__ is Reference: ret += ", super_class: " + self.super_class.description.__str__() return ret class Reference(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.handle = 0 def decode(self, io): handle_raw = io.read(4) if not handle_raw or len(handle_raw) != 4: raise Exception('Failed to unserialize Reference') self.handle = struct.unpack('>I', handle_raw)[0] return self def encode(self): if self.handle < Constants.BASE_WIRE_HANDLE: raise Exception('Failed to serialize Reference') encoded = "" encoded += struct.pack('>I', self.handle) return encoded def __str__(self): return hex(self.handle) class Reset(Element): pass class Utf(Element): def __init__(self, stream='', contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(2) if not raw_length or len(raw_length) != 2: raise Exception('Failed to unserialize Utf') self.length = struct.unpack('>H', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize Utf') return self def encode(self): encoded = struct.pack('>H', self.length) encoded += self.contents return encoded def __str__(self): return self.contents class LongUtf(Utf): def decode(self, io): raw_length = io.read(8) if not raw_length or len(raw_length) != 8: raise Exception('Failed to unserialize LongUtf') self.length = struct.unpack('>Q', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize LongUtf') return self def encode(self): encoded = struct.pack('>Q', [self.length]) encoded += self.contents return encoded def encode_content(content): # TODO encode content encoded = '' if content.__class__ is BlockData: encoded += struct.pack('>B', Constants.TC_BLOCKDATA) elif content.__class__ is BlockDataLong: encoded += struct.pack('>B', Constants.TC_BLOCKDATALONG) elif content.__class__ is EndBlockData: encoded += struct.pack('>B', Constants.TC_ENDBLOCKDATA) elif content.__class__ is NewObject: encoded += struct.pack('>B', Constants.TC_OBJECT) elif content.__class__ is NewClass: encoded += struct.pack('>B', Constants.TC_CLASS) elif content.__class__ is NewArray: encoded += struct.pack('>B', Constants.TC_ARRAY) elif content.__class__ is Utf: encoded += struct.pack('>B', Constants.TC_STRING) elif content.__class__ is LongUtf: encoded += struct.pack('>B', Constants.TC_LONGSTRING) elif content.__class__ is NewEnum: encoded += struct.pack('>B', Constants.TC_ENUM) elif content.__class__ is NewClassDesc: encoded += struct.pack('>B', Constants.TC_CLASSDESC) elif content.__class__ is ProxyClassDesc: encoded += struct.pack('>B', Constants.TC_PROXYCLASSDESC) elif content.__class__ is NullReference: encoded += struct.pack('>B', Constants.TC_NULL) elif content.__class__ is Reset: encoded += struct.pack('>B', Constants.TC_RESET) elif content.__class__ is Reference: encoded += struct.pack('>B', Constants.TC_REFERENCE) else: raise Exception('Failed to serialize content') encoded += content.encode() return encoded
null
161,820
import struct class BlockData(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(1) if not raw_length: raise Exception('Failed to unserialize BlockData') self.length = struct.unpack('>B', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockData') return self def encode(self): encoded = struct.pack(">B", self.length) encoded += self.contents return encoded def __str__(self): ret = '[' ret += ', '.join("0x%s" % byte.encode('hex') for byte in self.contents) ret += ']' return ret class BlockDataLong(Element): def __init__(self, stream=None, contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(4) if not raw_length or len(raw_length) != 4: raise Exception('Failed to unserialize BlockDataLong') self.length = struct.unpack('>i', raw_length)[0] if self.length == 0: self.contents = '' else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize BlockDataLong') return self def encode(self): encoded = struct.pack(">I", [self.length]) encoded += self.contents return encoded def __str__(self): return self.contents.__str__() class ClassDesc(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.description = None def decode(self, io): content = decode_content(io, self.stream) allowed_content = [NullReference, NewClassDesc, Reference, ProxyClassDesc] if content.__class__ not in allowed_content: raise Exception('ClassDesc unserialize failed') self.description = content return self def encode(self): encoded = '' allowed_contents = [NullReference, NewClassDesc, Reference, ProxyClassDesc] if self.description.__class__ not in allowed_contents: raise Exception('ClassDesc unserialize failed') encoded += encode_content(self.description) return encoded def __str__(self): return print_content(self.description) class EndBlockData(Element): pass class NewArray(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.array_description = None self.type = '' self.values = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.array_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.type = self.array_type() values_length = self.decode_values_length(io) for i in range(values_length): value = self.decode_value(io) self.values.append(value) return self def encode(self): if self.array_description.__class__ is not ClassDesc: raise Exception('Failed to serialize NewArray') encoded = '' encoded += self.array_description.encode() encoded += struct.pack(">I", len(self.values)) for value in self.values: encoded += self.encode_value(value) return encoded def decode_values_length(self, io): values_length = io.read(4) if not values_length or len(values_length) != 4: raise Exception('Failed to unserialize NewArray') return struct.unpack('>I', values_length)[0] def array_type(self): if not self.array_description: raise Exception('Empty NewArray description') if self.array_description.__class__ is not ClassDesc: raise Exception('Unsupported NewArray description class') desc = self.array_description.description if desc.__class__ is Reference: ref = desc.handle - Constants.BASE_WIRE_HANDLE desc = self.stream.references[ref] if desc.class_name.contents[0] != '[': # array raise Exception('Unsupported NewArray description') decoded_type = desc.class_name.contents[1] if decoded_type in Constants.PRIMITIVE_TYPE_CODES.keys(): return Constants.PRIMITIVE_TYPE_CODES[decoded_type] elif decoded_type == 'L': # object return desc.class_name.contents[2:desc.class_name.contents.index(';')] else: raise Exception('Unsupported NewArray Type') def decode_value(self, io): if self.type == 'byte': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'char': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>ss', value)[0] elif self.type == 'boolean': value = io.read(1) if not value: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>B', value)[0] elif self.type == 'short': value = io.read(2) if not value or len(value) != 2: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>H', value)[0] elif self.type == 'int': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>I', value)[0] elif self.type == 'long': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>Q', value)[0] elif self.type == 'float': value = io.read(4) if not value or len(value) != 4: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>F', value)[0] elif self.type == 'double': value = io.read(8) if not value or len(value) != 8: raise Exception('Failed to deserialize NewArray value') value = struct.unpack('>D', value)[0] else: value = decode_content(io, self.stream) return value def encode_value(self, value): if self.type == 'byte': res = struct.pack('>B', value) elif self.type == 'char': res = struct.pack('>ss', value) elif self.type == 'double': res = struct.pack('>D', value) elif self.type == 'float': res = struct.pack('>F', value) elif self.type == 'int': res = struct.pack('>I', value) elif self.type == 'long': res = struct.pack('>Q', value) elif self.type == 'short': res = struct.pack('>H', value) elif self.type == 'boolean': res = struct.pack('>B', value) elif self.type.__class__ is Element: res = value.encode() else: res = encode_content(value) return res def __str__(self): ret = self.type.__str__() + ', ' ret += '\n'.join(value.__str__() for value in self.values) return ret class NewClass(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_description = None def decode(self, io): class_desc = ClassDesc(self.stream) self.class_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) return self def encode(self): if self.class_description.__class__ != ClassDesc: raise Exception('Failed to serialize NewClass') encoded = '' encoded += self.class_description.encode() return encoded def __str__(self): return self.class_description.__str__() class NewClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.class_name = "" self.serial_version = 0 self.flags = 0 self.fields = [] self.class_annotation = None self.super_class = None def decode(self, io): utf = Utf(self.stream) self.class_name = utf.decode(io) self.serial_version = self.decode_serial_version(io) if self.stream: self.stream.add_reference(self) self.flags = self.decode_flags(io) field_length = self.decode_fields_length(io) for i in range(0, field_length): temp_field = Field(self.stream) field = temp_field.decode(io) self.fields.append(field) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_name.__class__ is not Utf \ and self.class_annotation.__class__ is not Annotation \ and self.super_class.__class__ is not ClassDesc: raise Exception('Filed to serialize NewClassDesc') encoded = '' encoded += self.class_name.encode() encoded += struct.pack('>Q', self.serial_version) encoded += struct.pack('>B', self.flags) encoded += struct.pack('>H', len(self.fields)) for field in self.fields: encoded += field.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_serial_version(self, io): raw_serial = io.read(8) if not raw_serial or len(raw_serial) != 8: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>Q', raw_serial)[0] def decode_flags(self, io): raw_flags = io.read(1) if not raw_flags: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>b', raw_flags)[0] def decode_fields_length(self, io): fields_length = io.read(2) if not fields_length or len(fields_length) != 2: raise Exception('Failed to unserialize ClassDescription') return struct.unpack('>h', fields_length)[0] def __str__(self): ret = self.class_name.__str__() + ", [" ret += ', '.join(field.__str__() for field in self.fields) ret += ']' # if self.super_class.description.__class__ is NewClassDesc: # ret += ", super_class: " + self.super_class.description.class_name.__str__() # elif self.super_class.description.__class__ is Reference: # ret += ", super_class: " + self.super_class.description.__str__() return ret class NewEnum(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.enum_description = None self.constant_name = None def decode(self, io): class_desc = ClassDesc(self.stream) self.enum_description = class_desc.decode(io) if self.stream: self.stream.add_reference(self) self.constant_name = self.decode_constant_name(io) return self def encode(self): if self.enum_description.__class__ is not ClassDesc or self.constant_name.__class__ is not Utf: raise Exception('Failed to serialize EnumDescription') encoded = '' encoded += self.enum_description.encode() encoded += encode_content(self.constant_name) return encoded def decode_constant_name(self, io): content = decode_content(io, self.stream) if content.__class__ is not Utf: raise Exception('Failed to unserialize NewEnum') return content class NewObject(Element): def __init__(self, stream=None): Element.__init__(self, stream) self.class_desc = None self.class_data = [] def decode(self, io): class_desc = ClassDesc(self.stream) self.class_desc = class_desc.decode(io) if self.stream: self.stream.add_reference(self) if self.class_desc.description.__class__ is NewClassDesc: self.class_data = self.decode_class_data(io, self.class_desc.description) elif self.class_desc.description.__class__ is Reference: ref = self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE self.class_data = self.decode_class_data(io, self.stream.references[ref]) return self def encode(self): if self.class_desc.__class__ is not ClassDesc: raise Exception('Failed to serialize NewObject') encoded = '' encoded += self.class_desc.encode() for value in self.class_data: if type(value) is list: encoded += self.encode_value(value) else: encoded += encode_content(value) return encoded def decode_class_data(self, io, my_class_desc): values = [] if my_class_desc.super_class.description.__class__ is not NullReference: if my_class_desc.super_class.description.__class__ is Reference: ref = my_class_desc.super_class.description.handle - Constants.BASE_WIRE_HANDLE values.extend(self.decode_class_data(io, self.stream.references[ref])) else: values.extend(self.decode_class_data(io, my_class_desc.super_class.description)) values.extend(self.decode_class_fields(io, my_class_desc)) return values def decode_class_fields(self, io, my_class_desc): values = [] for field in my_class_desc.fields: if field.is_primitive(): values.append(self.decode_value(io, field.type)) else: content = decode_content(io, self.stream) values.append(content) return values def decode_value(self, io, type): if type == 'byte': value_raw = io.read(1) val = struct.unpack(">b", value_raw)[0] value = ['byte', val] elif type == 'char': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['char', val] elif type == 'boolean': value_raw = io.read(1) val = struct.unpack(">B", value_raw)[0] value = ['boolean', val] elif type == 'short': value_raw = io.read(2) val = struct.unpack(">h", value_raw)[0] value = ['short', val] elif type == 'int': value_raw = io.read(4) val = struct.unpack(">i", value_raw)[0] value = ['int', val] elif type == 'long': value_raw = io.read(8) val = struct.unpack(">q", value_raw)[0] value = ['long', val] elif type == 'float': value_raw = io.read(4) val = struct.unpack(">f", value_raw)[0] value = ['float', val] elif type == 'double': value_raw = io.read(8) val = struct.unpack(">d", value_raw)[0] value = ['double', val] else: raise Exception("Unknown typecode: %s" % type) return value def encode_value(self, value): res = '' if value[0] == 'byte': res = struct.pack('>b', value[1]) elif value[0] == 'char': res = struct.pack('>h', value[1]) elif value[0] == 'double': res = struct.pack('>d', value[1]) elif value[0] == 'float': res = struct.pack('>f', value[1]) elif value[0] == 'int': res = struct.pack('>i', value[1]) elif value[0] == 'long': res = struct.pack('>Q', value[1]) elif value[0] == 'short': res = struct.pack('>h', value[1]) elif value[0] == 'boolean': res = struct.pack('>B', value[1]) else: raise Exception('Unsupported NewArray type') return res def __str__(self): ret = '' if self.class_desc.description.__class__ is NewClassDesc: ret += self.class_desc.description.class_name.__str__() elif self.class_desc.description.__class__ is ProxyClassDesc: ret += ','.join(iface.contents.__str__() for iface in self.class_desc.description.interfaces) elif self.class_desc.description.__class__ is Reference: ret += hex(self.class_desc.description.handle - Constants.BASE_WIRE_HANDLE) ret += ' => {' data_str = ', '.join(data.__str__() for data in self.class_data) ret += data_str ret += '}' return ret class NullReference(Element): pass class ProxyClassDesc(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.interfaces = [] self.class_annotation = None self.super_class = None def decode(self, io): if self.stream: self.stream.add_reference(self) interfaces_length = self.decode_interfaces_length(io) for i in range(0, interfaces_length): utf = Utf(self.stream) interface = utf.decode(io) self.interfaces.append(interface) annotation = Annotation(self.stream) super_class = ClassDesc(self.stream) self.class_annotation = annotation.decode(io) self.super_class = super_class.decode(io) return self def encode(self): if self.class_annotation.__class__ is not Annotation and self.super_class.__class__ is not ClassDesc: raise Exception('Failed to serialize ProxyClassDesc') encoded = '' encoded += struct.pack('>I', len(self.interfaces)) for interface in self.interfaces: encoded += interface.encode() encoded += self.class_annotation.encode() encoded += self.super_class.encode() return encoded def decode_interfaces_length(self, io): field_length = io.read(4) if not field_length or len(field_length) != 4: raise Exception('Failed to unserialize ProxyClassDesc') return struct.unpack('>I', field_length)[0] def __str__(self): ret = '[' interfaces_str = ', '.join(interface.__str__() for interface in self.interfaces) ret += interfaces_str + ']' if self.super_class.description.__class__ is NewClassDesc: ret += ", super_class: " + self.super_class.description.class_name.__str__() elif self.super_class.description.__class__ is Reference: ret += ", super_class: " + self.super_class.description.__str__() return ret class Reference(Element): def __init__(self, stream=''): Element.__init__(self, stream) self.handle = 0 def decode(self, io): handle_raw = io.read(4) if not handle_raw or len(handle_raw) != 4: raise Exception('Failed to unserialize Reference') self.handle = struct.unpack('>I', handle_raw)[0] return self def encode(self): if self.handle < Constants.BASE_WIRE_HANDLE: raise Exception('Failed to serialize Reference') encoded = "" encoded += struct.pack('>I', self.handle) return encoded def __str__(self): return hex(self.handle) class Reset(Element): pass class Utf(Element): def __init__(self, stream='', contents=''): Element.__init__(self, stream) self.contents = contents self.length = len(contents) def decode(self, io): raw_length = io.read(2) if not raw_length or len(raw_length) != 2: raise Exception('Failed to unserialize Utf') self.length = struct.unpack('>H', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize Utf') return self def encode(self): encoded = struct.pack('>H', self.length) encoded += self.contents return encoded def __str__(self): return self.contents class LongUtf(Utf): def decode(self, io): raw_length = io.read(8) if not raw_length or len(raw_length) != 8: raise Exception('Failed to unserialize LongUtf') self.length = struct.unpack('>Q', raw_length)[0] if self.length == 0: self.contents = "" else: self.contents = io.read(self.length) if not self.contents or len(self.contents) != self.length: raise Exception('Failed to unserialize LongUtf') return self def encode(self): encoded = struct.pack('>Q', [self.length]) encoded += self.contents return encoded def print_class(content): return content.__class__.__name__ def print_content(content): ret = '' if content.__class__ is BlockData: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is BlockDataLong: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is EndBlockData: ret += print_class(content) elif content.__class__ is NewObject: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is ClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewClass: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewArray: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is Utf: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is LongUtf: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewEnum: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NewClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is ProxyClassDesc: ret += "%s {%s}" % (print_class(content), str(content)) elif content.__class__ is NullReference: ret += print_class(content) elif content.__class__ is Reset: ret += print_class(content) elif content.__class__ is Reference: ret += "%s {%s}" % (print_class(content), str(content)) else: raise Exception('Failed to serialize content') return ret
null
161,821
import struct def get_key_by_value(dictionary, search_value): for key, value in dictionary.iteritems(): if value == search_value: return key raise Exception("There is no selected element in dictionary")
null
161,822
import requests from requests._internal_utils import to_native_string from requests.compat import is_py3 def get_redirect_target(self, resp): """hook requests.Session.get_redirect_target method""" if resp.is_redirect: location = resp.headers['location'] if is_py3: location = location.encode('latin1') # fix https://github.com/psf/requests/issues/4926 encoding_list = ['utf-8'] if resp.encoding and resp.encoding not in encoding_list: encoding_list.append(resp.encoding) if resp.apparent_encoding and resp.apparent_encoding not in encoding_list: encoding_list.append(resp.apparent_encoding) encoding_list.append('latin1') for encoding in encoding_list: try: return to_native_string(location, encoding) except Exception: pass return None def patch_redirect(): requests.Session.get_redirect_target = get_redirect_target
null
161,823
from pocsuite3.lib.core.data import conf from pocsuite3.lib.core.enums import HTTP_HEADER from pocsuite3.lib.utils import generate_random_user_agent, urlparse from requests.models import Request from requests.sessions import Session from requests.sessions import merge_cookies from requests.cookies import RequestsCookieJar from requests.utils import get_encodings_from_content, to_key_val_list from requests.compat import OrderedDict, Mapping def session_request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=False, cert=None, json=None): # In order to remove headers that are set to None def _merge_retain_none(request_setting, session_setting, dict_class=OrderedDict): if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) return merged_setting # Create the Request. if conf.get('http_headers', {}) == {}: conf.http_headers = {} merged_cookies = merge_cookies(merge_cookies(RequestsCookieJar(), self.cookies), cookies or conf.get('cookie', None)) if not conf.get('agent', '') and HTTP_HEADER.USER_AGENT not in conf.get('http_headers', {}): conf.http_headers[HTTP_HEADER.USER_AGENT] = generate_random_user_agent() # Fix no connection adapters were found pr = urlparse(url) if pr.scheme.lower() not in ['http', 'https']: url = pr._replace(scheme='https' if str(pr.port).endswith('443') else 'http').geturl() req = Request( method=method.upper(), url=url, headers=_merge_retain_none(headers, conf.get('http_headers', {})), files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=merged_cookies, hooks=hooks, ) prep = self.prepare_request(req) if proxies is None: proxies = conf.get('proxies', {}) settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) timeout = timeout or conf.get("timeout", 10) if timeout: timeout = float(timeout) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) if resp.encoding == 'ISO-8859-1': encodings = get_encodings_from_content(resp.text) if encodings: encoding = encodings[0] else: encoding = resp.apparent_encoding resp.encoding = encoding return resp def patch_session(): Session.request = session_request
null
161,824
import requests from requests.sessions import Session import json from requests.structures import CaseInsensitiveDict def httpraw(raw: str, ssl: bool = False, **kwargs): def patch_addraw(): requests.httpraw = httpraw
null
161,825
import requests import urllib3 from requests.exceptions import InvalidURL from urllib.parse import quote def patched_requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~" safe_without_percent = "!\"#$&\'()*+,-./:;<=>?@[\\]^_`{|}~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent) def patched_encode_target(target): return target def unquote_request_uri(): try: requests.utils.requote_uri.__code__ = patched_requote_uri.__code__ except Exception: pass try: urllib3.util.url._encode_target.__code__ = patched_encode_target.__code__ except Exception: pass
null
161,826
import ssl def remove_ssl_verify(): # It doesn't seem to work. 09/07/2022 ssl._create_default_https_context = ssl._create_unverified_context
null
161,827
from __future__ import absolute_import from collections import namedtuple import urllib3 def patched_parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ # While this code has overlap with stdlib's urlparse, it is much # simplified for our needs and less annoying. # Additionally, this implementations does silly things to be optimal # on CPython. def split_first(s, delims): """ Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, '', None return s[:min_idx], s[min_idx + 1:], min_delim if not url: # Empty return Url() scheme = None auth = None host = None port = None path = None fragment = None query = None # Scheme if '://' in url: scheme, url = url.split('://', 1) # Find the earliest Authority Terminator # (http://tools.ietf.org/html/rfc3986#section-3.2) url, path_, delim = split_first(url, ['/', '?', '#']) if delim: # Reassemble the path path = delim + path_ # Auth if '@' in url: # Last '@' denotes end of auth part auth, url = url.rsplit('@', 1) # IPv6 if url and url[0] == '[': host, url = url.split(']', 1) host += ']' # Port if ':' in url: _host, port = url.split(':', 1) if not host: host = _host if port: # If given, ports must be integers. No whitespace, no plus or # minus prefixes, no non-integer digits such as ^2 (superscript). if not port.isdigit(): raise LocationParseError(url) try: port = int(port) except ValueError: raise LocationParseError(url) else: # Blank ports are cool, too. (rfc3986#section-3.2.3) port = None elif not host and url: host = url if not path: return Url(scheme, auth, host, port, path, query, fragment) # Fragment if '#' in path: path, fragment = path.split('#', 1) # Query if '?' in path: path, query = path.split('?', 1) return Url(scheme, auth, host, port, path, query, fragment) def patch_urllib3_parse_url(): try: urllib3.util.parse_url.__code__ = patched_parse_url.__code__ except Exception: pass
null
161,828
import keyword def _totuple(x): """Utility stuff to convert string, int, long, float, None or anything to a usable tuple.""" if isinstance(x, basestring): out = x, elif isinstance(x, (int, long, float)): out = str(x), elif x is None: out = None, else: out = tuple(x) return out The provided code snippet includes necessary dependencies for implementing the `_argsdicts` function. Write a Python function `def _argsdicts(args, mydict)` to solve the following problem: A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1. Here is the function: def _argsdicts(args, mydict): """A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1.""" if len(args) == 0: args = None, elif len(args) == 1: args = _totuple(args[0]) else: raise Exception("We should have never gotten here.") mykeys = list(mydict.keys()) myvalues = list(map(_totuple, list(mydict.values()))) maxlength = max(list(map(len, [args] + myvalues))) for i in range(maxlength): thisdict = {} for key, value in zip(mykeys, myvalues): try: thisdict[key] = value[i] except IndexError: thisdict[key] = value[-1] try: thisarg = args[i] except IndexError: thisarg = args[-1] yield thisarg, thisdict
A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1.
161,829
try: basestring import string except NameError: # python 3 basestring = str string = str long = int import keyword The provided code snippet includes necessary dependencies for implementing the `escape` function. Write a Python function `def escape(text, newline=False)` to solve the following problem: Escape special html characters. Here is the function: def escape(text, newline=False): """Escape special html characters.""" if isinstance(text, basestring): if '&' in text: text = text.replace('&', '&amp;') if '>' in text: text = text.replace('>', '&gt;') if '<' in text: text = text.replace('<', '&lt;') if '\"' in text: text = text.replace('\"', '&quot;') if '\'' in text: text = text.replace('\'', '&quot;') if newline: if '\n' in text: text = text.replace('\n', '<br>') return text
Escape special html characters.
161,830
try: basestring import string except NameError: # python 3 basestring = str string = str long = int import keyword The provided code snippet includes necessary dependencies for implementing the `unescape` function. Write a Python function `def unescape(text)` to solve the following problem: Inverse of escape. Here is the function: def unescape(text): """Inverse of escape.""" if isinstance(text, basestring): if '&amp;' in text: text = text.replace('&amp;', '&') if '&gt;' in text: text = text.replace('&gt;', '>') if '&lt;' in text: text = text.replace('&lt;', '<') if '&quot;' in text: text = text.replace('&quot;', '\"') return text
Inverse of escape.
161,831
import hmac import hashlib import base64 import urllib.parse import requests import time from pocsuite3.api import PLUGIN_TYPE, get_results from pocsuite3.api import PluginBase from pocsuite3.api import logger from pocsuite3.api import register_plugin, conf DINGTALK_TOKEN = "" DINGTALK_SECRET = "" WX_WORK_KEY = "" def dingding_send(msg, access_token, secret, msgtype="markdown", title="pocsuite3消息推送"): ding_url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(access_token) timestamp = str(round(time.time() * 1000)) secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) param = "&timestamp={}&sign={}".format(timestamp, sign) ding_url = ding_url + param send_json = { "msgtype": msgtype, "markdown": { "title": title, "text": "# pocsuite3消息推送\n\n" + msg } } requests.post(ding_url, json=send_json) def wx_work_send(msg, key): webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key send_data = { "msgtype": "markdown", "markdown": { "content": "# pocsuite3消息推送\n\n" + msg } } requests.post(webhook_url, json=send_data) def web_hook_send(msg): dingtalk_token = conf.dingtalk_token or DINGTALK_TOKEN dingtalk_secret = conf.dingtalk_secret or DINGTALK_SECRET wx_work_key = conf.wx_work_key or WX_WORK_KEY if dingtalk_token and dingtalk_secret: dingding_send(msg, dingtalk_token, dingtalk_secret) if wx_work_key: wx_work_send(msg, wx_work_key)
null
161,832
from sys import version_info as _swig_python_version_info def swig_import_helper(): import importlib pkg = __name__.rpartition(".")[0] mname = ".".join((pkg, "_snowboydetect")).lstrip(".") try: return importlib.import_module(mname) except ImportError: return importlib.import_module("_snowboydetect")
null
161,833
from sys import version_info as _swig_python_version_info def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module( "_snowboydetect", [dirname(__file__)] ) except ImportError: import _snowboydetect return _snowboydetect try: _mod = imp.load_module("_snowboydetect", fp, pathname, description) finally: fp and fp.close() return _mod
null
161,834
from sys import version_info as _swig_python_version_info def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if name == "thisown": return self.this.own(value) if name == "this": if type(value).__name__ == "SwigPyObject": self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name, None) if method: return method(self, value) if not static: if _newclass: object.__setattr__(self, name, value) else: self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self, class_type, name, value): return _swig_setattr_nondynamic(self, class_type, name, value, 0)
null
161,835
from sys import version_info as _swig_python_version_info def _swig_getattr(self, class_type, name): if name == "thisown": return self.this.own() method = class_type.__swig_getmethods__.get(name, None) if method: return method(self) raise AttributeError( "'%s' object has no attribute '%s'" % (class_type.__name__, name) )
null
161,836
from sys import version_info as _swig_python_version_info def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % ( self.__class__.__module__, self.__class__.__name__, strthis, )
null
161,837
import collections import pyaudio from . import snowboydetect from robot import utils, logging import time import wave import os from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from robot import constants def py_error_handler(filename, line, function, err, fmt): pass
null
161,838
import collections import pyaudio from . import snowboydetect from robot import utils, logging import time import wave import os from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from robot import constants DETECT_DING = os.path.join(TOP_DIR, "resources/ding.wav") def no_alsa_error(): try: asound = cdll.LoadLibrary("libasound.so") asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) except: yield pass The provided code snippet includes necessary dependencies for implementing the `play_audio_file` function. Write a Python function `def play_audio_file(fname=DETECT_DING)` to solve the following problem: Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None Here is the function: def play_audio_file(fname=DETECT_DING): """Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None """ ding_wav = wave.open(fname, "rb") ding_data = ding_wav.readframes(ding_wav.getnframes()) with no_alsa_error(): audio = pyaudio.PyAudio() stream_out = audio.open( format=audio.get_format_from_width(ding_wav.getsampwidth()), channels=ding_wav.getnchannels(), rate=ding_wav.getframerate(), input=False, output=True, ) stream_out.start_stream() stream_out.write(ding_data) time.sleep(0.2) stream_out.stop_stream() stream_out.close() audio.terminate()
Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None
161,839
from .sdk import unit from robot import logging from abc import ABCMeta, abstractmethod logger = logging.getLogger(__name__) def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ engine for engine in list(get_subclasses(AbstractNLU)) if hasattr(engine, "SLUG") and engine.SLUG ] The provided code snippet includes necessary dependencies for implementing the `get_engine_by_slug` function. Write a Python function `def get_engine_by_slug(slug=None)` to solve the following problem: Returns: An NLU Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform Here is the function: def get_engine_by_slug(slug=None): """ Returns: An NLU Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 NLU slug '%s'", slug) selected_engines = list( filter( lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines(), ) ) if len(selected_engines) == 0: raise ValueError(f"错误:找不到名为 {slug} 的 NLU 引擎") else: if len(selected_engines) > 1: logger.warning(f"注意: 有多个 NLU 名称与指定的引擎名 {slug} 匹配") engine = selected_engines[0] logger.info(f"使用 {engine.SLUG} NLU 引擎") return engine.get_instance()
Returns: An NLU Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform
161,840
from . import config import uuid import requests import threading def getUUID(): mac = uuid.UUID(int=uuid.getnode()).hex[-12:] return ":".join([mac[e : e + 2] for e in range(0, 11, 2)])
null
161,841
from . import config import uuid import requests import threading class ReportThread(threading.Thread): def __init__(self, t): # 需要执行父类的初始化方法 threading.Thread.__init__(self) self.t = t def run(self): to_report = config.get("statistic", True) if to_report: try: persona = config.get("robot_name_cn", "孙悟空") url = "http://livecv.hahack.com:8022/statistic" payload = { "type": str(self.t), "uuid": getUUID(), "name": persona, "project": "wukong", } requests.post(url, data=payload, timeout=3) except Exception: return def report(t): ReportThread(t).start()
null
161,842
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart logger = logging.getLogger(__name__) def sendEmail( SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, PASSWORD, SMTP_SERVER, SMTP_PORT ): """ 发送邮件 :param SUBJECT: 邮件标题 :param BODY: 邮件正文 :param ATTACH_LIST: 附件 :param TO: 收件人 :param FROM: 发件人 :param SENDER: 发件人信息 :param PASSWORD: 密码 :param SMTP_SERVER: smtp 服务器 :param SMTP_PORT: smtp 端口号 :returns: True: 发送成功; False: 发送失败 """ txt = MIMEText(BODY.encode("utf-8"), "html", "utf-8") msg = MIMEMultipart() msg.attach(txt) for attach in ATTACH_LIST: try: att = MIMEText(open(attach, "rb").read(), "base64", "utf-8") filename = os.path.basename(attach) att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename="%s"' % filename msg.attach(att) except Exception: logger.error(f"附件 {attach} 发送失败!", stack_info=True) continue msg["From"] = SENDER msg["To"] = TO msg["Subject"] = SUBJECT try: session = smtplib.SMTP(SMTP_SERVER) session.connect(SMTP_SERVER, SMTP_PORT) session.starttls() session.login(FROM, PASSWORD) session.sendmail(SENDER, TO, msg.as_string()) session.close() return True except Exception as e: logger.error(e, stack_info=True) return False The provided code snippet includes necessary dependencies for implementing the `emailUser` function. Write a Python function `def emailUser(SUBJECT="", BODY="", ATTACH_LIST=[])` to solve the following problem: 给用户发送邮件 :param SUBJECT: subject line of the email :param BODY: body text of the email :returns: True: 发送成功; False: 发送失败 Here is the function: def emailUser(SUBJECT="", BODY="", ATTACH_LIST=[]): """ 给用户发送邮件 :param SUBJECT: subject line of the email :param BODY: body text of the email :returns: True: 发送成功; False: 发送失败 """ # add footer if BODY: BODY = "%s,<br><br>这是您要的内容:<br>%s<br>" % (config["first_name"], BODY) recipient = config.get("/email/address", "") robot_name = config.get("robot_name_cn", "wukong-robot") recipient = robot_name + " <%s>" % recipient user = config.get("/email/address", "") password = config.get("/email/password", "") server = config.get("/email/smtp_server", "") port = config.get("/email/smtp_port", "") if not recipient or not user or not password or not server or not port: return False try: sendEmail( SUBJECT, BODY, ATTACH_LIST, user, user, recipient, password, server, port ) return True except Exception as e: logger.error(e, stack_info=True) return False
给用户发送邮件 :param SUBJECT: subject line of the email :param BODY: body text of the email :returns: True: 发送成功; False: 发送失败
161,843
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `get_file_content` function. Write a Python function `def get_file_content(filePath, flag="rb")` to solve the following problem: 读取文件内容并返回 :param filePath: 文件路径 :returns: 文件内容 :raises IOError: 读取失败则抛出 IOError Here is the function: def get_file_content(filePath, flag="rb"): """ 读取文件内容并返回 :param filePath: 文件路径 :returns: 文件内容 :raises IOError: 读取失败则抛出 IOError """ with open(filePath, flag) as fp: return fp.read()
读取文件内容并返回 :param filePath: 文件路径 :returns: 文件内容 :raises IOError: 读取失败则抛出 IOError
161,844
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `check_and_delete` function. Write a Python function `def check_and_delete(fp, wait=0)` to solve the following problem: 检查并删除文件/文件夹 :param fp: 文件路径 Here is the function: def check_and_delete(fp, wait=0): """ 检查并删除文件/文件夹 :param fp: 文件路径 """ def run(): if wait > 0: time.sleep(wait) if isinstance(fp, str) and os.path.exists(fp): if os.path.isfile(fp): os.remove(fp) else: shutil.rmtree(fp) thread.start_new_thread(run, ())
检查并删除文件/文件夹 :param fp: 文件路径
161,845
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `convert_wav_to_mp3` function. Write a Python function `def convert_wav_to_mp3(wav_path)` to solve the following problem: 将 wav 文件转成 mp3 :param wav_path: wav 文件路径 :returns: mp3 文件路径 Here is the function: def convert_wav_to_mp3(wav_path): """ 将 wav 文件转成 mp3 :param wav_path: wav 文件路径 :returns: mp3 文件路径 """ if not os.path.exists(wav_path): logger.critical(f"文件错误 {wav_path}", stack_info=True) return None mp3_path = wav_path.replace(".wav", ".mp3") AudioSegment.from_wav(wav_path).export(mp3_path, format="mp3") return mp3_path
将 wav 文件转成 mp3 :param wav_path: wav 文件路径 :returns: mp3 文件路径
161,846
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `convert_mp3_to_wav` function. Write a Python function `def convert_mp3_to_wav(mp3_path)` to solve the following problem: 将 mp3 文件转成 wav :param mp3_path: mp3 文件路径 :returns: wav 文件路径 Here is the function: def convert_mp3_to_wav(mp3_path): """ 将 mp3 文件转成 wav :param mp3_path: mp3 文件路径 :returns: wav 文件路径 """ target = mp3_path.replace(".mp3", ".wav") if not os.path.exists(mp3_path): logger.critical(f"文件错误 {mp3_path}", stack_info=True) return None AudioSegment.from_mp3(mp3_path).export(target, format="wav") return target
将 mp3 文件转成 wav :param mp3_path: mp3 文件路径 :returns: wav 文件路径
161,847
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `clean` function. Write a Python function `def clean()` to solve the following problem: 清理垃圾数据 Here is the function: def clean(): """清理垃圾数据""" temp = constants.TEMP_PATH temp_files = os.listdir(temp) for f in temp_files: if os.path.isfile(os.path.join(temp, f)) and re.match( r"output[\d]*\.wav", os.path.basename(f) ): os.remove(os.path.join(temp, f))
清理垃圾数据
161,848
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart is_recordable = True The provided code snippet includes necessary dependencies for implementing the `setRecordable` function. Write a Python function `def setRecordable(value)` to solve the following problem: 设置是否可以开始录制语音 Here is the function: def setRecordable(value): """设置是否可以开始录制语音""" global is_recordable is_recordable = value
设置是否可以开始录制语音
161,849
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart is_recordable = True The provided code snippet includes necessary dependencies for implementing the `isRecordable` function. Write a Python function `def isRecordable()` to solve the following problem: 是否可以开始录制语音 Here is the function: def isRecordable(): """是否可以开始录制语音""" global is_recordable return is_recordable
是否可以开始录制语音
161,850
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart do_not_bother = False The provided code snippet includes necessary dependencies for implementing the `is_proper_time` function. Write a Python function `def is_proper_time()` to solve the following problem: 是否合适时间 Here is the function: def is_proper_time(): """是否合适时间""" global do_not_bother if do_not_bother == True: return False if not config.has("do_not_bother"): return True bother_profile = config.get("do_not_bother") if not bother_profile["enable"]: return True if "since" not in bother_profile or "till" not in bother_profile: return True since = bother_profile["since"] till = bother_profile["till"] current = time.localtime(time.time()).tm_hour if till > since: return current not in range(since, till) else: return not (current in range(since, 25) or current in range(-1, till))
是否合适时间
161,851
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `get_do_not_bother_on_hotword` function. Write a Python function `def get_do_not_bother_on_hotword()` to solve the following problem: 打开勿扰模式唤醒词 Here is the function: def get_do_not_bother_on_hotword(): """打开勿扰模式唤醒词""" return config.get("/do_not_bother/on_hotword", "悟空别吵.pmdl")
打开勿扰模式唤醒词
161,852
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `get_do_not_bother_off_hotword` function. Write a Python function `def get_do_not_bother_off_hotword()` to solve the following problem: 关闭勿扰模式唤醒词 Here is the function: def get_do_not_bother_off_hotword(): """关闭勿扰模式唤醒词""" return config.get("/do_not_bother/off_hotword", "悟空醒醒.pmdl")
关闭勿扰模式唤醒词
161,853
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `getTimezone` function. Write a Python function `def getTimezone()` to solve the following problem: 获取时区 Here is the function: def getTimezone(): """获取时区""" return timezone(config.get("timezone", "HKT"))
获取时区
161,854
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `getTimemStap` function. Write a Python function `def getTimemStap()` to solve the following problem: 获取时间戳 Here is the function: def getTimemStap(): """获取时间戳""" return str(time.time()).replace(".", "")
获取时间戳
161,855
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `getCache` function. Write a Python function `def getCache(msg)` to solve the following problem: 获取缓存的语音 Here is the function: def getCache(msg): """获取缓存的语音""" md5 = hashlib.md5(msg.encode("utf-8")).hexdigest() cache_paths = [ os.path.join(constants.TEMP_PATH, md5 + ext) for ext in [".mp3", ".wav", ".asiff"] ] return next((path for path in cache_paths if os.path.exists(path)), None)
获取缓存的语音
161,856
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `saveCache` function. Write a Python function `def saveCache(voice, msg)` to solve the following problem: 获取缓存的语音 Here is the function: def saveCache(voice, msg): """获取缓存的语音""" _, ext = os.path.splitext(voice) md5 = hashlib.md5(msg.encode("utf-8")).hexdigest() target = os.path.join(constants.TEMP_PATH, md5 + ext) shutil.copyfile(voice, target) return target
获取缓存的语音
161,857
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `lruCache` function. Write a Python function `def lruCache()` to solve the following problem: 清理最近未使用的缓存 Here is the function: def lruCache(): """清理最近未使用的缓存""" def run(*args): if config.get("/lru_cache/enable", True): days = config.get("/lru_cache/days", 7) subprocess.run( 'find . -name "*.mp3" -atime +%d -exec rm {} \;' % days, cwd=constants.TEMP_PATH, shell=True, ) thread.start_new_thread(run, ())
清理最近未使用的缓存
161,858
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `validyaml` function. Write a Python function `def validyaml(filename)` to solve the following problem: 校验 YAML 格式是否正确 :param filename: yaml文件路径 :returns: True: 正确; False: 不正确 Here is the function: def validyaml(filename): """ 校验 YAML 格式是否正确 :param filename: yaml文件路径 :returns: True: 正确; False: 不正确 """ try: with open(filename) as f: str = f.read() yaml.safe_load(str) return True except Exception: return False
校验 YAML 格式是否正确 :param filename: yaml文件路径 :returns: True: 正确; False: 不正确
161,859
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart The provided code snippet includes necessary dependencies for implementing the `validjson` function. Write a Python function `def validjson(s)` to solve the following problem: 校验某个 JSON 字符串是否正确 :param s: JOSN字符串 :returns: True: 正确; False: 不正确 Here is the function: def validjson(s): """ 校验某个 JSON 字符串是否正确 :param s: JOSN字符串 :returns: True: 正确; False: 不正确 """ try: json.loads(s) return True except Exception: return False
校验某个 JSON 字符串是否正确 :param s: JOSN字符串 :returns: True: 正确; False: 不正确
161,860
import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def getPunctuations(): return [",", ",", ".", "。", "?", "?", "!", "!", "\n"] The provided code snippet includes necessary dependencies for implementing the `stripPunctuation` function. Write a Python function `def stripPunctuation(s)` to solve the following problem: 移除字符串末尾的标点 Here is the function: def stripPunctuation(s): """ 移除字符串末尾的标点 """ punctuations = getPunctuations() if any(s.endswith(p) for p in punctuations): s = s[:-1] return s
移除字符串末尾的标点
161,861
import json from aip import AipSpeech from .sdk import TencentSpeech, AliSpeech, XunfeiSpeech, BaiduSpeech, FunASREngine from . import utils, config from robot import logging from abc import ABCMeta, abstractmethod import requests logger = logging.getLogger(__name__) def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ engine for engine in list(get_subclasses(AbstractASR)) if hasattr(engine, "SLUG") and engine.SLUG ] The provided code snippet includes necessary dependencies for implementing the `get_engine_by_slug` function. Write a Python function `def get_engine_by_slug(slug=None)` to solve the following problem: Returns: An ASR Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform Here is the function: def get_engine_by_slug(slug=None): """ Returns: An ASR Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 ASR slug '%s'", slug) selected_engines = list( filter( lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines(), ) ) if len(selected_engines) == 0: raise ValueError(f"错误:找不到名为 {slug} 的 ASR 引擎") else: if len(selected_engines) > 1: logger.warning(f"注意: 有多个 ASR 名称与指定的引擎名 {slug} 匹配") engine = selected_engines[0] logger.info(f"使用 {engine.SLUG} ASR 引擎") return engine.get_instance()
Returns: An ASR Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform
161,862
import logging import os from robot import constants from logging.handlers import RotatingFileHandler INFO = logging.INFO import logging from logging.handlers import RotatingFileHandler The provided code snippet includes necessary dependencies for implementing the `getLogger` function. Write a Python function `def getLogger(name)` to solve the following problem: 作用同标准模块 logging.getLogger(name) :returns: logger Here is the function: def getLogger(name): """ 作用同标准模块 logging.getLogger(name) :returns: logger """ format = "%(asctime)s - %(name)s - %(filename)s - %(funcName)s - line %(lineno)s - %(levelname)s - %(message)s" formatter = logging.Formatter(format) logging.basicConfig(format=format) logger = logging.getLogger(name) logger.setLevel(logging.INFO) # FileHandler file_handler = RotatingFileHandler( os.path.join(constants.TEMP_PATH, "wukong.log"), maxBytes=1024 * 1024, backupCount=5, ) file_handler.setLevel(level=logging.NOTSET) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger
作用同标准模块 logging.getLogger(name) :returns: logger
161,863
import logging import os from robot import constants from logging.handlers import RotatingFileHandler def tail(filepath, n=10): """ 实现 tail -n """ res = "" with open(filepath, "rb") as f: f_len = f.seek(0, 2) rem = f_len % PAGE page_n = f_len // PAGE r_len = rem if rem else PAGE while True: # 如果读取的页大小>=文件大小,直接读取数据输出 if r_len >= f_len: f.seek(0) lines = f.readlines()[::-1] break f.seek(-r_len, 2) lines = f.readlines()[::-1] count = len(lines) - 1 # 末行可能不完整,减一行,加大读取量 if count >= n: # 如果读取到的行数>=指定行数,则退出循环读取数据 break else: # 如果读取行数不够,载入更多的页大小读取数据 r_len += PAGE page_n -= 1 for line in lines[:n][::-1]: res += line.decode("utf-8") return res The provided code snippet includes necessary dependencies for implementing the `readLog` function. Write a Python function `def readLog(lines=200)` to solve the following problem: 获取最新的指定行数的 log :param lines: 最大的行数 :returns: 最新指定行数的 log Here is the function: def readLog(lines=200): """ 获取最新的指定行数的 log :param lines: 最大的行数 :returns: 最新指定行数的 log """ log_path = os.path.join(constants.TEMP_PATH, "wukong.log") if os.path.exists(log_path): return tail(log_path, lines) return ""
获取最新的指定行数的 log :param lines: 最大的行数 :returns: 最新指定行数的 log
161,864
import asyncio import subprocess import os import platform import queue import signal import threading from robot import logging from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from . import utils def py_error_handler(filename, line, function, err, fmt): pass
null
161,865
import asyncio import subprocess import os import platform import queue import signal import threading from robot import logging from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from . import utils c_error_handler = ERROR_HANDLER_FUNC(py_error_handler) def no_alsa_error(): try: asound = cdll.LoadLibrary("libasound.so") asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) except: yield pass
null
161,866
import asyncio import subprocess import os import platform import queue import signal import threading from robot import logging from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from . import utils def getPlayerByFileName(fname): foo, ext = os.path.splitext(fname) if ext in [".mp3", ".wav"]: return SoxPlayer() def play(fname, onCompleted=None): player = getPlayerByFileName(fname) player.play(fname, onCompleted=onCompleted)
null
161,867
import os import json import random import requests from uuid import getnode as get_mac from abc import ABCMeta, abstractmethod from robot import logging, config, utils from robot.sdk import unit The provided code snippet includes necessary dependencies for implementing the `get_unknown_response` function. Write a Python function `def get_unknown_response()` to solve the following problem: 不知道怎么回答的情况下的答复 :returns: 表示不知道的答复 Here is the function: def get_unknown_response(): """ 不知道怎么回答的情况下的答复 :returns: 表示不知道的答复 """ results = ["抱歉,我不会这个呢", "我不会这个呢", "我还不会这个呢", "我还没学会这个呢", "对不起,你说的这个,我还不会"] return random.choice(results)
不知道怎么回答的情况下的答复 :returns: 表示不知道的答复
161,868
import os import json import random import requests from uuid import getnode as get_mac from abc import ABCMeta, abstractmethod from robot import logging, config, utils from robot.sdk import unit logger = logging.getLogger(__name__) _robots(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ robot for robot in list(get_subclasses(AbstractRobot)) if hasattr(robot, "SLUG") and robot.SLUG ] The provided code snippet includes necessary dependencies for implementing the `get_robot_by_slug` function. Write a Python function `def get_robot_by_slug(slug)` to solve the following problem: Returns: A robot implementation available on the current platform Here is the function: def get_robot_by_slug(slug): """ Returns: A robot implementation available on the current platform """ if not slug or type(slug) is not str: raise TypeError("Invalid slug '%s'", slug) selected_robots = list( filter( lambda robot: hasattr(robot, "SLUG") and robot.SLUG == slug, get_robots() ) ) if len(selected_robots) == 0: raise ValueError("No robot found for slug '%s'" % slug) else: if len(selected_robots) > 1: logger.warning( "WARNING: Multiple robots found for slug '%s'. " + "This is most certainly a bug." % slug ) robot = selected_robots[0] logger.info(f"使用 {robot.SLUG} 对话机器人") return robot.get_instance()
Returns: A robot implementation available on the current platform
161,869
import itertools The provided code snippet includes necessary dependencies for implementing the `num2chinese` function. Write a Python function `def num2chinese(num, big=False, simp=True, o=False, twoalt=False)` to solve the following problem: Converts numbers to Chinese representations. `big` : use financial characters. `simp` : use simplified characters instead of traditional characters. `o` : use 〇 for zero. `twoalt`: use 两/兩 for two when appropriate. Note that `o` and `twoalt` is ignored when `big` is used, and `twoalt` is ignored when `o` is used for formal representations. Here is the function: def num2chinese(num, big=False, simp=True, o=False, twoalt=False): """ Converts numbers to Chinese representations. `big` : use financial characters. `simp` : use simplified characters instead of traditional characters. `o` : use 〇 for zero. `twoalt`: use 两/兩 for two when appropriate. Note that `o` and `twoalt` is ignored when `big` is used, and `twoalt` is ignored when `o` is used for formal representations. """ # check num first nd = str(num) if abs(float(nd)) >= 1e48: raise ValueError("number out of range") elif "e" in nd: raise ValueError("scientific notation is not supported") c_symbol = "正负点" if simp else "正負點" if o: # formal twoalt = False if big: c_basic = "零壹贰叁肆伍陆柒捌玖" if simp else "零壹貳參肆伍陸柒捌玖" c_unit1 = "拾佰仟" c_twoalt = "贰" if simp else "貳" else: c_basic = "〇一二三四五六七八九" if o else "零一二三四五六七八九" c_unit1 = "十百千" if twoalt: c_twoalt = "两" if simp else "兩" else: c_twoalt = "二" c_unit2 = "万亿兆京垓秭穰沟涧正载" if simp else "萬億兆京垓秭穰溝澗正載" revuniq = lambda l: "".join(k for k, g in itertools.groupby(reversed(l))) nd = str(num) result = [] if nd[0] == "+": result.append(c_symbol[0]) elif nd[0] == "-": result.append(c_symbol[1]) if "." in nd: integer, remainder = nd.lstrip("+-").split(".") else: integer, remainder = nd.lstrip("+-"), None if int(integer): splitted = [integer[max(i - 4, 0) : i] for i in range(len(integer), 0, -4)] intresult = [] for nu, unit in enumerate(splitted): # special cases if int(unit) == 0: # 0000 intresult.append(c_basic[0]) continue elif nu > 0 and int(unit) == 2: # 0002 intresult.append(c_twoalt + c_unit2[nu - 1]) continue ulist = [] unit = unit.zfill(4) for nc, ch in enumerate(reversed(unit)): if ch == "0": if ulist: # ???0 ulist.append(c_basic[0]) elif nc == 0: ulist.append(c_basic[int(ch)]) elif nc == 1 and ch == "1" and unit[1] == "0": # special case for tens # edit the 'elif' if you don't like # 十四, 三千零十四, 三千三百一十四 ulist.append(c_unit1[0]) elif nc > 1 and ch == "2": ulist.append(c_twoalt + c_unit1[nc - 1]) else: ulist.append(c_basic[int(ch)] + c_unit1[nc - 1]) ustr = revuniq(ulist) if nu == 0: intresult.append(ustr) else: intresult.append(ustr + c_unit2[nu - 1]) result.append(revuniq(intresult).strip(c_basic[0])) else: result.append(c_basic[0]) if remainder: result.append(c_symbol[2]) result.append("".join(c_basic[int(ch)] for ch in remainder)) return "".join(result)
Converts numbers to Chinese representations. `big` : use financial characters. `simp` : use simplified characters instead of traditional characters. `o` : use 〇 for zero. `twoalt`: use 两/兩 for two when appropriate. Note that `o` and `twoalt` is ignored when `big` is used, and `twoalt` is ignored when `o` is used for formal representations.
161,871
import requests def tts(text, server_url, api_key, speaker_id, length, noise, noisew, max, timeout): data = { "text": text, "id": speaker_id, "format": "wav", "lang": "auto", "length": length, "noise": noise, "noisew": noisew, "max": max } headers = {"X-API-KEY": api_key} url = f"{server_url}/voice" res = requests.post(url=url, data=data, headers=headers, timeout=timeout) res.raise_for_status() return res.content
null
161,872
import urllib.request import hmac import hashlib import base64 import time import random import os import json def formatSignString(param): signstr = "POSTaai.qcloud.com/asr/v1/" for t in param: if "appid" in t: signstr += str(t[1]) break signstr += "?" for x in param: tmp = x if "appid" in x: continue for t in tmp: signstr += str(t) signstr += "=" signstr = signstr[:-1] signstr += "&" signstr = signstr[:-1] # print 'signstr',signstr return signstr def sign(signstr, secret_key): sign_bytes = bytes(signstr, "utf-8") secret_bytes = bytes(secret_key, "utf-8") hmacstr = hmac.new(secret_bytes, sign_bytes, hashlib.sha1).digest() s = base64.b64encode(hmacstr).decode("utf-8") return s def randstr(n): seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in range(n): sa.append(random.choice(seed)) salt = "".join(sa) # print salt return salt def sendVoice( secret_key, secretid, appid, engine_model_type, res_type, result_text_format, voice_format, filepath, cutlength, template_name="", ): if len(str(secret_key)) == 0: print("secretKey can not empty") return if len(str(secretid)) == 0: print("secretid can not empty") return if len(str(appid)) == 0: print("appid can not empty") return if len(str(engine_model_type)) == 0 or ( str(engine_model_type) != "8k_0" and str(engine_model_type) != "16k_0" and str(engine_model_type) != "16k_en" ): print("engine_model_type is not right") return if len(str(res_type)) == 0 or (str(res_type) != "0" and str(res_type) != "1"): print("res_type is not right") return if len(str(result_text_format)) == 0 or ( str(result_text_format) != "0" and str(result_text_format) != "1" and str(result_text_format) != "2" and str(result_text_format) != "3" ): print("result_text_format is not right") return if len(str(voice_format)) == 0 or ( str(voice_format) != "1" and str(voice_format) != "4" and str(voice_format) != "6" ): print("voice_format is not right") return if len(str(filepath)) == 0: print("filepath can not empty") return if ( len(str(cutlength)) == 0 or str(cutlength).isdigit() == False or cutlength > 200000 ): print("cutlength can not empty") return # secret_key = "oaYWFO70LGDmcpfwo8uF1IInayysGtgZ" query_arr = dict() query_arr["appid"] = appid query_arr["projectid"] = 1013976 if len(template_name) > 0: query_arr["template_name"] = template_name query_arr["sub_service_type"] = 1 query_arr["engine_model_type"] = engine_model_type query_arr["res_type"] = res_type query_arr["result_text_format"] = result_text_format query_arr["voice_id"] = randstr(16) query_arr["timeout"] = 100 query_arr["source"] = 0 query_arr["secretid"] = secretid query_arr["timestamp"] = str(int(time.time())) query_arr["expired"] = int(time.time()) + 24 * 60 * 60 query_arr["nonce"] = query_arr["timestamp"][0:4] query_arr["voice_format"] = voice_format file_object = open(filepath, "rb") file_object.seek(0, os.SEEK_END) datalen = file_object.tell() file_object.seek(0, os.SEEK_SET) seq = 0 response = [] while datalen > 0: end = 0 if datalen < cutlength: end = 1 query_arr["end"] = end query_arr["seq"] = seq query = sorted(query_arr.items(), key=lambda d: d[0]) signstr = formatSignString(query) autho = sign(signstr, secret_key) if datalen < cutlength: content = file_object.read(datalen) else: content = file_object.read(cutlength) seq = seq + 1 datalen = datalen - cutlength headers = dict() headers["Authorization"] = autho headers["Content-Length"] = len(content) requrl = "http://" requrl += signstr[4::] req = urllib.request.Request(requrl, data=content, headers=headers) res_data = urllib.request.urlopen(req) r = res_data.read().decode("utf-8") res = json.loads(r) if res["code"] == 0: response.append(res["text"]) file_object.close() return response[len(response) - 1]
null
161,873
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser def get_token(api_key, secret_key): cache = open(os.path.join(constants.TEMP_PATH, "baidustt.ini"), "a+") try: pms = cache.readlines() if len(pms) > 0: time = pms[0] tk = pms[1] # 计算token是否过期 官方说明一个月,这里保守29天 time = dparser.parse(time) endtime = datetime.datetime.now() if (endtime - time).days <= 29: return tk finally: cache.close() URL = "http://openapi.baidu.com/oauth/2.0/token" params = { "grant_type": "client_credentials", "client_id": api_key, "client_secret": secret_key, } r = requests.get(URL, params=params) try: r.raise_for_status() token = r.json()["access_token"] return token except requests.exceptions.HTTPError: return "" The provided code snippet includes necessary dependencies for implementing the `getUnit` function. Write a Python function `def getUnit(query, service_id, api_key, secret_key)` to solve the following problem: NLU 解析 :param query: 用户的指令字符串 :param service_id: UNIT 的 service_id :param api_key: UNIT apk_key :param secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None Here is the function: def getUnit(query, service_id, api_key, secret_key): """ NLU 解析 :param query: 用户的指令字符串 :param service_id: UNIT 的 service_id :param api_key: UNIT apk_key :param secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None """ access_token = get_token(api_key, secret_key) url = ( "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token ) request = {"query": query, "user_id": str(get_mac())[:32]} body = { "log_id": str(uuid.uuid1()), "version": "2.0", "service_id": service_id, "session_id": str(uuid.uuid1()), "request": request, } try: headers = {"Content-Type": "application/json"} request = requests.post(url, json=body, headers=headers) return json.loads(request.text) except Exception: return None
NLU 解析 :param query: 用户的指令字符串 :param service_id: UNIT 的 service_id :param api_key: UNIT apk_key :param secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None
161,874
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `getIntent` function. Write a Python function `def getIntent(parsed)` to solve the following problem: 提取意图 :param parsed: UNIT 解析结果 :returns: 意图数组 Here is the function: def getIntent(parsed): """ 提取意图 :param parsed: UNIT 解析结果 :returns: 意图数组 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: try: return parsed["result"]["response_list"][0]["schema"]["intent"] except Exception as e: logger.warning(e) return "" else: return ""
提取意图 :param parsed: UNIT 解析结果 :returns: 意图数组
161,875
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser The provided code snippet includes necessary dependencies for implementing the `hasIntent` function. Write a Python function `def hasIntent(parsed, intent)` to solve the following problem: 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 Here is the function: def hasIntent(parsed, intent): """ 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] for response in response_list: if ( "schema" in response and "intent" in response["schema"] and response["schema"]["intent"] == intent ): return True return False else: return False
判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含
161,876
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser def getSlots(parsed, intent=""): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] if intent == "": try: return parsed["result"]["response_list"][0]["schema"]["slots"] except Exception as e: logger.warning(e) return [] for response in response_list: if ( "schema" in response and "intent" in response["schema"] and "slots" in response["schema"] and response["schema"]["intent"] == intent ): return response["schema"]["slots"] return [] else: return [] The provided code snippet includes necessary dependencies for implementing the `getSlotWords` function. Write a Python function `def getSlotWords(parsed, intent, name)` to solve the following problem: 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 Here is the function: def getSlotWords(parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ slots = getSlots(parsed, intent) words = [] for slot in slots: if slot["name"] == name: words.append(slot["normalized_word"]) return words
找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。
161,877
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser def getSlots(parsed, intent=""): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] if intent == "": try: return parsed["result"]["response_list"][0]["schema"]["slots"] except Exception as e: logger.warning(e) return [] for response in response_list: if ( "schema" in response and "intent" in response["schema"] and "slots" in response["schema"] and response["schema"]["intent"] == intent ): return response["schema"]["slots"] return [] else: return [] The provided code snippet includes necessary dependencies for implementing the `getSlotOriginalWords` function. Write a Python function `def getSlotOriginalWords(parsed, intent, name)` to solve the following problem: 找出命中某个词槽的原始内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 Here is the function: def getSlotOriginalWords(parsed, intent, name): """ 找出命中某个词槽的原始内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ slots = getSlots(parsed, intent) words = [] for slot in slots: if slot["name"] == name: words.append(slot["original_word"]) return words
找出命中某个词槽的原始内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。
161,878
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser The provided code snippet includes necessary dependencies for implementing the `getSayByConfidence` function. Write a Python function `def getSayByConfidence(parsed)` to solve the following problem: 提取 UNIT 置信度最高的回复文本 :param parsed: UNIT 解析结果 :returns: UNIT 的回复文本 Here is the function: def getSayByConfidence(parsed): """ 提取 UNIT 置信度最高的回复文本 :param parsed: UNIT 解析结果 :returns: UNIT 的回复文本 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] answer = {} for response in response_list: if ( "schema" in response and "intent_confidence" in response["schema"] and ( not answer or response["schema"]["intent_confidence"] > answer["schema"]["intent_confidence"] ) ): answer = response return answer["action_list"][0]["say"] else: return ""
提取 UNIT 置信度最高的回复文本 :param parsed: UNIT 解析结果 :returns: UNIT 的回复文本
161,879
import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `getSay` function. Write a Python function `def getSay(parsed, intent="")` to solve the following problem: 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 Here is the function: def getSay(parsed, intent=""): """ 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] if intent == "": try: return response_list[0]["action_list"][0]["say"] except Exception as e: logger.warning(e) return "" for response in response_list: if ( "schema" in response and "intent" in response["schema"] and response["schema"]["intent"] == intent ): try: return response["action_list"][0]["say"] except Exception as e: logger.warning(e) return "" return "" else: return ""
提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本
161,880
import _thread as thread from robot import config, logging from robot.drivers.AIY import AIY logger = logging.getLogger(__name__) aiy = AIY() pixels = Pixels() def wakeup(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.wakeup, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.wakeup() else: logger.error("错误:不支持的灯光类型", stack_info=True)
null
161,881
import _thread as thread from robot import config, logging from robot.drivers.AIY import AIY logger = logging.getLogger(__name__) aiy = AIY() pixels = Pixels() def think(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.think, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.think() else: logger.error("错误:不支持的灯光类型", stack_info=True)
null
161,882
import _thread as thread from robot import config, logging from robot.drivers.AIY import AIY logger = logging.getLogger(__name__) aiy = AIY() pixels = Pixels() def off(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.off, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.off() else: logger.error("错误:不支持的灯光类型", stack_info=True)
null
161,883
import http.client import urllib.parse import json from robot import utils from robot import logging logger = logging.getLogger(__name__) def processGETRequest(appKey, token, voice, text, format, sampleRate): host = "nls-gateway.cn-shanghai.aliyuncs.com" url = "https://" + host + "/stream/v1/tts" # 设置URL请求参数 url = url + "?appkey=" + appKey url = url + "&token=" + token url = url + "&text=" + text url = url + "&format=" + format url = url + "&sample_rate=" + str(sampleRate) url = url + "&voice=" + voice logger.debug(url) conn = http.client.HTTPSConnection(host) conn.request(method="GET", url=url) # 处理服务端返回的响应 response = conn.getresponse() logger.debug("Response status and response reason:") logger.debug(response.status, response.reason) contentType = response.getheader("Content-Type") logger.debug(contentType) body = response.read() if "audio/mpeg" == contentType: logger.debug("The GET request succeed!") tmpfile = utils.write_temp_file(body, ".mp3") conn.close() return tmpfile else: logger.debug("The GET request failed: " + str(body)) conn.close() return None
null
161,884
import http.client import urllib.parse import json from robot import utils from robot import logging def processPOSTRequest(appKey, token, voice, text, format, sampleRate): host = "nls-gateway.cn-shanghai.aliyuncs.com" url = "https://" + host + "/stream/v1/tts" # 设置HTTPS Headers httpHeaders = {"Content-Type": "application/json"} # 设置HTTPS Body body = { "appkey": appKey, "token": token, "text": text, "format": format, "sample_rate": sampleRate, "voice": voice, } body = json.dumps(body) logger.debug("The POST request body content: " + body) # Python 2.x 请使用httplib # conn = httplib.HTTPSConnection(host) # Python 3.x 请使用http.client conn = http.client.HTTPSConnection(host) conn.request(method="POST", url=url, body=body, headers=httpHeaders) # 处理服务端返回的响应 response = conn.getresponse() logger.debug("Response status and response reason:") logger.debug(response.status, response.reason) contentType = response.getheader("Content-Type") logger.debug(contentType) body = response.read() if "audio/mpeg" == contentType: logger.debug("The POST request succeed!") tmpfile = utils.write_temp_file(body, ".mp3") conn.close() return tmpfile else: logger.critical("The POST request failed: " + str(body), stack_info=True) conn.close() return None def tts(appKey, token, voice, text): # 采用RFC 3986规范进行urlencode编码 textUrlencode = text textUrlencode = urllib.parse.quote_plus(textUrlencode) textUrlencode = textUrlencode.replace("+", "%20") textUrlencode = textUrlencode.replace("*", "%2A") textUrlencode = textUrlencode.replace("%7E", "~") format = "mp3" sampleRate = 16000 return processPOSTRequest(appKey, token, voice, text, format, sampleRate)
null
161,885
import http.client import urllib.parse import json from robot import utils from robot import logging logger = logging.getLogger(__name__) def process(request, token, audioContent): def asr(appKey, token, wave_file): # 服务请求地址 url = "http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr" pcm = utils.get_pcm_from_wav(wave_file) # 音频文件 format = "pcm" sampleRate = 16000 enablePunctuationPrediction = True enableInverseTextNormalization = True enableVoiceDetection = False # 设置RESTful请求参数 request = url + "?appkey=" + appKey request = request + "&format=" + format request = request + "&sample_rate=" + str(sampleRate) if enablePunctuationPrediction: request = request + "&enable_punctuation_prediction=" + "true" if enableInverseTextNormalization: request = request + "&enable_inverse_text_normalization=" + "true" if enableVoiceDetection: request = request + "&enable_voice_detection=" + "true" logger.debug("Request: " + request) return process(request, token, pcm)
null
161,886
import websocket import hashlib import base64 import hmac import json import wave import tempfile from urllib.parse import urlencode import time import ssl from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime import _thread as thread from robot import logging gResult = "" class ASR_Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): # 控制台鉴权信息 self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin"} # 生成url def create_url(self): url = "wss://ws-api.xfyun.cn/v2/iat" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new( self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256, ).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = ( 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) ) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( encoding="utf-8" ) # 将请求的鉴权参数组合为字典 v = {"authorization": authorization, "date": date, "host": "ws-api.xfyun.cn"} # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 logger.debug("websocket url :", url) return url global gResult The provided code snippet includes necessary dependencies for implementing the `transcribe` function. Write a Python function `def transcribe(fpath, appid, api_key, api_secret)` to solve the following problem: 科大讯飞ASR Here is the function: def transcribe(fpath, appid, api_key, api_secret): """ 科大讯飞ASR """ global asrWsParam, gResult gResult = "" asrWsParam = ASR_Ws_Param(appid, api_key, APISecret=api_secret, AudioFile=fpath) websocket.enableTrace(False) wsUrl = asrWsParam.create_url() ws = websocket.WebSocketApp( wsUrl, on_message=asr_on_message, on_error=asr_on_error, on_close=asr_on_close ) ws.on_open = asr_on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return gResult
科大讯飞ASR
161,887
import websocket import hashlib import base64 import hmac import json import wave import tempfile from urllib.parse import urlencode import time import ssl from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime import _thread as thread from robot import logging ttsWsParam = None gTTSResult = "" class TTS_Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, Text, voice_name="xiaoyan"): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.Text = Text # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = { "aue": "raw", "auf": "audio/L16;rate=16000", "vcn": voice_name, "tte": "utf8", } self.Data = { "status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8"), } # 生成url def create_url(self): url = "wss://tts-api.xfyun.cn/v2/tts" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/tts " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new( self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256, ).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = ( 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) ) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( encoding="utf-8" ) # 将请求的鉴权参数组合为字典 v = {"authorization": authorization, "date": date, "host": "ws-api.xfyun.cn"} # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url The provided code snippet includes necessary dependencies for implementing the `synthesize` function. Write a Python function `def synthesize(msg, appid, api_key, api_secret, voice_name="xiaoyan")` to solve the following problem: 科大讯飞TTS Here is the function: def synthesize(msg, appid, api_key, api_secret, voice_name="xiaoyan"): """ 科大讯飞TTS """ global ttsWsParam, gTTSPath, gTTSResult with tempfile.NamedTemporaryFile() as f: gTTSPath = f.name ttsWsParam = TTS_Ws_Param( APPID=appid, APIKey=api_key, APISecret=api_secret, Text=msg, voice_name=voice_name, ) websocket.enableTrace(False) wsUrl = ttsWsParam.create_url() ws = websocket.WebSocketApp( wsUrl, on_message=tts_on_message, on_error=tts_on_error, on_close=tts_on_close ) ws.on_open = tts_on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return gTTSResult
科大讯飞TTS
161,888
import yaml import logging import os from . import constants logger = logging.getLogger(__name__) def init(): global has_init if os.path.isfile(constants.CONFIG_PATH): logger.critical(f"错误:{constants.CONFIG_PATH} 应该是个目录,而不应该是个文件") if not os.path.exists(constants.CONFIG_PATH): os.makedirs(constants.CONFIG_PATH) if not os.path.exists(constants.getConfigPath()): yes_no = input(f"配置文件{constants.getConfigPath()}不存在,要创建吗?(y/n)") if yes_no.lower() == "y": constants.newConfig() doInit(constants.getConfigPath()) else: doInit(constants.getDefaultConfigPath()) else: doInit(constants.getConfigPath()) has_init = True The provided code snippet includes necessary dependencies for implementing the `reload` function. Write a Python function `def reload()` to solve the following problem: 重新加载配置 Here is the function: def reload(): """ 重新加载配置 """ logger.info("配置文件发生变更,重新加载配置文件") init()
重新加载配置
161,889
import yaml import logging import os from . import constants _config = {} The provided code snippet includes necessary dependencies for implementing the `getConfig` function. Write a Python function `def getConfig()` to solve the following problem: 返回全部配置数据 :returns: 全部配置数据(字典类型) Here is the function: def getConfig(): """ 返回全部配置数据 :returns: 全部配置数据(字典类型) """ return _config
返回全部配置数据 :returns: 全部配置数据(字典类型)
161,890
import yaml import logging import os from . import constants def getText(): if os.path.exists(constants.getConfigPath()): with open(constants.getConfigPath(), "r") as f: return f.read() return ""
null
161,891
import yaml import logging import os from . import constants def dump(configStr): with open(constants.getConfigPath(), "w") as f: f.write(configStr)
null