File size: 459,292 Bytes
35691f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | {"code": " function selectObjectBySql($sql) {\n //$logFile = \"C:\\\\xampp\\\\htdocs\\\\supserg\\\\tmp\\\\queryLog.txt\";\n //$lfh = fopen($logFile, 'a');\n //fwrite($lfh, $sql . \"\\n\"); \n //fclose($lfh); \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return null;\n return mysqli_fetch_object($res);\n }", "label_name": "CWE-74", "label": 1}
{"code": "\tfunction show_vendor () {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\t$vendor_title = $vendor->title;\n\t\t\t$state = new geoRegion($vendor->state);\n\t\t\t$vendor->state = $state->name;\n\t\t\t//Removed unnecessary fields\n\t\t\tunset(\n $vendor->title,\n $vendor->table,\n $vendor->tablename,\n $vendor->classname,\n $vendor->identifier\n );\n\t\t\n\t\t\tassign_to_template(array(\n 'vendor_title' => $vendor_title,\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1}
{"code": "\tprotected function replaceTagCount( $tag, $nr ) {\n\t\treturn str_replace( '%NR%', $nr, $tag );\n\t}", "label_name": "CWE-400", "label": 2}
{"code": " function preview()\n {\n if ($this->params['id'] == 0) { // we want the default editor\n $demo = new stdClass();\n $demo->id = 0;\n $demo->name = \"Default\";\n if ($this->params['editor'] == 'ckeditor') {\n $demo->skin = 'kama';\n } elseif ($this->params['editor'] == 'tinymce') {\n $demo->skin = 'lightgray';\n }\n } else {\n $demo = self::getEditorSettings($this->params['id'], $this->params['editor']);\n }\n assign_to_template(\n array(\n 'demo' => $demo,\n 'editor' => $this->params['editor']\n )\n );\n }", "label_name": "CWE-200", "label": 10}
{"code": "function test1Controller($hphpdOutput, $hphpdProcessId, $serverPort) {\n // Request a page so that the client can debug it.\n waitForClientToOutput($hphpdOutput, \"Waiting for server response\");\n $url = \"http://\".php_uname('n').':'.$serverPort.'/test1.php';\n echo \"Requesting test1.php\\n\";\n request(php_uname('n'), $serverPort, 'test1.php', 10); // ignore response\n\n // Let client run until script quits\n waitForClientToOutput($hphpdOutput, \"quit\");\n}", "label_name": "CWE-668", "label": 7}
{"code": "\t\t\t\tforeach ($aco_value_array as $aco_value) {\n\t\t\t\t\t$this->debug_text(\"shift_acl(): ACO Section Value: $aco_section_value ACO VALUE: $aco_value\");\n\t\t\t\t\t$aco_key = array_search($aco_value, $acl_array['aco'][$aco_section_value]);\n\n\t\t\t\t\tif ($aco_key !== FALSE) {\n\t\t\t\t\t\t$this->debug_text(\"shift_acl(): Removing ACO. ($aco_key)\");\n\t\t\t\t\t\tunset($acl_array['aco'][$aco_section_value][$aco_key]);\n\t\t\t\t\t\t$update = 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->debug_text(\"shift_acl(): ACO doesn't exist, can't remove it.\");\n\t\t\t\t\t}\n\t\t\t\t}", "label_name": "CWE-863", "label": 11}
{"code": "\tstatic public function getCategoryName($_id = 0) {\n\n\t\tif ($_id != 0) {\n\t\t\t$stmt = Database::prepare(\"\n\t\t\t\tSELECT `name` FROM `\" . TABLE_PANEL_TICKET_CATS . \"` WHERE `id` = :id\"\n\t\t\t);\n\t\t\t$category = Database::pexecute_first($stmt, array('id' => $_id));\n\t\t\treturn $category['name'];\n\t\t}\n\t\treturn null;\n\t}", "label_name": "CWE-732", "label": 13}
{"code": " public function showall_tags() {\n $images = $this->image->find('all');\n $used_tags = array();\n foreach ($images as $image) {\n foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }\n }\n \n assign_to_template(array(\n 'tags'=>$used_tags\n ));\n } ", "label_name": "CWE-74", "label": 1}
{"code": "function XMLRPCaddResourceGroupPriv($name, $type, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $perms = explode(':', $permissions);\n updateResourcePrivs(\"$type/$name\", $nodeid, $perms, array());\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label_name": "CWE-20", "label": 0}
{"code": " function fread($handle, $length)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fread !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fread;\n }\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return $length < 8 ? \\str_repeat('s', $length) : 'test1234';\n }\n\n return \\fread($handle, $length);\n }", "label_name": "CWE-330", "label": 12}
{"code": " private function getTaskLink()\n {\n $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n return $link;\n }", "label_name": "CWE-200", "label": 10}
{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": 12}
{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " foreach($item->attributes as $name => $value)\n if ($name !== 'id' && $name !== 'listId')\n $copy->$name = $value;\n $lineItems[] = $copy;\n }\n return $lineItems;\n }", "label_name": "CWE-20", "label": 0}
{"code": " public function save()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->categoryValidator->validateCreation($values);\n\n if ($valid) {\n if ($this->categoryModel->create($values) !== false) {\n $this->flash->success(t('Your category have been created successfully.'));\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $errors = array('name' => array(t('Another category with the same name exists in this project')));\n }\n }\n\n $this->create($values, $errors);\n }", "label_name": "CWE-200", "label": 10}
{"code": " public function shouldRun(DateTime $date)\n {\n global $timedate;\n\n $runDate = clone $date;\n $this->handleTimeZone($runDate);\n\n $cron = Cron\\CronExpression::factory($this->schedule);\n if (empty($this->last_run) && $cron->isDue($runDate)) {\n return true;\n }\n\n $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);\n \n $this->handleTimeZone($lastRun);\n $next = $cron->getNextRunDate($lastRun);\n\n return $next <= $runDate;\n }", "label_name": "CWE-863", "label": 11}
{"code": "\t\t\t\t$fieldPickListValues[$value] = \\App\\Language::translate($value, $this->getModuleName(),false,false);\n\t\t\t}\n\t\t\t// Protection against deleting a value that does not exist on the list\n\t\t\tif ('picklist' === $fieldDataType) {\n\t\t\t\t$fieldValue = $this->get('fieldvalue');\n\t\t\t\tif (!empty($fieldValue) && !isset($fieldPickListValues[$fieldValue])) {\n\t\t\t\t\t$fieldPickListValues[$fieldValue] = \\App\\Language::translate($fieldValue, $this->getModuleName(),false,false);\n\t\t\t\t\t$this->set('isEditableReadOnly', true);\n\t\t\t\t}\n\t\t\t}\n\t\t} elseif (method_exists($this->getUITypeModel(), 'getPicklistValues')) {", "label_name": "CWE-20", "label": 0}
{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10}
{"code": " public function create_directory() {\n if (!AuthUser::hasPermission('file_manager_mkdir')) {\n Flash::set('error', __('You do not have sufficient permissions to create a directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_directory')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['directory'];\n\n $path = str_replace('..', '', $data['path']);\n $dirname = str_replace('..', '', $data['name']);\n $dir = FILES_DIR . \"/{$path}/{$dirname}\";\n\n if (mkdir($dir)) {\n $mode = Plugin::getSetting('dirmode', 'file_manager');\n chmod($dir, octdec($mode));\n } else {\n Flash::set('error', __('Directory :name has not been created!', array(':name' => $dirname)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0}
{"code": " protected function generateCookieHash($class, $username, $expires, $password)\n {\n return hash_hmac('sha256', $class.$username.$expires.$password, $this->getSecret());\n }", "label_name": "CWE-287", "label": 4}
{"code": "function get_filedisplay_views() {\n expTemplate::get_filedisplay_views();\n\n $paths = array(\n BASE.'framework/modules/common/views/file/',\n BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',\n );\n \n $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $views[$filename] = gt($filename);\n }\n }\n }\n }\n \n return $views;\n}", "label_name": "CWE-74", "label": 1}
{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1}
{"code": "\tpublic function Insert() {\n\n\t\t$ins_stmt = Database::prepare(\"\n\t\t\tINSERT INTO `\" . TABLE_PANEL_TICKETS . \"` SET\n `customerid` = :customerid,\n `adminid` = :adminid,\n `category` = :category,\n `priority` = :priority,\n `subject` = :subject,\n `message` = :message,\n `dt` = :dt,\n `lastchange` = :lastchange,\n `ip` = :ip,\n `status` = :status,\n `lastreplier` = :lastreplier,\n `by` = :by,\n `answerto` = :answerto\"\n\t\t);\n\t\t$ins_data = array(\n\t\t\t'customerid' => $this->Get('customer'),\n\t\t\t'adminid' => $this->Get('admin'),\n\t\t\t'category' => $this->Get('category'),\n\t\t\t'priority' => $this->Get('priority'),\n\t\t\t'subject' => $this->Get('subject'),\n\t\t\t'message' => $this->Get('message'),\n\t\t\t'dt' => time(),\n\t\t\t'lastchange' => time(),\n\t\t\t'ip' => $this->Get('ip'),\n\t\t\t'status' => $this->Get('status'),\n\t\t\t'lastreplier' => $this->Get('lastreplier'),\n\t\t\t'by' => $this->Get('by'),\n\t\t\t'answerto' => $this->Get('answerto')\n\t\t);\n\t\tDatabase::pexecute($ins_stmt, $ins_data);\n\t\t$this->tid = Database::lastInsertId();\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": 13}
{"code": " private static function sign($input, $key, $algo = 'HS256')\n {\n switch ($algo) {\n\n case 'HS256':\n return hash_hmac('sha256', $input, $key, true);\n\n case 'HS384':\n return hash_hmac('sha384', $input, $key, true);\n\n case 'HS512':\n return hash_hmac('sha512', $input, $key, true);\n\n case 'RS256':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA256);\n\n case 'RS384':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA384);\n\n case 'RS512':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA512);\n\n default:\n throw new Exception(\"Unsupported or invalid signing algorithm.\");\n }\n }", "label_name": "CWE-20", "label": 0}
{"code": " foreach ($week as $dayNum => $day) {\r\n if ($dayNum == $now['mday']) {\r\n $currentweek = $weekNum;\r\n }\r\n if ($dayNum <= $endofmonth) {\r\n// $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects(\"eventdate\", $locsql . \" AND date >= \" . expDateTime::startOfDayTimestamp($day['ts']) . \" AND date <= \" . expDateTime::endOfDayTimestamp($day['ts'])) : -1;\r\n $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find(\"count\", $locsql . \" AND date >= \" . expDateTime::startOfDayTimestamp($day['ts']) . \" AND date <= \" . expDateTime::endOfDayTimestamp($day['ts'])) : -1;\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-200", "label": 10}
{"code": "function XMLRPCremoveUserGroupPriv($name, $affiliation, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n\tglobal $user;\n\n if(! checkUserHasPriv(\"userGrant\", $user['id'], $nodeid)){\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to remove group privileges on this node');\n }\n\n\t$validate = array('name' => $name,\n\t 'affiliation' => $affiliation);\n\t$rc = validateAPIgroupInput($validate, 1);\n\tif($rc['status'] == 'error')\n\t\treturn $rc;\n\n $groupid = $rc['id'];\n $groupname = \"$name@$affiliation\";\n $perms = explode(':', $permissions);\n $usertypes = getTypes('users');\n array_push($usertypes[\"users\"], \"block\");\n\tarray_push($usertypes[\"users\"], \"cascade\");\n $cascadePrivs = getNodeCascadePriviliges($nodeid, \"usergroups\");\n $removegroupprivs = array();\n if(array_key_exists($groupname, $cascadePrivs['usergroups'])){\n foreach($perms as $permission){\n if(in_array($permission, $cascadePrivs['usergroups'][$groupname]['privs'])){\n array_push($removegroupprivs, $permission);\n }\n }\n $diff = array_diff($cascadePrivs['usergroups'][$groupname], $removegroupprivs);\n if(count($diff) == 1 && in_array(\"cascade\", $diff)){\n array_push($removegroupprivs, \"cascade\");\n\t}\n\t}\n if(empty($removegroupprivs)){\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Invalid or missing permissions list supplied');\n\t}\n\n updateUserOrGroupPrivs($groupid, $nodeid, array(), $removegroupprivs, \"group\");\n return array('status' => 'success');\n}", "label_name": "CWE-20", "label": 0}
{"code": "\t\tpublic function removeRemote($name)\n\t\t{\n\t\t\t$this->run('remote', 'remove', $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14}
{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10}
{"code": " public function pending() {\n// global $db;\n \n // make sure we have what we need.\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));\n\n // find the subscriber and their pending subscriptions\n $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);\n $subscriber = new subscribers($this->params['id']);\n \n // render the template\n assign_to_template(array(\n 'subscriber'=>$subscriber,\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": 1}
{"code": " private function getTaskLink()\n {\n $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n return $link;\n }", "label_name": "CWE-200", "label": 10}
{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10}
{"code": " public function update()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n $values = $this->request->getValues();\n list($valid, $errors) = $this->tagValidator->validateModification($values);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($valid) {\n if ($this->tagModel->update($values['id'], $values['name'])) {\n $this->flash->success(t('Tag updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n } else {\n $this->edit($values, $errors);\n }\n }", "label_name": "CWE-200", "label": 10}
{"code": "\tpublic function getPurchaseOrderByJSON() {\n\t\t\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-74", "label": 1}
{"code": " private function decryptContentEncryptionKey($private_key_or_secret) {\n switch ($this->header['alg']) {\n case 'RSA1_5':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'RSA-OAEP':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_OAEP);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'dir':\n $this->content_encryption_key = $private_key_or_secret;\n break;\n case 'A128KW':\n case 'A256KW':\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A256KW':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n if (!$this->content_encryption_key) {\n # NOTE:\n # Not to disclose timing difference between CEK decryption error and others.\n # Mitigating Bleichenbacher Attack on PKCS#1 v1.5\n # ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303\n $this->generateContentEncryptionKey(null);\n }\n }", "label_name": "CWE-200", "label": 10}
{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": "\tprivate function _addcontribution( $option ) {\n\t\t$this->addTable( 'recentchanges', 'rc' );\n\n\t\t$field = 'rc.rc_actor';\n\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'contribution'\t=> 'SUM(ABS(rc.rc_new_len - rc.rc_old_len))',\n\t\t\t\t'contributor'\t=> $field\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rc.rc_cur_id'\n\t\t\t]\n\t\t);\n\t\t$this->addGroupBy( 'rc.rc_cur_id' );\n\t}", "label_name": "CWE-400", "label": 2}
{"code": " public function saveconfig() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n $conf = serialize($calc->parseConfig($this->params)); \n $calc->update(array('config'=>$conf));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1}
{"code": " $links[] = CHtml::link(CHtml::encode($tag->tag),array('/search/search','term'=>CHtml::encode($tag->tag)));", "label_name": "CWE-20", "label": 0}
{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));\n self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));\n\n return new Response(200);\n }\n ]);", "label_name": "CWE-200", "label": 10}
{"code": " public function update_discount() {\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $discount = new discounts($id);\n // find required shipping method if needed\n if ($this->params['required_shipping_calculator_id'] > 0) {\n $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];\n } else {\n $this->params['required_shipping_calculator_id'] = 0;\n }\n \n $discount->update($this->params);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1}
{"code": " public static function navtojson() {\r\n return json_encode(self::navhierarchy());\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": 0}
{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-200", "label": 10}
{"code": " private function getStateId(string $state, string $machine)\n {\n return $this->getContainer()->get(Connection::class)\n ->fetchColumn('\n SELECT LOWER(HEX(state_machine_state.id))\n FROM state_machine_state\n INNER JOIN state_machine\n ON state_machine.id = state_machine_state.state_machine_id\n AND state_machine.technical_name = :machine\n WHERE state_machine_state.technical_name = :state\n ', [\n 'state' => $state,\n 'machine' => $machine,\n ]);\n }", "label_name": "CWE-732", "label": 13}
{"code": " $product = X2Model::model('Products')->findByAttributes(array('name'=>$lineItem->name));\n if (isset($product))\n $lineItem->productId = $product->id;\n if(empty($lineItem->currency))\n\t\t\t\t$lineItem->currency = $defaultCurrency;\n\t\t\tif($lineItem->isPercentAdjustment) {\n\t\t\t\t$lineItem->adjustment = Fields::strToNumeric(\n $lineItem->adjustment,'percentage');\n\t\t\t} else {\n\t\t\t\t$lineItem->adjustment = Fields::strToNumeric(\n $lineItem->adjustment,'currency',$curSym);\n\t\t\t}\n\t\t\t$lineItem->price = Fields::strToNumeric($lineItem->price,'currency',$curSym);\n\t\t\t$lineItem->total = Fields::strToNumeric($lineItem->total,'currency',$curSym);\n\t\t}", "label_name": "CWE-20", "label": 0}
{"code": "\tpublic function execute(&$params) {\n\t\t$options = $this->config['options'];\n\n\t\t$action = new Actions;\n\n\t\t$action->subject = $this->parseOption('subject',$params);\n $action->dueDate = $this->parseOption('dueDate',$params);\n\t\t$action->actionDescription = $this->parseOption('description',$params);\n\t\t$action->priority = $this->parseOption('priority',$params);\n\t\t$action->visibility = $this->parseOption('visibility',$params);\n\n\t\tif(isset($params['model']))\n\t\t\t$action->assignedTo = $this->parseOption('assignedTo',$params);\n\n\t\t// if(isset($this->config['attributes']))\n\t\t\t// $this->setModelAttributes($action,$this->config['attributes'],$params);\n\n if ($action->save()) {\n return array (\n true,\n Yii::t('studio', \"View created action: \").$action->getLink ());\n } else {\n return array(false, array_shift($action->getErrors()));\n }\n\n\n\n\t\t// if($this->parseOption('reminder',$params)) {\n\t\t\t// $notif=new Notification;\n\t\t\t// $notif->modelType='Actions';\n\t\t\t// $notif->createdBy=Yii::app()->user->getName();\n\t\t\t// $notif->modelId=$model->id;\n\t\t\t// if($_POST['notificationUsers']=='me'){\n\t\t\t\t// $notif->user=Yii::app()->user->getName();\n\t\t\t// }else{\n\t\t\t\t// $notif->user=$model->assignedTo;\n\t\t\t// }\n\t\t\t// $notif->createDate=$model->dueDate-($_POST['notificationTime']*60);\n\t\t\t// $notif->type='action_reminder';\n\t\t\t// $notif->save();\n\t\t\t// if($_POST['notificationUsers']=='both' && Yii::app()->user->getName()!=$model->assignedTo){\n\t\t\t\t// $notif2=new Notification;\n\t\t\t\t// $notif2->modelType='Actions';\n\t\t\t\t// $notif2->createdBy=Yii::app()->user->getName();\n\t\t\t\t// $notif2->modelId=$model->id;\n\t\t\t\t// $notif2->user=Yii::app()->user->getName();\n\t\t\t\t// $notif2->createDate=$model->dueDate-($_POST['notificationTime']*60);\n\t\t\t\t// $notif2->type='action_reminder';\n\t\t\t\t// $notif2->save();\n\t\t\t// }\n\t\t// }\n\t}", "label_name": "CWE-20", "label": 0}
{"code": " return $fa->nameGlyph($icons, 'icon-');\r\n }\r\n } else {\r\n return array();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " public static function DragnDropReRank2() {\r\n global $router, $db;\r\n\r\n $id = $router->params['id'];\r\n $page = new section($id);\r\n $old_rank = $page->rank;\r\n $old_parent = $page->parent;\r\n $new_rank = $router->params['position'] + 1; // rank\r\n $new_parent = intval($router->params['parent']);\r\n\r\n $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent); // close in hole\r\n $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent); // make room\r\n\r\n $params = array();\r\n $params['parent'] = $new_parent;\r\n $params['rank'] = $new_rank;\r\n $page->update($params);\r\n\r\n self::checkForSectionalAdmins($id);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " function generateAutoLoginLink($params){\n\n $dataRequest = array();\n $dataRequestAppend = array();\n\n // Destination ID\n if (isset($params['r'])){\n $dataRequest['r'] = $params['r'];\n $dataRequestAppend[] = '/(r)/'.rawurlencode(base64_encode($params['r']));\n }\n\n // User ID\n if (isset($params['u']) && is_numeric($params['u'])){\n $dataRequest['u'] = $params['u'];\n $dataRequestAppend[] = '/(u)/'.rawurlencode($params['u']);\n }\n\n // Username\n if (isset($params['l'])){\n $dataRequest['l'] = $params['l'];\n $dataRequestAppend[] = '/(l)/'.rawurlencode($params['l']);\n }\n\n if (!isset($params['l']) && !isset($params['u'])) {\n throw new Exception('Username or User ID has to be provided');\n }\n\n $ts = time() + $params['t'];\n\n // Expire time for link\n if (isset($params['t'])) {\n $dataRequest['t'] = $ts;\n $dataRequestAppend[] = '/(t)/'.rawurlencode($ts);\n }\n\n $hashValidation = sha1($params['secret_hash'].sha1($params['secret_hash'].implode(',', $dataRequest)));\n\n return $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect(\"user/autologin\") . \"/{$hashValidation}\".implode('', $dataRequestAppend);\n }", "label_name": "CWE-116", "label": 15}
{"code": " protected function prepareImport($model, $csvName) {\n $this->openX2 ('/admin/importModels?model='.ucfirst($model));\n $csv = implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'tests',\n 'data',\n 'csvs',\n $csvName\n ));\n $this->type ('data', $csv);\n $this->clickAndWait (\"dom=document.querySelector ('input[type=\\\"submit\\\"]')\");\n $this->assertCsvUploaded ($csv);\n }", "label_name": "CWE-20", "label": 0}
{"code": "\t\tpublic function checkout($name)\n\t\t{\n\t\t\t$this->run('checkout', $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14}
{"code": " function edit_optiongroup_master() {\n expHistory::set('editable', $this->params);\n \n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $record = new optiongroup_master($id); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": 1}
{"code": " public function showall() {\r\n global $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\CreateCardResponse::class, $gatewayMessage);\n ErrorHandling::safeExtend($this->payment, 'onCardCreated', $serviceResponse);\n }", "label_name": "CWE-436", "label": 5}
{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-74", "label": 1}
{"code": "\tprivate function readData() {\n\n\t\tif (isset($this->tid)\n\t\t\t&& $this->tid != - 1\n\t\t) {\n\t\t\t$_ticket_stmt = Database::prepare('\n\t\t\t\tSELECT * FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'\n\t\t\t);\n\t\t\t$_ticket = Database::pexecute_first($_ticket_stmt, array('tid' => $this->tid));\n\n\t\t\t$this->Set('customer', $_ticket['customerid'], true, false);\n\t\t\t$this->Set('admin', $_ticket['adminid'], true, false);\n\t\t\t$this->Set('subject', $_ticket['subject'], true, false);\n\t\t\t$this->Set('category', $_ticket['category'], true, false);\n\t\t\t$this->Set('priority', $_ticket['priority'], true, false);\n\t\t\t$this->Set('message', $_ticket['message'], true, false);\n\t\t\t$this->Set('dt', $_ticket['dt'], true, false);\n\t\t\t$this->Set('lastchange', $_ticket['lastchange'], true, false);\n\t\t\t$this->Set('ip', $_ticket['ip'], true, false);\n\t\t\t$this->Set('status', $_ticket['status'], true, false);\n\t\t\t$this->Set('lastreplier', $_ticket['lastreplier'], true, false);\n\t\t\t$this->Set('by', $_ticket['by'], true, false);\n\t\t\t$this->Set('answerto', $_ticket['answerto'], true, false);\n\t\t\t$this->Set('archived', $_ticket['archived'], true, false);\n\t\t}\n\t}", "label_name": "CWE-732", "label": 13}
{"code": " protected function AddAnAddress($kind, $address, $name = '') {\n if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {\n $this->SetError($this->Lang('Invalid recipient array').': '.$kind);\n if ($this->exceptions) {\n throw new phpmailerException('Invalid recipient array: ' . $kind);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('Invalid recipient array').': '.$kind);\n }\n return false;\n }\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->ValidateAddress($address)) {\n $this->SetError($this->Lang('invalid_address').': '. $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->Lang('invalid_address').': '.$address);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('invalid_address').': '.$address);\n }\n return false;\n }\n if ($kind != 'Reply-To') {\n if (!isset($this->all_recipients[strtolower($address)])) {\n array_push($this->$kind, array($address, $name));\n $this->all_recipients[strtolower($address)] = true;\n return true;\n }\n } else {\n if (!array_key_exists(strtolower($address), $this->ReplyTo)) {\n $this->ReplyTo[strtolower($address)] = array($address, $name);\n return true;\n }\n }\n return false;\n}", "label_name": "CWE-20", "label": 0}
{"code": " public function settings_save() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n if (!isset($_POST['settings'])) {\n Flash::set('error', 'File Manager - ' . __('form was not posted.'));\n redirect(get_url('plugin/file_manager/settings'));\n } else {\n $settings = $_POST['settings'];\n\n if ($settings['umask'] == 0)\n $settings['umask'] = 0;\n elseif (!preg_match('/^0?[0-7]{3}$/', $settings['umask']))\n $settings['umask'] = 0;\n if (strlen($settings['umask']) === 3)\n $settings['umask'] = '0' . $settings['umask'];\n elseif (strlen($settings['umask']) !== 4 && $settings['umask'] != 0)\n $settings['umask'] = 0;\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['dirmode']))\n $settings['dirmode'] = '0755';\n if (strlen($settings['dirmode']) === 3)\n $settings['dirmode'] = '0' . $settings['dirmode'];\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['filemode']))\n $settings['filemode'] = '0755';\n if (strlen($settings['filemode']) === 3)\n $settings['filemode'] = '0' . $settings['filemode'];\n }\n\n if (Plugin::setAllSettings($settings, 'file_manager'))\n Flash::setNow('success', 'File Manager - ' . __('plugin settings saved.'));\n else\n Flash::setNow('error', 'File Manager - ' . __('plugin settings not saved!'));\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": 0}
{"code": " public function getChart($renderer, $id, $store_in_session = true)\n {\n $c = null;\n $chart_data = null;\n if ($renderer != null && $store_in_session) {\n $session = new Tracker_Report_Session($renderer->report->id);\n $session->changeSessionNamespace(\"renderers.{$renderer->id}\");\n\n // look for the chart in the session\n $chart_data = $session->get(\"charts.$id\");\n }\n\n if (! $chart_data) {\n // not found. look in the db\n $dao = new GraphOnTrackersV5_ChartDao(CodendiDataAccess::instance());\n $chart_data = $dao->searchById($id)->getRow();\n }\n\n if ($chart_data) {\n if (! $renderer) {\n $report = null; //We don't know the report\n $renderer = Tracker_Report_RendererFactory::instance()->getReportRendererById($chart_data['report_graphic_id'], $report, $store_in_session);\n }\n if ($renderer) {\n $c = $this->instanciateChart($chart_data, $renderer, $store_in_session);\n }\n }\n return $c;\n }", "label_name": "CWE-862", "label": 8}
{"code": " Contacts::model()->deleteAll($criteria);\n }\n }\n echo $model->id;\n }\n }", "label_name": "CWE-20", "label": 0}
{"code": " $sloc = expCore::makeLocation('navigation', null, $section->id);\r\n // remove any manage permissions for this page and it's children\r\n // $db->delete('userpermission', \"module='navigationController' AND internal=\".$section->id);\r\n // $db->delete('grouppermission', \"module='navigationController' AND internal=\".$section->id);\r\n foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r\n foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": "\t\t\t\t$item = trim( $item );\n\t\t\t\tif ( strpos( $item, '|-' ) === 0 ) {\n\t\t\t\t\t$item = explode( '|-', $item, 2 );\n\t\t\t\t\tif ( count( $item ) == 2 ) {\n\t\t\t\t\t\t$item = $item[1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$rowsKey[$index] = $item;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ( strlen( $item ) > 0 ) {\n\t\t\t\t\t$word = explode( \"\\n|\", $item );\n\t\t\t\t\tif ( isset( $word[0] ) && empty( $word[0] ) ) {\n\t\t\t\t\t\tarray_shift( $word );\n\t\t\t\t\t}\n\t\t\t\t\tif ( isset( $word[abs( $sortColumn ) - 1] ) ) {\n\t\t\t\t\t\t$test = trim( $word[abs( $sortColumn ) - 1] );\n\t\t\t\t\t\tif ( strpos( $test, '|' ) > 0 ) {\n\t\t\t\t\t\t\t$test = trim( explode( '|', $test )[1] );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$rowsKey[$index] = $test;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->sort($rowsKey, $sortColumn);\n\t\t\t$newItems = [];\n\t\t\tforeach ( $rowsKey as $index => $val ) {\n\t\t\t\t$newItems[] = $items[$index];\n\t\t\t}\n\t\t\t$items = $newItems;\n\t\t}\n\n\t\treturn $this->listStart . $this->implodeItems( $items ) . $this->listEnd;\n\t}", "label_name": "CWE-400", "label": 2}
{"code": " public function manage_messages() {\n expHistory::set('manageable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1}
{"code": "\tpublic function Delete() {\n\n\t\t// Delete \"main\" ticket\n\t\t$del_stmt = Database::prepare('\n\t\t\tDELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'\n\t\t);\n\t\tDatabase::pexecute($del_stmt, array('tid' => $this->tid));\n\n\t\t// Delete \"answers\" to ticket\"\n\t\t$del_stmt = Database::prepare('\n\t\t\tDELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `answerto` = :tid'\n\t\t);\n\t\tDatabase::pexecute($del_stmt, array('tid' => $this->tid));\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": 13}
{"code": " public function gc($force = false, $expiredOnly = true)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->gcRecursive($this->cachePath, $expiredOnly);\n }\n }", "label_name": "CWE-330", "label": 12}
{"code": "function barcode_encode($code,$encoding)\n{\n global $genbarcode_loc;\n\n if (\n ((preg_match(\"/^ean$/i\", $encoding)\n && ( strlen($code)==12 || strlen($code)==13)))\n\n || (($encoding) && (preg_match(\"/^isbn$/i\", $encoding))\n && (( strlen($code)==9 || strlen($code)==10) ||\n (((preg_match(\"/^978/\", $code) && strlen($code)==12) ||\n (strlen($code)==13)))))\n\n || (( !isset($encoding) || !$encoding || (preg_match(\"/^ANY$/i\", $encoding) ))\n && (preg_match(\"/^[0-9]{12,13}$/\", $code)))\n )\n {\n /* use built-in EAN-Encoder */\n dol_syslog(\"barcode.lib.php::barcode_encode Use barcode_encode_ean\");\n $bars=barcode_encode_ean($code, $encoding);\n }\n else if (file_exists($genbarcode_loc))\n {\n /* use genbarcode */\n dol_syslog(\"barcode.lib.php::barcode_encode Use genbarcode \".$genbarcode_loc.\" code=\".$code.\" encoding=\".$encoding);\n $bars=barcode_encode_genbarcode($code, $encoding);\n }\n else\n {\n print \"barcode_encode needs an external programm for encodings other then EAN/ISBN<BR>\\n\";\n print \"<UL>\\n\";\n print \"<LI>download gnu-barcode from <A href=\\\"http://www.gnu.org/software/barcode/\\\">www.gnu.org/software/barcode/</A>\\n\";\n print \"<LI>compile and install them\\n\";\n print \"<LI>download genbarcode from <A href=\\\"http://www.ashberg.de/bar/\\\">www.ashberg.de/bar/</A>\\n\";\n print \"<LI>compile and install them\\n\";\n print \"<LI>specify path the genbarcode in barcode module setup\\n\";\n print \"</UL>\\n\";\n print \"<BR>\\n\";\n return false;\n }\n return $bars;\n}", "label_name": "CWE-20", "label": 0}
{"code": "\tprivate function _addlasteditor( $option ) {\n\t\t//Addlasteditor can not be used with addauthor.\n\t\tif ( !isset( $this->parametersProcessed['addauthor'] ) || !$this->parametersProcessed['addauthor'] ) {\n\t\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t\t$this->addWhere(\n\t\t\t\t[\n\t\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t\t'rev.revactor_timestamp = (SELECT MAX(rev_aux_max.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_max WHERE rev_aux_max.revactor_page = rev.revactor_page)'\n\t\t\t\t]\n\t\t\t);\n\t\t\t$this->_adduser( null, 'rev' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2}
{"code": " public function validateMulti(array $credentialCandidates)\n {\n $lastException = null;\n\n foreach ($credentialCandidates as $credential) {\n if (false == $credential instanceof CredentialInterface) {\n throw new \\InvalidArgumentException('Expected CredentialInterface');\n }\n if (null == $credential->getPublicKey()) {\n continue;\n }\n\n try {\n $result = $this->validate($credential->getPublicKey());\n\n if ($result === false) {\n return;\n }\n\n return $credential;\n } catch (LightSamlSecurityException $ex) {\n $lastException = $ex;\n }\n }\n\n if ($lastException) {\n throw $lastException;\n } else {\n throw new LightSamlSecurityException('No public key available for signature verification');\n }\n }", "label_name": "CWE-732", "label": 13}
{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory();\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10}
{"code": "\tprivate function _qualitypages( $option ) {\n\t\tif ( function_exists( 'efLoadFlaggedRevs' ) ) {\n\t\t\t//Do not add this again if 'stablepages' has already added it.\n\t\t\tif ( !$this->parametersProcessed['stablepages'] ) {\n\t\t\t\t$this->addJoin(\n\t\t\t\t\t'flaggedpages',\n\t\t\t\t\t[\n\t\t\t\t\t\t\"LEFT JOIN\",\n\t\t\t\t\t\t\"page_id = fp_page_id\"\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t\tswitch ( $option ) {\n\t\t\t\tcase 'only':\n\t\t\t\t\t$this->addWhere( 'fp_quality >= 1' );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'exclude':\n\t\t\t\t\t$this->addWhere( 'fp_quality = 0' );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2}
{"code": "\tfunction test_empty_comment() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => '',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": 8}
{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": "\t\tpublic function renameRemote($oldName, $newName)\n\t\t{\n\t\t\t$this->run('remote', 'rename', $oldName, $newName);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14}
{"code": " private function edebug($str) {\n if ($this->Debugoutput == \"error_log\") {\n error_log($str);\n } else {\n echo $str;\n }\n }", "label_name": "CWE-20", "label": 0}
{"code": " public function testGetEvents(){\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('admin');\n\n Yii::app()->settings->historyPrivacy = null;\n $lastEventId = 0;\n $lastTimestamp = 0;\n $events = Events::getEvents ($lastEventId, $lastTimestamp, 4);\n $this->assertEquals (\n Yii::app()->db->createCommand (\n \"select id from x2_events order by timestamp desc, id desc limit 4\")\n ->queryColumn (),\n array_map(function ($event) { return $event->id; }, $events['events'])\n ); \n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": 0}
{"code": " function delete_recurring() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item->is_recurring == 1) { // need to give user options\r\n expHistory::set('editable', $this->params);\r\n assign_to_template(array(\r\n 'checked_date' => $this->params['date_id'],\r\n 'event' => $item,\r\n ));\r\n } else { // Process a regular delete\r\n $item->delete();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": "\t\tpublic function fetch($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('fetch', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14}
{"code": " public function Connect ($host, $port = false, $tval = 30) {\n // Are we already connected?\n if ($this->connected) {\n return true;\n }\n\n /*\n On Windows this will raise a PHP Warning error if the hostname doesn't exist.\n Rather than supress it with @fsockopen, let's capture it cleanly instead\n */\n\n set_error_handler(array(&$this, 'catchWarning'));\n\n // Connect to the POP3 server\n $this->pop_conn = fsockopen($host, // POP3 Host\n $port, // Port #\n $errno, // Error Number\n $errstr, // Error Message\n $tval); // Timeout (seconds)\n\n // Restore the error handler\n restore_error_handler();\n\n // Does the Error Log now contain anything?\n if ($this->error && $this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n // Did we connect?\n if ($this->pop_conn == false) {\n // It would appear not...\n $this->error = array(\n 'error' => \"Failed to connect to server $host on port $port\",\n 'errno' => $errno,\n 'errstr' => $errstr\n );\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n return false;\n }\n\n // Increase the stream time-out\n\n // Check for PHP 4.3.0 or later\n if (version_compare(phpversion(), '5.0.0', 'ge')) {\n stream_set_timeout($this->pop_conn, $tval, 0);\n } else {\n // Does not work on Windows\n if (substr(PHP_OS, 0, 3) !== 'WIN') {\n socket_set_timeout($this->pop_conn, $tval, 0);\n }\n }\n\n // Get the POP3 server response\n $pop3_response = $this->getResponse();\n\n // Check for the +OK\n if ($this->checkResponse($pop3_response)) {\n // The connection is established and the POP3 server is talking\n $this->connected = true;\n return true;\n }\n return false;\n }", "label_name": "CWE-20", "label": 0}
{"code": " foreach ($fields as $field) {\n $fieldName = $field->fieldName;\n if ($field->type == 'date' || $field->type == 'dateTime') {\n if (is_numeric($record->$fieldName))\n $record->$fieldName = Formatter::formatLongDateTime($record->$fieldName);\n }elseif ($field->type == 'link') {\n $name = $record->$fieldName;\n if (!empty($field->linkType)) {\n list($name, $id) = Fields::nameAndId($name);\n }\n if (!empty($name))\n $record->$fieldName = $name;\n }elseif ($fieldName == 'visibility') {\n $record->$fieldName = $record->$fieldName == 1 ? 'Public' : 'Private';\n }\n }", "label_name": "CWE-20", "label": 0}
{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false];", "label_name": "CWE-330", "label": 12}
{"code": " $rndString = function ($len = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $randomString = '';\n for ($i = 0; $i < $len; $i++) {\n $randomString .= $characters[rand(0, strlen($characters) - 1)];\n }\n\n return $randomString;\n };", "label_name": "CWE-330", "label": 12}
{"code": " protected function renderImageByGD($code)\n {\n $image = imagecreatetruecolor($this->width, $this->height);\n\n $backColor = imagecolorallocate(\n $image,\n (int) ($this->backColor % 0x1000000 / 0x10000),\n (int) ($this->backColor % 0x10000 / 0x100),\n $this->backColor % 0x100\n );\n imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);\n imagecolordeallocate($image, $backColor);\n\n if ($this->transparent) {\n imagecolortransparent($image, $backColor);\n }\n\n $foreColor = imagecolorallocate(\n $image,\n (int) ($this->foreColor % 0x1000000 / 0x10000),\n (int) ($this->foreColor % 0x10000 / 0x100),\n $this->foreColor % 0x100\n );\n\n $length = strlen($code);\n $box = imagettfbbox(30, 0, $this->fontFile, $code);\n $w = $box[4] - $box[0] + $this->offset * ($length - 1);\n $h = $box[1] - $box[5];\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);\n $angle = mt_rand(-10, 10);\n $letter = $code[$i];\n $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);\n $x = $box[2] + $this->offset;\n }\n\n imagecolordeallocate($image, $foreColor);\n\n ob_start();\n imagepng($image);\n imagedestroy($image);\n\n return ob_get_clean();\n }", "label_name": "CWE-330", "label": 12}
{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label_name": "CWE-200", "label": 10}
{"code": " $evs = $this->event->find('all', \"id=\" . $edate->event_id . $featuresql);\r\n foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r\n if (count($events) < 500) { // magic number to not crash loop?\r\n $events = array_merge($events, $evs);\r\n } else {\r\n// $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');\r\n// $events = array_merge($events, $evs);\r\n flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));\r\n break; // keep from breaking system by too much data\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1}
{"code": " public static function decode($jwt, $key = null, $verify = true)\n {\n $tks = explode('.', $jwt);\n\n if (count($tks) != 3) {\n throw new Exception('Wrong number of segments');\n }\n\n list($headb64, $payloadb64, $cryptob64) = $tks;\n\n if (null === ($header = json_decode(JWT::urlsafeB64Decode($headb64)))) {\n throw new Exception('Invalid segment encoding');\n }\n\n if (null === $payload = json_decode(JWT::urlsafeB64Decode($payloadb64))) {\n throw new Exception('Invalid segment encoding');\n }\n\n $sig = JWT::urlsafeB64Decode($cryptob64);\n\n if ($verify) {\n if (empty($header->alg)) {\n throw new DomainException('Empty algorithm');\n }\n\n if (!JWT::verifySignature($sig, \"$headb64.$payloadb64\", $key, $header->alg)) {\n throw new UnexpectedValueException('Signature verification failed');\n }\n }\n\n return $payload;\n }", "label_name": "CWE-20", "label": 0}
{"code": " private function SendHello($hello, $host) {\n fputs($this->smtp_conn, $hello . \" \" . $host . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER: \" . $rply . $this->CRLF . '<br />');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => $hello . \" not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '<br />');\n }\n return false;\n }\n\n $this->helo_rply = $rply;\n\n return true;\n }", "label_name": "CWE-20", "label": 0}
{"code": " public function __construct(private \\Git_Exec $git_exec, private BranchCreationExecutor $branch_creation_executor)\n {\n }", "label_name": "CWE-862", "label": 8}
{"code": "\t function update_upcharge() {\n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\t\t\n\t\t//This will make sure that only the country or region that given a rate value will be saved in the db\n\t\t$upcharge = array();\n\t\tforeach($this->params['upcharge'] as $key => $item) {\n\t\t\tif(!empty($item)) {\n\t\t\t\t$upcharge[$key] = $item;\n\t\t\t}\n\t\t}\n\t\t$this->config['upcharge'] = $upcharge;\n\t\t\n $config->update(array('config'=>$this->config));\n flash('message', gt('Configuration updated'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1}
{"code": " public function Disconnect () {\n $this->sendString('QUIT');\n\n fclose($this->pop_conn);\n }", "label_name": "CWE-20", "label": 0}
{"code": " protected function getFile()\n {\n $task_id = $this->request->getIntegerParam('task_id');\n $file_id = $this->request->getIntegerParam('file_id');\n $model = 'projectFileModel';\n\n if ($task_id > 0) {\n $model = 'taskFileModel';\n $project_id = $this->taskFinderModel->getProjectId($task_id);\n\n if ($project_id !== $this->request->getIntegerParam('project_id')) {\n throw new AccessForbiddenException();\n }\n }\n\n $file = $this->$model->getById($file_id);\n\n if (empty($file)) {\n throw new PageNotFoundException();\n }\n\n $file['model'] = $model;\n return $file;\n }", "label_name": "CWE-200", "label": 10}
{"code": " private function getProjectForUser($id)\n {\n $project = $this->project_manager->getProject($id);\n $user = $this->user_manager->getCurrentUser();\n\n ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());\n\n return $project;\n }", "label_name": "CWE-863", "label": 11}
{"code": " public function getDisplayName ($plural=true) {\n $moduleName = X2Model::getModuleName (get_class ($this));\n return Modules::displayName ($plural, $moduleName);\n }", "label_name": "CWE-20", "label": 0}
{"code": " public function approve() {\n expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for note to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n $simplenote = new expSimpleNote($this->params['id']);\n assign_to_template(array(\n 'simplenote'=>$simplenote,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'tab'=>$this->params['tab']\n ));\n }", "label_name": "CWE-74", "label": 1}
{"code": " function preview()\n {\n if ($this->params['id'] == 0) { // we want the default editor\n $demo = new stdClass();\n $demo->id = 0;\n $demo->name = \"Default\";\n if ($this->params['editor'] == 'ckeditor') {\n $demo->skin = 'kama';\n } elseif ($this->params['editor'] == 'tinymce') {\n $demo->skin = 'lightgray';\n }\n } else {\n $demo = self::getEditorSettings($this->params['id'], expString::escape($this->params['editor']));\n }\n assign_to_template(\n array(\n 'demo' => $demo,\n 'editor' => $this->params['editor']\n )\n );\n }", "label_name": "CWE-200", "label": 10}
{"code": "\tpublic static function dplNumParserFunction( &$parser, $text = '' ) {\n\t\t$parser->addTrackingCategory( 'dplnum-parserfunc-tracking-category' );\n\t\t$num = str_replace( ' ', ' ', $text );\n\t\t$num = str_replace( ' ', ' ', $text );\n\t\t$num = preg_replace( '/([0-9])([.])([0-9][0-9]?[^0-9,])/', '\\1,\\3', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\\s*Mrd/', '\\1\\2 000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9])\\s*Mrd/', '\\1\\2 0000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9])\\s*Mrd/', '\\1\\2 00000000 ', $num );\n\t\t$num = preg_replace( '/\\s*Mrd/', '000000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\\s*Mio/', '\\1\\2 000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9])\\s*Mio/', '\\1\\2 0000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9])\\s*Mio/', '\\1\\2 00000 ', $num );\n\t\t$num = preg_replace( '/\\s*Mio/', '000000 ', $num );\n\t\t$num = preg_replace( '/[. ]/', '', $num );\n\t\t$num = preg_replace( '/^[^0-9]+/', '', $num );\n\t\t$num = preg_replace( '/[^0-9].*/', '', $num );\n\t\treturn $num;\n\t}", "label_name": "CWE-400", "label": 2}
{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-74", "label": 1}
{"code": "function(){function N(){d(K,X,function(){k(X);K.editComment(K.content,function(){p(X)},function(Q){l(X);N();b.handleError(Q,null,null,null,mxUtils.htmlEntities(mxResources.get(\"objectNotFound\")))})})}N()},K.isResolved),M(mxResources.get(\"delete\"),function(){b.confirm(mxResources.get(\"areYouSure\"),function(){k(X);K.deleteComment(function(N){if(!0===N){N=X.querySelector(\".geCommentTxt\");N.innerHTML=\"\";mxUtils.write(N,mxResources.get(\"msgDeleted\"));var Q=X.querySelectorAll(\".geCommentAction\");for(N=", "label_name": "CWE-20", "label": 0}
{"code": "this.editor.graph.pageVisible;0==q&&(this.editor.graph.pageVisible=q);var X=this.createDownloadRequest(M,d,l,W,x,p,y,A,B,I,O,P,K);this.editor.graph.pageVisible=U;return X}catch(u){this.handleError(u)}}))}else{var F=null,H=mxUtils.bind(this,function(M){M.length<=MAX_REQUEST_SIZE?this.saveData(z,\"svg\",M,\"image/svg+xml\"):this.handleError({message:mxResources.get(\"drawingTooLarge\")},mxResources.get(\"error\"),mxUtils.bind(this,function(){mxUtils.popup(F)}))});if(\"svg\"==d){var S=this.editor.graph.background;", "label_name": "CWE-20", "label": 0}
{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0}
{"code": "function concat(array1, array2, index) {\n return array1.concat(slice.call(array2, index));\n}", "label_name": "CWE-74", "label": 1}
{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": 0}
{"code": "u[E]}catch(J){null!=window.console&&console.log(\"Error in vars URL parameter: \"+J)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var z=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(u){var E=z.apply(this,arguments);null==E&&null!=this.globalVars&&(E=this.globalVars[u]);return E};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var u=this.themes[\"default-style2\"];this.defaultStylesheet=\n(new mxCodec(u.ownerDocument)).decode(u)}return this.defaultStylesheet};Graph.prototype.isViewer=function(){return urlParams.viewer};var L=Graph.prototype.getSvg;Graph.prototype.getSvg=function(u,E,J,T,N,Q,R,Y,ba,ea,Z,fa,aa,va){var ja=null,Ba=null,Ha=null;fa||null==this.themes||\"darkTheme\"!=this.defaultThemeName||(ja=this.stylesheet,Ba=this.shapeForegroundColor,Ha=this.shapeBackgroundColor,this.shapeForegroundColor=\"darkTheme\"==this.defaultThemeName?\"#000000\":Editor.lightColor,this.shapeBackgroundColor=", "label_name": "CWE-20", "label": 0}
{"code": " launchExtension({ extensionId }) {\n checkAuthentication(this)\n const extension = Extensions.findOne({ _id: extensionId })\n if (extension) {\n eval(extension.server)\n return 'notifications.success'\n }\n return new Meteor.Error('Extension does not exist')\n },", "label_name": "CWE-285", "label": 23}
{"code": " generateFunction: function(name, params) {\n return 'function(' + params + '){' +\n this.varsPrefix(name) +\n this.body(name) +\n '};';\n },", "label_name": "CWE-74", "label": 1}
{"code": "d.style.width=\"300px\";d.style.display=\"inline-flex\";d.style.justifyContent=\"center\";d.style.alignItems=\"center\";d.style.position=\"absolute\";var g=document.createElement(\"img\");g.onload=function(){function C(){l.model.setStyle(x,y+m())}l=new Graph(k);l.autoExtend=!1;l.autoScroll=!1;l.setGridEnabled(!1);l.setEnabled(!0);l.setPanning(!1);l.setConnectable(!1);l.getRubberband().setEnabled(!1);l.graphHandler.allowLivePreview=!1;var D=l.createVertexHandler;l.createVertexHandler=function(){var J=D.apply(this,\narguments);J.livePreview=!1;return J};if(null!=f)try{if(\"inset\"==f.substring(0,5)){var G=x.geometry,P=g.width,K=g.height,F=(300-P)/2,H=(300-K)/2,S=f.match(/\\(([^)]+)\\)/)[1].split(/[ ,]+/),V=parseFloat(S[0]),M=parseFloat(S[1]),W=parseFloat(S[2]),U=parseFloat(S[3]);isFinite(V)&&isFinite(M)&&isFinite(W)&&isFinite(U)?(G.x=U/100*P+F,G.y=V/100*K+H,G.width=(100-M)/100*P+F-G.x,G.height=(100-W)/100*K+H-G.y,\"round\"==S[4]?\"50%\"==S[5]?I.setAttribute(\"checked\",\"checked\"):(q=parseInt(S[5]),t.value=q,B.setAttribute(\"checked\",\n\"checked\"),O.style.visibility=\"visible\"):A.setAttribute(\"checked\",\"checked\")):f=null}else f=null}catch(J){}x.style=y+(f?f:m());x.vertex=!0;l.addCell(x,null,null,null,null);l.selectAll();l.addListener(mxEvent.CELLS_MOVED,C);l.addListener(mxEvent.CELLS_RESIZED,C);var X=l.graphHandler.mouseUp,u=l.graphHandler.mouseDown;l.graphHandler.mouseUp=function(){X.apply(this,arguments);k.style.backgroundColor=\"#fff9\"};l.graphHandler.mouseDown=function(){u.apply(this,arguments);k.style.backgroundColor=\"\"};l.dblClick=\nfunction(){};var E=l.getSelectionModel().changeSelection;l.getSelectionModel().changeSelection=function(){E.call(this,[x],[x])}};g.onerror=function(){g.onload=null;g.src=Editor.errorImage};g.setAttribute(\"src\",e);g.style.maxWidth=\"300px\";g.style.maxHeight=\"300px\";d.appendChild(g);v.appendChild(d);var k=document.createElement(\"div\");k.style.width=\"300px\";k.style.height=\"300px\";k.style.overflow=\"hidden\";k.style.backgroundColor=\"#fff9\";v.appendChild(k);var l=null,p=new mxGeometry(100,100,100,100),q=", "label_name": "CWE-20", "label": 0}
{"code": "Editor.prototype.csvToArray=function(u){if(!/^\\s*(?:'[^'\\\\]*(?:\\\\[\\S\\s][^'\\\\]*)*'|\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\"|[^,'\"\\s\\\\]*(?:\\s+[^,'\"\\s\\\\]+)*)\\s*(?:,\\s*(?:'[^'\\\\]*(?:\\\\[\\S\\s][^'\\\\]*)*'|\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\"|[^,'\"\\s\\\\]*(?:\\s+[^,'\"\\s\\\\]+)*)\\s*)*$/.test(u))return null;var E=[];u.replace(/(?!\\s*$)\\s*(?:'([^'\\\\]*(?:\\\\[\\S\\s][^'\\\\]*)*)'|\"([^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*)\"|([^,'\"\\s\\\\]*(?:\\s+[^,'\"\\s\\\\]+)*))\\s*(?:,|$)/g,function(J,T,N,Q){void 0!==T?E.push(T.replace(/\\\\'/g,\"'\")):void 0!==N?E.push(N.replace(/\\\\\"/g,\n'\"')):void 0!==Q&&E.push(Q);return\"\"});/,\\s*$/.test(u)&&E.push(\"\");return E};Editor.prototype.isCorsEnabledForUrl=function(u){if(mxClient.IS_CHROMEAPP||EditorUi.isElectronApp||u.substring(0,window.location.origin.length)==window.location.origin)return!0;null!=urlParams.cors&&null==this.corsRegExp&&(this.corsRegExp=new RegExp(decodeURIComponent(urlParams.cors)));return null!=this.corsRegExp&&this.corsRegExp.test(u)||\"https://raw.githubusercontent.com/\"===u.substring(0,34)||\"https://fonts.googleapis.com/\"===", "label_name": "CWE-20", "label": 0}
{"code": "function serializeObject(obj) {\n var seen = [];\n\n return JSON.stringify(obj, function(key, val) {\n val = toJsonReplacer(key, val);\n if (isObject(val)) {\n\n if (seen.indexOf(val) >= 0) return '...';\n\n seen.push(val);\n }\n return val;\n });\n}", "label_name": "CWE-74", "label": 1}
{"code": "function(K){l=K};this.setAutoScroll=function(K){p=K};this.setOpenFill=function(K){q=K};this.setStopClickEnabled=function(K){A=K};this.setSelectInserted=function(K){B=K};this.setSmoothing=function(K){f=K};this.setPerfectFreehandMode=function(K){O=K};this.setBrushSize=function(K){I.size=K};this.getBrushSize=function(){return I.size};var t=function(K){y=K;b.getRubberband().setEnabled(!K);b.graphHandler.setSelectEnabled(!K);b.graphHandler.setMoveEnabled(!K);b.container.style.cursor=K?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": 0}
{"code": "var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};", "label_name": "CWE-74", "label": 1}
{"code": "\"startWidth\",this.defaultArrowWidth)};Ca.prototype.getEndArrowWidth=function(){return this.getEdgeWidth()+mxUtils.getNumber(this.style,\"endWidth\",this.defaultArrowWidth)};Ca.prototype.getEdgeWidth=function(){return mxUtils.getNumber(this.style,\"width\",this.defaultWidth)+Math.max(0,this.strokewidth-1)};mxCellRenderer.registerShape(\"flexArrow\",Ca);mxUtils.extend(Ra,mxActor);Ra.prototype.size=30;Ra.prototype.isRoundable=function(){return!0};Ra.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,parseFloat(mxUtils.getValue(this.style,", "label_name": "CWE-20", "label": 0}
{"code": "function(Ta){var za=Fa[Ta],wa=Ta<Fa.length-1?Fa[Ta+1]:null;wa=null!=wa?T.getCellGeometry(wa.cell):null;var Ea=null!=wa&&null!=wa.alternateBounds?wa.alternateBounds:wa;wa=null!=Qa[Ta]?new V(Qa[Ta],mxConstants.NONE,1):new mxLine(new mxRectangle,mxConstants.NONE,1,!1);wa.isDashed=pa.isDashed;wa.svgStrokeTolerance++;za=new mxHandle(za,\"row-resize\",null,wa);za.tableHandle=!0;var Da=0;za.shape.node.parentNode.insertBefore(za.shape.node,za.shape.node.parentNode.firstChild);za.redraw=function(){if(null!=\nthis.shape){this.shape.stroke=0==Da?mxConstants.NONE:pa.stroke;if(this.shape.constructor==V)this.shape.line=L(Qa[Ta],0,Da),this.shape.updateBoundsFromLine();else{var Ya=T.getActualStartSize(ma.cell,!0);this.shape.bounds.height=1;this.shape.bounds.y=this.state.y+this.state.height+Da*ia;this.shape.bounds.x=ma.x+(Ta==Fa.length-1?0:Ya.x*ia);this.shape.bounds.width=ma.width-(Ta==Fa.length-1?0:Ya.width+Ya.x+ia)}this.shape.redraw()}};var La=!1;za.setPosition=function(Ya,Ua,eb){Da=Math.max(Graph.minTableRowHeight-", "label_name": "CWE-20", "label": 0}
{"code": "return returnValue;}},uploadifyUpload:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').startFileUpload(ID,false);});},uploadifyCancel:function(ID){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').cancelFileUpload(ID,true,false);});},uploadifyClearQueue:function(){jQuery(this).each(function(){document.getElementById(jQuery(this).attr('id')+'Uploader').clearFileUploadQueue(false);});}})})(jQuery);", "label_name": "CWE-20", "label": 0}
{"code": "function(u,E,J){if(null!=E){var T=function(Q){if(null!=Q)if(J)for(var R=0;R<Q.length;R++)E[Q[R].name]=Q[R];else for(var Y in E){var ba=!1;for(R=0;R<Q.length;R++)if(Q[R].name==Y&&Q[R].type==E[Y].type){ba=!0;break}ba||delete E[Y]}},N=this.editorUi.editor.graph.view.getState(u);null!=N&&null!=N.shape&&(N.shape.commonCustomPropAdded||(N.shape.commonCustomPropAdded=!0,N.shape.customProperties=N.shape.customProperties||[],N.cell.vertex?Array.prototype.push.apply(N.shape.customProperties,Editor.commonVertexProperties):\nArray.prototype.push.apply(N.shape.customProperties,Editor.commonEdgeProperties)),T(N.shape.customProperties));u=u.getAttribute(\"customProperties\");if(null!=u)try{T(JSON.parse(u))}catch(Q){}}};var x=StyleFormatPanel.prototype.init;StyleFormatPanel.prototype.init=function(){var u=this.editorUi.getSelectionState();\"image\"!=u.style.shape&&!u.containsLabel&&0<u.cells.length&&this.container.appendChild(this.addStyles(this.createPanel()));x.apply(this,arguments);if(Editor.enableCustomProperties){for(var E=", "label_name": "CWE-20", "label": 0}
{"code": " function addInterceptor(parsedExpression, interceptorFn) {\n if (!interceptorFn) return parsedExpression;\n var watchDelegate = parsedExpression.$$watchDelegate;\n var useInputs = false;\n\n var regularWatch =\n watchDelegate !== oneTimeLiteralWatchDelegate &&\n watchDelegate !== oneTimeWatchDelegate;\n\n var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {\n var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);\n return interceptorFn(value, scope, locals);\n } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {\n var value = parsedExpression(scope, locals, assign, inputs);\n var result = interceptorFn(value, scope, locals);\n // we only return the interceptor's result if the\n // initial value is defined (for bind-once)\n return isDefined(value) ? result : value;\n };\n\n // Propagate $$watchDelegates other then inputsWatchDelegate\n useInputs = !parsedExpression.inputs;\n if (parsedExpression.$$watchDelegate &&\n parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n fn.inputs = parsedExpression.inputs;\n } else if (!interceptorFn.$stateful) {\n // If there is an interceptor, but no watchDelegate then treat the interceptor like\n // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n fn.$$watchDelegate = inputsWatchDelegate;\n fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];\n }\n\n return fn;\n }", "label_name": "CWE-74", "label": 1}
{"code": "E=J}return E};Graph.prototype.getCellsById=function(u){var E=[];if(null!=u)for(var J=0;J<u.length;J++)if(\"*\"==u[J]){var T=this.model.getRoot();E=E.concat(this.model.filterDescendants(function(Q){return Q!=T},T))}else{var N=this.model.getCell(u[J]);null!=N&&E.push(N)}return E};var S=Graph.prototype.isCellVisible;Graph.prototype.isCellVisible=function(u){return S.apply(this,arguments)&&!this.isAllTagsHidden(this.getTagsForCell(u))};Graph.prototype.isAllTagsHidden=function(u){if(null==u||0==u.length||\n0==this.hiddenTags.length)return!1;u=u.split(\" \");if(u.length>this.hiddenTags.length)return!1;for(var E=0;E<u.length;E++)if(0>mxUtils.indexOf(this.hiddenTags,u[E]))return!1;return!0};Graph.prototype.getCellsForTags=function(u,E,J,T){var N=[];if(null!=u){E=null!=E?E:this.model.getDescendants(this.model.getRoot());for(var Q=0,R={},Y=0;Y<u.length;Y++)0<u[Y].length&&(R[u[Y]]=!0,Q++);for(Y=0;Y<E.length;Y++)if(J&&this.model.getParent(E[Y])==this.model.root||this.model.isVertex(E[Y])||this.model.isEdge(E[Y])){var ba=", "label_name": "CWE-20", "label": 0}
{"code": "!1;null!=H&&(S=\"1\"==x.getCurrentCellStyle(H).treeMoving);return S}function t(H){var S=!1;null!=H&&(H=A.getParent(H),S=x.view.getState(H),S=\"tree\"==(null!=S?S.style:x.getCellStyle(H)).containerType);return S}function D(H){var S=!1;null!=H&&(H=A.getParent(H),S=x.view.getState(H),x.view.getState(H),S=null!=(null!=S?S.style:x.getCellStyle(H)).childLayout);return S}function c(H){H=x.view.getState(H);if(null!=H){var S=x.getIncomingTreeEdges(H.cell);if(0<S.length&&(S=x.view.getState(S[0]),null!=S&&(S=S.absolutePoints,", "label_name": "CWE-20", "label": 0}
{"code": "'\" y=\"'+p.y.toFixed(2)+'\"/>'):V+('<line x=\"'+p.x.toFixed(2)+'\" y=\"'+p.y.toFixed(2)+'\"/>')}V+=\"</foreground></shape>\";if(b.isEnabled()&&!b.isCellLocked(b.getDefaultParent())){E=this.createStyle(\"stencil(\"+Graph.compress(V)+\")\");V=b.view.scale;X=b.view.translate;E=new mxCell(\"\",new mxGeometry(H/V-X.x,U/V-X.y,J/V,S/V),E);E.vertex=1;b.model.beginUpdate();try{E=b.addCell(E),b.fireEvent(new mxEventObject(\"cellsInserted\",\"cells\",[E])),b.fireEvent(new mxEventObject(\"freehandInserted\",\"cell\",E))}finally{b.model.endUpdate()}z&&\nb.setSelectionCells([E])}}for(E=0;E<u.length;E++)u[E].parentNode.removeChild(u[E]);d=null;u=[];D=[]}n(!1)};b.addListener(mxEvent.FIRE_MOUSE_EVENT,mxUtils.bind(this,function(J,E){J=E.getProperty(\"eventName\");E=E.getProperty(\"event\");J==mxEvent.MOUSE_MOVE&&x&&(null!=E.sourceState&&E.sourceState.setCursor(\"crosshair\"),E.consume())}));b.addMouseListener({mouseDown:mxUtils.bind(this,function(J,E){if(b.isEnabled()&&!b.isCellLocked(b.getDefaultParent())&&(J=E.getEvent(),x&&!mxEvent.isPopupTrigger(J)&&!mxEvent.isMultiTouchEvent(J))){var H=", "label_name": "CWE-20", "label": 0}
{"code": "var O=mxText.prototype.redraw;mxText.prototype.redraw=function(){O.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(u,E,J){function T(){for(var ja=R.getSelectionCells(),Ba=[],Ha=0;Ha<ja.length;Ha++)R.isCellVisible(ja[Ha])&&Ba.push(ja[Ha]);R.setSelectionCells(Ba)}function N(ja){R.hiddenTags=ja?[]:Y.slice();T();R.refresh()}function Q(ja,Ba){ea.innerHTML=\"\";if(0<ja.length){var Ha=document.createElement(\"table\");", "label_name": "CWE-20", "label": 0}
{"code": "n.toDataURL();if(y.length<e.length){var K=document.createElement(\"canvas\");K.width=L;K.height=M;var B=K.toDataURL();y!==B&&(e=y,x=L,A=M)}}}catch(F){}g(e,x,A)};EditorUi.prototype.extractGraphModelFromPng=function(c){return Editor.extractGraphModelFromPng(c)};EditorUi.prototype.loadImage=function(c,e,g){try{var k=new Image;k.onload=function(){k.width=0<k.width?k.width:120;k.height=0<k.height?k.height:120;e(k)};null!=g&&(k.onerror=g);k.src=c}catch(m){if(null!=g)g(m);else throw m;}};EditorUi.prototype.getDefaultSketchMode=", "label_name": "CWE-20", "label": 0}
{"code": "function isStateless($filter, filterName) {\n var fn = $filter(filterName);\n return !fn.$stateful;\n}", "label_name": "CWE-74", "label": 1}
{"code": " generateWebProxyAccessToken () {\n return this._transport\n .execute('signer_generateWebProxyAccessToken');\n }", "label_name": "CWE-346", "label": 16}
{"code": "\"startWidth\",this.defaultArrowWidth)};Ca.prototype.getEndArrowWidth=function(){return this.getEdgeWidth()+mxUtils.getNumber(this.style,\"endWidth\",this.defaultArrowWidth)};Ca.prototype.getEdgeWidth=function(){return mxUtils.getNumber(this.style,\"width\",this.defaultWidth)+Math.max(0,this.strokewidth-1)};mxCellRenderer.registerShape(\"flexArrow\",Ca);mxUtils.extend(Ra,mxActor);Ra.prototype.size=30;Ra.prototype.isRoundable=function(){return!0};Ra.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,parseFloat(mxUtils.getValue(this.style,", "label_name": "CWE-20", "label": 0}
{"code": "1E3<=F&&null!=this.sidebarWindow&&\"1\"!=urlParams.sketch&&this.sidebarWindow.window.setVisible(!0);null!=this.formatWindow&&(1E3<=F||\"1\"==urlParams.sketch)&&this.formatWindow.window.setVisible(!0)}else null!=this.sidebarWindow&&this.sidebarWindow.window.setVisible(!1),null!=this.formatWindow&&this.formatWindow.window.setVisible(!1)};EditorUi.prototype.chromelessWindowResize=function(){};var M=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(B){B=M.apply(this,arguments);\nvar F=this.editorUi,G=F.editor.graph;if(G.isEnabled()&&\"1\"==urlParams.sketch){var N=this.createOption(mxResources.get(\"sketch\"),function(){return Editor.sketchMode},function(J,E){F.setSketchMode(!Editor.sketchMode);null!=E&&mxEvent.isShiftDown(E)||G.updateCellStyles({sketch:J?\"1\":null},G.getVerticesAndEdges())},{install:function(J){this.listener=function(){J(Editor.sketchMode)};F.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){F.removeListener(this.listener)}});B.appendChild(N)}return B};", "label_name": "CWE-20", "label": 0}
{"code": "if(jQuery)(function(jQuery){jQuery.extend(jQuery.fn,{uploadify:function(options){jQuery(this).each(function(){settings=jQuery.extend({id:jQuery(this).attr('id'),uploader:'uploadify.swf',script:'uploadify.php',expressInstall:null,folder:'',height:30,width:110,cancelImg:'cancel.png',wmode:'opaque',scriptAccess:'sameDomain',fileDataName:'Filedata',method:'POST',queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:'percentage',onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},options);var pagePath=location.pathname;pagePath=pagePath.split('/');pagePath.pop();pagePath=pagePath.join('/')+'/';var data={};data.uploadifyID=settings.id;data.pagepath=pagePath;if(settings.buttonImg)data.buttonImg=escape(settings.buttonImg);if(settings.buttonText)data.buttonText=escape(settings.buttonText);if(settings.rollover)data.rollover=true;data.script=settings.script;data.folder=escape(settings.folder);if(settings.scriptData){var scriptDataString='';for(var name in settings.scriptData){scriptDataString+='&'+name+'='+settings.scriptData[name];}", "label_name": "CWE-20", "label": 0}
{"code": "function compile(src) {\n var cached;\n\n if (typeof src !== \"string\") {\n throw new TypeError(\"src must be a string, instead saw '\" + typeof src + \"'\");\n }\n\n if (!compile.cache) {\n return parser.parse(src);\n }\n\n cached = compile.cache[src];\n if (!cached) {\n cached = compile.cache[src] = parser.parse(src);\n }\n\n return cached;\n}", "label_name": "CWE-74", "label": 1}
{"code": "4)&&!!(a%100)||!(a%400)};d.isSameDay=function(a,c){return a.toDateString()===c.toDateString()};d.locale=function(a,c){c?u(a,{res:v,formatter:w,parser:x},c):\"function\"===typeof a?m=a(d):a&&(q&&!q.date&&console.warn(\"This method of changing the locale is deprecated. See documentation for details.\"),m=a);return m};d.extend=function(a){var c=a.extender||{},b;for(b in c)d[b]||(d[b]=c[b]);(a.formatter||a.parser||a.res)&&u(m,t[m],a)};d.plugin=function(a,c){\"function\"===typeof a?d.extend(r[a(d)]):(r[a]=r[a]||", "label_name": "CWE-400", "label": 2}
{"code": "function(y){this.spinner.stop();this.handleError(y)})})))}}),mxUtils.bind(this,function(){this.hideDialog()}),mxResources.get(\"saveAs\"),mxResources.get(\"download\"),!1,!1,v,null,1<x,A,k,q,m);x=this.isServices(x)?4<x?390:280:160;this.showDialog(c.container,420,x,!0,!0);c.init()};EditorUi.prototype.isServices=function(c){return 1!=c};EditorUi.prototype.getEditBlankXml=function(){return this.getFileData(!0)};EditorUi.prototype.exportFile=function(c,e,g,k,m,q){};EditorUi.prototype.pickFolder=function(c,", "label_name": "CWE-20", "label": 0}
{"code": "H&&!V)if(\"sharepoint\"==S)z(\"site\",null,H.id,H.displayName);else if(\"site\"==S)z(\"subsite\",null,H.id,H.name);else{var N=H.folder;H=H.remoteItem?H.remoteItem:H;var Q=(H.parentReference?H.parentReference.driveId:null)||S,R=H.id;N?z(Q,R,null,H.name):B()}}function z(N,Q,R,Y,ba){function ea(ra){P.stop();var Ca=document.createElement(\"table\");Ca.className=\"odFileListGrid\";for(var za=null,Ga=0,Na=0;null!=ra&&Na<ra.length;Na++){var Fa=ra[Na];if(1!=fa||!Fa.webUrl||0<Fa.webUrl.indexOf(\"sharepoint.com/sites/\")||\n0>Fa.webUrl.indexOf(\"sharepoint.com/\")){var Ea=Fa.displayName||Fa.name,Da=mxUtils.htmlEntities(Fa.description||Ea);fa&&(Fa.folder=2==fa?{isRoot:!0}:!0);var La=null!=Fa.folder;if(!g||La){var Aa=document.createElement(\"tr\");Aa.className=Ga++%2?\"odOddRow\":\"odEvenRow\";var ta=document.createElement(\"td\");ta.style.width=\"36px\";var ka=document.createElement(\"img\");ka.src=\"/images/\"+(La?\"folder.png\":\"file.png\");ka.className=\"odFileImg\";ta.appendChild(ka);Aa.appendChild(ta);ta=document.createElement(\"td\");\nLa=document.createElement(\"div\");La.className=\"odFileTitle\";La.innerHTML=mxUtils.htmlEntities(Ea);La.setAttribute(\"title\",Da);ta.appendChild(La);Aa.appendChild(ta);Ca.appendChild(Aa);null==za&&(za=Aa,za.className+=\" odRowSelected\",H=Fa,S=N,x||e(H));(function(oa,sa){Aa.addEventListener(\"dblclick\",t);Aa.addEventListener(\"click\",function(){za!=sa&&(za.className=za.className.replace(\"odRowSelected\",\"\"),za=sa,za.className+=\" odRowSelected\",H=oa,S=N,x||e(H))})})(Fa,Aa)}}}0==Ga?(ra=document.createElement(\"div\"),\nra.className=\"odEmptyFolder\",ra.innerHTML=mxUtils.htmlEntities(mxResources.get(\"folderEmpty\",null,\"Folder is empty!\")),va.appendChild(ra)):va.appendChild(Ca);O();V=!1}if(!V){y(\".odCatsList\").style.display=\"block\";y(\".odFilesSec\").style.display=\"block\";null!=E&&(E.innerHTML=\"\",E.style.top=\"50%\");var Z=V=!0,fa=0;W=arguments;var aa=setTimeout(function(){V=Z=!1;P.stop();d(mxResources.get(\"timeout\"))},2E4),va=y(\".odFilesList\");va.innerHTML=\"\";P.spin(va);switch(N){case \"recent\":M=[{name:mxResources.get(\"recent\",", "label_name": "CWE-20", "label": 0}
{"code": "App.prototype.fileCreated=function(b,f,l,d,u){var t=window.location.pathname;null!=f&&0<f.length&&(t+=\"?libs=\"+f);null!=u&&0<u.length&&(t+=\"?clibs=\"+u);t=this.getUrl(t);b.getMode()!=App.MODE_DEVICE&&(t+=\"#\"+b.getHash());if(this.spinner.spin(document.body,mxResources.get(\"inserting\"))){var D=b.getData();D=0<D.length?this.editor.extractGraphModel(mxUtils.parseXml(D).documentElement,!0):null;var c=window.location.protocol+\"//\"+window.location.hostname+t,e=D,g=null;null!=D&&/\\.svg$/i.test(b.getTitle())&&\n(g=this.createTemporaryGraph(this.editor.graph.getStylesheet()),document.body.appendChild(g.container),e=this.decodeNodeIntoGraph(e,g));b.setData(this.createFileData(D,g,b,c));null!=g&&g.container.parentNode.removeChild(g.container);var k=mxUtils.bind(this,function(){this.spinner.stop()}),m=mxUtils.bind(this,function(){k();var q=this.getCurrentFile();null==l&&null!=q&&(l=!q.isModified()&&null==q.getMode());var v=mxUtils.bind(this,function(){window.openFile=null;this.fileLoaded(b);l&&b.addAllSavedStatus();\nnull!=f&&this.sidebar.showEntries(f);if(null!=u){for(var A=[],z=u.split(\";\"),L=0;L<z.length;L++)A.push(decodeURIComponent(z[L]));this.loadLibraries(A)}}),x=mxUtils.bind(this,function(){l||null==q||!q.isModified()?v():this.confirm(mxResources.get(\"allChangesLost\"),null,v,mxResources.get(\"cancel\"),mxResources.get(\"discardChanges\"))});null!=d&&d();null==l||l?x():(b.constructor==LocalFile&&(window.openFile=new OpenFile(function(){window.openFile=null}),window.openFile.setData(b.getData(),b.getTitle(),\nnull==b.getMode())),null!=d&&d(),window.openWindow(t,null,x))});b.constructor==LocalFile?m():b.saveFile(b.getTitle(),!1,mxUtils.bind(this,function(){m()}),mxUtils.bind(this,function(q){k();null!=q&&\"AbortError\"==q.name||this.handleError(q)}))}};", "label_name": "CWE-20", "label": 0}
{"code": "\"/images/\"+ma+\".svg\";return!0}function M(fa,ca,ba,ja){function ia(na,Ja){null==qa?(na=/^https?:\\/\\//.test(na)&&!b.editor.isCorsEnabledForUrl(na)?PROXY_URL+\"?url=\"+encodeURIComponent(na):TEMPLATE_PATH+\"/\"+na,mxUtils.get(na,mxUtils.bind(this,function(Ga){200<=Ga.getStatus()&&299>=Ga.getStatus()&&(qa=Ga.getText());Ja(qa)}))):Ja(qa)}function ma(na,Ja,Ga){if(null!=na&&mxUtils.isAncestorNode(document.body,ca)&&(na=mxUtils.parseXml(na),na=Editor.extractGraphModel(na.documentElement,!0),null!=na)){\"mxfile\"==\nna.nodeName&&(na=Editor.parseDiagramNode(na.getElementsByTagName(\"diagram\")[0]));var Ra=new mxCodec(na.ownerDocument),Sa=new mxGraphModel;Ra.decode(na,Sa);na=Sa.root.getChildAt(0).children||[];b.sidebar.createTooltip(ca,na,Math.min((window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)-80,1E3),Math.min((window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-80,800),null!=fa.title?mxResources.get(fa.title,null,fa.title):null,!0,new mxPoint(Ja,\nGa),!0,null,!0);var Ha=document.createElement(\"div\");Ha.className=\"geTempDlgDialogMask\";Q.appendChild(Ha);var Na=b.sidebar.hideTooltip;b.sidebar.hideTooltip=function(){Ha&&(Q.removeChild(Ha),Ha=null,Na.apply(this,arguments),b.sidebar.hideTooltip=Na)};mxEvent.addListener(Ha,\"click\",function(){b.sidebar.hideTooltip()})}}var qa=null;if(Ca||b.sidebar.currentElt==ca)b.sidebar.hideTooltip();else{var oa=function(na){Ca&&b.sidebar.currentElt==ca&&ma(na,mxEvent.getClientX(ja),mxEvent.getClientY(ja));Ca=!1;\nba.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=ca;Ca=!0;ba.src=\"/images/aui-wait.gif\";fa.isExt?e(fa,oa,function(){A(mxResources.get(\"cantLoadPrev\"));Ca=!1;ba.src=\"/images/icon-search.svg\"}):ia(fa.url,oa)}}function n(fa,ca,ba){if(null!=C){for(var ja=C.className.split(\" \"),ia=0;ia<ja.length;ia++)if(-1<ja[ia].indexOf(\"Active\")){ja.splice(ia,1);break}C.className=ja.join(\" \")}null!=fa?(C=fa,C.className+=\" \"+ca,I=ba,Ba.className=\"geTempDlgCreateBtn\"):(I=C=null,Ba.className=", "label_name": "CWE-20", "label": 0}
{"code": " codePointAt: function(ch) {\n if (ch.length === 1) return ch.charCodeAt(0);\n // eslint-disable-next-line no-bitwise\n return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;\n },", "label_name": "CWE-74", "label": 1}
{"code": "c.setStrokeColor(this.stroke)}};mxCellRenderer.registerShape(\"partialRectangle\",Oa);mxUtils.extend(Qa,mxEllipse);Qa.prototype.paintVertexShape=function(c,l,x,p,v){mxEllipse.prototype.paintVertexShape.apply(this,arguments);c.setShadow(!1);c.begin();\"vertical\"==mxUtils.getValue(this.style,\"line\")?(c.moveTo(l+p/2,x),c.lineTo(l+p/2,x+v)):(c.moveTo(l,x+v/2),c.lineTo(l+p,x+v/2));c.end();c.stroke()};mxCellRenderer.registerShape(\"lineEllipse\",Qa);mxUtils.extend(Ta,mxActor);Ta.prototype.redrawPath=function(c,\nl,x,p,v){l=Math.min(p,v/2);c.moveTo(0,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(0,v);c.close();c.end()};mxCellRenderer.registerShape(\"delay\",Ta);mxUtils.extend(za,mxActor);za.prototype.size=.2;za.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,p);var A=Math.max(0,Math.min(l,l*parseFloat(mxUtils.getValue(this.style,\"size\",this.size))));l=(v-A)/2;x=l+A;var B=(p-A)/2;A=B+A;c.moveTo(0,l);c.lineTo(B,l);c.lineTo(B,0);c.lineTo(A,0);c.lineTo(A,l);c.lineTo(p,l);c.lineTo(p,x);", "label_name": "CWE-20", "label": 0}
{"code": " link: function(scope, element, attrs) {\n\n var width = 120;\n var height = 39;\n\n var div = $('<div class=\"terminal\">A</div>').css({\n position: 'absolute',\n left: -1000,\n top: -1000,\n display: 'block',\n padding: 0,\n margin: 0,\n 'font-family': 'monospace'\n }).appendTo($('body'));\n\n var charWidth = div.width();\n var charHeight = div.height();\n\n div.remove();\n\n // compensate for internal horizontal padding\n var cssWidth = width * charWidth + 20;\n // Add an extra line for the status bar and divider\n var cssHeight = (height * charHeight) + charHeight + 2;\n\n log.debug(\"desired console size in characters, width: \", width, \" height: \", height);\n log.debug(\"console size in pixels, width: \", cssWidth, \" height: \", cssHeight);\n log.debug(\"character size in pixels, width: \", charWidth, \" height: \", charHeight);\n\n element.css({\n width: cssWidth,\n height: cssHeight,\n 'min-width': cssWidth,\n 'min-height': cssHeight\n });\n\n gogo.Terminal(element.get(0), width, height);\n\n scope.$on(\"$destroy\", function(e) {\n document.onkeypress = null;\n document.onkeydown = null;\n });\n\n }", "label_name": "CWE-287", "label": 4}
{"code": "(ma=ka[la],null==ma&&(ma={},ka[la]=ma),la=ma[ca],null==la&&(la=[],ma[ca]=la),la.push(ia))}ha=ha.nextSibling}G(ta,oa,wa)}})}function K(ha){v&&(Ba.scrollTop=0,aa.innerHTML=\"\",Ea.spin(aa),U=!1,W=!0,va.innerHTML=mxUtils.htmlEntities(mxResources.get(\"recentDiag\")),ba=null,v(ua,function(){A(mxResources.get(\"cannotLoad\"));ua([])},ha?null:n))}function F(ha){if(\"\"==ha)null!=u&&(u.click(),u=null);else{if(null==TemplatesDialog.tagsList[c]){var da={};for(Ka in ta)for(var ca=ta[Ka],la=0;la<ca.length;la++){var ia=", "label_name": "CWE-20", "label": 0}
{"code": " object: function() {\n var properties = [], property;\n if (this.peekToken().text !== '}') {\n do {\n if (this.peek('}')) {\n // Support trailing commas per ES5.1.\n break;\n }\n property = {type: AST.Property, kind: 'init'};\n if (this.peek().constant) {\n property.key = this.constant();\n property.computed = false;\n this.consume(':');\n property.value = this.expression();\n } else if (this.peek().identifier) {\n property.key = this.identifier();\n property.computed = false;\n if (this.peek(':')) {\n this.consume(':');\n property.value = this.expression();\n } else {\n property.value = property.key;\n }\n } else if (this.peek('[')) {\n this.consume('[');\n property.key = this.expression();\n this.consume(']');\n property.computed = true;\n this.consume(':');\n property.value = this.expression();\n } else {\n this.throwError('invalid key', this.peek());\n }\n properties.push(property);\n } while (this.expect(','));\n }\n this.consume('}');\n\n return {type: AST.ObjectExpression, properties: properties };\n },", "label_name": "CWE-74", "label": 1}
{"code": "ka.size,ra,sa)):\"readOnly\"==va?(sa=document.createElement(\"input\"),sa.setAttribute(\"readonly\",\"\"),sa.value=ta,sa.style.width=\"96px\",sa.style.borderWidth=\"0px\",wa.appendChild(sa)):(wa.innerHTML=mxUtils.htmlEntities(decodeURIComponent(ta)),mxEvent.addListener(wa,\"click\",mxUtils.bind(Z,function(){function ca(){var ja=ba.value;ja=0==ja.length&&\"string\"!=va?0:ja;ka.allowAuto&&(null!=ja.trim&&\"auto\"==ja.trim().toLowerCase()?(ja=\"auto\",va=\"string\"):(ja=parseFloat(ja),ja=isNaN(ja)?0:ja));null!=ka.min&&ja<\nka.min?ja=ka.min:null!=ka.max&&ja>ka.max&&(ja=ka.max);ja=encodeURIComponent((\"int\"==va?parseInt(ja):ja)+\"\");T(za,ja,ka)}var ba=document.createElement(\"input\");P(wa,ba,!0);ba.value=decodeURIComponent(ta);ba.className=\"gePropEditor\";\"int\"!=va&&\"float\"!=va||ka.allowAuto||(ba.type=\"number\",ba.step=\"int\"==va?\"1\":\"any\",null!=ka.min&&(ba.min=parseFloat(ka.min)),null!=ka.max&&(ba.max=parseFloat(ka.max)));p.appendChild(ba);mxEvent.addListener(ba,\"keypress\",function(ja){13==ja.keyCode&&ca()});ba.focus();mxEvent.addListener(ba,", "label_name": "CWE-20", "label": 0}
{"code": " function onLoad() {\n return new Promise(function(resolve) {\n window.addEventListener('load', resolve, true);\n }).then(iframeLoaded);\n }", "label_name": "CWE-200", "label": 10}
{"code": "Na+=\"@import url(\"+La+\");\\n\":Fa+='@font-face {\\nfont-family: \"'+Da+'\";\\nsrc: url(\"'+La+'\");\\n}\\n'}Ga.appendChild(za.createTextNode(Na+Fa));ra.getElementsByTagName(\"defs\")[0].appendChild(Ga)}null!=ja&&(this.shapeBackgroundColor=Ha,this.shapeForegroundColor=Ba,this.stylesheet=ja,this.refresh());return ra};var C=Graph.prototype.createSvgImageExport;Graph.prototype.createSvgImageExport=function(){var u=C.apply(this,arguments);if(this.mathEnabled){var E=u.drawText;u.drawText=function(J,T){if(null!=J.text&&\nnull!=J.text.value&&J.text.checkBounds()&&(mxUtils.isNode(J.text.value)||J.text.dialect==mxConstants.DIALECT_STRICTHTML)){var N=J.text.getContentNode();if(null!=N){N=N.cloneNode(!0);if(N.getElementsByTagNameNS)for(var Q=N.getElementsByTagNameNS(\"http://www.w3.org/1998/Math/MathML\",\"math\");0<Q.length;)Q[0].parentNode.removeChild(Q[0]);null!=N.innerHTML&&(Q=J.text.value,J.text.value=N.innerHTML,E.apply(this,arguments),J.text.value=Q)}}else E.apply(this,arguments)}}return u};var D=mxCellRenderer.prototype.destroy;", "label_name": "CWE-20", "label": 0}
{"code": " peek: function(i) {\n var num = i || 1;\n return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n },", "label_name": "CWE-74", "label": 1}
{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(c,e,g,k){function m(x,A,z){c1=x>>2;c2=(x&3)<<4|A>>4;c3=(A&15)<<2|z>>6;c4=z&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(x){if(10>x)return String.fromCharCode(48+x);x-=10;if(26>x)return String.fromCharCode(65+x);x-=26;if(26>x)return String.fromCharCode(97+x);x-=26;return 0==x?\"-\":1==x?\"_\":\"?\"}var v=new XMLHttpRequest;v.open(\"GET\",(\"txt\"==e?PLANT_URL+\"/txt/\":\"png\"==e?PLANT_URL+\"/png/\":", "label_name": "CWE-20", "label": 0}
{"code": " throwError: function(msg, token) {\n throw $parseMinErr('syntax',\n 'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n },", "label_name": "CWE-74", "label": 1}
{"code": "mxEvent.getSource(D);null!=G;){if(G==x||G==y){D.stopPropagation();D.preventDefault();break}G=G.parentNode}});var L=function(D){return function(G,P,K,F,H,S,V,M,W){null!=W&&(/(\\.v(dx|sdx?))($|\\?)/i.test(W.name)||/(\\.vs(x|sx?))($|\\?)/i.test(W.name))?b.importVisio(W,mxUtils.bind(this,function(U){d(U,P,K,F,H,S,V,\"fixed\",mxEvent.isAltDown(D)?null:V.substring(0,V.lastIndexOf(\".\")).replace(/_/g,\" \"))})):null!=W&&(new XMLHttpRequest).upload&&b.isRemoteFileFormat(G,W.name)?b.isExternalDataComms()?b.parseFile(W,\nmxUtils.bind(this,function(U){4==U.readyState&&(b.spinner.stop(),200<=U.status&&299>=U.status&&(d(U.responseText,P,K,F,H,S,V,\"fixed\",mxEvent.isAltDown(D)?null:V.substring(0,V.lastIndexOf(\".\")).replace(/_/g,\" \")),x.scrollTop=x.scrollHeight))})):(b.spinner.stop(),b.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):(d(G,P,K,F,H,S,V,\"fixed\",mxEvent.isAltDown(D)?null:V.substring(0,V.lastIndexOf(\".\")).replace(/_/g,\" \")),x.scrollTop=x.scrollHeight)}};mxEvent.addListener(x,\"dragover\",g);", "label_name": "CWE-20", "label": 0}
{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function y(fa,ca){if(null!=I){var ba=function(oa){qa.isExternal?e(qa,function(na){ja(na,oa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?ja(na.getText(),oa):ia()})):ja(b.emptyDiagramXml,oa)},ja=function(oa,na){x||b.hideDialog(!0);f(oa,na,qa,ca)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){I=qa;Ba.className=\"geTempDlgCreateBtn\";ca&&(Ka.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": 0}
{"code": "function(la,ra){\"1\"==urlParams.sketch?(O.insertTemplateEnabled&&!O.isOffline()&&O.menus.addMenuItems(la,[\"insertTemplate\"],ra),O.menus.addMenuItems(la,[\"insertImage\",\"insertLink\",\"-\"],ra),O.menus.addSubmenu(\"insertLayout\",la,ra,mxResources.get(\"layout\")),O.menus.addSubmenu(\"insertAdvanced\",la,ra,mxResources.get(\"advanced\"))):(fa.apply(this,arguments),O.menus.addSubmenu(\"table\",la,ra))}})();var V=\"horizontalFlow verticalFlow - horizontalTree verticalTree radialTree - organic circle\".split(\" \"),Q=function(R,", "label_name": "CWE-20", "label": 0}
{"code": "[c,l,x])))};mxCellRenderer.registerShape(\"filledEdge\",Da);\"undefined\"!==typeof StyleFormatPanel&&function(){var c=StyleFormatPanel.prototype.getCustomColors;StyleFormatPanel.prototype.getCustomColors=function(){var l=this.editorUi.getSelectionState(),x=c.apply(this,arguments);\"umlFrame\"==l.style.shape&&x.push({title:mxResources.get(\"laneColor\"),key:\"swimlaneFillColor\",defaultValue:\"default\"});return x}}();mxMarker.addMarker(\"dash\",function(c,l,x,p,v,A,B,ha,K,xa){var na=v*(B+K+1),$a=A*(B+K+1);return function(){c.begin();", "label_name": "CWE-20", "label": 0}
{"code": "n)for(v=0;v<n.length;v++)n[v].node.style.visibility=c?\"visible\":\"hidden\"};var f=mxGuide.prototype.destroy;mxGuide.prototype.destroy=function(){f.call(this);var c=this.guidesArrVer,m=this.guidesArrHor;if(null!=c){for(var n=0;n<c.length;n++)c[n].destroy();this.guidesArrVer=null}if(null!=m){for(n=0;n<m.length;n++)m[n].destroy();this.guidesArrHor=null}}})();function mxRuler(b,e,f,c){function m(){var t=b.diagramContainer;p.style.top=t.offsetTop-g+\"px\";p.style.left=t.offsetLeft-g+\"px\";p.style.width=(f?0:t.offsetWidth)+g+\"px\";p.style.height=(f?t.offsetHeight:0)+g+\"px\"}function n(t,z,L){if(null!=v)return t;var C;return function(){var D=this,G=arguments,P=L&&!C;clearTimeout(C);C=setTimeout(function(){C=null;L||t.apply(D,G)},z);P&&t.apply(D,G)}}var v=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,", "label_name": "CWE-20", "label": 0}
{"code": " peekMultichar: function() {\n var ch = this.text.charAt(this.index);\n var peek = this.peek();\n if (!peek) {\n return ch;\n }\n var cp1 = ch.charCodeAt(0);\n var cp2 = peek.charCodeAt(0);\n if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {\n return ch + peek;\n }\n return ch;\n },", "label_name": "CWE-74", "label": 1}
{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0}
{"code": "m=P.name;v=\"\";O(null,!0)})));k.appendChild(F)})(D[G],G)}100==D.length&&(k.appendChild(A),B=function(){k.scrollTop>=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label_name": "CWE-20", "label": 0}
{"code": " URI.parseUserinfo = function(string, parts) {\n // extract username:password\n var firstBackSlash = string.indexOf('\\\\');\n var firstSlash = string.indexOf('/');\n var slash = firstBackSlash === -1 ? firstSlash : (firstSlash !== -1 ? Math.min(firstBackSlash, firstSlash): firstSlash)\n var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);\n var t;\n\n // authority@ must come before /path or \\path\n if (pos > -1 && (slash === -1 || pos < slash)) {\n t = string.substring(0, pos).split(':');\n parts.username = t[0] ? URI.decode(t[0]) : null;\n t.shift();\n parts.password = t[0] ? URI.decode(t.join(':')) : null;\n string = string.substring(pos + 1);\n } else {\n parts.username = null;\n parts.password = null;\n }\n\n return string;\n };", "label_name": "CWE-20", "label": 0}
{"code": "DrawioFileSync.prototype.merge=function(b,f,l,d,u,t){try{this.file.stats.merged++;this.lastModified=new Date;var D=this.file.getDescriptorRevisionId(l);if(!this.file.ignorePatches(b)){this.sendLocalChanges();var c=this.file.getShadowPages();this.file.backupPatch=this.file.isModified()&&!this.file.isRealtime()?this.ui.diffPages(c,this.ui.pages):null;var e=this.file.isRealtime()?this.ui.diffPages(c,this.file.ownPages):null;c=this.ui.applyPatches(c,b);var g=null==f?null:this.ui.getHashValueForPages(c);\nthis.file.setShadowPages(c);EditorUi.debug(\"DrawioFileSync.merge\",[this],\"patches\",b,\"backup\",this.file.backupPatch,\"pending\",e,\"checksum\",f,\"current\",g,\"valid\",f==g,\"attempt\",this.catchupRetryCount,\"of\",this.maxCatchupRetries,\"from\",this.file.getCurrentRevisionId(),\"to\",D,\"etag\",this.file.getDescriptorEtag(l));if(null!=f&&f!=g){var k=this.ui.hashValue(D),m=this.ui.hashValue(this.file.getCurrentRevisionId());this.file.checksumError(u,b,\"From: \"+m+\"\\nTo: \"+k+\"\\nChecksum: \"+f+\"\\nCurrent: \"+g,D,\"merge\");\n\"1\"==urlParams.test&&EditorUi.debug(\"DrawioFileSync.merge.checksumError\",[this],\"data\",[this.file.data,this.file.createData(),this.ui.getXmlForPages(c)]);return}null==this.patchRealtime(b,null,e)&&this.file.patch(b,DrawioFile.LAST_WRITE_WINS?this.file.backupPatch:null)}this.file.invalidChecksum=!1;this.file.inConflictState=!1;this.file.patchDescriptor(this.file.getDescriptor(),l);this.file.backupPatch=null;null!=d&&d(!0)}catch(x){this.file.inConflictState=!0;this.file.invalidChecksum=!0;this.file.descriptorChanged();\nnull!=u&&u(x);try{if(this.file.errorReportsEnabled)m=this.ui.hashValue(this.file.getCurrentRevisionId()),k=this.ui.hashValue(D),this.file.sendErrorReport(\"Error in merge\",\"From: \"+m+\"\\nTo: \"+k+\"\\nChecksum: \"+f+\"\\nPatches:\\n\"+this.file.compressReportData(JSON.stringify(b,null,2)),x);else{var q=this.file.getCurrentUser(),v=null!=q?q.id:\"unknown\";EditorUi.logError(\"Error in merge\",null,this.file.getMode()+\".\"+this.file.getId(),v,x)}}catch(A){}}};", "label_name": "CWE-20", "label": 0}
{"code": "if(null!=X&&0<X.length)for(var Y=0;Y<X.length;Y++)null!=X[Y].xml?c(null,null,0,0,0,0,X[Y]):c(X[Y].data,null,0,0,X[Y].w,X[Y].h,null,\"fixed\",X[Y].title);E=!0}else if(\"mxfile\"==V.documentElement.nodeName){var da=V.documentElement.getElementsByTagName(\"diagram\");for(Y=0;Y<da.length;Y++){X=mxUtils.getTextContent(da[Y]);T=b.stringToCells(Graph.decompress(X));var ha=b.editor.graph.getBoundingBoxFromGeometry(T);c(null,null,0,0,0,0,{xml:X,w:ha.width,h:ha.height})}E=!0}}catch(Z){}E||(b.spinner.stop(),b.handleError({message:mxResources.get(\"errorLoadingFile\")}))}}catch(Z){}return null}", "label_name": "CWE-20", "label": 0}
{"code": "document.createElement(\"tr\");la.className=\"gePropHeader\";var Aa=document.createElement(\"th\");Aa.className=\"gePropHeaderCell\";var Fa=document.createElement(\"img\");Fa.src=Sidebar.prototype.expandedImage;Fa.style.verticalAlign=\"middle\";Aa.appendChild(Fa);mxUtils.write(Aa,mxResources.get(\"property\"));la.style.cursor=\"pointer\";var xa=function(){var za=ua.querySelectorAll(\".gePropNonHeaderRow\");if(Z.editorUi.propertiesCollapsed){Fa.src=Sidebar.prototype.collapsedImage;var ta=\"none\";for(var ka=p.childNodes.length-\n1;0<=ka;ka--)try{var pa=p.childNodes[ka],sa=pa.nodeName.toUpperCase();\"INPUT\"!=sa&&\"SELECT\"!=sa||p.removeChild(pa)}catch(ya){}}else Fa.src=Sidebar.prototype.expandedImage,ta=\"\";for(ka=0;ka<za.length;ka++)za[ka].style.display=ta};mxEvent.addListener(la,\"click\",function(){Z.editorUi.propertiesCollapsed=!Z.editorUi.propertiesCollapsed;xa()});la.appendChild(Aa);Aa=document.createElement(\"th\");Aa.className=\"gePropHeaderCell\";Aa.innerHTML=mxResources.get(\"value\");la.appendChild(Aa);ua.appendChild(la);var Da=", "label_name": "CWE-20", "label": 0}
{"code": "g?\"&mime=\"+g:\"\")+(null!=m?\"&format=\"+m:\"\")+(null!=q?\"&base64=\"+q:\"\")+(null!=e?\"&filename=\"+encodeURIComponent(e):\"\")+(k?\"&binary=1\":\"\"))};EditorUi.prototype.base64ToBlob=function(c,e){e=e||\"\";c=atob(c);for(var g=c.length,k=Math.ceil(g/1024),m=Array(k),q=0;q<k;++q){for(var v=1024*q,x=Math.min(v+1024,g),A=Array(x-v),z=0;v<x;++z,++v)A[z]=c[v].charCodeAt(0);m[q]=new Uint8Array(A)}return new Blob(m,{type:e})};EditorUi.prototype.saveLocalFile=function(c,e,g,k,m,q,v,x){q=null!=q?q:!1;v=null!=v?v:\"vsdx\"!=", "label_name": "CWE-20", "label": 0}
{"code": "W?(mxUtils.setPrefixedStyle(M.cursor.style,\"transition\",\"all 600ms ease-out\"),mxUtils.setPrefixedStyle(T.style,\"transition\",\"all 600ms ease-out\"),window.setTimeout(U,0)):(mxUtils.setPrefixedStyle(M.cursor.style,\"transition\",null),mxUtils.setPrefixedStyle(T.style,\"transition\",null),U())}}function v(M,W){function U(){if(null==y[u]){var Y=t[u];null==Y&&(Y=p%x.length,t[u]=Y,p++);var ba=x[Y];Y=11<Y?\"black\":\"white\";y[u]={cursor:document.createElement(\"div\"),color:ba,selection:{}};I[W]=u;E=y[u].cursor;E.style.pointerEvents=\n\"none\";E.style.position=\"absolute\";E.style.display=\"none\";E.style.opacity=\"0.9\";E.style.zIndex=5E3;var ea=document.createElement(\"img\");mxUtils.setPrefixedStyle(ea.style,\"transform\",\"rotate(-45deg)translateX(-14px)\");ea.setAttribute(\"src\",Graph.createSvgImage(8,12,'<path d=\"M 4 0 L 8 12 L 4 10 L 0 12 Z\" stroke=\"'+ba+'\" fill=\"'+ba+'\"/>').src);ea.style.width=\"10px\";E.appendChild(ea);ea=document.createElement(\"div\");ea.style.backgroundColor=ba;ea.style.color=Y;ea.style.fontSize=\"9pt\";ea.style.padding=\n\"3px 7px\";ea.style.marginTop=\"8px\";ea.style.borderRadius=\"10px\";ea.style.maxWidth=\"100px\";ea.style.overflow=\"hidden\";ea.style.textOverflow=\"ellipsis\";ea.style.whiteSpace=\"nowrap\";mxUtils.write(ea,X);E.appendChild(ea);b.diagramContainer.appendChild(E)}else E=y[u].cursor;J=y[u].selection}if(!P){M=JSON.parse(M);K&&\"cursor\"!=M.type&&EditorUi.debug(\"P2PCollab: msg received\",[M]);if(null!=W){if(M.from==z||B[M.from]>=M.id){EditorUi.debug(\"P2PCollab: Dropped Message\",M,z,B[M.from]);return}B[M.from]=M.id}var X=", "label_name": "CWE-20", "label": 0}
{"code": "Wa,Xa,K,Ga,Ja,Ia,Ha);c.stroke()};Ea.prototype.moveNW=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(0,0):c.moveTo(0,ha)};Ea.prototype.moveNE=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(p,0):c.moveTo(p-ha,0)};Ea.prototype.moveSE=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(p,v):c.moveTo(p,v-ha)};Ea.prototype.moveSW=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(0,", "label_name": "CWE-20", "label": 0}
{"code": "u.nodeName&&(T=u.getElementsByTagName(\"diagram\"),0<T.length&&(N=T[Math.max(0,Math.min(T.length-1,urlParams.page||0))])),null!=N&&(u=Editor.parseDiagramNode(N,J)));null==u||\"mxGraphModel\"==u.nodeName||E&&\"mxfile\"==u.nodeName||(u=null);return u};Editor.parseDiagramNode=function(u,E){var J=mxUtils.trim(mxUtils.getTextContent(u)),T=null;0<J.length?(u=Graph.decompress(J,null,E),null!=u&&0<u.length&&(T=mxUtils.parseXml(u).documentElement)):(u=mxUtils.getChildNodes(u),0<u.length&&(T=mxUtils.createXmlDocument(),\nT.appendChild(T.importNode(u[0],!0)),T=T.documentElement));return T};Editor.getDiagramNodeXml=function(u){var E=mxUtils.getTextContent(u),J=null;0<E.length?J=Graph.decompress(E):null!=u.firstChild&&(J=mxUtils.getXml(u.firstChild));return J};Editor.extractGraphModelFromPdf=function(u){u=u.substring(u.indexOf(\",\")+1);u=window.atob&&!mxClient.IS_SF?atob(u):Base64.decode(u,!0);if(\"%PDF-1.7\"==u.substring(0,8)){var E=u.indexOf(\"EmbeddedFile\");if(-1<E){var J=u.indexOf(\"stream\",E)+9;if(0<u.substring(E,J).indexOf(\"application#2Fvnd.jgraph.mxfile\"))return E=", "label_name": "CWE-20", "label": 0}
{"code": " 'unary+': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = argument(scope, locals, assign, inputs);\n if (isDefined(arg)) {\n arg = +arg;\n } else {\n arg = 0;\n }\n return context ? {value: arg} : arg;\n };\n },", "label_name": "CWE-74", "label": 1}
{"code": "var M=mxText.prototype.redraw;mxText.prototype.redraw=function(){M.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(p,C,I){function T(){for(var la=R.getSelectionCells(),Aa=[],Fa=0;Fa<la.length;Fa++)R.isCellVisible(la[Fa])&&Aa.push(la[Fa]);R.setSelectionCells(Aa)}function P(la){R.hiddenTags=la?[]:Y.slice();T();R.refresh()}function O(la,Aa){ha.innerHTML=\"\";if(0<la.length){var Fa=document.createElement(\"table\");", "label_name": "CWE-20", "label": 0}
{"code": "ua([])},N?null:n)):K(N)),ba=ha,ea=N}function S(ha){null!=xa&&clearTimeout(xa);13==ha.keyCode?H(Na.value):xa=setTimeout(function(){H(Na.value)},1E3)}var V='<div class=\"geTempDlgHeader\"><img src=\"/images/draw.io-logo.svg\" class=\"geTempDlgHeaderLogo\"><input type=\"search\" class=\"geTempDlgSearchBox\" '+(d?\"\":'style=\"display: none\"')+' placeholder=\"'+mxResources.get(\"search\")+'\"></div><div class=\"geTemplatesList\" style=\"display: none\"><div class=\"geTempDlgBack\">< '+mxResources.get(\"back\")+'</div><div class=\"geTempDlgHLine\"></div><div class=\"geTemplatesLbl\">'+", "label_name": "CWE-20", "label": 0}
{"code": "function equals(o1, o2) {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n // eslint-disable-next-line no-self-compare\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n if (t1 === t2 && t1 === 'object') {\n if (isArray(o1)) {\n if (!isArray(o2)) return false;\n if ((length = o1.length) === o2.length) {\n for (key = 0; key < length; key++) {\n if (!equals(o1[key], o2[key])) return false;\n }\n return true;\n }\n } else if (isDate(o1)) {\n if (!isDate(o2)) return false;\n return equals(o1.getTime(), o2.getTime());\n } else if (isRegExp(o1)) {\n if (!isRegExp(o2)) return false;\n return o1.toString() === o2.toString();\n } else {\n if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||\n isArray(o2) || isDate(o2) || isRegExp(o2)) return false;\n keySet = createMap();\n for (key in o1) {\n if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n if (!equals(o1[key], o2[key])) return false;\n keySet[key] = true;\n }\n for (key in o2) {\n if (!(key in keySet) &&\n key.charAt(0) !== '$' &&\n isDefined(o2[key]) &&\n !isFunction(o2[key])) return false;\n }\n return true;\n }\n }\n return false;\n}", "label_name": "CWE-74", "label": 1}
{"code": "function(c){if(null!=c[EditorUi.DIFF_INSERT])for(var e=0;e<c[EditorUi.DIFF_INSERT].length;e++)try{var g=mxUtils.parseXml(c[EditorUi.DIFF_INSERT][e].data).documentElement.cloneNode(!1);null!=g.getAttribute(\"name\")&&g.setAttribute(\"name\",this.anonymizeString(g.getAttribute(\"name\")));c[EditorUi.DIFF_INSERT][e].data=mxUtils.getXml(g)}catch(q){c[EditorUi.DIFF_INSERT][e].data=q.message}if(null!=c[EditorUi.DIFF_UPDATE]){for(var k in c[EditorUi.DIFF_UPDATE]){var m=c[EditorUi.DIFF_UPDATE][k];null!=m.name&&\n(m.name=this.anonymizeString(m.name));null!=m.cells&&(e=mxUtils.bind(this,function(q){var v=m.cells[q];if(null!=v){for(var x in v)null!=v[x].value&&(v[x].value=\"[\"+v[x].value.length+\"]\"),null!=v[x].xmlValue&&(v[x].xmlValue=\"[\"+v[x].xmlValue.length+\"]\"),null!=v[x].style&&(v[x].style=\"[\"+v[x].style.length+\"]\"),mxUtils.isEmptyObject(v[x])&&delete v[x];mxUtils.isEmptyObject(v)&&delete m.cells[q]}}),e(EditorUi.DIFF_INSERT),e(EditorUi.DIFF_UPDATE),mxUtils.isEmptyObject(m.cells)&&delete m.cells);mxUtils.isEmptyObject(m)&&\ndelete c[EditorUi.DIFF_UPDATE][k]}mxUtils.isEmptyObject(c[EditorUi.DIFF_UPDATE])&&delete c[EditorUi.DIFF_UPDATE]}return c};EditorUi.prototype.anonymizeAttributes=function(c,e){if(null!=c.attributes)for(var g=0;g<c.attributes.length;g++)\"as\"!=c.attributes[g].name&&c.setAttribute(c.attributes[g].name,this.anonymizeString(c.attributes[g].value,e));if(null!=c.childNodes)for(g=0;g<c.childNodes.length;g++)this.anonymizeAttributes(c.childNodes[g],e)};EditorUi.prototype.anonymizeNode=function(c,e){e=c.getElementsByTagName(\"mxCell\");", "label_name": "CWE-20", "label": 0}
{"code": "Number(I.value),[e[t]])}}finally{f.getModel().endUpdate()}});O.className=\"geBtn gePrimaryBtn\";mxEvent.addListener(m,\"keypress\",function(t){13==t.keyCode&&O.click()});n=document.createElement(\"div\");n.style.marginTop=\"20px\";n.style.textAlign=\"right\";b.editor.cancelFirst?(n.appendChild(c),n.appendChild(O)):(n.appendChild(O),n.appendChild(c));m.appendChild(n);this.container=m},LibraryDialog=function(b,e,f,c,m,n){function v(D){for(D=document.elementFromPoint(D.clientX,D.clientY);null!=D&&D.parentNode!=\nx;)D=D.parentNode;var G=null;if(null!=D){var P=x.firstChild;for(G=0;null!=P&&P!=D;)P=P.nextSibling,G++}return G}function d(D,G,P,K,F,H,S,V,M){try{if(b.spinner.stop(),null==G||\"image/\"==G.substring(0,6))if(null==D&&null!=S||null==A[D]){var W=function(){Q.innerHTML=\"\";Q.style.cursor=\"pointer\";Q.style.whiteSpace=\"nowrap\";Q.style.textOverflow=\"ellipsis\";mxUtils.write(Q,null!=R.title&&0<R.title.length?R.title:mxResources.get(\"untitled\"));Q.style.color=null==R.title||0==R.title.length?\"#d0d0d0\":\"\"};x.style.backgroundImage=", "label_name": "CWE-20", "label": 0}
{"code": " function deleteConversation (convoId) {\n $.ajax({\n url: '/api/v1/messages/conversation/' + convoId,\n method: 'DELETE',\n success: function (response) {\n if (response.success) {\n // Check if on conversation\n var $convo = $('#message-content[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convo.length > 0) {\n History.pushState(null, null, '/messages', false)\n } else {\n var $convoLI = $('#convo-list').find('li[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convoLI.length > 0) {\n $convoLI.remove()\n }\n }\n\n $.event.trigger('$trudesk:chat:conversation:deleted', {\n conversation: response.conversation\n })\n\n helpers.UI.showSnackbar('Conversation Deleted.', false)\n }\n },\n error: function (error) {\n console.log(error)\n }\n })\n }", "label_name": "CWE-662", "label": 20}
{"code": "document.body.clientWidth||document.documentElement.clientWidth)-this.table.clientWidth));F=Math.max(0,Math.min(F,H-this.table.clientHeight-48));this.getX()==K&&this.getY()==F||mxWindow.prototype.setLocation.apply(this,arguments)};var P=mxUtils.bind(this,function(){var K=this.window.getX(),F=this.window.getY();this.window.setLocation(K,F)});mxEvent.addListener(window,\"resize\",P);this.destroy=function(){mxEvent.removeListener(window,\"resize\",P);this.window.destroy()}},ConfirmDialog=function(b,e,f,", "label_name": "CWE-20", "label": 0}
{"code": "ba.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=ca;Ca=!0;ba.src=\"/images/aui-wait.gif\";fa.isExt?e(fa,oa,function(){A(mxResources.get(\"cantLoadPrev\"));Ca=!1;ba.src=\"/images/icon-search.svg\"}):ia(fa.url,oa)}}function n(fa,ca,ba){if(null!=C){for(var ja=C.className.split(\" \"),ia=0;ia<ja.length;ia++)if(-1<ja[ia].indexOf(\"Active\")){ja.splice(ia,1);break}C.className=ja.join(\" \")}null!=fa?(C=fa,C.className+=\" \"+ca,I=ba,Ba.className=\"geTempDlgCreateBtn\"):(I=C=null,Ba.className=\n\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function y(fa,ca){if(null!=I){var ba=function(oa){qa.isExternal?e(qa,function(na){ja(na,oa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?ja(na.getText(),oa):ia()})):ja(b.emptyDiagramXml,oa)},ja=function(oa,na){x||b.hideDialog(!0);f(oa,na,qa,ca)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){I=qa;Ba.className=\"geTempDlgCreateBtn\";ca&&(Ka.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": 0}
{"code": "function(){g.checked&&(null==e||e.checked)?q.removeAttribute(\"disabled\"):q.setAttribute(\"disabled\",\"disabled\")}));mxUtils.br(c);return{getLink:function(){return g.checked?\"blank\"===q.value?\"_blank\":m:null},getEditInput:function(){return g},getEditSelect:function(){return q}}};EditorUi.prototype.addLinkSection=function(c,e){function g(){var x=document.createElement(\"div\");x.style.width=\"100%\";x.style.height=\"100%\";x.style.boxSizing=\"border-box\";null!=q&&q!=mxConstants.NONE?(x.style.border=\"1px solid black\",\nx.style.backgroundColor=q):(x.style.backgroundPosition=\"center center\",x.style.backgroundRepeat=\"no-repeat\",x.style.backgroundImage=\"url('\"+Dialog.prototype.closeImage+\"')\");v.innerHTML=\"\";v.appendChild(x)}mxUtils.write(c,mxResources.get(\"links\")+\":\");var k=document.createElement(\"select\");k.style.width=\"100px\";k.style.padding=\"0px\";k.style.marginLeft=\"8px\";k.style.marginRight=\"10px\";k.className=\"geBtn\";var m=document.createElement(\"option\");m.setAttribute(\"value\",\"auto\");mxUtils.write(m,mxResources.get(\"automatic\"));", "label_name": "CWE-20", "label": 0}
{"code": "null,\"Error fetching folder items\")+(null!=Ca?\" (\"+Ca+\")\":\"\"));V=!1;P.stop()}})}}function L(N){J.className=J.className.replace(\"odCatSelected\",\"\");J=N;J.className+=\" odCatSelected\"}function C(N){V||(T=null,z(\"search\",null,null,null,N))}var D=\"\";null==e&&(e=I,D='<div style=\"text-align: center;\" class=\"odPreview\"></div>');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem(\"mxODPickerRecentList\"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N[\"@microsoft.graph.downloadUrl\"];", "label_name": "CWE-20", "label": 0}
{"code": "function deleteAdlist() {\n var tr = $(this).closest(\"tr\");\n var id = tr.attr(\"data-id\");\n var address = tr.find(\"#address_\" + id).text();\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Deleting adlist...\", address);\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"delete_adlist\", id: id, token: token },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"far fa-trash-alt\", \"Successfully deleted adlist \", address);\n table.row(tr).remove().draw(false).ajax.reload(null, false);\n } else {\n utils.showAlert(\"error\", \"\", \"Error while deleting adlist with ID \" + id, response.message);\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\"error\", \"\", \"Error while deleting adlist with ID \" + id, jqXHR.responseText);\n console.log(exception); // eslint-disable-line no-console\n }\n });\n}", "label_name": "CWE-862", "label": 8}
{"code": "this.defaultFilename,!0);q.getHash=function(){return k};this.fileLoaded(q);\"csv\"==c.format&&this.importCsv(v,mxUtils.bind(this,function(M){this.editor.undoManager.clear();this.editor.setModified(!1);this.editor.setStatus(\"\")}));if(null!=c.update){var x=null!=c.interval?parseInt(c.interval):6E4,A=null,z=mxUtils.bind(this,function(){var M=this.currentPage;mxUtils.post(c.update,\"xml=\"+encodeURIComponent(mxUtils.getXml(this.editor.getGraphXml())),mxUtils.bind(this,function(n){M===this.currentPage&&(200<=", "label_name": "CWE-20", "label": 0}
{"code": "4)&&!!(a%100)||!(a%400)};d.isSameDay=function(a,c){return a.toDateString()===c.toDateString()};d.locale=function(a,c){c?u(a,{res:v,formatter:w,parser:x},c):\"function\"===typeof a?m=a(d):a&&(q&&!q.date&&console.warn(\"This method of changing the locale is deprecated. See documentation for details.\"),m=a);return m};d.extend=function(a){var c=a.extender||{},b;for(b in c)d[b]||(d[b]=c[b]);(a.formatter||a.parser||a.res)&&u(m,t[m],a)};d.plugin=function(a,c){\"function\"===typeof a?d.extend(r[a(d)]):(r[a]=r[a]||", "label_name": "CWE-400", "label": 2}
{"code": "function minErr(module, ErrorConstructor) {\n ErrorConstructor = ErrorConstructor || Error;\n return function() {\n var SKIP_INDEXES = 2;\n\n var templateArgs = arguments,\n code = templateArgs[0],\n message = '[' + (module ? module + ':' : '') + code + '] ',\n template = templateArgs[1],\n paramPrefix, i;\n\n message += template.replace(/\\{\\d+\\}/g, function(match) {\n var index = +match.slice(1, -1),\n shiftedIndex = index + SKIP_INDEXES;\n\n if (shiftedIndex < templateArgs.length) {\n return toDebugString(templateArgs[shiftedIndex]);\n }\n\n return match;\n });\n\n message += '\\nhttp://errors.angularjs.org/\"NG_VERSION_FULL\"/' +\n (module ? module + '/' : '') + code;\n\n for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {\n message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +\n encodeURIComponent(toDebugString(templateArgs[i]));\n }\n\n return new ErrorConstructor(message);\n };\n}", "label_name": "CWE-74", "label": 1}
{"code": "function assertArg(arg, name, reason) {\n if (!arg) {\n throw ngMinErr('areq', 'Argument \\'{0}\\' is {1}', (name || '?'), (reason || 'required'));\n }\n return arg;\n}", "label_name": "CWE-74", "label": 1}
{"code": "(T=mxUtils.getTextContent(N[0]),T=Graph.decompress(T,null,J),0<T.length&&(u=mxUtils.parseXml(T),u=u.documentElement))))}if(null!=u&&\"svg\"==u.nodeName)if(T=u.getAttribute(\"content\"),null!=T&&\"<\"!=T.charAt(0)&&\"%\"!=T.charAt(0)&&(T=unescape(window.atob?atob(T):Base64.decode(cont,T))),null!=T&&\"%\"==T.charAt(0)&&(T=decodeURIComponent(T)),null!=T&&0<T.length)u=mxUtils.parseXml(T).documentElement;else throw{message:mxResources.get(\"notADiagramFile\")};null==u||E||(N=null,\"diagram\"==u.nodeName?N=u:\"mxfile\"==\nu.nodeName&&(T=u.getElementsByTagName(\"diagram\"),0<T.length&&(N=T[Math.max(0,Math.min(T.length-1,urlParams.page||0))])),null!=N&&(u=Editor.parseDiagramNode(N,J)));null==u||\"mxGraphModel\"==u.nodeName||E&&\"mxfile\"==u.nodeName||(u=null);return u};Editor.parseDiagramNode=function(u,E){var J=mxUtils.trim(mxUtils.getTextContent(u)),T=null;0<J.length?(u=Graph.decompress(J,null,E),null!=u&&0<u.length&&(T=mxUtils.parseXml(u).documentElement)):(u=mxUtils.getChildNodes(u),0<u.length&&(T=mxUtils.createXmlDocument(),", "label_name": "CWE-20", "label": 0}
{"code": "function add (args, where, cb) {\n // this is hot code. almost everything passes through here.\n // the args can be any of:\n // ['url']\n // ['pkg', 'version']\n // ['pkg@version']\n // ['pkg', 'url']\n // This is tricky, because urls can contain @\n // Also, in some cases we get [name, null] rather\n // that just a single argument.\n\n var usage = 'Usage:\\n' +\n ' npm cache add <tarball-url>\\n' +\n ' npm cache add <pkg>@<ver>\\n' +\n ' npm cache add <tarball>\\n' +\n ' npm cache add <folder>\\n'\n var spec\n\n log.silly('cache add', 'args', args)\n\n if (args[1] === undefined) args[1] = null\n\n // at this point the args length must ==2\n if (args[1] !== null) {\n spec = args[0] + '@' + args[1]\n } else if (args.length === 2) {\n spec = args[0]\n }\n\n log.verbose('cache add', 'spec', spec)\n\n if (!spec) return cb(usage)\n\n adding++\n cb = afterAdd(cb)\n\n realizePackageSpecifier(spec, where, function (err, p) {\n if (err) return cb(err)\n\n log.silly('cache add', 'parsed spec', p)\n\n switch (p.type) {\n case 'local':\n case 'directory':\n addLocal(p, null, cb)\n break\n case 'remote':\n // get auth, if possible\n mapToRegistry(spec, npm.config, function (err, uri, auth) {\n if (err) return cb(err)\n\n addRemoteTarball(p.spec, { name: p.name }, null, auth, cb)\n })\n break\n case 'git':\n case 'hosted':\n addRemoteGit(p.rawSpec, cb)\n break\n default:\n if (p.name) return addNamed(p.name, p.spec, null, cb)\n\n cb(new Error(\"couldn't figure out how to install \" + spec))\n }\n })\n}", "label_name": "CWE-200", "label": 10}
{"code": "window.location.hash=null!=x?x.getHash():\"\"}))});b=decodeURIComponent(b.substring(1));StorageFile.getFileContent(this,b,mxUtils.bind(this,function(v){null!=v?(this.fileLoaded(new StorageFile(this,v,b)),null!=d&&d()):e({message:mxResources.get(\"fileNotFound\")})}),e)}else this.handleError({message:mxResources.get(\"serviceUnavailableOrBlocked\")},mxResources.get(\"errorLoadingFile\"),mxUtils.bind(this,function(){var v=this.getCurrentFile();window.location.hash=null!=v?v.getHash():\"\"}));else if(null!=l)this.spinner.stop(),", "label_name": "CWE-20", "label": 0}
{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=J){var ca=function(pa){qa.isExternal?g(qa,function(na){la(na,pa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,qa,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){J=qa;za.className=\"geTempDlgCreateBtn\";da&&(Ga.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": 0}
{"code": "var O=mxText.prototype.redraw;mxText.prototype.redraw=function(){O.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(u,E,J){function T(){for(var ja=R.getSelectionCells(),Ba=[],Ha=0;Ha<ja.length;Ha++)R.isCellVisible(ja[Ha])&&Ba.push(ja[Ha]);R.setSelectionCells(Ba)}function N(ja){R.hiddenTags=ja?[]:Y.slice();T();R.refresh()}function Q(ja,Ba){ea.innerHTML=\"\";if(0<ja.length){var Ha=document.createElement(\"table\");", "label_name": "CWE-20", "label": 0}
{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0}
{"code": "\":\");var q=\"#0000ff\",v=null;v=mxUtils.button(\"\",mxUtils.bind(this,function(x){this.pickColor(q||\"none\",function(A){q=A;g()});mxEvent.consume(x)}));g();v.style.padding=mxClient.IS_FF?\"4px 2px 4px 2px\":\"4px\";v.style.marginLeft=\"4px\";v.style.height=\"22px\";v.style.width=\"22px\";v.style.position=\"relative\";v.style.top=mxClient.IS_IE||mxClient.IS_IE11||mxClient.IS_EDGE?\"6px\":\"1px\";v.className=\"geColorBtn\";c.appendChild(v);mxUtils.br(c);return{getColor:function(){return q},getTarget:function(){return k.value},", "label_name": "CWE-20", "label": 0}
{"code": "E+J+Y(T^4294967295);N+=u.substring(ba-8,u.length);break}N+=u.substring(ba-8,ba-4+ea);Q(u,ea);Q(u,4)}while(ea);return\"data:image/png;base64,\"+(window.btoa?btoa(N):Base64.encode(N,!0))}};if(window.ColorDialog){FilenameDialog.filenameHelpLink=\"https://www.diagrams.net/doc/faq/save-file-formats\";var d=ColorDialog.addRecentColor;ColorDialog.addRecentColor=function(u,E){d.apply(this,arguments);mxSettings.setRecentColors(ColorDialog.recentColors);mxSettings.save()};var g=ColorDialog.resetRecentColors;ColorDialog.resetRecentColors=", "label_name": "CWE-20", "label": 0}
{"code": " async function doIt() {\n await test.server.serverCertificateManager.trustCertificate(certificate);\n const issuerCertificateFile = m(\"CA/public/cacert.pem\");\n const issuerCertificateRevocationListFile = m(\"CA/crl/revocation_list.der\");\n const issuerCertificate = readCertificate(issuerCertificateFile);\n const issuerCrl = await readCertificateRevocationList(issuerCertificateRevocationListFile);\n await test.server.serverCertificateManager.addIssuer(issuerCertificate);\n await test.server.serverCertificateManager.addRevocationList(issuerCrl);\n callback();\n }", "label_name": "CWE-400", "label": 2}
{"code": "\tfatalError:function(error) {\n\t\tconsole.error('[xmldom fatalError]\\t'+error,_locator(this.locator));\n\t throw error;\n\t}", "label_name": "CWE-436", "label": 5}
{"code": "\"boxShadow\",\"2px 2px 3px 0px #ddd\"),\"...\"!=A.substring(A.length-3,A.length)&&\"!\"!=A.charAt(A.length-1)&&(A+=\"...\"),z.innerHTML=A,x.appendChild(z),m.status=z),this.pause=mxUtils.bind(this,function(){var L=function(){};this.active&&(L=mxUtils.bind(this,function(){this.spin(x,A)}));this.stop();return L}),z=!0);return z};var v=m.stop;m.stop=function(){v.call(this);this.active=!1;null!=m.status&&null!=m.status.parentNode&&m.status.parentNode.removeChild(m.status);m.status=null};m.pause=function(){return function(){}};", "label_name": "CWE-20", "label": 0}
{"code": " computedMember: function(left, right, context, create) {\n return function(scope, locals, assign, inputs) {\n var lhs = left(scope, locals, assign, inputs);\n var rhs;\n var value;\n if (lhs != null) {\n rhs = right(scope, locals, assign, inputs);\n rhs = getStringValue(rhs);\n if (create && create !== 1) {\n if (lhs && !(lhs[rhs])) {\n lhs[rhs] = {};\n }\n }\n value = lhs[rhs];\n }\n if (context) {\n return {context: lhs, name: rhs, value: value};\n } else {\n return value;\n }\n };\n },", "label_name": "CWE-74", "label": 1}
{"code": "ka-aa,ha=ua+(ya.y-ua)/ka-aa,da=new Image;da.onload=function(){try{for(var ca=-Math.round(sa-mxUtils.mod((wa-xa)*Y,sa)),la=-Math.round(sa-mxUtils.mod((ua-ha)*Y,sa));ca<Da;ca+=sa)for(var ia=la;ia<La;ia+=sa)Aa.drawImage(da,ca/Y,ia/Y);Fa()}catch(ma){null!=N&&N(ma)}};da.onerror=function(ca){null!=N&&N(ca)};da.src=oa}else Fa()}catch(ca){null!=N&&N(ca)}});Ga.onerror=function(Fa){null!=N&&N(Fa)};ea&&this.graph.addSvgShadow(za);this.graph.mathEnabled&&this.addMathCss(za);var Na=mxUtils.bind(this,function(){try{null!=", "label_name": "CWE-20", "label": 0}
{"code": "Graph.sanitizeHtml=function(b,e){return DOMPurify.sanitize(b,{ADD_ATTR:[\"target\"],FORBID_TAGS:[\"form\"],ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i})};Graph.sanitizeSvg=function(b){return DOMPurify.sanitize(b,{IN_PLACE:!0})};", "label_name": "CWE-20", "label": 0}
{"code": "1?0:Ua.y*ia);this.shape.bounds.height=ma.height-(Ta==Ma.length-1?0:(Ua.height+Ua.y)*ia)}this.shape.redraw()}};var Ya=!1;za.setPosition=function(Ua,eb,jb){La=Math.max(Graph.minTableColumnWidth-Ea.width,eb.x-Ua.x-Ea.width);Ya=mxEvent.isShiftDown(jb.getEvent());null==Da||Ya||(La=Math.min(La,Da.width-Graph.minTableColumnWidth))};za.execute=function(Ua){if(0!=La)T.setTableColumnWidth(this.state.cell,La,Ya);else if(!M.blockDelayedSelection){var eb=T.getCellAt(Ua.getGraphX(),Ua.getGraphY())||ma.cell;T.graphHandler.selectCellForEvent(eb,\nUa)}La=0};za.positionChanged=function(){};za.reset=function(){La=0};z.push(za)})(ca)}}return null!=z?z.reverse():null};var R=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(z){R.apply(this,arguments);if(null!=this.moveHandles)for(var L=0;L<this.moveHandles.length;L++)this.moveHandles[L].style.visibility=z?\"\":\"hidden\";if(null!=this.cornerHandles)for(L=0;L<this.cornerHandles.length;L++)this.cornerHandles[L].node.style.visibility=z?\"\":\"hidden\"};mxVertexHandler.prototype.refreshMoveHandles=", "label_name": "CWE-20", "label": 0}
{"code": "Editor.enableExportUrl=!0;Editor.compressXml=!0;Editor.oneDriveInlinePicker=null!=window.urlParams&&\"0\"==window.urlParams.inlinePicker?!1:!0;Editor.globalVars=null;Editor.config=null;Editor.configVersion=null;Editor.defaultBorder=5;Editor.commonProperties=[{name:\"enumerate\",dispName:\"Enumerate\",type:\"bool\",defVal:!1,onChange:function(u){u.refresh()}},{name:\"enumerateValue\",dispName:\"Enumerate Value\",type:\"string\",defVal:\"\",isVisible:function(u,E){return\"1\"==mxUtils.getValue(u.style,\"enumerate\",\"0\")}},", "label_name": "CWE-20", "label": 0}
{"code": "[H],\"{1} ago\"));F.setAttribute(\"title\",K.toLocaleDateString()+\" \"+K.toLocaleTimeString())}function k(K){var F=document.createElement(\"img\");F.className=\"geCommentBusyImg\";F.src=IMAGE_PATH+\"/spin.gif\";K.appendChild(F);K.busyImg=F}function l(K){K.style.border=\"1px solid red\";K.removeChild(K.busyImg)}function p(K){K.style.border=\"\";K.removeChild(K.busyImg)}function q(K,F,H,S,V){function M(N,Q,R){var Y=document.createElement(\"li\");Y.className=\"geCommentAction\";var ba=document.createElement(\"a\");ba.className=", "label_name": "CWE-20", "label": 0}
{"code": "Da.addListener(\"stateChanged\",function(){La.style.opacity=Da.enabled?\"\":\"0.1\"});var Aa=function(){Na.style.display=0<F.editor.undoManager.history.length||H.isEditing()?\"inline-block\":\"none\";Fa.style.display=Na.style.display;Na.style.opacity=za.enabled?\"\":\"0.1\";Fa.style.opacity=Ga.enabled?\"\":\"0.1\"};Q.appendChild(Na);Q.appendChild(Fa);za.addListener(\"stateChanged\",Aa);Ga.addListener(\"stateChanged\",Aa);Aa();var ta=this.createPageMenuTab(!1,!0);ta.style.display=\"none\";ta.style.position=\"\";ta.style.marginLeft=", "label_name": "CWE-20", "label": 0}
{"code": "function e(F){F.dataTransfer.dropEffect=null!=z?\"move\":\"copy\";F.stopPropagation();F.preventDefault()}function g(F){F.stopPropagation();F.preventDefault();y=!1;L=D(F);if(null!=z)null!=L&&L<v.children.length?(k.splice(L>z?L-1:L,0,k.splice(z,1)[0]),v.insertBefore(v.children[z],v.children[L])):(k.push(k.splice(z,1)[0]),v.appendChild(v.children[z]));else if(0<F.dataTransfer.files.length)b.importFiles(F.dataTransfer.files,0,0,b.maxImageSize,K(F));else if(0<=mxUtils.indexOf(F.dataTransfer.types,\"text/uri-list\")){var G=\ndecodeURIComponent(F.dataTransfer.getData(\"text/uri-list\"));(/(\\.jpg)($|\\?)/i.test(G)||/(\\.png)($|\\?)/i.test(G)||/(\\.gif)($|\\?)/i.test(G)||/(\\.svg)($|\\?)/i.test(G))&&b.loadImage(G,function(N){c(G,null,0,0,N.width,N.height);v.scrollTop=v.scrollHeight})}F.stopPropagation();F.preventDefault()}var k=[];l=document.createElement(\"div\");l.style.height=\"100%\";var m=document.createElement(\"div\");m.style.whiteSpace=\"nowrap\";m.style.height=\"40px\";l.appendChild(m);mxUtils.write(m,mxResources.get(\"filename\")+", "label_name": "CWE-20", "label": 0}
{"code": "function(qb,yb){var ub=tb.apply(this,arguments);return null==ub||qb.view.graph.isCustomLink(ub)?null:ub};pa.getLinkTargetForCellState=function(qb,yb){return qb.view.graph.getLinkTargetForCell(qb.cell)};pa.drawCellState=function(qb,yb){for(var ub=qb.view.graph,vb=null!=Ta?Ta.get(qb.cell):ub.isCellSelected(qb.cell),wb=ub.model.getParent(qb.cell);!(ia&&null==Ta||vb)&&null!=wb;)vb=null!=Ta?Ta.get(wb):ub.isCellSelected(wb),wb=ub.model.getParent(wb);(ia&&null==Ta||vb)&&gb.apply(this,arguments)};pa.drawState(this.getView().getState(this.model.root),", "label_name": "CWE-20", "label": 0}
{"code": "function editClient() {\n var elem = $(this).attr(\"id\");\n var tr = $(this).closest(\"tr\");\n var id = tr.attr(\"data-id\");\n var groups = tr.find(\"#multiselect_\" + id).val();\n var ip = tr.find(\"#ip_\" + id).text();\n var name = tr.find(\"#name_\" + id).text();\n var comment = tr.find(\"#comment_\" + id).val();\n\n var done = \"edited\";\n var notDone = \"editing\";\n switch (elem) {\n case \"multiselect_\" + id:\n done = \"edited groups of\";\n notDone = \"editing groups of\";\n break;\n case \"comment_\" + id:\n done = \"edited comment of\";\n notDone = \"editing comment of\";\n break;\n default:\n alert(\"bad element or invalid data-id!\");\n return;\n }\n\n if (name.length > 0) {\n ip += \" (\" + name + \")\";\n }\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Editing client...\", ip);\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: {\n action: \"edit_client\",\n id: id,\n groups: groups,\n token: token,\n comment: comment\n },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"fas fa-pencil-alt\", \"Successfully \" + done + \" client\", ip);\n table.ajax.reload(null, false);\n } else {\n utils.showAlert(\n \"error\",\n \"Error while \" + notDone + \" client with ID \" + id,\n response.message\n );\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\n \"error\",\n \"\",\n \"Error while \" + notDone + \" client with ID \" + id,\n jqXHR.responseText\n );\n console.log(exception); // eslint-disable-line no-console\n }\n });\n}", "label_name": "CWE-862", "label": 8}
{"code": "Menus.prototype.createMenubar=function(n){var y=v.apply(this,arguments);if(null!=y&&\"1\"!=urlParams.noLangIcon){var K=this.get(\"language\");if(null!=K){K=y.addMenu(\"\",K.funct);K.setAttribute(\"title\",mxResources.get(\"language\"));K.style.width=\"16px\";K.style.paddingTop=\"2px\";K.style.paddingLeft=\"4px\";K.style.zIndex=\"1\";K.style.position=\"absolute\";K.style.display=\"block\";K.style.cursor=\"pointer\";K.style.right=\"17px\";\"atlas\"==uiTheme?(K.style.top=\"6px\",K.style.right=\"15px\"):K.style.top=\"min\"==uiTheme?\"2px\":\n\"0px\";var B=document.createElement(\"div\");B.style.backgroundImage=\"url(\"+Editor.globeImage+\")\";B.style.backgroundPosition=\"center center\";B.style.backgroundRepeat=\"no-repeat\";B.style.backgroundSize=\"19px 19px\";B.style.position=\"absolute\";B.style.height=\"19px\";B.style.width=\"19px\";B.style.marginTop=\"2px\";B.style.zIndex=\"1\";K.appendChild(B);mxUtils.setOpacity(K,40);\"1\"==urlParams.winCtrls&&(K.style.right=\"95px\",K.style.width=\"19px\",K.style.height=\"19px\",K.style.webkitAppRegion=\"no-drag\",B.style.webkitAppRegion=\n\"no-drag\");if(\"atlas\"==uiTheme||\"dark\"==uiTheme)K.style.opacity=\"0.85\",K.style.filter=\"invert(100%)\";document.body.appendChild(K);y.langIcon=K}}return y}}d.customLayoutConfig=[{layout:\"mxHierarchicalLayout\",config:{orientation:\"west\",intraCellSpacing:30,interRankCellSpacing:100,interHierarchySpacing:60,parallelEdgeSpacing:10}}];d.actions.addAction(\"runLayout\",function(){var n=new TextareaDialog(d,\"Run Layouts:\",JSON.stringify(d.customLayoutConfig,null,2),function(y){if(0<y.length)try{var K=JSON.parse(y);", "label_name": "CWE-20", "label": 0}
{"code": "function(A,z,L,M,n){q.apply(this,arguments);m()};t.resizeCell=function(){mxGraph.prototype.resizeCell.apply(this,arguments);m()};t.connectionHandler.addListener(mxEvent.CONNECT,function(){m()})}var v=mxUtils.button(mxResources.get(\"close\"),function(){b.confirm(mxResources.get(\"areYouSure\"),function(){null!=u.parentNode&&(t.destroy(),u.parentNode.removeChild(u));b.hideDialog()})});v.className=\"geBtn\";b.editor.cancelFirst&&d.appendChild(v);var x=mxUtils.button(mxResources.get(\"insert\"),function(A){t.clearCellOverlays();", "label_name": "CWE-20", "label": 0}
{"code": "var M=mxText.prototype.redraw;mxText.prototype.redraw=function(){M.apply(this,arguments);null!=this.node&&\"DIV\"==this.node.nodeName&&Graph.processFontAttributes(this.node)};Graph.prototype.createTagsDialog=function(p,C,I){function T(){for(var la=R.getSelectionCells(),Aa=[],Fa=0;Fa<la.length;Fa++)R.isCellVisible(la[Fa])&&Aa.push(la[Fa]);R.setSelectionCells(Aa)}function P(la){R.hiddenTags=la?[]:Y.slice();T();R.refresh()}function O(la,Aa){ha.innerHTML=\"\";if(0<la.length){var Fa=document.createElement(\"table\");", "label_name": "CWE-20", "label": 0}
{"code": "T.appendChild(T.importNode(u[0],!0)),T=T.documentElement));return T};Editor.getDiagramNodeXml=function(u){var E=mxUtils.getTextContent(u),J=null;0<E.length?J=Graph.decompress(E):null!=u.firstChild&&(J=mxUtils.getXml(u.firstChild));return J};Editor.extractGraphModelFromPdf=function(u){u=u.substring(u.indexOf(\",\")+1);u=window.atob&&!mxClient.IS_SF?atob(u):Base64.decode(u,!0);if(\"%PDF-1.7\"==u.substring(0,8)){var E=u.indexOf(\"EmbeddedFile\");if(-1<E){var J=u.indexOf(\"stream\",E)+9;if(0<u.substring(E,J).indexOf(\"application#2Fvnd.jgraph.mxfile\"))return E=", "label_name": "CWE-20", "label": 0}
{"code": "null!=sa[ua]&&(ua=sa[ua]);ua={url:oa.getAttribute(\"url\"),libs:oa.getAttribute(\"libs\"),title:oa.getAttribute(\"title\"),tooltip:oa.getAttribute(\"name\")||oa.getAttribute(\"url\"),preview:oa.getAttribute(\"preview\"),clibs:ua,tags:oa.getAttribute(\"tags\")};xa.push(ua);null!=ya&&(xa=za[wa],null==xa&&(xa={},za[wa]=xa),wa=xa[ya],null==wa&&(wa=[],xa[ya]=wa),wa.push(ua))}oa=oa.nextSibling}S.stop();C()}})};G.appendChild(fa);G.appendChild(Ba);G.appendChild(Z);var ta=!1,ka=l;/^https?:\\/\\//.test(ka)&&!b.editor.isCorsEnabledForUrl(ka)&&", "label_name": "CWE-20", "label": 0}
{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(c,e,g,k){function m(x,A,z){c1=x>>2;c2=(x&3)<<4|A>>4;c3=(A&15)<<2|z>>6;c4=z&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(x){if(10>x)return String.fromCharCode(48+x);x-=10;if(26>x)return String.fromCharCode(65+x);x-=26;if(26>x)return String.fromCharCode(97+x);x-=26;return 0==x?\"-\":1==x?\"_\":\"?\"}var v=new XMLHttpRequest;v.open(\"GET\",(\"txt\"==e?PLANT_URL+\"/txt/\":\"png\"==e?PLANT_URL+\"/png/\":", "label_name": "CWE-20", "label": 0}
{"code": " parse: function(text) {\n return this.astCompiler.compile(text);\n }", "label_name": "CWE-74", "label": 1}
{"code": "function(c,e){var g=document.createElement(\"div\"),k=this.editor.graph,m=k.getLinkForCell(e);null!=m&&k.setLinkForCell(e,this.updatePageLink(c,m));if(k.isHtmlLabel(e)){g.innerHTML=k.sanitizeHtml(k.getLabel(e));for(var q=g.getElementsByTagName(\"a\"),v=!1,x=0;x<q.length;x++)m=q[x].getAttribute(\"href\"),null!=m&&(q[x].setAttribute(\"href\",this.updatePageLink(c,m)),v=!0);v&&k.labelChanged(e,g.innerHTML)}for(x=0;x<k.model.getChildCount(e);x++)this.updatePageLinksForCell(c,k.model.getChildAt(e,x))};EditorUi.prototype.updatePageLink=", "label_name": "CWE-20", "label": 0}
{"code": "0;N<T;N++)u=Editor.crcTable[(u^E.charCodeAt(J+N))&255]^u>>>8;return u};Editor.crc32=function(u){for(var E=-1,J=0;J<u.length;J++)E=E>>>8^Editor.crcTable[(E^u.charCodeAt(J))&255];return(E^-1)>>>0};Editor.writeGraphModelToPng=function(u,E,J,T,N){function Q(Z,fa){var aa=ba;ba+=fa;return Z.substring(aa,ba)}function R(Z){Z=Q(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}u=u.substring(u.indexOf(\",\")+", "label_name": "CWE-20", "label": 0}
{"code": "y.y,n.width/K,n.height/K,\"fillColor=none;strokeColor=red;\")}));d.actions.addAction(\"testCheckFile\",mxUtils.bind(this,function(){var n=null!=d.pages&&null!=d.getCurrentFile()?d.getCurrentFile().getAnonymizedXmlForPages(d.pages):\"\";n=new TextareaDialog(d,\"Paste Data:\",n,function(y){if(0<y.length)try{var K=function(J){function E(I){if(null==C[I]){if(C[I]=!0,null!=U[I]){for(;0<U[I].length;){var T=U[I].pop();E(T)}delete U[I]}}else mxLog.debug(H+\": Visited: \"+I)}var H=J.parentNode.id,S=J.childNodes;J={};\nfor(var U={},Q=null,W={},V=0;V<S.length;V++){var X=S[V];if(null!=X.id&&0<X.id.length)if(null==J[X.id]){J[X.id]=X.id;var p=X.getAttribute(\"parent\");null==p?null!=Q?mxLog.debug(H+\": Multiple roots: \"+X.id):Q=X.id:(null==U[p]&&(U[p]=[]),U[p].push(X.id))}else W[X.id]=X.id}S=Object.keys(W);0<S.length?(S=H+\": \"+S.length+\" Duplicates: \"+S.join(\", \"),mxLog.debug(S+\" (see console)\")):mxLog.debug(H+\": Checked\");var C={};null==Q?mxLog.debug(H+\": No root\"):(E(Q),Object.keys(C).length!=Object.keys(J).length&&\n(mxLog.debug(H+\": Invalid tree: (see console)\"),console.log(H+\": Invalid tree\",U)))};\"<\"!=y.charAt(0)&&(y=Graph.decompress(y),mxLog.debug(\"See console for uncompressed XML\"),console.log(\"xml\",y));var B=mxUtils.parseXml(y),F=d.getPagesForNode(B.documentElement,\"mxGraphModel\");if(null!=F&&0<F.length)try{var G=d.getHashValueForPages(F);mxLog.debug(\"Checksum: \",G)}catch(J){mxLog.debug(\"Error: \",J.message)}else mxLog.debug(\"No pages found for checksum\");var N=B.getElementsByTagName(\"root\");for(y=0;y<N.length;y++)K(N[y]);", "label_name": "CWE-20", "label": 0}
{"code": "q(x)}),mxUtils.bind(this,function(){this.spinner.stop();this.openLocalFile(c,e,k)}));else{if(\"image/png\"==g.type.substring(0,9))c=this.extractGraphModelFromPng(c);else if(\"application/pdf\"==g.type){var v=Editor.extractGraphModelFromPdf(c);null!=v&&(m=null,k=!0,c=v)}this.spinner.stop();this.openLocalFile(c,e,k,m,null!=m?g:null)}}};EditorUi.prototype.openFiles=function(c,e){if(this.spinner.spin(document.body,mxResources.get(\"loading\")))for(var g=0;g<c.length;g++)mxUtils.bind(this,function(k){var m=\nnew FileReader;m.onload=mxUtils.bind(this,function(q){try{this.openFileHandle(q.target.result,k.name,k,e)}catch(v){this.handleError(v)}});m.onerror=mxUtils.bind(this,function(q){this.spinner.stop();this.handleError(q);window.openFile=null});\"image\"!==k.type.substring(0,5)&&\"application/pdf\"!==k.type||\"image/svg\"===k.type.substring(0,9)?m.readAsText(k):m.readAsDataURL(k)})(c[g])};EditorUi.prototype.openLocalFile=function(c,e,g,k,m){var q=this.getCurrentFile(),v=mxUtils.bind(this,function(){window.openFile=", "label_name": "CWE-20", "label": 0}
{"code": "this.customFonts)))}finally{U.getModel().endUpdate()}}}));this.editorUi.showDialog(W.container,380,Editor.enableWebFonts?250:180,!0,!0);W.init()}),y,null,!0)})))}})();function DiagramPage(b,f){this.node=b;null!=f?this.node.setAttribute(\"id\",f):null==this.getId()&&this.node.setAttribute(\"id\",Editor.guid())}DiagramPage.prototype.node=null;DiagramPage.prototype.root=null;DiagramPage.prototype.viewState=null;DiagramPage.prototype.getId=function(){return this.node.getAttribute(\"id\")};DiagramPage.prototype.getName=function(){return this.node.getAttribute(\"name\")};", "label_name": "CWE-20", "label": 0}
{"code": "function baseExtend(dst, objs, deep) {\n var h = dst.$$hashKey;\n\n for (var i = 0, ii = objs.length; i < ii; ++i) {\n var obj = objs[i];\n if (!isObject(obj) && !isFunction(obj)) continue;\n var keys = Object.keys(obj);\n for (var j = 0, jj = keys.length; j < jj; j++) {\n var key = keys[j];\n var src = obj[key];\n\n if (deep && isObject(src)) {\n if (isDate(src)) {\n dst[key] = new Date(src.valueOf());\n } else if (isRegExp(src)) {\n dst[key] = new RegExp(src);\n } else if (src.nodeName) {\n dst[key] = src.cloneNode(true);\n } else if (isElement(src)) {\n dst[key] = src.clone();\n } else {\n if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};\n baseExtend(dst[key], [src], true);\n }\n } else {\n dst[key] = src;\n }\n }\n }\n\n setHashKey(dst, h);\n return dst;\n}", "label_name": "CWE-74", "label": 1}
{"code": "\"...\");mxEvent.addListener(K,\"click\",function(J){function E(){c(H,S,function(U){g(S);b.addComment(U,function(Q){U.id=Q;F.push(U);m(S)},function(Q){k(S);E();b.handleError(Q,null,null,null,mxUtils.htmlEntities(mxResources.get(\"objectNotFound\")))})},!0)}var H=b.newComment(\"\",b.getCurrentUser()),S=q(H,F,null,0);E();J.preventDefault();mxEvent.consume(J)});y.appendChild(K)}K=L.cloneNode();K.innerHTML='<img src=\"'+IMAGE_PATH+'/check.png\" style=\"width: 16px; padding: 2px;\">';K.setAttribute(\"title\",mxResources.get(\"showResolved\"));", "label_name": "CWE-20", "label": 0}
{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": 0}
{"code": "mxResources.get(\"containsValidationErrors\"),mxResources.get(\"ok\"));else if(B&&b.hideDialog(),O=!y.model.contains(A),!B||O||I!=q){I=Graph.compress(I);y.getModel().beginUpdate();try{if(O){var t=b.editor.graph.getFreeInsertPoint();A.geometry.x=t.x;A.geometry.y=t.y;y.addCell(A)}y.setCellStyles(mxConstants.STYLE_SHAPE,\"stencil(\"+I+\")\",[A])}catch(z){throw z;}finally{y.getModel().endUpdate()}O&&(y.setSelectionCell(A),y.scrollCellToVisible(A))}};f=mxUtils.button(mxResources.get(\"preview\"),function(){x(l,", "label_name": "CWE-20", "label": 0}
{"code": "module.exports.isRepositoryClean = function (callback) {\n cp.exec(gitApp + ' ' + [ 'ls-files', '-m' ].join(' '), gitExtra, function (er, stdout, stderr) {\n // makeCommit parly inspired and taken from NPM version module\n var lines = stdout.trim().split('\\n').filter(function (line) {\n var file = path.basename(line.replace(/.{1,2}\\s+/, ''));\n return line.trim() && !line.match(/^\\?\\? /) && !fUtils.isPackageFile(line);\n }).map(function (line) {\n return line.trim()\n });\n\n if (lines.length) {\n return callback(new Error('Git working directory not clean.\\n'+lines.join('\\n')));\n }\n return callback();\n });\n};", "label_name": "CWE-77", "label": 14}
{"code": "Format.prototype.refresh=function(){null!=this.editorUi.getCurrentFile()||\"1\"==urlParams.embed||this.editorUi.editor.chromeless?l.apply(this,arguments):this.clear()};DiagramFormatPanel.prototype.isShadowOptionVisible=function(){var u=this.editorUi.getCurrentFile();return\"1\"==urlParams.embed||null!=u&&u.isEditable()};DiagramFormatPanel.prototype.isMathOptionVisible=function(u){return!1};var p=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(u){u=p.apply(this,arguments);\nthis.editorUi.getCurrentFile();if(mxClient.IS_SVG&&this.isShadowOptionVisible()){var E=this.editorUi,J=E.editor.graph,T=this.createOption(mxResources.get(\"shadow\"),function(){return J.shadowVisible},function(N){var Q=new ChangePageSetup(E);Q.ignoreColor=!0;Q.ignoreImage=!0;Q.shadowVisible=N;J.model.execute(Q)},{install:function(N){this.listener=function(){N(J.shadowVisible)};E.addListener(\"shadowVisibleChanged\",this.listener)},destroy:function(){E.removeListener(this.listener)}});Editor.enableShadowOption||\n(T.getElementsByTagName(\"input\")[0].setAttribute(\"disabled\",\"disabled\"),mxUtils.setOpacity(T,60));u.appendChild(T)}return u};var q=DiagramFormatPanel.prototype.addOptions;DiagramFormatPanel.prototype.addOptions=function(u){u=q.apply(this,arguments);var E=this.editorUi,J=E.editor.graph;if(J.isEnabled()){var T=E.getCurrentFile();if(null!=T&&T.isAutosaveOptional()){var N=this.createOption(mxResources.get(\"autosave\"),function(){return E.editor.autosave},function(R){E.editor.setAutosave(R);E.editor.autosave&&", "label_name": "CWE-20", "label": 0}
{"code": " body: function(section) {\n return this.state[section].body.join('');\n },", "label_name": "CWE-74", "label": 1}
{"code": "function reloadWithDebugInfo() {\n window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n window.location.reload();\n}", "label_name": "CWE-74", "label": 1}
{"code": "DotObject.prototype._cleanup = function (obj) {\n var ret\n var i\n var keys\n var root\n if (this.cleanup.length) {\n for (i = 0; i < this.cleanup.length; i++) {\n keys = this.cleanup[i].split('.')\n root = keys.splice(0, -1).join('.')\n ret = root ? this.pick(root, obj) : obj\n ret = ret[keys[0]].filter(function (v) { return v !== undefined })\n this.set(this.cleanup[i], ret, obj)\n }\n this.cleanup = []\n }\n}", "label_name": "CWE-74", "label": 1}
{"code": "0;e<this.pages.length;e++)this.updatePageRoot(this.pages[e]),this.addBasenamesForCell(this.pages[e].root,c);else this.addBasenamesForCell(this.editor.graph.model.getRoot(),c);e=[];for(var g in c)e.push(g);return e};EditorUi.prototype.addBasenamesForCell=function(c,e){function g(v){if(null!=v){var x=v.lastIndexOf(\".\");0<x&&(v=v.substring(x+1,v.length));null==e[v]&&(e[v]=!0)}}var k=this.editor.graph,m=k.getCellStyle(c);g(mxStencilRegistry.getBasenameForStencil(m[mxConstants.STYLE_SHAPE]));k.model.isEdge(c)&&\n(g(mxMarker.getPackageForType(m[mxConstants.STYLE_STARTARROW])),g(mxMarker.getPackageForType(m[mxConstants.STYLE_ENDARROW])));m=k.model.getChildCount(c);for(var q=0;q<m;q++)this.addBasenamesForCell(k.model.getChildAt(c,q),e)};EditorUi.prototype.setGraphEnabled=function(c){this.diagramContainer.style.visibility=c?\"\":\"hidden\";this.formatContainer.style.visibility=c?\"\":\"hidden\";this.sidebarFooterContainer.style.display=c?\"\":\"none\";this.sidebarContainer.style.display=c?\"\":\"none\";this.hsplit.style.display=", "label_name": "CWE-20", "label": 0}
{"code": "(z=2);return z};var I=mxVertexHandler.prototype.getSelectionBorderBounds;mxVertexHandler.prototype.getSelectionBorderBounds=function(){return I.apply(this,arguments).grow(-this.getSelectionBorderInset())};var V=null,Q=mxVertexHandler.prototype.createCustomHandles;mxVertexHandler.prototype.createCustomHandles=function(){null==V&&(V=mxCellRenderer.defaultShapes.tableLine);var z=Q.apply(this,arguments);if(this.graph.isTable(this.state.cell)){var L=function(Ta,za,wa){for(var Ea=[],Da=0;Da<Ta.length;Da++){var La=", "label_name": "CWE-20", "label": 0}
{"code": "function(){return mxClient.IS_CHROMEAPP||this.useCanvasForExport};Editor.prototype.getMaxCanvasScale=function(p,C,I){var T=mxClient.IS_FF?8192:16384;return Math.min(I,Math.min(T/p,T/C))};Editor.prototype.exportToCanvas=function(p,C,I,T,P,O,R,Y,da,ha,Z,ea,aa,ua,la,Aa,Fa,xa){try{O=null!=O?O:!0;R=null!=R?R:!0;ea=null!=ea?ea:this.graph;aa=null!=aa?aa:0;var Da=da?null:ea.background;Da==mxConstants.NONE&&(Da=null);null==Da&&(Da=T);null==Da&&0==da&&(Da=Aa?this.graph.defaultPageBackgroundColor:\"#ffffff\");", "label_name": "CWE-20", "label": 0}
{"code": "arguments);for(ua=0;ua<pa.length;ua++)!T&&this.model.contains(pa[ua])&&0==this.model.getChildCount(pa[ua])&&this.model.remove(pa[ua]);T&&this.updateCustomLinks(this.createCellMapping(ma,this.createCellLookup(z)),Ya)}finally{this.model.endUpdate()}return Ya};var q=Graph.prototype.removeCells;Graph.prototype.removeCells=function(z,L){var M=[];this.model.beginUpdate();try{for(var T=0;T<z.length;T++)if(this.isTableCell(z[T])){var ca=this.model.getParent(z[T]),ia=this.model.getParent(ca);1==this.model.getChildCount(ca)&&", "label_name": "CWE-20", "label": 0}
{"code": "E=J}return E};Graph.prototype.getCellsById=function(u){var E=[];if(null!=u)for(var J=0;J<u.length;J++)if(\"*\"==u[J]){var T=this.model.getRoot();E=E.concat(this.model.filterDescendants(function(Q){return Q!=T},T))}else{var N=this.model.getCell(u[J]);null!=N&&E.push(N)}return E};var S=Graph.prototype.isCellVisible;Graph.prototype.isCellVisible=function(u){return S.apply(this,arguments)&&!this.isAllTagsHidden(this.getTagsForCell(u))};Graph.prototype.isAllTagsHidden=function(u){if(null==u||0==u.length||", "label_name": "CWE-20", "label": 0}
{"code": "(q.parentNode.removeChild(q),q=null)});null!=X&&null!=W&&(/(\\.v(dx|sdx?))($|\\?)/i.test(W)||/(\\.vs(x|sx?))($|\\?)/i.test(W))?this.importVisio(X,function(I){C(I,\"text/xml\")},null,W):(new XMLHttpRequest).upload&&this.isRemoteFileFormat(J,W)&&null!=X?this.isExternalDataComms()?this.parseFile(X,mxUtils.bind(this,function(I){4==I.readyState&&(this.spinner.stop(),200<=I.status&&299>=I.status?C(I.responseText,\"text/xml\"):this.handleError({message:mxResources.get(413==I.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},\nmxResources.get(\"errorLoadingFile\")))})):(this.spinner.stop(),this.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):C(J,E)}}));N.stopPropagation();N.preventDefault()})),mxEvent.addListener(x,\"dragleave\",function(N){x.style.cursor=\"\";x.style.backgroundColor=\"\";N.stopPropagation();N.preventDefault()}));L=L.cloneNode(!1);L.setAttribute(\"src\",Editor.editImage);L.setAttribute(\"title\",mxResources.get(\"edit\"));z.insertBefore(L,z.firstChild);mxEvent.addListener(L,\"click\",K);mxEvent.addListener(x,", "label_name": "CWE-20", "label": 0}
{"code": "function(Ta){var za=Fa[Ta],wa=Ta<Fa.length-1?Fa[Ta+1]:null;wa=null!=wa?T.getCellGeometry(wa.cell):null;var Ea=null!=wa&&null!=wa.alternateBounds?wa.alternateBounds:wa;wa=null!=Qa[Ta]?new V(Qa[Ta],mxConstants.NONE,1):new mxLine(new mxRectangle,mxConstants.NONE,1,!1);wa.isDashed=pa.isDashed;wa.svgStrokeTolerance++;za=new mxHandle(za,\"row-resize\",null,wa);za.tableHandle=!0;var Da=0;za.shape.node.parentNode.insertBefore(za.shape.node,za.shape.node.parentNode.firstChild);za.redraw=function(){if(null!=\nthis.shape){this.shape.stroke=0==Da?mxConstants.NONE:pa.stroke;if(this.shape.constructor==V)this.shape.line=L(Qa[Ta],0,Da),this.shape.updateBoundsFromLine();else{var Ya=T.getActualStartSize(ma.cell,!0);this.shape.bounds.height=1;this.shape.bounds.y=this.state.y+this.state.height+Da*ia;this.shape.bounds.x=ma.x+(Ta==Fa.length-1?0:Ya.x*ia);this.shape.bounds.width=ma.width-(Ta==Fa.length-1?0:Ya.width+Ya.x+ia)}this.shape.redraw()}};var La=!1;za.setPosition=function(Ya,Ua,eb){Da=Math.max(Graph.minTableRowHeight-", "label_name": "CWE-20", "label": 0}
{"code": " identifier: function() {\n var token = this.consume();\n if (!token.identifier) {\n this.throwError('is not a valid identifier', token);\n }\n return { type: AST.Identifier, name: token.text };\n },", "label_name": "CWE-74", "label": 1}
{"code": "function isString(value) {return typeof value === 'string';}", "label_name": "CWE-74", "label": 1}
{"code": "1?0:Ua.y*ia);this.shape.bounds.height=ma.height-(Ta==Ma.length-1?0:(Ua.height+Ua.y)*ia)}this.shape.redraw()}};var Ya=!1;za.setPosition=function(Ua,eb,jb){La=Math.max(Graph.minTableColumnWidth-Ea.width,eb.x-Ua.x-Ea.width);Ya=mxEvent.isShiftDown(jb.getEvent());null==Da||Ya||(La=Math.min(La,Da.width-Graph.minTableColumnWidth))};za.execute=function(Ua){if(0!=La)T.setTableColumnWidth(this.state.cell,La,Ya);else if(!M.blockDelayedSelection){var eb=T.getCellAt(Ua.getGraphX(),Ua.getGraphY())||ma.cell;T.graphHandler.selectCellForEvent(eb,", "label_name": "CWE-20", "label": 0}
{"code": " escape: function(value) {\n if (isString(value)) return '\\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\\'';\n if (isNumber(value)) return value.toString();\n if (value === true) return 'true';\n if (value === false) return 'false';\n if (value === null) return 'null';\n if (typeof value === 'undefined') return 'undefined';\n\n throw $parseMinErr('esc', 'IMPOSSIBLE');\n },", "label_name": "CWE-74", "label": 1}
{"code": "(va.appendChild(Z),va.appendChild(fa),ba.appendChild(va));return{div:ba,refresh:aa}};Graph.prototype.getCustomFonts=function(){var u=this.extFonts;u=null!=u?u.slice():[];for(var E in Graph.customFontElements){var J=Graph.customFontElements[E];u.push({name:J.name,url:J.url})}return u};Graph.prototype.setFont=function(u,E){Graph.addFont(u,E);document.execCommand(\"fontname\",!1,u);if(null!=E){var J=this.cellEditor.textarea.getElementsByTagName(\"font\");E=Graph.getFontUrl(u,E);for(var T=0;T<J.length;T++)J[T].getAttribute(\"face\")==", "label_name": "CWE-20", "label": 0}
{"code": "{},J=u.vertices,T=u.edges,N=0;N<J.length;N++)this.findCommonProperties(J[N],E,0==N);for(N=0;N<T.length;N++)this.findCommonProperties(T[N],E,0==J.length&&0==N);null!=Object.getOwnPropertyNames&&0<Object.getOwnPropertyNames(E).length&&this.container.appendChild(this.addProperties(this.createPanel(),E,u))}};var y=StyleFormatPanel.prototype.addStyleOps;StyleFormatPanel.prototype.addStyleOps=function(u){this.addActions(u,[\"copyStyle\",\"pasteStyle\"]);return y.apply(this,arguments)};EditorUi.prototype.propertiesCollapsed=", "label_name": "CWE-20", "label": 0}
{"code": " javascript: function () {\n var str, j = i, e;\n\n if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings\n if (input.charAt(j) !== '`') { return; }\n if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) {\n error(\"You are using JavaScript, which has been disabled.\");\n }\n\n if (e) { $char('~'); }\n\n str = $re(/^`([^`]*)`/);\n if (str) {\n return new(tree.JavaScript)(str[1], i, e);\n }\n }", "label_name": "CWE-74", "label": 1}
{"code": " function send_to_iframes(key, data) {\n // propagate events to iframes\n iframes.forEach(function(iframe) {\n var payload = {\n name: uniq_prefix,\n key: key,\n data: data\n };\n iframe.window.postMessage(JSON.stringify(payload), \"*\");\n });\n }", "label_name": "CWE-200", "label": 10}
{"code": "\"nowrap\";H.style.overflow=\"hidden\";H.style.textOverflow=\"ellipsis\";H.setAttribute(\"title\",F.title+\" (\"+F.id+\")\");var S=document.createElement(\"input\");S.setAttribute(\"type\",\"checkbox\");S.checked=b.sidebar.isEntryVisible(F.id);S.defaultChecked=S.checked;H.appendChild(S);mxUtils.write(H,\" \"+F.title);l.appendChild(H);var V=function(M){if(null==M||\"INPUT\"!=mxEvent.getSource(M).nodeName){p.style.textAlign=\"center\";p.style.padding=\"0px\";p.style.color=\"\";p.innerHTML=\"\";if(null!=F.desc){var W=document.createElement(\"pre\");\nW.style.boxSizing=\"border-box\";W.style.fontFamily=\"inherit\";W.style.margin=\"20px\";W.style.right=\"0px\";W.style.textAlign=\"left\";mxUtils.write(W,F.desc);p.appendChild(W)}null!=F.imageCallback?F.imageCallback(p):null!=F.image?p.innerHTML+='<img border=\"0\" src=\"'+F.image+'\"/>':null==F.desc&&(p.style.padding=\"20px\",p.style.color=\"rgb(179, 179, 179)\",mxUtils.write(p,mxResources.get(\"noPreview\")));null!=q&&(q.style.backgroundColor=\"\");q=H;q.style.backgroundColor=Editor.isDarkMode()?\"#000000\":\"#ebf2f9\";null!=\nM&&mxEvent.consume(M)}};mxEvent.addListener(H,\"click\",V);mxEvent.addListener(H,\"dblclick\",function(M){S.checked=!S.checked;mxEvent.consume(M)});x.push(function(){return S.checked?F.id:null});0==D&&0==K&&V()})(G.entries[K])})(C[D])});g=document.createElement(\"div\");g.className=\"geDialogTitle\";mxUtils.write(g,mxResources.get(\"shapes\"));g.style.position=\"absolute\";g.style.top=\"0px\";g.style.left=\"0px\";g.style.lineHeight=\"40px\";g.style.height=\"40px\";g.style.right=\"0px\";var l=document.createElement(\"div\"),", "label_name": "CWE-20", "label": 0}
{"code": "(this.menus.findWindow.window.setVisible(!1),this.menus.findWindow.window.destroy(),this.menus.findWindow=null);null!=this.menus.findReplaceWindow&&(this.menus.findReplaceWindow.window.setVisible(!1),this.menus.findReplaceWindow.window.destroy(),this.menus.findReplaceWindow=null);B.apply(this,arguments)};var I=EditorUi.prototype.setGraphEnabled;EditorUi.prototype.setGraphEnabled=function(C){I.apply(this,arguments);if(C){var D=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;\n1E3<=D&&null!=this.sidebarWindow&&\"1\"!=urlParams.sketch&&this.sidebarWindow.window.setVisible(!0);null!=this.formatWindow&&(1E3<=D||\"1\"==urlParams.sketch)&&this.formatWindow.window.setVisible(!0)}else null!=this.sidebarWindow&&this.sidebarWindow.window.setVisible(!1),null!=this.formatWindow&&this.formatWindow.window.setVisible(!1)};EditorUi.prototype.chromelessWindowResize=function(){};var O=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(C){C=O.apply(this,arguments);", "label_name": "CWE-20", "label": 0}
{"code": "Ka=U.actions.get(\"zoomOut\"),bb=U.actions.get(\"resetView\");u=U.actions.get(\"fullscreen\");var Pa=U.actions.get(\"undo\"),Za=U.actions.get(\"redo\"),z=X(\"\",Pa.funct,null,mxResources.get(\"undo\")+\" (\"+Pa.shortcut+\")\",Pa,Editor.undoImage),L=X(\"\",Za.funct,null,mxResources.get(\"redo\")+\" (\"+Za.shortcut+\")\",Za,Editor.redoImage),M=X(\"\",u.funct,null,mxResources.get(\"fullscreen\"),u,Editor.fullscreenImage);if(null!=W){J=function(){ma.style.display=null!=U.pages&&(\"0\"!=urlParams.pages||1<U.pages.length||Editor.pagesVisible)?\n\"inline-block\":\"none\"};bb=function(){ma.innerHTML=\"\";if(null!=U.currentPage){mxUtils.write(ma,U.currentPage.getName());var za=null!=U.pages?U.pages.length:1,wa=U.getPageIndex(U.currentPage);wa=null!=wa?wa+1:1;var Ea=U.currentPage.getId();ma.setAttribute(\"title\",U.currentPage.getName()+\" (\"+wa+\"/\"+za+\")\"+(null!=Ea?\" [\"+Ea+\"]\":\"\"))}};M.parentNode.removeChild(M);var T=U.actions.get(\"delete\"),ca=X(\"\",T.funct,null,mxResources.get(\"delete\"),T,Editor.trashImage);ca.style.opacity=\"0.1\";P.appendChild(ca);", "label_name": "CWE-20", "label": 0}
{"code": "function makeMessage(msgType, length) {\n\n const total_length = length + 4 + 1;\n\n total_length.should.be.greaterThan(0);\n\n const buf = Buffer.alloc(total_length);\n\n buf.writeUInt8(msgType.charCodeAt(0), 0);\n buf.writeUInt32LE(total_length, 1);\n\n for (let i = 0; i < length; i++) {\n buf.writeUInt8(msgType.charCodeAt(0), i + 5);\n }\n\n return buf;\n}", "label_name": "CWE-400", "label": 2}
{"code": "l,x,p,v){l=Math.min(p,v/2);c.moveTo(0,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(0,v);c.close();c.end()};mxCellRenderer.registerShape(\"delay\",Ta);mxUtils.extend(za,mxActor);za.prototype.size=.2;za.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(v,p);var A=Math.max(0,Math.min(l,l*parseFloat(mxUtils.getValue(this.style,\"size\",this.size))));l=(v-A)/2;x=l+A;var B=(p-A)/2;A=B+A;c.moveTo(0,l);c.lineTo(B,l);c.lineTo(B,0);c.lineTo(A,0);c.lineTo(A,l);c.lineTo(p,l);c.lineTo(p,x);\nc.lineTo(A,x);c.lineTo(A,v);c.lineTo(B,v);c.lineTo(B,x);c.lineTo(0,x);c.close();c.end()};mxCellRenderer.registerShape(\"cross\",za);mxUtils.extend(wa,mxActor);wa.prototype.size=.25;wa.prototype.redrawPath=function(c,l,x,p,v){l=Math.min(p,v/2);x=Math.min(p-l,Math.max(0,parseFloat(mxUtils.getValue(this.style,\"size\",this.size)))*p);c.moveTo(0,v/2);c.lineTo(x,0);c.lineTo(p-l,0);c.quadTo(p,0,p,v/2);c.quadTo(p,v,p-l,v);c.lineTo(x,v);c.close();c.end()};mxCellRenderer.registerShape(\"display\",wa);mxUtils.extend(Ea,", "label_name": "CWE-20", "label": 0}
{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=J){var ca=function(pa){qa.isExternal?g(qa,function(na){la(na,pa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,qa,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){J=qa;za.className=\"geTempDlgCreateBtn\";da&&(Ga.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": 0}
{"code": "DotObject.prototype._cleanup = function (obj) {\n var ret\n var i\n var keys\n var root\n if (this.cleanup.length) {\n for (i = 0; i < this.cleanup.length; i++) {\n keys = this.cleanup[i].split('.')\n root = keys.splice(0, -1).join('.')\n ret = root ? this.pick(root, obj) : obj\n ret = ret[keys[0]].filter(function (v) { return v !== undefined })\n this.set(this.cleanup[i], ret, obj)\n }\n this.cleanup = []\n }\n}", "label_name": "CWE-74", "label": 1}
{"code": " identifier: function(name, context, create) {\n return function(scope, locals, assign, inputs) {\n var base = locals && (name in locals) ? locals : scope;\n if (create && create !== 1 && base && base[name] == null) {\n base[name] = {};\n }\n var value = base ? base[name] : undefined;\n if (context) {\n return {context: base, name: name, value: value};\n } else {\n return value;\n }\n };\n },", "label_name": "CWE-74", "label": 1}
{"code": " toggleExtensionState({ extensionId, state }) {\n checkAuthentication(this)\n const extension = Extensions.findOne({ _id: extensionId })\n if (extension) {\n Extensions.update({ _id: extension._id }, { $set: { isActive: state } })\n return 'notifications.success'\n }\n return new Meteor.Error('Extension does not exist.')\n },", "label_name": "CWE-285", "label": 23}
{"code": "function reverseParams(iteratorFn) {\n return function(value, key) {iteratorFn(key, value);};\n}", "label_name": "CWE-74", "label": 1}
{"code": "null);mxEvent.consume(ca)})))}if(null!=L)for(M=0;M<L.length;M++){var T=document.createElement(\"div\");T.style.marginTop=null!=z||0<M?\"6px\":\"0px\";T.appendChild(this.graph.createLinkForHint(L[M].getAttribute(\"href\"),mxUtils.getTextContent(L[M])));this.linkHint.appendChild(T)}}}catch(ca){}};mxEdgeHandler.prototype.updateLinkHint=mxVertexHandler.prototype.updateLinkHint;var Ca=mxEdgeHandler.prototype.init;mxEdgeHandler.prototype.init=function(){Ca.apply(this,arguments);this.constraintHandler.isEnabled=\nmxUtils.bind(this,function(){return this.state.view.graph.connectionHandler.isEnabled()});var z=mxUtils.bind(this,function(){null!=this.linkHint&&(this.linkHint.style.display=1==this.graph.getSelectionCount()?\"\":\"none\");null!=this.labelShape&&(this.labelShape.node.style.display=this.graph.isEnabled()&&this.graph.getSelectionCount()<this.graph.graphHandler.maxCells?\"\":\"none\")});this.changeHandler=mxUtils.bind(this,function(T,ca){this.updateLinkHint(this.graph.getLinkForCell(this.state.cell),this.graph.getLinksForState(this.state));\nz();this.redrawHandles()});this.graph.getSelectionModel().addListener(mxEvent.CHANGE,this.changeHandler);this.graph.getModel().addListener(mxEvent.CHANGE,this.changeHandler);var L=this.graph.getLinkForCell(this.state.cell),M=this.graph.getLinksForState(this.state);if(null!=L||null!=M&&0<M.length)this.updateLinkHint(L,M),this.redrawHandles()};var Ra=mxConnectionHandler.prototype.init;mxConnectionHandler.prototype.init=function(){Ra.apply(this,arguments);this.constraintHandler.isEnabled=mxUtils.bind(this,", "label_name": "CWE-20", "label": 0}
{"code": "\"plantUmlData\",JSON.stringify({data:F,format:K.format}))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};g.cellEditor.editMermaidData=function(D,G,P){var K=JSON.parse(P);G=new TextareaDialog(d,mxResources.get(\"mermaid\")+\":\",K.data,function(F){null!=F&&d.spinner.spin(document.body,mxResources.get(\"inserting\"))&&d.generateMermaidImage(F,K.config,function(H,S,V){d.spinner.stop();g.getModel().beginUpdate();try{g.setCellStyles(\"image\",", "label_name": "CWE-20", "label": 0}
{"code": "function pa(){mxEllipse.call(this)}function ua(){mxEllipse.call(this)}function ya(){mxRhombus.call(this)}function Fa(){mxEllipse.call(this)}function Ma(){mxEllipse.call(this)}function Oa(){mxEllipse.call(this)}function Qa(){mxEllipse.call(this)}function Ta(){mxActor.call(this)}function za(){mxActor.call(this)}function wa(){mxActor.call(this)}function Ea(c,l,x,p){mxShape.call(this);this.bounds=c;this.fill=l;this.stroke=x;this.strokewidth=null!=p?p:1;this.rectStyle=\"square\";this.size=10;this.absoluteCornerSize=", "label_name": "CWE-20", "label": 0}
{"code": " ifDefined: function(id, defaultValue) {\n return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n },", "label_name": "CWE-74", "label": 1}
{"code": " peek: function(e1, e2, e3, e4) {\n return this.peekAhead(0, e1, e2, e3, e4);\n },", "label_name": "CWE-74", "label": 1}
{"code": "aa[ua+5]);this.lastX=Z;this.lastY=ea}};p.prototype.rect=function(O,R,Y,da){this.passThrough?this.originalRect.apply(this.canvas,arguments):(this.path=[],this.nextShape=this.rc.generator.rectangle(O,R,Y,da,this.getStyle(!0,!0)))};p.prototype.ellipse=function(O,R,Y,da){this.passThrough?this.originalEllipse.apply(this.canvas,arguments):(this.path=[],this.nextShape=this.rc.generator.ellipse(O+Y/2,R+da/2,Y,da,this.getStyle(!0,!0)))};p.prototype.roundrect=function(O,R,Y,da,ha,Z){this.passThrough?this.originalRoundrect.apply(this.canvas,\narguments):(this.begin(),this.moveTo(O+ha,R),this.lineTo(O+Y-ha,R),this.quadTo(O+Y,R,O+Y,R+Z),this.lineTo(O+Y,R+da-Z),this.quadTo(O+Y,R+da,O+Y-ha,R+da),this.lineTo(O+ha,R+da),this.quadTo(O,R+da,O,R+da-Z),this.lineTo(O,R+Z),this.quadTo(O,R,O+ha,R))};p.prototype.drawPath=function(O){if(0<this.path.length){this.passThrough=!0;try{this.rc.path(this.path.join(\" \"),O)}catch(Y){}this.passThrough=!1}else if(null!=this.nextShape){for(var R in O)this.nextShape.options[R]=O[R];O.stroke!=mxConstants.NONE&&null!=", "label_name": "CWE-20", "label": 0}
{"code": "error_t enc28j60SendPacket(NetInterface *interface,\n const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)\n{\n size_t length;\n\n //Retrieve the length of the packet\n length = netBufferGetLength(buffer) - offset;\n\n //Check the frame length\n if(length > 1536)\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n //Report an error\n return ERROR_INVALID_LENGTH;\n }\n\n //Make sure the link is up before transmitting the frame\n if(!interface->linkState)\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n //Drop current packet\n return NO_ERROR;\n }\n\n //It is recommended to reset the transmit logic before\n //attempting to transmit a packet\n enc28j60SetBit(interface, ENC28J60_REG_ECON1, ECON1_TXRST);\n enc28j60ClearBit(interface, ENC28J60_REG_ECON1, ECON1_TXRST);\n\n //Interrupt flags should be cleared after the reset is completed\n enc28j60ClearBit(interface, ENC28J60_REG_EIR, EIR_TXIF | EIR_TXERIF);\n\n //Set transmit buffer location\n enc28j60WriteReg(interface, ENC28J60_REG_ETXSTL, LSB(ENC28J60_TX_BUFFER_START));\n enc28j60WriteReg(interface, ENC28J60_REG_ETXSTH, MSB(ENC28J60_TX_BUFFER_START));\n\n //Point to start of transmit buffer\n enc28j60WriteReg(interface, ENC28J60_REG_EWRPTL, LSB(ENC28J60_TX_BUFFER_START));\n enc28j60WriteReg(interface, ENC28J60_REG_EWRPTH, MSB(ENC28J60_TX_BUFFER_START));\n\n //Copy the data to the transmit buffer\n enc28j60WriteBuffer(interface, buffer, offset);\n\n //ETXND should point to the last byte in the data payload\n enc28j60WriteReg(interface, ENC28J60_REG_ETXNDL, LSB(ENC28J60_TX_BUFFER_START + length));\n enc28j60WriteReg(interface, ENC28J60_REG_ETXNDH, MSB(ENC28J60_TX_BUFFER_START + length));\n\n //Start transmission\n enc28j60SetBit(interface, ENC28J60_REG_ECON1, ECON1_TXRTS);\n\n //Successful processing\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_akcipher rakcipher;\n\n\tstrlcpy(rakcipher.type, \"akcipher\", sizeof(rakcipher.type));\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,\n\t\t sizeof(struct crypto_report_akcipher), &rakcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int dispatch_discard_io(struct xen_blkif *blkif,\n\t\t\t\tstruct blkif_request *req)\n{\n\tint err = 0;\n\tint status = BLKIF_RSP_OKAY;\n\tstruct block_device *bdev = blkif->vbd.bdev;\n\tunsigned long secure;\n\n\tblkif->st_ds_req++;\n\n\txen_blkif_get(blkif);\n\tsecure = (blkif->vbd.discard_secure &&\n\t\t (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?\n\t\t BLKDEV_DISCARD_SECURE : 0;\n\n\terr = blkdev_issue_discard(bdev, req->u.discard.sector_number,\n\t\t\t\t req->u.discard.nr_sectors,\n\t\t\t\t GFP_KERNEL, secure);\n\n\tif (err == -EOPNOTSUPP) {\n\t\tpr_debug(DRV_PFX \"discard op failed, not supported\\n\");\n\t\tstatus = BLKIF_RSP_EOPNOTSUPP;\n\t} else if (err)\n\t\tstatus = BLKIF_RSP_ERROR;\n\n\tmake_response(blkif, req->u.discard.id, req->operation, status);\n\txen_blkif_put(blkif);\n\treturn err;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)\n{\n\tint c;\n\tuchar buf[2];\n\n\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\tgoto error;\n\t}\n\tbuf[0] = c;\n\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\tgoto error;\n\t}\n\tbuf[1] = c;\n\thdr->magic = buf[0] << 8 | buf[1];\n\tif (hdr->magic != PGX_MAGIC) {\n\t\tjas_eprintf(\"invalid PGX signature\\n\");\n\t\tgoto error;\n\t}\n\tif ((c = pgx_getc(in)) == EOF || !isspace(c)) {\n\t\tgoto error;\n\t}\n\tif (pgx_getbyteorder(in, &hdr->bigendian)) {\n\t\tjas_eprintf(\"cannot get byte order\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getsgnd(in, &hdr->sgnd)) {\n\t\tjas_eprintf(\"cannot get signedness\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->prec)) {\n\t\tjas_eprintf(\"cannot get precision\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->width)) {\n\t\tjas_eprintf(\"cannot get width\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->height)) {\n\t\tjas_eprintf(\"cannot get height\\n\");\n\t\tgoto error;\n\t}\n\treturn 0;\n\nerror:\n\treturn -1;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int snd_seq_ioctl_create_port(struct snd_seq_client *client, void *arg)\n{\n\tstruct snd_seq_port_info *info = arg;\n\tstruct snd_seq_client_port *port;\n\tstruct snd_seq_port_callback *callback;\n\n\t/* it is not allowed to create the port for an another client */\n\tif (info->addr.client != client->number)\n\t\treturn -EPERM;\n\n\tport = snd_seq_create_port(client, (info->flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info->addr.port : -1);\n\tif (port == NULL)\n\t\treturn -ENOMEM;\n\n\tif (client->type == USER_CLIENT && info->kernel) {\n\t\tsnd_seq_delete_port(client, port->addr.port);\n\t\treturn -EINVAL;\n\t}\n\tif (client->type == KERNEL_CLIENT) {\n\t\tif ((callback = info->kernel) != NULL) {\n\t\t\tif (callback->owner)\n\t\t\t\tport->owner = callback->owner;\n\t\t\tport->private_data = callback->private_data;\n\t\t\tport->private_free = callback->private_free;\n\t\t\tport->event_input = callback->event_input;\n\t\t\tport->c_src.open = callback->subscribe;\n\t\t\tport->c_src.close = callback->unsubscribe;\n\t\t\tport->c_dest.open = callback->use;\n\t\t\tport->c_dest.close = callback->unuse;\n\t\t}\n\t}\n\n\tinfo->addr = port->addr;\n\n\tsnd_seq_set_port_info(port, info);\n\tsnd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18}
{"code": "horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)\n{\n int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;\n float fltsize = Fltsize;\n\n#define CLAMP(v) ( (v<(float)0.) ? 0\t\t\t\t\\\n\t\t : (v<(float)2.) ? FromLT2[(int)(v*fltsize)]\t\\\n\t\t : (v>(float)24.2) ? 2047\t\t\t\\\n\t\t : LogK1*log(v*LogK2) + 0.5 )\n\n mask = CODE_MASK;\n if (n >= stride) {\n\tif (stride == 3) {\n\t r2 = wp[0] = (uint16) CLAMP(ip[0]);\n\t g2 = wp[1] = (uint16) CLAMP(ip[1]);\n\t b2 = wp[2] = (uint16) CLAMP(ip[2]);\n\t n -= 3;\n\t while (n > 0) {\n\t\tn -= 3;\n\t\twp += 3;\n\t\tip += 3;\n\t\tr1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;\n\t }\n\t} else if (stride == 4) {\n\t r2 = wp[0] = (uint16) CLAMP(ip[0]);\n\t g2 = wp[1] = (uint16) CLAMP(ip[1]);\n\t b2 = wp[2] = (uint16) CLAMP(ip[2]);\n\t a2 = wp[3] = (uint16) CLAMP(ip[3]);\n\t n -= 4;\n\t while (n > 0) {\n\t\tn -= 4;\n\t\twp += 4;\n\t\tip += 4;\n\t\tr1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;\n\t\ta1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;\n\t }\n\t} else {\n\t ip += n - 1;\t/* point to last one */\n\t wp += n - 1;\t/* point to last one */\n\t n -= stride;\n\t while (n > 0) {\n\t\tREPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);\n\t\t\t\twp[stride] -= wp[0];\n\t\t\t\twp[stride] &= mask;\n\t\t\t\twp--; ip--)\n\t\tn -= stride;\n\t }\n\t REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)\n\t}\n }\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)\n{\n\treturn usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),\n\t\t\t RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE,\n\t\t\t indx, 0, data, size, 500);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void CLASS foveon_dp_load_raw()\n{\n unsigned c, roff[4], row, col, diff;\n ushort huff[512], vpred[2][2], hpred[2];\n\n fseek (ifp, 8, SEEK_CUR);\n foveon_huff (huff);\n roff[0] = 48;\n FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);\n FORC3 {\n fseek (ifp, data_offset+roff[c], SEEK_SET);\n getbits(-1);\n vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;\n for (row=0; row < height; row++) {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col++) {\n\tdiff = ljpeg_diff(huff);\n\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\n\telse hpred[col & 1] += diff;\n\timage[row*width+col][c] = hpred[col & 1];\n }\n }\n }\n}", "label_name": "CWE-119", "label": 26}
{"code": "static void smp_task_timedout(struct timer_list *t)\n{\n\tstruct sas_task_slow *slow = from_timer(slow, t, timer);\n\tstruct sas_task *task = slow->task;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&task->task_state_lock, flags);\n\tif (!(task->task_state_flags & SAS_TASK_STATE_DONE))\n\t\ttask->task_state_flags |= SAS_TASK_STATE_ABORTED;\n\tspin_unlock_irqrestore(&task->task_state_lock, flags);\n\n\tcomplete(&task->slow_task->completion);\n}", "label_name": "CWE-362", "label": 18}
{"code": "static void watchdog_overflow_callback(struct perf_event *event, int nmi,\n\t\t struct perf_sample_data *data,\n\t\t struct pt_regs *regs)\n{\n\t/* Ensure the watchdog never gets throttled */\n\tevent->hw.interrupts = 0;\n\n\tif (__this_cpu_read(watchdog_nmi_touch) == true) {\n\t\t__this_cpu_write(watchdog_nmi_touch, false);\n\t\treturn;\n\t}\n\n\t/* check for a hardlockup\n\t * This is done by making sure our timer interrupt\n\t * is incrementing. The timer interrupt should have\n\t * fired multiple times before we overflow'd. If it hasn't\n\t * then this is a good indication the cpu is stuck\n\t */\n\tif (is_hardlockup()) {\n\t\tint this_cpu = smp_processor_id();\n\n\t\t/* only print hardlockups once */\n\t\tif (__this_cpu_read(hard_watchdog_warn) == true)\n\t\t\treturn;\n\n\t\tif (hardlockup_panic)\n\t\t\tpanic(\"Watchdog detected hard LOCKUP on cpu %d\", this_cpu);\n\t\telse\n\t\t\tWARN(1, \"Watchdog detected hard LOCKUP on cpu %d\", this_cpu);\n\n\t\t__this_cpu_write(hard_watchdog_warn, true);\n\t\treturn;\n\t}\n\n\t__this_cpu_write(hard_watchdog_warn, false);\n\treturn;\n}", "label_name": "CWE-400", "label": 2}
{"code": "static char *fstrndup(const char *ptr, unsigned long len) {\n char *result;\n if (len <= 0) return NULL;\n result = ALLOC_N(char, len);\n memccpy(result, ptr, 0, len);\n return result;\n}", "label_name": "CWE-119", "label": 26}
{"code": "bittok2str_internal(register const struct tok *lp, register const char *fmt,\n\t register u_int v, const char *sep)\n{\n static char buf[256]; /* our stringbuffer */\n int buflen=0;\n register u_int rotbit; /* this is the bit we rotate through all bitpositions */\n register u_int tokval;\n const char * sepstr = \"\";\n\n\twhile (lp != NULL && lp->s != NULL) {\n tokval=lp->v; /* load our first value */\n rotbit=1;\n while (rotbit != 0) {\n /*\n * lets AND the rotating bit with our token value\n * and see if we have got a match\n */\n\t\tif (tokval == (v&rotbit)) {\n /* ok we have found something */\n buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, \"%s%s\",\n sepstr, lp->s);\n sepstr = sep;\n break;\n }\n rotbit=rotbit<<1; /* no match - lets shift and try again */\n }\n lp++;\n\t}\n\n if (buflen == 0)\n /* bummer - lets print the \"unknown\" message as advised in the fmt string if we got one */\n (void)snprintf(buf, sizeof(buf), fmt == NULL ? \"#%08x\" : fmt, v);\n return (buf);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)\n{\n VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);\n uint32_t val = data;\n\n if (addr > (vdev->config_len - sizeof(val)))\n return;\n\n stl_p(vdev->config + addr, val);\n\n if (k->set_config) {\n k->set_config(vdev, vdev->config);\n }\n}", "label_name": "CWE-269", "label": 6}
{"code": "BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n\tint lastBorder;\n\t/* Seek left */\n\tint leftLimit, rightLimit;\n\tint i;\n\tint restoreAlphaBleding;\n\n\tif (border < 0) {\n\t\t/* Refuse to fill to a non-solid border */\n\t\treturn;\n\t}\n\n\tleftLimit = (-1);\n\n\trestoreAlphaBleding = im->alphaBlendingFlag;\n\tim->alphaBlendingFlag = 0;\n\n\tif (x >= im->sx) {\n\t\tx = im->sx - 1;\n\t} else if (x < 0) {\n\t\tx = 0;\n\t}\n\tif (y >= im->sy) {\n\t\ty = im->sy - 1;\n\t} else if (y < 0) {\n\t\ty = 0;\n\t}\n\t\n\tfor (i = x; (i >= 0); i--) {\n\t\tif (gdImageGetPixel (im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel (im, i, y, color);\n\t\tleftLimit = i;\n\t}\n\tif (leftLimit == (-1)) {\n\t\tim->alphaBlendingFlag = restoreAlphaBleding;\n\t\treturn;\n\t}\n\t/* Seek right */\n\trightLimit = x;\n\tfor (i = (x + 1); (i < im->sx); i++) {\n\t\tif (gdImageGetPixel (im, i, y) == border) {\n\t\t\tbreak;\n\t\t}\n\t\tgdImageSetPixel (im, i, y, color);\n\t\trightLimit = i;\n\t}\n\t/* Look at lines above and below and start paints */\n\t/* Above */\n\tif (y > 0) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; (i <= rightLimit); i++) {\n\t\t\tint c;\n\t\t\tc = gdImageGetPixel (im, i, y - 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder (im, i, y - 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\t/* Below */\n\tif (y < ((im->sy) - 1)) {\n\t\tlastBorder = 1;\n\t\tfor (i = leftLimit; (i <= rightLimit); i++) {\n\t\t\tint c = gdImageGetPixel (im, i, y + 1);\n\t\t\tif (lastBorder) {\n\t\t\t\tif ((c != border) && (c != color)) {\n\t\t\t\t\tgdImageFillToBorder (im, i, y + 1, border, color);\n\t\t\t\t\tlastBorder = 0;\n\t\t\t\t}\n\t\t\t} else if ((c == border) || (c == color)) {\n\t\t\t\tlastBorder = 1;\n\t\t\t}\n\t\t}\n\t}\n\tim->alphaBlendingFlag = restoreAlphaBleding;\n}", "label_name": "CWE-119", "label": 26}
{"code": "int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tsize_t copied;\n\tint err;\n\n\tBT_DBG(\"sock %p sk %p len %zu\", sock, sk, len);\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb) {\n\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n\t\t\tmsg->msg_namelen = 0;\n\t\t\treturn 0;\n\t\t}\n\t\treturn err;\n\t}\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err == 0) {\n\t\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t\tif (bt_sk(sk)->skb_msg_name)\n\t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n\t\t\t\t\t\t&msg->msg_namelen);\n\t\telse\n\t\t\tmsg->msg_namelen = 0;\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void mark_commit(struct commit *c, void *data)\n{\n\tmark_object(&c->object, NULL, NULL, data);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void lpc546xxEthInitGpio(NetInterface *interface)\n{\n gpio_pin_config_t pinConfig;\n\n //Select RMII interface mode\n SYSCON->ETHPHYSEL |= SYSCON_ETHPHYSEL_PHY_SEL_MASK;\n\n //Enable IOCON clock\n CLOCK_EnableClock(kCLOCK_Iocon);\n\n //Enable GPIO clocks\n CLOCK_EnableClock(kCLOCK_Gpio0);\n CLOCK_EnableClock(kCLOCK_Gpio4);\n\n //Configure ENET_TXD1 (PA0_17)\n IOCON_PinMuxSet(IOCON, 0, 17, IOCON_FUNC7 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_TXD0 (PA4_8)\n IOCON_PinMuxSet(IOCON, 4, 8, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_RX_DV (PA4_10)\n IOCON_PinMuxSet(IOCON, 4, 10, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_RXD0 (PA4_11)\n IOCON_PinMuxSet(IOCON, 4, 11, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_RXD1 (PA4_12)\n IOCON_PinMuxSet(IOCON, 4, 12, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_TX_EN (PA4_13)\n IOCON_PinMuxSet(IOCON, 4, 13, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_RX_CLK (PA4_14)\n IOCON_PinMuxSet(IOCON, 4, 14, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_MDC (PA4_15)\n IOCON_PinMuxSet(IOCON, 4, 15, IOCON_FUNC1 | IOCON_MODE_INACT |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_MDIO (PA4_16)\n IOCON_PinMuxSet(IOCON, 4, 16, IOCON_FUNC1 | IOCON_MODE_PULLUP |\n IOCON_DIGITAL_EN | IOCON_INPFILT_OFF);\n\n //Configure ENET_RST as an output\n pinConfig.pinDirection = kGPIO_DigitalOutput;\n pinConfig.outputLogic = 0;\n GPIO_PinInit(GPIO, 2, 26, &pinConfig);\n\n //Reset PHY transceiver (hard reset)\n GPIO_WritePinOutput(GPIO, 2, 26, 0);\n sleep(10);\n GPIO_WritePinOutput(GPIO, 2, 26, 1);\n sleep(10);\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *m, size_t len, int flags)\n\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint ret;\n\tint copylen;\n\n\tret = -EOPNOTSUPP;\n\tif (m->msg_flags&MSG_OOB)\n\t\tgoto read_error;\n\n\tm->msg_namelen = 0;\n\n\tskb = skb_recv_datagram(sk, flags, 0 , &ret);\n\tif (!skb)\n\t\tgoto read_error;\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tm->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\tret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen);\n\tif (ret)\n\t\tgoto out_free;\n\n\tret = (flags & MSG_TRUNC) ? skb->len : copylen;\nout_free:\n\tskb_free_datagram(sk, skb);\n\tcaif_check_flow_release(sk);\n\treturn ret;\n\nread_error:\n\treturn ret;\n}", "label_name": "CWE-20", "label": 0}
{"code": "ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,\n void *(*allocfunc)(void *, u_int, u_int),\n void (*freefunc)(void *, void *))\n{\n\tssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_out_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_out_stream.opaque = ctx;\n\tssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;\n\tssh->state->compression_in_stream.zfree = (free_func)freefunc;\n\tssh->state->compression_in_stream.opaque = ctx;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,\n\t\tunsigned long address, unsigned int *flags, int *nonblocking)\n{\n\tunsigned int fault_flags = 0;\n\tint ret;\n\n\t/* mlock all present pages, but do not fault in new pages */\n\tif ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)\n\t\treturn -ENOENT;\n\t/* For mm_populate(), just skip the stack guard page. */\n\tif ((*flags & FOLL_POPULATE) &&\n\t\t\t(stack_guard_page_start(vma, address) ||\n\t\t\t stack_guard_page_end(vma, address + PAGE_SIZE)))\n\t\treturn -ENOENT;\n\tif (*flags & FOLL_WRITE)\n\t\tfault_flags |= FAULT_FLAG_WRITE;\n\tif (*flags & FOLL_REMOTE)\n\t\tfault_flags |= FAULT_FLAG_REMOTE;\n\tif (nonblocking)\n\t\tfault_flags |= FAULT_FLAG_ALLOW_RETRY;\n\tif (*flags & FOLL_NOWAIT)\n\t\tfault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;\n\tif (*flags & FOLL_TRIED) {\n\t\tVM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);\n\t\tfault_flags |= FAULT_FLAG_TRIED;\n\t}\n\n\tret = handle_mm_fault(vma, address, fault_flags);\n\tif (ret & VM_FAULT_ERROR) {\n\t\tif (ret & VM_FAULT_OOM)\n\t\t\treturn -ENOMEM;\n\t\tif (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))\n\t\t\treturn *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT;\n\t\tif (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))\n\t\t\treturn -EFAULT;\n\t\tBUG();\n\t}\n\n\tif (tsk) {\n\t\tif (ret & VM_FAULT_MAJOR)\n\t\t\ttsk->maj_flt++;\n\t\telse\n\t\t\ttsk->min_flt++;\n\t}\n\n\tif (ret & VM_FAULT_RETRY) {\n\t\tif (nonblocking)\n\t\t\t*nonblocking = 0;\n\t\treturn -EBUSY;\n\t}\n\n\t/*\n\t * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when\n\t * necessary, even if maybe_mkwrite decided not to set pte_write. We\n\t * can thus safely do subsequent page lookups as if they were reads.\n\t * But only do so when looping for pte_write is futile: in some cases\n\t * userspace may also be wanting to write to the gotten user page,\n\t * which a read fault here might prevent (a readonly page might get\n\t * reCOWed by userspace write).\n\t */\n\tif ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))\n\t\t*flags &= ~FOLL_WRITE;\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int get_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)\n{\n\tint ret;\n\n\tret = usb_control_msg(pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0),\n\t\t\t PEGASUS_REQ_GET_REGS, PEGASUS_REQT_READ, 0,\n\t\t\t indx, data, size, 1000);\n\tif (ret < 0)\n\t\tnetif_dbg(pegasus, drv, pegasus->net,\n\t\t\t \"%s returned %d\\n\", __func__, ret);\n\treturn ret;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode)\n{\n\tM_fs_info_t *info = NULL;\n\tchar *pold = NULL;\n\tchar *pnew = NULL;\n\tM_fs_type_t type;\n\tM_bool ret = M_TRUE;\n\n\tif (mode & M_FS_FILE_MODE_OVERWRITE)\n\t\treturn M_TRUE;\n\n\t/* If we're not overwriting we need to verify existance.\n \t *\n \t * For files we need to check if the file name exists in the\n\t * directory it's being copied to.\n\t *\n\t * For directories we need to check if the directory name\n\t * exists in the directory it's being copied to.\n\t */\n\n\tif (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS)\n\t\treturn M_FALSE;\n\n\ttype = M_fs_info_get_type(info);\n\tM_fs_info_destroy(info);\n\n\tif (type != M_FS_TYPE_DIR) {\n\t\t/* File exists at path. */\n\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS)\n\t\t{\n\t\t\tret = M_FALSE;\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t/* Is dir */\n\tpold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO);\n\tpnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO);\n\tif (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n\t\tret = M_FALSE;\n\t\tgoto done;\n\t}\n\ndone:\n\tM_free(pnew);\n\tM_free(pold);\n\treturn ret;\n}", "label_name": "CWE-732", "label": 13}
{"code": "header_read (SF_PRIVATE *psf, void *ptr, int bytes)\n{\tint count = 0 ;\n\n\tif (psf->headindex >= SIGNED_SIZEOF (psf->header))\n\t\treturn psf_fread (ptr, 1, bytes, psf) ;\n\n\tif (psf->headindex + bytes > SIGNED_SIZEOF (psf->header))\n\t{\tint most ;\n\n\t\tmost = SIGNED_SIZEOF (psf->header) - psf->headend ;\n\t\tpsf_fread (psf->header + psf->headend, 1, most, psf) ;\n\t\tmemcpy (ptr, psf->header + psf->headend, most) ;\n\t\tpsf->headend = psf->headindex += most ;\n\t\tpsf_fread ((char *) ptr + most, bytes - most, 1, psf) ;\n\t\treturn bytes ;\n\t\t} ;\n\n\tif (psf->headindex + bytes > psf->headend)\n\t{\tcount = psf_fread (psf->header + psf->headend, 1, bytes - (psf->headend - psf->headindex), psf) ;\n\t\tif (count != bytes - (int) (psf->headend - psf->headindex))\n\t\t{\tpsf_log_printf (psf, \"Error : psf_fread returned short count.\\n\") ;\n\t\t\treturn count ;\n\t\t\t} ;\n\t\tpsf->headend += count ;\n\t\t} ;\n\n\tmemcpy (ptr, psf->header + psf->headindex, bytes) ;\n\tpsf->headindex += bytes ;\n\n\treturn bytes ;\n} /* header_read */", "label_name": "CWE-119", "label": 26}
{"code": "static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,\n jas_stream_t *in)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tunsigned int i;\n\tuint_fast8_t tmp;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (jpc_getuint16(in, &siz->caps) ||\n\t jpc_getuint32(in, &siz->width) ||\n\t jpc_getuint32(in, &siz->height) ||\n\t jpc_getuint32(in, &siz->xoff) ||\n\t jpc_getuint32(in, &siz->yoff) ||\n\t jpc_getuint32(in, &siz->tilewidth) ||\n\t jpc_getuint32(in, &siz->tileheight) ||\n\t jpc_getuint32(in, &siz->tilexoff) ||\n\t jpc_getuint32(in, &siz->tileyoff) ||\n\t jpc_getuint16(in, &siz->numcomps)) {\n\t\treturn -1;\n\t}\n\tif (!siz->width || !siz->height || !siz->tilewidth ||\n\t !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {\n\t\treturn -1;\n\t}\n\tif (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {\n\t\tjas_eprintf(\"all tiles are outside the image area\\n\");\n\t\treturn -1;\n\t}\n\tif (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {\n\t\treturn -1;\n\t}\n\tfor (i = 0; i < siz->numcomps; ++i) {\n\t\tif (jpc_getuint8(in, &tmp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].hsamp) ||\n\t\t jpc_getuint8(in, &siz->comps[i].vsamp)) {\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tif (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {\n\t\t\tjas_eprintf(\"invalid XRsiz value %d\\n\", siz->comps[i].hsamp);\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tif (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {\n\t\t\tjas_eprintf(\"invalid YRsiz value %d\\n\", siz->comps[i].vsamp);\n\t\t\tjas_free(siz->comps);\n\t\t\treturn -1;\n\t\t}\n\t\tsiz->comps[i].sgnd = (tmp >> 7) & 1;\n\t\tsiz->comps[i].prec = (tmp & 0x7f) + 1;\n\t}\n\tif (jas_stream_eof(in)) {\n\t\tjas_free(siz->comps);\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0}
{"code": "int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n\t\t struct sockaddr_storage *kern_address, int mode)\n{\n\tint tot_len;\n\n\tif (kern_msg->msg_namelen) {\n\t\tif (mode == VERIFY_READ) {\n\t\t\tint err = move_addr_to_kernel(kern_msg->msg_name,\n\t\t\t\t\t\t kern_msg->msg_namelen,\n\t\t\t\t\t\t kern_address);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t}\n\t\tkern_msg->msg_name = kern_address;\n\t} else\n\t\tkern_msg->msg_name = NULL;\n\n\ttot_len = iov_from_user_compat_to_kern(kern_iov,\n\t\t\t\t\t (struct compat_iovec __user *)kern_msg->msg_iov,\n\t\t\t\t\t kern_msg->msg_iovlen);\n\tif (tot_len >= 0)\n\t\tkern_msg->msg_iov = kern_iov;\n\n\treturn tot_len;\n}", "label_name": "CWE-20", "label": 0}
{"code": "error_t httpCheckCharset(const char_t *s, size_t length, uint_t charset)\n{\n error_t error;\n size_t i;\n uint8_t c;\n uint_t m;\n\n //Initialize status code\n error = NO_ERROR;\n\n //Parse string\n for(i = 0; i < length; i++)\n {\n //Get current character\n c = (uint8_t) s[i];\n\n //Any 8-bit sequence of data\n m = HTTP_CHARSET_OCTET;\n\n //Check if character is a control character\n if(iscntrl(c))\n m |= HTTP_CHARSET_CTL;\n\n //Check if character is printable\n if(isprint(c) && c <= 126)\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_VCHAR;\n\n //Check if character is blank\n if(c == ' ' || c == '\\t')\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_LWS;\n\n //Check if character is alphabetic\n if(isalpha(c))\n m |= HTTP_CHARSET_TCHAR | HTTP_CHARSET_ALPHA;\n\n //Check if character is decimal digit\n if(osIsdigit(c))\n m |= HTTP_CHARSET_TCHAR | HTTP_CHARSET_DIGIT;\n\n //Check if character is hexadecimal digit\n if(isxdigit(c))\n m |= HTTP_CHARSET_HEX;\n\n //Check if character is in the extended character set\n if(c >= 128)\n m |= HTTP_CHARSET_TEXT | HTTP_CHARSET_OBS_TEXT;\n\n //Check if character is a token character\n if(strchr(\"!#$%&'*+-.^_`|~\", c))\n m |= HTTP_CHARSET_TCHAR;\n\n //Invalid character?\n if((m & charset) == 0)\n error = ERROR_INVALID_SYNTAX;\n }\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int br_parse_ip_options(struct sk_buff *skb)\n{\n\tstruct ip_options *opt;\n\tstruct iphdr *iph;\n\tstruct net_device *dev = skb->dev;\n\tu32 len;\n\n\tiph = ip_hdr(skb);\n\topt = &(IPCB(skb)->opt);\n\n\t/* Basic sanity checks */\n\tif (iph->ihl < 5 || iph->version != 4)\n\t\tgoto inhdr_error;\n\n\tif (!pskb_may_pull(skb, iph->ihl*4))\n\t\tgoto inhdr_error;\n\n\tiph = ip_hdr(skb);\n\tif (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))\n\t\tgoto inhdr_error;\n\n\tlen = ntohs(iph->tot_len);\n\tif (skb->len < len) {\n\t\tIP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS);\n\t\tgoto drop;\n\t} else if (len < (iph->ihl*4))\n\t\tgoto inhdr_error;\n\n\tif (pskb_trim_rcsum(skb, len)) {\n\t\tIP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS);\n\t\tgoto drop;\n\t}\n\n\t/* Zero out the CB buffer if no options present */\n\tif (iph->ihl == 5) {\n\t\tmemset(IPCB(skb), 0, sizeof(struct inet_skb_parm));\n\t\treturn 0;\n\t}\n\n\topt->optlen = iph->ihl*4 - sizeof(struct iphdr);\n\tif (ip_options_compile(dev_net(dev), opt, skb))\n\t\tgoto inhdr_error;\n\n\t/* Check correct handling of SRR option */\n\tif (unlikely(opt->srr)) {\n\t\tstruct in_device *in_dev = __in_dev_get_rcu(dev);\n\t\tif (in_dev && !IN_DEV_SOURCE_ROUTE(in_dev))\n\t\t\tgoto drop;\n\n\t\tif (ip_options_rcv_srr(skb))\n\t\t\tgoto drop;\n\t}\n\n\treturn 0;\n\ninhdr_error:\n\tIP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS);\ndrop:\n\treturn -1;\n}", "label_name": "CWE-665", "label": 32}
{"code": "static unsigned int xdr_set_page_base(struct xdr_stream *xdr,\n\t\t\t\t unsigned int base, unsigned int len)\n{\n\tunsigned int pgnr;\n\tunsigned int maxlen;\n\tunsigned int pgoff;\n\tunsigned int pgend;\n\tvoid *kaddr;\n\n\tmaxlen = xdr->buf->page_len;\n\tif (base >= maxlen) {\n\t\tbase = maxlen;\n\t\tmaxlen = 0;\n\t} else\n\t\tmaxlen -= base;\n\tif (len > maxlen)\n\t\tlen = maxlen;\n\n\txdr_stream_page_set_pos(xdr, base);\n\tbase += xdr->buf->page_base;\n\n\tpgnr = base >> PAGE_SHIFT;\n\txdr->page_ptr = &xdr->buf->pages[pgnr];\n\tkaddr = page_address(*xdr->page_ptr);\n\n\tpgoff = base & ~PAGE_MASK;\n\txdr->p = (__be32*)(kaddr + pgoff);\n\n\tpgend = pgoff + len;\n\tif (pgend > PAGE_SIZE)\n\t\tpgend = PAGE_SIZE;\n\txdr->end = (__be32*)(kaddr + pgend);\n\txdr->iov = NULL;\n\treturn len;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static void save_text_if_changed(const char *name, const char *new_value)\n{\n /* a text value can't be change if the file is not loaded */\n /* returns NULL if the name is not found; otherwise nonzero */\n if (!g_hash_table_lookup(g_loaded_texts, name))\n return;\n\n const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : \"\";\n if (!old_value)\n old_value = \"\";\n if (strcmp(new_value, old_value) != 0)\n {\n struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name);\n if (dd)\n dd_save_text(dd, name, new_value);\n\n//FIXME: else: what to do with still-unsaved data in the widget??\n dd_close(dd);\n problem_data_reload_from_dump_dir();\n update_gui_state_from_problem_data(/* don't update selected event */ 0);\n }\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int __key_instantiate_and_link(struct key *key,\n\t\t\t\t struct key_preparsed_payload *prep,\n\t\t\t\t struct key *keyring,\n\t\t\t\t struct key *authkey,\n\t\t\t\t struct assoc_array_edit **_edit)\n{\n\tint ret, awaken;\n\n\tkey_check(key);\n\tkey_check(keyring);\n\n\tawaken = 0;\n\tret = -EBUSY;\n\n\tmutex_lock(&key_construction_mutex);\n\n\t/* can't instantiate twice */\n\tif (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {\n\t\t/* instantiate the key */\n\t\tret = key->type->instantiate(key, prep);\n\n\t\tif (ret == 0) {\n\t\t\t/* mark the key as being instantiated */\n\t\t\tatomic_inc(&key->user->nikeys);\n\t\t\tset_bit(KEY_FLAG_INSTANTIATED, &key->flags);\n\n\t\t\tif (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))\n\t\t\t\tawaken = 1;\n\n\t\t\t/* and link it into the destination keyring */\n\t\t\tif (keyring) {\n\t\t\t\tif (test_bit(KEY_FLAG_KEEP, &keyring->flags))\n\t\t\t\t\tset_bit(KEY_FLAG_KEEP, &key->flags);\n\n\t\t\t\t__key_link(key, _edit);\n\t\t\t}\n\n\t\t\t/* disable the authorisation key */\n\t\t\tif (authkey)\n\t\t\t\tkey_revoke(authkey);\n\n\t\t\tif (prep->expiry != TIME_T_MAX) {\n\t\t\t\tkey->expiry = prep->expiry;\n\t\t\t\tkey_schedule_gc(prep->expiry + key_gc_delay);\n\t\t\t}\n\t\t}\n\t}\n\n\tmutex_unlock(&key_construction_mutex);\n\n\t/* wake up anyone waiting for a key to be constructed */\n\tif (awaken)\n\t\twake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);\n\n\treturn ret;\n}", "label_name": "CWE-20", "label": 0}
{"code": "int install_user_keyrings(void)\n{\n\tstruct user_struct *user;\n\tconst struct cred *cred;\n\tstruct key *uid_keyring, *session_keyring;\n\tkey_perm_t user_keyring_perm;\n\tchar buf[20];\n\tint ret;\n\tuid_t uid;\n\n\tuser_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;\n\tcred = current_cred();\n\tuser = cred->user;\n\tuid = from_kuid(cred->user_ns, user->uid);\n\n\tkenter(\"%p{%u}\", user, uid);\n\n\tif (user->uid_keyring) {\n\t\tkleave(\" = 0 [exist]\");\n\t\treturn 0;\n\t}\n\n\tmutex_lock(&key_user_keyring_mutex);\n\tret = 0;\n\n\tif (!user->uid_keyring) {\n\t\t/* get the UID-specific keyring\n\t\t * - there may be one in existence already as it may have been\n\t\t * pinned by a session, but the user_struct pointing to it\n\t\t * may have been destroyed by setuid */\n\t\tsprintf(buf, \"_uid.%u\", uid);\n\n\t\tuid_keyring = find_keyring_by_name(buf, true);\n\t\tif (IS_ERR(uid_keyring)) {\n\t\t\tuid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,\n\t\t\t\t\t\t cred, user_keyring_perm,\n\t\t\t\t\t\t KEY_ALLOC_IN_QUOTA, NULL);\n\t\t\tif (IS_ERR(uid_keyring)) {\n\t\t\t\tret = PTR_ERR(uid_keyring);\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\n\t\t/* get a default session keyring (which might also exist\n\t\t * already) */\n\t\tsprintf(buf, \"_uid_ses.%u\", uid);\n\n\t\tsession_keyring = find_keyring_by_name(buf, true);\n\t\tif (IS_ERR(session_keyring)) {\n\t\t\tsession_keyring =\n\t\t\t\tkeyring_alloc(buf, user->uid, INVALID_GID,\n\t\t\t\t\t cred, user_keyring_perm,\n\t\t\t\t\t KEY_ALLOC_IN_QUOTA, NULL);\n\t\t\tif (IS_ERR(session_keyring)) {\n\t\t\t\tret = PTR_ERR(session_keyring);\n\t\t\t\tgoto error_release;\n\t\t\t}\n\n\t\t\t/* we install a link from the user session keyring to\n\t\t\t * the user keyring */\n\t\t\tret = key_link(session_keyring, uid_keyring);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto error_release_both;\n\t\t}\n\n\t\t/* install the keyrings */\n\t\tuser->uid_keyring = uid_keyring;\n\t\tuser->session_keyring = session_keyring;\n\t}\n\n\tmutex_unlock(&key_user_keyring_mutex);\n\tkleave(\" = 0\");\n\treturn 0;\n\nerror_release_both:\n\tkey_put(session_keyring);\nerror_release:\n\tkey_put(uid_keyring);\nerror:\n\tmutex_unlock(&key_user_keyring_mutex);\n\tkleave(\" = %d\", ret);\n\treturn ret;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static void opl3_setup_voice(int dev, int voice, int chn)\n{\n\tstruct channel_info *info =\n\t&synth_devs[dev]->chn_info[chn];\n\n\topl3_set_instr(dev, voice, info->pgm_num);\n\n\tdevc->voc[voice].bender = 0;\n\tdevc->voc[voice].bender_range = info->bender_range;\n\tdevc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];\n\tdevc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;\n}", "label_name": "CWE-119", "label": 26}
{"code": "void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)\n{\n int width = decoder_info->width;\n int height = decoder_info->height;\n stream_t *stream = decoder_info->stream;\n frame_type_t frame_type = decoder_info->frame_info.frame_type;\n int split_flag = 0;\n\n if (yposY >= height || xposY >= width)\n return;\n\n int decode_this_size = (yposY + size <= height) && (xposY + size <= width);\n int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;\n\n int bit_start = stream->bitcnt;\n\n int mode = MODE_SKIP;\n \n block_context_t block_context;\n TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);\n decoder_info->block_context = &block_context;\n\n split_flag = decode_super_mode(decoder_info,size,decode_this_size);\n mode = decoder_info->mode;\n \n /* Read delta_qp and set block-level qp */\n if (size == (1<<decoder_info->log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {\n /* Read delta_qp */\n int delta_qp = read_delta_qp(stream);\n int prev_qp;\n if (yposY == 0 && xposY == 0)\n prev_qp = decoder_info->frame_info.qp;\n else\n prev_qp = decoder_info->frame_info.qpb;\n decoder_info->frame_info.qpb = prev_qp + delta_qp;\n }\n\n decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);\n\n if (split_flag){\n int new_size = size/2;\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);\n }\n else if (decode_this_size || decode_rectangular_size){\n decode_block(decoder_info,size,yposY,xposY,sub);\n }\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_comp rcomp;\n\n\tstrlcpy(rcomp.type, \"compression\", sizeof(rcomp.type));\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,\n\t\t sizeof(struct crypto_report_comp), &rcomp))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-200", "label": 10}
{"code": "static void stellaris_enet_unrealize(DeviceState *dev, Error **errp)\n{\n stellaris_enet_state *s = STELLARIS_ENET(dev);\n\n unregister_savevm(DEVICE(s), \"stellaris_enet\", s);\n\n memory_region_destroy(&s->mmio);\n}", "label_name": "CWE-119", "label": 26}
{"code": "static void perf_swevent_overflow(struct perf_event *event, u64 overflow,\n\t\t\t\t int nmi, struct perf_sample_data *data,\n\t\t\t\t struct pt_regs *regs)\n{\n\tstruct hw_perf_event *hwc = &event->hw;\n\tint throttle = 0;\n\n\tdata->period = event->hw.last_period;\n\tif (!overflow)\n\t\toverflow = perf_swevent_set_period(event);\n\n\tif (hwc->interrupts == MAX_INTERRUPTS)\n\t\treturn;\n\n\tfor (; overflow; overflow--) {\n\t\tif (__perf_event_overflow(event, nmi, throttle,\n\t\t\t\t\t data, regs)) {\n\t\t\t/*\n\t\t\t * We inhibit the overflow from happening when\n\t\t\t * hwc->interrupts == MAX_INTERRUPTS.\n\t\t\t */\n\t\t\tbreak;\n\t\t}\n\t\tthrottle = 1;\n\t}\n}", "label_name": "CWE-400", "label": 2}
{"code": "jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)\n{\n\tjpc_streamlist_t *streams;\n\tuchar *dataptr;\n\tuint_fast32_t datacnt;\n\tuint_fast32_t tpcnt;\n\tjpc_ppxstabent_t *ent;\n\tint entno;\n\tjas_stream_t *stream;\n\tint n;\n\n\tif (!(streams = jpc_streamlist_create())) {\n\t\tgoto error;\n\t}\n\n\tif (!tab->numents) {\n\t\treturn streams;\n\t}\n\n\tentno = 0;\n\tent = tab->ents[entno];\n\tdataptr = ent->data;\n\tdatacnt = ent->len;\n\tfor (;;) {\n\n\t\t/* Get the length of the packet header data for the current\n\t\t tile-part. */\n\t\tif (datacnt < 4) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(stream = jas_stream_memopen(0, 0))) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),\n\t\t stream)) {\n\t\t\tgoto error;\n\t\t}\n\t\ttpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)\n\t\t | dataptr[3];\n\t\tdatacnt -= 4;\n\t\tdataptr += 4;\n\n\t\t/* Get the packet header data for the current tile-part. */\n\t\twhile (tpcnt) {\n\t\t\tif (!datacnt) {\n\t\t\t\tif (++entno >= tab->numents) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tent = tab->ents[entno];\n\t\t\t\tdataptr = ent->data;\n\t\t\t\tdatacnt = ent->len;\n\t\t\t}\n\t\t\tn = JAS_MIN(tpcnt, datacnt);\n\t\t\tif (jas_stream_write(stream, dataptr, n) != n) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\ttpcnt -= n;\n\t\t\tdataptr += n;\n\t\t\tdatacnt -= n;\n\t\t}\n\t\tjas_stream_rewind(stream);\n\t\tif (!datacnt) {\n\t\t\tif (++entno >= tab->numents) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tent = tab->ents[entno];\n\t\t\tdataptr = ent->data;\n\t\t\tdatacnt = ent->len;\n\t\t}\n\t}\n\n\treturn streams;\n\nerror:\n\tif (streams) {\n\t\tjpc_streamlist_destroy(streams);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0}
{"code": "struct task_struct * __cpuinit fork_idle(int cpu)\n{\n\tstruct task_struct *task;\n\tstruct pt_regs regs;\n\n\ttask = copy_process(CLONE_VM, 0, idle_regs(®s), 0, NULL,\n\t\t\t &init_struct_pid, 0);\n\tif (!IS_ERR(task))\n\t\tinit_idle(task, cpu);\n\n\treturn task;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int su3000_frontend_attach(struct dvb_usb_adapter *d)\n{\n\tu8 obuf[3] = { 0xe, 0x80, 0 };\n\tu8 ibuf[] = { 0 };\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x02;\n\tobuf[2] = 1;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\tmsleep(300);\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x83;\n\tobuf[2] = 0;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0xe;\n\tobuf[1] = 0x83;\n\tobuf[2] = 1;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x0e transfer failed.\");\n\n\tobuf[0] = 0x51;\n\n\tif (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0)\n\t\terr(\"command 0x51 transfer failed.\");\n\n\td->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config,\n\t\t\t\t\t&d->dev->i2c_adap);\n\tif (d->fe_adap[0].fe == NULL)\n\t\treturn -EIO;\n\n\tif (dvb_attach(ts2020_attach, d->fe_adap[0].fe,\n\t\t\t\t&dw2104_ts2020_config,\n\t\t\t\t&d->dev->i2c_adap)) {\n\t\tinfo(\"Attached DS3000/TS2020!\");\n\t\treturn 0;\n\t}\n\n\tinfo(\"Failed to attach DS3000/TS2020!\");\n\treturn -EIO;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void device_init()\n{\n\n hw_init(LOW_FREQUENCY);\n\n if (! tsc_sensor_exists())\n {\n _NFC_status = nfc_init();\n }\n\n if (_NFC_status == NFC_IS_ACTIVE)\n {\n printf1(TAG_NFC, \"Have NFC\\r\\n\");\n isLowFreq = 1;\n IS_BUTTON_PRESSED = is_physical_button_pressed;\n }\n else\n {\n printf1(TAG_NFC, \"Have NO NFC\\r\\n\");\n hw_init(HIGH_FREQUENCY);\n isLowFreq = 0;\n device_init_button();\n }\n\n usbhid_init();\n ctaphid_init();\n ctap_init();\n\n device_migrate();\n\n#if BOOT_TO_DFU\n flash_option_bytes_init(1);\n#else\n flash_option_bytes_init(0);\n#endif\n\n\n}", "label_name": "CWE-326", "label": 9}
{"code": "static void read_module(RBuffer *b, ut64 addr, struct minidump_module *module) {\n\tst64 o_addr = r_buf_seek (b, 0, R_BUF_CUR);\n\tr_buf_seek (b, addr, R_BUF_SET);\n\tmodule->base_of_image = r_buf_read_le64 (b);\n\tmodule->size_of_image = r_buf_read_le32 (b);\n\tmodule->check_sum = r_buf_read_le32 (b);\n\tmodule->time_date_stamp = r_buf_read_le32 (b);\n\tmodule->module_name_rva = r_buf_read_le32 (b);\n\tmodule->version_info.dw_signature = r_buf_read_le32 (b);\n\tmodule->version_info.dw_struc_version = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_version_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_version_ls = r_buf_read_le32 (b);\n\tmodule->version_info.dw_product_version_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_product_version_ls = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_flags_mask = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_flags = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_os = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_type = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_subtype = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_date_ms = r_buf_read_le32 (b);\n\tmodule->version_info.dw_file_date_ls = r_buf_read_le32 (b);\n\tmodule->cv_record.data_size = r_buf_read_le32 (b);\n\tmodule->cv_record.rva = r_buf_read_le32 (b);\n\tmodule->misc_record.data_size = r_buf_read_le32 (b);\n\tmodule->misc_record.rva = r_buf_read_le32 (b);\n\tmodule->reserved_0 = r_buf_read_le64 (b);\n\tmodule->reserved_1 = r_buf_read_le64 (b);\n\tr_buf_seek (b, o_addr, R_BUF_SET);\n}", "label_name": "CWE-400", "label": 2}
{"code": "void user_describe(const struct key *key, struct seq_file *m)\n{\n\tseq_puts(m, key->description);\n\tif (key_is_instantiated(key))\n\t\tseq_printf(m, \": %u\", key->datalen);\n}", "label_name": "CWE-20", "label": 0}
{"code": "static VALUE cState_indent_set(VALUE self, VALUE indent)\n{\n unsigned long len;\n GET_STATE(self);\n Check_Type(indent, T_STRING);\n len = RSTRING_LEN(indent);\n if (len == 0) {\n if (state->indent) {\n ruby_xfree(state->indent);\n state->indent = NULL;\n state->indent_len = 0;\n }\n } else {\n if (state->indent) ruby_xfree(state->indent);\n state->indent = strdup(RSTRING_PTR(indent));\n state->indent_len = len;\n }\n return Qnil;\n}", "label_name": "CWE-119", "label": 26}
{"code": "void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,\n\t\t\t\tunsigned long end, unsigned long vmflag)\n{\n\tunsigned long addr;\n\t/* do a global flush by default */\n\tunsigned long base_pages_to_flush = TLB_FLUSH_ALL;\n\n\tpreempt_disable();\n\tif (current->active_mm != mm)\n\t\tgoto out;\n\n\tif (!current->mm) {\n\t\tleave_mm(smp_processor_id());\n\t\tgoto out;\n\t}\n\n\tif ((end != TLB_FLUSH_ALL) && !(vmflag & VM_HUGETLB))\n\t\tbase_pages_to_flush = (end - start) >> PAGE_SHIFT;\n\n\tif (base_pages_to_flush > tlb_single_page_flush_ceiling) {\n\t\tbase_pages_to_flush = TLB_FLUSH_ALL;\n\t\tcount_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);\n\t\tlocal_flush_tlb();\n\t} else {\n\t\t/* flush range by one by one 'invlpg' */\n\t\tfor (addr = start; addr < end;\taddr += PAGE_SIZE) {\n\t\t\tcount_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);\n\t\t\t__flush_tlb_single(addr);\n\t\t}\n\t}\n\ttrace_tlb_flush(TLB_LOCAL_MM_SHOOTDOWN, base_pages_to_flush);\nout:\n\tif (base_pages_to_flush == TLB_FLUSH_ALL) {\n\t\tstart = 0UL;\n\t\tend = TLB_FLUSH_ALL;\n\t}\n\tif (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids)\n\t\tflush_tlb_others(mm_cpumask(mm), mm, start, end);\n\tpreempt_enable();\n}", "label_name": "CWE-362", "label": 18}
{"code": "char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC)\n{\n\tchar buffer[4096];\n char buffer2[4096];\n\tchar *buf = buffer, *buf2 = buffer2, *d, *d_url;\n int l;\n\n\tif (name_len > sizeof(buffer)-2) {\n\t\tbuf = estrndup(name, name_len);\n\t} else {\n\t\tmemcpy(buf, name, name_len);\n\t\tbuf[name_len] = 0;\n\t}\n\t\n\tname_len = php_url_decode(buf, name_len);\n normalize_varname(buf);\n name_len = strlen(buf);\n\t\n\tif (SUHOSIN_G(cookie_plainlist)) {\n\t\tif (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) {\nencrypt_return_plain:\n\t\t\tif (buf != buffer) {\n\t\t\t\tefree(buf);\n\t\t\t}\n\t\t\treturn estrndup(value, value_len);\n\t\t}\n\t} else if (SUHOSIN_G(cookie_cryptlist)) {\n\t\tif (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) {\n\t\t\tgoto encrypt_return_plain;\n\t\t}\n\t}\n\t\n\tif (strlen(value) <= sizeof(buffer2)-2) {\n\t\tmemcpy(buf2, value, value_len);\n\t\tbuf2[value_len] = 0;\n\t} else {\n\t\tbuf2 = estrndup(value, value_len);\n\t}\n\t\n\tvalue_len = php_url_decode(buf2, value_len);\n\t\n\td = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC);\n\td_url = php_url_encode(d, strlen(d), &l);\n\tefree(d);\n if (buf != buffer) {\n\t\tefree(buf);\n\t}\n if (buf2 != buffer2) {\n\t\tefree(buf2);\n\t}\n\treturn d_url;\n}", "label_name": "CWE-119", "label": 26}
{"code": "struct dentry *debugfs_rename(struct dentry *old_dir, struct dentry *old_dentry,\n\t\tstruct dentry *new_dir, const char *new_name)\n{\n\tint error;\n\tstruct dentry *dentry = NULL, *trap;\n\tconst char *old_name;\n\n\ttrap = lock_rename(new_dir, old_dir);\n\t/* Source or destination directories don't exist? */\n\tif (d_really_is_negative(old_dir) || d_really_is_negative(new_dir))\n\t\tgoto exit;\n\t/* Source does not exist, cyclic rename, or mountpoint? */\n\tif (d_really_is_negative(old_dentry) || old_dentry == trap ||\n\t d_mountpoint(old_dentry))\n\t\tgoto exit;\n\tdentry = lookup_one_len(new_name, new_dir, strlen(new_name));\n\t/* Lookup failed, cyclic rename or target exists? */\n\tif (IS_ERR(dentry) || dentry == trap || d_really_is_positive(dentry))\n\t\tgoto exit;\n\n\told_name = fsnotify_oldname_init(old_dentry->d_name.name);\n\n\terror = simple_rename(d_inode(old_dir), old_dentry, d_inode(new_dir),\n\t\t\t dentry, 0);\n\tif (error) {\n\t\tfsnotify_oldname_free(old_name);\n\t\tgoto exit;\n\t}\n\td_move(old_dentry, dentry);\n\tfsnotify_move(d_inode(old_dir), d_inode(new_dir), old_name,\n\t\td_is_dir(old_dentry),\n\t\tNULL, old_dentry);\n\tfsnotify_oldname_free(old_name);\n\tunlock_rename(new_dir, old_dir);\n\tdput(dentry);\n\treturn old_dentry;\nexit:\n\tif (dentry && !IS_ERR(dentry))\n\t\tdput(dentry);\n\tunlock_rename(new_dir, old_dir);\n\treturn NULL;\n}", "label_name": "CWE-362", "label": 18}
{"code": "error_t lpc546xxEthSendPacket(NetInterface *interface,\n const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)\n{\n size_t length;\n\n //Retrieve the length of the packet\n length = netBufferGetLength(buffer) - offset;\n\n //Check the frame length\n if(length > LPC546XX_ETH_TX_BUFFER_SIZE)\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n //Report an error\n return ERROR_INVALID_LENGTH;\n }\n\n //Make sure the current buffer is available for writing\n if((txDmaDesc[txIndex].tdes3 & ENET_TDES3_OWN) != 0)\n {\n return ERROR_FAILURE;\n }\n\n //Copy user data to the transmit buffer\n netBufferRead(txBuffer[txIndex], buffer, offset, length);\n\n //Set the start address of the buffer\n txDmaDesc[txIndex].tdes0 = (uint32_t) txBuffer[txIndex];\n //Write the number of bytes to send\n txDmaDesc[txIndex].tdes2 = ENET_TDES2_IOC | (length & ENET_TDES2_B1L);\n //Give the ownership of the descriptor to the DMA\n txDmaDesc[txIndex].tdes3 = ENET_TDES3_OWN | ENET_TDES3_FD | ENET_TDES3_LD;\n\n //Clear TBU flag to resume processing\n ENET->DMA_CH[0].DMA_CHX_STAT = ENET_DMA_CH_DMA_CHX_STAT_TBU_MASK;\n //Instruct the DMA to poll the transmit descriptor list\n ENET->DMA_CH[0].DMA_CHX_TXDESC_TAIL_PTR = 0;\n\n //Increment index and wrap around if necessary\n if(++txIndex >= LPC546XX_ETH_TX_BUFFER_COUNT)\n {\n txIndex = 0;\n }\n\n //Check whether the next buffer is available for writing\n if((txDmaDesc[txIndex].tdes3 & ENET_TDES3_OWN) == 0)\n {\n //The transmitter can accept another packet\n osSetEvent(&interface->nicTxEvent);\n }\n\n //Data successfully written\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": 0}
{"code": "void test_checkout_nasty__git_tilde1(void)\n{\n#ifdef GIT_WIN32\n\ttest_checkout_fails(\"refs/heads/git_tilde1\", \".git/foobar\");\n#endif\n}", "label_name": "CWE-706", "label": 29}
{"code": "error_t tja1100Init(NetInterface *interface)\n{\n uint16_t value;\n\n //Debug message\n TRACE_INFO(\"Initializing TJA1100...\\r\\n\");\n\n //Undefined PHY address?\n if(interface->phyAddr >= 32)\n {\n //Use the default address\n interface->phyAddr = TJA1100_PHY_ADDR;\n }\n\n //Initialize serial management interface\n if(interface->smiDriver != NULL)\n {\n interface->smiDriver->init();\n }\n\n //Initialize external interrupt line driver\n if(interface->extIntDriver != NULL)\n {\n interface->extIntDriver->init();\n }\n\n //Reset PHY transceiver\n tja1100WritePhyReg(interface, TJA1100_BASIC_CTRL,\n TJA1100_BASIC_CTRL_RESET);\n\n //Wait for the reset to complete\n while(tja1100ReadPhyReg(interface, TJA1100_BASIC_CTRL) &\n TJA1100_BASIC_CTRL_RESET)\n {\n }\n\n //Dump PHY registers for debugging purpose\n tja1100DumpPhyReg(interface);\n\n //Enable configuration register access\n value = tja1100ReadPhyReg(interface, TJA1100_EXTENDED_CTRL);\n value |= TJA1100_EXTENDED_CTRL_CONFIG_EN;\n tja1100WritePhyReg(interface, TJA1100_EXTENDED_CTRL, value);\n\n //Select RMII mode (25MHz XTAL)\n value = tja1100ReadPhyReg(interface, TJA1100_CONFIG1);\n value &= ~TJA1100_CONFIG1_MII_MODE;\n value |= TJA1100_CONFIG1_MII_MODE_RMII_25MHZ;\n tja1100WritePhyReg(interface, TJA1100_CONFIG1, value);\n\n //The PHY is configured for autonomous operation\n value = tja1100ReadPhyReg(interface, TJA1100_CONFIG1);\n value |= TJA1100_CONFIG1_AUTO_OP;\n tja1100WritePhyReg(interface, TJA1100_CONFIG1, value);\n\n //Force the TCP/IP stack to poll the link state at startup\n interface->phyEvent = TRUE;\n //Notify the TCP/IP stack of the event\n osSetEvent(&netEvent);\n\n //Successful initialization\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 4, &tmp))\n\t\treturn -1;\n\t*val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) &\n\t 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp);\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void test_show_object(struct object *object,\n\t\t\t struct strbuf *path,\n\t\t\t const char *last, void *data)\n{\n\tstruct bitmap_test_data *tdata = data;\n\tint bitmap_pos;\n\n\tbitmap_pos = bitmap_position(object->oid.hash);\n\tif (bitmap_pos < 0)\n\t\tdie(\"Object not in bitmap: %s\\n\", oid_to_hex(&object->oid));\n\n\tbitmap_set(tdata->base, bitmap_pos);\n\tdisplay_progress(tdata->prg, ++tdata->seen);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void show_object_with_name(FILE *out, struct object *obj,\n\t\t\t struct strbuf *path, const char *component)\n{\n\tchar *name = path_name(path, component);\n\tchar *p;\n\n\tfprintf(out, \"%s \", oid_to_hex(&obj->oid));\n\tfor (p = name; *p && *p != '\\n'; p++)\n\t\tfputc(*p, out);\n\tfputc('\\n', out);\n\n\tfree(name);\n}", "label_name": "CWE-119", "label": 26}
{"code": "static pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn,\n\t\t\t unsigned long size)\n{\n\tgfn_t end_gfn;\n\tpfn_t pfn;\n\n\tpfn = gfn_to_pfn_memslot(slot, gfn);\n\tend_gfn = gfn + (size >> PAGE_SHIFT);\n\tgfn += 1;\n\n\tif (is_error_noslot_pfn(pfn))\n\t\treturn pfn;\n\n\twhile (gfn < end_gfn)\n\t\tgfn_to_pfn_memslot(slot, gfn++);\n\n\treturn pfn;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\tstruct msghdr *msg, size_t len, int noblock,\n\t\t\tint flags, int *addr_len)\n{\n\tstruct sk_buff *skb = NULL;\n\tstruct sockaddr_pn sa;\n\tint rval = -EOPNOTSUPP;\n\tint copylen;\n\n\tif (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|\n\t\t\tMSG_CMSG_COMPAT))\n\t\tgoto out_nofree;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(sa);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n\tif (skb == NULL)\n\t\tgoto out_nofree;\n\n\tpn_skb_get_src_sockaddr(skb, &sa);\n\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\trval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);\n\tif (rval) {\n\t\trval = -EFAULT;\n\t\tgoto out;\n\t}\n\n\trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n\n\tif (msg->msg_name != NULL)\n\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n\nout:\n\tskb_free_datagram(sk, skb);\n\nout_nofree:\n\treturn rval;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void command_port_read_callback(struct urb *urb)\n{\n\tstruct usb_serial_port *command_port = urb->context;\n\tstruct whiteheat_command_private *command_info;\n\tint status = urb->status;\n\tunsigned char *data = urb->transfer_buffer;\n\tint result;\n\n\tcommand_info = usb_get_serial_port_data(command_port);\n\tif (!command_info) {\n\t\tdev_dbg(&urb->dev->dev, \"%s - command_info is NULL, exiting.\\n\", __func__);\n\t\treturn;\n\t}\n\tif (status) {\n\t\tdev_dbg(&urb->dev->dev, \"%s - nonzero urb status: %d\\n\", __func__, status);\n\t\tif (status != -ENOENT)\n\t\t\tcommand_info->command_finished = WHITEHEAT_CMD_FAILURE;\n\t\twake_up(&command_info->wait_command);\n\t\treturn;\n\t}\n\n\tusb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data);\n\n\tif (data[0] == WHITEHEAT_CMD_COMPLETE) {\n\t\tcommand_info->command_finished = WHITEHEAT_CMD_COMPLETE;\n\t\twake_up(&command_info->wait_command);\n\t} else if (data[0] == WHITEHEAT_CMD_FAILURE) {\n\t\tcommand_info->command_finished = WHITEHEAT_CMD_FAILURE;\n\t\twake_up(&command_info->wait_command);\n\t} else if (data[0] == WHITEHEAT_EVENT) {\n\t\t/* These are unsolicited reports from the firmware, hence no\n\t\t waiting command to wakeup */\n\t\tdev_dbg(&urb->dev->dev, \"%s - event received\\n\", __func__);\n\t} else if (data[0] == WHITEHEAT_GET_DTR_RTS) {\n\t\tmemcpy(command_info->result_buffer, &data[1],\n\t\t\t\t\t\turb->actual_length - 1);\n\t\tcommand_info->command_finished = WHITEHEAT_CMD_COMPLETE;\n\t\twake_up(&command_info->wait_command);\n\t} else\n\t\tdev_dbg(&urb->dev->dev, \"%s - bad reply from firmware\\n\", __func__);\n\n\t/* Continue trying to always read */\n\tresult = usb_submit_urb(command_port->read_urb, GFP_ATOMIC);\n\tif (result)\n\t\tdev_dbg(&urb->dev->dev, \"%s - failed resubmitting read urb, error %d\\n\",\n\t\t\t__func__, result);\n}", "label_name": "CWE-119", "label": 26}
{"code": "static void smp_task_done(struct sas_task *task)\n{\n\tif (!del_timer(&task->slow_task->timer))\n\t\treturn;\n\tcomplete(&task->slow_task->completion);\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int hns_xgmac_get_sset_count(int stringset)\n{\n\tif (stringset == ETH_SS_STATS)\n\t\treturn ARRAY_SIZE(g_xgmac_stats_string);\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)\n{\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tunsigned char *p;\n\tint ok = 0;\n\tint r;\n\tsize_t len;\n\n\tsc_format_path(str_path, &path);\n\tif (SC_SUCCESS != sc_select_file(card, &path, &file)) {\n\t\tgoto err;\n\t}\n\n\tlen = file ? file->size : 4096;\n\tp = realloc(*data, len);\n\tif (!p) {\n\t\tgoto err;\n\t}\n\t*data = p;\n\t*data_len = len;\n\n\tr = sc_read_binary(card, 0, p, len, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\t*data_len = r;\n\tok = 1;\n\nerr:\n\tsc_file_free(file);\n\n\treturn ok;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int install_thread_keyring(void)\n{\n\tstruct cred *new;\n\tint ret;\n\n\tnew = prepare_creds();\n\tif (!new)\n\t\treturn -ENOMEM;\n\n\tBUG_ON(new->thread_keyring);\n\n\tret = install_thread_keyring_to_cred(new);\n\tif (ret < 0) {\n\t\tabort_creds(new);\n\t\treturn ret;\n\t}\n\n\treturn commit_creds(new);\n}", "label_name": "CWE-404", "label": 30}
{"code": "static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\tstruct msghdr *msg, size_t len, int noblock,\n\t\t\tint flags, int *addr_len)\n{\n\tstruct sk_buff *skb = NULL;\n\tstruct sockaddr_pn sa;\n\tint rval = -EOPNOTSUPP;\n\tint copylen;\n\n\tif (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|\n\t\t\tMSG_CMSG_COMPAT))\n\t\tgoto out_nofree;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(sa);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n\tif (skb == NULL)\n\t\tgoto out_nofree;\n\n\tpn_skb_get_src_sockaddr(skb, &sa);\n\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\trval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);\n\tif (rval) {\n\t\trval = -EFAULT;\n\t\tgoto out;\n\t}\n\n\trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n\n\tif (msg->msg_name != NULL)\n\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n\nout:\n\tskb_free_datagram(sk, skb);\n\nout_nofree:\n\treturn rval;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int hash_recvmsg(struct kiocb *unused, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tunsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));\n\tint err;\n\n\tif (len > ds)\n\t\tlen = ds;\n\telse if (len < ds)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tmsg->msg_namelen = 0;\n\n\tlock_sock(sk);\n\tif (ctx->more) {\n\t\tctx->more = 0;\n\t\tahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);\n\t\terr = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),\n\t\t\t\t\t\t &ctx->completion);\n\t\tif (err)\n\t\t\tgoto unlock;\n\t}\n\n\terr = memcpy_toiovec(msg->msg_iov, ctx->result, len);\n\nunlock:\n\trelease_sock(sk);\n\n\treturn err ?: len;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int pfkey_recvmsg(struct kiocb *kiocb,\n\t\t\t struct socket *sock, struct msghdr *msg, size_t len,\n\t\t\t int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct pfkey_sock *pfk = pfkey_sk(sk);\n\tstruct sk_buff *skb;\n\tint copied, err;\n\n\terr = -EINVAL;\n\tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n\t\tgoto out;\n\n\tmsg->msg_namelen = 0;\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n\tif (skb == NULL)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (copied > len) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto out_free;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\terr = (flags & MSG_TRUNC) ? skb->len : copied;\n\n\tif (pfk->dump.dump != NULL &&\n\t 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)\n\t\tpfkey_do_dump(pfk);\n\nout_free:\n\tskb_free_datagram(sk, skb);\nout:\n\treturn err;\n}", "label_name": "CWE-20", "label": 0}
{"code": "unsigned paravirt_patch_call(void *insnbuf,\n\t\t\t const void *target, u16 tgt_clobbers,\n\t\t\t unsigned long addr, u16 site_clobbers,\n\t\t\t unsigned len)\n{\n\tstruct branch *b = insnbuf;\n\tunsigned long delta = (unsigned long)target - (addr+5);\n\n\tif (tgt_clobbers & ~site_clobbers)\n\t\treturn len;\t/* target would clobber too much for this site */\n\tif (len < 5)\n\t\treturn len;\t/* call too long for patch site */\n\n\tb->opcode = 0xe8; /* call */\n\tb->delta = delta;\n\tBUILD_BUG_ON(sizeof(*b) != 5);\n\n\treturn 5;\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int do_remount(struct path *path, int flags, int mnt_flags,\n\t\t void *data)\n{\n\tint err;\n\tstruct super_block *sb = path->mnt->mnt_sb;\n\tstruct mount *mnt = real_mount(path->mnt);\n\n\tif (!check_mnt(mnt))\n\t\treturn -EINVAL;\n\n\tif (path->dentry != path->mnt->mnt_root)\n\t\treturn -EINVAL;\n\n\terr = security_sb_remount(sb, data);\n\tif (err)\n\t\treturn err;\n\n\tdown_write(&sb->s_umount);\n\tif (flags & MS_BIND)\n\t\terr = change_mount_flags(path->mnt, flags);\n\telse if (!capable(CAP_SYS_ADMIN))\n\t\terr = -EPERM;\n\telse\n\t\terr = do_remount_sb(sb, flags, data, 0);\n\tif (!err) {\n\t\tlock_mount_hash();\n\t\tmnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;\n\t\tmnt->mnt.mnt_flags = mnt_flags;\n\t\ttouch_mnt_namespace(mnt->mnt_ns);\n\t\tunlock_mount_hash();\n\t}\n\tup_write(&sb->s_umount);\n\treturn err;\n}", "label_name": "CWE-269", "label": 6}
{"code": "static void coerce_reg_to_32(struct bpf_reg_state *reg)\n{\n\t/* clear high 32 bits */\n\treg->var_off = tnum_cast(reg->var_off, 4);\n\t/* Update bounds */\n\t__update_reg_bounds(reg);\n}", "label_name": "CWE-119", "label": 26}
{"code": "newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)\n{\n\tstruct sshbuf *b;\n\tstruct sshcipher_ctx *cc;\n\tstruct sshcomp *comp;\n\tstruct sshenc *enc;\n\tstruct sshmac *mac;\n\tstruct newkeys *newkey;\n\tint r;\n\n\tif ((newkey = ssh->state->newkeys[mode]) == NULL)\n\t\treturn SSH_ERR_INTERNAL_ERROR;\n\tenc = &newkey->enc;\n\tmac = &newkey->mac;\n\tcomp = &newkey->comp;\n\tcc = (mode == MODE_OUT) ? ssh->state->send_context :\n\t ssh->state->receive_context;\n\tif ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)\n\t\treturn r;\n\tif ((b = sshbuf_new()) == NULL)\n\t\treturn SSH_ERR_ALLOC_FAIL;\n\t/* The cipher struct is constant and shared, you export pointer */\n\tif ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||\n\t (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||\n\t (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||\n\t (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||\n\t (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||\n\t (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)\n\t\tgoto out;\n\tif (cipher_authlen(enc->cipher) == 0) {\n\t\tif ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||\n\t\t (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||\n\t\t (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)\n\t\t\tgoto out;\n\t}\n\tif ((r = sshbuf_put_u32(b, comp->type)) != 0 ||\n\t (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||\n\t (r = sshbuf_put_cstring(b, comp->name)) != 0)\n\t\tgoto out;\n\tr = sshbuf_put_stringb(m, b);\n out:\n\tsshbuf_free(b);\n\treturn r;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)\n{\n const uint8_t *frame_start = frame;\n const uint8_t *frame_end = frame + width * height;\n int mask = 0x10000, bitbuf = 0;\n int i, v, offset, count, segments;\n\n segments = bytestream2_get_le16(gb);\n while (segments--) {\n if (bytestream2_get_bytes_left(gb) < 2)\n return AVERROR_INVALIDDATA;\n if (mask == 0x10000) {\n bitbuf = bytestream2_get_le16u(gb);\n mask = 1;\n }\n\n if (bitbuf & mask) {\n v = bytestream2_get_le16(gb);\n offset = (v & 0x1FFF) << 2;\n count = ((v >> 13) + 2) << 1;\n if (frame - frame_start < offset || frame_end - frame < count*2 + width)\n return AVERROR_INVALIDDATA;\n for (i = 0; i < count; i++) {\n frame[0] = frame[1] =\n frame[width] = frame[width + 1] = frame[-offset];\n\n frame += 2;\n }\n } else if (bitbuf & (mask << 1)) {\n v = bytestream2_get_le16(gb)*2;\n if (frame - frame_end < v)\n return AVERROR_INVALIDDATA;\n frame += v;\n } else {\n if (frame_end - frame < width + 3)\n return AVERROR_INVALIDDATA;\n frame[0] = frame[1] =\n frame[width] = frame[width + 1] = bytestream2_get_byte(gb);\n frame += 2;\n frame[0] = frame[1] =\n frame[width] = frame[width + 1] = bytestream2_get_byte(gb);\n frame += 2;\n }\n mask <<= 2;\n }\n\n return 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\tTIFFPredictorState* sp = PredictorState(tif);\n\ttmsize_t stride = sp->stride;\n\tuint32 *wp = (uint32*) cp0;\n\ttmsize_t wc = cc/4;\n\n\tassert((cc%(4*stride))==0);\n\n\tif (wc > stride) {\n\t\twc -= stride;\n\t\twp += wc - 1;\n\t\tdo {\n\t\t\tREPEAT4(stride, wp[stride] -= wp[0]; wp--)\n\t\t\twc -= stride;\n\t\t} while (wc > 0);\n\t}\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int nr_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;\n\tsize_t copied;\n\tstruct sk_buff *skb;\n\tint er;\n\n\t/*\n\t * This works for seqpacket too. The receiver has ordered the queue for\n\t * us! We do one quick check first though\n\t */\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_ESTABLISHED) {\n\t\trelease_sock(sk);\n\t\treturn -ENOTCONN;\n\t}\n\n\t/* Now we can treat all alike */\n\tif ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\ter = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (er < 0) {\n\t\tskb_free_datagram(sk, skb);\n\t\trelease_sock(sk);\n\t\treturn er;\n\t}\n\n\tif (sax != NULL) {\n\t\tmemset(sax, 0, sizeof(sax));\n\t\tsax->sax25_family = AF_NETROM;\n\t\tskb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,\n\t\t\t AX25_ADDR_LEN);\n\t}\n\n\tmsg->msg_namelen = sizeof(*sax);\n\n\tskb_free_datagram(sk, skb);\n\n\trelease_sock(sk);\n\treturn copied;\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\tops->destroy(dev);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)\n{\n return snprintf(dest, destlen, \"%s.hcache\", path);\n}", "label_name": "CWE-119", "label": 26}
{"code": "void svhandler_flash_pgm_word(void) {\n uint32_t dst = _param_1;\n uint32_t src = _param_2;\n\n // Do not allow firmware to erase bootstrap or bootloader sectors.\n if ((dst >= BSTRP_FLASH_SECT_START) &&\n (dst <= (BSTRP_FLASH_SECT_START + BSTRP_FLASH_SECT_LEN))) {\n return;\n }\n\n if ((dst >= BLDR_FLASH_SECT_START) &&\n (dst <= (BLDR_FLASH_SECT_START + 2 * BLDR_FLASH_SECT_LEN))) {\n return;\n }\n\n // Unlock flash.\n flash_clear_status_flags();\n flash_unlock();\n\n // Flash write.\n flash_program_word(dst, src);\n _param_1 = !!flash_chk_status();\n _param_2 = 0;\n _param_3 = 0;\n\n // Wait for any write operation to complete.\n flash_wait_for_last_operation();\n\n // Disable writes to flash.\n FLASH_CR &= ~FLASH_CR_PG;\n\n // Lock flash register\n FLASH_CR |= FLASH_CR_LOCK;\n}", "label_name": "CWE-668", "label": 7}
{"code": "int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,\n\t\tsize_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct atm_vcc *vcc;\n\tstruct sk_buff *skb;\n\tint copied, error = -EINVAL;\n\n\tmsg->msg_namelen = 0;\n\n\tif (sock->state != SS_CONNECTED)\n\t\treturn -ENOTCONN;\n\n\t/* only handle MSG_DONTWAIT and MSG_PEEK */\n\tif (flags & ~(MSG_DONTWAIT | MSG_PEEK))\n\t\treturn -EOPNOTSUPP;\n\n\tvcc = ATM_SD(sock);\n\tif (test_bit(ATM_VF_RELEASED, &vcc->flags) ||\n\t test_bit(ATM_VF_CLOSE, &vcc->flags) ||\n\t !test_bit(ATM_VF_READY, &vcc->flags))\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);\n\tif (!skb)\n\t\treturn error;\n\n\tcopied = skb->len;\n\tif (copied > size) {\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\terror = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (error)\n\t\treturn error;\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\tif (!(flags & MSG_PEEK)) {\n\t\tpr_debug(\"%d -= %d\\n\", atomic_read(&sk->sk_rmem_alloc),\n\t\t\t skb->truesize);\n\t\tatm_return(vcc, skb->truesize);\n\t}\n\n\tskb_free_datagram(sk, skb);\n\treturn copied;\n}", "label_name": "CWE-20", "label": 0}
{"code": "void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)\n{\n\tvcpu->arch.apic->vapic_addr = vapic_addr;\n\tif (vapic_addr)\n\t\t__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);\n\telse\n\t\t__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int rawsock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied;\n\tint rc;\n\n\tpr_debug(\"sock=%p sk=%p len=%zu flags=%d\\n\", sock, sk, len, flags);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rc);\n\tif (!skb)\n\t\treturn rc;\n\n\tmsg->msg_namelen = 0;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\trc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tskb_free_datagram(sk, skb);\n\n\treturn rc ? : copied;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int handle_emulation_failure(struct kvm_vcpu *vcpu)\n{\n\t++vcpu->stat.insn_emulation_fail;\n\ttrace_kvm_emulate_insn_failed(vcpu);\n\tvcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;\n\tvcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;\n\tvcpu->run->internal.ndata = 0;\n\tkvm_queue_exception(vcpu, UD_VECTOR);\n\treturn EMULATE_FAIL;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)\n{\n\tif (file->f_flags & O_DSYNC)\n\t\treturn 0;\n\tif (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))\n\t\treturn 1;\n\tif (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||\n\t\t\t(inode->i_flock->fl_start == 0 &&\n\t\t\tinode->i_flock->fl_end == OFFSET_MAX &&\n\t\t\tinode->i_flock->fl_type != F_RDLCK)))\n\t\treturn 1;\n\treturn 0;\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int ptrace_check_attach(struct task_struct *child, bool ignore_state)\n{\n\tint ret = -ESRCH;\n\n\t/*\n\t * We take the read lock around doing both checks to close a\n\t * possible race where someone else was tracing our child and\n\t * detached between these two checks. After this locked check,\n\t * we are sure that this is our traced child and that can only\n\t * be changed by us so it's not changing right after this.\n\t */\n\tread_lock(&tasklist_lock);\n\tif ((child->ptrace & PT_PTRACED) && child->parent == current) {\n\t\t/*\n\t\t * child->sighand can't be NULL, release_task()\n\t\t * does ptrace_unlink() before __exit_signal().\n\t\t */\n\t\tspin_lock_irq(&child->sighand->siglock);\n\t\tWARN_ON_ONCE(task_is_stopped(child));\n\t\tif (ignore_state || (task_is_traced(child) &&\n\t\t\t\t !(child->jobctl & JOBCTL_LISTENING)))\n\t\t\tret = 0;\n\t\tspin_unlock_irq(&child->sighand->siglock);\n\t}\n\tread_unlock(&tasklist_lock);\n\n\tif (!ret && !ignore_state)\n\t\tret = wait_task_inactive(child, TASK_TRACED) ? 0 : -ESRCH;\n\n\t/* All systems go.. */\n\treturn ret;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static inline int verify_replay(struct xfrm_usersa_info *p,\n\t\t\t\tstruct nlattr **attrs)\n{\n\tstruct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];\n\n\tif ((p->flags & XFRM_STATE_ESN) && !rt)\n\t\treturn -EINVAL;\n\n\tif (!rt)\n\t\treturn 0;\n\n\tif (p->id.proto != IPPROTO_ESP)\n\t\treturn -EINVAL;\n\n\tif (p->replay_window != 0)\n\t\treturn -EINVAL;\n\n\treturn 0;\n}", "label_name": "CWE-200", "label": 10}
{"code": "void Huff_Compress(msg_t *mbuf, int offset) {\n\tint\t\t\ti, ch, size;\n\tbyte\t\tseq[65536];\n\tbyte*\t\tbuffer;\n\thuff_t\t\thuff;\n\n\tsize = mbuf->cursize - offset;\n\tbuffer = mbuf->data+ + offset;\n\n\tif (size<=0) {\n\t\treturn;\n\t}\n\n\tCom_Memset(&huff, 0, sizeof(huff_t));\n\t// Add the NYT (not yet transmitted) node into the tree/list */\n\thuff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);\n\thuff.tree->symbol = NYT;\n\thuff.tree->weight = 0;\n\thuff.lhead->next = huff.lhead->prev = NULL;\n\thuff.tree->parent = huff.tree->left = huff.tree->right = NULL;\n\n\tseq[0] = (size>>8);\n\tseq[1] = size&0xff;\n\n\tbloc = 16;\n\n\tfor (i=0; i<size; i++ ) {\n\t\tch = buffer[i];\n\t\tHuff_transmit(&huff, ch, seq);\t\t\t\t\t\t/* Transmit symbol */\n\t\tHuff_addRef(&huff, (byte)ch);\t\t\t\t\t\t\t\t/* Do update */\n\t}\n\n\tbloc += 8;\t\t\t\t\t\t\t\t\t\t\t\t// next byte\n\n\tmbuf->cursize = (bloc>>3) + offset;\n\tCom_Memcpy(mbuf->data+offset, seq, (bloc>>3));\n}", "label_name": "CWE-119", "label": 26}
{"code": "asmlinkage void user_unaligned_trap(struct pt_regs *regs, unsigned int insn)\n{\n\tenum direction dir;\n\n\tif(!(current->thread.flags & SPARC_FLAG_UNALIGNED) ||\n\t (((insn >> 30) & 3) != 3))\n\t\tgoto kill_user;\n\tdir = decode_direction(insn);\n\tif(!ok_for_user(regs, insn, dir)) {\n\t\tgoto kill_user;\n\t} else {\n\t\tint err, size = decode_access_size(insn);\n\t\tunsigned long addr;\n\n\t\tif(floating_point_load_or_store_p(insn)) {\n\t\t\tprintk(\"User FPU load/store unaligned unsupported.\\n\");\n\t\t\tgoto kill_user;\n\t\t}\n\n\t\taddr = compute_effective_address(regs, insn);\n\t\tperf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr);\n\t\tswitch(dir) {\n\t\tcase load:\n\t\t\terr = do_int_load(fetch_reg_addr(((insn>>25)&0x1f),\n\t\t\t\t\t\t\t regs),\n\t\t\t\t\t size, (unsigned long *) addr,\n\t\t\t\t\t decode_signedness(insn));\n\t\t\tbreak;\n\n\t\tcase store:\n\t\t\terr = do_int_store(((insn>>25)&0x1f), size,\n\t\t\t\t\t (unsigned long *) addr, regs);\n\t\t\tbreak;\n\n\t\tcase both:\n\t\t\t/*\n\t\t\t * This was supported in 2.4. However, we question\n\t\t\t * the value of SWAP instruction across word boundaries.\n\t\t\t */\n\t\t\tprintk(\"Unaligned SWAP unsupported.\\n\");\n\t\t\terr = -EFAULT;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tunaligned_panic(\"Impossible user unaligned trap.\");\n\t\t\tgoto out;\n\t\t}\n\t\tif (err)\n\t\t\tgoto kill_user;\n\t\telse\n\t\t\tadvance(regs);\n\t\tgoto out;\n\t}\n\nkill_user:\n\tuser_mna_trap_fault(regs, insn);\nout:\n\t;\n}", "label_name": "CWE-400", "label": 2}
{"code": "is_link_trusted (NautilusFile *file,\n gboolean is_launcher)\n{\n GFile *location;\n gboolean res;\n\n if (!is_launcher)\n {\n return TRUE;\n }\n\n if (nautilus_file_can_execute (file))\n {\n return TRUE;\n }\n\n res = FALSE;\n\n if (nautilus_file_is_local (file))\n {\n location = nautilus_file_get_location (file);\n res = nautilus_is_in_system_dir (location);\n g_object_unref (location);\n }\n\n return res;\n}", "label_name": "CWE-20", "label": 0}
{"code": "int mesg_make_query (u_char *qname, uint16_t qtype, uint16_t qclass,\n\t\t uint32_t id, int rd, u_char *buf, int buflen) {\n\tchar *fn = \"mesg_make_query()\";\n\tu_char *ucp;\n\tint i, written_len;\n\tMesg_Hdr *hdr;\n\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"%s: (qtype: %s, id: %d): start\", fn,\n\t\t\tstring_rtype (qtype), id);\n\n\thdr = (Mesg_Hdr *) buf;\n\n\t/* write header */\n\thdr->id = id;\n\thdr->opcode = OP_QUERY;\n\thdr->rcode = RC_OK;\n\thdr->rd = rd;\n\thdr->qr = hdr->aa = hdr->tc = hdr->ra = hdr->zero = 0;\n\thdr->qdcnt = ntohs (1);\n\thdr->ancnt = hdr->nscnt = hdr->arcnt = ntohs (0);\n\n\twritten_len = sizeof (Mesg_Hdr);\n\tucp = (u_char *) (hdr + 1);\n\n\t/* write qname */\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"%s: qname offset = %zd\", fn, ucp - buf);\n\n\ti = dname_copy (qname, ucp, buflen - written_len);\n\tif (i < 0)\n\t\treturn -1;\n\n\twritten_len += i;\n\tucp += i;\n\n\t/* write qtype / qclass */\n\tif (T.debug > 4)\n\t\tsyslog (LOG_DEBUG, \"%s: qtype/qclass offset = %zd\",\n\t\t\tfn, ucp - buf);\n\n\twritten_len += sizeof (uint16_t) * 2;\n\tif (written_len > buflen)\n\t\treturn -1;\n\n\tPUTSHORT (qtype, ucp);\n\tPUTSHORT (qclass, ucp);\n\n\treturn written_len;\n}", "label_name": "CWE-330", "label": 12}
{"code": "static int persistent_prepare_exception(struct dm_exception_store *store,\n\t\t\t\t\tstruct dm_exception *e)\n{\n\tstruct pstore *ps = get_info(store);\n\tuint32_t stride;\n\tchunk_t next_free;\n\tsector_t size = get_dev_size(dm_snap_cow(store->snap)->bdev);\n\n\t/* Is there enough room ? */\n\tif (size < ((ps->next_free + 1) * store->chunk_size))\n\t\treturn -ENOSPC;\n\n\te->new_chunk = ps->next_free;\n\n\t/*\n\t * Move onto the next free pending, making sure to take\n\t * into account the location of the metadata chunks.\n\t */\n\tstride = (ps->exceptions_per_area + 1);\n\tnext_free = ++ps->next_free;\n\tif (sector_div(next_free, stride) == 1)\n\t\tps->next_free++;\n\n\tatomic_inc(&ps->pending_count);\n\treturn 0;\n}", "label_name": "CWE-200", "label": 10}
{"code": "struct r_bin_pe_addr_t *PE_(check_unknow)(RBinPEObj *pe) {\n\tstruct r_bin_pe_addr_t *entry;\n\tif (!pe || !pe->b) {\n\t\treturn 0LL;\n\t}\n\tut8 b[512];\n\tZERO_FILL (b);\n\tentry = PE_ (r_bin_pe_get_entrypoint) (pe);\n\t// option2: /x 8bff558bec83ec20\n\tif (r_buf_read_at (pe->b, entry->paddr, b, 512) < 1) {\n\t\tpe_printf (\"Warning: Cannot read entry at 0x%08\"PFMT64x\"\\n\", entry->paddr);\n\t\tfree (entry);\n\t\treturn NULL;\n\t}\n\t/* Decode the jmp instruction, this gets the address of the 'main'\n\t function for PE produced by a compiler whose name someone forgot to\n\t write down. */\n\t// this is dirty only a single byte check, can return false positives\n\tif (b[367] == 0xe8) {\n\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, 367);\n\t\treturn entry;\n\t}\n\tsize_t i;\n\tfor (i = 0; i < 512 - 16 ; i++) {\n\t\t// 5. ff 15 .. .. .. .. 50 e8 [main]\n\t\tif (!memcmp (b + i, \"\\xff\\x15\", 2)) {\n\t\t\tif (b[i + 6] == 0x50) {\n\t\t\t\tif (b[i + 7] == 0xe8) {\n\t\t\t\t\tfollow_offset (entry, pe->b, b, sizeof (b), pe->big_endian, i + 7);\n\t\t\t\t\treturn entry;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfree (entry);\n\treturn NULL;\n}", "label_name": "CWE-400", "label": 2}
{"code": "static void perf_event_task_output(struct perf_event *event,\n\t\t\t\t struct perf_task_event *task_event)\n{\n\tstruct perf_output_handle handle;\n\tstruct perf_sample_data\tsample;\n\tstruct task_struct *task = task_event->task;\n\tint ret, size = task_event->event_id.header.size;\n\n\tperf_event_header__init_id(&task_event->event_id.header, &sample, event);\n\n\tret = perf_output_begin(&handle, event,\n\t\t\t\ttask_event->event_id.header.size, 0, 0);\n\tif (ret)\n\t\tgoto out;\n\n\ttask_event->event_id.pid = perf_event_pid(event, task);\n\ttask_event->event_id.ppid = perf_event_pid(event, current);\n\n\ttask_event->event_id.tid = perf_event_tid(event, task);\n\ttask_event->event_id.ptid = perf_event_tid(event, current);\n\n\tperf_output_put(&handle, task_event->event_id);\n\n\tperf_event__output_id_sample(event, &handle, &sample);\n\n\tperf_output_end(&handle);\nout:\n\ttask_event->event_id.header.size = size;\n}", "label_name": "CWE-400", "label": 2}
{"code": "void sctp_generate_proto_unreach_event(unsigned long data)\n{\n\tstruct sctp_transport *transport = (struct sctp_transport *) data;\n\tstruct sctp_association *asoc = transport->asoc;\n\tstruct net *net = sock_net(asoc->base.sk);\n\n\tbh_lock_sock(asoc->base.sk);\n\tif (sock_owned_by_user(asoc->base.sk)) {\n\t\tpr_debug(\"%s: sock is busy\\n\", __func__);\n\n\t\t/* Try again later. */\n\t\tif (!mod_timer(&transport->proto_unreach_timer,\n\t\t\t\tjiffies + (HZ/20)))\n\t\t\tsctp_association_hold(asoc);\n\t\tgoto out_unlock;\n\t}\n\n\t/* Is this structure just waiting around for us to actually\n\t * get destroyed?\n\t */\n\tif (asoc->base.dead)\n\t\tgoto out_unlock;\n\n\tsctp_do_sm(net, SCTP_EVENT_T_OTHER,\n\t\t SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),\n\t\t asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC);\n\nout_unlock:\n\tbh_unlock_sock(asoc->base.sk);\n\tsctp_association_put(asoc);\n}", "label_name": "CWE-362", "label": 18}
{"code": "escapes(cp, tp)\nconst char\t*cp;\nchar *tp;\n{\n while (*cp) {\n\tint\tcval = 0, meta = 0;\n\n\tif (*cp == '\\\\' && cp[1] && index(\"mM\", cp[1]) && cp[2]) {\n\t\tmeta = 1;\n\t\tcp += 2;\n\t}\n\tif (*cp == '\\\\' && cp[1] && index(\"0123456789xXoO\", cp[1]) && cp[2]) {\n\t NEARDATA const char hex[] = \"00112233445566778899aAbBcCdDeEfF\";\n\t const char *dp;\n\t int dcount = 0;\n\n\t cp++;\n\t if (*cp == 'x' || *cp == 'X')\n\t\tfor (++cp; *cp && (dp = index(hex, *cp)) && (dcount++ < 2); cp++)\n\t\t cval = (cval * 16) + ((int)(dp - hex) / 2);\n\t else if (*cp == 'o' || *cp == 'O')\n\t\tfor (++cp; *cp && (index(\"01234567\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 8) + (*cp - '0');\n\t else\n\t\tfor (; *cp && (index(\"0123456789\",*cp)) && (dcount++ < 3); cp++)\n\t\t cval = (cval * 10) + (*cp - '0');\n\t} else if (*cp == '\\\\' && cp[1]) {\t/* C-style character escapes */\n\t switch (*++cp) {\n\t case '\\\\': cval = '\\\\'; break;\n\t case 'n': cval = '\\n'; break;\n\t case 't': cval = '\\t'; break;\n\t case 'b': cval = '\\b'; break;\n\t case 'r': cval = '\\r'; break;\n\t default: cval = *cp;\n\t }\n\t cp++;\n\t} else if (*cp == '^' && cp[1]) { /* expand control-character syntax */\n\t cval = (*++cp & 0x1f);\n\t cp++;\n\t} else\n\t cval = *cp++;\n\n\tif (meta)\n\t cval |= 0x80;\n\t*tp++ = cval;\n }\n *tp = '\\0';\n}", "label_name": "CWE-269", "label": 6}
{"code": "cpStripToTile(uint8* out, uint8* in,\n uint32 rows, uint32 cols, int outskew, int inskew)\n{\n\twhile (rows-- > 0) {\n\t\tuint32 j = cols;\n\t\twhile (j-- > 0)\n\t\t\t*out++ = *in++;\n\t\tout += outskew;\n\t\tin += inskew;\n\t}\n}", "label_name": "CWE-119", "label": 26}
{"code": "ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr,\n bool *set_rtrn)\n{\n bool ok = false;\n const char *ident;\n\n switch (expr->expr.op) {\n case EXPR_VALUE:\n if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) {\n log_err(ctx,\n \"Found constant of type %s where boolean was expected\\n\",\n expr_value_type_to_string(expr->expr.value_type));\n return false;\n }\n *set_rtrn = expr->boolean.set;\n return true;\n\n case EXPR_IDENT:\n ident = xkb_atom_text(ctx, expr->ident.ident);\n if (ident) {\n if (istreq(ident, \"true\") ||\n istreq(ident, \"yes\") ||\n istreq(ident, \"on\")) {\n *set_rtrn = true;\n return true;\n }\n else if (istreq(ident, \"false\") ||\n istreq(ident, \"no\") ||\n istreq(ident, \"off\")) {\n *set_rtrn = false;\n return true;\n }\n }\n log_err(ctx, \"Identifier \\\"%s\\\" of type boolean is unknown\\n\", ident);\n return false;\n\n case EXPR_FIELD_REF:\n log_err(ctx, \"Default \\\"%s.%s\\\" of type boolean is unknown\\n\",\n xkb_atom_text(ctx, expr->field_ref.element),\n xkb_atom_text(ctx, expr->field_ref.field));\n return false;\n\n case EXPR_INVERT:\n case EXPR_NOT:\n ok = ExprResolveBoolean(ctx, expr, set_rtrn);\n if (ok)\n *set_rtrn = !*set_rtrn;\n return ok;\n case EXPR_ADD:\n case EXPR_SUBTRACT:\n case EXPR_MULTIPLY:\n case EXPR_DIVIDE:\n case EXPR_ASSIGN:\n case EXPR_NEGATE:\n case EXPR_UNARY_PLUS:\n log_err(ctx, \"%s of boolean values not permitted\\n\",\n expr_op_type_to_string(expr->expr.op));\n break;\n\n default:\n log_wsgo(ctx, \"Unknown operator %d in ResolveBoolean\\n\",\n expr->expr.op);\n break;\n }\n\n return false;\n}", "label_name": "CWE-400", "label": 2}
{"code": "error_t am335xEthDeleteVlanAddrEntry(uint_t port, uint_t vlanId, MacAddr *macAddr)\n{\n error_t error;\n uint_t index;\n Am335xAleEntry entry;\n\n //Search the ALE table for the specified VLAN/address entry\n index = am335xEthFindVlanAddrEntry(vlanId, macAddr);\n\n //Matching ALE entry found?\n if(index < CPSW_ALE_MAX_ENTRIES)\n {\n //Clear the contents of the entry\n entry.word2 = 0;\n entry.word1 = 0;\n entry.word0 = 0;\n\n //Update the ALE table\n am335xEthWriteEntry(index, &entry);\n\n //Sucessful processing\n error = NO_ERROR;\n }\n else\n {\n //Entry not found\n error = ERROR_NOT_FOUND;\n }\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int sdp_parse_fmtp_config_h264(AVFormatContext *s,\n AVStream *stream,\n PayloadContext *h264_data,\n const char *attr, const char *value)\n{\n AVCodecParameters *par = stream->codecpar;\n\n if (!strcmp(attr, \"packetization-mode\")) {\n av_log(s, AV_LOG_DEBUG, \"RTP Packetization Mode: %d\\n\", atoi(value));\n h264_data->packetization_mode = atoi(value);\n /*\n * Packetization Mode:\n * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed)\n * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.\n * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A),\n * and 29 (FU-B) are allowed.\n */\n if (h264_data->packetization_mode > 1)\n av_log(s, AV_LOG_ERROR,\n \"Interleaved RTP mode is not supported yet.\\n\");\n } else if (!strcmp(attr, \"profile-level-id\")) {\n if (strlen(value) == 6)\n parse_profile_level_id(s, h264_data, value);\n } else if (!strcmp(attr, \"sprop-parameter-sets\")) {\n int ret;\n if (value[strlen(value) - 1] == ',') {\n av_log(s, AV_LOG_WARNING, \"Missing PPS in sprop-parameter-sets, ignoring\\n\");\n return 0;\n }\n par->extradata_size = 0;\n av_freep(&par->extradata);\n ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata,\n &par->extradata_size, value);\n av_log(s, AV_LOG_DEBUG, \"Extradata set to %p (size: %d)\\n\",\n par->extradata, par->extradata_size);\n return ret;\n }\n return 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)\n{\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tunsigned char *p;\n\tint ok = 0;\n\tint r;\n\tsize_t len;\n\n\tsc_format_path(str_path, &path);\n\tif (SC_SUCCESS != sc_select_file(card, &path, &file)) {\n\t\tgoto err;\n\t}\n\n\tlen = file ? file->size : 4096;\n\tp = realloc(*data, len);\n\tif (!p) {\n\t\tgoto err;\n\t}\n\t*data = p;\n\t*data_len = len;\n\n\tr = sc_read_binary(card, 0, p, len, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\t*data_len = r;\n\tok = 1;\n\nerr:\n\tsc_file_free(file);\n\n\treturn ok;\n}", "label_name": "CWE-119", "label": 26}
{"code": "void ip_options_build(struct sk_buff * skb, struct ip_options * opt,\n\t\t\t __be32 daddr, struct rtable *rt, int is_frag)\n{\n\tunsigned char *iph = skb_network_header(skb);\n\n\tmemcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options));\n\tmemcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen);\n\topt = &(IPCB(skb)->opt);\n\n\tif (opt->srr)\n\t\tmemcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4);\n\n\tif (!is_frag) {\n\t\tif (opt->rr_needaddr)\n\t\t\tip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt);\n\t\tif (opt->ts_needaddr)\n\t\t\tip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt);\n\t\tif (opt->ts_needtime) {\n\t\t\tstruct timespec tv;\n\t\t\t__be32 midtime;\n\t\t\tgetnstimeofday(&tv);\n\t\t\tmidtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC);\n\t\t\tmemcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4);\n\t\t}\n\t\treturn;\n\t}\n\tif (opt->rr) {\n\t\tmemset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]);\n\t\topt->rr = 0;\n\t\topt->rr_needaddr = 0;\n\t}\n\tif (opt->ts) {\n\t\tmemset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]);\n\t\topt->ts = 0;\n\t\topt->ts_needaddr = opt->ts_needtime = 0;\n\t}\n}", "label_name": "CWE-362", "label": 18}
{"code": "error_t am335xEthAddVlanEntry(uint_t port, uint_t vlanId)\n{\n error_t error;\n uint_t index;\n Am335xAleEntry entry;\n\n //Ensure that there are no duplicate address entries in the ALE table\n index = am335xEthFindVlanEntry(vlanId);\n\n //No matching entry found?\n if(index >= CPSW_ALE_MAX_ENTRIES)\n {\n //Find a free entry in the ALE table\n index = am335xEthFindFreeEntry();\n }\n\n //Sanity check\n if(index < CPSW_ALE_MAX_ENTRIES)\n {\n //Set up a VLAN table entry\n entry.word2 = 0;\n entry.word1 = CPSW_ALE_WORD1_ENTRY_TYPE_VLAN;\n entry.word0 = 0;\n\n //Set VLAN identifier\n entry.word1 |= CPSW_ALE_WORD1_VLAN_ID(vlanId);\n\n //Force the packet VLAN tag to be removed on egress\n entry.word0 |= CPSW_ALE_WORD0_FORCE_UNTAG_EGRESS(1 << port) |\n CPSW_ALE_WORD0_FORCE_UNTAG_EGRESS(1 << CPSW_PORT0);\n\n //Set VLAN member list\n entry.word0 |= CPSW_ALE_WORD0_VLAN_MEMBER_LIST(1 << port) |\n CPSW_ALE_WORD0_VLAN_MEMBER_LIST(1 << CPSW_PORT0);\n\n //Add a new entry to the ALE table\n am335xEthWriteEntry(index, &entry);\n\n //Sucessful processing\n error = NO_ERROR;\n }\n else\n {\n //The ALE table is full\n error = ERROR_FAILURE;\n }\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": 0}
{"code": "void rza1EthEventHandler(NetInterface *interface)\n{\n error_t error;\n\n //Packet received?\n if((ETHER.EESR0 & ETHER_EESR0_FR) != 0)\n {\n //Clear FR interrupt flag\n ETHER.EESR0 = ETHER_EESR0_FR;\n\n //Process all pending packets\n do\n {\n //Read incoming packet\n error = rza1EthReceivePacket(interface);\n\n //No more data in the receive buffer?\n } while(error != ERROR_BUFFER_EMPTY);\n }\n\n //Re-enable EDMAC interrupts\n ETHER.EESIPR0 = ETHER_EESIPR0_TWBIP | ETHER_EESIPR0_FRIP;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int do_new_mount(struct path *path, const char *fstype, int flags,\n\t\t\tint mnt_flags, const char *name, void *data)\n{\n\tstruct file_system_type *type;\n\tstruct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;\n\tstruct vfsmount *mnt;\n\tint err;\n\n\tif (!fstype)\n\t\treturn -EINVAL;\n\n\ttype = get_fs_type(fstype);\n\tif (!type)\n\t\treturn -ENODEV;\n\n\tif (user_ns != &init_user_ns) {\n\t\tif (!(type->fs_flags & FS_USERNS_MOUNT)) {\n\t\t\tput_filesystem(type);\n\t\t\treturn -EPERM;\n\t\t}\n\t\t/* Only in special cases allow devices from mounts\n\t\t * created outside the initial user namespace.\n\t\t */\n\t\tif (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) {\n\t\t\tflags |= MS_NODEV;\n\t\t\tmnt_flags |= MNT_NODEV;\n\t\t}\n\t}\n\n\tmnt = vfs_kern_mount(type, flags, name, data);\n\tif (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) &&\n\t !mnt->mnt_sb->s_subtype)\n\t\tmnt = fs_set_subtype(mnt, fstype);\n\n\tput_filesystem(type);\n\tif (IS_ERR(mnt))\n\t\treturn PTR_ERR(mnt);\n\n\terr = do_add_mount(real_mount(mnt), path, mnt_flags);\n\tif (err)\n\t\tmntput(mnt);\n\treturn err;\n}", "label_name": "CWE-269", "label": 6}
{"code": "static int oidc_cache_crypto_encrypt_impl(request_rec *r,\n\t\tunsigned char *plaintext, int plaintext_len, const unsigned char *aad,\n\t\tint aad_len, unsigned char *key, const unsigned char *iv, int iv_len,\n\t\tunsigned char *ciphertext, const unsigned char *tag, int tag_len) {\n\tEVP_CIPHER_CTX *ctx;\n\n\tint len;\n\n\tint ciphertext_len;\n\n\t/* create and initialize the context */\n\tif (!(ctx = EVP_CIPHER_CTX_new())) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_new\");\n\t\treturn -1;\n\t}\n\n\t/* initialize the encryption cipher */\n\tif (!EVP_EncryptInit_ex(ctx, OIDC_CACHE_CIPHER, NULL, NULL, NULL)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_EncryptInit_ex\");\n\t\treturn -1;\n\t}\n\n\t/* set IV length */\n\tif (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_SET_IVLEN, iv_len, NULL)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_ctrl\");\n\t\treturn -1;\n\t}\n\n\t/* initialize key and IV */\n\tif (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_EncryptInit_ex\");\n\t\treturn -1;\n\t}\n\n\t/* provide AAD data */\n\tif (!EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_DecryptUpdate aad: aad_len=%d\",\n\t\t\t\taad_len);\n\t\treturn -1;\n\t}\n\n\t/* provide the message to be encrypted and obtain the encrypted output */\n\tif (!EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_EncryptUpdate ciphertext\");\n\t\treturn -1;\n\t}\n\tciphertext_len = len;\n\n\t/*\n\t * finalize the encryption; normally ciphertext bytes may be written at\n\t * this stage, but this does not occur in GCM mode\n\t */\n\tif (!EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_EncryptFinal_ex\");\n\t\treturn -1;\n\t}\n\tciphertext_len += len;\n\n\t/* get the tag */\n\tif (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_GET_TAG, tag_len,\n\t\t\t(void *) tag)) {\n\t\toidc_cache_crypto_openssl_error(r, \"EVP_CIPHER_CTX_ctrl\");\n\t\treturn -1;\n\t}\n\n\t/* clean up */\n\tEVP_CIPHER_CTX_free(ctx);\n\n\treturn ciphertext_len;\n}", "label_name": "CWE-330", "label": 12}
{"code": "fixExec2Error(int action,\n u_char * var_val,\n u_char var_val_type,\n size_t var_val_len,\n u_char * statP, oid * name, size_t name_len)\n{\n netsnmp_old_extend *exten = NULL;\n unsigned int idx;\n\n idx = name[name_len-1] -1;\n exten = &compatability_entries[ idx ];\n\n#ifndef NETSNMP_NO_WRITE_SUPPORT\n switch (action) {\n case MODE_SET_RESERVE1:\n if (var_val_type != ASN_INTEGER) {\n snmp_log(LOG_ERR, \"Wrong type != int\\n\");\n return SNMP_ERR_WRONGTYPE;\n }\n idx = *((long *) var_val);\n if (idx != 1) {\n snmp_log(LOG_ERR, \"Wrong value != 1\\n\");\n return SNMP_ERR_WRONGVALUE;\n }\n if (!exten || !exten->efix_entry) {\n snmp_log(LOG_ERR, \"No command to run\\n\");\n return SNMP_ERR_GENERR;\n }\n return SNMP_ERR_NOERROR;\n\n case MODE_SET_COMMIT:\n netsnmp_cache_check_and_reload( exten->efix_entry->cache );\n }\n#endif /* !NETSNMP_NO_WRITE_SUPPORT */\n return SNMP_ERR_NOERROR;\n}", "label_name": "CWE-269", "label": 6}
{"code": "static inline void arch_dup_mmap(struct mm_struct *oldmm,\n\t\t\t\t struct mm_struct *mm)\n{\n\tif (oldmm->context.asce_limit < mm->context.asce_limit)\n\t\tcrst_table_downgrade(mm, oldmm->context.asce_limit);\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void dns_resolver_describe(const struct key *key, struct seq_file *m)\n{\n\tseq_puts(m, key->description);\n\tif (key_is_instantiated(key)) {\n\t\tint err = PTR_ERR(key->payload.data[dns_key_error]);\n\n\t\tif (err)\n\t\t\tseq_printf(m, \": %d\", err);\n\t\telse\n\t\t\tseq_printf(m, \": %u\", key->datalen);\n\t}\n}", "label_name": "CWE-20", "label": 0}
{"code": "static ssize_t k90_show_current_profile(struct device *dev,\n\t\t\t\t\tstruct device_attribute *attr,\n\t\t\t\t\tchar *buf)\n{\n\tint ret;\n\tstruct usb_interface *usbif = to_usb_interface(dev->parent);\n\tstruct usb_device *usbdev = interface_to_usbdev(usbif);\n\tint current_profile;\n\tchar data[8];\n\n\tret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),\n\t\t\t K90_REQUEST_STATUS,\n\t\t\t USB_DIR_IN | USB_TYPE_VENDOR |\n\t\t\t USB_RECIP_DEVICE, 0, 0, data, 8,\n\t\t\t USB_CTRL_SET_TIMEOUT);\n\tif (ret < 0) {\n\t\tdev_warn(dev, \"Failed to get K90 initial state (error %d).\\n\",\n\t\t\t ret);\n\t\treturn -EIO;\n\t}\n\tcurrent_profile = data[7];\n\tif (current_profile < 1 || current_profile > 3) {\n\t\tdev_warn(dev, \"Read invalid current profile: %02hhx.\\n\",\n\t\t\t data[7]);\n\t\treturn -EIO;\n\t}\n\n\treturn snprintf(buf, PAGE_SIZE, \"%d\\n\", current_profile);\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len,\n\t\t\t int flags)\n{\n\tint err;\n\tstruct sk_buff *skb;\n\tstruct sock *sk = sock->sk;\n\n\terr = -EIO;\n\tif (sk->sk_state & PPPOX_BOUND)\n\t\tgoto end;\n\n\tmsg->msg_namelen = 0;\n\n\terr = 0;\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\tgoto end;\n\n\tif (len > skb->len)\n\t\tlen = skb->len;\n\telse if (len < skb->len)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);\n\tif (likely(err == 0))\n\t\terr = len;\n\n\tkfree_skb(skb);\nend:\n\treturn err;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void construct_get_dest_keyring(struct key **_dest_keyring)\n{\n\tstruct request_key_auth *rka;\n\tconst struct cred *cred = current_cred();\n\tstruct key *dest_keyring = *_dest_keyring, *authkey;\n\n\tkenter(\"%p\", dest_keyring);\n\n\t/* find the appropriate keyring */\n\tif (dest_keyring) {\n\t\t/* the caller supplied one */\n\t\tkey_get(dest_keyring);\n\t} else {\n\t\t/* use a default keyring; falling through the cases until we\n\t\t * find one that we actually have */\n\t\tswitch (cred->jit_keyring) {\n\t\tcase KEY_REQKEY_DEFL_DEFAULT:\n\t\tcase KEY_REQKEY_DEFL_REQUESTOR_KEYRING:\n\t\t\tif (cred->request_key_auth) {\n\t\t\t\tauthkey = cred->request_key_auth;\n\t\t\t\tdown_read(&authkey->sem);\n\t\t\t\trka = authkey->payload.data[0];\n\t\t\t\tif (!test_bit(KEY_FLAG_REVOKED,\n\t\t\t\t\t &authkey->flags))\n\t\t\t\t\tdest_keyring =\n\t\t\t\t\t\tkey_get(rka->dest_keyring);\n\t\t\t\tup_read(&authkey->sem);\n\t\t\t\tif (dest_keyring)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcase KEY_REQKEY_DEFL_THREAD_KEYRING:\n\t\t\tdest_keyring = key_get(cred->thread_keyring);\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_PROCESS_KEYRING:\n\t\t\tdest_keyring = key_get(cred->process_keyring);\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_SESSION_KEYRING:\n\t\t\trcu_read_lock();\n\t\t\tdest_keyring = key_get(\n\t\t\t\trcu_dereference(cred->session_keyring));\n\t\t\trcu_read_unlock();\n\n\t\t\tif (dest_keyring)\n\t\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_USER_SESSION_KEYRING:\n\t\t\tdest_keyring =\n\t\t\t\tkey_get(cred->user->session_keyring);\n\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_USER_KEYRING:\n\t\t\tdest_keyring = key_get(cred->user->uid_keyring);\n\t\t\tbreak;\n\n\t\tcase KEY_REQKEY_DEFL_GROUP_KEYRING:\n\t\tdefault:\n\t\t\tBUG();\n\t\t}\n\t}\n\n\t*_dest_keyring = dest_keyring;\n\tkleave(\" [dk %d]\", key_serial(dest_keyring));\n\treturn;\n}", "label_name": "CWE-862", "label": 8}
{"code": "PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */\n{\n\tconst char *p, *q;\n\tchar *name;\n\tconst char *endptr = val + vallen;\n\tzval *current;\n\tint namelen;\n\tint has_value;\n\tphp_unserialize_data_t var_hash;\n\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\n\tp = val;\n\n\twhile (p < endptr) {\n\t\tzval **tmp;\n\t\tq = p;\n\t\twhile (*q != PS_DELIMITER) {\n\t\t\tif (++q >= endptr) goto break_outer_loop;\n\t\t}\n\t\tif (p[0] == PS_UNDEF_MARKER) {\n\t\t\tp++;\n\t\t\thas_value = 0;\n\t\t} else {\n\t\t\thas_value = 1;\n\t\t}\n\n\t\tnamelen = q - p;\n\t\tname = estrndup(p, namelen);\n\t\tq++;\n\n\t\tif (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {\n\t\t\tif ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {\n\t\t\t\tgoto skip;\n\t\t\t}\n\t\t}\n\n\t\tif (has_value) {\n\t\t\tALLOC_INIT_ZVAL(current);\n\t\t\tif (php_var_unserialize(¤t, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {\n\t\t\t\tphp_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);\n\t\t\t} else {\n\t\t\t\tvar_push_dtor_no_addref(&var_hash, ¤t);\n\t\t\t\tefree(name);\n\t\t\t\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\t\t\t\treturn FAILURE;\n\t\t\t}\n\t\t\tvar_push_dtor_no_addref(&var_hash, ¤t);\n\t\t}\n\t\tPS_ADD_VARL(name, namelen);\nskip:\n\t\tefree(name);\n\n\t\tp = q;\n\t}\nbreak_outer_loop:\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\n\treturn SUCCESS;\n}", "label_name": "CWE-74", "label": 1}
{"code": "int ip_options_get_from_user(struct net *net, struct ip_options **optp,\n\t\t\t unsigned char __user *data, int optlen)\n{\n\tstruct ip_options *opt = ip_options_get_alloc(optlen);\n\n\tif (!opt)\n\t\treturn -ENOMEM;\n\tif (optlen && copy_from_user(opt->__data, data, optlen)) {\n\t\tkfree(opt);\n\t\treturn -EFAULT;\n\t}\n\treturn ip_options_get_finish(net, optp, opt, optlen);\n}", "label_name": "CWE-362", "label": 18}
{"code": "static unsigned int help(struct sk_buff *skb,\n\t\t\t enum ip_conntrack_info ctinfo,\n\t\t\t unsigned int protoff,\n\t\t\t unsigned int matchoff,\n\t\t\t unsigned int matchlen,\n\t\t\t struct nf_conntrack_expect *exp)\n{\n\tchar buffer[sizeof(\"4294967296 65635\")];\n\tu_int16_t port;\n\tunsigned int ret;\n\n\t/* Reply comes from server. */\n\texp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;\n\texp->dir = IP_CT_DIR_REPLY;\n\texp->expectfn = nf_nat_follow_master;\n\n\t/* Try to get same port: if not, try to change it. */\n\tfor (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) {\n\t\tint ret;\n\n\t\texp->tuple.dst.u.tcp.port = htons(port);\n\t\tret = nf_ct_expect_related(exp);\n\t\tif (ret == 0)\n\t\t\tbreak;\n\t\telse if (ret != -EBUSY) {\n\t\t\tport = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (port == 0) {\n\t\tnf_ct_helper_log(skb, exp->master, \"all ports in use\");\n\t\treturn NF_DROP;\n\t}\n\n\tret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo,\n\t\t\t\t protoff, matchoff, matchlen, buffer,\n\t\t\t\t strlen(buffer));\n\tif (ret != NF_ACCEPT) {\n\t\tnf_ct_helper_log(skb, exp->master, \"cannot mangle packet\");\n\t\tnf_ct_unexpect_related(exp);\n\t}\n\treturn ret;\n}", "label_name": "CWE-200", "label": 10}
{"code": "test_string_matching (xd3_stream *stream, int ignore)\n{\n usize_t i;\n int ret;\n xd3_config config;\n char rbuf[TESTBUFSIZE];\n\n for (i = 0; i < SIZEOF_ARRAY (match_tests); i += 1)\n {\n const string_match_test *test = & match_tests[i];\n char *rptr = rbuf;\n usize_t len = (usize_t) strlen (test->input);\n\n xd3_free_stream (stream);\n xd3_init_config (& config, 0);\n\n config.smatch_cfg = XD3_SMATCH_SOFT;\n config.smatcher_soft.large_look = 4;\n config.smatcher_soft.large_step = 4;\n config.smatcher_soft.small_look = 4;\n config.smatcher_soft.small_chain = 10;\n config.smatcher_soft.small_lchain = 10;\n config.smatcher_soft.max_lazy = (test->flags & SM_LAZY) ? 10 : 0;\n config.smatcher_soft.long_enough = 10;\n\n if ((ret = xd3_config_stream (stream, & config))) { return ret; }\n if ((ret = xd3_encode_init_full (stream))) { return ret; }\n\n xd3_avail_input (stream, (uint8_t*)test->input, len);\n\n if ((ret = stream->smatcher.string_match (stream))) { return ret; }\n\n *rptr = 0;\n while (! xd3_rlist_empty (& stream->iopt_used))\n\t{\n\t xd3_rinst *inst = xd3_rlist_pop_front (& stream->iopt_used);\n\n\t switch (inst->type)\n\t {\n\t case XD3_RUN: *rptr++ = 'R'; break;\n\t case XD3_CPY: *rptr++ = 'C'; break;\n\t default: CHECK(0);\n\t }\n\n\t snprintf_func (rptr, rbuf+TESTBUFSIZE-rptr, \"%d/%d\", \n\t\t\t inst->pos, inst->size);\n\t rptr += strlen (rptr);\n\n\t if (inst->type == XD3_CPY)\n\t {\n\t *rptr++ = '@';\n\t snprintf_func (rptr, rbuf+TESTBUFSIZE-rptr, \"%\"Q\"d\", inst->addr);\n\t rptr += strlen (rptr);\n\t }\n\n\t *rptr++ = ' ';\n\n\t xd3_rlist_push_back (& stream->iopt_free, inst);\n\t}\n\n if (rptr != rbuf)\n\t{\n\t rptr -= 1; *rptr = 0;\n\t}\n\n if (strcmp (rbuf, test->result) != 0)\n\t{\n\t XPR(NT \"test %u: expected %s: got %s\", i, test->result, rbuf);\n\t stream->msg = \"wrong result\";\n\t return XD3_INTERNAL;\n\t}\n }\n\n return 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static int misaligned_load(struct pt_regs *regs,\n\t\t\t __u32 opcode,\n\t\t\t int displacement_not_indexed,\n\t\t\t int width_shift,\n\t\t\t int do_sign_extend)\n{\n\t/* Return -1 for a fault, 0 for OK */\n\tint error;\n\tint destreg;\n\t__u64 address;\n\n\terror = generate_and_check_address(regs, opcode,\n\t\t\tdisplacement_not_indexed, width_shift, &address);\n\tif (error < 0) {\n\t\treturn error;\n\t}\n\n\tperf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address);\n\n\tdestreg = (opcode >> 4) & 0x3f;\n\tif (user_mode(regs)) {\n\t\t__u64 buffer;\n\n\t\tif (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) {\n\t\t\treturn -1; /* fault */\n\t\t}\n\t\tswitch (width_shift) {\n\t\tcase 1:\n\t\t\tif (do_sign_extend) {\n\t\t\t\tregs->regs[destreg] = (__u64)(__s64) *(__s16 *) &buffer;\n\t\t\t} else {\n\t\t\t\tregs->regs[destreg] = (__u64) *(__u16 *) &buffer;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tregs->regs[destreg] = (__u64)(__s64) *(__s32 *) &buffer;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tregs->regs[destreg] = buffer;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintk(\"Unexpected width_shift %d in misaligned_load, PC=%08lx\\n\",\n\t\t\t\twidth_shift, (unsigned long) regs->pc);\n\t\t\tbreak;\n\t\t}\n\t} else {\n\t\t/* kernel mode - we can take short cuts since if we fault, it's a genuine bug */\n\t\t__u64 lo, hi;\n\n\t\tswitch (width_shift) {\n\t\tcase 1:\n\t\t\tmisaligned_kernel_word_load(address, do_sign_extend, ®s->regs[destreg]);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tasm (\"ldlo.l %1, 0, %0\" : \"=r\" (lo) : \"r\" (address));\n\t\t\tasm (\"ldhi.l %1, 3, %0\" : \"=r\" (hi) : \"r\" (address));\n\t\t\tregs->regs[destreg] = lo | hi;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tasm (\"ldlo.q %1, 0, %0\" : \"=r\" (lo) : \"r\" (address));\n\t\t\tasm (\"ldhi.q %1, 7, %0\" : \"=r\" (hi) : \"r\" (address));\n\t\t\tregs->regs[destreg] = lo | hi;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tprintk(\"Unexpected width_shift %d in misaligned_load, PC=%08lx\\n\",\n\t\t\t\twidth_shift, (unsigned long) regs->pc);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\n}", "label_name": "CWE-400", "label": 2}
{"code": "static int trusted_update(struct key *key, struct key_preparsed_payload *prep)\n{\n\tstruct trusted_key_payload *p;\n\tstruct trusted_key_payload *new_p;\n\tstruct trusted_key_options *new_o;\n\tsize_t datalen = prep->datalen;\n\tchar *datablob;\n\tint ret = 0;\n\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n\t\treturn -ENOKEY;\n\tp = key->payload.data[0];\n\tif (!p->migratable)\n\t\treturn -EPERM;\n\tif (datalen <= 0 || datalen > 32767 || !prep->data)\n\t\treturn -EINVAL;\n\n\tdatablob = kmalloc(datalen + 1, GFP_KERNEL);\n\tif (!datablob)\n\t\treturn -ENOMEM;\n\tnew_o = trusted_options_alloc();\n\tif (!new_o) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tnew_p = trusted_payload_alloc(key);\n\tif (!new_p) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmemcpy(datablob, prep->data, datalen);\n\tdatablob[datalen] = '\\0';\n\tret = datablob_parse(datablob, new_p, new_o);\n\tif (ret != Opt_update) {\n\t\tret = -EINVAL;\n\t\tkzfree(new_p);\n\t\tgoto out;\n\t}\n\n\tif (!new_o->keyhandle) {\n\t\tret = -EINVAL;\n\t\tkzfree(new_p);\n\t\tgoto out;\n\t}\n\n\t/* copy old key values, and reseal with new pcrs */\n\tnew_p->migratable = p->migratable;\n\tnew_p->key_len = p->key_len;\n\tmemcpy(new_p->key, p->key, p->key_len);\n\tdump_payload(p);\n\tdump_payload(new_p);\n\n\tret = key_seal(new_p, new_o);\n\tif (ret < 0) {\n\t\tpr_info(\"trusted_key: key_seal failed (%d)\\n\", ret);\n\t\tkzfree(new_p);\n\t\tgoto out;\n\t}\n\tif (new_o->pcrlock) {\n\t\tret = pcrlock(new_o->pcrlock);\n\t\tif (ret < 0) {\n\t\t\tpr_info(\"trusted_key: pcrlock failed (%d)\\n\", ret);\n\t\t\tkzfree(new_p);\n\t\t\tgoto out;\n\t\t}\n\t}\n\trcu_assign_keypointer(key, new_p);\n\tcall_rcu(&p->rcu, trusted_rcu_free);\nout:\n\tkzfree(datablob);\n\tkzfree(new_o);\n\treturn ret;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val)\n{\n\tint i;\n\tint c;\n\tulonglong v;\n\tv = 0;\n\tfor (i = n; i > 0; --i) {\n\t\tif ((c = jas_stream_getc(in)) == EOF)\n\t\t\treturn -1;\n\t\tv = (v << 8) | c;\n\t}\n\t*val = v;\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0}
{"code": "int main(int argc, char **argv, char **envp)\n{\n\tint opt;\n\n\twhile ((opt = getopt(argc, argv, \"b:h:k:p:q:w:z:xv\")) != -1) {\n\t\tswitch (opt) {\n\t\tcase 'b':\n\t\t\ttmate_settings->bind_addr = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\ttmate_settings->tmate_host = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\ttmate_settings->keys_dir = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\ttmate_settings->ssh_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\ttmate_settings->ssh_port_advertized = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\ttmate_settings->websocket_hostname = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'z':\n\t\t\ttmate_settings->websocket_port = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\ttmate_settings->use_proxy_protocol = true;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\ttmate_settings->log_level++;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tinit_logging(tmate_settings->log_level);\n\n\tsetup_locale();\n\n\tif (!tmate_settings->tmate_host)\n\t\ttmate_settings->tmate_host = get_full_hostname();\n\n\tcmdline = *argv;\n\tcmdline_end = *envp;\n\n\ttmate_preload_trace_lib();\n\ttmate_catch_sigsegv();\n\ttmate_init_rand();\n\n\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n\t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\t/* The websocket server needs to access the /session dir to rename sockets */\n\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n\t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n\t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n\n\ttmate_ssh_server_main(tmate_session,\n\t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18}
{"code": "asmlinkage long compat_sys_ptrace(compat_long_t request, compat_long_t pid,\n\t\t\t\t compat_long_t addr, compat_long_t data)\n{\n\tstruct task_struct *child;\n\tlong ret;\n\n\tif (request == PTRACE_TRACEME) {\n\t\tret = ptrace_traceme();\n\t\tgoto out;\n\t}\n\n\tchild = ptrace_get_task_struct(pid);\n\tif (IS_ERR(child)) {\n\t\tret = PTR_ERR(child);\n\t\tgoto out;\n\t}\n\n\tif (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {\n\t\tret = ptrace_attach(child, request, addr, data);\n\t\t/*\n\t\t * Some architectures need to do book-keeping after\n\t\t * a ptrace attach.\n\t\t */\n\t\tif (!ret)\n\t\t\tarch_ptrace_attach(child);\n\t\tgoto out_put_task_struct;\n\t}\n\n\tret = ptrace_check_attach(child, request == PTRACE_KILL ||\n\t\t\t\t request == PTRACE_INTERRUPT);\n\tif (!ret)\n\t\tret = compat_arch_ptrace(child, request, addr, data);\n\n out_put_task_struct:\n\tput_task_struct(child);\n out:\n\treturn ret;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port)\n{\n\tstruct usb_serial\t*serial = port->serial;\n\tstruct usb_serial_port\t*wport;\n\n\twport = serial->port[1];\n\ttty_port_tty_set(&wport->port, tty);\n\n\treturn usb_serial_generic_open(tty, port);\n}", "label_name": "CWE-404", "label": 30}
{"code": "static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,\n int bufsize)\n{\n\t/* If this function is being called, the buffer should not have been\n\t initialized yet. */\n\tassert(!stream->bufbase_);\n\n\tif (bufmode != JAS_STREAM_UNBUF) {\n\t\t/* The full- or line-buffered mode is being employed. */\n\t\tif (!buf) {\n\t\t\t/* The caller has not specified a buffer to employ, so allocate\n\t\t\t one. */\n\t\t\tif ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE +\n\t\t\t JAS_STREAM_MAXPUTBACK))) {\n\t\t\t\tstream->bufmode_ |= JAS_STREAM_FREEBUF;\n\t\t\t\tstream->bufsize_ = JAS_STREAM_BUFSIZE;\n\t\t\t} else {\n\t\t\t\t/* The buffer allocation has failed. Resort to unbuffered\n\t\t\t\t operation. */\n\t\t\t\tstream->bufbase_ = stream->tinybuf_;\n\t\t\t\tstream->bufsize_ = 1;\n\t\t\t}\n\t\t} else {\n\t\t\t/* The caller has specified a buffer to employ. */\n\t\t\t/* The buffer must be large enough to accommodate maximum\n\t\t\t putback. */\n\t\t\tassert(bufsize > JAS_STREAM_MAXPUTBACK);\n\t\t\tstream->bufbase_ = JAS_CAST(uchar *, buf);\n\t\t\tstream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;\n\t\t}\n\t} else {\n\t\t/* The unbuffered mode is being employed. */\n\t\t/* A buffer should not have been supplied by the caller. */\n\t\tassert(!buf);\n\t\t/* Use a trivial one-character buffer. */\n\t\tstream->bufbase_ = stream->tinybuf_;\n\t\tstream->bufsize_ = 1;\n\t}\n\tstream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];\n\tstream->ptr_ = stream->bufstart_;\n\tstream->cnt_ = 0;\n\tstream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static void bt_for_each(struct blk_mq_hw_ctx *hctx,\n\t\tstruct blk_mq_bitmap_tags *bt, unsigned int off,\n\t\tbusy_iter_fn *fn, void *data, bool reserved)\n{\n\tstruct request *rq;\n\tint bit, i;\n\n\tfor (i = 0; i < bt->map_nr; i++) {\n\t\tstruct blk_align_bitmap *bm = &bt->map[i];\n\n\t\tfor (bit = find_first_bit(&bm->word, bm->depth);\n\t\t bit < bm->depth;\n\t\t bit = find_next_bit(&bm->word, bm->depth, bit + 1)) {\n\t\t \trq = blk_mq_tag_to_rq(hctx->tags, off + bit);\n\t\t\tif (rq->q == hctx->queue)\n\t\t\t\tfn(hctx, rq, data, reserved);\n\t\t}\n\n\t\toff += (1 << bt->bits_per_word);\n\t}\n}", "label_name": "CWE-362", "label": 18}
{"code": "CAMLprim value caml_alloc_dummy_float (value size)\n{\n mlsize_t wosize = Int_val(size) * Double_wosize;\n\n if (wosize == 0) return Atom(0);\n return caml_alloc (wosize, 0);\n}", "label_name": "CWE-200", "label": 10}
{"code": "static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct irda_sock *self = irda_sk(sk);\n\tstruct sk_buff *skb;\n\tsize_t copied;\n\tint err;\n\n\tIRDA_DEBUG(4, \"%s()\\n\", __func__);\n\n\tmsg->msg_namelen = 0;\n\n\tskb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,\n\t\t\t\tflags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tskb_reset_transport_header(skb);\n\tcopied = skb->len;\n\n\tif (copied > size) {\n\t\tIRDA_DEBUG(2, \"%s(), Received truncated frame (%zd < %zd)!\\n\",\n\t\t\t __func__, copied, size);\n\t\tcopied = size;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tskb_free_datagram(sk, skb);\n\n\t/*\n\t * Check if we have previously stopped IrTTP and we know\n\t * have more free space in our rx_queue. If so tell IrTTP\n\t * to start delivering frames again before our rx_queue gets\n\t * empty\n\t */\n\tif (self->rx_flow == FLOW_STOP) {\n\t\tif ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {\n\t\t\tIRDA_DEBUG(2, \"%s(), Starting IrTTP\\n\", __func__);\n\t\t\tself->rx_flow = FLOW_START;\n\t\t\tirttp_flow_request(self->tsap, FLOW_START);\n\t\t}\n\t}\n\n\treturn copied;\n}", "label_name": "CWE-20", "label": 0}
{"code": "dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)\n{\n#ifdef CONFIG_DYNAMIC_FTRACE\n\t/*\n\t * ftrace must be first, everything else may cause a recursive crash.\n\t * See note by declaration of modifying_ftrace_code in ftrace.c\n\t */\n\tif (unlikely(atomic_read(&modifying_ftrace_code)) &&\n\t ftrace_int3_handler(regs))\n\t\treturn;\n#endif\n\tif (poke_int3_handler(regs))\n\t\treturn;\n\n\tist_enter(regs);\n\tRCU_LOCKDEP_WARN(!rcu_is_watching(), \"entry code didn't wake RCU\");\n#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP\n\tif (kgdb_ll_trap(DIE_INT3, \"int3\", regs, error_code, X86_TRAP_BP,\n\t\t\t\tSIGTRAP) == NOTIFY_STOP)\n\t\tgoto exit;\n#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */\n\n#ifdef CONFIG_KPROBES\n\tif (kprobe_int3_handler(regs))\n\t\tgoto exit;\n#endif\n\n\tif (notify_die(DIE_INT3, \"int3\", regs, error_code, X86_TRAP_BP,\n\t\t\tSIGTRAP) == NOTIFY_STOP)\n\t\tgoto exit;\n\n\t/*\n\t * Let others (NMI) know that the debug stack is in use\n\t * as we may switch to the interrupt stack.\n\t */\n\tdebug_stack_usage_inc();\n\tcond_local_irq_enable(regs);\n\tdo_trap(X86_TRAP_BP, SIGTRAP, \"int3\", regs, error_code, NULL);\n\tcond_local_irq_disable(regs);\n\tdebug_stack_usage_dec();\nexit:\n\tist_exit(regs);\n}", "label_name": "CWE-362", "label": 18}
{"code": "int sctp_verify_asconf(const struct sctp_association *asoc,\n\t\t struct sctp_paramhdr *param_hdr, void *chunk_end,\n\t\t struct sctp_paramhdr **errp) {\n\tsctp_addip_param_t *asconf_param;\n\tunion sctp_params param;\n\tint length, plen;\n\n\tparam.v = (sctp_paramhdr_t *) param_hdr;\n\twhile (param.v <= chunk_end - sizeof(sctp_paramhdr_t)) {\n\t\tlength = ntohs(param.p->length);\n\t\t*errp = param.p;\n\n\t\tif (param.v > chunk_end - length ||\n\t\t length < sizeof(sctp_paramhdr_t))\n\t\t\treturn 0;\n\n\t\tswitch (param.p->type) {\n\t\tcase SCTP_PARAM_ADD_IP:\n\t\tcase SCTP_PARAM_DEL_IP:\n\t\tcase SCTP_PARAM_SET_PRIMARY:\n\t\t\tasconf_param = (sctp_addip_param_t *)param.v;\n\t\t\tplen = ntohs(asconf_param->param_hdr.length);\n\t\t\tif (plen < sizeof(sctp_addip_param_t) +\n\t\t\t sizeof(sctp_paramhdr_t))\n\t\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase SCTP_PARAM_SUCCESS_REPORT:\n\t\tcase SCTP_PARAM_ADAPTATION_LAYER_IND:\n\t\t\tif (length != sizeof(sctp_addip_param_t))\n\t\t\t\treturn 0;\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tparam.v += WORD_ROUND(length);\n\t}\n\n\tif (param.v != chunk_end)\n\t\treturn 0;\n\n\treturn 1;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static inline u32 net_hash_mix(const struct net *net)\n{\n#ifdef CONFIG_NET_NS\n\treturn (u32)(((unsigned long)net) >> ilog2(sizeof(*net)));\n#else\n\treturn 0;\n#endif\n}", "label_name": "CWE-326", "label": 9}
{"code": "parsegid(const char *s, gid_t *gid)\n{\n\tstruct group *gr;\n\tconst char *errstr;\n\n\tif ((gr = getgrnam(s)) != NULL) {\n\t\t*gid = gr->gr_gid;\n\t\treturn 0;\n\t}\n\t#if !defined(__linux__) && !defined(__NetBSD__)\n\t*gid = strtonum(s, 0, GID_MAX, &errstr);\n\t#else\n\tsscanf(s, \"%d\", gid);\n\t#endif\n\tif (errstr)\n\t\treturn -1;\n\treturn 0;\n}", "label_name": "CWE-754", "label": 31}
{"code": "int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint ret = 0, size = 0;\n\tconst char *name = NULL;\n\tchar *value = NULL;\n\tstruct iattr newattrs;\n\tumode_t new_mode = inode->i_mode, old_mode = inode->i_mode;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\tname = XATTR_NAME_POSIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\tret = posix_acl_equiv_mode(acl, &new_mode);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto out;\n\t\t\tif (ret == 0)\n\t\t\t\tacl = NULL;\n\t\t}\n\t\tbreak;\n\tcase ACL_TYPE_DEFAULT:\n\t\tif (!S_ISDIR(inode->i_mode)) {\n\t\t\tret = acl ? -EINVAL : 0;\n\t\t\tgoto out;\n\t\t}\n\t\tname = XATTR_NAME_POSIX_ACL_DEFAULT;\n\t\tbreak;\n\tdefault:\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tif (acl) {\n\t\tsize = posix_acl_xattr_size(acl->a_count);\n\t\tvalue = kmalloc(size, GFP_NOFS);\n\t\tif (!value) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\n\t\tret = posix_acl_to_xattr(&init_user_ns, acl, value, size);\n\t\tif (ret < 0)\n\t\t\tgoto out_free;\n\t}\n\n\tif (new_mode != old_mode) {\n\t\tnewattrs.ia_mode = new_mode;\n\t\tnewattrs.ia_valid = ATTR_MODE;\n\t\tret = __ceph_setattr(inode, &newattrs);\n\t\tif (ret)\n\t\t\tgoto out_free;\n\t}\n\n\tret = __ceph_setxattr(inode, name, value, size, 0);\n\tif (ret) {\n\t\tif (new_mode != old_mode) {\n\t\t\tnewattrs.ia_mode = old_mode;\n\t\t\tnewattrs.ia_valid = ATTR_MODE;\n\t\t\t__ceph_setattr(inode, &newattrs);\n\t\t}\n\t\tgoto out_free;\n\t}\n\n\tceph_set_cached_acl(inode, type, acl);\n\nout_free:\n\tkfree(value);\nout:\n\treturn ret;\n}", "label_name": "CWE-285", "label": 23}
{"code": "static int filter_frame(AVFilterLink *inlink, AVFrame *in)\n{\n GradFunContext *s = inlink->dst->priv;\n AVFilterLink *outlink = inlink->dst->outputs[0];\n AVFrame *out;\n int p, direct;\n\n if (av_frame_is_writable(in)) {\n direct = 1;\n out = in;\n } else {\n direct = 0;\n out = ff_get_video_buffer(outlink, outlink->w, outlink->h);\n if (!out) {\n av_frame_free(&in);\n return AVERROR(ENOMEM);\n }\n av_frame_copy_props(out, in);\n }\n\n for (p = 0; p < 4 && in->data[p]; p++) {\n int w = inlink->w;\n int h = inlink->h;\n int r = s->radius;\n if (p) {\n w = s->chroma_w;\n h = s->chroma_h;\n r = s->chroma_r;\n }\n\n if (FFMIN(w, h) > 2 * r)\n filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r);\n else if (out->data[p] != in->data[p])\n av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h);\n }\n\n if (!direct)\n av_frame_free(&in);\n\n return ff_filter_frame(outlink, out);\n}", "label_name": "CWE-119", "label": 26}
{"code": "int ext4_orphan_del(handle_t *handle, struct inode *inode)\n{\n\tstruct list_head *prev;\n\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\tstruct ext4_sb_info *sbi;\n\t__u32 ino_next;\n\tstruct ext4_iloc iloc;\n\tint err = 0;\n\n\t/* ext4_handle_valid() assumes a valid handle_t pointer */\n\tif (handle && !ext4_handle_valid(handle))\n\t\treturn 0;\n\n\tmutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);\n\tif (list_empty(&ei->i_orphan))\n\t\tgoto out;\n\n\tino_next = NEXT_ORPHAN(inode);\n\tprev = ei->i_orphan.prev;\n\tsbi = EXT4_SB(inode->i_sb);\n\n\tjbd_debug(4, \"remove inode %lu from orphan list\\n\", inode->i_ino);\n\n\tlist_del_init(&ei->i_orphan);\n\n\t/* If we're on an error path, we may not have a valid\n\t * transaction handle with which to update the orphan list on\n\t * disk, but we still need to remove the inode from the linked\n\t * list in memory. */\n\tif (sbi->s_journal && !handle)\n\t\tgoto out;\n\n\terr = ext4_reserve_inode_write(handle, inode, &iloc);\n\tif (err)\n\t\tgoto out_err;\n\n\tif (prev == &sbi->s_orphan) {\n\t\tjbd_debug(4, \"superblock will point to %u\\n\", ino_next);\n\t\tBUFFER_TRACE(sbi->s_sbh, \"get_write_access\");\n\t\terr = ext4_journal_get_write_access(handle, sbi->s_sbh);\n\t\tif (err)\n\t\t\tgoto out_brelse;\n\t\tsbi->s_es->s_last_orphan = cpu_to_le32(ino_next);\n\t\terr = ext4_handle_dirty_super(handle, inode->i_sb);\n\t} else {\n\t\tstruct ext4_iloc iloc2;\n\t\tstruct inode *i_prev =\n\t\t\t&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;\n\n\t\tjbd_debug(4, \"orphan inode %lu will point to %u\\n\",\n\t\t\t i_prev->i_ino, ino_next);\n\t\terr = ext4_reserve_inode_write(handle, i_prev, &iloc2);\n\t\tif (err)\n\t\t\tgoto out_brelse;\n\t\tNEXT_ORPHAN(i_prev) = ino_next;\n\t\terr = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);\n\t}\n\tif (err)\n\t\tgoto out_brelse;\n\tNEXT_ORPHAN(inode) = 0;\n\terr = ext4_mark_iloc_dirty(handle, inode, &iloc);\n\nout_err:\n\text4_std_error(inode->i_sb, err);\nout:\n\tmutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);\n\treturn err;\n\nout_brelse:\n\tbrelse(iloc.bh);\n\tgoto out_err;\n}", "label_name": "CWE-20", "label": 0}
{"code": "void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)\n{\n\tu64 overrun;\n\n\tlockdep_assert_held(&cfs_b->lock);\n\n\tif (cfs_b->period_active)\n\t\treturn;\n\n\tcfs_b->period_active = 1;\n\toverrun = hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);\n\tcfs_b->runtime_expires += (overrun + 1) * ktime_to_ns(cfs_b->period);\n\tcfs_b->expires_seq++;\n\thrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);\n}", "label_name": "CWE-400", "label": 2}
{"code": "int snd_timer_close(struct snd_timer_instance *timeri)\n{\n\tstruct snd_timer *timer = NULL;\n\tstruct snd_timer_instance *slave, *tmp;\n\n\tif (snd_BUG_ON(!timeri))\n\t\treturn -ENXIO;\n\n\t/* force to stop the timer */\n\tsnd_timer_stop(timeri);\n\n\tif (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {\n\t\t/* wait, until the active callback is finished */\n\t\tspin_lock_irq(&slave_active_lock);\n\t\twhile (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {\n\t\t\tspin_unlock_irq(&slave_active_lock);\n\t\t\tudelay(10);\n\t\t\tspin_lock_irq(&slave_active_lock);\n\t\t}\n\t\tspin_unlock_irq(&slave_active_lock);\n\t\tmutex_lock(®ister_mutex);\n\t\tlist_del(&timeri->open_list);\n\t\tmutex_unlock(®ister_mutex);\n\t} else {\n\t\ttimer = timeri->timer;\n\t\tif (snd_BUG_ON(!timer))\n\t\t\tgoto out;\n\t\t/* wait, until the active callback is finished */\n\t\tspin_lock_irq(&timer->lock);\n\t\twhile (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {\n\t\t\tspin_unlock_irq(&timer->lock);\n\t\t\tudelay(10);\n\t\t\tspin_lock_irq(&timer->lock);\n\t\t}\n\t\tspin_unlock_irq(&timer->lock);\n\t\tmutex_lock(®ister_mutex);\n\t\tlist_del(&timeri->open_list);\n\t\tif (timer && list_empty(&timer->open_list_head) &&\n\t\t timer->hw.close)\n\t\t\ttimer->hw.close(timer);\n\t\t/* remove slave links */\n\t\tlist_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,\n\t\t\t\t\t open_list) {\n\t\t\tspin_lock_irq(&slave_active_lock);\n\t\t\t_snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION);\n\t\t\tlist_move_tail(&slave->open_list, &snd_timer_slave_list);\n\t\t\tslave->master = NULL;\n\t\t\tslave->timer = NULL;\n\t\t\tspin_unlock_irq(&slave_active_lock);\n\t\t}\n\t\tmutex_unlock(®ister_mutex);\n\t}\n out:\n\tif (timeri->private_free)\n\t\ttimeri->private_free(timeri);\n\tkfree(timeri->owner);\n\tkfree(timeri);\n\tif (timer)\n\t\tmodule_put(timer->module);\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)\n{\n\trcu_read_lock();\n\t__ptrace_link(child, new_parent, __task_cred(new_parent));\n\trcu_read_unlock();\n}", "label_name": "CWE-269", "label": 6}
{"code": "static int empty_write_end(struct page *page, unsigned from,\n\t\t\t unsigned to, int mode)\n{\n\tstruct inode *inode = page->mapping->host;\n\tstruct gfs2_inode *ip = GFS2_I(inode);\n\tstruct buffer_head *bh;\n\tunsigned offset, blksize = 1 << inode->i_blkbits;\n\tpgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT;\n\n\tzero_user(page, from, to-from);\n\tmark_page_accessed(page);\n\n\tif (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) {\n\t\tif (!gfs2_is_writeback(ip))\n\t\t\tgfs2_page_add_databufs(ip, page, from, to);\n\n\t\tblock_commit_write(page, from, to);\n\t\treturn 0;\n\t}\n\n\toffset = 0;\n\tbh = page_buffers(page);\n\twhile (offset < to) {\n\t\tif (offset >= from) {\n\t\t\tset_buffer_uptodate(bh);\n\t\t\tmark_buffer_dirty(bh);\n\t\t\tclear_buffer_new(bh);\n\t\t\twrite_dirty_buffer(bh, WRITE);\n\t\t}\n\t\toffset += blksize;\n\t\tbh = bh->b_this_page;\n\t}\n\n\toffset = 0;\n\tbh = page_buffers(page);\n\twhile (offset < to) {\n\t\tif (offset >= from) {\n\t\t\twait_on_buffer(bh);\n\t\t\tif (!buffer_uptodate(bh))\n\t\t\t\treturn -EIO;\n\t\t}\n\t\toffset += blksize;\n\t\tbh = bh->b_this_page;\n\t}\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)\n{\tSF_PRIVATE *psf = (SF_PRIVATE*) client_data ;\n\tFLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;\n\n\tpflac->frame = frame ;\n\tpflac->bufferpos = 0 ;\n\n\tpflac->bufferbackup = SF_FALSE ;\n\tpflac->wbuffer = buffer ;\n\n\tflac_buffer_copy (psf) ;\n\n\treturn FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;\n} /* sf_flac_write_callback */", "label_name": "CWE-119", "label": 26}
{"code": "videobuf_vm_open(struct vm_area_struct *vma)\n{\n\tstruct videobuf_mapping *map = vma->vm_private_data;\n\n\tdprintk(2,\"vm_open %p [count=%d,vma=%08lx-%08lx]\\n\",map,\n\t\tmap->count,vma->vm_start,vma->vm_end);\n\n\tmap->count++;\n}", "label_name": "CWE-119", "label": 26}
{"code": "int irssi_ssl_handshake(GIOChannel *handle)\n{\n\tGIOSSLChannel *chan = (GIOSSLChannel *)handle;\n\tint ret, err;\n\tX509 *cert;\n\tconst char *errstr;\n\n\tret = SSL_connect(chan->ssl);\n\tif (ret <= 0) {\n\t\terr = SSL_get_error(chan->ssl, ret);\n\t\tswitch (err) {\n\t\t\tcase SSL_ERROR_WANT_READ:\n\t\t\t\treturn 1;\n\t\t\tcase SSL_ERROR_WANT_WRITE:\n\t\t\t\treturn 3;\n\t\t\tcase SSL_ERROR_ZERO_RETURN:\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", \"server closed connection\");\n\t\t\t\treturn -1;\n\t\t\tcase SSL_ERROR_SYSCALL:\n\t\t\t\terrstr = ERR_reason_error_string(ERR_get_error());\n\t\t\t\tif (errstr == NULL && ret == -1)\n\t\t\t\t\terrstr = strerror(errno);\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", errstr != NULL ? errstr : \"server closed connection unexpectedly\");\n\t\t\t\treturn -1;\n\t\t\tdefault:\n\t\t\t\terrstr = ERR_reason_error_string(ERR_get_error());\n\t\t\t\tg_warning(\"SSL handshake failed: %s\", errstr != NULL ? errstr : \"unknown SSL error\");\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\n\tcert = SSL_get_peer_certificate(chan->ssl);\n\tif (cert == NULL) {\n\t\tg_warning(\"SSL server supplied no certificate\");\n\t\treturn -1;\n\t}\n\tret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert);\n\tX509_free(cert);\n\treturn ret ? 0 : -1;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey)\n{\n\tint ok = 0;\n\tunsigned char challenge[30];\n\tunsigned char signature[256];\n\tunsigned int siglen = sizeof signature;\n\tconst EVP_MD *md = EVP_sha1();\n\tEVP_MD_CTX *md_ctx = EVP_MD_CTX_new();\n\tEVP_PKEY *privkey = PKCS11_get_private_key(authkey);\n\tEVP_PKEY *pubkey = PKCS11_get_public_key(authkey);\n\n\t/* Verify a SHA-1 hash of random data, signed by the key.\n\t *\n\t * Note that this will not work keys that aren't eligible for signing.\n\t * Unfortunately, libp11 currently has no way of checking\n\t * C_GetAttributeValue(CKA_SIGN), see\n\t * https://github.com/OpenSC/libp11/issues/219. Since we don't want to\n\t * implement try and error, we live with this limitation */\n\tif (1 != randomize(pamh, challenge, sizeof challenge)) {\n\t\tgoto err;\n\t}\n\tif (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md\n\t\t\t|| !EVP_SignInit(md_ctx, md)\n\t\t\t|| !EVP_SignUpdate(md_ctx, challenge, sizeof challenge)\n\t\t\t|| !EVP_SignFinal(md_ctx, signature, &siglen, privkey)\n\t\t\t|| !EVP_MD_CTX_reset(md_ctx)\n\t\t\t|| !EVP_VerifyInit(md_ctx, md)\n\t\t\t|| !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge)\n\t\t\t|| 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) {\n\t\tpam_syslog(pamh, LOG_DEBUG, \"Error verifying key: %s\\n\",\n\t\t\t\tERR_reason_error_string(ERR_get_error()));\n\t\tprompt(flags, pamh, PAM_ERROR_MSG, NULL, _(\"Error verifying key\"));\n\t\tgoto err;\n\t}\n\tok = 1;\n\nerr:\n\tif (NULL != pubkey)\n\t\tEVP_PKEY_free(pubkey);\n\tif (NULL != privkey)\n\t\tEVP_PKEY_free(privkey);\n\tif (NULL != md_ctx) {\n\t\tEVP_MD_CTX_free(md_ctx);\n\t}\n\treturn ok;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static VALUE cState_space_set(VALUE self, VALUE space)\n{\n unsigned long len;\n GET_STATE(self);\n Check_Type(space, T_STRING);\n len = RSTRING_LEN(space);\n if (len == 0) {\n if (state->space) {\n ruby_xfree(state->space);\n state->space = NULL;\n state->space_len = 0;\n }\n } else {\n if (state->space) ruby_xfree(state->space);\n state->space = strdup(RSTRING_PTR(space));\n state->space_len = len;\n }\n return Qnil;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static enum try_read_result try_read_network(conn *c) {\n enum try_read_result gotdata = READ_NO_DATA_RECEIVED;\n int res;\n\n assert(c != NULL);\n\n if (c->rcurr != c->rbuf) {\n if (c->rbytes != 0) /* otherwise there's nothing to copy */\n memmove(c->rbuf, c->rcurr, c->rbytes);\n c->rcurr = c->rbuf;\n }\n\n while (1) {\n if (c->rbytes >= c->rsize) {\n char *new_rbuf = realloc(c->rbuf, c->rsize * 2);\n if (!new_rbuf) {\n if (settings.verbose > 0)\n fprintf(stderr, \"Couldn't realloc input buffer\\n\");\n c->rbytes = 0; /* ignore what we read */\n out_string(c, \"SERVER_ERROR out of memory reading request\");\n c->write_and_go = conn_closing;\n return READ_MEMORY_ERROR;\n }\n c->rcurr = c->rbuf = new_rbuf;\n c->rsize *= 2;\n }\n\n int avail = c->rsize - c->rbytes;\n res = read(c->sfd, c->rbuf + c->rbytes, avail);\n if (res > 0) {\n pthread_mutex_lock(&c->thread->stats.mutex);\n c->thread->stats.bytes_read += res;\n pthread_mutex_unlock(&c->thread->stats.mutex);\n gotdata = READ_DATA_RECEIVED;\n c->rbytes += res;\n if (res == avail) {\n continue;\n } else {\n break;\n }\n }\n if (res == 0) {\n return READ_ERROR;\n }\n if (res == -1) {\n if (errno == EAGAIN || errno == EWOULDBLOCK) {\n break;\n }\n return READ_ERROR;\n }\n }\n return gotdata;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static Var* Pe_r_bin_pe_parse_var(RBinPEObj* pe, PE_DWord* curAddr) {\n\tVar* var = calloc (1, sizeof (*var));\n\tif (!var) {\n\t\tpe_printf (\"Warning: calloc (Var)\\n\");\n\t\treturn NULL;\n\t}\n\tif ((var->wLength = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wLength)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wLength);\n\tif ((var->wValueLength = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wValueLength)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wValueLength);\n\tif ((var->wType = r_buf_read_le16_at (pe->b, *curAddr)) == UT16_MAX) {\n\t\tpe_printf (\"Warning: read (Var wType)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += sizeof (var->wType);\n\tif (var->wType != 0 && var->wType != 1) {\n\t\tpe_printf (\"Warning: check (Var wType)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\n\tvar->szKey = (ut16*) malloc (UT16_ALIGN (TRANSLATION_UTF_16_LEN)); //L\"Translation\"\n\tif (!var->szKey) {\n\t\tpe_printf (\"Warning: malloc (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tif (r_buf_read_at (pe->b, *curAddr, (ut8*) var->szKey, TRANSLATION_UTF_16_LEN) < 1) {\n\t\tpe_printf (\"Warning: read (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += TRANSLATION_UTF_16_LEN;\n\tif (memcmp (var->szKey, TRANSLATION_UTF_16, TRANSLATION_UTF_16_LEN)) {\n\t\tpe_printf (\"Warning: check (Var szKey)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\talign32 (*curAddr);\n\tvar->numOfValues = var->wValueLength / 4;\n\tif (!var->numOfValues) {\n\t\tpe_printf (\"Warning: check (Var numOfValues)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tvar->Value = (ut32*) malloc (var->wValueLength);\n\tif (!var->Value) {\n\t\tpe_printf (\"Warning: malloc (Var Value)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\tif (r_buf_read_at (pe->b, *curAddr, (ut8*) var->Value, var->wValueLength) != var->wValueLength) {\n\t\tpe_printf (\"Warning: read (Var Value)\\n\");\n\t\tfree_Var (var);\n\t\treturn NULL;\n\t}\n\t*curAddr += var->wValueLength;\n\treturn var;\n}", "label_name": "CWE-400", "label": 2}
{"code": "static void slc_bump(struct slcan *sl)\n{\n\tstruct sk_buff *skb;\n\tstruct can_frame cf;\n\tint i, tmp;\n\tu32 tmpid;\n\tchar *cmd = sl->rbuff;\n\n\tcf.can_id = 0;\n\n\tswitch (*cmd) {\n\tcase 'r':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 't':\n\t\t/* store dlc ASCII value and terminate SFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1;\n\t\tbreak;\n\tcase 'R':\n\t\tcf.can_id = CAN_RTR_FLAG;\n\t\t/* fallthrough */\n\tcase 'T':\n\t\tcf.can_id |= CAN_EFF_FLAG;\n\t\t/* store dlc ASCII value and terminate EFF CAN ID string */\n\t\tcf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN];\n\t\tsl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0;\n\t\t/* point to payload data behind the dlc */\n\t\tcmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1;\n\t\tbreak;\n\tdefault:\n\t\treturn;\n\t}\n\n\tif (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid))\n\t\treturn;\n\n\tcf.can_id |= tmpid;\n\n\t/* get can_dlc from sanitized ASCII value */\n\tif (cf.can_dlc >= '0' && cf.can_dlc < '9')\n\t\tcf.can_dlc -= '0';\n\telse\n\t\treturn;\n\n\t*(u64 *) (&cf.data) = 0; /* clear payload */\n\n\t/* RTR frames may have a dlc > 0 but they never have any data bytes */\n\tif (!(cf.can_id & CAN_RTR_FLAG)) {\n\t\tfor (i = 0; i < cf.can_dlc; i++) {\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] = (tmp << 4);\n\t\t\ttmp = hex_to_bin(*cmd++);\n\t\t\tif (tmp < 0)\n\t\t\t\treturn;\n\t\t\tcf.data[i] |= tmp;\n\t\t}\n\t}\n\n\tskb = dev_alloc_skb(sizeof(struct can_frame) +\n\t\t\t sizeof(struct can_skb_priv));\n\tif (!skb)\n\t\treturn;\n\n\tskb->dev = sl->dev;\n\tskb->protocol = htons(ETH_P_CAN);\n\tskb->pkt_type = PACKET_BROADCAST;\n\tskb->ip_summed = CHECKSUM_UNNECESSARY;\n\n\tcan_skb_reserve(skb);\n\tcan_skb_prv(skb)->ifindex = sl->dev->ifindex;\n\tcan_skb_prv(skb)->skbcnt = 0;\n\n\tskb_put_data(skb, &cf, sizeof(struct can_frame));\n\n\tsl->dev->stats.rx_packets++;\n\tsl->dev->stats.rx_bytes += cf.can_dlc;\n\tnetif_rx_ni(skb);\n}", "label_name": "CWE-909", "label": 25}
{"code": "const char * util_acl_to_str(const sc_acl_entry_t *e)\n{\n\tstatic char line[80], buf[20];\n\tunsigned int acl;\n\n\tif (e == NULL)\n\t\treturn \"N/A\";\n\tline[0] = 0;\n\twhile (e != NULL) {\n\t\tacl = e->method;\n\n\t\tswitch (acl) {\n\t\tcase SC_AC_UNKNOWN:\n\t\t\treturn \"N/A\";\n\t\tcase SC_AC_NEVER:\n\t\t\treturn \"NEVR\";\n\t\tcase SC_AC_NONE:\n\t\t\treturn \"NONE\";\n\t\tcase SC_AC_CHV:\n\t\t\tstrcpy(buf, \"CHV\");\n\t\t\tif (e->key_ref != SC_AC_KEY_REF_NONE)\n\t\t\t\tsprintf(buf + 3, \"%d\", e->key_ref);\n\t\t\tbreak;\n\t\tcase SC_AC_TERM:\n\t\t\tstrcpy(buf, \"TERM\");\n\t\t\tbreak;\n\t\tcase SC_AC_PRO:\n\t\t\tstrcpy(buf, \"PROT\");\n\t\t\tbreak;\n\t\tcase SC_AC_AUT:\n\t\t\tstrcpy(buf, \"AUTH\");\n\t\t\tif (e->key_ref != SC_AC_KEY_REF_NONE)\n\t\t\t\tsprintf(buf + 4, \"%d\", e->key_ref);\n\t\t\tbreak;\n\t\tcase SC_AC_SEN:\n\t\t\tstrcpy(buf, \"Sec.Env. \");\n\t\t\tif (e->key_ref != SC_AC_KEY_REF_NONE)\n\t\t\t\tsprintf(buf + 3, \"#%d\", e->key_ref);\n\t\t\tbreak;\n\t\tcase SC_AC_SCB:\n\t\t\tstrcpy(buf, \"Sec.ControlByte \");\n\t\t\tif (e->key_ref != SC_AC_KEY_REF_NONE)\n\t\t\t\tsprintf(buf + 3, \"Ox%X\", e->key_ref);\n\t\t\tbreak;\n\t\tcase SC_AC_IDA:\n\t\t\tstrcpy(buf, \"PKCS#15 AuthID \");\n\t\t\tif (e->key_ref != SC_AC_KEY_REF_NONE)\n\t\t\t\tsprintf(buf + 3, \"#%d\", e->key_ref);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstrcpy(buf, \"????\");\n\t\t\tbreak;\n\t\t}\n\t\tstrcat(line, buf);\n\t\tstrcat(line, \" \");\n\t\te = e->next;\n\t}\n\tline[strlen(line)-1] = 0; /* get rid of trailing space */\n\treturn line;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static pfunc check_literal(struct jv_parser* p) {\n if (p->tokenpos == 0) return 0;\n\n const char* pattern = 0;\n int plen;\n jv v;\n switch (p->tokenbuf[0]) {\n case 't': pattern = \"true\"; plen = 4; v = jv_true(); break;\n case 'f': pattern = \"false\"; plen = 5; v = jv_false(); break;\n case 'n': pattern = \"null\"; plen = 4; v = jv_null(); break;\n }\n if (pattern) {\n if (p->tokenpos != plen) return \"Invalid literal\";\n for (int i=0; i<plen; i++)\n if (p->tokenbuf[i] != pattern[i])\n return \"Invalid literal\";\n TRY(value(p, v));\n } else {\n // FIXME: better parser\n p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid\n char* end = 0;\n double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end);\n if (end == 0 || *end != 0)\n return \"Invalid numeric literal\";\n TRY(value(p, jv_number(d)));\n }\n p->tokenpos = 0;\n return 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)\n\t{\tpsf->header [psf->headindex++] = x ;\n\t\tpsf->header [psf->headindex++] = (x >> 8) ;\n\t\tpsf->header [psf->headindex++] = (x >> 16) ;\n\t\tpsf->header [psf->headindex++] = (x >> 24) ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\tpsf->header [psf->headindex++] = 0 ;\n\t\t} ;\n} /* header_put_le_8byte */", "label_name": "CWE-119", "label": 26}
{"code": "cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,\n size_t len, const cdf_header_t *h, cdf_secid_t id)\n{\n\tsize_t ss = CDF_SHORT_SEC_SIZE(h);\n\tsize_t pos = CDF_SHORT_SEC_POS(h, id);\n\tassert(ss == len);\n\tif (pos > CDF_SEC_SIZE(h) * sst->sst_len) {\n\t\tDPRINTF((\"Out of bounds read %\" SIZE_T_FORMAT \"u > %\"\n\t\t SIZE_T_FORMAT \"u\\n\",\n\t\t pos, CDF_SEC_SIZE(h) * sst->sst_len));\n\t\treturn -1;\n\t}\n\t(void)memcpy(((char *)buf) + offs,\n\t ((const char *)sst->sst_tab) + pos, len);\n\treturn len;\n}", "label_name": "CWE-119", "label": 26}
{"code": "int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n\t\t\t size_t sec_attr_len)\n{\n\tu8 *tmp;\n\tif (!sc_file_valid(file)) {\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\t}\n\n\tif (sec_attr == NULL) {\n\t\tif (file->sec_attr != NULL)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn 0;\n\t }\n\ttmp = (u8 *) realloc(file->sec_attr, sec_attr_len);\n\tif (!tmp) {\n\t\tif (file->sec_attr)\n\t\t\tfree(file->sec_attr);\n\t\tfile->sec_attr = NULL;\n\t\tfile->sec_attr_len = 0;\n\t\treturn SC_ERROR_OUT_OF_MEMORY;\n\t}\n\tfile->sec_attr = tmp;\n\tmemcpy(file->sec_attr, sec_attr, sec_attr_len);\n\tfile->sec_attr_len = sec_attr_len;\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static long madvise_remove(struct vm_area_struct *vma,\n\t\t\t\tstruct vm_area_struct **prev,\n\t\t\t\tunsigned long start, unsigned long end)\n{\n\tloff_t offset;\n\tint error;\n\n\t*prev = NULL;\t/* tell sys_madvise we drop mmap_sem */\n\n\tif (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB))\n\t\treturn -EINVAL;\n\n\tif (!vma->vm_file || !vma->vm_file->f_mapping\n\t\t|| !vma->vm_file->f_mapping->host) {\n\t\t\treturn -EINVAL;\n\t}\n\n\tif ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))\n\t\treturn -EACCES;\n\n\toffset = (loff_t)(start - vma->vm_start)\n\t\t\t+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);\n\n\t/* filesystem's fallocate may need to take i_mutex */\n\tup_read(¤t->mm->mmap_sem);\n\terror = do_fallocate(vma->vm_file,\n\t\t\t\tFALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,\n\t\t\t\toffset, end - start);\n\tdown_read(¤t->mm->mmap_sem);\n\treturn error;\n}", "label_name": "CWE-362", "label": 18}
{"code": "static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)\n{\n HTTPContext *s = h->priv_data;\n URLContext *old_hd = s->hd;\n int64_t old_off = s->off;\n uint8_t old_buf[BUFFER_SIZE];\n int old_buf_size, ret;\n AVDictionary *options = NULL;\n\n if (whence == AVSEEK_SIZE)\n return s->filesize;\n else if (!force_reconnect &&\n ((whence == SEEK_CUR && off == 0) ||\n (whence == SEEK_SET && off == s->off)))\n return s->off;\n else if ((s->filesize == -1 && whence == SEEK_END))\n return AVERROR(ENOSYS);\n\n if (whence == SEEK_CUR)\n off += s->off;\n else if (whence == SEEK_END)\n off += s->filesize;\n else if (whence != SEEK_SET)\n return AVERROR(EINVAL);\n if (off < 0)\n return AVERROR(EINVAL);\n s->off = off;\n\n if (s->off && h->is_streamed)\n return AVERROR(ENOSYS);\n\n /* we save the old context in case the seek fails */\n old_buf_size = s->buf_end - s->buf_ptr;\n memcpy(old_buf, s->buf_ptr, old_buf_size);\n s->hd = NULL;\n\n /* if it fails, continue on old connection */\n if ((ret = http_open_cnx(h, &options)) < 0) {\n av_dict_free(&options);\n memcpy(s->buffer, old_buf, old_buf_size);\n s->buf_ptr = s->buffer;\n s->buf_end = s->buffer + old_buf_size;\n s->hd = old_hd;\n s->off = old_off;\n return ret;\n }\n av_dict_free(&options);\n ffurl_close(old_hd);\n return off;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev,\n\t\t\tstruct rf_tech_specific_params_nfcb_poll *nfcb_poll,\n\t\t\t\t\t\t __u8 *data)\n{\n\tnfcb_poll->sensb_res_len = *data++;\n\n\tpr_debug(\"sensb_res_len %d\\n\", nfcb_poll->sensb_res_len);\n\n\tmemcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len);\n\tdata += nfcb_poll->sensb_res_len;\n\n\treturn data;\n}", "label_name": "CWE-119", "label": 26}
{"code": "static void process_blob(struct rev_info *revs,\n\t\t\t struct blob *blob,\n\t\t\t show_object_fn show,\n\t\t\t struct strbuf *path,\n\t\t\t const char *name,\n\t\t\t void *cb_data)\n{\n\tstruct object *obj = &blob->object;\n\n\tif (!revs->blob_objects)\n\t\treturn;\n\tif (!obj)\n\t\tdie(\"bad blob object\");\n\tif (obj->flags & (UNINTERESTING | SEEN))\n\t\treturn;\n\tobj->flags |= SEEN;\n\tshow(obj, path, name, cb_data);\n}", "label_name": "CWE-119", "label": 26}
{"code": "def _decompressContent(response, new_content):\n content = new_content\n try:\n encoding = response.get(\"content-encoding\", None)\n if encoding in [\"gzip\", \"deflate\"]:\n if encoding == \"gzip\":\n content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()\n if encoding == \"deflate\":\n content = zlib.decompress(content, -zlib.MAX_WBITS)\n response[\"content-length\"] = str(len(content))\n # Record the historical presence of the encoding in a way the won't interfere.\n response[\"-content-encoding\"] = response[\"content-encoding\"]\n del response[\"content-encoding\"]\n except (IOError, zlib.error):\n content = \"\"\n raise FailedToDecompressContent(\n _(\"Content purported to be compressed with %s but failed to decompress.\")\n % response.get(\"content-encoding\"),\n response,\n content,\n )\n return content", "label_name": "CWE-400", "label": 2}
{"code": "def test_digest_auth_stale():\n # Test that we can handle a nonce becoming stale\n http = httplib2.Http()\n password = tests.gen_password()\n grenew_nonce = [None]\n requests = []\n handler = tests.http_reflect_with_auth(\n allow_scheme=\"digest\",\n allow_credentials=((\"joe\", password),),\n out_renew_nonce=grenew_nonce,\n out_requests=requests,\n )\n with tests.server_request(handler, request_count=4) as uri:\n http.add_credentials(\"joe\", password)\n response, _ = http.request(uri, \"GET\")\n assert response.status == 200\n info = httplib2._parse_www_authenticate(\n requests[0][1].headers, \"www-authenticate\"\n )\n grenew_nonce[0]()\n response, _ = http.request(uri, \"GET\")\n assert response.status == 200\n assert not response.fromcache\n assert getattr(response, \"_stale_digest\", False)\n info2 = httplib2._parse_www_authenticate(\n requests[2][1].headers, \"www-authenticate\"\n )\n nonce1 = info.get(\"digest\", {}).get(\"nonce\", \"\")\n nonce2 = info2.get(\"digest\", {}).get(\"nonce\", \"\")\n assert nonce1 != \"\"\n assert nonce2 != \"\"\n assert nonce1 != nonce2, (nonce1, nonce2)", "label_name": "CWE-400", "label": 2}
{"code": "def test_digest_object_auth_info():\n credentials = (\"joe\", \"password\")\n host = None\n request_uri = \"/digest/nextnonce/\"\n headers = {}\n response = httplib2.Response({})\n response[\"www-authenticate\"] = (\n 'Digest realm=\"myrealm\", nonce=\"barney\", '\n 'algorithm=MD5, qop=\"auth\", stale=true'\n )\n response[\"authentication-info\"] = 'nextnonce=\"fred\"'\n content = b\"\"\n d = httplib2.DigestAuthentication(\n credentials, host, request_uri, headers, response, content, None\n )\n # Returns true to force a retry\n assert not d.response(response, content)\n assert d.challenge[\"nonce\"] == \"fred\"\n assert d.challenge[\"nc\"] == 1", "label_name": "CWE-400", "label": 2}
{"code": " def server_socket_thread(srv):\n try:\n while gcounter[0] < request_count:\n try:\n client, _ = srv.accept()\n except ssl.SSLError as e:\n if e.reason in tls_skip_errors:\n return\n raise\n\n try:\n client.settimeout(timeout)\n fun(client, tick)\n finally:\n try:\n client.shutdown(socket.SHUT_RDWR)\n except (IOError, socket.error):\n pass\n # FIXME: client.close() introduces connection reset by peer\n # at least in other/connection_close test\n # should not be a problem since socket would close upon garbage collection\n if gcounter[0] > request_count:\n gresult[0] = Exception(\n \"Request count expected={0} actual={1}\".format(\n request_count, gcounter[0]\n )\n )\n except Exception as e:\n # traceback.print_exc caused IOError: concurrent operation on sys.stderr.close() under setup.py test\n print(traceback.format_exc(), file=sys.stderr)\n gresult[0] = e", "label_name": "CWE-400", "label": 2}
{"code": " def __init__(\n self,\n host,\n port=None,\n key_file=None,\n cert_file=None,\n strict=None,\n timeout=None,\n proxy_info=None,", "label_name": "CWE-400", "label": 2}
{"code": " def read_config(self, config, **kwargs):\n consent_config = config.get(\"user_consent\")\n self.terms_template = self.read_templates([\"terms.html\"], autoescape=True)[0]\n\n if consent_config is None:\n return\n self.user_consent_version = str(consent_config[\"version\"])\n self.user_consent_template_dir = self.abspath(consent_config[\"template_dir\"])\n if not path.isdir(self.user_consent_template_dir):\n raise ConfigError(\n \"Could not find template directory '%s'\"\n % (self.user_consent_template_dir,)\n )\n self.user_consent_server_notice_content = consent_config.get(\n \"server_notice_content\"\n )\n self.block_events_without_consent_error = consent_config.get(\n \"block_events_error\"\n )\n self.user_consent_server_notice_to_guests = bool(\n consent_config.get(\"send_server_notice_to_guests\", False)\n )\n self.user_consent_at_registration = bool(\n consent_config.get(\"require_at_registration\", False)\n )\n self.user_consent_policy_name = consent_config.get(\n \"policy_name\", \"Privacy Policy\"\n )", "label_name": "CWE-74", "label": 1}
{"code": " def from_xml(self, content):\n \"\"\"\n Given some XML data, returns a Python dictionary of the decoded data.\n \"\"\"\n if lxml is None:\n raise ImproperlyConfigured(\"Usage of the XML aspects requires lxml.\")\n \n return self.from_etree(parse_xml(StringIO(content)).getroot())", "label_name": "CWE-20", "label": 0}
{"code": " def set_admins(self) -> None:\n name = self.results[\"deploy\"][\"func-name\"][\"value\"]\n key = self.results[\"deploy\"][\"func-key\"][\"value\"]\n table_service = TableService(account_name=name, account_key=key)\n if self.admins:\n update_admins(table_service, self.application_name, self.admins)", "label_name": "CWE-346", "label": 16}
{"code": "def crawl_items(spider_cls, resource_cls, settings, spider_kwargs=None):\n \"\"\" Use spider_cls to crawl resource_cls. URL of the resource is passed\n to the spider as ``url`` argument.\n Return ``(items, resource_url, crawler)`` tuple.\n \"\"\"\n spider_kwargs = {} if spider_kwargs is None else spider_kwargs\n crawler = make_crawler(spider_cls, settings)\n with MockServer(resource_cls) as s:\n root_url = s.root_url\n yield crawler.crawl(url=root_url, **spider_kwargs)\n result = crawler.spider.collected_items, s.root_url, crawler\n returnValue(result)", "label_name": "CWE-200", "label": 10}
{"code": " def __init__(\n self,\n *,\n resource_group: str,\n location: str,\n application_name: str,\n owner: str,\n client_id: Optional[str],\n client_secret: Optional[str],\n app_zip: str,\n tools: str,\n instance_specific: str,\n third_party: str,\n arm_template: str,\n workbook_data: str,\n create_registration: bool,\n migrations: List[str],\n export_appinsights: bool,\n log_service_principal: bool,\n multi_tenant_domain: str,\n upgrade: bool,\n subscription_id: Optional[str],\n admins: List[UUID]", "label_name": "CWE-285", "label": 23}
{"code": " def _affinity_host(self, context, instance_id):\n return self.compute_api.get(context, instance_id)['host']", "label_name": "CWE-20", "label": 0}
{"code": " def CreateAuthenticator():\n \"\"\"Create a packet autenticator. All RADIUS packets contain a sixteen\n byte authenticator which is used to authenticate replies from the\n RADIUS server and in the password hiding algorithm. This function\n returns a suitable random string that can be used as an authenticator.\n\n :return: valid packet authenticator\n :rtype: binary string\n \"\"\"\n\n data = []\n for i in range(16):\n data.append(random.randrange(0, 256))\n if six.PY3:\n return bytes(data)\n else:\n return ''.join(chr(b) for b in data)", "label_name": "CWE-20", "label": 0}
{"code": " def post(self, request):\n totp_secret = pyotp.random_base32()\n request.user.totp_secret = totp_secret\n request.user.totp_status = TOTPStatus.VERIFYING\n request.user.save()\n add_2fa.send(sender=self.__class__, user=request.user)\n return FormattedResponse({\"totp_secret\": totp_secret})", "label_name": "CWE-287", "label": 4}
{"code": " def _auth_from_challenge(self, host, request_uri, headers, response, content):\n \"\"\"A generator that creates Authorization objects\n that can be applied to requests.\n \"\"\"\n challenges = _parse_www_authenticate(response, \"www-authenticate\")\n for cred in self.credentials.iter(host):\n for scheme in AUTH_SCHEME_ORDER:\n if scheme in challenges:\n yield AUTH_SCHEME_CLASSES[scheme](\n cred, host, request_uri, headers, response, content, self\n )", "label_name": "CWE-400", "label": 2}
{"code": " def test_auth_plugin_prompt_password_in_session(self, httpbin):\n self.start_session(httpbin)\n session_path = self.config_dir / 'test-session.json'\n\n class Plugin(AuthPlugin):\n auth_type = 'test-prompted'\n\n def get_auth(self, username=None, password=None):\n basic_auth_header = \"Basic \" + b64encode(self.raw_auth.encode()).strip().decode('latin1')\n return basic_auth(basic_auth_header)\n\n plugin_manager.register(Plugin)\n\n with mock.patch(\n 'httpie.cli.argtypes.AuthCredentials._getpass',\n new=lambda self, prompt: 'password'\n ):\n r1 = http(\n '--session', str(session_path),\n httpbin + '/basic-auth/user/password',\n '--auth-type',\n Plugin.auth_type,\n '--auth', 'user',\n )\n\n r2 = http(\n '--session', str(session_path),\n httpbin + '/basic-auth/user/password',\n )\n assert HTTP_OK in r1\n assert HTTP_OK in r2\n\n # additional test for issue: https://github.com/httpie/httpie/issues/1098\n with open(session_path) as session_file:\n session_file_lines = ''.join(session_file.readlines())\n assert \"\\\"type\\\": \\\"test-prompted\\\"\" in session_file_lines\n assert \"\\\"raw_auth\\\": \\\"user:password\\\"\" in session_file_lines\n\n plugin_manager.unregister(Plugin)", "label_name": "CWE-200", "label": 10}
{"code": "def test_digest():\n # Test that we support Digest Authentication\n http = httplib2.Http()\n password = tests.gen_password()\n handler = tests.http_reflect_with_auth(\n allow_scheme=\"digest\", allow_credentials=((\"joe\", password),)\n )\n with tests.server_request(handler, request_count=3) as uri:\n response, content = http.request(uri, \"GET\")\n assert response.status == 401\n http.add_credentials(\"joe\", password)\n response, content = http.request(uri, \"GET\")\n assert response.status == 200, content.decode()", "label_name": "CWE-400", "label": 2}
{"code": "def main(req: func.HttpRequest) -> func.HttpResponse:\n response = ok(\n Info(\n resource_group=get_base_resource_group(),\n region=get_base_region(),\n subscription=get_subscription(),\n versions=versions(),\n instance_id=get_instance_id(),\n insights_appid=get_insights_appid(),\n insights_instrumentation_key=get_insights_instrumentation_key(),\n )\n )\n\n return response", "label_name": "CWE-346", "label": 16}
{"code": " def _lookup(self, name, *args, **kwargs):\n instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)\n\n if instance is not None:\n wantlist = kwargs.pop('wantlist', False)\n\n from ansible.utils.listify import listify_lookup_plugin_terms\n loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)\n # safely catch run failures per #5059\n try:\n ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)\n except (AnsibleUndefinedVariable, UndefinedError) as e:\n raise AnsibleUndefinedVariable(e)\n except Exception as e:\n if self._fail_on_lookup_errors:\n raise AnsibleError(\"An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, \"\n \"original message: %s\" % (name, type(e), e))\n ran = None\n\n if ran:\n if wantlist:\n ran = wrap_var(ran)\n else:\n try:\n ran = UnsafeProxy(\",\".join(ran))\n except TypeError:\n if isinstance(ran, list) and len(ran) == 1:\n ran = wrap_var(ran[0])\n else:\n ran = wrap_var(ran)\n\n return ran\n else:\n raise AnsibleError(\"lookup plugin (%s) not found\" % name)", "label_name": "CWE-20", "label": 0}
{"code": " def setUp(self):\n shape = (2, 4, 3)\n rand = np.random.random\n self.x = rand(shape) + rand(shape).astype(np.complex)*1j\n self.x[0,:, 1] = [nan, inf, -inf, nan]\n self.dtype = self.x.dtype\n self.filename = tempfile.mktemp()", "label_name": "CWE-20", "label": 0}
{"code": " def CreateID(self):\n \"\"\"Create a packet ID. All RADIUS requests have a ID which is used to\n identify a request. This is used to detect retries and replay attacks.\n This function returns a suitable random number that can be used as ID.\n\n :return: ID number\n :rtype: integer\n\n \"\"\"\n return random.randrange(0, 256)", "label_name": "CWE-20", "label": 0}
{"code": "def accounts_home_from_multiuse_invite(request: HttpRequest, confirmation_key: str) -> HttpResponse:\n multiuse_object = None\n try:\n multiuse_object = get_object_from_key(confirmation_key, [Confirmation.MULTIUSE_INVITE])\n # Required for OAuth 2\n except ConfirmationKeyException as exception:\n realm = get_realm_from_request(request)\n if realm is None or realm.invite_required:\n return render_confirmation_key_error(request, exception)\n return accounts_home(\n request, multiuse_object_key=confirmation_key, multiuse_object=multiuse_object\n )", "label_name": "CWE-863", "label": 11}
{"code": " def get_auth(self, username=None, password=None):\n basic_auth_header = \"Basic \" + b64encode(self.raw_auth.encode()).strip().decode('latin1')\n return basic_auth(basic_auth_header)", "label_name": "CWE-200", "label": 10}
{"code": " def publish(self, id_, identity, uow=None):\n \"\"\"Publish a draft.\n\n Idea:\n - Get the draft from the data layer (draft is not passed in)\n - Validate it more strictly than when it was originally saved\n (drafts can be incomplete but only complete drafts can be turned\n into records)\n - Create or update associated (published) record with data\n \"\"\"\n self.require_permission(identity, \"publish\")\n\n # Get the draft\n draft = self.draft_cls.pid.resolve(id_, registered_only=False)\n\n # Validate the draft strictly - since a draft can be saved with errors\n # we do a strict validation here to make sure only valid drafts can be\n # published.\n self._validate_draft(identity, draft)\n\n # Create the record from the draft\n latest_id = draft.versions.latest_id\n record = self.record_cls.publish(draft)\n\n # Run components\n self.run_components(\n 'publish', identity, draft=draft, record=record, uow=uow)\n\n # Commit and index\n uow.register(RecordCommitOp(record, indexer=self.indexer))\n uow.register(RecordDeleteOp(draft, force=False, indexer=self.indexer))\n\n if latest_id:\n self._reindex_latest(latest_id, uow=uow)\n\n return self.result_item(\n self, identity, record, links_tpl=self.links_item_tpl)", "label_name": "CWE-863", "label": 11}
{"code": " def _redirect_request_using_get(self, request, redirect_url):\n redirected = request.replace(url=redirect_url, method='GET', body='')\n redirected.headers.pop('Content-Type', None)\n redirected.headers.pop('Content-Length', None)\n return redirected", "label_name": "CWE-863", "label": 11}
{"code": "def useruid(s, login):\n \"\"\"Connect to a LDAP and check the uid matching the given field data\"\"\"\n uid = False\n c = Connection(s, config.LDAPACC, \n password=config.LDAPPASS, auto_bind=True)\n\n if c.result[\"description\"] != \"success\":\n app.logger.error(\"Error connecting to the LDAP with the service account\")\n return False\n\n # Look for the user entry.\n if not c.search(config.LDAPBASE,\n \"(\" + config.LDAPFIELD + \"=\" + login + \")\") :\n app.logger.error(\"Error: Connection to the LDAP with service account failed\")\n else:\n if len(c.entries) >= 1 :\n if len(c.entries) > 1 :\n app.logger.error(\"Error: multiple entries with this login. \"+ \\\n \"Trying first entry...\")\n uid = c.entries[0].entry_dn\n else:\n app.logger.error(\"Error: Login not found\")\n c.unbind()\n \n return uid", "label_name": "CWE-74", "label": 1}
{"code": "def _returndata_encoding(contract_sig):\n if contract_sig.is_from_json:\n return Encoding.JSON_ABI\n return Encoding.ABI", "label_name": "CWE-119", "label": 26}
{"code": " def response(self, response, content):\n if \"authentication-info\" not in response:\n challenge = _parse_www_authenticate(response, \"www-authenticate\").get(\n \"digest\", {}\n )\n if \"true\" == challenge.get(\"stale\"):\n self.challenge[\"nonce\"] = challenge[\"nonce\"]\n self.challenge[\"nc\"] = 1\n return True\n else:\n updated_challenge = _parse_www_authenticate(\n response, \"authentication-info\"\n ).get(\"digest\", {})\n\n if \"nextnonce\" in updated_challenge:\n self.challenge[\"nonce\"] = updated_challenge[\"nextnonce\"]\n self.challenge[\"nc\"] = 1\n return False", "label_name": "CWE-400", "label": 2}
{"code": "def _should_decode(typ):\n # either a basetype which needs to be clamped\n # or a complex type which contains something that\n # needs to be clamped.\n if isinstance(typ, BaseType):\n return typ.typ not in (\"int256\", \"uint256\", \"bytes32\")\n if isinstance(typ, (ByteArrayLike, DArrayType)):\n return True\n if isinstance(typ, SArrayType):\n return _should_decode(typ.subtype)\n if isinstance(typ, TupleLike):\n return any(_should_decode(t) for t in typ.tuple_members())\n raise CompilerPanic(f\"_should_decode({typ})\") # pragma: notest", "label_name": "CWE-119", "label": 26}
{"code": "def _cnonce():\n dig = _md5(\n \"%s:%s\"\n % (time.ctime(), [\"0123456789\"[random.randrange(0, 9)] for i in range(20)])\n ).hexdigest()\n return dig[:16]", "label_name": "CWE-400", "label": 2}
{"code": " def test_manage_pools(self) -> None:\n user1 = uuid4()\n user2 = uuid4()\n\n # by default, any can modify\n self.assertIsNone(\n check_can_manage_pools_impl(\n InstanceConfig(allow_pool_management=True), UserInfo()\n )\n )\n\n # with oid, but no admin\n self.assertIsNone(\n check_can_manage_pools_impl(\n InstanceConfig(allow_pool_management=True), UserInfo(object_id=user1)\n )\n )\n\n # is admin\n self.assertIsNone(\n check_can_manage_pools_impl(\n InstanceConfig(allow_pool_management=False, admins=[user1]),\n UserInfo(object_id=user1),\n )\n )\n\n # no user oid set\n self.assertIsNotNone(\n check_can_manage_pools_impl(\n InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo()\n )\n )\n\n # not an admin\n self.assertIsNotNone(\n check_can_manage_pools_impl(\n InstanceConfig(allow_pool_management=False, admins=[user1]),\n UserInfo(object_id=user2),\n )\n )", "label_name": "CWE-285", "label": 23}
{"code": " def __init__(self, crawler, splash_base_url, slot_policy, log_400):\n self.crawler = crawler\n self.splash_base_url = splash_base_url\n self.slot_policy = slot_policy\n self.log_400 = log_400\n self.crawler.signals.connect(self.spider_opened, signals.spider_opened)", "label_name": "CWE-200", "label": 10}
{"code": " def test_patch_bot_role(self) -> None:\n self.login(\"desdemona\")\n\n email = \"default-bot@zulip.com\"\n user_profile = self.get_bot_user(email)\n\n do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile)\n\n req = dict(role=UserProfile.ROLE_GUEST)\n\n result = self.client_patch(f\"/json/bots/{self.get_bot_user(email).id}\", req)\n self.assert_json_success(result)\n\n user_profile = self.get_bot_user(email)\n self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST)\n\n # Test for not allowing a non-owner user to make assign a bot an owner role\n desdemona = self.example_user(\"desdemona\")\n do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)\n\n req = dict(role=UserProfile.ROLE_REALM_OWNER)\n\n result = self.client_patch(f\"/json/bots/{self.get_bot_user(email).id}\", req)\n self.assert_json_error(result, \"Must be an organization owner\")", "label_name": "CWE-285", "label": 23}
{"code": " def test_file_position_after_tofile(self):\n # gh-4118\n sizes = [io.DEFAULT_BUFFER_SIZE//8,\n io.DEFAULT_BUFFER_SIZE,\n io.DEFAULT_BUFFER_SIZE*8]\n\n for size in sizes:\n err_msg = \"%d\" % (size,)\n\n f = open(self.filename, 'wb')\n f.seek(size-1)\n f.write(b'\\0')\n f.seek(10)\n f.write(b'12')\n np.array([0], dtype=np.float64).tofile(f)\n pos = f.tell()\n f.close()\n assert_equal(pos, 10 + 2 + 8, err_msg=err_msg)\n\n f = open(self.filename, 'r+b')\n f.read(2)\n f.seek(0, 1) # seek between read&write required by ANSI C\n np.array([0], dtype=np.float64).tofile(f)\n pos = f.tell()\n f.close()\n assert_equal(pos, 10, err_msg=err_msg)\n\n os.unlink(self.filename)", "label_name": "CWE-20", "label": 0}
{"code": "def make_tarfile(output_filename, source_dir, archive_name, custom_filter=None):\n # Helper for filtering out modification timestamps\n def _filter_timestamps(tar_info):\n tar_info.mtime = 0\n return tar_info if custom_filter is None else custom_filter(tar_info)\n\n unzipped_filename = tempfile.mktemp()\n try:\n with tarfile.open(unzipped_filename, \"w\") as tar:\n tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps)\n # When gzipping the tar, don't include the tar's filename or modification time in the\n # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile)\n with gzip.GzipFile(\n filename=\"\", fileobj=open(output_filename, \"wb\"), mode=\"wb\", mtime=0\n ) as gzipped_tar, open(unzipped_filename, \"rb\") as tar:\n gzipped_tar.write(tar.read())\n finally:\n os.remove(unzipped_filename)", "label_name": "CWE-668", "label": 7}
{"code": " async def send_transaction(self, account, to, selector_name, calldata, nonce=None, max_fee=0):\n return await self.send_transactions(account, [(to, selector_name, calldata)], nonce, max_fee)", "label_name": "CWE-863", "label": 11}
{"code": " async def start_verification(self, client_id, username):\n async with self.lock:\n await self.db.execute('SELECT code FROM scratchverifier_usage WHERE \\\nclient_id=? AND username=?', (client_id, username))\n row = await self.db.fetchone()\n if row is not None:\n await self.db.execute('UPDATE scratchverifier_usage SET expiry=? \\\nWHERE client_id=? AND username=? AND code=?', (int(time.time()) + VERIFY_EXPIRY,\n client_id, username, row[0]))\n return row[0]\n code = sha256(\n str(client_id).encode()\n + str(time.time()).encode()\n + username.encode()\n + token_bytes()\n # 0->A, 1->B, etc, to avoid Scratch's phone number censor\n ).hexdigest().translate({ord('0') + i: ord('A') + i for i in range(10)})\n await self.db.execute('INSERT INTO scratchverifier_usage (client_id, \\\ncode, username, expiry) VALUES (?, ?, ?, ?)', (client_id, code, username,\n int(time.time() + VERIFY_EXPIRY)))\n await self.db.execute('INSERT INTO scratchverifier_logs (client_id, \\\nusername, log_time, log_type) VALUES (?, ?, ?, ?)', (client_id, username,\n int(time.time()), 1))\n await self.db.execute('DELETE FROM scratchverifier_usage WHERE \\\nexpiry<=?', (int(time.time()),))\n return code", "label_name": "CWE-287", "label": 4}
{"code": " def _resolve_orders(orders):\n requester = get_user_or_app_from_context(info.context)\n if not requester.has_perm(OrderPermissions.MANAGE_ORDERS):\n orders = list(\n filter(lambda order: order.status != OrderStatus.DRAFT, orders)\n )\n\n return create_connection_slice(\n orders, info, kwargs, OrderCountableConnection\n )", "label_name": "CWE-863", "label": 11}
{"code": " def validate(self, data):\n user = providers.get_provider('login').login_user(**data, context=self.context)\n if user is not None:\n data['user'] = user\n return data", "label_name": "CWE-287", "label": 4}
{"code": "def test_parse_www_authenticate_correct(data, strict):\n headers, info = data\n # FIXME: move strict to parse argument\n httplib2.USE_WWW_AUTH_STRICT_PARSING = strict\n try:\n assert httplib2._parse_www_authenticate(headers) == info\n finally:\n httplib2.USE_WWW_AUTH_STRICT_PARSING = 0", "label_name": "CWE-400", "label": 2}
{"code": " def update_headers(self, request_headers: HTTPHeadersDict):\n \"\"\"\n Update the session headers with the request ones while ignoring\n certain name prefixes.\n\n \"\"\"\n headers = self.headers\n for name, value in request_headers.copy().items():\n\n if value is None:\n continue # Ignore explicitly unset headers\n\n if type(value) is not str:\n value = value.decode()\n\n if name.lower() == 'user-agent' and value.startswith('HTTPie/'):\n continue\n\n if name.lower() == 'cookie':\n for cookie_name, morsel in SimpleCookie(value).items():\n self['cookies'][cookie_name] = {'value': morsel.value}\n del request_headers[name]\n continue\n\n for prefix in SESSION_IGNORED_HEADER_PREFIXES:\n if name.lower().startswith(prefix.lower()):\n break\n else:\n headers[name] = value\n\n self['headers'] = dict(headers)", "label_name": "CWE-200", "label": 10}
{"code": " def format_help_for_context(self, ctx: commands.Context) -> str:\n #Thanks Sinbad! And Trusty in whose cogs I found this.\n pre_processed = super().format_help_for_context(ctx)\n return f\"{pre_processed}\\n\\nVersion: {self.__version__}\"", "label_name": "CWE-74", "label": 1}
{"code": " public void addViolation(String msg) {\n violationOccurred = true;\n context.buildConstraintViolationWithTemplate(msg)\n .addConstraintViolation();\n }", "label_name": "CWE-74", "label": 1}
{"code": " public void getPermissions() {\n List<String> permissions = method.getPermissions();\n assertThat(permissions).containsExactlyInAnyOrder(\"net:*\", \"net:listening\", \"*:*\");\n }", "label_name": "CWE-400", "label": 2}
{"code": " public void translate(ServerPlayerChangeHeldItemPacket packet, GeyserSession session) {\n PlayerHotbarPacket hotbarPacket = new PlayerHotbarPacket();\n hotbarPacket.setContainerId(0);\n hotbarPacket.setSelectedHotbarSlot(packet.getSlot());\n hotbarPacket.setSelectHotbarSlot(true);\n session.sendUpstreamPacket(hotbarPacket);\n\n session.getPlayerInventory().setHeldItemSlot(packet.getSlot());\n }", "label_name": "CWE-287", "label": 4}
{"code": " public void testSetSelfIsNoOp() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name\", \"value\");\n headers.set(headers);\n assertThat(headers.size()).isEqualTo(1);\n }", "label_name": "CWE-74", "label": 1}
{"code": " public Cipher decrypt() {\n try {\n Cipher cipher = Secret.getCipher(ALGORITHM);\n cipher.init(Cipher.DECRYPT_MODE, getKey());\n return cipher;\n } catch (GeneralSecurityException e) {\n throw new AssertionError(e);\n }\n }", "label_name": "CWE-326", "label": 9}
{"code": " public void headersWithDifferentNamesAndValuesShouldNotBeEquivalent() {\n final HttpHeadersBase h1 = newEmptyHeaders();\n h1.set(\"name1\", \"value1\");\n final HttpHeadersBase h2 = newEmptyHeaders();\n h2.set(\"name2\", \"value2\");\n assertThat(h1).isNotEqualTo(h2);\n assertThat(h2).isNotEqualTo(h1);\n assertThat(h1).isEqualTo(h1);\n assertThat(h2).isEqualTo(h2);\n }", "label_name": "CWE-74", "label": 1}
{"code": "\tpublic SecretKey deriveKey(final SecretKey sharedSecret,\n\t\t\t\t final int keyLengthBits,\n\t\t\t\t final byte[] otherInfo)\n\t\tthrows JOSEException {\n\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n\t\tfinal MessageDigest md = getMessageDigest();\n\n\t\tfor (int i=1; i <= computeDigestCycles(ByteUtils.bitLength(md.getDigestLength()), keyLengthBits); i++) {\n\n\t\t\tbyte[] counterBytes = IntegerUtils.toBytes(i);\n\n\t\t\tmd.update(counterBytes);\n\t\t\tmd.update(sharedSecret.getEncoded());\n\n\t\t\tif (otherInfo != null) {\n\t\t\t\tmd.update(otherInfo);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tbaos.write(md.digest());\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new JOSEException(\"Couldn't write derived key: \" + e.getMessage(), e);\n\t\t\t}\n\t\t}\n\n\t\tbyte[] derivedKeyMaterial = baos.toByteArray();\n\n\t\tfinal int keyLengthBytes = ByteUtils.byteLength(keyLengthBits);\n\n\t\tif (derivedKeyMaterial.length == keyLengthBytes) {\n\t\t\t// Return immediately\n\t\t\treturn new SecretKeySpec(derivedKeyMaterial, \"AES\");\n\t\t}\n\n\t\treturn new SecretKeySpec(ByteUtils.subArray(derivedKeyMaterial, 0, keyLengthBytes), \"AES\");\n\t}", "label_name": "CWE-345", "label": 22}
{"code": " public void getAllReturnsEmptyListForUnknownName() {\n final HttpHeadersBase headers = newEmptyHeaders();\n assertThat(headers.getAll(\"noname\").size()).isEqualTo(0);\n }", "label_name": "CWE-74", "label": 1}
{"code": " public void shouldThrowExceptionForBadConnection() throws Exception {\n String url = \"http://not-exists\";\n HgCommand hgCommand = new HgCommand(null, null, null, null, null);\n\n assertThatThrownBy(() -> hgCommand.checkConnection(new UrlArgument(url)))\n .isExactlyInstanceOf(CommandLineException.class);\n }", "label_name": "CWE-77", "label": 14}
{"code": " public static <T> T withEncodedPassword(AuthenticationRequestType type, Properties info,\n PasswordAction<byte[], T> action) throws PSQLException, IOException {\n byte[] encodedPassword = withPassword(type, info, password -> {\n if (password == null) {\n throw new PSQLException(\n GT.tr(\"The server requested password-based authentication, but no password was provided.\"),\n PSQLState.CONNECTION_REJECTED);\n }\n ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(password));\n byte[] bytes = new byte[buf.limit()];\n buf.get(bytes);\n return bytes;\n });\n\n try {\n return action.apply(encodedPassword);\n } finally {\n java.util.Arrays.fill(encodedPassword, (byte) 0);\n }\n }", "label_name": "CWE-665", "label": 32}
{"code": " public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,\n ServletException {\n if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {\n HttpServletRequest httpReq = (HttpServletRequest) request;\n HttpServletResponse httpResp = (HttpServletResponse) response;\n\n if (\"GET\".equals(httpReq.getMethod())) {\n Meteor meteor = Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null);\n\n String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM);\n\n Session session = null;\n\n if (pushSessionId != null) {\n ensureServletContextAvailable(request);\n PushContext pushContext = (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME);\n session = pushContext.getSessionManager().getPushSession(pushSessionId);\n }\n\n if (session == null) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(MessageFormat.format(\"Session {0} was not found\", pushSessionId));\n }\n httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);\n return;\n }\n\n httpResp.setContentType(\"text/plain\");\n\n try {\n Request pushRequest = new RequestImpl(meteor, session);\n\n httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session);\n httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest);\n\n pushRequest.suspend();\n } catch (Exception e) {\n LOGGER.error(e.getMessage(), e);\n }\n\n return;\n }\n }\n }", "label_name": "CWE-20", "label": 0}
{"code": " public void translate(ServerDisplayScoreboardPacket packet, GeyserSession session) {\n session.getWorldCache().getScoreboard()\n .displayObjective(packet.getName(), packet.getPosition());\n }", "label_name": "CWE-287", "label": 4}
{"code": " public void testPseudoHeadersMustComeFirstWhenIterating() {\n final HttpHeadersBase headers = newHttp2Headers();\n verifyPseudoHeadersFirst(headers);\n verifyAllPseudoHeadersPresent(headers);\n }", "label_name": "CWE-74", "label": 1}
{"code": " public void translate(ServerRemoveEntitiesPacket packet, GeyserSession session) {\n for (int entityId : packet.getEntityIds()) {\n Entity entity = session.getEntityCache().getEntityByJavaId(entityId);\n if (entity != null) {\n session.getEntityCache().removeEntity(entity, false);\n }\n }\n }", "label_name": "CWE-287", "label": 4}
{"code": " public void addSynchronously(MediaPackage mediaPackage) throws SearchException, MediaPackageException,\n IllegalArgumentException, UnauthorizedException {\n if (mediaPackage == null) {\n throw new IllegalArgumentException(\"Unable to add a null mediapackage\");\n }\n logger.debug(\"Attempting to add mediapackage {} to search index\", mediaPackage.getIdentifier());\n AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA();\n\n Date now = new Date();\n\n try {\n if (indexManager.add(mediaPackage, acl, now)) {\n logger.info(\"Added mediapackage `{}` to the search index, using ACL `{}`\", mediaPackage, acl);\n } else {\n logger.warn(\"Failed to add mediapackage {} to the search index\", mediaPackage.getIdentifier());\n }\n } catch (SolrServerException e) {\n throw new SearchException(e);\n }\n\n try {\n persistence.storeMediaPackage(mediaPackage, acl, now);\n } catch (SearchServiceDatabaseException e) {\n logger.error(\"Could not store media package to search database {}: {}\", mediaPackage.getIdentifier(), e);\n throw new SearchException(e);\n }\n }", "label_name": "CWE-863", "label": 11}
{"code": " public void testPseudoHeadersWithClearDoesNotLeak() {\n final HttpHeadersBase headers = newHttp2Headers();\n\n assertThat(headers.isEmpty()).isFalse();\n headers.clear();\n assertThat(headers.isEmpty()).isTrue();\n\n // Combine 2 headers together, make sure pseudo headers stay up front.\n headers.add(\"name1\", \"value1\");\n headers.scheme(\"nothing\");\n verifyPseudoHeadersFirst(headers);\n\n final HttpHeadersBase other = newEmptyHeaders();\n other.add(\"name2\", \"value2\");\n other.authority(\"foo\");\n verifyPseudoHeadersFirst(other);\n\n headers.add(other);\n verifyPseudoHeadersFirst(headers);\n\n // Make sure the headers are what we expect them to be, and no leaking behind the scenes.\n assertThat(headers.size()).isEqualTo(4);\n assertThat(headers.get(\"name1\")).isEqualTo(\"value1\");\n assertThat(headers.get(\"name2\")).isEqualTo(\"value2\");\n assertThat(headers.scheme()).isEqualTo(\"nothing\");\n assertThat(headers.authority()).isEqualTo(\"foo\");\n }", "label_name": "CWE-74", "label": 1}
{"code": " public UserCause(User user, String message) {\n super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(\n user!=null ? user.getId() : Jenkins.ANONYMOUS.getName(),\n message != null ? \" : \" + message : \"\"\n ));\n this.user = user;\n }", "label_name": "CWE-200", "label": 10}
{"code": " public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {\n JsonNode certData;\n try {\n certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());\n } catch (IOException ex) {\n throw new RuntimeException(\"Certificate JSON can not be read.\");\n }\n\n JsonNode certChainData = certData.get(\"chain\");\n if (certChainData.getNodeType() != JsonNodeType.ARRAY) {\n throw new RuntimeException(\"Certificate data is not valid\");\n }\n\n encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);\n }", "label_name": "CWE-287", "label": 4}
{"code": "\tpublic void onTurnEnded(TurnEndedEvent event) {\n\t\tsuper.onTurnEnded(event);\n\n\t\tfinal String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();\n\n\t\tif (out.contains(\"An error occurred during initialization\")) {\n\t\t\tmessagedInitialization = true;\t\n\t\t}\t\n\n\t\tif (out.contains(\"access denied (java.net.SocketPermission\")\n\t\t\t\t|| out.contains(\"access denied (\\\"java.net.SocketPermission\\\"\")) {\n\t\t\tmessagedAccessDenied = true;\t\n\t\t}\t\n\t}", "label_name": "CWE-862", "label": 8}
{"code": " protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException\n {\n // Determine the edited document (translation).\n XWikiDocument editedDocument = getEditedDocument(context);\n EditForm editForm = (EditForm) context.getForm();\n\n // Update the edited document based on the template specified on the request.\n editedDocument.readFromTemplate(editForm, context);\n\n // The default values from the template can be overwritten by additional request parameters.\n updateDocumentTitleAndContentFromRequest(editedDocument, context);\n editedDocument.readObjectsFromForm(editForm, context);\n\n // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid\n // using XWikiGuest instead (because those fields were not previously initialized).\n if (editedDocument.isNew()) {\n editedDocument.setCreatorReference(context.getUserReference());\n editedDocument.setAuthorReference(context.getUserReference());\n editedDocument.setContentAuthorReference(context.getUserReference());\n }\n\n // Expose the edited document on the XWiki context and the Velocity context.\n putDocumentOnContext(editedDocument, context);\n\n return editedDocument;\n }", "label_name": "CWE-862", "label": 8}
{"code": " public static AsciiString of(AsciiString name) {\n final AsciiString lowerCased = name.toLowerCase();\n final AsciiString cached = map.get(lowerCased);\n return cached != null ? cached : lowerCased;\n }", "label_name": "CWE-74", "label": 1}
{"code": "\tprotected void switchToConversation(Contact contact, String body) {\n\t\tConversation conversation = xmppConnectionService\n\t\t\t\t.findOrCreateConversation(contact.getAccount(),\n\t\t\t\t\t\tcontact.getJid(), false, true);\n\t\tswitchToConversation(conversation, body);\n\t}", "label_name": "CWE-200", "label": 10}
{"code": "\tprivate boolean handleJid(Invite invite) {\n\t\tList<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);\n\t\tif (invite.isAction(XmppUri.ACTION_JOIN)) {\n\t\t\tConversation muc = xmppConnectionService.findFirstMuc(invite.getJid());\n\t\t\tif (muc != null) {\n\t\t\t\tswitchToConversation(muc, invite.getBody());\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tshowJoinConferenceDialog(invite.getJid().asBareJid().toString());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (contacts.size() == 0) {\n\t\t\tshowCreateContactDialog(invite.getJid().toString(), invite);\n\t\t\treturn false;\n\t\t} else if (contacts.size() == 1) {\n\t\t\tContact contact = contacts.get(0);\n\t\t\tif (!invite.isSafeSource() && invite.hasFingerprints()) {\n\t\t\t\tdisplayVerificationWarningDialog(contact, invite);\n\t\t\t} else {\n\t\t\t\tif (invite.hasFingerprints()) {\n\t\t\t\t\tif (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {\n\t\t\t\t\t\tToast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (invite.account != null) {\n\t\t\t\t\txmppConnectionService.getShortcutService().report(contact);\n\t\t\t\t}\n\t\t\t\tswitchToConversation(contact, invite.getBody());\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tif (mMenuSearchView != null) {\n\t\t\t\tmMenuSearchView.expandActionView();\n\t\t\t\tmSearchEditText.setText(\"\");\n\t\t\t\tmSearchEditText.append(invite.getJid().toString());\n\t\t\t\tfilter(invite.getJid().toString());\n\t\t\t} else {\n\t\t\t\tmInitialSearchValue.push(invite.getJid().toString());\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}", "label_name": "CWE-200", "label": 10}
{"code": " public OHttpSession getSession(final String iId) {\r\n acquireSharedLock();\r\n try {\r\n\r\n final OHttpSession sess = sessions.get(iId);\r\n if (sess != null)\r\n sess.updateLastUpdatedOn();\r\n return sess;\r\n\r\n } finally {\r\n releaseSharedLock();\r\n }\r\n }\r", "label_name": "CWE-200", "label": 10}
{"code": " public void deleteById(Integer id) {\n databaseTypeDao.selectOptionalById(id).ifPresent(data -> {\n if (DatabaseTypes.has(data.getDatabaseType())) {\n throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();\n }\n databaseTypeDao.deleteById(id);\n driverResources.delete(data.getDatabaseType());\n });\n }", "label_name": "CWE-20", "label": 0}
{"code": " public void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminalOverriddenFromUIToNonTerminal()\n throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"nonterminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, true);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y.WebHome as non-terminal even if the template provider says otherwise.\n // Also using a template, as specified in the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": 8}
{"code": "\tprivate void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm) {\n\t\tIntent intent = new Intent(this, ConversationsActivity.class);\n\t\tintent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);\n\t\tintent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());\n\t\tif (text != null) {\n\t\t\tintent.putExtra(Intent.EXTRA_TEXT, text);\n\t\t\tif (asQuote) {\n\t\t\t\tintent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);\n\t\t\t}\n\t\t}\n\t\tif (nick != null) {\n\t\t\tintent.putExtra(ConversationsActivity.EXTRA_NICK, nick);\n\t\t\tintent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);\n\t\t}\n\t\tintent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);\n\t\tstartActivity(intent);\n\t\tfinish();\n\t}", "label_name": "CWE-200", "label": 10}
{"code": " public void validateFail(ViolationCollector col) {\n } ", "label_name": "CWE-74", "label": 1}
{"code": " public void existingDocumentFromUITopLevelDocument() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI name=Y\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y.WebHome since we default to non-terminal documents.\n verify(mockURLFactory).createURL(\"Y\", \"WebHome\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": 8}
{"code": " default List<String> getPermissions() {\n List<String> permissions = new ArrayList<>();\n permissions.add(\"*:*\");\n permissions.add(this.getName().replace('_', ':'));\n permissions.add(this.getName().substring(0, this.getName().indexOf('_')) + \":*\");\n return permissions;\n };", "label_name": "CWE-400", "label": 2}
{"code": "\tprivate static void validate(final byte[] iv, final int authTagLength)\n\t\tthrows JOSEException {\n\t\t\n\t\tif (ByteUtils.bitLength(iv) != IV_BIT_LENGTH) {\n\t\t\tthrow new JOSEException(String.format(\"IV length of %d bits is required, got %d\", IV_BIT_LENGTH, ByteUtils.bitLength(iv)));\n\t\t}\n\n\t\tif (authTagLength != AUTH_TAG_BIT_LENGTH) {\n\t\t\tthrow new JOSEException(String.format(\"Authentication tag length of %d bits is required, got %d\", AUTH_TAG_BIT_LENGTH, authTagLength));\n\t\t}\n\t}", "label_name": "CWE-345", "label": 22}
{"code": " public void testEntryEquals() {\n final HttpHeadersBase nameValue = newEmptyHeaders();\n nameValue.add(\"name\", \"value\");\n final HttpHeadersBase nameValueCopy = newEmptyHeaders();\n nameValueCopy.add(\"name\", \"value\");\n final Map.Entry<AsciiString, String> same1 = nameValue.iterator().next();\n final Map.Entry<AsciiString, String> same2 = nameValueCopy.iterator().next();\n assertThat(same2).isEqualTo(same1);\n assertThat(same2.hashCode()).isEqualTo(same1.hashCode());\n\n final HttpHeadersBase name1Value = newEmptyHeaders();\n name1Value.add(\"name1\", \"value\");\n final HttpHeadersBase name2Value = newEmptyHeaders();\n name2Value.add(\"name2\", \"value\");\n final Map.Entry<AsciiString, String> nameDifferent1 = name1Value.iterator().next();\n final Map.Entry<AsciiString, String> nameDifferent2 = name2Value.iterator().next();\n assertThat(nameDifferent1).isNotEqualTo(nameDifferent2);\n assertThat(nameDifferent1.hashCode()).isNotEqualTo(nameDifferent2.hashCode());\n\n final HttpHeadersBase nameValue1 = newEmptyHeaders();\n nameValue1.add(\"name\", \"value1\");\n final HttpHeadersBase nameValue2 = newEmptyHeaders();\n nameValue2.add(\"name\", \"value2\");\n final Map.Entry<AsciiString, String> valueDifferent1 = nameValue1.iterator().next();\n final Map.Entry<AsciiString, String> valueDifferent2 = nameValue2.iterator().next();\n assertThat(valueDifferent1).isNotEqualTo(valueDifferent2);\n assertThat(valueDifferent1.hashCode()).isNotEqualTo(valueDifferent2.hashCode());\n }", "label_name": "CWE-74", "label": 1}
{"code": " public void newDocumentFromURLTemplateProviderSpecifiedNonTerminalButOverriddenFromUITerminal() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference = new DocumentReference(\"xwiki\", \"X\", \"Y\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST,\n false);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y as terminal and using a template, as specified in the template\n // provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": 8}
{"code": " public void translate(ServerSetTitlesAnimationPacket packet, GeyserSession session) {\n SetTitlePacket titlePacket = new SetTitlePacket();\n titlePacket.setType(SetTitlePacket.Type.TIMES);\n titlePacket.setText(\"\");\n titlePacket.setFadeInTime(packet.getFadeIn());\n titlePacket.setFadeOutTime(packet.getFadeOut());\n titlePacket.setStayTime(packet.getStay());\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label_name": "CWE-287", "label": 4}
{"code": " public void translate(ServerEntityCollectItemPacket packet, GeyserSession session) {\n // Collected entity is the other entity\n Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId());\n if (collectedEntity == null) return;\n // Collector is the entity 'picking up' the item\n Entity collectorEntity;\n if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) {\n collectorEntity = session.getPlayerEntity();\n } else {\n collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId());\n }\n if (collectorEntity == null) return;\n if (collectedEntity instanceof ExpOrbEntity) {\n // Player just picked up an experience orb\n LevelEventPacket xpPacket = new LevelEventPacket();\n xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP);\n xpPacket.setPosition(collectedEntity.getPosition());\n xpPacket.setData(0);\n session.sendUpstreamPacket(xpPacket);\n } else {\n // Item is being picked up (visual only)\n TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket();\n takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId());\n takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId());\n session.sendUpstreamPacket(takeItemEntityPacket);\n }\n }", "label_name": "CWE-287", "label": 4}
{"code": " public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButOldPageTypeButOverriddenFromUIToNonTerminal()\n throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"nonterminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, null,\n \"page\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y.WebHome as non-terminal, since even if the template provider did not\n // specify a \"terminal\" property and it used the old \"page\" type, the UI explicitly asked for a non-terminal\n // document. Also using a template, as specified in the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": 8}
{"code": " public void translate(ServerExplosionPacket packet, GeyserSession session) {\n for (ExplodedBlockRecord record : packet.getExploded()) {\n Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());\n ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());\n }\n\n Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n // Since bedrock does not play an explosion sound and particles sound, we have to manually do so\n LevelEventPacket levelEventPacket = new LevelEventPacket();\n levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);\n levelEventPacket.setData(0);\n levelEventPacket.setPosition(pos.toFloat());\n session.sendUpstreamPacket(levelEventPacket);\n\n LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();\n levelSoundEventPacket.setRelativeVolumeDisabled(false);\n levelSoundEventPacket.setBabySound(false);\n levelSoundEventPacket.setExtraData(-1);\n levelSoundEventPacket.setSound(SoundEvent.EXPLODE);\n levelSoundEventPacket.setIdentifier(\":\");\n levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));\n session.sendUpstreamPacket(levelSoundEventPacket);\n\n if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {\n SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();\n motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());\n motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));\n session.sendUpstreamPacket(motionPacket);\n }\n }", "label_name": "CWE-287", "label": 4}
{"code": " protected Details authenticate(String username, String password) throws AuthenticationException {\n Details u = loadUserByUsername(username);\n if (!u.isPasswordCorrect(password))\n throw new BadCredentialsException(\"Failed to login as \"+username);\n return u;\n }", "label_name": "CWE-200", "label": 10}
{"code": " public String resolveSqlDriverNameFromJar(String driverFileUrl) {\n String tempFilePath = \"temp/\" + UUID.randomUUID() + \".jar\";\n File driverFile = doDownload(driverFileUrl, tempFilePath);\n String className = doResolveSqlDriverNameFromJar(driverFile);\n try {\n Files.deleteIfExists(driverFile.toPath());\n } catch (IOException e) {\n log.error(\"delete driver error \" + tempFilePath, e);\n }\n return className;\n }", "label_name": "CWE-20", "label": 0}
{"code": " public void shouldCloneFromRemoteRepo() {\n assertThat(clientRepo.listFiles().length > 0, is(true));\n }", "label_name": "CWE-77", "label": 14}
{"code": " void newDocumentInvalidName() throws Exception\n {\n when(mockDocument.isNew()).thenReturn(true);\n DocumentReference documentReference = new DocumentReference(\"XWiki\", \"Foo\", \"Bar\");\n when(mockDocument.getDocumentReference()).thenReturn(documentReference);\n when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true);\n EntityNameValidation entityNameValidation = mock(EntityNameValidation.class);\n when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation);\n when(entityNameValidation.isValid(documentReference)).thenReturn(false);\n\n assertTrue(saveAction.save(this.context));\n assertEquals(\"entitynamevalidation.create.invalidname\", context.get(\"message\"));\n assertArrayEquals(new Object[] { \"Foo.Bar\" }, (Object[]) context.get(\"messageParameters\"));\n }", "label_name": "CWE-862", "label": 8}
{"code": " private String escapeEl(@Nullable String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n final Matcher m = ESCAPE_PATTERN.matcher(s);\n final StringBuffer sb = new StringBuffer(s.length() + 16);\n while (m.find()) {\n m.appendReplacement(sb, \"\\\\\\\\\\\\${\");\n }\n m.appendTail(sb);\n\n return sb.toString();\n }", "label_name": "CWE-74", "label": 1}
{"code": " public <T> List<T> search(final String filter, final Object[] filterArgs, final Mapper<T> mapper, final int maxResultCount) {\n final List<T> searchResults = new ArrayList<>();\n for (String searchBase : ldapConfiguration.getSearchBases()) {\n int resultsToFetch = resultsToFetch(maxResultCount, searchResults.size());\n\n if (resultsToFetch == -1) {\n break;\n }\n\n try {\n final SearchRequest searchRequest = new SearchRequestImpl()\n .setScope(SearchScope.SUBTREE)\n .addAttributes(\"*\")\n .setSizeLimit(resultsToFetch)\n .setFilter(format(filter, filterArgs))\n .setTimeLimit(ldapConfiguration.getSearchTimeout())\n .setBase(new Dn(searchBase));\n\n searchResults.addAll(ldapConnectionTemplate.search(searchRequest, mapper));\n } catch (LdapException e) {\n LOG.error(e.getMessage(), e);\n }\n }\n\n return searchResults;\n }", "label_name": "CWE-74", "label": 1}
{"code": "Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const\n{\n\tDoQuickSanityCheck();\n\tModularArithmetic modn(m_n);\n\tInteger r, rInv;\n\tdo {\t// do this in a loop for people using small numbers for testing\n\t\tr.Randomize(rng, Integer::One(), m_n - Integer::One());\n\t\trInv = modn.MultiplicativeInverse(r);\n\t} while (rInv.IsZero());\n\tInteger re = modn.Square(r);\n\tre = modn.Multiply(re, x);\t\t\t// blind\n\n\tInteger cp=re%m_p, cq=re%m_q;\n\tif (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)\n\t{\n\t\tcp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;\n\t\tcq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;\n\t}\n\n\t#pragma omp parallel\n\t\t#pragma omp sections\n\t\t{\n\t\t\t#pragma omp section\n\t\t\t\tcp = ModularSquareRoot(cp, m_p);\n\t\t\t#pragma omp section\n\t\t\t\tcq = ModularSquareRoot(cq, m_q);\n\t\t}\n\n\tInteger y = CRT(cq, m_q, cp, m_p, m_u);\n\ty = modn.Multiply(y, rInv);\t\t\t\t// unblind\n\ty = STDMIN(y, m_n-y);\n\tif (ApplyFunction(y) != x)\t\t\t\t// check\n\t\tthrow Exception(Exception::OTHER_ERROR, \"InvertibleRWFunction: computational error during private key operation\");\n\treturn y;\n}", "label_name": "CWE-200", "label": 10}
{"code": "void CSecurityTLS::initGlobal()\n{\n static bool globalInitDone = false;\n\n if (!globalInitDone) {\n gnutls_global_init();\n globalInitDone = true;\n }\n}", "label_name": "CWE-119", "label": 26}
{"code": "TEST_F(GroupVerifierTest, TestRequiresAnyWithAllowMissingButOk) {\n TestUtility::loadFromYaml(RequiresAnyConfig, proto_config_);\n proto_config_.mutable_rules(0)\n ->mutable_requires()\n ->mutable_requires_any()\n ->add_requirements()\n ->mutable_allow_missing();\n\n createAsyncMockAuthsAndVerifier(std::vector<std::string>{\"example_provider\", \"other_provider\"});\n EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n\n auto headers = Http::TestRequestHeaderMapImpl{};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n callbacks_[\"example_provider\"](Status::JwtMissed);\n callbacks_[\"other_provider\"](Status::JwtUnknownIssuer);\n}", "label_name": "CWE-287", "label": 4}
{"code": "\tchar const* parse_int(char const* start, char const* end, char delimiter, boost::int64_t& val)\n\t{\n\t\twhile (start < end && *start != delimiter)\n\t\t{\n\t\t\tif (!is_digit(*start)) { return 0; }\n\t\t\tval *= 10;\n\t\t\tval += *start - '0';\n\t\t\t++start;\n\t\t}\n\t\treturn start;\n\t}", "label_name": "CWE-119", "label": 26}
{"code": "\t\tDeleteRunner(ReferenceHandle& that, Local<Value> key_handle) :\n\t\t\t\tkey{ExternalCopy::CopyIfPrimitive(key_handle)},\n\t\t\t\tcontext{that.context},\n\t\t\t\treference{that.reference} {\n\t\t\tthat.CheckDisposed();\n\t\t\tif (!key) {\n\t\t\t\tthrow RuntimeTypeError(\"Invalid `key`\");\n\t\t\t}\n\t\t}", "label_name": "CWE-913", "label": 24}
{"code": "jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)\n{\n\tjas_matrix_t *y;\n\tint i;\n\tint j;\n\ty = jas_matrix_create(x->numrows_, x->numcols_);\n\tfor (i = 0; i < x->numrows_; ++i) {\n\t\tfor (j = 0; j < x->numcols_; ++j) {\n\t\t\t*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);\n\t\t}\n\t}\n\treturn y;\n}", "label_name": "CWE-20", "label": 0}
{"code": "TEST_F(AllowMissingInAndOfOrListTest, GoodAndBadJwts) {\n EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n // Use the token with example.com issuer for x-other.\n auto headers =\n Http::TestRequestHeaderMapImpl{{kExampleHeader, GoodToken}, {kOtherHeader, GoodToken}};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n EXPECT_THAT(headers, JwtOutputSuccess(kExampleHeader));\n EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n}", "label_name": "CWE-287", "label": 4}
{"code": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop packet to dummy client\n\tif(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static inline bool isMountable(const RemoteFsDevice::Details &d)\n{\n return RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": 0}
{"code": "FastCGIServer::FastCGIServer(const std::string &address,\n int port,\n int workers,\n bool useFileSocket)\n : Server(address, port),\n m_worker(&m_eventBaseManager),\n m_dispatcher(workers, workers,\n RuntimeOption::ServerThreadDropCacheTimeoutSeconds,\n RuntimeOption::ServerThreadDropStack,\n this,\n RuntimeOption::ServerThreadJobLIFOSwitchThreshold,\n RuntimeOption::ServerThreadJobMaxQueuingMilliSeconds,\n RequestPriority::k_numPriorities) {\n folly::SocketAddress sock_addr;\n if (useFileSocket) {\n sock_addr.setFromPath(address);\n } else if (address.empty()) {\n sock_addr.setFromLocalPort(port);\n } else {\n sock_addr.setFromHostPort(address, port);\n }\n m_socketConfig.bindAddress = sock_addr;\n m_socketConfig.acceptBacklog = RuntimeOption::ServerBacklog;\n std::chrono::seconds timeout;\n if (RuntimeOption::ConnectionTimeoutSeconds >= 0) {\n timeout = std::chrono::seconds(RuntimeOption::ConnectionTimeoutSeconds);\n } else {\n // default to 2 minutes\n timeout = std::chrono::seconds(120);\n }\n m_socketConfig.connectionIdleTimeout = timeout;\n}", "label_name": "CWE-668", "label": 7}
{"code": "void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,\n int c0, int r1, int c1)\n{\n\tint i;\n\n\tif (mat0->data_) {\n\t\tif (!(mat0->flags_ & JAS_MATRIX_REF)) {\n\t\t\tjas_free(mat0->data_);\n\t\t}\n\t\tmat0->data_ = 0;\n\t\tmat0->datasize_ = 0;\n\t}\n\tif (mat0->rows_) {\n\t\tjas_free(mat0->rows_);\n\t\tmat0->rows_ = 0;\n\t}\n\tmat0->flags_ |= JAS_MATRIX_REF;\n\tmat0->numrows_ = r1 - r0 + 1;\n\tmat0->numcols_ = c1 - c0 + 1;\n\tmat0->maxrows_ = mat0->numrows_;\n\tif (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {\n\t\t/*\n\t\t\tThere is no way to indicate failure to the caller.\n\t\t\tSo, we have no choice but to abort.\n\t\t\tIdeally, this function should have a non-void return type.\n\t\t\tIn practice, a non-void return type probably would not help\n\t\t\tmuch anyways as the caller would just have to terminate anyways.\n\t\t*/\n\t\tabort();\n\t}\n\n\tfor (i = 0; i < mat0->numrows_; ++i) {\n\t\tmat0->rows_[i] = mat1->rows_[r0 + i] + c0;\n\t}\n\n\tmat0->xstart_ = mat1->xstart_ + c0;\n\tmat0->ystart_ = mat1->ystart_ + r0;\n\tmat0->xend_ = mat0->xstart_ + mat0->numcols_;\n\tmat0->yend_ = mat0->ystart_ + mat0->numrows_;\n}", "label_name": "CWE-20", "label": 0}
{"code": "\t\tvoid Phase2() final {\n\t\t\tLocal<Context> context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal<Value> key_inner = key->CopyInto();\n\t\t\tLocal<Object> object = Local<Object>::Cast(Deref(reference));\n\t\t\tbool allow = [&]() {\n\t\t\t\tif (!inherit) {\n\t\t\t\t\tif (key_inner->IsName()) {\n\t\t\t\t\t\treturn Unmaybe(object->HasRealNamedProperty(context_handle, key_inner.As<Name>()));\n\t\t\t\t\t} else if (key_inner->IsNumber()) {\n\t\t\t\t\t\treturn Unmaybe(object->HasRealIndexedProperty(context_handle, HandleCast<uint32_t>(key_inner)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}();\n\t\t\tLocal<Value> value = allow ?\n\t\t\t\tUnmaybe(object->Get(context_handle, key_inner)) :\n\t\t\t\tUndefined(Isolate::GetCurrent()).As<Value>();\n\t\t\tret = TransferOut(value, options);\n\t\t}", "label_name": "CWE-913", "label": 24}
{"code": "QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly)\n{\n QString mount_point = mountPoint(device);\n\n if (!mount_point.isEmpty())\n return mount_point;\n\n mount_point = \"%1/.%2/mount/%3\";\n const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);\n\n mount_point = mount_point.arg(tmp_paths.isEmpty() ? \"/tmp\" : tmp_paths.first()).arg(qApp->applicationName()).arg(name);\n\n if (!QDir::current().mkpath(mount_point)) {\n dCError(\"mkpath \\\"%s\\\" failed\", qPrintable(mount_point));\n\n return QString();\n }\n\n if (!mountDevice(device, mount_point, readonly)) {\n dCError(\"Mount the device \\\"%s\\\" to \\\"%s\\\" failed\", qPrintable(device), qPrintable(mount_point));\n\n return QString();\n }\n\n return mount_point;\n}", "label_name": "CWE-362", "label": 18}
{"code": "void CConfig::Write(CFile& File, unsigned int iIndentation) {\n CString sIndentation = CString(iIndentation, '\\t');\n\n for (const auto& it : m_ConfigEntries) {\n for (const CString& sValue : it.second) {\n File.Write(sIndentation + it.first + \" = \" + sValue + \"\\n\");\n }\n }\n\n for (const auto& it : m_SubConfigs) {\n for (const auto& it2 : it.second) {\n File.Write(\"\\n\");\n\n File.Write(sIndentation + \"<\" + it.first + \" \" + it2.first + \">\\n\");\n it2.second.m_pSubConfig->Write(File, iIndentation + 1);\n File.Write(sIndentation + \"</\" + it.first + \">\\n\");\n }\n }\n}", "label_name": "CWE-20", "label": 0}
{"code": "jas_image_t *jas_image_create0()\n{\n\tjas_image_t *image;\n\n\tif (!(image = jas_malloc(sizeof(jas_image_t)))) {\n\t\treturn 0;\n\t}\n\n\timage->tlx_ = 0;\n\timage->tly_ = 0;\n\timage->brx_ = 0;\n\timage->bry_ = 0;\n\timage->clrspc_ = JAS_CLRSPC_UNKNOWN;\n\timage->numcmpts_ = 0;\n\timage->maxcmpts_ = 0;\n\timage->cmpts_ = 0;\n\timage->inmem_ = true;\n\timage->cmprof_ = 0;\n\n\treturn image;\n}", "label_name": "CWE-20", "label": 0}
{"code": "void TensorSliceReader::LoadShard(int shard) const {\n CHECK_LT(shard, sss_.size());\n if (sss_[shard] || !status_.ok()) {\n return; // Already loaded, or invalid.\n }\n string value;\n SavedTensorSlices sts;\n const string fname = fnames_[shard];\n VLOG(1) << \"Reading meta data from file \" << fname << \"...\";\n Table* table;\n Status s = open_function_(fname, &table);\n if (!s.ok()) {\n status_ = errors::DataLoss(\"Unable to open table file \", fname, \": \",\n s.ToString());\n return;\n }\n sss_[shard].reset(table);\n if (!(table->Get(kSavedTensorSlicesKey, &value) &&\n ParseProtoUnlimited(&sts, value))) {\n status_ = errors::Internal(\n \"Failed to find the saved tensor slices at the beginning of the \"\n \"checkpoint file: \",\n fname);\n return;\n }\n status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,\n TF_CHECKPOINT_VERSION_MIN_PRODUCER, \"Checkpoint\",\n \"checkpoint\");\n if (!status_.ok()) return;\n for (const SavedSliceMeta& ssm : sts.meta().tensor()) {\n TensorShape ssm_shape;\n status_ = TensorShape::BuildTensorShapeBase(ssm.shape(), &ssm_shape);\n if (!status_.ok()) return;\n for (const TensorSliceProto& tsp : ssm.slice()) {\n TensorSlice ss_slice(tsp);\n status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,\n ss_slice, &tensors_);\n if (!status_.ok()) return;\n }\n }\n}", "label_name": "CWE-345", "label": 22}
{"code": "void CUser::SetClientEncoding(const CString& s) {\n m_sClientEncoding = s;\n for (CClient* pClient : GetAllClients()) {\n pClient->SetEncoding(s);\n }\n}", "label_name": "CWE-20", "label": 0}
{"code": "std::string controller::bookmark(\n\t\tconst std::string& url,\n\t\tconst std::string& title,\n\t\tconst std::string& description,\n\t\tconst std::string& feed_title)\n{\n\tstd::string bookmark_cmd = cfg.get_configvalue(\"bookmark-cmd\");\n\tbool is_interactive = cfg.get_configvalue_as_bool(\"bookmark-interactive\");\n\tif (bookmark_cmd.length() > 0) {\n\t\tstd::string cmdline = strprintf::fmt(\"%s '%s' %s %s %s\",\n\t\t bookmark_cmd,\n\t\t utils::replace_all(url,\"'\", \"%27\"),\n\t\t quote_empty(stfl::quote(title)),\n\t\t quote_empty(stfl::quote(description)),\n\t\t quote_empty(stfl::quote(feed_title)));\n\n\t\tLOG(level::DEBUG, \"controller::bookmark: cmd = %s\", cmdline);\n\n\t\tif (is_interactive) {\n\t\t\tv->push_empty_formaction();\n\t\t\tstfl::reset();\n\t\t\tutils::run_interactively(cmdline, \"controller::bookmark\");\n\t\t\tv->pop_current_formaction();\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\tchar * my_argv[4];\n\t\t\tmy_argv[0] = const_cast<char *>(\"/bin/sh\");\n\t\t\tmy_argv[1] = const_cast<char *>(\"-c\");\n\t\t\tmy_argv[2] = const_cast<char *>(cmdline.c_str());\n\t\t\tmy_argv[3] = nullptr;\n\t\t\treturn utils::run_program(my_argv, \"\");\n\t\t}\n\t} else {\n\t\treturn _(\"bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.\");\n\t}\n}", "label_name": "CWE-943", "label": 38}
{"code": "error_t ssiProcessExecCommand(HttpConnection *connection, const char_t *tag, size_t length)\n{\n char_t *separator;\n char_t *attribute;\n char_t *value;\n\n //First, check whether CGI is supported by the server\n if(connection->settings->cgiCallback == NULL)\n return ERROR_INVALID_TAG;\n\n //Discard invalid SSI directives\n if(length < 4 || length >= HTTP_SERVER_BUFFER_SIZE)\n return ERROR_INVALID_TAG;\n\n //Skip the SSI exec command (4 bytes)\n osMemcpy(connection->buffer, tag + 4, length - 4);\n //Ensure the resulting string is NULL-terminated\n connection->buffer[length - 4] = '\\0';\n\n //Check whether a separator is present\n separator = strchr(connection->buffer, '=');\n //Separator not found?\n if(!separator)\n return ERROR_INVALID_TAG;\n\n //Split the tag\n *separator = '\\0';\n\n //Get attribute name and value\n attribute = strTrimWhitespace(connection->buffer);\n value = strTrimWhitespace(separator + 1);\n\n //Remove leading simple or double quote\n if(value[0] == '\\'' || value[0] == '\\\"')\n value++;\n\n //Get the length of the attribute value\n length = osStrlen(value);\n\n //Remove trailing simple or double quote\n if(length > 0)\n {\n if(value[length - 1] == '\\'' || value[length - 1] == '\\\"')\n value[length - 1] = '\\0';\n }\n\n //Enforce attribute name\n if(osStrcasecmp(attribute, \"cgi\") && osStrcasecmp(attribute, \"cmd\") && osStrcasecmp(attribute, \"cmd_argument\"))\n return ERROR_INVALID_TAG;\n //Check the length of the CGI parameter\n if(osStrlen(value) > HTTP_SERVER_CGI_PARAM_MAX_LEN)\n return ERROR_INVALID_TAG;\n\n //The scratch buffer may be altered by the user-defined callback.\n //So the CGI parameter must be copied prior to function invocation\n osStrcpy(connection->cgiParam, value);\n\n //Invoke user-defined callback\n return connection->settings->cgiCallback(connection, connection->cgiParam);\n}", "label_name": "CWE-20", "label": 0}
{"code": "bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) {\n if (!enabled_per_settings)\n return false;\n if (IsScriptDisabledForPreview(render_frame()))\n return false;\n if (is_interstitial_page_)\n return true;\n\n blink::WebLocalFrame* frame = render_frame()->GetWebFrame();\n const auto it = cached_script_permissions_.find(frame);\n if (it != cached_script_permissions_.end())\n return it->second;\n\n // Evaluate the content setting rules before\n // IsWhitelistedForContentSettings(); if there is only the default rule\n // allowing all scripts, it's quicker this way.\n bool allow = true;\n if (content_setting_rules_) {\n ContentSetting setting = GetContentSettingFromRules(\n content_setting_rules_->script_rules, frame,\n url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());\n allow = setting != CONTENT_SETTING_BLOCK;\n }\n allow = allow || IsWhitelistedForContentSettings();\n\n cached_script_permissions_[frame] = allow;\n return allow;\n}", "label_name": "CWE-20", "label": 0}
{"code": "static inline bool isValid(const RemoteFsDevice::Details &d)\n{\n return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": 0}
{"code": "void jas_matrix_divpow2(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t*data = (*data >= 0) ? ((*data) >> n) :\n\t\t\t\t (-((-(*data)) >> n));\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": 0}
{"code": " def from_string(string)\n raise Errors::InvalidObjectId.new(string) unless legal?(string)\n data = []\n 12.times { |i| data << string[i*2, 2].to_i(16) }\n new data\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"defaults to an empty selector\" do\n Moped::Query.should_receive(:new).\n with(collection, {}).and_return(query)\n collection.find.should eq query\n end", "label_name": "CWE-20", "label": 0}
{"code": " def taxable_ids(loc = which_location, org = which_organization, inner_method = which_ancestry_method)\n if SETTINGS[:locations_enabled] && loc.present?\n inner_ids_loc = if Location.ignore?(self.to_s)\n self.unscoped.pluck(\"#{table_name}.id\")\n else\n inner_select(loc, inner_method)\n end\n end", "label_name": "CWE-200", "label": 10}
{"code": " def login(database, username, password)\n auth[database.to_s] = [username, password]\n end", "label_name": "CWE-20", "label": 0}
{"code": " def perform_accept_invitation\n params.require(:id)\n params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {})\n\n invite = Invite.find_by(invite_key: params[:id])\n\n if invite.present?\n begin\n attrs = {\n username: params[:username],\n name: params[:name],\n password: params[:password],\n user_custom_fields: params[:user_custom_fields],\n ip_address: request.remote_ip,\n session: session\n }\n\n if invite.is_invite_link?\n params.require(:email)\n attrs[:email] = params[:email]\n else\n attrs[:email] = invite.email\n attrs[:email_token] = params[:email_token] if params[:email_token].present?\n end\n\n user = invite.redeem(**attrs)\n rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e\n return render json: failed_json.merge(message: e.message), status: 412\n end\n\n if user.blank?\n return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404\n end\n\n log_on_user(user) if user.active?\n user.update_timezone_if_missing(params[:timezone])\n post_process_invite(user)\n create_topic_invite_notifications(invite, user)\n\n topic = invite.topics.first\n response = {}\n\n if user.present?\n if user.active?\n if user.guardian.can_see?(topic)\n response[:redirect_to] = path(topic.relative_url)\n else\n response[:redirect_to] = path(\"/\")\n end\n else\n response[:message] = I18n.t('invite.confirm_email')\n if user.guardian.can_see?(topic)\n cookies[:destination_url] = path(topic.relative_url)\n end\n end\n end\n\n render json: success_json.merge(response)\n else\n render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404\n end\n end", "label_name": "CWE-863", "label": 11}
{"code": " def email_verify_send\n\n raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]\n\n user = User.find_by(email: params[:email].downcase)\n if !user\n # result is always positive to avoid leaking of existing user accounts\n render json: { message: 'ok' }, status: :ok\n return\n end\n\n #if user.verified == true\n # render json: { error: 'Already verified!' }, status: :unprocessable_entity\n # return\n #end\n\n Token.create(action: 'Signup', user_id: user.id)\n\n result = User.signup_new_token(user)\n if result && result[:token]\n user = result[:user]\n NotificationFactory::Mailer.notification(\n template: 'signup',\n user: user,\n objects: result\n )\n\n # only if system is in develop mode, send token back to browser for browser tests\n if Setting.get('developer_mode') == true\n render json: { message: 'ok', token: result[:token].name }, status: :ok\n return\n end\n\n # token sent to user, send ok to browser\n render json: { message: 'ok' }, status: :ok\n return\n end\n\n # unable to generate token\n render json: { message: 'failed' }, status: :ok\n end", "label_name": "CWE-863", "label": 11}
{"code": " it \"yields all indexes on the collection\" do\n indexes.to_a.should eq \\\n session[:\"system.indexes\"].find(ns: \"moped_test.users\").to_a\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"returns an enumerator\" do\n cursor = mock(Moped::Cursor)\n Moped::Cursor.stub(new: cursor)\n\n query.each.should be_a Enumerator\n end", "label_name": "CWE-400", "label": 2}
{"code": " def spec_summary entry, spec\n entry << \"\\n\\n\" << format_text(spec.summary, 68, 4)\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"creates an index with a generated name\" do\n indexes.create(key)\n indexes[key][\"name\"].should eq \"location.latlong_2d_name_1_age_-1\"\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"syncs the cluster\" do\n cluster.should_receive(:sync) do\n cluster.servers << server\n end\n cluster.socket_for :write\n end", "label_name": "CWE-400", "label": 2}
{"code": " def first\n session.simple_query(operation)\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"raises a QueryFailure exception\" do\n expect {\n session.query(query)\n }.to raise_exception(Moped::Errors::QueryFailure)\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"removes all matching documents\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |delete|\n delete.flags.should eq []\n delete.selector.should eq query.operation.selector\n end\n\n query.remove_all\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"returns a new indexes instance\" do\n collection.indexes.should be_an_instance_of Moped::Indexes\n end", "label_name": "CWE-400", "label": 2}
{"code": " def generation_time\n Time.at(@data.pack(\"C4\").unpack(\"N\")[0]).utc\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"returns the master connection\" do\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"sets the query operation's skip field\" do\n query.skip(5)\n query.operation.skip.should eq 5\n end", "label_name": "CWE-20", "label": 0}
{"code": " def socket_for(mode)\n sync unless primaries.any? || (secondaries.any? && mode == :read)\n\n server = nil\n while primaries.any? || (secondaries.any? && mode == :read)\n if mode == :write || secondaries.empty?\n server = primaries.sample\n else\n server = secondaries.sample\n end\n\n if server\n socket = server.socket\n socket.connect unless socket.connection\n\n if socket.alive?\n break server\n else\n remove server\n end\n end\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"recognizes and generates #index\" do\n { :get => \"/users\" }.should route_to(:controller => \"users\", :action => \"index\")\n end", "label_name": "CWE-200", "label": 10}
{"code": " it \"should return HTTP_X_FORWARDED_FOR as remote_address\" do\n @connection.request.env['HTTP_X_FORWARDED_FOR'] = '1.2.3.4'\n @connection.remote_address.should == '1.2.3.4'\n end", "label_name": "CWE-20", "label": 0}
{"code": " it 'logs in correctly' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,\n second_factor_method: UserSecondFactor.methods[:totp]\n }\n\n expect(response).to redirect_to(\"/\")\n end", "label_name": "CWE-287", "label": 4}
{"code": " it \"returns the socket\" do\n cluster.stub(:sync) { cluster.servers << server }\n cluster.socket_for(:write).should eq socket\n end", "label_name": "CWE-20", "label": 0}
{"code": " def test_update_invalid\n Domain.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": 10}
{"code": " def password_policy(password)\n if Setting.get('password_min_size').to_i > password.length\n return [\"Can\\'t update password, it must be at least %s characters long!\", Setting.get('password_min_size')]\n end\n if Setting.get('password_need_digit').to_i == 1 && password !~ /\\d/\n return [\"Can't update password, it must contain at least 1 digit!\"]\n end\n if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )\n return [\"Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!\"]\n end\n\n true\n end", "label_name": "CWE-863", "label": 11}
{"code": " it \"updates the record matching selector with change\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |update|\n update.flags.should eq []\n update.selector.should eq query.operation.selector\n update.update.should eq change\n end\n\n query.update change\n end", "label_name": "CWE-400", "label": 2}
{"code": " def fast_forward_to_first_boundary\n loop do\n read_buffer = @io.gets\n break if read_buffer == full_boundary\n raise EOFError, \"bad content body\" if read_buffer.nil?\n end\n end", "label_name": "CWE-119", "label": 26}
{"code": " it \"returns a new indexes instance\" do\n collection.indexes.should be_an_instance_of Moped::Indexes\n end", "label_name": "CWE-20", "label": 0}
{"code": " def initialize(image_path, colors=16, depth=8)\n output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-`\n @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?)\n end", "label_name": "CWE-77", "label": 14}
{"code": " def test_update_invalid\n AuthSourceLdap.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": 10}
{"code": " it \"raises a connection failure exception\" do\n cluster.sync_server(server).should be_empty\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"merges the old and new session's options\" do\n session.with(new_options) do |new_session|\n new_session.options.should eq options.merge(new_options)\n end\n end", "label_name": "CWE-400", "label": 2}
{"code": " def __bson_dump__(io, key)\n io << Types::OBJECT_ID\n io << key\n io << NULL_BYTE\n io << data.pack('C12')\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"removes the stored credentials\" do\n cluster.logout :admin\n cluster.auth.should be_empty\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"should redeem the invite if invited by non staff but not approve\" do\n SiteSetting.must_approve_users = true\n inviter = invite.invited_by\n user = invite_redeemer.redeem\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.invited_by).to eq(inviter)\n expect(inviter.notifications.count).to eq(1)\n expect(user.approved).to eq(false)\n end", "label_name": "CWE-863", "label": 11}
{"code": " it 'should return the right response' do\n email_token.update!(created_at: 999.years.ago)\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label_name": "CWE-287", "label": 4}
{"code": " it \"returns a random slave connection\" do\n secondaries = [server]\n cluster.stub(secondaries: secondaries)\n secondaries.should_receive(:sample).and_return(server)\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-20", "label": 0}
{"code": " def request(args = {})\n { :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v|\n args[k] ||= v\n end\n ['test', :find, args[:key], args]\n end", "label_name": "CWE-287", "label": 4}
{"code": " def query(query)\n if options[:consistency] == :eventual\n query.flags |= [:slave_ok] if query.respond_to? :flags\n mode = :read\n else\n mode = :write\n end\n\n reply = socket_for(mode).execute(query)\n\n reply.tap do |reply|\n if reply.flags.include?(:query_failure)\n raise Errors::QueryFailure.new(query, reply.documents.first)\n end\n end\n end", "label_name": "CWE-20", "label": 0}
{"code": " def setup\n FactoryGirl.create(:host)\n end", "label_name": "CWE-200", "label": 10}
{"code": " it \"should use the rest terminus when the 'puppet' URI scheme is used and a host name is present\" do\n uri = \"puppet://myhost/fakemod/my/file\"\n\n # It appears that the mocking somehow interferes with the caching subsystem.\n # This mock somehow causes another terminus to get generated.\n term = @indirection.terminus(:rest)\n @indirection.stubs(:terminus).with(:rest).returns term\n term.expects(:find)\n @indirection.find(uri)\n end", "label_name": "CWE-200", "label": 10}
{"code": " def dup\n session = super\n session.instance_variable_set :@options, options.dup\n\n if defined? @current_database\n session.send(:remove_instance_variable, :@current_database)\n end\n\n session\n end", "label_name": "CWE-20", "label": 0}
{"code": " def query(query)\n if options[:consistency] == :eventual\n query.flags |= [:slave_ok] if query.respond_to? :flags\n mode = :read\n else\n mode = :write\n end\n\n reply = socket_for(mode).execute(query)\n\n reply.tap do |reply|\n if reply.flags.include?(:query_failure)\n raise Errors::QueryFailure.new(query, reply.documents.first)\n end\n end\n end", "label_name": "CWE-400", "label": 2}
{"code": " it \"creates an index\" do\n indexes.create(key, background: true)\n indexes[key][\"background\"].should eq true\n end", "label_name": "CWE-400", "label": 2}
{"code": " def logout(database)\n auth.delete(database.to_s)\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"syncs each seed node\" do\n server = Moped::Server.allocate\n Moped::Server.should_receive(:new).with(\"127.0.0.1:27017\").and_return(server)\n\n cluster.should_receive(:sync_server).with(server).and_return([])\n cluster.sync\n end", "label_name": "CWE-400", "label": 2}
{"code": " def remove(server)\n servers.delete(server)\n end", "label_name": "CWE-20", "label": 0}
{"code": " it \"returns the socket\" do\n cluster.stub(:sync) { cluster.servers << server }\n cluster.socket_for(:write).should eq socket\n end", "label_name": "CWE-400", "label": 2}
{"code": " def socket_for(mode)\n if options[:retain_socket]\n @socket ||= cluster.socket_for(mode)\n else\n cluster.socket_for(mode)\n end\n end", "label_name": "CWE-20", "label": 0}
{"code": " def bulk_unread_topic_ids\n topic_query = TopicQuery.new(current_user)\n\n if inbox = params[:private_message_inbox]\n filter = private_message_filter(topic_query, inbox)\n topic_query.options[:limit] = false\n topics = topic_query.filter_private_messages_unread(current_user, filter)\n else\n topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics\n topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == \"true\"\n\n if params[:category_id]\n if params[:include_subcategories]\n topics = topics.where(<<~SQL, category_id: params[:category_id])\n category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR\n category_id = :category_id\n SQL\n else\n topics = topics.where('category_id = ?', params[:category_id])\n end\n end\n\n if params[:tag_name].present?\n topics = topics.joins(:tags).where(\"tags.name\": params[:tag_name])\n end\n end\n\n topics.pluck(:id)\n end", "label_name": "CWE-863", "label": 11}
{"code": " it \"should redeem the invite if invited by staff\" do\n SiteSetting.must_approve_users = true\n inviter = invite.invited_by\n inviter.admin = true\n user = invite_redeemer.redeem\n invite.reload\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.invited_by).to eq(inviter)\n expect(inviter.notifications.count).to eq(1)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": 11}
{"code": "func TestBuilder_BuildBootstrapLayeredRuntime(t *testing.T) {\n\tb := New(\"localhost:1111\", \"localhost:2222\", filemgr.NewManager(), nil)\n\tstaticCfg, err := b.BuildBootstrapLayeredRuntime()\n\tassert.NoError(t, err)\n\ttestutil.AssertProtoJSONEqual(t, `\n\t\t{ \"layers\": [{\n\t\t\t\"name\": \"static_layer_0\",\n\t\t\t\"staticLayer\": {\n\t\t\t\t\"overload\": {\n\t\t\t\t\t\"global_downstream_max_connections\": 50000\n\t\t\t\t}\n\t\t\t}\n\t\t}] }\n\t`, staticCfg)\n}", "label_name": "CWE-200", "label": 10}
{"code": "func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {\n\tadded, err := cs.addVote(vote, peerID)\n\tif err != nil {\n\t\t// If the vote height is off, we'll just ignore it,\n\t\t// But if it's a conflicting sig, add it to the cs.evpool.\n\t\t// If it's otherwise invalid, punish peer.\n\t\t// nolint: gocritic\n\t\tif voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {\n\t\t\tif cs.privValidatorPubKey == nil {\n\t\t\t\treturn false, errPubKeyIsNotSet\n\t\t\t}\n\n\t\t\tif bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {\n\t\t\t\tcs.Logger.Error(\n\t\t\t\t\t\"Found conflicting vote from ourselves. Did you unsafe_reset a validator?\",\n\t\t\t\t\t\"height\",\n\t\t\t\t\tvote.Height,\n\t\t\t\t\t\"round\",\n\t\t\t\t\tvote.Round,\n\t\t\t\t\t\"type\",\n\t\t\t\t\tvote.Type)\n\t\t\t\treturn added, err\n\t\t\t}\n\t\t\tvar timestamp time.Time\n\t\t\tif voteErr.VoteA.Height == cs.state.InitialHeight {\n\t\t\t\ttimestamp = cs.state.LastBlockTime // genesis time\n\t\t\t} else {\n\t\t\t\ttimestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)\n\t\t\t}\n\t\t\tev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)\n\t\t\tevidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)\n\t\t\tif evidenceErr != nil {\n\t\t\t\tcs.Logger.Error(\"Failed to add evidence to the evidence pool\", \"err\", evidenceErr)\n\t\t\t}\n\t\t\treturn added, err\n\t\t} else if err == types.ErrVoteNonDeterministicSignature {\n\t\t\tcs.Logger.Debug(\"Vote has non-deterministic signature\", \"err\", err)\n\t\t} else {\n\t\t\t// Either\n\t\t\t// 1) bad peer OR\n\t\t\t// 2) not a bad peer? this can also err sometimes with \"Unexpected step\" OR\n\t\t\t// 3) tmkms use with multiple validators connecting to a single tmkms instance\n\t\t\t// \t\t(https://github.com/tendermint/tendermint/issues/3839).\n\t\t\tcs.Logger.Info(\"Error attempting to add vote\", \"err\", err)\n\t\t\treturn added, ErrAddingVote\n\t\t}\n\t}\n\treturn added, nil\n}", "label_name": "CWE-400", "label": 2}
{"code": "func remount(m *configs.Mount, rootfs string) error {\n\tvar (\n\t\tdest = m.Destination\n\t)\n\tif !strings.HasPrefix(dest, rootfs) {\n\t\tdest = filepath.Join(rootfs, dest)\n\t}\n\treturn unix.Mount(m.Source, dest, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), \"\")\n}", "label_name": "CWE-362", "label": 18}
{"code": "func (r *TokenRevocationHandler) RevokeToken(ctx context.Context, token string, tokenType fosite.TokenType, client fosite.Client) error {\n\tdiscoveryFuncs := []func() (request fosite.Requester, err error){\n\t\tfunc() (request fosite.Requester, err error) {\n\t\t\t// Refresh token\n\t\t\tsignature := r.RefreshTokenStrategy.RefreshTokenSignature(token)\n\t\t\treturn r.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil)\n\t\t},\n\t\tfunc() (request fosite.Requester, err error) {\n\t\t\t// Access token\n\t\t\tsignature := r.AccessTokenStrategy.AccessTokenSignature(token)\n\t\t\treturn r.TokenRevocationStorage.GetAccessTokenSession(ctx, signature, nil)\n\t\t},\n\t}\n\n\t// Token type hinting\n\tif tokenType == fosite.AccessToken {\n\t\tdiscoveryFuncs[0], discoveryFuncs[1] = discoveryFuncs[1], discoveryFuncs[0]\n\t}\n\n\tvar ar fosite.Requester\n\tvar err error\n\tif ar, err = discoveryFuncs[0](); err != nil {\n\t\tar, err = discoveryFuncs[1]()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ar.GetClient().GetID() != client.GetID() {\n\t\treturn errors.WithStack(fosite.ErrRevocationClientMismatch)\n\t}\n\n\trequestID := ar.GetID()\n\tr.TokenRevocationStorage.RevokeRefreshToken(ctx, requestID)\n\tr.TokenRevocationStorage.RevokeAccessToken(ctx, requestID)\n\n\treturn nil\n}", "label_name": "CWE-755", "label": 21}
{"code": "func TestAddEvidenceFromConsensus(t *testing.T) {\n\tvar height int64 = 10\n\tpool, val := defaultTestPool(height)\n\tev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, val, evidenceChainID)\n\n\trequire.NoError(t, pool.AddEvidenceFromConsensus(ev))\n\n\t// evidence from consensus should not be added immediately but reside in the consensus buffer\n\tevList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Empty(t, evList)\n\trequire.Zero(t, evSize)\n\n\tnext := pool.EvidenceFront()\n\trequire.Nil(t, next)\n\n\t// move to next height and update state and evidence pool\n\tstate := pool.State()\n\tstate.LastBlockHeight++\n\tpool.Update(state, []types.Evidence{})\n\n\t// should be able to retrieve evidence from pool\n\tevList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Equal(t, []types.Evidence{ev}, evList)\n\n\t// shouldn't be able to submit the same evidence twice\n\trequire.NoError(t, pool.AddEvidenceFromConsensus(ev))\n\tstate = pool.State()\n\tstate.LastBlockHeight++\n\tpool.Update(state, []types.Evidence{})\n\tevList2, _ := pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Equal(t, evList, evList2)\n}", "label_name": "CWE-400", "label": 2}
{"code": "func (svc Service) GetTeamScheduledQueries(ctx context.Context, teamID uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureTeamPack(ctx, teamID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)\n}", "label_name": "CWE-863", "label": 11}
{"code": "func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) {\n\t// sanity check\n\tif state.LastBlockHeight <= evpool.state.LastBlockHeight {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"Failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d\",\n\t\t\tstate.LastBlockHeight,\n\t\t\tevpool.state.LastBlockHeight,\n\t\t))\n\t}\n\tevpool.logger.Info(\"Updating evidence pool\", \"last_block_height\", state.LastBlockHeight,\n\t\t\"last_block_time\", state.LastBlockTime)\n\n\tevpool.logger.Info(\n\t\t\"updating evidence pool\",\n\t\t\"last_block_height\", state.LastBlockHeight,\n\t\t\"last_block_time\", state.LastBlockTime,\n\t)\n\n\tevpool.mtx.Lock()\n\t// flush awaiting evidence from consensus into pool\n\tevpool.flushConsensusBuffer()\n\t// update state\n\tevpool.state = state\n\tevpool.mtx.Unlock()\n\n\t// move committed evidence out from the pending pool and into the committed pool\n\tevpool.markEvidenceAsCommitted(ev)\n\n\t// prune pending evidence when it has expired. This also updates when the next evidence will expire\n\tif evpool.Size() > 0 && state.LastBlockHeight > evpool.pruningHeight &&\n\t\tstate.LastBlockTime.After(evpool.pruningTime) {\n\t\tevpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence()\n\t}\n}", "label_name": "CWE-400", "label": 2}
{"code": " from: db.getServerTitle() + \" <\" + db.getReturnAddress() + \">\",\n subject: subject,\n text: text,\n };\n\n sendEmail(sendOptions);\n};", "label_name": "CWE-287", "label": 4}
{"code": " parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {\n // \"\"\"Extract pushed bytes after opreturn. Returns list of bytes() objects,\n // one per push.\n let ops: PushDataOperation[];\n \n // Strict refusal of non-push opcodes; bad scripts throw OpreturnError.\"\"\"\n try {\n ops = this.getScriptOperations(script);\n } catch(e) {\n //console.log(e);\n throw Error('Script error');\n }\n\n if(ops[0].opcode !== this.BITBOX.Script.opcodes.OP_RETURN)\n throw Error('No OP_RETURN');\n let chunks: (Buffer|null)[] = [];\n ops.slice(1).forEach(opitem => {\n if(opitem.opcode > this.BITBOX.Script.opcodes.OP_16)\n throw Error(\"Non-push opcode\");\n if(opitem.opcode > this.BITBOX.Script.opcodes.OP_PUSHDATA4) {\n if(opitem.opcode === 80)\n throw Error('Non-push opcode');\n if(!allow_op_number)\n throw Error('OP_1NEGATE to OP_16 not allowed');\n if(opitem.opcode === this.BITBOX.Script.opcodes.OP_1NEGATE)\n opitem.data = Buffer.from([0x81]);\n else // OP_1 - OP_16\n opitem.data = Buffer.from([opitem.opcode - 80]);\n }\n if(opitem.opcode === this.BITBOX.Script.opcodes.OP_0 && !allow_op_0){\n throw Error('OP_0 not allowed');\n }\n chunks.push(opitem.data)\n });\n //console.log(chunks);\n return chunks\n }", "label_name": "CWE-20", "label": 0}
{"code": "export function verify_multi_chunk_message(packets: any[]) {\n\n const messageBuilder = new MessageBuilder({});\n messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);\n\n messageBuilder.on(\"full_message_body\", (fullMessageBody: Buffer) => {\n console.log(\"full_message_body received:\");\n analyseExtensionObject(fullMessageBody, 0, 0);\n });\n messageBuilder.on(\"start_chunk\", (info) => {\n console.log(\" starting new chunk \", info.messageHeader);\n });\n\n messageBuilder.on(\"chunk\", (messageChunk) => {\n console.log(messageHeaderToString(messageChunk));\n });\n\n let totalLength = 0;\n packets.forEach((packet) => {\n if (packet instanceof Array) {\n packet = Buffer.from(packet);\n }\n totalLength += packet.length;\n // console.log(sprintf(\" adding packet size : %5d l=%d\", packet.length, totalLength));\n messageBuilder.feed(packet);\n });\n}", "label_name": "CWE-400", "label": 2}
{"code": "export async function validateTransfer(\n connection: Connection,\n signature: TransactionSignature,\n { recipient, amount, splToken, reference, memo }: ValidateTransferFields,\n options?: { commitment?: Finality }\n): Promise<TransactionResponse> {\n const response = await connection.getTransaction(signature, options);\n if (!response) throw new ValidateTransferError('not found');\n\n const message = response.transaction.message;\n const meta = response.meta;\n if (!meta) throw new ValidateTransferError('missing meta');\n if (meta.err) throw meta.err;\n\n const [preAmount, postAmount] = splToken\n ? await validateSPLTokenTransfer(message, meta, recipient, splToken)\n : await validateSystemTransfer(message, meta, recipient);\n\n if (postAmount.minus(preAmount).lt(amount)) throw new ValidateTransferError('amount not transferred');\n\n if (reference) {\n if (!Array.isArray(reference)) {\n reference = [reference];\n }\n\n for (const pubkey of reference) {\n if (!message.accountKeys.some((accountKey) => accountKey.equals(pubkey)))\n throw new ValidateTransferError('reference not found');\n }\n }\n\n // FIXME: add memo check\n\n return response;\n}", "label_name": "CWE-670", "label": 36}
{"code": " function simulateOpenSecureChannel(callback: SimpleCallback) {\n \n clientChannel.create(\"fake://foobar:123\", (err?: Error) => {\n \n if (param.shouldFailAtClientConnection) {\n if (!err) {\n return callback(new Error(\" Should have failed here !\"));\n }\n callback();\n } else {\n if (err) {\n return callback(err);\n }\n setImmediate(() => callback());\n }\n });\n }", "label_name": "CWE-400", "label": 2}
{"code": "export function fetchRemote(remote: string, cwd: string) {\n const results = git([\"fetch\", remote], { cwd });\n\n if (!results.success) {\n throw gitError(`Cannot fetch remote: ${remote}`);\n }\n}", "label_name": "CWE-77", "label": 14}
{"code": " await manager.update(User, organizationUser.userId, { invitationToken: uuid.v4(), password: uuid.v4() });\n });", "label_name": "CWE-74", "label": 1}
{"code": " constructor(options?: { signatureLength?: number }) {\n super();\n\n this.id = \"\";\n\n this._tick0 = 0;\n this._tick1 = 0;\n this._hasReceivedError = false;\n this.blocks = [];\n this.messageChunks = [];\n this._expectedChannelId = 0;\n\n options = options || {};\n\n this.signatureLength = options.signatureLength || 0;\n\n this.options = options;\n\n this._packetAssembler = new PacketAssembler({\n minimumSizeInBytes: 0,\n readMessageFunc: readRawMessageHeader\n });\n\n this._packetAssembler.on(\"message\", (messageChunk) => this._feed_messageChunk(messageChunk));\n\n this._packetAssembler.on(\"newMessage\", (info, data) => {\n if (doPerfMonitoring) {\n // record tick 0: when the first data is received\n this._tick0 = get_clock_tick();\n }\n /**\n *\n * notify the observers that a new message is being built\n * @event start_chunk\n * @param info\n * @param data\n */\n this.emit(\"start_chunk\", info, data);\n });\n\n this._securityDefeated = false;\n this.totalBodySize = 0;\n this.totalMessageSize = 0;\n this.channelId = 0;\n this.offsetBodyStart = 0;\n this.sequenceHeader = null;\n this._init_new();\n }", "label_name": "CWE-400", "label": 2}
{"code": " this._transport.on(\"message\", (messageChunk: Buffer) => {\r\n /**\r\n * notify the observers that ClientSecureChannelLayer has received a message chunk\r\n * @event receive_chunk\r\n * @param message_chunk\r\n */\r\n this.emit(\"receive_chunk\", messageChunk);\r\n this._on_receive_message_chunk(messageChunk);\r\n });\r", "label_name": "CWE-400", "label": 2}
{"code": " get lokadIdHex() { return \"534c5000\" }", "label_name": "CWE-20", "label": 0}
{"code": " privateKey: this.getPrivateKey() || undefined,\r\n securityMode: this.securityMode\r\n });\r\n this._requests = {};\r\n\r\n this.messageBuilder\r\n .on(\"message\", (response: Response, msgType: string, requestId: number) => {\r\n this._on_message_received(response, msgType, requestId);\r\n })\r\n .on(\"start_chunk\", () => {\r\n //\r\n if (doPerfMonitoring) {\r\n this._tick2 = get_clock_tick();\r\n }\r\n })\r\n .on(\"error\", (err, requestId) => {\r\n //\r\n let requestData = this._requests[requestId];\r\n\r\n if (doDebug) {\r\n debugLog(\"request id = \", requestId, err);\r\n debugLog(\" message was \");\r\n debugLog(requestData);\r\n }\r\n\r\n if (!requestData) {\r\n requestData = this._requests[requestId + 1];\r\n if (doTraceClientRequestContent) {\r\n errorLog(\" message was 2:\", requestData ? requestData.request.toString() : \"<null>\");\r\n }\r\n }\r\n });\r\n\r\n this.__in_normal_close_operation = false;\r\n\r\n this._timeout_request_count = 0;\r\n\r\n this._securityTokenTimeoutId = null;\r\n\r\n this.transportTimeout = options.transportTimeout || ClientSecureChannelLayer.defaultTransportTimeout;\r\n\r\n this.channelId = 0;\r\n\r\n this.connectionStrategy = coerceConnectionStrategy(options.connectionStrategy);\r\n }\r", "label_name": "CWE-400", "label": 2}
{"code": "function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {\n // eslint-disable-next-line no-undef\n const wr = new WeakRef<CallIntoRenderer>(value);\n const mapKey = id[0] + '~' + id[1];\n rendererFunctionCache.set(mapKey, wr);\n finalizationRegistry.register(value, {\n id,\n webContents: wc,\n frameId\n } as FinalizerInfo);\n return value;\n}", "label_name": "CWE-668", "label": 7}
|