desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Execute task code with given arguments.'
def __call__(self, *args, **kwargs):
call = (lambda : super(RequestContextTask, self).__call__(*args, **kwargs)) context = kwargs.pop(self.CONTEXT_ARG_NAME, None) gl = kwargs.pop(self.GLOBALS_ARG_NAME, {}) if ((context is None) or has_request_context()): return call() with app.test_request_context(**context): for i in g...
'Includes all the information about current Flask request context as an additional argument to the task.'
def _include_request_context(self, kwargs):
if (not has_request_context()): return context = {'path': request.path, 'base_url': request.url_root, 'method': request.method, 'headers': dict(request.headers)} if ('?' in request.url): context['query_string'] = request.url[(request.url.find('?') + 1):] kwargs[self.CONTEXT_ARG_NAME] = c...
'Takes an event id and returns the event in iCal format'
@staticmethod def export(event_id):
event = EventModel.query.get(event_id) cal = Calendar() cal.add('prodid', '-//fossasia//open-event//EN') cal.add('version', '2.0') cal.add('x-wr-calname', event.name) cal.add('x-wr-caldesc', ('Schedule for sessions at ' + event.name)) tz = (event.timezone or 'UTC') tz = pytz....
'Speakers Call Validate Date - Tests if the function runs without an exception :return:'
def test_date_pass(self):
schema = SpeakersCallSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} SpeakersCallSchema.validate_date(schema, data, original_data)
'Speakers Call Validate Date - Tests if exception is raised when ends_at is before starts_at :return:'
def test_date_start_gt_end(self):
schema = SpeakersCallSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} with self.assertRaises(UnprocessableEntity): SpeakersCallSchema.validate_...
'Speakers Call Validate Date - Tests if validation works on values stored in db and not given in \'data\' :return:'
def test_date_db_populate(self):
with app.test_request_context(): schema = SpeakersCallSchema() obj = SpeakersCallFactory() db.session.add(obj) db.session.commit() original_data = {'data': {'id': 1}} data = {} SpeakersCallSchema.validate_date(schema, data, original_data)
'Tickets Validate Date - Tests if the function runs without an exception :return:'
def test_date_pass(self):
schema = TicketSchema() original_data = {'data': {}} data = {'sales_starts_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'sales_ends_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} TicketSchema.validate_date(schema, data, original_data)
'Tickets Validate Date - Tests if exception is raised when sales_ends_at is before sales_starts_at :return:'
def test_date_start_gt_end(self):
schema = TicketSchema() original_data = {'data': {}} data = {'sales_starts_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'sales_ends_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} with self.assertRaises(UnprocessableEntity): TicketSchema.validate_...
'Tickets Validate Date - Tests if validation works on values stored in db and not given in \'data\' :return:'
def test_date_db_populate(self):
with app.test_request_context(): schema = TicketSchema() obj = TicketFactory() db.session.add(obj) db.session.commit() original_data = {'data': {'id': 1}} data = {} TicketSchema.validate_date(schema, data, original_data)
'Tickets Validate Quantity - Tests if the function runs without an exception :return:'
def test_quantity_pass(self):
schema = TicketSchema() data = {'min_order': 10, 'max_order': 20, 'quantity': 30} TicketSchema.validate_quantity(schema, data)
'Tickets Validate Quantity - Tests if exception is raised when min_order greater than max :return:'
def test_quantity_min_gt_max(self):
schema = TicketSchema() data = {'min_order': 20, 'max_order': 10, 'quantity': 30} with self.assertRaises(UnprocessableEntity): TicketSchema.validate_quantity(schema, data)
'Tickets Validate Quantity - Tests if exception is raised when quantity less than max_order :return:'
def test_quantity_quantity_gt_min(self):
schema = TicketSchema() data = {'min_order': 10, 'max_order': 20, 'quantity': 5} with self.assertRaises(UnprocessableEntity): TicketSchema.validate_quantity(schema, data)
'Sessions Validate Date - Tests if the function runs without an exception :return:'
def test_date_pass(self):
schema = SessionSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} SessionSchema.validate_date(schema, data, original_data)
'Sessions Validate Date - Tests if exception is raised when ends_at is before starts_at :return:'
def test_date_start_gt_end(self):
schema = SessionSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} with self.assertRaises(UnprocessableEntity): SessionSchema.validate_date(schem...
'Sessions Validate Date - Tests if validation works on values stored in db and not given in \'data\' :return:'
def test_date_db_populate(self):
with app.test_request_context(): schema = SessionSchema() obj = SessionFactory() db.session.add(obj) db.session.commit() original_data = {'data': {'id': 1}} data = {} SessionSchema.validate_date(schema, data, original_data)
'Events Validate Date - Tests if the function runs without an exception :return:'
def test_date_pass(self):
schema = EventSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} EventSchema.validate_date(schema, data, original_data)
'Events Validate Date - Tests if exception is raised when ends_at is before starts_at :return:'
def test_date_start_gt_end(self):
schema = EventSchema() original_data = {'data': {}} data = {'starts_at': datetime(2003, 9, 4, 12, 30, 45).replace(tzinfo=timezone('UTC')), 'ends_at': datetime(2003, 8, 4, 12, 30, 45).replace(tzinfo=timezone('UTC'))} with self.assertRaises(UnprocessableEntity): EventSchema.validate_date(schema, d...
'Events Validate Date - Tests if validation works on values stored in db and not given in \'data\' :return:'
def test_date_db_populate(self):
with app.test_request_context(): schema = EventSchema() obj = EventFactoryBasic() db.session.add(obj) db.session.commit() original_data = {'data': {'id': 1}} data = {} EventSchema.validate_date(schema, data, original_data)
'Discount Code Validate Quantity - Tests if the function runs without an exception :return:'
def test_quantity_pass(self):
schema = DiscountCodeSchemaTicket() original_data = {'data': {}} data = {'min_quantity': 10, 'max_quantity': 20, 'tickets_number': 30} DiscountCodeSchemaTicket.validate_quantity(schema, data, original_data)
'Discount Code Validate Quantity - Tests if exception is raised when min_quantity greater than max :return:'
def test_quantity_min_gt_max(self):
schema = DiscountCodeSchemaTicket() original_data = {'data': {}} data = {'min_quantity': 20, 'max_quantity': 10, 'tickets_number': 30} with self.assertRaises(UnprocessableEntity): DiscountCodeSchemaTicket.validate_quantity(schema, data, original_data)
'Discount Code Validate Quantity - Tests if exception is raised when min_quantity greater than max :return:'
def test_quantity_max_gt_tickets_number(self):
schema = DiscountCodeSchemaTicket() original_data = {'data': {}} data = {'min_quantity': 10, 'max_quantity': 30, 'tickets_number': 20} with self.assertRaises(UnprocessableEntity): DiscountCodeSchemaTicket.validate_quantity(schema, data, original_data)
'Discount Code Validate Quantity - Tests if validation works on values stored in db and not given in \'data\' :return:'
def test_quantity_db_populate(self):
with app.test_request_context(): schema = DiscountCodeSchemaTicket() obj = DiscountCodeFactory() db.session.add(obj) db.session.commit() original_data = {'data': {'id': 1}} data = {} DiscountCodeSchemaTicket.validate_quantity(schema, data, original_data)
'read one page'
def read_tasks(self, type_id=0):
page_size = self.page_size limit = self.limit if (limit and (limit < page_size)): page_size = limit first_page = self.read_task_page_info_by_page_index(type_id, 0, page_size) tasks = first_page['tasks'] for (i, task) in enumerate(tasks): task['#'] = i return tasks
'read all pages'
def read_all_tasks_immediately(self, type_id):
all_tasks = [] page_size = self.page_size limit = self.limit if (limit and (limit < page_size)): page_size = limit first_page = self.read_task_page_info_by_page_index(type_id, 0, page_size) all_tasks.extend(first_page['tasks']) total_tasks = first_page['total_task_number'] if (li...
'read all pages, lazily'
def read_all_tasks_on_demand(self, type_id):
fetch_page = (lambda page_index, page_size: self.read_task_page_info_by_page_index(type_id, page_index, page_size)) return OnDemandTaskList(fetch_page, self.page_size, self.limit)
'read all pages'
def read_all_tasks(self, type_id=0):
return self.read_all_tasks_on_demand(type_id)
'read first page of completed tasks'
def read_completed(self):
return self.read_tasks(2)
'read all pages of completed tasks'
def read_all_completed(self):
return self.read_all_tasks(2)
'read one page'
def read_history(self, type=0):
tasks = self.read_history_page(type)[0] for (i, task) in enumerate(tasks): task['#'] = i return tasks
'read all pages of deleted/expired tasks'
def read_all_history(self, type=0):
all_tasks = [] (tasks, next_link) = self.read_history_page(type) all_tasks.extend(tasks) while next_link: if (self.limit and (len(all_tasks) > self.limit)): break (tasks, next_link) = self.read_history_page_url(next_link) all_tasks.extend(tasks) if self.limit: ...
'Run the callback unless it has already been called or cancelled'
def __call__(self, wr=None):
try: del _finalizer_registry[self._key] except KeyError: sub_debug('finalizer no longer registered') else: sub_debug('finalizer calling %s with args %s and kwargs %s', self._callback, self._args, self._kwargs) res = self._callback(*self._args,...
'Cancel finalization of the object'
def cancel(self):
try: del _finalizer_registry[self._key] except KeyError: pass else: self._weakref = self._callback = self._args = self._kwargs = self._key = None
'Return whether this finalizer is still waiting to invoke callback'
def still_active(self):
return (self._key in _finalizer_registry)
'Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object.'
def accept(self):
c = self._listener.accept() if self._authkey: deliver_challenge(c, self._authkey) answer_challenge(c, self._authkey) return c
'Close the bound socket or named pipe of `self`.'
def close(self):
return self._listener.close()
'Resend fragments requires a ping done first to find missing fragments'
def resend_message(self, msg_id):
if ((self.pending_msg_id == msg_id) and (msg_id in self.pending_messages.keys())): print '[+] Found saved message, only resending missing fragments' for i in self.pending_messages[msg_id].keys(): if (not self.pending_fragments[(i - 1)]): self.send_dat...
'Queue any number of params for next call. Returns log.'
def queue(self, **params):
try: for key in params: self.__queue[key] = deepcopy(params[key]) except: self.notify_of_error(('Could not set queue by dictionary. Parameters were:\n' + str(params))) return self
'Get the value of key from the params, return default if not found.'
def get(self, key, default=None):
return self.__params.get(key, default)
'Set the value of params for all future calls. Returns log.'
def set(self, **params):
try: for key in params: self.__params[key] = deepcopy(params[key]) except: self.notify_of_error(('Could not set params. Parameters were:\n' + str(params))) return self
'Set various attributes about the machine from which the log is being produced. Returns log.'
def set_machine_info(self, hostname=None, os_name=None, os_version=None, os_arch=None, hw_processor=None, **params):
return self.set(local_hostname=hostname, local_os_name=os_name, local_os_version=os_version, local_os_arch=os_arch, local_hw_processor=hw_processor, **params)
'Reports this tool was opened, pass in command line if known. Returns log.'
def open(self, command_line=None, **params):
self('tool opened', command_line=command_line, **params) return self
'Reports this tool was closed.'
def close(self, command_line=None, results=None, status=None, success=None, **params):
self.running = False self('tool closed', command_line=command_line, command_results=results, command_status=status, command_success=success, command_uuid=(uuid() if command_line else None), **params)
'A tool\'s internal command caused activity on the remote machine. Returns event_uuid.'
def command(self, name, results=None, status=None, success=None, *args, **params):
return self('command executed', command_name=name, command_args=str(args), command_results=results, command_status=status, command_success=success, command_uuid=uuid(), **params)
'Reports that a command was run from this tool instance, spawning a child tool. Returns log.'
def launch_from_command(self, command_name, tool_name, tool_version, **params):
parent_uuid = self.command(command_name, **params) child = self.make_child(tool_name, tool_version, parent_uuid) return child
'Upload a file given its local path. Returns event_uuid.'
def file_from_path(self, full_path, parent_uuid=None, **params):
try: full_path = os.path.realpath(os.path.normpath(full_path)) (file_path, file_name) = os.path.split(full_path) shutil.copyfile(full_path, ((self.basefilename() + '.') + file_name)) except: self.notify_of_error(('Could not access file ' + full_path)) else: ...
'Upload a file given its content. Returns event_uuid.'
def file_from_content(self, content, storage_name, parent_uuid=None, **params):
try: storage_name = (storage_name or ('%s.txt' % uuid())) full_path = ((self.basefilename() + '.') + storage_name) with open(full_path, 'wb') as f: f.write(content.encode('utf-8')) except: self.notify_of_error(('Could not write file ' + full_path)) els...
'Upload a file given an open file descriptor to a local path. Returns event_uuid.'
def file_from_file(self, fd, parent_uuid=None, **params):
try: fd.flush() return self.file_from_path(fd.name, parent_uuid, **params) except: self.notify_of_error(('Could not access file descriptor for ' + str(fd))) return None
'Queues the start time of execution. Results in stop time being marked by next log call. Returns log.'
def start(self):
return self.queue(start_time=datetime.utcnow())
'Intended for use by other methods (success/fail). Reports execution of an exploit from within this tool. Returns event_uuid.'
def execute_exploit(self, **params):
return self('exploit executed', **params)
'Reports execution of this tool and the command line that started it.'
def execute_tool_from_command_line(self, command_line, **params):
return self.execute_tool(command_line=command_line, **params)
'Reports successful exploitation from this tool and the command line that started it.'
def successful_exploit_from_command_line(self, command_line, **params):
return self.successful_exploit(command_line=command_line, **params)
'Reports failed exploitation from this tool and the command line that started it.'
def failed_exploit_from_command_line(self, command_line, **params):
return self.failed_exploit(command_line=command_line, **params)
'Ran single-fire local command to exploit with sub-tool name/version. Report successful exploit. Return event_uuid.'
def successful_exploit_from_command(self, command, tool_name, tool_version, **params):
return self.launch_from_command(command, tool_name, tool_version).successful_exploit(**params)
'Ran single-file local command to exploit with sub-tool name/version. Report failed exploit. Return event_uuid.'
def failed_exploit_from_command(self, command, tool_name, tool_version, **params):
return self.launch_from_command(command, tool_name, tool_version).failed_exploit(**params)
'Enable a network interface on the reporting machine.'
def interface_enabled(self, ip, project=None, mac=None, name=None, **params):
return self(event_type='interface enabled', interface_ip=ip, interface_project=project, interface_mac=mac, interface_name=name, **params)
'Disable a network interface on the reporting machine.'
def interface_disabled(self, ip, project=None, mac=None, name=None, **params):
return self(event_type='interface disabled', interface_ip=ip, interface_project=project, interface_mac=mac, interface_name=name, **params)
'Open a local RAW/UDP or TCP LISTENing socket.'
def socket_opened(self, port, ip='0.0.0.0', project=None, is_tcp=None, is_udp=None, is_raw=None, **params):
if (is_raw or is_tcp or is_udp): return self(event_type='socket opened', socket_port=port, socket_ip=ip, socket_project=project, socket_is_raw=is_raw, socket_is_tcp=is_tcp, socket_is_udp=is_udp, **params) else: self.notify_of_error('Could not open socket. No socket type ...
'Close a local socket and any open connections.'
def socket_closed(self, port, ip='0.0.0.0', project=None, is_tcp=None, is_udp=None, is_raw=None, **params):
if (is_raw or is_tcp or is_udp): return self(event_type='socket closed', socket_port=port, socket_ip=ip, socket_project=project, socket_is_raw=is_raw, socket_is_tcp=is_tcp, socket_is_udp=is_udp, **params) else: self.notify_of_error('Could not close socket. No socket type...
'Create a channel from a listening ip:port or [ip,...]:port to a redirector, from which data is forwarded to an ip:port.'
def channel_opened(self, listen_ip, listen_port, redirect_from_ip, forward_to_ip, forward_to_port, is_tcp=None, listen_project=None, redirect_from_project=None, forward_to_project=None, **params):
return self(event_type='channel opened', channel_listen_ip=listen_ip, channel_listen_port=listen_port, channel_listen_project=listen_project, channel_forward_to_ip=forward_to_ip, channel_forward_to_port=forward_to_port, channel_forward_to_project=forward_to_project, channel_redirect_from_ip=redirect_from_ip, cha...
'Terminate a channel from a listening ip:port or [ip,...]:port to a redirector, from which data is forwarded to an ip:port.'
def channel_closed(self, listen_ip, listen_port, listen_project=None, **params):
return self(event_type='channel closed', channel_listen_ip=listen_ip, channel_listen_port=listen_port, channel_listen_project=listen_project, **params)
'Open (successfully) a direct connection between source (initiating) and destination (receiving) ip:port pairs.'
def connection_opened(self, source_ip, source_port, destination_ip, destination_port, is_tcp=None, source_project=None, destination_project=None, **params):
return self(event_type='connection opened', connection_source_ip=source_ip, connection_source_project=source_project, connection_source_port=source_port, connection_destination_ip=destination_ip, connection_destination_project=destination_project, connection_destination_port=destination_port, connection_is_tcp=i...
'Close a direct connection between source (initiating) and destination (receiving) ip:port pairs.'
def connection_closed(self, source_ip, source_port, destination_ip, destination_port, is_tcp=None, source_project=None, destination_project=None, **params):
return self(event_type='connection closed', connection_source_ip=source_ip, connection_source_project=source_project, connection_source_port=source_port, connection_destination_ip=destination_ip, connection_destination_project=destination_project, connection_destination_port=destination_port, connection_is_tcp=i...
'Connection from source ip:port to destination (listening) ip:port was refused.'
def connection_refused(self, source_ip, source_port, destination_ip, destination_port, is_tcp=None, source_project=None, destination_project=None, **params):
return self(event_type='connection refused', connection_source_ip=source_ip, connection_source_project=source_project, connection_source_port=source_port, connection_destination_ip=destination_ip, connection_destination_project=destination_project, connection_destination_port=destination_port, connection_is_tcp=...
'Connection from source ip:port to destination (listening) ip:port was rejected.'
def connection_rejected(self, source_ip, source_port, destination_ip, destination_port, is_tcp=None, source_project=None, destination_project=None, **params):
return self(event_type='connection rejected', connection_source_ip=source_ip, connection_source_project=source_project, connection_source_port=source_port, connection_destination_ip=destination_ip, connection_destination_project=destination_project, connection_destination_port=destination_port, connection_is_tcp...
'Connection from source ip:port to destination (listening) ip:port failed.'
def connection_failed(self, source_ip, source_port, destination_ip, destination_port, is_tcp=None, source_project=None, destination_project=None, **params):
return self(event_type='connection failed', connection_source_ip=source_ip, connection_source_project=source_project, connection_source_port=source_port, connection_destination_ip=destination_ip, connection_destination_project=destination_project, connection_destination_port=destination_port, connection_is_tcp=i...
'Send a trigger from source ip:port at a target (probably locally listening) ip:port.'
def trigger_sent(self, trigger_type, source_ip, source_port, target_ip, target_port, is_tcp=None, **params):
return self(event_type='trigger sent', trigger_source_ip=source_ip, trigger_source_port=source_port, trigger_target_ip=target_ip, trigger_target_port=target_port, trigger_type=trigger_type, **params)
'Basic log call. At a minimum, this will write the tool name and version specified during init, an event_type (heartbeat if not specified), a parent event (only if specified), and an event_time (now if not specified).'
def __call__(self, event_type='heartbeat', parent_uuid=None, event_time=None, **params):
try: d = self._flatten(event_time=(event_time if event_time else datetime.utcnow()), event_type=event_type, event_uuid=uuid(), event_parent_uuid=parent_uuid, **params) if d.get('start_time'): d['stop_time'] = d['event_time'] d['event_time'] = d['start_time'] if self.e...
'@param stdin @param stdout @param use_raw @param noprompt Do we want to prompt for values upon plugin execution? @param completekey Command completion'
def __init__(self, stdin=None, stdout=None, use_raw=1, noprompt=False, completekey='tab', enablecolor=True, history=4096):
import sys if (stdin is not None): self.stdin = stdin else: self.stdin = sys.stdin if (stdout is not None): self.stdout = stdout else: self.stdout = sys.stdout self.stderr = self.stdout self.logout = DevNull() self.noprompt = noprompt self.raw_input = ...
'Switch to enable or disable color output'
def setcolormode(self, isEnabled):
self.enablecolor = isEnabled
'Effectively "main" from Commandlinewrapper'
def __call__(self, argv):
logConfig = None context = {} rendezvous = None try: (opts, args) = self.__coli_parser.parse_args(argv) if (opts.InConfig is None): raise ExploitConfigError('You must pass a valid --InConfig option') self.config = truantchild.Config([opts.InConfig]) ...
'Setup so that we can do logging'
def processWrapperParams(self, options):
fh = None if (options.LogFile is not None): print 'logging to file' fh = exma.openEMForWriting(options.OutConfig) logger = get_logger(options.LogFile) else: print 'logging to stdout' fh = exma.openEMForWriting(None) logger = get_logger(None) re...
'Convert Truantchild parameters into a dictionary for easy processing'
def tc2Dict(self, params):
d = {} for (k, v) in params.getParameterList(): d[k] = v return d
'Convert inputs to optparse style options for ease of processing in Python'
def tc2List(self, inputs):
args = [] for (k, v) in inputs.getParameterList(): args += ['--{0}'.format(k), str(v)] return args
'A parameter iterator'
def iterParams(self, params):
for (k, v) in params.getParameterList(): (yield k)
'Convert from optparse options back to Truantchild parameters after execution'
def options2Tc(self, options, outputs):
for (name, val) in outputs.getParameterList(): if (name in options.keys()): outputs.set(name, options[name])
'Basically stolen from plugin::createsRendezvous'
def __needRendezvous(self, params, checkForContract):
if checkForContract: for (name, val) in params.getParameterList(): if ('Socket' == params.findOption(name).getType()): return True return False
'bindRendezvous taken from exma.dll'
def __exma_bindRendezvous(self, outputs, namespaceUri, schemaVersion):
rendezvous = ctypes.c_ushort() sock = ctypes.c_uint() ret = exma.bindRendezvous(ctypes.pointer(rendezvous), ctypes.pointer(sock)) return (rendezvous.value, sock.value)
'Add output parameters after the script runs to do rendezvous'
def addWrapperOutputParams(self, outputs, namespaceUri, schemaVersion):
rendezvous = None sock = None if self.__needRendezvous(outputs, True): (rendezvous, sock) = self.__exma_bindRendezvous(outputs, namespaceUri, schemaVersion) outputs.addRendezvousParam(str(rendezvous)) return (rendezvous, sock)
'Perform the rendezvous socket transfer between plugins'
def __transformSocket(self, rendezvous, remoteSocket, localSocket, cache):
ls = ctypes.c_uint() if (remoteSocket is None): localSocket = None return for (l, r) in cache: if (remoteSocket == r): localSocket = l return exma.recvSocket(ctypes.c_uint(rendezvous), ctypes.c_uint(remoteSocket), ctypes.pointer(ls)) localSocket = ls.v...
'Connect all sockets to rendezvous server sockets'
def doRendezvousClient(self, inputs):
cache = [] rendezvousLocation = None sock = ctypes.c_uint() local = None sockparams = [] for (name, val) in inputs.getParameterList(): if ((name == 'Rendezvous') and inputs.hasValidValue('Rendezvous')): rendezvousLocation = inputs.get('Rendezvous') elif ('Socket' == i...
'Setup the rendezvous server so the next plugin can talk \'through\' us'
def doRendezvousServer(self, rendezvous, sock):
if (sock is not None): r = ctypes.c_uint(sock) if ((-1) == exma.sendSockets(r)): return (-1) exma.closeRendezvous(ctypes.c_ushort(rendezvous), r) sock = None return 0
'Process the input parameters and achieve the intended purpose'
def processParams(self, inputs, constants, outputs, context, logConfig):
raise NotImplementedError('processParams must be implemented')
'Return the plugin ID'
def getID(self):
raise NotImplementedError('getID must be implemented')
'Cleanup any errant connections or data after the rendezvous is done'
def cleanup(self, flags, context, logConfig):
raise NotImplementedError('cleanup must be implemented')
'Validate parameters to verify sane values'
def validateParams(self, inputs):
raise NotImplementedError('validateParams must be implemented')
'Initialize the Console object. newbuffer=1 will allocate a new buffer so the old content will be restored on exit.'
def __init__(self, newbuffer=0):
if newbuffer: self.hout = self.CreateConsoleScreenBuffer((GENERIC_READ | GENERIC_WRITE), 0, None, 1, None) self.SetConsoleActiveScreenBuffer(self.hout) else: self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE) self.hin = self.GetStdHandle(STD_INPUT_HANDLE) self.inmode = c_int(0) ...
'Cleanup the console when finished.'
def __del__(self):
self.SetConsoleTextAttribute(self.hout, self.saveattr) self.SetConsoleMode(self.hin, self.inmode) self.FreeConsole()
'Return a long with x and y packed inside, also handle negative x and y.'
def fixcoord(self, x, y):
if ((x < 0) or (y < 0)): info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) if (x < 0): x = (info.srWindow.Right - x) y = (info.srWindow.Bottom + y) return c_int(((y << 16) | x))
'Move or query the window cursor.'
def pos(self, x=None, y=None):
if (x is None): info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) return (info.dwCursorPosition.X, info.dwCursorPosition.Y) else: return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y))
'Move to home.'
def home(self):
self.pos(0, 0)
'write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the scroll amount. For example, I remember the cursor position of the prompt so that I can redraw the line but if the windo...
def write_scrolling(self, text, attr=None):
(x, y) = self.pos() (w, h) = self.size() scroll = 0 chunks = self.motion_char_re.split(text) for chunk in chunks: log(('C:' + chunk)) n = self.write_color(chunk, attr) if (len(chunk) == 1): if (chunk[0] == '\n'): x = 0 y += 1 ...
'write text at current cursor position and interpret color escapes. return the number of characters written.'
def write_color(self, text, attr=None):
log(('write_color("%s", %s)' % (text, attr))) chunks = self.terminal_escape.split(text) log(('chunks=%s' % repr(chunks))) junk = c_int(0) n = 0 for chunk in chunks: m = self.escape_parts.match(chunk) if m: attr = self.escape_to_color[m.group(1)] continu...
'write text at current cursor position.'
def write_plain(self, text, attr=None):
log(('write("%s", %s)' % (text, attr))) if (attr is None): attr = self.attr n = c_int(0) self.SetConsoleTextAttribute(self.hout, attr) self.WriteConsoleA(self.hout, ensure_text(chunk), len(chunk), byref(junk), None) return len(text)
'Fill the entire screen.'
def page(self, attr=None, fill=' '):
if (attr is None): attr = self.attr if (len(fill) != 1): raise ValueError info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) if ((info.dwCursorPosition.X != 0) or (info.dwCursorPosition.Y != 0)): self.SetConsoleCursorPosition(self.hout...
'Write text at the given position.'
def text(self, x, y, text, attr=None):
if (attr is None): attr = self.attr pos = self.fixcoord(x, y) n = c_int(0) self.WriteConsoleOutputCharacterA(self.hout, text, len(text), pos, byref(n)) self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))
'Fill Rectangle.'
def rectangle(self, rect, attr=None, fill=' '):
log_sock(('rect:%s' % [rect])) (x0, y0, x1, y1) = rect n = c_int(0) if (attr is None): attr = self.attr for y in range(y0, y1): pos = self.fixcoord(x0, y) self.FillConsoleOutputAttribute(self.hout, attr, (x1 - x0), pos, byref(n)) self.FillConsoleOutputCharacterA(self....
'Scroll a rectangle.'
def scroll(self, rect, dx, dy, attr=None, fill=' '):
if (attr is None): attr = self.attr (x0, y0, x1, y1) = rect source = SMALL_RECT(x0, y0, (x1 - 1), (y1 - 1)) dest = self.fixcoord((x0 + dx), (y0 + dy)) style = CHAR_INFO() style.Char.AsciiChar = fill[0] style.Attributes = attr return self.ScrollConsoleScreenBufferA(self.hout, byre...
'Scroll the window by the indicated number of lines.'
def scroll_window(self, lines):
info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) rect = info.srWindow log(('sw: rtop=%d rbot=%d' % (rect.Top, rect.Bottom))) top = (rect.Top + lines) bot = (rect.Bottom + lines) h = (bot - top) maxbot = (info.dwSize.Y - 1) if (top < 0)...
'Get next event from queue.'
def get(self):
inputHookFunc = c_int.from_address(self.inputHookPtr).value Cevent = INPUT_RECORD() count = c_int(0) while 1: if inputHookFunc: call_function(inputHookFunc, ()) status = self.ReadConsoleInputA(self.hin, byref(Cevent), 1, byref(count)) if (status and (count.value == 1)...
'Return next key press event from the queue, ignoring others.'
def getkeypress(self):
while 1: e = self.get() if ((e.type == 'KeyPress') and (e.keycode not in key_modifiers)): log(e) if (e.keyinfo.keyname == 'next'): self.scroll_window(12) elif (e.keyinfo.keyname == 'prior'): self.scroll_window((-12)) els...