func_name
stringlengths 2
53
| func_src_before
stringlengths 63
114k
| func_src_after
stringlengths 86
114k
| line_changes
dict | char_changes
dict | commit_link
stringlengths 66
117
| file_name
stringlengths 5
72
| vul_type
stringclasses 9
values |
---|---|---|---|---|---|---|---|
_find_host_exhaustive | def _find_host_exhaustive(self, connector, hosts):
for host in hosts:
ssh_cmd = 'svcinfo lshost -delim ! %s' % host
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return(len(out.strip()),
'_find_host_exhaustive',
ssh_cmd, out, err)
for attr_line in out.split('\n'):
# If '!' not found, return the string and two empty strings
attr_name, foo, attr_val = attr_line.partition('!')
if (attr_name == 'iscsi_name' and
'initiator' in connector and
attr_val == connector['initiator']):
return host
elif (attr_name == 'WWPN' and
'wwpns' in connector and
attr_val.lower() in
map(str.lower, map(str, connector['wwpns']))):
return host
return None | def _find_host_exhaustive(self, connector, hosts):
for host in hosts:
ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return(len(out.strip()),
'_find_host_exhaustive',
ssh_cmd, out, err)
for attr_line in out.split('\n'):
# If '!' not found, return the string and two empty strings
attr_name, foo, attr_val = attr_line.partition('!')
if (attr_name == 'iscsi_name' and
'initiator' in connector and
attr_val == connector['initiator']):
return host
elif (attr_name == 'WWPN' and
'wwpns' in connector and
attr_val.lower() in
map(str.lower, map(str, connector['wwpns']))):
return host
return None | {
"deleted": [
{
"line_no": 3,
"char_start": 82,
"char_end": 140,
"line": " ssh_cmd = 'svcinfo lshost -delim ! %s' % host\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 82,
"char_end": 147,
"line": " ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]\n"
}
]
} | {
"deleted": [
{
"char_start": 128,
"char_end": 131,
"chars": " %s"
},
{
"char_start": 132,
"char_end": 134,
"chars": " %"
}
],
"added": [
{
"char_start": 104,
"char_end": 105,
"chars": "["
},
{
"char_start": 113,
"char_end": 115,
"chars": "',"
},
{
"char_start": 116,
"char_end": 117,
"chars": "'"
},
{
"char_start": 123,
"char_end": 125,
"chars": "',"
},
{
"char_start": 126,
"char_end": 127,
"chars": "'"
},
{
"char_start": 133,
"char_end": 135,
"chars": "',"
},
{
"char_start": 136,
"char_end": 137,
"chars": "'"
},
{
"char_start": 139,
"char_end": 140,
"chars": ","
},
{
"char_start": 145,
"char_end": 146,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
_create_vdisk | def _create_vdisk(self, name, size, units, opts):
"""Create a new vdisk."""
LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)
model_update = None
autoex = '-autoexpand' if opts['autoexpand'] else ''
easytier = '-easytier on' if opts['easytier'] else '-easytier off'
# Set space-efficient options
if opts['rsize'] == -1:
ssh_cmd_se_opt = ''
else:
ssh_cmd_se_opt = (
'-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %
{'rsize': opts['rsize'],
'autoex': autoex,
'warn': opts['warning']})
if opts['compression']:
ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'
else:
ssh_cmd_se_opt = ssh_cmd_se_opt + (
' -grainsize %d' % opts['grainsize'])
ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '
'-iogrp 0 -size %(size)s -unit '
'%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'
% {'name': name,
'mdiskgrp': self.configuration.storwize_svc_volpool_name,
'size': size, 'unit': units, 'easytier': easytier,
'ssh_cmd_se_opt': ssh_cmd_se_opt})
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return(len(out.strip()), '_create_vdisk',
ssh_cmd, out, err)
# Ensure that the output is as expected
match_obj = re.search('Virtual Disk, id \[([0-9]+)\], '
'successfully created', out)
# Make sure we got a "successfully created" message with vdisk id
self._driver_assert(
match_obj is not None,
_('_create_vdisk %(name)s - did not find '
'success message in CLI output.\n '
'stdout: %(out)s\n stderr: %(err)s')
% {'name': name, 'out': str(out), 'err': str(err)})
LOG.debug(_('leave: _create_vdisk: volume %s ') % name) | def _create_vdisk(self, name, size, units, opts):
"""Create a new vdisk."""
LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)
model_update = None
easytier = 'on' if opts['easytier'] else 'off'
# Set space-efficient options
if opts['rsize'] == -1:
ssh_cmd_se_opt = []
else:
ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),
'-autoexpand', '-warning',
'%s%%' % str(opts['warning'])]
if not opts['autoexpand']:
ssh_cmd_se_opt.remove('-autoexpand')
if opts['compression']:
ssh_cmd_se_opt.append('-compressed')
else:
ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])
ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',
self.configuration.storwize_svc_volpool_name,
'-iogrp', '0', '-size', size, '-unit',
units, '-easytier', easytier] + ssh_cmd_se_opt
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return(len(out.strip()), '_create_vdisk',
ssh_cmd, out, err)
# Ensure that the output is as expected
match_obj = re.search('Virtual Disk, id \[([0-9]+)\], '
'successfully created', out)
# Make sure we got a "successfully created" message with vdisk id
self._driver_assert(
match_obj is not None,
_('_create_vdisk %(name)s - did not find '
'success message in CLI output.\n '
'stdout: %(out)s\n stderr: %(err)s')
% {'name': name, 'out': str(out), 'err': str(err)})
LOG.debug(_('leave: _create_vdisk: volume %s ') % name) | {
"deleted": [
{
"line_no": 7,
"char_start": 181,
"char_end": 242,
"line": " autoex = '-autoexpand' if opts['autoexpand'] else ''\n"
},
{
"line_no": 8,
"char_start": 242,
"char_end": 317,
"line": " easytier = '-easytier on' if opts['easytier'] else '-easytier off'\n"
},
{
"line_no": 12,
"char_start": 388,
"char_end": 420,
"line": " ssh_cmd_se_opt = ''\n"
},
{
"line_no": 14,
"char_start": 434,
"char_end": 465,
"line": " ssh_cmd_se_opt = (\n"
},
{
"line_no": 15,
"char_start": 465,
"char_end": 535,
"line": " '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %\n"
},
{
"line_no": 16,
"char_start": 535,
"char_end": 576,
"line": " {'rsize': opts['rsize'],\n"
},
{
"line_no": 17,
"char_start": 576,
"char_end": 611,
"line": " 'autoex': autoex,\n"
},
{
"line_no": 18,
"char_start": 611,
"char_end": 654,
"line": " 'warn': opts['warning']})\n"
},
{
"line_no": 20,
"char_start": 690,
"char_end": 755,
"line": " ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'\n"
},
{
"line_no": 22,
"char_start": 773,
"char_end": 825,
"line": " ssh_cmd_se_opt = ssh_cmd_se_opt + (\n"
},
{
"line_no": 23,
"char_start": 825,
"char_end": 883,
"line": " ' -grainsize %d' % opts['grainsize'])\n"
},
{
"line_no": 24,
"char_start": 883,
"char_end": 884,
"line": "\n"
},
{
"line_no": 25,
"char_start": 884,
"char_end": 960,
"line": " ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '\n"
},
{
"line_no": 26,
"char_start": 960,
"char_end": 1012,
"line": " '-iogrp 0 -size %(size)s -unit '\n"
},
{
"line_no": 27,
"char_start": 1012,
"char_end": 1074,
"line": " '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n"
},
{
"line_no": 28,
"char_start": 1074,
"char_end": 1110,
"line": " % {'name': name,\n"
},
{
"line_no": 29,
"char_start": 1110,
"char_end": 1187,
"line": " 'mdiskgrp': self.configuration.storwize_svc_volpool_name,\n"
},
{
"line_no": 30,
"char_start": 1187,
"char_end": 1257,
"line": " 'size': size, 'unit': units, 'easytier': easytier,\n"
},
{
"line_no": 31,
"char_start": 1257,
"char_end": 1311,
"line": " 'ssh_cmd_se_opt': ssh_cmd_se_opt})\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 181,
"char_end": 236,
"line": " easytier = 'on' if opts['easytier'] else 'off'\n"
},
{
"line_no": 11,
"char_start": 307,
"char_end": 339,
"line": " ssh_cmd_se_opt = []\n"
},
{
"line_no": 13,
"char_start": 353,
"char_end": 422,
"line": " ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),\n"
},
{
"line_no": 14,
"char_start": 422,
"char_end": 479,
"line": " '-autoexpand', '-warning',\n"
},
{
"line_no": 15,
"char_start": 479,
"char_end": 540,
"line": " '%s%%' % str(opts['warning'])]\n"
},
{
"line_no": 16,
"char_start": 540,
"char_end": 579,
"line": " if not opts['autoexpand']:\n"
},
{
"line_no": 17,
"char_start": 579,
"char_end": 632,
"line": " ssh_cmd_se_opt.remove('-autoexpand')\n"
},
{
"line_no": 18,
"char_start": 632,
"char_end": 633,
"line": "\n"
},
{
"line_no": 20,
"char_start": 669,
"char_end": 722,
"line": " ssh_cmd_se_opt.append('-compressed')\n"
},
{
"line_no": 22,
"char_start": 740,
"char_end": 818,
"line": " ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])\n"
},
{
"line_no": 23,
"char_start": 818,
"char_end": 819,
"line": "\n"
},
{
"line_no": 24,
"char_start": 819,
"char_end": 888,
"line": " ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',\n"
},
{
"line_no": 25,
"char_start": 888,
"char_end": 953,
"line": " self.configuration.storwize_svc_volpool_name,\n"
},
{
"line_no": 26,
"char_start": 953,
"char_end": 1011,
"line": " '-iogrp', '0', '-size', size, '-unit',\n"
},
{
"line_no": 27,
"char_start": 1011,
"char_end": 1077,
"line": " units, '-easytier', easytier] + ssh_cmd_se_opt\n"
}
]
} | {
"deleted": [
{
"char_start": 189,
"char_end": 250,
"chars": "autoex = '-autoexpand' if opts['autoexpand'] else ''\n "
},
{
"char_start": 262,
"char_end": 272,
"chars": "-easytier "
},
{
"char_start": 302,
"char_end": 312,
"chars": "-easytier "
},
{
"char_start": 417,
"char_end": 419,
"chars": "''"
},
{
"char_start": 483,
"char_end": 503,
"chars": "rsize %(rsize)d%% %("
},
{
"char_start": 509,
"char_end": 511,
"chars": ")s"
},
{
"char_start": 521,
"char_end": 535,
"chars": "%(warn)d%%' %\n"
},
{
"char_start": 551,
"char_end": 552,
"chars": "{"
},
{
"char_start": 553,
"char_end": 554,
"chars": "r"
},
{
"char_start": 555,
"char_end": 558,
"chars": "ize"
},
{
"char_start": 559,
"char_end": 560,
"chars": ":"
},
{
"char_start": 568,
"char_end": 569,
"chars": "s"
},
{
"char_start": 570,
"char_end": 572,
"chars": "ze"
},
{
"char_start": 574,
"char_end": 575,
"chars": ","
},
{
"char_start": 590,
"char_end": 593,
"chars": " "
},
{
"char_start": 602,
"char_end": 610,
"chars": " autoex,"
},
{
"char_start": 627,
"char_end": 628,
"chars": " "
},
{
"char_start": 629,
"char_end": 630,
"chars": "w"
},
{
"char_start": 631,
"char_end": 636,
"chars": "rn': "
},
{
"char_start": 638,
"char_end": 643,
"chars": "ts['w"
},
{
"char_start": 644,
"char_end": 645,
"chars": "r"
},
{
"char_start": 646,
"char_end": 649,
"chars": "ing"
},
{
"char_start": 650,
"char_end": 652,
"chars": "]}"
},
{
"char_start": 720,
"char_end": 735,
"chars": " = ssh_cmd_se_o"
},
{
"char_start": 736,
"char_end": 740,
"chars": "t + "
},
{
"char_start": 741,
"char_end": 742,
"chars": " "
},
{
"char_start": 803,
"char_end": 815,
"chars": " = ssh_cmd_s"
},
{
"char_start": 816,
"char_end": 819,
"chars": "_op"
},
{
"char_start": 820,
"char_end": 823,
"chars": " + "
},
{
"char_start": 824,
"char_end": 845,
"chars": "\n "
},
{
"char_start": 846,
"char_end": 847,
"chars": " "
},
{
"char_start": 857,
"char_end": 860,
"chars": " %d"
},
{
"char_start": 862,
"char_end": 864,
"chars": "% "
},
{
"char_start": 902,
"char_end": 903,
"chars": "("
},
{
"char_start": 926,
"char_end": 928,
"chars": "%("
},
{
"char_start": 932,
"char_end": 934,
"chars": ")s"
},
{
"char_start": 944,
"char_end": 958,
"chars": " %(mdiskgrp)s "
},
{
"char_start": 959,
"char_end": 1108,
"chars": "\n '-iogrp 0 -size %(size)s -unit '\n '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n % {'name': name"
},
{
"char_start": 1128,
"char_end": 1140,
"chars": " 'mdiskgrp':"
},
{
"char_start": 1212,
"char_end": 1213,
"chars": ":"
},
{
"char_start": 1226,
"char_end": 1227,
"chars": ":"
},
{
"char_start": 1245,
"char_end": 1246,
"chars": ":"
},
{
"char_start": 1255,
"char_end": 1275,
"chars": ",\n "
},
{
"char_start": 1276,
"char_end": 1293,
"chars": "'ssh_cmd_se_opt':"
},
{
"char_start": 1308,
"char_end": 1310,
"chars": "})"
}
],
"added": [
{
"char_start": 336,
"char_end": 338,
"chars": "[]"
},
{
"char_start": 382,
"char_end": 405,
"chars": "['-rsize', '%s%%' % str"
},
{
"char_start": 406,
"char_end": 421,
"chars": "opts['rsize']),"
},
{
"char_start": 439,
"char_end": 440,
"chars": " "
},
{
"char_start": 441,
"char_end": 454,
"chars": " '-"
},
{
"char_start": 460,
"char_end": 466,
"chars": "pand',"
},
{
"char_start": 467,
"char_end": 468,
"chars": "'"
},
{
"char_start": 477,
"char_end": 478,
"chars": ","
},
{
"char_start": 495,
"char_end": 509,
"chars": " "
},
{
"char_start": 510,
"char_end": 511,
"chars": "%"
},
{
"char_start": 512,
"char_end": 514,
"chars": "%%"
},
{
"char_start": 515,
"char_end": 517,
"chars": " %"
},
{
"char_start": 518,
"char_end": 522,
"chars": "str("
},
{
"char_start": 528,
"char_end": 530,
"chars": "wa"
},
{
"char_start": 531,
"char_end": 532,
"chars": "n"
},
{
"char_start": 533,
"char_end": 535,
"chars": "ng"
},
{
"char_start": 537,
"char_end": 539,
"chars": ")]"
},
{
"char_start": 552,
"char_end": 554,
"chars": "if"
},
{
"char_start": 555,
"char_end": 558,
"chars": "not"
},
{
"char_start": 559,
"char_end": 564,
"chars": "opts["
},
{
"char_start": 571,
"char_end": 575,
"chars": "pand"
},
{
"char_start": 576,
"char_end": 577,
"chars": "]"
},
{
"char_start": 595,
"char_end": 606,
"chars": "ssh_cmd_se_"
},
{
"char_start": 609,
"char_end": 617,
"chars": ".remove("
},
{
"char_start": 618,
"char_end": 619,
"chars": "-"
},
{
"char_start": 620,
"char_end": 627,
"chars": "utoexpa"
},
{
"char_start": 628,
"char_end": 629,
"chars": "d"
},
{
"char_start": 631,
"char_end": 632,
"chars": "\n"
},
{
"char_start": 699,
"char_end": 705,
"chars": ".appen"
},
{
"char_start": 706,
"char_end": 707,
"chars": "("
},
{
"char_start": 720,
"char_end": 721,
"chars": ")"
},
{
"char_start": 770,
"char_end": 771,
"chars": "."
},
{
"char_start": 772,
"char_end": 773,
"chars": "x"
},
{
"char_start": 774,
"char_end": 777,
"chars": "end"
},
{
"char_start": 778,
"char_end": 779,
"chars": "["
},
{
"char_start": 791,
"char_end": 792,
"chars": ","
},
{
"char_start": 793,
"char_end": 797,
"chars": "str("
},
{
"char_start": 813,
"char_end": 815,
"chars": "])"
},
{
"char_start": 837,
"char_end": 838,
"chars": "["
},
{
"char_start": 846,
"char_end": 848,
"chars": "',"
},
{
"char_start": 849,
"char_end": 850,
"chars": "'"
},
{
"char_start": 857,
"char_end": 859,
"chars": "',"
},
{
"char_start": 860,
"char_end": 861,
"chars": "'"
},
{
"char_start": 866,
"char_end": 868,
"chars": "',"
},
{
"char_start": 873,
"char_end": 874,
"chars": ","
},
{
"char_start": 875,
"char_end": 876,
"chars": "'"
},
{
"char_start": 973,
"char_end": 989,
"chars": "-iogrp', '0', '-"
},
{
"char_start": 994,
"char_end": 995,
"chars": ","
},
{
"char_start": 1003,
"char_end": 1004,
"chars": "-"
},
{
"char_start": 1009,
"char_end": 1029,
"chars": ",\n "
},
{
"char_start": 1038,
"char_end": 1039,
"chars": "-"
},
{
"char_start": 1048,
"char_end": 1049,
"chars": ","
},
{
"char_start": 1058,
"char_end": 1059,
"chars": "]"
},
{
"char_start": 1060,
"char_end": 1061,
"chars": "+"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
test_invalid_iscsi_ip | def test_invalid_iscsi_ip(self):
self.flags(lock_path=self.tempdir)
#record driver set up
self.clear_mox()
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_port_cmd = 'showport'
_run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])
show_port_i_cmd = 'showport -iscsi'
_run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),
''])
show_port_i_cmd = 'showport -iscsiname'
_run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])
config = self.setup_configuration()
config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']
config.iscsi_ip_address = '10.10.10.10'
self.mox.ReplayAll()
# no valid ip addr should be configured.
self.assertRaises(exception.InvalidInput,
self.setup_driver,
config,
set_up_fakes=False) | def test_invalid_iscsi_ip(self):
self.flags(lock_path=self.tempdir)
#record driver set up
self.clear_mox()
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_port_cmd = ['showport']
_run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])
show_port_i_cmd = ['showport', '-iscsi']
_run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),
''])
show_port_i_cmd = ['showport', '-iscsiname']
_run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])
config = self.setup_configuration()
config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']
config.iscsi_ip_address = '10.10.10.10'
self.mox.ReplayAll()
# no valid ip addr should be configured.
self.assertRaises(exception.InvalidInput,
self.setup_driver,
config,
set_up_fakes=False) | {
"deleted": [
{
"line_no": 9,
"char_start": 294,
"char_end": 329,
"line": " show_port_cmd = 'showport'\n"
},
{
"line_no": 12,
"char_start": 401,
"char_end": 445,
"line": " show_port_i_cmd = 'showport -iscsi'\n"
},
{
"line_no": 16,
"char_start": 583,
"char_end": 631,
"line": " show_port_i_cmd = 'showport -iscsiname'\n"
}
],
"added": [
{
"line_no": 9,
"char_start": 294,
"char_end": 331,
"line": " show_port_cmd = ['showport']\n"
},
{
"line_no": 12,
"char_start": 403,
"char_end": 452,
"line": " show_port_i_cmd = ['showport', '-iscsi']\n"
},
{
"line_no": 16,
"char_start": 590,
"char_end": 643,
"line": " show_port_i_cmd = ['showport', '-iscsiname']\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 318,
"char_end": 319,
"chars": "["
},
{
"char_start": 329,
"char_end": 330,
"chars": "]"
},
{
"char_start": 429,
"char_end": 430,
"chars": "["
},
{
"char_start": 439,
"char_end": 441,
"chars": "',"
},
{
"char_start": 442,
"char_end": 443,
"chars": "'"
},
{
"char_start": 450,
"char_end": 451,
"chars": "]"
},
{
"char_start": 616,
"char_end": 617,
"chars": "["
},
{
"char_start": 626,
"char_end": 628,
"chars": "',"
},
{
"char_start": 629,
"char_end": 630,
"chars": "'"
},
{
"char_start": 641,
"char_end": 642,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/tests/test_hp3par.py | cwe-078 |
get_output | def get_output(command: str) -> bytes:
"""
Run a command and return raw output
:param str command: the command to run
:returns: the stdout output of the command
"""
return subprocess.check_output(command.split()) | def get_output(command: List[str]) -> str:
"""
Run a command and return raw output
:param str command: the command to run
:returns: the stdout output of the command
"""
result = subprocess.run(command, stdout=subprocess.PIPE, check=True)
return result.stdout.decode() | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 39,
"line": "def get_output(command: str) -> bytes:\n"
},
{
"line_no": 8,
"char_start": 186,
"char_end": 237,
"line": " return subprocess.check_output(command.split())\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 43,
"line": "def get_output(command: List[str]) -> str:\n"
},
{
"line_no": 8,
"char_start": 190,
"char_end": 263,
"line": " result = subprocess.run(command, stdout=subprocess.PIPE, check=True)\n"
},
{
"line_no": 9,
"char_start": 263,
"char_end": 296,
"line": " return result.stdout.decode()\n"
}
]
} | {
"deleted": [
{
"char_start": 32,
"char_end": 36,
"chars": "byte"
},
{
"char_start": 213,
"char_end": 215,
"chars": "_o"
},
{
"char_start": 217,
"char_end": 218,
"chars": "p"
},
{
"char_start": 220,
"char_end": 221,
"chars": "("
},
{
"char_start": 223,
"char_end": 227,
"chars": "mman"
},
{
"char_start": 228,
"char_end": 234,
"chars": ".split"
},
{
"char_start": 236,
"char_end": 237,
"chars": ")"
}
],
"added": [
{
"char_start": 24,
"char_end": 29,
"chars": "List["
},
{
"char_start": 32,
"char_end": 33,
"chars": "]"
},
{
"char_start": 38,
"char_end": 39,
"chars": "s"
},
{
"char_start": 40,
"char_end": 41,
"chars": "r"
},
{
"char_start": 196,
"char_end": 199,
"chars": "sul"
},
{
"char_start": 200,
"char_end": 204,
"chars": " = s"
},
{
"char_start": 205,
"char_end": 207,
"chars": "bp"
},
{
"char_start": 208,
"char_end": 216,
"chars": "ocess.ru"
},
{
"char_start": 217,
"char_end": 226,
"chars": "(command,"
},
{
"char_start": 227,
"char_end": 234,
"chars": "stdout="
},
{
"char_start": 245,
"char_end": 251,
"chars": "PIPE, "
},
{
"char_start": 256,
"char_end": 259,
"chars": "=Tr"
},
{
"char_start": 260,
"char_end": 269,
"chars": "e)\n re"
},
{
"char_start": 270,
"char_end": 285,
"chars": "urn result.stdo"
},
{
"char_start": 287,
"char_end": 290,
"chars": ".de"
},
{
"char_start": 293,
"char_end": 294,
"chars": "e"
}
]
} | github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76 | isort/hooks.py | cwe-078 |
openscript | openscript(
char_u *name,
int directly) /* when TRUE execute directly */
{
if (curscript + 1 == NSCRIPT)
{
emsg(_(e_nesting));
return;
}
#ifdef FEAT_EVAL
if (ignore_script)
/* Not reading from script, also don't open one. Warning message? */
return;
#endif
if (scriptin[curscript] != NULL) /* already reading script */
++curscript;
/* use NameBuff for expanded name */
expand_env(name, NameBuff, MAXPATHL);
if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
{
semsg(_(e_notopen), name);
if (curscript)
--curscript;
return;
}
if (save_typebuf() == FAIL)
return;
/*
* Execute the commands from the file right now when using ":source!"
* after ":global" or ":argdo" or in a loop. Also when another command
* follows. This means the display won't be updated. Don't do this
* always, "make test" would fail.
*/
if (directly)
{
oparg_T oa;
int oldcurscript;
int save_State = State;
int save_restart_edit = restart_edit;
int save_insertmode = p_im;
int save_finish_op = finish_op;
int save_msg_scroll = msg_scroll;
State = NORMAL;
msg_scroll = FALSE; /* no msg scrolling in Normal mode */
restart_edit = 0; /* don't go to Insert mode */
p_im = FALSE; /* don't use 'insertmode' */
clear_oparg(&oa);
finish_op = FALSE;
oldcurscript = curscript;
do
{
update_topline_cursor(); // update cursor position and topline
normal_cmd(&oa, FALSE); // execute one command
vpeekc(); // check for end of file
}
while (scriptin[oldcurscript] != NULL);
State = save_State;
msg_scroll = save_msg_scroll;
restart_edit = save_restart_edit;
p_im = save_insertmode;
finish_op = save_finish_op;
}
} | openscript(
char_u *name,
int directly) /* when TRUE execute directly */
{
if (curscript + 1 == NSCRIPT)
{
emsg(_(e_nesting));
return;
}
// Disallow sourcing a file in the sandbox, the commands would be executed
// later, possibly outside of the sandbox.
if (check_secure())
return;
#ifdef FEAT_EVAL
if (ignore_script)
/* Not reading from script, also don't open one. Warning message? */
return;
#endif
if (scriptin[curscript] != NULL) /* already reading script */
++curscript;
/* use NameBuff for expanded name */
expand_env(name, NameBuff, MAXPATHL);
if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
{
semsg(_(e_notopen), name);
if (curscript)
--curscript;
return;
}
if (save_typebuf() == FAIL)
return;
/*
* Execute the commands from the file right now when using ":source!"
* after ":global" or ":argdo" or in a loop. Also when another command
* follows. This means the display won't be updated. Don't do this
* always, "make test" would fail.
*/
if (directly)
{
oparg_T oa;
int oldcurscript;
int save_State = State;
int save_restart_edit = restart_edit;
int save_insertmode = p_im;
int save_finish_op = finish_op;
int save_msg_scroll = msg_scroll;
State = NORMAL;
msg_scroll = FALSE; /* no msg scrolling in Normal mode */
restart_edit = 0; /* don't go to Insert mode */
p_im = FALSE; /* don't use 'insertmode' */
clear_oparg(&oa);
finish_op = FALSE;
oldcurscript = curscript;
do
{
update_topline_cursor(); // update cursor position and topline
normal_cmd(&oa, FALSE); // execute one command
vpeekc(); // check for end of file
}
while (scriptin[oldcurscript] != NULL);
State = save_State;
msg_scroll = save_msg_scroll;
restart_edit = save_restart_edit;
p_im = save_insertmode;
finish_op = save_finish_op;
}
} | {
"deleted": [],
"added": [
{
"line_no": 10,
"char_start": 160,
"char_end": 161,
"line": "\n"
},
{
"line_no": 13,
"char_start": 287,
"char_end": 311,
"line": " if (check_secure())\n"
},
{
"line_no": 14,
"char_start": 311,
"char_end": 320,
"line": "\treturn;\n"
},
{
"line_no": 15,
"char_start": 320,
"char_end": 321,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 160,
"char_end": 321,
"chars": "\n // Disallow sourcing a file in the sandbox, the commands would be executed\n // later, possibly outside of the sandbox.\n if (check_secure())\n\treturn;\n\n"
}
]
} | github.com/vim/vim/commit/53575521406739cf20bbe4e384d88e7dca11f040 | src/getchar.c | cwe-078 |
add_user | def add_user(username, password):
encPass = crypt.crypt(password,"22")
os.system("useradd -G docker,wheel -p "+encPass+" "+username) | def add_user(username, password):
encPass = crypt.crypt(password,"22")
#subprocess escapes the username stopping code injection
subprocess.call(['useradd','-G','docker,wheel','-p',encPass,username]) | {
"deleted": [
{
"line_no": 3,
"char_start": 75,
"char_end": 140,
"line": " os.system(\"useradd -G docker,wheel -p \"+encPass+\" \"+username)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 136,
"char_end": 210,
"line": " subprocess.call(['useradd','-G','docker,wheel','-p',encPass,username])\n"
}
]
} | {
"deleted": [
{
"char_start": 81,
"char_end": 82,
"chars": "."
},
{
"char_start": 83,
"char_end": 84,
"chars": "y"
},
{
"char_start": 89,
"char_end": 90,
"chars": "\""
},
{
"char_start": 97,
"char_end": 98,
"chars": " "
},
{
"char_start": 100,
"char_end": 101,
"chars": " "
},
{
"char_start": 113,
"char_end": 114,
"chars": " "
},
{
"char_start": 116,
"char_end": 119,
"chars": " \"+"
},
{
"char_start": 126,
"char_end": 131,
"chars": "+\" \"+"
}
],
"added": [
{
"char_start": 79,
"char_end": 85,
"chars": "#subpr"
},
{
"char_start": 86,
"char_end": 88,
"chars": "ce"
},
{
"char_start": 90,
"char_end": 92,
"chars": " e"
},
{
"char_start": 93,
"char_end": 99,
"chars": "capes "
},
{
"char_start": 100,
"char_end": 101,
"chars": "h"
},
{
"char_start": 102,
"char_end": 109,
"chars": " userna"
},
{
"char_start": 110,
"char_end": 155,
"chars": "e stopping code injection\n subprocess.call"
},
{
"char_start": 156,
"char_end": 158,
"chars": "['"
},
{
"char_start": 165,
"char_end": 168,
"chars": "','"
},
{
"char_start": 170,
"char_end": 173,
"chars": "','"
},
{
"char_start": 185,
"char_end": 188,
"chars": "','"
},
{
"char_start": 190,
"char_end": 192,
"chars": "',"
},
{
"char_start": 199,
"char_end": 200,
"chars": ","
},
{
"char_start": 208,
"char_end": 209,
"chars": "]"
}
]
} | github.com/Internet-of-People/titania-os/commit/9b7805119938343fcac9dc929d8882f1d97cf14a | vuedj/configtitania/views.py | cwe-078 |
write_section | def write_section(self, section_name, section_data):
self.write_line("")
self.write_line("define %s {" % section_name)
sorted_keys = section_data.keys()
sorted_keys.sort()
for key in sorted_keys:
value = section_data[key]
self.icinga_lines.append(("%s%-45s%s" % (self.indent, key, self.value_to_icinga(value))))
self.write_line("}") | def write_section(self, section_name, section_data):
self.write_line("")
self.write_line("define %s {" % section_name)
sorted_keys = section_data.keys()
sorted_keys.sort()
for key in sorted_keys:
value = self.value_to_icinga(section_data[key])
icinga_line = "%s%-45s%s" % (self.indent, key, value)
if "\n" in icinga_line or "}" in icinga_line:
msg = "Found forbidden newline or '}' character in section %r."
raise Exception(msg % section_name)
self.icinga_lines.append(icinga_line)
self.write_line("}") | {
"deleted": [
{
"line_no": 7,
"char_start": 240,
"char_end": 278,
"line": " value = section_data[key]\n"
},
{
"line_no": 8,
"char_start": 278,
"char_end": 380,
"line": " self.icinga_lines.append((\"%s%-45s%s\" % (self.indent, key, self.value_to_icinga(value))))\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 240,
"char_end": 300,
"line": " value = self.value_to_icinga(section_data[key])\n"
},
{
"line_no": 8,
"char_start": 300,
"char_end": 366,
"line": " icinga_line = \"%s%-45s%s\" % (self.indent, key, value)\n"
},
{
"line_no": 9,
"char_start": 366,
"char_end": 367,
"line": "\n"
},
{
"line_no": 10,
"char_start": 367,
"char_end": 425,
"line": " if \"\\n\" in icinga_line or \"}\" in icinga_line:\n"
},
{
"line_no": 11,
"char_start": 425,
"char_end": 505,
"line": " msg = \"Found forbidden newline or '}' character in section %r.\"\n"
},
{
"line_no": 12,
"char_start": 505,
"char_end": 557,
"line": " raise Exception(msg % section_name)\n"
},
{
"line_no": 13,
"char_start": 557,
"char_end": 558,
"line": "\n"
},
{
"line_no": 14,
"char_start": 558,
"char_end": 608,
"line": " self.icinga_lines.append(icinga_line)\n"
}
]
} | {
"deleted": [
{
"char_start": 290,
"char_end": 295,
"chars": "self."
},
{
"char_start": 306,
"char_end": 316,
"chars": "s.append(("
},
{
"char_start": 349,
"char_end": 350,
"chars": "s"
},
{
"char_start": 351,
"char_end": 352,
"chars": "l"
},
{
"char_start": 353,
"char_end": 355,
"chars": ".v"
},
{
"char_start": 357,
"char_end": 358,
"chars": "u"
},
{
"char_start": 370,
"char_end": 371,
"chars": "v"
},
{
"char_start": 373,
"char_end": 374,
"chars": "u"
},
{
"char_start": 375,
"char_end": 378,
"chars": ")))"
}
],
"added": [
{
"char_start": 262,
"char_end": 283,
"chars": "lf.value_to_icinga(se"
},
{
"char_start": 298,
"char_end": 299,
"chars": ")"
},
{
"char_start": 323,
"char_end": 326,
"chars": " = "
},
{
"char_start": 359,
"char_end": 442,
"chars": "value)\n\n if \"\\n\" in icinga_line or \"}\" in icinga_line:\n m"
},
{
"char_start": 443,
"char_end": 461,
"chars": "g = \"Found forbidd"
},
{
"char_start": 462,
"char_end": 467,
"chars": "n new"
},
{
"char_start": 468,
"char_end": 502,
"chars": "ine or '}' character in section %r"
},
{
"char_start": 503,
"char_end": 522,
"chars": "\"\n r"
},
{
"char_start": 523,
"char_end": 525,
"chars": "is"
},
{
"char_start": 526,
"char_end": 532,
"chars": " Excep"
},
{
"char_start": 533,
"char_end": 548,
"chars": "ion(msg % secti"
},
{
"char_start": 549,
"char_end": 550,
"chars": "n"
},
{
"char_start": 551,
"char_end": 575,
"chars": "name)\n\n self."
},
{
"char_start": 581,
"char_end": 594,
"chars": "_lines.append"
},
{
"char_start": 595,
"char_end": 600,
"chars": "icing"
},
{
"char_start": 601,
"char_end": 602,
"chars": "_"
},
{
"char_start": 603,
"char_end": 605,
"chars": "in"
}
]
} | github.com/Scout24/monitoring-config-generator/commit/a4b01b72d2e3d6ec2600c384a77f675fa9bbf6b7 | src/main/python/monitoring_config_generator/MonitoringConfigGenerator.py | cwe-078 |
_update_volume_stats | def _update_volume_stats(self):
"""Retrieve stats info from volume group."""
LOG.debug(_("Updating volume stats"))
data = {}
data['vendor_name'] = 'IBM'
data['driver_version'] = '1.1'
data['storage_protocol'] = list(self._enabled_protocols)
data['total_capacity_gb'] = 0 # To be overwritten
data['free_capacity_gb'] = 0 # To be overwritten
data['reserved_percentage'] = 0
data['QoS_support'] = False
pool = self.configuration.storwize_svc_volpool_name
#Get storage system name
ssh_cmd = 'svcinfo lssystem -delim !'
attributes = self._execute_command_and_parse_attributes(ssh_cmd)
if not attributes or not attributes['name']:
exception_message = (_('_update_volume_stats: '
'Could not get system name'))
raise exception.VolumeBackendAPIException(data=exception_message)
backend_name = self.configuration.safe_get('volume_backend_name')
if not backend_name:
backend_name = '%s_%s' % (attributes['name'], pool)
data['volume_backend_name'] = backend_name
ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool
attributes = self._execute_command_and_parse_attributes(ssh_cmd)
if not attributes:
LOG.error(_('Could not get pool data from the storage'))
exception_message = (_('_update_volume_stats: '
'Could not get storage pool data'))
raise exception.VolumeBackendAPIException(data=exception_message)
data['total_capacity_gb'] = (float(attributes['capacity']) /
(1024 ** 3))
data['free_capacity_gb'] = (float(attributes['free_capacity']) /
(1024 ** 3))
data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']
data['compression_support'] = self._compression_enabled
self._stats = data | def _update_volume_stats(self):
"""Retrieve stats info from volume group."""
LOG.debug(_("Updating volume stats"))
data = {}
data['vendor_name'] = 'IBM'
data['driver_version'] = '1.1'
data['storage_protocol'] = list(self._enabled_protocols)
data['total_capacity_gb'] = 0 # To be overwritten
data['free_capacity_gb'] = 0 # To be overwritten
data['reserved_percentage'] = 0
data['QoS_support'] = False
pool = self.configuration.storwize_svc_volpool_name
#Get storage system name
ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']
attributes = self._execute_command_and_parse_attributes(ssh_cmd)
if not attributes or not attributes['name']:
exception_message = (_('_update_volume_stats: '
'Could not get system name'))
raise exception.VolumeBackendAPIException(data=exception_message)
backend_name = self.configuration.safe_get('volume_backend_name')
if not backend_name:
backend_name = '%s_%s' % (attributes['name'], pool)
data['volume_backend_name'] = backend_name
ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]
attributes = self._execute_command_and_parse_attributes(ssh_cmd)
if not attributes:
LOG.error(_('Could not get pool data from the storage'))
exception_message = (_('_update_volume_stats: '
'Could not get storage pool data'))
raise exception.VolumeBackendAPIException(data=exception_message)
data['total_capacity_gb'] = (float(attributes['capacity']) /
(1024 ** 3))
data['free_capacity_gb'] = (float(attributes['free_capacity']) /
(1024 ** 3))
data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']
data['compression_support'] = self._compression_enabled
self._stats = data | {
"deleted": [
{
"line_no": 18,
"char_start": 584,
"char_end": 630,
"line": " ssh_cmd = 'svcinfo lssystem -delim !'\n"
},
{
"line_no": 30,
"char_start": 1179,
"char_end": 1244,
"line": " ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 584,
"char_end": 641,
"line": " ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']\n"
},
{
"line_no": 30,
"char_start": 1190,
"char_end": 1265,
"line": " ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]\n"
}
]
} | {
"deleted": [
{
"char_start": 1232,
"char_end": 1235,
"chars": " %s"
},
{
"char_start": 1236,
"char_end": 1238,
"chars": " %"
}
],
"added": [
{
"char_start": 602,
"char_end": 603,
"chars": "["
},
{
"char_start": 611,
"char_end": 613,
"chars": "',"
},
{
"char_start": 614,
"char_end": 615,
"chars": "'"
},
{
"char_start": 623,
"char_end": 625,
"chars": "',"
},
{
"char_start": 626,
"char_end": 627,
"chars": "'"
},
{
"char_start": 633,
"char_end": 635,
"chars": "',"
},
{
"char_start": 636,
"char_end": 637,
"chars": "'"
},
{
"char_start": 639,
"char_end": 640,
"chars": "]"
},
{
"char_start": 1208,
"char_end": 1209,
"chars": "["
},
{
"char_start": 1217,
"char_end": 1219,
"chars": "',"
},
{
"char_start": 1220,
"char_end": 1221,
"chars": "'"
},
{
"char_start": 1231,
"char_end": 1233,
"chars": "',"
},
{
"char_start": 1234,
"char_end": 1235,
"chars": "'"
},
{
"char_start": 1241,
"char_end": 1243,
"chars": "',"
},
{
"char_start": 1244,
"char_end": 1245,
"chars": "'"
},
{
"char_start": 1251,
"char_end": 1253,
"chars": "',"
},
{
"char_start": 1254,
"char_end": 1255,
"chars": "'"
},
{
"char_start": 1257,
"char_end": 1258,
"chars": ","
},
{
"char_start": 1263,
"char_end": 1264,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
test_create_modify_host | def test_create_modify_host(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
self.fake_get_cpg)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
self.fake_get_domain)
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_host_cmd = 'showhost -verbose fakehost'
_run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])
create_host_cmd = ('createhost -add fakehost '
'123456789012345 123456789054321')
_run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])
show_host_cmd = 'showhost -verbose fakehost'
_run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])
self.mox.ReplayAll()
host = self.driver._create_host(self.volume, self.connector)
self.assertEqual(host['name'], self.FAKE_HOST) | def test_create_modify_host(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
self.fake_get_cpg)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
self.fake_get_domain)
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_host_cmd = ['showhost', '-verbose', 'fakehost']
_run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])
create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',
'123456789054321']
_run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])
show_host_cmd = ['showhost', '-verbose', 'fakehost']
_run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])
self.mox.ReplayAll()
host = self.driver._create_host(self.volume, self.connector)
self.assertEqual(host['name'], self.FAKE_HOST) | {
"deleted": [
{
"line_no": 13,
"char_start": 504,
"char_end": 557,
"line": " show_host_cmd = 'showhost -verbose fakehost'\n"
},
{
"line_no": 16,
"char_start": 635,
"char_end": 690,
"line": " create_host_cmd = ('createhost -add fakehost '\n"
},
{
"line_no": 17,
"char_start": 690,
"char_end": 752,
"line": " '123456789012345 123456789054321')\n"
},
{
"line_no": 20,
"char_start": 818,
"char_end": 871,
"line": " show_host_cmd = 'showhost -verbose fakehost'\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 504,
"char_end": 565,
"line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n"
},
{
"line_no": 16,
"char_start": 643,
"char_end": 723,
"line": " create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',\n"
},
{
"line_no": 17,
"char_start": 723,
"char_end": 769,
"line": " '123456789054321']\n"
},
{
"line_no": 20,
"char_start": 835,
"char_end": 896,
"line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n"
}
]
} | {
"deleted": [
{
"char_start": 661,
"char_end": 662,
"chars": "("
},
{
"char_start": 728,
"char_end": 744,
"chars": "12345 1234567890"
},
{
"char_start": 750,
"char_end": 751,
"chars": ")"
}
],
"added": [
{
"char_start": 528,
"char_end": 529,
"chars": "["
},
{
"char_start": 538,
"char_end": 540,
"chars": "',"
},
{
"char_start": 541,
"char_end": 542,
"chars": "'"
},
{
"char_start": 550,
"char_end": 552,
"chars": "',"
},
{
"char_start": 553,
"char_end": 554,
"chars": "'"
},
{
"char_start": 563,
"char_end": 564,
"chars": "]"
},
{
"char_start": 669,
"char_end": 670,
"chars": "["
},
{
"char_start": 681,
"char_end": 683,
"chars": "',"
},
{
"char_start": 684,
"char_end": 685,
"chars": "'"
},
{
"char_start": 689,
"char_end": 691,
"chars": "',"
},
{
"char_start": 692,
"char_end": 693,
"chars": "'"
},
{
"char_start": 701,
"char_end": 703,
"chars": "',"
},
{
"char_start": 705,
"char_end": 722,
"chars": "123456789012345',"
},
{
"char_start": 767,
"char_end": 768,
"chars": "]"
},
{
"char_start": 859,
"char_end": 860,
"chars": "["
},
{
"char_start": 869,
"char_end": 871,
"chars": "',"
},
{
"char_start": 872,
"char_end": 873,
"chars": "'"
},
{
"char_start": 881,
"char_end": 883,
"chars": "',"
},
{
"char_start": 884,
"char_end": 885,
"chars": "'"
},
{
"char_start": 894,
"char_end": 895,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/tests/test_hp3par.py | cwe-078 |
install | def install(filename, target):
'''Run a package's installer script against the given target directory.'''
print(' Unpacking %s...' % filename)
os.system('tar xf ' + filename)
basename = filename.split('.tar')[0]
print(' Installing %s...' % basename)
install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target
os.system('%s/install.sh %s' % (basename, install_opts))
print(' Cleaning %s...' % basename)
os.system('rm -rf %s' % basename) | def install(filename, target):
'''Run a package's installer script against the given target directory.'''
print(' Unpacking %s...' % filename)
subprocess.check_call(['tar', 'xf', filename])
basename = filename.split('.tar')[0]
print(' Installing %s...' % basename)
install_cmd = [os.path.join(basename, 'install.sh')]
install_cmd += ['--prefix=' + os.path.abspath(target)]
install_cmd += ['--disable-ldconfig']
subprocess.check_call(install_cmd)
print(' Cleaning %s...' % basename)
subprocess.check_call(['rm', '-rf', basename]) | {
"deleted": [
{
"line_no": 4,
"char_start": 147,
"char_end": 181,
"line": " os.system('tar xf ' + filename)\n"
},
{
"line_no": 7,
"char_start": 260,
"char_end": 326,
"line": " install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target\n"
},
{
"line_no": 8,
"char_start": 326,
"char_end": 385,
"line": " os.system('%s/install.sh %s' % (basename, install_opts))\n"
},
{
"line_no": 10,
"char_start": 423,
"char_end": 458,
"line": " os.system('rm -rf %s' % basename)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 147,
"char_end": 196,
"line": " subprocess.check_call(['tar', 'xf', filename])\n"
},
{
"line_no": 7,
"char_start": 275,
"char_end": 330,
"line": " install_cmd = [os.path.join(basename, 'install.sh')]\n"
},
{
"line_no": 8,
"char_start": 330,
"char_end": 387,
"line": " install_cmd += ['--prefix=' + os.path.abspath(target)]\n"
},
{
"line_no": 9,
"char_start": 387,
"char_end": 427,
"line": " install_cmd += ['--disable-ldconfig']\n"
},
{
"line_no": 10,
"char_start": 427,
"char_end": 464,
"line": " subprocess.check_call(install_cmd)\n"
},
{
"line_no": 12,
"char_start": 502,
"char_end": 550,
"line": " subprocess.check_call(['rm', '-rf', basename])\n"
}
]
} | {
"deleted": [
{
"char_start": 149,
"char_end": 150,
"chars": "o"
},
{
"char_start": 151,
"char_end": 152,
"chars": "."
},
{
"char_start": 153,
"char_end": 154,
"chars": "y"
},
{
"char_start": 155,
"char_end": 156,
"chars": "t"
},
{
"char_start": 157,
"char_end": 158,
"chars": "m"
},
{
"char_start": 166,
"char_end": 167,
"chars": " "
},
{
"char_start": 168,
"char_end": 170,
"chars": " +"
},
{
"char_start": 287,
"char_end": 295,
"chars": "${PWD}/%"
},
{
"char_start": 317,
"char_end": 318,
"chars": "%"
},
{
"char_start": 319,
"char_end": 321,
"chars": "ta"
},
{
"char_start": 322,
"char_end": 328,
"chars": "get\n "
},
{
"char_start": 329,
"char_end": 335,
"chars": "s.syst"
},
{
"char_start": 336,
"char_end": 340,
"chars": "m('%"
},
{
"char_start": 341,
"char_end": 344,
"chars": "/in"
},
{
"char_start": 345,
"char_end": 349,
"chars": "tall"
},
{
"char_start": 350,
"char_end": 351,
"chars": "s"
},
{
"char_start": 352,
"char_end": 363,
"chars": " %s' % (bas"
},
{
"char_start": 364,
"char_end": 365,
"chars": "n"
},
{
"char_start": 366,
"char_end": 370,
"chars": "me, "
},
{
"char_start": 378,
"char_end": 383,
"chars": "opts)"
},
{
"char_start": 426,
"char_end": 428,
"chars": "s."
},
{
"char_start": 429,
"char_end": 430,
"chars": "y"
},
{
"char_start": 431,
"char_end": 432,
"chars": "t"
},
{
"char_start": 433,
"char_end": 434,
"chars": "m"
},
{
"char_start": 442,
"char_end": 445,
"chars": " %s"
},
{
"char_start": 446,
"char_end": 448,
"chars": " %"
}
],
"added": [
{
"char_start": 149,
"char_end": 154,
"chars": "subpr"
},
{
"char_start": 155,
"char_end": 158,
"chars": "ces"
},
{
"char_start": 160,
"char_end": 162,
"chars": "ch"
},
{
"char_start": 163,
"char_end": 170,
"chars": "ck_call"
},
{
"char_start": 171,
"char_end": 172,
"chars": "["
},
{
"char_start": 176,
"char_end": 178,
"chars": "',"
},
{
"char_start": 179,
"char_end": 180,
"chars": "'"
},
{
"char_start": 183,
"char_end": 184,
"chars": ","
},
{
"char_start": 193,
"char_end": 194,
"chars": "]"
},
{
"char_start": 285,
"char_end": 292,
"chars": "cmd = ["
},
{
"char_start": 293,
"char_end": 295,
"chars": "s."
},
{
"char_start": 296,
"char_end": 297,
"chars": "a"
},
{
"char_start": 298,
"char_end": 307,
"chars": "h.join(ba"
},
{
"char_start": 308,
"char_end": 314,
"chars": "ename,"
},
{
"char_start": 315,
"char_end": 345,
"chars": "'install.sh')]\n install_cmd +"
},
{
"char_start": 347,
"char_end": 348,
"chars": "["
},
{
"char_start": 358,
"char_end": 391,
"chars": "' + os.path.abspath(target)]\n in"
},
{
"char_start": 392,
"char_end": 400,
"chars": "tall_cmd"
},
{
"char_start": 401,
"char_end": 406,
"chars": "+= ['"
},
{
"char_start": 425,
"char_end": 427,
"chars": "]\n"
},
{
"char_start": 429,
"char_end": 433,
"chars": "subp"
},
{
"char_start": 435,
"char_end": 438,
"chars": "ces"
},
{
"char_start": 440,
"char_end": 442,
"chars": "ch"
},
{
"char_start": 443,
"char_end": 447,
"chars": "ck_c"
},
{
"char_start": 459,
"char_end": 462,
"chars": "cmd"
},
{
"char_start": 504,
"char_end": 509,
"chars": "subpr"
},
{
"char_start": 510,
"char_end": 512,
"chars": "ce"
},
{
"char_start": 514,
"char_end": 517,
"chars": ".ch"
},
{
"char_start": 518,
"char_end": 525,
"chars": "ck_call"
},
{
"char_start": 526,
"char_end": 527,
"chars": "["
},
{
"char_start": 530,
"char_end": 532,
"chars": "',"
},
{
"char_start": 533,
"char_end": 534,
"chars": "'"
},
{
"char_start": 538,
"char_end": 539,
"chars": ","
},
{
"char_start": 548,
"char_end": 549,
"chars": "]"
}
]
} | github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb | repack_rust.py | cwe-078 |
_get_least_used_nsp | def _get_least_used_nsp(self, nspss):
""""Return the nsp that has the fewest active vluns."""
# return only the nsp (node:server:port)
result = self.common._cli_run('showvlun -a -showcols Port', None)
# count the number of nsps (there is 1 for each active vlun)
nsp_counts = {}
for nsp in nspss:
# initialize counts to zero
nsp_counts[nsp] = 0
current_least_used_nsp = None
if result:
# first line is header
result = result[1:]
for line in result:
nsp = line.strip()
if nsp in nsp_counts:
nsp_counts[nsp] = nsp_counts[nsp] + 1
# identify key (nsp) of least used nsp
current_smallest_count = sys.maxint
for (nsp, count) in nsp_counts.iteritems():
if count < current_smallest_count:
current_least_used_nsp = nsp
current_smallest_count = count
return current_least_used_nsp | def _get_least_used_nsp(self, nspss):
""""Return the nsp that has the fewest active vluns."""
# return only the nsp (node:server:port)
result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])
# count the number of nsps (there is 1 for each active vlun)
nsp_counts = {}
for nsp in nspss:
# initialize counts to zero
nsp_counts[nsp] = 0
current_least_used_nsp = None
if result:
# first line is header
result = result[1:]
for line in result:
nsp = line.strip()
if nsp in nsp_counts:
nsp_counts[nsp] = nsp_counts[nsp] + 1
# identify key (nsp) of least used nsp
current_smallest_count = sys.maxint
for (nsp, count) in nsp_counts.iteritems():
if count < current_smallest_count:
current_least_used_nsp = nsp
current_smallest_count = count
return current_least_used_nsp | {
"deleted": [
{
"line_no": 4,
"char_start": 155,
"char_end": 229,
"line": " result = self.common._cli_run('showvlun -a -showcols Port', None)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 155,
"char_end": 234,
"line": " result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])\n"
}
]
} | {
"deleted": [
{
"char_start": 221,
"char_end": 227,
"chars": ", None"
}
],
"added": [
{
"char_start": 193,
"char_end": 194,
"chars": "["
},
{
"char_start": 203,
"char_end": 205,
"chars": "',"
},
{
"char_start": 206,
"char_end": 207,
"chars": "'"
},
{
"char_start": 209,
"char_end": 211,
"chars": "',"
},
{
"char_start": 212,
"char_end": 213,
"chars": "'"
},
{
"char_start": 222,
"char_end": 224,
"chars": "',"
},
{
"char_start": 225,
"char_end": 226,
"chars": "'"
},
{
"char_start": 231,
"char_end": 232,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_iscsi.py | cwe-078 |
_start_fc_map | def _start_fc_map(self, fc_map_id, source, target):
try:
out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)
except exception.ProcessExecutionError as e:
with excutils.save_and_reraise_exception():
LOG.error(_('_start_fc_map: Failed to start FlashCopy '
'from %(source)s to %(target)s.\n'
'stdout: %(out)s\n stderr: %(err)s')
% {'source': source,
'target': target,
'out': e.stdout,
'err': e.stderr}) | def _start_fc_map(self, fc_map_id, source, target):
try:
out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])
except exception.ProcessExecutionError as e:
with excutils.save_and_reraise_exception():
LOG.error(_('_start_fc_map: Failed to start FlashCopy '
'from %(source)s to %(target)s.\n'
'stdout: %(out)s\n stderr: %(err)s')
% {'source': source,
'target': target,
'out': e.stdout,
'err': e.stderr}) | {
"deleted": [
{
"line_no": 3,
"char_start": 69,
"char_end": 143,
"line": " out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 69,
"char_end": 144,
"line": " out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])\n"
}
]
} | {
"deleted": [
{
"char_start": 125,
"char_end": 128,
"chars": " %s"
},
{
"char_start": 129,
"char_end": 131,
"chars": " %"
}
],
"added": [
{
"char_start": 106,
"char_end": 107,
"chars": "["
},
{
"char_start": 115,
"char_end": 117,
"chars": "',"
},
{
"char_start": 118,
"char_end": 119,
"chars": "'"
},
{
"char_start": 130,
"char_end": 131,
"chars": ","
},
{
"char_start": 141,
"char_end": 142,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
resolve_hostname | @then(parsers.parse("the hostname '{hostname}' should be resolved"))
def resolve_hostname(busybox_pod, host, hostname):
with host.sudo():
# test dns resolve
cmd_nslookup = ("kubectl --kubeconfig=/etc/kubernetes/admin.conf"
" exec -ti {0} nslookup {1}".format(
pod_name,
hostname))
res = host.run(cmd_nslookup)
assert res.rc == 0, "Cannot resolve {}".format(hostname) | @then(parsers.parse("the hostname '{hostname}' should be resolved"))
def resolve_hostname(busybox_pod, host, hostname):
with host.sudo():
# test dns resolve
result = host.run(
"kubectl --kubeconfig=/etc/kubernetes/admin.conf "
"exec -ti %s nslookup %s",
busybox_pod,
hostname,
)
assert result.rc == 0, "Cannot resolve {}".format(hostname) | {
"deleted": [
{
"line_no": 3,
"char_start": 120,
"char_end": 146,
"line": " with host.sudo():\n"
},
{
"line_no": 5,
"char_start": 177,
"char_end": 255,
"line": " cmd_nslookup = (\"kubectl --kubeconfig=/etc/kubernetes/admin.conf\"\n"
},
{
"line_no": 6,
"char_start": 255,
"char_end": 320,
"line": " \" exec -ti {0} nslookup {1}\".format(\n"
},
{
"line_no": 7,
"char_start": 320,
"char_end": 362,
"line": " pod_name,\n"
},
{
"line_no": 8,
"char_start": 362,
"char_end": 405,
"line": " hostname))\n"
},
{
"line_no": 9,
"char_start": 405,
"char_end": 446,
"line": " res = host.run(cmd_nslookup)\n"
},
{
"line_no": 10,
"char_start": 446,
"char_end": 514,
"line": " assert res.rc == 0, \"Cannot resolve {}\".format(hostname)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 120,
"char_end": 142,
"line": " with host.sudo():\n"
},
{
"line_no": 5,
"char_start": 169,
"char_end": 196,
"line": " result = host.run(\n"
},
{
"line_no": 6,
"char_start": 196,
"char_end": 259,
"line": " \"kubectl --kubeconfig=/etc/kubernetes/admin.conf \"\n"
},
{
"line_no": 7,
"char_start": 259,
"char_end": 298,
"line": " \"exec -ti %s nslookup %s\",\n"
},
{
"line_no": 8,
"char_start": 298,
"char_end": 323,
"line": " busybox_pod,\n"
},
{
"line_no": 9,
"char_start": 323,
"char_end": 345,
"line": " hostname,\n"
},
{
"line_no": 10,
"char_start": 345,
"char_end": 355,
"line": " )\n"
},
{
"line_no": 11,
"char_start": 355,
"char_end": 356,
"line": "\n"
},
{
"line_no": 12,
"char_start": 356,
"char_end": 423,
"line": " assert result.rc == 0, \"Cannot resolve {}\".format(hostname)"
}
]
} | {
"deleted": [
{
"char_start": 124,
"char_end": 128,
"chars": " "
},
{
"char_start": 146,
"char_end": 150,
"chars": " "
},
{
"char_start": 189,
"char_end": 201,
"chars": "cmd_nslookup"
},
{
"char_start": 202,
"char_end": 203,
"chars": "="
},
{
"char_start": 204,
"char_end": 205,
"chars": "("
},
{
"char_start": 255,
"char_end": 265,
"chars": " "
},
{
"char_start": 277,
"char_end": 283,
"chars": " "
},
{
"char_start": 284,
"char_end": 285,
"chars": " "
},
{
"char_start": 294,
"char_end": 297,
"chars": "{0}"
},
{
"char_start": 307,
"char_end": 310,
"chars": "{1}"
},
{
"char_start": 311,
"char_end": 319,
"chars": ".format("
},
{
"char_start": 332,
"char_end": 352,
"chars": " "
},
{
"char_start": 355,
"char_end": 360,
"chars": "_name"
},
{
"char_start": 374,
"char_end": 394,
"chars": " "
},
{
"char_start": 402,
"char_end": 404,
"chars": "))"
},
{
"char_start": 405,
"char_end": 406,
"chars": " "
},
{
"char_start": 414,
"char_end": 444,
"chars": " res = host.run(cmd_nslookup"
},
{
"char_start": 446,
"char_end": 450,
"chars": " "
}
],
"added": [
{
"char_start": 177,
"char_end": 179,
"chars": "re"
},
{
"char_start": 180,
"char_end": 181,
"chars": "u"
},
{
"char_start": 182,
"char_end": 187,
"chars": "t = h"
},
{
"char_start": 188,
"char_end": 192,
"chars": "st.r"
},
{
"char_start": 193,
"char_end": 206,
"chars": "n(\n "
},
{
"char_start": 256,
"char_end": 257,
"chars": " "
},
{
"char_start": 281,
"char_end": 283,
"chars": "%s"
},
{
"char_start": 293,
"char_end": 295,
"chars": "%s"
},
{
"char_start": 296,
"char_end": 297,
"chars": ","
},
{
"char_start": 310,
"char_end": 318,
"chars": "busybox_"
},
{
"char_start": 343,
"char_end": 344,
"chars": ","
},
{
"char_start": 355,
"char_end": 356,
"chars": "\n"
},
{
"char_start": 374,
"char_end": 377,
"chars": "ult"
}
]
} | github.com/scality/metalk8s/commit/82d92836d4ff78c623a0e06302c94cfa5ff79908 | tests/post/steps/test_dns.py | cwe-078 |
_modify_3par_fibrechan_host | def _modify_3par_fibrechan_host(self, hostname, wwn):
# when using -add, you can not send the persona or domain options
out = self.common._cli_run('createhost -add %s %s'
% (hostname, " ".join(wwn)), None) | def _modify_3par_fibrechan_host(self, hostname, wwns):
# when using -add, you can not send the persona or domain options
command = ['createhost', '-add', hostname]
for wwn in wwns:
command.append(wwn)
out = self.common._cli_run(command) | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 58,
"line": " def _modify_3par_fibrechan_host(self, hostname, wwn):\n"
},
{
"line_no": 3,
"char_start": 132,
"char_end": 191,
"line": " out = self.common._cli_run('createhost -add %s %s'\n"
},
{
"line_no": 4,
"char_start": 191,
"char_end": 260,
"line": " % (hostname, \" \".join(wwn)), None)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 59,
"line": " def _modify_3par_fibrechan_host(self, hostname, wwns):\n"
},
{
"line_no": 3,
"char_start": 133,
"char_end": 184,
"line": " command = ['createhost', '-add', hostname]\n"
},
{
"line_no": 4,
"char_start": 184,
"char_end": 209,
"line": " for wwn in wwns:\n"
},
{
"line_no": 5,
"char_start": 209,
"char_end": 241,
"line": " command.append(wwn)\n"
},
{
"line_no": 6,
"char_start": 241,
"char_end": 242,
"line": "\n"
},
{
"line_no": 7,
"char_start": 242,
"char_end": 285,
"line": " out = self.common._cli_run(command)\n"
}
]
} | {
"deleted": [
{
"char_start": 58,
"char_end": 58,
"chars": ""
},
{
"char_start": 140,
"char_end": 151,
"chars": "out = self."
},
{
"char_start": 155,
"char_end": 156,
"chars": "o"
},
{
"char_start": 157,
"char_end": 167,
"chars": "._cli_run("
},
{
"char_start": 184,
"char_end": 188,
"chars": "%s %"
},
{
"char_start": 189,
"char_end": 190,
"chars": "'"
},
{
"char_start": 191,
"char_end": 194,
"chars": " "
},
{
"char_start": 202,
"char_end": 204,
"chars": " "
},
{
"char_start": 226,
"char_end": 230,
"chars": "% (h"
},
{
"char_start": 231,
"char_end": 232,
"chars": "s"
},
{
"char_start": 233,
"char_end": 238,
"chars": "name,"
},
{
"char_start": 239,
"char_end": 240,
"chars": "\""
},
{
"char_start": 241,
"char_end": 242,
"chars": "\""
},
{
"char_start": 243,
"char_end": 244,
"chars": "j"
},
{
"char_start": 248,
"char_end": 256,
"chars": "wwn)), N"
},
{
"char_start": 258,
"char_end": 259,
"chars": "e"
}
],
"added": [
{
"char_start": 55,
"char_end": 56,
"chars": "s"
},
{
"char_start": 145,
"char_end": 146,
"chars": "a"
},
{
"char_start": 147,
"char_end": 152,
"chars": "d = ["
},
{
"char_start": 163,
"char_end": 165,
"chars": "',"
},
{
"char_start": 166,
"char_end": 167,
"chars": "'"
},
{
"char_start": 171,
"char_end": 173,
"chars": "',"
},
{
"char_start": 174,
"char_end": 176,
"chars": "ho"
},
{
"char_start": 177,
"char_end": 183,
"chars": "tname]"
},
{
"char_start": 192,
"char_end": 195,
"chars": "for"
},
{
"char_start": 196,
"char_end": 199,
"chars": "wwn"
},
{
"char_start": 200,
"char_end": 202,
"chars": "in"
},
{
"char_start": 203,
"char_end": 209,
"chars": "wwns:\n"
},
{
"char_start": 221,
"char_end": 242,
"chars": "command.append(wwn)\n\n"
},
{
"char_start": 251,
"char_end": 252,
"chars": "u"
},
{
"char_start": 254,
"char_end": 255,
"chars": "="
},
{
"char_start": 256,
"char_end": 260,
"chars": "self"
},
{
"char_start": 261,
"char_end": 265,
"chars": "comm"
},
{
"char_start": 266,
"char_end": 271,
"chars": "n._cl"
},
{
"char_start": 272,
"char_end": 275,
"chars": "_ru"
},
{
"char_start": 277,
"char_end": 278,
"chars": "c"
},
{
"char_start": 279,
"char_end": 282,
"chars": "mma"
},
{
"char_start": 283,
"char_end": 284,
"chars": "d"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_fc.py | cwe-078 |
test_settings_path_skip_issue_909 | def test_settings_path_skip_issue_909(tmpdir):
base_dir = tmpdir.mkdir('project')
config_dir = base_dir.mkdir('conf')
config_dir.join('.isort.cfg').write('[isort]\n'
'skip =\n'
' file_to_be_skipped.py\n'
'skip_glob =\n'
' *glob_skip*\n')
base_dir.join('file_glob_skip.py').write('import os\n'
'\n'
'print("Hello World")\n'
'\n'
'import sys\n')
base_dir.join('file_to_be_skipped.py').write('import os\n'
'\n'
'print("Hello World")'
'\n'
'import sys\n')
test_run_directory = os.getcwd()
os.chdir(str(base_dir))
with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors
check_output(['isort', '--check-only'])
results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])
os.chdir(str(test_run_directory))
assert b'skipped 2' in results.lower() | def test_settings_path_skip_issue_909(tmpdir):
base_dir = tmpdir.mkdir('project')
config_dir = base_dir.mkdir('conf')
config_dir.join('.isort.cfg').write('[isort]\n'
'skip =\n'
' file_to_be_skipped.py\n'
'skip_glob =\n'
' *glob_skip*\n')
base_dir.join('file_glob_skip.py').write('import os\n'
'\n'
'print("Hello World")\n'
'\n'
'import sys\n')
base_dir.join('file_to_be_skipped.py').write('import os\n'
'\n'
'print("Hello World")'
'\n'
'import sys\n')
test_run_directory = os.getcwd()
os.chdir(str(base_dir))
with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors
subprocess.run(['isort', '--check-only'], check=True)
result = subprocess.run(
['isort', '--check-only', '--settings-path=conf/.isort.cfg'],
stdout=subprocess.PIPE,
check=True
)
os.chdir(str(test_run_directory))
assert b'skipped 2' in result.stdout.lower() | {
"deleted": [
{
"line_no": 24,
"char_start": 1201,
"char_end": 1249,
"line": " check_output(['isort', '--check-only'])\n"
},
{
"line_no": 25,
"char_start": 1249,
"char_end": 1338,
"line": " results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])\n"
},
{
"line_no": 28,
"char_start": 1377,
"char_end": 1419,
"line": " assert b'skipped 2' in results.lower()\n"
}
],
"added": [
{
"line_no": 24,
"char_start": 1201,
"char_end": 1263,
"line": " subprocess.run(['isort', '--check-only'], check=True)\n"
},
{
"line_no": 25,
"char_start": 1263,
"char_end": 1292,
"line": " result = subprocess.run(\n"
},
{
"line_no": 26,
"char_start": 1292,
"char_end": 1362,
"line": " ['isort', '--check-only', '--settings-path=conf/.isort.cfg'],\n"
},
{
"line_no": 27,
"char_start": 1362,
"char_end": 1394,
"line": " stdout=subprocess.PIPE,\n"
},
{
"line_no": 28,
"char_start": 1394,
"char_end": 1413,
"line": " check=True\n"
},
{
"line_no": 29,
"char_start": 1413,
"char_end": 1419,
"line": " )\n"
},
{
"line_no": 32,
"char_start": 1458,
"char_end": 1506,
"line": " assert b'skipped 2' in result.stdout.lower()\n"
}
]
} | {
"deleted": [
{
"char_start": 1209,
"char_end": 1216,
"chars": "check_o"
},
{
"char_start": 1217,
"char_end": 1218,
"chars": "t"
},
{
"char_start": 1220,
"char_end": 1221,
"chars": "t"
},
{
"char_start": 1259,
"char_end": 1260,
"chars": "s"
},
{
"char_start": 1264,
"char_end": 1265,
"chars": "h"
},
{
"char_start": 1266,
"char_end": 1273,
"chars": "ck_outp"
},
{
"char_start": 1274,
"char_end": 1275,
"chars": "t"
}
],
"added": [
{
"char_start": 1209,
"char_end": 1215,
"chars": "subpro"
},
{
"char_start": 1217,
"char_end": 1221,
"chars": "ss.r"
},
{
"char_start": 1222,
"char_end": 1223,
"chars": "n"
},
{
"char_start": 1249,
"char_end": 1261,
"chars": ", check=True"
},
{
"char_start": 1276,
"char_end": 1282,
"chars": "subpro"
},
{
"char_start": 1284,
"char_end": 1288,
"chars": "ss.r"
},
{
"char_start": 1289,
"char_end": 1290,
"chars": "n"
},
{
"char_start": 1291,
"char_end": 1300,
"chars": "\n "
},
{
"char_start": 1360,
"char_end": 1417,
"chars": ",\n stdout=subprocess.PIPE,\n check=True\n "
},
{
"char_start": 1491,
"char_end": 1492,
"chars": "."
},
{
"char_start": 1493,
"char_end": 1498,
"chars": "tdout"
}
]
} | github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76 | test_isort.py | cwe-078 |
_create_3par_fibrechan_host | def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):
"""Create a 3PAR host.
Create a 3PAR host, if there is already a host on the 3par using
the same wwn but with a different hostname, return the hostname
used by 3PAR.
"""
out = self.common._cli_run('createhost -persona %s -domain %s %s %s'
% (persona_id, domain,
hostname, " ".join(wwn)), None)
if out and len(out) > 1:
return self.common.parse_create_host_error(hostname, out)
return hostname | def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):
"""Create a 3PAR host.
Create a 3PAR host, if there is already a host on the 3par using
the same wwn but with a different hostname, return the hostname
used by 3PAR.
"""
command = ['createhost', '-persona', persona_id, '-domain', domain,
hostname]
for wwn in wwns:
command.append(wwn)
out = self.common._cli_run(command)
if out and len(out) > 1:
return self.common.parse_create_host_error(hostname, out)
return hostname | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 78,
"line": " def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):\n"
},
{
"line_no": 8,
"char_start": 289,
"char_end": 366,
"line": " out = self.common._cli_run('createhost -persona %s -domain %s %s %s'\n"
},
{
"line_no": 9,
"char_start": 366,
"char_end": 424,
"line": " % (persona_id, domain,\n"
},
{
"line_no": 10,
"char_start": 424,
"char_end": 494,
"line": " hostname, \" \".join(wwn)), None)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 79,
"line": " def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):\n"
},
{
"line_no": 8,
"char_start": 290,
"char_end": 366,
"line": " command = ['createhost', '-persona', persona_id, '-domain', domain,\n"
},
{
"line_no": 9,
"char_start": 366,
"char_end": 395,
"line": " hostname]\n"
},
{
"line_no": 10,
"char_start": 395,
"char_end": 420,
"line": " for wwn in wwns:\n"
},
{
"line_no": 11,
"char_start": 420,
"char_end": 452,
"line": " command.append(wwn)\n"
},
{
"line_no": 12,
"char_start": 452,
"char_end": 453,
"line": "\n"
},
{
"line_no": 13,
"char_start": 453,
"char_end": 497,
"line": " out = self.common._cli_run(command)\n"
}
]
} | {
"deleted": [
{
"char_start": 297,
"char_end": 308,
"chars": "out = self."
},
{
"char_start": 312,
"char_end": 313,
"chars": "o"
},
{
"char_start": 314,
"char_end": 324,
"chars": "._cli_run("
},
{
"char_start": 345,
"char_end": 346,
"chars": "%"
},
{
"char_start": 356,
"char_end": 365,
"chars": "%s %s %s'"
},
{
"char_start": 366,
"char_end": 373,
"chars": " "
},
{
"char_start": 392,
"char_end": 407,
"chars": " % (per"
},
{
"char_start": 408,
"char_end": 409,
"chars": "o"
},
{
"char_start": 411,
"char_end": 418,
"chars": "_id, do"
},
{
"char_start": 419,
"char_end": 423,
"chars": "ain,"
},
{
"char_start": 456,
"char_end": 461,
"chars": " "
},
{
"char_start": 462,
"char_end": 464,
"chars": "ho"
},
{
"char_start": 465,
"char_end": 469,
"chars": "tnam"
},
{
"char_start": 470,
"char_end": 475,
"chars": ", \" \""
},
{
"char_start": 476,
"char_end": 477,
"chars": "j"
},
{
"char_start": 481,
"char_end": 489,
"chars": "wwn)), N"
},
{
"char_start": 491,
"char_end": 492,
"chars": "e"
}
],
"added": [
{
"char_start": 55,
"char_end": 56,
"chars": "s"
},
{
"char_start": 302,
"char_end": 303,
"chars": "a"
},
{
"char_start": 304,
"char_end": 309,
"chars": "d = ["
},
{
"char_start": 320,
"char_end": 322,
"chars": "',"
},
{
"char_start": 323,
"char_end": 324,
"chars": "'"
},
{
"char_start": 332,
"char_end": 334,
"chars": "',"
},
{
"char_start": 335,
"char_end": 338,
"chars": "per"
},
{
"char_start": 339,
"char_end": 346,
"chars": "ona_id,"
},
{
"char_start": 347,
"char_end": 348,
"chars": "'"
},
{
"char_start": 355,
"char_end": 357,
"chars": "',"
},
{
"char_start": 358,
"char_end": 365,
"chars": "domain,"
},
{
"char_start": 385,
"char_end": 387,
"chars": "ho"
},
{
"char_start": 388,
"char_end": 389,
"chars": "t"
},
{
"char_start": 392,
"char_end": 394,
"chars": "e]"
},
{
"char_start": 403,
"char_end": 406,
"chars": "for"
},
{
"char_start": 407,
"char_end": 410,
"chars": "wwn"
},
{
"char_start": 411,
"char_end": 413,
"chars": "in"
},
{
"char_start": 414,
"char_end": 420,
"chars": "wwns:\n"
},
{
"char_start": 432,
"char_end": 453,
"chars": "command.append(wwn)\n\n"
},
{
"char_start": 462,
"char_end": 463,
"chars": "u"
},
{
"char_start": 465,
"char_end": 466,
"chars": "="
},
{
"char_start": 467,
"char_end": 471,
"chars": "self"
},
{
"char_start": 472,
"char_end": 476,
"chars": "comm"
},
{
"char_start": 477,
"char_end": 482,
"chars": "n._cl"
},
{
"char_start": 483,
"char_end": 486,
"chars": "_ru"
},
{
"char_start": 488,
"char_end": 489,
"chars": "c"
},
{
"char_start": 490,
"char_end": 493,
"chars": "mma"
},
{
"char_start": 494,
"char_end": 495,
"chars": "d"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_fc.py | cwe-078 |
take_bug_report | def take_bug_report(self, test_name, begin_time):
"""Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test case that triggered this bug report.
begin_time: Logline format timestamp taken when the test started.
"""
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
# This check is necessary for builds before N, where adb shell's ret
# code and stderr are not propagated properly.
if 'not found' in stdout:
new_br = False
except adb.AdbError:
new_br = False
br_path = os.path.join(self.log_path, 'BugReports')
utils.create_dir(br_path)
base_name = ',%s,%s.txt' % (begin_time, self.serial)
if new_br:
base_name = base_name.replace('.txt', '.zip')
test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
out_name = test_name[:test_name_len] + base_name
full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
# in case device restarted, wait for adb interface to return
self.wait_for_boot_completion()
self.log.info('Taking bugreport for %s.', test_name)
if new_br:
out = self.adb.shell('bugreportz').decode('utf-8')
if not out.startswith('OK'):
raise DeviceError(self, 'Failed to take bugreport: %s' % out)
br_out_path = out.split(':')[1].strip()
self.adb.pull('%s %s' % (br_out_path, full_out_path))
else:
self.adb.bugreport(' > %s' % full_out_path)
self.log.info('Bugreport for %s taken at %s.', test_name,
full_out_path) | def take_bug_report(self, test_name, begin_time):
"""Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test case that triggered this bug report.
begin_time: Logline format timestamp taken when the test started.
"""
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
# This check is necessary for builds before N, where adb shell's ret
# code and stderr are not propagated properly.
if 'not found' in stdout:
new_br = False
except adb.AdbError:
new_br = False
br_path = os.path.join(self.log_path, 'BugReports')
utils.create_dir(br_path)
base_name = ',%s,%s.txt' % (begin_time, self.serial)
if new_br:
base_name = base_name.replace('.txt', '.zip')
test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
out_name = test_name[:test_name_len] + base_name
full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
# in case device restarted, wait for adb interface to return
self.wait_for_boot_completion()
self.log.info('Taking bugreport for %s.', test_name)
if new_br:
out = self.adb.shell('bugreportz').decode('utf-8')
if not out.startswith('OK'):
raise DeviceError(self, 'Failed to take bugreport: %s' % out)
br_out_path = out.split(':')[1].strip()
self.adb.pull([br_out_path, full_out_path])
else:
# shell=True as this command redirects the stdout to a local file
# using shell redirection.
self.adb.bugreport(' > %s' % full_out_path, shell=True)
self.log.info('Bugreport for %s taken at %s.', test_name,
full_out_path) | {
"deleted": [
{
"line_no": 33,
"char_start": 1526,
"char_end": 1592,
"line": " self.adb.pull('%s %s' % (br_out_path, full_out_path))\n"
},
{
"line_no": 35,
"char_start": 1606,
"char_end": 1662,
"line": " self.adb.bugreport(' > %s' % full_out_path)\n"
}
],
"added": [
{
"line_no": 33,
"char_start": 1526,
"char_end": 1582,
"line": " self.adb.pull([br_out_path, full_out_path])\n"
},
{
"line_no": 37,
"char_start": 1713,
"char_end": 1781,
"line": " self.adb.bugreport(' > %s' % full_out_path, shell=True)\n"
}
]
} | {
"deleted": [
{
"char_start": 1552,
"char_end": 1563,
"chars": "'%s %s' % ("
},
{
"char_start": 1589,
"char_end": 1590,
"chars": ")"
}
],
"added": [
{
"char_start": 1552,
"char_end": 1553,
"chars": "["
},
{
"char_start": 1579,
"char_end": 1580,
"chars": "]"
},
{
"char_start": 1608,
"char_end": 1725,
"chars": "# shell=True as this command redirects the stdout to a local file\n # using shell redirection.\n "
},
{
"char_start": 1767,
"char_end": 1779,
"chars": ", shell=True"
}
]
} | github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee | mobly/controllers/android_device.py | cwe-078 |
test_create_invalid_host | def test_create_invalid_host(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
self.fake_get_cpg)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
self.fake_get_domain)
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_host_cmd = 'showhost -verbose fakehost'
_run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])
create_host_cmd = ('createhost -iscsi -persona 1 -domain '
'(\'OpenStack\',) '
'fakehost iqn.1993-08.org.debian:01:222')
in_use_ret = pack('\r\nalready used by host fakehost.foo ')
_run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])
show_3par_cmd = 'showhost -verbose fakehost.foo'
_run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])
self.mox.ReplayAll()
host = self.driver._create_host(self.volume, self.connector)
self.assertEquals(host['name'], 'fakehost.foo') | def test_create_invalid_host(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
self.fake_get_cpg)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
self.fake_get_domain)
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_host_cmd = ['showhost', '-verbose', 'fakehost']
_run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])
create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',
('OpenStack',), 'fakehost',
'iqn.1993-08.org.debian:01:222'])
in_use_ret = pack('\r\nalready used by host fakehost.foo ')
_run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])
show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']
_run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])
self.mox.ReplayAll()
host = self.driver._create_host(self.volume, self.connector)
self.assertEquals(host['name'], 'fakehost.foo') | {
"deleted": [
{
"line_no": 13,
"char_start": 505,
"char_end": 558,
"line": " show_host_cmd = 'showhost -verbose fakehost'\n"
},
{
"line_no": 16,
"char_start": 639,
"char_end": 706,
"line": " create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n"
},
{
"line_no": 17,
"char_start": 706,
"char_end": 753,
"line": " '(\\'OpenStack\\',) '\n"
},
{
"line_no": 18,
"char_start": 753,
"char_end": 822,
"line": " 'fakehost iqn.1993-08.org.debian:01:222')\n"
},
{
"line_no": 22,
"char_start": 960,
"char_end": 1017,
"line": " show_3par_cmd = 'showhost -verbose fakehost.foo'\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 505,
"char_end": 566,
"line": " show_host_cmd = ['showhost', '-verbose', 'fakehost']\n"
},
{
"line_no": 16,
"char_start": 647,
"char_end": 727,
"line": " create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n"
},
{
"line_no": 17,
"char_start": 727,
"char_end": 782,
"line": " ('OpenStack',), 'fakehost',\n"
},
{
"line_no": 18,
"char_start": 782,
"char_end": 844,
"line": " 'iqn.1993-08.org.debian:01:222'])\n"
},
{
"line_no": 22,
"char_start": 982,
"char_end": 1047,
"line": " show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n"
}
]
} | {
"deleted": [
{
"char_start": 703,
"char_end": 704,
"chars": " "
},
{
"char_start": 733,
"char_end": 734,
"chars": "'"
},
{
"char_start": 735,
"char_end": 736,
"chars": "\\"
},
{
"char_start": 746,
"char_end": 747,
"chars": "\\"
},
{
"char_start": 780,
"char_end": 789,
"chars": "'fakehost"
}
],
"added": [
{
"char_start": 529,
"char_end": 530,
"chars": "["
},
{
"char_start": 539,
"char_end": 541,
"chars": "',"
},
{
"char_start": 542,
"char_end": 543,
"chars": "'"
},
{
"char_start": 551,
"char_end": 553,
"chars": "',"
},
{
"char_start": 554,
"char_end": 555,
"chars": "'"
},
{
"char_start": 564,
"char_end": 565,
"chars": "]"
},
{
"char_start": 674,
"char_end": 675,
"chars": "["
},
{
"char_start": 686,
"char_end": 688,
"chars": "',"
},
{
"char_start": 689,
"char_end": 690,
"chars": "'"
},
{
"char_start": 696,
"char_end": 698,
"chars": "',"
},
{
"char_start": 699,
"char_end": 700,
"chars": "'"
},
{
"char_start": 708,
"char_end": 710,
"chars": "',"
},
{
"char_start": 711,
"char_end": 712,
"chars": "'"
},
{
"char_start": 713,
"char_end": 715,
"chars": "',"
},
{
"char_start": 716,
"char_end": 717,
"chars": "'"
},
{
"char_start": 725,
"char_end": 726,
"chars": ","
},
{
"char_start": 768,
"char_end": 769,
"chars": ","
},
{
"char_start": 771,
"char_end": 781,
"chars": "fakehost',"
},
{
"char_start": 782,
"char_end": 783,
"chars": " "
},
{
"char_start": 841,
"char_end": 842,
"chars": "]"
},
{
"char_start": 1006,
"char_end": 1007,
"chars": "["
},
{
"char_start": 1016,
"char_end": 1018,
"chars": "',"
},
{
"char_start": 1019,
"char_end": 1020,
"chars": "'"
},
{
"char_start": 1028,
"char_end": 1030,
"chars": "',"
},
{
"char_start": 1031,
"char_end": 1032,
"chars": "'"
},
{
"char_start": 1045,
"char_end": 1046,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/tests/test_hp3par.py | cwe-078 |
__getattr__.adb_call | def adb_call(*args):
clean_name = name.replace('_', '-')
arg_str = ' '.join(str(elem) for elem in args)
return self._exec_adb_cmd(clean_name, arg_str) | def adb_call(args=None, shell=False):
"""Wrapper for an ADB command.
Args:
args: string or list of strings, arguments to the adb command.
See subprocess.Proc() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
Returns:
The output of the adb command run if exit code is 0.
"""
args = args or ''
clean_name = name.replace('_', '-')
return self._exec_adb_cmd(clean_name, args, shell=shell) | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 29,
"line": " def adb_call(*args):\n"
},
{
"line_no": 3,
"char_start": 77,
"char_end": 136,
"line": " arg_str = ' '.join(str(elem) for elem in args)\n"
},
{
"line_no": 4,
"char_start": 136,
"char_end": 194,
"line": " return self._exec_adb_cmd(clean_name, arg_str)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 46,
"line": " def adb_call(args=None, shell=False):\n"
},
{
"line_no": 2,
"char_start": 46,
"char_end": 89,
"line": " \"\"\"Wrapper for an ADB command.\n"
},
{
"line_no": 3,
"char_start": 89,
"char_end": 90,
"line": "\n"
},
{
"line_no": 4,
"char_start": 90,
"char_end": 108,
"line": " Args:\n"
},
{
"line_no": 5,
"char_start": 108,
"char_end": 187,
"line": " args: string or list of strings, arguments to the adb command.\n"
},
{
"line_no": 6,
"char_start": 187,
"char_end": 244,
"line": " See subprocess.Proc() documentation.\n"
},
{
"line_no": 7,
"char_start": 244,
"char_end": 324,
"line": " shell: bool, True to run this command through the system shell,\n"
},
{
"line_no": 8,
"char_start": 324,
"char_end": 401,
"line": " False to invoke it directly. See subprocess.Proc() docs.\n"
},
{
"line_no": 9,
"char_start": 401,
"char_end": 402,
"line": "\n"
},
{
"line_no": 10,
"char_start": 402,
"char_end": 423,
"line": " Returns:\n"
},
{
"line_no": 11,
"char_start": 423,
"char_end": 492,
"line": " The output of the adb command run if exit code is 0.\n"
},
{
"line_no": 12,
"char_start": 492,
"char_end": 508,
"line": " \"\"\"\n"
},
{
"line_no": 13,
"char_start": 508,
"char_end": 538,
"line": " args = args or ''\n"
},
{
"line_no": 15,
"char_start": 586,
"char_end": 654,
"line": " return self._exec_adb_cmd(clean_name, args, shell=shell)\n"
}
]
} | {
"deleted": [
{
"char_start": 21,
"char_end": 22,
"chars": "*"
},
{
"char_start": 42,
"char_end": 44,
"chars": "le"
},
{
"char_start": 46,
"char_end": 47,
"chars": "_"
},
{
"char_start": 52,
"char_end": 53,
"chars": "="
},
{
"char_start": 54,
"char_end": 55,
"chars": "n"
},
{
"char_start": 58,
"char_end": 60,
"chars": ".r"
},
{
"char_start": 62,
"char_end": 64,
"chars": "la"
},
{
"char_start": 67,
"char_end": 71,
"chars": "'_',"
},
{
"char_start": 72,
"char_end": 76,
"chars": "'-')"
},
{
"char_start": 92,
"char_end": 93,
"chars": "_"
},
{
"char_start": 95,
"char_end": 96,
"chars": "r"
},
{
"char_start": 97,
"char_end": 98,
"chars": "="
},
{
"char_start": 99,
"char_end": 100,
"chars": "'"
},
{
"char_start": 101,
"char_end": 104,
"chars": "'.j"
},
{
"char_start": 107,
"char_end": 109,
"chars": "(s"
},
{
"char_start": 111,
"char_end": 112,
"chars": "("
},
{
"char_start": 115,
"char_end": 116,
"chars": "m"
},
{
"char_start": 123,
"char_end": 124,
"chars": "l"
},
{
"char_start": 125,
"char_end": 126,
"chars": "m"
},
{
"char_start": 128,
"char_end": 129,
"chars": "n"
},
{
"char_start": 189,
"char_end": 190,
"chars": "_"
},
{
"char_start": 191,
"char_end": 193,
"chars": "tr"
}
],
"added": [
{
"char_start": 25,
"char_end": 43,
"chars": "=None, shell=False"
},
{
"char_start": 58,
"char_end": 66,
"chars": "\"\"\"Wrapp"
},
{
"char_start": 67,
"char_end": 73,
"chars": "r for "
},
{
"char_start": 75,
"char_end": 85,
"chars": " ADB comma"
},
{
"char_start": 86,
"char_end": 124,
"chars": "d.\n\n Args:\n "
},
{
"char_start": 125,
"char_end": 144,
"chars": "rgs: string or list"
},
{
"char_start": 145,
"char_end": 147,
"chars": "of"
},
{
"char_start": 148,
"char_end": 152,
"chars": "stri"
},
{
"char_start": 153,
"char_end": 157,
"chars": "gs, "
},
{
"char_start": 158,
"char_end": 161,
"chars": "rgu"
},
{
"char_start": 163,
"char_end": 185,
"chars": "nts to the adb command"
},
{
"char_start": 186,
"char_end": 208,
"chars": "\n S"
},
{
"char_start": 209,
"char_end": 214,
"chars": "e sub"
},
{
"char_start": 215,
"char_end": 217,
"chars": "ro"
},
{
"char_start": 219,
"char_end": 226,
"chars": "ss.Proc"
},
{
"char_start": 227,
"char_end": 228,
"chars": ")"
},
{
"char_start": 229,
"char_end": 243,
"chars": "documentation."
},
{
"char_start": 244,
"char_end": 249,
"chars": " "
},
{
"char_start": 260,
"char_end": 284,
"chars": "shell: bool, True to run"
},
{
"char_start": 285,
"char_end": 294,
"chars": "this comm"
},
{
"char_start": 295,
"char_end": 300,
"chars": "nd th"
},
{
"char_start": 301,
"char_end": 303,
"chars": "ou"
},
{
"char_start": 304,
"char_end": 312,
"chars": "h the sy"
},
{
"char_start": 314,
"char_end": 339,
"chars": "em shell,\n "
},
{
"char_start": 342,
"char_end": 351,
"chars": " False t"
},
{
"char_start": 352,
"char_end": 353,
"chars": " "
},
{
"char_start": 355,
"char_end": 361,
"chars": "voke i"
},
{
"char_start": 362,
"char_end": 365,
"chars": " di"
},
{
"char_start": 367,
"char_end": 369,
"chars": "ct"
},
{
"char_start": 370,
"char_end": 374,
"chars": "y. S"
},
{
"char_start": 375,
"char_end": 393,
"chars": "e subprocess.Proc("
},
{
"char_start": 395,
"char_end": 396,
"chars": "d"
},
{
"char_start": 397,
"char_end": 418,
"chars": "cs.\n\n Retu"
},
{
"char_start": 419,
"char_end": 426,
"chars": "ns:\n "
},
{
"char_start": 427,
"char_end": 441,
"chars": " Th"
},
{
"char_start": 442,
"char_end": 455,
"chars": " output of th"
},
{
"char_start": 456,
"char_end": 463,
"chars": " adb co"
},
{
"char_start": 464,
"char_end": 472,
"chars": "mand run"
},
{
"char_start": 474,
"char_end": 519,
"chars": "f exit code is 0.\n \"\"\"\n "
},
{
"char_start": 524,
"char_end": 584,
"chars": " = args or ''\n clean_name = name.replace('_', '-'"
},
{
"char_start": 639,
"char_end": 648,
"chars": "s, shell="
},
{
"char_start": 649,
"char_end": 653,
"chars": "hell"
}
]
} | github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee | mobly/controllers/android_device_lib/adb.py | cwe-078 |
test_skip_paths_issue_938 | def test_skip_paths_issue_938(tmpdir):
base_dir = tmpdir.mkdir('project')
config_dir = base_dir.mkdir('conf')
config_dir.join('.isort.cfg').write('[isort]\n'
'line_length = 88\n'
'multi_line_output = 4\n'
'lines_after_imports = 2\n'
'skip_glob =\n'
' migrations/**.py\n')
base_dir.join('dont_skip.py').write('import os\n'
'\n'
'print("Hello World")'
'\n'
'import sys\n')
migrations_dir = base_dir.mkdir('migrations')
migrations_dir.join('file_glob_skip.py').write('import os\n'
'\n'
'print("Hello World")\n'
'\n'
'import sys\n')
test_run_directory = os.getcwd()
os.chdir(str(base_dir))
results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])
os.chdir(str(test_run_directory))
assert b'skipped' not in results.lower()
os.chdir(str(base_dir))
results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])
os.chdir(str(test_run_directory))
assert b'skipped 1' in results.lower() | def test_skip_paths_issue_938(tmpdir):
base_dir = tmpdir.mkdir('project')
config_dir = base_dir.mkdir('conf')
config_dir.join('.isort.cfg').write('[isort]\n'
'line_length = 88\n'
'multi_line_output = 4\n'
'lines_after_imports = 2\n'
'skip_glob =\n'
' migrations/**.py\n')
base_dir.join('dont_skip.py').write('import os\n'
'\n'
'print("Hello World")'
'\n'
'import sys\n')
migrations_dir = base_dir.mkdir('migrations')
migrations_dir.join('file_glob_skip.py').write('import os\n'
'\n'
'print("Hello World")\n'
'\n'
'import sys\n')
test_run_directory = os.getcwd()
os.chdir(str(base_dir))
result = subprocess.run(
['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],
stdout=subprocess.PIPE,
check=True,
)
os.chdir(str(test_run_directory))
assert b'skipped' not in result.stdout.lower()
os.chdir(str(base_dir))
result = subprocess.run(
['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],
stdout=subprocess.PIPE,
check=True,
)
os.chdir(str(test_run_directory))
assert b'skipped 1' in result.stdout.lower() | {
"deleted": [
{
"line_no": 25,
"char_start": 1187,
"char_end": 1273,
"line": " results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n"
},
{
"line_no": 28,
"char_start": 1312,
"char_end": 1357,
"line": " assert b'skipped' not in results.lower()\n"
},
{
"line_no": 31,
"char_start": 1386,
"char_end": 1525,
"line": " results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n"
},
{
"line_no": 34,
"char_start": 1564,
"char_end": 1606,
"line": " assert b'skipped 1' in results.lower()\n"
}
],
"added": [
{
"line_no": 25,
"char_start": 1187,
"char_end": 1216,
"line": " result = subprocess.run(\n"
},
{
"line_no": 26,
"char_start": 1216,
"char_end": 1283,
"line": " ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n"
},
{
"line_no": 27,
"char_start": 1283,
"char_end": 1315,
"line": " stdout=subprocess.PIPE,\n"
},
{
"line_no": 28,
"char_start": 1315,
"char_end": 1335,
"line": " check=True,\n"
},
{
"line_no": 29,
"char_start": 1335,
"char_end": 1341,
"line": " )\n"
},
{
"line_no": 32,
"char_start": 1380,
"char_end": 1431,
"line": " assert b'skipped' not in result.stdout.lower()\n"
},
{
"line_no": 35,
"char_start": 1460,
"char_end": 1489,
"line": " result = subprocess.run(\n"
},
{
"line_no": 36,
"char_start": 1489,
"char_end": 1609,
"line": " ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n"
},
{
"line_no": 37,
"char_start": 1609,
"char_end": 1641,
"line": " stdout=subprocess.PIPE,\n"
},
{
"line_no": 38,
"char_start": 1641,
"char_end": 1661,
"line": " check=True,\n"
},
{
"line_no": 39,
"char_start": 1661,
"char_end": 1667,
"line": " )\n"
},
{
"line_no": 42,
"char_start": 1706,
"char_end": 1754,
"line": " assert b'skipped 1' in result.stdout.lower()\n"
}
]
} | {
"deleted": [
{
"char_start": 1197,
"char_end": 1198,
"chars": "s"
},
{
"char_start": 1202,
"char_end": 1203,
"chars": "h"
},
{
"char_start": 1204,
"char_end": 1211,
"chars": "ck_outp"
},
{
"char_start": 1212,
"char_end": 1213,
"chars": "t"
},
{
"char_start": 1396,
"char_end": 1397,
"chars": "s"
},
{
"char_start": 1401,
"char_end": 1402,
"chars": "h"
},
{
"char_start": 1403,
"char_end": 1410,
"chars": "ck_outp"
},
{
"char_start": 1411,
"char_end": 1412,
"chars": "t"
}
],
"added": [
{
"char_start": 1200,
"char_end": 1206,
"chars": "subpro"
},
{
"char_start": 1208,
"char_end": 1212,
"chars": "ss.r"
},
{
"char_start": 1213,
"char_end": 1214,
"chars": "n"
},
{
"char_start": 1215,
"char_end": 1224,
"chars": "\n "
},
{
"char_start": 1281,
"char_end": 1339,
"chars": ",\n stdout=subprocess.PIPE,\n check=True,\n "
},
{
"char_start": 1415,
"char_end": 1416,
"chars": "."
},
{
"char_start": 1417,
"char_end": 1422,
"chars": "tdout"
},
{
"char_start": 1473,
"char_end": 1479,
"chars": "subpro"
},
{
"char_start": 1481,
"char_end": 1485,
"chars": "ss.r"
},
{
"char_start": 1486,
"char_end": 1487,
"chars": "n"
},
{
"char_start": 1488,
"char_end": 1497,
"chars": "\n "
},
{
"char_start": 1607,
"char_end": 1665,
"chars": ",\n stdout=subprocess.PIPE,\n check=True,\n "
},
{
"char_start": 1739,
"char_end": 1740,
"chars": "."
},
{
"char_start": 1741,
"char_end": 1746,
"chars": "tdout"
}
]
} | github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76 | test_isort.py | cwe-078 |
_ensure_vdisk_no_fc_mappings | def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):
# Ensure vdisk has no FlashCopy mappings
mapping_ids = self._get_vdisk_fc_mappings(name)
while len(mapping_ids):
wait_for_copy = False
for map_id in mapping_ids:
attrs = self._get_flashcopy_mapping_attributes(map_id)
if not attrs:
continue
source = attrs['source_vdisk_name']
target = attrs['target_vdisk_name']
copy_rate = attrs['copy_rate']
status = attrs['status']
if copy_rate == '0':
# Case #2: A vdisk that has snapshots
if source == name:
if not allow_snaps:
return False
ssh_cmd = ('svctask chfcmap -copyrate 50 '
'-autodelete on %s' % map_id)
out, err = self._run_ssh(ssh_cmd)
wait_for_copy = True
# Case #3: A snapshot
else:
msg = (_('Vdisk %(name)s not involved in '
'mapping %(src)s -> %(tgt)s') %
{'name': name, 'src': source, 'tgt': target})
self._driver_assert(target == name, msg)
if status in ['copying', 'prepared']:
self._run_ssh('svctask stopfcmap %s' % map_id)
elif status in ['stopping', 'preparing']:
wait_for_copy = True
else:
self._run_ssh('svctask rmfcmap -force %s' % map_id)
# Case 4: Copy in progress - wait and will autodelete
else:
if status == 'prepared':
self._run_ssh('svctask stopfcmap %s' % map_id)
self._run_ssh('svctask rmfcmap -force %s' % map_id)
elif status == 'idle_or_copied':
# Prepare failed
self._run_ssh('svctask rmfcmap -force %s' % map_id)
else:
wait_for_copy = True
if wait_for_copy:
time.sleep(5)
mapping_ids = self._get_vdisk_fc_mappings(name)
return True | def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):
# Ensure vdisk has no FlashCopy mappings
mapping_ids = self._get_vdisk_fc_mappings(name)
while len(mapping_ids):
wait_for_copy = False
for map_id in mapping_ids:
attrs = self._get_flashcopy_mapping_attributes(map_id)
if not attrs:
continue
source = attrs['source_vdisk_name']
target = attrs['target_vdisk_name']
copy_rate = attrs['copy_rate']
status = attrs['status']
if copy_rate == '0':
# Case #2: A vdisk that has snapshots
if source == name:
if not allow_snaps:
return False
ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',
'-autodelete', 'on', map_id]
out, err = self._run_ssh(ssh_cmd)
wait_for_copy = True
# Case #3: A snapshot
else:
msg = (_('Vdisk %(name)s not involved in '
'mapping %(src)s -> %(tgt)s') %
{'name': name, 'src': source, 'tgt': target})
self._driver_assert(target == name, msg)
if status in ['copying', 'prepared']:
self._run_ssh(['svctask', 'stopfcmap', map_id])
elif status in ['stopping', 'preparing']:
wait_for_copy = True
else:
self._run_ssh(['svctask', 'rmfcmap', '-force',
map_id])
# Case 4: Copy in progress - wait and will autodelete
else:
if status == 'prepared':
self._run_ssh(['svctask', 'stopfcmap', map_id])
self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])
elif status == 'idle_or_copied':
# Prepare failed
self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])
else:
wait_for_copy = True
if wait_for_copy:
time.sleep(5)
mapping_ids = self._get_vdisk_fc_mappings(name)
return True | {
"deleted": [
{
"line_no": 20,
"char_start": 820,
"char_end": 887,
"line": " ssh_cmd = ('svctask chfcmap -copyrate 50 '\n"
},
{
"line_no": 21,
"char_start": 887,
"char_end": 952,
"line": " '-autodelete on %s' % map_id)\n"
},
{
"line_no": 31,
"char_start": 1459,
"char_end": 1534,
"line": " self._run_ssh('svctask stopfcmap %s' % map_id)\n"
},
{
"line_no": 35,
"char_start": 1679,
"char_end": 1759,
"line": " self._run_ssh('svctask rmfcmap -force %s' % map_id)\n"
},
{
"line_no": 39,
"char_start": 1896,
"char_end": 1967,
"line": " self._run_ssh('svctask stopfcmap %s' % map_id)\n"
},
{
"line_no": 40,
"char_start": 1967,
"char_end": 2043,
"line": " self._run_ssh('svctask rmfcmap -force %s' % map_id)\n"
},
{
"line_no": 43,
"char_start": 2137,
"char_end": 2213,
"line": " self._run_ssh('svctask rmfcmap -force %s' % map_id)\n"
}
],
"added": [
{
"line_no": 20,
"char_start": 820,
"char_end": 896,
"line": " ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',\n"
},
{
"line_no": 21,
"char_start": 896,
"char_end": 960,
"line": " '-autodelete', 'on', map_id]\n"
},
{
"line_no": 31,
"char_start": 1467,
"char_end": 1543,
"line": " self._run_ssh(['svctask', 'stopfcmap', map_id])\n"
},
{
"line_no": 35,
"char_start": 1688,
"char_end": 1763,
"line": " self._run_ssh(['svctask', 'rmfcmap', '-force',\n"
},
{
"line_no": 36,
"char_start": 1763,
"char_end": 1815,
"line": " map_id])\n"
},
{
"line_no": 40,
"char_start": 1952,
"char_end": 2024,
"line": " self._run_ssh(['svctask', 'stopfcmap', map_id])\n"
},
{
"line_no": 41,
"char_start": 2024,
"char_end": 2104,
"line": " self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n"
},
{
"line_no": 44,
"char_start": 2198,
"char_end": 2278,
"line": " self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n"
}
]
} | {
"deleted": [
{
"char_start": 854,
"char_end": 855,
"chars": "("
},
{
"char_start": 884,
"char_end": 885,
"chars": " "
},
{
"char_start": 937,
"char_end": 940,
"chars": " %s"
},
{
"char_start": 941,
"char_end": 943,
"chars": " %"
},
{
"char_start": 950,
"char_end": 951,
"chars": ")"
},
{
"char_start": 1519,
"char_end": 1522,
"chars": " %s"
},
{
"char_start": 1523,
"char_end": 1525,
"chars": " %"
},
{
"char_start": 1745,
"char_end": 1748,
"chars": "%s'"
},
{
"char_start": 1749,
"char_end": 1750,
"chars": "%"
},
{
"char_start": 1952,
"char_end": 1955,
"chars": " %s"
},
{
"char_start": 1956,
"char_end": 1958,
"chars": " %"
},
{
"char_start": 2028,
"char_end": 2031,
"chars": " %s"
},
{
"char_start": 2032,
"char_end": 2034,
"chars": " %"
},
{
"char_start": 2198,
"char_end": 2201,
"chars": " %s"
},
{
"char_start": 2202,
"char_end": 2204,
"chars": " %"
}
],
"added": [
{
"char_start": 854,
"char_end": 855,
"chars": "["
},
{
"char_start": 863,
"char_end": 865,
"chars": "',"
},
{
"char_start": 866,
"char_end": 867,
"chars": "'"
},
{
"char_start": 874,
"char_end": 876,
"chars": "',"
},
{
"char_start": 877,
"char_end": 878,
"chars": "'"
},
{
"char_start": 887,
"char_end": 889,
"chars": "',"
},
{
"char_start": 890,
"char_end": 891,
"chars": "'"
},
{
"char_start": 894,
"char_end": 895,
"chars": ","
},
{
"char_start": 943,
"char_end": 945,
"chars": "',"
},
{
"char_start": 946,
"char_end": 947,
"chars": "'"
},
{
"char_start": 950,
"char_end": 951,
"chars": ","
},
{
"char_start": 958,
"char_end": 959,
"chars": "]"
},
{
"char_start": 1509,
"char_end": 1510,
"chars": "["
},
{
"char_start": 1518,
"char_end": 1520,
"chars": "',"
},
{
"char_start": 1521,
"char_end": 1522,
"chars": "'"
},
{
"char_start": 1532,
"char_end": 1533,
"chars": ","
},
{
"char_start": 1540,
"char_end": 1541,
"chars": "]"
},
{
"char_start": 1730,
"char_end": 1731,
"chars": "["
},
{
"char_start": 1739,
"char_end": 1741,
"chars": "',"
},
{
"char_start": 1742,
"char_end": 1743,
"chars": "'"
},
{
"char_start": 1750,
"char_end": 1752,
"chars": "',"
},
{
"char_start": 1753,
"char_end": 1754,
"chars": "'"
},
{
"char_start": 1760,
"char_end": 1767,
"chars": "',\n "
},
{
"char_start": 1768,
"char_end": 1775,
"chars": " "
},
{
"char_start": 1776,
"char_end": 1805,
"chars": " "
},
{
"char_start": 1812,
"char_end": 1813,
"chars": "]"
},
{
"char_start": 1990,
"char_end": 1991,
"chars": "["
},
{
"char_start": 1999,
"char_end": 2001,
"chars": "',"
},
{
"char_start": 2002,
"char_end": 2003,
"chars": "'"
},
{
"char_start": 2013,
"char_end": 2014,
"chars": ","
},
{
"char_start": 2021,
"char_end": 2022,
"chars": "]"
},
{
"char_start": 2062,
"char_end": 2063,
"chars": "["
},
{
"char_start": 2071,
"char_end": 2073,
"chars": "',"
},
{
"char_start": 2074,
"char_end": 2075,
"chars": "'"
},
{
"char_start": 2082,
"char_end": 2084,
"chars": "',"
},
{
"char_start": 2085,
"char_end": 2086,
"chars": "'"
},
{
"char_start": 2093,
"char_end": 2094,
"chars": ","
},
{
"char_start": 2101,
"char_end": 2102,
"chars": "]"
},
{
"char_start": 2236,
"char_end": 2237,
"chars": "["
},
{
"char_start": 2245,
"char_end": 2247,
"chars": "',"
},
{
"char_start": 2248,
"char_end": 2249,
"chars": "'"
},
{
"char_start": 2256,
"char_end": 2258,
"chars": "',"
},
{
"char_start": 2259,
"char_end": 2260,
"chars": "'"
},
{
"char_start": 2267,
"char_end": 2268,
"chars": ","
},
{
"char_start": 2275,
"char_end": 2276,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
tcp_forward | def tcp_forward(self, host_port, device_port):
"""Starts tcp forwarding.
Args:
host_port: Port number to use on the computer.
device_port: Port number to use on the android device.
"""
self.forward('tcp:%d tcp:%d' % (host_port, device_port)) | def tcp_forward(self, host_port, device_port):
"""Starts tcp forwarding.
Args:
host_port: Port number to use on the computer.
device_port: Port number to use on the android device.
"""
self.forward(['tcp:%d' % host_port, 'tcp:%d' % device_port]) | {
"deleted": [
{
"line_no": 8,
"char_start": 238,
"char_end": 302,
"line": " self.forward('tcp:%d tcp:%d' % (host_port, device_port))\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 238,
"char_end": 306,
"line": " self.forward(['tcp:%d' % host_port, 'tcp:%d' % device_port])\n"
}
]
} | {
"deleted": [
{
"char_start": 266,
"char_end": 273,
"chars": " tcp:%d"
},
{
"char_start": 277,
"char_end": 278,
"chars": "("
},
{
"char_start": 300,
"char_end": 301,
"chars": ")"
}
],
"added": [
{
"char_start": 259,
"char_end": 260,
"chars": "["
},
{
"char_start": 282,
"char_end": 293,
"chars": "'tcp:%d' % "
},
{
"char_start": 304,
"char_end": 305,
"chars": "]"
}
]
} | github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee | mobly/controllers/android_device_lib/adb.py | cwe-078 |
repack | def repack(host, targets, channel='stable'):
url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'
req = requests.get(url)
req.raise_for_status()
manifest = toml.loads(req.content)
if manifest['manifest-version'] != '2':
print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])
return
print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))
rustc_version, rustc = package(manifest, 'rustc', host)
if rustc['available']:
print('rustc %s\n %s\n %s' % (rustc_version, rustc['url'], rustc['hash']))
fetch(rustc['url'])
cargo_version, cargo = package(manifest, 'cargo', host)
if cargo['available']:
print('cargo %s\n %s\n %s' % (cargo_version, cargo['url'], cargo['hash']))
fetch(cargo['url'])
stds = []
for target in targets:
version, info = package(manifest, 'rust-std', target)
if info['available']:
print('rust-std %s\n %s\n %s' % (version, info['url'], info['hash']))
fetch(info['url'])
stds.append(info)
print('Installing packages...')
tar_basename = 'rustc-%s-repack' % host
install_dir = 'rustc'
os.system('rm -rf %s' % install_dir)
install(os.path.basename(rustc['url']), install_dir)
install(os.path.basename(cargo['url']), install_dir)
for std in stds:
install(os.path.basename(std['url']), install_dir)
print('Tarring %s...' % tar_basename)
os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))
os.system('rm -rf %s' % install_dir) | def repack(host, targets, channel='stable'):
print("Repacking rust for %s..." % host)
url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'
req = requests.get(url)
req.raise_for_status()
manifest = toml.loads(req.content)
if manifest['manifest-version'] != '2':
print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])
return
print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))
rustc_version, rustc = package(manifest, 'rustc', host)
if rustc['available']:
print('rustc %s\n %s\n %s' % (rustc_version, rustc['url'], rustc['hash']))
fetch(rustc['url'])
cargo_version, cargo = package(manifest, 'cargo', host)
if cargo['available']:
print('cargo %s\n %s\n %s' % (cargo_version, cargo['url'], cargo['hash']))
fetch(cargo['url'])
stds = []
for target in targets:
version, info = package(manifest, 'rust-std', target)
if info['available']:
print('rust-std %s\n %s\n %s' % (version, info['url'], info['hash']))
fetch(info['url'])
stds.append(info)
print('Installing packages...')
tar_basename = 'rustc-%s-repack' % host
install_dir = 'rustc'
subprocess.check_call(['rm', '-rf', install_dir])
install(os.path.basename(rustc['url']), install_dir)
install(os.path.basename(cargo['url']), install_dir)
for std in stds:
install(os.path.basename(std['url']), install_dir)
print('Tarring %s...' % tar_basename)
subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])
subprocess.check_call(['rm', '-rf', install_dir]) | {
"deleted": [
{
"line_no": 28,
"char_start": 1161,
"char_end": 1200,
"line": " os.system('rm -rf %s' % install_dir)\n"
},
{
"line_no": 34,
"char_start": 1424,
"char_end": 1493,
"line": " os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))\n"
},
{
"line_no": 35,
"char_start": 1493,
"char_end": 1531,
"line": " os.system('rm -rf %s' % install_dir)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 45,
"char_end": 88,
"line": " print(\"Repacking rust for %s...\" % host)\n"
},
{
"line_no": 29,
"char_start": 1204,
"char_end": 1256,
"line": " subprocess.check_call(['rm', '-rf', install_dir])\n"
},
{
"line_no": 35,
"char_start": 1480,
"char_end": 1560,
"line": " subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])\n"
},
{
"line_no": 36,
"char_start": 1560,
"char_end": 1611,
"line": " subprocess.check_call(['rm', '-rf', install_dir])\n"
}
]
} | {
"deleted": [
{
"char_start": 1166,
"char_end": 1170,
"chars": "syst"
},
{
"char_start": 1171,
"char_end": 1172,
"chars": "m"
},
{
"char_start": 1180,
"char_end": 1183,
"chars": " %s"
},
{
"char_start": 1184,
"char_end": 1186,
"chars": " %"
},
{
"char_start": 1426,
"char_end": 1427,
"chars": "o"
},
{
"char_start": 1428,
"char_end": 1429,
"chars": "."
},
{
"char_start": 1430,
"char_end": 1431,
"chars": "y"
},
{
"char_start": 1432,
"char_end": 1433,
"chars": "t"
},
{
"char_start": 1434,
"char_end": 1435,
"chars": "m"
},
{
"char_start": 1444,
"char_end": 1460,
"chars": " %s.tar.bz2 %s/*"
},
{
"char_start": 1462,
"char_end": 1465,
"chars": "% ("
},
{
"char_start": 1490,
"char_end": 1491,
"chars": ")"
},
{
"char_start": 1498,
"char_end": 1502,
"chars": "syst"
},
{
"char_start": 1503,
"char_end": 1504,
"chars": "m"
},
{
"char_start": 1512,
"char_end": 1515,
"chars": " %s"
},
{
"char_start": 1516,
"char_end": 1518,
"chars": " %"
}
],
"added": [
{
"char_start": 47,
"char_end": 90,
"chars": "print(\"Repacking rust for %s...\" % host)\n "
},
{
"char_start": 1206,
"char_end": 1211,
"chars": "subpr"
},
{
"char_start": 1212,
"char_end": 1214,
"chars": "ce"
},
{
"char_start": 1216,
"char_end": 1219,
"chars": ".ch"
},
{
"char_start": 1220,
"char_end": 1227,
"chars": "ck_call"
},
{
"char_start": 1228,
"char_end": 1229,
"chars": "["
},
{
"char_start": 1232,
"char_end": 1234,
"chars": "',"
},
{
"char_start": 1235,
"char_end": 1236,
"chars": "'"
},
{
"char_start": 1240,
"char_end": 1241,
"chars": ","
},
{
"char_start": 1253,
"char_end": 1254,
"chars": "]"
},
{
"char_start": 1482,
"char_end": 1487,
"chars": "subpr"
},
{
"char_start": 1488,
"char_end": 1491,
"chars": "ces"
},
{
"char_start": 1493,
"char_end": 1495,
"chars": "ch"
},
{
"char_start": 1496,
"char_end": 1503,
"chars": "ck_call"
},
{
"char_start": 1504,
"char_end": 1505,
"chars": "["
},
{
"char_start": 1509,
"char_end": 1511,
"chars": "',"
},
{
"char_start": 1512,
"char_end": 1513,
"chars": "'"
},
{
"char_start": 1517,
"char_end": 1518,
"chars": ","
},
{
"char_start": 1531,
"char_end": 1544,
"chars": " + '.tar.bz2'"
},
{
"char_start": 1557,
"char_end": 1558,
"chars": "]"
},
{
"char_start": 1562,
"char_end": 1567,
"chars": "subpr"
},
{
"char_start": 1568,
"char_end": 1570,
"chars": "ce"
},
{
"char_start": 1572,
"char_end": 1575,
"chars": ".ch"
},
{
"char_start": 1576,
"char_end": 1583,
"chars": "ck_call"
},
{
"char_start": 1584,
"char_end": 1585,
"chars": "["
},
{
"char_start": 1588,
"char_end": 1590,
"chars": "',"
},
{
"char_start": 1591,
"char_end": 1592,
"chars": "'"
},
{
"char_start": 1596,
"char_end": 1597,
"chars": ","
},
{
"char_start": 1609,
"char_end": 1610,
"chars": "]"
}
]
} | github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb | repack_rust.py | cwe-078 |
extend_volume | def extend_volume(self, volume, new_size):
volume_name = self._get_3par_vol_name(volume['id'])
old_size = volume.size
growth_size = int(new_size) - old_size
LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
(volume_name, old_size, new_size, growth_size))
try:
self._cli_run("growvv -f %s %sg" % (volume_name, growth_size),
None)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_("Error extending volume %s") % volume) | def extend_volume(self, volume, new_size):
volume_name = self._get_3par_vol_name(volume['id'])
old_size = volume.size
growth_size = int(new_size) - old_size
LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
(volume_name, old_size, new_size, growth_size))
try:
self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_("Error extending volume %s") % volume) | {
"deleted": [
{
"line_no": 8,
"char_start": 331,
"char_end": 406,
"line": " self._cli_run(\"growvv -f %s %sg\" % (volume_name, growth_size),\n"
},
{
"line_no": 9,
"char_start": 406,
"char_end": 438,
"line": " None)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 331,
"char_end": 409,
"line": " self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])\n"
}
]
} | {
"deleted": [
{
"char_start": 357,
"char_end": 358,
"chars": "\""
},
{
"char_start": 367,
"char_end": 375,
"chars": " %s %sg\""
},
{
"char_start": 376,
"char_end": 379,
"chars": "% ("
},
{
"char_start": 403,
"char_end": 436,
"chars": "),\n None"
}
],
"added": [
{
"char_start": 357,
"char_end": 359,
"chars": "['"
},
{
"char_start": 365,
"char_end": 367,
"chars": "',"
},
{
"char_start": 368,
"char_end": 369,
"chars": "'"
},
{
"char_start": 371,
"char_end": 373,
"chars": "',"
},
{
"char_start": 387,
"char_end": 395,
"chars": "'%dg' % "
},
{
"char_start": 406,
"char_end": 407,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
_remove_volume_set | def _remove_volume_set(self, vvs_name):
# Must first clear the QoS rules before removing the volume set
self._cli_run('setqos -clear vvset:%s' % (vvs_name), None)
self._cli_run('removevvset -f %s' % (vvs_name), None) | def _remove_volume_set(self, vvs_name):
# Must first clear the QoS rules before removing the volume set
self._cli_run(['setqos', '-clear', 'vvset:%s' % (vvs_name)])
self._cli_run(['removevvset', '-f', vvs_name]) | {
"deleted": [
{
"line_no": 3,
"char_start": 116,
"char_end": 183,
"line": " self._cli_run('setqos -clear vvset:%s' % (vvs_name), None)\n"
},
{
"line_no": 4,
"char_start": 183,
"char_end": 244,
"line": " self._cli_run('removevvset -f %s' % (vvs_name), None)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 116,
"char_end": 185,
"line": " self._cli_run(['setqos', '-clear', 'vvset:%s' % (vvs_name)])\n"
},
{
"line_no": 4,
"char_start": 185,
"char_end": 239,
"line": " self._cli_run(['removevvset', '-f', vvs_name])\n"
}
]
} | {
"deleted": [
{
"char_start": 175,
"char_end": 181,
"chars": ", None"
},
{
"char_start": 220,
"char_end": 223,
"chars": " %s"
},
{
"char_start": 224,
"char_end": 226,
"chars": " %"
},
{
"char_start": 227,
"char_end": 228,
"chars": "("
},
{
"char_start": 236,
"char_end": 243,
"chars": "), None"
}
],
"added": [
{
"char_start": 138,
"char_end": 139,
"chars": "["
},
{
"char_start": 146,
"char_end": 148,
"chars": "',"
},
{
"char_start": 149,
"char_end": 150,
"chars": "'"
},
{
"char_start": 156,
"char_end": 158,
"chars": "',"
},
{
"char_start": 159,
"char_end": 160,
"chars": "'"
},
{
"char_start": 182,
"char_end": 183,
"chars": "]"
},
{
"char_start": 207,
"char_end": 208,
"chars": "["
},
{
"char_start": 220,
"char_end": 222,
"chars": "',"
},
{
"char_start": 223,
"char_end": 224,
"chars": "'"
},
{
"char_start": 227,
"char_end": 228,
"chars": ","
},
{
"char_start": 237,
"char_end": 238,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
_get_3par_hostname_from_wwn_iqn | def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
out = self._cli_run('showhost -d', None)
# wwns_iqn may be a list of strings or a single
# string. So, if necessary, create a list to loop.
if not isinstance(wwns_iqn, list):
wwn_iqn_list = [wwns_iqn]
else:
wwn_iqn_list = wwns_iqn
for wwn_iqn in wwn_iqn_list:
for showhost in out:
if (wwn_iqn.upper() in showhost.upper()):
return showhost.split(',')[1] | def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
out = self._cli_run(['showhost', '-d'])
# wwns_iqn may be a list of strings or a single
# string. So, if necessary, create a list to loop.
if not isinstance(wwns_iqn, list):
wwn_iqn_list = [wwns_iqn]
else:
wwn_iqn_list = wwns_iqn
for wwn_iqn in wwn_iqn_list:
for showhost in out:
if (wwn_iqn.upper() in showhost.upper()):
return showhost.split(',')[1] | {
"deleted": [
{
"line_no": 2,
"char_start": 57,
"char_end": 106,
"line": " out = self._cli_run('showhost -d', None)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 57,
"char_end": 105,
"line": " out = self._cli_run(['showhost', '-d'])\n"
}
]
} | {
"deleted": [
{
"char_start": 98,
"char_end": 104,
"chars": ", None"
}
],
"added": [
{
"char_start": 85,
"char_end": 86,
"chars": "["
},
{
"char_start": 95,
"char_end": 97,
"chars": "',"
},
{
"char_start": 98,
"char_end": 99,
"chars": "'"
},
{
"char_start": 102,
"char_end": 103,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
get_ports | def get_ports(self):
# First get the active FC ports
out = self._cli_run('showport', None)
# strip out header
# N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,
# Protocol,Label,Partner,FailoverState
out = out[1:len(out) - 2]
ports = {'FC': [], 'iSCSI': {}}
for line in out:
tmp = line.split(',')
if tmp:
if tmp[1] == 'target' and tmp[2] == 'ready':
if tmp[6] == 'FC':
ports['FC'].append(tmp[4])
# now get the active iSCSI ports
out = self._cli_run('showport -iscsi', None)
# strip out header
# N:S:P,State,IPAddr,Netmask,Gateway,
# TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port
out = out[1:len(out) - 2]
for line in out:
tmp = line.split(',')
if tmp and len(tmp) > 2:
if tmp[1] == 'ready':
ports['iSCSI'][tmp[2]] = {}
# now get the nsp and iqn
result = self._cli_run('showport -iscsiname', None)
if result:
# first line is header
# nsp, ip,iqn
result = result[1:]
for line in result:
info = line.split(",")
if info and len(info) > 2:
if info[1] in ports['iSCSI']:
nsp = info[0]
ip_addr = info[1]
iqn = info[2]
ports['iSCSI'][ip_addr] = {'nsp': nsp,
'iqn': iqn
}
LOG.debug("PORTS = %s" % pprint.pformat(ports))
return ports | def get_ports(self):
# First get the active FC ports
out = self._cli_run(['showport'])
# strip out header
# N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,
# Protocol,Label,Partner,FailoverState
out = out[1:len(out) - 2]
ports = {'FC': [], 'iSCSI': {}}
for line in out:
tmp = line.split(',')
if tmp:
if tmp[1] == 'target' and tmp[2] == 'ready':
if tmp[6] == 'FC':
ports['FC'].append(tmp[4])
# now get the active iSCSI ports
out = self._cli_run(['showport', '-iscsi'])
# strip out header
# N:S:P,State,IPAddr,Netmask,Gateway,
# TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port
out = out[1:len(out) - 2]
for line in out:
tmp = line.split(',')
if tmp and len(tmp) > 2:
if tmp[1] == 'ready':
ports['iSCSI'][tmp[2]] = {}
# now get the nsp and iqn
result = self._cli_run(['showport', '-iscsiname'])
if result:
# first line is header
# nsp, ip,iqn
result = result[1:]
for line in result:
info = line.split(",")
if info and len(info) > 2:
if info[1] in ports['iSCSI']:
nsp = info[0]
ip_addr = info[1]
iqn = info[2]
ports['iSCSI'][ip_addr] = {'nsp': nsp,
'iqn': iqn
}
LOG.debug("PORTS = %s" % pprint.pformat(ports))
return ports | {
"deleted": [
{
"line_no": 3,
"char_start": 65,
"char_end": 111,
"line": " out = self._cli_run('showport', None)\n"
},
{
"line_no": 20,
"char_start": 603,
"char_end": 656,
"line": " out = self._cli_run('showport -iscsi', None)\n"
},
{
"line_no": 34,
"char_start": 1031,
"char_end": 1091,
"line": " result = self._cli_run('showport -iscsiname', None)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 65,
"char_end": 107,
"line": " out = self._cli_run(['showport'])\n"
},
{
"line_no": 20,
"char_start": 599,
"char_end": 651,
"line": " out = self._cli_run(['showport', '-iscsi'])\n"
},
{
"line_no": 34,
"char_start": 1026,
"char_end": 1085,
"line": " result = self._cli_run(['showport', '-iscsiname'])\n"
}
]
} | {
"deleted": [
{
"char_start": 103,
"char_end": 109,
"chars": ", None"
},
{
"char_start": 648,
"char_end": 654,
"chars": ", None"
},
{
"char_start": 1083,
"char_end": 1089,
"chars": ", None"
}
],
"added": [
{
"char_start": 93,
"char_end": 94,
"chars": "["
},
{
"char_start": 104,
"char_end": 105,
"chars": "]"
},
{
"char_start": 627,
"char_end": 628,
"chars": "["
},
{
"char_start": 637,
"char_end": 639,
"chars": "',"
},
{
"char_start": 640,
"char_end": 641,
"chars": "'"
},
{
"char_start": 648,
"char_end": 649,
"chars": "]"
},
{
"char_start": 1057,
"char_end": 1058,
"chars": "["
},
{
"char_start": 1067,
"char_end": 1069,
"chars": "',"
},
{
"char_start": 1070,
"char_end": 1071,
"chars": "'"
},
{
"char_start": 1082,
"char_end": 1083,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
test_get_least_used_nsp | def test_get_least_used_nsp(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_vlun_cmd = 'showvlun -a -showcols Port'
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
self.mox.ReplayAll()
# in use count 11 12
nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])
self.assertEqual(nsp, '0:2:1')
# in use count 11 10
nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])
self.assertEqual(nsp, '1:2:1')
# in use count 0 10
nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])
self.assertEqual(nsp, '1:1:1') | def test_get_least_used_nsp(self):
self.flags(lock_path=self.tempdir)
#record
self.clear_mox()
_run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)
show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
_run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
self.mox.ReplayAll()
# in use count 11 12
nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])
self.assertEqual(nsp, '0:2:1')
# in use count 11 10
nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])
self.assertEqual(nsp, '1:2:1')
# in use count 0 10
nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])
self.assertEqual(nsp, '1:1:1') | {
"deleted": [
{
"line_no": 9,
"char_start": 282,
"char_end": 335,
"line": " show_vlun_cmd = 'showvlun -a -showcols Port'\n"
}
],
"added": [
{
"line_no": 9,
"char_start": 282,
"char_end": 346,
"line": " show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 306,
"char_end": 307,
"chars": "["
},
{
"char_start": 316,
"char_end": 318,
"chars": "',"
},
{
"char_start": 319,
"char_end": 320,
"chars": "'"
},
{
"char_start": 322,
"char_end": 324,
"chars": "',"
},
{
"char_start": 325,
"char_end": 326,
"chars": "'"
},
{
"char_start": 335,
"char_end": 337,
"chars": "',"
},
{
"char_start": 338,
"char_end": 339,
"chars": "'"
},
{
"char_start": 344,
"char_end": 345,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/tests/test_hp3par.py | cwe-078 |
_cmd_to_dict | def _cmd_to_dict(self, cmd):
arg_list = cmd.split()
no_param_args = [
'autodelete',
'autoexpand',
'bytes',
'compressed',
'force',
'nohdr',
]
one_param_args = [
'chapsecret',
'cleanrate',
'copyrate',
'delim',
'filtervalue',
'grainsize',
'hbawwpn',
'host',
'iogrp',
'iscsiname',
'mdiskgrp',
'name',
'rsize',
'scsi',
'size',
'source',
'target',
'unit',
'easytier',
'warning',
'wwpn',
]
# Handle the special case of lsnode which is a two-word command
# Use the one word version of the command internally
if arg_list[0] in ('svcinfo', 'svctask'):
if arg_list[1] == 'lsnode':
if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! <node id>
ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}
else:
ret = {'cmd': 'lsnodecanister'}
else:
ret = {'cmd': arg_list[1]}
arg_list.pop(0)
else:
ret = {'cmd': arg_list[0]}
skip = False
for i in range(1, len(arg_list)):
if skip:
skip = False
continue
if arg_list[i][0] == '-':
if arg_list[i][1:] in no_param_args:
ret[arg_list[i][1:]] = True
elif arg_list[i][1:] in one_param_args:
ret[arg_list[i][1:]] = arg_list[i + 1]
skip = True
else:
raise exception.InvalidInput(
reason=_('unrecognized argument %s') % arg_list[i])
else:
ret['obj'] = arg_list[i]
return ret | def _cmd_to_dict(self, arg_list):
no_param_args = [
'autodelete',
'autoexpand',
'bytes',
'compressed',
'force',
'nohdr',
]
one_param_args = [
'chapsecret',
'cleanrate',
'copyrate',
'delim',
'filtervalue',
'grainsize',
'hbawwpn',
'host',
'iogrp',
'iscsiname',
'mdiskgrp',
'name',
'rsize',
'scsi',
'size',
'source',
'target',
'unit',
'easytier',
'warning',
'wwpn',
]
# Handle the special case of lsnode which is a two-word command
# Use the one word version of the command internally
if arg_list[0] in ('svcinfo', 'svctask'):
if arg_list[1] == 'lsnode':
if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! <node id>
ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}
else:
ret = {'cmd': 'lsnodecanister'}
else:
ret = {'cmd': arg_list[1]}
arg_list.pop(0)
else:
ret = {'cmd': arg_list[0]}
skip = False
for i in range(1, len(arg_list)):
if skip:
skip = False
continue
if arg_list[i][0] == '-':
if arg_list[i][1:] in no_param_args:
ret[arg_list[i][1:]] = True
elif arg_list[i][1:] in one_param_args:
ret[arg_list[i][1:]] = arg_list[i + 1]
skip = True
else:
raise exception.InvalidInput(
reason=_('unrecognized argument %s') % arg_list[i])
else:
ret['obj'] = arg_list[i]
return ret | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 33,
"line": " def _cmd_to_dict(self, cmd):\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 38,
"line": " def _cmd_to_dict(self, arg_list):\n"
}
]
} | {
"deleted": [
{
"char_start": 27,
"char_end": 41,
"chars": "cmd):\n "
},
{
"char_start": 49,
"char_end": 62,
"chars": " = cmd.split("
}
],
"added": [
{
"char_start": 36,
"char_end": 37,
"chars": ":"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/tests/test_storwize_svc.py | cwe-078 |
_cli_run | def _cli_run(self, verb, cli_args):
"""Runs a CLI command over SSH, without doing any result parsing."""
cli_arg_strings = []
if cli_args:
for k, v in cli_args.items():
if k == '':
cli_arg_strings.append(" %s" % k)
else:
cli_arg_strings.append(" %s=%s" % (k, v))
cmd = verb + ''.join(cli_arg_strings)
LOG.debug("SSH CMD = %s " % cmd)
(stdout, stderr) = self._run_ssh(cmd, False)
# we have to strip out the input and exit lines
tmp = stdout.split("\r\n")
out = tmp[5:len(tmp) - 2]
return out | def _cli_run(self, cmd):
"""Runs a CLI command over SSH, without doing any result parsing."""
LOG.debug("SSH CMD = %s " % cmd)
(stdout, stderr) = self._run_ssh(cmd, False)
# we have to strip out the input and exit lines
tmp = stdout.split("\r\n")
out = tmp[5:len(tmp) - 2]
return out | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 40,
"line": " def _cli_run(self, verb, cli_args):\n"
},
{
"line_no": 3,
"char_start": 117,
"char_end": 146,
"line": " cli_arg_strings = []\n"
},
{
"line_no": 4,
"char_start": 146,
"char_end": 167,
"line": " if cli_args:\n"
},
{
"line_no": 5,
"char_start": 167,
"char_end": 209,
"line": " for k, v in cli_args.items():\n"
},
{
"line_no": 6,
"char_start": 209,
"char_end": 237,
"line": " if k == '':\n"
},
{
"line_no": 7,
"char_start": 237,
"char_end": 291,
"line": " cli_arg_strings.append(\" %s\" % k)\n"
},
{
"line_no": 8,
"char_start": 291,
"char_end": 313,
"line": " else:\n"
},
{
"line_no": 9,
"char_start": 313,
"char_end": 375,
"line": " cli_arg_strings.append(\" %s=%s\" % (k, v))\n"
},
{
"line_no": 10,
"char_start": 375,
"char_end": 376,
"line": "\n"
},
{
"line_no": 11,
"char_start": 376,
"char_end": 422,
"line": " cmd = verb + ''.join(cli_arg_strings)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 29,
"line": " def _cli_run(self, cmd):\n"
}
]
} | {
"deleted": [
{
"char_start": 23,
"char_end": 29,
"chars": "verb, "
},
{
"char_start": 30,
"char_end": 37,
"chars": "li_args"
},
{
"char_start": 116,
"char_end": 421,
"chars": "\n cli_arg_strings = []\n if cli_args:\n for k, v in cli_args.items():\n if k == '':\n cli_arg_strings.append(\" %s\" % k)\n else:\n cli_arg_strings.append(\" %s=%s\" % (k, v))\n\n cmd = verb + ''.join(cli_arg_strings)"
}
],
"added": [
{
"char_start": 24,
"char_end": 26,
"chars": "md"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
_call_external_zip | def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
try:
spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
except DistutilsExecError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise ExecError, \
("unable to create zip file '%s': "
"could neither import the 'zipfile' module nor "
"find a standalone zip utility") % zip_filename | def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
cmd = ["zip", zipoptions, zip_filename, base_dir]
if logger is not None:
logger.info(' '.join(cmd))
if dry_run:
return
import subprocess
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise ExecError, \
("unable to create zip file '%s': "
"could neither import the 'zipfile' module nor "
"find a standalone zip utility") % zip_filename | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 78,
"line": "def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):\n"
},
{
"line_no": 7,
"char_start": 212,
"char_end": 264,
"line": " from distutils.errors import DistutilsExecError\n"
},
{
"line_no": 8,
"char_start": 264,
"char_end": 302,
"line": " from distutils.spawn import spawn\n"
},
{
"line_no": 10,
"char_start": 311,
"char_end": 387,
"line": " spawn([\"zip\", zipoptions, zip_filename, base_dir], dry_run=dry_run)\n"
},
{
"line_no": 11,
"char_start": 387,
"char_end": 418,
"line": " except DistutilsExecError:\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 74,
"line": "def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):\n"
},
{
"line_no": 7,
"char_start": 208,
"char_end": 262,
"line": " cmd = [\"zip\", zipoptions, zip_filename, base_dir]\n"
},
{
"line_no": 8,
"char_start": 262,
"char_end": 289,
"line": " if logger is not None:\n"
},
{
"line_no": 9,
"char_start": 289,
"char_end": 324,
"line": " logger.info(' '.join(cmd))\n"
},
{
"line_no": 10,
"char_start": 324,
"char_end": 340,
"line": " if dry_run:\n"
},
{
"line_no": 11,
"char_start": 340,
"char_end": 355,
"line": " return\n"
},
{
"line_no": 12,
"char_start": 355,
"char_end": 377,
"line": " import subprocess\n"
},
{
"line_no": 14,
"char_start": 386,
"char_end": 421,
"line": " subprocess.check_call(cmd)\n"
},
{
"line_no": 15,
"char_start": 421,
"char_end": 463,
"line": " except subprocess.CalledProcessError:\n"
}
]
} | {
"deleted": [
{
"char_start": 54,
"char_end": 60,
"chars": "=False"
},
{
"char_start": 69,
"char_end": 72,
"chars": "=Fa"
},
{
"char_start": 73,
"char_end": 74,
"chars": "s"
},
{
"char_start": 216,
"char_end": 219,
"chars": "fro"
},
{
"char_start": 221,
"char_end": 222,
"chars": "d"
},
{
"char_start": 223,
"char_end": 226,
"chars": "stu"
},
{
"char_start": 230,
"char_end": 231,
"chars": "."
},
{
"char_start": 233,
"char_end": 237,
"chars": "rors"
},
{
"char_start": 239,
"char_end": 241,
"chars": "mp"
},
{
"char_start": 243,
"char_end": 244,
"chars": "t"
},
{
"char_start": 245,
"char_end": 246,
"chars": "D"
},
{
"char_start": 248,
"char_end": 250,
"chars": "tu"
},
{
"char_start": 251,
"char_end": 252,
"chars": "i"
},
{
"char_start": 253,
"char_end": 256,
"chars": "sEx"
},
{
"char_start": 257,
"char_end": 259,
"chars": "cE"
},
{
"char_start": 260,
"char_end": 261,
"chars": "r"
},
{
"char_start": 262,
"char_end": 263,
"chars": "r"
},
{
"char_start": 270,
"char_end": 272,
"chars": "om"
},
{
"char_start": 273,
"char_end": 276,
"chars": "dis"
},
{
"char_start": 278,
"char_end": 287,
"chars": "tils.spaw"
},
{
"char_start": 298,
"char_end": 301,
"chars": "awn"
},
{
"char_start": 321,
"char_end": 336,
"chars": "awn([\"zip\", zip"
},
{
"char_start": 337,
"char_end": 342,
"chars": "ption"
},
{
"char_start": 343,
"char_end": 348,
"chars": ", zip"
},
{
"char_start": 349,
"char_end": 351,
"chars": "fi"
},
{
"char_start": 352,
"char_end": 355,
"chars": "ena"
},
{
"char_start": 356,
"char_end": 378,
"chars": "e, base_dir], dry_run="
},
{
"char_start": 379,
"char_end": 385,
"chars": "ry_run"
},
{
"char_start": 398,
"char_end": 400,
"chars": "Di"
},
{
"char_start": 401,
"char_end": 402,
"chars": "t"
},
{
"char_start": 403,
"char_end": 405,
"chars": "ti"
},
{
"char_start": 406,
"char_end": 409,
"chars": "sEx"
}
],
"added": [
{
"char_start": 63,
"char_end": 65,
"chars": ", "
},
{
"char_start": 66,
"char_end": 69,
"chars": "ogg"
},
{
"char_start": 70,
"char_end": 71,
"chars": "r"
},
{
"char_start": 212,
"char_end": 213,
"chars": "c"
},
{
"char_start": 214,
"char_end": 215,
"chars": "d"
},
{
"char_start": 216,
"char_end": 232,
"chars": "= [\"zip\", zipopt"
},
{
"char_start": 233,
"char_end": 235,
"chars": "on"
},
{
"char_start": 236,
"char_end": 243,
"chars": ", zip_f"
},
{
"char_start": 245,
"char_end": 254,
"chars": "ename, ba"
},
{
"char_start": 256,
"char_end": 259,
"chars": "_di"
},
{
"char_start": 260,
"char_end": 265,
"chars": "]\n "
},
{
"char_start": 267,
"char_end": 270,
"chars": "f l"
},
{
"char_start": 271,
"char_end": 274,
"chars": "gge"
},
{
"char_start": 278,
"char_end": 281,
"chars": " no"
},
{
"char_start": 282,
"char_end": 297,
"chars": " None:\n "
},
{
"char_start": 298,
"char_end": 301,
"chars": "ogg"
},
{
"char_start": 303,
"char_end": 307,
"chars": ".inf"
},
{
"char_start": 308,
"char_end": 323,
"chars": "(' '.join(cmd))"
},
{
"char_start": 328,
"char_end": 329,
"chars": "i"
},
{
"char_start": 332,
"char_end": 336,
"chars": "ry_r"
},
{
"char_start": 337,
"char_end": 350,
"chars": "n:\n re"
},
{
"char_start": 351,
"char_end": 353,
"chars": "ur"
},
{
"char_start": 354,
"char_end": 358,
"chars": "\n "
},
{
"char_start": 367,
"char_end": 369,
"chars": "ub"
},
{
"char_start": 370,
"char_end": 376,
"chars": "rocess"
},
{
"char_start": 395,
"char_end": 397,
"chars": "ub"
},
{
"char_start": 398,
"char_end": 399,
"chars": "r"
},
{
"char_start": 400,
"char_end": 401,
"chars": "c"
},
{
"char_start": 402,
"char_end": 403,
"chars": "s"
},
{
"char_start": 404,
"char_end": 407,
"chars": ".ch"
},
{
"char_start": 408,
"char_end": 410,
"chars": "ck"
},
{
"char_start": 411,
"char_end": 418,
"chars": "call(cm"
},
{
"char_start": 434,
"char_end": 440,
"chars": "bproce"
},
{
"char_start": 441,
"char_end": 447,
"chars": "s.Call"
},
{
"char_start": 448,
"char_end": 452,
"chars": "dPro"
},
{
"char_start": 453,
"char_end": 456,
"chars": "ess"
}
]
} | github.com/python/cpython/commit/add531a1e55b0a739b0f42582f1c9747e5649ace | Lib/shutil.py | cwe-078 |
_create_host | def _create_host(self, connector):
"""Create a new host on the storage system.
We create a host name and associate it with the given connection
information.
"""
LOG.debug(_('enter: _create_host: host %s') % connector['host'])
rand_id = str(random.randint(0, 99999999)).zfill(8)
host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),
rand_id)
# Get all port information from the connector
ports = []
if 'initiator' in connector:
ports.append('-iscsiname %s' % connector['initiator'])
if 'wwpns' in connector:
for wwpn in connector['wwpns']:
ports.append('-hbawwpn %s' % wwpn)
# When creating a host, we need one port
self._driver_assert(len(ports), _('_create_host: No connector ports'))
port1 = ports.pop(0)
ssh_cmd = ('svctask mkhost -force %(port1)s -name "%(host_name)s"' %
{'port1': port1, 'host_name': host_name})
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return('successfully created' in out,
'_create_host', ssh_cmd, out, err)
# Add any additional ports to the host
for port in ports:
ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))
out, err = self._run_ssh(ssh_cmd)
LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %
{'host': connector['host'], 'host_name': host_name})
return host_name | def _create_host(self, connector):
"""Create a new host on the storage system.
We create a host name and associate it with the given connection
information.
"""
LOG.debug(_('enter: _create_host: host %s') % connector['host'])
rand_id = str(random.randint(0, 99999999)).zfill(8)
host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),
rand_id)
# Get all port information from the connector
ports = []
if 'initiator' in connector:
ports.append('-iscsiname %s' % connector['initiator'])
if 'wwpns' in connector:
for wwpn in connector['wwpns']:
ports.append('-hbawwpn %s' % wwpn)
# When creating a host, we need one port
self._driver_assert(len(ports), _('_create_host: No connector ports'))
port1 = ports.pop(0)
arg_name, arg_val = port1.split()
ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',
'"%s"' % host_name]
out, err = self._run_ssh(ssh_cmd)
self._assert_ssh_return('successfully created' in out,
'_create_host', ssh_cmd, out, err)
# Add any additional ports to the host
for port in ports:
arg_name, arg_val = port.split()
ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,
host_name]
out, err = self._run_ssh(ssh_cmd)
LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %
{'host': connector['host'], 'host_name': host_name})
return host_name | {
"deleted": [
{
"line_no": 26,
"char_start": 916,
"char_end": 993,
"line": " ssh_cmd = ('svctask mkhost -force %(port1)s -name \"%(host_name)s\"' %\n"
},
{
"line_no": 27,
"char_start": 993,
"char_end": 1054,
"line": " {'port1': port1, 'host_name': host_name})\n"
},
{
"line_no": 34,
"char_start": 1301,
"char_end": 1380,
"line": " ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))\n"
}
],
"added": [
{
"line_no": 26,
"char_start": 916,
"char_end": 958,
"line": " arg_name, arg_val = port1.split()\n"
},
{
"line_no": 27,
"char_start": 958,
"char_end": 1036,
"line": " ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',\n"
},
{
"line_no": 28,
"char_start": 1036,
"char_end": 1075,
"line": " '\"%s\"' % host_name]\n"
},
{
"line_no": 35,
"char_start": 1322,
"char_end": 1367,
"line": " arg_name, arg_val = port.split()\n"
},
{
"line_no": 36,
"char_start": 1367,
"char_end": 1445,
"line": " ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,\n"
},
{
"line_no": 37,
"char_start": 1445,
"char_end": 1479,
"line": " host_name]\n"
}
]
} | {
"deleted": [
{
"char_start": 934,
"char_end": 935,
"chars": "("
},
{
"char_start": 958,
"char_end": 962,
"chars": "%(po"
},
{
"char_start": 963,
"char_end": 969,
"chars": "t1)s -"
},
{
"char_start": 974,
"char_end": 981,
"chars": "\"%(host"
},
{
"char_start": 986,
"char_end": 989,
"chars": ")s\""
},
{
"char_start": 990,
"char_end": 992,
"chars": " %"
},
{
"char_start": 1012,
"char_end": 1013,
"chars": "{"
},
{
"char_start": 1014,
"char_end": 1019,
"chars": "port1"
},
{
"char_start": 1020,
"char_end": 1021,
"chars": ":"
},
{
"char_start": 1022,
"char_end": 1041,
"chars": "port1, 'host_name':"
},
{
"char_start": 1051,
"char_end": 1053,
"chars": "})"
},
{
"char_start": 1323,
"char_end": 1324,
"chars": "("
},
{
"char_start": 1351,
"char_end": 1357,
"chars": " %s %s"
},
{
"char_start": 1359,
"char_end": 1360,
"chars": "%"
},
{
"char_start": 1361,
"char_end": 1364,
"chars": "(po"
},
{
"char_start": 1365,
"char_end": 1366,
"chars": "t"
},
{
"char_start": 1377,
"char_end": 1379,
"chars": "))"
}
],
"added": [
{
"char_start": 924,
"char_end": 966,
"chars": "arg_name, arg_val = port1.split()\n "
},
{
"char_start": 976,
"char_end": 977,
"chars": "["
},
{
"char_start": 985,
"char_end": 987,
"chars": "',"
},
{
"char_start": 988,
"char_end": 989,
"chars": "'"
},
{
"char_start": 995,
"char_end": 997,
"chars": "',"
},
{
"char_start": 998,
"char_end": 999,
"chars": "'"
},
{
"char_start": 1005,
"char_end": 1007,
"chars": "',"
},
{
"char_start": 1008,
"char_end": 1009,
"chars": "a"
},
{
"char_start": 1010,
"char_end": 1012,
"chars": "g_"
},
{
"char_start": 1016,
"char_end": 1017,
"chars": ","
},
{
"char_start": 1018,
"char_end": 1021,
"chars": "arg"
},
{
"char_start": 1022,
"char_end": 1029,
"chars": "val, '-"
},
{
"char_start": 1034,
"char_end": 1035,
"chars": ","
},
{
"char_start": 1056,
"char_end": 1060,
"chars": "\"%s\""
},
{
"char_start": 1062,
"char_end": 1063,
"chars": "%"
},
{
"char_start": 1073,
"char_end": 1074,
"chars": "]"
},
{
"char_start": 1322,
"char_end": 1367,
"chars": " arg_name, arg_val = port.split()\n"
},
{
"char_start": 1389,
"char_end": 1390,
"chars": "["
},
{
"char_start": 1398,
"char_end": 1400,
"chars": "',"
},
{
"char_start": 1401,
"char_end": 1402,
"chars": "'"
},
{
"char_start": 1413,
"char_end": 1415,
"chars": "',"
},
{
"char_start": 1416,
"char_end": 1417,
"chars": "'"
},
{
"char_start": 1424,
"char_end": 1425,
"chars": ","
},
{
"char_start": 1426,
"char_end": 1435,
"chars": "arg_name,"
},
{
"char_start": 1436,
"char_end": 1437,
"chars": "a"
},
{
"char_start": 1438,
"char_end": 1443,
"chars": "g_val"
},
{
"char_start": 1444,
"char_end": 1467,
"chars": "\n "
},
{
"char_start": 1477,
"char_end": 1478,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
_get_iscsi_ip_addrs | def _get_iscsi_ip_addrs(self):
generator = self._port_conf_generator('svcinfo lsportip')
header = next(generator, None)
if not header:
return
for port_data in generator:
try:
port_node_id = port_data['node_id']
port_ipv4 = port_data['IP_address']
port_ipv6 = port_data['IP_address_6']
state = port_data['state']
except KeyError:
self._handle_keyerror('lsportip', header)
if port_node_id in self._storage_nodes and (
state == 'configured' or state == 'online'):
node = self._storage_nodes[port_node_id]
if len(port_ipv4):
node['ipv4'].append(port_ipv4)
if len(port_ipv6):
node['ipv6'].append(port_ipv6) | def _get_iscsi_ip_addrs(self):
generator = self._port_conf_generator(['svcinfo', 'lsportip'])
header = next(generator, None)
if not header:
return
for port_data in generator:
try:
port_node_id = port_data['node_id']
port_ipv4 = port_data['IP_address']
port_ipv6 = port_data['IP_address_6']
state = port_data['state']
except KeyError:
self._handle_keyerror('lsportip', header)
if port_node_id in self._storage_nodes and (
state == 'configured' or state == 'online'):
node = self._storage_nodes[port_node_id]
if len(port_ipv4):
node['ipv4'].append(port_ipv4)
if len(port_ipv6):
node['ipv6'].append(port_ipv6) | {
"deleted": [
{
"line_no": 2,
"char_start": 35,
"char_end": 101,
"line": " generator = self._port_conf_generator('svcinfo lsportip')\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 35,
"char_end": 106,
"line": " generator = self._port_conf_generator(['svcinfo', 'lsportip'])\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 81,
"char_end": 82,
"chars": "["
},
{
"char_start": 90,
"char_end": 92,
"chars": "',"
},
{
"char_start": 93,
"char_end": 94,
"chars": "'"
},
{
"char_start": 103,
"char_end": 104,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
talk | def talk(myText):
if( myText.find( "twitter" ) >= 0 ):
myText += "0"
myText = myText[7:-1]
try:
myText = twitter.getTweet( myText )
except:
print( "!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.")
return
os.system( "espeak \",...\" 2>/dev/null" ) # Sometimes the beginning of audio can get cut off. Insert silence.
time.sleep( 0.5 )
os.system( "espeak -w speech.wav \"" + myText + "\" -s 130" )
audio.play("speech.wav")
return myText | def talk(myText):
if( myText.find( "twitter" ) >= 0 ):
myText += "0"
myText = myText[7:-1]
try:
myText = twitter.getTweet( myText )
except:
print( "!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.")
return
os.system( "espeak \",...\" 2>/dev/null" ) # Sometimes the beginning of audio can get cut off. Insert silence.
time.sleep( 0.5 )
subprocess.call(["espeak", "-w", "speech.wav", myText, "-s", "130"])
audio.play("speech.wav")
return myText | {
"deleted": [
{
"line_no": 13,
"char_start": 441,
"char_end": 508,
"line": " os.system( \"espeak -w speech.wav \\\"\" + myText + \"\\\" -s 130\" )\r\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 441,
"char_end": 515,
"line": " subprocess.call([\"espeak\", \"-w\", \"speech.wav\", myText, \"-s\", \"130\"])\r\n"
}
]
} | {
"deleted": [
{
"char_start": 447,
"char_end": 448,
"chars": "."
},
{
"char_start": 449,
"char_end": 454,
"chars": "ystem"
},
{
"char_start": 455,
"char_end": 456,
"chars": " "
},
{
"char_start": 477,
"char_end": 479,
"chars": " \\"
},
{
"char_start": 480,
"char_end": 483,
"chars": "\" +"
},
{
"char_start": 490,
"char_end": 492,
"chars": " +"
},
{
"char_start": 494,
"char_end": 497,
"chars": "\\\" "
},
{
"char_start": 504,
"char_end": 505,
"chars": " "
}
],
"added": [
{
"char_start": 445,
"char_end": 450,
"chars": "subpr"
},
{
"char_start": 451,
"char_end": 454,
"chars": "ces"
},
{
"char_start": 456,
"char_end": 460,
"chars": "call"
},
{
"char_start": 461,
"char_end": 462,
"chars": "["
},
{
"char_start": 469,
"char_end": 471,
"chars": "\","
},
{
"char_start": 472,
"char_end": 473,
"chars": "\""
},
{
"char_start": 475,
"char_end": 477,
"chars": "\","
},
{
"char_start": 478,
"char_end": 479,
"chars": "\""
},
{
"char_start": 490,
"char_end": 491,
"chars": ","
},
{
"char_start": 498,
"char_end": 499,
"chars": ","
},
{
"char_start": 503,
"char_end": 505,
"chars": "\","
},
{
"char_start": 506,
"char_end": 507,
"chars": "\""
},
{
"char_start": 511,
"char_end": 512,
"chars": "]"
}
]
} | github.com/ntc-chip-revived/ChippyRuxpin/commit/0cd7d78e4d806852fd75fee03c24cce322f76014 | chippyRuxpin.py | cwe-078 |
_exec_cmd | def _exec_cmd(self, cmd):
"""Executes adb commands in a new shell.
This is specific to executing adb binary because stderr is not a good
indicator of cmd execution status.
Args:
cmds: A string that is the adb command to execute.
Returns:
The output of the adb command run if exit code is 0.
Raises:
AdbError is raised if the adb command exit code is not 0.
"""
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
ret = proc.returncode
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out,
err, ret)
if ret == 0:
return out
else:
raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret) | def _exec_cmd(self, args, shell):
"""Executes adb commands.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
Returns:
The output of the adb command run if exit code is 0.
Raises:
AdbError is raised if the adb command exit code is not 0.
"""
proc = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)
(out, err) = proc.communicate()
ret = proc.returncode
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out,
err, ret)
if ret == 0:
return out
else:
raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret) | {
"deleted": [
{
"line_no": 1,
"char_start": 0,
"char_end": 30,
"line": " def _exec_cmd(self, cmd):\n"
},
{
"line_no": 8,
"char_start": 216,
"char_end": 279,
"line": " cmds: A string that is the adb command to execute.\n"
},
{
"line_no": 17,
"char_start": 494,
"char_end": 571,
"line": " cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n"
},
{
"line_no": 20,
"char_start": 641,
"char_end": 717,
"line": " logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out,\n"
},
{
"line_no": 25,
"char_start": 807,
"char_end": 880,
"line": " raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret)\n"
}
],
"added": [
{
"line_no": 1,
"char_start": 0,
"char_end": 38,
"line": " def _exec_cmd(self, args, shell):\n"
},
{
"line_no": 2,
"char_start": 38,
"char_end": 72,
"line": " \"\"\"Executes adb commands.\n"
},
{
"line_no": 5,
"char_start": 87,
"char_end": 151,
"line": " args: string or list of strings, program arguments.\n"
},
{
"line_no": 6,
"char_start": 151,
"char_end": 205,
"line": " See subprocess.Popen() documentation.\n"
},
{
"line_no": 7,
"char_start": 205,
"char_end": 281,
"line": " shell: bool, True to run this command through the system shell,\n"
},
{
"line_no": 8,
"char_start": 281,
"char_end": 355,
"line": " False to invoke it directly. See subprocess.Popen() docs.\n"
},
{
"line_no": 17,
"char_start": 570,
"char_end": 649,
"line": " args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)\n"
},
{
"line_no": 20,
"char_start": 719,
"char_end": 796,
"line": " logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out,\n"
}
]
} | {
"deleted": [
{
"char_start": 24,
"char_end": 27,
"chars": "cmd"
},
{
"char_start": 63,
"char_end": 65,
"chars": "in"
},
{
"char_start": 66,
"char_end": 67,
"chars": "a"
},
{
"char_start": 68,
"char_end": 71,
"chars": "new"
},
{
"char_start": 73,
"char_end": 79,
"chars": "hell.\n"
},
{
"char_start": 88,
"char_end": 92,
"chars": "This"
},
{
"char_start": 93,
"char_end": 94,
"chars": "i"
},
{
"char_start": 97,
"char_end": 102,
"chars": "pecif"
},
{
"char_start": 103,
"char_end": 104,
"chars": "c"
},
{
"char_start": 108,
"char_end": 113,
"chars": "execu"
},
{
"char_start": 119,
"char_end": 121,
"chars": "db"
},
{
"char_start": 122,
"char_end": 125,
"chars": "bin"
},
{
"char_start": 127,
"char_end": 133,
"chars": "y beca"
},
{
"char_start": 134,
"char_end": 135,
"chars": "s"
},
{
"char_start": 136,
"char_end": 138,
"chars": " s"
},
{
"char_start": 139,
"char_end": 145,
"chars": "derr i"
},
{
"char_start": 147,
"char_end": 150,
"chars": "not"
},
{
"char_start": 151,
"char_end": 152,
"chars": "a"
},
{
"char_start": 153,
"char_end": 158,
"chars": "good\n"
},
{
"char_start": 166,
"char_end": 175,
"chars": "indicator"
},
{
"char_start": 176,
"char_end": 178,
"chars": "of"
},
{
"char_start": 179,
"char_end": 182,
"chars": "cmd"
},
{
"char_start": 184,
"char_end": 185,
"chars": "x"
},
{
"char_start": 186,
"char_end": 187,
"chars": "c"
},
{
"char_start": 188,
"char_end": 190,
"chars": "ti"
},
{
"char_start": 193,
"char_end": 194,
"chars": "s"
},
{
"char_start": 197,
"char_end": 199,
"chars": "us"
},
{
"char_start": 200,
"char_end": 201,
"chars": "\n"
},
{
"char_start": 210,
"char_end": 218,
"chars": "Args:\n "
},
{
"char_start": 231,
"char_end": 233,
"chars": "s:"
},
{
"char_start": 234,
"char_end": 237,
"chars": "A s"
},
{
"char_start": 239,
"char_end": 241,
"chars": "in"
},
{
"char_start": 245,
"char_end": 247,
"chars": "at"
},
{
"char_start": 248,
"char_end": 249,
"chars": "i"
},
{
"char_start": 250,
"char_end": 251,
"chars": " "
},
{
"char_start": 255,
"char_end": 258,
"chars": "adb"
},
{
"char_start": 259,
"char_end": 263,
"chars": "comm"
},
{
"char_start": 264,
"char_end": 266,
"chars": "nd"
},
{
"char_start": 271,
"char_end": 272,
"chars": "x"
},
{
"char_start": 274,
"char_end": 275,
"chars": "u"
},
{
"char_start": 506,
"char_end": 509,
"chars": "cmd"
},
{
"char_start": 565,
"char_end": 568,
"chars": "Tru"
},
{
"char_start": 707,
"char_end": 710,
"chars": "cmd"
},
{
"char_start": 838,
"char_end": 841,
"chars": "cmd"
}
],
"added": [
{
"char_start": 24,
"char_end": 35,
"chars": "args, shell"
},
{
"char_start": 70,
"char_end": 73,
"chars": ".\n\n"
},
{
"char_start": 76,
"char_end": 80,
"chars": " "
},
{
"char_start": 81,
"char_end": 84,
"chars": "Arg"
},
{
"char_start": 85,
"char_end": 86,
"chars": ":"
},
{
"char_start": 96,
"char_end": 102,
"chars": " arg"
},
{
"char_start": 103,
"char_end": 104,
"chars": ":"
},
{
"char_start": 106,
"char_end": 108,
"chars": "tr"
},
{
"char_start": 109,
"char_end": 116,
"chars": "ng or l"
},
{
"char_start": 117,
"char_end": 118,
"chars": "s"
},
{
"char_start": 119,
"char_end": 120,
"chars": " "
},
{
"char_start": 121,
"char_end": 122,
"chars": "f"
},
{
"char_start": 123,
"char_end": 124,
"chars": "s"
},
{
"char_start": 125,
"char_end": 126,
"chars": "r"
},
{
"char_start": 129,
"char_end": 131,
"chars": "s,"
},
{
"char_start": 132,
"char_end": 137,
"chars": "progr"
},
{
"char_start": 138,
"char_end": 139,
"chars": "m"
},
{
"char_start": 142,
"char_end": 145,
"chars": "gum"
},
{
"char_start": 146,
"char_end": 148,
"chars": "nt"
},
{
"char_start": 149,
"char_end": 151,
"chars": ".\n"
},
{
"char_start": 167,
"char_end": 168,
"chars": "S"
},
{
"char_start": 170,
"char_end": 177,
"chars": " subpro"
},
{
"char_start": 178,
"char_end": 183,
"chars": "ess.P"
},
{
"char_start": 184,
"char_end": 186,
"chars": "pe"
},
{
"char_start": 187,
"char_end": 189,
"chars": "()"
},
{
"char_start": 190,
"char_end": 197,
"chars": "documen"
},
{
"char_start": 200,
"char_end": 203,
"chars": "ion"
},
{
"char_start": 217,
"char_end": 223,
"chars": "shell:"
},
{
"char_start": 224,
"char_end": 229,
"chars": "bool,"
},
{
"char_start": 230,
"char_end": 234,
"chars": "True"
},
{
"char_start": 235,
"char_end": 237,
"chars": "to"
},
{
"char_start": 238,
"char_end": 241,
"chars": "run"
},
{
"char_start": 242,
"char_end": 246,
"chars": "this"
},
{
"char_start": 248,
"char_end": 250,
"chars": "om"
},
{
"char_start": 251,
"char_end": 253,
"chars": "an"
},
{
"char_start": 256,
"char_end": 257,
"chars": "h"
},
{
"char_start": 258,
"char_end": 260,
"chars": "ou"
},
{
"char_start": 261,
"char_end": 262,
"chars": "h"
},
{
"char_start": 265,
"char_end": 270,
"chars": "e sys"
},
{
"char_start": 271,
"char_end": 273,
"chars": "em"
},
{
"char_start": 277,
"char_end": 293,
"chars": "ll,\n "
},
{
"char_start": 294,
"char_end": 298,
"chars": " F"
},
{
"char_start": 299,
"char_end": 302,
"chars": "lse"
},
{
"char_start": 303,
"char_end": 304,
"chars": "t"
},
{
"char_start": 305,
"char_end": 307,
"chars": " i"
},
{
"char_start": 308,
"char_end": 316,
"chars": "voke it "
},
{
"char_start": 317,
"char_end": 321,
"chars": "irec"
},
{
"char_start": 322,
"char_end": 325,
"chars": "ly."
},
{
"char_start": 326,
"char_end": 327,
"chars": "S"
},
{
"char_start": 329,
"char_end": 336,
"chars": " subpro"
},
{
"char_start": 338,
"char_end": 353,
"chars": "ss.Popen() docs"
},
{
"char_start": 582,
"char_end": 586,
"chars": "args"
},
{
"char_start": 642,
"char_end": 644,
"chars": "sh"
},
{
"char_start": 645,
"char_end": 647,
"chars": "ll"
},
{
"char_start": 785,
"char_end": 789,
"chars": "args"
},
{
"char_start": 917,
"char_end": 921,
"chars": "args"
}
]
} | github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee | mobly/controllers/android_device_lib/adb.py | cwe-078 |
_get_conn_fc_wwpns | def _get_conn_fc_wwpns(self, host_name):
wwpns = []
cmd = 'svcinfo lsfabric -host %s' % host_name
generator = self._port_conf_generator(cmd)
header = next(generator, None)
if not header:
return wwpns
for port_data in generator:
try:
wwpns.append(port_data['local_wwpn'])
except KeyError as e:
self._handle_keyerror('lsfabric', header)
return wwpns | def _get_conn_fc_wwpns(self, host_name):
wwpns = []
cmd = ['svcinfo', 'lsfabric', '-host', host_name]
generator = self._port_conf_generator(cmd)
header = next(generator, None)
if not header:
return wwpns
for port_data in generator:
try:
wwpns.append(port_data['local_wwpn'])
except KeyError as e:
self._handle_keyerror('lsfabric', header)
return wwpns | {
"deleted": [
{
"line_no": 3,
"char_start": 64,
"char_end": 118,
"line": " cmd = 'svcinfo lsfabric -host %s' % host_name\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 64,
"char_end": 122,
"line": " cmd = ['svcinfo', 'lsfabric', '-host', host_name]\n"
}
]
} | {
"deleted": [
{
"char_start": 101,
"char_end": 104,
"chars": " %s"
},
{
"char_start": 105,
"char_end": 107,
"chars": " %"
}
],
"added": [
{
"char_start": 78,
"char_end": 79,
"chars": "["
},
{
"char_start": 87,
"char_end": 89,
"chars": "',"
},
{
"char_start": 90,
"char_end": 91,
"chars": "'"
},
{
"char_start": 99,
"char_end": 101,
"chars": "',"
},
{
"char_start": 102,
"char_end": 103,
"chars": "'"
},
{
"char_start": 109,
"char_end": 110,
"chars": ","
},
{
"char_start": 120,
"char_end": 121,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
_create_3par_iscsi_host | def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):
"""Create a 3PAR host.
Create a 3PAR host, if there is already a host on the 3par using
the same iqn but with a different hostname, return the hostname
used by 3PAR.
"""
cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \
(persona_id, domain, hostname, iscsi_iqn)
out = self.common._cli_run(cmd, None)
if out and len(out) > 1:
return self.common.parse_create_host_error(hostname, out)
return hostname | def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):
"""Create a 3PAR host.
Create a 3PAR host, if there is already a host on the 3par using
the same iqn but with a different hostname, return the hostname
used by 3PAR.
"""
cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain',
domain, hostname, iscsi_iqn]
out = self.common._cli_run(cmd)
if out and len(out) > 1:
return self.common.parse_create_host_error(hostname, out)
return hostname | {
"deleted": [
{
"line_no": 8,
"char_start": 291,
"char_end": 358,
"line": " cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \\\n"
},
{
"line_no": 9,
"char_start": 358,
"char_end": 414,
"line": " (persona_id, domain, hostname, iscsi_iqn)\n"
},
{
"line_no": 10,
"char_start": 414,
"char_end": 460,
"line": " out = self.common._cli_run(cmd, None)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 291,
"char_end": 365,
"line": " cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain',\n"
},
{
"line_no": 9,
"char_start": 365,
"char_end": 409,
"line": " domain, hostname, iscsi_iqn]\n"
},
{
"line_no": 10,
"char_start": 409,
"char_end": 449,
"line": " out = self.common._cli_run(cmd)\n"
}
]
} | {
"deleted": [
{
"char_start": 333,
"char_end": 334,
"chars": "%"
},
{
"char_start": 343,
"char_end": 352,
"chars": " %s %s %s"
},
{
"char_start": 353,
"char_end": 357,
"chars": " % \\"
},
{
"char_start": 372,
"char_end": 384,
"chars": "(persona_id,"
},
{
"char_start": 412,
"char_end": 413,
"chars": ")"
},
{
"char_start": 452,
"char_end": 458,
"chars": ", None"
}
],
"added": [
{
"char_start": 305,
"char_end": 306,
"chars": "["
},
{
"char_start": 317,
"char_end": 319,
"chars": "',"
},
{
"char_start": 320,
"char_end": 321,
"chars": "'"
},
{
"char_start": 327,
"char_end": 329,
"chars": "',"
},
{
"char_start": 330,
"char_end": 331,
"chars": "'"
},
{
"char_start": 339,
"char_end": 341,
"chars": "',"
},
{
"char_start": 342,
"char_end": 345,
"chars": "per"
},
{
"char_start": 346,
"char_end": 353,
"chars": "ona_id,"
},
{
"char_start": 354,
"char_end": 355,
"chars": "'"
},
{
"char_start": 363,
"char_end": 364,
"chars": ","
},
{
"char_start": 407,
"char_end": 408,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_iscsi.py | cwe-078 |
_delete_3par_host | def _delete_3par_host(self, hostname):
self._cli_run('removehost %s' % hostname, None) | def _delete_3par_host(self, hostname):
self._cli_run(['removehost', hostname]) | {
"deleted": [
{
"line_no": 2,
"char_start": 43,
"char_end": 98,
"line": " self._cli_run('removehost %s' % hostname, None)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 43,
"char_end": 90,
"line": " self._cli_run(['removehost', hostname])\n"
}
]
} | {
"deleted": [
{
"char_start": 76,
"char_end": 79,
"chars": " %s"
},
{
"char_start": 80,
"char_end": 82,
"chars": " %"
},
{
"char_start": 91,
"char_end": 97,
"chars": ", None"
}
],
"added": [
{
"char_start": 65,
"char_end": 66,
"chars": "["
},
{
"char_start": 78,
"char_end": 79,
"chars": ","
},
{
"char_start": 88,
"char_end": 89,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f | cinder/volume/drivers/san/hp/hp_3par_common.py | cwe-078 |
process_statistics | def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
for notifier in os.listdir(self.data):
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = self.data + '/' + notifier
self.logger.debug("Running %s %s" % (npath, " ".join(args)))
async_run(npath, args) | def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
self.debug_log("running triggers")
for notifier in os.listdir(self.data):
self.debug_log("running %s" % notifier)
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = os.path.join(self.data, notifier)
self.async_run([npath] + args) | {
"deleted": [
{
"line_no": 10,
"char_start": 425,
"char_end": 472,
"line": " npath = self.data + '/' + notifier\n"
},
{
"line_no": 11,
"char_start": 472,
"char_end": 545,
"line": " self.logger.debug(\"Running %s %s\" % (npath, \" \".join(args)))\n"
},
{
"line_no": 12,
"char_start": 545,
"char_end": 579,
"line": " async_run(npath, args)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 168,
"char_end": 211,
"line": " self.debug_log(\"running triggers\")\n"
},
{
"line_no": 6,
"char_start": 258,
"char_end": 310,
"line": " self.debug_log(\"running %s\" % notifier)\n"
},
{
"line_no": 12,
"char_start": 520,
"char_end": 574,
"line": " npath = os.path.join(self.data, notifier)\n"
},
{
"line_no": 13,
"char_start": 574,
"char_end": 616,
"line": " self.async_run([npath] + args)"
}
]
} | {
"deleted": [
{
"char_start": 454,
"char_end": 462,
"chars": " + '/' +"
},
{
"char_start": 489,
"char_end": 557,
"chars": "logger.debug(\"Running %s %s\" % (npath, \" \".join(args)))\n "
},
{
"char_start": 572,
"char_end": 573,
"chars": ","
}
],
"added": [
{
"char_start": 176,
"char_end": 219,
"chars": "self.debug_log(\"running triggers\")\n "
},
{
"char_start": 257,
"char_end": 309,
"chars": "\n self.debug_log(\"running %s\" % notifier)"
},
{
"char_start": 540,
"char_end": 553,
"chars": "os.path.join("
},
{
"char_start": 562,
"char_end": 563,
"chars": ","
},
{
"char_start": 572,
"char_end": 573,
"chars": ")"
},
{
"char_start": 601,
"char_end": 602,
"chars": "["
},
{
"char_start": 607,
"char_end": 610,
"chars": "] +"
}
]
} | github.com/Bcfg2/bcfg2/commit/a524967e8d5c4c22e49cd619aed20c87a316c0be | src/lib/Server/Plugins/Trigger.py | cwe-078 |
_delete_host | def _delete_host(self, host_name):
"""Delete a host on the storage system."""
LOG.debug(_('enter: _delete_host: host %s ') % host_name)
ssh_cmd = 'svctask rmhost %s ' % host_name
out, err = self._run_ssh(ssh_cmd)
# No output should be returned from rmhost
self._assert_ssh_return(len(out.strip()) == 0,
'_delete_host', ssh_cmd, out, err)
LOG.debug(_('leave: _delete_host: host %s ') % host_name) | def _delete_host(self, host_name):
"""Delete a host on the storage system."""
LOG.debug(_('enter: _delete_host: host %s ') % host_name)
ssh_cmd = ['svctask', 'rmhost', host_name]
out, err = self._run_ssh(ssh_cmd)
# No output should be returned from rmhost
self._assert_ssh_return(len(out.strip()) == 0,
'_delete_host', ssh_cmd, out, err)
LOG.debug(_('leave: _delete_host: host %s ') % host_name) | {
"deleted": [
{
"line_no": 6,
"char_start": 158,
"char_end": 209,
"line": " ssh_cmd = 'svctask rmhost %s ' % host_name\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 158,
"char_end": 209,
"line": " ssh_cmd = ['svctask', 'rmhost', host_name]\n"
}
]
} | {
"deleted": [
{
"char_start": 191,
"char_end": 195,
"chars": " %s "
},
{
"char_start": 196,
"char_end": 198,
"chars": " %"
}
],
"added": [
{
"char_start": 176,
"char_end": 177,
"chars": "["
},
{
"char_start": 185,
"char_end": 187,
"chars": "',"
},
{
"char_start": 188,
"char_end": 189,
"chars": "'"
},
{
"char_start": 196,
"char_end": 197,
"chars": ","
},
{
"char_start": 207,
"char_end": 208,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
fetch | def fetch(url):
'''Download and verify a package url.'''
base = os.path.basename(url)
print('Fetching %s...' % base)
fetch_file(url + '.asc')
fetch_file(url)
fetch_file(url + '.sha256')
fetch_file(url + '.asc.sha256')
print('Verifying %s...' % base)
# TODO: check for verification failure.
os.system('shasum -c %s.sha256' % base)
os.system('shasum -c %s.asc.sha256' % base)
os.system('gpg --verify %s.asc %s' % (base, base))
os.system('keybase verify %s.asc' % base) | def fetch(url):
'''Download and verify a package url.'''
base = os.path.basename(url)
print('Fetching %s...' % base)
fetch_file(url + '.asc')
fetch_file(url)
fetch_file(url + '.sha256')
fetch_file(url + '.asc.sha256')
print('Verifying %s...' % base)
# TODO: check for verification failure.
subprocess.check_call(['shasum', '-c', base + '.sha256'])
subprocess.check_call(['shasum', '-c', base + '.asc.sha256'])
subprocess.check_call(['gpg', '--verify', base + '.asc', base])
subprocess.check_call(['keybase', 'verify', base + '.asc']) | {
"deleted": [
{
"line_no": 11,
"char_start": 308,
"char_end": 350,
"line": " os.system('shasum -c %s.sha256' % base)\n"
},
{
"line_no": 12,
"char_start": 350,
"char_end": 396,
"line": " os.system('shasum -c %s.asc.sha256' % base)\n"
},
{
"line_no": 13,
"char_start": 396,
"char_end": 449,
"line": " os.system('gpg --verify %s.asc %s' % (base, base))\n"
},
{
"line_no": 14,
"char_start": 449,
"char_end": 492,
"line": " os.system('keybase verify %s.asc' % base)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 308,
"char_end": 368,
"line": " subprocess.check_call(['shasum', '-c', base + '.sha256'])\n"
},
{
"line_no": 12,
"char_start": 368,
"char_end": 432,
"line": " subprocess.check_call(['shasum', '-c', base + '.asc.sha256'])\n"
},
{
"line_no": 13,
"char_start": 432,
"char_end": 498,
"line": " subprocess.check_call(['gpg', '--verify', base + '.asc', base])\n"
},
{
"line_no": 14,
"char_start": 498,
"char_end": 559,
"line": " subprocess.check_call(['keybase', 'verify', base + '.asc'])\n"
}
]
} | {
"deleted": [
{
"char_start": 312,
"char_end": 313,
"chars": "."
},
{
"char_start": 314,
"char_end": 317,
"chars": "yst"
},
{
"char_start": 318,
"char_end": 319,
"chars": "m"
},
{
"char_start": 331,
"char_end": 332,
"chars": "%"
},
{
"char_start": 341,
"char_end": 348,
"chars": " % base"
},
{
"char_start": 353,
"char_end": 355,
"chars": "s."
},
{
"char_start": 356,
"char_end": 357,
"chars": "y"
},
{
"char_start": 358,
"char_end": 359,
"chars": "t"
},
{
"char_start": 360,
"char_end": 361,
"chars": "m"
},
{
"char_start": 373,
"char_end": 374,
"chars": "%"
},
{
"char_start": 387,
"char_end": 394,
"chars": " % base"
},
{
"char_start": 400,
"char_end": 401,
"chars": "."
},
{
"char_start": 402,
"char_end": 405,
"chars": "yst"
},
{
"char_start": 406,
"char_end": 407,
"chars": "m"
},
{
"char_start": 422,
"char_end": 425,
"chars": "%s."
},
{
"char_start": 427,
"char_end": 432,
"chars": "c %s'"
},
{
"char_start": 433,
"char_end": 434,
"chars": "%"
},
{
"char_start": 435,
"char_end": 437,
"chars": "(b"
},
{
"char_start": 439,
"char_end": 440,
"chars": "e"
},
{
"char_start": 446,
"char_end": 447,
"chars": ")"
},
{
"char_start": 453,
"char_end": 454,
"chars": "."
},
{
"char_start": 455,
"char_end": 458,
"chars": "yst"
},
{
"char_start": 459,
"char_end": 460,
"chars": "m"
},
{
"char_start": 477,
"char_end": 480,
"chars": "%s."
},
{
"char_start": 482,
"char_end": 484,
"chars": "c'"
},
{
"char_start": 485,
"char_end": 486,
"chars": "%"
},
{
"char_start": 487,
"char_end": 488,
"chars": "b"
},
{
"char_start": 490,
"char_end": 491,
"chars": "e"
}
],
"added": [
{
"char_start": 310,
"char_end": 315,
"chars": "subpr"
},
{
"char_start": 316,
"char_end": 319,
"chars": "ces"
},
{
"char_start": 321,
"char_end": 323,
"chars": "ch"
},
{
"char_start": 324,
"char_end": 331,
"chars": "ck_call"
},
{
"char_start": 332,
"char_end": 333,
"chars": "["
},
{
"char_start": 340,
"char_end": 342,
"chars": "',"
},
{
"char_start": 343,
"char_end": 344,
"chars": "'"
},
{
"char_start": 346,
"char_end": 348,
"chars": "',"
},
{
"char_start": 349,
"char_end": 351,
"chars": "ba"
},
{
"char_start": 352,
"char_end": 357,
"chars": "e + '"
},
{
"char_start": 365,
"char_end": 366,
"chars": "]"
},
{
"char_start": 371,
"char_end": 378,
"chars": "ubproce"
},
{
"char_start": 380,
"char_end": 383,
"chars": ".ch"
},
{
"char_start": 384,
"char_end": 391,
"chars": "ck_call"
},
{
"char_start": 392,
"char_end": 393,
"chars": "["
},
{
"char_start": 400,
"char_end": 402,
"chars": "',"
},
{
"char_start": 403,
"char_end": 404,
"chars": "'"
},
{
"char_start": 406,
"char_end": 408,
"chars": "',"
},
{
"char_start": 409,
"char_end": 411,
"chars": "ba"
},
{
"char_start": 412,
"char_end": 417,
"chars": "e + '"
},
{
"char_start": 429,
"char_end": 430,
"chars": "]"
},
{
"char_start": 435,
"char_end": 442,
"chars": "ubproce"
},
{
"char_start": 444,
"char_end": 447,
"chars": ".ch"
},
{
"char_start": 448,
"char_end": 455,
"chars": "ck_call"
},
{
"char_start": 456,
"char_end": 457,
"chars": "["
},
{
"char_start": 461,
"char_end": 463,
"chars": "',"
},
{
"char_start": 464,
"char_end": 465,
"chars": "'"
},
{
"char_start": 473,
"char_end": 475,
"chars": "',"
},
{
"char_start": 476,
"char_end": 478,
"chars": "ba"
},
{
"char_start": 479,
"char_end": 484,
"chars": "e + '"
},
{
"char_start": 495,
"char_end": 496,
"chars": "]"
},
{
"char_start": 500,
"char_end": 505,
"chars": "subpr"
},
{
"char_start": 506,
"char_end": 508,
"chars": "ce"
},
{
"char_start": 510,
"char_end": 513,
"chars": ".ch"
},
{
"char_start": 514,
"char_end": 521,
"chars": "ck_call"
},
{
"char_start": 522,
"char_end": 523,
"chars": "["
},
{
"char_start": 531,
"char_end": 533,
"chars": "',"
},
{
"char_start": 534,
"char_end": 535,
"chars": "'"
},
{
"char_start": 541,
"char_end": 543,
"chars": "',"
},
{
"char_start": 544,
"char_end": 546,
"chars": "ba"
},
{
"char_start": 547,
"char_end": 552,
"chars": "e + '"
},
{
"char_start": 557,
"char_end": 558,
"chars": "]"
}
]
} | github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb | repack_rust.py | cwe-078 |
_formatCredentials | def _formatCredentials(self, data, name):
"""
Credentials are of the form
RCLONE_CONFIG_CURRENT_TYPE=s3
^ ^ ^ ^
[mandatory ][name ][key][value]
"""
prefix = "RCLONE_CONFIG_{}".format(name.upper())
credentials = ''
credentials += "{}_TYPE='{}' ".format(prefix, data.type)
def _addCredential(credentials, env_key, data_key):
value = getattr(data, data_key, None)
if value is not None:
credentials += "{}='{}' ".format(env_key, value)
return credentials
if data.type == 's3':
credentials = _addCredential(credentials,
'{}_REGION'.format(prefix),
's3_region'
)
credentials = _addCredential(credentials,
'{}_ACCESS_KEY_ID'.format(prefix),
's3_access_key_id'
)
credentials = _addCredential(credentials,
'{}_SECRET_ACCESS_KEY'.format(prefix),
's3_secret_access_key'
)
credentials = _addCredential(credentials,
'{}_ENDPOINT'.format(prefix),
's3_endpoint'
)
credentials = _addCredential(credentials,
'{}_V2_AUTH'.format(prefix),
's3_v2_auth'
)
elif data.type == 'azureblob':
credentials = _addCredential(credentials,
'{}_ACCOUNT'.format(prefix),
'azure_account'
)
credentials = _addCredential(credentials,
'{}_KEY'.format(prefix),
'azure_key'
)
elif data.type == 'swift':
credentials = _addCredential(credentials,
'{}_USER'.format(prefix),
'swift_user'
)
credentials = _addCredential(credentials,
'{}_KEY'.format(prefix),
'swift_key'
)
credentials = _addCredential(credentials,
'{}_AUTH'.format(prefix),
'swift_auth'
)
credentials = _addCredential(credentials,
'{}_TENANT'.format(prefix),
'swift_tenant'
)
elif data.type == 'google cloud storage':
credentials = _addCredential(credentials,
'{}_CLIENT_ID'.format(prefix),
'gcp_client_id'
)
credentials = _addCredential(credentials,
'{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix),
'gcp_service_account_credentials'
)
credentials = _addCredential(credentials,
'{}_PROJECT_NUMBER'.format(prefix),
'gcp_project_number'
)
credentials = _addCredential(credentials,
'{}_OBJECT_ACL'.format(prefix),
'gcp_object_acl'
)
credentials = _addCredential(credentials,
'{}_BUCKET_ACL'.format(prefix),
'gcp_bucket_acl'
)
else:
logging.error("Connection type unknown: {}".format(data.type))
return credentials | def _formatCredentials(self, data, name):
"""
Credentials are of the form
RCLONE_CONFIG_CURRENT_TYPE=s3
^ ^ ^ ^
[mandatory ][name ][key][value]
"""
prefix = "RCLONE_CONFIG_{}".format(name.upper())
credentials = {}
credentials['{}_TYPE'.format(prefix)] = data.type
def _addCredential(credentials, env_key, data_key):
value = getattr(data, data_key, None)
if value is not None:
credentials[env_key] = value
return credentials
if data.type == 's3':
credentials = _addCredential(credentials,
'{}_REGION'.format(prefix),
's3_region'
)
credentials = _addCredential(credentials,
'{}_ACCESS_KEY_ID'.format(prefix),
's3_access_key_id'
)
credentials = _addCredential(credentials,
'{}_SECRET_ACCESS_KEY'.format(prefix),
's3_secret_access_key'
)
credentials = _addCredential(credentials,
'{}_ENDPOINT'.format(prefix),
's3_endpoint'
)
credentials = _addCredential(credentials,
'{}_V2_AUTH'.format(prefix),
's3_v2_auth'
)
elif data.type == 'azureblob':
credentials = _addCredential(credentials,
'{}_ACCOUNT'.format(prefix),
'azure_account'
)
credentials = _addCredential(credentials,
'{}_KEY'.format(prefix),
'azure_key'
)
elif data.type == 'swift':
credentials = _addCredential(credentials,
'{}_USER'.format(prefix),
'swift_user'
)
credentials = _addCredential(credentials,
'{}_KEY'.format(prefix),
'swift_key'
)
credentials = _addCredential(credentials,
'{}_AUTH'.format(prefix),
'swift_auth'
)
credentials = _addCredential(credentials,
'{}_TENANT'.format(prefix),
'swift_tenant'
)
elif data.type == 'google cloud storage':
credentials = _addCredential(credentials,
'{}_CLIENT_ID'.format(prefix),
'gcp_client_id'
)
credentials = _addCredential(credentials,
'{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix),
'gcp_service_account_credentials'
)
credentials = _addCredential(credentials,
'{}_PROJECT_NUMBER'.format(prefix),
'gcp_project_number'
)
credentials = _addCredential(credentials,
'{}_OBJECT_ACL'.format(prefix),
'gcp_object_acl'
)
credentials = _addCredential(credentials,
'{}_BUCKET_ACL'.format(prefix),
'gcp_bucket_acl'
)
else:
logging.error("Connection type unknown: {}".format(data.type))
return credentials | {
"deleted": [
{
"line_no": 11,
"char_start": 283,
"char_end": 308,
"line": " credentials = ''\n"
},
{
"line_no": 12,
"char_start": 308,
"char_end": 373,
"line": " credentials += \"{}_TYPE='{}' \".format(prefix, data.type)\n"
},
{
"line_no": 17,
"char_start": 518,
"char_end": 583,
"line": " credentials += \"{}='{}' \".format(env_key, value)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 283,
"char_end": 308,
"line": " credentials = {}\n"
},
{
"line_no": 12,
"char_start": 308,
"char_end": 366,
"line": " credentials['{}_TYPE'.format(prefix)] = data.type\n"
},
{
"line_no": 17,
"char_start": 511,
"char_end": 556,
"line": " credentials[env_key] = value\n"
}
]
} | {
"deleted": [
{
"char_start": 305,
"char_end": 307,
"chars": "''"
},
{
"char_start": 327,
"char_end": 332,
"chars": " += \""
},
{
"char_start": 339,
"char_end": 340,
"chars": "="
},
{
"char_start": 341,
"char_end": 346,
"chars": "{}' \""
},
{
"char_start": 360,
"char_end": 361,
"chars": ","
},
{
"char_start": 371,
"char_end": 372,
"chars": ")"
},
{
"char_start": 545,
"char_end": 567,
"chars": " += \"{}='{}' \".format("
},
{
"char_start": 574,
"char_end": 575,
"chars": ","
},
{
"char_start": 581,
"char_end": 582,
"chars": ")"
}
],
"added": [
{
"char_start": 305,
"char_end": 307,
"chars": "{}"
},
{
"char_start": 327,
"char_end": 329,
"chars": "['"
},
{
"char_start": 351,
"char_end": 355,
"chars": ")] ="
},
{
"char_start": 538,
"char_end": 539,
"chars": "["
},
{
"char_start": 546,
"char_end": 549,
"chars": "] ="
}
]
} | github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db | src/backend/api/utils/rclone_connection.py | cwe-078 |
initHeader | def initHeader(self):
"""Initialize the IP header according to the IP format definition.
"""
# Ethernet header
# Retrieve remote MAC address
dstMacAddr = arpreq.arpreq(self.remoteIP)
if dstMacAddr is not None:
dstMacAddr = dstMacAddr.replace(':', '')
dstMacAddr = binascii.unhexlify(dstMacAddr)
else:
# Force ARP resolution
p = subprocess.Popen("ping -c1 {}".format(self.remoteIP), shell=True)
p.wait()
time.sleep(0.1)
dstMacAddr = arpreq.arpreq(self.remoteIP)
if dstMacAddr is not None:
dstMacAddr = dstMacAddr.replace(':', '')
dstMacAddr = binascii.unhexlify(dstMacAddr)
else:
raise Exception("Cannot resolve IP address to a MAC address for IP: '{}'".format(self.remoteIP))
# Retrieve local MAC address
srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]
eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))
eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))
eth_type = Field(name='eth.type', domain=Raw(b"\x08\x00"))
# IP header
ip_ver = Field(
name='ip.version', domain=BitArray(
value=bitarray('0100'))) # IP Version 4
ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))
ip_tos = Field(
name='ip.tos',
domain=Data(
dataType=BitArray(nbBits=8),
originalValue=bitarray('00000000'),
svas=SVAS.PERSISTENT))
ip_tot_len = Field(
name='ip.len', domain=BitArray(bitarray('0000000000000000')))
ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))
ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT))
ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT))
ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT))
ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED))
ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000')))
ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))
ip_daddr = Field(
name='ip.dst', domain=IPv4(self.remoteIP))
ip_payload = Field(name='ip.payload', domain=Raw())
ip_ihl.domain = Size([ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id, ip_flags,
ip_frag_off,
ip_ttl, ip_proto,
ip_checksum,
ip_saddr,
ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32))
ip_tot_len.domain = Size([ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr,
ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8))
ip_checksum.domain = InternetChecksum(fields=[ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))
self.header = Symbol(name='Ethernet layer', fields=[eth_dst,
eth_src,
eth_type,
ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr,
ip_payload]) | def initHeader(self):
"""Initialize the IP header according to the IP format definition.
"""
# Ethernet header
# Retrieve remote MAC address
dstMacAddr = arpreq.arpreq(self.remoteIP)
if dstMacAddr is not None:
dstMacAddr = dstMacAddr.replace(':', '')
dstMacAddr = binascii.unhexlify(dstMacAddr)
else:
# Force ARP resolution
p = subprocess.Popen(["/bin/ping", "-c1", self.remoteIP])
p.wait()
time.sleep(0.1)
dstMacAddr = arpreq.arpreq(self.remoteIP)
if dstMacAddr is not None:
dstMacAddr = dstMacAddr.replace(':', '')
dstMacAddr = binascii.unhexlify(dstMacAddr)
else:
raise Exception("Cannot resolve IP address to a MAC address for IP: '{}'".format(self.remoteIP))
# Retrieve local MAC address
srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]
eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))
eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))
eth_type = Field(name='eth.type', domain=Raw(b"\x08\x00"))
# IP header
ip_ver = Field(
name='ip.version', domain=BitArray(
value=bitarray('0100'))) # IP Version 4
ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))
ip_tos = Field(
name='ip.tos',
domain=Data(
dataType=BitArray(nbBits=8),
originalValue=bitarray('00000000'),
svas=SVAS.PERSISTENT))
ip_tot_len = Field(
name='ip.len', domain=BitArray(bitarray('0000000000000000')))
ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))
ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT))
ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT))
ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT))
ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED))
ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000')))
ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))
ip_daddr = Field(
name='ip.dst', domain=IPv4(self.remoteIP))
ip_payload = Field(name='ip.payload', domain=Raw())
ip_ihl.domain = Size([ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id, ip_flags,
ip_frag_off,
ip_ttl, ip_proto,
ip_checksum,
ip_saddr,
ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32))
ip_tot_len.domain = Size([ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr,
ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8))
ip_checksum.domain = InternetChecksum(fields=[ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))
self.header = Symbol(name='Ethernet layer', fields=[eth_dst,
eth_src,
eth_type,
ip_ver,
ip_ihl,
ip_tos,
ip_tot_len,
ip_id,
ip_flags,
ip_frag_off,
ip_ttl,
ip_proto,
ip_checksum,
ip_saddr,
ip_daddr,
ip_payload]) | {
"deleted": [
{
"line_no": 15,
"char_start": 423,
"char_end": 505,
"line": " p = subprocess.Popen(\"ping -c1 {}\".format(self.remoteIP), shell=True)\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 423,
"char_end": 493,
"line": " p = subprocess.Popen([\"/bin/ping\", \"-c1\", self.remoteIP])\n"
}
]
} | {
"deleted": [
{
"char_start": 465,
"char_end": 468,
"chars": " {}"
},
{
"char_start": 469,
"char_end": 477,
"chars": ".format("
},
{
"char_start": 490,
"char_end": 503,
"chars": "), shell=True"
}
],
"added": [
{
"char_start": 456,
"char_end": 457,
"chars": "["
},
{
"char_start": 458,
"char_end": 463,
"chars": "/bin/"
},
{
"char_start": 467,
"char_end": 469,
"chars": "\","
},
{
"char_start": 470,
"char_end": 471,
"chars": "\""
},
{
"char_start": 475,
"char_end": 477,
"chars": ", "
},
{
"char_start": 490,
"char_end": 491,
"chars": "]"
}
]
} | github.com/netzob/netzob/commit/557abf64867d715497979b029efedbd2777b912e | src/netzob/Simulator/Channels/RawEthernetClient.py | cwe-078 |
poll | def poll(self, poll_input):
username = poll_input.credentials.username
password = poll_input.credentials.password
domain = poll_input.credentials.domain
if domain is None:
opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'
options = opt_str.format(
username, password,
poll_input.server, poll_input.port)
else:
opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'
options = opt_str.format(
domain.domain, username, password,
poll_input.server, poll_input.port)
try:
output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)
result = RdpPollResult(True)
return result
except Exception as e:
if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):
result = RdpPollResult(True)
return result
print("{{{{%s}}}}" % e.output)
result = RdpPollResult(False, e)
return result | def poll(self, poll_input):
username = poll_input.credentials.username
password = poll_input.credentials.password
domain = poll_input.credentials.domain
if domain is None:
opt_str = '--ignore-certificate --authonly -u \'{}\' -p \'{}\' {}:{}'
options = opt_str.format(
username, password,
poll_input.server, poll_input.port)
else:
opt_str = '--ignore-certificate --authonly -d {} -u \'{}\' -p \'{}\' {}:{}'
options = opt_str.format(
domain.domain, username, password,
poll_input.server, poll_input.port)
try:
output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)
result = RdpPollResult(True)
return result
except Exception as e:
if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):
result = RdpPollResult(True)
return result
print("{{{{%s}}}}" % e.output)
result = RdpPollResult(False, e)
return result | {
"deleted": [
{
"line_no": 7,
"char_start": 217,
"char_end": 291,
"line": " opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'\n"
},
{
"line_no": 12,
"char_start": 439,
"char_end": 519,
"line": " opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 217,
"char_end": 299,
"line": " opt_str = '--ignore-certificate --authonly -u \\'{}\\' -p \\'{}\\' {}:{}'\n"
},
{
"line_no": 12,
"char_start": 447,
"char_end": 535,
"line": " opt_str = '--ignore-certificate --authonly -d {} -u \\'{}\\' -p \\'{}\\' {}:{}'\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 275,
"char_end": 277,
"chars": "\\'"
},
{
"char_start": 279,
"char_end": 281,
"chars": "\\'"
},
{
"char_start": 285,
"char_end": 287,
"chars": "\\'"
},
{
"char_start": 289,
"char_end": 291,
"chars": "\\'"
},
{
"char_start": 511,
"char_end": 513,
"chars": "\\'"
},
{
"char_start": 515,
"char_end": 517,
"chars": "\\'"
},
{
"char_start": 521,
"char_end": 523,
"chars": "\\'"
},
{
"char_start": 525,
"char_end": 527,
"chars": "\\'"
}
]
} | github.com/DSU-DefSecClub/ScoringEngine/commit/010eefe1ad416c0bdaa16fd59eca0dc8e3086a13 | polling/poll_rdp.py | cwe-078 |
terminate_connection | def terminate_connection(self, volume, connector, **kwargs):
"""Cleanup after an iSCSI connection has been terminated.
When we clean up a terminated connection between a given connector
and volume, we:
1. Translate the given connector to a host name
2. Remove the volume-to-host mapping if it exists
3. Delete the host if it has no more mappings (hosts are created
automatically by this driver when mappings are created)
"""
LOG.debug(_('enter: terminate_connection: volume %(vol)s with '
'connector %(conn)s') % {'vol': str(volume),
'conn': str(connector)})
vol_name = volume['name']
host_name = self._get_host_from_connector(connector)
# Verify that _get_host_from_connector returned the host.
# This should always succeed as we terminate an existing connection.
self._driver_assert(
host_name is not None,
_('_get_host_from_connector failed to return the host name '
'for connector'))
# Check if vdisk-host mapping exists, remove if it does
mapping_data = self._get_hostvdisk_mappings(host_name)
if vol_name in mapping_data:
ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \
(host_name, vol_name)
out, err = self._run_ssh(ssh_cmd)
# Verify CLI behaviour - no output is returned from
# rmvdiskhostmap
self._assert_ssh_return(len(out.strip()) == 0,
'terminate_connection', ssh_cmd, out, err)
del mapping_data[vol_name]
else:
LOG.error(_('terminate_connection: No mapping of volume '
'%(vol_name)s to host %(host_name)s found') %
{'vol_name': vol_name, 'host_name': host_name})
# If this host has no more mappings, delete it
if not mapping_data:
self._delete_host(host_name)
LOG.debug(_('leave: terminate_connection: volume %(vol)s with '
'connector %(conn)s') % {'vol': str(volume),
'conn': str(connector)}) | def terminate_connection(self, volume, connector, **kwargs):
"""Cleanup after an iSCSI connection has been terminated.
When we clean up a terminated connection between a given connector
and volume, we:
1. Translate the given connector to a host name
2. Remove the volume-to-host mapping if it exists
3. Delete the host if it has no more mappings (hosts are created
automatically by this driver when mappings are created)
"""
LOG.debug(_('enter: terminate_connection: volume %(vol)s with '
'connector %(conn)s') % {'vol': str(volume),
'conn': str(connector)})
vol_name = volume['name']
host_name = self._get_host_from_connector(connector)
# Verify that _get_host_from_connector returned the host.
# This should always succeed as we terminate an existing connection.
self._driver_assert(
host_name is not None,
_('_get_host_from_connector failed to return the host name '
'for connector'))
# Check if vdisk-host mapping exists, remove if it does
mapping_data = self._get_hostvdisk_mappings(host_name)
if vol_name in mapping_data:
ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,
vol_name]
out, err = self._run_ssh(ssh_cmd)
# Verify CLI behaviour - no output is returned from
# rmvdiskhostmap
self._assert_ssh_return(len(out.strip()) == 0,
'terminate_connection', ssh_cmd, out, err)
del mapping_data[vol_name]
else:
LOG.error(_('terminate_connection: No mapping of volume '
'%(vol_name)s to host %(host_name)s found') %
{'vol_name': vol_name, 'host_name': host_name})
# If this host has no more mappings, delete it
if not mapping_data:
self._delete_host(host_name)
LOG.debug(_('leave: terminate_connection: volume %(vol)s with '
'connector %(conn)s') % {'vol': str(volume),
'conn': str(connector)}) | {
"deleted": [
{
"line_no": 27,
"char_start": 1277,
"char_end": 1340,
"line": " ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \\\n"
},
{
"line_no": 28,
"char_start": 1340,
"char_end": 1378,
"line": " (host_name, vol_name)\n"
}
],
"added": [
{
"line_no": 27,
"char_start": 1277,
"char_end": 1349,
"line": " ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,\n"
},
{
"line_no": 28,
"char_start": 1349,
"char_end": 1382,
"line": " vol_name]\n"
}
]
} | {
"deleted": [
{
"char_start": 1329,
"char_end": 1330,
"chars": "%"
},
{
"char_start": 1332,
"char_end": 1340,
"chars": "%s' % \\\n"
},
{
"char_start": 1356,
"char_end": 1367,
"chars": "(host_name,"
},
{
"char_start": 1376,
"char_end": 1377,
"chars": ")"
}
],
"added": [
{
"char_start": 1299,
"char_end": 1300,
"chars": "["
},
{
"char_start": 1308,
"char_end": 1310,
"chars": "',"
},
{
"char_start": 1311,
"char_end": 1312,
"chars": "'"
},
{
"char_start": 1326,
"char_end": 1328,
"chars": "',"
},
{
"char_start": 1329,
"char_end": 1330,
"chars": "'"
},
{
"char_start": 1335,
"char_end": 1337,
"chars": "',"
},
{
"char_start": 1338,
"char_end": 1340,
"chars": "ho"
},
{
"char_start": 1341,
"char_end": 1350,
"chars": "t_name,\n "
},
{
"char_start": 1367,
"char_end": 1371,
"chars": " "
},
{
"char_start": 1380,
"char_end": 1381,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
_port_conf_generator | def _port_conf_generator(self, cmd):
ssh_cmd = '%s -delim !' % cmd
out, err = self._run_ssh(ssh_cmd)
if not len(out.strip()):
return
port_lines = out.strip().split('\n')
if not len(port_lines):
return
header = port_lines.pop(0)
yield header
for portip_line in port_lines:
try:
port_data = self._get_hdr_dic(header, portip_line, '!')
except exception.VolumeBackendAPIException:
with excutils.save_and_reraise_exception():
self._log_cli_output_error('_port_conf_generator',
ssh_cmd, out, err)
yield port_data | def _port_conf_generator(self, cmd):
ssh_cmd = cmd + ['-delim', '!']
out, err = self._run_ssh(ssh_cmd)
if not len(out.strip()):
return
port_lines = out.strip().split('\n')
if not len(port_lines):
return
header = port_lines.pop(0)
yield header
for portip_line in port_lines:
try:
port_data = self._get_hdr_dic(header, portip_line, '!')
except exception.VolumeBackendAPIException:
with excutils.save_and_reraise_exception():
self._log_cli_output_error('_port_conf_generator',
ssh_cmd, out, err)
yield port_data | {
"deleted": [
{
"line_no": 2,
"char_start": 41,
"char_end": 79,
"line": " ssh_cmd = '%s -delim !' % cmd\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 41,
"char_end": 81,
"line": " ssh_cmd = cmd + ['-delim', '!']\n"
}
]
} | {
"deleted": [
{
"char_start": 59,
"char_end": 62,
"chars": "'%s"
},
{
"char_start": 72,
"char_end": 78,
"chars": " % cmd"
}
],
"added": [
{
"char_start": 59,
"char_end": 64,
"chars": "cmd +"
},
{
"char_start": 65,
"char_end": 67,
"chars": "['"
},
{
"char_start": 73,
"char_end": 75,
"chars": "',"
},
{
"char_start": 76,
"char_end": 77,
"chars": "'"
},
{
"char_start": 79,
"char_end": 80,
"chars": "]"
}
]
} | github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4 | cinder/volume/drivers/storwize_svc.py | cwe-078 |
init_settings | def init_settings(self, ipython_app, kernel_manager, contents_manager,
cluster_manager, session_manager, kernel_spec_manager,
config_manager,
log, base_url, default_url, settings_overrides,
jinja_env_options=None):
_template_path = settings_overrides.get(
"template_path",
ipython_app.template_file_path,
)
if isinstance(_template_path, py3compat.string_types):
_template_path = (_template_path,)
template_path = [os.path.expanduser(path) for path in _template_path]
jenv_opt = jinja_env_options if jinja_env_options else {}
env = Environment(loader=FileSystemLoader(template_path), **jenv_opt)
sys_info = get_sys_info()
if sys_info['commit_source'] == 'repository':
# don't cache (rely on 304) when working from master
version_hash = ''
else:
# reset the cache on server restart
version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
settings = dict(
# basics
log_function=log_request,
base_url=base_url,
default_url=default_url,
template_path=template_path,
static_path=ipython_app.static_file_path,
static_handler_class = FileFindHandler,
static_url_prefix = url_path_join(base_url,'/static/'),
static_handler_args = {
# don't cache custom.js
'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],
},
version_hash=version_hash,
# authentication
cookie_secret=ipython_app.cookie_secret,
login_url=url_path_join(base_url,'/login'),
login_handler_class=ipython_app.login_handler_class,
logout_handler_class=ipython_app.logout_handler_class,
password=ipython_app.password,
# managers
kernel_manager=kernel_manager,
contents_manager=contents_manager,
cluster_manager=cluster_manager,
session_manager=session_manager,
kernel_spec_manager=kernel_spec_manager,
config_manager=config_manager,
# IPython stuff
jinja_template_vars=ipython_app.jinja_template_vars,
nbextensions_path=ipython_app.nbextensions_path,
websocket_url=ipython_app.websocket_url,
mathjax_url=ipython_app.mathjax_url,
config=ipython_app.config,
jinja2_env=env,
terminals_available=False, # Set later if terminals are available
)
# allow custom overrides for the tornado web app.
settings.update(settings_overrides)
return settings | def init_settings(self, ipython_app, kernel_manager, contents_manager,
cluster_manager, session_manager, kernel_spec_manager,
config_manager,
log, base_url, default_url, settings_overrides,
jinja_env_options=None):
_template_path = settings_overrides.get(
"template_path",
ipython_app.template_file_path,
)
if isinstance(_template_path, py3compat.string_types):
_template_path = (_template_path,)
template_path = [os.path.expanduser(path) for path in _template_path]
jenv_opt = {"autoescape": True}
jenv_opt.update(jinja_env_options if jinja_env_options else {})
env = Environment(loader=FileSystemLoader(template_path), **jenv_opt)
sys_info = get_sys_info()
if sys_info['commit_source'] == 'repository':
# don't cache (rely on 304) when working from master
version_hash = ''
else:
# reset the cache on server restart
version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
settings = dict(
# basics
log_function=log_request,
base_url=base_url,
default_url=default_url,
template_path=template_path,
static_path=ipython_app.static_file_path,
static_handler_class = FileFindHandler,
static_url_prefix = url_path_join(base_url,'/static/'),
static_handler_args = {
# don't cache custom.js
'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],
},
version_hash=version_hash,
# authentication
cookie_secret=ipython_app.cookie_secret,
login_url=url_path_join(base_url,'/login'),
login_handler_class=ipython_app.login_handler_class,
logout_handler_class=ipython_app.logout_handler_class,
password=ipython_app.password,
# managers
kernel_manager=kernel_manager,
contents_manager=contents_manager,
cluster_manager=cluster_manager,
session_manager=session_manager,
kernel_spec_manager=kernel_spec_manager,
config_manager=config_manager,
# IPython stuff
jinja_template_vars=ipython_app.jinja_template_vars,
nbextensions_path=ipython_app.nbextensions_path,
websocket_url=ipython_app.websocket_url,
mathjax_url=ipython_app.mathjax_url,
config=ipython_app.config,
jinja2_env=env,
terminals_available=False, # Set later if terminals are available
)
# allow custom overrides for the tornado web app.
settings.update(settings_overrides)
return settings | {
"deleted": [
{
"line_no": 15,
"char_start": 629,
"char_end": 695,
"line": " jenv_opt = jinja_env_options if jinja_env_options else {}\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 629,
"char_end": 669,
"line": " jenv_opt = {\"autoescape\": True}\n"
},
{
"line_no": 16,
"char_start": 669,
"char_end": 741,
"line": " jenv_opt.update(jinja_env_options if jinja_env_options else {})\n"
},
{
"line_no": 17,
"char_start": 741,
"char_end": 742,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 648,
"char_end": 693,
"chars": "{\"autoescape\": True}\n jenv_opt.update("
},
{
"char_start": 739,
"char_end": 741,
"chars": ")\n"
}
]
} | github.com/ipython/ipython/commit/3ab41641cf6fce3860c73d5cf4645aa12e1e5892 | IPython/html/notebookapp.py | cwe-079 |
DeletionConfirmationDlg::DeletionConfirmationDlg | DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {
setupUi(this);
if (size == 1)
label->setText(tr("Are you sure you want to delete '%1' from the transfer list?", "Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?").arg(name));
else
label->setText(tr("Are you sure you want to delete these %1 torrents from the transfer list?", "Are you sure you want to delete these 5 torrents from the transfer list?").arg(QString::number(size)));
// Icons
lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon("dialog-warning").pixmap(lbl_warn->height()));
lbl_warn->setFixedWidth(lbl_warn->height());
rememberBtn->setIcon(GuiIconProvider::instance()->getIcon("object-locked"));
move(Utils::Misc::screenCenter(this));
checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());
connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));
buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
} | DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {
setupUi(this);
if (size == 1)
label->setText(tr("Are you sure you want to delete '%1' from the transfer list?", "Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?").arg(Utils::String::toHtmlEscaped(name)));
else
label->setText(tr("Are you sure you want to delete these %1 torrents from the transfer list?", "Are you sure you want to delete these 5 torrents from the transfer list?").arg(QString::number(size)));
// Icons
lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon("dialog-warning").pixmap(lbl_warn->height()));
lbl_warn->setFixedWidth(lbl_warn->height());
rememberBtn->setIcon(GuiIconProvider::instance()->getIcon("object-locked"));
move(Utils::Misc::screenCenter(this));
checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());
connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));
buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
} | {
"deleted": [
{
"line_no": 4,
"char_start": 163,
"char_end": 341,
"line": " label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(name));\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 163,
"char_end": 371,
"line": " label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(Utils::String::toHtmlEscaped(name)));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 333,
"char_end": 362,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 366,
"char_end": 367,
"chars": ")"
}
]
} | github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16 | src/gui/deletionconfirmationdlg.h | cwe-079 |
get | @auth.public
def get(self, build_id):
try:
build_id = int(build_id)
except ValueError as ex:
self.response.write(ex.message)
self.abort(400)
build = model.Build.get_by_id(build_id)
can_view = build and user.can_view_build_async(build).get_result()
if not can_view:
if auth.get_current_identity().is_anonymous:
return self.redirect(gae_users.create_login_url(self.request.url))
self.response.write('build %d not found' % build_id)
self.abort(404)
return self.redirect(str(build.url)) | @auth.public
def get(self, build_id):
try:
build_id = int(build_id)
except ValueError:
self.response.write('invalid build id')
self.abort(400)
build = model.Build.get_by_id(build_id)
can_view = build and user.can_view_build_async(build).get_result()
if not can_view:
if auth.get_current_identity().is_anonymous:
return self.redirect(self.create_login_url(self.request.url))
self.response.write('build %d not found' % build_id)
self.abort(404)
return self.redirect(str(build.url)) | {
"deleted": [
{
"line_no": 5,
"char_start": 82,
"char_end": 111,
"line": " except ValueError as ex:\n"
},
{
"line_no": 6,
"char_start": 111,
"char_end": 149,
"line": " self.response.write(ex.message)\n"
},
{
"line_no": 14,
"char_start": 360,
"char_end": 435,
"line": " return self.redirect(gae_users.create_login_url(self.request.url))\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 82,
"char_end": 105,
"line": " except ValueError:\n"
},
{
"line_no": 6,
"char_start": 105,
"char_end": 151,
"line": " self.response.write('invalid build id')\n"
},
{
"line_no": 14,
"char_start": 362,
"char_end": 432,
"line": " return self.redirect(self.create_login_url(self.request.url))\n"
}
]
} | {
"deleted": [
{
"char_start": 103,
"char_end": 109,
"chars": " as ex"
},
{
"char_start": 137,
"char_end": 144,
"chars": "ex.mess"
},
{
"char_start": 145,
"char_end": 147,
"chars": "ge"
},
{
"char_start": 389,
"char_end": 394,
"chars": "gae_u"
},
{
"char_start": 396,
"char_end": 398,
"chars": "rs"
}
],
"added": [
{
"char_start": 131,
"char_end": 135,
"chars": "'inv"
},
{
"char_start": 136,
"char_end": 149,
"chars": "lid build id'"
},
{
"char_start": 393,
"char_end": 395,
"chars": "lf"
}
]
} | github.com/asdfghjjklllllaaa/infra/commit/2f39f3df54fb79b56744f00bcf97583b3807851f | appengine/cr-buildbucket/handlers.py | cwe-079 |
index | def index(request, is_mobile=False):
hue_collections = DashboardController(request.user).get_search_collections()
collection_id = request.GET.get('collection')
if not hue_collections or not collection_id:
return admin_collections(request, True, is_mobile)
try:
collection_doc = Document2.objects.get(id=collection_id)
if USE_NEW_EDITOR.get():
collection_doc.can_read_or_exception(request.user)
else:
collection_doc.doc.get().can_read_or_exception(request.user)
collection = Collection2(request.user, document=collection_doc)
except Exception, e:
raise PopupException(e, title=_("Dashboard does not exist or you don't have the permission to access it."))
query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}
if request.method == 'GET':
if 'q' in request.GET:
query['qs'][0]['q'] = request.GET.get('q')
if 'qd' in request.GET:
query['qd'] = request.GET.get('qd')
template = 'search.mako'
if is_mobile:
template = 'search_m.mako'
return render(template, request, {
'collection': collection,
'query': json.dumps(query),
'initial': json.dumps({
'collections': [],
'layout': DEFAULT_LAYOUT,
'is_latest': LATEST.get(),
'engines': get_engines(request.user)
}),
'is_owner': collection_doc.doc.get().can_write(request.user),
'can_edit_index': can_edit_index(request.user),
'is_embeddable': request.GET.get('is_embeddable', False),
'mobile': is_mobile,
}) | def index(request, is_mobile=False):
hue_collections = DashboardController(request.user).get_search_collections()
collection_id = request.GET.get('collection')
if not hue_collections or not collection_id:
return admin_collections(request, True, is_mobile)
try:
collection_doc = Document2.objects.get(id=collection_id)
if USE_NEW_EDITOR.get():
collection_doc.can_read_or_exception(request.user)
else:
collection_doc.doc.get().can_read_or_exception(request.user)
collection = Collection2(request.user, document=collection_doc)
except Exception, e:
raise PopupException(e, title=_("Dashboard does not exist or you don't have the permission to access it."))
query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}
if request.method == 'GET':
if 'q' in request.GET:
query['qs'][0]['q'] = antixss(request.GET.get('q', ''))
if 'qd' in request.GET:
query['qd'] = antixss(request.GET.get('qd', ''))
template = 'search.mako'
if is_mobile:
template = 'search_m.mako'
return render(template, request, {
'collection': collection,
'query': json.dumps(query),
'initial': json.dumps({
'collections': [],
'layout': DEFAULT_LAYOUT,
'is_latest': LATEST.get(),
'engines': get_engines(request.user)
}),
'is_owner': collection_doc.can_write(request.user) if USE_NEW_EDITOR.get() else collection_doc.doc.get().can_write(request.user),
'can_edit_index': can_edit_index(request.user),
'is_embeddable': request.GET.get('is_embeddable', False),
'mobile': is_mobile,
}) | {
"deleted": [
{
"line_no": 22,
"char_start": 814,
"char_end": 863,
"line": " query['qs'][0]['q'] = request.GET.get('q')\n"
},
{
"line_no": 24,
"char_start": 891,
"char_end": 933,
"line": " query['qd'] = request.GET.get('qd')\n"
},
{
"line_no": 39,
"char_start": 1285,
"char_end": 1351,
"line": " 'is_owner': collection_doc.doc.get().can_write(request.user),\n"
}
],
"added": [
{
"line_no": 22,
"char_start": 814,
"char_end": 876,
"line": " query['qs'][0]['q'] = antixss(request.GET.get('q', ''))\n"
},
{
"line_no": 24,
"char_start": 904,
"char_end": 959,
"line": " query['qd'] = antixss(request.GET.get('qd', ''))\n"
},
{
"line_no": 39,
"char_start": 1311,
"char_end": 1445,
"line": " 'is_owner': collection_doc.can_write(request.user) if USE_NEW_EDITOR.get() else collection_doc.doc.get().can_write(request.user),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 842,
"char_end": 850,
"chars": "antixss("
},
{
"char_start": 869,
"char_end": 874,
"chars": ", '')"
},
{
"char_start": 924,
"char_end": 932,
"chars": "antixss("
},
{
"char_start": 952,
"char_end": 957,
"chars": ", '')"
},
{
"char_start": 1326,
"char_end": 1394,
"chars": " collection_doc.can_write(request.user) if USE_NEW_EDITOR.get() else"
}
]
} | github.com/gethue/hue/commit/37b529b1f9aeb5d746599a9ed4e2288cf3ad3e1d | desktop/libs/dashboard/src/dashboard/views.py | cwe-079 |
respond_error | def respond_error(self, context, exception):
context.respond_server_error()
stack = traceback.format_exc()
return """
<html>
<body>
<style>
body {
font-family: sans-serif;
color: #888;
text-align: center;
}
body pre {
width: 600px;
text-align: left;
margin: auto;
font-family: monospace;
}
</style>
<img src="/ajenti:static/main/error.jpeg" />
<br/>
<p>
Server error
</p>
<pre>
%s
</pre>
</body>
</html>
""" % stack | def respond_error(self, context, exception):
context.respond_server_error()
stack = traceback.format_exc()
return """
<html>
<body>
<style>
body {
font-family: sans-serif;
color: #888;
text-align: center;
}
body pre {
width: 600px;
text-align: left;
margin: auto;
font-family: monospace;
}
</style>
<img src="/ajenti:static/main/error.jpeg" />
<br/>
<p>
Server error
</p>
<pre>
%s
</pre>
</body>
</html>
""" % cgi.escape(stack) | {
"deleted": [
{
"line_no": 33,
"char_start": 871,
"char_end": 890,
"line": " \"\"\" % stack\n"
}
],
"added": [
{
"line_no": 33,
"char_start": 871,
"char_end": 902,
"line": " \"\"\" % cgi.escape(stack)"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 885,
"char_end": 896,
"chars": "cgi.escape("
},
{
"char_start": 901,
"char_end": 902,
"chars": ")"
}
]
} | github.com/Eugeny/ajenti/commit/d3fc5eb142ff16d55d158afb050af18d5ff09120 | ajenti/routing.py | cwe-079 |
edit_bundle | @check_document_access_permission()
def edit_bundle(request):
bundle_id = request.GET.get('bundle')
doc = None
if bundle_id:
doc = Document2.objects.get(id=bundle_id)
bundle = Bundle(document=doc)
else:
bundle = Bundle()
coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])
for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')]
return render('editor/bundle_editor.mako', request, {
'bundle_json': bundle.json,
'coordinators_json': json.dumps(coordinators),
'doc1_id': doc.doc.get().id if doc else -1,
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | @check_document_access_permission()
def edit_bundle(request):
bundle_id = request.GET.get('bundle')
doc = None
if bundle_id:
doc = Document2.objects.get(id=bundle_id)
bundle = Bundle(document=doc)
else:
bundle = Bundle()
coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])
for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')]
return render('editor/bundle_editor.mako', request, {
'bundle_json': bundle.json_for_html(),
'coordinators_json': json.dumps(coordinators, cls=JSONEncoderForHTML),
'doc1_id': doc.doc.get().id if doc else -1,
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | {
"deleted": [
{
"line_no": 16,
"char_start": 498,
"char_end": 532,
"line": " 'bundle_json': bundle.json,\n"
},
{
"line_no": 17,
"char_start": 532,
"char_end": 585,
"line": " 'coordinators_json': json.dumps(coordinators),\n"
}
],
"added": [
{
"line_no": 16,
"char_start": 498,
"char_end": 543,
"line": " 'bundle_json': bundle.json_for_html(),\n"
},
{
"line_no": 17,
"char_start": 543,
"char_end": 620,
"line": " 'coordinators_json': json.dumps(coordinators, cls=JSONEncoderForHTML),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 530,
"char_end": 541,
"chars": "_for_html()"
},
{
"char_start": 593,
"char_end": 617,
"chars": ", cls=JSONEncoderForHTML"
}
]
} | github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735 | apps/oozie/src/oozie/views/editor2.py | cwe-079 |
history_data | def history_data(start_time, offset=None):
"""Return history data.
Arguments:
start_time: select history starting from this timestamp.
offset: number of items to skip
"""
# history atimes are stored as ints, ensure start_time is not a float
start_time = int(start_time)
hist = objreg.get('web-history')
if offset is not None:
entries = hist.entries_before(start_time, limit=1000, offset=offset)
else:
# end is 24hrs earlier than start
end_time = start_time - 24*60*60
entries = hist.entries_between(end_time, start_time)
return [{"url": e.url, "title": e.title or e.url, "time": e.atime}
for e in entries] | def history_data(start_time, offset=None):
"""Return history data.
Arguments:
start_time: select history starting from this timestamp.
offset: number of items to skip
"""
# history atimes are stored as ints, ensure start_time is not a float
start_time = int(start_time)
hist = objreg.get('web-history')
if offset is not None:
entries = hist.entries_before(start_time, limit=1000, offset=offset)
else:
# end is 24hrs earlier than start
end_time = start_time - 24*60*60
entries = hist.entries_between(end_time, start_time)
return [{"url": html.escape(e.url),
"title": html.escape(e.title) or html.escape(e.url),
"time": e.atime} for e in entries] | {
"deleted": [
{
"line_no": 18,
"char_start": 603,
"char_end": 674,
"line": " return [{\"url\": e.url, \"title\": e.title or e.url, \"time\": e.atime}\n"
},
{
"line_no": 19,
"char_start": 674,
"char_end": 703,
"line": " for e in entries]\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 603,
"char_end": 643,
"line": " return [{\"url\": html.escape(e.url),\n"
},
{
"line_no": 19,
"char_start": 643,
"char_end": 709,
"line": " \"title\": html.escape(e.title) or html.escape(e.url),\n"
},
{
"line_no": 20,
"char_start": 709,
"char_end": 756,
"line": " \"time\": e.atime} for e in entries]\n"
}
]
} | {
"deleted": [
{
"char_start": 673,
"char_end": 685,
"chars": "\n "
}
],
"added": [
{
"char_start": 623,
"char_end": 635,
"chars": "html.escape("
},
{
"char_start": 640,
"char_end": 641,
"chars": ")"
},
{
"char_start": 642,
"char_end": 655,
"chars": "\n "
},
{
"char_start": 665,
"char_end": 677,
"chars": "html.escape("
},
{
"char_start": 684,
"char_end": 685,
"chars": ")"
},
{
"char_start": 689,
"char_end": 701,
"chars": "html.escape("
},
{
"char_start": 706,
"char_end": 707,
"chars": ")"
},
{
"char_start": 708,
"char_end": 721,
"chars": "\n "
}
]
} | github.com/qutebrowser/qutebrowser/commit/4c9360237f186681b1e3f2a0f30c45161cf405c7 | qutebrowser/browser/qutescheme.py | cwe-079 |
json_dumps | @register.filter
def json_dumps(value, indent=None):
if isinstance(value, QuerySet):
result = serialize('json', value, indent=indent)
else:
result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)
return mark_safe(result) | @register.filter
def json_dumps(value, indent=None):
if isinstance(value, QuerySet):
result = serialize('json', value, indent=indent)
else:
result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)
return mark_safe(force_text(result).translate(_safe_js_escapes)) | {
"deleted": [
{
"line_no": 8,
"char_start": 231,
"char_end": 259,
"line": " return mark_safe(result)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 231,
"char_end": 299,
"line": " return mark_safe(force_text(result).translate(_safe_js_escapes))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 252,
"char_end": 263,
"chars": "force_text("
},
{
"char_start": 270,
"char_end": 299,
"chars": ".translate(_safe_js_escapes))"
}
]
} | github.com/djblets/djblets/commit/77a68c03cd619a0996f3f37337b8c39ca6643d6e | djblets/util/templatetags/djblets_js.py | cwe-079 |
htmlvalue | def htmlvalue(self, val):
return self.block.render_basic(val) | def htmlvalue(self, val):
"""
Return an HTML representation of this block that is safe to be included
in comparison views
"""
return escape(text_from_html(self.block.render_basic(val))) | {
"deleted": [
{
"line_no": 2,
"char_start": 30,
"char_end": 73,
"line": " return self.block.render_basic(val)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 30,
"char_end": 42,
"line": " \"\"\"\n"
},
{
"line_no": 3,
"char_start": 42,
"char_end": 122,
"line": " Return an HTML representation of this block that is safe to be included\n"
},
{
"line_no": 4,
"char_start": 122,
"char_end": 150,
"line": " in comparison views\n"
},
{
"line_no": 5,
"char_start": 150,
"char_end": 162,
"line": " \"\"\"\n"
},
{
"line_no": 6,
"char_start": 162,
"char_end": 229,
"line": " return escape(text_from_html(self.block.render_basic(val)))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 38,
"char_end": 68,
"chars": "\"\"\"\n Return an HTML rep"
},
{
"char_start": 70,
"char_end": 73,
"chars": "sen"
},
{
"char_start": 74,
"char_end": 117,
"chars": "ation of this block that is safe to be incl"
},
{
"char_start": 118,
"char_end": 138,
"chars": "ded\n in compa"
},
{
"char_start": 139,
"char_end": 142,
"chars": "iso"
},
{
"char_start": 144,
"char_end": 199,
"chars": "views\n \"\"\"\n return escape(text_from_html("
},
{
"char_start": 227,
"char_end": 229,
"chars": "))"
}
]
} | github.com/wagtail/wagtail/commit/61045ceefea114c40ac4b680af58990dbe732389 | wagtail/admin/compare.py | cwe-079 |
gravatar | @register.tag
@basictag(takes_context=True)
def gravatar(context, user, size=None):
"""
Outputs the HTML for displaying a user's gravatar.
This can take an optional size of the image (defaults to 80 if not
specified).
This is also influenced by the following settings:
GRAVATAR_SIZE - Default size for gravatars
GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x)
GRAVATAR_DEFAULT - Default image set to show if the user hasn't
specified a gravatar (identicon, monsterid, wavatar)
See http://www.gravatar.com/ for more information.
"""
url = get_gravatar_url(context['request'], user, size)
if url:
return ('<img src="%s" width="%s" height="%s" alt="%s" '
' class="gravatar"/>' %
(url, size, size, user.get_full_name() or user.username))
else:
return '' | @register.tag
@basictag(takes_context=True)
def gravatar(context, user, size=None):
"""
Outputs the HTML for displaying a user's gravatar.
This can take an optional size of the image (defaults to 80 if not
specified).
This is also influenced by the following settings:
GRAVATAR_SIZE - Default size for gravatars
GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x)
GRAVATAR_DEFAULT - Default image set to show if the user hasn't
specified a gravatar (identicon, monsterid, wavatar)
See http://www.gravatar.com/ for more information.
"""
url = get_gravatar_url(context['request'], user, size)
if url:
return format_html(
'<img src="{0}" width="{1}" height="{1}" alt="{2}" '
'class="gravatar"/>',
url, size, user.get_full_name() or user.username)
else:
return '' | {
"deleted": [
{
"line_no": 22,
"char_start": 698,
"char_end": 763,
"line": " return ('<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"%s\" '\n"
},
{
"line_no": 23,
"char_start": 763,
"char_end": 807,
"line": " ' class=\"gravatar\"/>' %\n"
},
{
"line_no": 24,
"char_start": 807,
"char_end": 881,
"line": " (url, size, size, user.get_full_name() or user.username))\n"
}
],
"added": [
{
"line_no": 22,
"char_start": 698,
"char_end": 726,
"line": " return format_html(\n"
},
{
"line_no": 23,
"char_start": 726,
"char_end": 791,
"line": " '<img src=\"{0}\" width=\"{1}\" height=\"{1}\" alt=\"{2}\" '\n"
},
{
"line_no": 24,
"char_start": 791,
"char_end": 825,
"line": " 'class=\"gravatar\"/>',\n"
},
{
"line_no": 25,
"char_start": 825,
"char_end": 887,
"line": " url, size, user.get_full_name() or user.username)\n"
}
]
} | {
"deleted": [
{
"char_start": 725,
"char_end": 727,
"chars": "%s"
},
{
"char_start": 736,
"char_end": 738,
"chars": "%s"
},
{
"char_start": 748,
"char_end": 750,
"chars": "%s"
},
{
"char_start": 757,
"char_end": 759,
"chars": "%s"
},
{
"char_start": 775,
"char_end": 779,
"chars": " "
},
{
"char_start": 780,
"char_end": 785,
"chars": " "
},
{
"char_start": 804,
"char_end": 806,
"chars": " %"
},
{
"char_start": 807,
"char_end": 811,
"chars": " "
},
{
"char_start": 823,
"char_end": 824,
"chars": "("
},
{
"char_start": 827,
"char_end": 833,
"chars": ", size"
},
{
"char_start": 878,
"char_end": 879,
"chars": ")"
}
],
"added": [
{
"char_start": 713,
"char_end": 724,
"chars": "format_html"
},
{
"char_start": 725,
"char_end": 738,
"chars": "\n "
},
{
"char_start": 749,
"char_end": 752,
"chars": "{0}"
},
{
"char_start": 761,
"char_end": 764,
"chars": "{1}"
},
{
"char_start": 774,
"char_end": 777,
"chars": "{1}"
},
{
"char_start": 784,
"char_end": 787,
"chars": "{2}"
},
{
"char_start": 823,
"char_end": 824,
"chars": ","
}
]
} | github.com/djblets/djblets/commit/77ac64642ad530bf69e390c51fc6fdcb8914c8e7 | djblets/gravatars/templatetags/gravatars.py | cwe-079 |
PeerListWidget::addPeer | QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)
{
int row = m_listModel->rowCount();
// Adding Peer to peer list
m_listModel->insertRow(row);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);
if (m_resolveCountries) {
const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());
if (!ico.isNull()) {
m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);
const QString countryName = Net::GeoIPManager::CountryName(peer.country());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);
}
else {
m_missingFlags.insert(ip);
}
}
m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());
QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";")));
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole);
return m_listModel->item(row, PeerListDelegate::IP);
} | QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)
{
int row = m_listModel->rowCount();
// Adding Peer to peer list
m_listModel->insertRow(row);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);
if (m_resolveCountries) {
const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());
if (!ico.isNull()) {
m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);
const QString countryName = Net::GeoIPManager::CountryName(peer.country());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);
}
else {
m_missingFlags.insert(ip);
}
}
m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);
m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client()));
m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());
m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());
QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";")));
m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole);
return m_listModel->item(row, PeerListDelegate::IP);
} | {
"deleted": [
{
"line_no": 24,
"char_start": 1441,
"char_end": 1533,
"line": " m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n"
}
],
"added": [
{
"line_no": 24,
"char_start": 1441,
"char_end": 1563,
"line": " m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client()));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1517,
"char_end": 1546,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 1558,
"char_end": 1559,
"chars": ")"
}
]
} | github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16 | src/gui/properties/peerlistwidget.cpp | cwe-079 |
is_safe_url | def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
"""
if url is not None:
url = url.strip()
if not url:
return False
# Chrome treats \ completely as /
url = url.replace('\\', '/')
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.startswith('///'):
return False
url_info = urlparse(url)
# Forbid URLs like http:///example.com - with a scheme, but without a hostname.
# In that URL, example.com is not the hostname but, a path component. However,
# Chrome will still consider example.com to be the hostname, so we must not
# allow this syntax.
if not url_info.netloc and url_info.scheme:
return False
# Forbid URLs that start with control characters. Some browsers (like
# Chrome) ignore quite a few control characters at the start of a
# URL and might consider the URL as scheme relative.
if unicodedata.category(url[0])[0] == 'C':
return False
return ((not url_info.netloc or url_info.netloc == host) and
(not url_info.scheme or url_info.scheme in ['http', 'https'])) | def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
"""
if url is not None:
url = url.strip()
if not url:
return False
# Chrome treats \ completely as / in paths but it could be part of some
# basic auth credentials so we need to check both URLs.
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) | {
"deleted": [
{
"line_no": 13,
"char_start": 346,
"char_end": 379,
"line": " url = url.replace('\\\\', '/')\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 444,
"char_end": 525,
"line": " return _is_safe_url(url, host) and _is_safe_url(url.replace('\\\\', '/'), host)\n"
}
]
} | {
"deleted": [
{
"char_start": 345,
"char_end": 346,
"chars": "\n"
},
{
"char_start": 347,
"char_end": 396,
"chars": " url = url.replace('\\\\', '/')\n # Chrome cons"
},
{
"char_start": 397,
"char_end": 403,
"chars": "ders a"
},
{
"char_start": 404,
"char_end": 405,
"chars": "y"
},
{
"char_start": 406,
"char_end": 422,
"chars": "URL with more th"
},
{
"char_start": 423,
"char_end": 425,
"chars": "n "
},
{
"char_start": 426,
"char_end": 433,
"chars": "wo slas"
},
{
"char_start": 434,
"char_end": 435,
"chars": "e"
},
{
"char_start": 436,
"char_end": 439,
"chars": " to"
},
{
"char_start": 441,
"char_end": 448,
"chars": "e absol"
},
{
"char_start": 450,
"char_end": 471,
"chars": "e, but\n # urlparse"
},
{
"char_start": 473,
"char_end": 477,
"chars": "s no"
},
{
"char_start": 479,
"char_end": 480,
"chars": "s"
},
{
"char_start": 481,
"char_end": 502,
"chars": " flexible. Treat any "
},
{
"char_start": 503,
"char_end": 504,
"chars": "r"
},
{
"char_start": 505,
"char_end": 510,
"chars": " with"
},
{
"char_start": 511,
"char_end": 514,
"chars": "thr"
},
{
"char_start": 515,
"char_end": 536,
"chars": "e slashes as unsafe.\n"
},
{
"char_start": 537,
"char_end": 549,
"chars": " if url.st"
},
{
"char_start": 552,
"char_end": 568,
"chars": "swith('///'):\n "
},
{
"char_start": 569,
"char_end": 598,
"chars": " return False\n url_inf"
},
{
"char_start": 599,
"char_end": 601,
"chars": " ="
},
{
"char_start": 602,
"char_end": 608,
"chars": "urlpar"
},
{
"char_start": 610,
"char_end": 615,
"chars": "(url)"
},
{
"char_start": 622,
"char_end": 625,
"chars": "For"
},
{
"char_start": 626,
"char_end": 649,
"chars": "id URLs like http:///ex"
},
{
"char_start": 650,
"char_end": 668,
"chars": "mple.com - with a "
},
{
"char_start": 669,
"char_end": 681,
"chars": "cheme, but w"
},
{
"char_start": 682,
"char_end": 727,
"chars": "thout a hostname.\n # In that URL, example."
},
{
"char_start": 728,
"char_end": 730,
"chars": "om"
},
{
"char_start": 731,
"char_end": 747,
"chars": "is not the hostn"
},
{
"char_start": 748,
"char_end": 752,
"chars": "me b"
},
{
"char_start": 754,
"char_end": 761,
"chars": ", a pat"
},
{
"char_start": 764,
"char_end": 780,
"chars": "omponent. Howeve"
},
{
"char_start": 781,
"char_end": 794,
"chars": ",\n # Chrom"
},
{
"char_start": 795,
"char_end": 812,
"chars": " will still consi"
},
{
"char_start": 814,
"char_end": 842,
"chars": "r example.com to be the host"
},
{
"char_start": 843,
"char_end": 857,
"chars": "ame, so we mus"
},
{
"char_start": 858,
"char_end": 877,
"chars": " not\n # allow th"
},
{
"char_start": 878,
"char_end": 884,
"chars": "s synt"
},
{
"char_start": 885,
"char_end": 901,
"chars": "x.\n if not ur"
},
{
"char_start": 902,
"char_end": 928,
"chars": "_info.netloc and url_info."
},
{
"char_start": 929,
"char_end": 936,
"chars": "cheme:\n"
},
{
"char_start": 937,
"char_end": 954,
"chars": " return Fal"
},
{
"char_start": 955,
"char_end": 964,
"chars": "e\n # F"
},
{
"char_start": 965,
"char_end": 985,
"chars": "rbid URLs that start"
},
{
"char_start": 987,
"char_end": 1006,
"chars": "ith control charact"
},
{
"char_start": 1007,
"char_end": 1010,
"chars": "rs."
},
{
"char_start": 1011,
"char_end": 1047,
"chars": "Some browsers (like\n # Chrome) ig"
},
{
"char_start": 1048,
"char_end": 1050,
"chars": "or"
},
{
"char_start": 1051,
"char_end": 1056,
"chars": " quit"
},
{
"char_start": 1058,
"char_end": 1067,
"chars": "a few con"
},
{
"char_start": 1068,
"char_end": 1069,
"chars": "r"
},
{
"char_start": 1070,
"char_end": 1071,
"chars": "l"
},
{
"char_start": 1074,
"char_end": 1079,
"chars": "aract"
},
{
"char_start": 1080,
"char_end": 1110,
"chars": "rs at the start of a\n # URL"
},
{
"char_start": 1111,
"char_end": 1122,
"chars": "and might c"
},
{
"char_start": 1123,
"char_end": 1130,
"chars": "nsider "
},
{
"char_start": 1132,
"char_end": 1133,
"chars": "e"
},
{
"char_start": 1137,
"char_end": 1139,
"chars": " a"
},
{
"char_start": 1140,
"char_end": 1156,
"chars": " scheme relative"
},
{
"char_start": 1162,
"char_end": 1213,
"chars": "if unicodedata.category(url[0])[0] == 'C':\n "
},
{
"char_start": 1220,
"char_end": 1246,
"chars": "False\n return ((not url"
},
{
"char_start": 1248,
"char_end": 1249,
"chars": "n"
},
{
"char_start": 1250,
"char_end": 1253,
"chars": "o.n"
},
{
"char_start": 1254,
"char_end": 1262,
"chars": "tloc or "
},
{
"char_start": 1265,
"char_end": 1274,
"chars": "_info.net"
},
{
"char_start": 1275,
"char_end": 1280,
"chars": "oc =="
},
{
"char_start": 1290,
"char_end": 1296,
"chars": "\n "
},
{
"char_start": 1297,
"char_end": 1311,
"chars": " (not url"
},
{
"char_start": 1313,
"char_end": 1317,
"chars": "nfo."
},
{
"char_start": 1318,
"char_end": 1320,
"chars": "ch"
},
{
"char_start": 1321,
"char_end": 1325,
"chars": "me o"
},
{
"char_start": 1326,
"char_end": 1327,
"chars": " "
},
{
"char_start": 1330,
"char_end": 1335,
"chars": "_info"
},
{
"char_start": 1336,
"char_end": 1339,
"chars": "sch"
},
{
"char_start": 1340,
"char_end": 1341,
"chars": "m"
},
{
"char_start": 1343,
"char_end": 1347,
"chars": "in ["
},
{
"char_start": 1348,
"char_end": 1352,
"chars": "http"
},
{
"char_start": 1355,
"char_end": 1356,
"chars": "'"
},
{
"char_start": 1357,
"char_end": 1360,
"chars": "ttp"
},
{
"char_start": 1361,
"char_end": 1364,
"chars": "'])"
}
],
"added": [
{
"char_start": 349,
"char_end": 350,
"chars": "p"
},
{
"char_start": 359,
"char_end": 360,
"chars": "i"
},
{
"char_start": 362,
"char_end": 364,
"chars": "co"
},
{
"char_start": 366,
"char_end": 367,
"chars": "d"
},
{
"char_start": 371,
"char_end": 372,
"chars": "p"
},
{
"char_start": 376,
"char_end": 377,
"chars": "o"
},
{
"char_start": 381,
"char_end": 382,
"chars": "m"
},
{
"char_start": 408,
"char_end": 409,
"chars": "i"
},
{
"char_start": 416,
"char_end": 417,
"chars": "w"
},
{
"char_start": 430,
"char_end": 432,
"chars": "ck"
},
{
"char_start": 455,
"char_end": 457,
"chars": "_i"
},
{
"char_start": 458,
"char_end": 462,
"chars": "_saf"
},
{
"char_start": 463,
"char_end": 464,
"chars": "_"
},
{
"char_start": 466,
"char_end": 467,
"chars": "l"
},
{
"char_start": 471,
"char_end": 472,
"chars": ","
},
{
"char_start": 486,
"char_end": 490,
"chars": "_saf"
},
{
"char_start": 491,
"char_end": 493,
"chars": "_u"
},
{
"char_start": 494,
"char_end": 496,
"chars": "l("
},
{
"char_start": 500,
"char_end": 505,
"chars": "repla"
},
{
"char_start": 507,
"char_end": 508,
"chars": "("
},
{
"char_start": 509,
"char_end": 511,
"chars": "\\\\"
},
{
"char_start": 515,
"char_end": 520,
"chars": "/'), "
},
{
"char_start": 521,
"char_end": 522,
"chars": "o"
},
{
"char_start": 523,
"char_end": 524,
"chars": "t"
}
]
} | github.com/django/django/commit/c5544d289233f501917e25970c03ed444abbd4f0 | django/utils/http.py | cwe-079 |
get_context_data | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = self.object.comment_set.all().order_by('-time')
context['form'] = self.get_form()
context['md'] = markdown(self.object.content,
extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
])
return context | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = self.object.comment_set.all().order_by('-time')
context['form'] = self.get_form()
context['md'] = safe_md(self.object.content)
return context | {
"deleted": [
{
"line_no": 5,
"char_start": 215,
"char_end": 269,
"line": " context['md'] = markdown(self.object.content,\n"
},
{
"line_no": 6,
"char_start": 269,
"char_end": 315,
"line": " extensions=[\n"
},
{
"line_no": 7,
"char_start": 315,
"char_end": 381,
"line": " 'markdown.extensions.extra',\n"
},
{
"line_no": 8,
"char_start": 381,
"char_end": 452,
"line": " 'markdown.extensions.codehilite',\n"
},
{
"line_no": 9,
"char_start": 452,
"char_end": 516,
"line": " 'markdown.extensions.toc',\n"
},
{
"line_no": 10,
"char_start": 516,
"char_end": 552,
"line": " ])\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 215,
"char_end": 268,
"line": " context['md'] = safe_md(self.object.content)\n"
}
]
} | {
"deleted": [
{
"char_start": 239,
"char_end": 240,
"chars": "m"
},
{
"char_start": 241,
"char_end": 243,
"chars": "rk"
},
{
"char_start": 244,
"char_end": 247,
"chars": "own"
},
{
"char_start": 267,
"char_end": 550,
"chars": ",\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ]"
}
],
"added": [
{
"char_start": 239,
"char_end": 240,
"chars": "s"
},
{
"char_start": 241,
"char_end": 245,
"chars": "fe_m"
}
]
} | github.com/Cheng-mq1216/production-practice/commit/333dc34f5feada55d1f6ff1255949ca00dec0f9c | app/Index/views.py | cwe-079 |
edit_workflow | @check_document_access_permission()
def edit_workflow(request):
workflow_id = request.GET.get('workflow')
if workflow_id:
wid = {}
if workflow_id.isdigit():
wid['id'] = workflow_id
else:
wid['uuid'] = workflow_id
doc = Document2.objects.get(type='oozie-workflow2', **wid)
workflow = Workflow(document=doc)
else:
doc = None
workflow = Workflow()
workflow.set_workspace(request.user)
workflow.check_workspace(request.fs, request.user)
workflow_data = workflow.get_data()
api = get_oozie(request.user)
credentials = Credentials()
try:
credentials.fetch(api)
except Exception, e:
LOG.error(smart_str(e))
return render('editor/workflow_editor.mako', request, {
'layout_json': json.dumps(workflow_data['layout']),
'workflow_json': json.dumps(workflow_data['workflow']),
'credentials_json': json.dumps(credentials.credentials.keys()),
'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES),
'doc1_id': doc.doc.get().id if doc else -1,
'subworkflows_json': json.dumps(_get_workflows(request.user)),
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | @check_document_access_permission()
def edit_workflow(request):
workflow_id = request.GET.get('workflow')
if workflow_id:
wid = {}
if workflow_id.isdigit():
wid['id'] = workflow_id
else:
wid['uuid'] = workflow_id
doc = Document2.objects.get(type='oozie-workflow2', **wid)
workflow = Workflow(document=doc)
else:
doc = None
workflow = Workflow()
workflow.set_workspace(request.user)
workflow.check_workspace(request.fs, request.user)
workflow_data = workflow.get_data()
api = get_oozie(request.user)
credentials = Credentials()
try:
credentials.fetch(api)
except Exception, e:
LOG.error(smart_str(e))
return render('editor/workflow_editor.mako', request, {
'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML),
'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML),
'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),
'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),
'doc1_id': doc.doc.get().id if doc else -1,
'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | {
"deleted": [
{
"line_no": 30,
"char_start": 743,
"char_end": 801,
"line": " 'layout_json': json.dumps(workflow_data['layout']),\n"
},
{
"line_no": 31,
"char_start": 801,
"char_end": 863,
"line": " 'workflow_json': json.dumps(workflow_data['workflow']),\n"
},
{
"line_no": 32,
"char_start": 863,
"char_end": 933,
"line": " 'credentials_json': json.dumps(credentials.credentials.keys()),\n"
},
{
"line_no": 33,
"char_start": 933,
"char_end": 1005,
"line": " 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES),\n"
},
{
"line_no": 35,
"char_start": 1055,
"char_end": 1124,
"line": " 'subworkflows_json': json.dumps(_get_workflows(request.user)),\n"
}
],
"added": [
{
"line_no": 30,
"char_start": 743,
"char_end": 825,
"line": " 'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML),\n"
},
{
"line_no": 31,
"char_start": 825,
"char_end": 911,
"line": " 'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML),\n"
},
{
"line_no": 32,
"char_start": 911,
"char_end": 1005,
"line": " 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n"
},
{
"line_no": 33,
"char_start": 1005,
"char_end": 1101,
"line": " 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),\n"
},
{
"line_no": 35,
"char_start": 1151,
"char_end": 1244,
"line": " 'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 798,
"char_end": 822,
"chars": ", cls=JSONEncoderForHTML"
},
{
"char_start": 884,
"char_end": 908,
"chars": ", cls=JSONEncoderForHTML"
},
{
"char_start": 978,
"char_end": 1002,
"chars": ", cls=JSONEncoderForHTML"
},
{
"char_start": 1074,
"char_end": 1098,
"chars": ", cls=JSONEncoderForHTML"
},
{
"char_start": 1217,
"char_end": 1241,
"chars": ", cls=JSONEncoderForHTML"
}
]
} | github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735 | apps/oozie/src/oozie/views/editor2.py | cwe-079 |
simple_search | @classmethod
def simple_search(cls, query, using=None, index=None):
es_search = cls.search(using=using, index=index)
es_query = cls.get_es_query(query=query)
highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]
es_search = es_search.query(es_query).highlight(*highlighted_fields)
return es_search | @classmethod
def simple_search(cls, query, using=None, index=None):
"""
Do a search without facets.
This is used in:
* The Docsearch API
* The Project Admin Search page
"""
es_search = cls.search(using=using, index=index)
es_search = es_search.highlight_options(encoder='html')
es_query = cls.get_es_query(query=query)
highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]
es_search = es_search.query(es_query).highlight(*highlighted_fields)
return es_search | {
"deleted": [
{
"line_no": 6,
"char_start": 259,
"char_end": 260,
"line": "\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 76,
"char_end": 88,
"line": " \"\"\"\n"
},
{
"line_no": 4,
"char_start": 88,
"char_end": 124,
"line": " Do a search without facets.\n"
},
{
"line_no": 5,
"char_start": 124,
"char_end": 125,
"line": "\n"
},
{
"line_no": 6,
"char_start": 125,
"char_end": 150,
"line": " This is used in:\n"
},
{
"line_no": 7,
"char_start": 150,
"char_end": 151,
"line": "\n"
},
{
"line_no": 8,
"char_start": 151,
"char_end": 179,
"line": " * The Docsearch API\n"
},
{
"line_no": 9,
"char_start": 179,
"char_end": 219,
"line": " * The Project Admin Search page\n"
},
{
"line_no": 10,
"char_start": 219,
"char_end": 231,
"line": " \"\"\"\n"
},
{
"line_no": 11,
"char_start": 231,
"char_end": 232,
"line": "\n"
},
{
"line_no": 13,
"char_start": 289,
"char_end": 353,
"line": " es_search = es_search.highlight_options(encoder='html')\n"
},
{
"line_no": 14,
"char_start": 353,
"char_end": 354,
"line": "\n"
},
{
"line_no": 18,
"char_start": 557,
"char_end": 558,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 259,
"char_end": 260,
"chars": "\n"
}
],
"added": [
{
"char_start": 84,
"char_end": 240,
"chars": "\"\"\"\n Do a search without facets.\n\n This is used in:\n\n * The Docsearch API\n * The Project Admin Search page\n \"\"\"\n\n "
},
{
"char_start": 289,
"char_end": 354,
"chars": " es_search = es_search.highlight_options(encoder='html')\n\n"
},
{
"char_start": 556,
"char_end": 557,
"chars": "\n"
}
]
} | github.com/readthedocs/readthedocs.org/commit/1ebe494ffde18109307f205d2bd94102452f697a | readthedocs/search/documents.py | cwe-079 |
HPHP::WddxPacket::recursiveAddVar | bool WddxPacket::recursiveAddVar(const String& varName,
const Variant& varVariant,
bool hasVarTag) {
bool isArray = varVariant.isArray();
bool isObject = varVariant.isObject();
if (isArray || isObject) {
if (hasVarTag) {
m_packetString += "<var name='";
m_packetString += varName.data();
m_packetString += "'>";
}
Array varAsArray;
Object varAsObject = varVariant.toObject();
if (isArray) varAsArray = varVariant.toArray();
if (isObject) varAsArray = varAsObject.toArray();
int length = varAsArray.length();
if (length > 0) {
ArrayIter it = ArrayIter(varAsArray);
if (it.first().isString()) isObject = true;
if (isObject) {
m_packetString += "<struct>";
if (!isArray) {
m_packetString += "<var name='php_class_name'><string>";
m_packetString += varAsObject->o_getClassName().c_str();
m_packetString += "</string></var>";
}
} else {
m_packetString += "<array length='";
m_packetString += std::to_string(length);
m_packetString += "'>";
}
for (ArrayIter it(varAsArray); it; ++it) {
Variant key = it.first();
Variant value = it.second();
recursiveAddVar(key.toString(), value, isObject);
}
if (isObject) {
m_packetString += "</struct>";
}
else {
m_packetString += "</array>";
}
}
else {
//empty object
if (isObject) {
m_packetString += "<struct>";
if (!isArray) {
m_packetString += "<var name='php_class_name'><string>";
m_packetString += varAsObject->o_getClassName().c_str();
m_packetString += "</string></var>";
}
m_packetString += "</struct>";
}
}
if (hasVarTag) {
m_packetString += "</var>";
}
return true;
}
std::string varType = getDataTypeString(varVariant.getType()).data();
if (!getWddxEncoded(varType, "", varName, false).empty()) {
std::string varValue = varVariant.toString().data();
if (varType.compare("boolean") == 0) {
varValue = varVariant.toBoolean() ? "true" : "false";
}
m_packetString += getWddxEncoded(varType, varValue, varName, hasVarTag);
return true;
}
return false;
} | bool WddxPacket::recursiveAddVar(const String& varName,
const Variant& varVariant,
bool hasVarTag) {
bool isArray = varVariant.isArray();
bool isObject = varVariant.isObject();
if (isArray || isObject) {
if (hasVarTag) {
m_packetString += "<var name='";
m_packetString += varName.data();
m_packetString += "'>";
}
Array varAsArray;
Object varAsObject = varVariant.toObject();
if (isArray) varAsArray = varVariant.toArray();
if (isObject) varAsArray = varAsObject.toArray();
int length = varAsArray.length();
if (length > 0) {
ArrayIter it = ArrayIter(varAsArray);
if (it.first().isString()) isObject = true;
if (isObject) {
m_packetString += "<struct>";
if (!isArray) {
m_packetString += "<var name='php_class_name'><string>";
m_packetString += varAsObject->o_getClassName().c_str();
m_packetString += "</string></var>";
}
} else {
m_packetString += "<array length='";
m_packetString += std::to_string(length);
m_packetString += "'>";
}
for (ArrayIter it(varAsArray); it; ++it) {
Variant key = it.first();
Variant value = it.second();
recursiveAddVar(key.toString(), value, isObject);
}
if (isObject) {
m_packetString += "</struct>";
}
else {
m_packetString += "</array>";
}
}
else {
//empty object
if (isObject) {
m_packetString += "<struct>";
if (!isArray) {
m_packetString += "<var name='php_class_name'><string>";
m_packetString += varAsObject->o_getClassName().c_str();
m_packetString += "</string></var>";
}
m_packetString += "</struct>";
}
}
if (hasVarTag) {
m_packetString += "</var>";
}
return true;
}
std::string varType = getDataTypeString(varVariant.getType()).data();
if (!getWddxEncoded(varType, "", varName, false).empty()) {
std::string varValue;
if (varType.compare("boolean") == 0) {
varValue = varVariant.toBoolean() ? "true" : "false";
} else {
varValue = StringUtil::HtmlEncode(varVariant.toString(),
StringUtil::QuoteStyle::Double,
"UTF-8", false, false).toCppString();
}
m_packetString += getWddxEncoded(varType, varValue, varName, hasVarTag);
return true;
}
return false;
} | {
"deleted": [
{
"line_no": 68,
"char_start": 2068,
"char_end": 2125,
"line": " std::string varValue = varVariant.toString().data();\n"
}
],
"added": [
{
"line_no": 68,
"char_start": 2068,
"char_end": 2094,
"line": " std::string varValue;\n"
},
{
"line_no": 71,
"char_start": 2197,
"char_end": 2210,
"line": " } else {\n"
},
{
"line_no": 72,
"char_start": 2210,
"char_end": 2273,
"line": " varValue = StringUtil::HtmlEncode(varVariant.toString(),\n"
},
{
"line_no": 73,
"char_start": 2273,
"char_end": 2345,
"line": " StringUtil::QuoteStyle::Double,\n"
},
{
"line_no": 74,
"char_start": 2345,
"char_end": 2423,
"line": " \"UTF-8\", false, false).toCppString();\n"
}
]
} | {
"deleted": [
{
"char_start": 2092,
"char_end": 2123,
"chars": " = varVariant.toString().data()"
},
{
"char_start": 2168,
"char_end": 2168,
"chars": ""
}
],
"added": [
{
"char_start": 2094,
"char_end": 2094,
"chars": ""
},
{
"char_start": 2195,
"char_end": 2421,
"chars": ";\n } else {\n varValue = StringUtil::HtmlEncode(varVariant.toString(),\n StringUtil::QuoteStyle::Double,\n \"UTF-8\", false, false).toCppString()"
}
]
} | github.com/facebook/hhvm/commit/324701c9fd31beb4f070f1b7ef78b115fbdfec34 | hphp/runtime/ext/wddx/ext_wddx.cpp | cwe-079 |
mode_receive | def mode_receive(self, request):
"""
This is called by render_POST when the client is telling us
that it is ready to receive data as soon as it is available.
This is the basis of a long-polling (comet) mechanism: the
server will wait to reply until data is available.
Args:
request (Request): Incoming request.
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time.time(), False)
dataentries = self.databuffer.get(csessid, [])
if dataentries:
return dataentries.pop(0)
request.notifyFinish().addErrback(self._responseFailed, csessid, request)
if csessid in self.requests:
self.requests[csessid].finish() # Clear any stale request.
self.requests[csessid] = request
return server.NOT_DONE_YET | def mode_receive(self, request):
"""
This is called by render_POST when the client is telling us
that it is ready to receive data as soon as it is available.
This is the basis of a long-polling (comet) mechanism: the
server will wait to reply until data is available.
Args:
request (Request): Incoming request.
"""
csessid = cgi.escape(request.args['csessid'][0])
self.last_alive[csessid] = (time.time(), False)
dataentries = self.databuffer.get(csessid, [])
if dataentries:
return dataentries.pop(0)
request.notifyFinish().addErrback(self._responseFailed, csessid, request)
if csessid in self.requests:
self.requests[csessid].finish() # Clear any stale request.
self.requests[csessid] = request
return server.NOT_DONE_YET | {
"deleted": [
{
"line_no": 12,
"char_start": 389,
"char_end": 438,
"line": " csessid = request.args.get('csessid')[0]\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 389,
"char_end": 446,
"line": " csessid = cgi.escape(request.args['csessid'][0])\n"
}
]
} | {
"deleted": [
{
"char_start": 419,
"char_end": 424,
"chars": ".get("
},
{
"char_start": 433,
"char_end": 434,
"chars": ")"
}
],
"added": [
{
"char_start": 407,
"char_end": 418,
"chars": "cgi.escape("
},
{
"char_start": 430,
"char_end": 431,
"chars": "["
},
{
"char_start": 440,
"char_end": 441,
"chars": "]"
},
{
"char_start": 444,
"char_end": 445,
"chars": ")"
}
]
} | github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93 | evennia/server/portal/webclient_ajax.py | cwe-079 |
edit_coordinator | @check_document_access_permission()
def edit_coordinator(request):
coordinator_id = request.GET.get('coordinator')
doc = None
if coordinator_id:
doc = Document2.objects.get(id=coordinator_id)
coordinator = Coordinator(document=doc)
else:
coordinator = Coordinator()
api = get_oozie(request.user)
credentials = Credentials()
try:
credentials.fetch(api)
except Exception, e:
LOG.error(smart_str(e))
workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])
for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]
if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):
raise PopupException(_('You don\'t have access to the workflow of this coordinator.'))
return render('editor/coordinator_editor.mako', request, {
'coordinator_json': coordinator.json,
'credentials_json': json.dumps(credentials.credentials.keys()),
'workflows_json': json.dumps(workflows),
'doc1_id': doc.doc.get().id if doc else -1,
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | @check_document_access_permission()
def edit_coordinator(request):
coordinator_id = request.GET.get('coordinator')
doc = None
if coordinator_id:
doc = Document2.objects.get(id=coordinator_id)
coordinator = Coordinator(document=doc)
else:
coordinator = Coordinator()
api = get_oozie(request.user)
credentials = Credentials()
try:
credentials.fetch(api)
except Exception, e:
LOG.error(smart_str(e))
workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])
for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]
if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):
raise PopupException(_('You don\'t have access to the workflow of this coordinator.'))
return render('editor/coordinator_editor.mako', request, {
'coordinator_json': coordinator.json_for_html(),
'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),
'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML),
'doc1_id': doc.doc.get().id if doc else -1,
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
}) | {
"deleted": [
{
"line_no": 27,
"char_start": 915,
"char_end": 959,
"line": " 'coordinator_json': coordinator.json,\n"
},
{
"line_no": 28,
"char_start": 959,
"char_end": 1029,
"line": " 'credentials_json': json.dumps(credentials.credentials.keys()),\n"
},
{
"line_no": 29,
"char_start": 1029,
"char_end": 1076,
"line": " 'workflows_json': json.dumps(workflows),\n"
}
],
"added": [
{
"line_no": 27,
"char_start": 915,
"char_end": 970,
"line": " 'coordinator_json': coordinator.json_for_html(),\n"
},
{
"line_no": 28,
"char_start": 970,
"char_end": 1064,
"line": " 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n"
},
{
"line_no": 29,
"char_start": 1064,
"char_end": 1135,
"line": " 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 957,
"char_end": 968,
"chars": "_for_html()"
},
{
"char_start": 1037,
"char_end": 1061,
"chars": ", cls=JSONEncoderForHTML"
},
{
"char_start": 1108,
"char_end": 1132,
"chars": ", cls=JSONEncoderForHTML"
}
]
} | github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735 | apps/oozie/src/oozie/views/editor2.py | cwe-079 |
_keyify | def _keyify(key):
return _key_pattern.sub(' ', key.lower()) | def _keyify(key):
key = escape(key.lower(), quote=True)
return _key_pattern.sub(' ', key) | {
"deleted": [
{
"line_no": 2,
"char_start": 18,
"char_end": 63,
"line": " return _key_pattern.sub(' ', key.lower())\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 18,
"char_end": 60,
"line": " key = escape(key.lower(), quote=True)\n"
},
{
"line_no": 3,
"char_start": 60,
"char_end": 97,
"line": " return _key_pattern.sub(' ', key)\n"
}
]
} | {
"deleted": [
{
"char_start": 54,
"char_end": 62,
"chars": ".lower()"
}
],
"added": [
{
"char_start": 22,
"char_end": 64,
"chars": "key = escape(key.lower(), quote=True)\n "
}
]
} | github.com/lepture/mistune/commit/5f06d724bc05580e7f203db2d4a4905fc1127f98 | mistune.py | cwe-079 |
batch_edit_translations | @login_required(redirect_field_name='', login_url='/403')
@require_POST
@require_AJAX
@transaction.atomic
def batch_edit_translations(request):
"""Perform an action on a list of translations.
Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view
are defined in `models.BatchActionsForm`.
"""
form = forms.BatchActionsForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(form.errors.as_json())
locale = get_object_or_404(Locale, code=form.cleaned_data['locale'])
entities = Entity.objects.filter(pk__in=form.cleaned_data['entities'])
if not entities.exists():
return JsonResponse({'count': 0})
# Batch editing is only available to translators. Check if user has
# translate permissions for all of the projects in passed entities.
# Also make sure projects are not enabled in read-only mode for a locale.
projects_pk = entities.values_list('resource__project__pk', flat=True)
projects = Project.objects.filter(pk__in=projects_pk.distinct())
for project in projects:
if (
not request.user.can_translate(project=project, locale=locale)
or readonly_exists(projects, locale)
):
return HttpResponseForbidden(
"Forbidden: You don't have permission for batch editing"
)
# Find all impacted active translations, including plural forms.
active_translations = Translation.objects.filter(
active=True,
locale=locale,
entity__in=entities,
)
# Execute the actual action.
action_function = ACTIONS_FN_MAP[form.cleaned_data['action']]
action_status = action_function(
form,
request.user,
active_translations,
locale,
)
if action_status.get('error'):
return JsonResponse(action_status)
invalid_translation_count = len(action_status.get('invalid_translation_pks', []))
if action_status['count'] == 0:
return JsonResponse({
'count': 0,
'invalid_translation_count': invalid_translation_count,
})
update_stats(action_status['translated_resources'], locale)
mark_changed_translation(action_status['changed_entities'], locale)
# Update latest translation.
if action_status['latest_translation_pk']:
Translation.objects.get(
pk=action_status['latest_translation_pk']
).update_latest_translation()
update_translation_memory(
action_status['changed_translation_pks'],
project,
locale
)
return JsonResponse({
'count': action_status['count'],
'invalid_translation_count': invalid_translation_count,
}) | @login_required(redirect_field_name='', login_url='/403')
@require_POST
@require_AJAX
@transaction.atomic
def batch_edit_translations(request):
"""Perform an action on a list of translations.
Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view
are defined in `models.BatchActionsForm`.
"""
form = forms.BatchActionsForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(form.errors.as_json(escape_html=True))
locale = get_object_or_404(Locale, code=form.cleaned_data['locale'])
entities = Entity.objects.filter(pk__in=form.cleaned_data['entities'])
if not entities.exists():
return JsonResponse({'count': 0})
# Batch editing is only available to translators. Check if user has
# translate permissions for all of the projects in passed entities.
# Also make sure projects are not enabled in read-only mode for a locale.
projects_pk = entities.values_list('resource__project__pk', flat=True)
projects = Project.objects.filter(pk__in=projects_pk.distinct())
for project in projects:
if (
not request.user.can_translate(project=project, locale=locale)
or readonly_exists(projects, locale)
):
return HttpResponseForbidden(
"Forbidden: You don't have permission for batch editing"
)
# Find all impacted active translations, including plural forms.
active_translations = Translation.objects.filter(
active=True,
locale=locale,
entity__in=entities,
)
# Execute the actual action.
action_function = ACTIONS_FN_MAP[form.cleaned_data['action']]
action_status = action_function(
form,
request.user,
active_translations,
locale,
)
if action_status.get('error'):
return JsonResponse(action_status)
invalid_translation_count = len(action_status.get('invalid_translation_pks', []))
if action_status['count'] == 0:
return JsonResponse({
'count': 0,
'invalid_translation_count': invalid_translation_count,
})
update_stats(action_status['translated_resources'], locale)
mark_changed_translation(action_status['changed_entities'], locale)
# Update latest translation.
if action_status['latest_translation_pk']:
Translation.objects.get(
pk=action_status['latest_translation_pk']
).update_latest_translation()
update_translation_memory(
action_status['changed_translation_pks'],
project,
locale
)
return JsonResponse({
'count': action_status['count'],
'invalid_translation_count': invalid_translation_count,
}) | {
"deleted": [
{
"line_no": 14,
"char_start": 406,
"char_end": 467,
"line": " return HttpResponseBadRequest(form.errors.as_json())\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 406,
"char_end": 483,
"line": " return HttpResponseBadRequest(form.errors.as_json(escape_html=True))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 464,
"char_end": 480,
"chars": "escape_html=True"
}
]
} | github.com/onefork/pontoon-sr/commit/fc07ed9c68e08d41f74c078b4e7727f1a0888be8 | pontoon/batch/views.py | cwe-079 |
make_eb_config | def make_eb_config(application_name, default_region):
# Capture our current directory
UTILS_DIR = os.path.dirname(os.path.abspath(__file__))
# Create the jinja2 environment.
# Notice the use of trim_blocks, which greatly helps control whitespace.
j2_env = Environment(loader=FileSystemLoader(UTILS_DIR))
return j2_env.get_template('templates/eb/config.yml').render(
APPLICATION_NAME=application_name,
DEFAULT_REGION=default_region
) | def make_eb_config(application_name, default_region):
# Capture our current directory
UTILS_DIR = os.path.dirname(os.path.abspath(__file__))
# Create the jinja2 environment.
# Notice the use of trim_blocks, which greatly helps control whitespace.
j2_env = Environment(loader=FileSystemLoader(UTILS_DIR), autoescape=True)
return j2_env.get_template('templates/eb/config.yml').render(
APPLICATION_NAME=application_name,
DEFAULT_REGION=default_region
) | {
"deleted": [
{
"line_no": 6,
"char_start": 263,
"char_end": 324,
"line": " j2_env = Environment(loader=FileSystemLoader(UTILS_DIR))\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 263,
"char_end": 341,
"line": " j2_env = Environment(loader=FileSystemLoader(UTILS_DIR), autoescape=True)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 322,
"char_end": 339,
"chars": ", autoescape=True"
}
]
} | github.com/OkunaOrg/okuna-www-api/commit/8c40c66ea7c483a0cbda4c21940180af909aab99 | utils/make_eb_config.py | cwe-079 |
mode_keepalive | def mode_keepalive(self, request):
"""
This is called by render_POST when the
client is replying to the keepalive.
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time.time(), False)
return '""' | def mode_keepalive(self, request):
"""
This is called by render_POST when the
client is replying to the keepalive.
"""
csessid = cgi.escape(request.args['csessid'][0])
self.last_alive[csessid] = (time.time(), False)
return '""' | {
"deleted": [
{
"line_no": 6,
"char_start": 155,
"char_end": 204,
"line": " csessid = request.args.get('csessid')[0]\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 155,
"char_end": 212,
"line": " csessid = cgi.escape(request.args['csessid'][0])\n"
}
]
} | {
"deleted": [
{
"char_start": 185,
"char_end": 190,
"chars": ".get("
},
{
"char_start": 199,
"char_end": 200,
"chars": ")"
}
],
"added": [
{
"char_start": 173,
"char_end": 184,
"chars": "cgi.escape("
},
{
"char_start": 196,
"char_end": 197,
"chars": "["
},
{
"char_start": 206,
"char_end": 207,
"chars": "]"
},
{
"char_start": 210,
"char_end": 211,
"chars": ")"
}
]
} | github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93 | evennia/server/portal/webclient_ajax.py | cwe-079 |
Logger::addPeer | void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)
{
QWriteLocker locker(&lock);
Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };
m_peers.push_back(temp);
if (m_peers.size() >= MAX_LOG_MESSAGES)
m_peers.pop_front();
emit newLogPeer(temp);
} | void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)
{
QWriteLocker locker(&lock);
Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) };
m_peers.push_back(temp);
if (m_peers.size() >= MAX_LOG_MESSAGES)
m_peers.pop_front();
emit newLogPeer(temp);
} | {
"deleted": [
{
"line_no": 5,
"char_start": 112,
"char_end": 210,
"line": " Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 112,
"char_end": 270,
"line": " Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) };\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 187,
"char_end": 216,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 218,
"char_end": 219,
"chars": ")"
},
{
"char_start": 230,
"char_end": 259,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 265,
"char_end": 266,
"chars": ")"
}
]
} | github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16 | src/base/logger.cpp | cwe-079 |
subscribe_for_tags | @csrf.csrf_protect
def subscribe_for_tags(request):
"""process subscription of users by tags"""
#todo - use special separator to split tags
tag_names = request.REQUEST.get('tags','').strip().split()
pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
if request.user.is_authenticated():
if request.method == 'POST':
if 'ok' in request.POST:
request.user.mark_tags(
pure_tag_names,
wildcards,
reason = 'good',
action = 'add'
)
request.user.message_set.create(
message = _('Your tag subscription was saved, thanks!')
)
else:
message = _(
'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
) % {'url': request.path + '?tags=' + request.REQUEST['tags']}
request.user.message_set.create(message = message)
return HttpResponseRedirect(reverse('index'))
else:
data = {'tags': tag_names}
return render(request, 'subscribe_for_tags.html', data)
else:
all_tag_names = pure_tag_names + wildcards
message = _('Please sign in to subscribe for: %(tags)s') \
% {'tags': ', '.join(all_tag_names)}
request.user.message_set.create(message = message)
request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
return HttpResponseRedirect(url_utils.get_login_url()) | @csrf.csrf_protect
def subscribe_for_tags(request):
"""process subscription of users by tags"""
#todo - use special separator to split tags
tag_names = request.REQUEST.get('tags','').strip().split()
pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
if request.user.is_authenticated():
if request.method == 'POST':
if 'ok' in request.POST:
request.user.mark_tags(
pure_tag_names,
wildcards,
reason = 'good',
action = 'add'
)
request.user.message_set.create(
message = _('Your tag subscription was saved, thanks!')
)
else:
message = _(
'Tag subscription was canceled (<a href="%(url)s">undo</a>).'
) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}
request.user.message_set.create(message = message)
return HttpResponseRedirect(reverse('index'))
else:
data = {'tags': tag_names}
return render(request, 'subscribe_for_tags.html', data)
else:
all_tag_names = pure_tag_names + wildcards
message = _('Please sign in to subscribe for: %(tags)s') \
% {'tags': ', '.join(all_tag_names)}
request.user.message_set.create(message = message)
request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
return HttpResponseRedirect(url_utils.get_login_url()) | {
"deleted": [
{
"line_no": 22,
"char_start": 905,
"char_end": 984,
"line": " ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n"
}
],
"added": [
{
"line_no": 22,
"char_start": 905,
"char_end": 992,
"line": " ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 933,
"char_end": 940,
"chars": "escape("
},
{
"char_start": 952,
"char_end": 953,
"chars": ")"
}
]
} | github.com/ASKBOT/askbot-devel/commit/a676a86b6b7a5737d4da4f59f71e037406f88d29 | askbot/views/commands.py | cwe-079 |
nav_path | def nav_path(request):
"""Return current path as list of items with "name" and "href" members
The href members are view_directory links for directories and view_log
links for files, but are set to None when the link would point to
the current view"""
if not request.repos:
return []
is_dir = request.pathtype == vclib.DIR
# add root item
items = []
root_item = _item(name=request.server.escape(request.repos.name), href=None)
if request.path_parts or request.view_func is not view_directory:
root_item.href = request.get_url(view_func=view_directory,
where='', pathtype=vclib.DIR,
params={}, escape=1)
items.append(root_item)
# add path part items
path_parts = []
for part in request.path_parts:
path_parts.append(part)
is_last = len(path_parts) == len(request.path_parts)
item = _item(name=part, href=None)
if not is_last or (is_dir and request.view_func is not view_directory):
item.href = request.get_url(view_func=view_directory,
where=_path_join(path_parts),
pathtype=vclib.DIR,
params={}, escape=1)
elif not is_dir and request.view_func is not view_log:
item.href = request.get_url(view_func=view_log,
where=_path_join(path_parts),
pathtype=vclib.FILE,
params={}, escape=1)
items.append(item)
return items | def nav_path(request):
"""Return current path as list of items with "name" and "href" members
The href members are view_directory links for directories and view_log
links for files, but are set to None when the link would point to
the current view"""
if not request.repos:
return []
is_dir = request.pathtype == vclib.DIR
# add root item
items = []
root_item = _item(name=request.server.escape(request.repos.name), href=None)
if request.path_parts or request.view_func is not view_directory:
root_item.href = request.get_url(view_func=view_directory,
where='', pathtype=vclib.DIR,
params={}, escape=1)
items.append(root_item)
# add path part items
path_parts = []
for part in request.path_parts:
path_parts.append(part)
is_last = len(path_parts) == len(request.path_parts)
item = _item(name=request.server.escape(part), href=None)
if not is_last or (is_dir and request.view_func is not view_directory):
item.href = request.get_url(view_func=view_directory,
where=_path_join(path_parts),
pathtype=vclib.DIR,
params={}, escape=1)
elif not is_dir and request.view_func is not view_log:
item.href = request.get_url(view_func=view_log,
where=_path_join(path_parts),
pathtype=vclib.FILE,
params={}, escape=1)
items.append(item)
return items | {
"deleted": [
{
"line_no": 28,
"char_start": 897,
"char_end": 936,
"line": " item = _item(name=part, href=None)\n"
}
],
"added": [
{
"line_no": 28,
"char_start": 897,
"char_end": 959,
"line": " item = _item(name=request.server.escape(part), href=None)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 919,
"char_end": 941,
"chars": "request.server.escape("
},
{
"char_start": 945,
"char_end": 946,
"chars": ")"
}
]
} | github.com/viewvc/viewvc/commit/9dcfc7daa4c940992920d3b2fbd317da20e44aad | lib/viewvc.py | cwe-079 |
__init__ | def __init__(self, *args, **kwargs):
"""
Takes two additional keyword arguments:
:param cartpos: The cart position the form should be for
:param event: The event this belongs to
"""
cartpos = self.cartpos = kwargs.pop('cartpos', None)
orderpos = self.orderpos = kwargs.pop('orderpos', None)
pos = cartpos or orderpos
item = pos.item
questions = pos.item.questions_to_ask
event = kwargs.pop('event')
super().__init__(*args, **kwargs)
if item.admission and event.settings.attendee_names_asked:
self.fields['attendee_name_parts'] = NamePartsFormField(
max_length=255,
required=event.settings.attendee_names_required,
scheme=event.settings.name_scheme,
label=_('Attendee name'),
initial=(cartpos.attendee_name_parts if cartpos else orderpos.attendee_name_parts),
)
if item.admission and event.settings.attendee_emails_asked:
self.fields['attendee_email'] = forms.EmailField(
required=event.settings.attendee_emails_required,
label=_('Attendee email'),
initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email)
)
for q in questions:
# Do we already have an answer? Provide it as the initial value
answers = [a for a in pos.answerlist if a.question_id == q.id]
if answers:
initial = answers[0]
else:
initial = None
tz = pytz.timezone(event.settings.timezone)
help_text = rich_text(q.help_text)
if q.type == Question.TYPE_BOOLEAN:
if q.required:
# For some reason, django-bootstrap3 does not set the required attribute
# itself.
widget = forms.CheckboxInput(attrs={'required': 'required'})
else:
widget = forms.CheckboxInput()
if initial:
initialbool = (initial.answer == "True")
else:
initialbool = False
field = forms.BooleanField(
label=q.question, required=q.required,
help_text=help_text,
initial=initialbool, widget=widget,
)
elif q.type == Question.TYPE_NUMBER:
field = forms.DecimalField(
label=q.question, required=q.required,
help_text=q.help_text,
initial=initial.answer if initial else None,
min_value=Decimal('0.00'),
)
elif q.type == Question.TYPE_STRING:
field = forms.CharField(
label=q.question, required=q.required,
help_text=help_text,
initial=initial.answer if initial else None,
)
elif q.type == Question.TYPE_TEXT:
field = forms.CharField(
label=q.question, required=q.required,
help_text=help_text,
widget=forms.Textarea,
initial=initial.answer if initial else None,
)
elif q.type == Question.TYPE_CHOICE:
field = forms.ModelChoiceField(
queryset=q.options,
label=q.question, required=q.required,
help_text=help_text,
widget=forms.Select,
empty_label='',
initial=initial.options.first() if initial else None,
)
elif q.type == Question.TYPE_CHOICE_MULTIPLE:
field = forms.ModelMultipleChoiceField(
queryset=q.options,
label=q.question, required=q.required,
help_text=help_text,
widget=forms.CheckboxSelectMultiple,
initial=initial.options.all() if initial else None,
)
elif q.type == Question.TYPE_FILE:
field = forms.FileField(
label=q.question, required=q.required,
help_text=help_text,
initial=initial.file if initial else None,
widget=UploadedFileWidget(position=pos, event=event, answer=initial),
)
elif q.type == Question.TYPE_DATE:
field = forms.DateField(
label=q.question, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None,
widget=DatePickerWidget(),
)
elif q.type == Question.TYPE_TIME:
field = forms.TimeField(
label=q.question, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None,
widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
)
elif q.type == Question.TYPE_DATETIME:
field = SplitDateTimeField(
label=q.question, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None,
widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
)
field.question = q
if answers:
# Cache the answer object for later use
field.answer = answers[0]
self.fields['question_%s' % q.id] = field
responses = question_form_fields.send(sender=event, position=pos)
data = pos.meta_info_data
for r, response in sorted(responses, key=lambda r: str(r[0])):
for key, value in response.items():
# We need to be this explicit, since OrderedDict.update does not retain ordering
self.fields[key] = value
value.initial = data.get('question_form_data', {}).get(key) | def __init__(self, *args, **kwargs):
"""
Takes two additional keyword arguments:
:param cartpos: The cart position the form should be for
:param event: The event this belongs to
"""
cartpos = self.cartpos = kwargs.pop('cartpos', None)
orderpos = self.orderpos = kwargs.pop('orderpos', None)
pos = cartpos or orderpos
item = pos.item
questions = pos.item.questions_to_ask
event = kwargs.pop('event')
super().__init__(*args, **kwargs)
if item.admission and event.settings.attendee_names_asked:
self.fields['attendee_name_parts'] = NamePartsFormField(
max_length=255,
required=event.settings.attendee_names_required,
scheme=event.settings.name_scheme,
label=_('Attendee name'),
initial=(cartpos.attendee_name_parts if cartpos else orderpos.attendee_name_parts),
)
if item.admission and event.settings.attendee_emails_asked:
self.fields['attendee_email'] = forms.EmailField(
required=event.settings.attendee_emails_required,
label=_('Attendee email'),
initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email)
)
for q in questions:
# Do we already have an answer? Provide it as the initial value
answers = [a for a in pos.answerlist if a.question_id == q.id]
if answers:
initial = answers[0]
else:
initial = None
tz = pytz.timezone(event.settings.timezone)
help_text = rich_text(q.help_text)
label = escape(q.question) # django-bootstrap3 calls mark_safe
if q.type == Question.TYPE_BOOLEAN:
if q.required:
# For some reason, django-bootstrap3 does not set the required attribute
# itself.
widget = forms.CheckboxInput(attrs={'required': 'required'})
else:
widget = forms.CheckboxInput()
if initial:
initialbool = (initial.answer == "True")
else:
initialbool = False
field = forms.BooleanField(
label=label, required=q.required,
help_text=help_text,
initial=initialbool, widget=widget,
)
elif q.type == Question.TYPE_NUMBER:
field = forms.DecimalField(
label=label, required=q.required,
help_text=q.help_text,
initial=initial.answer if initial else None,
min_value=Decimal('0.00'),
)
elif q.type == Question.TYPE_STRING:
field = forms.CharField(
label=label, required=q.required,
help_text=help_text,
initial=initial.answer if initial else None,
)
elif q.type == Question.TYPE_TEXT:
field = forms.CharField(
label=label, required=q.required,
help_text=help_text,
widget=forms.Textarea,
initial=initial.answer if initial else None,
)
elif q.type == Question.TYPE_CHOICE:
field = forms.ModelChoiceField(
queryset=q.options,
label=label, required=q.required,
help_text=help_text,
widget=forms.Select,
empty_label='',
initial=initial.options.first() if initial else None,
)
elif q.type == Question.TYPE_CHOICE_MULTIPLE:
field = forms.ModelMultipleChoiceField(
queryset=q.options,
label=label, required=q.required,
help_text=help_text,
widget=forms.CheckboxSelectMultiple,
initial=initial.options.all() if initial else None,
)
elif q.type == Question.TYPE_FILE:
field = forms.FileField(
label=label, required=q.required,
help_text=help_text,
initial=initial.file if initial else None,
widget=UploadedFileWidget(position=pos, event=event, answer=initial),
)
elif q.type == Question.TYPE_DATE:
field = forms.DateField(
label=label, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None,
widget=DatePickerWidget(),
)
elif q.type == Question.TYPE_TIME:
field = forms.TimeField(
label=label, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None,
widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
)
elif q.type == Question.TYPE_DATETIME:
field = SplitDateTimeField(
label=label, required=q.required,
help_text=help_text,
initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None,
widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
)
field.question = q
if answers:
# Cache the answer object for later use
field.answer = answers[0]
self.fields['question_%s' % q.id] = field
responses = question_form_fields.send(sender=event, position=pos)
data = pos.meta_info_data
for r, response in sorted(responses, key=lambda r: str(r[0])):
for key, value in response.items():
# We need to be this explicit, since OrderedDict.update does not retain ordering
self.fields[key] = value
value.initial = data.get('question_form_data', {}).get(key) | {
"deleted": [
{
"line_no": 55,
"char_start": 2264,
"char_end": 2323,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 61,
"char_start": 2531,
"char_end": 2590,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 68,
"char_start": 2853,
"char_end": 2912,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 74,
"char_start": 3124,
"char_end": 3183,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 82,
"char_start": 3487,
"char_end": 3546,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 91,
"char_start": 3910,
"char_end": 3969,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 98,
"char_start": 4245,
"char_end": 4304,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 105,
"char_start": 4604,
"char_end": 4663,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 112,
"char_start": 4971,
"char_end": 5030,
"line": " label=q.question, required=q.required,\n"
},
{
"line_no": 119,
"char_start": 5405,
"char_end": 5464,
"line": " label=q.question, required=q.required,\n"
}
],
"added": [
{
"line_no": 41,
"char_start": 1711,
"char_end": 1787,
"line": " label = escape(q.question) # django-bootstrap3 calls mark_safe\n"
},
{
"line_no": 56,
"char_start": 2340,
"char_end": 2394,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 62,
"char_start": 2602,
"char_end": 2656,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 69,
"char_start": 2919,
"char_end": 2973,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 75,
"char_start": 3185,
"char_end": 3239,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 83,
"char_start": 3543,
"char_end": 3597,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 92,
"char_start": 3961,
"char_end": 4015,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 99,
"char_start": 4291,
"char_end": 4345,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 106,
"char_start": 4645,
"char_end": 4699,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 113,
"char_start": 5007,
"char_end": 5061,
"line": " label=label, required=q.required,\n"
},
{
"line_no": 120,
"char_start": 5436,
"char_end": 5490,
"line": " label=label, required=q.required,\n"
}
]
} | {
"deleted": [
{
"char_start": 1759,
"char_end": 1759,
"chars": ""
},
{
"char_start": 2290,
"char_end": 2294,
"chars": "q.qu"
},
{
"char_start": 2295,
"char_end": 2300,
"chars": "stion"
},
{
"char_start": 2557,
"char_end": 2561,
"chars": "q.qu"
},
{
"char_start": 2562,
"char_end": 2567,
"chars": "stion"
},
{
"char_start": 2879,
"char_end": 2883,
"chars": "q.qu"
},
{
"char_start": 2884,
"char_end": 2889,
"chars": "stion"
},
{
"char_start": 3150,
"char_end": 3154,
"chars": "q.qu"
},
{
"char_start": 3155,
"char_end": 3160,
"chars": "stion"
},
{
"char_start": 3513,
"char_end": 3517,
"chars": "q.qu"
},
{
"char_start": 3518,
"char_end": 3523,
"chars": "stion"
},
{
"char_start": 3936,
"char_end": 3940,
"chars": "q.qu"
},
{
"char_start": 3941,
"char_end": 3946,
"chars": "stion"
},
{
"char_start": 4271,
"char_end": 4275,
"chars": "q.qu"
},
{
"char_start": 4276,
"char_end": 4281,
"chars": "stion"
},
{
"char_start": 4630,
"char_end": 4634,
"chars": "q.qu"
},
{
"char_start": 4635,
"char_end": 4640,
"chars": "stion"
},
{
"char_start": 4997,
"char_end": 5001,
"chars": "q.qu"
},
{
"char_start": 5002,
"char_end": 5007,
"chars": "stion"
},
{
"char_start": 5431,
"char_end": 5435,
"chars": "q.qu"
},
{
"char_start": 5436,
"char_end": 5441,
"chars": "stion"
}
],
"added": [
{
"char_start": 1723,
"char_end": 1799,
"chars": "label = escape(q.question) # django-bootstrap3 calls mark_safe\n "
},
{
"char_start": 2366,
"char_end": 2369,
"chars": "lab"
},
{
"char_start": 2370,
"char_end": 2371,
"chars": "l"
},
{
"char_start": 2628,
"char_end": 2631,
"chars": "lab"
},
{
"char_start": 2632,
"char_end": 2633,
"chars": "l"
},
{
"char_start": 2945,
"char_end": 2948,
"chars": "lab"
},
{
"char_start": 2949,
"char_end": 2950,
"chars": "l"
},
{
"char_start": 3211,
"char_end": 3214,
"chars": "lab"
},
{
"char_start": 3215,
"char_end": 3216,
"chars": "l"
},
{
"char_start": 3569,
"char_end": 3572,
"chars": "lab"
},
{
"char_start": 3573,
"char_end": 3574,
"chars": "l"
},
{
"char_start": 3987,
"char_end": 3990,
"chars": "lab"
},
{
"char_start": 3991,
"char_end": 3992,
"chars": "l"
},
{
"char_start": 4317,
"char_end": 4320,
"chars": "lab"
},
{
"char_start": 4321,
"char_end": 4322,
"chars": "l"
},
{
"char_start": 4671,
"char_end": 4674,
"chars": "lab"
},
{
"char_start": 4675,
"char_end": 4676,
"chars": "l"
},
{
"char_start": 5033,
"char_end": 5036,
"chars": "lab"
},
{
"char_start": 5037,
"char_end": 5038,
"chars": "l"
},
{
"char_start": 5462,
"char_end": 5465,
"chars": "lab"
},
{
"char_start": 5466,
"char_end": 5467,
"chars": "l"
}
]
} | github.com/pretix/pretix/commit/affc6254a8316643d4afe9e8b7f8cd288c86ca1f | src/pretix/base/forms/questions.py | cwe-079 |
link_dialog | def link_dialog(request):
# list of wiki pages
name = request.values.get("pagename", "")
if name:
from MoinMoin import search
# XXX error handling!
searchresult = search.searchPages(request, 't:"%s"' % name)
pages = [p.page_name for p in searchresult.hits]
pages.sort()
pages[0:0] = [name]
page_list = '''
<tr>
<td colspan=2>
<select id="sctPagename" size="1" onchange="OnChangePagename(this.value);">
%s
</select>
<td>
</tr>
''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page))
for page in pages])
else:
page_list = ""
# list of interwiki names
interwiki_list = wikiutil.load_wikimap(request)
interwiki = interwiki_list.keys()
interwiki.sort()
iwpreferred = request.cfg.interwiki_preferred[:]
if not iwpreferred or iwpreferred and iwpreferred[-1] is not None:
resultlist = iwpreferred
for iw in interwiki:
if not iw in iwpreferred:
resultlist.append(iw)
else:
resultlist = iwpreferred[:-1]
interwiki = "\n".join(
['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key))
for key in resultlist])
# wiki url
url_prefix_static = request.cfg.url_prefix_static
scriptname = request.script_root + '/'
action = scriptname
basepage = wikiutil.escape(request.page.page_name)
request.write(u'''
<!--
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2004 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* File Name: fck_link.html
* Link dialog window.
*
* Version: 2.0 FC (Preview)
* Modified: 2005-02-18 23:55:22
*
* File Authors:
* Frederico Caldeira Knabben ([email protected])
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="robots" content="index,nofollow">
<html>
<head>
<title>Link Properties</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow" />
<script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script>
<script src="%(url_prefix_static)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script>
<script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script>
</head>
<body scroll="no" style="OVERFLOW: hidden">
<div id="divInfo" style="DISPLAY: none">
<span fckLang="DlgLnkType">Link Type</span><br />
<select id="cmbLinkType" onchange="SetLinkType(this.value);">
<option value="wiki" selected="selected">WikiPage</option>
<option value="interwiki">Interwiki</option>
<option value="url" fckLang="DlgLnkTypeURL">URL</option>
</select>
<br />
<br />
<div id="divLinkTypeWiki">
<table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0">
<tr>
<td>
<form action=%(action)s method="GET">
<input type="hidden" name="action" value="fckdialog">
<input type="hidden" name="dialog" value="link">
<input type="hidden" id="basepage" name="basepage" value="%(basepage)s">
<table cellSpacing="0" cellPadding="0" align="center" border="0">
<tr>
<td>
<span fckLang="PageDlgName">Page Name</span><br>
<input id="txtPagename" name="pagename" size="30" value="%(name)s">
</td>
<td valign="bottom">
<input id=btnSearchpage type="submit" value="Search">
</td>
</tr>
%(page_list)s
</table>
</form>
</td>
</tr>
</table>
</div>
<div id="divLinkTypeInterwiki">
<table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0">
<tr>
<td>
<table cellSpacing="0" cellPadding="0" align="center" border="0">
<tr>
<td>
<span fckLang="WikiDlgName">Wiki:PageName</span><br>
<select id="sctInterwiki" size="1">
%(interwiki)s
</select>:
<input id="txtInterwikipagename"></input>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="divLinkTypeUrl">
<table cellspacing="0" cellpadding="0" width="100%%" border="0">
<tr>
<td nowrap="nowrap">
<span fckLang="DlgLnkProto">Protocol</span><br />
<select id="cmbLinkProtocol">
<option value="http://" selected="selected">http://</option>
<option value="https://">https://</option>
<option value="ftp://">ftp://</option>
<option value="file://">file://</option>
<option value="news://">news://</option>
<option value="mailto:">mailto:</option>
<option value="" fckLang="DlgLnkProtoOther"><other></option>
</select>
</td>
<td nowrap="nowrap"> </td>
<td nowrap="nowrap" width="100%%">
<span fckLang="DlgLnkURL">URL</span><br />
<input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" />
</td>
</tr>
</table>
<br />
</div>
</div>
</body>
</html>
''' % locals()) | def link_dialog(request):
# list of wiki pages
name = request.values.get("pagename", "")
name_escaped = wikiutil.escape(name)
if name:
from MoinMoin import search
# XXX error handling!
searchresult = search.searchPages(request, 't:"%s"' % name)
pages = [p.page_name for p in searchresult.hits]
pages.sort()
pages[0:0] = [name]
page_list = '''
<tr>
<td colspan=2>
<select id="sctPagename" size="1" onchange="OnChangePagename(this.value);">
%s
</select>
<td>
</tr>
''' % "\n".join(['<option value="%s">%s</option>' % (wikiutil.escape(page), wikiutil.escape(page))
for page in pages])
else:
page_list = ""
# list of interwiki names
interwiki_list = wikiutil.load_wikimap(request)
interwiki = interwiki_list.keys()
interwiki.sort()
iwpreferred = request.cfg.interwiki_preferred[:]
if not iwpreferred or iwpreferred and iwpreferred[-1] is not None:
resultlist = iwpreferred
for iw in interwiki:
if not iw in iwpreferred:
resultlist.append(iw)
else:
resultlist = iwpreferred[:-1]
interwiki = "\n".join(
['<option value="%s">%s</option>' % (wikiutil.escape(key), wikiutil.escape(key))
for key in resultlist])
# wiki url
url_prefix_static = request.cfg.url_prefix_static
scriptname = request.script_root + '/'
action = scriptname
basepage = wikiutil.escape(request.page.page_name)
request.write(u'''
<!--
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2004 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* File Name: fck_link.html
* Link dialog window.
*
* Version: 2.0 FC (Preview)
* Modified: 2005-02-18 23:55:22
*
* File Authors:
* Frederico Caldeira Knabben ([email protected])
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="robots" content="index,nofollow">
<html>
<head>
<title>Link Properties</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow" />
<script src="%(url_prefix_static)s/applets/FCKeditor/editor/dialog/common/fck_dialog_common.js" type="text/javascript"></script>
<script src="%(url_prefix_static)s/applets/moinFCKplugins/moinlink/fck_link.js" type="text/javascript"></script>
<script src="%(url_prefix_static)s/applets/moinFCKplugins/moinurllib.js" type="text/javascript"></script>
</head>
<body scroll="no" style="OVERFLOW: hidden">
<div id="divInfo" style="DISPLAY: none">
<span fckLang="DlgLnkType">Link Type</span><br />
<select id="cmbLinkType" onchange="SetLinkType(this.value);">
<option value="wiki" selected="selected">WikiPage</option>
<option value="interwiki">Interwiki</option>
<option value="url" fckLang="DlgLnkTypeURL">URL</option>
</select>
<br />
<br />
<div id="divLinkTypeWiki">
<table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0">
<tr>
<td>
<form action=%(action)s method="GET">
<input type="hidden" name="action" value="fckdialog">
<input type="hidden" name="dialog" value="link">
<input type="hidden" id="basepage" name="basepage" value="%(basepage)s">
<table cellSpacing="0" cellPadding="0" align="center" border="0">
<tr>
<td>
<span fckLang="PageDlgName">Page Name</span><br>
<input id="txtPagename" name="pagename" size="30" value="%(name_escaped)s">
</td>
<td valign="bottom">
<input id=btnSearchpage type="submit" value="Search">
</td>
</tr>
%(page_list)s
</table>
</form>
</td>
</tr>
</table>
</div>
<div id="divLinkTypeInterwiki">
<table height="100%%" cellSpacing="0" cellPadding="0" width="100%%" border="0">
<tr>
<td>
<table cellSpacing="0" cellPadding="0" align="center" border="0">
<tr>
<td>
<span fckLang="WikiDlgName">Wiki:PageName</span><br>
<select id="sctInterwiki" size="1">
%(interwiki)s
</select>:
<input id="txtInterwikipagename"></input>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div id="divLinkTypeUrl">
<table cellspacing="0" cellpadding="0" width="100%%" border="0">
<tr>
<td nowrap="nowrap">
<span fckLang="DlgLnkProto">Protocol</span><br />
<select id="cmbLinkProtocol">
<option value="http://" selected="selected">http://</option>
<option value="https://">https://</option>
<option value="ftp://">ftp://</option>
<option value="file://">file://</option>
<option value="news://">news://</option>
<option value="mailto:">mailto:</option>
<option value="" fckLang="DlgLnkProtoOther"><other></option>
</select>
</td>
<td nowrap="nowrap"> </td>
<td nowrap="nowrap" width="100%%">
<span fckLang="DlgLnkURL">URL</span><br />
<input id="txtUrl" style="WIDTH: 100%%" type="text" onkeyup="OnUrlChange();" onchange="OnUrlChange();" />
</td>
</tr>
</table>
<br />
</div>
</div>
</body>
</html>
''' % locals()) | {
"deleted": [
{
"line_no": 100,
"char_start": 3711,
"char_end": 3789,
"line": " <input id=\"txtPagename\" name=\"pagename\" size=\"30\" value=\"%(name)s\">\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 97,
"char_end": 138,
"line": " name_escaped = wikiutil.escape(name)\n"
},
{
"line_no": 101,
"char_start": 3752,
"char_end": 3838,
"line": " <input id=\"txtPagename\" name=\"pagename\" size=\"30\" value=\"%(name_escaped)s\">\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 101,
"char_end": 142,
"chars": "name_escaped = wikiutil.escape(name)\n "
},
{
"char_start": 3825,
"char_end": 3833,
"chars": "_escaped"
}
]
} | github.com/moinwiki/moin-1.9/commit/70955a8eae091cc88fd9a6e510177e70289ec024 | MoinMoin/action/fckdialog.py | cwe-079 |
action_save_user | def action_save_user(request: HttpRequest, default_forward_url: str = "/admin/users"):
"""
This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse
:param request: the HttpRequest
:param default_forward_url: The URL to forward to if nothing was specified
:return: The crafted HttpResponse
"""
forward_url = default_forward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
if not request.user.is_authenticated:
return HttpResponseForbidden()
profile = Profile.objects.get(authuser=request.user)
if profile.rights < 2:
return HttpResponseForbidden()
try:
if request.GET.get("user_id"):
pid = int(request.GET["user_id"])
displayname = str(request.POST["display_name"])
dect = int(request.POST["dect"])
notes = str(request.POST["notes"])
pw1 = str(request.POST["password"])
pw2 = str(request.POST["confirm_password"])
mail = str(request.POST["email"])
rights = int(request.POST["rights"])
user: Profile = Profile.objects.get(pk=pid)
user.displayName = displayname
user.dect = dect
user.notes = notes
user.rights = rights
user.number_of_allowed_reservations = int(request.POST["allowed_reservations"])
if request.POST.get("active"):
user.active = magic.parse_bool(request.POST["active"])
au: User = user.authuser
if check_password_conformity(pw1, pw2):
logging.log(logging.INFO, "Set password for user: " + user.displayName)
au.set_password(pw1)
else:
logging.log(logging.INFO, "Failed to set password for: " + user.displayName)
au.email = mail
au.save()
user.save()
else:
# assume new user
username = str(request.POST["username"])
displayname = str(request.POST["display_name"])
dect = int(request.POST["dect"])
notes = str(request.POST["notes"])
pw1 = str(request.POST["password"])
pw2 = str(request.POST["confirm_password"])
mail = str(request.POST["email"])
rights = int(request.POST["rights"])
if not check_password_conformity(pw1, pw2):
recreate_form('password mismatch')
auth_user: User = User.objects.create_user(username=username, email=mail, password=pw1)
auth_user.save()
user: Profile = Profile()
user.rights = rights
user.number_of_allowed_reservations = int(request.POST["allowed_reservations"])
user.displayName = displayname
user.authuser = auth_user
user.dect = dect
user.notes = notes
user.active = True
user.save()
pass
pass
except Exception as e:
return HttpResponseBadRequest(str(e))
return redirect(forward_url) | def action_save_user(request: HttpRequest, default_forward_url: str = "/admin/users"):
"""
This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse
:param request: the HttpRequest
:param default_forward_url: The URL to forward to if nothing was specified
:return: The crafted HttpResponse
"""
forward_url = default_forward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
if not request.user.is_authenticated:
return HttpResponseForbidden()
profile = Profile.objects.get(authuser=request.user)
if profile.rights < 2:
return HttpResponseForbidden()
try:
if request.GET.get("user_id"):
pid = int(request.GET["user_id"])
displayname = str(request.POST["display_name"])
dect = int(request.POST["dect"])
notes = str(request.POST["notes"])
pw1 = str(request.POST["password"])
pw2 = str(request.POST["confirm_password"])
mail = str(request.POST["email"])
rights = int(request.POST["rights"])
user: Profile = Profile.objects.get(pk=pid)
user.displayName = escape(displayname)
user.dect = dect
user.notes = escape(notes)
user.rights = rights
user.number_of_allowed_reservations = int(request.POST["allowed_reservations"])
if request.POST.get("active"):
user.active = magic.parse_bool(request.POST["active"])
au: User = user.authuser
if check_password_conformity(pw1, pw2):
logging.log(logging.INFO, "Set password for user: " + user.displayName)
au.set_password(pw1)
else:
logging.log(logging.INFO, "Failed to set password for: " + user.displayName)
au.email = escape(mail)
au.save()
user.save()
else:
# assume new user
username = str(request.POST["username"])
displayname = str(request.POST["display_name"])
dect = int(request.POST["dect"])
notes = str(request.POST["notes"])
pw1 = str(request.POST["password"])
pw2 = str(request.POST["confirm_password"])
mail = str(request.POST["email"])
rights = int(request.POST["rights"])
if not check_password_conformity(pw1, pw2):
recreate_form('password mismatch')
auth_user: User = User.objects.create_user(username=escape(username), email=escape(mail), password=pw1)
auth_user.save()
user: Profile = Profile()
user.rights = rights
user.number_of_allowed_reservations = int(request.POST["allowed_reservations"])
user.displayName = escape(displayname)
user.authuser = auth_user
user.dect = dect
user.notes = escape(notes)
user.active = True
user.save()
pass
pass
except Exception as e:
return HttpResponseBadRequest(str(e))
return redirect(forward_url) | {
"deleted": [
{
"line_no": 27,
"char_start": 1188,
"char_end": 1231,
"line": " user.displayName = displayname\n"
},
{
"line_no": 29,
"char_start": 1260,
"char_end": 1291,
"line": " user.notes = notes\n"
},
{
"line_no": 40,
"char_start": 1855,
"char_end": 1883,
"line": " au.email = mail\n"
},
{
"line_no": 55,
"char_start": 2484,
"char_end": 2584,
"line": " auth_user: User = User.objects.create_user(username=username, email=mail, password=pw1)\n"
},
{
"line_no": 60,
"char_start": 2776,
"char_end": 2819,
"line": " user.displayName = displayname\n"
},
{
"line_no": 63,
"char_start": 2886,
"char_end": 2917,
"line": " user.notes = notes\n"
}
],
"added": [
{
"line_no": 27,
"char_start": 1188,
"char_end": 1239,
"line": " user.displayName = escape(displayname)\n"
},
{
"line_no": 29,
"char_start": 1268,
"char_end": 1307,
"line": " user.notes = escape(notes)\n"
},
{
"line_no": 40,
"char_start": 1871,
"char_end": 1907,
"line": " au.email = escape(mail)\n"
},
{
"line_no": 55,
"char_start": 2508,
"char_end": 2624,
"line": " auth_user: User = User.objects.create_user(username=escape(username), email=escape(mail), password=pw1)\n"
},
{
"line_no": 60,
"char_start": 2816,
"char_end": 2867,
"line": " user.displayName = escape(displayname)\n"
},
{
"line_no": 63,
"char_start": 2934,
"char_end": 2973,
"line": " user.notes = escape(notes)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1219,
"char_end": 1226,
"chars": "escape("
},
{
"char_start": 1237,
"char_end": 1238,
"chars": ")"
},
{
"char_start": 1293,
"char_end": 1300,
"chars": "escape("
},
{
"char_start": 1305,
"char_end": 1306,
"chars": ")"
},
{
"char_start": 1894,
"char_end": 1901,
"chars": "escape("
},
{
"char_start": 1905,
"char_end": 1906,
"chars": ")"
},
{
"char_start": 2572,
"char_end": 2579,
"chars": "escape("
},
{
"char_start": 2587,
"char_end": 2588,
"chars": ")"
},
{
"char_start": 2596,
"char_end": 2603,
"chars": "escape("
},
{
"char_start": 2607,
"char_end": 2608,
"chars": ")"
},
{
"char_start": 2847,
"char_end": 2854,
"chars": "escape("
},
{
"char_start": 2865,
"char_end": 2866,
"chars": ")"
},
{
"char_start": 2959,
"char_end": 2966,
"chars": "escape("
},
{
"char_start": 2971,
"char_end": 2972,
"chars": ")"
}
]
} | github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600 | c3shop/frontpage/management/edit_user.py | cwe-079 |
save | def save(self):
# copy the user's input from plain text to description to be processed
self.description = self.description_plain_text
if CE.settings.auto_cross_reference:
self.auto_cross_ref()
else:
self.find_tag()
self.slug = slugify(self.title)
super().save() | def save(self):
# copy the user's input from plain text to description to be processed
# uses bleach to remove potentially harmful HTML code
self.description = bleach.clean(str(self.description_plain_text),
tags=CE.settings.bleach_allowed,
strip=True)
if CE.settings.auto_cross_reference:
self.auto_cross_ref()
else:
self.find_tag()
self.slug = slugify(self.title)
super().save() | {
"deleted": [
{
"line_no": 3,
"char_start": 99,
"char_end": 154,
"line": " self.description = self.description_plain_text\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 161,
"char_end": 235,
"line": " self.description = bleach.clean(str(self.description_plain_text),\n"
},
{
"line_no": 5,
"char_start": 235,
"char_end": 308,
"line": " tags=CE.settings.bleach_allowed,\n"
},
{
"line_no": 6,
"char_start": 308,
"char_end": 360,
"line": " strip=True)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 107,
"char_end": 169,
"chars": "# uses bleach to remove potentially harmful HTML code\n "
},
{
"char_start": 188,
"char_end": 205,
"chars": "bleach.clean(str("
},
{
"char_start": 232,
"char_end": 359,
"chars": "),\n tags=CE.settings.bleach_allowed,\n strip=True)"
}
]
} | github.com/stevetasticsteve/CLA_Hub/commit/a06d85cd0b0964f8469e5c4bc9a6c132aa0b4c37 | CE/models.py | cwe-079 |
PropertiesWidget::loadTorrentInfos | void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)
{
clear();
m_torrent = torrent;
downloaded_pieces->setTorrent(m_torrent);
pieces_availability->setTorrent(m_torrent);
if (!m_torrent) return;
// Save path
updateSavePath(m_torrent);
// Hash
hash_lbl->setText(m_torrent->hash());
PropListModel->model()->clear();
if (m_torrent->hasMetadata()) {
// Creation date
lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));
label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));
// Comment
comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));
// URL seeds
loadUrlSeeds();
label_created_by_val->setText(m_torrent->creator());
// List files in torrent
PropListModel->model()->setupModelData(m_torrent->info());
filesList->setExpanded(PropListModel->index(0, 0), true);
// Load file priorities
PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());
}
// Load dynamic data
loadDynamicData();
} | void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)
{
clear();
m_torrent = torrent;
downloaded_pieces->setTorrent(m_torrent);
pieces_availability->setTorrent(m_torrent);
if (!m_torrent) return;
// Save path
updateSavePath(m_torrent);
// Hash
hash_lbl->setText(m_torrent->hash());
PropListModel->model()->clear();
if (m_torrent->hasMetadata()) {
// Creation date
lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));
label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));
// Comment
comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment())));
// URL seeds
loadUrlSeeds();
label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator()));
// List files in torrent
PropListModel->model()->setupModelData(m_torrent->info());
filesList->setExpanded(PropListModel->index(0, 0), true);
// Load file priorities
PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());
}
// Load dynamic data
loadDynamicData();
} | {
"deleted": [
{
"line_no": 21,
"char_start": 655,
"char_end": 737,
"line": " comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));\n"
},
{
"line_no": 26,
"char_start": 784,
"char_end": 845,
"line": " label_created_by_val->setText(m_torrent->creator());\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 655,
"char_end": 767,
"line": " comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment())));\n"
},
{
"line_no": 26,
"char_start": 814,
"char_end": 905,
"line": " label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator()));\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 713,
"char_end": 742,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 761,
"char_end": 762,
"chars": ")"
},
{
"char_start": 852,
"char_end": 881,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 900,
"char_end": 901,
"chars": ")"
}
]
} | github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16 | src/gui/properties/propertieswidget.cpp | cwe-079 |
mode_close | def mode_close(self, request):
"""
This is called by render_POST when the client is signalling
that it is about to be closed.
Args:
request (Request): Incoming request.
"""
csessid = request.args.get('csessid')[0]
try:
sess = self.sessionhandler.sessions_from_csessid(csessid)[0]
sess.sessionhandler.disconnect(sess)
except IndexError:
self.client_disconnect(csessid)
return '""' | def mode_close(self, request):
"""
This is called by render_POST when the client is signalling
that it is about to be closed.
Args:
request (Request): Incoming request.
"""
csessid = cgi.escape(request.args['csessid'][0])
try:
sess = self.sessionhandler.sessions_from_csessid(csessid)[0]
sess.sessionhandler.disconnect(sess)
except IndexError:
self.client_disconnect(csessid)
return '""' | {
"deleted": [
{
"line_no": 10,
"char_start": 231,
"char_end": 280,
"line": " csessid = request.args.get('csessid')[0]\n"
}
],
"added": [
{
"line_no": 10,
"char_start": 231,
"char_end": 288,
"line": " csessid = cgi.escape(request.args['csessid'][0])\n"
}
]
} | {
"deleted": [
{
"char_start": 261,
"char_end": 266,
"chars": ".get("
},
{
"char_start": 275,
"char_end": 276,
"chars": ")"
}
],
"added": [
{
"char_start": 249,
"char_end": 260,
"chars": "cgi.escape("
},
{
"char_start": 272,
"char_end": 273,
"chars": "["
},
{
"char_start": 282,
"char_end": 283,
"chars": "]"
},
{
"char_start": 286,
"char_end": 287,
"chars": ")"
}
]
} | github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93 | evennia/server/portal/webclient_ajax.py | cwe-079 |
get_queryset | def get_queryset(self, **kwargs):
queryset = Article.objects.order_by('-time')
for i in queryset:
i.md = markdown(i.content, extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
])
return queryset | def get_queryset(self, **kwargs):
queryset = Article.objects.order_by('-time')
for i in queryset:
i.md = safe_md(i.content)
return queryset | {
"deleted": [
{
"line_no": 4,
"char_start": 118,
"char_end": 170,
"line": " i.md = markdown(i.content, extensions=[\n"
},
{
"line_no": 5,
"char_start": 170,
"char_end": 215,
"line": " 'markdown.extensions.extra',\n"
},
{
"line_no": 6,
"char_start": 215,
"char_end": 265,
"line": " 'markdown.extensions.codehilite',\n"
},
{
"line_no": 7,
"char_start": 265,
"char_end": 308,
"line": " 'markdown.extensions.toc',\n"
},
{
"line_no": 8,
"char_start": 308,
"char_end": 323,
"line": " ])\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 118,
"char_end": 156,
"line": " i.md = safe_md(i.content)\n"
}
]
} | {
"deleted": [
{
"char_start": 137,
"char_end": 162,
"chars": "markdown(i.content, exten"
},
{
"char_start": 163,
"char_end": 188,
"chars": "ions=[\n 'm"
},
{
"char_start": 189,
"char_end": 196,
"chars": "rkdown."
},
{
"char_start": 197,
"char_end": 232,
"chars": "xtensions.extra',\n '"
},
{
"char_start": 233,
"char_end": 236,
"chars": "ark"
},
{
"char_start": 237,
"char_end": 247,
"chars": "own.extens"
},
{
"char_start": 248,
"char_end": 251,
"chars": "ons"
},
{
"char_start": 254,
"char_end": 289,
"chars": "dehilite',\n 'markdow"
},
{
"char_start": 290,
"char_end": 293,
"chars": ".ex"
},
{
"char_start": 296,
"char_end": 302,
"chars": "sions."
},
{
"char_start": 303,
"char_end": 321,
"chars": "oc',\n ]"
}
],
"added": [
{
"char_start": 139,
"char_end": 140,
"chars": "f"
},
{
"char_start": 141,
"char_end": 142,
"chars": "_"
},
{
"char_start": 144,
"char_end": 145,
"chars": "("
}
]
} | github.com/Cheng-mq1216/production-practice/commit/333dc34f5feada55d1f6ff1255949ca00dec0f9c | app/Index/views.py | cwe-079 |
screenshotcommentcounts | @register.tag
@basictag(takes_context=True)
def screenshotcommentcounts(context, screenshot):
"""
Returns a JSON array of current comments for a screenshot.
Each entry in the array has a dictionary containing the following keys:
=========== ==================================================
Key Description
=========== ==================================================
text The text of the comment
localdraft True if this is the current user's draft comment
x The X location of the comment's region
y The Y location of the comment's region
w The width of the comment's region
h The height of the comment's region
=========== ==================================================
"""
comments = {}
user = context.get('user', None)
for comment in screenshot.comments.all():
review = get_object_or_none(comment.review)
if review and (review.public or review.user == user):
position = '%dx%d+%d+%d' % (comment.w, comment.h, \
comment.x, comment.y)
comments.setdefault(position, []).append({
'id': comment.id,
'text': comment.text,
'user': {
'username': review.user.username,
'name': review.user.get_full_name() or review.user.username,
},
'url': comment.get_review_url(),
'localdraft' : review.user == user and \
not review.public,
'x' : comment.x,
'y' : comment.y,
'w' : comment.w,
'h' : comment.h,
})
return simplejson.dumps(comments) | @register.tag
@basictag(takes_context=True)
def screenshotcommentcounts(context, screenshot):
"""
Returns a JSON array of current comments for a screenshot.
Each entry in the array has a dictionary containing the following keys:
=========== ==================================================
Key Description
=========== ==================================================
text The text of the comment
localdraft True if this is the current user's draft comment
x The X location of the comment's region
y The Y location of the comment's region
w The width of the comment's region
h The height of the comment's region
=========== ==================================================
"""
comments = {}
user = context.get('user', None)
for comment in screenshot.comments.all():
review = get_object_or_none(comment.review)
if review and (review.public or review.user == user):
position = '%dx%d+%d+%d' % (comment.w, comment.h, \
comment.x, comment.y)
comments.setdefault(position, []).append({
'id': comment.id,
'text': escape(comment.text),
'user': {
'username': review.user.username,
'name': review.user.get_full_name() or review.user.username,
},
'url': comment.get_review_url(),
'localdraft' : review.user == user and \
not review.public,
'x' : comment.x,
'y' : comment.y,
'w' : comment.w,
'h' : comment.h,
})
return simplejson.dumps(comments) | {
"deleted": [
{
"line_no": 32,
"char_start": 1249,
"char_end": 1287,
"line": " 'text': comment.text,\n"
}
],
"added": [
{
"line_no": 32,
"char_start": 1249,
"char_end": 1295,
"line": " 'text': escape(comment.text),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1273,
"char_end": 1280,
"chars": "escape("
},
{
"char_start": 1292,
"char_end": 1293,
"chars": ")"
}
]
} | github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d | reviewboard/reviews/templatetags/reviewtags.py | cwe-079 |
mode_input | def mode_input(self, request):
"""
This is called by render_POST when the client
is sending data to the server.
Args:
request (Request): Incoming request.
"""
csessid = request.args.get('csessid')[0]
self.last_alive[csessid] = (time.time(), False)
sess = self.sessionhandler.sessions_from_csessid(csessid)
if sess:
sess = sess[0]
cmdarray = json.loads(request.args.get('data')[0])
sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]})
return '""' | def mode_input(self, request):
"""
This is called by render_POST when the client
is sending data to the server.
Args:
request (Request): Incoming request.
"""
csessid = cgi.escape(request.args['csessid'][0])
self.last_alive[csessid] = (time.time(), False)
sess = self.sessionhandler.sessions_from_csessid(csessid)
if sess:
sess = sess[0]
cmdarray = json.loads(cgi.escape(request.args.get('data')[0]))
sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]})
return '""' | {
"deleted": [
{
"line_no": 10,
"char_start": 217,
"char_end": 266,
"line": " csessid = request.args.get('csessid')[0]\n"
},
{
"line_no": 11,
"char_start": 266,
"char_end": 267,
"line": "\n"
},
{
"line_no": 16,
"char_start": 433,
"char_end": 496,
"line": " cmdarray = json.loads(request.args.get('data')[0])\n"
}
],
"added": [
{
"line_no": 10,
"char_start": 217,
"char_end": 274,
"line": " csessid = cgi.escape(request.args['csessid'][0])\n"
},
{
"line_no": 15,
"char_start": 440,
"char_end": 515,
"line": " cmdarray = json.loads(cgi.escape(request.args.get('data')[0]))\n"
}
]
} | {
"deleted": [
{
"char_start": 247,
"char_end": 252,
"chars": ".get("
},
{
"char_start": 261,
"char_end": 262,
"chars": ")"
},
{
"char_start": 265,
"char_end": 266,
"chars": "\n"
}
],
"added": [
{
"char_start": 235,
"char_end": 246,
"chars": "cgi.escape("
},
{
"char_start": 258,
"char_end": 259,
"chars": "["
},
{
"char_start": 268,
"char_end": 269,
"chars": "]"
},
{
"char_start": 272,
"char_end": 273,
"chars": ")"
},
{
"char_start": 474,
"char_end": 485,
"chars": "cgi.escape("
},
{
"char_start": 512,
"char_end": 513,
"chars": ")"
}
]
} | github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93 | evennia/server/portal/webclient_ajax.py | cwe-079 |
get_list_context | def get_list_context(context=None):
list_context = frappe._dict(
template = "templates/includes/blog/blog.html",
get_list = get_blog_list,
hide_filters = True,
children = get_children(),
# show_search = True,
title = _('Blog')
)
category = frappe.local.form_dict.blog_category or frappe.local.form_dict.category
if category:
category_title = get_blog_category(category)
list_context.sub_title = _("Posts filed under {0}").format(category_title)
list_context.title = category_title
elif frappe.local.form_dict.blogger:
blogger = frappe.db.get_value("Blogger", {"name": frappe.local.form_dict.blogger}, "full_name")
list_context.sub_title = _("Posts by {0}").format(blogger)
list_context.title = blogger
elif frappe.local.form_dict.txt:
list_context.sub_title = _('Filtered by "{0}"').format(frappe.local.form_dict.txt)
if list_context.sub_title:
list_context.parents = [{"name": _("Home"), "route": "/"},
{"name": "Blog", "route": "/blog"}]
else:
list_context.parents = [{"name": _("Home"), "route": "/"}]
list_context.update(frappe.get_doc("Blog Settings", "Blog Settings").as_dict(no_default_fields=True))
return list_context | def get_list_context(context=None):
list_context = frappe._dict(
template = "templates/includes/blog/blog.html",
get_list = get_blog_list,
hide_filters = True,
children = get_children(),
# show_search = True,
title = _('Blog')
)
category = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category)
if category:
category_title = get_blog_category(category)
list_context.sub_title = _("Posts filed under {0}").format(category_title)
list_context.title = category_title
elif frappe.local.form_dict.blogger:
blogger = frappe.db.get_value("Blogger", {"name": frappe.local.form_dict.blogger}, "full_name")
list_context.sub_title = _("Posts by {0}").format(blogger)
list_context.title = blogger
elif frappe.local.form_dict.txt:
list_context.sub_title = _('Filtered by "{0}"').format(sanitize_html(frappe.local.form_dict.txt))
if list_context.sub_title:
list_context.parents = [{"name": _("Home"), "route": "/"},
{"name": "Blog", "route": "/blog"}]
else:
list_context.parents = [{"name": _("Home"), "route": "/"}]
list_context.update(frappe.get_doc("Blog Settings", "Blog Settings").as_dict(no_default_fields=True))
return list_context | {
"deleted": [
{
"line_no": 11,
"char_start": 244,
"char_end": 328,
"line": "\tcategory = frappe.local.form_dict.blog_category or frappe.local.form_dict.category\n"
},
{
"line_no": 23,
"char_start": 768,
"char_end": 853,
"line": "\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(frappe.local.form_dict.txt)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 244,
"char_end": 343,
"line": "\tcategory = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category)\n"
},
{
"line_no": 23,
"char_start": 783,
"char_end": 883,
"line": "\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(sanitize_html(frappe.local.form_dict.txt))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 256,
"char_end": 270,
"chars": "sanitize_html("
},
{
"char_start": 341,
"char_end": 342,
"chars": ")"
},
{
"char_start": 840,
"char_end": 854,
"chars": "sanitize_html("
},
{
"char_start": 880,
"char_end": 881,
"chars": ")"
}
]
} | github.com/omirajkar/bench_frappe/commit/2fa19c25066ed17478d683666895e3266936aee6 | frappe/website/doctype/blog_post/blog_post.py | cwe-079 |
mode_init | def mode_init(self, request):
"""
This is called by render_POST when the client requests an init
mode operation (at startup)
Args:
request (Request): Incoming request.
"""
csessid = request.args.get('csessid')[0]
remote_addr = request.getClientIP()
host_string = "%s (%s:%s)" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)
sess = AjaxWebClientSession()
sess.client = self
sess.init_session("ajax/comet", remote_addr, self.sessionhandler)
sess.csessid = csessid
csession = _CLIENT_SESSIONS(session_key=sess.csessid)
uid = csession and csession.get("webclient_authenticated_uid", False)
if uid:
# the client session is already logged in
sess.uid = uid
sess.logged_in = True
sess.sessionhandler.connect(sess)
self.last_alive[csessid] = (time.time(), False)
if not self.keep_alive:
# the keepalive is not running; start it.
self.keep_alive = LoopingCall(self._keepalive)
self.keep_alive.start(_KEEPALIVE, now=False)
return jsonify({'msg': host_string, 'csessid': csessid}) | def mode_init(self, request):
"""
This is called by render_POST when the client requests an init
mode operation (at startup)
Args:
request (Request): Incoming request.
"""
csessid = cgi.escape(request.args['csessid'][0])
remote_addr = request.getClientIP()
host_string = "%s (%s:%s)" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)
sess = AjaxWebClientSession()
sess.client = self
sess.init_session("ajax/comet", remote_addr, self.sessionhandler)
sess.csessid = csessid
csession = _CLIENT_SESSIONS(session_key=sess.csessid)
uid = csession and csession.get("webclient_authenticated_uid", False)
if uid:
# the client session is already logged in
sess.uid = uid
sess.logged_in = True
sess.sessionhandler.connect(sess)
self.last_alive[csessid] = (time.time(), False)
if not self.keep_alive:
# the keepalive is not running; start it.
self.keep_alive = LoopingCall(self._keepalive)
self.keep_alive.start(_KEEPALIVE, now=False)
return jsonify({'msg': host_string, 'csessid': csessid}) | {
"deleted": [
{
"line_no": 10,
"char_start": 230,
"char_end": 279,
"line": " csessid = request.args.get('csessid')[0]\n"
}
],
"added": [
{
"line_no": 10,
"char_start": 230,
"char_end": 287,
"line": " csessid = cgi.escape(request.args['csessid'][0])\n"
}
]
} | {
"deleted": [
{
"char_start": 260,
"char_end": 265,
"chars": ".get("
},
{
"char_start": 274,
"char_end": 275,
"chars": ")"
}
],
"added": [
{
"char_start": 248,
"char_end": 259,
"chars": "cgi.escape("
},
{
"char_start": 271,
"char_end": 272,
"chars": "["
},
{
"char_start": 281,
"char_end": 282,
"chars": "]"
},
{
"char_start": 285,
"char_end": 286,
"chars": ")"
}
]
} | github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93 | evennia/server/portal/webclient_ajax.py | cwe-079 |
handle_file | def handle_file(u: Profile, headline: str, category: str, text: str, file):
m: Media = Media()
upload_base_path: str = 'uploads/' + str(date.today().year)
high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(" ", "_"))
low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(" ", "_"))
if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):
os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)
with open(high_res_file_name, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
# TODO crop image
original = Image.open(high_res_file_name)
width, height = original.size
diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))
width /= diameter
height /= diameter
width *= IMAGE_SCALE
height *= IMAGE_SCALE
cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)
cropped.save(low_res_file_name)
m.text = text
m.cachedText = compile_markdown(text)
m.category = category
m.highResFile = "/" + high_res_file_name
m.lowResFile = "/" + low_res_file_name
m.headline = headline
m.save()
mu: MediaUpload = MediaUpload()
mu.UID = u
mu.MID = m
mu.save()
logging.info("Uploaded file '" + str(file.name) + "' and cropped it. The resulting PK is " + str(m.pk)) | def handle_file(u: Profile, headline: str, category: str, text: str, file):
m: Media = Media()
upload_base_path: str = 'uploads/' + str(date.today().year)
high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(" ", "_"))
low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(" ", "_"))
if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):
os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)
with open(high_res_file_name, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
# TODO crop image
original = Image.open(high_res_file_name)
width, height = original.size
diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))
width /= diameter
height /= diameter
width *= IMAGE_SCALE
height *= IMAGE_SCALE
cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)
cropped.save(low_res_file_name)
m.text = escape(text)
m.cachedText = compile_markdown(escape(text))
m.category = escape(category)
m.highResFile = "/" + high_res_file_name
m.lowResFile = "/" + low_res_file_name
m.headline = escape(headline)
m.save()
mu: MediaUpload = MediaUpload()
mu.UID = u
mu.MID = m
mu.save()
logging.info("Uploaded file '" + str(file.name) + "' and cropped it. The resulting PK is " + str(m.pk)) | {
"deleted": [
{
"line_no": 21,
"char_start": 1021,
"char_end": 1039,
"line": " m.text = text\n"
},
{
"line_no": 22,
"char_start": 1039,
"char_end": 1081,
"line": " m.cachedText = compile_markdown(text)\n"
},
{
"line_no": 23,
"char_start": 1081,
"char_end": 1107,
"line": " m.category = category\n"
},
{
"line_no": 26,
"char_start": 1195,
"char_end": 1221,
"line": " m.headline = headline\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 1021,
"char_end": 1047,
"line": " m.text = escape(text)\n"
},
{
"line_no": 22,
"char_start": 1047,
"char_end": 1097,
"line": " m.cachedText = compile_markdown(escape(text))\n"
},
{
"line_no": 23,
"char_start": 1097,
"char_end": 1131,
"line": " m.category = escape(category)\n"
},
{
"line_no": 26,
"char_start": 1219,
"char_end": 1253,
"line": " m.headline = escape(headline)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1034,
"char_end": 1041,
"chars": "escape("
},
{
"char_start": 1045,
"char_end": 1046,
"chars": ")"
},
{
"char_start": 1083,
"char_end": 1090,
"chars": "escape("
},
{
"char_start": 1094,
"char_end": 1095,
"chars": ")"
},
{
"char_start": 1114,
"char_end": 1121,
"chars": "escape("
},
{
"char_start": 1129,
"char_end": 1130,
"chars": ")"
},
{
"char_start": 1236,
"char_end": 1243,
"chars": "escape("
},
{
"char_start": 1251,
"char_end": 1252,
"chars": ")"
}
]
} | github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600 | c3shop/frontpage/management/mediatools/media_actions.py | cwe-079 |
commentcounts | @register.tag
@basictag(takes_context=True)
def commentcounts(context, filediff, interfilediff=None):
"""
Returns a JSON array of current comments for a filediff, sorted by
line number.
Each entry in the array has a dictionary containing the following keys:
=========== ==================================================
Key Description
=========== ==================================================
comment_id The ID of the comment
text The text of the comment
line The first line number
num_lines The number of lines this comment spans
user A dictionary containing "username" and "name" keys
for the user
url The URL to the comment
localdraft True if this is the current user's draft comment
=========== ==================================================
"""
comment_dict = {}
user = context.get('user', None)
if interfilediff:
query = Comment.objects.filter(filediff=filediff,
interfilediff=interfilediff)
else:
query = Comment.objects.filter(filediff=filediff,
interfilediff__isnull=True)
for comment in query:
review = get_object_or_none(comment.review)
if review and (review.public or review.user == user):
key = (comment.first_line, comment.num_lines)
comment_dict.setdefault(key, []).append({
'comment_id': comment.id,
'text': comment.text,
'line': comment.first_line,
'num_lines': comment.num_lines,
'user': {
'username': review.user.username,
'name': review.user.get_full_name() or review.user.username,
},
#'timestamp': comment.timestamp,
'url': comment.get_review_url(),
'localdraft': review.user == user and \
not review.public,
})
comments_array = []
for key, value in comment_dict.iteritems():
comments_array.append({
'linenum': key[0],
'num_lines': key[1],
'comments': value,
})
comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or
cmp(x['num_lines'], y['num_lines'])))
return simplejson.dumps(comments_array) | @register.tag
@basictag(takes_context=True)
def commentcounts(context, filediff, interfilediff=None):
"""
Returns a JSON array of current comments for a filediff, sorted by
line number.
Each entry in the array has a dictionary containing the following keys:
=========== ==================================================
Key Description
=========== ==================================================
comment_id The ID of the comment
text The text of the comment
line The first line number
num_lines The number of lines this comment spans
user A dictionary containing "username" and "name" keys
for the user
url The URL to the comment
localdraft True if this is the current user's draft comment
=========== ==================================================
"""
comment_dict = {}
user = context.get('user', None)
if interfilediff:
query = Comment.objects.filter(filediff=filediff,
interfilediff=interfilediff)
else:
query = Comment.objects.filter(filediff=filediff,
interfilediff__isnull=True)
for comment in query:
review = get_object_or_none(comment.review)
if review and (review.public or review.user == user):
key = (comment.first_line, comment.num_lines)
comment_dict.setdefault(key, []).append({
'comment_id': comment.id,
'text': escape(comment.text),
'line': comment.first_line,
'num_lines': comment.num_lines,
'user': {
'username': review.user.username,
'name': review.user.get_full_name() or review.user.username,
},
#'timestamp': comment.timestamp,
'url': comment.get_review_url(),
'localdraft': review.user == user and \
not review.public,
})
comments_array = []
for key, value in comment_dict.iteritems():
comments_array.append({
'linenum': key[0],
'num_lines': key[1],
'comments': value,
})
comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or
cmp(x['num_lines'], y['num_lines'])))
return simplejson.dumps(comments_array) | {
"deleted": [
{
"line_no": 41,
"char_start": 1548,
"char_end": 1586,
"line": " 'text': comment.text,\n"
}
],
"added": [
{
"line_no": 41,
"char_start": 1548,
"char_end": 1594,
"line": " 'text': escape(comment.text),\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1572,
"char_end": 1579,
"chars": "escape("
},
{
"char_start": 1591,
"char_end": 1592,
"chars": ")"
}
]
} | github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d | reviewboard/reviews/templatetags/reviewtags.py | cwe-079 |
oidc_handle_session_management_iframe_rp | static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %s);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return DONE;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
if (s_poll_interval == NULL)
s_poll_interval = "3000";
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, s_poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE);
} | static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return DONE;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE);
} | {
"deleted": [
{
"line_no": 21,
"char_start": 743,
"char_end": 803,
"line": "\t\t\t\" timerID = setInterval('checkSession()', %s);\\n\"\n"
},
{
"line_no": 64,
"char_start": 2273,
"char_end": 2303,
"line": "\tif (s_poll_interval == NULL)\n"
},
{
"line_no": 65,
"char_start": 2303,
"char_end": 2331,
"line": "\t\ts_poll_interval = \"3000\";\n"
},
{
"line_no": 69,
"char_start": 2458,
"char_end": 2521,
"line": "\t\t\tsession_state, op_iframe_id, s_poll_interval, redirect_uri,\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 743,
"char_end": 803,
"line": "\t\t\t\" timerID = setInterval('checkSession()', %d);\\n\"\n"
},
{
"line_no": 64,
"char_start": 2273,
"char_end": 2351,
"line": "\tint poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;\n"
},
{
"line_no": 65,
"char_start": 2351,
"char_end": 2409,
"line": "\tif ((poll_interval <= 0) || (poll_interval > 3600 * 24))\n"
},
{
"line_no": 66,
"char_start": 2409,
"char_end": 2433,
"line": "\t\tpoll_interval = 3000;\n"
},
{
"line_no": 70,
"char_start": 2560,
"char_end": 2621,
"line": "\t\t\tsession_state, op_iframe_id, poll_interval, redirect_uri,\n"
}
]
} | {
"deleted": [
{
"char_start": 796,
"char_end": 797,
"chars": "s"
},
{
"char_start": 2275,
"char_end": 2276,
"chars": "f"
},
{
"char_start": 2293,
"char_end": 2296,
"chars": " =="
},
{
"char_start": 2304,
"char_end": 2306,
"chars": "\ts"
},
{
"char_start": 2323,
"char_end": 2324,
"chars": "\""
},
{
"char_start": 2328,
"char_end": 2329,
"chars": "\""
},
{
"char_start": 2490,
"char_end": 2492,
"chars": "s_"
}
],
"added": [
{
"char_start": 796,
"char_end": 797,
"chars": "d"
},
{
"char_start": 2275,
"char_end": 2291,
"chars": "nt poll_interval"
},
{
"char_start": 2292,
"char_end": 2294,
"chars": "= "
},
{
"char_start": 2310,
"char_end": 2335,
"chars": "? strtol(s_poll_interval,"
},
{
"char_start": 2340,
"char_end": 2344,
"chars": ", 10"
},
{
"char_start": 2345,
"char_end": 2350,
"chars": " : 0;"
},
{
"char_start": 2352,
"char_end": 2361,
"chars": "if ((poll"
},
{
"char_start": 2362,
"char_end": 2411,
"chars": "interval <= 0) || (poll_interval > 3600 * 24))\n\t\t"
}
]
} | github.com/zmartzone/mod_auth_openidc/commit/132a4111bf3791e76437619a66336dce2ce4c79b | src/mod_auth_openidc.c | cwe-079 |
Logger::addMessage | void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
QWriteLocker locker(&lock);
Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };
m_messages.push_back(temp);
if (m_messages.size() >= MAX_LOG_MESSAGES)
m_messages.pop_front();
emit newLogMessage(temp);
} | void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
QWriteLocker locker(&lock);
Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };
m_messages.push_back(temp);
if (m_messages.size() >= MAX_LOG_MESSAGES)
m_messages.pop_front();
emit newLogMessage(temp);
} | {
"deleted": [
{
"line_no": 5,
"char_start": 109,
"char_end": 199,
"line": " Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 109,
"char_end": 229,
"line": " Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 188,
"char_end": 217,
"chars": "Utils::String::toHtmlEscaped("
},
{
"char_start": 224,
"char_end": 225,
"chars": ")"
}
]
} | github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16 | src/base/logger.cpp | cwe-079 |
get | @handler.unsupported_on_local_server
@handler.get(handler.HTML)
def get(self):
"""Handle a get request."""
self.render(
'login.html', {
'apiKey': local_config.ProjectConfig().get('firebase.api_key'),
'authDomain': auth.auth_domain(),
'dest': self.request.get('dest'),
}) | @handler.unsupported_on_local_server
@handler.get(handler.HTML)
def get(self):
"""Handle a get request."""
dest = self.request.get('dest')
base_handler.check_redirect_url(dest)
self.render(
'login.html', {
'apiKey': local_config.ProjectConfig().get('firebase.api_key'),
'authDomain': auth.auth_domain(),
'dest': dest,
}) | {
"deleted": [
{
"line_no": 9,
"char_start": 280,
"char_end": 326,
"line": " 'dest': self.request.get('dest'),\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 117,
"char_end": 153,
"line": " dest = self.request.get('dest')\n"
},
{
"line_no": 6,
"char_start": 153,
"char_end": 195,
"line": " base_handler.check_redirect_url(dest)\n"
},
{
"line_no": 7,
"char_start": 195,
"char_end": 196,
"line": "\n"
},
{
"line_no": 12,
"char_start": 359,
"char_end": 385,
"line": " 'dest': dest,\n"
}
]
} | {
"deleted": [
{
"char_start": 300,
"char_end": 318,
"chars": "self.request.get('"
},
{
"char_start": 322,
"char_end": 324,
"chars": "')"
}
],
"added": [
{
"char_start": 121,
"char_end": 200,
"chars": "dest = self.request.get('dest')\n base_handler.check_redirect_url(dest)\n\n "
}
]
} | github.com/google/clusterfuzz/commit/3d66c1146550eecd4e34d47332a8616b435a21fe | src/appengine/handlers/login.py | cwe-079 |
manipulate_reservation_action | def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):
"""
This function is used to alter the reservation beeing build inside
a cookie. This function automatically crafts the required response.
"""
js_string: str = ""
r: GroupReservation = None
u: Profile = get_current_user(request)
forward_url: str = default_foreward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
if "srid" in request.GET:
if not request.GET.get("rid"):
return HttpResponseRedirect("/admin?error=missing%20primary%20reservation%20id")
srid: int = int(request.GET["srid"])
sr: SubReservation = None
if srid == 0:
sr = SubReservation()
else:
sr = SubReservation.objects.get(id=srid)
if request.POST.get("notes"):
sr.notes = request.POST["notes"]
else:
sr.notes = " "
sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET["rid"]))
sr.save()
print(request.POST)
print(sr.notes)
return HttpResponseRedirect("/admin/reservations/edit?rid=" + str(int(request.GET["rid"])) + "&srid=" + str(sr.id))
if "rid" in request.GET:
# update reservation
r = GroupReservation.objects.get(id=int(request.GET["rid"]))
elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():
r = GroupReservation()
r.createdByUser = u
r.ready = False
r.open = True
r.pickupDate = datetime.datetime.now()
else:
return HttpResponseRedirect("/admin?error=Too%20Many%20reservations")
if request.POST.get("notes"):
r.notes = request.POST["notes"]
if request.POST.get("contact"):
r.responsiblePerson = str(request.POST["contact"])
if (r.createdByUser == u or o.rights > 1) and not r.submitted:
r.save()
else:
return HttpResponseRedirect("/admin?error=noyb")
response: HttpResponseRedirect = HttpResponseRedirect(forward_url + "?rid=" + str(r.id))
return response | def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):
"""
This function is used to alter the reservation beeing build inside
a cookie. This function automatically crafts the required response.
"""
js_string: str = ""
r: GroupReservation = None
u: Profile = get_current_user(request)
forward_url: str = default_foreward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
if "srid" in request.GET:
if not request.GET.get("rid"):
return HttpResponseRedirect("/admin?error=missing%20primary%20reservation%20id")
srid: int = int(request.GET["srid"])
sr: SubReservation = None
if srid == 0:
sr = SubReservation()
else:
sr = SubReservation.objects.get(id=srid)
if request.POST.get("notes"):
sr.notes = escape(request.POST["notes"])
else:
sr.notes = " "
sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET["rid"]))
sr.save()
print(request.POST)
print(sr.notes)
return HttpResponseRedirect("/admin/reservations/edit?rid=" + str(int(request.GET["rid"])) + "&srid=" + str(sr.id))
if "rid" in request.GET:
# update reservation
r = GroupReservation.objects.get(id=int(request.GET["rid"]))
elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():
r = GroupReservation()
r.createdByUser = u
r.ready = False
r.open = True
r.pickupDate = datetime.datetime.now()
else:
return HttpResponseRedirect("/admin?error=Too%20Many%20reservations")
if request.POST.get("notes"):
r.notes = escape(request.POST["notes"])
if request.POST.get("contact"):
r.responsiblePerson = escape(str(request.POST["contact"]))
if (r.createdByUser == u or o.rights > 1) and not r.submitted:
r.save()
else:
return HttpResponseRedirect("/admin?error=noyb")
response: HttpResponseRedirect = HttpResponseRedirect(forward_url + "?rid=" + str(r.id))
return response | {
"deleted": [
{
"line_no": 22,
"char_start": 869,
"char_end": 914,
"line": " sr.notes = request.POST[\"notes\"]\n"
},
{
"line_no": 42,
"char_start": 1748,
"char_end": 1788,
"line": " r.notes = request.POST[\"notes\"]\n"
},
{
"line_no": 44,
"char_start": 1824,
"char_end": 1883,
"line": " r.responsiblePerson = str(request.POST[\"contact\"])\n"
}
],
"added": [
{
"line_no": 22,
"char_start": 869,
"char_end": 922,
"line": " sr.notes = escape(request.POST[\"notes\"])\n"
},
{
"line_no": 42,
"char_start": 1756,
"char_end": 1804,
"line": " r.notes = escape(request.POST[\"notes\"])\n"
},
{
"line_no": 44,
"char_start": 1840,
"char_end": 1907,
"line": " r.responsiblePerson = escape(str(request.POST[\"contact\"]))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 892,
"char_end": 899,
"chars": "escape("
},
{
"char_start": 920,
"char_end": 921,
"chars": ")"
},
{
"char_start": 1774,
"char_end": 1781,
"chars": "escape("
},
{
"char_start": 1802,
"char_end": 1803,
"chars": ")"
},
{
"char_start": 1870,
"char_end": 1877,
"chars": "escape("
},
{
"char_start": 1904,
"char_end": 1905,
"chars": ")"
}
]
} | github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600 | c3shop/frontpage/management/reservation_actions.py | cwe-079 |
html_content | @property
async def html_content(self):
content = await self.content
if not content:
return ''
return markdown(content) | @property
async def html_content(self):
content = markupsafe.escape(await self.content)
if not content:
return ''
return markdown(content) | {
"deleted": [
{
"line_no": 3,
"char_start": 48,
"char_end": 85,
"line": " content = await self.content\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 48,
"char_end": 104,
"line": " content = markupsafe.escape(await self.content)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 66,
"char_end": 84,
"chars": "markupsafe.escape("
},
{
"char_start": 102,
"char_end": 103,
"chars": ")"
}
]
} | github.com/dongweiming/lyanna/commit/fcefac79e4b7601e81a3b3fe0ad26ab18ee95d7d | models/comment.py | cwe-079 |
get_context_data | def get_context_data(self, *args, **kwargs):
data = super().get_context_data(*args, **kwargs)
if self.request.GET.get('back', None) is not None:
data['back_link'] = self.request.GET['back']
return data | def get_context_data(self, *args, **kwargs):
data = super().get_context_data(*args, **kwargs)
back = self.request.GET.get('back', None)
parsed_back_url = urllib.parse.urlparse(back)
# We only allow blank scheme, e.g. relative urls to avoid reflected XSS
if back is not None and parsed_back_url.scheme == "":
data['back_link'] = back
return data | {
"deleted": [
{
"line_no": 4,
"char_start": 107,
"char_end": 166,
"line": " if self.request.GET.get('back', None) is not None:\n"
},
{
"line_no": 5,
"char_start": 166,
"char_end": 223,
"line": " data['back_link'] = self.request.GET['back']\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 107,
"char_end": 157,
"line": " back = self.request.GET.get('back', None)\n"
},
{
"line_no": 5,
"char_start": 157,
"char_end": 211,
"line": " parsed_back_url = urllib.parse.urlparse(back)\n"
},
{
"line_no": 6,
"char_start": 211,
"char_end": 212,
"line": "\n"
},
{
"line_no": 8,
"char_start": 292,
"char_end": 354,
"line": " if back is not None and parsed_back_url.scheme == \"\":\n"
},
{
"line_no": 9,
"char_start": 354,
"char_end": 391,
"line": " data['back_link'] = back\n"
}
]
} | {
"deleted": [
{
"char_start": 115,
"char_end": 117,
"chars": "if"
},
{
"char_start": 198,
"char_end": 216,
"chars": "self.request.GET['"
},
{
"char_start": 220,
"char_end": 222,
"chars": "']"
}
],
"added": [
{
"char_start": 115,
"char_end": 121,
"chars": "back ="
},
{
"char_start": 156,
"char_end": 307,
"chars": "\n parsed_back_url = urllib.parse.urlparse(back)\n\n # We only allow blank scheme, e.g. relative urls to avoid reflected XSS\n if back"
},
{
"char_start": 319,
"char_end": 352,
"chars": " and parsed_back_url.scheme == \"\""
}
]
} | github.com/pirati-web/socialnisystem.cz/commit/1bd25d971ac3f9ac7ae3915cc2dd86b0ceb44b53 | socialsystem/core/views.py | cwe-079 |
add_article_action | def add_article_action(request: HttpRequest, default_foreward_url: str):
forward_url: str = default_foreward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
else:
forward_url = "/admin"
if "rid" not in request.GET:
return HttpResponseRedirect("/admin?error=Missing%20reservation%20id%20in%20request")
u: Profile = get_current_user(request)
current_reservation = GroupReservation.objects.get(id=str(request.GET["rid"]))
if current_reservation.createdByUser != u and u.rights < 2:
return HttpResponseRedirect("/admin?error=noyb")
if current_reservation.submitted == True:
return HttpResponseRedirect("/admin?error=Already%20submitted")
# Test for multiple or single article
if "article_id" in request.POST:
# Actual adding of article
aid: int = int(request.GET.get("article_id"))
quantity: int = int(request.POST["quantity"])
notes: str = request.POST["notes"]
ar = ArticleRequested()
ar.AID = Article.objects.get(id=aid)
ar.RID = current_reservation
if "srid" in request.GET:
ar.SRID = SubReservation.objects.get(id=int(request.GET["srid"]))
ar.amount = quantity
ar.notes = notes
ar.save()
# Actual adding of multiple articles
else:
if "group_id" not in request.GET:
return HttpResponseRedirect("/admin?error=missing%20group%20id")
g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET["group_id"]))
for art in Article.objects.all().filter(group=g):
if str("quantity_" + str(art.id)) not in request.POST or str("notes_" + str(art.id)) not in request.POST:
return HttpResponseRedirect("/admin?error=Missing%20article%20data%20in%20request")
amount = int(request.POST["quantity_" + str(art.id)])
if amount > 0:
ar = ArticleRequested()
ar.AID = art
ar.RID = current_reservation
ar.amount = amount
if "srid" in request.GET:
ar.SRID = SubReservation.objects.get(id=int(request.GET["srid"]))
ar.notes = str(request.POST[str("notes_" + str(art.id))])
ar.save()
if "srid" in request.GET:
response = HttpResponseRedirect(forward_url + "?rid=" + str(current_reservation.id) + "&srid=" + request.GET["srid"])
else:
response = HttpResponseRedirect(forward_url + "?rid=" + str(current_reservation.id))
return response | def add_article_action(request: HttpRequest, default_foreward_url: str):
forward_url: str = default_foreward_url
if request.GET.get("redirect"):
forward_url = request.GET["redirect"]
else:
forward_url = "/admin"
if "rid" not in request.GET:
return HttpResponseRedirect("/admin?error=Missing%20reservation%20id%20in%20request")
u: Profile = get_current_user(request)
current_reservation = GroupReservation.objects.get(id=str(request.GET["rid"]))
if current_reservation.createdByUser != u and u.rights < 2:
return HttpResponseRedirect("/admin?error=noyb")
if current_reservation.submitted == True:
return HttpResponseRedirect("/admin?error=Already%20submitted")
# Test for multiple or single article
if "article_id" in request.POST:
# Actual adding of article
aid: int = int(request.GET.get("article_id"))
quantity: int = int(request.POST["quantity"])
notes: str = escape(request.POST["notes"])
ar = ArticleRequested()
ar.AID = Article.objects.get(id=aid)
ar.RID = current_reservation
if "srid" in request.GET:
ar.SRID = SubReservation.objects.get(id=int(request.GET["srid"]))
ar.amount = quantity
ar.notes = notes
ar.save()
# Actual adding of multiple articles
else:
if "group_id" not in request.GET:
return HttpResponseRedirect("/admin?error=missing%20group%20id")
g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET["group_id"]))
for art in Article.objects.all().filter(group=g):
if str("quantity_" + str(art.id)) not in request.POST or str("notes_" + str(art.id)) not in request.POST:
return HttpResponseRedirect("/admin?error=Missing%20article%20data%20in%20request")
amount = int(request.POST["quantity_" + str(art.id)])
if amount > 0:
ar = ArticleRequested()
ar.AID = art
ar.RID = current_reservation
ar.amount = amount
if "srid" in request.GET:
ar.SRID = SubReservation.objects.get(id=int(request.GET["srid"]))
ar.notes = escape(str(request.POST[str("notes_" + str(art.id))]))
ar.save()
if "srid" in request.GET:
response = HttpResponseRedirect(forward_url + "?rid=" + str(current_reservation.id) + "&srid=" + request.GET["srid"])
else:
response = HttpResponseRedirect(forward_url + "?rid=" + str(current_reservation.id))
return response | {
"deleted": [
{
"line_no": 20,
"char_start": 954,
"char_end": 997,
"line": " notes: str = request.POST[\"notes\"]\n"
},
{
"line_no": 45,
"char_start": 2195,
"char_end": 2269,
"line": " ar.notes = str(request.POST[str(\"notes_\" + str(art.id))])\n"
}
],
"added": [
{
"line_no": 20,
"char_start": 954,
"char_end": 1005,
"line": " notes: str = escape(request.POST[\"notes\"])\n"
},
{
"line_no": 45,
"char_start": 2203,
"char_end": 2285,
"line": " ar.notes = escape(str(request.POST[str(\"notes_\" + str(art.id))]))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 975,
"char_end": 982,
"chars": "escape("
},
{
"char_start": 1003,
"char_end": 1004,
"chars": ")"
},
{
"char_start": 2230,
"char_end": 2237,
"chars": "escape("
},
{
"char_start": 2282,
"char_end": 2283,
"chars": ")"
}
]
} | github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600 | c3shop/frontpage/management/reservation_actions.py | cwe-079 |
build_board | def build_board(conn, game,size):
# we'll build the empty board, and then fill in with the move list that
# we get from the DB.
board = []
for i in range(size):
board.append([""]*size)
# search for all moves that have happenend during this game.
cursor = conn.cursor()
cursor.execute("SELECT x,y,letter FROM moves WHERE gameID = %d;" % game)
counts = {"X":0, "O":0}
for move in cursor.fetchall():
(x,y,letter) = move
x = int(x)
y = int(y)
assert x >= 0 and x < size
assert y >= 0 and y < size
assert letter in "XO"
assert board[x][y] == ""
board[x][y] = letter
counts[letter] += 1
cursor.close()
assert counts["X"] >= counts["O"]
assert counts["X"] <= counts["O"]+1
if counts["X"] == counts["O"]:
nextPlayer = 0
else:
nextPlayer = 1
letter = "XO"[nextPlayer]
return (board,nextPlayer,letter) | def build_board(conn, game,size):
# we'll build the empty board, and then fill in with the move list that
# we get from the DB.
board = []
for i in range(size):
board.append([""]*size)
# search for all moves that have happenend during this game.
cursor = conn.cursor()
cursor.execute("SELECT x,y,letter FROM moves WHERE gameID = %d;", (game,))
counts = {"X":0, "O":0}
for move in cursor.fetchall():
(x,y,letter) = move
x = int(x)
y = int(y)
assert x >= 0 and x < size
assert y >= 0 and y < size
assert letter in "XO"
assert board[x][y] == ""
board[x][y] = letter
counts[letter] += 1
cursor.close()
assert counts["X"] >= counts["O"]
assert counts["X"] <= counts["O"]+1
if counts["X"] == counts["O"]:
nextPlayer = 0
else:
nextPlayer = 1
letter = "XO"[nextPlayer]
return (board,nextPlayer,letter) | {
"deleted": [
{
"line_no": 11,
"char_start": 303,
"char_end": 380,
"line": " cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\" % game)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 303,
"char_end": 382,
"line": " cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\", (game,))\n"
}
]
} | {
"deleted": [
{
"char_start": 371,
"char_end": 373,
"chars": " %"
}
],
"added": [
{
"char_start": 371,
"char_end": 372,
"chars": ","
},
{
"char_start": 373,
"char_end": 374,
"chars": "("
},
{
"char_start": 378,
"char_end": 380,
"chars": ",)"
}
]
} | github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da | cgi/common.py | cwe-089 |
check_and_update_ranks | def check_and_update_ranks(self, scene):
# There are 2 cases here:
# 1) Ranks have never been calculated for this scene before
# - This means we need to calculate what the ranks were every month of this scenes history
# - We should only do this if ranks don't already exist for this scene
# 2) Ranks have been calculated for this scene before
# - We already have bulk ranks. We should check if it has been more than 1 month since we last
# calculated ranks. If so, calculate again with the brackets that have come out this month
LOG.info('About to check if ranks need updating for {}'.format(scene))
# First, do we have any ranks for this scene already?
sql = 'select count(*) from ranks where scene="{}";'.format(scene)
res = self.db.exec(sql)
count = res[0][0]
n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK
if count == 0:
LOG.info('Detected that we need to bulk update ranks for {}'.format(scene))
# Alright, we have nothing. Bulk update ranks
first_month = bracket_utils.get_first_month(self.db, scene)
last_month = bracket_utils.get_last_month(self.db, scene)
# Iterate through all tournaments going month by month, and calculate ranks
months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True)
for month in months:
urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)
self.process_ranks(scene, urls, month)
else:
# Get the date of the last time we calculated ranks
sql = "select date from ranks where scene='{}' order by date desc limit 1;".format(scene)
res = self.db.exec(sql)
last_rankings_date = res[0][0]
# Check to see if it's been more than 1 month since we last calculated ranks
more_than_one_month = bracket_utils.has_month_passed(last_rankings_date)
if more_than_one_month:
# Get only the last n tournaments, so it doesn't take too long to process
today = datetime.datetime.today().strftime('%Y-%m-%d')
msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today)
LOG.info(msg)
# We should only ever calculate ranks on the 1st. If today is not the first, log error
if not today.split('-')[-1] == '1':
LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today))
months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True)
for month in months:
# Make sure that we actually have matches during this month
# Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30
prev_date = bracket_utils.get_previous_month(month)
brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date)
if len(brackets_during_month) > 0:
tweet('Calculating {} ranks for {}'.format(month, scene))
urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)
self.process_ranks(scene, urls, month)
else:
LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene)) | def check_and_update_ranks(self, scene):
# There are 2 cases here:
# 1) Ranks have never been calculated for this scene before
# - This means we need to calculate what the ranks were every month of this scenes history
# - We should only do this if ranks don't already exist for this scene
# 2) Ranks have been calculated for this scene before
# - We already have bulk ranks. We should check if it has been more than 1 month since we last
# calculated ranks. If so, calculate again with the brackets that have come out this month
LOG.info('About to check if ranks need updating for {}'.format(scene))
# First, do we have any ranks for this scene already?
sql = 'select count(*) from ranks where scene="{scene}";'
args = {'scene': scene}
res = self.db.exec(sql, args)
count = res[0][0]
n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK
if count == 0:
LOG.info('Detected that we need to bulk update ranks for {}'.format(scene))
# Alright, we have nothing. Bulk update ranks
first_month = bracket_utils.get_first_month(self.db, scene)
last_month = bracket_utils.get_last_month(self.db, scene)
# Iterate through all tournaments going month by month, and calculate ranks
months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True)
for month in months:
urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)
self.process_ranks(scene, urls, month)
else:
# Get the date of the last time we calculated ranks
sql = "select date from ranks where scene='{scene}' order by date desc limit 1;"
args = {'scene': scene}
res = self.db.exec(sql, args)
last_rankings_date = res[0][0]
# Check to see if it's been more than 1 month since we last calculated ranks
more_than_one_month = bracket_utils.has_month_passed(last_rankings_date)
if more_than_one_month:
# Get only the last n tournaments, so it doesn't take too long to process
today = datetime.datetime.today().strftime('%Y-%m-%d')
msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today)
LOG.info(msg)
# We should only ever calculate ranks on the 1st. If today is not the first, log error
if not today.split('-')[-1] == '1':
LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today))
months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True)
for month in months:
# Make sure that we actually have matches during this month
# Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30
prev_date = bracket_utils.get_previous_month(month)
brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date)
if len(brackets_during_month) > 0:
tweet('Calculating {} ranks for {}'.format(month, scene))
urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)
self.process_ranks(scene, urls, month)
else:
LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene)) | {
"deleted": [
{
"line_no": 12,
"char_start": 763,
"char_end": 838,
"line": " sql = 'select count(*) from ranks where scene=\"{}\";'.format(scene)\n"
},
{
"line_no": 13,
"char_start": 838,
"char_end": 870,
"line": " res = self.db.exec(sql)\n"
},
{
"line_no": 31,
"char_start": 1777,
"char_end": 1879,
"line": " sql = \"select date from ranks where scene='{}' order by date desc limit 1;\".format(scene)\n"
},
{
"line_no": 32,
"char_start": 1879,
"char_end": 1915,
"line": " res = self.db.exec(sql)\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 763,
"char_end": 829,
"line": " sql = 'select count(*) from ranks where scene=\"{scene}\";'\n"
},
{
"line_no": 13,
"char_start": 829,
"char_end": 861,
"line": " args = {'scene': scene}\n"
},
{
"line_no": 14,
"char_start": 861,
"char_end": 899,
"line": " res = self.db.exec(sql, args)\n"
},
{
"line_no": 32,
"char_start": 1806,
"char_end": 1899,
"line": " sql = \"select date from ranks where scene='{scene}' order by date desc limit 1;\"\n"
},
{
"line_no": 33,
"char_start": 1899,
"char_end": 1935,
"line": " args = {'scene': scene}\n"
},
{
"line_no": 34,
"char_start": 1935,
"char_end": 1977,
"line": " res = self.db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 823,
"char_end": 826,
"chars": ".fo"
},
{
"char_start": 827,
"char_end": 831,
"chars": "mat("
},
{
"char_start": 836,
"char_end": 837,
"chars": ")"
},
{
"char_start": 1864,
"char_end": 1867,
"chars": ".fo"
},
{
"char_start": 1868,
"char_end": 1872,
"chars": "mat("
},
{
"char_start": 1877,
"char_end": 1878,
"chars": ")"
}
],
"added": [
{
"char_start": 819,
"char_end": 824,
"chars": "scene"
},
{
"char_start": 828,
"char_end": 837,
"chars": "\n "
},
{
"char_start": 838,
"char_end": 846,
"chars": "rgs = {'"
},
{
"char_start": 851,
"char_end": 860,
"chars": "': scene}"
},
{
"char_start": 891,
"char_end": 897,
"chars": ", args"
},
{
"char_start": 1862,
"char_end": 1867,
"chars": "scene"
},
{
"char_start": 1898,
"char_end": 1911,
"chars": "\n "
},
{
"char_start": 1912,
"char_end": 1920,
"chars": "rgs = {'"
},
{
"char_start": 1925,
"char_end": 1934,
"chars": "': scene}"
},
{
"char_start": 1969,
"char_end": 1975,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | process_data.py | cwe-089 |
tag_num_to_tag | def tag_num_to_tag(self, tag_num):
''' Returns tag given tag_num. '''
q = "SELECT tag FROM tags WHERE rowid = '" + str(tag_num) + "'"
self.query(q)
return self.c.fetchone()[0] | def tag_num_to_tag(self, tag_num):
''' Returns tag given tag_num. '''
q = "SELECT tag FROM tags WHERE rowid = ?"
self.query(q, tag_num)
return self.c.fetchone()[0] | {
"deleted": [
{
"line_no": 4,
"char_start": 83,
"char_end": 155,
"line": " q = \"SELECT tag FROM tags WHERE rowid = '\" + str(tag_num) + \"'\"\n"
},
{
"line_no": 5,
"char_start": 155,
"char_end": 177,
"line": " self.query(q)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 83,
"char_end": 134,
"line": " q = \"SELECT tag FROM tags WHERE rowid = ?\"\n"
},
{
"line_no": 5,
"char_start": 134,
"char_end": 165,
"line": " self.query(q, tag_num)\n"
}
]
} | {
"deleted": [
{
"char_start": 131,
"char_end": 153,
"chars": "'\" + str(tag_num) + \"'"
}
],
"added": [
{
"char_start": 131,
"char_end": 132,
"chars": "?"
},
{
"char_start": 154,
"char_end": 163,
"chars": ", tag_num"
}
]
} | github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b | modules/query_lastfm.py | cwe-089 |
get_item | @api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)
cursor = mysql.connection.cursor()
cursor.execute(sql)
data = cursor.fetchone()
if data:
item = {}
for tup in zip([column[0] for column in cursor.description], data):
item[tup[0]] = tup[1]
else:
return jsonify({"error": "item not found"}), 404
return jsonify(item) | @api.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''
cursor = mysql.connection.cursor()
cursor.execute(sql, [item_id])
data = cursor.fetchone()
if data:
item = {}
for tup in zip([column[0] for column in cursor.description], data):
item[tup[0]] = tup[1]
else:
return jsonify({"error": "item not found"}), 404
return jsonify(item) | {
"deleted": [
{
"line_no": 3,
"char_start": 75,
"char_end": 182,
"line": " sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)\n"
},
{
"line_no": 5,
"char_start": 221,
"char_end": 245,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 75,
"char_end": 166,
"line": " sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''\n"
},
{
"line_no": 5,
"char_start": 205,
"char_end": 240,
"line": " cursor.execute(sql, [item_id])\n"
}
]
} | {
"deleted": [
{
"char_start": 136,
"char_end": 138,
"chars": "{}"
},
{
"char_start": 165,
"char_end": 181,
"chars": ".format(item_id)"
}
],
"added": [
{
"char_start": 136,
"char_end": 138,
"chars": "%s"
},
{
"char_start": 227,
"char_end": 238,
"chars": ", [item_id]"
}
]
} | github.com/cosileone/TimeIsMoneyFriend-API/commit/3d3b5defd26ef7d205915bf643b6b1df90a15e44 | timf/api/views.py | cwe-089 |
getPostsByPostid | def getPostsByPostid(self,postid):
sqlText="select users.name,post.comment from users,post where \
users.userid=post.userid and post.postid=%d"%(postid)
result=sql.queryDB(self.conn,sqlText)
return result; | def getPostsByPostid(self,postid):
sqlText="select users.name,post.comment from users,post where \
users.userid=post.userid and post.postid=%s"
params=[postid]
result=sql.queryDB(self.conn,sqlText,params)
return result; | {
"deleted": [
{
"line_no": 3,
"char_start": 111,
"char_end": 181,
"line": " users.userid=post.userid and post.postid=%d\"%(postid)\n"
},
{
"line_no": 4,
"char_start": 181,
"char_end": 227,
"line": " result=sql.queryDB(self.conn,sqlText)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 111,
"char_end": 172,
"line": " users.userid=post.userid and post.postid=%s\"\n"
},
{
"line_no": 4,
"char_start": 172,
"char_end": 196,
"line": " params=[postid]\n"
},
{
"line_no": 5,
"char_start": 196,
"char_end": 249,
"line": " result=sql.queryDB(self.conn,sqlText,params)\n"
}
]
} | {
"deleted": [
{
"char_start": 169,
"char_end": 170,
"chars": "d"
},
{
"char_start": 171,
"char_end": 173,
"chars": "%("
},
{
"char_start": 179,
"char_end": 180,
"chars": ")"
}
],
"added": [
{
"char_start": 169,
"char_end": 170,
"chars": "s"
},
{
"char_start": 171,
"char_end": 188,
"chars": "\n params=["
},
{
"char_start": 194,
"char_end": 195,
"chars": "]"
},
{
"char_start": 240,
"char_end": 247,
"chars": ",params"
}
]
} | github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9 | modules/post.py | cwe-089 |
getFileCacheID | def getFileCacheID(self, pth):
"""
Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.
:param pth:
:return:
"""
command = "SELECT file_id FROM {0} WHERE path='{1}'".format(TABLE_NAME, pth)
data = self._run_command(command)
try:
data = data[0][0]
except IndexError:
data = None
return data | def getFileCacheID(self, pth):
"""
Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.
:param pth:
:return:
"""
command = "SELECT file_id FROM {0} WHERE path=?;".format(TABLE_NAME)
params = (pth,)
data = self._run_command(command, params)
try:
data = data[0][0]
except IndexError:
data = None
return data | {
"deleted": [
{
"line_no": 7,
"char_start": 168,
"char_end": 247,
"line": "\t\tcommand = \"SELECT file_id FROM {0} WHERE path='{1}'\".format(TABLE_NAME, pth)\n"
},
{
"line_no": 8,
"char_start": 247,
"char_end": 283,
"line": "\t\tdata = self._run_command(command)\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 168,
"char_end": 239,
"line": "\t\tcommand = \"SELECT file_id FROM {0} WHERE path=?;\".format(TABLE_NAME)\n"
},
{
"line_no": 8,
"char_start": 239,
"char_end": 257,
"line": "\t\tparams = (pth,)\n"
},
{
"line_no": 9,
"char_start": 257,
"char_end": 301,
"line": "\t\tdata = self._run_command(command, params)\n"
}
]
} | {
"deleted": [
{
"char_start": 216,
"char_end": 221,
"chars": "'{1}'"
},
{
"char_start": 240,
"char_end": 241,
"chars": ","
}
],
"added": [
{
"char_start": 216,
"char_end": 218,
"chars": "?;"
},
{
"char_start": 237,
"char_end": 247,
"chars": ")\n\t\tparams"
},
{
"char_start": 248,
"char_end": 251,
"chars": "= ("
},
{
"char_start": 254,
"char_end": 255,
"chars": ","
},
{
"char_start": 291,
"char_end": 299,
"chars": ", params"
}
]
} | github.com/Highstaker/Picture-sender-telegram-bot/commit/db4bc6adb41e086418761426ff4958a81c30adca | file_db.py | cwe-089 |
add_post | def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("insert into posts values('%s')" % content)
db.commit()
db.close() | def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("insert into posts values(%s)",(content,))
db.commit()
db.close() | {
"deleted": [
{
"line_no": 5,
"char_start": 147,
"char_end": 203,
"line": " c.execute(\"insert into posts values('%s')\" % content)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 147,
"char_end": 202,
"line": " c.execute(\"insert into posts values(%s)\",(content,))\n"
}
]
} | {
"deleted": [
{
"char_start": 185,
"char_end": 186,
"chars": "'"
},
{
"char_start": 188,
"char_end": 189,
"chars": "'"
},
{
"char_start": 191,
"char_end": 194,
"chars": " % "
}
],
"added": [
{
"char_start": 189,
"char_end": 191,
"chars": ",("
},
{
"char_start": 198,
"char_end": 200,
"chars": ",)"
}
]
} | github.com/tfalbo/SuzyMakeup/commit/1a5d6ccf02bec303d454f87a6bb39baed30c205f | vagrant/forum/forumdb.py | cwe-089 |
getSubmissionDateFromDatabase | def getSubmissionDateFromDatabase(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT Date FROM ChallengeRankings WHERE SubmissionID = '" + str(submission.id) + "'").fetchone()[0]
database.close() | def getSubmissionDateFromDatabase(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?", [str(submission.id)]).fetchone()[0]
database.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 124,
"char_end": 252,
"line": " return cursor.execute(\"SELECT Date FROM ChallengeRankings WHERE SubmissionID = '\" + str(submission.id) + \"'\").fetchone()[0]\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 124,
"char_end": 247,
"line": " return cursor.execute(\"SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?\", [str(submission.id)]).fetchone()[0]\n"
}
]
} | {
"deleted": [
{
"char_start": 207,
"char_end": 208,
"chars": "'"
},
{
"char_start": 209,
"char_end": 211,
"chars": " +"
},
{
"char_start": 230,
"char_end": 236,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 207,
"char_end": 208,
"chars": "?"
},
{
"char_start": 209,
"char_end": 210,
"chars": ","
},
{
"char_start": 211,
"char_end": 212,
"chars": "["
},
{
"char_start": 230,
"char_end": 231,
"chars": "]"
}
]
} | github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9 | CheckAndPostForSeriesSubmissions.py | cwe-089 |
ranks | @endpoints.route("/ranks")
def ranks():
if db == None:
init()
scene = request.args.get('scene', default='austin')
date = request.args.get('date')
# If no date was provided, pick the date of the latest tournament
if date == None:
sql = "SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;".format(scene)
res = db.exec(sql)
date = res[0][0]
# Get all the urls that this player has participated in
sql = "SELECT * FROM ranks WHERE scene = '{}' and date='{}'".format(scene, date)
res = db.exec(sql)
# Make a dict out of this data
# eg {'christmasmike': 50}
cur_ranks = {}
for r in res:
tag = r[1]
rank = r[2]
cur_ranks[tag] = rank
# Now get the ranks from last month, so we know if these players went up or down
y, m, d = date.split('-')
prev_date = bracket_utils.get_previous_month(date)
# Get all the urls that this player has participated in
sql = "SELECT * FROM ranks WHERE scene = '{}' and date='{}'".format(scene, prev_date)
res = db.exec(sql)
# Make a dict out of this data
# eg {'christmasmike': 50}
prev_ranks = {}
for r in res:
tag = r[1]
rank = r[2]
prev_ranks[tag] = rank
return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date) | @endpoints.route("/ranks")
def ranks():
if db == None:
init()
scene = request.args.get('scene', default='austin')
date = request.args.get('date')
# If no date was provided, pick the date of the latest tournament
if date == None:
sql = "SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;"
args = {'scene': scene}
res = db.exec(sql, args)
date = res[0][0]
# Get all the urls that this player has participated in
sql = "SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"
args = {'scene': scene, 'date': date}
res = db.exec(sql, args)
# Make a dict out of this data
# eg {'christmasmike': 50}
cur_ranks = {}
for r in res:
tag = r[1]
rank = r[2]
cur_ranks[tag] = rank
# Now get the ranks from last month, so we know if these players went up or down
y, m, d = date.split('-')
prev_date = bracket_utils.get_previous_month(date)
# Get all the urls that this player has participated in
sql = "SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'"
args = {'scene': scene, 'date': prev_date}
res = db.exec(sql, args)
# Make a dict out of this data
# eg {'christmasmike': 50}
prev_ranks = {}
for r in res:
tag = r[1]
rank = r[2]
prev_ranks[tag] = rank
return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date) | {
"deleted": [
{
"line_no": 11,
"char_start": 260,
"char_end": 367,
"line": " sql = \"SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;\".format(scene)\n"
},
{
"line_no": 12,
"char_start": 367,
"char_end": 394,
"line": " res = db.exec(sql)\n"
},
{
"line_no": 16,
"char_start": 480,
"char_end": 565,
"line": " sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, date)\n"
},
{
"line_no": 17,
"char_start": 565,
"char_end": 588,
"line": " res = db.exec(sql)\n"
},
{
"line_no": 33,
"char_start": 994,
"char_end": 1084,
"line": " sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, prev_date)\n"
},
{
"line_no": 34,
"char_start": 1084,
"char_end": 1107,
"line": " res = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 260,
"char_end": 358,
"line": " sql = \"SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;\"\n"
},
{
"line_no": 12,
"char_start": 358,
"char_end": 390,
"line": " args = {'scene': scene}\n"
},
{
"line_no": 13,
"char_start": 390,
"char_end": 423,
"line": " res = db.exec(sql, args)\n"
},
{
"line_no": 17,
"char_start": 509,
"char_end": 583,
"line": " sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n"
},
{
"line_no": 18,
"char_start": 583,
"char_end": 625,
"line": " args = {'scene': scene, 'date': date}\n"
},
{
"line_no": 19,
"char_start": 625,
"char_end": 654,
"line": " res = db.exec(sql, args)\n"
},
{
"line_no": 35,
"char_start": 1060,
"char_end": 1134,
"line": " sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n"
},
{
"line_no": 36,
"char_start": 1134,
"char_end": 1181,
"line": " args = {'scene': scene, 'date': prev_date}\n"
},
{
"line_no": 37,
"char_start": 1181,
"char_end": 1210,
"line": " res = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 352,
"char_end": 355,
"chars": ".fo"
},
{
"char_start": 356,
"char_end": 360,
"chars": "mat("
},
{
"char_start": 365,
"char_end": 366,
"chars": ")"
},
{
"char_start": 544,
"char_end": 547,
"chars": ".fo"
},
{
"char_start": 548,
"char_end": 552,
"chars": "mat("
},
{
"char_start": 563,
"char_end": 564,
"chars": ")"
},
{
"char_start": 1058,
"char_end": 1061,
"chars": ".fo"
},
{
"char_start": 1062,
"char_end": 1066,
"chars": "mat("
},
{
"char_start": 1082,
"char_end": 1083,
"chars": ")"
}
],
"added": [
{
"char_start": 321,
"char_end": 326,
"chars": "scene"
},
{
"char_start": 357,
"char_end": 366,
"chars": "\n "
},
{
"char_start": 367,
"char_end": 375,
"chars": "rgs = {'"
},
{
"char_start": 380,
"char_end": 389,
"chars": "': scene}"
},
{
"char_start": 415,
"char_end": 421,
"chars": ", args"
},
{
"char_start": 556,
"char_end": 561,
"chars": "scene"
},
{
"char_start": 575,
"char_end": 579,
"chars": "date"
},
{
"char_start": 582,
"char_end": 587,
"chars": "\n "
},
{
"char_start": 588,
"char_end": 604,
"chars": "rgs = {'scene': "
},
{
"char_start": 611,
"char_end": 612,
"chars": "'"
},
{
"char_start": 616,
"char_end": 624,
"chars": "': date}"
},
{
"char_start": 646,
"char_end": 652,
"chars": ", args"
},
{
"char_start": 1107,
"char_end": 1112,
"chars": "scene"
},
{
"char_start": 1126,
"char_end": 1130,
"chars": "date"
},
{
"char_start": 1133,
"char_end": 1138,
"chars": "\n "
},
{
"char_start": 1139,
"char_end": 1155,
"chars": "rgs = {'scene': "
},
{
"char_start": 1162,
"char_end": 1170,
"chars": "'date': "
},
{
"char_start": 1179,
"char_end": 1180,
"chars": "}"
},
{
"char_start": 1202,
"char_end": 1208,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | endpoints.py | cwe-089 |