code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
else:
doc = path_or_doc
assert isinstance(doc, OpenDocument), doc
styles = {_style_name(style): style for style in doc.styles.childNodes}
return styles | def load_styles(path_or_doc) | Return a dictionary of all styles contained in an ODF document. | 3.746426 | 3.319595 | 1.128579 |
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
if style in (None, 'normal-text'):
return 'text'
elif style == 'url':
return 'link'
else:
return style
elif tag == 'h':
assert style is not None
return style
elif tag in ('list', 'list-item', 'line-break'):
if style == '_numbered_list':
return 'numbered-list'
else:
return tag
elif tag == 's':
return 'spaces'
raise Exception("The tag '{0}' with style '{1}' hasn't "
"been implemented.".format(tag, style)) | def _item_type(item) | Indicate to the ODF reader the type of the block or text. | 3.537336 | 3.255119 | 1.086699 |
for stylename in sorted(styles):
self._doc.styles.addElement(styles[stylename]) | def add_styles(self, **styles) | Add ODF styles to the current document. | 6.6444 | 4.638978 | 1.432298 |
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
el = cls(**kwargs)
self._doc.text.addElement(el) | def _add_element(self, cls, **kwargs) | Add an element. | 10.731535 | 9.759947 | 1.099549 |
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name = el.attributes.get(style_field, None)
if not name:
return None
return self._get_style_name(name) | def _style_name(self, el) | Return the style name of an element. | 3.279888 | 3.047411 | 1.076287 |
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
# Create the container.
container = cls(**kwargs)
self._containers.append(container) | def start_container(self, cls, **kwargs) | Append a new container. | 7.022392 | 6.617144 | 1.061242 |
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
else:
parent = self._doc.text
if not cancel:
parent.addElement(container) | def end_container(self, cancel=None) | Finishes and registers the currently-active container, unless
'cancel' is True. | 3.87897 | 3.901067 | 0.994335 |
self.start_container(cls, **kwargs)
yield
self.end_container() | def container(self, cls, **kwargs) | Container context manager. | 6.317796 | 3.944621 | 1.601623 |
# Use the next paragraph style if one was set.
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | def start_paragraph(self, stylename=None) | Start a new paragraph. | 6.509 | 5.874132 | 1.108079 |
if self._containers and _is_paragraph(self._containers[-1]):
return False
else:
self.start_paragraph()
return True | def require_paragraph(self) | Create a new paragraph unless the currently-active container
is already a paragraph. | 6.627504 | 4.502259 | 1.47204 |
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1))
container.addElement(S(c=n))
text = text[n:]
elif ' ' in text:
assert not text.startswith(' ')
i = text.index(' ')
container.addElement(Span(text=text[:i]))
text = text[i:]
else:
container.addElement(Span(text=text))
text = '' | def _code_line(self, line) | Add a code line. | 4.08994 | 3.858107 | 1.06009 |
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
self._code_line(line)
self.linebreak()
self._code_line(lines[-1]) | def code(self, text, lang=None) | Add a code block. | 6.010719 | 5.466398 | 1.099576 |
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | def start_numbered_list(self) | Start a numbered list. | 10.513759 | 9.939459 | 1.05778 |
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | def start_list(self) | Start a list. | 12.471486 | 10.510187 | 1.186609 |
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=text))
else:
container.addElement(Span(text=text)) | def text(self, text, stylename=None) | Add text within the current container. | 3.352093 | 2.991693 | 1.120467 |
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
out = _ensure_string(out)
# HACK: skip <matplotlib ...> outputs.
if out.startswith('<matplotlib'):
continue
text_outputs.append(out)
return stdout + '\n'.join(text_outputs).rstrip() | def _cell_output(cell) | Return the output of an ipynb cell. | 4.131298 | 3.499776 | 1.180446 |
'Post-processing to add some nice-ish spacing for deeper map/list levels.'
if isinstance(vspacing, int):
vspacing = ['\n']*(vspacing+1)
buff.seek(0)
result = list()
for line in buff:
level = 0
line = line.decode('utf-8')
result.append(line)
if ':' in line or re.search(r'---(\s*$|\s)', line):
while line.startswith(' '):
level, line = level + 1, line[2:]
if len(vspacing) > level and len(result) != 1:
vspace = vspacing[level]
result.insert( -1, vspace
if not isinstance(vspace, int) else '\n'*vspace )
buff.seek(0), buff.truncate()
buff.write(''.join(result).encode('utf-8')) | def dump_add_vspacing(buff, vspacing) | Post-processing to add some nice-ish spacing for deeper map/list levels. | 4.420139 | 3.192681 | 1.38446 |
if grep:
return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep))
return self.adb_shell('dumpsys {0}'.format(service)) | def _dump(self, service, grep=None) | Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped. | 2.897279 | 3.271578 | 0.885591 |
dump_grep = self._dump(service, grep=grep)
if not dump_grep:
return False
return dump_grep.strip().find(search) > -1 | def _dump_has(self, service, grep, search) | Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not. | 5.166377 | 7.027076 | 0.73521 |
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
for bad_line in ps:
# The splitting of the StreamingShell doesn't always work
# this is to ensure that we get only one line
for line in bad_line.splitlines():
if search in line:
result.append(line.strip().rsplit(' ', 1)[-1])
return result
except InvalidChecksumError as e:
print(e)
self.connect()
raise IOError | def _ps(self, search='') | Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields | 7.266543 | 7.349918 | 0.988656 |
self._adb_lock.acquire(**LOCK_KWARGS)
try:
if not self.adb_server_ip:
# python-adb
try:
if self.adbkey:
signer = Signer(self.adbkey)
# Connect to the device
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000)
else:
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000)
# ADB connection successfully established
self._available = True
except socket_error as serr:
if self._available or always_log_errors:
if serr.strerror is None:
serr.strerror = "Timed out trying to connect to ADB device."
logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror)
# ADB connection attempt failed
self._adb = None
self._available = False
finally:
return self._available
else:
# pure-python-adb
try:
self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port)
self._adb_device = self._adb_client.device(self.host)
self._available = bool(self._adb_device)
except:
self._available = False
finally:
return self._available
finally:
self._adb_lock.release() | def connect(self, always_log_errors=True) | Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise | 3.068944 | 2.967185 | 1.034295 |
# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True)
# Check if device is off.
if not screen_on:
state = STATE_OFF
current_app = None
running_apps = None
# Check if screen saver is on.
elif not awake:
state = STATE_IDLE
current_app = None
running_apps = None
else:
# Get the current app.
if isinstance(_current_app, dict) and 'package' in _current_app:
current_app = _current_app['package']
else:
current_app = None
# Get the running apps.
if running_apps is None and current_app:
running_apps = [current_app]
# Get the state.
# TODO: determine the state differently based on the `current_app`.
if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]:
state = STATE_STANDBY
# Amazon Video
elif current_app == AMAZON_VIDEO:
if wake_lock_size == 5:
state = STATE_PLAYING
else:
# wake_lock_size == 2
state = STATE_PAUSED
# Netflix
elif current_app == NETFLIX:
if wake_lock_size > 3:
state = STATE_PLAYING
else:
state = STATE_PAUSED
# Check if `wake_lock_size` is 1 (device is playing).
elif wake_lock_size == 1:
state = STATE_PLAYING
# Otherwise, device is paused.
else:
state = STATE_PAUSED
return state, current_app, running_apps | def update(self, get_running_apps=True) | Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps | 2.713167 | 2.7154 | 0.999178 |
if not self.available or not self.screen_on:
return STATE_OFF
if self.current_app["package"] == app:
return STATE_ON
return STATE_OFF | def app_state(self, app) | Informs if application is running. | 6.183901 | 5.189744 | 1.191562 |
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
# Check if screen saver is on.
if not self.awake:
return STATE_IDLE
# Check if the launcher is active.
if self.launcher or self.settings:
return STATE_STANDBY
# Check for a wake lock (device is playing).
if self.wake_lock:
return STATE_PLAYING
# Otherwise, device is paused.
return STATE_PAUSED | def state(self) | Compute and return the device state.
:returns: Device state. | 4.153677 | 4.023136 | 1.032448 |
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
# make sure the device is available
try:
# case 1: the device is currently available
if any([self.host in dev.get_serial_no() for dev in adb_devices]):
if not self._available:
self._available = True
return True
# case 2: the device is not currently available
if self._available:
logging.error('ADB server is not connected to the device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB device is unavailable; encountered an error when searching for device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB server is unavailable.')
self._available = False
return False | def available(self) | Check whether the ADB connection is intact. | 3.922847 | 3.654759 | 1.073353 |
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | def running_apps(self) | Return a list of running user applications. | 4.03749 | 3.73679 | 1.08047 |
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was successfully found
if matches:
(pkg, activity) = matches.group("package", "activity")
return {"package": pkg, "activity": activity}
# case 2: current app could not be found
logging.warning("Couldn't get current app, reply was %s", current_focus)
return None | def current_app(self) | Return the current app. | 4.145256 | 3.932049 | 1.054223 |
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | def wake_lock_size(self) | Get the size of the current wake lock. | 4.757697 | 4.135121 | 1.150558 |
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD + " && " +
RUNNING_APPS_CMD)
else:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD)
# ADB command was unsuccessful
if output is None:
return None, None, None, None, None
# `screen_on` property
if not output:
return False, False, -1, None, None
screen_on = output[0] == '1'
# `awake` property
if len(output) < 2:
return screen_on, False, -1, None, None
awake = output[1] == '1'
lines = output.strip().splitlines()
# `wake_lock_size` property
if len(lines[0]) < 3:
return screen_on, awake, -1, None, None
wake_lock_size = int(lines[0].split("=")[1].strip())
# `current_app` property
if len(lines) < 2:
return screen_on, awake, wake_lock_size, None, None
matches = WINDOW_REGEX.search(lines[1])
if matches:
# case 1: current app was successfully found
(pkg, activity) = matches.group("package", "activity")
current_app = {"package": pkg, "activity": activity}
else:
# case 2: current app could not be found
current_app = None
# `running_apps` property
if not get_running_apps or len(lines) < 3:
return screen_on, awake, wake_lock_size, current_app, None
running_apps = [line.strip().rsplit(' ', 1)[-1] for line in lines[2:] if line.strip()]
return screen_on, awake, wake_lock_size, current_app, running_apps | def get_properties(self, get_running_apps=True, lazy=False) | Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties. | 2.172234 | 1.926846 | 1.127352 |
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A valid device identifier contains "
"only ascii word characters or dashes. "
"Device '%s' not added.", device_id)
return valid | def is_valid_device_id(device_id) | Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not. | 7.179301 | 4.498484 | 1.595938 |
valid = is_valid_device_id(device_id) and is_valid_host(host)
if valid:
devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port))
return valid | def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037) | Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for the ADB server
:returns: Added successfully or not. | 2.818333 | 2.72976 | 1.032447 |
req = request.get_json()
success = False
if 'device_id' in req and 'host' in req:
success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037))
return jsonify(success=success) | def add_device() | Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
} | 3.290849 | 2.782597 | 1.182654 |
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) | def list_devices() | List devices via HTTP GET. | 3.188352 | 3.107516 | 1.026013 |
if device_id not in devices:
return jsonify(success=False)
return jsonify(state=devices[device_id].state) | def device_state(device_id) | Get device state via HTTP GET. | 3.500927 | 3.961143 | 0.883817 |
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | def current_app(device_id) | Get currently running app. | 2.450363 | 2.468327 | 0.992722 |
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
return jsonify(running_apps=devices[device_id].running_apps) | def running_apps(device_id) | Get running apps via HTTP GET. | 2.606177 | 2.692565 | 0.967916 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
app_state = devices[device_id].app_state(app_id)
return jsonify(state=app_state, status=app_state) | def get_app_state(device_id, app_id) | Get the state of the requested app | 2.28653 | 2.276205 | 1.004536 |
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=success) | def device_action(device_id, action_id) | Initiate device action via HTTP GET. | 3.319788 | 3.560539 | 0.932383 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].launch_app(app_id)
return jsonify(success=success) | def app_start(device_id, app_id) | Starts an app with corresponding package name | 2.206415 | 2.222938 | 0.992567 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return jsonify(success=success) | def app_stop(device_id, app_id) | stops an app with corresponding package name | 2.120993 | 2.102356 | 1.008865 |
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | def device_connect(device_id) | Force a connection attempt via HTTP GET. | 3.400551 | 3.613303 | 0.94112 |
config_file = open(config_file_path, 'r')
config = yaml.load(config_file)
config_file.close()
return config | def _parse_config(config_file_path) | Parse Config File from yaml file. | 2.195587 | 1.723808 | 1.273684 |
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
if config['devices'][device]['host'] == args.default:
raise ValueError('host set in default param must not be defined in config')
add(device, config['devices'][device]['host'], config['devices'][device].get('adbkey', ''),
config['devices'][device].get('adb_server_ip', ''), config['devices'][device].get('adb_server_port', 5037)) | def _add_devices_from_config(args) | Add devices from config. | 4.068524 | 3.917095 | 1.038658 |
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file')
args = parser.parse_args()
if args.config:
_add_devices_from_config(args)
if args.default and not add('default', args.default):
exit('invalid hostname')
app.run(host='0.0.0.0', port=args.port) | def main() | Set up the server. | 3.676073 | 3.561544 | 1.032157 |
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | def _load_words(self) | Loads the list of profane words from file. | 3.849836 | 2.942184 | 1.308496 |
# TODO: what if character isn't str()-able?
if isinstance(character, int):
character = str(character)
self._censor_char = character | def set_censor(self, character) | Replaces the original censor character '*' with ``character``. | 6.62479 | 5.954524 | 1.112564 |
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for w in self._censor_list]
profane_words.extend(self._extra_censor_list)
profane_words.extend([inflection.pluralize(word) for word in profane_words])
profane_words = list(set(profane_words))
# We sort the list based on decreasing word length so that words like
# 'fu' aren't substituted before 'fuck' if no_word_boundaries = true
profane_words.sort(key=len)
profane_words.reverse()
return profane_words | def get_profane_words(self) | Returns all profane words currently in use. | 4.053548 | 4.007121 | 1.011586 |
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b'
regex_string = regex_string.format(word)
regex = re.compile(regex_string, re.IGNORECASE)
res = regex.sub(self._censor_char * len(word), res)
return res | def censor(self, input_text) | Returns input_text with any profane words censored. | 3.321332 | 3.080147 | 1.078303 |
chunks = []
while data:
info = SMB2NetworkInterfaceInfo()
data = info.unpack(data)
chunks.append(info)
return chunks | def unpack_multiple(data) | Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages | 7.675019 | 3.963559 | 1.936396 |
return {
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
SMB2CreateDurableHandleResponse(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
SMB2CreateDurableHandleReconnect(),
CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST:
SMB2CreateQueryMaximalAccessResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE:
SMB2CreateResponseLease(),
CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID:
SMB2CreateQueryOnDiskIDResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2:
SMB2CreateResponseLeaseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2:
SMB2CreateDurableHandleResponseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2:
SMB2CreateDurableHandleReconnectV2,
CreateContextName.SMB2_CREATE_APP_INSTANCE_ID:
SMB2CreateAppInstanceId(),
CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION:
SMB2CreateAppInstanceVersion()
}.get(name, None) | def get_response_structure(name) | Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown | 2.298054 | 2.194152 | 1.047354 |
buffer_name = self['buffer_name'].get_value()
structure = CreateContextName.get_response_structure(buffer_name)
if structure:
structure.unpack(self['buffer_data'].get_value())
return structure
else:
# unknown structure, just return the raw bytes
return self['buffer_data'].get_value() | def get_context_data(self) | Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name | 6.357072 | 4.186457 | 1.518485 |
data = b""
msg_count = len(messages)
for i, msg in enumerate(messages):
if i == msg_count - 1:
msg['next_entry_offset'] = 0
else:
# because the end padding val won't be populated if the entry
# offset is 0, we set to 1 so the len calc is correct
msg['next_entry_offset'] = 1
msg['next_entry_offset'] = len(msg)
data += msg.pack()
return data | def pack_multiple(messages) | Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2CreateEABuffer structures
:return: bytes object that is set on the SMB2CreateContextRequest
buffer_data field. | 5.00319 | 4.691438 | 1.066451 |
print_bytes = print_name.encode('utf-16-le')
sub_bytes = substitute_name.encode('utf-16-le')
path_buffer = print_bytes + sub_bytes
self['print_name_offset'].set_value(0)
self['print_name_length'].set_value(len(print_bytes))
self['substitute_name_offset'].set_value(len(print_bytes))
self['substitute_name_length'].set_value(len(sub_bytes))
self['path_buffer'].set_value(path_buffer) | def set_name(self, print_name, substitute_name) | Set's the path_buffer and print/substitute name length of the message
with the values passed in. These values should be a string and not a
byte string as it is encoded in this function.
:param print_name: The print name string to set
:param substitute_name: The substitute name string to set | 2.066052 | 1.967339 | 1.050176 |
log.info("Session: %s - Creating connection to share %s"
% (self.session.username, self.share_name))
utf_share_name = self.share_name.encode('utf-16-le')
connect = SMB2TreeConnectRequest()
connect['buffer'] = utf_share_name
log.info("Session: %s - Sending Tree Connect message"
% self.session.username)
log.debug(str(connect))
request = self.session.connection.send(connect,
sid=self.session.session_id)
log.info("Session: %s - Receiving Tree Connect response"
% self.session.username)
response = self.session.connection.receive(request)
tree_response = SMB2TreeConnectResponse()
tree_response.unpack(response['data'].get_value())
log.debug(str(tree_response))
# https://msdn.microsoft.com/en-us/library/cc246687.aspx
self.tree_connect_id = response['tree_id'].get_value()
log.info("Session: %s - Created tree connection with ID %d"
% (self.session.username, self.tree_connect_id))
self._connected = True
self.session.tree_connect_table[self.tree_connect_id] = self
capabilities = tree_response['capabilities']
self.is_dfs_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_DFS)
self.is_ca_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
dialect = self.session.connection.dialect
if dialect >= Dialects.SMB_3_0_0 and \
self.session.connection.supports_encryption:
self.encrypt_data = tree_response['share_flags'].has_flag(
ShareFlags.SMB2_SHAREFLAG_ENCRYPT_DATA)
self.is_scaleout_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_SCALEOUT)
# secure negotiate is only valid for SMB 3 dialects before 3.1.1
if dialect < Dialects.SMB_3_1_1 and require_secure_negotiate:
self._verify_dialect_negotiate() | def connect(self, require_secure_negotiate=True) | Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks | 2.796909 | 2.724298 | 1.026653 |
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
log.info("Session: %s, Tree: %s - Sending Tree Disconnect message"
% (self.session.username, self.share_name))
log.debug(str(req))
request = self.session.connection.send(req,
sid=self.session.session_id,
tid=self.tree_connect_id)
log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response"
% (self.session.username, self.share_name))
res = self.session.connection.receive(request)
res_disconnect = SMB2TreeDisconnect()
res_disconnect.unpack(res['data'].get_value())
log.debug(str(res_disconnect))
self._connected = False
del self.session.tree_connect_table[self.tree_connect_id] | def disconnect(self) | Disconnects the tree connection. | 2.852148 | 2.639244 | 1.080668 |
log.info("Setting up transport connection")
self.transport.connect()
log.info("Starting negotiation with SMB server")
smb_response = self._send_smb2_negotiate(dialect, timeout)
log.info("Negotiated dialect: %s"
% str(smb_response['dialect_revision']))
self.dialect = smb_response['dialect_revision'].get_value()
self.max_transact_size = smb_response['max_transact_size'].get_value()
self.max_read_size = smb_response['max_read_size'].get_value()
self.max_write_size = smb_response['max_write_size'].get_value()
self.server_guid = smb_response['server_guid'].get_value()
self.gss_negotiate_token = smb_response['buffer'].get_value()
if not self.require_signing and \
smb_response['security_mode'].has_flag(
SecurityMode.SMB2_NEGOTIATE_SIGNING_REQUIRED):
self.require_signing = True
log.info("Connection require signing: %s" % self.require_signing)
capabilities = smb_response['capabilities']
# SMB 2.1
if self.dialect >= Dialects.SMB_2_1_0:
self.supports_file_leasing = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LEASING)
self.supports_multi_credit = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LARGE_MTU)
# SMB 3.x
if self.dialect >= Dialects.SMB_3_0_0:
self.supports_directory_leasing = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
self.supports_multi_channel = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_MULTI_CHANNEL)
# TODO: SMB2_GLOBAL_CAP_PERSISTENT_HANDLES
self.supports_persistent_handles = False
self.supports_encryption = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_ENCRYPTION) \
and self.dialect < Dialects.SMB_3_1_1
self.server_capabilities = capabilities
self.server_security_mode = \
smb_response['security_mode'].get_value()
# TODO: Check/add server to server_list in Client Page 203
# SMB 3.1
if self.dialect >= Dialects.SMB_3_1_1:
for context in smb_response['negotiate_context_list']:
if context['context_type'].get_value() == \
NegotiateContextType.SMB2_ENCRYPTION_CAPABILITIES:
cipher_id = context['data']['ciphers'][0]
self.cipher_id = Ciphers.get_cipher(cipher_id)
self.supports_encryption = self.cipher_id != 0
else:
hash_id = context['data']['hash_algorithms'][0]
self.preauth_integrity_hash_id = \
HashAlgorithms.get_algorithm(hash_id) | def connect(self, dialect=None, timeout=60) | Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that denote the capabilities of the
server.
:param dialect: If specified, forces the dialect that is negotiated
with the server, if not set, then the newest dialect supported by
the server is used up to SMB 3.1.1
:param timeout: The timeout in seconds to wait for the initial
negotiation process to complete | 2.633231 | 2.598356 | 1.013422 |
if close:
for session in list(self.session_table.values()):
session.disconnect(True)
log.info("Disconnecting transport connection")
self.transport.disconnect() | def disconnect(self, close=True) | Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections of each session. | 6.139377 | 7.479328 | 0.820846 |
header = self._generate_packet_header(message, sid, tid,
credit_request)
# get the actual Session and TreeConnect object instead of the IDs
session = self.session_table.get(sid, None) if sid else None
tree = None
if tid and session:
if tid not in session.tree_connect_table.keys():
error_msg = "Cannot find Tree with the ID %d in the session " \
"tree table" % tid
raise smbprotocol.exceptions.SMBException(error_msg)
tree = session.tree_connect_table[tid]
if session and session.signing_required and session.signing_key:
self._sign(header, session)
request = Request(header)
self.outstanding_requests[header['message_id'].get_value()] = request
send_data = header.pack()
if (session and session.encrypt_data) or (tree and tree.encrypt_data):
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return request | def send(self, message, sid=None, tid=None, credit_request=None) | Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent for
:param credit_request: Specifies extra credits to be requested with the
SMB header
:return: Request of the message that was sent | 4.199358 | 3.974149 | 1.056668 |
send_data = b""
session = self.session_table[sid]
tree = session.tree_connect_table[tid]
requests = []
total_requests = len(messages)
for i, message in enumerate(messages):
if i == total_requests - 1:
next_command = 0
padding = b""
else:
msg_length = 64 + len(message)
# each compound message must start at the 8-byte boundary
mod = msg_length % 8
padding_length = 8 - mod if mod > 0 else 0
padding = b"\x00" * padding_length
next_command = msg_length + padding_length
header = self._generate_packet_header(message, sid, tid, None)
header['next_command'] = next_command
if i != 0 and related:
header['session_id'] = b"\xff" * 8
header['tree_id'] = b"\xff" * 4
header['flags'].set_flag(
Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS
)
if session.signing_required and session.signing_key:
self._sign(header, session, padding=padding)
send_data += header.pack() + padding
request = Request(header)
requests.append(request)
self.outstanding_requests[header['message_id'].get_value()] = \
request
if session.encrypt_data or tree.encrypt_data:
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return requests | def send_compound(self, messages, sid, tid, related=False) | Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the message is sent for
:return: List<Request> for each request that was sent, each entry in
the list is in the same order of the message list that was passed
in | 3.799263 | 3.696969 | 1.02767 |
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
status != NtStatus.STATUS_PENDING):
break
current_time = time.time() - start_time
if timeout and (current_time > timeout):
error_msg = "Connection timeout of %d seconds exceeded while" \
" waiting for a response from the server" \
% timeout
raise smbprotocol.exceptions.SMBException(error_msg)
response = request.response
status = response['status'].get_value()
if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]:
raise smbprotocol.exceptions.SMBResponseException(response, status)
# now we have a retrieval request for the response, we can delete
# the request from the outstanding requests
message_id = request.message['message_id'].get_value()
del self.outstanding_requests[message_id]
return response | def receive(self, request, wait=True, timeout=None) | Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message | 3.744974 | 3.405751 | 1.099603 |
log.info("Sending Echo request with a timeout of %d and credit "
"request of %d" % (timeout, credit_request))
echo_msg = SMB2Echo()
log.debug(str(echo_msg))
req = self.send(echo_msg, sid=sid, credit_request=credit_request)
log.info("Receiving Echo response")
response = self.receive(req, timeout=timeout)
log.info("Credits granted from the server echo response: %d"
% response['credit_response'].get_value())
echo_resp = SMB2Echo()
echo_resp.unpack(response['data'].get_value())
log.debug(str(echo_resp))
return response['credit_response'].get_value() | def echo(self, sid=0, timeout=60, credit_request=1) | Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket will close.
:param sid: When talking to a Windows host this must be populated with
a valid session_id from a negotiated session
:param timeout: The timeout in seconds to wait for the Echo Response
:param credit_request: The number of credits to request
:return: the credits that were granted by the server | 3.371056 | 3.09437 | 1.089416 |
while True:
message_bytes = self.transport.receive()
# there were no messages receives, so break from the loop
if message_bytes is None:
break
# check if the message is encrypted and decrypt if necessary
if message_bytes[:4] == b"\xfdSMB":
message = SMB2TransformHeader()
message.unpack(message_bytes)
message_bytes = self._decrypt(message)
# now retrieve message(s) from response
is_last = False
session_id = None
while not is_last:
next_command = struct.unpack("<L", message_bytes[20:24])[0]
header_length = \
next_command if next_command != 0 else len(message_bytes)
header_bytes = message_bytes[:header_length]
message = SMB2HeaderResponse()
message.unpack(header_bytes)
flags = message['flags']
if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS):
session_id = message['session_id'].get_value()
self._verify(message, session_id)
message_id = message['message_id'].get_value()
request = self.outstanding_requests.get(message_id, None)
if not request:
error_msg = "Received response with an unknown message " \
"ID: %d" % message_id
raise smbprotocol.exceptions.SMBException(error_msg)
# add the upper credit limit based on the credits granted by
# the server
credit_response = message['credit_response'].get_value()
self.sequence_window['high'] += \
credit_response if credit_response > 0 else 1
request.response = message
self.outstanding_requests[message_id] = request
message_bytes = message_bytes[header_length:]
is_last = next_command == 0 | def _flush_message_buffer(self) | Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests | 3.669548 | 3.535239 | 1.037992 |
credit_size = 65536
if not self.supports_multi_credit:
credit_charge = 0
elif message.COMMAND == Commands.SMB2_READ:
max_size = message['length'].get_value() + \
message['read_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_WRITE:
max_size = message['length'].get_value() + \
message['write_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_IOCTL:
max_in_size = len(message['buffer'])
max_out_size = message['max_output_response'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY:
max_in_size = len(message['buffer'])
max_out_size = message['output_buffer_length'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
else:
credit_charge = 1
# python 2 returns a float where we need an integer
return int(credit_charge) | def _calculate_credit_charge(self, message) | Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing messages only
the Read, Write, Query Directory or IOCTL commands will end in this
scenario and each require their own calculation to get the proper
value. The generic formula for calculating the credit charge is
https://msdn.microsoft.com/en-us/library/dn529312.aspx
(max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1
:param message: The message being sent
:return: The credit charge to set on the header | 2.305194 | 2.028613 | 1.13634 |
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.values()):
open.close(False)
for tree in list(self.tree_connect_table.values()):
tree.disconnect()
log.info("Session: %s - Logging off of SMB Session" % self.username)
logoff = SMB2Logoff()
log.info("Session: %s - Sending Logoff message" % self.username)
log.debug(str(logoff))
request = self.connection.send(logoff, sid=self.session_id)
log.info("Session: %s - Receiving Logoff response" % self.username)
res = self.connection.receive(request)
res_logoff = SMB2Logoff()
res_logoff.unpack(res['data'].get_value())
log.debug(str(res_logoff))
self._connected = False
del self.connection.session_table[self.session_id] | def disconnect(self, close=True) | Logs off the session
:param close: Will close all tree connects in a session | 3.49579 | 3.224981 | 1.083972 |
kdf = KBKDFHMAC(
algorithm=hashes.SHA256(),
mode=Mode.CounterMode,
length=16,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=label,
context=context,
fixed=None,
backend=default_backend()
)
return kdf.derive(ki) | def _smb3kdf(self, ki, label, context) | See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to the KDF
:param label: The purpose of this derived key as bytes string
:param context: The context information of this derived key as bytes
string
:return: Key derived by the KDF as specified by [SP800-108] 5.1 | 3.688459 | 4.095804 | 0.900546 |
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
raise ValueError("Invalid packed data length for field %s of %d "
"does not fit field size of %d"
% (self.name, len(packed_value), size))
return packed_value | def pack(self) | Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value | 3.786149 | 3.856693 | 0.981709 |
parsed_value = self._parse_value(value)
self.value = parsed_value | def set_value(self, value) | Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used | 4.971091 | 5.603873 | 0.887081 |
size = self._get_calculated_size(self.size, data)
self.set_value(data[0:size])
return data[len(self):] | def unpack(self, data) | Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields | 6.831242 | 6.502886 | 1.050494 |
if isinstance(value, types.LambdaType):
expanded_value = value(self.structure)
return self._get_calculated_value(expanded_value)
else:
# perform one final parsing of the value in case lambda value
# returned a different type
return self._parse_value(value) | def _get_calculated_value(self, value) | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value | 6.643018 | 6.488593 | 1.0238 |
# if the size is derived from a lambda function, run it now; otherwise
# return the value we passed in or the length of the data if the size
# is None (last field value)
if size is None:
return len(data)
elif isinstance(size, types.LambdaType):
expanded_size = size(self.structure)
return self._get_calculated_size(expanded_size, data)
else:
return size | def _get_calculated_size(self, size, data) | Get's the final size of the field and runs the lambda functions
recursively until a final size is derived. If size is None then it
will just return the length of the data as it is assumed it is the
final field (None should only be set on size for the final field).
:param size: The size to calculate/expand
:param data: The data that the size is being calculated for
:return: The final size | 5.433995 | 4.602952 | 1.180546 |
if isinstance(size, types.LambdaType):
size = size(self.structure)
struct_format = {
1: 'B',
2: 'H',
4: 'L',
8: 'Q'
}
if size not in struct_format.keys():
raise InvalidFieldDefinition("Cannot struct format of size %s"
% size)
return struct_format[size] | def _get_struct_format(self, size) | Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified | 3.663051 | 3.959809 | 0.925057 |
structs = smbprotocol.query_info
resp_structure = {
FileInformationClass.FILE_DIRECTORY_INFORMATION:
structs.FileDirectoryInformation,
FileInformationClass.FILE_NAMES_INFORMATION:
structs.FileNamesInformation,
FileInformationClass.FILE_BOTH_DIRECTORY_INFORMATION:
structs.FileBothDirectoryInformation,
FileInformationClass.FILE_ID_BOTH_DIRECTORY_INFORMATION:
structs.FileIdBothDirectoryInformation,
FileInformationClass.FILE_FULL_DIRECTORY_INFORMATION:
structs.FileFullDirectoryInformation,
FileInformationClass.FILE_ID_FULL_DIRECTORY_INFORMATION:
structs.FileIdFullDirectoryInformation,
}[file_information_class]
query_results = []
current_offset = 0
is_next = True
while is_next:
result = resp_structure()
result.unpack(buffer[current_offset:])
query_results.append(result)
current_offset += result['next_entry_offset'].get_value()
is_next = result['next_entry_offset'].get_value() != 0
return query_results | def unpack_response(file_information_class, buffer) | Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
:return: List of query_info.* structures based on the
FileInformationClass used in the initial query request. | 2.392245 | 2.157133 | 1.108993 |
create = SMB2CreateRequest()
create['impersonation_level'] = impersonation_level
create['desired_access'] = desired_access
create['file_attributes'] = file_attributes
create['share_access'] = share_access
create['create_disposition'] = create_disposition
create['create_options'] = create_options
if self.file_name == "":
create['buffer_path'] = b"\x00\x00"
else:
create['buffer_path'] = self.file_name.encode('utf-16-le')
if create_contexts:
create['buffer_contexts'] = smbprotocol.create_contexts.\
SMB2CreateContextRequest.pack_multiple(create_contexts)
if self.connection.dialect >= Dialects.SMB_3_0_0:
self.desired_access = desired_access
self.share_mode = share_access
self.create_options = create_options
self.file_attributes = file_attributes
self.create_disposition = create_disposition
if not send:
return create, self._create_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Create Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(create))
request = self.connection.send(create,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._create_response(request) | def create(self, impersonation_level, desired_access, file_attributes,
share_access, create_disposition, create_options,
create_contexts=None, send=True) | This will open the file based on the input parameters supplied. Any
file open should also be called with Open.close() when it is finished.
More details on how each option affects the open process can be found
here https://msdn.microsoft.com/en-us/library/cc246502.aspx.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CreateRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param impersonation_level: (ImpersonationLevel) The type of
impersonation level that is issuing the create request.
:param desired_access: The level of access that is required of the
open. FilePipePrinterAccessMask or DirectoryAccessMask should be
used depending on the type of file being opened.
:param file_attributes: (FileAttributes) attributes to set on the file
being opened, this usually is for opens that creates a file.
:param share_access: (ShareAccess) Specifies the sharing mode for the
open.
:param create_disposition: (CreateDisposition) Defines the action the
server MUST take if the file already exists.
:param create_options: (CreateOptions) Specifies the options to be
applied when creating or opening the file.
:param create_contexts: (List<SMB2CreateContextRequest>) List of
context request values to be applied to the create.
Create Contexts are used to encode additional flags and attributes when
opening files. More details on create context request values can be
found here https://msdn.microsoft.com/en-us/library/cc246504.aspx.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: List of context response values or None if there are no
context response values. If the context response value is not known
to smbprotocol then the list value would be raw bytes otherwise
it is a Structure defined in create_contexts.py | 2.469712 | 2.446656 | 1.009423 |
if length > self.connection.max_read_size:
raise SMBException("The requested read length %d is greater than "
"the maximum negotiated read size %d"
% (length, self.connection.max_read_size))
read = SMB2ReadRequest()
read['length'] = length
read['offset'] = offset
read['minimum_count'] = min_length
read['file_id'] = self.file_id
read['padding'] = b"\x50"
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_READFLAG_READ_UNBUFFERED",
True)
read['flags'].set_flag(ReadFlags.SMB2_READFLAG_READ_UNBUFFERED)
if not send:
return read, self._read_response
log.info("Session: %s, Tree Connect ID: %s - sending SMB2 Read "
"Request for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(read))
request = self.connection.send(read,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._read_response(request, wait) | def read(self, offset, length, min_length=0, unbuffered=False, wait=True,
send=True) | Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param offset: The offset to start the read of the file.
:param length: The number of bytes to read from the offset.
:param min_length: The minimum number of bytes to be read for a
successful operation.
:param unbuffered: Whether to the server should cache the read data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: A byte string of the bytes read | 3.181997 | 3.057421 | 1.040745 |
data_len = len(data)
if data_len > self.connection.max_write_size:
raise SMBException("The requested write length %d is greater than "
"the maximum negotiated write size %d"
% (data_len, self.connection.max_write_size))
write = SMB2WriteRequest()
write['length'] = len(data)
write['offset'] = offset
write['file_id'] = self.file_id
write['buffer'] = data
if write_through:
if self.connection.dialect < Dialects.SMB_2_1_0:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_2_1_0,
"SMB2_WRITEFLAG_WRITE_THROUGH",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_THROUGH)
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_WRITEFLAG_WRITE_UNBUFFERED",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_UNBUFFERED)
if not send:
return write, self._write_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Write Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(write))
request = self.connection.send(write,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._write_response(request, wait) | def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True) | Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param data: The bytes data to write.
:param offset: The offset in the file to write the bytes at
:param write_through: Whether written data is persisted to the
underlying storage, not valid for SMB 2.0.2.
:param unbuffered: Whether to the server should cache the write data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The number of bytes written | 2.423855 | 2.331074 | 1.039802 |
flush = SMB2FlushRequest()
flush['file_id'] = self.file_id
if not send:
return flush, self._flush_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Flush Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(flush))
request = self.connection.send(flush,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._flush_response(request) | def flush(self, send=True) | A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The SMB2FlushResponse received from the server | 3.737654 | 3.584403 | 1.042755 |
query = SMB2QueryDirectoryRequest()
query['file_information_class'] = file_information_class
query['flags'] = flags
query['file_index'] = file_index
query['file_id'] = self.file_id
query['output_buffer_length'] = max_output
query['buffer'] = pattern.encode('utf-16-le')
if not send:
return query, self._query_directory_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Query "
"Directory Request for directory %s"
% (self.tree_connect.session.username,
self.tree_connect.share_name, self.file_name))
log.debug(str(query))
request = self.connection.send(query,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._query_directory_response(request) | def query_directory(self, pattern, file_information_class, flags=None,
file_index=0, max_output=65536, send=True) | Run a Query/Find on an opened directory based on the params passed in.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2QueryDirectoryRequest, receive_func) instead
of sending the the request and waiting for the response. The
receive_func can be used to get the response from the server by passing
in the Request that was used to sent it out of band.
:param pattern: The string pattern to use for the query, this pattern
format is based on the SMB server but * is usually a wildcard
:param file_information_class: FileInformationClass that defines the
format of the result that is returned
:param flags: QueryDirectoryFlags that control how the operation must
be processed.
:param file_index: If the flags SMB2_INDEX_SPECIFIED, this is the index
the query should resume on, otherwise should be 0
:param max_output: The maximum output size, defaulted to the max credit
size but can be increased to reduced round trip operations.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: A list of structures defined in query_info.py, the list entry
structure is based on the value of file_information_class in the
request message | 2.674908 | 2.770301 | 0.965566 |
# it is already closed and this isn't for an out of band request
if not self._connected and send:
return
close = SMB2CloseRequest()
close['file_id'] = self.file_id
if get_attributes:
close['flags'] = CloseFlags.SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB
if not send:
return close, self._close_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Close Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(close))
request = self.connection.send(close,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._close_response(request) | def close(self, get_attributes=False, send=True) | Closes an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CloseRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param get_attributes: (Bool) whether to get the latest attributes on
the close and set them on the Open object
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: SMB2CloseResponse message received from the server | 4.778839 | 4.372494 | 1.092932 |
if not sid_string.startswith("S-"):
raise ValueError("A SID string must start with S-")
sid_entries = sid_string.split("-")
if len(sid_entries) < 3:
raise ValueError("A SID string must start with S and contain a "
"revision and identifier authority, e.g. S-1-0")
revision = int(sid_entries[1])
id_authority = int(sid_entries[2])
sub_authorities = [int(i) for i in sid_entries[3:]]
self['revision'].set_value(revision)
self['identifier_authority'].set_value(id_authority)
self['sub_authorities'] = sub_authorities | def from_string(self, sid_string) | Used to set the structure parameters based on the input string
:param sid_string: String of the sid in S-x-x-x-x form | 2.948179 | 3.139393 | 0.939092 |
if not self.status["done"]:
r = Request("get", self.url + ".json", {"token": self.payload["token"]})
for param, when in MessageRequest.params.iteritems():
self.status[param] = bool(r.answer[param])
self.status[when] = int(r.answer[when])
for param in ["acknowledged_by", "acknowledged_by_device"]:
self.status[param] = r.answer[param]
self.status["last_delivered_at"] = int(r.answer["last_delivered_at"])
if any(self.status[param] for param in MessageRequest.params):
self.status["done"] = True
return self.status["done"] | def poll(self) | If the message request has a priority of 2, Pushover keeps sending
the same notification until the client acknowledges it. Calling the
:func:`poll` function fetches the status of the :class:`MessageRequest`
object until the notifications either expires, is acknowledged by the
client, or the callback url is reached. The status is available in the
``status`` dictionary.
Returns ``True`` when the request has expired or been acknowledged and
``False`` otherwise so that a typical handling of a priority-2
notification can look like this::
request = p.message("Urgent!", priority=2, expire=120, retry=60)
while not request.poll():
# do something
time.sleep(5)
print request.status | 4.230202 | 4.033097 | 1.048872 |
if not Pushover._SOUNDS:
request = Request("get", SOUND_URL, {"token": self.token})
Pushover._SOUNDS = request.answer["sounds"]
return Pushover._SOUNDS | def sounds(self) | Return a dictionary of sounds recognized by Pushover and that can be
used in a notification message. | 8.380565 | 6.20283 | 1.351087 |
payload = {"user": user, "token": self.token}
if device:
payload["device"] = device
try:
request = Request("post", USER_URL, payload)
except RequestError:
return None
else:
return request.answer["devices"] | def verify(self, user, device=None) | Verify that the `user` and optional `device` exist. Returns
`None` when the user/device does not exist or a list of the user's
devices otherwise. | 5.426257 | 4.670197 | 1.16189 |
payload = {"message": message, "user": user, "token": self.token}
for key, value in kwargs.iteritems():
if key not in Pushover.message_keywords:
raise ValueError("{0}: invalid message parameter".format(key))
elif key == "timestamp" and value is True:
payload[key] = int(time.time())
elif key == "sound" and value not in self.sounds:
raise ValueError("{0}: invalid sound".format(value))
else:
payload[key] = value
return MessageRequest(payload) | def message(self, user, message, **kwargs) | Send `message` to the user specified by `user`. It is possible
to specify additional properties of the message by passing keyword
arguments. The list of valid keywords is ``title, priority, sound,
callback, timestamp, url, url_title, device, retry, expire and html``
which are described in the Pushover API documentation.
For convenience, you can simply set ``timestamp=True`` to set the
timestamp to the current timestamp.
An image can be attached to a message by passing a file-like object
to the `attachment` keyword argument.
This method returns a :class:`MessageRequest` object. | 3.469647 | 2.609223 | 1.329762 |
payload = {"user": user, "token": self.token}
for key, value in kwargs.iteritems():
if key not in Pushover.glance_keywords:
raise ValueError("{0}: invalid glance parameter".format(key))
else:
payload[key] = value
return Request("post", GLANCE_URL, payload) | def glance(self, user, **kwargs) | Send a glance to the user. The default property is ``text``, as this
is used on most glances, however a valid glance does not need to
require text and can be constructed using any combination of valid
keyword properties. The list of valid keywords is ``title, text,
subtext, count, percent and device`` which are described in the
Pushover Glance API documentation.
This method returns a :class:`GlanceRequest` object. | 4.961055 | 3.644927 | 1.361085 |
# Ensure inputs are numpy arrays
w = np.array(w)
v = np.array(v)
# Check dimensions
if(len(w.shape) != 2):
raise TypeError('Estimated coefficients must be in NxM matrix')
if(len(v.shape) != 1):
raise TypeError('Real coefficients must be in 1d array')
# Ensure equal length between estimated and real coeffs
N, M = w.shape
L = v.size
if(M < L):
v = v[:-(L-M)]
elif(M > L):
v = np.concatenate((v, np.zeros(M-L)))
# Calculate and return MSWE
mswe = np.mean((w - v)**2, axis=1)
return mswe | def mswe(w, v) | Calculate mean squared weight error between estimated and true filter
coefficients, in respect to iterations.
Parameters
----------
v : array-like
True coefficients used to generate desired signal, must be a
one-dimensional array.
w : array-like
Estimated coefficients from adaptive filtering algorithm. Must be an
N x M matrix where N is the number of iterations, and M is the number
of filter coefficients.
Returns
-------
mswe : numpy.array
One-dimensional array containing the mean-squared weight error for
every iteration.
Raises
------
TypeError
If inputs have wrong dimensions
Note
----
To use this function with the adaptive filter functions set the optional
parameter returnCoeffs to True. This will return a coefficient matrix w
corresponding with the input-parameter w. | 3.145776 | 2.807203 | 1.120609 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT]
try:
dest_file_handler = open(dest_file, "w")
except IOError:
print("IOError: Failed to create a log file")
# We have to check if device is available or not before executing this command
# as adb bugreport will wait-for-device infinitely and does not come out of
# loop
# Execute only if device is available only
if _isDeviceAvailable():
result = _exec_command_to_file(adb_full_cmd, dest_file_handler)
return (result, "Success: Bug report saved to: " + dest_file)
else:
return (0, "Device Not Found") | def bugreport(dest_file="default.log") | Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting
:return: result of _exec_command() execution | 6.422838 | 6.267801 | 1.024735 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest]
return _exec_command(adb_full_cmd) | def push(src, dest) | Push object from host to target
:param src: string path to source object on host
:param dest: string destination path on target
:return: result of _exec_command() execution | 5.991015 | 5.548427 | 1.079768 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PULL, src, dest]
return _exec_command(adb_full_cmd) | def pull(src, dest) | Pull object from target to host
:param src: string path of object on target
:param dest: string destination path on host
:return: result of _exec_command() execution | 6.087822 | 5.493781 | 1.10813 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_DEVICES, _convert_opts(opts)]
return _exec_command(adb_full_cmd) | def devices(opts=[]) | Get list of all available devices including emulators
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 6.638703 | 6.566708 | 1.010964 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL, cmd]
return _exec_command(adb_full_cmd) | def shell(cmd) | Execute shell command on target
:param cmd: string shell command to execute
:return: result of _exec_command() execution | 6.16681 | 5.747232 | 1.073005 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_INSTALL, _convert_opts(opts), apk]
return _exec_command(adb_full_cmd) | def install(apk, opts=[]) | Install *.apk on target
:param apk: string path to apk on host to install
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 6.200609 | 5.610373 | 1.105205 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_UNINSTALL, _convert_opts(opts), app]
return _exec_command(adb_full_cmd) | def uninstall(app, opts=[]) | Uninstall app from target
:param app: app name to uninstall from target (e.g. "com.example.android.valid")
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 7.016722 | 5.995275 | 1.170375 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL ,v.ADB_COMMAND_SYNC]
return _exec_command(adb_full_cmd) | def sync() | Copy host->device only if changed
:return: result of _exec_command() execution | 6.946085 | 5.91874 | 1.173575 |
t = tempfile.TemporaryFile()
final_adb_cmd = []
for e in adb_cmd:
if e != '': # avoid items with empty string...
final_adb_cmd.append(e) # ... so that final command doesn't
# contain extra spaces
print('\n*** Executing ' + ' '.join(adb_cmd) + ' ' + 'command')
try:
output = check_output(final_adb_cmd, stderr=t)
except CalledProcessError as e:
t.seek(0)
result = e.returncode, t.read()
else:
result = 0, output
print('\n' + result[1])
return result | def _exec_command(adb_cmd) | Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code | 4.371 | 4.29271 | 1.018238 |
t = tempfile.TemporaryFile()
final_adb_cmd = []
for e in adb_cmd:
if e != '': # avoid items with empty string...
final_adb_cmd.append(e) # ... so that final command doesn't
# contain extra spaces
print('\n*** Executing ' + ' '.join(adb_cmd) + ' ' + 'command')
try:
output = call(final_adb_cmd, stdout=dest_file_handler, stderr=t)
except CalledProcessError as e:
t.seek(0)
result = e.returncode, t.read()
else:
result = output
dest_file_handler.close()
return result | def _exec_command_to_file(adb_cmd, dest_file_handler) | Format adb command and execute it in shell and redirects to a file
:param adb_cmd: list adb command to execute
:param dest_file_handler: file handler to which output will be redirected
:return: string '0' and writes shell command output to file if successful, otherwise
raise CalledProcessError exception and return error code | 4.429555 | 4.234411 | 1.046085 |
"Detects if the data was changed. This is added in 1.6."
if initial is None and data is None:
return False
if data and not hasattr(data, '__iter__'):
data = self.widget.decompress(data)
initial = self.to_python(initial)
data = self.to_python(data)
if hasattr(self, '_coerce'):
data = self._coerce(data)
if isinstance(data, Model) and isinstance(initial, Model):
return model_vars(data) != model_vars(initial)
else:
return data != initial | def has_changed(self, initial, data) | Detects if the data was changed. This is added in 1.6. | 3.881357 | 3.019745 | 1.285326 |
# Wrap function to maintian the original doc string, etc
@wraps(func)
def decorator(lookup_cls):
# Construct a class decorator from the original function
original = lookup_cls.results
def inner(self, request):
# Wrap lookup_cls.results by first calling func and checking the result
result = func(request)
if isinstance(result, HttpResponse):
return result
return original(self, request)
# Replace original lookup_cls.results with wrapped version
lookup_cls.results = inner
return lookup_cls
# Return the constructed decorator
return decorator | def results_decorator(func) | Helper for constructing simple decorators around Lookup.results.
func is a function which takes a request as the first parameter. If func
returns an HttpReponse it is returned otherwise the original Lookup.results
is returned. | 6.023503 | 5.072611 | 1.187456 |
"Lookup decorator to require the user to be authenticated."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) | def login_required(request) | Lookup decorator to require the user to be authenticated. | 4.252019 | 2.777143 | 1.531077 |
"Lookup decorator to require the user is a staff member."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) # Unauthorized
elif not user.is_staff:
return HttpResponseForbidden() | def staff_member_required(request) | Lookup decorator to require the user is a staff member. | 3.867361 | 2.835388 | 1.363962 |
"Construct result dictionary for the match item."
result = {
'id': self.get_item_id(item),
'value': self.get_item_value(item),
'label': self.get_item_label(item),
}
for key in settings.SELECTABLE_ESCAPED_KEYS:
if key in result:
result[key] = conditional_escape(result[key])
return result | def format_item(self, item) | Construct result dictionary for the match item. | 4.420635 | 3.287766 | 1.344571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.