{"code": " public function testPopBeforeSmtpBad()\n {\n //Start a fake POP server on a different port\n //so we don't inadvertently connect to the previous instance\n $pid = shell_exec('nohup ./runfakepopserver.sh 1101 >/dev/null 2>/dev/null & printf \"%u\" $!');\n $this->pids[] = $pid;\n\n sleep(2);\n //Test a known-bad login\n $this->assertFalse(\n POP3::popBeforeSmtp('localhost', 1101, 10, 'user', 'xxx', $this->Mail->SMTPDebug),\n 'POP before SMTP should have failed'\n );\n shell_exec('kill -TERM '.escapeshellarg($pid));\n sleep(2);\n }", "label_name": "CWE-20", "label": 0} {"code": "function mci_account_get_array_by_id( $p_user_id ) {\n\t$t_result = array();\n\t$t_result['id'] = $p_user_id;\n\n\tif( user_exists( $p_user_id ) ) {\n\t\t$t_result['name'] = user_get_field( $p_user_id, 'username' );\n\t\t$t_dummy = user_get_field( $p_user_id, 'realname' );\n\n\t\tif( !empty( $t_dummy ) ) {\n\t\t\t$t_result['real_name'] = $t_dummy;\n\t\t}\n\n\t\t$t_dummy = user_get_field( $p_user_id, 'email' );\n\n\t\tif( !empty( $t_dummy ) ) {\n\t\t\t$t_result['email'] = $t_dummy;\n\t\t}\n\t}\n\treturn $t_result;\n}", "label_name": "CWE-200", "label": 10} {"code": " public static function validatePMAStorage($path, $values)\n {\n $result = array(\n 'Server_pmadb' => '',\n 'Servers/1/controluser' => '',\n 'Servers/1/controlpass' => ''\n );\n $error = false;\n\n if ($values['Servers/1/pmadb'] == '') {\n return $result;\n }\n\n $result = array();\n if ($values['Servers/1/controluser'] == '') {\n $result['Servers/1/controluser'] = __(\n 'Empty phpMyAdmin control user while using phpMyAdmin configuration '\n . 'storage!'\n );\n $error = true;\n }\n if ($values['Servers/1/controlpass'] == '') {\n $result['Servers/1/controlpass'] = __(\n 'Empty phpMyAdmin control user password while using phpMyAdmin '\n . 'configuration storage!'\n );\n $error = true;\n }\n if (! $error) {\n $test = static::testDBConnection(\n $values['Servers/1/connect_type'],\n $values['Servers/1/host'], $values['Servers/1/port'],\n $values['Servers/1/socket'], $values['Servers/1/controluser'],\n $values['Servers/1/controlpass'], 'Server_pmadb'\n );\n if ($test !== true) {\n $result = array_merge($result, $test);\n }\n }\n return $result;\n }", "label_name": "CWE-200", "label": 10} {"code": " public static function validateRegex($path, $values)\n {\n $result = array($path => '');\n\n if ($values[$path] == '') {\n return $result;\n }\n\n static::testPHPErrorMsg();\n\n $matches = array();\n // in libraries/ListDatabase.php _checkHideDatabase(),\n // a '/' is used as the delimiter for hide_db\n preg_match('/' . $values[$path] . '/', '', $matches);\n\n static::testPHPErrorMsg(false);\n\n if (isset($php_errormsg)) {\n $error = preg_replace('/^preg_match\\(\\): /', '', $php_errormsg);\n return array($path => $error);\n }\n\n return $result;\n }", "label_name": "CWE-200", "label": 10} {"code": "function getResourceGroups($type=\"\") {\n\t$return = array();\n\t$query = \"SELECT g.id AS id, \"\n\t . \"g.name AS name, \"\n\t . \"t.name AS type, \"\n\t . \"g.ownerusergroupid AS ownerid, \"\n\t . \"CONCAT(u.name, '@', a.name) AS owner \"\n\t . \"FROM resourcegroup g, \"\n\t . \"resourcetype t, \"\n\t . \"usergroup u, \"\n\t . \"affiliation a \"\n\t . \"WHERE g.resourcetypeid = t.id AND \"\n\t . \"g.ownerusergroupid = u.id AND \"\n\t . \"u.affiliationid = a.id \";\n\n\tif(! empty($type))\n\t\t$query .= \"AND t.name = '$type' \";\n\n\t$query .= \"ORDER BY t.name, g.name\";\n\t$qh = doQuery($query, 281);\n\twhile($row = mysql_fetch_assoc($qh)) {\n\t\tif(empty($type))\n\t\t\t$return[$row[\"id\"]][\"name\"] = $row[\"type\"] . \"/\" . $row[\"name\"];\n\t\telse\n\t\t\t$return[$row[\"id\"]][\"name\"] = $row[\"name\"];\n\t\t$return[$row[\"id\"]][\"ownerid\"] = $row[\"ownerid\"];\n\t\t$return[$row[\"id\"]][\"owner\"] = $row[\"owner\"];\n\t}\n\treturn $return;\n}", "label_name": "CWE-20", "label": 0} {"code": "function XMLRPCblockAllocation($imageid, $start, $end, $numMachines,\n $usergroupid, $ignoreprivileges=0) {\n\tglobal $user, $xmlrpcBlockAPIUsers;\n\tif(! in_array($user['id'], $xmlrpcBlockAPIUsers)) {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 34,\n\t\t 'errormsg' => 'access denied for managing block allocations');\n\t}\n\t$ownerid = getUserlistID('vclreload@Local');\n\t$name = \"API:$start\";\n\t$managementnodes = getManagementNodes('future');\n\tif(empty($managementnodes)) {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 12,\n\t\t 'errormsg' => 'could not allocate a management node to handle block allocation');\n\t}\n\t$mnid = array_rand($managementnodes);\n\t$query = \"INSERT INTO blockRequest \"\n\t . \"(name, \"\n\t . \"imageid, \"\n\t . \"numMachines, \"\n\t . \"groupid, \"\n\t . \"repeating, \"\n\t . \"ownerid, \"\n\t . \"admingroupid, \"\n\t . \"managementnodeid, \"\n\t . \"expireTime, \"\n\t . \"status) \"\n\t . \"VALUES \"\n\t . \"('$name', \"\n\t . \"$imageid, \"\n\t . \"$numMachines, \"\n\t . \"$usergroupid, \"\n\t . \"'list', \"\n\t . \"$ownerid, \"\n\t . \"0, \"\n\t . \"$mnid, \"\n\t . \"'$end', \"\n\t . \"'accepted')\";\n\tdoQuery($query, 101);\n\t$brid = dbLastInsertID();\n\t$query = \"INSERT INTO blockTimes \"\n\t . \"(blockRequestid, \"\n\t . \"start, \"\n\t . \"end) \"\n\t . \"VALUES \"\n\t . \"($brid, \"\n\t . \"'$start', \"\n\t . \"'$end')\";\n\tdoQuery($query, 101);\n\t$btid = dbLastInsertID();\n\t$return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);\n\t$return['blockTimesid'] = $btid;\n\treturn $return;\n}", "label_name": "CWE-20", "label": 0} {"code": "\t\taddChangeLogEntry($request[\"logid\"], NULL, unixToDatetime($end),\n\t\t $request['start'], NULL, NULL, 0);\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 44,\n\t\t 'errormsg' => 'concurrent license restriction');\n\t}", "label_name": "CWE-20", "label": 0} {"code": "function XMLRPCgetUserGroups($groupType=0, $affiliationid=0) {\n global $user;\n $groups = getUserGroups($groupType, $affiliationid);\n\n // Filter out any groups to which the user does not have access.\n $usergroups = array();\n foreach($groups as $id => $group){\n if($group['ownerid'] == $user['id'] || \n (array_key_exists(\"editgroupid\", $group) &&\n array_key_exists($group['editgroupid'], $user[\"groups\"])) || \n (array_key_exists($id, $user[\"groups\"]))){\n array_push($usergroups, $group);\n }\n }\n return array(\n \"status\" => \"success\",\n \"groups\" => $usergroups);\n}", "label_name": "CWE-20", "label": 0} {"code": " public function __construct($exceptions = false) {\n $this->exceptions = ($exceptions == true);\n }", "label_name": "CWE-20", "label": 0} {"code": " private function mail_passthru($to, $subject, $body, $header, $params) {\n if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {\n $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);\n } else {\n $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);\n }\n return $rt;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function Mail($from) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Mail() without being connected\");\n return false;\n }\n\n $useVerp = ($this->do_verp ? \" XVERP\" : \"\");\n fputs($this->smtp_conn,\"MAIL FROM:<\" . $from . \">\" . $useVerp . $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 . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"MAIL 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 . '
');\n }\n return false;\n }\n return true;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function SendAndMail($from) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called SendAndMail() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"SAML FROM:\" . $from . $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 . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"SAML 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 . '
');\n }\n return false;\n }\n return true;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function actionEditDropdown() {\n $model = new Dropdowns;\n\n if (isset($_POST['Dropdowns'])) {\n $model = Dropdowns::model()->findByPk(\n $_POST['Dropdowns']['id']);\n if ($model->id == Actions::COLORS_DROPDOWN_ID) {\n if (AuxLib::issetIsArray($_POST['Dropdowns']['values']) &&\n AuxLib::issetIsArray($_POST['Dropdowns']['labels']) &&\n count($_POST['Dropdowns']['values']) ===\n count($_POST['Dropdowns']['labels'])) {\n\n if (AuxLib::issetIsArray($_POST['Admin']) &&\n isset($_POST['Admin']['enableColorDropdownLegend'])) {\n\n Yii::app()->settings->enableColorDropdownLegend = \n $_POST['Admin']['enableColorDropdownLegend'];\n Yii::app()->settings->save();\n }\n\n $options = array_combine(\n $_POST['Dropdowns']['values'], $_POST['Dropdowns']['labels']);\n $temp = array();\n foreach ($options as $value => $label) {\n if ($value != \"\")\n $temp[$value] = $label;\n }\n $model->options = json_encode($temp);\n $model->save();\n }\n } else {\n $model->attributes = $_POST['Dropdowns'];\n $temp = array();\n if (is_array($model->options) && count($model->options) > 0) {\n foreach ($model->options as $option) {\n if ($option != \"\")\n $temp[$option] = $option;\n }\n $model->options = json_encode($temp);\n if ($model->save()) {\n \n }\n }\n }\n }\n $this->redirect(\n 'manageDropDowns'\n );\n }", "label_name": "CWE-20", "label": 0} {"code": " public function beforeSave() {\n if(strpos($this->tag,self::DELIM) !== false) {\n $this->tag = strtr($this->tag,array(self::DELIM => ''));\n }\n return true;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function actionGetItems() {\n $sql = 'SELECT id, name as value FROM x2_accounts WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'] . '%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function rules() {\n $parentRules = parent::rules();\n $parentRules[] = array(\n 'firstName,lastName', 'required', 'on' => 'webForm');\n return $parentRules;\n }", "label_name": "CWE-20", "label": 0} {"code": " public function getDisplayName ($plural=true) {\n return Yii::t('contacts', '{contact} List|{contact} Lists', array(\n (int) $plural,\n '{contact}' => Modules::displayName(false, 'Contacts'),\n ));\n }", "label_name": "CWE-20", "label": 0} {"code": "\tpublic function actionView($id) {\n\t\t$model = CActiveRecord::model('Docs')->findByPk($id);\n if (!$this->checkPermissions($model, 'view')) $this->denied ();\n\n\t\tif(isset($model)){\n\t\t\t$permissions=explode(\", \",$model->editPermissions);\n\t\t\tif(in_array(Yii::app()->user->getName(),$permissions))\n\t\t\t\t$editFlag=true;\n\t\t\telse\n\t\t\t\t$editFlag=false;\n\t\t}\n\t\t//echo $model->visibility;exit;\n\t\tif (!isset($model) ||\n\t\t\t !(($model->visibility==1 ||\n\t\t\t\t($model->visibility==0 && $model->createdBy==Yii::app()->user->getName())) ||\n\t\t\t\tYii::app()->params->isAdmin|| $editFlag))\n\t\t\t$this->redirect(array('/docs/docs/index'));\n\n // add doc to user's recent item list\n User::addRecentItem('d', $id, Yii::app()->user->getId());\n X2Flow::trigger('RecordViewTrigger',array('model'=>$model));\n\t\t$this->render('view', array(\n\t\t\t'model' => $model,\n\t\t));\n\t}", "label_name": "CWE-20", "label": 0} {"code": " public function actionView($id){\n\n // add media object to user's recent item list\n User::addRecentItem('m', $id, Yii::app()->user->getId()); \n\n $this->render('view', array(\n 'model' => $this->loadModel($id),\n ));\n }", "label_name": "CWE-20", "label": 0} {"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value FROM x2_x2leads WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": 0} {"code": " public function testGetFilteredEventsDataProvider () {\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('testuser');\n Yii::app()->settings->historyPrivacy = null;\n $profile = Profile::model()->findByAttributes(array('username' => 'testuser'));\n $retVal = Events::getFilteredEventsDataProvider ($profile, true, null, false);\n $dataProvider = $retVal['dataProvider'];\n $events = $dataProvider->getData ();\n $expectedEvents = Events::getEvents (0, 0, count ($events), $profile);\n\n // verify events from getData\n $this->assertEquals (\n Yii::app()->db->createCommand (\"\n select id\n from x2_events\n where user='testuser' or visibility\n order by timestamp desc, id desc\n \")->queryColumn (),\n array_map (\n function ($event) { return $event->id; }, \n $expectedEvents['events']\n )\n );\n\n // ensure that getFilteredEventsDataProvider returns same events as getData\n $this->assertEquals (\n array_map (\n function ($event) { return $event->id; }, \n $expectedEvents['events']\n ),\n array_map (\n function ($event) { return $event->id; }, \n $events\n )\n );\n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": 0} {"code": "\tstatic public function getStatusText($_lng, $_status = 0)\n\t{\n\t\tswitch($_status)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\treturn $_lng['ticket']['open'];\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\treturn $_lng['ticket']['wait_reply'];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn $_lng['ticket']['replied'];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn $_lng['ticket']['closed'];\n\t\t\t\tbreak;\n\t\t}\n\t}", "label_name": "CWE-732", "label": 13} {"code": "\tstatic public function getLastArchived($_num = 10, $_admin = 1) {\n\n\t\tif ($_num > 0) {\n\n\t\t\t$archived = array();\n\t\t\t$counter = 0;\n\t\t\t$result_stmt = Database::prepare(\"\n\t\t\t\tSELECT *, (\n\t\t\t\t\tSELECT COUNT(`sub`.`id`)\n\t\t\t\t\tFROM `\" . TABLE_PANEL_TICKETS . \"` `sub`\n\t\t\t\t\tWHERE `sub`.`answerto` = `main`.`id`\n\t\t\t\t) as `ticket_answers`\n\t\t\t\tFROM `\" . TABLE_PANEL_TICKETS . \"` `main`\n\t\t\t\tWHERE `main`.`answerto` = '0' AND `main`.`archived` = '1'\n\t\t\t\tAND `main`.`adminid` = :adminid\n\t\t\t\tORDER BY `main`.`lastchange` DESC LIMIT 0, \".(int)$_num\n\t\t\t);\n\t\t\tDatabase::pexecute($result_stmt, array('adminid' => $_admin));\n\n\t\t\twhile ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {\n\n\t\t\t\t$archived[$counter]['id'] = $row['id'];\n\t\t\t\t$archived[$counter]['customerid'] = $row['customerid'];\n\t\t\t\t$archived[$counter]['adminid'] = $row['adminid'];\n\t\t\t\t$archived[$counter]['lastreplier'] = $row['lastreplier'];\n\t\t\t\t$archived[$counter]['ticket_answers'] = $row['ticket_answers'];\n\t\t\t\t$archived[$counter]['category'] = $row['category'];\n\t\t\t\t$archived[$counter]['priority'] = $row['priority'];\n\t\t\t\t$archived[$counter]['subject'] = $row['subject'];\n\t\t\t\t$archived[$counter]['message'] = $row['message'];\n\t\t\t\t$archived[$counter]['dt'] = $row['dt'];\n\t\t\t\t$archived[$counter]['lastchange'] = $row['lastchange'];\n\t\t\t\t$archived[$counter]['status'] = $row['status'];\n\t\t\t\t$archived[$counter]['by'] = $row['by'];\n\t\t\t\t$counter++;\n\t\t\t}\n\n\t\t\tif (isset($archived[0]['id'])) {\n\t\t\t\treturn $archived;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}", "label_name": "CWE-732", "label": 13} {"code": " public function settings() {\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 $settings = Plugin::getAllSettings('file_manager');\n\n if (!$settings) {\n Flash::set('error', 'Files - ' . __('unable to retrieve plugin settings.'));\n return;\n }\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": 0} {"code": " public function rename() {\n if (!AuthUser::hasPermission('file_manager_rename')) {\n Flash::set('error', __('You do not have sufficient permissions to rename this file or 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/rename')) {\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['file'];\n\n $data['current_name'] = str_replace('..', '', $data['current_name']);\n $data['new_name'] = str_replace('..', '', $data['new_name']);\n\n // Clean filenames\n $data['new_name'] = preg_replace('/ /', '_', $data['new_name']);\n $data['new_name'] = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $data['new_name']);\n\n $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));\n $file = FILES_DIR . '/' . $data['current_name'];\n\n // Check another file doesn't already exist with same name\n if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {\n Flash::set('error', __('A file or directory with that name already exists!'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }\n\n if (file_exists($file)) {\n if (!rename($file, FILES_DIR . '/' . $path . '/' . $data['new_name']))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!' . $file));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} {"code": "function article_save()\n{\n global $txp_user, $vars, $prefs;\n\n extract($prefs);\n\n $incoming = array_map('assert_string', psa($vars));\n\n $oldArticle = safe_row('Status, url_title, Title, '.\n 'unix_timestamp(LastMod) as sLastMod, LastModID, '.\n 'unix_timestamp(Posted) as sPosted, '.\n 'unix_timestamp(Expires) as sExpires',\n 'textpattern', 'ID = '.(int) $incoming['ID']);", "label_name": "CWE-269", "label": 6} {"code": " function insertObject($object, $table) {\n //if ($table==\"text\") eDebug($object,true); \n $sql = \"INSERT INTO `\" . $this->prefix . \"$table` (\";\n $values = \") VALUES (\";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n if ($var{0} != '_') {\n $sql .= \"`$var`,\";\n if ($values != \") VALUES (\") {\n $values .= \",\";\n }\n $values .= \"'\" . $this->escapeString($val) . \"'\";\n }\n }\n $sql = substr($sql, 0, -1) . substr($values, 0) . \")\";\n //if($table=='text')eDebug($sql,true);\n if (@mysqli_query($this->connection, $sql) != false) {\n $id = mysqli_insert_id($this->connection);\n return $id;\n } else\n return 0;\n }", "label_name": "CWE-74", "label": 1} {"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": "\tpublic function update() {\n global $user;\n\n if (expSession::get('customer-signup')) expSession::set('customer-signup', false);\n if (isset($this->params['address_country_id'])) {\n $this->params['country'] = $this->params['address_country_id'];\n unset($this->params['address_country_id']);\n }\n if (isset($this->params['address_region_id'])) {\n $this->params['state'] = $this->params['address_region_id'];\n unset($this->params['address_region_id']);\n }\n\t\tif ($user->isLoggedIn()) {\n\t\t\t// check to see how many other addresses this user has already.\n\t\t\t$count = $this->address->find('count', 'user_id='.$user->id);\n\t\t\t// if this is first address save for this user we'll make this the default\n\t\t\tif ($count == 0) \n {\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n }\n\t\t\t// associate this address with the current user.\n\t\t\t$this->params['user_id'] = $user->id;\n\t\t\t// save the object\n\t\t\t$this->address->update($this->params);\n\t\t}\n else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){\n //user is not logged in, but allow anonymous checkout is enabled so we'll check \n //a few things that we don't check in the parent 'stuff and create a user account.\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1; \n $this->address->update($this->params);\n }\n\t\texpHistory::back(); \n\t}", "label_name": "CWE-74", "label": 1} {"code": " public function activate_address()\n {\n global $db, $user;\n\n $object = new stdClass();\n $object->id = $this->params['id'];\n $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], \"user_id=\" . $user->id);\n flash(\"message\", gt(\"Successfully updated address.\"));\n expHistory::back(); \n }", "label_name": "CWE-74", "label": 1} {"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} {"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-74", "label": 1} {"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} {"code": "\tpublic function approve_submit() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\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']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t $comment = new expComment($this->params['id']);\n\t $comment->body = $this->params['body'];\n\t $comment->approved = $this->params['approved'];\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} {"code": " public function subscriptions() {\n global $db;\n \n expHistory::set('manageable', $this->params);\n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $sub = new subscribers($this->params['id']);\n if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // get this users subscriptions\n $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);\n \n // get a list of all available E-Alerts\n $ealerts = new expeAlerts();\n assign_to_template(array(\n 'subscriber'=>$sub,\n 'subscriptions'=>$subscriptions,\n 'ealerts'=>$ealerts->find('all')\n ));\n }", "label_name": "CWE-74", "label": 1} {"code": " function delete_option_master() {\n global $db;\n\n $masteroption = new option_master($this->params['id']);\n \n // delete any implementations of this option master\n $db->delete('option', 'option_master_id='.$masteroption->id);\n $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);\n //eDebug($masteroption);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} {"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": " static function displayname() {\r\n return \"Events\";\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " function import() {\r\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname);\r\n $modules = new expPaginator(array(\r\n 'records' => $pullable_modules,\r\n 'controller' => $this->loc->mod,\r\n 'action' => $this->params['action'],\r\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\r\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\r\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\r\n 'columns' => array(\r\n gt('Title') => 'title',\r\n gt('Page') => 'section'\r\n ),\r\n ));\r\n\r\n assign_to_template(array(\r\n 'modules' => $modules,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public static function _date2timestamp( $datetime, $wtz=null ) {\r\n if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;\r\n if( !isset( $datetime['min'] )) $datetime['min'] = 0;\r\n if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;\r\n if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))\r\n return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n $output = $offset = 0;\r\n if( empty( $wtz )) {\r\n if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {\r\n $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;\r\n $wtz = 'UTC';\r\n }\r\n else\r\n $wtz = $datetime['tz'];\r\n }\r\n if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))\r\n $wtz = 'UTC';\r\n try {\r\n $strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );\r\n $d = new DateTime( $strdate, new DateTimeZone( $wtz ));\r\n if( 0 != $offset ) // adjust for offset\r\n $d->modify( $offset.' seconds' );\r\n $output = $d->format( 'U' );\r\n unset( $d );\r\n }\r\n catch( Exception $e ) {\r\n $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n }\r\n return $output;\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public function buildControl() {\r\n $control = new colorcontrol();\r\n if (!empty($this->params['value'])) $control->value = $this->params['value'];\r\n if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];\r\n $control->default = $this->params['value'];\r\n if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];\r\n if (isset($this->params['flip'])) $control->flip = $this->params['flip'];\r\n $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';\r\n $control->name = $this->params['name'];\r\n $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';\r\n $control->id = isset($this->params['id']) && $this->params['id'] != \"\" ? $this->params['id'] : \"\";\r\n //echo $control->id;\r\n if (empty($control->id)) $control->id = $this->params['name'];\r\n if (empty($control->name)) $control->name = $this->params['id'];\r\n\r\n // attempt to translate the label\r\n if (!empty($this->params['label'])) {\r\n $this->params['label'] = gt($this->params['label']);\r\n } else {\r\n $this->params['label'] = null;\r\n }\r\n echo $control->toHTML($this->params['label'], $this->params['name']);\r\n// $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));\r\n// $ar->send();\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " function delete_selected() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item && $item->is_recurring == 1) {\r\n $event_remaining = false;\r\n $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);\r\n foreach ($eventdates as $ed) {\r\n if (array_key_exists($ed->id, $this->params['dates'])) {\r\n $ed->delete();\r\n } else {\r\n $event_remaining = true;\r\n }\r\n }\r\n if (!$event_remaining) {\r\n $item->delete(); // model will also ensure we delete all event dates\r\n }\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-74", "label": 1} {"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-74", "label": 1} {"code": " public function editTitle() {\n global $user;\n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->title = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n } ", "label_name": "CWE-74", "label": 1} {"code": " $src = substr($ref->source, strlen($prefix)) . $section->id;\r\n if (call_user_func(array($ref->module, 'hasContent'))) {\r\n $oloc = expCore::makeLocation($ref->module, $ref->source);\r\n $nloc = expCore::makeLocation($ref->module, $src);\r\n if ($ref->module != \"container\") {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);\r\n } else {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " function remove() {\r\n global $db;\r\n\r\n $section = $db->selectObject('section', 'id=' . $this->params['id']);\r\n if ($section) {\r\n section::removeLevel($section->id);\r\n $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);\r\n $section->parent = -1;\r\n $db->updateObject($section, 'section');\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public static function canView($section) {\r\n global $db;\r\n\r\n if ($section == null) {\r\n return false;\r\n }\r\n if ($section->public == 0) {\r\n // Not a public section. Check permissions.\r\n return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));\r\n } else { // Is public. check parents.\r\n if ($section->parent <= 0) {\r\n // Out of parents, and since we are still checking, we haven't hit a private section.\r\n return true;\r\n } else {\r\n $s = $db->selectObject('section', 'id=' . $section->parent);\r\n return self::canView($s);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public function breadcrumb() {\r\n global $sectionObj;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // Show not only the location of a page in the hierarchy but also the location of a standalone page\r\n $current = new section($id);\r\n if ($current->parent == -1) { // standalone page\r\n $navsections = section::levelTemplate(-1, 0);\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 } else {\r\n $navsections = section::levelTemplate(0, 0);\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 ));\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public function breadcrumb() {\r\n global $sectionObj;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // Show not only the location of a page in the hierarchy but also the location of a standalone page\r\n $current = new section($id);\r\n if ($current->parent == -1) { // standalone page\r\n $navsections = section::levelTemplate(-1, 0);\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 } else {\r\n $navsections = section::levelTemplate(0, 0);\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 ));\r\n }\r", "label_name": "CWE-74", "label": 1} {"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n // figure out if should limit the results\n if (isset($this->params['limit'])) {\n $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];\n } else {\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n } \n $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';\n\n // pull the news posts from the database\n $items = $this->news->find('all', $this->aggregateWhereClause(), $order);\n\n // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.\n if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);\n \n // setup the pagination object to paginate the news stories.\n $page = new expPaginator(array(\n 'records'=>$items,\n 'limit'=>$limit,\n 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'view'=>empty($this->params['view']) ? null : $this->params['view']\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'items'=>$page->records,\n 'rank'=>($order==='rank')?1:0,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": 1} {"code": " public function autocomplete() {\n return;\n global $db;\n\n $model = $this->params['model'];\n $mod = new $model();\n $srchcol = explode(\",\",$this->params['searchoncol']);\n /*for ($i=0; $i=1) $sql .= \" OR \";\n $sql .= $srchcol[$i].' LIKE \\'%'.$this->params['query'].'%\\'';\n }*/\n // $sql .= ' AND parent_id=0';\n //eDebug($sql);\n \n //$res = $mod->find('all',$sql,'id',25);\n $sql = \"select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from \".$db->prefix.\"product as p INNER JOIN \".$db->prefix.\"content_expfiles as cef ON p.id=cef.content_id INNER JOIN \".$db->prefix.\"expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') desc LIMIT 25\";\n //$res = $db->selectObjectsBySql($sql);\n //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');\n \n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} {"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": 0} {"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": 0} {"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": 0} {"code": " protected function createSubRequest($uri, Request $request)\n {\n $cookies = $request->cookies->all();\n $server = $request->server->all();\n\n // Override the arguments to emulate a sub-request.\n // Sub-request object will point to localhost as client ip and real client ip\n // will be included into trusted header for client ip\n try {\n if ($trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {\n $currentXForwardedFor = $request->headers->get($trustedHeaderName, '');\n\n $server['HTTP_'.$trustedHeaderName] = ($currentXForwardedFor ? $currentXForwardedFor.', ' : '').$request->getClientIp();\n }\n } catch (\\InvalidArgumentException $e) {\n // Do nothing\n }\n\n $server['REMOTE_ADDR'] = $this->resolveTrustedProxy();\n\n unset($server['HTTP_IF_MODIFIED_SINCE']);\n unset($server['HTTP_IF_NONE_MATCH']);\n\n $subRequest = Request::create($uri, 'get', array(), $cookies, array(), $server);\n if ($request->headers->has('Surrogate-Capability')) {\n $subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability'));\n }\n\n if ($session = $request->getSession()) {\n $subRequest->setSession($session);\n }\n\n return $subRequest;\n }", "label_name": "CWE-20", "label": 0} {"code": " protected function tearDown()\n {\n Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->originalTrustedHeaderName);\n }", "label_name": "CWE-20", "label": 0} {"code": " public function testXForwarderForHeaderForPassRequests()\n {\n $this->setNextResponse();\n $server = array('REMOTE_ADDR' => '10.0.0.1');\n $this->request('POST', '/', $server);\n\n $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));\n }", "label_name": "CWE-20", "label": 0} {"code": " public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)\n {\n $this->catch = $catch;\n $this->backendRequest = $request;\n\n return parent::handle($request, $type, $catch);\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 confirm()\n {\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->response->html($this->helper->layout->project('custom_filter/remove', array(\n 'project' => $project,\n 'filter' => $filter,\n 'title' => t('Remove a custom filter')\n )));\n }", "label_name": "CWE-200", "label": 10} {"code": " public function confirm()\n {\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->response->html($this->helper->layout->project('custom_filter/remove', array(\n 'project' => $project,\n 'filter' => $filter,\n 'title' => t('Remove a custom filter')\n )));\n }", "label_name": "CWE-200", "label": 10} {"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 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": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": 10} {"code": " public function confirm()\n {\n $task = $this->getTask();\n $link_id = $this->request->getIntegerParam('link_id');\n $link = $this->taskExternalLinkModel->getById($link_id);\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n $this->response->html($this->template->render('task_external_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} {"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": " public function gc($force = false)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->db->createCommand()\n ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())\n ->execute();\n }\n }", "label_name": "CWE-330", "label": 12} {"code": " protected function setUp()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::setUp();\n $this->security = new ExposedSecurity();\n $this->security->derivationIterations = 1000; // speed up test running\n }", "label_name": "CWE-330", "label": 12} {"code": "\tprivate function get_submit_action() {\r\n\r\n\t\t$action = null;\r\n\r\n\t\tif ( isset( $_POST['geo_mashup_add_location'] ) or isset( $_POST['geo_mashup_update_location'] ) ) {\r\n\r\n\t\t\t// Clients without javascript may need server side geocoding\r\n\t\t\tif ( ! empty( $_POST['geo_mashup_search'] ) and isset( $_POST['geo_mashup_no_js'] ) and 'true' == $_POST['geo_mashup_no_js'] ) {\r\n\r\n\t\t\t\t$action = 'geocode';\r\n\r\n\t\t\t} else {\r\n\r\n\t\t\t\t$action = 'save';\r\n\r\n\t\t\t}\r\n\r\n\t\t} else if ( isset( $_POST['geo_mashup_changed'] ) and 'true' == $_POST['geo_mashup_changed'] and ! empty( $_POST['geo_mashup_location'] ) ) {\r\n\r\n\t\t\t// The geo mashup submit button wasn't used, but a change was made and the post saved\r\n\t\t\t$action = 'save';\r\n\t\t\t\t \r\n\t\t} else if ( isset( $_POST['geo_mashup_delete_location'] ) ) {\r\n\r\n\t\t\t$action = 'delete';\r\n\r\n\t\t} else if ( ! empty( $_POST['geo_mashup_location_id'] ) and empty( $_POST['geo_mashup_location'] ) ) {\r\n\r\n\t\t\t// There was a location, but it was cleared before this save\r\n\t\t\t$action = 'delete';\r\n\r\n\t\t}\r\n\t\treturn $action;\r\n\t}\r", "label_name": "CWE-20", "label": 0} {"code": "\tpublic function save_comment( $comment_id = 0, $approval = '' ) {\r\n\t\tif ( !$comment_id || 'spam' === $approval || empty( $_POST['comment_location'] ) || !is_array( $_POST['comment_location'] ) ) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tGeoMashupDB::set_object_location( 'comment', $comment_id, $_POST['comment_location'] );\r\n\t}\r", "label_name": "CWE-20", "label": 0} {"code": "\tpublic function print_form() {\r\n\t\tglobal $user_id;\r\n\r\n\t\tinclude_once( GEO_MASHUP_DIR_PATH . '/edit-form.php');\r\n\t\tif ( isset( $_GET['user_id'] ) ) {\r\n\t\t\t$object_id = $_GET['user_id'];\r\n\t\t} else {\r\n\t\t\t$object_id = $user_id;\r\n\t\t}\r\n\t\techo '

' . __( 'Location', 'GeoMashup' ) . '

';\r\n\t\tgeo_mashup_edit_form( 'user', $object_id, get_class( $this ) );\r\n\t}\r", "label_name": "CWE-20", "label": 0} {"code": " foreach ($project_templates as $project_template) {\n if ((int) $project_template->getGroupId() === \\Project::ADMIN_PROJECT_ID) {\n continue;\n }\n $company_templates[] = new CompanyTemplate($project_template, $this->glyph_finder);\n }", "label_name": "CWE-863", "label": 11} {"code": " protected function get_remote_contents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)\n {\n $method = (function_exists('curl_exec') && !ini_get('safe_mode') && !ini_get('open_basedir')) ? 'curl_get_contents' : 'fsock_get_contents';\n return $this->$method($url, $timeout, $redirect_max, $ua, $fp);\n }", "label_name": "CWE-200", "label": 10} {"code": " static function decrypt($string, $key) {\n\n $result = '';\n $string = base64_decode($string);\n\n for ($i=0; $iID,\n\t\t\tarray(\n\t\t\t\t'content' => rand_str( 100 ),\n\t\t\t),\n\t\t);\n\n\t\t// First time it's a valid comment.\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$this->assertNotIXRError( $result );\n\n\t\t// Run second time for duplication error.\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": 8} {"code": "function deleteAllCustomDNSEntries()\n{\n $handle = fopen($customDNSFile, \"r\");\n if ($handle)\n {\n try\n {\n while (($line = fgets($handle)) !== false) {\n $line = str_replace(\"\\r\",\"\", $line);\n $line = str_replace(\"\\n\",\"\", $line);\n $explodedLine = explode (\" \", $line);\n\n if (count($explodedLine) != 2)\n continue;\n\n $ip = $explodedLine[0];\n $domain = $explodedLine[1];\n\n pihole_execute(\"-a removecustomdns \".$ip.\" \".$domain);\n }\n }\n catch (\\Exception $ex)\n {\n return errorJsonResponse($ex->getMessage());\n }\n\n fclose($handle);\n }\n\n return successJsonResponse();\n}", "label_name": "CWE-862", "label": 8} {"code": " public function testIsExpiredReturnsTrueIfCompiledFileDoesntExist()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(false);\n $this->assertTrue($compiler->isExpired('foo'));\n }", "label_name": "CWE-327", "label": 3} {"code": "\t \t\tself::$collectedInfo[$params['name']] = array('definition' => $params, 'value' => $_FILES[$params['name']]);\r\n\t \t}\r\n\r\n \t} else {\r\n \t\tif (isset(self::$collectedInfo[$params['name']]['value'])){\r\n \t\t\t$valueContent = self::$collectedInfo[$params['name']]['value'];\r\n \t\t\t$downloadLink = \"id.'/'.self::$collectedObject->hash.'/'.$params['name'].\"\\\">Download (\".htmlspecialchars($valueContent['name']).\")\";\r\n \t\t}\r\n \t}\r\n \t\r\n \treturn \"{$downloadLink}\";\r\n }\r", "label_name": "CWE-116", "label": 15} {"code": " protected function checkTrustedHostPattern()\n {\n if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === GeneralUtility::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) {\n $this->messageQueue->enqueue(new FlashMessage(\n 'Trusted hosts pattern is configured to allow all header values. Check the pattern defined in Admin'\n . ' Tools -> Settings -> Configure Installation-Wide Options -> System -> trustedHostsPattern'\n . ' and adapt it to expected host value(s).',\n 'Trusted hosts pattern is insecure',\n FlashMessage::WARNING\n ));\n } else {\n if (GeneralUtility::hostHeaderValueMatchesTrustedHostsPattern($_SERVER['HTTP_HOST'])) {\n $this->messageQueue->enqueue(new FlashMessage(\n '',\n 'Trusted hosts pattern is configured to allow current host value.'\n ));\n } else {\n $this->messageQueue->enqueue(new FlashMessage(\n 'The trusted hosts pattern will be configured to allow all header values. This is because your $SERVER_NAME:$SERVER_PORT'\n . ' is \"' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . '\" while your HTTP_HOST is \"'\n . $_SERVER['HTTP_HOST'] . '\". Check the pattern defined in Admin'\n . ' Tools -> Settings -> Configure Installation-Wide Options -> System -> trustedHostsPattern'\n . ' and adapt it to expected host value(s).',\n 'Trusted hosts pattern mismatch',\n FlashMessage::ERROR\n ));\n }\n }\n }", "label_name": "CWE-20", "label": 0} {"code": " public function getFileContent($file, $identifier)\n {\n $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file));\n $this->process->execute($resource, $content, $this->repoDir);\n\n if (!trim($content)) {\n return null;\n }\n\n return $content;\n }", "label_name": "CWE-20", "label": 0} {"code": "\tpublic function __construct( $title, $namespace ) {\n\t\t$this->mTitle = $title;\n\t\t$this->mNamespace = $namespace;\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic static function dplChapterParserFunction( &$parser, $text = '', $heading = ' ', $maxLength = -1, $page = '?page?', $link = 'default', $trim = false ) {\n\t\t$parser->addTrackingCategory( 'dplchapter-parserfunc-tracking-category' );\n\t\t$output = \\DPL\\LST::extractHeadingFromText( $parser, $page, '?title?', $text, $heading, '', $sectionHeading, true, $maxLength, $link, $trim );\n\t\treturn $output[0];\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\t\t\t$parameter = strtolower( $parameter ); //Force lower case for ease of use.\n\t\t\tif ( empty( $parameter ) || substr( $parameter, 0, 1 ) == '#' || ( $this->parameters->exists( $parameter ) && !$this->parameters->testRichness( $parameter ) ) ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ( !$this->parameters->exists( $parameter ) ) {\n\t\t\t\t$this->logger->addMessage( \\DynamicPageListHooks::WARN_UNKNOWNPARAM, $parameter, implode( ', ', $this->parameters->getParametersForRichness() ) );\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t//Ignore parameter settings without argument (except namespace and category).\n\t\t\tif ( !strlen( $option ) ) {\n\t\t\t\tif ( $parameter != 'namespace' && $parameter != 'notnamespace' && $parameter != 'category' && $this->parameters->exists( $parameter ) ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$parameters[$parameter][] = $option;\n\t\t}\n\t\treturn $parameters;\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tprivate function getOutput() {\n\t\t//@TODO: 2015-08-28 Consider calling $this->replaceVariables() here. Might cause issues with text returned in the results.\n\t\treturn $this->output;\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic function addOrderBy( $orderBy ) {\n\t\tif ( empty( $orderBy ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty order by clause was passed.' );\n\t\t}\n\t\t$this->orderBy[] = $orderBy;\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tprivate function _adduser( $option, $tableAlias = '' ) {\n\t\t$tableAlias = ( !empty( $tableAlias ) ? $tableAlias . '.' : '' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t$tableAlias . 'revactor_actor',\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic static function newFromStyle( $style, \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\t$style = strtolower( $style );\n\t\tswitch ( $style ) {\n\t\t\tcase 'category':\n\t\t\t\t$class = 'CategoryList';\n\t\t\t\tbreak;\n\t\t\tcase 'definition':\n\t\t\t\t$class = 'DefinitionList';\n\t\t\t\tbreak;\n\t\t\tcase 'gallery':\n\t\t\t\t$class = 'GalleryList';\n\t\t\t\tbreak;\n\t\t\tcase 'inline':\n\t\t\t\t$class = 'InlineList';\n\t\t\t\tbreak;\n\t\t\tcase 'ordered':\n\t\t\t\t$class = 'OrderedList';\n\t\t\t\tbreak;\n\t\t\tcase 'subpage':\n\t\t\t\t$class = 'SubPageList';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\tcase 'unordered':\n\t\t\t\t$class = 'UnorderedList';\n\t\t\t\tbreak;\n\t\t\tcase 'userformat':\n\t\t\t\t$class = 'UserFormatList';\n\t\t\t\tbreak;\n\t\t}\n\t\t$class = '\\DPL\\Lister\\\\' . $class;\n\n\t\treturn new $class( $parameters, $parser );\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic function setHeadListAttributes( $attributes ) {\n\t\t$this->headListAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic function setPageTextMatch( array $pageTextMatch = [] ) {\n\t\t$this->pageTextMatch = (array)$pageTextMatch;\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic function setListAttributes( $attributes ) {\n\t\t$this->listAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "CWE-400", "label": 2} {"code": "\tpublic function setSectionSeparators( ?array $separators ) {\n\t\t$this->sectionSeparators = (array)$separators ?? [];\n\t}", "label_name": "CWE-400", "label": 2} {"code": " public function __construct(AuthManager $auth, Repository $config)\n {\n $this->lockoutTime = $config->get('auth.lockout.time');\n $this->maxLoginAttempts = $config->get('auth.lockout.attempts');\n\n $this->auth = $auth;\n $this->config = $config;\n }", "label_name": "CWE-287", "label": 4} {"code": " public function __construct(\n AuthManager $auth,\n Repository $config,\n CacheRepository $cache,\n UserRepositoryInterface $repository,\n ViewFactory $view\n ) {\n parent::__construct($auth, $config);\n\n $this->view = $view;\n $this->cache = $cache;\n $this->repository = $repository;\n }", "label_name": "CWE-287", "label": 4} {"code": " $bool = self::evaluateTypedCondition($array, $expression);\n\n if (!$bool) {\n $hit->parentNode->removeChild($hit);\n } else {\n $hit->removeAttribute('n-if');\n }\n }\n return $doc->saveHTML();\n }", "label_name": "CWE-74", "label": 1} {"code": "\t\t\t\tLP_Request::register_ajax( $action, $callback );\n\t\t\t}\n\n\t\t\tadd_action( 'wp_ajax_learnpress_upload-user-avatar', array( __CLASS__, 'upload_user_avatar' ) );\n\t\t}", "label_name": "CWE-610", "label": 17} {"code": " public function destroy(Appointment $appointment)\n {\n if (!auth()->user()->can(\"appointment-create\")) {\n return response(\"Access denied\", 403);\n }\n\n $deleted = $appointment->delete();\n if ($deleted) {\n return response(\"Success\");\n }\n return response(\"Error\", 503);\n }", "label_name": "CWE-862", "label": 8} {"code": " public function rules()\n {\n return [\n 'name' => 'required',\n 'email' => 'required|email',\n 'address' => '',\n 'primary_number' => 'numeric',\n 'secondary_number' => 'numeric',\n 'password' => 'required|min:5|confirmed',\n 'password_confirmation' => 'required|min:5',\n 'image_path' => '',\n 'roles' => 'required',\n 'departments' => 'required'\n ];\n }", "label_name": "CWE-862", "label": 8} {"code": " public function rules()\n {\n return [\n 'name' => 'required',\n 'email' => 'required|email',\n 'address' => '',\n 'primary_number' => 'numeric',\n 'secondary_number' => 'numeric',\n 'password' => 'sometimes',\n 'password_confirmation' => 'sometimes',\n 'image_path' => '',\n 'departments' => 'required'\n ];\n }", "label_name": "CWE-862", "label": 8} {"code": "\t\tpublic function createBranch($name, $checkout = FALSE)\n\t\t{\n\t\t\t// git branch $name\n\t\t\t$this->run('branch', $name);\n\n\t\t\tif ($checkout) {\n\t\t\t\t$this->checkout($name);\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} {"code": "\t\tpublic function pull($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('pull', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} {"code": "\t\tpublic function addRemote($name, $url, array $params = NULL)\n\t\t{\n\t\t\t$this->run('remote', 'add', $params, $name, $url);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} {"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": "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": " resolve: function resolve(hostname) {\n var output,\n nodeBinary = process.execPath,\n scriptPath = path.join(__dirname, \"../scripts/dns-lookup-script\"),\n response,\n cmd = util.format('\"%s\" \"%s\" %s', nodeBinary, scriptPath, hostname);\n\n response = shell.exec(cmd, {silent: true});\n if (response && response.code === 0) {\n output = response.output;\n if (output && net.isIP(output)) {\n return output;\n }\n }\n debug('hostname', \"fail to resolve hostname \" + hostname);\n return null;\n }", "label_name": "CWE-77", "label": 14} {"code": "RecordViewWidgetManager.prototype._init = function () {\n this._hiddenWidgetsMenuSelector = '#x2-hidden-widgets-menu';\n this._hiddenWidgetsMenuItemSelector = \n '.x2-hidden-widgets-menu-item.' + this.widgetType + '-widget';\n this._setUpRecordViewTypeToggleBehavior ();\n this._widgetsBoxSelector = '#' + this.cssSelectorPrefix + 'widgets-container-2';\n this._widgetsBoxSelector2 = '#' + this.cssSelectorPrefix + 'widgets-container-inner';\n\n SortableWidgetManager.prototype._init.call (this);\n};", "label_name": "CWE-20", "label": 0} {"code": " function process () {\n var packet = packets.shift()\n var done = completeParse\n\n if (packet) {\n that._handlePacket(packet, process)\n } else {\n completeParse = null\n done()\n }\n }", "label_name": "CWE-674", "label": 28} {"code": "MqttClient.prototype._setupStream = function () {\n var connectPacket\n var that = this\n var writable = new Writable()\n var parser = mqttPacket.parser(this.options)\n var completeParse = null\n var packets = []\n\n this._clearReconnect()\n\n this.stream = this.streamBuilder(this)\n\n parser.on('packet', function (packet) {\n packets.push(packet)\n })\n\n function process () {\n var packet = packets.shift()\n var done = completeParse\n\n if (packet) {\n that._handlePacket(packet, process)\n } else {\n completeParse = null\n done()\n }\n }\n\n writable._write = function (buf, enc, done) {\n completeParse = done\n parser.parse(buf)\n process()\n }\n\n this.stream.pipe(writable)\n\n // Suppress connection errors\n this.stream.on('error', nop)\n\n // Echo stream close\n eos(this.stream, this.emit.bind(this, 'close'))\n\n // Send a connect packet\n connectPacket = Object.create(this.options)\n connectPacket.cmd = 'connect'\n // avoid message queue\n sendPacket(this, connectPacket)\n\n // Echo connection errors\n parser.on('error', this.emit.bind(this, 'error'))\n\n // many drain listeners are needed for qos 1 callbacks if the connection is intermittent\n this.stream.setMaxListeners(1000)\n\n clearTimeout(this.connackTimer)\n this.connackTimer = setTimeout(function () {\n that._cleanUp(true)\n }, this.options.connectTimeout)\n}", "label_name": "CWE-674", "label": 28} {"code": " writable._write = function (buf, enc, done) {\n completeParse = done\n parser.parse(buf)\n process()\n }", "label_name": "CWE-674", "label": 28} {"code": "\t\titems: function (schema, post, callback) {\n\t\t\tif (typeof callback === 'function') {\n\t\t\t\treturn this.asyncItems(schema, post, callback);\n\t\t\t}\n\t\t\tif (!(schema.items instanceof Object) || !(post instanceof Object)) {\n\t\t\t\treturn post;\n\t\t\t}\n\t\t\tvar i;\n\t\t\tif (_typeIs.array(schema.items) && _typeIs.array(post)) {\n\t\t\t\tvar minLength = schema.items.length < post.length ? schema.items.length : post.length;\n\t\t\t\tfor (i = 0; i < minLength; i++) {\n\t\t\t\t\tthis._deeperArray(i);\n\t\t\t\t\tpost[i] = this._sanitize(schema.items[i], post[i]);\n\t\t\t\t\tthis._back();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (i in post) {\n\t\t\t\t\tif(post.hasOwnProperty(i)){\n\t\t\t\t\t\tthis._deeperArray(i);\n\t\t\t\t\t\tpost[i] = this._sanitize(schema.items, post[i]);\n\t\t\t\t\t\tthis._back();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn post;\n\t\t},", "label_name": "CWE-668", "label": 7} {"code": "\t\titems: function (schema, candidate, callback) {\n\t\t\tif (typeof callback === 'function') {\n\t\t\t\treturn this.asyncItems(schema, candidate, callback);\n\t\t\t}\n\t\t\tif (!(schema.items instanceof Object) || !(candidate instanceof Object)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar items = schema.items;\n\t\t\tvar i, l;\n\t\t\t// If provided schema is an array\n\t\t\t// then call validate for each case\n\t\t\t// else it is an Object\n\t\t\t// then call validate for each key\n\t\t\tif (_typeIs.array(items) && _typeIs.array(candidate)) {\n\t\t\t\tfor (i = 0, l = items.length; i < l; i++) {\n\t\t\t\t\tthis._deeperArray(i);\n\t\t\t\t\tthis._validate(items[i], candidate[i]);\n\t\t\t\t\tthis._back();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (var key in candidate) {\n\t\t\t\t\tif (candidate.hasOwnProperty(key)){\n\t\t\t\t\t\tthis._deeperArray(key);\n\t\t\t\t\t\tthis._validate(items, candidate[key]);\n\t\t\t\t\t\tthis._back();\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}", "label_name": "CWE-668", "label": 7} {"code": "DotObject.prototype.set = function (path, val, obj, merge) {\n var i\n var k\n var keys\n var key\n\n // Do not operate if the value is undefined.\n if (typeof val === 'undefined') {\n return obj\n }\n keys = parsePath(path, this.separator)\n\n for (i = 0; i < keys.length; i++) {\n key = keys[i]\n if (i === (keys.length - 1)) {\n if (merge && isObject(val) && isObject(obj[key])) {\n for (k in val) {\n if (hasOwnProperty.call(val, k)) {\n obj[key][k] = val[k]\n }\n }\n } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {\n for (var j = 0; j < val.length; j++) {\n obj[keys[i]].push(val[j])\n }\n } else {\n obj[key] = val\n }\n } else if (\n // force the value to be an object\n !hasOwnProperty.call(obj, key) ||\n (!isObject(obj[key]) && !Array.isArray(obj[key]))\n ) {\n // initialize as array if next key is numeric\n if (/^\\d+$/.test(keys[i + 1])) {\n obj[key] = []\n } else {\n obj[key] = {}\n }\n }\n obj = obj[key]\n }\n return obj\n}", "label_name": "CWE-74", "label": 1} {"code": " const res = (result) => {\n let val = '';\n if (!pattern || ((typeof pattern !== 'object') && (typeof pattern !== 'string') && typeof pattern !== 'function')) {\n val = String(pattern)\n } else if (pattern.constructor === JpvObject) {\n val = `operator \"${pattern.type}\": ${JSON.stringify(pattern.value)}`;\n } else {\n JSON.stringify(pattern)\n }\n\n\n if (typeof pattern === 'function') {\n val = pattern.toString();\n }\n if (!result && options && options.debug) {\n options.logger(`error - the value of: {${options.deepLog.join('.')}: ` +\n `${String(value)}} not matched with: ${val}`);\n }\n return result;\n };", "label_name": "CWE-20", "label": 0} {"code": "d.addHours=function(a,c){return d.addMinutes(a,60*c)};d.addMinutes=function(a,c){return d.addSeconds(a,60*c)};d.addSeconds=function(a,c){return d.addMilliseconds(a,1E3*c)};d.addMilliseconds=function(a,c){return new Date(a.getTime()+c)};d.subtract=function(a,c){var b=a.getTime()-c.getTime();return{toMilliseconds:function(){return b},toSeconds:function(){return b/1E3},toMinutes:function(){return b/6E4},toHours:function(){return b/36E5},toDays:function(){return b/864E5}}};d.isLeapYear=function(a){return!(a%", "label_name": "CWE-400", "label": 2} {"code": "c,!c&&r[a]&&(d.extend(r[a]),q&&!q.date&&console.warn(\"This method of applying plugins is deprecated. See documentation for details.\")))};d.locale(m,{});\"object\"===typeof module&&\"object\"===typeof module.exports?module.exports=d:\"function\"===typeof define&&define.amd?define([],function(){return d}):q.date=d})(this);", "label_name": "CWE-400", "label": 2} {"code": "var escapeQuotes = function (str) {\n if (typeof str === 'string') {\n return str.replace(/([\"$`\\\\])/g, '\\\\$1');\n } else {\n return str;\n }\n};", "label_name": "CWE-77", "label": 14} {"code": " filterChain: function() {\n var left = this.expression();\n while (this.expect('|')) {\n left = this.filter(left);\n }\n return left;\n },", "label_name": "CWE-74", "label": 1} {"code": "function allowAutoBootstrap(document) {\n if (!document.currentScript) {\n return true;\n }\n var src = document.currentScript.getAttribute('src');\n var link = document.createElement('a');\n link.href = src;\n var scriptProtocol = link.protocol;\n var docLoadProtocol = document.location.protocol;\n if ((scriptProtocol === 'resource:' ||\n scriptProtocol === 'chrome-extension:') &&\n docLoadProtocol !== scriptProtocol) {\n return false;\n }\n return true;\n}", "label_name": "CWE-74", "label": 1} {"code": "function bind(self, fn) {\n var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n if (isFunction(fn) && !(fn instanceof RegExp)) {\n return curryArgs.length\n ? function() {\n return arguments.length\n ? fn.apply(self, concat(curryArgs, arguments, 0))\n : fn.apply(self, curryArgs);\n }\n : function() {\n return arguments.length\n ? fn.apply(self, arguments)\n : fn.call(self);\n };\n } else {\n // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).\n return fn;\n }\n}", "label_name": "CWE-74", "label": 1} {"code": " lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n var self = this;\n return function() {\n self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);\n };\n },", "label_name": "CWE-74", "label": 1} {"code": " } : 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 };", "label_name": "CWE-74", "label": 1} {"code": " member: function(left, right, computed) {\n if (computed) return this.computedMember(left, right);\n return this.nonComputedMember(left, right);\n },", "label_name": "CWE-74", "label": 1} {"code": " function isAllDefined(value) {\n var allDefined = true;\n forEach(value, function(val) {\n if (!isDefined(val)) allDefined = false;\n });\n return allDefined;\n }", "label_name": "CWE-74", "label": 1} {"code": "var Parser = function Parser(lexer, $filter, options) {\n this.lexer = lexer;\n this.$filter = $filter;\n this.options = options;\n this.ast = new AST(lexer, options);\n this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :\n new ASTCompiler(this.ast, $filter);\n};", "label_name": "CWE-74", "label": 1} {"code": " ternary: function() {\n var test = this.logicalOR();\n var alternate;\n var consequent;\n if (this.expect('?')) {\n alternate = this.expression();\n if (this.consume(':')) {\n consequent = this.expression();\n return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};\n }\n }\n return test;\n },", "label_name": "CWE-74", "label": 1} {"code": " 'unary!': function(argument, context) {\n return function(scope, locals, assign, inputs) {\n var arg = !argument(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },", "label_name": "CWE-74", "label": 1} {"code": " angular.resumeBootstrap = function(extraModules) {\n forEach(extraModules, function(module) {\n modules.push(module);\n });\n return doBootstrap();\n };", "label_name": "CWE-74", "label": 1} {"code": " compile: function(expression) {\n var self = this;\n var ast = this.astBuilder.ast(expression);\n this.state = {\n nextId: 0,\n filters: {},\n fn: {vars: [], body: [], own: {}},\n assign: {vars: [], body: [], own: {}},\n inputs: []\n };\n findConstantAndWatchExpressions(ast, self.$filter);\n var extra = '';\n var assignable;\n this.stage = 'assign';\n if ((assignable = assignableAST(ast))) {\n this.state.computing = 'assign';\n var result = this.nextId();\n this.recurse(assignable, result);\n this.return_(result);\n extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n }\n var toWatch = getInputs(ast.body);\n self.stage = 'inputs';\n forEach(toWatch, function(watch, key) {\n var fnKey = 'fn' + key;\n self.state[fnKey] = {vars: [], body: [], own: {}};\n self.state.computing = fnKey;\n var intoId = self.nextId();\n self.recurse(watch, intoId);\n self.return_(intoId);\n self.state.inputs.push(fnKey);\n watch.watchId = key;\n });\n this.state.computing = 'fn';\n this.stage = 'main';\n this.recurse(ast);\n var fnString =\n // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n this.filterPrefix() +\n 'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n extra +\n this.watchFns() +\n 'return fn;';\n\n // eslint-disable-next-line no-new-func\n var fn = (new Function('$filter',\n 'getStringValue',\n 'ifDefined',\n 'plus',\n fnString))(\n this.$filter,\n getStringValue,\n ifDefined,\n plusFn);\n this.state = this.stage = undefined;\n fn.ast = ast;\nfn.literal = isLiteral(ast);\n fn.constant = isConstant(ast);\n return fn;\n },", "label_name": "CWE-74", "label": 1} {"code": " var unwatch = scope.$watch(function constantWatch(scope) {\n unwatch();\n return parsedExpression(scope);\n }, listener, objectEquality);", "label_name": "CWE-74", "label": 1} {"code": " copySync: function (from, dist) {\n this._supportExecSync();\n try {\n var cmd = '';\n var stats = fs.lstatSync(from);\n dist = path.resolve(dist);\n if (stats.isDirectory()) {\n if (this._win32) {\n // windows\n cmd = 'echo da|xcopy /s /e \"' + path.join(from, '*') + '\" \"' + dist + '\"';\n } else {\n // linux or mac\n cmd = 'cp -f -R -p ' + path.join(from, '*').replace(/ /g, '\\\\ ') + ' ' + dist.replace(/ /g, '\\\\ ');\n }\n } else if (stats.isFile()) {\n if (this._win32) {\n // windows\n cmd = 'echo fa|xcopy \"' + from + '\" \"' + dist + '\"';\n } else {\n // linux or mac\n cmd = 'cp -f -p ' + from.replace(/ /g, '\\\\ ') + ' ' + dist.replace(/ /g, '\\\\ ');\n }\n }\n cmd && child_process.execSync(cmd);\n } catch (e) {}\n },", "label_name": "CWE-77", "label": 14} {"code": " remove: function (from, callback) {\n var that = this,\n cmd = '';\n fs.lstat(from, function (err, stats) {\n if (err) {\n callback(err);\n } else {\n if (that._win32) {\n // windows\n if (stats.isDirectory()) {\n cmd = 'rd /s /q \"' + from + '\"';\n } else if (stats.isFile()) {\n cmd = 'del /f \"' + from + '\"';\n }\n } else {\n // linux or mac\n cmd = 'rm -rf ' + from.replace(/ /g, '\\\\ ');\n }\n if (cmd) {\n child_process.exec(cmd, function (error, stdout, stderr) {\n callback && callback(error);\n });\n } else {\n callback && callback(null);\n }\n }\n });\n },", "label_name": "CWE-77", "label": 14} {"code": " text: src.slice(2, cap[0].length - 2)\n };\n }\n }\n }\n };", "label_name": "CWE-400", "label": 2} {"code": "function ElementAttributes(source){\n\t\n}", "label_name": "CWE-436", "label": 5} {"code": "exports.debug = (msg, tag, traceId) => {\n // @todo: this function should depend on companion's debug option instead\n if (process.env.NODE_ENV !== 'production') {\n // @ts-ignore\n log(msg, tag, 'debug', traceId, chalk.bold.blue)\n }\n}", "label_name": "CWE-863", "label": 11} {"code": "export function isOriginPotentiallyTrustworthy(url) {\n\t// 1. If origin is an opaque origin, return \"Not Trustworthy\".\n\t// Not applicable\n\n\t// 2. Assert: origin is a tuple origin.\n\t// Not for implementations\n\n\t// 3. If origin's scheme is either \"https\" or \"wss\", return \"Potentially Trustworthy\".\n\tif (/^(http|ws)s:$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return \"Potentially Trustworthy\".\n\tconst hostIp = url.host.replace(/(^\\[)|(]$)/g, '');\n\tconst hostIPVersion = isIP(hostIp);\n\n\tif (hostIPVersion === 4 && /^127\\./.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\tif (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\t// 5. If origin's host component is \"localhost\" or falls within \".localhost\", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return \"Potentially Trustworthy\".\n\t// We are returning FALSE here because we cannot ensure conformance to\n\t// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)\n\tif (/^(.+\\.)*localhost$/.test(url.host)) {\n\t\treturn false;\n\t}\n\n\t// 6. If origin's scheme component is file, return \"Potentially Trustworthy\".\n\tif (url.protocol === 'file:') {\n\t\treturn true;\n\t}\n\n\t// 7. If origin's scheme component is one which the user agent considers to be authenticated, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 8. If origin has been configured as a trustworthy origin, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 9. Return \"Not Trustworthy\".\n\treturn false;\n}", "label_name": "CWE-400", "label": 2} {"code": " function buildMessageHTML (message) {\n var html = ''\n var loggedInAccountId = window.trudeskSessionService.getUser()._id\n if (loggedInAccountId === undefined) return false\n var left = true\n if (message.owner._id.toString() === loggedInAccountId.toString()) {\n left = false\n }\n\n var image = message.owner.image === undefined ? 'defaultProfile.jpg' : message.owner.image\n\n if (left) {\n html += '
'\n html +=\n ''\n html += '
'\n html += '

' + message.body + '

'\n html += '
'\n html += '
'\n } else {\n html += '
'\n html +=\n '
'\n html += '

' + message.body + '

'\n html += '
'\n html += '
'\n }\n\n return html\n }", "label_name": "CWE-662", "label": 20} {"code": "z.y,t.width/L,t.height/L,\"fillColor=none;strokeColor=red;\")}));c.actions.addAction(\"testCheckFile\",mxUtils.bind(this,function(){var t=null!=c.pages&&null!=c.getCurrentFile()?c.getCurrentFile().getAnonymizedXmlForPages(c.pages):\"\";t=new TextareaDialog(c,\"Paste Data:\",t,function(z){if(0=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": "for(la=ma=0;la
< '+mxResources.get(\"back\")+'
'+", "label_name": "CWE-20", "label": 0} {"code": "Q.marginBottom||0;R.allowGaps=Q.allowGaps||0;R.horizontal=\"1\"==mxUtils.getValue(Q,\"horizontalRack\",\"0\");R.resizeParent=!1;R.fill=!0;return R}return T.apply(this,arguments)};this.updateGlobalUrlVariables()};var B=Graph.prototype.postProcessCellStyle;Graph.prototype.postProcessCellStyle=function(u,E){return Graph.processFontStyle(B.apply(this,arguments))};var I=mxSvgCanvas2D.prototype.updateTextNodes;mxSvgCanvas2D.prototype.updateTextNodes=function(u,E,J,T,N,Q,R,Y,ba,ea,Z){I.apply(this,arguments);Graph.processFontAttributes(Z)};", "label_name": "CWE-20", "label": 0} {"code": "function(){return null!=q?q.readyState:3};this.getLastError=function(){return S};this.mouseListeners={startX:0,startY:0,scrollLeft:0,scrollTop:0,mouseDown:function(M,W){},mouseMove:function(M,W){var U,X=-1;return function(){clearTimeout(U);var u=this,E=arguments,J=function(){U=null;X=Date.now();M.apply(u,E)};Date.now()-X>W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label_name": "CWE-20", "label": 0} {"code": "this.customFonts)))}finally{V.getModel().endUpdate()}}}));this.editorUi.showDialog(W.container,380,Editor.enableWebFonts?250:180,!0,!0);W.init()}),z,null,!0)})))}})();function DiagramPage(b,e){this.node=b;null!=e?this.node.setAttribute(\"id\",e):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": "folderId:Q,siteId:R});ja=\"/drives/\"+R+(Q?\"/items/\"+Q:\"/root\")+\"/children\";break;case \"search\":N=S;M=[{driveId:N,name:mxResources.get(\"back\",null,\"Back\")}];ba=encodeURIComponent(ba.replace(/'/g,\"\\\\'\"));ja=N?\"/drives/\"+N+\"/root/search(q='\"+ba+\"')\":\"/me/drive/root/search(q='\"+ba+\"')\";break;default:null==Q?M=[{driveId:N}]:M.push({name:Y,driveId:N,folderId:Q}),ja=(N?\"/drives/\"+N:\"/me/drive\")+(Q?\"/items/\"+Q:\"/root\")+\"/children\"}fa||(ja+=(0
');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": "z,mxUtils.bind(this,function(){var E=null;if(!t){E=parseInt(H.value);var J=parseInt(V.value);E=K.checked||E==G&&J==G?null:{from:Math.max(0,Math.min(D-1,E-1)),to:Math.max(0,Math.min(D-1,J-1))}}c.downloadFile(\"pdf\",null,null,!M.checked,t?!0:!K.checked&&null==E,!W.checked,null!=X&&X.checked,null,null,U.checked,null!=u&&u.checked,E)}),null,mxResources.get(\"export\"));c.showDialog(z.container,300,L,!0,!0)}else c.showDialog((new PrintDialog(c,mxResources.get(\"formatPdf\"))).container,360,null!=c.pages&&1<", "label_name": "CWE-20", "label": 0} {"code": "mxResources.get(\"dragImagesHere\"));f.appendChild(y);var A={},B=null,I=null,O=null;e=function(D){\"true\"!=mxEvent.getSource(D).getAttribute(\"contentEditable\")&&null!=O&&(O(),O=null,mxEvent.consume(D))};mxEvent.addListener(x,\"mousedown\",e);mxEvent.addListener(x,\"pointerdown\",e);mxEvent.addListener(x,\"touchstart\",e);var t=new mxUrlConverter,z=!1;if(null!=c)for(e=0;ef&&(mxUtils.br(g),v=1);var O=document.createElement(\"a\");O.style.overflow=\"hidden\";O.style.display=\"inline-block\";O.className=\"geBaseButton\";O.style.boxSizing=\"border-box\";O.style.fontSize=\"11px\";O.style.position=\"relative\";O.style.margin=\"4px\";O.style.marginTop=\"8px\";O.style.marginBottom=\"0px\";O.style.padding=\"8px 10px 8px 10px\";O.style.width=\"88px\";O.style.height=\"100px\";O.style.whiteSpace=\"nowrap\";O.setAttribute(\"title\",", "label_name": "CWE-20", "label": 0} {"code": "Editor.createRoughCanvas=function(u){var E=rough.canvas({getContext:function(){return u}});E.draw=function(J){var T=J.sets||[];J=J.options||this.getDefaultOptions();for(var N=0;N=this.status)try{var ea=Y.responseText;\nba&&(ea=\"data:image/png;base64,\"+Editor.base64Encode(ea),ea=Editor.extractGraphModelFromPng(ea));var Z=mxUtils.parseXml(ea),fa=\"mxlibrary\"==Z.documentElement.nodeName?Z.documentElement:Editor.extractGraphModel(Z.documentElement);if(null!=fa){Q(fa.ownerDocument);return}}catch(aa){}R()}};ba&&Y.overrideMimeType&&Y.overrideMimeType(\"text/plain; charset=x-user-defined\");Y.send()}function B(){p&&null!=F?K.exportToCanvas(function(N){N=EditorUi.prototype.createImageDataUri(N,null,\"png\");v(H,N);n(H)},400,", "label_name": "CWE-20", "label": 0} {"code": "\"80px\";mxUtils.setPrefixedStyle(m.style,\"transform\",\"translate(50%,-50%)\");n.appendChild(m);mxClient.IS_FF||null==navigator.clipboard||\"image/png\"!=x||(A=mxUtils.button(mxResources.get(\"copy\"),function(P){P=b.base64ToBlob(L,\"image/png\");P=new ClipboardItem({\"image/png\":P,\"text/html\":new Blob([''],{type:\"text/html\"})});navigator.clipboard.write([P]).then(mxUtils.bind(this,function(){b.alert(mxResources.get(\"copiedToClipboard\"))}))[\"catch\"](mxUtils.bind(this,function(K){b.handleError(K)}))}),", "label_name": "CWE-20", "label": 0} {"code": "function(){b.hideDialog(!0)});f.className=\"geBtn\";d=null!=d?mxUtils.button(mxResources.get(\"ignore\"),d):null;null!=d&&(d.className=\"geBtn\");b.editor.cancelFirst?(y.appendChild(f),null!=d&&y.appendChild(d),y.appendChild(v),y.appendChild(n)):(y.appendChild(n),y.appendChild(v),null!=d&&y.appendChild(d),y.appendChild(f));k.appendChild(y);k.appendChild(A);this.container=k},FindWindow=function(b,e,f,c,m,n){function v(U,X,u,E){if(\"object\"===typeof X.value&&null!=X.value.attributes){X=X.value.attributes;\nfor(var J=0;J=Math.max(U.x,V.x)||S&&Math.min(U.y+U.height,V.y+V.height)>=Math.max(U.y,V.y))&&M.push(U)}M.sort(function(X,u){return S?X.x+X.width-u.x-u.width:X.y+X.height-\nu.y-u.height})}return M}function q(H,S){var V=d(H),M=S==mxConstants.DIRECTION_EAST||S==mxConstants.DIRECTION_WEST;(V==mxConstants.DIRECTION_EAST||V==mxConstants.DIRECTION_WEST)==M&&V!=S?x.actions.get(\"selectParent\").funct():V==S?(S=y.getOutgoingTreeEdges(H),null!=S&&0\\x3c/script>')),ma.closeDocument(),!ma.mathEnabled&&ya&&PrintDialog.printPreview(ma));null!=xa&&(N.shapeForegroundColor=ha,N.shapeBackgroundColor=da,N.stylesheet=\nxa,N.refresh())}}var N=u.editor.graph,Q=document.createElement(\"div\"),R=document.createElement(\"h3\");R.style.width=\"100%\";R.style.textAlign=\"center\";R.style.marginTop=\"0px\";mxUtils.write(R,E||mxResources.get(\"print\"));Q.appendChild(R);var Y=1,ba=1;R=document.createElement(\"div\");R.style.cssText=\"border-bottom:1px solid lightGray;padding-bottom:12px;margin-bottom:12px;\";var ea=document.createElement(\"input\");ea.style.cssText=\"margin-right:8px;margin-bottom:8px;\";ea.setAttribute(\"value\",\"all\");ea.setAttribute(\"type\",", "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(C){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=C?C:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var B=EditorUi.prototype.destroy;EditorUi.prototype.destroy=function(){null!=this.sidebarWindow&&(this.sidebarWindow.window.setVisible(!1),this.sidebarWindow.window.destroy(),this.sidebarWindow=null);null!=this.formatWindow&&(this.formatWindow.window.setVisible(!1),this.formatWindow.window.destroy(),\nthis.formatWindow=null);null!=this.actions.outlineWindow&&(this.actions.outlineWindow.window.setVisible(!1),this.actions.outlineWindow.window.destroy(),this.actions.outlineWindow=null);null!=this.actions.layersWindow&&(this.actions.layersWindow.window.setVisible(!1),this.actions.layersWindow.destroy(),this.actions.layersWindow=null);null!=this.menus.tagsWindow&&(this.menus.tagsWindow.window.setVisible(!1),this.menus.tagsWindow.window.destroy(),this.menus.tagsWindow=null);null!=this.menus.findWindow&&\n(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;", "label_name": "CWE-20", "label": 0} {"code": "this.customFonts)))}finally{V.getModel().endUpdate()}}}));this.editorUi.showDialog(W.container,380,Editor.enableWebFonts?250:180,!0,!0);W.init()}),z,null,!0)})))}})();function DiagramPage(b,e){this.node=b;null!=e?this.node.setAttribute(\"id\",e):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(t){k.editorUiRefresh.apply(b,arguments);m()};m();var q=document.createElement(\"canvas\");q.width=p.offsetWidth;q.height=p.offsetHeight;p.style.overflow=\"hidden\";q.style.position=\"relative\";p.appendChild(q);var x=q.getContext(\"2d\");this.ui=b;var y=b.editor.graph;this.graph=y;this.container=p;this.canvas=q;var A=function(t,z,L,C,D){t=Math.round(t);z=Math.round(z);L=Math.round(L);C=Math.round(C);x.beginPath();x.moveTo(t+.5,z+.5);x.lineTo(L+.5,C+.5);x.stroke();D&&(f?(x.save(),x.translate(t,z),\nx.rotate(-Math.PI/2),x.fillText(D,0,0),x.restore()):x.fillText(D,t,z))},B=function(){x.clearRect(0,0,q.width,q.height);x.beginPath();x.lineWidth=.7;x.strokeStyle=l.strokeClr;x.setLineDash([]);x.font=\"9px Arial\";x.textAlign=\"center\";var t=y.view.scale,z=y.view.getBackgroundPageBounds(),L=y.view.translate,C=y.pageVisible;L=C?g+(f?z.y-y.container.scrollTop:z.x-y.container.scrollLeft):g+(f?L.y*t-y.container.scrollTop:L.x*t-y.container.scrollLeft);var D=0;C&&(D=y.getPageLayout(),D=f?D.y*y.pageFormat.height:", "label_name": "CWE-20", "label": 0} {"code": "H,[D]);var M=g.model.getGeometry(D);null!=M&&(M=M.clone(),M.width=Math.max(M.width,S),M.height=Math.max(M.height,V),g.cellsResized([D],[M],!1));g.setAttributeForCell(D,\"mermaidData\",JSON.stringify({data:F,config:K.config},null,2))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};var k=g.cellEditor.startEditing;g.cellEditor.startEditing=function(D,G){try{var P=this.graph.getAttributeForCell(D,\"plantUmlData\");if(null!=\nP)this.editPlantUmlData(D,G,P);else if(P=this.graph.getAttributeForCell(D,\"mermaidData\"),null!=P)this.editMermaidData(D,G,P);else{var K=g.getCellStyle(D);\"1\"==mxUtils.getValue(K,\"metaEdit\",\"0\")?d.showDataDialog(D):k.apply(this,arguments)}}catch(F){d.handleError(F)}};g.getLinkTitle=function(D){return d.getLinkTitle(D)};g.customLinkClicked=function(D){var G=!1;try{d.handleCustomLink(D),G=!0}catch(P){d.handleError(P)}return G};var l=g.parseBackgroundImage;g.parseBackgroundImage=function(D){var G=l.apply(this,", "label_name": "CWE-20", "label": 0} {"code": "6)},function(L){for(var C=0;C=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": "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": "rect:F.diagramContainer.getBoundingClientRect()}),\"*\");F.refresh()}Q.style.left=F.diagramContainer.offsetLeft+\"px\";Q.style.top=F.diagramContainer.offsetTop-Q.offsetHeight-4+\"px\";N.style.display=\"\";N.style.left=F.diagramContainer.offsetLeft-N.offsetWidth-4+\"px\";N.style.top=F.diagramContainer.offsetTop+\"px\";T.style.left=F.diagramContainer.offsetLeft+F.diagramContainer.offsetWidth-T.offsetWidth+\"px\";T.style.top=Q.style.top;T.style.right=\"\";F.bottomResizer.style.left=F.diagramContainer.offsetLeft+(F.diagramContainer.offsetWidth-\nF.bottomResizer.offsetWidth)/2+\"px\";F.bottomResizer.style.top=F.diagramContainer.offsetTop+F.diagramContainer.offsetHeight-F.bottomResizer.offsetHeight/2-1+\"px\";F.rightResizer.style.left=F.diagramContainer.offsetLeft+F.diagramContainer.offsetWidth-F.rightResizer.offsetWidth/2-1+\"px\";F.rightResizer.style.top=F.diagramContainer.offsetTop+(F.diagramContainer.offsetHeight-F.bottomResizer.offsetHeight)/2+\"px\"}F.bottomResizer.style.visibility=Editor.inlineFullscreen?\"hidden\":\"\";F.rightResizer.style.visibility=\nF.bottomResizer.style.visibility;S.style.display=\"none\";Q.style.visibility=\"\";T.style.visibility=\"\"}),Y=mxUtils.bind(this,function(){Ea.style.backgroundImage=\"url(\"+(Editor.inlineFullscreen?Editor.fullscreenExitImage:Editor.fullscreenImage)+\")\";this.diagramContainer.style.background=Editor.inlineFullscreen?Editor.isDarkMode()?Editor.darkColor:\"#ffffff\":\"transparent\";R()});u=mxUtils.bind(this,function(){Y();b(F,!0);F.initFormatWindow();var da=this.diagramContainer.getBoundingClientRect();this.formatWindow.window.setLocation(da.x+", "label_name": "CWE-20", "label": 0} {"code": "T.isModified()&&T.fileChanged()},{install:function(R){this.listener=function(){R(E.editor.autosave)};E.editor.addListener(\"autosaveChanged\",this.listener)},destroy:function(){E.editor.removeListener(this.listener)}});u.appendChild(N)}}if(this.isMathOptionVisible()&&J.isEnabled()&&\"undefined\"!==typeof MathJax){N=this.createOption(mxResources.get(\"mathematicalTypesetting\"),function(){return J.mathEnabled},function(R){E.actions.get(\"mathematicalTypesetting\").funct()},{install:function(R){this.listener=", "label_name": "CWE-20", "label": 0} {"code": "this.startDrawing=function(){n(!0)};this.isDrawing=function(){return x};var y=mxUtils.bind(this,function(J){if(d){var E=c.length,H=A&&0c.length;H||D.push.apply(D,c);c=[];D.push(null);u.push(d);d=null;(H||k)&&this.stopDrawing();k&&2<=E&&this.startDrawing();mxEvent.consume(J)}}),K=new mxCell;K.edge=!0;var B=function(){var J=b.getCurrentCellStyle(K);J=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(J,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label_name": "CWE-20", "label": 0} {"code": "EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createSvgDataUri\");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedCssFonts\");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedExtFonts\");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent(\"SHOULD NOT BE CALLED: exportToCanvas\");\nreturn this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createImageUrlConverter\");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImages\");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImageToDataUri\");", "label_name": "CWE-20", "label": 0} {"code": "EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createSvgDataUri\");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedCssFonts\");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedExtFonts\");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent(\"SHOULD NOT BE CALLED: exportToCanvas\");", "label_name": "CWE-20", "label": 0} {"code": "function(){b.spinner.stop();if(null==b.linkPicker){var n=b.drive.createLinkPicker();b.linkPicker=n.setCallback(function(y){LinkDialog.filePicked(y)}).build()}b.linkPicker.setVisible(!0)}))});\"undefined\"!=typeof Dropbox&&\"undefined\"!=typeof Dropbox.choose&&c(IMAGE_PATH+\"/dropbox-logo.svg\",mxResources.get(\"dropbox\"),function(){Dropbox.choose({linkType:\"direct\",cancel:function(){},success:function(n){k.value=n[0].link;k.focus()}})});null!=b.oneDrive&&c(IMAGE_PATH+\"/onedrive-logo.svg\",mxResources.get(\"oneDrive\"),", "label_name": "CWE-20", "label": 0} {"code": "q&&k.apply(this,arguments)}),A=mxUtils.bind(this,function(){window.clearTimeout(v);q&&m.apply(this,arguments)});g=g||{};g.callbackId=this.remoteInvokeCallbacks.length;this.remoteInvokeCallbacks.push({callback:x,error:A});c=JSON.stringify({event:\"remoteInvoke\",funtionName:c,functionArgs:e,msgMarkers:g});null!=this.remoteWin?this.remoteWin.postMessage(c,\"*\"):this.remoteInvokeQueue.push(c)};EditorUi.prototype.handleRemoteInvoke=function(c,e){var g=mxUtils.bind(this,function(z,L){var M={event:\"remoteInvokeResponse\",\nmsgMarkers:c.msgMarkers};null!=L?M.error={errResp:L}:null!=z&&(M.resp=z);this.remoteWin.postMessage(JSON.stringify(M),\"*\")});try{var k=c.funtionName,m=this.remoteInvokableFns[k];if(null!=m&&\"function\"===typeof this[k]){if(m.allowedDomains){for(var q=!1,v=0;vm.oldVersion&&q.createObjectStore(\"objects\",{keyPath:\"key\"});", "label_name": "CWE-20", "label": 0} {"code": "p[C]}catch(I){null!=window.console&&console.log(\"Error in vars URL parameter: \"+I)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var y=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(p){var C=y.apply(this,arguments);null==C&&null!=this.globalVars&&(C=this.globalVars[p]);return C};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var p=this.themes[\"default-style2\"];this.defaultStylesheet=", "label_name": "CWE-20", "label": 0} {"code": "c;else if(\"mxfile\"==c.nodeName){var k=c.getElementsByTagName(\"diagram\");if(0=x.getStatus()?null!=l&&l():d({code:x.getStatus(),message:x.getStatus()}))}));EditorUi.debug(\"DrawioFileSync.fileSaved\",[this],\"diff\",g,m.length,\"bytes\",\"from\",c,\"to\",e,\"etag\",this.file.getCurrentEtag(),\"checksum\",k)}}this.file.setShadowPages(b);this.scheduleCleanup()};", "label_name": "CWE-20", "label": 0} {"code": "u,t,D,c,e),mxUtils.bind(this,function(g){return this.isTreeEdge(g)}))};Graph.prototype.getIncomingTreeEdges=function(d,u){return this.getTreeEdges(d,u,!0,!1,!1)};Graph.prototype.getOutgoingTreeEdges=function(d,u){return this.getTreeEdges(d,u,!1,!0,!1)};var f=EditorUi.prototype.init;EditorUi.prototype.init=function(){f.apply(this,arguments);this.editor.isChromelessView()&&!this.editor.editable||this.addTrees()};EditorUi.prototype.addTrees=function(){function d(H){return A.isVertex(H)&&t(H)}function u(H){var S=\n!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(0this.status)if(\"txt\"==e)g(this.response);else{var A=new FileReader;A.readAsDataURL(this.response);A.onloadend=function(z){var L=new Image;L.onload=\nfunction(){try{var M=L.width,n=L.height;if(0==M&&0==n){var y=A.result,K=y.indexOf(\",\"),B=decodeURIComponent(escape(atob(y.substring(K+1)))),F=mxUtils.parseXml(B).getElementsByTagName(\"svg\");0c.length;H||D.push.apply(D,c);c=[];D.push(null);u.push(d);d=null;(H||k)&&this.stopDrawing();k&&2<=E&&this.startDrawing();mxEvent.consume(J)}}),K=new mxCell;K.edge=!0;var B=function(){var J=b.getCurrentCellStyle(K);J=mxUtils.getValue(b.currentVertexStyle,mxConstants.STYLE_STROKECOLOR,mxUtils.getValue(J,mxConstants.STYLE_STROKECOLOR,\"#000\"));\"default\"==", "label_name": "CWE-20", "label": 0} {"code": "this.sidebar&&null!=urlParams[\"search-shapes\"]&&null!=this.sidebar.searchShapes&&(this.sidebar.searchShapes(urlParams[\"search-shapes\"]),this.sidebar.showEntries(\"search\"));var E=this;mxWindow.prototype.fit=function(){if(Editor.inlineFullscreen||null==E.embedViewport)mxUtils.fit(this.div);else{var ca=parseInt(this.div.offsetLeft),ba=parseInt(this.div.offsetWidth),ja=E.embedViewport.x+E.embedViewport.width,ia=parseInt(this.div.offsetTop),ma=parseInt(this.div.offsetHeight),qa=E.embedViewport.y+E.embedViewport.height;\nthis.div.style.left=Math.max(E.embedViewport.x,Math.min(ca,ja-ba))+\"px\";this.div.style.top=Math.max(E.embedViewport.y,Math.min(ia,qa-ma))+\"px\";this.div.style.height=Math.min(E.embedViewport.height,parseInt(this.div.style.height))+\"px\";this.div.style.width=Math.min(E.embedViewport.width,parseInt(this.div.style.width))+\"px\"}};this.keyHandler.bindAction(75,!0,\"toggleShapes\",!0);EditorUi.windowed&&(\"1\"==urlParams.sketch||1E3<=d)&&\"1\"!=urlParams.embedInline&&(b(this,!0),\"1\"==urlParams.sketch?(this.initFormatWindow(),", "label_name": "CWE-20", "label": 0} {"code": "U+\";\"))}),mxUtils.bind(this,function(p){e.setSelectionCells(this.insertTextAt(U,H,S,!0))})):0<=mxUtils.indexOf(F.dataTransfer.types,\"text/plain\")&&e.setSelectionCells(this.insertTextAt(F.dataTransfer.getData(\"text/plain\"),H,S,!0))}}F.stopPropagation();F.preventDefault()}),!1)}e.enableFlowAnimation=!0;this.initPages();\"1\"==urlParams.embed&&this.initializeEmbedMode();this.installSettings()};EditorUi.prototype.installImagePasteHandler=function(){if(!mxClient.IS_IE){var c=this.editor.graph;c.container.addEventListener(\"paste\",\nmxUtils.bind(this,function(e){if(!mxEvent.isConsumed(e))try{for(var g=e.clipboardData||e.originalEvent.clipboardData,k=!1,m=0;m'),Xa.writeln(Editor.mathJaxWebkitCss),Xa.writeln(\"\");mxClient.IS_GC&&(Xa.writeln('\"));null!=p.editor.fontCss&&(Xa.writeln('\"));for(var db=Ha.getCustomFonts(),cb=0;cb'):(Xa.writeln('\"))}};if(\"undefined\"!==typeof MathJax){var jb=Na.renderPage;Na.renderPage=function(Xa,db,cb,fb,eb,lb){var kb=mxClient.NO_FO;mxClient.NO_FO=this.graph.mathEnabled&&!p.editor.useForeignObjectForMath?!0:p.editor.originalNoForeignObject;var gb=jb.apply(this,arguments);mxClient.NO_FO=kb;this.graph.mathEnabled?this.mathEnabled=this.mathEnabled||!0:gb.className=\"geDisableMathJax\";return gb}}Wa=null;bb=P.shapeForegroundColor;$a=P.shapeBackgroundColor;Va=P.enableFlowAnimation;", "label_name": "CWE-20", "label": 0} {"code": "B)):N.isSelectionEmpty()&&N.isEnabled()?(B.addSeparator(),this.addMenuItems(B,[\"editData\"],null,G),B.addSeparator(),this.addSubmenu(\"layout\",B),this.addSubmenu(\"insert\",B),this.addMenuItems(B,[\"-\",\"exitGroup\"],null,G)):N.isEnabled()&&this.addMenuItems(B,[\"-\",\"lockUnlock\"],null,G)};var A=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(B,F,G){A.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&this.addMenuItems(B,[\"copyAsImage\"],null,G)};EditorUi.prototype.toggleFormatPanel=", "label_name": "CWE-20", "label": 0} {"code": "DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return\"draw.io\"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader(\"Content-Language\",\"da, mi, en, de-DE\")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent(\"SHOULD NOT BE CALLED: loadUrl\");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: loadFonts\");return this.editor.loadFonts(c)};", "label_name": "CWE-20", "label": 0} {"code": "M.checked,n.getLink(),B.checked)}),null,mxResources.get(\"embed\"),m);this.showDialog(e.container,280,300,!0,!0)};EditorUi.prototype.createEmbedImage=function(c,e,g,k,m,q,v,x){function A(y){var K=\" \",B=\"\";k&&(K=\" onclick=\\\"(function(img){if(img.wnd!=null&&!img.wnd.closed){img.wnd.focus();}else{var r=function(evt){if(evt.data=='ready'&&evt.source==img.wnd){img.wnd.postMessage(decodeURIComponent(img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('\"+\nEditorUi.lightboxHost+\"/?client=1\"+(null!=L?\"&page=\"+L:\"\")+(m?\"&edit=_blank\":\"\")+(q?\"&layers=1\":\"\")+\"');}})(this);\\\"\",B+=\"cursor:pointer;\");c&&(B+=\"max-width:100%;\");var F=\"\";g&&(F=' width=\"'+Math.round(z.width)+'\" height=\"'+Math.round(z.height)+'\"');v('\")}var z=this.editor.graph.getGraphBounds(),L=this.getSelectedPageIndex();if(this.isExportToCanvas())this.editor.exportToCanvas(mxUtils.bind(this,function(y){var K=k?this.getFileData(!0):null;y=", "label_name": "CWE-20", "label": 0} {"code": "index:I,defVal:la.defVal,countProperty:la.countProperty,size:la.size},0==I%2,la.flipBkg),C.parentNode.insertBefore(Ka,C.nextSibling),C=Ka;p.appendChild(ua);xa();return p};StyleFormatPanel.prototype.addStyles=function(p){function C(la){mxEvent.addListener(la,\"mouseenter\",function(){la.style.opacity=\"1\"});mxEvent.addListener(la,\"mouseleave\",function(){la.style.opacity=\"0.5\"})}var I=this.editorUi,T=I.editor.graph,P=document.createElement(\"div\");P.style.whiteSpace=\"nowrap\";P.style.paddingLeft=\"24px\";", "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(0H.getCenterX())return mxConstants.DIRECTION_WEST}}return mxConstants.DIRECTION_EAST}function e(H,S){S=null!=S?S:!0;x.model.beginUpdate();try{var U=x.model.getParent(H),Q=x.getIncomingTreeEdges(H),W=x.cloneCells([Q[0],H]);x.model.setTerminal(W[0],x.model.getTerminal(Q[0],", "label_name": "CWE-20", "label": 0} {"code": "f.appendChild(e);this.container=f},NewDialog=function(b,f,l,d,u,t,D,c,e,g,k,m,q,v,x,A,z,L){function M(pa){null!=pa&&(Fa=xa=pa?135:140);pa=!0;if(null!=Ma)for(;HmxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+\"=\"+urlParams[m],g=\"&\")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0 {\n assert(!err);\n });\n\n transport.on(\"message\", (messageChunk) => {\n utils.compare_buffers(messageChunk, openChannelRequest);\n\n // it should provide bytesRead and bytesWritten\n transport.bytesRead.should.be.greaterThan(0);\n transport.bytesWritten.should.be.greaterThan(20);\n\n done();\n });\n\n let counter = 1;\n fakeSocket.client.on(\"data\", (data) => {\n counter++;\n });\n\n transport.bytesRead.should.equal(0);\n transport.bytesWritten.should.equal(0);\n }", "label_name": "CWE-400", "label": 2} {"code": " function publish_callback(err, response) {\n should.exist(response);\n should(err.message).match(/BadNoSubscription/);\n }", "label_name": "CWE-400", "label": 2} {"code": " function register_some_node(callback) {\n\n session.registerNodes(nodesToRegister, function (err, _registeredNodeIds) {\n if (err) {\n return callback(err);\n }\n registeredNodeIds = _registeredNodeIds;\n callback();\n });\n },", "label_name": "CWE-400", "label": 2} {"code": "split_der(asn1buf *buf, uint8_t *const *der, size_t len, taginfo *tag_out)\n{\n krb5_error_code ret;\n const uint8_t *contents, *remainder;\n size_t clen, rlen;\n\n ret = get_tag(*der, len, tag_out, &contents, &clen, &remainder, &rlen);\n if (ret)\n return ret;\n if (rlen != 0)\n return ASN1_BAD_LENGTH;\n insert_bytes(buf, contents, clen);\n return 0;\n}", "label_name": "CWE-674", "label": 28} {"code": "static void rose_loopback_timer(unsigned long param)\n{\n\tstruct sk_buff *skb;\n\tstruct net_device *dev;\n\trose_address *dest;\n\tstruct sock *sk;\n\tunsigned short frametype;\n\tunsigned int lci_i, lci_o;\n\n\twhile ((skb = skb_dequeue(&loopback_queue)) != NULL) {\n\t\tlci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);\n\t\tframetype = skb->data[2];\n\t\tdest = (rose_address *)(skb->data + 4);\n\t\tlci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i;\n\n\t\tskb_reset_transport_header(skb);\n\n\t\tsk = rose_find_socket(lci_o, rose_loopback_neigh);\n\t\tif (sk) {\n\t\t\tif (rose_process_rx_frame(sk, skb) == 0)\n\t\t\t\tkfree_skb(skb);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (frametype == ROSE_CALL_REQUEST) {\n\t\t\tif ((dev = rose_dev_get(dest)) != NULL) {\n\t\t\t\tif (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)\n\t\t\t\t\tkfree_skb(skb);\n\t\t\t} else {\n\t\t\t\tkfree_skb(skb);\n\t\t\t}\n\t\t} else {\n\t\t\tkfree_skb(skb);\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": 0} {"code": "struct sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb,\n\t\t\t\t struct request_sock *req,\n\t\t\t\t struct dst_entry *dst)\n{\n\tstruct inet_request_sock *ireq;\n\tstruct inet_sock *newinet;\n\tstruct sock *newsk;\n\n\tif (sk_acceptq_is_full(sk))\n\t\tgoto exit_overflow;\n\n\tif (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)\n\t\tgoto exit;\n\n\tnewsk = dccp_create_openreq_child(sk, req, skb);\n\tif (newsk == NULL)\n\t\tgoto exit_nonewsk;\n\n\tsk_setup_caps(newsk, dst);\n\n\tnewinet\t\t = inet_sk(newsk);\n\tireq\t\t = inet_rsk(req);\n\tnewinet->inet_daddr\t= ireq->rmt_addr;\n\tnewinet->inet_rcv_saddr = ireq->loc_addr;\n\tnewinet->inet_saddr\t= ireq->loc_addr;\n\tnewinet->opt\t = ireq->opt;\n\tireq->opt\t = NULL;\n\tnewinet->mc_index = inet_iif(skb);\n\tnewinet->mc_ttl\t = ip_hdr(skb)->ttl;\n\tnewinet->inet_id = jiffies;\n\n\tdccp_sync_mss(newsk, dst_mtu(dst));\n\n\tif (__inet_inherit_port(sk, newsk) < 0) {\n\t\tsock_put(newsk);\n\t\tgoto exit;\n\t}\n\t__inet_hash_nolisten(newsk, NULL);\n\n\treturn newsk;\n\nexit_overflow:\n\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);\nexit_nonewsk:\n\tdst_release(dst);\nexit:\n\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);\n\treturn NULL;\n}", "label_name": "CWE-362", "label": 18} {"code": "struct dst_entry *inet_csk_route_req(struct sock *sk,\n\t\t\t\t const struct request_sock *req)\n{\n\tstruct rtable *rt;\n\tconst struct inet_request_sock *ireq = inet_rsk(req);\n\tstruct ip_options *opt = inet_rsk(req)->opt;\n\tstruct net *net = sock_net(sk);\n\tstruct flowi4 fl4;\n\n\tflowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark,\n\t\t\t RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,\n\t\t\t sk->sk_protocol, inet_sk_flowi_flags(sk),\n\t\t\t (opt && opt->srr) ? opt->faddr : ireq->rmt_addr,\n\t\t\t ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport);\n\tsecurity_req_classify_flow(req, flowi4_to_flowi(&fl4));\n\trt = ip_route_output_flow(net, &fl4, sk);\n\tif (IS_ERR(rt))\n\t\tgoto no_route;\n\tif (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway)\n\t\tgoto route_err;\n\treturn &rt->dst;\n\nroute_err:\n\tip_rt_put(rt);\nno_route:\n\tIP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);\n\treturn NULL;\n}", "label_name": "CWE-362", "label": 18} {"code": "static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,\n\t\t\t struct ipcm_cookie *ipc, struct rtable **rtp)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ip_options *opt;\n\tstruct rtable *rt;\n\n\t/*\n\t * setup for corking.\n\t */\n\topt = ipc->opt;\n\tif (opt) {\n\t\tif (cork->opt == NULL) {\n\t\t\tcork->opt = kmalloc(sizeof(struct ip_options) + 40,\n\t\t\t\t\t sk->sk_allocation);\n\t\t\tif (unlikely(cork->opt == NULL))\n\t\t\t\treturn -ENOBUFS;\n\t\t}\n\t\tmemcpy(cork->opt, opt, sizeof(struct ip_options) + opt->optlen);\n\t\tcork->flags |= IPCORK_OPT;\n\t\tcork->addr = ipc->addr;\n\t}\n\trt = *rtp;\n\tif (unlikely(!rt))\n\t\treturn -EFAULT;\n\t/*\n\t * We steal reference to this route, caller should not release it\n\t */\n\t*rtp = NULL;\n\tcork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ?\n\t\t\t rt->dst.dev->mtu : dst_mtu(rt->dst.path);\n\tcork->dst = &rt->dst;\n\tcork->length = 0;\n\tcork->tx_flags = ipc->tx_flags;\n\tcork->page = NULL;\n\tcork->off = 0;\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": 18} {"code": "static int apparmor_setprocattr(struct task_struct *task, char *name,\n\t\t\t\tvoid *value, size_t size)\n{\n\tchar *command, *args = value;\n\tsize_t arg_size;\n\tint error;\n\n\tif (size == 0)\n\t\treturn -EINVAL;\n\t/* args points to a PAGE_SIZE buffer, AppArmor requires that\n\t * the buffer must be null terminated or have size <= PAGE_SIZE -1\n\t * so that AppArmor can null terminate them\n\t */\n\tif (args[size - 1] != '\\0') {\n\t\tif (size == PAGE_SIZE)\n\t\t\treturn -EINVAL;\n\t\targs[size] = '\\0';\n\t}\n\n\t/* task can only write its own attributes */\n\tif (current != task)\n\t\treturn -EACCES;\n\n\targs = value;\n\targs = strim(args);\n\tcommand = strsep(&args, \" \");\n\tif (!args)\n\t\treturn -EINVAL;\n\targs = skip_spaces(args);\n\tif (!*args)\n\t\treturn -EINVAL;\n\n\targ_size = size - (args - (char *) value);\n\tif (strcmp(name, \"current\") == 0) {\n\t\tif (strcmp(command, \"changehat\") == 0) {\n\t\t\terror = aa_setprocattr_changehat(args, arg_size,\n\t\t\t\t\t\t\t !AA_DO_TEST);\n\t\t} else if (strcmp(command, \"permhat\") == 0) {\n\t\t\terror = aa_setprocattr_changehat(args, arg_size,\n\t\t\t\t\t\t\t AA_DO_TEST);\n\t\t} else if (strcmp(command, \"changeprofile\") == 0) {\n\t\t\terror = aa_setprocattr_changeprofile(args, !AA_ONEXEC,\n\t\t\t\t\t\t\t !AA_DO_TEST);\n\t\t} else if (strcmp(command, \"permprofile\") == 0) {\n\t\t\terror = aa_setprocattr_changeprofile(args, !AA_ONEXEC,\n\t\t\t\t\t\t\t AA_DO_TEST);\n\t\t} else if (strcmp(command, \"permipc\") == 0) {\n\t\t\terror = aa_setprocattr_permipc(args);\n\t\t} else {\n\t\t\tstruct common_audit_data sa;\n\t\t\tCOMMON_AUDIT_DATA_INIT(&sa, NONE);\n\t\t\tsa.aad.op = OP_SETPROCATTR;\n\t\t\tsa.aad.info = name;\n\t\t\tsa.aad.error = -EINVAL;\n\t\t\treturn aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL,\n\t\t\t\t\t&sa, NULL);\n\t\t}\n\t} else if (strcmp(name, \"exec\") == 0) {\n\t\terror = aa_setprocattr_changeprofile(args, AA_ONEXEC,\n\t\t\t\t\t\t !AA_DO_TEST);\n\t} else {\n\t\t/* only support the \"current\" and \"exec\" process attributes */\n\t\treturn -EINVAL;\n\t}\n\tif (!error)\n\t\terror = size;\n\treturn error;\n}", "label_name": "CWE-20", "label": 0} {"code": "xscale1pmu_handle_irq(int irq_num, void *dev)\n{\n\tunsigned long pmnc;\n\tstruct perf_sample_data data;\n\tstruct cpu_hw_events *cpuc;\n\tstruct pt_regs *regs;\n\tint idx;\n\n\t/*\n\t * NOTE: there's an A stepping erratum that states if an overflow\n\t * bit already exists and another occurs, the previous\n\t * Overflow bit gets cleared. There's no workaround.\n\t *\t Fixed in B stepping or later.\n\t */\n\tpmnc = xscale1pmu_read_pmnc();\n\n\t/*\n\t * Write the value back to clear the overflow flags. Overflow\n\t * flags remain in pmnc for use below. We also disable the PMU\n\t * while we process the interrupt.\n\t */\n\txscale1pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE);\n\n\tif (!(pmnc & XSCALE1_OVERFLOWED_MASK))\n\t\treturn IRQ_NONE;\n\n\tregs = get_irq_regs();\n\n\tperf_sample_data_init(&data, 0);\n\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\tfor (idx = 0; idx <= armpmu->num_events; ++idx) {\n\t\tstruct perf_event *event = cpuc->events[idx];\n\t\tstruct hw_perf_event *hwc;\n\n\t\tif (!test_bit(idx, cpuc->active_mask))\n\t\t\tcontinue;\n\n\t\tif (!xscale1_pmnc_counter_has_overflowed(pmnc, idx))\n\t\t\tcontinue;\n\n\t\thwc = &event->hw;\n\t\tarmpmu_event_update(event, hwc, idx, 1);\n\t\tdata.period = event->hw.last_period;\n\t\tif (!armpmu_event_set_period(event, hwc, idx))\n\t\t\tcontinue;\n\n\t\tif (perf_event_overflow(event, 0, &data, regs))\n\t\t\tarmpmu->disable(hwc, idx);\n\t}\n\n\tirq_work_run();\n\n\t/*\n\t * Re-enable the PMU.\n\t */\n\tpmnc = xscale1pmu_read_pmnc() | XSCALE_PMU_ENABLE;\n\txscale1pmu_write_pmnc(pmnc);\n\n\treturn IRQ_HANDLED;\n}", "label_name": "CWE-400", "label": 2} {"code": "static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode)\n{\n\tstruct thread_info *ti = task_thread_info(current);\n\n\tif ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) {\n\t\tint rd = (opcode & RD) >> 11;\n\t\tint rt = (opcode & RT) >> 16;\n\t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n\t\t\t\t1, 0, regs, 0);\n\t\tswitch (rd) {\n\t\tcase 0:\t\t/* CPU number */\n\t\t\tregs->regs[rt] = smp_processor_id();\n\t\t\treturn 0;\n\t\tcase 1:\t\t/* SYNCI length */\n\t\t\tregs->regs[rt] = min(current_cpu_data.dcache.linesz,\n\t\t\t\t\t current_cpu_data.icache.linesz);\n\t\t\treturn 0;\n\t\tcase 2:\t\t/* Read count register */\n\t\t\tregs->regs[rt] = read_c0_count();\n\t\t\treturn 0;\n\t\tcase 3:\t\t/* Count register resolution */\n\t\t\tswitch (current_cpu_data.cputype) {\n\t\t\tcase CPU_20KC:\n\t\t\tcase CPU_25KF:\n\t\t\t\tregs->regs[rt] = 1;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tregs->regs[rt] = 2;\n\t\t\t}\n\t\t\treturn 0;\n\t\tcase 29:\n\t\t\tregs->regs[rt] = ti->tp_value;\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Not ours. */\n\treturn -1;\n}", "label_name": "CWE-400", "label": 2} {"code": "static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)\n{\n\tenum hrtimer_restart ret = HRTIMER_RESTART;\n\tstruct perf_sample_data data;\n\tstruct pt_regs *regs;\n\tstruct perf_event *event;\n\tu64 period;\n\n\tevent = container_of(hrtimer, struct perf_event, hw.hrtimer);\n\n\tif (event->state != PERF_EVENT_STATE_ACTIVE)\n\t\treturn HRTIMER_NORESTART;\n\n\tevent->pmu->read(event);\n\n\tperf_sample_data_init(&data, 0);\n\tdata.period = event->hw.last_period;\n\tregs = get_irq_regs();\n\n\tif (regs && !perf_exclude_event(event, regs)) {\n\t\tif (!(event->attr.exclude_idle && current->pid == 0))\n\t\t\tif (perf_event_overflow(event, 0, &data, regs))\n\t\t\t\tret = HRTIMER_NORESTART;\n\t}\n\n\tperiod = max_t(u64, 10000, event->hw.sample_period);\n\thrtimer_forward_now(hrtimer, ns_to_ktime(period));\n\n\treturn ret;\n}", "label_name": "CWE-400", "label": 2} {"code": "static void perf_swevent_event(struct perf_event *event, u64 nr,\n\t\t\t int nmi, struct perf_sample_data *data,\n\t\t\t struct pt_regs *regs)\n{\n\tstruct hw_perf_event *hwc = &event->hw;\n\n\tlocal64_add(nr, &event->count);\n\n\tif (!regs)\n\t\treturn;\n\n\tif (!is_sampling_event(event))\n\t\treturn;\n\n\tif (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)\n\t\treturn perf_swevent_overflow(event, 1, nmi, data, regs);\n\n\tif (local64_add_negative(nr, &hwc->period_left))\n\t\treturn;\n\n\tperf_swevent_overflow(event, 0, nmi, data, regs);\n}", "label_name": "CWE-400", "label": 2} {"code": "static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,\n\t\t\t int mode)\n{\n\tstruct gfs2_inode *ip = GFS2_I(inode);\n\tstruct buffer_head *dibh;\n\tint error;\n\tu64 start = offset >> PAGE_CACHE_SHIFT;\n\tunsigned int start_offset = offset & ~PAGE_CACHE_MASK;\n\tu64 end = (offset + len - 1) >> PAGE_CACHE_SHIFT;\n\tpgoff_t curr;\n\tstruct page *page;\n\tunsigned int end_offset = (offset + len) & ~PAGE_CACHE_MASK;\n\tunsigned int from, to;\n\n\tif (!end_offset)\n\t\tend_offset = PAGE_CACHE_SIZE;\n\n\terror = gfs2_meta_inode_buffer(ip, &dibh);\n\tif (unlikely(error))\n\t\tgoto out;\n\n\tgfs2_trans_add_bh(ip->i_gl, dibh, 1);\n\n\tif (gfs2_is_stuffed(ip)) {\n\t\terror = gfs2_unstuff_dinode(ip, NULL);\n\t\tif (unlikely(error))\n\t\t\tgoto out;\n\t}\n\n\tcurr = start;\n\toffset = start << PAGE_CACHE_SHIFT;\n\tfrom = start_offset;\n\tto = PAGE_CACHE_SIZE;\n\twhile (curr <= end) {\n\t\tpage = grab_cache_page_write_begin(inode->i_mapping, curr,\n\t\t\t\t\t\t AOP_FLAG_NOFS);\n\t\tif (unlikely(!page)) {\n\t\t\terror = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\n\t\tif (curr == end)\n\t\t\tto = end_offset;\n\t\terror = write_empty_blocks(page, from, to, mode);\n\t\tif (!error && offset + to > inode->i_size &&\n\t\t !(mode & FALLOC_FL_KEEP_SIZE)) {\n\t\t\ti_size_write(inode, offset + to);\n\t\t}\n\t\tunlock_page(page);\n\t\tpage_cache_release(page);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tcurr++;\n\t\toffset += PAGE_CACHE_SIZE;\n\t\tfrom = 0;\n\t}\n\n\tmark_inode_dirty(inode);\n\n\tbrelse(dibh);\n\nout:\n\treturn error;\n}", "label_name": "CWE-119", "label": 26} {"code": "xlate_to_uni(const unsigned char *name, int len, unsigned char *outname,\n\t int *longlen, int *outlen, int escape, int utf8,\n\t struct nls_table *nls)\n{\n\tconst unsigned char *ip;\n\tunsigned char nc;\n\tunsigned char *op;\n\tunsigned int ec;\n\tint i, k, fill;\n\tint charlen;\n\n\tif (utf8) {\n\t\t*outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname);\n\t\tif (*outlen < 0)\n\t\t\treturn *outlen;\n\t\telse if (*outlen > FAT_LFN_LEN)\n\t\t\treturn -ENAMETOOLONG;\n\n\t\top = &outname[*outlen * sizeof(wchar_t)];\n\t} else {\n\t\tif (nls) {\n\t\t\tfor (i = 0, ip = name, op = outname, *outlen = 0;\n\t\t\t i < len && *outlen <= FAT_LFN_LEN;\n\t\t\t *outlen += 1)\n\t\t\t{\n\t\t\t\tif (escape && (*ip == ':')) {\n\t\t\t\t\tif (i > len - 5)\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\tec = 0;\n\t\t\t\t\tfor (k = 1; k < 5; k++) {\n\t\t\t\t\t\tnc = ip[k];\n\t\t\t\t\t\tec <<= 4;\n\t\t\t\t\t\tif (nc >= '0' && nc <= '9') {\n\t\t\t\t\t\t\tec |= nc - '0';\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nc >= 'a' && nc <= 'f') {\n\t\t\t\t\t\t\tec |= nc - ('a' - 10);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nc >= 'A' && nc <= 'F') {\n\t\t\t\t\t\t\tec |= nc - ('A' - 10);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\t}\n\t\t\t\t\t*op++ = ec & 0xFF;\n\t\t\t\t\t*op++ = ec >> 8;\n\t\t\t\t\tip += 5;\n\t\t\t\t\ti += 5;\n\t\t\t\t} else {\n\t\t\t\t\tif ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0)\n\t\t\t\t\t\treturn -EINVAL;\n\t\t\t\t\tip += charlen;\n\t\t\t\t\ti += charlen;\n\t\t\t\t\top += 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i < len)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t} else {\n\t\t\tfor (i = 0, ip = name, op = outname, *outlen = 0;\n\t\t\t i < len && *outlen <= FAT_LFN_LEN;\n\t\t\t i++, *outlen += 1)\n\t\t\t{\n\t\t\t\t*op++ = *ip++;\n\t\t\t\t*op++ = 0;\n\t\t\t}\n\t\t\tif (i < len)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t}\n\t}\n\n\t*longlen = *outlen;\n\tif (*outlen % 13) {\n\t\t*op++ = 0;\n\t\t*op++ = 0;\n\t\t*outlen += 1;\n\t\tif (*outlen % 13) {\n\t\t\tfill = 13 - (*outlen % 13);\n\t\t\tfor (i = 0; i < fill; i++) {\n\t\t\t\t*op++ = 0xff;\n\t\t\t\t*op++ = 0xff;\n\t\t\t}\n\t\t\t*outlen += fill;\n\t\t}\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26} {"code": "void pid_ns_release_proc(struct pid_namespace *ns)\n{\n\tmntput(ns->proc_mnt);\n}", "label_name": "CWE-119", "label": 26} {"code": "static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,\n\t\t\tstruct nci_rf_intf_activated_ntf *ntf, __u8 *data)\n{\n\tstruct activation_params_nfca_poll_iso_dep *nfca_poll;\n\tstruct activation_params_nfcb_poll_iso_dep *nfcb_poll;\n\n\tswitch (ntf->activation_rf_tech_and_mode) {\n\tcase NCI_NFC_A_PASSIVE_POLL_MODE:\n\t\tnfca_poll = &ntf->activation_params.nfca_poll_iso_dep;\n\t\tnfca_poll->rats_res_len = *data++;\n\t\tpr_debug(\"rats_res_len %d\\n\", nfca_poll->rats_res_len);\n\t\tif (nfca_poll->rats_res_len > 0) {\n\t\t\tmemcpy(nfca_poll->rats_res,\n\t\t\t data, nfca_poll->rats_res_len);\n\t\t}\n\t\tbreak;\n\n\tcase NCI_NFC_B_PASSIVE_POLL_MODE:\n\t\tnfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;\n\t\tnfcb_poll->attrib_res_len = *data++;\n\t\tpr_debug(\"attrib_res_len %d\\n\", nfcb_poll->attrib_res_len);\n\t\tif (nfcb_poll->attrib_res_len > 0) {\n\t\t\tmemcpy(nfcb_poll->attrib_res,\n\t\t\t data, nfcb_poll->attrib_res_len);\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tpr_err(\"unsupported activation_rf_tech_and_mode 0x%x\\n\",\n\t\t ntf->activation_rf_tech_and_mode);\n\t\treturn NCI_STATUS_RF_PROTOCOL_ERROR;\n\t}\n\n\treturn NCI_STATUS_OK;\n}", "label_name": "CWE-119", "label": 26} {"code": "static int load_script(struct linux_binprm *bprm)\n{\n\tconst char *i_arg, *i_name;\n\tchar *cp;\n\tstruct file *file;\n\tchar interp[BINPRM_BUF_SIZE];\n\tint retval;\n\n\tif ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))\n\t\treturn -ENOEXEC;\n\t/*\n\t * This section does the #! interpretation.\n\t * Sorta complicated, but hopefully it will work. -TYT\n\t */\n\n\tallow_write_access(bprm->file);\n\tfput(bprm->file);\n\tbprm->file = NULL;\n\n\tbprm->buf[BINPRM_BUF_SIZE - 1] = '\\0';\n\tif ((cp = strchr(bprm->buf, '\\n')) == NULL)\n\t\tcp = bprm->buf+BINPRM_BUF_SIZE-1;\n\t*cp = '\\0';\n\twhile (cp > bprm->buf) {\n\t\tcp--;\n\t\tif ((*cp == ' ') || (*cp == '\\t'))\n\t\t\t*cp = '\\0';\n\t\telse\n\t\t\tbreak;\n\t}\n\tfor (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\\t'); cp++);\n\tif (*cp == '\\0') \n\t\treturn -ENOEXEC; /* No interpreter name found */\n\ti_name = cp;\n\ti_arg = NULL;\n\tfor ( ; *cp && (*cp != ' ') && (*cp != '\\t'); cp++)\n\t\t/* nothing */ ;\n\twhile ((*cp == ' ') || (*cp == '\\t'))\n\t\t*cp++ = '\\0';\n\tif (*cp)\n\t\ti_arg = cp;\n\tstrcpy (interp, i_name);\n\t/*\n\t * OK, we've parsed out the interpreter name and\n\t * (optional) argument.\n\t * Splice in (1) the interpreter's name for argv[0]\n\t * (2) (optional) argument to interpreter\n\t * (3) filename of shell script (replace argv[0])\n\t *\n\t * This is done in reverse order, because of how the\n\t * user environment and arguments are stored.\n\t */\n\tretval = remove_arg_zero(bprm);\n\tif (retval)\n\t\treturn retval;\n\tretval = copy_strings_kernel(1, &bprm->interp, bprm);\n\tif (retval < 0) return retval; \n\tbprm->argc++;\n\tif (i_arg) {\n\t\tretval = copy_strings_kernel(1, &i_arg, bprm);\n\t\tif (retval < 0) return retval; \n\t\tbprm->argc++;\n\t}\n\tretval = copy_strings_kernel(1, &i_name, bprm);\n\tif (retval) return retval; \n\tbprm->argc++;\n\tbprm->interp = interp;\n\n\t/*\n\t * OK, now restart the process with the interpreter's dentry.\n\t */\n\tfile = open_exec(interp);\n\tif (IS_ERR(file))\n\t\treturn PTR_ERR(file);\n\n\tbprm->file = file;\n\tretval = prepare_binprm(bprm);\n\tif (retval < 0)\n\t\treturn retval;\n\treturn search_binary_handler(bprm);\n}", "label_name": "CWE-200", "label": 10} {"code": "void xenvif_disconnect(struct xenvif *vif)\n{\n\tstruct net_device *dev = vif->dev;\n\tif (netif_carrier_ok(dev)) {\n\t\trtnl_lock();\n\t\tnetif_carrier_off(dev); /* discard queued packets */\n\t\tif (netif_running(dev))\n\t\t\txenvif_down(vif);\n\t\trtnl_unlock();\n\t\txenvif_put(vif);\n\t}\n\n\tatomic_dec(&vif->refcnt);\n\twait_event(vif->waiting_to_free, atomic_read(&vif->refcnt) == 0);\n\n\tdel_timer_sync(&vif->credit_timeout);\n\n\tif (vif->irq)\n\t\tunbind_from_irqhandler(vif->irq, vif);\n\n\tunregister_netdev(vif->dev);\n\n\txen_netbk_unmap_frontend_rings(vif);\n\n\tfree_netdev(vif->dev);\n}", "label_name": "CWE-20", "label": 0} {"code": "static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb)\n{\n\tstruct block_device *bdev;\n\tchar b[BDEVNAME_SIZE];\n\n\tbdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);\n\tif (IS_ERR(bdev))\n\t\tgoto fail;\n\treturn bdev;\n\nfail:\n\text3_msg(sb, \"error: failed to open journal device %s: %ld\",\n\t\t__bdevname(dev, b), PTR_ERR(bdev));\n\n\treturn NULL;\n}", "label_name": "CWE-20", "label": 0} {"code": "static long snd_timer_user_ioctl(struct file *file, unsigned int cmd,\n\t\t\t\t unsigned long arg)\n{\n\tstruct snd_timer_user *tu;\n\tvoid __user *argp = (void __user *)arg;\n\tint __user *p = argp;\n\n\ttu = file->private_data;\n\tswitch (cmd) {\n\tcase SNDRV_TIMER_IOCTL_PVERSION:\n\t\treturn put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0;\n\tcase SNDRV_TIMER_IOCTL_NEXT_DEVICE:\n\t\treturn snd_timer_user_next_device(argp);\n\tcase SNDRV_TIMER_IOCTL_TREAD:\n\t{\n\t\tint xarg;\n\n\t\tmutex_lock(&tu->tread_sem);\n\t\tif (tu->timeri)\t{\t/* too late */\n\t\t\tmutex_unlock(&tu->tread_sem);\n\t\t\treturn -EBUSY;\n\t\t}\n\t\tif (get_user(xarg, p)) {\n\t\t\tmutex_unlock(&tu->tread_sem);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\ttu->tread = xarg ? 1 : 0;\n\t\tmutex_unlock(&tu->tread_sem);\n\t\treturn 0;\n\t}\n\tcase SNDRV_TIMER_IOCTL_GINFO:\n\t\treturn snd_timer_user_ginfo(file, argp);\n\tcase SNDRV_TIMER_IOCTL_GPARAMS:\n\t\treturn snd_timer_user_gparams(file, argp);\n\tcase SNDRV_TIMER_IOCTL_GSTATUS:\n\t\treturn snd_timer_user_gstatus(file, argp);\n\tcase SNDRV_TIMER_IOCTL_SELECT:\n\t\treturn snd_timer_user_tselect(file, argp);\n\tcase SNDRV_TIMER_IOCTL_INFO:\n\t\treturn snd_timer_user_info(file, argp);\n\tcase SNDRV_TIMER_IOCTL_PARAMS:\n\t\treturn snd_timer_user_params(file, argp);\n\tcase SNDRV_TIMER_IOCTL_STATUS:\n\t\treturn snd_timer_user_status(file, argp);\n\tcase SNDRV_TIMER_IOCTL_START:\n\tcase SNDRV_TIMER_IOCTL_START_OLD:\n\t\treturn snd_timer_user_start(file);\n\tcase SNDRV_TIMER_IOCTL_STOP:\n\tcase SNDRV_TIMER_IOCTL_STOP_OLD:\n\t\treturn snd_timer_user_stop(file);\n\tcase SNDRV_TIMER_IOCTL_CONTINUE:\n\tcase SNDRV_TIMER_IOCTL_CONTINUE_OLD:\n\t\treturn snd_timer_user_continue(file);\n\tcase SNDRV_TIMER_IOCTL_PAUSE:\n\tcase SNDRV_TIMER_IOCTL_PAUSE_OLD:\n\t\treturn snd_timer_user_pause(file);\n\t}\n\treturn -ENOTTY;\n}", "label_name": "CWE-362", "label": 18} {"code": "struct sk_buff **udp_gro_receive(struct sk_buff **head, struct sk_buff *skb,\n\t\t\t\t struct udphdr *uh)\n{\n\tstruct udp_offload_priv *uo_priv;\n\tstruct sk_buff *p, **pp = NULL;\n\tstruct udphdr *uh2;\n\tunsigned int off = skb_gro_offset(skb);\n\tint flush = 1;\n\n\tif (NAPI_GRO_CB(skb)->udp_mark ||\n\t (skb->ip_summed != CHECKSUM_PARTIAL &&\n\t NAPI_GRO_CB(skb)->csum_cnt == 0 &&\n\t !NAPI_GRO_CB(skb)->csum_valid))\n\t\tgoto out;\n\n\t/* mark that this skb passed once through the udp gro layer */\n\tNAPI_GRO_CB(skb)->udp_mark = 1;\n\n\trcu_read_lock();\n\tuo_priv = rcu_dereference(udp_offload_base);\n\tfor (; uo_priv != NULL; uo_priv = rcu_dereference(uo_priv->next)) {\n\t\tif (net_eq(read_pnet(&uo_priv->net), dev_net(skb->dev)) &&\n\t\t uo_priv->offload->port == uh->dest &&\n\t\t uo_priv->offload->callbacks.gro_receive)\n\t\t\tgoto unflush;\n\t}\n\tgoto out_unlock;\n\nunflush:\n\tflush = 0;\n\n\tfor (p = *head; p; p = p->next) {\n\t\tif (!NAPI_GRO_CB(p)->same_flow)\n\t\t\tcontinue;\n\n\t\tuh2 = (struct udphdr *)(p->data + off);\n\n\t\t/* Match ports and either checksums are either both zero\n\t\t * or nonzero.\n\t\t */\n\t\tif ((*(u32 *)&uh->source != *(u32 *)&uh2->source) ||\n\t\t (!uh->check ^ !uh2->check)) {\n\t\t\tNAPI_GRO_CB(p)->same_flow = 0;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tskb_gro_pull(skb, sizeof(struct udphdr)); /* pull encapsulating udp header */\n\tskb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr));\n\tNAPI_GRO_CB(skb)->proto = uo_priv->offload->ipproto;\n\tpp = uo_priv->offload->callbacks.gro_receive(head, skb,\n\t\t\t\t\t\t uo_priv->offload);\n\nout_unlock:\n\trcu_read_unlock();\nout:\n\tNAPI_GRO_CB(skb)->flush |= flush;\n\treturn pp;\n}", "label_name": "CWE-400", "label": 2} {"code": "static inline int check_entry_size_and_hooks(struct arpt_entry *e,\n\t\t\t\t\t struct xt_table_info *newinfo,\n\t\t\t\t\t const unsigned char *base,\n\t\t\t\t\t const unsigned char *limit,\n\t\t\t\t\t const unsigned int *hook_entries,\n\t\t\t\t\t const unsigned int *underflows,\n\t\t\t\t\t unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct arpt_entry) >= limit ||\n\t (unsigned char *)e + e->next_offset > limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_entry(e);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_ARP_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_err(\"Underflows must be unconditional and \"\n\t\t\t\t \"use the STANDARD target with \"\n\t\t\t\t \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26} {"code": "static bool check_underflow(const struct arpt_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->arp))\n\t\treturn false;\n\tt = arpt_get_target_c(e);\n\tif (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)\n\t\treturn false;\n\tverdict = ((struct xt_standard_target *)t)->verdict;\n\tverdict = -verdict - 1;\n\treturn verdict == NF_DROP || verdict == NF_ACCEPT;\n}", "label_name": "CWE-119", "label": 26} {"code": "static bool check_underflow(const struct ipt_entry *e)\n{\n\tconst struct xt_entry_target *t;\n\tunsigned int verdict;\n\n\tif (!unconditional(&e->ip))\n\t\treturn false;\n\tt = ipt_get_target_c(e);\n\tif (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)\n\t\treturn false;\n\tverdict = ((struct xt_standard_target *)t)->verdict;\n\tverdict = -verdict - 1;\n\treturn verdict == NF_DROP || verdict == NF_ACCEPT;\n}", "label_name": "CWE-119", "label": 26} {"code": "get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,\n\t\t const char *hookname, const char **chainname,\n\t\t const char **comment, unsigned int *rulenum)\n{\n\tconst struct xt_standard_target *t = (void *)ipt_get_target_c(s);\n\n\tif (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {\n\t\t/* Head of user chain: ERROR target with chainname */\n\t\t*chainname = t->target.data;\n\t\t(*rulenum) = 0;\n\t} else if (s == e) {\n\t\t(*rulenum)++;\n\n\t\tif (s->target_offset == sizeof(struct ipt_entry) &&\n\t\t strcmp(t->target.u.kernel.target->name,\n\t\t\t XT_STANDARD_TARGET) == 0 &&\n\t\t t->verdict < 0 &&\n\t\t unconditional(&s->ip)) {\n\t\t\t/* Tail of chains: STANDARD target (return/policy) */\n\t\t\t*comment = *chainname == hookname\n\t\t\t\t? comments[NF_IP_TRACE_COMMENT_POLICY]\n\t\t\t\t: comments[NF_IP_TRACE_COMMENT_RETURN];\n\t\t}\n\t\treturn 1;\n\t} else\n\t\t(*rulenum)++;\n\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26} {"code": "static int sclp_ctl_ioctl_sccb(void __user *user_area)\n{\n\tstruct sclp_ctl_sccb ctl_sccb;\n\tstruct sccb_header *sccb;\n\tint rc;\n\n\tif (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb)))\n\t\treturn -EFAULT;\n\tif (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw))\n\t\treturn -EOPNOTSUPP;\n\tsccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);\n\tif (!sccb)\n\t\treturn -ENOMEM;\n\tif (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) {\n\t\trc = -EFAULT;\n\t\tgoto out_free;\n\t}\n\tif (sccb->length > PAGE_SIZE || sccb->length < 8)\n\t\treturn -EINVAL;\n\tif (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) {\n\t\trc = -EFAULT;\n\t\tgoto out_free;\n\t}\n\trc = sclp_sync_request(ctl_sccb.cmdw, sccb);\n\tif (rc)\n\t\tgoto out_free;\n\tif (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length))\n\t\trc = -EFAULT;\nout_free:\n\tfree_page((unsigned long) sccb);\n\treturn rc;\n}", "label_name": "CWE-362", "label": 18} {"code": "static int __btrfs_set_acl(struct btrfs_trans_handle *trans,\n\t\t\t struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint ret, size = 0;\n\tconst char *name;\n\tchar *value = NULL;\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, &inode->i_mode);\n\t\t\tif (ret < 0)\n\t\t\t\treturn ret;\n\t\t\tif (ret == 0)\n\t\t\t\tacl = NULL;\n\t\t}\n\t\tret = 0;\n\t\tbreak;\n\tcase ACL_TYPE_DEFAULT:\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EINVAL : 0;\n\t\tname = XATTR_NAME_POSIX_ACL_DEFAULT;\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\n\tif (acl) {\n\t\tsize = posix_acl_xattr_size(acl->a_count);\n\t\tvalue = kmalloc(size, GFP_KERNEL);\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;\n\t}\n\n\tret = __btrfs_setxattr(trans, inode, name, value, size, 0);\nout:\n\tkfree(value);\n\n\tif (!ret)\n\t\tset_cached_acl(inode, type, acl);\n\n\treturn ret;\n}", "label_name": "CWE-285", "label": 23} {"code": "__ext4_set_acl(handle_t *handle, struct inode *inode, int type,\n\t struct posix_acl *acl)\n{\n\tint name_index;\n\tvoid *value = NULL;\n\tsize_t size = 0;\n\tint error;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\tname_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\terror = posix_acl_equiv_mode(acl, &inode->i_mode);\n\t\t\tif (error < 0)\n\t\t\t\treturn error;\n\t\t\telse {\n\t\t\t\tinode->i_ctime = ext4_current_time(inode);\n\t\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\t\tif (error == 0)\n\t\t\t\t\tacl = NULL;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ACL_TYPE_DEFAULT:\n\t\tname_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EACCES : 0;\n\t\tbreak;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\tif (acl) {\n\t\tvalue = ext4_acl_to_disk(acl, &size);\n\t\tif (IS_ERR(value))\n\t\t\treturn (int)PTR_ERR(value);\n\t}\n\n\terror = ext4_xattr_set_handle(handle, inode, name_index, \"\",\n\t\t\t\t value, size, 0);\n\n\tkfree(value);\n\tif (!error)\n\t\tset_cached_acl(inode, type, acl);\n\n\treturn error;\n}", "label_name": "CWE-285", "label": 23} {"code": "int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n{\n\tint rc, xprefix;\n\n\tswitch (type) {\n\tcase ACL_TYPE_ACCESS:\n\t\txprefix = JFFS2_XPREFIX_ACL_ACCESS;\n\t\tif (acl) {\n\t\t\tumode_t mode = inode->i_mode;\n\t\t\trc = posix_acl_equiv_mode(acl, &mode);\n\t\t\tif (rc < 0)\n\t\t\t\treturn rc;\n\t\t\tif (inode->i_mode != mode) {\n\t\t\t\tstruct iattr attr;\n\n\t\t\t\tattr.ia_valid = ATTR_MODE | ATTR_CTIME;\n\t\t\t\tattr.ia_mode = mode;\n\t\t\t\tattr.ia_ctime = CURRENT_TIME_SEC;\n\t\t\t\trc = jffs2_do_setattr(inode, &attr);\n\t\t\t\tif (rc < 0)\n\t\t\t\t\treturn rc;\n\t\t\t}\n\t\t\tif (rc == 0)\n\t\t\t\tacl = NULL;\n\t\t}\n\t\tbreak;\n\tcase ACL_TYPE_DEFAULT:\n\t\txprefix = JFFS2_XPREFIX_ACL_DEFAULT;\n\t\tif (!S_ISDIR(inode->i_mode))\n\t\t\treturn acl ? -EACCES : 0;\n\t\tbreak;\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n\trc = __jffs2_set_acl(inode, xprefix, acl);\n\tif (!rc)\n\t\tset_cached_acl(inode, type, acl);\n\treturn rc;\n}", "label_name": "CWE-285", "label": 23} {"code": "static int proc_sys_readdir(struct file *file, struct dir_context *ctx)\n{\n\tstruct ctl_table_header *head = grab_header(file_inode(file));\n\tstruct ctl_table_header *h = NULL;\n\tstruct ctl_table *entry;\n\tstruct ctl_dir *ctl_dir;\n\tunsigned long pos;\n\n\tif (IS_ERR(head))\n\t\treturn PTR_ERR(head);\n\n\tctl_dir = container_of(head, struct ctl_dir, header);\n\n\tif (!dir_emit_dots(file, ctx))\n\t\treturn 0;\n\n\tpos = 2;\n\n\tfor (first_entry(ctl_dir, &h, &entry); h; next_entry(&h, &entry)) {\n\t\tif (!scan(h, entry, &pos, file, ctx)) {\n\t\t\tsysctl_head_finish(h);\n\t\t\tbreak;\n\t\t}\n\t}\n\tsysctl_head_finish(head);\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int atusb_get_and_show_revision(struct atusb *atusb)\n{\n\tstruct usb_device *usb_dev = atusb->usb_dev;\n\tunsigned char buffer[3];\n\tint ret;\n\n\t/* Get a couple of the ATMega Firmware values */\n\tret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),\n\t\t\t\tATUSB_ID, ATUSB_REQ_FROM_DEV, 0, 0,\n\t\t\t\tbuffer, 3, 1000);\n\tif (ret >= 0) {\n\t\tatusb->fw_ver_maj = buffer[0];\n\t\tatusb->fw_ver_min = buffer[1];\n\t\tatusb->fw_hw_type = buffer[2];\n\n\t\tdev_info(&usb_dev->dev,\n\t\t\t \"Firmware: major: %u, minor: %u, hardware type: %u\\n\",\n\t\t\t atusb->fw_ver_maj, atusb->fw_ver_min, atusb->fw_hw_type);\n\t}\n\tif (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 2) {\n\t\tdev_info(&usb_dev->dev,\n\t\t\t \"Firmware version (%u.%u) predates our first public release.\",\n\t\t\t atusb->fw_ver_maj, atusb->fw_ver_min);\n\t\tdev_info(&usb_dev->dev, \"Please update to version 0.2 or newer\");\n\t}\n\n\treturn ret;\n}", "label_name": "CWE-119", "label": 26} {"code": "static enum led_brightness k90_backlight_get(struct led_classdev *led_cdev)\n{\n\tint ret;\n\tstruct k90_led *led = container_of(led_cdev, struct k90_led, cdev);\n\tstruct device *dev = led->cdev.dev->parent;\n\tstruct usb_interface *usbif = to_usb_interface(dev->parent);\n\tstruct usb_device *usbdev = interface_to_usbdev(usbif);\n\tint brightness;\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\tbrightness = data[4];\n\tif (brightness < 0 || brightness > 3) {\n\t\tdev_warn(dev,\n\t\t\t \"Read invalid backlight brightness: %02hhx.\\n\",\n\t\t\t data[4]);\n\t\treturn -EIO;\n\t}\n\treturn brightness;\n}", "label_name": "CWE-119", "label": 26} {"code": "static int cp2112_gpio_get_all(struct gpio_chip *chip)\n{\n\tstruct cp2112_device *dev = gpiochip_get_data(chip);\n\tstruct hid_device *hdev = dev->hdev;\n\tu8 *buf = dev->in_out_buffer;\n\tunsigned long flags;\n\tint ret;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,\n\t\t\t\t CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_GET_REPORT);\n\tif (ret != CP2112_GPIO_GET_LENGTH) {\n\t\thid_err(hdev, \"error requesting GPIO values: %d\\n\", ret);\n\t\tret = ret < 0 ? ret : -EIO;\n\t\tgoto exit;\n\t}\n\n\tret = buf[1];\n\nexit:\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\treturn ret;\n}", "label_name": "CWE-404", "label": 30} {"code": "static int cxusb_ctrl_msg(struct dvb_usb_device *d,\n\t\t\t u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)\n{\n\tstruct cxusb_state *st = d->priv;\n\tint ret, wo;\n\n\tif (1 + wlen > MAX_XFER_SIZE) {\n\t\twarn(\"i2c wr: len=%d is too big!\\n\", wlen);\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\two = (rbuf == NULL || rlen == 0); /* write-only */\n\n\tmutex_lock(&d->data_mutex);\n\tst->data[0] = cmd;\n\tmemcpy(&st->data[1], wbuf, wlen);\n\tif (wo)\n\t\tret = dvb_usb_generic_write(d, st->data, 1 + wlen);\n\telse\n\t\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen,\n\t\t\t\t\t rbuf, rlen, 0);\n\n\tmutex_unlock(&d->data_mutex);\n\treturn ret;\n}", "label_name": "CWE-119", "label": 26} {"code": "static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)\n{\n\tstruct hlist_head *hashent = ucounts_hashentry(ns, uid);\n\tstruct ucounts *ucounts, *new;\n\n\tspin_lock_irq(&ucounts_lock);\n\tucounts = find_ucounts(ns, uid, hashent);\n\tif (!ucounts) {\n\t\tspin_unlock_irq(&ucounts_lock);\n\n\t\tnew = kzalloc(sizeof(*new), GFP_KERNEL);\n\t\tif (!new)\n\t\t\treturn NULL;\n\n\t\tnew->ns = ns;\n\t\tnew->uid = uid;\n\t\tatomic_set(&new->count, 0);\n\n\t\tspin_lock_irq(&ucounts_lock);\n\t\tucounts = find_ucounts(ns, uid, hashent);\n\t\tif (ucounts) {\n\t\t\tkfree(new);\n\t\t} else {\n\t\t\thlist_add_head(&new->node, hashent);\n\t\t\tucounts = new;\n\t\t}\n\t}\n\tif (!atomic_add_unless(&ucounts->count, 1, INT_MAX))\n\t\tucounts = NULL;\n\tspin_unlock_irq(&ucounts_lock);\n\treturn ucounts;\n}", "label_name": "CWE-362", "label": 18} {"code": "int install_process_keyring_to_cred(struct cred *new)\n{\n\tstruct key *keyring;\n\n\tif (new->process_keyring)\n\t\treturn -EEXIST;\n\n\tkeyring = keyring_alloc(\"_pid\", new->uid, new->gid, new,\n\t\t\t\tKEY_POS_ALL | KEY_USR_VIEW,\n\t\t\t\tKEY_ALLOC_QUOTA_OVERRUN,\n\t\t\t\tNULL, NULL);\n\tif (IS_ERR(keyring))\n\t\treturn PTR_ERR(keyring);\n\n\tnew->process_keyring = keyring;\n\treturn 0;\n}", "label_name": "CWE-404", "label": 30} {"code": "int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)\n{\n\tstruct dentry *parent;\n\tstruct inode *p_inode;\n\tint ret = 0;\n\n\tif (!dentry)\n\t\tdentry = path->dentry;\n\n\tif (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))\n\t\treturn 0;\n\n\tparent = dget_parent(dentry);\n\tp_inode = parent->d_inode;\n\n\tif (unlikely(!fsnotify_inode_watches_children(p_inode)))\n\t\t__fsnotify_update_child_dentry_flags(p_inode);\n\telse if (p_inode->i_fsnotify_mask & mask) {\n\t\t/* we are notifying a parent so come up with the new mask which\n\t\t * specifies these are events which came from a child. */\n\t\tmask |= FS_EVENT_ON_CHILD;\n\n\t\tif (path)\n\t\t\tret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,\n\t\t\t\t dentry->d_name.name, 0);\n\t\telse\n\t\t\tret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,\n\t\t\t\t dentry->d_name.name, 0);\n\t}\n\n\tdput(parent);\n\n\treturn ret;\n}", "label_name": "CWE-362", "label": 18} {"code": "void uwbd_stop(struct uwb_rc *rc)\n{\n\tkthread_stop(rc->uwbd.task);\n\tuwbd_flush(rc);\n}", "label_name": "CWE-119", "label": 26} {"code": "int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)\n{\n\t__u64 start = F2FS_BYTES_TO_BLK(range->start);\n\t__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;\n\tunsigned int start_segno, end_segno;\n\tstruct cp_control cpc;\n\tint err = 0;\n\n\tif (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)\n\t\treturn -EINVAL;\n\n\tcpc.trimmed = 0;\n\tif (end <= MAIN_BLKADDR(sbi))\n\t\tgoto out;\n\n\tif (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {\n\t\tf2fs_msg(sbi->sb, KERN_WARNING,\n\t\t\t\"Found FS corruption, run fsck to fix.\");\n\t\tgoto out;\n\t}\n\n\t/* start/end segment number in main_area */\n\tstart_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);\n\tend_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :\n\t\t\t\t\t\tGET_SEGNO(sbi, end);\n\tcpc.reason = CP_DISCARD;\n\tcpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));\n\n\t/* do checkpoint to issue discard commands safely */\n\tfor (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {\n\t\tcpc.trim_start = start_segno;\n\n\t\tif (sbi->discard_blks == 0)\n\t\t\tbreak;\n\t\telse if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))\n\t\t\tcpc.trim_end = end_segno;\n\t\telse\n\t\t\tcpc.trim_end = min_t(unsigned int,\n\t\t\t\trounddown(start_segno +\n\t\t\t\tBATCHED_TRIM_SEGMENTS(sbi),\n\t\t\t\tsbi->segs_per_sec) - 1, end_segno);\n\n\t\tmutex_lock(&sbi->gc_mutex);\n\t\terr = write_checkpoint(sbi, &cpc);\n\t\tmutex_unlock(&sbi->gc_mutex);\n\t\tif (err)\n\t\t\tbreak;\n\n\t\tschedule();\n\t}\n\t/* It's time to issue all the filed discards */\n\tmark_discard_range_all(sbi);\n\tf2fs_wait_discard_bios(sbi);\nout:\n\trange->len = F2FS_BLK_TO_BYTES(cpc.trimmed);\n\treturn err;\n}", "label_name": "CWE-20", "label": 0} {"code": "void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)\n{\n\t__issue_discard_cmd(sbi, false);\n\t__drop_discard_cmd(sbi);\n\t__wait_discard_cmd(sbi, false);\n}", "label_name": "CWE-20", "label": 0} {"code": "static int keyring_search_iterator(const void *object, void *iterator_data)\n{\n\tstruct keyring_search_context *ctx = iterator_data;\n\tconst struct key *key = keyring_ptr_to_key(object);\n\tunsigned long kflags = key->flags;\n\n\tkenter(\"{%d}\", key->serial);\n\n\t/* ignore keys not of this type */\n\tif (key->type != ctx->index_key.type) {\n\t\tkleave(\" = 0 [!type]\");\n\t\treturn 0;\n\t}\n\n\t/* skip invalidated, revoked and expired keys */\n\tif (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {\n\t\tif (kflags & ((1 << KEY_FLAG_INVALIDATED) |\n\t\t\t (1 << KEY_FLAG_REVOKED))) {\n\t\t\tctx->result = ERR_PTR(-EKEYREVOKED);\n\t\t\tkleave(\" = %d [invrev]\", ctx->skipped_ret);\n\t\t\tgoto skipped;\n\t\t}\n\n\t\tif (key->expiry && ctx->now.tv_sec >= key->expiry) {\n\t\t\tif (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))\n\t\t\t\tctx->result = ERR_PTR(-EKEYEXPIRED);\n\t\t\tkleave(\" = %d [expire]\", ctx->skipped_ret);\n\t\t\tgoto skipped;\n\t\t}\n\t}\n\n\t/* keys that don't match */\n\tif (!ctx->match_data.cmp(key, &ctx->match_data)) {\n\t\tkleave(\" = 0 [!match]\");\n\t\treturn 0;\n\t}\n\n\t/* key must have search permissions */\n\tif (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&\n\t key_task_permission(make_key_ref(key, ctx->possessed),\n\t\t\t\tctx->cred, KEY_NEED_SEARCH) < 0) {\n\t\tctx->result = ERR_PTR(-EACCES);\n\t\tkleave(\" = %d [!perm]\", ctx->skipped_ret);\n\t\tgoto skipped;\n\t}\n\n\tif (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {\n\t\t/* we set a different error code if we pass a negative key */\n\t\tif (kflags & (1 << KEY_FLAG_NEGATIVE)) {\n\t\t\tsmp_rmb();\n\t\t\tctx->result = ERR_PTR(key->reject_error);\n\t\t\tkleave(\" = %d [neg]\", ctx->skipped_ret);\n\t\t\tgoto skipped;\n\t\t}\n\t}\n\n\t/* Found */\n\tctx->result = make_key_ref(key, ctx->possessed);\n\tkleave(\" = 1 [found]\");\n\treturn 1;\n\nskipped:\n\treturn ctx->skipped_ret;\n}", "label_name": "CWE-20", "label": 0} {"code": "int wait_for_key_construction(struct key *key, bool intr)\n{\n\tint ret;\n\n\tret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,\n\t\t\t intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);\n\tif (ret)\n\t\treturn -ERESTARTSYS;\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tsmp_rmb();\n\t\treturn key->reject_error;\n\t}\n\treturn key_validate(key);\n}", "label_name": "CWE-20", "label": 0} {"code": "static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n\t\t\t\t\t const char *callout_info,\n\t\t\t\t\t size_t callout_len,\n\t\t\t\t\t void *aux,\n\t\t\t\t\t struct key *dest_keyring,\n\t\t\t\t\t unsigned long flags)\n{\n\tstruct key_user *user;\n\tstruct key *key;\n\tint ret;\n\n\tkenter(\"\");\n\n\tif (ctx->index_key.type == &key_type_keyring)\n\t\treturn ERR_PTR(-EPERM);\n\n\tuser = key_user_lookup(current_fsuid());\n\tif (!user)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tconstruct_get_dest_keyring(&dest_keyring);\n\n\tret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);\n\tkey_user_put(user);\n\n\tif (ret == 0) {\n\t\tret = construct_key(key, callout_info, callout_len, aux,\n\t\t\t\t dest_keyring);\n\t\tif (ret < 0) {\n\t\t\tkdebug(\"cons failed\");\n\t\t\tgoto construction_failed;\n\t\t}\n\t} else if (ret == -EINPROGRESS) {\n\t\tret = 0;\n\t} else {\n\t\tgoto couldnt_alloc_key;\n\t}\n\n\tkey_put(dest_keyring);\n\tkleave(\" = key %d\", key_serial(key));\n\treturn key;\n\nconstruction_failed:\n\tkey_negate_and_link(key, key_negative_timeout, NULL, NULL);\n\tkey_put(key);\ncouldnt_alloc_key:\n\tkey_put(dest_keyring);\n\tkleave(\" = %d\", ret);\n\treturn ERR_PTR(ret);\n}", "label_name": "CWE-862", "label": 8} {"code": "evtchn_port_t evtchn_from_irq(unsigned irq)\n{\n\tif (WARN(irq >= nr_irqs, \"Invalid irq %d!\\n\", irq))\n\t\treturn 0;\n\n\treturn info_for_irq(irq)->evtchn;\n}", "label_name": "CWE-362", "label": 18} {"code": "static int __init xfrm6_tunnel_init(void)\n{\n\tint rv;\n\n\trv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);\n\tif (rv < 0)\n\t\tgoto err;\n\trv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);\n\tif (rv < 0)\n\t\tgoto unreg;\n\trv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);\n\tif (rv < 0)\n\t\tgoto dereg6;\n\trv = xfrm6_tunnel_spi_init();\n\tif (rv < 0)\n\t\tgoto dereg46;\n\trv = register_pernet_subsys(&xfrm6_tunnel_net_ops);\n\tif (rv < 0)\n\t\tgoto deregspi;\n\treturn 0;\n\nderegspi:\n\txfrm6_tunnel_spi_fini();\ndereg46:\n\txfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);\ndereg6:\n\txfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);\nunreg:\n\txfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);\nerr:\n\treturn rv;\n}", "label_name": "CWE-362", "label": 18} {"code": "static int net_ctl_permissions(struct ctl_table_header *head,\n\t\t\t struct ctl_table *table)\n{\n\tstruct net *net = container_of(head->set, struct net, sysctls);\n\tkuid_t root_uid = make_kuid(net->user_ns, 0);\n\tkgid_t root_gid = make_kgid(net->user_ns, 0);\n\n\t/* Allow network administrator to have same access as root. */\n\tif (ns_capable(net->user_ns, CAP_NET_ADMIN) ||\n\t uid_eq(root_uid, current_uid())) {\n\t\tint mode = (table->mode >> 6) & 7;\n\t\treturn (mode << 6) | (mode << 3) | mode;\n\t}\n\t/* Allow netns root group to have the same access as the root group */\n\tif (gid_eq(root_gid, current_gid())) {\n\t\tint mode = (table->mode >> 3) & 7;\n\t\treturn (mode << 3) | mode;\n\t}\n\treturn table->mode;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int raw_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n\t\t size_t len, int noblock, int flags, int *addr_len)\n{\n\tstruct inet_sock *inet = inet_sk(sk);\n\tsize_t copied = 0;\n\tint err = -EOPNOTSUPP;\n\tstruct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;\n\tstruct sk_buff *skb;\n\n\tif (flags & MSG_OOB)\n\t\tgoto out;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(*sin);\n\n\tif (flags & MSG_ERRQUEUE) {\n\t\terr = ip_recv_error(sk, msg, len);\n\t\tgoto out;\n\t}\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb)\n\t\tgoto out;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\tif (err)\n\t\tgoto done;\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t/* Copy the address. */\n\tif (sin) {\n\t\tsin->sin_family = AF_INET;\n\t\tsin->sin_addr.s_addr = ip_hdr(skb)->saddr;\n\t\tsin->sin_port = 0;\n\t\tmemset(&sin->sin_zero, 0, sizeof(sin->sin_zero));\n\t}\n\tif (inet->cmsg_flags)\n\t\tip_cmsg_recv(msg, skb);\n\tif (flags & MSG_TRUNC)\n\t\tcopied = skb->len;\ndone:\n\tskb_free_datagram(sk, skb);\nout:\n\tif (err)\n\t\treturn err;\n\treturn copied;\n}", "label_name": "CWE-20", "label": 0} {"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-200", "label": 10} {"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": "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 int hci_sock_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, err;\n\n\tBT_DBG(\"sock %p, sk %p\", sock, sk);\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tif (sk->sk_state == BT_CLOSED)\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb)\n\t\treturn err;\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\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tswitch (hci_pi(sk)->channel) {\n\tcase HCI_CHANNEL_RAW:\n\t\thci_sock_cmsg(sk, msg, skb);\n\t\tbreak;\n\tcase HCI_CHANNEL_USER:\n\tcase HCI_CHANNEL_CONTROL:\n\tcase HCI_CHANNEL_MONITOR:\n\t\tsock_recv_timestamp(msg, sk, skb);\n\t\tbreak;\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int rfcomm_sock_recvmsg(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 rfcomm_dlc *d = rfcomm_pi(sk)->dlc;\n\tint len;\n\n\tif (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {\n\t\trfcomm_dlc_accept(d);\n\t\tmsg->msg_namelen = 0;\n\t\treturn 0;\n\t}\n\n\tlen = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);\n\n\tlock_sock(sk);\n\tif (!(flags & MSG_PEEK) && len > 0)\n\t\tatomic_sub(len, &sk->sk_rmem_alloc);\n\n\tif (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))\n\t\trfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);\n\trelease_sock(sk);\n\n\treturn len;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int rfcomm_sock_recvmsg(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 rfcomm_dlc *d = rfcomm_pi(sk)->dlc;\n\tint len;\n\n\tif (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {\n\t\trfcomm_dlc_accept(d);\n\t\tmsg->msg_namelen = 0;\n\t\treturn 0;\n\t}\n\n\tlen = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);\n\n\tlock_sock(sk);\n\tif (!(flags & MSG_PEEK) && len > 0)\n\t\tatomic_sub(len, &sk->sk_rmem_alloc);\n\n\tif (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))\n\t\trfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);\n\trelease_sock(sk);\n\n\treturn len;\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": "int verify_iovec(struct msghdr *m, struct iovec *iov, struct sockaddr_storage *address, int mode)\n{\n\tint size, ct, err;\n\n\tif (m->msg_namelen) {\n\t\tif (mode == VERIFY_READ) {\n\t\t\tvoid __user *namep;\n\t\t\tnamep = (void __user __force *) m->msg_name;\n\t\t\terr = move_addr_to_kernel(namep, m->msg_namelen,\n\t\t\t\t\t\t address);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t}\n\t\tm->msg_name = address;\n\t} else {\n\t\tm->msg_name = NULL;\n\t}\n\n\tsize = m->msg_iovlen * sizeof(struct iovec);\n\tif (copy_from_user(iov, (void __user __force *) m->msg_iov, size))\n\t\treturn -EFAULT;\n\n\tm->msg_iov = iov;\n\terr = 0;\n\n\tfor (ct = 0; ct < m->msg_iovlen; ct++) {\n\t\tsize_t len = iov[ct].iov_len;\n\n\t\tif (len > INT_MAX - err) {\n\t\t\tlen = INT_MAX - err;\n\t\t\tiov[ct].iov_len = len;\n\t\t}\n\t\terr += len;\n\t}\n\n\treturn err;\n}", "label_name": "CWE-20", "label": 0} {"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": "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": "static int rose_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rose_sock *rose = rose_sk(sk);\n\tstruct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;\n\tsize_t copied;\n\tunsigned char *asmptr;\n\tstruct sk_buff *skb;\n\tint n, er, qbit;\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\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\treturn -ENOTCONN;\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\treturn er;\n\n\tqbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;\n\n\tskb_pull(skb, ROSE_MIN_LEN);\n\n\tif (rose->qbitincl) {\n\t\tasmptr = skb_push(skb, 1);\n\t\t*asmptr = qbit;\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\tskb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tif (srose != NULL) {\n\t\tmemset(srose, 0, msg->msg_namelen);\n\t\tsrose->srose_family = AF_ROSE;\n\t\tsrose->srose_addr = rose->dest_addr;\n\t\tsrose->srose_call = rose->dest_call;\n\t\tsrose->srose_ndigis = rose->dest_ndigis;\n\t\tif (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {\n\t\t\tstruct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;\n\t\t\tfor (n = 0 ; n < rose->dest_ndigis ; n++)\n\t\t\t\tfull_srose->srose_digis[n] = rose->dest_digis[n];\n\t\t\tmsg->msg_namelen = sizeof(struct full_sockaddr_rose);\n\t\t} else {\n\t\t\tif (rose->dest_ndigis >= 1) {\n\t\t\t\tsrose->srose_ndigis = 1;\n\t\t\t\tsrose->srose_digi = rose->dest_digis[0];\n\t\t\t}\n\t\t\tmsg->msg_namelen = sizeof(struct sockaddr_rose);\n\t\t}\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn copied;\n}", "label_name": "CWE-20", "label": 0} {"code": "static void unix_copy_addr(struct msghdr *msg, struct sock *sk)\n{\n\tstruct unix_sock *u = unix_sk(sk);\n\n\tmsg->msg_namelen = 0;\n\tif (u->addr) {\n\t\tmsg->msg_namelen = u->addr->len;\n\t\tmemcpy(msg->msg_name, u->addr->name, u->addr->len);\n\t}\n}", "label_name": "CWE-20", "label": 0} {"code": "static void unix_copy_addr(struct msghdr *msg, struct sock *sk)\n{\n\tstruct unix_sock *u = unix_sk(sk);\n\n\tmsg->msg_namelen = 0;\n\tif (u->addr) {\n\t\tmsg->msg_namelen = u->addr->len;\n\t\tmemcpy(msg->msg_name, u->addr->name, u->addr->len);\n\t}\n}", "label_name": "CWE-20", "label": 0} {"code": "static bool dccp_new(struct nf_conn *ct, const struct sk_buff *skb,\n\t\t unsigned int dataoff, unsigned int *timeouts)\n{\n\tstruct net *net = nf_ct_net(ct);\n\tstruct dccp_net *dn;\n\tstruct dccp_hdr _dh, *dh;\n\tconst char *msg;\n\tu_int8_t state;\n\n\tdh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);\n\tBUG_ON(dh == NULL);\n\n\tstate = dccp_state_table[CT_DCCP_ROLE_CLIENT][dh->dccph_type][CT_DCCP_NONE];\n\tswitch (state) {\n\tdefault:\n\t\tdn = dccp_pernet(net);\n\t\tif (dn->dccp_loose == 0) {\n\t\t\tmsg = \"nf_ct_dccp: not picking up existing connection \";\n\t\t\tgoto out_invalid;\n\t\t}\n\tcase CT_DCCP_REQUEST:\n\t\tbreak;\n\tcase CT_DCCP_INVALID:\n\t\tmsg = \"nf_ct_dccp: invalid state transition \";\n\t\tgoto out_invalid;\n\t}\n\n\tct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT;\n\tct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER;\n\tct->proto.dccp.state = CT_DCCP_NONE;\n\tct->proto.dccp.last_pkt = DCCP_PKT_REQUEST;\n\tct->proto.dccp.last_dir = IP_CT_DIR_ORIGINAL;\n\tct->proto.dccp.handshake_seq = 0;\n\treturn true;\n\nout_invalid:\n\tif (LOG_INVALID(net, IPPROTO_DCCP))\n\t\tnf_log_packet(net, nf_ct_l3num(ct), 0, skb, NULL, NULL,\n\t\t\t NULL, \"%s\", msg);\n\treturn false;\n}", "label_name": "CWE-20", "label": 0} {"code": "static void rd_release_device_space(struct rd_dev *rd_dev)\n{\n\tu32 i, j, page_count = 0, sg_per_table;\n\tstruct rd_dev_sg_table *sg_table;\n\tstruct page *pg;\n\tstruct scatterlist *sg;\n\n\tif (!rd_dev->sg_table_array || !rd_dev->sg_table_count)\n\t\treturn;\n\n\tsg_table = rd_dev->sg_table_array;\n\n\tfor (i = 0; i < rd_dev->sg_table_count; i++) {\n\t\tsg = sg_table[i].sg_table;\n\t\tsg_per_table = sg_table[i].rd_sg_count;\n\n\t\tfor (j = 0; j < sg_per_table; j++) {\n\t\t\tpg = sg_page(&sg[j]);\n\t\t\tif (pg) {\n\t\t\t\t__free_page(pg);\n\t\t\t\tpage_count++;\n\t\t\t}\n\t\t}\n\n\t\tkfree(sg);\n\t}\n\n\tpr_debug(\"CORE_RD[%u] - Released device space for Ramdisk\"\n\t\t\" Device ID: %u, pages %u in %u tables total bytes %lu\\n\",\n\t\trd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,\n\t\trd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);\n\n\tkfree(sg_table);\n\trd_dev->sg_table_array = NULL;\n\trd_dev->sg_table_count = 0;\n}", "label_name": "CWE-200", "label": 10} {"code": "bool __net_get_random_once(void *buf, int nbytes, bool *done,\n\t\t\t struct static_key *done_key)\n{\n\tstatic DEFINE_SPINLOCK(lock);\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&lock, flags);\n\tif (*done) {\n\t\tspin_unlock_irqrestore(&lock, flags);\n\t\treturn false;\n\t}\n\n\tget_random_bytes(buf, nbytes);\n\t*done = true;\n\tspin_unlock_irqrestore(&lock, flags);\n\n\t__net_random_once_disable_jump(done_key);\n\n\treturn true;\n}", "label_name": "CWE-200", "label": 10} {"code": "static int udf_pc_to_char(struct super_block *sb, unsigned char *from,\n\t\t\t int fromlen, unsigned char *to, int tolen)\n{\n\tstruct pathComponent *pc;\n\tint elen = 0;\n\tint comp_len;\n\tunsigned char *p = to;\n\n\t/* Reserve one byte for terminating \\0 */\n\ttolen--;\n\twhile (elen < fromlen) {\n\t\tpc = (struct pathComponent *)(from + elen);\n\t\tswitch (pc->componentType) {\n\t\tcase 1:\n\t\t\t/*\n\t\t\t * Symlink points to some place which should be agreed\n \t\t\t * upon between originator and receiver of the media. Ignore.\n\t\t\t */\n\t\t\tif (pc->lengthComponentIdent > 0)\n\t\t\t\tbreak;\n\t\t\t/* Fall through */\n\t\tcase 2:\n\t\t\tif (tolen == 0)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t\tp = to;\n\t\t\t*p++ = '/';\n\t\t\ttolen--;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tif (tolen < 3)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t\tmemcpy(p, \"../\", 3);\n\t\t\tp += 3;\n\t\t\ttolen -= 3;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tif (tolen < 2)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t\tmemcpy(p, \"./\", 2);\n\t\t\tp += 2;\n\t\t\ttolen -= 2;\n\t\t\t/* that would be . - just ignore */\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tcomp_len = udf_get_filename(sb, pc->componentIdent,\n\t\t\t\t\t\t pc->lengthComponentIdent,\n\t\t\t\t\t\t p, tolen);\n\t\t\tp += comp_len;\n\t\t\ttolen -= comp_len;\n\t\t\tif (tolen == 0)\n\t\t\t\treturn -ENAMETOOLONG;\n\t\t\t*p++ = '/';\n\t\t\ttolen--;\n\t\t\tbreak;\n\t\t}\n\t\telen += sizeof(struct pathComponent) + pc->lengthComponentIdent;\n\t}\n\tif (p > to + 1)\n\t\tp[-1] = '\\0';\n\telse\n\t\tp[0] = '\\0';\n\treturn 0;\n}", "label_name": "CWE-119", "label": 26} {"code": "static inline int xrstor_state(struct xsave_struct *fx, u64 mask)\n{\n\tint err = 0;\n\tu32 lmask = mask;\n\tu32 hmask = mask >> 32;\n\n\t/*\n\t * Use xrstors to restore context if it is enabled. xrstors supports\n\t * compacted format of xsave area which is not supported by xrstor.\n\t */\n\talternative_input(\n\t\t\"1: \" XRSTOR,\n\t\t\"1: \" XRSTORS,\n\t\tX86_FEATURE_XSAVES,\n\t\t\"D\" (fx), \"m\" (*fx), \"a\" (lmask), \"d\" (hmask)\n\t\t: \"memory\");\n\n\tasm volatile(\"2:\\n\"\n\t\t xstate_fault\n\t\t : \"0\" (0)\n\t\t : \"memory\");\n\n\treturn err;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int get_bitmap_file(struct mddev *mddev, void __user * arg)\n{\n\tmdu_bitmap_file_t *file = NULL; /* too big for stack allocation */\n\tchar *ptr;\n\tint err;\n\n\tfile = kmalloc(sizeof(*file), GFP_NOIO);\n\tif (!file)\n\t\treturn -ENOMEM;\n\n\terr = 0;\n\tspin_lock(&mddev->lock);\n\t/* bitmap disabled, zero the first byte and copy out */\n\tif (!mddev->bitmap_info.file)\n\t\tfile->pathname[0] = '\\0';\n\telse if ((ptr = file_path(mddev->bitmap_info.file,\n\t\t\t file->pathname, sizeof(file->pathname))),\n\t\t IS_ERR(ptr))\n\t\terr = PTR_ERR(ptr);\n\telse\n\t\tmemmove(file->pathname, ptr,\n\t\t\tsizeof(file->pathname)-(ptr-file->pathname));\n\tspin_unlock(&mddev->lock);\n\n\tif (err == 0 &&\n\t copy_to_user(arg, file, sizeof(*file)))\n\t\terr = -EFAULT;\n\n\tkfree(file);\n\treturn err;\n}", "label_name": "CWE-200", "label": 10} {"code": "static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,\n\t\t\t loff_t *ppos)\n{\n\tstruct usb_yurex *dev;\n\tint retval = 0;\n\tint bytes_read = 0;\n\tchar in_buffer[20];\n\tunsigned long flags;\n\n\tdev = file->private_data;\n\n\tmutex_lock(&dev->io_mutex);\n\tif (!dev->interface) {\t\t/* already disconnected */\n\t\tretval = -ENODEV;\n\t\tgoto exit;\n\t}\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\tbytes_read = snprintf(in_buffer, 20, \"%lld\\n\", dev->bbu);\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\n\tif (*ppos < bytes_read) {\n\t\tif (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos))\n\t\t\tretval = -EFAULT;\n\t\telse {\n\t\t\tretval = bytes_read - *ppos;\n\t\t\t*ppos += bytes_read;\n\t\t}\n\t}\n\nexit:\n\tmutex_unlock(&dev->io_mutex);\n\treturn retval;\n}", "label_name": "CWE-20", "label": 0} {"code": "static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)\n{\n struct ipddp_route __user *rt = ifr->ifr_data;\n struct ipddp_route rcp, rcp2, *rp;\n\n if(!capable(CAP_NET_ADMIN))\n return -EPERM;\n\n\tif(copy_from_user(&rcp, rt, sizeof(rcp)))\n\t\treturn -EFAULT;\n\n switch(cmd)\n {\n\t\tcase SIOCADDIPDDPRT:\n return ipddp_create(&rcp);\n\n case SIOCFINDIPDDPRT:\n\t\t\tspin_lock_bh(&ipddp_route_lock);\n\t\t\trp = __ipddp_find_route(&rcp);\n\t\t\tif (rp)\n\t\t\t\tmemcpy(&rcp2, rp, sizeof(rcp2));\n\t\t\tspin_unlock_bh(&ipddp_route_lock);\n\n\t\t\tif (rp) {\n\t\t\t\tif (copy_to_user(rt, &rcp2,\n\t\t\t\t\t\t sizeof(struct ipddp_route)))\n\t\t\t\t\treturn -EFAULT;\n\t\t\t\treturn 0;\n\t\t\t} else\n\t\t\t\treturn -ENOENT;\n\n case SIOCDELIPDDPRT:\n return ipddp_delete(&rcp);\n\n default:\n return -EINVAL;\n }\n}", "label_name": "CWE-200", "label": 10} {"code": "static int usb_enumerate_device_otg(struct usb_device *udev)\n{\n\tint err = 0;\n\n#ifdef\tCONFIG_USB_OTG\n\t/*\n\t * OTG-aware devices on OTG-capable root hubs may be able to use SRP,\n\t * to wake us after we've powered off VBUS; and HNP, switching roles\n\t * \"host\" to \"peripheral\". The OTG descriptor helps figure this out.\n\t */\n\tif (!udev->bus->is_b_host\n\t\t\t&& udev->config\n\t\t\t&& udev->parent == udev->bus->root_hub) {\n\t\tstruct usb_otg_descriptor\t*desc = NULL;\n\t\tstruct usb_bus\t\t\t*bus = udev->bus;\n\t\tunsigned\t\t\tport1 = udev->portnum;\n\n\t\t/* descriptor may appear anywhere in config */\n\t\terr = __usb_get_extra_descriptor(udev->rawdescriptors[0],\n\t\t\t\tle16_to_cpu(udev->config[0].desc.wTotalLength),\n\t\t\t\tUSB_DT_OTG, (void **) &desc);\n\t\tif (err || !(desc->bmAttributes & USB_OTG_HNP))\n\t\t\treturn 0;\n\n\t\tdev_info(&udev->dev, \"Dual-Role OTG device on %sHNP port\\n\",\n\t\t\t\t\t(port1 == bus->otg_port) ? \"\" : \"non-\");\n\n\t\t/* enable HNP before suspend, it's simpler */\n\t\tif (port1 == bus->otg_port) {\n\t\t\tbus->b_hnp_enable = 1;\n\t\t\terr = usb_control_msg(udev,\n\t\t\t\tusb_sndctrlpipe(udev, 0),\n\t\t\t\tUSB_REQ_SET_FEATURE, 0,\n\t\t\t\tUSB_DEVICE_B_HNP_ENABLE,\n\t\t\t\t0, NULL, 0,\n\t\t\t\tUSB_CTRL_SET_TIMEOUT);\n\t\t\tif (err < 0) {\n\t\t\t\t/*\n\t\t\t\t * OTG MESSAGE: report errors here,\n\t\t\t\t * customize to match your product.\n\t\t\t\t */\n\t\t\t\tdev_err(&udev->dev, \"can't set HNP mode: %d\\n\",\n\t\t\t\t\t\t\t\t\terr);\n\t\t\t\tbus->b_hnp_enable = 0;\n\t\t\t}\n\t\t} else if (desc->bLength == sizeof\n\t\t\t\t(struct usb_otg_descriptor)) {\n\t\t\t/* Set a_alt_hnp_support for legacy otg device */\n\t\t\terr = usb_control_msg(udev,\n\t\t\t\tusb_sndctrlpipe(udev, 0),\n\t\t\t\tUSB_REQ_SET_FEATURE, 0,\n\t\t\t\tUSB_DEVICE_A_ALT_HNP_SUPPORT,\n\t\t\t\t0, NULL, 0,\n\t\t\t\tUSB_CTRL_SET_TIMEOUT);\n\t\t\tif (err < 0)\n\t\t\t\tdev_err(&udev->dev,\n\t\t\t\t\t\"set a_alt_hnp_support failed: %d\\n\",\n\t\t\t\t\terr);\n\t\t}\n\t}\n#endif\n\treturn err;\n}", "label_name": "CWE-400", "label": 2} {"code": "void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)\n{\n\tstatic u32 ip_idents_hashrnd __read_mostly;\n\tu32 hash, id;\n\n\tnet_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));\n\n\thash = jhash_3words((__force u32)iph->daddr,\n\t\t\t (__force u32)iph->saddr,\n\t\t\t iph->protocol ^ net_hash_mix(net),\n\t\t\t ip_idents_hashrnd);\n\tid = ip_idents_reserve(hash, segs);\n\tiph->id = htons(id);\n}", "label_name": "CWE-326", "label": 9} {"code": "int insn_get_code_seg_params(struct pt_regs *regs)\n{\n\tstruct desc_struct *desc;\n\tshort sel;\n\n\tif (v8086_mode(regs))\n\t\t/* Address and operand size are both 16-bit. */\n\t\treturn INSN_CODE_SEG_PARAMS(2, 2);\n\n\tsel = get_segment_selector(regs, INAT_SEG_REG_CS);\n\tif (sel < 0)\n\t\treturn sel;\n\n\tdesc = get_desc(sel);\n\tif (!desc)\n\t\treturn -EINVAL;\n\n\t/*\n\t * The most significant byte of the Type field of the segment descriptor\n\t * determines whether a segment contains data or code. If this is a data\n\t * segment, return error.\n\t */\n\tif (!(desc->type & BIT(3)))\n\t\treturn -EINVAL;\n\n\tswitch ((desc->l << 1) | desc->d) {\n\tcase 0: /*\n\t\t * Legacy mode. CS.L=0, CS.D=0. Address and operand size are\n\t\t * both 16-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(2, 2);\n\tcase 1: /*\n\t\t * Legacy mode. CS.L=0, CS.D=1. Address and operand size are\n\t\t * both 32-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(4, 4);\n\tcase 2: /*\n\t\t * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit;\n\t\t * operand size is 32-bit.\n\t\t */\n\t\treturn INSN_CODE_SEG_PARAMS(4, 8);\n\tcase 3: /* Invalid setting. CS.L=1, CS.D=1 */\n\t\t/* fall through */\n\tdefault:\n\t\treturn -EINVAL;\n\t}\n}", "label_name": "CWE-362", "label": 18} {"code": "static int filter_frame(AVFilterLink *inlink, AVFrame *in)\n{\n PadContext *s = inlink->dst->priv;\n AVFrame *out;\n int needs_copy = frame_needs_copy(s, in);\n\n if (needs_copy) {\n av_log(inlink->dst, AV_LOG_DEBUG, \"Direct padding impossible allocating new frame\\n\");\n out = ff_get_video_buffer(inlink->dst->outputs[0],\n FFMAX(inlink->w, s->w),\n FFMAX(inlink->h, s->h));\n if (!out) {\n av_frame_free(&in);\n return AVERROR(ENOMEM);\n }\n\n av_frame_copy_props(out, in);\n } else {\n int i;\n\n out = in;\n for (i = 0; i < 4 && out->data[i]; i++) {\n int hsub = s->draw.hsub[i];\n int vsub = s->draw.vsub[i];\n out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +\n (s->y >> vsub) * out->linesize[i];\n }\n }\n\n /* top bar */\n if (s->y) {\n ff_fill_rectangle(&s->draw, &s->color,\n out->data, out->linesize,\n 0, 0, s->w, s->y);\n }\n\n /* bottom bar */\n if (s->h > s->y + s->in_h) {\n ff_fill_rectangle(&s->draw, &s->color,\n out->data, out->linesize,\n 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);\n }\n\n /* left border */\n ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,\n 0, s->y, s->x, in->height);\n\n if (needs_copy) {\n ff_copy_rectangle2(&s->draw,\n out->data, out->linesize, in->data, in->linesize,\n s->x, s->y, 0, 0, in->width, in->height);\n }\n\n /* right border */\n ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,\n s->x + s->in_w, s->y, s->w - s->x - s->in_w,\n in->height);\n\n out->width = s->w;\n out->height = s->h;\n\n if (in != out)\n av_frame_free(&in);\n return ff_filter_frame(inlink->dst->outputs[0], out);\n}", "label_name": "CWE-119", "label": 26} {"code": "static void scsi_write_complete(void * opaque, int ret)\n{\n SCSIDiskReq *r = (SCSIDiskReq *)opaque;\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);\n uint32_t len;\n uint32_t n;\n\n if (r->req.aiocb != NULL) {\n r->req.aiocb = NULL;\n bdrv_acct_done(s->bs, &r->acct);\n }\n\n if (ret) {\n if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) {\n return;\n }\n }\n\n n = r->iov.iov_len / 512;\n r->sector += n;\n r->sector_count -= n;\n if (r->sector_count == 0) {\n scsi_req_complete(&r->req, GOOD);\n } else {\n len = r->sector_count * 512;\n if (len > SCSI_DMA_BUF_SIZE) {\n len = SCSI_DMA_BUF_SIZE;\n }\n r->iov.iov_len = len;\n DPRINTF(\"Write complete tag=0x%x more=%d\\n\", r->req.tag, len);\n scsi_req_data(&r->req, len);\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "static void scsi_write_data(SCSIRequest *req)\n{\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);\n uint32_t n;\n\n /* No data transfer may already be in progress */\n assert(r->req.aiocb == NULL);\n\n if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {\n DPRINTF(\"Data transfer direction invalid\\n\");\n scsi_write_complete(r, -EINVAL);\n return;\n }\n\n n = r->iov.iov_len / 512;\n if (n) {\n if (s->tray_open) {\n scsi_write_complete(r, -ENOMEDIUM);\n }\n qemu_iovec_init_external(&r->qiov, &r->iov, 1);\n\n bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);\n r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,\n scsi_write_complete, r);\n if (r->req.aiocb == NULL) {\n scsi_write_complete(r, -ENOMEM);\n }\n } else {\n /* Invoke completion routine to fetch data from host. */\n scsi_write_complete(r, 0);\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)\n{\n\tPyObject *logical = NULL;\t/* input unicode or string object */\n\tFriBidiParType base = FRIBIDI_TYPE_RTL;\t/* optional direction */\n\tconst char *encoding = \"utf-8\";\t/* optional input string encoding */\n\tint clean = 0; /* optional flag to clean the string */\n\tint reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/\n\n\tstatic char *kwargs[] =\n\t { \"logical\", \"base_direction\", \"encoding\", \"clean\", \"reordernsm\", NULL };\n\n if (!PyArg_ParseTupleAndKeywords (args, kw, \"O|isii\", kwargs,\n\t\t\t\t\t &logical, &base, &encoding, &clean, &reordernsm))\n\t\treturn NULL;\n\n\t/* Validate base */\n\n\tif (!(base == FRIBIDI_TYPE_RTL ||\n\t base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON))\n\t\treturn PyErr_Format (PyExc_ValueError,\n\t\t\t\t \"invalid value %d: use either RTL, LTR or ON\",\n\t\t\t\t base);\n\n\t/* Check object type and delegate to one of the log2vis functions */\n\n\tif (PyUnicode_Check (logical))\n\t return log2vis_unicode (logical, base, clean, reordernsm);\n\telse if (PyString_Check (logical))\n\t return log2vis_encoded_string (logical, encoding, base, clean, reordernsm);\n\telse\n\t\treturn PyErr_Format (PyExc_TypeError,\n\t\t\t\t \"expected unicode or str, not %s\",\n\t\t\t\t logical->ob_type->tp_name);\n}", "label_name": "CWE-119", "label": 26} {"code": "static void stellaris_enet_save(QEMUFile *f, void *opaque)\n{\n stellaris_enet_state *s = (stellaris_enet_state *)opaque;\n int i;\n\n qemu_put_be32(f, s->ris);\n qemu_put_be32(f, s->im);\n qemu_put_be32(f, s->rctl);\n qemu_put_be32(f, s->tctl);\n qemu_put_be32(f, s->thr);\n qemu_put_be32(f, s->mctl);\n qemu_put_be32(f, s->mdv);\n qemu_put_be32(f, s->mtxd);\n qemu_put_be32(f, s->mrxd);\n qemu_put_be32(f, s->np);\n qemu_put_be32(f, s->tx_fifo_len);\n qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));\n for (i = 0; i < 31; i++) {\n qemu_put_be32(f, s->rx[i].len);\n qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));\n\n }\n qemu_put_be32(f, s->next_packet);\n qemu_put_be32(f, s->rx_fifo_offset);\n}", "label_name": "CWE-119", "label": 26} {"code": "ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */\n{\n\tstruct _store_object *obj;\n\tint failure = 0;\n\n\tif (!EG(objects_store).object_buckets) {\n\t\treturn;\n\t}\n\n\tobj = &EG(objects_store).object_buckets[handle].bucket.obj;\n\n\t/*\tMake sure we hold a reference count during the destructor call\n\t\totherwise, when the destructor ends the storage might be freed\n\t\twhen the refcount reaches 0 a second time\n\t */\n\tif (EG(objects_store).object_buckets[handle].valid) {\n\t\tif (obj->refcount == 1) {\n\t\t\tif (!EG(objects_store).object_buckets[handle].destructor_called) {\n\t\t\t\tEG(objects_store).object_buckets[handle].destructor_called = 1;\n\n\t\t\t\tif (obj->dtor) {\n\t\t\t\t\tif (handlers && !obj->handlers) {\n\t\t\t\t\t\tobj->handlers = handlers;\n\t\t\t\t\t}\n\t\t\t\t\tzend_try {\n\t\t\t\t\t\tobj->dtor(obj->object, handle TSRMLS_CC);\n\t\t\t\t\t} zend_catch {\n\t\t\t\t\t\tfailure = 1;\n\t\t\t\t\t} zend_end_try();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t/* re-read the object from the object store as the store might have been reallocated in the dtor */\n\t\t\tobj = &EG(objects_store).object_buckets[handle].bucket.obj;\n\n\t\t\tif (obj->refcount == 1) {\n\t\t\t\tGC_REMOVE_ZOBJ_FROM_BUFFER(obj);\n\t\t\t\tif (obj->free_storage) {\n\t\t\t\t\tzend_try {\n\t\t\t\t\t\tobj->free_storage(obj->object TSRMLS_CC);\n\t\t\t\t\t} zend_catch {\n\t\t\t\t\t\tfailure = 1;\n\t\t\t\t\t} zend_end_try();\n\t\t\t\t}\n\t\t\t\tZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();\n\t\t\t}\n\t\t}\n\t}\n\n\tobj->refcount--;\n\n#if ZEND_DEBUG_OBJECTS\n\tif (obj->refcount == 0) {\n\t\tfprintf(stderr, \"Deallocated object id #%d\\n\", handle);\n\t} else {\n\t\tfprintf(stderr, \"Decreased refcount of object id #%d\\n\", handle);\n\t}\n#endif\n\tif (failure) {\n\t\tzend_bailout();\n\t}\n}", "label_name": "CWE-119", "label": 26} {"code": "ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)\n{\n\tzend_object_handle handle = Z_OBJ_HANDLE_P(zobject);\n\tzend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];\n\t\n\tobj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;\n\tobj_bucket->destructor_called = 1;\n}", "label_name": "CWE-119", "label": 26} {"code": "void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)\n{\n\tint lastBorder;\n\t/* Seek left */\n\tint leftLimit = -1, rightLimit;\n\tint i, restoreAlphaBlending = 0;\n\n\tif (border < 0) {\n\t\t/* Refuse to fill to a non-solid border */\n\t\treturn;\n\t}\n\n\tif (!im->trueColor) {\n\t\tif ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\trestoreAlphaBlending = 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\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 = restoreAlphaBlending;\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 = 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\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\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 = restoreAlphaBlending;\n}", "label_name": "CWE-119", "label": 26} {"code": "horizontalDifference8(unsigned char *ip, int n, int stride, \n\tunsigned short *wp, uint16 *From8)\n{\n register int r1, g1, b1, a1, r2, g2, b2, a2, mask;\n\n#undef\t CLAMP\n#define CLAMP(v) (From8[(v)])\n\n mask = CODE_MASK;\n if (n >= stride) {\n\tif (stride == 3) {\n\t r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);\n\t b2 = wp[2] = CLAMP(ip[2]);\n\t n -= 3;\n\t while (n > 0) {\n\t\tn -= 3;\n\t\tr1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;\n\t\twp += 3;\n\t\tip += 3;\n\t }\n\t} else if (stride == 4) {\n\t r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);\n\t b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);\n\t n -= 4;\n\t while (n > 0) {\n\t\tn -= 4;\n\t\tr1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;\n\t\tg1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;\n\t\tb1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;\n\t\ta1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;\n\t\twp += 4;\n\t\tip += 4;\n\t }\n\t} else {\n\t wp += n + stride - 1;\t/* point to last one */\n\t ip += n + stride - 1;\t/* point to last one */\n\t n -= stride;\n\t while (n > 0) {\n\t\tREPEAT(stride, wp[0] = 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] = CLAMP(ip[0]); wp--; ip--)\n\t}\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n\ttmsize_t stride = PredictorState(tif)->stride;\n\tuint16* wp = (uint16*) cp0;\n\ttmsize_t wc = cc / 2;\n\n\tassert((cc%(2*stride))==0);\n\n\tif (wc > stride) {\n\t\twc -= stride;\n\t\tdo {\n\t\t\tREPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)\n\t\t\twc -= stride;\n\t\t} while (wc > 0);\n\t}\n}", "label_name": "CWE-119", "label": 26} {"code": "PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)\n{\n\tstatic const char module[] = \"PredictorEncodeTile\";\n\tTIFFPredictorState *sp = PredictorState(tif);\n uint8 *working_copy;\n\ttmsize_t cc = cc0, rowsize;\n\tunsigned char* bp;\n int result_code;\n\n\tassert(sp != NULL);\n\tassert(sp->encodepfunc != NULL);\n\tassert(sp->encodetile != NULL);\n\n /* \n * Do predictor manipulation in a working buffer to avoid altering\n * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965\n */\n working_copy = (uint8*) _TIFFmalloc(cc0);\n if( working_copy == NULL )\n {\n TIFFErrorExt(tif->tif_clientdata, module, \n \"Out of memory allocating \" TIFF_SSIZE_FORMAT \" byte temp buffer.\",\n cc0 );\n return 0;\n }\n memcpy( working_copy, bp0, cc0 );\n bp = working_copy;\n\n\trowsize = sp->rowsize;\n\tassert(rowsize > 0);\n\tassert((cc0%rowsize)==0);\n\twhile (cc > 0) {\n\t\t(*sp->encodepfunc)(tif, bp, rowsize);\n\t\tcc -= rowsize;\n\t\tbp += rowsize;\n\t}\n\tresult_code = (*sp->encodetile)(tif, working_copy, cc0, s);\n\n _TIFFfree( working_copy );\n\n return result_code;\n}", "label_name": "CWE-119", "label": 26} {"code": "static int rename_in_ns(int pid, char *oldname, char **newnamep)\n{\n\tint fd = -1, ofd = -1, ret, ifindex = -1;\n\tbool grab_newname = false;\n\n\tofd = lxc_preserve_ns(getpid(), \"net\");\n\tif (ofd < 0) {\n\t\tfprintf(stderr, \"Failed opening network namespace path for '%d'.\", getpid());\n\t\treturn -1;\n\t}\n\n\tfd = lxc_preserve_ns(pid, \"net\");\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Failed opening network namespace path for '%d'.\", pid);\n\t\treturn -1;\n\t}\n\n\tif (setns(fd, 0) < 0) {\n\t\tfprintf(stderr, \"setns to container network namespace\\n\");\n\t\tgoto out_err;\n\t}\n\tclose(fd); fd = -1;\n\tif (!*newnamep) {\n\t\tgrab_newname = true;\n\t\t*newnamep = VETH_DEF_NAME;\n\t\tif (!(ifindex = if_nametoindex(oldname))) {\n\t\t\tfprintf(stderr, \"failed to get netdev index\\n\");\n\t\t\tgoto out_err;\n\t\t}\n\t}\n\tif ((ret = lxc_netdev_rename_by_name(oldname, *newnamep)) < 0) {\n\t\tfprintf(stderr, \"Error %d renaming netdev %s to %s in container\\n\", ret, oldname, *newnamep);\n\t\tgoto out_err;\n\t}\n\tif (grab_newname) {\n\t\tchar ifname[IFNAMSIZ], *namep = ifname;\n\t\tif (!if_indextoname(ifindex, namep)) {\n\t\t\tfprintf(stderr, \"Failed to get new netdev name\\n\");\n\t\t\tgoto out_err;\n\t\t}\n\t\t*newnamep = strdup(namep);\n\t\tif (!*newnamep)\n\t\t\tgoto out_err;\n\t}\n\tif (setns(ofd, 0) < 0) {\n\t\tfprintf(stderr, \"Error returning to original netns\\n\");\n\t\tclose(ofd);\n\t\treturn -1;\n\t}\n\tclose(ofd);\n\n\treturn 0;\n\nout_err:\n\tif (ofd >= 0)\n\t\tclose(ofd);\n\tif (setns(ofd, 0) < 0)\n\t\tfprintf(stderr, \"Error returning to original network namespace\\n\");\n\tif (fd >= 0)\n\t\tclose(fd);\n\treturn -1;\n}", "label_name": "CWE-862", "label": 8} {"code": "cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)\n{\n\tsize_t i, j;\n\tcdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size);\n\n\tDPRINTF((\"Chain:\"));\n\tfor (j = i = 0; sid >= 0; i++, j++) {\n\t\tDPRINTF((\" %d\", sid));\n\t\tif (j >= CDF_LOOP_LIMIT) {\n\t\t\tDPRINTF((\"Counting chain loop limit\"));\n\t\t\terrno = EFTYPE;\n\t\t\treturn (size_t)-1;\n\t\t}\n\t\tif (sid > maxsector) {\n\t\t\tDPRINTF((\"Sector %d > %d\\n\", sid, maxsector));\n\t\t\terrno = EFTYPE;\n\t\t\treturn (size_t)-1;\n\t\t}\n\t\tsid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);\n\t}\n\tif (i == 0) {\n\t\tDPRINTF((\" none, sid: %d\\n\", sid));\n\t\treturn (size_t)-1;\n\n\t}\n\tDPRINTF((\"\\n\"));\n\treturn i;\n}", "label_name": "CWE-20", "label": 0} {"code": "static void gdCtxPrintf(gdIOCtx * out, const char *format, ...)\n{\n\tchar buf[4096];\n\tint len;\n\tva_list args;\n\n\tva_start(args, format);\n\tlen = vsnprintf(buf, sizeof(buf)-1, format, args);\n\tva_end(args);\n\tout->putBuf(out, buf, len);\n}", "label_name": "CWE-119", "label": 26} {"code": "PGTYPESinterval_from_asc(char *str, char **endptr)\n{\n\tinterval *result = NULL;\n\tfsec_t\t\tfsec;\n\tstruct tm\ttt,\n\t\t\t *tm = &tt;\n\tint\t\t\tdtype;\n\tint\t\t\tnf;\n\tchar\t *field[MAXDATEFIELDS];\n\tint\t\t\tftype[MAXDATEFIELDS];\n\tchar\t\tlowstr[MAXDATELEN + MAXDATEFIELDS];\n\tchar\t *realptr;\n\tchar\t **ptr = (endptr != NULL) ? endptr : &realptr;\n\n\ttm->tm_year = 0;\n\ttm->tm_mon = 0;\n\ttm->tm_mday = 0;\n\ttm->tm_hour = 0;\n\ttm->tm_min = 0;\n\ttm->tm_sec = 0;\n\tfsec = 0;\n\n\tif (strlen(str) >= sizeof(lowstr))\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\treturn NULL;\n\t}\n\n\tif (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 ||\n\t\t(DecodeInterval(field, ftype, nf, &dtype, tm, &fsec) != 0 &&\n\t\t DecodeISO8601Interval(str, &dtype, tm, &fsec) != 0))\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\treturn NULL;\n\t}\n\n\tresult = (interval *) pgtypes_alloc(sizeof(interval));\n\tif (!result)\n\t\treturn NULL;\n\n\tif (dtype != DTK_DELTA)\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\tfree(result);\n\t\treturn NULL;\n\t}\n\n\tif (tm2interval(tm, fsec, result) != 0)\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\tfree(result);\n\t\treturn NULL;\n\t}\n\n\terrno = 0;\n\treturn result;\n}", "label_name": "CWE-119", "label": 26} {"code": "int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)\n{\n char *str;\n ASN1_TIME atm;\n long offset;\n char buff1[24], buff2[24], *p;\n int i, j;\n\n p = buff1;\n i = ctm->length;\n str = (char *)ctm->data;\n if (ctm->type == V_ASN1_UTCTIME) {\n if ((i < 11) || (i > 17))\n return 0;\n memcpy(p, str, 10);\n p += 10;\n str += 10;\n } else {\n if (i < 13)\n return 0;\n memcpy(p, str, 12);\n p += 12;\n str += 12;\n }\n\n if ((*str == 'Z') || (*str == '-') || (*str == '+')) {\n *(p++) = '0';\n *(p++) = '0';\n } else {\n *(p++) = *(str++);\n *(p++) = *(str++);\n /* Skip any fractional seconds... */\n if (*str == '.') {\n str++;\n while ((*str >= '0') && (*str <= '9'))\n str++;\n }\n\n }\n *(p++) = 'Z';\n *(p++) = '\\0';\n\n if (*str == 'Z')\n offset = 0;\n else {\n if ((*str != '+') && (*str != '-'))\n return 0;\n offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;\n offset += (str[3] - '0') * 10 + (str[4] - '0');\n if (*str == '-')\n offset = -offset;\n }\n atm.type = ctm->type;\n atm.flags = 0;\n atm.length = sizeof(buff2);\n atm.data = (unsigned char *)buff2;\n\n if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)\n return 0;\n\n if (ctm->type == V_ASN1_UTCTIME) {\n i = (buff1[0] - '0') * 10 + (buff1[1] - '0');\n if (i < 50)\n i += 100; /* cf. RFC 2459 */\n j = (buff2[0] - '0') * 10 + (buff2[1] - '0');\n if (j < 50)\n j += 100;\n\n if (i < j)\n return -1;\n if (i > j)\n return 1;\n }\n i = strcmp(buff1, buff2);\n if (i == 0) /* wait a second then return younger :-) */\n return -1;\n else\n return i;\n}", "label_name": "CWE-119", "label": 26} {"code": "ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes)\n{\n int x;\n int chunk;\n UINT8* out;\n UINT8* ptr;\n\n ptr = buf;\n\n chunk = 3 * state->xsize;\n\n for (;;) {\n\n\t/* We need data for two full lines before we can do anything */\n\tif (bytes < chunk)\n\t return ptr - buf;\n\n\t/* Unpack first line */\n\tout = state->buffer;\n\tfor (x = 0; x < state->xsize; x++) {\n\t out[0] = ptr[x];\n\t out[1] = ptr[(x+4*state->xsize)/2];\n\t out[2] = ptr[(x+5*state->xsize)/2];\n\t out += 4;\n\t}\n\n\tstate->shuffle((UINT8*) im->image[state->y],\n\t\t state->buffer, state->xsize);\n\n\tif (++state->y >= state->ysize)\n\t return -1; /* This can hardly happen */\n\n\t/* Unpack second line */\n\tout = state->buffer;\n\tfor (x = 0; x < state->xsize; x++) {\n\t out[0] = ptr[x+state->xsize];\n\t out[1] = ptr[(x+4*state->xsize)/2];\n\t out[2] = ptr[(x+5*state->xsize)/2];\n\t out += 4;\n\t}\n\n\tstate->shuffle((UINT8*) im->image[state->y],\n\t\t state->buffer, state->xsize);\n\n\tif (++state->y >= state->ysize)\n\t return -1;\n\n\tptr += chunk;\n\tbytes -= chunk;\n\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)\n{\n\tchar *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;\n\tchar url_address[256], port[6];\n\tint url_len, port_len = 0;\n\n\t*sockaddr_url = url;\n\turl_begin = strstr(url, \"//\");\n\tif (!url_begin)\n\t\turl_begin = url;\n\telse\n\t\turl_begin += 2;\n\n\t/* Look for numeric ipv6 entries */\n\tipv6_begin = strstr(url_begin, \"[\");\n\tipv6_end = strstr(url_begin, \"]\");\n\tif (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)\n\t\turl_end = strstr(ipv6_end, \":\");\n\telse\n\t\turl_end = strstr(url_begin, \":\");\n\tif (url_end) {\n\t\turl_len = url_end - url_begin;\n\t\tport_len = strlen(url_begin) - url_len - 1;\n\t\tif (port_len < 1)\n\t\t\treturn false;\n\t\tport_start = url_end + 1;\n\t} else\n\t\turl_len = strlen(url_begin);\n\n\tif (url_len < 1)\n\t\treturn false;\n\n\tsprintf(url_address, \"%.*s\", url_len, url_begin);\n\n\tif (port_len) {\n\t\tchar *slash;\n\n\t\tsnprintf(port, 6, \"%.*s\", port_len, port_start);\n\t\tslash = strchr(port, '/');\n\t\tif (slash)\n\t\t\t*slash = '\\0';\n\t} else\n\t\tstrcpy(port, \"80\");\n\n\t*sockaddr_port = strdup(port);\n\t*sockaddr_url = strdup(url_address);\n\n\treturn true;\n}", "label_name": "CWE-119", "label": 26} {"code": "ppp_hdlc(netdissect_options *ndo,\n const u_char *p, int length)\n{\n\tu_char *b, *s, *t, c;\n\tint i, proto;\n\tconst void *se;\n\n if (length <= 0)\n return;\n\n\tb = (uint8_t *)malloc(length);\n\tif (b == NULL)\n\t\treturn;\n\n\t/*\n\t * Unescape all the data into a temporary, private, buffer.\n\t * Do this so that we dont overwrite the original packet\n\t * contents.\n\t */\n\tfor (s = (u_char *)p, t = b, i = length; i > 0; i--) {\n\t\tc = *s++;\n\t\tif (c == 0x7d) {\n\t\t\tif (i > 1) {\n\t\t\t\ti--;\n\t\t\t\tc = *s++ ^ 0x20;\n\t\t\t} else\n\t\t\t\tcontinue;\n\t\t}\n\t\t*t++ = c;\n\t}\n\n\tse = ndo->ndo_snapend;\n\tndo->ndo_snapend = t;\n\tlength = t - b;\n\n /* now lets guess about the payload codepoint format */\n if (length < 1)\n goto trunc;\n proto = *b; /* start with a one-octet codepoint guess */\n\n switch (proto) {\n case PPP_IP:\n\t\tip_print(ndo, b + 1, length - 1);\n\t\tgoto cleanup;\n case PPP_IPV6:\n\t\tip6_print(ndo, b + 1, length - 1);\n\t\tgoto cleanup;\n default: /* no luck - try next guess */\n\t\tbreak;\n }\n\n if (length < 2)\n goto trunc;\n proto = EXTRACT_16BITS(b); /* next guess - load two octets */\n\n switch (proto) {\n case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */\n if (length < 4)\n goto trunc;\n proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */\n handle_ppp(ndo, proto, b + 4, length - 4);\n break;\n default: /* last guess - proto must be a PPP proto-id */\n handle_ppp(ndo, proto, b + 2, length - 2);\n break;\n }\n\ncleanup:\n\tndo->ndo_snapend = se;\n\tfree(b);\n return;\n\ntrunc:\n\tndo->ndo_snapend = se;\n\tfree(b);\n\tND_PRINT((ndo, \"[|ppp]\"));\n}", "label_name": "CWE-119", "label": 26} {"code": "flac_read_loop (SF_PRIVATE *psf, unsigned len)\n{\tFLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;\n\n\tpflac->pos = 0 ;\n\tpflac->len = len ;\n\tpflac->remain = len ;\n\n\t/* First copy data that has already been decoded and buffered. */\n\tif (pflac->frame != NULL && pflac->bufferpos < pflac->frame->header.blocksize)\n\t\tflac_buffer_copy (psf) ;\n\n\t/* Decode some more. */\n\twhile (pflac->pos < pflac->len)\n\t{\tif (FLAC__stream_decoder_process_single (pflac->fsd) == 0)\n\t\t\tbreak ;\n\t\tif (FLAC__stream_decoder_get_state (pflac->fsd) >= FLAC__STREAM_DECODER_END_OF_STREAM)\n\t\t\tbreak ;\n\t\t} ;\n\n\tpflac->ptr = NULL ;\n\n\treturn pflac->pos ;\n} /* flac_read_loop */", "label_name": "CWE-119", "label": 26} {"code": "header_put_byte (SF_PRIVATE *psf, char x)\n{\tif (psf->headindex < SIGNED_SIZEOF (psf->header) - 1)\n\t\tpsf->header [psf->headindex++] = x ;\n} /* header_put_byte */", "label_name": "CWE-119", "label": 26} {"code": "static void finish_object(struct object *obj,\n\t\t\t struct strbuf *path, const char *name,\n\t\t\t void *cb_data)\n{\n\tstruct rev_list_info *info = cb_data;\n\tif (obj->type == OBJ_BLOB && !has_object_file(&obj->oid))\n\t\tdie(\"missing blob object '%s'\", oid_to_hex(&obj->oid));\n\tif (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT)\n\t\tparse_object(obj->oid.hash);\n}", "label_name": "CWE-119", "label": 26} {"code": "static void process_tree(struct rev_info *revs,\n\t\t\t struct tree *tree,\n\t\t\t show_object_fn show,\n\t\t\t struct strbuf *base,\n\t\t\t const char *name,\n\t\t\t void *cb_data)\n{\n\tstruct object *obj = &tree->object;\n\tstruct tree_desc desc;\n\tstruct name_entry entry;\n\tenum interesting match = revs->diffopt.pathspec.nr == 0 ?\n\t\tall_entries_interesting: entry_not_interesting;\n\tint baselen = base->len;\n\n\tif (!revs->tree_objects)\n\t\treturn;\n\tif (!obj)\n\t\tdie(\"bad tree object\");\n\tif (obj->flags & (UNINTERESTING | SEEN))\n\t\treturn;\n\tif (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {\n\t\tif (revs->ignore_missing_links)\n\t\t\treturn;\n\t\tdie(\"bad tree object %s\", oid_to_hex(&obj->oid));\n\t}\n\n\tobj->flags |= SEEN;\n\tshow(obj, base, name, cb_data);\n\n\tstrbuf_addstr(base, name);\n\tif (base->len)\n\t\tstrbuf_addch(base, '/');\n\n\tinit_tree_desc(&desc, tree->buffer, tree->size);\n\n\twhile (tree_entry(&desc, &entry)) {\n\t\tif (match != all_entries_interesting) {\n\t\t\tmatch = tree_entry_interesting(&entry, base, 0,\n\t\t\t\t\t\t &revs->diffopt.pathspec);\n\t\t\tif (match == all_entries_not_interesting)\n\t\t\t\tbreak;\n\t\t\tif (match == entry_not_interesting)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tif (S_ISDIR(entry.mode))\n\t\t\tprocess_tree(revs,\n\t\t\t\t lookup_tree(entry.sha1),\n\t\t\t\t show, base, entry.path,\n\t\t\t\t cb_data);\n\t\telse if (S_ISGITLINK(entry.mode))\n\t\t\tprocess_gitlink(revs, entry.sha1,\n\t\t\t\t\tshow, base, entry.path,\n\t\t\t\t\tcb_data);\n\t\telse\n\t\t\tprocess_blob(revs,\n\t\t\t\t lookup_blob(entry.sha1),\n\t\t\t\t show, base, entry.path,\n\t\t\t\t cb_data);\n\t}\n\tstrbuf_setlen(base, baselen);\n\tfree_tree_buffer(tree);\n}", "label_name": "CWE-119", "label": 26} {"code": "static void mark_object(struct object *obj, struct strbuf *path,\n\t\t\tconst char *name, void *data)\n{\n\tupdate_progress(data);\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 unsigned char *read_chunk(struct mschm_decompressor_p *self,\n\t\t\t\t struct mschmd_header *chm,\n\t\t\t\t struct mspack_file *fh,\n\t\t\t\t unsigned int chunk_num)\n{\n struct mspack_system *sys = self->system;\n unsigned char *buf;\n\n /* check arguments - most are already checked by chmd_fast_find */\n if (chunk_num > chm->num_chunks) return NULL;\n \n /* ensure chunk cache is available */\n if (!chm->chunk_cache) {\n\tsize_t size = sizeof(unsigned char *) * chm->num_chunks;\n\tif (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {\n\t self->error = MSPACK_ERR_NOMEMORY;\n\t return NULL;\n\t}\n\tmemset(chm->chunk_cache, 0, size);\n }\n\n /* try to answer out of chunk cache */\n if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];\n\n /* need to read chunk - allocate memory for it */\n if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {\n\tself->error = MSPACK_ERR_NOMEMORY;\n\treturn NULL;\n }\n\n /* seek to block and read it */\n if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),\n\t\t MSPACK_SYS_SEEK_START))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {\n\tself->error = MSPACK_ERR_READ;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* check the signature. Is is PMGL or PMGI? */\n if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&\n\t ((buf[3] == 0x4C) || (buf[3] == 0x49))))\n {\n\tself->error = MSPACK_ERR_SEEK;\n\tsys->free(buf);\n\treturn NULL;\n }\n\n /* all OK. Store chunk in cache and return it */\n return chm->chunk_cache[chunk_num] = buf;\n}", "label_name": "CWE-20", "label": 0} {"code": "int pgx_validate(jas_stream_t *in)\n{\n\tuchar buf[PGX_MAGICLEN];\n\tuint_fast32_t magic;\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Did we read enough data? */\n\tif (n < PGX_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Compute the signature value. */\n\tmagic = (buf[0] << 8) | buf[1];\n\n\t/* Ensure that the signature is correct for this format. */\n\tif (magic != PGX_MAGIC) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0} {"code": "int ras_validate(jas_stream_t *in)\n{\n\tuchar buf[RAS_MAGICLEN];\n\tint i;\n\tint n;\n\tuint_fast32_t magic;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Did we read enough data? */\n\tif (n < RAS_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\tmagic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) |\n\t (JAS_CAST(uint_fast32_t, buf[1]) << 16) |\n\t (JAS_CAST(uint_fast32_t, buf[2]) << 8) |\n\t buf[3];\n\n\t/* Is the signature correct for the Sun Rasterfile format? */\n\tif (magic != RAS_MAGIC) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0} {"code": "void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,\n int stride, int parity)\n{\n\n\tint bufsize = JPC_CEILDIVPOW2(numrows, 1);\n\tjpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];\n\tjpc_fix_t *buf = splitbuf;\n\tjpc_fix_t *srcptr;\n\tjpc_fix_t *dstptr;\n\tregister jpc_fix_t *srcptr2;\n\tregister jpc_fix_t *dstptr2;\n\tregister int n;\n\tregister int i;\n\tint m;\n\tint hstartcol;\n\n\t/* Get a buffer. */\n\tif (bufsize > QMFB_SPLITBUFSIZE) {\n\t\tif (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {\n\t\t\t/* We have no choice but to commit suicide in this case. */\n\t\t\tabort();\n\t\t}\n\t}\n\n\tif (numrows >= 2) {\n\t\thstartcol = (numrows + 1 - parity) >> 1;\n\t\t// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);\n\t\tm = numrows - hstartcol;\n\n\t\t/* Save the samples destined for the highpass channel. */\n\t\tn = m;\n\t\tdstptr = buf;\n\t\tsrcptr = &a[(1 - parity) * stride];\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += numcols;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the appropriate samples into the lowpass channel. */\n\t\tdstptr = &a[(1 - parity) * stride];\n\t\tsrcptr = &a[(2 - parity) * stride];\n\t\tn = numrows - m - (!parity);\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += stride << 1;\n\t\t}\n\t\t/* Copy the saved samples into the highpass channel. */\n\t\tdstptr = &a[hstartcol * stride];\n\t\tsrcptr = buf;\n\t\tn = m;\n\t\twhile (n-- > 0) {\n\t\t\tdstptr2 = dstptr;\n\t\t\tsrcptr2 = srcptr;\n\t\t\tfor (i = 0; i < numcols; ++i) {\n\t\t\t\t*dstptr2 = *srcptr2;\n\t\t\t\t++dstptr2;\n\t\t\t\t++srcptr2;\n\t\t\t}\n\t\t\tdstptr += stride;\n\t\t\tsrcptr += numcols;\n\t\t}\n\t}\n\n\t/* If the split buffer was allocated on the heap, free this memory. */\n\tif (buf != splitbuf) {\n\t\tjas_free(buf);\n\t}\n\n}", "label_name": "CWE-119", "label": 26} {"code": "fm_mgr_config_init\r\n(\r\n\t\t\t\t\tOUT\tp_fm_config_conx_hdlt\t\t*p_hdl,\r\n\t\t\t\tIN\t\tint\t\t\t\t\t\t\tinstance,\r\n\tOPTIONAL\tIN\t\tchar\t\t\t\t\t\t*rem_address,\r\n\tOPTIONAL\tIN\t\tchar\t\t\t\t\t\t*community\r\n)\r\n{\r\n\tfm_config_conx_hdl *hdl;\r\n\tfm_mgr_config_errno_t res = FM_CONF_OK;\r\n\r\n\r\n\tif ( (hdl = calloc(1,sizeof(fm_config_conx_hdl))) == NULL )\r\n\t{\r\n\t\tres = FM_CONF_NO_MEM;\r\n\t\tgoto cleanup;\r\n\t}\r\n\r\n\thdl->instance = instance;\r\n\r\n\t*p_hdl = hdl;\r\n\r\n\t\t// connect to the snmp agent via localhost?\r\n\tif(!rem_address || (strcmp(rem_address,\"localhost\") == 0))\r\n\t{\r\n\t\tif ( fm_mgr_config_mgr_connect(hdl, FM_MGR_SM) == FM_CONF_INIT_ERR )\r\n\t\t{\r\n\t\t\tres = FM_CONF_INIT_ERR;\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\r\n\t\tif ( fm_mgr_config_mgr_connect(hdl, FM_MGR_PM) == FM_CONF_INIT_ERR )\r\n\t\t{\r\n\t\t\tres = FM_CONF_INIT_ERR;\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\r\n\t\tif ( fm_mgr_config_mgr_connect(hdl, FM_MGR_FE) == FM_CONF_INIT_ERR )\r\n\t\t{\r\n\t\t\tres = FM_CONF_INIT_ERR;\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\treturn res;\r\n\r\n\r\n\tcleanup:\r\n\r\n\tif ( hdl ) {\r\n\t\tfree(hdl);\r\n\t\thdl = NULL;\r\n\t}\r\n\r\n\treturn res;\r\n}\r", "label_name": "CWE-362", "label": 18} {"code": "CAMLprim value caml_alloc_dummy(value size)\n{\n mlsize_t wosize = Int_val(size);\n\n if (wosize == 0) return Atom(0);\n return caml_alloc (wosize, 0);\n}", "label_name": "CWE-200", "label": 10} {"code": "ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)\n{\n\tstruct session_state *state = ssh->state;\n\tstruct sshbuf *b = NULL;\n\tint r;\n\tconst u_char *inblob, *outblob;\n\tsize_t inl, outl;\n\n\tif ((r = sshbuf_froms(m, &b)) != 0)\n\t\tgoto out;\n\tif ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||\n\t (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)\n\t\tgoto out;\n\tif (inl == 0)\n\t\tstate->compression_in_started = 0;\n\telse if (inl != sizeof(state->compression_in_stream)) {\n\t\tr = SSH_ERR_INTERNAL_ERROR;\n\t\tgoto out;\n\t} else {\n\t\tstate->compression_in_started = 1;\n\t\tmemcpy(&state->compression_in_stream, inblob, inl);\n\t}\n\tif (outl == 0)\n\t\tstate->compression_out_started = 0;\n\telse if (outl != sizeof(state->compression_out_stream)) {\n\t\tr = SSH_ERR_INTERNAL_ERROR;\n\t\tgoto out;\n\t} else {\n\t\tstate->compression_out_started = 1;\n\t\tmemcpy(&state->compression_out_stream, outblob, outl);\n\t}\n\tr = 0;\n out:\n\tsshbuf_free(b);\n\treturn r;\n}", "label_name": "CWE-119", "label": 26} {"code": "privsep_preauth(Authctxt *authctxt)\n{\n\tint status, r;\n\tpid_t pid;\n\tstruct ssh_sandbox *box = NULL;\n\n\t/* Set up unprivileged child process to deal with network data */\n\tpmonitor = monitor_init();\n\t/* Store a pointer to the kex for later rekeying */\n\tpmonitor->m_pkex = &active_state->kex;\n\n\tif (use_privsep == PRIVSEP_ON)\n\t\tbox = ssh_sandbox_init();\n\tpid = fork();\n\tif (pid == -1) {\n\t\tfatal(\"fork of unprivileged child failed\");\n\t} else if (pid != 0) {\n\t\tdebug2(\"Network child is on pid %ld\", (long)pid);\n\n\t\tpmonitor->m_pid = pid;\n\t\tif (have_agent) {\n\t\t\tr = ssh_get_authentication_socket(&auth_sock);\n\t\t\tif (r != 0) {\n\t\t\t\terror(\"Could not get agent socket: %s\",\n\t\t\t\t ssh_err(r));\n\t\t\t\thave_agent = 0;\n\t\t\t}\n\t\t}\n\t\tif (box != NULL)\n\t\t\tssh_sandbox_parent_preauth(box, pid);\n\t\tmonitor_child_preauth(authctxt, pmonitor);\n\n\t\t/* Sync memory */\n\t\tmonitor_sync(pmonitor);\n\n\t\t/* Wait for the child's exit status */\n\t\twhile (waitpid(pid, &status, 0) < 0) {\n\t\t\tif (errno == EINTR)\n\t\t\t\tcontinue;\n\t\t\tpmonitor->m_pid = -1;\n\t\t\tfatal(\"%s: waitpid: %s\", __func__, strerror(errno));\n\t\t}\n\t\tprivsep_is_preauth = 0;\n\t\tpmonitor->m_pid = -1;\n\t\tif (WIFEXITED(status)) {\n\t\t\tif (WEXITSTATUS(status) != 0)\n\t\t\t\tfatal(\"%s: preauth child exited with status %d\",\n\t\t\t\t __func__, WEXITSTATUS(status));\n\t\t} else if (WIFSIGNALED(status))\n\t\t\tfatal(\"%s: preauth child terminated by signal %d\",\n\t\t\t __func__, WTERMSIG(status));\n\t\tif (box != NULL)\n\t\t\tssh_sandbox_parent_finish(box);\n\t\treturn 1;\n\t} else {\n\t\t/* child */\n\t\tclose(pmonitor->m_sendfd);\n\t\tclose(pmonitor->m_log_recvfd);\n\n\t\t/* Arrange for logging to be sent to the monitor */\n\t\tset_log_handler(mm_log_handler, pmonitor);\n\n\t\tprivsep_preauth_child();\n\t\tsetproctitle(\"%s\", \"[net]\");\n\t\tif (box != NULL)\n\t\t\tssh_sandbox_child(box);\n\n\t\treturn 0;\n\t}\n}", "label_name": "CWE-119", "label": 26} {"code": "static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,\n gint64 *data_offset)\n{\n\tgint64\t\toffset;\n\tint\t\tpkt_len;\n\tchar\t\tline[NETSCREEN_LINE_LENGTH];\n\tchar\t\tcap_int[NETSCREEN_MAX_INT_NAME_LENGTH];\n\tgboolean\tcap_dir;\n\tchar\t\tcap_dst[13];\n\n\t/* Find the next packet */\n\toffset = netscreen_seek_next_packet(wth, err, err_info, line);\n\tif (offset < 0)\n\t\treturn FALSE;\n\n\t/* Parse the header */\n\tpkt_len = parse_netscreen_rec_hdr(&wth->phdr, line, cap_int, &cap_dir,\n\t cap_dst, err, err_info);\n\tif (pkt_len == -1)\n\t\treturn FALSE;\n\n\t/* Convert the ASCII hex dump to binary data, and fill in some\n\t struct wtap_pkthdr fields */\n\tif (!parse_netscreen_hex_dump(wth->fh, pkt_len, cap_int,\n\t cap_dst, &wth->phdr, wth->frame_buffer, err, err_info))\n\t\treturn FALSE;\n\n\t/*\n\t * If the per-file encapsulation isn't known, set it to this\n\t * packet's encapsulation.\n\t *\n\t * If it *is* known, and it isn't this packet's encapsulation,\n\t * set it to WTAP_ENCAP_PER_PACKET, as this file doesn't\n\t * have a single encapsulation for all packets in the file.\n\t */\n\tif (wth->file_encap == WTAP_ENCAP_UNKNOWN)\n\t\twth->file_encap = wth->phdr.pkt_encap;\n\telse {\n\t\tif (wth->file_encap != wth->phdr.pkt_encap)\n\t\t\twth->file_encap = WTAP_ENCAP_PER_PACKET;\n\t}\n\n\t*data_offset = offset;\n\treturn TRUE;\n}", "label_name": "CWE-20", "label": 0} {"code": "grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf,\n struct grub_ext4_extent_header *ext_block,\n grub_uint32_t fileblock)\n{\n struct grub_ext4_extent_idx *index;\n\n while (1)\n {\n int i;\n grub_disk_addr_t block;\n\n index = (struct grub_ext4_extent_idx *) (ext_block + 1);\n\n if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC)\n return 0;\n\n if (ext_block->depth == 0)\n return ext_block;\n\n for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++)\n {\n if (fileblock < grub_le_to_cpu32(index[i].block))\n break;\n }\n\n if (--i < 0)\n return 0;\n\n block = grub_le_to_cpu16 (index[i].leaf_hi);\n block = (block << 32) + grub_le_to_cpu32 (index[i].leaf);\n if (grub_disk_read (data->disk,\n block << LOG2_EXT2_BLOCK_SIZE (data),\n 0, EXT2_BLOCK_SIZE(data), buf))\n return 0;\n\n ext_block = (struct grub_ext4_extent_header *) buf;\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "static void send(node_t *node, node_t *child, byte *fout) {\n\tif (node->parent) {\n\t\tsend(node->parent, node, fout);\n\t}\n\tif (child) {\n\t\tif (node->right == child) {\n\t\t\tadd_bit(1, fout);\n\t\t} else {\n\t\t\tadd_bit(0, fout);\n\t\t}\n\t}\n}", "label_name": "CWE-119", "label": 26} {"code": "static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)\n{\n unsigned long len;\n GET_STATE(self);\n Check_Type(object_nl, T_STRING);\n len = RSTRING_LEN(object_nl);\n if (len == 0) {\n if (state->object_nl) {\n ruby_xfree(state->object_nl);\n state->object_nl = NULL;\n }\n } else {\n if (state->object_nl) ruby_xfree(state->object_nl);\n state->object_nl = strdup(RSTRING_PTR(object_nl));\n state->object_nl_len = len;\n }\n return Qnil;\n}", "label_name": "CWE-119", "label": 26} {"code": "static int db_dict_iter_lookup_key_values(struct db_dict_value_iter *iter)\n{\n\tstruct db_dict_iter_key *key;\n\tstring_t *path;\n\tconst char *error;\n\tint ret;\n\n\t/* sort the keys so that we'll first lookup the keys without\n\t default value. if their lookup fails, the user doesn't exist. */\n\tarray_sort(&iter->keys, db_dict_iter_key_cmp);\n\n\tpath = t_str_new(128);\n\tstr_append(path, DICT_PATH_SHARED);\n\n\tarray_foreach_modifiable(&iter->keys, key) {\n\t\tif (!key->used)\n\t\t\tcontinue;\n\n\t\tstr_truncate(path, strlen(DICT_PATH_SHARED));\n\t\tret = var_expand(path, key->key->key, iter->var_expand_table, &error);\n\t\tif (ret <= 0) {\n\t\t\tauth_request_log_error(iter->auth_request, AUTH_SUBSYS_DB,\n\t\t\t\t\"Failed to expand key %s: %s\", key->key->key, error);\n\t\t\treturn -1;\n\t\t}\n\t\tret = dict_lookup(iter->conn->dict, iter->pool,\n\t\t\t\t str_c(path), &key->value, &error);\n\t\tif (ret > 0) {\n\t\t\tauth_request_log_debug(iter->auth_request, AUTH_SUBSYS_DB,\n\t\t\t\t\t \"Lookup: %s = %s\", str_c(path),\n\t\t\t\t\t key->value);\n\t\t} else if (ret < 0) {\n\t\t\tauth_request_log_error(iter->auth_request, AUTH_SUBSYS_DB,\n\t\t\t\t\"Failed to lookup key %s: %s\", str_c(path), error);\n\t\t\treturn -1;\n\t\t} else if (key->key->default_value != NULL) {\n\t\t\tauth_request_log_debug(iter->auth_request, AUTH_SUBSYS_DB,\n\t\t\t\t\"Lookup: %s not found, using default value %s\",\n\t\t\t\tstr_c(path), key->key->default_value);\n\t\t\tkey->value = key->key->default_value;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}", "label_name": "CWE-20", "label": 0} {"code": "static pyc_object *get_set_object(RBuffer *buffer) {\n\tpyc_object *ret = NULL;\n\tbool error = false;\n\tut32 n = get_ut32 (buffer, &error);\n\tif (n > ST32_MAX) {\n\t\teprintf (\"bad marshal data (set size out of range)\\n\");\n\t\treturn NULL;\n\t}\n\tif (error) {\n\t\treturn NULL;\n\t}\n\tret = get_array_object_generic (buffer, n);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->type = TYPE_SET;\n\treturn ret;\n}", "label_name": "CWE-119", "label": 26} {"code": "void CLASS foveon_load_camf()\n{\n unsigned type, wide, high, i, j, row, col, diff;\n ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];\n\n fseek (ifp, meta_offset, SEEK_SET);\n type = get4(); get4(); get4();\n wide = get4();\n high = get4();\n if (type == 2) {\n fread (meta_data, 1, meta_length, ifp);\n for (i=0; i < meta_length; i++) {\n high = (high * 1597 + 51749) % 244944;\n wide = high * (INT64) 301593171 >> 24;\n meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;\n }\n } else if (type == 4) {\n free (meta_data);\n meta_data = (char *) malloc (meta_length = wide*high*3/2);\n merror (meta_data, \"foveon_load_camf()\");\n foveon_huff (huff);\n get4();\n getbits(-1);\n for (j=row=0; row < high; row++) {\n for (col=0; col < wide; col++) {\n\tdiff = ljpeg_diff(huff);\n\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\n\telse hpred[col & 1] += diff;\n\tif (col & 1) {\n\t meta_data[j++] = hpred[0] >> 4;\n\t meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;\n\t meta_data[j++] = hpred[1];\n }\n }\n }\n } else\n fprintf (stderr,_(\"%s has unknown CAMF type %d.\\n\"), ifname, type);\n}", "label_name": "CWE-119", "label": 26} {"code": "static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)\n{\n int err;\n#ifdef WOLFSSL_SMALL_STACK\n byte* buf;\n#else\n byte buf[ECC_MAXSIZE_GEN];\n#endif\n\n#ifdef WOLFSSL_SMALL_STACK\n buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);\n if (buf == NULL)\n return MEMORY_E;\n#endif\n\n /*generate 8 extra bytes to mitigate bias from the modulo operation below*/\n /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/\n size += 8;\n\n /* make up random string */\n err = wc_RNG_GenerateBlock(rng, buf, size);\n\n /* load random buffer data into k */\n if (err == 0)\n err = mp_read_unsigned_bin(k, (byte*)buf, size);\n\n /* quick sanity check to make sure we're not dealing with a 0 key */\n if (err == MP_OKAY) {\n if (mp_iszero(k) == MP_YES)\n err = MP_ZERO_E;\n }\n\n /* the key should be smaller than the order of base point */\n if (err == MP_OKAY) {\n if (mp_cmp(k, order) != MP_LT) {\n err = mp_mod(k, order, k);\n }\n }\n\n ForceZero(buf, ECC_MAXSIZE);\n#ifdef WOLFSSL_SMALL_STACK\n XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);\n#endif\n\n return err;\n}", "label_name": "CWE-200", "label": 10} {"code": "static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)\n{\n\tcac_private_data_t * priv = CAC_DATA(card);\n\n\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);\n if (card->serialnr.len) {\n *serial = card->serialnr;\n SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n }\n\tif (priv->cac_id_len) {\n\t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);\n}", "label_name": "CWE-119", "label": 26} {"code": "static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)\n{\n\tcac_private_data_t * priv = CAC_DATA(card);\n\n\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);\n if (card->serialnr.len) {\n *serial = card->serialnr;\n SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n }\n\tif (priv->cac_id_len) {\n\t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);\n}", "label_name": "CWE-119", "label": 26} {"code": "decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)\n{\n\tsize_t cipher_len;\n\tsize_t i;\n\tunsigned char iv[16] = { 0 };\n\tunsigned char plaintext[4096] = { 0 };\n\tepass2003_exdata *exdata = NULL;\n\n\tif (!card->drv_data) \n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\n\texdata = (epass2003_exdata *)card->drv_data;\n\n\t/* no cipher */\n\tif (in[0] == 0x99)\n\t\treturn 0;\n\n\t/* parse cipher length */\n\tif (0x01 == in[2] && 0x82 != in[1]) {\n\t\tcipher_len = in[1];\n\t\ti = 3;\n\t}\n\telse if (0x01 == in[3] && 0x81 == in[1]) {\n\t\tcipher_len = in[2];\n\t\ti = 4;\n\t}\n\telse if (0x01 == in[4] && 0x82 == in[1]) {\n\t\tcipher_len = in[2] * 0x100;\n\t\tcipher_len += in[3];\n\t\ti = 5;\n\t}\n\telse {\n\t\treturn -1;\n\t}\n\n\tif (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)\n\t\treturn -1;\n\n\t/* decrypt */\n\tif (KEY_TYPE_AES == exdata->smtype)\n\t\taes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\telse\n\t\tdes3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\n\t/* unpadding */\n\twhile (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))\n\t\tcipher_len--;\n\n\tif (2 == cipher_len)\n\t\treturn -1;\n\n\tmemcpy(out, plaintext, cipher_len - 2);\n\t*out_len = cipher_len - 2;\n\treturn 0;\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 int read_public_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\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(\"I1012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select public key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\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 public 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_public_key(p, keysize, rsa);\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": "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": "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 int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len)\n{\n\tu8 buf[CAC_MAX_SIZE];\n\tu8 *out_ptr;\n\tsize_t size = 0;\n\tsize_t left = 0;\n\tsize_t len, next_len;\n\tsc_apdu_t apdu;\n\tint r = SC_SUCCESS;\n\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);\n\t/* get the size */\n\tsize = left = *out_buf ? *out_len : sizeof(buf);\n\tout_ptr = *out_buf ? *out_buf : buf;\n\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 );\n\tnext_len = MIN(left, 100);\n\tfor (; left > 0; left -= len, out_ptr += len) {\n\t\tlen = next_len;\n\t\tapdu.resp = out_ptr;\n\t\tapdu.le = len;\n\t\tapdu.resplen = left;\n\t\tr = sc_transmit_apdu(card, &apdu);\n\t\tif (r < 0) {\n\t\t\tbreak;\n\t\t}\n\t\tif (apdu.resplen == 0) {\n\t\t\tr = SC_ERROR_INTERNAL;\n\t\t\tbreak;\n\t\t}\n\t\t/* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */\n\t\tif (apdu.sw1 != 0x63 || apdu.sw2 < 1) {\n\t\t\t/* we've either finished reading, or hit an error, break */\n\t\t\tr = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\t\tleft -= len;\n\t\t\tbreak;\n\t\t}\n\t\tnext_len = MIN(left, apdu.sw2);\n\t}\n\tif (r < 0) {\n\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);\n\t}\n\tr = size - left;\n\tif (*out_buf == NULL) {\n\t\t*out_buf = malloc(r);\n\t\tif (*out_buf == NULL) {\n\t\t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,\n\t\t\t\tSC_ERROR_OUT_OF_MEMORY);\n\t\t}\n\t\tmemcpy(*out_buf, buf, r);\n\t}\n\t*out_len = r;\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);\n}", "label_name": "CWE-119", "label": 26} {"code": "char* _single_string_alloc_and_copy( LPCWSTR in )\n{\n char *chr;\n int len = 0;\n\n if ( !in )\n {\n return in;\n }\n\n while ( in[ len ] != 0 )\n {\n len ++;\n }\n\n chr = malloc( len + 1 );\n\n len = 0;\n while ( in[ len ] != 0 )\n {\n chr[ len ] = 0xFF & in[ len ];\n len ++;\n }\n chr[ len ++ ] = '\\0';\n\n return chr;\n}", "label_name": "CWE-119", "label": 26} {"code": "do_prefetch_tables (const void *gcmM, size_t gcmM_size)\n{\n prefetch_table(gcmM, gcmM_size);\n prefetch_table(gcmR, sizeof(gcmR));\n}", "label_name": "CWE-668", "label": 7} {"code": "prepenv(const struct rule *rule)\n{\n\tstatic const char *safeset[] = {\n\t\t\"DISPLAY\", \"HOME\", \"LOGNAME\", \"MAIL\",\n\t\t\"PATH\", \"TERM\", \"USER\", \"USERNAME\",\n\t\tNULL\n\t};\n\tstruct env *env;\n\n\tenv = createenv(rule);\n\n\t/* if we started with blank, fill some defaults then apply rules */\n\tif (!(rule->options & KEEPENV))\n\t\tfillenv(env, safeset);\n\tif (rule->envlist)\n\t\tfillenv(env, rule->envlist);\n\n\treturn flattenenv(env);\n}", "label_name": "CWE-909", "label": 25} {"code": "void dhcpAddOption(DhcpMessage *message, uint8_t optionCode,\n const void *optionValue, size_t optionLen)\n{\n size_t n;\n DhcpOption *option;\n\n //Point to the very first option\n n = 0;\n\n //Parse DHCP options\n while(1)\n {\n //Point to the current option\n option = (DhcpOption *) (message->options + n);\n\n //End option detected?\n if(option->code == DHCP_OPT_END)\n break;\n\n //Jump to next the next option\n n += sizeof(DhcpOption) + option->length;\n }\n\n //Sanity check\n if(optionLen <= UINT8_MAX)\n {\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Option code\n option->code = optionCode;\n //Option length\n option->length = (uint8_t) optionLen;\n //Option value\n osMemcpy(option->value, optionValue, optionLen);\n\n //Jump to next the next option\n n += sizeof(DhcpOption) + option->length;\n\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Always terminate the options field with 255\n option->code = DHCP_OPT_END;\n }\n}", "label_name": "CWE-20", "label": 0} {"code": "DhcpOption *dhcpGetOption(const DhcpMessage *message,\n size_t length, uint8_t optionCode)\n{\n uint_t i;\n DhcpOption *option;\n\n //Make sure the DHCP header is valid\n if(length < sizeof(DhcpMessage))\n return NULL;\n //Get the length of the options field\n length -= sizeof(DhcpMessage);\n\n //Parse DHCP options\n for(i = 0; i < length; i++)\n {\n //Point to the current option\n option = (DhcpOption *) (message->options + i);\n\n //Pad option detected?\n if(option->code == DHCP_OPT_PAD)\n continue;\n //End option detected?\n if(option->code == DHCP_OPT_END)\n break;\n //Check option length\n if((i + 1) >= length || (i + 1 + option->length) >= length)\n break;\n\n //Current option code matches the specified one?\n if(option->code == optionCode)\n return option;\n\n //Jump to the next option\n i += option->length + 1;\n }\n\n //Specified option code not found\n return NULL;\n}", "label_name": "CWE-20", "label": 0} {"code": "bool_t enc28j60IrqHandler(NetInterface *interface)\n{\n bool_t flag;\n uint8_t status;\n\n //This flag will be set if a higher priority task must be woken\n flag = FALSE;\n\n //Clear the INTIE bit, immediately after an interrupt event\n enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_INTIE);\n\n //Read interrupt status register\n status = enc28j60ReadReg(interface, ENC28J60_REG_EIR);\n\n //Link status change?\n if((status & EIR_LINKIF) != 0)\n {\n //Disable LINKIE interrupt\n enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_LINKIE);\n\n //Set event flag\n interface->nicEvent = TRUE;\n //Notify the TCP/IP stack of the event\n flag |= osSetEventFromIsr(&netEvent);\n }\n\n //Packet received?\n if((status & EIR_PKTIF) != 0)\n {\n //Disable PKTIE interrupt\n enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_PKTIE);\n\n //Set event flag\n interface->nicEvent = TRUE;\n //Notify the TCP/IP stack of the event\n flag |= osSetEventFromIsr(&netEvent);\n }\n\n //Packet transmission complete?\n if((status & (EIR_TXIF | EIE_TXERIE)) != 0)\n {\n //Clear interrupt flags\n enc28j60ClearBit(interface, ENC28J60_REG_EIR, EIR_TXIF | EIE_TXERIE);\n\n //Notify the TCP/IP stack that the transmitter is ready to send\n flag |= osSetEventFromIsr(&interface->nicTxEvent);\n }\n\n //Once the interrupt has been serviced, the INTIE bit\n //is set again to re-enable interrupts\n enc28j60SetBit(interface, ENC28J60_REG_EIE, EIE_INTIE);\n\n //A higher priority task must be woken?\n return flag;\n}", "label_name": "CWE-20", "label": 0} {"code": "error_t ksz8851UpdateMacAddrFilter(NetInterface *interface)\n{\n uint_t i;\n uint_t k;\n uint32_t crc;\n uint16_t hashTable[4];\n MacFilterEntry *entry;\n\n //Debug message\n TRACE_DEBUG(\"Updating MAC filter...\\r\\n\");\n\n //Clear hash table\n osMemset(hashTable, 0, sizeof(hashTable));\n\n //The MAC address filter contains the list of MAC addresses to accept\n //when receiving an Ethernet frame\n for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)\n {\n //Point to the current entry\n entry = &interface->macAddrFilter[i];\n\n //Valid entry?\n if(entry->refCount > 0)\n {\n //Compute CRC over the current MAC address\n crc = ksz8851CalcCrc(&entry->addr, sizeof(MacAddr));\n //Calculate the corresponding index in the table\n k = (crc >> 26) & 0x3F;\n //Update hash table contents\n hashTable[k / 16] |= (1 << (k % 16));\n }\n }\n\n //Write the hash table to the KSZ8851 controller\n ksz8851WriteReg(interface, KSZ8851_REG_MAHTR0, hashTable[0]);\n ksz8851WriteReg(interface, KSZ8851_REG_MAHTR1, hashTable[1]);\n ksz8851WriteReg(interface, KSZ8851_REG_MAHTR2, hashTable[2]);\n ksz8851WriteReg(interface, KSZ8851_REG_MAHTR3, hashTable[3]);\n\n //Debug message\n TRACE_DEBUG(\" MAHTR0 = %04\" PRIX16 \"\\r\\n\", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR0));\n TRACE_DEBUG(\" MAHTR1 = %04\" PRIX16 \"\\r\\n\", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR1));\n TRACE_DEBUG(\" MAHTR2 = %04\" PRIX16 \"\\r\\n\", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR2));\n TRACE_DEBUG(\" MAHTR3 = %04\" PRIX16 \"\\r\\n\", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR3));\n\n //Successful processing\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": 0} {"code": "uint16_t lpc546xxEthReadPhyReg(uint8_t opcode, uint8_t phyAddr,\n uint8_t regAddr)\n{\n uint16_t data;\n uint32_t temp;\n\n //Valid opcode?\n if(opcode == SMI_OPCODE_READ)\n {\n //Take care not to alter MDC clock configuration\n temp = ENET->MAC_MDIO_ADDR & ENET_MAC_MDIO_ADDR_CR_MASK;\n //Set up a read operation\n temp |= ENET_MAC_MDIO_ADDR_MOC(3) | ENET_MAC_MDIO_ADDR_MB_MASK;\n //PHY address\n temp |= ENET_MAC_MDIO_ADDR_PA(phyAddr);\n //Register address\n temp |= ENET_MAC_MDIO_ADDR_RDA(regAddr);\n\n //Start a read operation\n ENET->MAC_MDIO_ADDR = temp;\n //Wait for the read to complete\n while((ENET->MAC_MDIO_ADDR & ENET_MAC_MDIO_ADDR_MB_MASK) != 0)\n {\n }\n\n //Get register value\n data = ENET->MAC_MDIO_DATA & ENET_MAC_MDIO_DATA_MD_MASK;\n }\n else\n {\n //The MAC peripheral only supports standard Clause 22 opcodes\n data = 0;\n }\n\n //Return the value of the PHY register\n return data;\n}", "label_name": "CWE-20", "label": 0} {"code": "error_t lpc546xxEthUpdateMacAddrFilter(NetInterface *interface)\n{\n uint_t i;\n bool_t acceptMulticast;\n\n //Debug message\n TRACE_DEBUG(\"Updating MAC filter...\\r\\n\");\n\n //Set the MAC address of the station\n ENET->MAC_ADDR_LOW = interface->macAddr.w[0] | (interface->macAddr.w[1] << 16);\n ENET->MAC_ADDR_HIGH = interface->macAddr.w[2];\n\n //This flag will be set if multicast addresses should be accepted\n acceptMulticast = FALSE;\n\n //The MAC address filter contains the list of MAC addresses to accept\n //when receiving an Ethernet frame\n for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)\n {\n //Valid entry?\n if(interface->macAddrFilter[i].refCount > 0)\n {\n //Accept multicast addresses\n acceptMulticast = TRUE;\n //We are done\n break;\n }\n }\n\n //Enable the reception of multicast frames if necessary\n if(acceptMulticast)\n {\n ENET->MAC_FRAME_FILTER |= ENET_MAC_FRAME_FILTER_PM_MASK;\n }\n else\n {\n ENET->MAC_FRAME_FILTER &= ~ENET_MAC_FRAME_FILTER_PM_MASK;\n }\n\n //Successful processing\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": 0} {"code": "error_t lpc546xxEthReceivePacket(NetInterface *interface)\n{\n error_t error;\n size_t n;\n NetRxAncillary ancillary;\n\n //The current buffer is available for reading?\n if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_OWN) == 0)\n {\n //FD and LD flags should be set\n if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_FD) != 0 &&\n (rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_LD) != 0)\n {\n //Make sure no error occurred\n if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_ES) == 0)\n {\n //Retrieve the length of the frame\n n = rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_PL;\n //Limit the number of data to read\n n = MIN(n, LPC546XX_ETH_RX_BUFFER_SIZE);\n\n //Additional options can be passed to the stack along with the packet\n ancillary = NET_DEFAULT_RX_ANCILLARY;\n\n //Pass the packet to the upper layer\n nicProcessPacket(interface, rxBuffer[rxIndex], n, &ancillary);\n\n //Valid packet received\n error = NO_ERROR;\n }\n else\n {\n //The received packet contains an error\n error = ERROR_INVALID_PACKET;\n }\n }\n else\n {\n //The packet is not valid\n error = ERROR_INVALID_PACKET;\n }\n\n //Set the start address of the buffer\n rxDmaDesc[rxIndex].rdes0 = (uint32_t) rxBuffer[rxIndex];\n //Give the ownership of the descriptor back to the DMA\n rxDmaDesc[rxIndex].rdes3 = ENET_RDES3_OWN | ENET_RDES3_IOC | ENET_RDES3_BUF1V;\n\n //Increment index and wrap around if necessary\n if(++rxIndex >= LPC546XX_ETH_RX_BUFFER_COUNT)\n {\n rxIndex = 0;\n }\n }\n else\n {\n //No more data in the receive buffer\n error = ERROR_BUFFER_EMPTY;\n }\n\n //Clear RBU flag to resume processing\n ENET->DMA_CH[0].DMA_CHX_STAT = ENET_DMA_CH_DMA_CHX_STAT_RBU_MASK;\n //Instruct the DMA to poll the receive descriptor list\n ENET->DMA_CH[0].DMA_CHX_RXDESC_TAIL_PTR = 0;\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": 0} {"code": "error_t tja1101Init(NetInterface *interface)\n{\n uint16_t value;\n\n //Debug message\n TRACE_INFO(\"Initializing TJA1101...\\r\\n\");\n\n //Undefined PHY address?\n if(interface->phyAddr >= 32)\n {\n //Use the default address\n interface->phyAddr = TJA1101_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 tja1101WritePhyReg(interface, TJA1101_BASIC_CTRL,\n TJA1101_BASIC_CTRL_RESET);\n\n //Wait for the reset to complete\n while(tja1101ReadPhyReg(interface, TJA1101_BASIC_CTRL) &\n TJA1101_BASIC_CTRL_RESET)\n {\n }\n\n //Dump PHY registers for debugging purpose\n tja1101DumpPhyReg(interface);\n\n //Enable configuration register access\n value = tja1101ReadPhyReg(interface, TJA1101_EXTENDED_CTRL);\n value |= TJA1101_EXTENDED_CTRL_CONFIG_EN;\n tja1101WritePhyReg(interface, TJA1101_EXTENDED_CTRL, value);\n\n //Select RMII mode (25MHz XTAL)\n value = tja1101ReadPhyReg(interface, TJA1101_CONFIG1);\n value &= ~TJA1101_CONFIG1_MII_MODE;\n value |= TJA1101_CONFIG1_MII_MODE_RMII_25MHZ;\n tja1101WritePhyReg(interface, TJA1101_CONFIG1, value);\n\n //The PHY is configured for autonomous operation\n value = tja1101ReadPhyReg(interface, TJA1101_COMM_CTRL);\n value |= TJA1101_COMM_CTRL_AUTO_OP;\n tja1101WritePhyReg(interface, TJA1101_COMM_CTRL, 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": " def to_yaml(self, data, options=None):\n \"\"\"\n Given some Python data, produces YAML output.\n \"\"\"\n options = options or {}\n \n if yaml is None:\n raise ImproperlyConfigured(\"Usage of the YAML aspects requires yaml.\")\n \n return yaml.dump(self.to_simple(data, options))", "label_name": "CWE-20", "label": 0} {"code": "def check_password(password, encoded, setter=None, preferred='default'):\n \"\"\"\n Returns a boolean of whether the raw password matches the three\n part encoded digest.\n\n If setter is specified, it'll be called when you need to\n regenerate the password.\n \"\"\"\n if password is None or not is_password_usable(encoded):\n return False\n\n preferred = get_hasher(preferred)\n hasher = identify_hasher(encoded)\n\n must_update = hasher.algorithm != preferred.algorithm\n if not must_update:\n must_update = preferred.must_update(encoded)\n is_correct = hasher.verify(password, encoded)\n if setter and is_correct and must_update:\n setter(password)\n return is_correct", "label_name": "CWE-200", "label": 10} {"code": " def test_filename(self):\n tmpname = mktemp('', 'mmap')\n fp = memmap(tmpname, dtype=self.dtype, mode='w+',\n shape=self.shape)\n abspath = os.path.abspath(tmpname)\n fp[:] = self.data[:]\n self.assertEqual(abspath, fp.filename)\n b = fp[:1]\n self.assertEqual(abspath, b.filename)\n del b\n del fp\n os.unlink(tmpname)", "label_name": "CWE-20", "label": 0} {"code": " def tearDown(self):\n if os.path.isfile(self.filename):\n os.unlink(self.filename)", "label_name": "CWE-20", "label": 0} {"code": " def visit_Call(self, call):\n if call.func.id in INVALID_CALLS:\n raise Exception(\"invalid function: %s\" % call.func.id)", "label_name": "CWE-74", "label": 1} {"code": " def _expand(self, key_material):\n output = [b\"\"]\n counter = 1\n\n while (self._algorithm.digest_size // 8) * len(output) < self._length:\n h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)\n h.update(output[-1])\n h.update(self._info)\n h.update(six.int2byte(counter))\n output.append(h.finalize())\n counter += 1\n\n return b\"\".join(output)[:self._length]", "label_name": "CWE-20", "label": 0} {"code": " def _update_load_status(self, ok: bool) -> None:\n \"\"\"Update the load status after a page finished loading.\n\n Needs to be called by subclasses to trigger a load status update, e.g.\n as a response to a loadFinished signal.\n \"\"\"\n if ok and not self._has_ssl_errors:\n if self.url().scheme() == 'https':\n self._set_load_status(usertypes.LoadStatus.success_https)\n else:\n self._set_load_status(usertypes.LoadStatus.success)\n elif ok:\n self._set_load_status(usertypes.LoadStatus.warn)\n else:\n self._set_load_status(usertypes.LoadStatus.error)", "label_name": "CWE-684", "label": 35} {"code": " async def on_send_leave_request(\n self, origin: str, content: JsonDict, room_id: str", "label_name": "CWE-400", "label": 2} {"code": " async def on_GET(self, origin, content, query, context):\n return await self.handler.on_context_state_request(\n origin,\n context,\n parse_string_from_args(query, \"event_id\", None, required=False),\n )", "label_name": "CWE-400", "label": 2} {"code": " async def on_GET(self, origin, _content, query, context, user_id):\n \"\"\"\n Args:\n origin (unicode): The authenticated server_name of the calling server\n\n _content (None): (GETs don't have bodies)\n\n query (dict[bytes, list[bytes]]): Query params from the request.\n\n **kwargs (dict[unicode, unicode]): the dict mapping keys to path\n components as specified in the path match regexp.\n\n Returns:\n Tuple[int, object]: (response code, response object)\n \"\"\"\n versions = query.get(b\"ver\")\n if versions is not None:\n supported_versions = [v.decode(\"utf-8\") for v in versions]\n else:\n supported_versions = [\"1\"]\n\n content = await self.handler.on_make_join_request(\n origin, context, user_id, supported_versions=supported_versions\n )\n return 200, content", "label_name": "CWE-400", "label": 2} {"code": "def _is_javascript_scheme(s):\n if _is_image_dataurl(s):\n return None\n return _is_possibly_malicious_scheme(s)", "label_name": "CWE-74", "label": 1} {"code": " def __setstate__(self, state):\n \"\"\"Restore from pickled state.\"\"\"\n self.__dict__ = state\n self._lock = threading.Lock()\n self._descriptor_cache = weakref.WeakKeyDictionary()\n self._key_for_call_stats = self._get_key_for_call_stats()", "label_name": "CWE-667", "label": 27} {"code": " def testValuesInVariable(self):\n indices = constant_op.constant([[1]], dtype=dtypes.int64)\n values = variables.Variable([1], trainable=False, dtype=dtypes.float32)\n shape = constant_op.constant([1], dtype=dtypes.int64)\n\n sp_input = sparse_tensor.SparseTensor(indices, values, shape)\n sp_output = sparse_ops.sparse_add(sp_input, sp_input)\n\n with test_util.force_cpu():\n self.evaluate(variables.global_variables_initializer())\n output = self.evaluate(sp_output)\n self.assertAllEqual(output.values, [2])", "label_name": "CWE-20", "label": 0} {"code": " def skip(self, type):\n if type == TType.STOP:\n return\n elif type == TType.BOOL:\n self.readBool()\n elif type == TType.BYTE:\n self.readByte()\n elif type == TType.I16:\n self.readI16()\n elif type == TType.I32:\n self.readI32()\n elif type == TType.I64:\n self.readI64()\n elif type == TType.DOUBLE:\n self.readDouble()\n elif type == TType.FLOAT:\n self.readFloat()\n elif type == TType.STRING:\n self.readString()\n elif type == TType.STRUCT:\n name = self.readStructBegin()\n while True:\n (name, type, id) = self.readFieldBegin()\n if type == TType.STOP:\n break\n self.skip(type)\n self.readFieldEnd()\n self.readStructEnd()\n elif type == TType.MAP:\n (ktype, vtype, size) = self.readMapBegin()\n for _ in range(size):\n self.skip(ktype)\n self.skip(vtype)\n self.readMapEnd()\n elif type == TType.SET:\n (etype, size) = self.readSetBegin()\n for _ in range(size):\n self.skip(etype)\n self.readSetEnd()\n elif type == TType.LIST:\n (etype, size) = self.readListBegin()\n for _ in range(size):\n self.skip(etype)\n self.readListEnd()", "label_name": "CWE-755", "label": 21} {"code": "def _new_fixed_fetch(validate_certificate):\n\n def fixed_fetch(\n url,\n payload=None,\n method=\"GET\",\n headers={},\n allow_truncated=False,\n follow_redirects=True,\n deadline=None,\n ):\n return fetch(\n url,\n payload=payload,\n method=method,\n headers=headers,\n allow_truncated=allow_truncated,\n follow_redirects=follow_redirects,\n deadline=deadline,\n validate_certificate=validate_certificate,\n )\n\n return fixed_fetch", "label_name": "CWE-400", "label": 2} {"code": " def _request(\n self,\n conn,\n host,\n absolute_uri,\n request_uri,\n method,\n body,\n headers,\n redirections,\n cachekey,", "label_name": "CWE-400", "label": 2} {"code": "def _normalize_headers(headers):\n return dict(\n [\n (key.lower(), NORMALIZE_SPACE.sub(value, \" \").strip())\n for (key, value) in headers.iteritems()\n ]\n )", "label_name": "CWE-400", "label": 2} {"code": "def _parse_cache_control(headers):\n retval = {}\n if \"cache-control\" in headers:\n parts = headers[\"cache-control\"].split(\",\")\n parts_with_args = [\n tuple([x.strip().lower() for x in part.split(\"=\", 1)])\n for part in parts\n if -1 != part.find(\"=\")\n ]\n parts_wo_args = [\n (name.strip().lower(), 1) for name in parts if -1 == name.find(\"=\")\n ]\n retval = dict(parts_with_args + parts_wo_args)\n return retval", "label_name": "CWE-400", "label": 2} {"code": " def __init__(self, desc, response, content):\n self.response = response\n self.content = content\n HttpLib2Error.__init__(self, desc)", "label_name": "CWE-400", "label": 2} {"code": "def _parse_cache_control(headers):\n retval = {}\n if \"cache-control\" in headers:\n parts = headers[\"cache-control\"].split(\",\")\n parts_with_args = [\n tuple([x.strip().lower() for x in part.split(\"=\", 1)])\n for part in parts\n if -1 != part.find(\"=\")\n ]\n parts_wo_args = [\n (name.strip().lower(), 1) for name in parts if -1 == name.find(\"=\")\n ]\n retval = dict(parts_with_args + parts_wo_args)\n return retval", "label_name": "CWE-400", "label": 2} {"code": "def _updateCache(request_headers, response_headers, content, cache, cachekey):\n if cachekey:\n cc = _parse_cache_control(request_headers)\n cc_response = _parse_cache_control(response_headers)\n if \"no-store\" in cc or \"no-store\" in cc_response:\n cache.delete(cachekey)\n else:\n info = email.message.Message()\n for key, value in response_headers.items():\n if key not in [\"status\", \"content-encoding\", \"transfer-encoding\"]:\n info[key] = value\n\n # Add annotations to the cache to indicate what headers\n # are variant for this request.\n vary = response_headers.get(\"vary\", None)\n if vary:\n vary_headers = vary.lower().replace(\" \", \"\").split(\",\")\n for header in vary_headers:\n key = \"-varied-%s\" % header\n try:\n info[key] = request_headers[header]\n except KeyError:\n pass\n\n status = response_headers.status\n if status == 304:\n status = 200\n\n status_header = \"status: %d\\r\\n\" % status\n\n try:\n header_str = info.as_string()\n except UnicodeEncodeError:\n setattr(info, \"_write_headers\", _bind_write_headers(info))\n header_str = info.as_string()\n\n header_str = re.sub(\"\\r(?!\\n)|(? Result[UserInfo]:\n \"\"\"Obtains the Access Token from the Authorization Header\"\"\"\n token_str = get_auth_token(request)\n if token_str is None:\n return Error(\n code=ErrorCode.INVALID_REQUEST,\n errors=[\"unable to find authorization token\"],\n )\n\n # This token has already been verified by the azure authentication layer\n token = jwt.decode(token_str, options={\"verify_signature\": False})\n\n application_id = UUID(token[\"appid\"]) if \"appid\" in token else None\n object_id = UUID(token[\"oid\"]) if \"oid\" in token else None\n upn = token.get(\"upn\")\n return UserInfo(application_id=application_id, object_id=object_id, upn=upn)", "label_name": "CWE-346", "label": 16} {"code": "def main() -> None:\n formatter = argparse.ArgumentDefaultsHelpFormatter\n parser = argparse.ArgumentParser(formatter_class=formatter)\n parser.add_argument(\"resource_group\")\n parser.add_argument(\"storage_account\")\n parser.add_argument(\"admins\", type=UUID, nargs=\"*\")\n args = parser.parse_args()\n\n client = get_client_from_cli_profile(StorageManagementClient)\n storage_keys = client.storage_accounts.list_keys(\n args.resource_group, args.storage_account\n )\n table_service = TableService(\n account_name=args.storage_account, account_key=storage_keys.keys[0].value\n )\n update_admins(table_service, args.resource_group, args.admins)", "label_name": "CWE-285", "label": 23} {"code": "def test_bad_request(settings):\n class BadRequestSpider(ResponseSpider):\n custom_settings = {'HTTPERROR_ALLOW_ALL': True}\n\n def start_requests(self):\n yield SplashRequest(self.url, endpoint='execute',\n args={'lua_source': DEFAULT_SCRIPT, 'wait': 'bar'})\n\n class GoodRequestSpider(ResponseSpider):\n custom_settings = {'HTTPERROR_ALLOW_ALL': True}\n\n def start_requests(self):\n yield SplashRequest(self.url, endpoint='execute',\n args={'lua_source': DEFAULT_SCRIPT})\n\n\n items, url, crawler = yield crawl_items(BadRequestSpider, HelloWorld,\n settings)\n resp = items[0]['response']\n assert resp.status == 400\n assert resp.splash_response_status == 400\n\n items, url, crawler = yield crawl_items(GoodRequestSpider, Http400Resource,\n settings)\n resp = items[0]['response']\n assert resp.status == 400\n assert resp.splash_response_status == 200", "label_name": "CWE-200", "label": 10} {"code": "def test_adjust_timeout():\n mw = _get_mw()\n req1 = scrapy.Request(\"http://example.com\", meta = {\n 'splash': {'args': {'timeout': 60, 'html': 1}},\n\n # download_timeout is always present,\n # it is set by DownloadTimeoutMiddleware\n 'download_timeout': 30,\n })\n req1 = mw.process_request(req1, None)\n assert req1.meta['download_timeout'] > 60\n\n req2 = scrapy.Request(\"http://example.com\", meta = {\n 'splash': {'args': {'html': 1}},\n 'download_timeout': 30,\n })\n req2 = mw.process_request(req2, None)\n assert req2.meta['download_timeout'] == 30", "label_name": "CWE-200", "label": 10} {"code": " def render_GET(self, request):\n request.setHeader(b'content-type', to_bytes(self.content_type))\n for name, value in self.extra_headers.items():\n request.setHeader(to_bytes(name), to_bytes(value))\n request.setResponseCode(self.status_code)\n return to_bytes(self.html)", "label_name": "CWE-200", "label": 10} {"code": "def temppath():\n path = tempfile.mktemp()\n try:\n yield path\n finally:\n if os.path.exists(path):\n if os.path.isfile(path):\n os.remove(path)\n else:\n shutil.rmtree(path)", "label_name": "CWE-668", "label": 7} {"code": " def test_session_with_cookie_followed_by_another_header(self, httpbin):\n \"\"\"\n Make sure headers don\u2019t get mutated \u2014 \n \"\"\"\n self.start_session(httpbin)\n session_data = {\n \"headers\": {\n \"cookie\": \"...\",\n \"zzz\": \"...\"\n }\n }\n session_path = self.config_dir / 'session-data.json'\n session_path.write_text(json.dumps(session_data))\n r = http('--session', str(session_path), 'GET', httpbin.url + '/get',\n env=self.env())\n assert HTTP_OK in r\n assert 'Zzz' in r", "label_name": "CWE-200", "label": 10} {"code": " def test_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin):\n session = Session(self.config_dir)\n session['cookies'] = initial_cookie\n session.remove_cookies([expired_cookie])\n assert expired_cookie not in session.cookies", "label_name": "CWE-200", "label": 10} {"code": "def needs_clamp(t, encoding):\n if encoding not in (Encoding.ABI, Encoding.JSON_ABI):\n return False\n if isinstance(t, (ByteArrayLike, DArrayType)):\n if encoding == Encoding.JSON_ABI:\n # don't have bytestring size bound from json, don't clamp\n return False\n return True\n if isinstance(t, BaseType) and t.typ not in (\"int256\", \"uint256\", \"bytes32\"):\n return True\n if isinstance(t, SArrayType):\n return needs_clamp(t.subtype, encoding)\n if isinstance(t, TupleLike):\n return any(needs_clamp(m, encoding) for m in t.tuple_members())\n return False", "label_name": "CWE-119", "label": 26} {"code": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String encoding = request.getHeader(\"Accept-Encoding\");\n boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf(\"gzip\") > -1);\n SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute(\"terminal\");\n if (st == null || st.isClosed()) {\n st = new SessionTerminal(getCommandProcessor(), getThreadIO());\n request.getSession().setAttribute(\"terminal\", st);\n }\n String str = request.getParameter(\"k\");\n String f = request.getParameter(\"f\");\n String dump = st.handle(str, f != null && f.length() > 0);\n if (dump != null) {\n if (supportsGzip) {\n response.setHeader(\"Content-Encoding\", \"gzip\");\n response.setHeader(\"Content-Type\", \"text/html\");\n try {\n GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());\n gzos.write(dump.getBytes());\n gzos.close();\n } catch (IOException ie) {\n LOG.info(\"Exception writing response: \", ie);\n }\n } else {\n response.getOutputStream().write(dump.getBytes());\n }\n }\n }", "label_name": "CWE-287", "label": 4} {"code": " public void setExpirationTime(int expirationTime) {\r\n this.expirationTime = expirationTime;\r\n }\r", "label_name": "CWE-200", "label": 10} {"code": " protected ObjectStreamClass readClassDescriptor()\n throws IOException, ClassNotFoundException {\n int type = read();\n if (type < 0) {\n throw new EOFException();\n }\n switch (type) {\n case ThrowableObjectOutputStream.TYPE_EXCEPTION:\n return ObjectStreamClass.lookup(Exception.class);\n case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:\n return ObjectStreamClass.lookup(StackTraceElement.class);\n case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:\n return super.readClassDescriptor();\n case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:\n String className = readUTF();\n Class clazz = loadClass(className);\n return ObjectStreamClass.lookup(clazz);\n default:\n throw new StreamCorruptedException(\n \"Unexpected class descriptor type: \" + type);\n }\n }", "label_name": "CWE-74", "label": 1} {"code": "\tpublic static SecretKey decryptCEK(final SecretKey kek,\n\t\t\t\t\t final byte[] iv,\n\t\t\t\t\t final AuthenticatedCipherText authEncrCEK,\n\t\t\t\t\t final int keyLength,\n\t\t\t\t\t final Provider provider)\n\t\tthrows JOSEException {\n\n\t\tbyte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);\n\n\t\tif (ByteUtils.bitLength(keyBytes) != keyLength) {\n\n\t\t\tthrow new KeyLengthException(\"CEK key length mismatch: \" + ByteUtils.bitLength(keyBytes) + \" != \" + keyLength);\n\t\t}\n\n\t\treturn new SecretKeySpec(keyBytes, \"AES\");\n\t}", "label_name": "CWE-345", "label": 22} {"code": " private String loginUser(URI hostUri) throws Throwable {\n URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);\n // wait for factory availability\n this.host.waitForReplicatedFactoryServiceAvailable(usersLink);\n\n String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);\n URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);\n AuthenticationRequest login = new AuthenticationRequest();\n login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;\n\n String[] authToken = new String[1];\n authToken[0] = null;\n\n Date exp = this.host.getTestExpiration();\n while (new Date().before(exp)) {\n Operation loginPost = Operation.createPost(loginUri)\n .setBody(login)\n .addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)\n .forceRemote()\n .setCompletion((op, ex) -> {\n if (ex != null) {\n this.host.completeIteration();\n return;\n }\n authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);\n this.host.completeIteration();\n });\n\n this.host.testStart(1);\n this.host.send(loginPost);\n this.host.testWait();\n\n if (authToken[0] != null) {\n break;\n }\n Thread.sleep(250);\n }\n\n if (new Date().after(exp)) {\n throw new TimeoutException();\n }\n\n assertNotNull(authToken[0]);\n\n return authToken[0];\n }", "label_name": "CWE-732", "label": 13} {"code": "\tprivate void displayVerificationWarningDialog(final Contact contact, final Invite invite) {\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(this);\n\t\tbuilder.setTitle(R.string.verify_omemo_keys);\n\t\tView view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);\n\t\tfinal CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);\n\t\tTextView warning = view.findViewById(R.id.warning);\n\t\twarning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));\n\t\tbuilder.setView(view);\n\t\tbuilder.setPositiveButton(R.string.confirm, (dialog, which) -> {\n\t\t\tif (isTrustedSource.isChecked() && invite.hasFingerprints()) {\n\t\t\t\txmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());\n\t\t\t}\n\t\t\tswitchToConversation(contact, invite.getBody());\n\t\t});\n\t\tbuilder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());\n\t\tAlertDialog dialog = builder.create();\n\t\tdialog.setCanceledOnTouchOutside(false);\n\t\tdialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());\n\t\tdialog.show();\n\t}", "label_name": "CWE-200", "label": 10} {"code": "\tpublic void checkAccess(ThreadGroup g) {\n\t\tif (RobocodeProperties.isSecurityOff()) {\n\t\t\treturn;\n\t\t}\n\t\tThread c = Thread.currentThread();\n\n\t\tif (isSafeThread(c)) {\n\t\t\treturn;\n\t\t}\n\t\tsuper.checkAccess(g);\n\n\t\tfinal ThreadGroup cg = c.getThreadGroup();\n\n\t\tif (cg == null) {\n\t\t\t// What the heck is going on here? JDK 1.3 is sending me a dead thread.\n\t\t\t// This crashes the entire jvm if I don't return here.\n\t\t\treturn;\n\t\t}\n\n\t\t// Bug fix #382 Unable to run robocode.bat -- Access Control Exception\n\t\tif (\"SeedGenerator Thread\".equals(c.getName()) && \"SeedGenerator ThreadGroup\".equals(cg.getName())) {\n\t\t\treturn; // The SeedGenerator might create a thread, which needs to be silently ignored\n\t\t}\n\t\t\n\t\tIHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);\n\n\t\tif (robotProxy == null) {\n\t\t\tthrow new AccessControlException(\"Preventing \" + c.getName() + \" from access to \" + g.getName());\t\t\t\n\t\t}\n\n\t\tif (cg.activeCount() > 5) {\n\t\t\tString message = \"Robots are only allowed to create up to 5 threads!\";\n\n\t\t\trobotProxy.punishSecurityViolation(message);\n\t\t\tthrow new AccessControlException(message);\n\t\t}\n\t}", "label_name": "CWE-862", "label": 8} {"code": " final void set(CharSequence name, String value) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(value, \"value\");\n final int h = normalizedName.hashCode();\n final int i = index(h);\n remove0(h, i, normalizedName);\n add0(h, i, normalizedName, value);\n }", "label_name": "CWE-74", "label": 1} {"code": " public void removingANameForASecondTimeShouldReturnFalse() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name2\", \"value2\");\n assertThat(headers.remove(\"name2\")).isTrue();\n assertThat(headers.remove(\"name2\")).isFalse();\n }", "label_name": "CWE-74", "label": 1} {"code": " public void subsetOfHeadersShouldNotBeEquivalent() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n headers1.add(\"name2\", \"value2\");\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n assertThat(headers1).isNotEqualTo(headers2);\n }", "label_name": "CWE-74", "label": 1} {"code": " public void testCopy() throws Exception {\n HttpHeadersBase headers = newEmptyHeaders();\n headers.addLong(\"long\", Long.MAX_VALUE);\n headers.addInt(\"int\", Integer.MIN_VALUE);\n headers.addDouble(\"double\", Double.MAX_VALUE);\n headers.addFloat(\"float\", Float.MAX_VALUE);\n final long millis = System.currentTimeMillis();\n headers.addTimeMillis(\"millis\", millis);\n headers.addObject(\"object\", \"Hello World\");\n headers.add(\"name\", \"value\");\n\n final HttpHeadersBase oldHeaders = headers;\n headers = newEmptyHeaders();\n headers.add(oldHeaders);\n\n assertThat(headers.containsLong(\"long\", Long.MAX_VALUE)).isTrue();\n assertThat(headers.containsLong(\"long\", Long.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsInt(\"int\", Integer.MIN_VALUE)).isTrue();\n assertThat(headers.containsInt(\"int\", Integer.MAX_VALUE)).isFalse();\n\n assertThat(headers.containsDouble(\"double\", Double.MAX_VALUE)).isTrue();\n assertThat(headers.containsDouble(\"double\", Double.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsFloat(\"float\", Float.MAX_VALUE)).isTrue();\n assertThat(headers.containsFloat(\"float\", Float.MIN_VALUE)).isFalse();\n\n assertThat(headers.containsTimeMillis(\"millis\", millis)).isTrue();\n // This test doesn't work on midnight, January 1, 1970 UTC\n assertThat(headers.containsTimeMillis(\"millis\", 0)).isFalse();\n\n assertThat(headers.containsObject(\"object\", \"Hello World\")).isTrue();\n assertThat(headers.containsObject(\"object\", \"\")).isFalse();\n\n assertThat(headers.contains(\"name\", \"value\")).isTrue();\n assertThat(headers.contains(\"name\", \"value1\")).isFalse();\n }", "label_name": "CWE-74", "label": 1} {"code": " public void multipleTestingOfSameClass() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))\n .isEmpty();\n assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))\n .isEmpty();\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": 1} {"code": " public void validateFail3(ViolationCollector col) {\n col.addViolation(FAILED + \"3\");\n }", "label_name": "CWE-74", "label": 1} {"code": " public void addViolation(String message) {\n violationOccurred = true;\n String messageTemplate = escapeEl(message);\n context.buildConstraintViolationWithTemplate(messageTemplate)\n .addConstraintViolation();\n }", "label_name": "CWE-74", "label": 1} {"code": " public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException,\n NotFoundException {\n SearchResult result;\n try {\n result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));\n if (result.getItems().length == 0) {\n logger.warn(\n \"Can not delete mediapackage {}, which is not available for the current user to delete from the search index.\",\n mediaPackageId);\n return false;\n }\n logger.info(\"Removing mediapackage {} from search index\", mediaPackageId);\n\n Date now = new Date();\n try {\n persistence.deleteMediaPackage(mediaPackageId, now);\n logger.info(\"Removed mediapackage {} from search persistence\", mediaPackageId);\n } catch (NotFoundException e) {\n // even if mp not found in persistence, it might still exist in search index.\n logger.info(\"Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.\",\n mediaPackageId);\n } catch (SearchServiceDatabaseException e) {\n logger.error(\"Could not delete media package with id {} from persistence storage\", mediaPackageId);\n throw new SearchException(e);\n }\n\n return indexManager.delete(mediaPackageId, now);\n } catch (SolrServerException e) {\n logger.info(\"Could not delete media package with id {} from search index\", mediaPackageId);\n throw new SearchException(e);\n }\n }", "label_name": "CWE-863", "label": 11} {"code": " public boolean isValid(String value, ConstraintValidatorContext context) {\n long longValue = 0;\n boolean failed = false;\n String errorMessage = \"\";\n try {\n longValue = Long.parseLong(value);\n } catch (NumberFormatException ex) {\n failed = true;\n errorMessage = String.format(\"Invalid integer value: '%s'\", value);\n }\n\n if (!failed && longValue < 0) {\n failed = true;\n errorMessage = String.format(\"Expected positive integer value, got: '%s'\", value);\n }\n\n if (!failed) {\n return true;\n }\n\n LOG.warn(errorMessage);\n context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();\n\n return false;\n }", "label_name": "CWE-74", "label": 1} {"code": " default boolean contains(String name) {\n return get(name, Object.class).isPresent();\n }", "label_name": "CWE-400", "label": 2} {"code": " public Argument argumentType() {\n return Argument.of(Publisher.class);\n }", "label_name": "CWE-400", "label": 2} {"code": " default OptionalLong contentLength() {\n Optional optional = getFirst(HttpHeaders.CONTENT_LENGTH, Long.class);\n return optional.map(OptionalLong::of).orElseGet(OptionalLong::empty);\n }", "label_name": "CWE-400", "label": 2} {"code": " public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {\n Modification lastCommit = hgCommand.latestOneModificationAsModifications().get(0);\n\n makeACommitToSecondBranch();\n hg(workingDirectory, \"pull\").runOrBomb(null);\n Modification actual = hgCommand.latestOneModificationAsModifications().get(0);\n assertThat(actual, is(lastCommit));\n assertThat(actual.getComment(), is(lastCommit.getComment()));\n }", "label_name": "CWE-77", "label": 14} {"code": "error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,\n size_t offset, NetTxAncillary *ancillary)\n{\n error_t error;\n bool_t status;\n\n //Gather entropy\n netContext.entropy += netGetSystemTickCount();\n\n#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)\n //Retrieve the length of the packet\n size_t length = netBufferGetLength(buffer) - offset;\n\n //Debug message\n TRACE_DEBUG(\"Sending packet (%\" PRIuSIZE \" bytes)...\\r\\n\", length);\n TRACE_DEBUG_NET_BUFFER(\" \", buffer, offset, length);\n#endif\n\n //Check whether the interface is enabled for operation\n if(interface->configured && interface->nicDriver != NULL)\n {\n //Loopback interface?\n if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)\n {\n //The loopback interface is always available\n status = TRUE;\n }\n else\n {\n //Wait for the transmitter to be ready to send\n status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);\n }\n\n //Check whether the specified event is in signaled state\n if(status)\n {\n //Disable interrupts\n interface->nicDriver->disableIrq(interface);\n\n //Send the packet\n error = interface->nicDriver->sendPacket(interface, buffer, offset,\n ancillary);\n\n //Re-enable interrupts if necessary\n if(interface->configured)\n {\n interface->nicDriver->enableIrq(interface);\n }\n }\n else\n {\n //If the transmitter is busy, then drop the packet\n error = NO_ERROR;\n }\n }\n else\n {\n //Report an error\n error = ERROR_INVALID_INTERFACE;\n }\n\n //Return status code\n return error;\n}", "label_name": "CWE-20", "label": 0} {"code": " private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,\n String parent) throws XWikiException\n {\n XWiki xwiki = context.getWiki();\n DocumentReferenceResolver resolver = getCurrentMixedDocumentReferenceResolver();\n\n // Set the locale and default locale, considering that we're creating the original version of the document\n // (not a translation).\n newDocument.setLocale(Locale.ROOT);\n if (newDocument.getDefaultLocale() == Locale.ROOT) {\n newDocument.setDefaultLocale(xwiki.getLocalePreference(context));\n }\n\n // Copy the template.\n DocumentReference templateReference = resolver.resolve(template);\n newDocument.readFromTemplate(templateReference, context);\n\n // Set the parent field.\n if (!StringUtils.isEmpty(parent)) {\n DocumentReference parentReference = resolver.resolve(parent);\n newDocument.setParentReference(parentReference);\n }\n\n // Set the document title\n if (title != null) {\n newDocument.setTitle(title);\n }\n\n // Set the author and creator.\n DocumentReference currentUserReference = context.getUserReference();\n newDocument.setAuthorReference(currentUserReference);\n newDocument.setCreatorReference(currentUserReference);\n\n // Make sure the user is allowed to make this modification\n xwiki.checkSavingDocument(currentUserReference, newDocument, context);\n\n xwiki.saveDocument(newDocument, context);\n }", "label_name": "CWE-862", "label": 8} {"code": " public void existingDocumentFromUIDeprecated() 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 space=X&page=Y\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"page\")).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 since the deprecated parameters were creating terminal documents by default.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": 8} {"code": " public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() 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 spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that allows usage in target space.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Arrays.asList(\"X\"));\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 // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document.\n // Note2: We are creating X.Y and using the template extracted from 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 String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)\n {\n\n HttpServletRequest servletRequest = xwikiContext.getRequest();\n HttpServletResponse servletResponse = xwikiContext.getResponse();\n\n try {\n return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);\n } catch (Exception e) {\n LOGGER.warn(\"Exception including url: \" + url, e);\n return \"Exception including \\\"\" + url + \"\\\", see logs for details.\";\n }\n\n }", "label_name": "CWE-862", "label": 8} {"code": " public void translate(ServerEntityHeadLookPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n\n if (entity == null) return;\n\n entity.updateHeadLookRotation(session, packet.getHeadYaw());\n }", "label_name": "CWE-287", "label": 4} {"code": " public void translate(ServerPlayerActionAckPacket packet, GeyserSession session) {\n ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());\n if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {\n LevelEventPacket stopBreak = new LevelEventPacket();\n stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);\n stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));\n stopBreak.setData(0);\n session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);\n session.sendUpstreamPacket(stopBreak);\n }\n }", "label_name": "CWE-287", "label": 4} {"code": " public void translate(ServerSetSubtitleTextPacket packet, GeyserSession session) {\n String text;\n if (packet.getText() == null) { //TODO 1.17 can this happen?\n text = \" \";\n } else {\n text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());\n }\n\n SetTitlePacket titlePacket = new SetTitlePacket();\n titlePacket.setType(SetTitlePacket.Type.SUBTITLE);\n titlePacket.setText(text);\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label_name": "CWE-287", "label": 4} {"code": " public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {\n String text;\n if (packet.getText() == null) { //TODO 1.17 can this happen?\n text = \" \";\n } else {\n text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());\n }\n\n SetTitlePacket titlePacket = new SetTitlePacket();\n titlePacket.setType(SetTitlePacket.Type.TITLE);\n titlePacket.setText(text);\n titlePacket.setXuid(\"\");\n titlePacket.setPlatformOnlineId(\"\");\n session.sendUpstreamPacket(titlePacket);\n }", "label_name": "CWE-287", "label": 4} {"code": " public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (entity == null) {\n return;\n }\n\n UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();\n updateEquipPacket.setWindowId((short) packet.getWindowId());\n updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());\n updateEquipPacket.setUniqueEntityId(entity.getGeyserId());\n\n NbtMapBuilder builder = NbtMap.builder();\n List slots = new ArrayList<>();\n\n InventoryTranslator inventoryTranslator;\n if (entity instanceof LlamaEntity) {\n inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());\n slots.add(CARPET_SLOT);\n } else if (entity instanceof ChestedHorseEntity) {\n inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());\n slots.add(SADDLE_SLOT);\n } else {\n inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());\n slots.add(SADDLE_SLOT);\n slots.add(ARMOR_SLOT);\n }\n\n // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)\n builder.putList(\"slots\", NbtType.COMPOUND, slots);\n\n updateEquipPacket.setTag(builder.build());\n session.sendUpstreamPacket(updateEquipPacket);\n\n session.setInventoryTranslator(inventoryTranslator);\n InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));\n }", "label_name": "CWE-287", "label": 4} {"code": " private static boolean validateChainData(JsonNode data) throws Exception {\n ECPublicKey lastKey = null;\n boolean validChain = false;\n for (JsonNode node : data) {\n JWSObject jwt = JWSObject.parse(node.asText());\n\n if (!validChain) {\n validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());\n }\n\n if (lastKey != null) {\n if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false;\n }\n\n JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());\n JsonNode ipkNode = payloadNode.get(\"identityPublicKey\");\n Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, \"identityPublicKey node is missing in chain\");\n lastKey = EncryptionUtils.generateKey(ipkNode.asText());\n }\n return validChain;\n }", "label_name": "CWE-287", "label": 4} {"code": " setImmediate(() => {\n if (!this.pendingPublishRequestCount) {\n return;\n }\n const starving_subscription = this._find_starving_subscription();\n if (starving_subscription) {\n doDebug && debugLog(chalk.bgWhite.red(\"feeding most late subscription subscriptionId = \"), starving_subscription.id);\n starving_subscription.process_subscription();\n }\n });", "label_name": "CWE-400", "label": 2} {"code": " public boolean isAvailable() {\n try {\n GeoTools.getInitialContext();\n return true;\n } catch (Exception e) {\n return false;\n }\n }", "label_name": "CWE-20", "label": 0} {"code": " public DataSource createNewDataSource(Map params) throws IOException {\n String refName = (String) JNDI_REFNAME.lookUp(params);\n try {\n return (DataSource) GeoTools.getInitialContext().lookup(refName);\n } catch (Exception e) {\n throw new DataSourceException(\"Could not find the specified data source in JNDI\", e);\n }\n }", "label_name": "CWE-20", "label": 0} {"code": " protected DataSource createDataSource() throws SQLException {\n InitialContext context = null;\n DataSource source = null;\n try {\n context = GeoTools.getInitialContext();\n source = (DataSource) context.lookup(datasourceName);\n } catch (IllegalArgumentException | NoInitialContextException exception) {\n // Fall back on 'return null' below.\n } catch (NamingException exception) {\n registerInto = context;\n // Fall back on 'return null' below.\n }\n return source;\n }", "label_name": "CWE-20", "label": 0} {"code": " public void validate() {\n final String filter = format(ldapConfiguration.getUserSearchFilter(), \"test\");\n ldapConnectionTemplate.searchFirst(ldapConfiguration.getSearchBases().get(0), filter, SearchScope.SUBTREE, entry -> entry);\n }", "label_name": "CWE-74", "label": 1} {"code": " public static UnsafeAccess getInstance() {\n SecurityCheck.getInstance();\n return INSTANCE;\n }", "label_name": "CWE-200", "label": 10} {"code": "static int intel_pmu_handle_irq(struct pt_regs *regs)\n{\n\tstruct perf_sample_data data;\n\tstruct cpu_hw_events *cpuc;\n\tint bit, loops;\n\tu64 status;\n\tint handled;\n\n\tperf_sample_data_init(&data, 0);\n\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\n\t/*\n\t * Some chipsets need to unmask the LVTPC in a particular spot\n\t * inside the nmi handler. As a result, the unmasking was pushed\n\t * into all the nmi handlers.\n\t *\n\t * This handler doesn't seem to have any issues with the unmasking\n\t * so it was left at the top.\n\t */\n\tapic_write(APIC_LVTPC, APIC_DM_NMI);\n\n\tintel_pmu_disable_all();\n\thandled = intel_pmu_drain_bts_buffer();\n\tstatus = intel_pmu_get_status();\n\tif (!status) {\n\t\tintel_pmu_enable_all(0);\n\t\treturn handled;\n\t}\n\n\tloops = 0;\nagain:\n\tintel_pmu_ack_status(status);\n\tif (++loops > 100) {\n\t\tWARN_ONCE(1, \"perfevents: irq loop stuck!\\n\");\n\t\tperf_event_print_debug();\n\t\tintel_pmu_reset();\n\t\tgoto done;\n\t}\n\n\tinc_irq_stat(apic_perf_irqs);\n\n\tintel_pmu_lbr_read();\n\n\t/*\n\t * PEBS overflow sets bit 62 in the global status register\n\t */\n\tif (__test_and_clear_bit(62, (unsigned long *)&status)) {\n\t\thandled++;\n\t\tx86_pmu.drain_pebs(regs);\n\t}\n\n\tfor_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {\n\t\tstruct perf_event *event = cpuc->events[bit];\n\n\t\thandled++;\n\n\t\tif (!test_bit(bit, cpuc->active_mask))\n\t\t\tcontinue;\n\n\t\tif (!intel_pmu_save_and_restart(event))\n\t\t\tcontinue;\n\n\t\tdata.period = event->hw.last_period;\n\n\t\tif (perf_event_overflow(event, 1, &data, regs))\n\t\t\tx86_pmu_stop(event, 0);\n\t}\n\n\t/*\n\t * Repeat if there is more work to be done:\n\t */\n\tstatus = intel_pmu_get_status();\n\tif (status)\n\t\tgoto again;\n\ndone:\n\tintel_pmu_enable_all(0);\n\treturn handled;\n}", "label_name": "CWE-400", "label": 2} {"code": "mptctl_fw_download(unsigned long arg)\n{\n\tstruct mpt_fw_xfer __user *ufwdl = (void __user *) arg;\n\tstruct mpt_fw_xfer\t kfwdl;\n\n\tif (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::_ioctl_fwdl - \"\n\t\t\t\t\"Unable to copy mpt_fw_xfer struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, ufwdl);\n\t\treturn -EFAULT;\n\t}\n\n\treturn mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);\n}", "label_name": "CWE-362", "label": 18} {"code": "compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_fw_xfer32 kfw32;\n\tstruct mpt_fw_xfer kfw;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\n\tif (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = kfw32.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mptfwxfer_ioctl @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mptfwxfer_ioctl() called\\n\",\n\t iocp->name));\n\tkfw.iocnum = iocnum;\n\tkfw.fwlen = kfw32.fwlen;\n\tkfw.bufp = compat_ptr(kfw32.bufp);\n\n\tret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label_name": "CWE-362", "label": 18} {"code": "inline typename V::VectorType FBUnserializer::unserializeList() {\n p_ += CODE_SIZE;\n\n // the list size is written so we can reserve it in the vector\n // in future. Skip past it for now.\n unserializeInt64();\n\n typename V::VectorType ret = V::createVector();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n V::vectorAppend(ret, unserializeThing());\n code = nextCode();\n }\n p_ += CODE_SIZE;\n return ret;\n}", "label_name": "CWE-674", "label": 28} {"code": "static Variant HHVM_FUNCTION(simplexml_import_dom,\n const Object& node,\n const String& class_name /* = \"SimpleXMLElement\" */) {\n auto domnode = Native::data(node);\n xmlNodePtr nodep = domnode->nodep();\n\n if (nodep) {\n if (nodep->doc == nullptr) {\n raise_warning(\"Imported Node must have associated Document\");\n return init_null();\n }\n if (nodep->type == XML_DOCUMENT_NODE ||\n nodep->type == XML_HTML_DOCUMENT_NODE) {\n nodep = xmlDocGetRootElement((xmlDocPtr) nodep);\n }\n }\n\n if (nodep && nodep->type == XML_ELEMENT_NODE) {\n auto cls = class_from_name(class_name, \"simplexml_import_dom\");\n if (!cls) {\n return init_null();\n }\n Object obj = create_object(cls->nameStr(), Array(), false);\n auto sxe = Native::data(obj.get());\n sxe->node = libxml_register_node(nodep);\n return obj;\n } else {\n raise_warning(\"Invalid Nodetype to import\");\n return init_null();\n }\n return false;\n}", "label_name": "CWE-345", "label": 22} {"code": "bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n\t{\n\tbool orig = (endp == &orig_state);\n\tbinpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow();\n\n\tu_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems.\n\tint len = endp->pkt_length - 5;\n\n\t// DNP3 Packet : DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer\n\t// DNP3 Serial Transport Layer data is always 1 byte.\n\t// Get FIN FIR seq field in transport header.\n\t// FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not.\n\t// FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not.\n\n\tint is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet.\n\tint is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet.\n\n\tint transport = PSEUDO_TRANSPORT_LEN;\n\n\tint i = 0;\n\twhile ( len > 0 )\n\t\t{\n\t\tint n = min(len, 16);\n\n\t\t// Make sure chunk has a correct checksum.\n\t\tif ( ! CheckCRC(n, data, data + n, \"app_chunk\") )\n\t\t\treturn false;\n\n\t\t// Pass on to BinPAC.\n\t\tassert(data + n < endp->buffer + endp->buffer_len);\n\t\tflow->flow_buffer()->BufferData(data + transport, data + n);\n\t\ttransport = 0;\n\n\t\tdata += n + 2;\n\t\tlen -= n;\n\t\t}\n\n\tif ( is_first )\n\t\tendp->encountered_first_chunk = true;\n\n\tif ( ! is_first && ! endp->encountered_first_chunk )\n\t\t{\n\t\t// We lost the first chunk.\n\t\tanalyzer->Weird(\"dnp3_first_application_layer_chunk_missing\");\n\t\treturn false;\n\t\t}\n\n\tif ( is_last )\n\t\t{\n\t\tflow->flow_buffer()->FinishBuffer();\n\t\tflow->FlowEOF();\n\t\tClearEndpointState(orig);\n\t\t}\n\n\treturn true;\n\t}", "label_name": "CWE-119", "label": 26} {"code": "jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)\n{\n\tjas_matrix_t *y;\n\tint i;\n\tint j;\n\ty = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),\n\t jas_seq2d_xend(x), jas_seq2d_yend(x));\n\tassert(y);\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": "int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)\n{\n\tint size;\n\tint i;\n\n\tsize = numrows * numcols;\n\tif (size > matrix->datasize_ || numrows > matrix->maxrows_) {\n\t\treturn -1;\n\t}\n\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[numcols * i];\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-20", "label": 0} {"code": "void CSecurityTLS::shutdown(bool needbye)\n{\n if (session && needbye)\n if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS)\n vlog.error(\"gnutls_bye failed\");\n\n if (anon_cred) {\n gnutls_anon_free_client_credentials(anon_cred);\n anon_cred = 0;\n }\n\n if (cert_cred) {\n gnutls_certificate_free_credentials(cert_cred);\n cert_cred = 0;\n }\n\n if (session) {\n gnutls_deinit(session);\n session = 0;\n\n gnutls_global_deinit();\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "void SSecurityTLS::initGlobal()\n{\n static bool globalInitDone = false;\n\n if (!globalInitDone) {\n if (gnutls_global_init() != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_global_init failed\");\n globalInitDone = true;\n }\n}", "label_name": "CWE-119", "label": 26} {"code": "void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix)\n{\n int stride;\n U8 *buf;\n int w, h, b;\n\n w = r.width();\n h = r.height();\n b = format.bpp/8;\n\n if (h == 0)\n return;\n\n buf = getBufferRW(r, &stride);\n\n if (b == 1) {\n while (h--) {\n memset(buf, *(const U8*)pix, w);\n buf += stride * b;\n }\n } else {\n U8 *start;\n int w1;\n\n start = buf;\n\n w1 = w;\n while (w1--) {\n memcpy(buf, pix, b);\n buf += b;\n }\n buf += (stride - w) * b;\n h--;\n\n while (h--) {\n memcpy(buf, start, w * b);\n buf += stride * b;\n }\n }\n\n commitBufferRW(r);\n}", "label_name": "CWE-119", "label": 26} {"code": "char *Hub::inflate(char *data, size_t &length) {\n dynamicInflationBuffer.clear();\n\n inflationStream.next_in = (Bytef *) data;\n inflationStream.avail_in = length;\n\n int err;\n do {\n inflationStream.next_out = (Bytef *) inflationBuffer;\n inflationStream.avail_out = LARGE_BUFFER_SIZE;\n err = ::inflate(&inflationStream, Z_FINISH);\n if (!inflationStream.avail_in) {\n break;\n }\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n } while (err == Z_BUF_ERROR);\n\n inflateReset(&inflationStream);\n\n if (err != Z_BUF_ERROR && err != Z_OK) {\n length = 0;\n return nullptr;\n }\n\n if (dynamicInflationBuffer.length()) {\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n\n length = dynamicInflationBuffer.length();\n return (char *) dynamicInflationBuffer.data();\n }\n\n length = LARGE_BUFFER_SIZE - inflationStream.avail_out;\n return inflationBuffer;\n}", "label_name": "CWE-20", "label": 0} {"code": "R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {\n\tRBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);\n\tif (!se) {\n\t\treturn NULL;\n\t}\n\tse->tag = type;\n\tif (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {\n\t\tse->info.obj_val_cp_idx = (ut16) value;\n\t} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {\n\t\t/*if (bin->offset_sz == 4) {\n\t\tse->info.uninit_offset = value;\n\t\t} else {\n\t\tse->info.uninit_offset = (ut16) value;\n\t\t}*/\n\t\tse->info.uninit_offset = (ut16) value;\n\t}\n\treturn se;\n}", "label_name": "CWE-119", "label": 26} {"code": "static const char* ConvertOneFloat(PyObject* v, T* out) {\n if (PyErr_Occurred()) {\n return nullptr;\n }\n if (TF_PREDICT_TRUE(PyFloat_Check(v))) {\n const double as_double = PyFloat_AS_DOUBLE(v);\n *out = static_cast(as_double);\n // Check for overflow\n if (TF_PREDICT_FALSE(sizeof(T) < sizeof(double) && std::isinf(*out) &&\n std::isfinite(as_double))) {\n return ErrorOutOfRangeDouble;\n }\n return nullptr;\n }\n#if PY_MAJOR_VERSION < 3\n if (PyInt_Check(v)) {\n *out = PyInt_AS_LONG(v);\n return nullptr;\n }\n#endif\n if (PyLong_Check(v)) {\n *out = PyLong_AsDouble(v);\n if (PyErr_Occurred()) return ErrorOutOfRangeDouble;\n return nullptr;\n }\n if (PyIsInstance(v, &PyFloatingArrType_Type)) { // NumPy float types\n Safe_PyObjectPtr as_float = make_safe(PyNumber_Float(v));\n if (PyErr_Occurred()) {\n return nullptr;\n }\n return ConvertOneFloat(as_float.get(), out);\n }\n if (PyIsInstance(v, &PyIntegerArrType_Type)) { // NumPy integers\n#if PY_MAJOR_VERSION < 3\n Safe_PyObjectPtr as_int = make_safe(PyNumber_Int(v));\n#else\n Safe_PyObjectPtr as_int = make_safe(PyNumber_Long(v));\n#endif\n if (PyErr_Occurred()) {\n return nullptr;\n }\n return ConvertOneFloat(as_int.get(), out);\n }\n return ErrorMixedTypes;\n}", "label_name": "CWE-20", "label": 0} {"code": " void readStructEnd() {\n lastFieldId_ = nestedStructFieldIds_.back();\n nestedStructFieldIds_.pop_back();\n }", "label_name": "CWE-674", "label": 28} {"code": "uint64_t HeaderMapImpl::byteSize() const {\n uint64_t byte_size = 0;\n for (const HeaderEntryImpl& header : headers_) {\n byte_size += header.key().size();\n byte_size += header.value().size();\n }\n\n return byte_size;\n}", "label_name": "CWE-400", "label": 2} {"code": "void HeaderMapImpl::removePrefix(const LowerCaseString& prefix) {\n headers_.remove_if([&](const HeaderEntryImpl& entry) {\n bool to_remove = absl::StartsWith(entry.key().getStringView(), prefix.get());\n if (to_remove) {\n // If this header should be removed, make sure any references in the\n // static lookup table are cleared as well.\n EntryCb cb = ConstSingleton::get().find(entry.key().getStringView());\n if (cb) {\n StaticLookupResponse ref_lookup_response = cb(*this);\n if (ref_lookup_response.entry_) {\n *ref_lookup_response.entry_ = nullptr;\n }\n }\n }\n return to_remove;\n });\n}", "label_name": "CWE-400", "label": 2} {"code": "void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n if (is_draining_for_deletion_) {\n closeIdleConnectionsForDrainingPool();\n }\n\n if (isIdleImpl()) {\n ENVOY_LOG(debug, \"invoking idle callbacks - is_draining_for_deletion_={}\",\n is_draining_for_deletion_);\n for (const Instance::IdleCb& cb : idle_callbacks_) {\n cb();\n }\n }\n}", "label_name": "CWE-674", "label": 28} {"code": " CdsIntegrationTest()\n : HttpIntegrationTest(Http::CodecType::HTTP2, ipVersion(),\n ConfigHelper::discoveredClustersBootstrap(\n sotwOrDelta() == Grpc::SotwOrDelta::Sotw ||\n sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw\n ? \"GRPC\"\n : \"DELTA_GRPC\")) {\n if (sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw ||\n sotwOrDelta() == Grpc::SotwOrDelta::UnifiedDelta) {\n config_helper_.addRuntimeOverride(\"envoy.reloadable_features.unified_mux\", \"true\");\n }\n use_lds_ = false;\n sotw_or_delta_ = sotwOrDelta();\n }", "label_name": "CWE-674", "label": 28} {"code": "TEST_F(RouterTest, RetryUpstreamResetResponseStarted) {\n NiceMock encoder1;\n Http::ResponseDecoder* response_decoder = nullptr;\n expectNewStreamWithImmediateEncoder(encoder1, &response_decoder, Http::Protocol::Http10);\n\n expectResponseTimerCreate();\n\n Http::TestRequestHeaderMapImpl headers{{\"x-envoy-retry-on\", \"5xx\"}, {\"x-envoy-internal\", \"true\"}};\n HttpTestUtility::addDefaultHeaders(headers);\n router_.decodeHeaders(headers, true);\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\n\n // Since the response is already started we don't retry.\n EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _, _)).WillOnce(Return(RetryStatus::No));\n EXPECT_CALL(callbacks_, encodeHeaders_(_, false));\n Http::ResponseHeaderMapPtr response_headers(\n new Http::TestResponseHeaderMapImpl{{\":status\", \"200\"}});\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putHttpResponseCode(200));\n response_decoder->decodeHeaders(std::move(response_headers), false);\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _));\n // Normally, sendLocalReply will actually send the reply, but in this case the\n // HCM will detect the headers have already been sent and not route through\n // the encoder again.\n EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] {\n }));\n encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset);\n // For normal HTTP, once we have a 200 we consider this a success, even if a\n // later reset occurs.\n EXPECT_TRUE(verifyHostUpstreamStats(1, 0));\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\n}", "label_name": "CWE-670", "label": 36} {"code": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n if (!buffers[i] ||\n !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) {\n abort();\n }\n buffer_pool_.push(buffers[i]);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "label_name": "CWE-668", "label": 7} {"code": " RectangleRequest(const struct RectangleRequest &req)\n : Explicit()\n {\n // Not nice, but this is really faster and simpler\n memcpy(this,&req,sizeof(struct RectangleRequest));\n // Not linked in any way if this is new.\n rr_pNext = NULL;\n }", "label_name": "CWE-119", "label": 26} {"code": " def forwarded_for\n @env[FORWARDED_FOR]\n end", "label_name": "CWE-20", "label": 0} {"code": " def check_action_permission!(skip_source = nil)\n super(skip_source)\n # only perform the following check, if we are called from\n # BsRequest.permission_check_change_state! (that is, if\n # skip_source is set to true). Always executing this check\n # would be a regression, because this code is also executed\n # if a new request is created (which could fail if User.current\n # cannot modify the source_package).\n return unless skip_source\n target_project = Project.get_by_name(self.target_project)\n return unless target_project && target_project.is_a?(Project)\n target_package = target_project.packages.find_by_name(self.target_package)\n initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')\n return if target_package || !initialize_devel_package\n source_package = Package.get_by_project_and_name(source_project, self.source_package)\n return if !source_package || User.current.can_modify?(source_package)\n msg = 'No permission to initialize the source package as a devel package'\n raise PostRequestNoPermission, msg\n end", "label_name": "CWE-732", "label": 13} {"code": " def munge_name(name)\n # LAK:NOTE http://snurl.com/21zf8 [groups_google_com]\n # Change to name.downcase.split(\".\",-1).reverse for FQDN support\n name.downcase.split(\".\").reverse\n end", "label_name": "CWE-287", "label": 4} {"code": " def select_terminus(request)\n # We rely on the request's parsing of the URI.\n\n # Short-circuit to :file if it's a fully-qualified path or specifies a 'file' protocol.\n return PROTOCOL_MAP[\"file\"] if Puppet::Util.absolute_path?(request.key)\n return PROTOCOL_MAP[\"file\"] if request.protocol == \"file\"\n\n # We're heading over the wire the protocol is 'puppet' and we've got a server name or we're not named 'apply' or 'puppet'\n if request.protocol == \"puppet\" and (request.server or ![\"puppet\",\"apply\"].include?(Puppet.settings[:name]))\n return PROTOCOL_MAP[\"puppet\"]\n end\n\n if request.protocol and PROTOCOL_MAP[request.protocol].nil?\n raise(ArgumentError, \"URI protocol '#{request.protocol}' is not currently supported for file serving\")\n end\n\n # If we're still here, we're using the file_server or modules.\n :file_server\n end", "label_name": "CWE-200", "label": 10} {"code": " it \"should should include the IndirectionHooks module in its indirection\" do\n Puppet::FileServing::Metadata.indirection.singleton_class.included_modules.should include(Puppet::FileServing::IndirectionHooks)\n end", "label_name": "CWE-200", "label": 10} {"code": " def setup_user(operation, type = \"\", search = nil, user = :one)\n @one = users(user)\n as_admin do\n permission = Permission.find_by_name(\"#{operation}_#{type}\") || FactoryGirl.create(:permission, :name => \"#{operation}_#{type}\")\n filter = FactoryGirl.build(:filter, :search => search)\n filter.permissions = [ permission ]\n role = Role.where(:name => \"#{operation}_#{type}\").first_or_create\n role.filters = [ filter ]\n role.save!\n filter.role = role\n filter.save!\n @one.roles << role\n yield(@one) if block_given?\n @one.save!\n end\n User.current = @one\n end", "label_name": "CWE-200", "label": 10} {"code": " def test_clone\n get :clone, {:id => Hostgroup.first}, set_session_user\n assert_template 'new'\n end", "label_name": "CWE-200", "label": 10} {"code": " def initialize\n # Generate and cache 3 bytes of identifying information from the current\n # machine.\n @machine_id = Digest::MD5.digest(Socket.gethostname).unpack(\"C3\")\n\n @mutex = Mutex.new\n @last_timestamp = nil\n @counter = 0\n end", "label_name": "CWE-20", "label": 0} {"code": " def next\n now = Time.new.to_i\n\n counter = @mutex.synchronize do\n last_timestamp, @last_timestamp = @last_timestamp, now\n\n if last_timestamp == now\n @counter += 1\n else\n @counter = 0\n end\n end\n\n generate(now, counter)\n end", "label_name": "CWE-20", "label": 0} {"code": " def __bson_load__(io)\n new io.read(12).unpack('C*')\n end", "label_name": "CWE-20", "label": 0} {"code": " def initialize(data = nil, time = nil)\n if data\n @data = data\n elsif time\n @data = @@generator.generate(time.to_i)\n else\n @data = @@generator.next\n end\n end", "label_name": "CWE-20", "label": 0} {"code": " def sync_server(server)\n [].tap do |hosts|\n socket = server.socket\n\n if socket.connect\n info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1)\n\n if info[\"ismaster\"]\n server.primary = true\n end\n\n if info[\"secondary\"]\n server.secondary = true\n end\n\n if info[\"primary\"]\n hosts.push info[\"primary\"]\n end\n\n if info[\"hosts\"]\n hosts.concat info[\"hosts\"]\n end\n\n if info[\"passives\"]\n hosts.concat info[\"passives\"]\n end\n\n merge(server)\n\n end\n end.uniq\n end", "label_name": "CWE-20", "label": 0} {"code": " def reconnect\n @servers = servers.map { |server| Server.new(server.address) }\n end", "label_name": "CWE-20", "label": 0} {"code": " def initialize(session, query_operation)\n @session = session\n @query_op = query_operation.dup\n\n @get_more_op = Protocol::GetMore.new(\n @query_op.database,\n @query_op.collection,\n 0,\n @query_op.limit\n )\n\n @kill_cursor_op = Protocol::KillCursors.new([0])\n end", "label_name": "CWE-400", "label": 2} {"code": " def limited?\n @query_op.limit > 0\n end", "label_name": "CWE-20", "label": 0} {"code": " def logout\n session.cluster.logout(name)\n end", "label_name": "CWE-400", "label": 2} {"code": " def initialize(string)\n super(\"'#{string}' is not a valid object id.\")\n end", "label_name": "CWE-400", "label": 2} {"code": " def remove_all\n delete = Protocol::Delete.new(\n operation.database,\n operation.collection,\n operation.selector\n )\n\n session.with(consistency: :strong) do |session|\n session.execute delete\n end\n end", "label_name": "CWE-400", "label": 2} {"code": " def update(change, flags = nil)\n update = Protocol::Update.new(\n operation.database,\n operation.collection,\n operation.selector,\n change,\n flags: flags\n )\n\n session.with(consistency: :strong) do |session|\n session.execute update\n end\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"returns the same hash\" do\n Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"adds the node to the master set\" do\n cluster.sync_server server\n cluster.primaries.should include server\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"adds the credentials to the auth cache\" do\n cluster.login(\"admin\", \"username\", \"password\")\n cluster.auth.should eq(\"admin\" => [\"username\", \"password\"])\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"stores the list of seeds\" do\n cluster.seeds.should eq [\"127.0.0.1:27017\", \"127.0.0.1:27018\"]\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"has an empty list of primaries\" do\n cluster.primaries.should be_empty\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"applies the cached authentication\" do\n cluster.stub(:sync) { cluster.servers << server }\n socket.should_receive(:apply_auth).with(cluster.auth)\n cluster.socket_for(:write)\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"returns all other known hosts\" do\n cluster.sync_server(server).should =~ [\"localhost:61085\", \"localhost:61086\", \"localhost:61084\"]\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"stores the database\" do\n collection.database.should eq database\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"removes the first matching document\" 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 [:remove_first]\n delete.selector.should eq query.operation.selector\n end\n\n query.remove\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"executes a distinct command\" do\n database.should_receive(:command).with(\n distinct: collection.name,\n key: \"name\",\n query: selector\n ).and_return(\"values\" => [ \"durran\", \"bernerd\" ])\n query.distinct(:name)\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"sets the query operation's fields\" do\n query.select(a: 1)\n query.operation.fields.should eq(a: 1)\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"yields all documents in the cursor\" do\n cursor = Moped::Cursor.allocate\n cursor.stub(:to_enum).and_return([1, 2].to_enum)\n\n Moped::Cursor.stub(new: cursor)\n\n query.to_a.should eq [1, 2]\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"returns the document\" do\n session.simple_query(query).should eq(a: 1)\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"stores the cluster\" do\n session.cluster.should be_a(Moped::Cluster)\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"doesn't try to set flags\" do\n session.stub(socket_for: socket)\n expect { session.query(query) }.not_to raise_exception\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"returns the new session\" do\n session.stub(with: new_session)\n session.new(new_options).should eql new_session\n end", "label_name": "CWE-400", "label": 2} {"code": " it \"queries a slave node\" do\n session.should_receive(:socket_for).with(:read).\n and_return(socket)\n session.query(query)\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"sets the :database option\" do\n session.use :admin\n session.options[:database].should eq(:admin)\n end", "label_name": "CWE-400", "label": 2} {"code": " it 'avoids xss attacks' do\n h = last_response.headers['X-MiniProfiler-Ids']\n id = ::JSON.parse(h)[0]\n get \"/mini-profiler-resources/results?id=%22%3E%3Cqss%3E\"\n last_response.should_not be_ok\n last_response.body.should_not =~ //\n last_response.body.should =~ /<qss>/\n end", "label_name": "CWE-200", "label": 10} {"code": " it 'should not choke on valueless attributes' do\n @s.fragment('foo foo bar')\n .must_equal 'foo foo bar'\n end", "label_name": "CWE-20", "label": 0} {"code": " it \"generates the correct messages for a secure topic\" do\n Jobs.run_immediately!\n UserActionManager.enable\n\n admin = Fabricate(:admin)\n\n cat = Fabricate(:category)\n cat.set_permissions(admins: :full)\n cat.save\n\n created_post = nil\n\n messages = MessageBus.track_publish do\n created_post = PostCreator.new(admin, basic_topic_params.merge(category: cat.id)).create\n _reply = PostCreator.new(admin, raw: \"this is my test reply 123 testing\", topic_id: created_post.topic_id).create\n end\n\n messages.filter! { |m| m.channel != \"/distributed_hash\" }\n\n channels = messages.map { |m| m.channel }.sort\n\n # 2 for topic, one to notify of new topic another for tracking state\n expect(channels).to eq(\n [\n \"/new\",\n \"/u/#{admin.username}\",\n \"/u/#{admin.username}\",\n \"/unread/#{admin.id}\",\n \"/unread/#{admin.id}\",\n \"/latest\",\n \"/latest\",\n \"/topic/#{created_post.topic_id}\",\n \"/topic/#{created_post.topic_id}\",\n \"/user\",\n \"/user\",\n \"/user\"\n ].sort\n )\n\n admin_ids = [Group[:admins].id]\n expect(messages.any? { |m| m.group_ids != admin_ids && m.user_ids != [admin.id] }).to eq(false)\n end", "label_name": "CWE-200", "label": 10} {"code": " it 'returns a list of all private messages that has been archived' do\n UserArchivedMessage.archive!(user_2.id, private_message)\n GroupArchivedMessage.archive!(user_2.id, group_message)\n\n topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics\n\n expect(topics).to contain_exactly(private_message, group_message)\n end", "label_name": "CWE-863", "label": 11} {"code": " it \"should redeem the invite if invited by non staff and approve if staff not required to approve\" do\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(true)\n end", "label_name": "CWE-863", "label": 11} {"code": " it \"should redeem the invite if invited by non staff and approve if email in auto_approve_email_domains setting\" do\n SiteSetting.must_approve_users = true\n SiteSetting.auto_approve_email_domains = \"example.com\"\n user = invite_redeemer.redeem\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": 11} {"code": " def email_login\n raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email\n second_factor_token = params[:second_factor_token]\n second_factor_method = params[:second_factor_method].to_i\n token = params[:token]\n valid_token = !!EmailToken.valid_token_format?(token)\n user = EmailToken.confirmable(token)&.user\n\n if valid_token && user&.totp_enabled?\n if !second_factor_token.present?\n @second_factor_required = true\n @backup_codes_enabled = true if user&.backup_codes_enabled?\n return render layout: 'no_ember'\n elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)\n RateLimiter.new(nil, \"second-factor-min-#{request.remote_ip}\", 3, 1.minute).performed!\n @error = I18n.t('login.invalid_second_factor_code')\n return render layout: 'no_ember'\n end\n end\n\n if user = EmailToken.confirm(token)\n if login_not_approved_for?(user)\n @error = login_not_approved[:error]\n elsif payload = login_error_check(user)\n @error = payload[:error]\n else\n log_on_user(user)\n return redirect_to path(\"/\")\n end\n else\n @error = I18n.t('email_login.invalid_token')\n end\n\n render layout: 'no_ember'\n end", "label_name": "CWE-287", "label": 4} {"code": " it 'should authenticate user and delete token' do\n user = Fabricate(:user)\n\n get \"/session/current.json\"\n expect(response.status).to eq(404)\n\n token = SecureRandom.hex\n $redis.setex \"otp_#{token}\", 10.minutes, user.username\n\n get \"/session/otp/#{token}\"\n\n expect(response.status).to eq(302)\n expect(response).to redirect_to(\"/\")\n expect($redis.get(\"otp_#{token}\")).to eq(nil)\n\n get \"/session/current.json\"\n expect(response.status).to eq(200)\n end", "label_name": "CWE-287", "label": 4} {"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": " def email_login\n raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email\n second_factor_token = params[:second_factor_token]\n second_factor_method = params[:second_factor_method].to_i\n token = params[:token]\n valid_token = !!EmailToken.valid_token_format?(token)\n user = EmailToken.confirmable(token)&.user\n\n if valid_token && user&.totp_enabled?\n if !second_factor_token.present?\n @second_factor_required = true\n @backup_codes_enabled = true if user&.backup_codes_enabled?\n return render layout: 'no_ember'\n elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)\n RateLimiter.new(nil, \"second-factor-min-#{request.remote_ip}\", 3, 1.minute).performed!\n @error = I18n.t('login.invalid_second_factor_code')\n return render layout: 'no_ember'\n end\n end\n\n if user = EmailToken.confirm(token)\n if login_not_approved_for?(user)\n @error = login_not_approved[:error]\n elsif payload = login_error_check(user)\n @error = payload[:error]\n else\n log_on_user(user)\n return redirect_to path(\"/\")\n end\n else\n @error = I18n.t('email_login.invalid_token')\n end\n\n render layout: 'no_ember'\n end", "label_name": "CWE-287", "label": 4} {"code": "func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {\n\tswitch m.Device {\n\tcase \"cgroup\":\n\t\t// No mount point(s) need to be created:\n\t\t//\n\t\t// * for v1, mount points are saved by CRIU because\n\t\t// /sys/fs/cgroup is a tmpfs mount\n\t\t//\n\t\t// * for v2, /sys/fs/cgroup is a real mount, but\n\t\t// the mountpoint appears as soon as /sys is mounted\n\t\treturn nil\n\tcase \"bind\":\n\t\t// The prepareBindMount() function checks if source\n\t\t// exists. So it cannot be used for other filesystem types.\n\t\tif err := prepareBindMount(m, c.config.Rootfs); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// for all other filesystems just create the mountpoints\n\t\tdest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := checkProcMount(c.config.Rootfs, dest, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.Destination = dest\n\t\tif err := os.MkdirAll(dest, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": 18} {"code": "func mountCgroupV1(m *configs.Mount, c *mountConfig) error {\n\tbinds, err := getCgroupMounts(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar merged []string\n\tfor _, b := range binds {\n\t\tss := filepath.Base(b.Destination)\n\t\tif strings.Contains(ss, \",\") {\n\t\t\tmerged = append(merged, ss)\n\t\t}\n\t}\n\ttmpfs := &configs.Mount{\n\t\tSource: \"tmpfs\",\n\t\tDevice: \"tmpfs\",\n\t\tDestination: m.Destination,\n\t\tFlags: defaultMountFlags,\n\t\tData: \"mode=755\",\n\t\tPropagationFlags: m.PropagationFlags,\n\t}\n\tif err := mountToRootfs(tmpfs, c); err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range binds {\n\t\tif c.cgroupns {\n\t\t\tsubsystemPath := filepath.Join(c.root, b.Destination)\n\t\t\tif err := os.MkdirAll(subsystemPath, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tflags := defaultMountFlags\n\t\t\tif m.Flags&unix.MS_RDONLY != 0 {\n\t\t\t\tflags = flags | unix.MS_RDONLY\n\t\t\t}\n\t\t\tcgroupmount := &configs.Mount{\n\t\t\t\tSource: \"cgroup\",\n\t\t\t\tDevice: \"cgroup\", // this is actually fstype\n\t\t\t\tDestination: subsystemPath,\n\t\t\t\tFlags: flags,\n\t\t\t\tData: filepath.Base(subsystemPath),\n\t\t\t}\n\t\t\tif err := mountNewCgroup(cgroupmount); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := mountToRootfs(b, c); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, mc := range merged {\n\t\tfor _, ss := range strings.Split(mc, \",\") {\n\t\t\t// symlink(2) is very dumb, it will just shove the path into\n\t\t\t// the link and doesn't do any checks or relative path\n\t\t\t// conversion. Also, don't error out if the cgroup already exists.\n\t\t\tif err := os.Symlink(mc, filepath.Join(c.root, m.Destination, ss)); err != nil && !os.IsExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": 18} {"code": "func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif !f.valid {\n\t\treturn errBadFilter\n\t}\n\n\tif len(conds) == 0 {\n\t\tif err := f.addRuleWrapper(call, action, exact, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// We don't support conditional filtering in library version v2.1\n\t\tif !checkVersionAbove(2, 2, 1) {\n\t\t\treturn VersionError{\n\t\t\t\tmessage: \"conditional filtering is not supported\",\n\t\t\t\tminimum: \"2.2.1\",\n\t\t\t}\n\t\t}\n\n\t\tfor _, cond := range conds {\n\t\t\tcmpStruct := C.make_struct_arg_cmp(C.uint(cond.Argument), cond.Op.toNative(), C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))\n\t\t\tdefer C.free(cmpStruct)\n\n\t\t\tif err := f.addRuleWrapper(call, action, exact, C.scmp_cast_t(cmpStruct)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "label_name": "CWE-20", "label": 0} {"code": "func doesPolicySignatureV2Match(formValues http.Header) APIErrorCode {\n\tcred := globalActiveCred\n\taccessKey := formValues.Get(xhttp.AmzAccessKeyID)\n\tcred, _, s3Err := checkKeyValid(accessKey)\n\tif s3Err != ErrNone {\n\t\treturn s3Err\n\t}\n\tpolicy := formValues.Get(\"Policy\")\n\tsignature := formValues.Get(xhttp.AmzSignatureV2)\n\tif !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) {\n\t\treturn ErrSignatureDoesNotMatch\n\t}\n\treturn ErrNone\n}", "label_name": "CWE-285", "label": 23} {"code": "\t\taction := args[2].(func(child argoappv1.ResourceNode, appName string))\n\t\tappName := \"\"\n\t\tif res, ok := data.namespacedResources[key]; ok {\n\t\t\tappName = res.AppName\n\t\t}\n\t\taction(argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: key.Kind, Group: key.Group, Namespace: key.Namespace, Name: key.Name}}, appName)\n\t}).Return(nil)", "label_name": "CWE-269", "label": 6} {"code": "func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) {\n\n\tstate, err := stateDB.Load()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot load state: %w\", err)\n\t}\n\n\tpool := &Pool{\n\t\tstateDB: stateDB,\n\t\tblockStore: blockStore,\n\t\tstate: state,\n\t\tlogger: log.NewNopLogger(),\n\t\tevidenceStore: evidenceDB,\n\t\tevidenceList: clist.New(),\n\t\tconsensusBuffer: make([]types.Evidence, 0),\n\t}\n\n\t// if pending evidence already in db, in event of prior failure, then check for expiration,\n\t// update the size and load it back to the evidenceList\n\tpool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence()\n\tevList, _, err := pool.listEvidence(baseKeyPending, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tatomic.StoreUint32(&pool.evidenceSize, uint32(len(evList)))\n\tfor _, ev := range evList {\n\t\tpool.evidenceList.PushBack(ev)\n\t}\n\n\treturn pool, nil\n}", "label_name": "CWE-400", "label": 2} {"code": "func (EmptyEvidencePool) Update(State, types.EvidenceList) {}", "label_name": "CWE-400", "label": 2} {"code": "func makeStreamDistributedQueryCampaignResultsHandler(svc kolide.Service, jwtKey string, logger kitlog.Logger) http.Handler {\n\topt := sockjs.DefaultOptions\n\topt.Websocket = true\n\topt.RawWebsocket = true\n\treturn sockjs.NewHandler(\"/api/v1/kolide/results\", opt, func(session sockjs.Session) {\n\t\tdefer session.Close(0, \"none\")\n\n\t\tconn := &websocket.Conn{Session: session}\n\n\t\t// Receive the auth bearer token\n\t\ttoken, err := conn.ReadAuthToken()\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"failed to read auth token\")\n\t\t\treturn\n\t\t}\n\n\t\t// Authenticate with the token\n\t\tvc, err := authViewer(context.Background(), jwtKey, token, svc)\n\t\tif err != nil || !vc.CanPerformActions() {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"unauthorized viewer\")\n\t\t\tconn.WriteJSONError(\"unauthorized\")\n\t\t\treturn\n\t\t}\n\n\t\tctx := viewer.NewContext(context.Background(), *vc)\n\n\t\tmsg, err := conn.ReadJSONMessage()\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"reading select_campaign JSON\")\n\t\t\tconn.WriteJSONError(\"error reading select_campaign\")\n\t\t\treturn\n\t\t}\n\t\tif msg.Type != \"select_campaign\" {\n\t\t\tlogger.Log(\"err\", \"unexpected msg type, expected select_campaign\", \"msg-type\", msg.Type)\n\t\t\tconn.WriteJSONError(\"expected select_campaign\")\n\t\t\treturn\n\t\t}\n\n\t\tvar info struct {\n\t\t\tCampaignID uint `json:\"campaign_id\"`\n\t\t}\n\t\terr = json.Unmarshal(*(msg.Data.(*json.RawMessage)), &info)\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"unmarshaling select_campaign data\")\n\t\t\tconn.WriteJSONError(\"error unmarshaling select_campaign data\")\n\t\t\treturn\n\t\t}\n\t\tif info.CampaignID == 0 {\n\t\t\tlogger.Log(\"err\", \"campaign ID not set\")\n\t\t\tconn.WriteJSONError(\"0 is not a valid campaign ID\")\n\t\t\treturn\n\t\t}\n\n\t\tsvc.StreamCampaignResults(ctx, conn, info.CampaignID)\n\n\t})\n}", "label_name": "CWE-400", "label": 2} {"code": "func (svc Service) TeamScheduleQuery(ctx context.Context, teamID uint, q *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); 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\tq.PackID = gp.ID\n\n\treturn svc.unauthorizedScheduleQuery(ctx, q)\n}", "label_name": "CWE-863", "label": 11} {"code": "func (svc *Service) DeleteUser(ctx context.Context, id uint) error {\n\tif err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionWrite); err != nil {\n\t\treturn err\n\t}\n\n\treturn svc.ds.DeleteUser(ctx, id)\n}", "label_name": "CWE-863", "label": 11} {"code": "func InitGenesis(\n\tctx sdk.Context,\n\tk keeper.Keeper,\n\tak types.AccountKeeper,\n\tsk types.StakingKeeper,\n\tdata types.GenesisState,\n) {\n\t// Ensure inflation module account is set on genesis\n\tif acc := ak.GetModuleAccount(ctx, types.ModuleName); acc == nil {\n\t\tpanic(\"the inflation module account has not been set\")\n\t}\n\n\t// Set genesis state\n\tparams := data.Params\n\tk.SetParams(ctx, params)\n\n\tperiod := data.Period\n\tk.SetPeriod(ctx, period)\n\n\tepochIdentifier := data.EpochIdentifier\n\tk.SetEpochIdentifier(ctx, epochIdentifier)\n\n\tepochsPerPeriod := data.EpochsPerPeriod\n\tk.SetEpochsPerPeriod(ctx, epochsPerPeriod)\n\n\t// Get bondedRatio\n\tbondedRatio := sk.BondedRatio(ctx)\n\n\t// Calculate epoch mint provision\n\tepochMintProvision := types.CalculateEpochMintProvision(\n\t\tparams,\n\t\tperiod,\n\t\tepochsPerPeriod,\n\t\tbondedRatio,\n\t)\n\tk.SetEpochMintProvision(ctx, epochMintProvision)\n}", "label_name": "CWE-287", "label": 4} {"code": "func TestBuilder_BuildBootstrapStaticResources(t *testing.T) {\n\tt.Run(\"valid\", func(t *testing.T) {\n\t\tb := New(\"localhost:1111\", \"localhost:2222\", filemgr.NewManager(), nil)\n\t\tstaticCfg, err := b.BuildBootstrapStaticResources()\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"clusters\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"pomerium-control-plane-grpc\",\n\t\t\t\t\t\t\"type\": \"STATIC\",\n\t\t\t\t\t\t\"connectTimeout\": \"5s\",\n\t\t\t\t\t\t\"http2ProtocolOptions\": {},\n\t\t\t\t\t\t\"loadAssignment\": {\n\t\t\t\t\t\t\t\"clusterName\": \"pomerium-control-plane-grpc\",\n\t\t\t\t\t\t\t\"endpoints\": [{\n\t\t\t\t\t\t\t\t\"lbEndpoints\": [{\n\t\t\t\t\t\t\t\t\t\"endpoint\": {\n\t\t\t\t\t\t\t\t\t\t\"address\": {\n\t\t\t\t\t\t\t\t\t\t\t\"socketAddress\":{\n\t\t\t\t\t\t\t\t\t\t\t\t\"address\": \"127.0.0.1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"portValue\": 1111\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t`, staticCfg)\n\t})\n\tt.Run(\"bad gRPC address\", func(t *testing.T) {\n\t\tb := New(\"xyz:zyx\", \"localhost:2222\", filemgr.NewManager(), nil)\n\t\t_, err := b.BuildBootstrapStaticResources()\n\t\tassert.Error(t, err)\n\t})\n}", "label_name": "CWE-200", "label": 10} {"code": "func (mgr *MetricsManager) updateInfo(cfg *Config) {\n\tserviceName := telemetry.ServiceName(cfg.Options.Services)\n\tif serviceName == mgr.serviceName {\n\t\treturn\n\t}\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Error(context.TODO()).Err(err).Msg(\"telemetry/metrics: failed to get OS hostname\")\n\t\thostname = \"__unknown__\"\n\t}\n\n\tmetrics.SetBuildInfo(serviceName, hostname, cfg.EnvoyVersion)\n\tmgr.serviceName = serviceName\n}", "label_name": "CWE-200", "label": 10} {"code": "func (mgr *MetricsManager) updateServer(cfg *Config) {\n\tif cfg.Options.MetricsAddr == mgr.addr &&\n\t\tcfg.Options.MetricsBasicAuth == mgr.basicAuth &&\n\t\tcfg.Options.InstallationID == mgr.installationID {\n\t\treturn\n\t}\n\n\tmgr.addr = cfg.Options.MetricsAddr\n\tmgr.basicAuth = cfg.Options.MetricsBasicAuth\n\tmgr.installationID = cfg.Options.InstallationID\n\tmgr.handler = nil\n\n\tif mgr.addr == \"\" {\n\t\tlog.Info(context.TODO()).Msg(\"metrics: http server disabled\")\n\t\treturn\n\t}\n\n\thandler, err := metrics.PrometheusHandler(EnvoyAdminURL, mgr.installationID)\n\tif err != nil {\n\t\tlog.Error(context.TODO()).Err(err).Msg(\"metrics: failed to create prometheus handler\")\n\t\treturn\n\t}\n\n\tif username, password, ok := cfg.Options.GetMetricsBasicAuth(); ok {\n\t\thandler = middleware.RequireBasicAuth(username, password)(handler)\n\t}\n\n\tmgr.handler = handler\n}", "label_name": "CWE-200", "label": 10} {"code": "func (s *Service) handleMessage(stream StepStream, addr string, exp *certificateExpirationCheck) error {\n\trequest, err := stream.Recv()\n\tif err == io.EOF {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\ts.Logger.Warningf(\"Stream read from %s failed: %v\", addr, err)\n\t\treturn err\n\t}\n\n\texp.checkExpiration(time.Now(), extractChannel(request))\n\n\tif s.StepLogger.IsEnabledFor(zap.DebugLevel) {\n\t\tnodeName := commonNameFromContext(stream.Context())\n\t\ts.StepLogger.Debugf(\"Received message from %s(%s): %v\", nodeName, addr, requestAsString(request))\n\t}\n\n\tif submitReq := request.GetSubmitRequest(); submitReq != nil {\n\t\tnodeName := commonNameFromContext(stream.Context())\n\t\ts.Logger.Debugf(\"Received message from %s(%s): %v\", nodeName, addr, requestAsString(request))\n\t\treturn s.handleSubmit(submitReq, stream, addr)\n\t}\n\n\t// Else, it's a consensus message.\n\treturn s.Dispatcher.DispatchConsensus(stream.Context(), request.GetConsensusRequest())\n}", "label_name": "CWE-20", "label": 0} {"code": " static buildGenesisOpReturn(config: configBuildGenesisOpReturn, type = 0x01) {\n let hash;\n try { \n hash = config.hash!.toString('hex')\n } catch (_) { hash = null }\n \n return SlpTokenType1.buildGenesisOpReturn(\n config.ticker,\n config.name,\n config.documentUri,\n hash,\n config.decimals,\n config.batonVout,\n config.initialQuantity, \n type\n )\n }", "label_name": "CWE-20", "label": 0} {"code": " link: new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n const {\n response: { headers },\n } = context;\n expect(headers.get('access-control-allow-origin')).toEqual('*');\n checked = true;\n return response;\n });\n }).concat(", "label_name": "CWE-863", "label": 11} {"code": "\t\t\t.then((promiseResult) => {\n\t\t\t\t// This promise resolver simply swallows the result of Promise.all.\n\t\t\t\t// When we decide we want to expose this level of detail\n\t\t\t\t// to other extensions then we will design that return type and implement it here.\n\t\t\t}),", "label_name": "CWE-863", "label": 11} {"code": "module.exports = (yargs) => {\n yargs.command('exec [commands...]', 'Execute command in docker container', () => {}, async (argv) => {\n const containers = docker.getContainers();\n const services = Object.keys(containers);\n\n if (services.includes(argv.containername) || services.some((service) => service.includes(argv.containername))) {\n const container = containers[argv.containername]\n ? containers[argv.containername]\n : Object.entries(containers).find(([key]) => key.includes(argv.containername))[1];\n\n if (argv.commands.length === 0) {\n // if we have default connect command then use it\n if (container.connectCommand) {\n // eslint-disable-next-line no-param-reassign\n argv.commands = container.connectCommand;\n } else {\n // otherwise fall back to bash (if it exists inside container)\n argv.commands.push('bash');\n }\n }\n await executeInContainer({\n containerName: container.name,\n commands: argv.commands\n });\n\n return;\n }\n\n logger.error(`No container found \"${argv.containername}\"`);\n });\n};", "label_name": "CWE-670", "label": 36} {"code": "function applyInlineFootnotes(elem) {\n const footnoteRefs = elem.querySelectorAll(\"sup.footnote-ref\");\n\n footnoteRefs.forEach((footnoteRef) => {\n const expandableFootnote = document.createElement(\"a\");\n expandableFootnote.classList.add(\"expand-footnote\");\n expandableFootnote.innerHTML = iconHTML(\"ellipsis-h\");\n expandableFootnote.href = \"\";\n expandableFootnote.role = \"button\";\n expandableFootnote.dataset.footnoteId = footnoteRef\n .querySelector(\"a\")\n .id.replace(\"footnote-ref-\", \"\");\n\n footnoteRef.after(expandableFootnote);\n });\n\n if (footnoteRefs.length) {\n elem.classList.add(\"inline-footnotes\");\n }\n}", "label_name": "CWE-755", "label": 21} {"code": " private _readPacketInfo(data: Buffer) {\n return this.readMessageFunc(data);\n }", "label_name": "CWE-400", "label": 2} {"code": " function check_response(err: Error | null, response: any) {\n should.not.exist(err);\n //xx debugLog(response.toString());\n response.responseHeader.serviceResult.should.eql(StatusCodes.BadInvalidArgument);\n }", "label_name": "CWE-400", "label": 2} {"code": "function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) {\r\n assert(typeof requestData.callback === \"function\");\r\n\r\n const request = requestData.request;\r\n\r\n if (!response && !err && requestData.msgType !== \"CLO\") {\r\n // this case happens when CLO is called and when some pending transactions\r\n // remains in the queue...\r\n err = new Error(\" Connection has been closed by client , but this transaction cannot be honored\");\r\n }\r\n\r\n if (response && response instanceof ServiceFault) {\r\n response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];\r\n err = new Error(\" serviceResult = \" + response.responseHeader.serviceResult.toString());\r\n // \" returned by server \\n response:\" + response.toString() + \"\\n request: \" + request.toString());\r\n (err as any).response = response;\r\n ((err as any).request = request), (response = undefined);\r\n }\r\n\r\n const theCallbackFunction = requestData.callback;\r\n /* istanbul ignore next */\r\n if (!theCallbackFunction) {\r\n throw new Error(\"Internal error\");\r\n }\r\n assert(requestData.msgType === \"CLO\" || (err && !response) || (!err && response));\r\n\r\n // let set callback to undefined to prevent callback to be called again\r\n requestData.callback = undefined;\r\n\r\n theCallbackFunction(err || null, !err && response !== null ? response : undefined);\r\n}\r", "label_name": "CWE-400", "label": 2} {"code": " get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })\n}))", "label_name": "CWE-20", "label": 0} {"code": " redirect: `${url}/error?${new URLSearchParams({\n error: error as string,\n })}`,\n }\n }\n\n try {\n const redirect = await emailSignin(email, options)\n return { redirect }\n } catch (error) {\n logger.error(\"SIGNIN_EMAIL_ERROR\", {\n error: error as Error,\n providerId: provider.id,\n })\n return { redirect: `${url}/error?error=EmailSignin` }\n }\n }\n return { redirect: `${url}/signin` }\n}", "label_name": "CWE-863", "label": 11}